4 * Copyright 1996, 1998 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "wine/port.h"
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
40 #ifdef HAVE_SYS_PRCTL_H
41 # include <sys/prctl.h>
43 #include <sys/types.h>
46 #define WIN32_NO_STATUS
48 #include "kernel_private.h"
49 #include "wine/library.h"
50 #include "wine/server.h"
51 #include "wine/unicode.h"
52 #include "wine/debug.h"
54 WINE_DEFAULT_DEBUG_CHANNEL(process);
55 WINE_DECLARE_DEBUG_CHANNEL(file);
56 WINE_DECLARE_DEBUG_CHANNEL(relay);
59 extern char **__wine_get_main_environment(void);
61 extern char **__wine_main_environ;
62 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
73 static UINT process_error_mode;
75 static DWORD shutdown_flags = 0;
76 static DWORD shutdown_priority = 0x280;
79 HMODULE kernel32_handle = 0;
81 const WCHAR *DIR_Windows = NULL;
82 const WCHAR *DIR_System = NULL;
83 const WCHAR *DIR_SysWow64 = NULL;
86 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
87 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
88 #define PDB32_DOS_PROC 0x0010 /* Dos process */
89 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
90 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
91 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
93 static const WCHAR comW[] = {'.','c','o','m',0};
94 static const WCHAR batW[] = {'.','b','a','t',0};
95 static const WCHAR cmdW[] = {'.','c','m','d',0};
96 static const WCHAR pifW[] = {'.','p','i','f',0};
97 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
99 static void exec_process( LPCWSTR name );
101 extern void SHELL_LoadRegistry(void);
104 /***********************************************************************
107 static inline int contains_path( LPCWSTR name )
109 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
113 /***********************************************************************
116 * Check if an environment variable needs to be handled specially when
117 * passed through the Unix environment (i.e. prefixed with "WINE").
119 static inline int is_special_env_var( const char *var )
121 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
122 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
123 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
124 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
125 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
129 /***********************************************************************
132 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
134 unsigned int len = strlenW( prefix );
136 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
137 while (filename[len] == '\\') len++;
142 /***************************************************************************
145 * Get the path of a builtin module when the native file does not exist.
147 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
148 UINT size, struct binary_info *binary_info )
152 void *redir_disabled = 0;
153 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
155 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
156 Wow64RevertWow64FsRedirection( redir_disabled );
158 if (contains_path( libname ))
160 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
161 filename, &file_part ) > size * sizeof(WCHAR))
162 return FALSE; /* too long */
164 if ((len = is_path_prefix( DIR_System, filename )))
166 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
168 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
174 if (filename + len != file_part) return FALSE;
178 len = strlenW( DIR_System );
179 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
180 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
181 file_part = filename + len;
182 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
183 strcpyW( file_part, libname );
184 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
186 if (ext && !strchrW( file_part, '.' ))
188 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
189 return FALSE; /* too long */
190 strcatW( file_part, ext );
192 binary_info->type = BINARY_UNIX_LIB;
193 binary_info->flags = flags;
194 binary_info->res_start = NULL;
195 binary_info->res_end = NULL;
200 /***********************************************************************
201 * open_builtin_exe_file
203 * Open an exe file for a builtin exe.
205 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
206 int test_only, int *file_exists )
208 char exename[MAX_PATH];
213 if ((p = strrchrW( name, '/' ))) name = p + 1;
214 if ((p = strrchrW( name, '\\' ))) name = p + 1;
216 /* we don't want to depend on the current codepage here */
217 len = strlenW( name ) + 1;
218 if (len >= sizeof(exename)) return NULL;
219 for (i = 0; i < len; i++)
221 if (name[i] > 127) return NULL;
222 exename[i] = (char)name[i];
223 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
225 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
229 /***********************************************************************
232 * Open a specific exe file, taking load order into account.
233 * Returns the file handle or 0 for a builtin exe.
235 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
239 TRACE("looking for %s\n", debugstr_w(name) );
241 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
242 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
244 WCHAR buffer[MAX_PATH];
245 /* file doesn't exist, check for builtin */
246 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
249 else MODULE_get_binary_info( handle, binary_info );
255 /***********************************************************************
258 * Open an exe file, and return the full name and file handle.
259 * Returns FALSE if file could not be found.
260 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
261 * If file is a builtin exe, returns TRUE and sets handle to 0.
263 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
264 HANDLE *handle, struct binary_info *binary_info )
266 static const WCHAR exeW[] = {'.','e','x','e',0};
269 TRACE("looking for %s\n", debugstr_w(name) );
271 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ))
273 if (get_builtin_path( name, exeW, buffer, buflen, binary_info ))
275 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
276 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
285 /* no builtin found, try native without extension in case it is a Unix app */
287 if (!SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
290 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
291 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
292 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
294 MODULE_get_binary_info( *handle, binary_info );
301 /***********************************************************************
302 * build_initial_environment
304 * Build the Win32 environment from the Unix environment
306 static BOOL build_initial_environment(void)
312 char **env = __wine_get_main_environment();
314 /* Compute the total size of the Unix environment */
315 for (e = env; *e; e++)
317 if (is_special_env_var( *e )) continue;
318 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
320 size *= sizeof(WCHAR);
322 /* Now allocate the environment */
324 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
325 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
328 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
329 endptr = p + size / sizeof(WCHAR);
331 /* And fill it with the Unix environment */
332 for (e = env; *e; e++)
336 /* skip Unix special variables and use the Wine variants instead */
337 if (!strncmp( str, "WINE", 4 ))
339 if (is_special_env_var( str + 4 )) str += 4;
340 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
342 else if (is_special_env_var( str )) continue; /* skip it */
344 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
352 /***********************************************************************
353 * set_registry_variables
355 * Set environment variables by enumerating the values of a key;
356 * helper for set_registry_environment().
357 * Note that Windows happily truncates the value if it's too big.
359 static void set_registry_variables( HANDLE hkey, ULONG type )
361 static const WCHAR pathW[] = {'P','A','T','H'};
362 static const WCHAR sep[] = {';',0};
363 UNICODE_STRING env_name, env_value;
367 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
370 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
373 tmp.MaximumLength = sizeof(tmpbuf);
375 for (index = 0; ; index++)
377 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
378 buffer, sizeof(buffer), &size );
379 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
381 if (info->Type != type)
383 env_name.Buffer = info->Name;
384 env_name.Length = env_name.MaximumLength = info->NameLength;
385 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
386 env_value.Length = info->DataLength;
387 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
388 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
389 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
390 if (!env_value.Length) continue;
391 if (info->Type == REG_EXPAND_SZ)
393 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
394 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
395 RtlCopyUnicodeString( &env_value, &tmp );
398 if (env_name.Length == sizeof(pathW) &&
399 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
400 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
402 RtlAppendUnicodeToString( &tmp, sep );
403 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
404 RtlCopyUnicodeString( &env_value, &tmp );
406 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
411 /***********************************************************************
412 * set_registry_environment
414 * Set the environment variables specified in the registry.
416 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
417 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
418 * on the order in which the variables are processed. But on Windows it
419 * does not really matter since they only use %SystemDrive% and
420 * %SystemRoot% which are predefined. But Wine defines these in the
421 * registry, so we need two passes.
423 static BOOL set_registry_environment( BOOL volatile_only )
425 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
426 'S','y','s','t','e','m','\\',
427 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
428 'C','o','n','t','r','o','l','\\',
429 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
430 'E','n','v','i','r','o','n','m','e','n','t',0};
431 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
432 static const WCHAR volatile_envW[] = {'V','o','l','a','t','i','l','e',' ','E','n','v','i','r','o','n','m','e','n','t',0};
434 OBJECT_ATTRIBUTES attr;
435 UNICODE_STRING nameW;
439 attr.Length = sizeof(attr);
440 attr.RootDirectory = 0;
441 attr.ObjectName = &nameW;
443 attr.SecurityDescriptor = NULL;
444 attr.SecurityQualityOfService = NULL;
446 /* first the system environment variables */
447 RtlInitUnicodeString( &nameW, env_keyW );
448 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
450 set_registry_variables( hkey, REG_SZ );
451 set_registry_variables( hkey, REG_EXPAND_SZ );
456 /* then the ones for the current user */
457 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
458 RtlInitUnicodeString( &nameW, envW );
459 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
461 set_registry_variables( hkey, REG_SZ );
462 set_registry_variables( hkey, REG_EXPAND_SZ );
466 RtlInitUnicodeString( &nameW, volatile_envW );
467 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
469 set_registry_variables( hkey, REG_SZ );
470 set_registry_variables( hkey, REG_EXPAND_SZ );
474 NtClose( attr.RootDirectory );
479 /***********************************************************************
482 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
484 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
485 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
486 DWORD len, size = sizeof(buffer);
488 UNICODE_STRING nameW;
490 RtlInitUnicodeString( &nameW, name );
491 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
494 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
495 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
497 if (info->Type == REG_EXPAND_SZ)
499 UNICODE_STRING value, expanded;
501 value.MaximumLength = len * sizeof(WCHAR);
502 value.Buffer = (WCHAR *)info->Data;
503 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
504 value.Length = len * sizeof(WCHAR);
505 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
506 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
507 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
508 else RtlFreeUnicodeString( &expanded );
510 else if (info->Type == REG_SZ)
512 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
514 memcpy( ret, info->Data, len * sizeof(WCHAR) );
522 /***********************************************************************
523 * set_additional_environment
525 * Set some additional environment variables not specified in the registry.
527 static void set_additional_environment(void)
529 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
530 'S','o','f','t','w','a','r','e','\\',
531 'M','i','c','r','o','s','o','f','t','\\',
532 'W','i','n','d','o','w','s',' ','N','T','\\',
533 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
534 'P','r','o','f','i','l','e','L','i','s','t',0};
535 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
536 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
537 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
538 OBJECT_ATTRIBUTES attr;
539 UNICODE_STRING nameW;
540 WCHAR *profile_dir = NULL, *all_users_dir = NULL;
544 /* set the ALLUSERSPROFILE variables */
546 attr.Length = sizeof(attr);
547 attr.RootDirectory = 0;
548 attr.ObjectName = &nameW;
550 attr.SecurityDescriptor = NULL;
551 attr.SecurityQualityOfService = NULL;
552 RtlInitUnicodeString( &nameW, profile_keyW );
553 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
555 profile_dir = get_reg_value( hkey, profiles_valueW );
556 all_users_dir = get_reg_value( hkey, all_users_valueW );
560 if (profile_dir && all_users_dir)
564 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
565 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
566 strcpyW( value, profile_dir );
567 p = value + strlenW(value);
568 if (p > value && p[-1] != '\\') *p++ = '\\';
569 strcpyW( p, all_users_dir );
570 SetEnvironmentVariableW( allusersW, value );
571 HeapFree( GetProcessHeap(), 0, value );
574 HeapFree( GetProcessHeap(), 0, all_users_dir );
575 HeapFree( GetProcessHeap(), 0, profile_dir );
578 /***********************************************************************
581 * Set the Wine library Unicode argv global variables.
583 static void set_library_wargv( char **argv )
591 for (argc = 0; argv[argc]; argc++)
592 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
594 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
595 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
596 p = (WCHAR *)(wargv + argc + 1);
597 for (argc = 0; argv[argc]; argc++)
599 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
606 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
608 for (argc = 0; wargv[argc]; argc++)
609 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
611 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
612 q = (char *)(argv + argc + 1);
613 for (argc = 0; wargv[argc]; argc++)
615 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
622 __wine_main_argc = argc;
623 __wine_main_argv = argv;
624 __wine_main_wargv = wargv;
628 /***********************************************************************
629 * update_library_argv0
631 * Update the argv[0] global variable with the binary we have found.
633 static void update_library_argv0( const WCHAR *argv0 )
635 DWORD len = strlenW( argv0 );
637 if (len > strlenW( __wine_main_wargv[0] ))
639 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
641 strcpyW( __wine_main_wargv[0], argv0 );
643 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
644 if (len > strlen( __wine_main_argv[0] ) + 1)
646 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
648 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
652 /***********************************************************************
655 * Build the command line of a process from the argv array.
657 * Note that it does NOT necessarily include the file name.
658 * Sometimes we don't even have any command line options at all.
660 * We must quote and escape characters so that the argv array can be rebuilt
661 * from the command line:
662 * - spaces and tabs must be quoted
664 * - quotes must be escaped
666 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
667 * resulting in an odd number of '\' followed by a '"'
670 * - '\'s that are not followed by a '"' can be left as is
674 static BOOL build_command_line( WCHAR **argv )
679 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
681 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
684 for (arg = argv; *arg; arg++)
686 int has_space,bcount;
692 if( !*a ) has_space=1;
697 if (*a==' ' || *a=='\t') {
699 } else if (*a=='"') {
700 /* doubling of '\' preceding a '"',
701 * plus escaping of said '"'
709 len+=(a-*arg)+1 /* for the separating space */;
711 len+=2; /* for the quotes */
714 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
717 p = rupp->CommandLine.Buffer;
718 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
719 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
720 for (arg = argv; *arg; arg++)
722 int has_space,has_quote;
725 /* Check for quotes and spaces in this argument */
726 has_space=has_quote=0;
728 if( !*a ) has_space=1;
730 if (*a==' ' || *a=='\t') {
734 } else if (*a=='"') {
742 /* Now transfer it to the command line */
759 /* Double all the '\\' preceding this '"', plus one */
760 for (i=0;i<=bcount;i++)
772 while ((*p=*x++)) p++;
778 if (p > rupp->CommandLine.Buffer)
779 p--; /* remove last space */
786 /***********************************************************************
787 * init_current_directory
789 * Initialize the current directory from the Unix cwd or the parent info.
791 static void init_current_directory( CURDIR *cur_dir )
793 UNICODE_STRING dir_str;
798 /* if we received a cur dir from the parent, try this first */
800 if (cur_dir->DosPath.Length)
802 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
805 /* now try to get it from the Unix cwd */
807 for (size = 256; ; size *= 2)
809 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
810 if (getcwd( cwd, size )) break;
811 HeapFree( GetProcessHeap(), 0, cwd );
812 if (errno == ERANGE) continue;
817 /* try to use PWD if it is valid, so that we don't resolve symlinks */
819 pwd = getenv( "PWD" );
822 struct stat st1, st2;
824 if (!pwd || stat( pwd, &st1 ) == -1 ||
825 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
831 ANSI_STRING unix_name;
832 UNICODE_STRING nt_name;
833 RtlInitAnsiString( &unix_name, pwd );
834 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
836 UNICODE_STRING dos_path;
837 /* skip the \??\ prefix, nt_name is 0 terminated */
838 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
839 RtlSetCurrentDirectory_U( &dos_path );
840 RtlFreeUnicodeString( &nt_name );
844 if (!cur_dir->DosPath.Length) /* still not initialized */
846 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
847 "starting in the Windows directory.\n", cwd ? cwd : "" );
848 RtlInitUnicodeString( &dir_str, DIR_Windows );
849 RtlSetCurrentDirectory_U( &dir_str );
851 HeapFree( GetProcessHeap(), 0, cwd );
854 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
855 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
859 /***********************************************************************
862 * Initialize the windows and system directories from the environment.
864 static void init_windows_dirs(void)
866 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
868 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
869 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
870 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
871 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
872 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
877 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
879 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
880 GetEnvironmentVariableW( windirW, buffer, len );
881 DIR_Windows = buffer;
883 else DIR_Windows = default_windirW;
885 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
887 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
888 GetEnvironmentVariableW( winsysdirW, buffer, len );
893 len = strlenW( DIR_Windows );
894 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
895 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
896 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
900 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
901 ERR( "directory %s could not be created, error %u\n",
902 debugstr_w(DIR_Windows), GetLastError() );
903 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
904 ERR( "directory %s could not be created, error %u\n",
905 debugstr_w(DIR_System), GetLastError() );
907 #ifndef _WIN64 /* SysWow64 is always defined on 64-bit */
911 len = strlenW( DIR_Windows );
912 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
913 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
914 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
915 DIR_SysWow64 = buffer;
916 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
917 ERR( "directory %s could not be created, error %u\n",
918 debugstr_w(DIR_SysWow64), GetLastError() );
921 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
922 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
924 /* set the directories in ntdll too */
925 __wine_init_windows_dir( DIR_Windows, DIR_System );
929 /***********************************************************************
932 * Start the wineboot process if necessary. Return the handles to wait on.
934 static void start_wineboot( HANDLE handles[2] )
936 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
939 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
941 ERR( "failed to create wineboot event, expect trouble\n" );
944 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
946 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
947 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
948 const DWORD expected_type = (sizeof(void*) > sizeof(int) || is_wow64) ?
949 SCS_64BIT_BINARY : SCS_32BIT_BINARY;
951 PROCESS_INFORMATION pi;
955 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
957 memset( &si, 0, sizeof(si) );
959 si.dwFlags = STARTF_USESTDHANDLES;
962 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
964 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
965 lstrcatW( app, wineboot );
967 Wow64DisableWow64FsRedirection( &redir );
968 if (GetBinaryTypeW( app, &type ) && type != expected_type)
970 if (type == SCS_64BIT_BINARY)
971 MESSAGE( "wine: '%s' is a 64-bit prefix, it cannot be used with 32-bit Wine.\n",
972 wine_get_config_dir() );
974 MESSAGE( "wine: '%s' is a 32-bit prefix, it cannot be used with %s Wine.\n",
975 wine_get_config_dir(), is_wow64 ? "wow64" : "64-bit" );
979 strcpyW( cmdline, app );
980 strcatW( cmdline, args );
981 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
983 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
984 CloseHandle( pi.hThread );
985 handles[1] = pi.hProcess;
989 ERR( "failed to start wineboot, err %u\n", GetLastError() );
990 CloseHandle( handles[0] );
993 Wow64RevertWow64FsRedirection( redir );
998 /***********************************************************************
1001 * Startup routine of a new process. Runs on the new process stack.
1003 static DWORD WINAPI start_process( PEB *peb )
1005 IMAGE_NT_HEADERS *nt;
1006 LPTHREAD_START_ROUTINE entry;
1008 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1009 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1010 nt->OptionalHeader.AddressOfEntryPoint);
1012 if (!nt->OptionalHeader.AddressOfEntryPoint)
1014 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1015 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1019 if (TRACE_ON(relay))
1020 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1021 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1023 SetLastError( 0 ); /* clear error code */
1024 if (peb->BeingDebugged) DbgBreakPoint();
1025 return entry( peb );
1029 /***********************************************************************
1032 * Change the process name in the ps output.
1034 static void set_process_name( int argc, char *argv[] )
1036 #ifdef HAVE_SETPROCTITLE
1037 setproctitle("-%s", argv[1]);
1042 char *p, *prctl_name = argv[1];
1043 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1046 # define PR_SET_NAME 15
1049 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1050 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1052 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1054 offset = argv[1] - argv[0];
1055 memmove( argv[1] - offset, argv[1], end - argv[1] );
1056 memset( end - offset, 0, offset );
1057 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1061 #endif /* HAVE_PRCTL */
1063 /* remove argv[0] */
1064 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1069 /***********************************************************************
1070 * __wine_kernel_init
1072 * Wine initialisation: load and start the main exe file.
1074 void CDECL __wine_kernel_init(void)
1076 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1077 static const WCHAR dotW[] = {'.',0};
1078 static const WCHAR exeW[] = {'.','e','x','e',0};
1080 WCHAR *p, main_exe_name[MAX_PATH+1];
1081 PEB *peb = NtCurrentTeb()->Peb;
1082 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1083 HANDLE boot_events[2];
1084 BOOL got_environment = TRUE;
1086 /* Initialize everything */
1088 setbuf(stdout,NULL);
1089 setbuf(stderr,NULL);
1090 kernel32_handle = GetModuleHandleW(kernel32W);
1091 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1095 if (!params->Environment)
1097 /* Copy the parent environment */
1098 if (!build_initial_environment()) exit(1);
1100 /* convert old configuration to new format */
1101 convert_old_config();
1103 got_environment = set_registry_environment( FALSE );
1104 set_additional_environment();
1107 init_windows_dirs();
1108 init_current_directory( ¶ms->CurrentDirectory );
1110 set_process_name( __wine_main_argc, __wine_main_argv );
1111 set_library_wargv( __wine_main_argv );
1112 boot_events[0] = boot_events[1] = 0;
1114 if (peb->ProcessParameters->ImagePathName.Buffer)
1116 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1120 struct binary_info binary_info;
1122 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1123 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1125 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1126 ExitProcess( GetLastError() );
1128 update_library_argv0( main_exe_name );
1129 if (!build_command_line( __wine_main_wargv )) goto error;
1130 start_wineboot( boot_events );
1133 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1134 p = strrchrW( main_exe_name, '.' );
1135 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1137 TRACE( "starting process name=%s argv[0]=%s\n",
1138 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1140 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1141 MODULE_get_dll_load_path(main_exe_name) );
1145 DWORD timeout = 30000, count = 1;
1147 if (boot_events[1]) count++;
1148 if (!got_environment) timeout = 300000; /* initial prefix creation can take longer */
1149 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1150 ERR( "boot event wait timed out\n" );
1151 CloseHandle( boot_events[0] );
1152 if (boot_events[1]) CloseHandle( boot_events[1] );
1153 /* reload environment now that wineboot has run */
1154 set_registry_environment( got_environment );
1155 set_additional_environment();
1158 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1163 DWORD error = GetLastError();
1165 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1166 if (error == ERROR_BAD_EXE_FORMAT ||
1167 error == ERROR_INVALID_ADDRESS ||
1168 error == ERROR_NOT_ENOUGH_MEMORY)
1170 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1171 /* if we get back here, it failed */
1173 else if (error == ERROR_MOD_NOT_FOUND)
1175 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1176 else p = main_exe_name;
1177 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1179 /* args 1 and 2 are --app-name full_path */
1180 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1181 debugstr_w(__wine_main_wargv[3]) );
1182 ExitProcess( ERROR_BAD_EXE_FORMAT );
1185 args[0] = (DWORD_PTR)main_exe_name;
1186 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1187 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1188 WideCharToMultiByte( CP_ACP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1189 MESSAGE( "wine: %s", msg );
1190 ExitProcess( error );
1193 LdrInitializeThunk( start_process, 0, 0, 0 );
1196 ExitProcess( GetLastError() );
1200 /***********************************************************************
1203 * Build an argv array from a command-line.
1204 * 'reserved' is the number of args to reserve before the first one.
1206 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1210 char *arg,*s,*d,*cmdline;
1211 int in_quotes,bcount,len;
1213 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1214 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1215 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1222 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1225 /* skip the remaining spaces */
1226 while (*s==' ' || *s=='\t') {
1233 } else if (*s=='\\') {
1234 /* '\', count them */
1236 } else if ((*s=='"') && ((bcount & 1)==0)) {
1238 in_quotes=!in_quotes;
1241 /* a regular character */
1246 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1248 HeapFree( GetProcessHeap(), 0, cmdline );
1252 arg = d = s = (char *)(argv + argc);
1253 memcpy( d, cmdline, len );
1258 if ((*s==' ' || *s=='\t') && !in_quotes) {
1259 /* Close the argument and copy it */
1263 /* skip the remaining spaces */
1266 } while (*s==' ' || *s=='\t');
1268 /* Start with a new argument */
1271 } else if (*s=='\\') {
1275 } else if (*s=='"') {
1277 if ((bcount & 1)==0) {
1278 /* Preceded by an even number of '\', this is half that
1279 * number of '\', plus a '"' which we discard.
1283 in_quotes=!in_quotes;
1285 /* Preceded by an odd number of '\', this is half that
1286 * number of '\' followed by a '"'
1294 /* a regular character */
1305 HeapFree( GetProcessHeap(), 0, cmdline );
1310 /***********************************************************************
1313 * Build the environment of a new child process.
1315 static char **build_envp( const WCHAR *envW )
1317 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1322 int count = 1, length;
1325 for (end = envW; *end; count++) end += strlenW(end) + 1;
1327 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1328 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1329 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1331 for (p = env; *p; p += strlen(p) + 1)
1332 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1334 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1336 if (!(p = getenv(unix_vars[i]))) continue;
1337 length += strlen(unix_vars[i]) + strlen(p) + 2;
1341 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1343 char **envptr = envp;
1344 char *dst = (char *)(envp + count);
1346 /* some variables must not be modified, so we get them directly from the unix env */
1347 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1349 if (!(p = getenv(unix_vars[i]))) continue;
1350 *envptr++ = strcpy( dst, unix_vars[i] );
1353 dst += strlen(dst) + 1;
1356 /* now put the Windows environment strings */
1357 for (p = env; *p; p += strlen(p) + 1)
1359 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1360 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1361 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1362 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1363 if (is_special_env_var( p )) /* prefix it with "WINE" */
1365 *envptr++ = strcpy( dst, "WINE" );
1370 *envptr++ = strcpy( dst, p );
1372 dst += strlen(dst) + 1;
1376 HeapFree( GetProcessHeap(), 0, env );
1381 /***********************************************************************
1384 * Fork and exec a new Unix binary, checking for errors.
1386 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1387 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1389 int fd[2], stdin_fd = -1, stdout_fd = -1;
1391 char **argv, **envp;
1393 if (!env) env = GetEnvironmentStringsW();
1396 if (pipe2( fd, O_CLOEXEC ) == -1)
1401 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1404 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1405 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1408 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1410 HANDLE hstdin, hstdout;
1412 if (startup->dwFlags & STARTF_USESTDHANDLES)
1414 hstdin = startup->hStdInput;
1415 hstdout = startup->hStdOutput;
1419 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1420 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1423 if (is_console_handle( hstdin ))
1424 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1425 if (is_console_handle( hstdout ))
1426 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1427 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1428 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1431 argv = build_argv( cmdline, 0 );
1432 envp = build_envp( env );
1434 if (!(pid = fork())) /* child */
1438 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1441 if (!(pid = fork()))
1443 int fd = open( "/dev/null", O_RDWR );
1445 /* close stdin and stdout */
1453 else if (pid != -1) _exit(0); /* parent */
1459 dup2( stdin_fd, 0 );
1462 if (stdout_fd != -1)
1464 dup2( stdout_fd, 1 );
1469 /* Reset signals that we previously set to SIG_IGN */
1470 signal( SIGPIPE, SIG_DFL );
1471 signal( SIGCHLD, SIG_DFL );
1473 if (newdir) chdir(newdir);
1475 if (argv && envp) execve( filename, argv, envp );
1477 write( fd[1], &err, sizeof(err) );
1480 HeapFree( GetProcessHeap(), 0, argv );
1481 HeapFree( GetProcessHeap(), 0, envp );
1482 if (stdin_fd != -1) close( stdin_fd );
1483 if (stdout_fd != -1) close( stdout_fd );
1485 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1490 if (pid == -1) FILE_SetDosError();
1496 static inline DWORD append_string( void **ptr, const WCHAR *str )
1498 DWORD len = strlenW( str );
1499 memcpy( *ptr, str, len * sizeof(WCHAR) );
1500 *ptr = (WCHAR *)*ptr + len;
1501 return len * sizeof(WCHAR);
1504 /***********************************************************************
1505 * create_startup_info
1507 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1508 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1509 const STARTUPINFOW *startup, DWORD *info_size )
1511 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1512 startup_info_t *info;
1515 UNICODE_STRING newdir;
1516 WCHAR imagepath[MAX_PATH];
1517 HANDLE hstdin, hstdout, hstderr;
1519 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1520 lstrcpynW( imagepath, filename, MAX_PATH );
1521 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1522 lstrcpynW( imagepath, filename, MAX_PATH );
1524 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1526 newdir.Buffer = NULL;
1529 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1530 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1536 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1537 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1539 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1542 size = sizeof(*info);
1543 size += strlenW( cur_dir ) * sizeof(WCHAR);
1544 size += cur_params->DllPath.Length;
1545 size += strlenW( imagepath ) * sizeof(WCHAR);
1546 size += strlenW( cmdline ) * sizeof(WCHAR);
1547 if (startup->lpTitle) size += strlenW( startup->lpTitle ) * sizeof(WCHAR);
1548 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1549 /* FIXME: shellinfo */
1550 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1551 size = (size + 1) & ~1;
1554 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1556 info->console_flags = cur_params->ConsoleFlags;
1557 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1558 if (flags & CREATE_NEW_CONSOLE) info->console = (obj_handle_t)1; /* FIXME: cf. kernel_main.c */
1560 if (startup->dwFlags & STARTF_USESTDHANDLES)
1562 hstdin = startup->hStdInput;
1563 hstdout = startup->hStdOutput;
1564 hstderr = startup->hStdError;
1568 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1569 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1570 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1572 info->hstdin = wine_server_obj_handle( hstdin );
1573 info->hstdout = wine_server_obj_handle( hstdout );
1574 info->hstderr = wine_server_obj_handle( hstderr );
1575 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1577 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1578 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1579 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1580 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1584 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1585 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1586 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1589 info->x = startup->dwX;
1590 info->y = startup->dwY;
1591 info->xsize = startup->dwXSize;
1592 info->ysize = startup->dwYSize;
1593 info->xchars = startup->dwXCountChars;
1594 info->ychars = startup->dwYCountChars;
1595 info->attribute = startup->dwFillAttribute;
1596 info->flags = startup->dwFlags;
1597 info->show = startup->wShowWindow;
1600 info->curdir_len = append_string( &ptr, cur_dir );
1601 info->dllpath_len = cur_params->DllPath.Length;
1602 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1603 ptr = (char *)ptr + cur_params->DllPath.Length;
1604 info->imagepath_len = append_string( &ptr, imagepath );
1605 info->cmdline_len = append_string( &ptr, cmdline );
1606 if (startup->lpTitle) info->title_len = append_string( &ptr, startup->lpTitle );
1607 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1608 if (startup->lpReserved2 && startup->cbReserved2)
1610 info->runtime_len = startup->cbReserved2;
1611 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1615 RtlFreeUnicodeString( &newdir );
1620 /***********************************************************************
1623 * Create a new process. If hFile is a valid handle we have an exe
1624 * file, otherwise it is a Winelib app.
1626 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1627 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1628 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1629 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1630 const struct binary_info *binary_info, int exec_only )
1632 BOOL ret, success = FALSE;
1633 HANDLE process_info;
1635 char *winedebug = NULL;
1637 startup_info_t *startup_info;
1638 DWORD startup_info_size;
1639 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1643 if (sizeof(void *) == sizeof(int) && !is_wow64 && (binary_info->flags & BINARY_FLAG_64BIT))
1645 ERR( "starting 64-bit process %s not supported on this platform\n", debugstr_w(filename) );
1646 SetLastError( ERROR_BAD_EXE_FORMAT );
1650 RtlAcquirePebLock();
1652 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1653 &startup_info_size )))
1655 RtlReleasePebLock();
1658 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
1662 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1663 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1665 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1666 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1667 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1669 env_end += strlenW(env_end) + 1;
1673 /* create the socket for the new process */
1675 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1677 RtlReleasePebLock();
1678 HeapFree( GetProcessHeap(), 0, winedebug );
1679 HeapFree( GetProcessHeap(), 0, startup_info );
1680 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1683 wine_server_send_fd( socketfd[1] );
1684 close( socketfd[1] );
1686 /* create the process on the server side */
1688 SERVER_START_REQ( new_process )
1690 req->inherit_all = inherit;
1691 req->create_flags = flags;
1692 req->socket_fd = socketfd[1];
1693 req->exe_file = wine_server_obj_handle( hFile );
1694 req->process_access = PROCESS_ALL_ACCESS;
1695 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1696 req->thread_access = THREAD_ALL_ACCESS;
1697 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1698 req->info_size = startup_info_size;
1700 wine_server_add_data( req, startup_info, startup_info_size );
1701 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
1702 if ((ret = !wine_server_call_err( req )))
1704 info->dwProcessId = (DWORD)reply->pid;
1705 info->dwThreadId = (DWORD)reply->tid;
1706 info->hProcess = wine_server_ptr_handle( reply->phandle );
1707 info->hThread = wine_server_ptr_handle( reply->thandle );
1709 process_info = wine_server_ptr_handle( reply->info );
1713 RtlReleasePebLock();
1716 close( socketfd[0] );
1717 HeapFree( GetProcessHeap(), 0, startup_info );
1718 HeapFree( GetProcessHeap(), 0, winedebug );
1722 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1724 if (startup_info->hstdin)
1725 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
1726 FILE_READ_DATA, &stdin_fd, NULL );
1727 if (startup_info->hstdout)
1728 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
1729 FILE_WRITE_DATA, &stdout_fd, NULL );
1731 HeapFree( GetProcessHeap(), 0, startup_info );
1733 /* create the child process */
1734 argv = build_argv( cmd_line, 1 );
1736 if (exec_only || !(pid = fork())) /* child */
1738 char preloader_reserve[64], socket_env[64];
1740 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1742 if (!(pid = fork()))
1744 int fd = open( "/dev/null", O_RDWR );
1746 /* close stdin and stdout */
1754 else if (pid != -1) _exit(0); /* parent */
1758 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1759 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1762 if (stdin_fd != -1) close( stdin_fd );
1763 if (stdout_fd != -1) close( stdout_fd );
1765 /* Reset signals that we previously set to SIG_IGN */
1766 signal( SIGPIPE, SIG_DFL );
1767 signal( SIGCHLD, SIG_DFL );
1769 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1770 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1771 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1773 putenv( preloader_reserve );
1774 putenv( socket_env );
1775 if (winedebug) putenv( winedebug );
1776 if (unixdir) chdir(unixdir);
1778 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1782 /* this is the parent */
1784 if (stdin_fd != -1) close( stdin_fd );
1785 if (stdout_fd != -1) close( stdout_fd );
1786 close( socketfd[0] );
1787 HeapFree( GetProcessHeap(), 0, argv );
1788 HeapFree( GetProcessHeap(), 0, winedebug );
1795 /* wait for the new process info to be ready */
1797 WaitForSingleObject( process_info, INFINITE );
1798 SERVER_START_REQ( get_new_process_info )
1800 req->info = wine_server_obj_handle( process_info );
1801 wine_server_call( req );
1802 success = reply->success;
1803 err = reply->exit_code;
1809 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1812 CloseHandle( process_info );
1816 CloseHandle( process_info );
1817 CloseHandle( info->hProcess );
1818 CloseHandle( info->hThread );
1819 info->hProcess = info->hThread = 0;
1820 info->dwProcessId = info->dwThreadId = 0;
1825 /***********************************************************************
1826 * create_vdm_process
1828 * Create a new VDM process for a 16-bit or DOS application.
1830 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1831 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1832 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1833 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1834 const struct binary_info *binary_info, int exec_only )
1836 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1839 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1840 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1844 SetLastError( ERROR_OUTOFMEMORY );
1847 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1848 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1849 flags, startup, info, unixdir, binary_info, exec_only );
1850 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1855 /***********************************************************************
1856 * create_cmd_process
1858 * Create a new cmd shell process for a .BAT file.
1860 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1861 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1862 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1863 LPPROCESS_INFORMATION info )
1866 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1867 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1868 WCHAR comspec[MAX_PATH];
1872 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1874 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1875 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1878 strcpyW( newcmdline, comspec );
1879 strcatW( newcmdline, slashcW );
1880 strcatW( newcmdline, cmd_line );
1881 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1882 flags, env, cur_dir, startup, info );
1883 HeapFree( GetProcessHeap(), 0, newcmdline );
1888 /*************************************************************************
1891 * Helper for CreateProcess: retrieve the file name to load from the
1892 * app name and command line. Store the file name in buffer, and
1893 * return a possibly modified command line.
1894 * Also returns a handle to the opened file if it's a Windows binary.
1896 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1897 int buflen, HANDLE *handle, struct binary_info *binary_info )
1899 static const WCHAR quotesW[] = {'"','%','s','"',0};
1901 WCHAR *name, *pos, *ret = NULL;
1905 /* if we have an app name, everything is easy */
1909 /* use the unmodified app name as file name */
1910 lstrcpynW( buffer, appname, buflen );
1911 *handle = open_exe_file( buffer, binary_info );
1912 if (!(ret = cmdline) || !cmdline[0])
1914 /* no command-line, create one */
1915 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1916 sprintfW( ret, quotesW, appname );
1921 /* first check for a quoted file name */
1923 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1925 int len = p - cmdline - 1;
1926 /* extract the quoted portion as file name */
1927 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1928 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1931 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
1932 ret = cmdline; /* no change necessary */
1936 /* now try the command-line word by word */
1938 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1946 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1948 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
1953 if (*p) got_space = TRUE;
1956 if (ret && got_space) /* now build a new command-line with quotes */
1958 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1960 sprintfW( ret, quotesW, name );
1963 else if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
1966 HeapFree( GetProcessHeap(), 0, name );
1971 /**********************************************************************
1972 * CreateProcessA (KERNEL32.@)
1974 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1975 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1976 DWORD flags, LPVOID env, LPCSTR cur_dir,
1977 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1980 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1981 UNICODE_STRING desktopW, titleW;
1984 desktopW.Buffer = NULL;
1985 titleW.Buffer = NULL;
1986 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1987 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1988 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1990 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1991 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1993 memcpy( &infoW, startup_info, sizeof(infoW) );
1994 infoW.lpDesktop = desktopW.Buffer;
1995 infoW.lpTitle = titleW.Buffer;
1997 if (startup_info->lpReserved)
1998 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1999 debugstr_a(startup_info->lpReserved));
2001 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
2002 inherit, flags, env, cur_dirW, &infoW, info );
2004 HeapFree( GetProcessHeap(), 0, app_nameW );
2005 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2006 HeapFree( GetProcessHeap(), 0, cur_dirW );
2007 RtlFreeUnicodeString( &desktopW );
2008 RtlFreeUnicodeString( &titleW );
2013 /**********************************************************************
2014 * CreateProcessW (KERNEL32.@)
2016 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2017 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2018 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2019 LPPROCESS_INFORMATION info )
2023 char *unixdir = NULL;
2024 WCHAR name[MAX_PATH];
2025 WCHAR *tidy_cmdline, *p, *envW = env;
2026 struct binary_info binary_info;
2028 /* Process the AppName and/or CmdLine to get module name and path */
2030 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2032 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2033 &hFile, &binary_info )))
2035 if (hFile == INVALID_HANDLE_VALUE) goto done;
2037 /* Warn if unsupported features are used */
2039 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2040 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2041 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2042 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2043 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2047 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2049 SetLastError(ERROR_DIRECTORY);
2055 WCHAR buf[MAX_PATH];
2056 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2059 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2064 while (*p) p += strlen(p) + 1;
2065 p++; /* final null */
2066 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
2067 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2068 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
2069 flags |= CREATE_UNICODE_ENVIRONMENT;
2072 info->hThread = info->hProcess = 0;
2073 info->dwProcessId = info->dwThreadId = 0;
2075 if (binary_info.flags & BINARY_FLAG_DLL)
2077 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2078 SetLastError( ERROR_BAD_EXE_FORMAT );
2080 else switch (binary_info.type)
2083 TRACE( "starting %s as Win32 binary (%p-%p)\n",
2084 debugstr_w(name), binary_info.res_start, binary_info.res_end );
2085 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2086 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2091 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2092 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2093 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2095 case BINARY_UNIX_LIB:
2096 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
2097 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2098 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2100 case BINARY_UNKNOWN:
2101 /* check for .com or .bat extension */
2102 if ((p = strrchrW( name, '.' )))
2104 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2106 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2107 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2108 inherit, flags, startup_info, info, unixdir,
2109 &binary_info, FALSE );
2112 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2114 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2115 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2116 inherit, flags, startup_info, info );
2121 case BINARY_UNIX_EXE:
2123 /* unknown file, try as unix executable */
2126 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2128 if ((unix_name = wine_get_unix_file_name( name )))
2130 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2131 HeapFree( GetProcessHeap(), 0, unix_name );
2136 if (hFile) CloseHandle( hFile );
2139 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2140 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2141 HeapFree( GetProcessHeap(), 0, unixdir );
2143 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2148 /**********************************************************************
2151 static void exec_process( LPCWSTR name )
2155 STARTUPINFOW startup_info;
2156 PROCESS_INFORMATION info;
2157 struct binary_info binary_info;
2159 hFile = open_exe_file( name, &binary_info );
2160 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2162 memset( &startup_info, 0, sizeof(startup_info) );
2163 startup_info.cb = sizeof(startup_info);
2165 /* Determine executable type */
2167 if (binary_info.flags & BINARY_FLAG_DLL) return;
2168 switch (binary_info.type)
2171 TRACE( "starting %s as Win32 binary (%p-%p)\n",
2172 debugstr_w(name), binary_info.res_start, binary_info.res_end );
2173 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2174 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2176 case BINARY_UNIX_LIB:
2177 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2178 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2179 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2181 case BINARY_UNKNOWN:
2182 /* check for .com or .pif extension */
2183 if (!(p = strrchrW( name, '.' ))) break;
2184 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2189 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2190 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2191 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2196 CloseHandle( hFile );
2200 /***********************************************************************
2203 * Wrapper to call WaitForInputIdle USER function
2205 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2207 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2209 HMODULE mod = GetModuleHandleA( "user32.dll" );
2212 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2213 if (ptr) return ptr( process, timeout );
2219 /***********************************************************************
2220 * WinExec (KERNEL32.@)
2222 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2224 PROCESS_INFORMATION info;
2225 STARTUPINFOA startup;
2229 memset( &startup, 0, sizeof(startup) );
2230 startup.cb = sizeof(startup);
2231 startup.dwFlags = STARTF_USESHOWWINDOW;
2232 startup.wShowWindow = nCmdShow;
2234 /* cmdline needs to be writable for CreateProcess */
2235 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2236 strcpy( cmdline, lpCmdLine );
2238 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2239 0, NULL, NULL, &startup, &info ))
2241 /* Give 30 seconds to the app to come up */
2242 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2243 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2245 /* Close off the handles */
2246 CloseHandle( info.hThread );
2247 CloseHandle( info.hProcess );
2249 else if ((ret = GetLastError()) >= 32)
2251 FIXME("Strange error set by CreateProcess: %d\n", ret );
2254 HeapFree( GetProcessHeap(), 0, cmdline );
2259 /**********************************************************************
2260 * LoadModule (KERNEL32.@)
2262 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2264 LOADPARMS32 *params = paramBlock;
2265 PROCESS_INFORMATION info;
2266 STARTUPINFOA startup;
2267 HINSTANCE hInstance;
2269 char filename[MAX_PATH];
2272 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2274 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2275 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2276 return ULongToHandle(GetLastError());
2278 len = (BYTE)params->lpCmdLine[0];
2279 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2280 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2282 strcpy( cmdline, filename );
2283 p = cmdline + strlen(cmdline);
2285 memcpy( p, params->lpCmdLine + 1, len );
2288 memset( &startup, 0, sizeof(startup) );
2289 startup.cb = sizeof(startup);
2290 if (params->lpCmdShow)
2292 startup.dwFlags = STARTF_USESHOWWINDOW;
2293 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2296 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2297 params->lpEnvAddress, NULL, &startup, &info ))
2299 /* Give 30 seconds to the app to come up */
2300 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2301 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2302 hInstance = (HINSTANCE)33;
2303 /* Close off the handles */
2304 CloseHandle( info.hThread );
2305 CloseHandle( info.hProcess );
2307 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2309 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2310 hInstance = (HINSTANCE)11;
2313 HeapFree( GetProcessHeap(), 0, cmdline );
2318 /******************************************************************************
2319 * TerminateProcess (KERNEL32.@)
2321 * Terminates a process.
2324 * handle [I] Process to terminate.
2325 * exit_code [I] Exit code.
2329 * Failure: FALSE, check GetLastError().
2331 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2333 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2334 if (status) SetLastError( RtlNtStatusToDosError(status) );
2338 /***********************************************************************
2339 * ExitProcess (KERNEL32.@)
2341 * Exits the current process.
2344 * status [I] Status code to exit with.
2350 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2352 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2353 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2354 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2356 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2360 void WINAPI process_ExitProcess( DWORD status )
2362 LdrShutdownProcess();
2363 NtTerminateProcess(GetCurrentProcess(), status);
2369 void WINAPI ExitProcess( DWORD status )
2371 LdrShutdownProcess();
2372 NtTerminateProcess(GetCurrentProcess(), status);
2378 /***********************************************************************
2379 * GetExitCodeProcess [KERNEL32.@]
2381 * Gets termination status of specified process.
2384 * hProcess [in] Handle to the process.
2385 * lpExitCode [out] Address to receive termination status.
2391 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2394 PROCESS_BASIC_INFORMATION pbi;
2396 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2398 if (status == STATUS_SUCCESS)
2400 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2403 SetLastError( RtlNtStatusToDosError(status) );
2408 /***********************************************************************
2409 * SetErrorMode (KERNEL32.@)
2411 UINT WINAPI SetErrorMode( UINT mode )
2413 UINT old = process_error_mode;
2414 process_error_mode = mode;
2418 /***********************************************************************
2419 * GetErrorMode (KERNEL32.@)
2421 UINT WINAPI GetErrorMode( void )
2423 return process_error_mode;
2426 /**********************************************************************
2427 * TlsAlloc [KERNEL32.@]
2429 * Allocates a thread local storage index.
2432 * Success: TLS index.
2433 * Failure: 0xFFFFFFFF
2435 DWORD WINAPI TlsAlloc( void )
2438 PEB * const peb = NtCurrentTeb()->Peb;
2440 RtlAcquirePebLock();
2441 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2442 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2445 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2448 if (!NtCurrentTeb()->TlsExpansionSlots &&
2449 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2450 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2452 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2454 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2458 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2459 index += TLS_MINIMUM_AVAILABLE;
2462 else SetLastError( ERROR_NO_MORE_ITEMS );
2464 RtlReleasePebLock();
2469 /**********************************************************************
2470 * TlsFree [KERNEL32.@]
2472 * Releases a thread local storage index, making it available for reuse.
2475 * index [in] TLS index to free.
2481 BOOL WINAPI TlsFree( DWORD index )
2485 RtlAcquirePebLock();
2486 if (index >= TLS_MINIMUM_AVAILABLE)
2488 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2489 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2493 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2494 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2496 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2497 else SetLastError( ERROR_INVALID_PARAMETER );
2498 RtlReleasePebLock();
2503 /**********************************************************************
2504 * TlsGetValue [KERNEL32.@]
2506 * Gets value in a thread's TLS slot.
2509 * index [in] TLS index to retrieve value for.
2512 * Success: Value stored in calling thread's TLS slot for index.
2513 * Failure: 0 and GetLastError() returns NO_ERROR.
2515 LPVOID WINAPI TlsGetValue( DWORD index )
2519 if (index < TLS_MINIMUM_AVAILABLE)
2521 ret = NtCurrentTeb()->TlsSlots[index];
2525 index -= TLS_MINIMUM_AVAILABLE;
2526 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2528 SetLastError( ERROR_INVALID_PARAMETER );
2531 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2532 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2534 SetLastError( ERROR_SUCCESS );
2539 /**********************************************************************
2540 * TlsSetValue [KERNEL32.@]
2542 * Stores a value in the thread's TLS slot.
2545 * index [in] TLS index to set value for.
2546 * value [in] Value to be stored.
2552 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2554 if (index < TLS_MINIMUM_AVAILABLE)
2556 NtCurrentTeb()->TlsSlots[index] = value;
2560 index -= TLS_MINIMUM_AVAILABLE;
2561 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2563 SetLastError( ERROR_INVALID_PARAMETER );
2566 if (!NtCurrentTeb()->TlsExpansionSlots &&
2567 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2568 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2570 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2573 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2579 /***********************************************************************
2580 * GetProcessFlags (KERNEL32.@)
2582 DWORD WINAPI GetProcessFlags( DWORD processid )
2584 IMAGE_NT_HEADERS *nt;
2587 if (processid && processid != GetCurrentProcessId()) return 0;
2589 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2591 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2592 flags |= PDB32_CONSOLE_PROC;
2594 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2595 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2600 /***********************************************************************
2601 * GetProcessDword (KERNEL32.18)
2603 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2605 FIXME( "(%d, %d): not supported\n", dwProcessID, offset );
2610 /*********************************************************************
2611 * OpenProcess (KERNEL32.@)
2613 * Opens a handle to a process.
2616 * access [I] Desired access rights assigned to the returned handle.
2617 * inherit [I] Determines whether or not child processes will inherit the handle.
2618 * id [I] Process identifier of the process to get a handle to.
2621 * Success: Valid handle to the specified process.
2622 * Failure: NULL, check GetLastError().
2624 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2628 OBJECT_ATTRIBUTES attr;
2631 cid.UniqueProcess = ULongToHandle(id);
2632 cid.UniqueThread = 0; /* FIXME ? */
2634 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2635 attr.RootDirectory = NULL;
2636 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2637 attr.SecurityDescriptor = NULL;
2638 attr.SecurityQualityOfService = NULL;
2639 attr.ObjectName = NULL;
2641 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2643 status = NtOpenProcess(&handle, access, &attr, &cid);
2644 if (status != STATUS_SUCCESS)
2646 SetLastError( RtlNtStatusToDosError(status) );
2653 /*********************************************************************
2654 * GetProcessId (KERNEL32.@)
2656 * Gets the a unique identifier of a process.
2659 * hProcess [I] Handle to the process.
2663 * Failure: FALSE, check GetLastError().
2667 * The identifier is unique only on the machine and only until the process
2668 * exits (including system shutdown).
2670 DWORD WINAPI GetProcessId( HANDLE hProcess )
2673 PROCESS_BASIC_INFORMATION pbi;
2675 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2677 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2678 SetLastError( RtlNtStatusToDosError(status) );
2683 /*********************************************************************
2684 * CloseHandle (KERNEL32.@)
2689 * handle [I] Handle to close.
2693 * Failure: FALSE, check GetLastError().
2695 BOOL WINAPI CloseHandle( HANDLE handle )
2699 /* stdio handles need special treatment */
2700 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2701 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2702 (handle == (HANDLE)STD_ERROR_HANDLE))
2703 handle = GetStdHandle( HandleToULong(handle) );
2705 if (is_console_handle(handle))
2706 return CloseConsoleHandle(handle);
2708 status = NtClose( handle );
2709 if (status) SetLastError( RtlNtStatusToDosError(status) );
2714 /*********************************************************************
2715 * GetHandleInformation (KERNEL32.@)
2717 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2719 OBJECT_DATA_INFORMATION info;
2720 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2722 if (status) SetLastError( RtlNtStatusToDosError(status) );
2726 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2727 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2733 /*********************************************************************
2734 * SetHandleInformation (KERNEL32.@)
2736 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2738 OBJECT_DATA_INFORMATION info;
2741 /* if not setting both fields, retrieve current value first */
2742 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2743 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2745 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2747 SetLastError( RtlNtStatusToDosError(status) );
2751 if (mask & HANDLE_FLAG_INHERIT)
2752 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2753 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2754 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2756 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2757 if (status) SetLastError( RtlNtStatusToDosError(status) );
2762 /*********************************************************************
2763 * DuplicateHandle (KERNEL32.@)
2765 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2766 HANDLE dest_process, HANDLE *dest,
2767 DWORD access, BOOL inherit, DWORD options )
2771 if (is_console_handle(source))
2773 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2774 if (source_process != dest_process ||
2775 source_process != GetCurrentProcess())
2777 SetLastError(ERROR_INVALID_PARAMETER);
2780 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2781 return (*dest != INVALID_HANDLE_VALUE);
2783 status = NtDuplicateObject( source_process, source, dest_process, dest,
2784 access, inherit ? OBJ_INHERIT : 0, options );
2785 if (status) SetLastError( RtlNtStatusToDosError(status) );
2790 /***********************************************************************
2791 * ConvertToGlobalHandle (KERNEL32.@)
2793 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2795 HANDLE ret = INVALID_HANDLE_VALUE;
2796 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2797 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2802 /***********************************************************************
2803 * SetHandleContext (KERNEL32.@)
2805 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2807 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2808 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2809 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2814 /***********************************************************************
2815 * GetHandleContext (KERNEL32.@)
2817 DWORD WINAPI GetHandleContext(HANDLE hnd)
2819 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2820 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2821 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2826 /***********************************************************************
2827 * CreateSocketHandle (KERNEL32.@)
2829 HANDLE WINAPI CreateSocketHandle(void)
2831 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2832 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2833 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2834 return INVALID_HANDLE_VALUE;
2838 /***********************************************************************
2839 * SetPriorityClass (KERNEL32.@)
2841 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2844 PROCESS_PRIORITY_CLASS ppc;
2846 ppc.Foreground = FALSE;
2847 switch (priorityclass)
2849 case IDLE_PRIORITY_CLASS:
2850 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2851 case BELOW_NORMAL_PRIORITY_CLASS:
2852 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2853 case NORMAL_PRIORITY_CLASS:
2854 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2855 case ABOVE_NORMAL_PRIORITY_CLASS:
2856 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2857 case HIGH_PRIORITY_CLASS:
2858 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2859 case REALTIME_PRIORITY_CLASS:
2860 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2862 SetLastError(ERROR_INVALID_PARAMETER);
2866 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2869 if (status != STATUS_SUCCESS)
2871 SetLastError( RtlNtStatusToDosError(status) );
2878 /***********************************************************************
2879 * GetPriorityClass (KERNEL32.@)
2881 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2884 PROCESS_BASIC_INFORMATION pbi;
2886 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2888 if (status != STATUS_SUCCESS)
2890 SetLastError( RtlNtStatusToDosError(status) );
2893 switch (pbi.BasePriority)
2895 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2896 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2897 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2898 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2899 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2900 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2902 SetLastError( ERROR_INVALID_PARAMETER );
2907 /***********************************************************************
2908 * SetProcessAffinityMask (KERNEL32.@)
2910 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2914 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2915 &affmask, sizeof(DWORD_PTR));
2918 SetLastError( RtlNtStatusToDosError(status) );
2925 /**********************************************************************
2926 * GetProcessAffinityMask (KERNEL32.@)
2928 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2929 PDWORD_PTR lpProcessAffinityMask,
2930 PDWORD_PTR lpSystemAffinityMask )
2932 PROCESS_BASIC_INFORMATION pbi;
2935 status = NtQueryInformationProcess(hProcess,
2936 ProcessBasicInformation,
2937 &pbi, sizeof(pbi), NULL);
2940 SetLastError( RtlNtStatusToDosError(status) );
2943 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2944 if (lpSystemAffinityMask) *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2949 /***********************************************************************
2950 * GetProcessVersion (KERNEL32.@)
2952 DWORD WINAPI GetProcessVersion( DWORD pid )
2956 PROCESS_BASIC_INFORMATION pbi;
2959 IMAGE_DOS_HEADER dos;
2960 IMAGE_NT_HEADERS nt;
2963 if (!pid || pid == GetCurrentProcessId())
2965 IMAGE_NT_HEADERS *nt;
2967 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2968 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2969 nt->OptionalHeader.MinorSubsystemVersion);
2973 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
2974 if (!process) return 0;
2976 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
2977 if (status) goto err;
2979 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
2980 if (status || count != sizeof(peb)) goto err;
2982 memset(&dos, 0, sizeof(dos));
2983 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
2984 if (status || count != sizeof(dos)) goto err;
2985 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
2987 memset(&nt, 0, sizeof(nt));
2988 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
2989 if (status || count != sizeof(nt)) goto err;
2990 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
2992 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
2995 CloseHandle(process);
2997 if (status != STATUS_SUCCESS)
2998 SetLastError(RtlNtStatusToDosError(status));
3004 /***********************************************************************
3005 * SetProcessWorkingSetSize [KERNEL32.@]
3006 * Sets the min/max working set sizes for a specified process.
3009 * hProcess [I] Handle to the process of interest
3010 * minset [I] Specifies minimum working set size
3011 * maxset [I] Specifies maximum working set size
3017 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3020 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3021 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3022 /* Trim the working set to zero */
3023 /* Swap the process out of physical RAM */
3028 /***********************************************************************
3029 * GetProcessWorkingSetSize (KERNEL32.@)
3031 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3034 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3035 /* 32 MB working set size */
3036 if (minset) *minset = 32*1024*1024;
3037 if (maxset) *maxset = 32*1024*1024;
3042 /***********************************************************************
3043 * SetProcessShutdownParameters (KERNEL32.@)
3045 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3047 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3048 shutdown_flags = flags;
3049 shutdown_priority = level;
3054 /***********************************************************************
3055 * GetProcessShutdownParameters (KERNEL32.@)
3058 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3060 *lpdwLevel = shutdown_priority;
3061 *lpdwFlags = shutdown_flags;
3066 /***********************************************************************
3067 * GetProcessPriorityBoost (KERNEL32.@)
3069 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3071 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3073 /* Report that no boost is present.. */
3074 *pDisablePriorityBoost = FALSE;
3079 /***********************************************************************
3080 * SetProcessPriorityBoost (KERNEL32.@)
3082 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3084 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3085 /* Say we can do it. I doubt the program will notice that we don't. */
3090 /***********************************************************************
3091 * ReadProcessMemory (KERNEL32.@)
3093 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3094 SIZE_T *bytes_read )
3096 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3097 if (status) SetLastError( RtlNtStatusToDosError(status) );
3102 /***********************************************************************
3103 * WriteProcessMemory (KERNEL32.@)
3105 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3106 SIZE_T *bytes_written )
3108 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3109 if (status) SetLastError( RtlNtStatusToDosError(status) );
3114 /****************************************************************************
3115 * FlushInstructionCache (KERNEL32.@)
3117 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3120 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3121 if (status) SetLastError( RtlNtStatusToDosError(status) );
3126 /******************************************************************
3127 * GetProcessIoCounters (KERNEL32.@)
3129 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3133 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3134 ioc, sizeof(*ioc), NULL);
3135 if (status) SetLastError( RtlNtStatusToDosError(status) );
3139 /******************************************************************
3140 * GetProcessHandleCount (KERNEL32.@)
3142 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3146 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3147 cnt, sizeof(*cnt), NULL);
3148 if (status) SetLastError( RtlNtStatusToDosError(status) );
3152 /******************************************************************
3153 * QueryFullProcessImageNameA (KERNEL32.@)
3155 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3158 DWORD pdwSizeW = *pdwSize;
3159 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3161 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3164 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3165 lpExeName, *pdwSize, NULL, NULL));
3167 *pdwSize = strlen(lpExeName);
3169 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3173 /******************************************************************
3174 * QueryFullProcessImageNameW (KERNEL32.@)
3176 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3178 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3179 UNICODE_STRING *dynamic_buffer = NULL;
3180 UNICODE_STRING nt_path;
3181 UNICODE_STRING *result = NULL;
3185 RtlInitUnicodeStringEx(&nt_path, NULL);
3186 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3187 * as this is on Wine. */
3188 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3189 sizeof(buffer) - sizeof(WCHAR), &needed);
3190 if (status == STATUS_INFO_LENGTH_MISMATCH)
3192 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3193 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3194 result = dynamic_buffer;
3197 result = (PUNICODE_STRING)buffer;
3199 if (status) goto cleanup;
3201 if (dwFlags & PROCESS_NAME_NATIVE)
3203 result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3204 if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3206 status = STATUS_OBJECT_PATH_NOT_FOUND;
3212 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3214 status = STATUS_BUFFER_TOO_SMALL;
3218 *pdwSize = result->Length/sizeof(WCHAR);
3219 memcpy( lpExeName, result->Buffer, result->Length );
3220 lpExeName[*pdwSize] = 0;
3223 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3224 RtlFreeUnicodeString(&nt_path);
3225 if (status) SetLastError( RtlNtStatusToDosError(status) );
3229 /***********************************************************************
3230 * ProcessIdToSessionId (KERNEL32.@)
3231 * This function is available on Terminal Server 4SP4 and Windows 2000
3233 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3235 /* According to MSDN, if the calling process is not in a terminal
3236 * services environment, then the sessionid returned is zero.
3243 /***********************************************************************
3244 * RegisterServiceProcess (KERNEL32.@)
3246 * A service process calls this function to ensure that it continues to run
3247 * even after a user logged off.
3249 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3251 /* I don't think that Wine needs to do anything in this function */
3252 return 1; /* success */
3256 /**********************************************************************
3257 * IsWow64Process (KERNEL32.@)
3259 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3264 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3266 if (status != STATUS_SUCCESS)
3268 SetLastError( RtlNtStatusToDosError( status ) );
3271 *Wow64Process = (pbi != 0);
3276 /***********************************************************************
3277 * GetCurrentProcess (KERNEL32.@)
3279 * Get a handle to the current process.
3285 * A handle representing the current process.
3287 #undef GetCurrentProcess
3288 HANDLE WINAPI GetCurrentProcess(void)
3290 return (HANDLE)~(ULONG_PTR)0;
3293 /***********************************************************************
3294 * CmdBatNotification (KERNEL32.@)
3296 * Notifies the system that a batch file has started or finished.
3299 * bBatchRunning [I] TRUE if a batch file has started or
3300 * FALSE if a batch file has finished executing.
3305 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3307 FIXME("%d\n", bBatchRunning);
3312 /***********************************************************************
3313 * RegisterApplicationRestart (KERNEL32.@)
3315 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3317 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3322 /**********************************************************************
3323 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3325 DWORD WINAPI WTSGetActiveConsoleSessionId(void)