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"
30 #ifdef HAVE_SYS_TIME_H
31 # include <sys/time.h>
33 #ifdef HAVE_SYS_IOCTL_H
34 #include <sys/ioctl.h>
36 #ifdef HAVE_SYS_SOCKET_H
37 #include <sys/socket.h>
39 #ifdef HAVE_SYS_PRCTL_H
40 # include <sys/prctl.h>
42 #include <sys/types.h>
45 #define WIN32_NO_STATUS
46 #include "wine/winbase16.h"
47 #include "wine/winuser16.h"
49 #include "kernel_private.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, "HOME=", sizeof("HOME=")-1 ) ||
123 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
124 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
128 /***************************************************************************
131 * Get the path of a builtin module when the native file does not exist.
133 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
136 UINT len = strlenW( DIR_System );
138 if (contains_path( libname ))
140 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
141 filename, &file_part ) > size * sizeof(WCHAR))
142 return FALSE; /* too long */
144 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
146 while (filename[len] == '\\') len++;
147 if (filename + len != file_part) return FALSE;
151 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
152 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
153 file_part = filename + len;
154 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
155 strcpyW( file_part, libname );
157 if (ext && !strchrW( file_part, '.' ))
159 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
160 return FALSE; /* too long */
161 strcatW( file_part, ext );
167 /***********************************************************************
168 * open_builtin_exe_file
170 * Open an exe file for a builtin exe.
172 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
173 int test_only, int *file_exists )
175 char exename[MAX_PATH];
180 if ((p = strrchrW( name, '/' ))) name = p + 1;
181 if ((p = strrchrW( name, '\\' ))) name = p + 1;
183 /* we don't want to depend on the current codepage here */
184 len = strlenW( name ) + 1;
185 if (len >= sizeof(exename)) return NULL;
186 for (i = 0; i < len; i++)
188 if (name[i] > 127) return NULL;
189 exename[i] = (char)name[i];
190 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
192 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
196 /***********************************************************************
199 * Open a specific exe file, taking load order into account.
200 * Returns the file handle or 0 for a builtin exe.
202 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
206 TRACE("looking for %s\n", debugstr_w(name) );
208 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
209 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
211 WCHAR buffer[MAX_PATH];
212 /* file doesn't exist, check for builtin */
213 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer) ))
216 binary_info->type = BINARY_UNIX_LIB;
217 binary_info->flags = 0;
218 binary_info->res_start = NULL;
219 binary_info->res_end = NULL;
222 else MODULE_get_binary_info( handle, binary_info );
228 /***********************************************************************
231 * Open an exe file, and return the full name and file handle.
232 * Returns FALSE if file could not be found.
233 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
234 * If file is a builtin exe, returns TRUE and sets handle to 0.
236 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
237 HANDLE *handle, struct binary_info *binary_info )
239 static const WCHAR exeW[] = {'.','e','x','e',0};
242 TRACE("looking for %s\n", debugstr_w(name) );
244 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
245 !get_builtin_path( name, exeW, buffer, buflen ))
247 /* no builtin found, try native without extension in case it is a Unix app */
249 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
251 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
252 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
253 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
255 MODULE_get_binary_info( *handle, binary_info );
262 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
263 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
264 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
266 MODULE_get_binary_info( *handle, binary_info );
270 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
271 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
275 binary_info->type = BINARY_UNIX_LIB;
276 binary_info->flags = 0;
277 binary_info->res_start = NULL;
278 binary_info->res_end = NULL;
286 /***********************************************************************
287 * build_initial_environment
289 * Build the Win32 environment from the Unix environment
291 static BOOL build_initial_environment(void)
297 char **env = __wine_get_main_environment();
299 /* Compute the total size of the Unix environment */
300 for (e = env; *e; e++)
302 if (is_special_env_var( *e )) continue;
303 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
305 size *= sizeof(WCHAR);
307 /* Now allocate the environment */
309 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
310 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
313 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
314 endptr = p + size / sizeof(WCHAR);
316 /* And fill it with the Unix environment */
317 for (e = env; *e; e++)
321 /* skip Unix special variables and use the Wine variants instead */
322 if (!strncmp( str, "WINE", 4 ))
324 if (is_special_env_var( str + 4 )) str += 4;
325 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
327 else if (is_special_env_var( str )) continue; /* skip it */
329 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
337 /***********************************************************************
338 * set_registry_variables
340 * Set environment variables by enumerating the values of a key;
341 * helper for set_registry_environment().
342 * Note that Windows happily truncates the value if it's too big.
344 static void set_registry_variables( HANDLE hkey, ULONG type )
346 UNICODE_STRING env_name, env_value;
350 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
351 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
353 for (index = 0; ; index++)
355 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
356 buffer, sizeof(buffer), &size );
357 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
359 if (info->Type != type)
361 env_name.Buffer = info->Name;
362 env_name.Length = env_name.MaximumLength = info->NameLength;
363 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
364 env_value.Length = env_value.MaximumLength = info->DataLength;
365 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
366 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
367 if (info->Type == REG_EXPAND_SZ)
369 WCHAR buf_expanded[1024];
370 UNICODE_STRING env_expanded;
371 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
372 env_expanded.Buffer=buf_expanded;
373 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
374 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
375 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
379 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
385 /***********************************************************************
386 * set_registry_environment
388 * Set the environment variables specified in the registry.
390 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
391 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
392 * on the order in which the variables are processed. But on Windows it
393 * does not really matter since they only use %SystemDrive% and
394 * %SystemRoot% which are predefined. But Wine defines these in the
395 * registry, so we need two passes.
397 static BOOL set_registry_environment(void)
399 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
400 'S','y','s','t','e','m','\\',
401 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
402 'C','o','n','t','r','o','l','\\',
403 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
404 'E','n','v','i','r','o','n','m','e','n','t',0};
405 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
407 OBJECT_ATTRIBUTES attr;
408 UNICODE_STRING nameW;
412 attr.Length = sizeof(attr);
413 attr.RootDirectory = 0;
414 attr.ObjectName = &nameW;
416 attr.SecurityDescriptor = NULL;
417 attr.SecurityQualityOfService = NULL;
419 /* first the system environment variables */
420 RtlInitUnicodeString( &nameW, env_keyW );
421 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
423 set_registry_variables( hkey, REG_SZ );
424 set_registry_variables( hkey, REG_EXPAND_SZ );
429 /* then the ones for the current user */
430 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
431 RtlInitUnicodeString( &nameW, envW );
432 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
434 set_registry_variables( hkey, REG_SZ );
435 set_registry_variables( hkey, REG_EXPAND_SZ );
438 NtClose( attr.RootDirectory );
443 /***********************************************************************
446 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
448 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
449 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
450 DWORD len, size = sizeof(buffer);
452 UNICODE_STRING nameW;
454 RtlInitUnicodeString( &nameW, name );
455 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
458 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
459 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
461 if (info->Type == REG_EXPAND_SZ)
463 UNICODE_STRING value, expanded;
465 value.MaximumLength = len * sizeof(WCHAR);
466 value.Buffer = (WCHAR *)info->Data;
467 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
468 value.Length = len * sizeof(WCHAR);
469 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
470 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
471 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
472 else RtlFreeUnicodeString( &expanded );
474 else if (info->Type == REG_SZ)
476 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
478 memcpy( ret, info->Data, len * sizeof(WCHAR) );
486 /***********************************************************************
487 * set_additional_environment
489 * Set some additional environment variables not specified in the registry.
491 static void set_additional_environment(void)
493 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
494 'S','o','f','t','w','a','r','e','\\',
495 'M','i','c','r','o','s','o','f','t','\\',
496 'W','i','n','d','o','w','s',' ','N','T','\\',
497 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
498 'P','r','o','f','i','l','e','L','i','s','t',0};
499 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
500 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
501 static const WCHAR usernameW[] = {'U','S','E','R','N','A','M','E',0};
502 static const WCHAR userprofileW[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
503 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
504 OBJECT_ATTRIBUTES attr;
505 UNICODE_STRING nameW;
506 WCHAR *user_name = NULL, *profile_dir = NULL, *all_users_dir = NULL;
508 const char *name = wine_get_user_name();
511 /* set the USERNAME variable */
513 len = MultiByteToWideChar( CP_UNIXCP, 0, name, -1, NULL, 0 );
516 user_name = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
517 MultiByteToWideChar( CP_UNIXCP, 0, name, -1, user_name, len );
518 SetEnvironmentVariableW( usernameW, user_name );
520 else WARN( "user name %s not convertible.\n", debugstr_a(name) );
522 /* set the USERPROFILE and ALLUSERSPROFILE variables */
524 attr.Length = sizeof(attr);
525 attr.RootDirectory = 0;
526 attr.ObjectName = &nameW;
528 attr.SecurityDescriptor = NULL;
529 attr.SecurityQualityOfService = NULL;
530 RtlInitUnicodeString( &nameW, profile_keyW );
531 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
533 profile_dir = get_reg_value( hkey, profiles_valueW );
534 all_users_dir = get_reg_value( hkey, all_users_valueW );
542 if (all_users_dir) len = max( len, strlenW(all_users_dir) + 1 );
543 len += strlenW(profile_dir) + 1;
544 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
545 strcpyW( value, profile_dir );
546 p = value + strlenW(value);
547 if (p > value && p[-1] != '\\') *p++ = '\\';
549 strcpyW( p, user_name );
550 SetEnvironmentVariableW( userprofileW, value );
554 strcpyW( p, all_users_dir );
555 SetEnvironmentVariableW( allusersW, value );
557 HeapFree( GetProcessHeap(), 0, value );
560 HeapFree( GetProcessHeap(), 0, all_users_dir );
561 HeapFree( GetProcessHeap(), 0, profile_dir );
562 HeapFree( GetProcessHeap(), 0, user_name );
565 /***********************************************************************
568 * Set the Wine library Unicode argv global variables.
570 static void set_library_wargv( char **argv )
578 for (argc = 0; argv[argc]; argc++)
579 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
581 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
582 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
583 p = (WCHAR *)(wargv + argc + 1);
584 for (argc = 0; argv[argc]; argc++)
586 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
593 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
595 for (argc = 0; wargv[argc]; argc++)
596 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
598 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
599 q = (char *)(argv + argc + 1);
600 for (argc = 0; wargv[argc]; argc++)
602 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
609 __wine_main_argc = argc;
610 __wine_main_argv = argv;
611 __wine_main_wargv = wargv;
615 /***********************************************************************
616 * update_library_argv0
618 * Update the argv[0] global variable with the binary we have found.
620 static void update_library_argv0( const WCHAR *argv0 )
622 DWORD len = strlenW( argv0 );
624 if (len > strlenW( __wine_main_wargv[0] ))
626 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
628 strcpyW( __wine_main_wargv[0], argv0 );
630 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
631 if (len > strlen( __wine_main_argv[0] ) + 1)
633 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
635 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
639 /***********************************************************************
642 * Build the command line of a process from the argv array.
644 * Note that it does NOT necessarily include the file name.
645 * Sometimes we don't even have any command line options at all.
647 * We must quote and escape characters so that the argv array can be rebuilt
648 * from the command line:
649 * - spaces and tabs must be quoted
651 * - quotes must be escaped
653 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
654 * resulting in an odd number of '\' followed by a '"'
657 * - '\'s that are not followed by a '"' can be left as is
661 static BOOL build_command_line( WCHAR **argv )
666 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
668 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
671 for (arg = argv; *arg; arg++)
673 int has_space,bcount;
679 if( !*a ) has_space=1;
684 if (*a==' ' || *a=='\t') {
686 } else if (*a=='"') {
687 /* doubling of '\' preceding a '"',
688 * plus escaping of said '"'
696 len+=(a-*arg)+1 /* for the separating space */;
698 len+=2; /* for the quotes */
701 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
704 p = rupp->CommandLine.Buffer;
705 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
706 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
707 for (arg = argv; *arg; arg++)
709 int has_space,has_quote;
712 /* Check for quotes and spaces in this argument */
713 has_space=has_quote=0;
715 if( !*a ) has_space=1;
717 if (*a==' ' || *a=='\t') {
721 } else if (*a=='"') {
729 /* Now transfer it to the command line */
746 /* Double all the '\\' preceding this '"', plus one */
747 for (i=0;i<=bcount;i++)
759 while ((*p=*x++)) p++;
765 if (p > rupp->CommandLine.Buffer)
766 p--; /* remove last space */
773 /***********************************************************************
774 * init_current_directory
776 * Initialize the current directory from the Unix cwd or the parent info.
778 static void init_current_directory( CURDIR *cur_dir )
780 UNICODE_STRING dir_str;
785 /* if we received a cur dir from the parent, try this first */
787 if (cur_dir->DosPath.Length)
789 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
792 /* now try to get it from the Unix cwd */
794 for (size = 256; ; size *= 2)
796 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
797 if (getcwd( cwd, size )) break;
798 HeapFree( GetProcessHeap(), 0, cwd );
799 if (errno == ERANGE) continue;
804 /* try to use PWD if it is valid, so that we don't resolve symlinks */
806 pwd = getenv( "PWD" );
809 struct stat st1, st2;
811 if (!pwd || stat( pwd, &st1 ) == -1 ||
812 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
819 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, pwd, -1, NULL, 0 );
820 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
822 MultiByteToWideChar( CP_UNIXCP, 0, pwd, -1, dirW, lenW );
823 RtlInitUnicodeString( &dir_str, dirW );
824 RtlSetCurrentDirectory_U( &dir_str );
825 RtlFreeUnicodeString( &dir_str );
829 if (!cur_dir->DosPath.Length) /* still not initialized */
831 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
832 "starting in the Windows directory.\n", cwd ? cwd : "" );
833 RtlInitUnicodeString( &dir_str, DIR_Windows );
834 RtlSetCurrentDirectory_U( &dir_str );
836 HeapFree( GetProcessHeap(), 0, cwd );
839 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
840 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
844 /***********************************************************************
847 * Initialize the windows and system directories from the environment.
849 static void init_windows_dirs(void)
851 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
853 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
854 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
855 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
856 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
857 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
862 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
864 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
865 GetEnvironmentVariableW( windirW, buffer, len );
866 DIR_Windows = buffer;
868 else DIR_Windows = default_windirW;
870 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
872 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
873 GetEnvironmentVariableW( winsysdirW, buffer, len );
878 len = strlenW( DIR_Windows );
879 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
880 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
881 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
885 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
886 ERR( "directory %s could not be created, error %u\n",
887 debugstr_w(DIR_Windows), GetLastError() );
888 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
889 ERR( "directory %s could not be created, error %u\n",
890 debugstr_w(DIR_System), GetLastError() );
892 #ifndef _WIN64 /* SysWow64 is always defined on 64-bit */
896 len = strlenW( DIR_Windows );
897 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
898 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
899 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
900 DIR_SysWow64 = buffer;
901 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
902 ERR( "directory %s could not be created, error %u\n",
903 debugstr_w(DIR_SysWow64), GetLastError() );
906 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
907 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
909 /* set the directories in ntdll too */
910 __wine_init_windows_dir( DIR_Windows, DIR_System );
914 /***********************************************************************
917 * Start the wineboot process if necessary. Return the handles to wait on.
919 static void start_wineboot( HANDLE handles[2] )
921 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
924 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
926 ERR( "failed to create wineboot event, expect trouble\n" );
929 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
931 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
932 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
933 const DWORD expected_type = (sizeof(void*) > sizeof(int) || is_wow64) ?
934 SCS_64BIT_BINARY : SCS_32BIT_BINARY;
936 PROCESS_INFORMATION pi;
940 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
942 memset( &si, 0, sizeof(si) );
944 si.dwFlags = STARTF_USESTDHANDLES;
947 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
949 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
950 lstrcatW( app, wineboot );
952 Wow64DisableWow64FsRedirection( &redir );
953 if (GetBinaryTypeW( app, &type ) && type != expected_type)
955 if (type == SCS_64BIT_BINARY)
956 MESSAGE( "wine: '%s' is a 64-bit prefix, it cannot be used with 32-bit Wine.\n",
957 wine_get_config_dir() );
959 MESSAGE( "wine: '%s' is a 32-bit prefix, it cannot be used with %s Wine.\n",
960 wine_get_config_dir(), is_wow64 ? "wow64" : "64-bit" );
964 strcpyW( cmdline, app );
965 strcatW( cmdline, args );
966 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
968 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
969 CloseHandle( pi.hThread );
970 handles[1] = pi.hProcess;
974 ERR( "failed to start wineboot, err %u\n", GetLastError() );
975 CloseHandle( handles[0] );
978 Wow64RevertWow64FsRedirection( redir );
983 /***********************************************************************
986 * Startup routine of a new process. Runs on the new process stack.
988 static DWORD WINAPI start_process( PEB *peb )
990 IMAGE_NT_HEADERS *nt;
991 LPTHREAD_START_ROUTINE entry;
993 nt = RtlImageNtHeader( peb->ImageBaseAddress );
994 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
995 nt->OptionalHeader.AddressOfEntryPoint);
997 if (!nt->OptionalHeader.AddressOfEntryPoint)
999 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1000 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1004 if (TRACE_ON(relay))
1005 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1006 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1008 SetLastError( 0 ); /* clear error code */
1009 if (peb->BeingDebugged) DbgBreakPoint();
1010 return entry( peb );
1014 /***********************************************************************
1017 * Change the process name in the ps output.
1019 static void set_process_name( int argc, char *argv[] )
1021 #ifdef HAVE_SETPROCTITLE
1022 setproctitle("-%s", argv[1]);
1027 char *p, *prctl_name = argv[1];
1028 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1031 # define PR_SET_NAME 15
1034 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1035 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1037 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1039 offset = argv[1] - argv[0];
1040 memmove( argv[1] - offset, argv[1], end - argv[1] );
1041 memset( end - offset, 0, offset );
1042 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1046 #endif /* HAVE_PRCTL */
1048 /* remove argv[0] */
1049 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1054 /***********************************************************************
1055 * __wine_kernel_init
1057 * Wine initialisation: load and start the main exe file.
1059 void CDECL __wine_kernel_init(void)
1061 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1062 static const WCHAR dotW[] = {'.',0};
1063 static const WCHAR exeW[] = {'.','e','x','e',0};
1065 WCHAR *p, main_exe_name[MAX_PATH+1];
1066 PEB *peb = NtCurrentTeb()->Peb;
1067 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1068 HANDLE boot_events[2];
1069 BOOL got_environment = TRUE;
1071 /* Initialize everything */
1073 setbuf(stdout,NULL);
1074 setbuf(stderr,NULL);
1075 kernel32_handle = GetModuleHandleW(kernel32W);
1076 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1080 if (!params->Environment)
1082 /* Copy the parent environment */
1083 if (!build_initial_environment()) exit(1);
1085 /* convert old configuration to new format */
1086 convert_old_config();
1088 got_environment = set_registry_environment();
1089 set_additional_environment();
1092 init_windows_dirs();
1093 init_current_directory( ¶ms->CurrentDirectory );
1095 set_process_name( __wine_main_argc, __wine_main_argv );
1096 set_library_wargv( __wine_main_argv );
1097 boot_events[0] = boot_events[1] = 0;
1099 if (peb->ProcessParameters->ImagePathName.Buffer)
1101 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1105 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1106 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH ))
1108 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1109 ExitProcess( GetLastError() );
1111 update_library_argv0( main_exe_name );
1112 if (!build_command_line( __wine_main_wargv )) goto error;
1113 start_wineboot( boot_events );
1116 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1117 p = strrchrW( main_exe_name, '.' );
1118 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1120 TRACE( "starting process name=%s argv[0]=%s\n",
1121 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1123 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1124 MODULE_get_dll_load_path(main_exe_name) );
1128 DWORD timeout = 30000, count = 1;
1130 if (boot_events[1]) count++;
1131 if (!got_environment) timeout = 300000; /* initial prefix creation can take longer */
1132 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1133 ERR( "boot event wait timed out\n" );
1134 CloseHandle( boot_events[0] );
1135 if (boot_events[1]) CloseHandle( boot_events[1] );
1136 /* if we didn't find environment section, try again now that wineboot has run */
1137 if (!got_environment)
1139 set_registry_environment();
1140 set_additional_environment();
1144 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1147 DWORD error = GetLastError();
1149 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1150 if (error == ERROR_BAD_EXE_FORMAT ||
1151 error == ERROR_INVALID_ADDRESS ||
1152 error == ERROR_NOT_ENOUGH_MEMORY)
1154 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1155 /* if we get back here, it failed */
1157 else if (error == ERROR_MOD_NOT_FOUND)
1159 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1160 else p = main_exe_name;
1161 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1163 /* args 1 and 2 are --app-name full_path */
1164 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1165 debugstr_w(__wine_main_wargv[3]) );
1166 ExitProcess( ERROR_BAD_EXE_FORMAT );
1169 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, msg, sizeof(msg), NULL );
1170 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name), msg );
1171 ExitProcess( error );
1174 LdrInitializeThunk( start_process, 0, 0, 0 );
1177 ExitProcess( GetLastError() );
1181 /***********************************************************************
1184 * Build an argv array from a command-line.
1185 * 'reserved' is the number of args to reserve before the first one.
1187 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1191 char *arg,*s,*d,*cmdline;
1192 int in_quotes,bcount,len;
1194 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1195 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1196 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1203 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1206 /* skip the remaining spaces */
1207 while (*s==' ' || *s=='\t') {
1214 } else if (*s=='\\') {
1215 /* '\', count them */
1217 } else if ((*s=='"') && ((bcount & 1)==0)) {
1219 in_quotes=!in_quotes;
1222 /* a regular character */
1227 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1229 HeapFree( GetProcessHeap(), 0, cmdline );
1233 arg = d = s = (char *)(argv + argc);
1234 memcpy( d, cmdline, len );
1239 if ((*s==' ' || *s=='\t') && !in_quotes) {
1240 /* Close the argument and copy it */
1244 /* skip the remaining spaces */
1247 } while (*s==' ' || *s=='\t');
1249 /* Start with a new argument */
1252 } else if (*s=='\\') {
1256 } else if (*s=='"') {
1258 if ((bcount & 1)==0) {
1259 /* Preceded by an even number of '\', this is half that
1260 * number of '\', plus a '"' which we discard.
1264 in_quotes=!in_quotes;
1266 /* Preceded by an odd number of '\', this is half that
1267 * number of '\' followed by a '"'
1275 /* a regular character */
1286 HeapFree( GetProcessHeap(), 0, cmdline );
1291 /***********************************************************************
1294 * Build the environment of a new child process.
1296 static char **build_envp( const WCHAR *envW )
1298 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1303 int count = 1, length;
1306 for (end = envW; *end; count++) end += strlenW(end) + 1;
1308 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1309 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1310 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1312 for (p = env; *p; p += strlen(p) + 1)
1313 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1315 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1317 if (!(p = getenv(unix_vars[i]))) continue;
1318 length += strlen(unix_vars[i]) + strlen(p) + 2;
1322 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1324 char **envptr = envp;
1325 char *dst = (char *)(envp + count);
1327 /* some variables must not be modified, so we get them directly from the unix env */
1328 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1330 if (!(p = getenv(unix_vars[i]))) continue;
1331 *envptr++ = strcpy( dst, unix_vars[i] );
1334 dst += strlen(dst) + 1;
1337 /* now put the Windows environment strings */
1338 for (p = env; *p; p += strlen(p) + 1)
1340 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1341 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1342 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1343 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1344 if (is_special_env_var( p )) /* prefix it with "WINE" */
1346 *envptr++ = strcpy( dst, "WINE" );
1351 *envptr++ = strcpy( dst, p );
1353 dst += strlen(dst) + 1;
1357 HeapFree( GetProcessHeap(), 0, env );
1362 /***********************************************************************
1365 * Fork and exec a new Unix binary, checking for errors.
1367 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1368 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1370 int fd[2], stdin_fd = -1, stdout_fd = -1;
1372 char **argv, **envp;
1374 if (!env) env = GetEnvironmentStringsW();
1377 if (pipe2( fd, O_CLOEXEC ) == -1)
1382 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1385 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1386 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1389 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1391 HANDLE hstdin, hstdout;
1393 if (startup->dwFlags & STARTF_USESTDHANDLES)
1395 hstdin = startup->hStdInput;
1396 hstdout = startup->hStdOutput;
1400 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1401 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1404 if (is_console_handle( hstdin ))
1405 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1406 if (is_console_handle( hstdout ))
1407 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1408 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1409 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1412 argv = build_argv( cmdline, 0 );
1413 envp = build_envp( env );
1415 if (!(pid = fork())) /* child */
1419 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1422 if (!(pid = fork()))
1424 int fd = open( "/dev/null", O_RDWR );
1426 /* close stdin and stdout */
1434 else if (pid != -1) _exit(0); /* parent */
1440 dup2( stdin_fd, 0 );
1443 if (stdout_fd != -1)
1445 dup2( stdout_fd, 1 );
1450 /* Reset signals that we previously set to SIG_IGN */
1451 signal( SIGPIPE, SIG_DFL );
1452 signal( SIGCHLD, SIG_DFL );
1454 if (newdir) chdir(newdir);
1456 if (argv && envp) execve( filename, argv, envp );
1458 write( fd[1], &err, sizeof(err) );
1461 HeapFree( GetProcessHeap(), 0, argv );
1462 HeapFree( GetProcessHeap(), 0, envp );
1463 if (stdin_fd != -1) close( stdin_fd );
1464 if (stdout_fd != -1) close( stdout_fd );
1466 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1471 if (pid == -1) FILE_SetDosError();
1477 static inline DWORD append_string( void **ptr, const WCHAR *str )
1479 DWORD len = strlenW( str );
1480 memcpy( *ptr, str, len * sizeof(WCHAR) );
1481 *ptr = (WCHAR *)*ptr + len;
1482 return len * sizeof(WCHAR);
1485 /***********************************************************************
1486 * create_startup_info
1488 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1489 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1490 const STARTUPINFOW *startup, DWORD *info_size )
1492 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1493 startup_info_t *info;
1496 UNICODE_STRING newdir;
1497 WCHAR imagepath[MAX_PATH];
1498 HANDLE hstdin, hstdout, hstderr;
1500 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1501 lstrcpynW( imagepath, filename, MAX_PATH );
1502 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1503 lstrcpynW( imagepath, filename, MAX_PATH );
1505 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1507 newdir.Buffer = NULL;
1510 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1511 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1517 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1518 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1520 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1523 size = sizeof(*info);
1524 size += strlenW( cur_dir ) * sizeof(WCHAR);
1525 size += cur_params->DllPath.Length;
1526 size += strlenW( imagepath ) * sizeof(WCHAR);
1527 size += strlenW( cmdline ) * sizeof(WCHAR);
1528 if (startup->lpTitle) size += strlenW( startup->lpTitle ) * sizeof(WCHAR);
1529 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1530 /* FIXME: shellinfo */
1531 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1532 size = (size + 1) & ~1;
1535 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1537 info->console_flags = cur_params->ConsoleFlags;
1538 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1539 if (flags & CREATE_NEW_CONSOLE) info->console = (obj_handle_t)1; /* FIXME: cf. kernel_main.c */
1541 if (startup->dwFlags & STARTF_USESTDHANDLES)
1543 hstdin = startup->hStdInput;
1544 hstdout = startup->hStdOutput;
1545 hstderr = startup->hStdError;
1549 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1550 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1551 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1553 info->hstdin = wine_server_obj_handle( hstdin );
1554 info->hstdout = wine_server_obj_handle( hstdout );
1555 info->hstderr = wine_server_obj_handle( hstderr );
1556 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1558 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1559 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1560 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1561 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1565 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1566 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1567 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1570 info->x = startup->dwX;
1571 info->y = startup->dwY;
1572 info->xsize = startup->dwXSize;
1573 info->ysize = startup->dwYSize;
1574 info->xchars = startup->dwXCountChars;
1575 info->ychars = startup->dwYCountChars;
1576 info->attribute = startup->dwFillAttribute;
1577 info->flags = startup->dwFlags;
1578 info->show = startup->wShowWindow;
1581 info->curdir_len = append_string( &ptr, cur_dir );
1582 info->dllpath_len = cur_params->DllPath.Length;
1583 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1584 ptr = (char *)ptr + cur_params->DllPath.Length;
1585 info->imagepath_len = append_string( &ptr, imagepath );
1586 info->cmdline_len = append_string( &ptr, cmdline );
1587 if (startup->lpTitle) info->title_len = append_string( &ptr, startup->lpTitle );
1588 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1589 if (startup->lpReserved2 && startup->cbReserved2)
1591 info->runtime_len = startup->cbReserved2;
1592 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1596 RtlFreeUnicodeString( &newdir );
1601 /***********************************************************************
1604 * Create a new process. If hFile is a valid handle we have an exe
1605 * file, otherwise it is a Winelib app.
1607 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1608 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1609 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1610 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1611 const struct binary_info *binary_info, int exec_only )
1613 BOOL ret, success = FALSE;
1614 HANDLE process_info;
1616 char *winedebug = NULL;
1618 startup_info_t *startup_info;
1619 DWORD startup_info_size;
1620 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1624 if (sizeof(void *) == sizeof(int) && !is_wow64 && (binary_info->flags & BINARY_FLAG_64BIT))
1626 ERR( "starting 64-bit process %s not supported on this platform\n", debugstr_w(filename) );
1627 SetLastError( ERROR_BAD_EXE_FORMAT );
1631 RtlAcquirePebLock();
1633 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1634 &startup_info_size )))
1636 RtlReleasePebLock();
1639 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
1643 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1644 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1646 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1647 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1648 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1650 env_end += strlenW(env_end) + 1;
1654 /* create the socket for the new process */
1656 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1658 RtlReleasePebLock();
1659 HeapFree( GetProcessHeap(), 0, winedebug );
1660 HeapFree( GetProcessHeap(), 0, startup_info );
1661 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1664 wine_server_send_fd( socketfd[1] );
1665 close( socketfd[1] );
1667 /* create the process on the server side */
1669 SERVER_START_REQ( new_process )
1671 req->inherit_all = inherit;
1672 req->create_flags = flags;
1673 req->socket_fd = socketfd[1];
1674 req->exe_file = wine_server_obj_handle( hFile );
1675 req->process_access = PROCESS_ALL_ACCESS;
1676 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1677 req->thread_access = THREAD_ALL_ACCESS;
1678 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1679 req->info_size = startup_info_size;
1681 wine_server_add_data( req, startup_info, startup_info_size );
1682 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
1683 if ((ret = !wine_server_call_err( req )))
1685 info->dwProcessId = (DWORD)reply->pid;
1686 info->dwThreadId = (DWORD)reply->tid;
1687 info->hProcess = wine_server_ptr_handle( reply->phandle );
1688 info->hThread = wine_server_ptr_handle( reply->thandle );
1690 process_info = wine_server_ptr_handle( reply->info );
1694 RtlReleasePebLock();
1697 close( socketfd[0] );
1698 HeapFree( GetProcessHeap(), 0, startup_info );
1699 HeapFree( GetProcessHeap(), 0, winedebug );
1703 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1705 if (startup_info->hstdin)
1706 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
1707 FILE_READ_DATA, &stdin_fd, NULL );
1708 if (startup_info->hstdout)
1709 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
1710 FILE_WRITE_DATA, &stdout_fd, NULL );
1712 HeapFree( GetProcessHeap(), 0, startup_info );
1714 /* create the child process */
1715 argv = build_argv( cmd_line, 1 );
1717 if (exec_only || !(pid = fork())) /* child */
1719 char preloader_reserve[64], socket_env[64];
1721 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1723 if (!(pid = fork()))
1725 int fd = open( "/dev/null", O_RDWR );
1727 /* close stdin and stdout */
1735 else if (pid != -1) _exit(0); /* parent */
1739 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1740 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1743 if (stdin_fd != -1) close( stdin_fd );
1744 if (stdout_fd != -1) close( stdout_fd );
1746 /* Reset signals that we previously set to SIG_IGN */
1747 signal( SIGPIPE, SIG_DFL );
1748 signal( SIGCHLD, SIG_DFL );
1750 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1751 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1752 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1754 putenv( preloader_reserve );
1755 putenv( socket_env );
1756 if (winedebug) putenv( winedebug );
1757 if (unixdir) chdir(unixdir);
1759 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1763 /* this is the parent */
1765 if (stdin_fd != -1) close( stdin_fd );
1766 if (stdout_fd != -1) close( stdout_fd );
1767 close( socketfd[0] );
1768 HeapFree( GetProcessHeap(), 0, argv );
1769 HeapFree( GetProcessHeap(), 0, winedebug );
1776 /* wait for the new process info to be ready */
1778 WaitForSingleObject( process_info, INFINITE );
1779 SERVER_START_REQ( get_new_process_info )
1781 req->info = wine_server_obj_handle( process_info );
1782 wine_server_call( req );
1783 success = reply->success;
1784 err = reply->exit_code;
1790 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1793 CloseHandle( process_info );
1797 CloseHandle( process_info );
1798 CloseHandle( info->hProcess );
1799 CloseHandle( info->hThread );
1800 info->hProcess = info->hThread = 0;
1801 info->dwProcessId = info->dwThreadId = 0;
1806 /***********************************************************************
1807 * create_vdm_process
1809 * Create a new VDM process for a 16-bit or DOS application.
1811 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1812 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1813 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1814 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1815 const struct binary_info *binary_info, int exec_only )
1817 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1820 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1821 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1825 SetLastError( ERROR_OUTOFMEMORY );
1828 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1829 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1830 flags, startup, info, unixdir, binary_info, exec_only );
1831 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1836 /***********************************************************************
1837 * create_cmd_process
1839 * Create a new cmd shell process for a .BAT file.
1841 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1842 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1843 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1844 LPPROCESS_INFORMATION info )
1847 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1848 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1849 WCHAR comspec[MAX_PATH];
1853 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1855 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1856 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1859 strcpyW( newcmdline, comspec );
1860 strcatW( newcmdline, slashcW );
1861 strcatW( newcmdline, cmd_line );
1862 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1863 flags, env, cur_dir, startup, info );
1864 HeapFree( GetProcessHeap(), 0, newcmdline );
1869 /*************************************************************************
1872 * Helper for CreateProcess: retrieve the file name to load from the
1873 * app name and command line. Store the file name in buffer, and
1874 * return a possibly modified command line.
1875 * Also returns a handle to the opened file if it's a Windows binary.
1877 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1878 int buflen, HANDLE *handle, struct binary_info *binary_info )
1880 static const WCHAR quotesW[] = {'"','%','s','"',0};
1882 WCHAR *name, *pos, *ret = NULL;
1886 /* if we have an app name, everything is easy */
1890 /* use the unmodified app name as file name */
1891 lstrcpynW( buffer, appname, buflen );
1892 *handle = open_exe_file( buffer, binary_info );
1893 if (!(ret = cmdline) || !cmdline[0])
1895 /* no command-line, create one */
1896 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1897 sprintfW( ret, quotesW, appname );
1902 /* first check for a quoted file name */
1904 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1906 int len = p - cmdline - 1;
1907 /* extract the quoted portion as file name */
1908 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1909 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1912 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
1913 ret = cmdline; /* no change necessary */
1917 /* now try the command-line word by word */
1919 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1927 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1929 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
1934 if (*p) got_space = TRUE;
1937 if (ret && got_space) /* now build a new command-line with quotes */
1939 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1941 sprintfW( ret, quotesW, name );
1944 else if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
1947 HeapFree( GetProcessHeap(), 0, name );
1952 /**********************************************************************
1953 * CreateProcessA (KERNEL32.@)
1955 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1956 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1957 DWORD flags, LPVOID env, LPCSTR cur_dir,
1958 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1961 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1962 UNICODE_STRING desktopW, titleW;
1965 desktopW.Buffer = NULL;
1966 titleW.Buffer = NULL;
1967 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1968 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1969 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1971 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1972 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1974 memcpy( &infoW, startup_info, sizeof(infoW) );
1975 infoW.lpDesktop = desktopW.Buffer;
1976 infoW.lpTitle = titleW.Buffer;
1978 if (startup_info->lpReserved)
1979 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1980 debugstr_a(startup_info->lpReserved));
1982 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1983 inherit, flags, env, cur_dirW, &infoW, info );
1985 HeapFree( GetProcessHeap(), 0, app_nameW );
1986 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1987 HeapFree( GetProcessHeap(), 0, cur_dirW );
1988 RtlFreeUnicodeString( &desktopW );
1989 RtlFreeUnicodeString( &titleW );
1994 /**********************************************************************
1995 * CreateProcessW (KERNEL32.@)
1997 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1998 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1999 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2000 LPPROCESS_INFORMATION info )
2004 char *unixdir = NULL;
2005 WCHAR name[MAX_PATH];
2006 WCHAR *tidy_cmdline, *p, *envW = env;
2007 struct binary_info binary_info;
2009 /* Process the AppName and/or CmdLine to get module name and path */
2011 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2013 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2014 &hFile, &binary_info )))
2016 if (hFile == INVALID_HANDLE_VALUE) goto done;
2018 /* Warn if unsupported features are used */
2020 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2021 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2022 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2023 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2024 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2028 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2030 SetLastError(ERROR_DIRECTORY);
2036 WCHAR buf[MAX_PATH];
2037 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2040 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2045 while (*p) p += strlen(p) + 1;
2046 p++; /* final null */
2047 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
2048 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2049 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
2050 flags |= CREATE_UNICODE_ENVIRONMENT;
2053 info->hThread = info->hProcess = 0;
2054 info->dwProcessId = info->dwThreadId = 0;
2056 if (binary_info.flags & BINARY_FLAG_DLL)
2058 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2059 SetLastError( ERROR_BAD_EXE_FORMAT );
2061 else switch (binary_info.type)
2064 TRACE( "starting %s as Win32 binary (%p-%p)\n",
2065 debugstr_w(name), binary_info.res_start, binary_info.res_end );
2066 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2067 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2072 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2073 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2074 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2076 case BINARY_UNIX_LIB:
2077 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
2078 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2079 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2081 case BINARY_UNKNOWN:
2082 /* check for .com or .bat extension */
2083 if ((p = strrchrW( name, '.' )))
2085 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2087 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2088 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2089 inherit, flags, startup_info, info, unixdir,
2090 &binary_info, FALSE );
2093 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2095 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2096 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2097 inherit, flags, startup_info, info );
2102 case BINARY_UNIX_EXE:
2104 /* unknown file, try as unix executable */
2107 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2109 if ((unix_name = wine_get_unix_file_name( name )))
2111 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2112 HeapFree( GetProcessHeap(), 0, unix_name );
2117 if (hFile) CloseHandle( hFile );
2120 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2121 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2122 HeapFree( GetProcessHeap(), 0, unixdir );
2124 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2129 /**********************************************************************
2132 static void exec_process( LPCWSTR name )
2136 STARTUPINFOW startup_info;
2137 PROCESS_INFORMATION info;
2138 struct binary_info binary_info;
2140 hFile = open_exe_file( name, &binary_info );
2141 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2143 memset( &startup_info, 0, sizeof(startup_info) );
2144 startup_info.cb = sizeof(startup_info);
2146 /* Determine executable type */
2148 if (binary_info.flags & BINARY_FLAG_DLL) return;
2149 switch (binary_info.type)
2152 TRACE( "starting %s as Win32 binary (%p-%p)\n",
2153 debugstr_w(name), binary_info.res_start, binary_info.res_end );
2154 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2155 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2157 case BINARY_UNIX_LIB:
2158 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2159 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2160 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2162 case BINARY_UNKNOWN:
2163 /* check for .com or .pif extension */
2164 if (!(p = strrchrW( name, '.' ))) break;
2165 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2170 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2171 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2172 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2177 CloseHandle( hFile );
2181 /***********************************************************************
2184 * Wrapper to call WaitForInputIdle USER function
2186 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2188 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2190 HMODULE mod = GetModuleHandleA( "user32.dll" );
2193 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2194 if (ptr) return ptr( process, timeout );
2200 /***********************************************************************
2201 * WinExec (KERNEL32.@)
2203 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2205 PROCESS_INFORMATION info;
2206 STARTUPINFOA startup;
2210 memset( &startup, 0, sizeof(startup) );
2211 startup.cb = sizeof(startup);
2212 startup.dwFlags = STARTF_USESHOWWINDOW;
2213 startup.wShowWindow = nCmdShow;
2215 /* cmdline needs to be writable for CreateProcess */
2216 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2217 strcpy( cmdline, lpCmdLine );
2219 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2220 0, NULL, NULL, &startup, &info ))
2222 /* Give 30 seconds to the app to come up */
2223 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2224 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2226 /* Close off the handles */
2227 CloseHandle( info.hThread );
2228 CloseHandle( info.hProcess );
2230 else if ((ret = GetLastError()) >= 32)
2232 FIXME("Strange error set by CreateProcess: %d\n", ret );
2235 HeapFree( GetProcessHeap(), 0, cmdline );
2240 /**********************************************************************
2241 * LoadModule (KERNEL32.@)
2243 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2245 LOADPARMS32 *params = paramBlock;
2246 PROCESS_INFORMATION info;
2247 STARTUPINFOA startup;
2248 HINSTANCE hInstance;
2250 char filename[MAX_PATH];
2253 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2255 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2256 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2257 return ULongToHandle(GetLastError());
2259 len = (BYTE)params->lpCmdLine[0];
2260 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2261 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2263 strcpy( cmdline, filename );
2264 p = cmdline + strlen(cmdline);
2266 memcpy( p, params->lpCmdLine + 1, len );
2269 memset( &startup, 0, sizeof(startup) );
2270 startup.cb = sizeof(startup);
2271 if (params->lpCmdShow)
2273 startup.dwFlags = STARTF_USESHOWWINDOW;
2274 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2277 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2278 params->lpEnvAddress, NULL, &startup, &info ))
2280 /* Give 30 seconds to the app to come up */
2281 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2282 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2283 hInstance = (HINSTANCE)33;
2284 /* Close off the handles */
2285 CloseHandle( info.hThread );
2286 CloseHandle( info.hProcess );
2288 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2290 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2291 hInstance = (HINSTANCE)11;
2294 HeapFree( GetProcessHeap(), 0, cmdline );
2299 /******************************************************************************
2300 * TerminateProcess (KERNEL32.@)
2302 * Terminates a process.
2305 * handle [I] Process to terminate.
2306 * exit_code [I] Exit code.
2310 * Failure: FALSE, check GetLastError().
2312 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2314 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2315 if (status) SetLastError( RtlNtStatusToDosError(status) );
2319 /***********************************************************************
2320 * ExitProcess (KERNEL32.@)
2322 * Exits the current process.
2325 * status [I] Status code to exit with.
2331 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2333 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2334 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2335 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2337 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2341 void WINAPI process_ExitProcess( DWORD status )
2343 LdrShutdownProcess();
2344 NtTerminateProcess(GetCurrentProcess(), status);
2350 void WINAPI ExitProcess( DWORD status )
2352 LdrShutdownProcess();
2353 NtTerminateProcess(GetCurrentProcess(), status);
2359 /***********************************************************************
2360 * GetExitCodeProcess [KERNEL32.@]
2362 * Gets termination status of specified process.
2365 * hProcess [in] Handle to the process.
2366 * lpExitCode [out] Address to receive termination status.
2372 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2375 PROCESS_BASIC_INFORMATION pbi;
2377 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2379 if (status == STATUS_SUCCESS)
2381 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2384 SetLastError( RtlNtStatusToDosError(status) );
2389 /***********************************************************************
2390 * SetErrorMode (KERNEL32.@)
2392 UINT WINAPI SetErrorMode( UINT mode )
2394 UINT old = process_error_mode;
2395 process_error_mode = mode;
2399 /***********************************************************************
2400 * GetErrorMode (KERNEL32.@)
2402 UINT WINAPI GetErrorMode( void )
2404 return process_error_mode;
2407 /**********************************************************************
2408 * TlsAlloc [KERNEL32.@]
2410 * Allocates a thread local storage index.
2413 * Success: TLS index.
2414 * Failure: 0xFFFFFFFF
2416 DWORD WINAPI TlsAlloc( void )
2419 PEB * const peb = NtCurrentTeb()->Peb;
2421 RtlAcquirePebLock();
2422 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2423 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2426 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2429 if (!NtCurrentTeb()->TlsExpansionSlots &&
2430 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2431 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2433 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2435 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2439 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2440 index += TLS_MINIMUM_AVAILABLE;
2443 else SetLastError( ERROR_NO_MORE_ITEMS );
2445 RtlReleasePebLock();
2450 /**********************************************************************
2451 * TlsFree [KERNEL32.@]
2453 * Releases a thread local storage index, making it available for reuse.
2456 * index [in] TLS index to free.
2462 BOOL WINAPI TlsFree( DWORD index )
2466 RtlAcquirePebLock();
2467 if (index >= TLS_MINIMUM_AVAILABLE)
2469 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2470 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2474 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2475 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2477 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2478 else SetLastError( ERROR_INVALID_PARAMETER );
2479 RtlReleasePebLock();
2484 /**********************************************************************
2485 * TlsGetValue [KERNEL32.@]
2487 * Gets value in a thread's TLS slot.
2490 * index [in] TLS index to retrieve value for.
2493 * Success: Value stored in calling thread's TLS slot for index.
2494 * Failure: 0 and GetLastError() returns NO_ERROR.
2496 LPVOID WINAPI TlsGetValue( DWORD index )
2500 if (index < TLS_MINIMUM_AVAILABLE)
2502 ret = NtCurrentTeb()->TlsSlots[index];
2506 index -= TLS_MINIMUM_AVAILABLE;
2507 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2509 SetLastError( ERROR_INVALID_PARAMETER );
2512 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2513 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2515 SetLastError( ERROR_SUCCESS );
2520 /**********************************************************************
2521 * TlsSetValue [KERNEL32.@]
2523 * Stores a value in the thread's TLS slot.
2526 * index [in] TLS index to set value for.
2527 * value [in] Value to be stored.
2533 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2535 if (index < TLS_MINIMUM_AVAILABLE)
2537 NtCurrentTeb()->TlsSlots[index] = value;
2541 index -= TLS_MINIMUM_AVAILABLE;
2542 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2544 SetLastError( ERROR_INVALID_PARAMETER );
2547 if (!NtCurrentTeb()->TlsExpansionSlots &&
2548 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2549 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2551 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2554 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2560 /***********************************************************************
2561 * GetProcessFlags (KERNEL32.@)
2563 DWORD WINAPI GetProcessFlags( DWORD processid )
2565 IMAGE_NT_HEADERS *nt;
2568 if (processid && processid != GetCurrentProcessId()) return 0;
2570 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2572 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2573 flags |= PDB32_CONSOLE_PROC;
2575 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2576 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2581 /***********************************************************************
2582 * GetProcessDword (KERNEL32.18)
2584 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2586 FIXME( "(%d, %d): not supported\n", dwProcessID, offset );
2591 /*********************************************************************
2592 * OpenProcess (KERNEL32.@)
2594 * Opens a handle to a process.
2597 * access [I] Desired access rights assigned to the returned handle.
2598 * inherit [I] Determines whether or not child processes will inherit the handle.
2599 * id [I] Process identifier of the process to get a handle to.
2602 * Success: Valid handle to the specified process.
2603 * Failure: NULL, check GetLastError().
2605 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2609 OBJECT_ATTRIBUTES attr;
2612 cid.UniqueProcess = ULongToHandle(id);
2613 cid.UniqueThread = 0; /* FIXME ? */
2615 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2616 attr.RootDirectory = NULL;
2617 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2618 attr.SecurityDescriptor = NULL;
2619 attr.SecurityQualityOfService = NULL;
2620 attr.ObjectName = NULL;
2622 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2624 status = NtOpenProcess(&handle, access, &attr, &cid);
2625 if (status != STATUS_SUCCESS)
2627 SetLastError( RtlNtStatusToDosError(status) );
2634 /*********************************************************************
2635 * GetProcessId (KERNEL32.@)
2637 * Gets the a unique identifier of a process.
2640 * hProcess [I] Handle to the process.
2644 * Failure: FALSE, check GetLastError().
2648 * The identifier is unique only on the machine and only until the process
2649 * exits (including system shutdown).
2651 DWORD WINAPI GetProcessId( HANDLE hProcess )
2654 PROCESS_BASIC_INFORMATION pbi;
2656 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2658 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2659 SetLastError( RtlNtStatusToDosError(status) );
2664 /*********************************************************************
2665 * CloseHandle (KERNEL32.@)
2670 * handle [I] Handle to close.
2674 * Failure: FALSE, check GetLastError().
2676 BOOL WINAPI CloseHandle( HANDLE handle )
2680 /* stdio handles need special treatment */
2681 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2682 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2683 (handle == (HANDLE)STD_ERROR_HANDLE))
2684 handle = GetStdHandle( HandleToULong(handle) );
2686 if (is_console_handle(handle))
2687 return CloseConsoleHandle(handle);
2689 status = NtClose( handle );
2690 if (status) SetLastError( RtlNtStatusToDosError(status) );
2695 /*********************************************************************
2696 * GetHandleInformation (KERNEL32.@)
2698 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2700 OBJECT_DATA_INFORMATION info;
2701 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2703 if (status) SetLastError( RtlNtStatusToDosError(status) );
2707 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2708 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2714 /*********************************************************************
2715 * SetHandleInformation (KERNEL32.@)
2717 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2719 OBJECT_DATA_INFORMATION info;
2722 /* if not setting both fields, retrieve current value first */
2723 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2724 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2726 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2728 SetLastError( RtlNtStatusToDosError(status) );
2732 if (mask & HANDLE_FLAG_INHERIT)
2733 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2734 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2735 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2737 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2738 if (status) SetLastError( RtlNtStatusToDosError(status) );
2743 /*********************************************************************
2744 * DuplicateHandle (KERNEL32.@)
2746 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2747 HANDLE dest_process, HANDLE *dest,
2748 DWORD access, BOOL inherit, DWORD options )
2752 if (is_console_handle(source))
2754 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2755 if (source_process != dest_process ||
2756 source_process != GetCurrentProcess())
2758 SetLastError(ERROR_INVALID_PARAMETER);
2761 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2762 return (*dest != INVALID_HANDLE_VALUE);
2764 status = NtDuplicateObject( source_process, source, dest_process, dest,
2765 access, inherit ? OBJ_INHERIT : 0, options );
2766 if (status) SetLastError( RtlNtStatusToDosError(status) );
2771 /***********************************************************************
2772 * ConvertToGlobalHandle (KERNEL32.@)
2774 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2776 HANDLE ret = INVALID_HANDLE_VALUE;
2777 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2778 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2783 /***********************************************************************
2784 * SetHandleContext (KERNEL32.@)
2786 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2788 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2789 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2790 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2795 /***********************************************************************
2796 * GetHandleContext (KERNEL32.@)
2798 DWORD WINAPI GetHandleContext(HANDLE hnd)
2800 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2801 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2802 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2807 /***********************************************************************
2808 * CreateSocketHandle (KERNEL32.@)
2810 HANDLE WINAPI CreateSocketHandle(void)
2812 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2813 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2814 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2815 return INVALID_HANDLE_VALUE;
2819 /***********************************************************************
2820 * SetPriorityClass (KERNEL32.@)
2822 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2825 PROCESS_PRIORITY_CLASS ppc;
2827 ppc.Foreground = FALSE;
2828 switch (priorityclass)
2830 case IDLE_PRIORITY_CLASS:
2831 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2832 case BELOW_NORMAL_PRIORITY_CLASS:
2833 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2834 case NORMAL_PRIORITY_CLASS:
2835 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2836 case ABOVE_NORMAL_PRIORITY_CLASS:
2837 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2838 case HIGH_PRIORITY_CLASS:
2839 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2840 case REALTIME_PRIORITY_CLASS:
2841 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2843 SetLastError(ERROR_INVALID_PARAMETER);
2847 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2850 if (status != STATUS_SUCCESS)
2852 SetLastError( RtlNtStatusToDosError(status) );
2859 /***********************************************************************
2860 * GetPriorityClass (KERNEL32.@)
2862 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2865 PROCESS_BASIC_INFORMATION pbi;
2867 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2869 if (status != STATUS_SUCCESS)
2871 SetLastError( RtlNtStatusToDosError(status) );
2874 switch (pbi.BasePriority)
2876 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2877 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2878 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2879 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2880 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2881 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2883 SetLastError( ERROR_INVALID_PARAMETER );
2888 /***********************************************************************
2889 * SetProcessAffinityMask (KERNEL32.@)
2891 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2895 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2896 &affmask, sizeof(DWORD_PTR));
2899 SetLastError( RtlNtStatusToDosError(status) );
2906 /**********************************************************************
2907 * GetProcessAffinityMask (KERNEL32.@)
2909 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2910 PDWORD_PTR lpProcessAffinityMask,
2911 PDWORD_PTR lpSystemAffinityMask )
2913 PROCESS_BASIC_INFORMATION pbi;
2916 status = NtQueryInformationProcess(hProcess,
2917 ProcessBasicInformation,
2918 &pbi, sizeof(pbi), NULL);
2921 SetLastError( RtlNtStatusToDosError(status) );
2924 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2925 if (lpSystemAffinityMask) *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2930 /***********************************************************************
2931 * GetProcessVersion (KERNEL32.@)
2933 DWORD WINAPI GetProcessVersion( DWORD pid )
2937 PROCESS_BASIC_INFORMATION pbi;
2940 IMAGE_DOS_HEADER dos;
2941 IMAGE_NT_HEADERS nt;
2944 if (!pid || pid == GetCurrentProcessId())
2946 IMAGE_NT_HEADERS *nt;
2948 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2949 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2950 nt->OptionalHeader.MinorSubsystemVersion);
2954 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
2955 if (!process) return 0;
2957 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
2958 if (status) goto err;
2960 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
2961 if (status || count != sizeof(peb)) goto err;
2963 memset(&dos, 0, sizeof(dos));
2964 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
2965 if (status || count != sizeof(dos)) goto err;
2966 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
2968 memset(&nt, 0, sizeof(nt));
2969 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
2970 if (status || count != sizeof(nt)) goto err;
2971 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
2973 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
2976 CloseHandle(process);
2978 if (status != STATUS_SUCCESS)
2979 SetLastError(RtlNtStatusToDosError(status));
2985 /***********************************************************************
2986 * SetProcessWorkingSetSize [KERNEL32.@]
2987 * Sets the min/max working set sizes for a specified process.
2990 * hProcess [I] Handle to the process of interest
2991 * minset [I] Specifies minimum working set size
2992 * maxset [I] Specifies maximum working set size
2998 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3001 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3002 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3003 /* Trim the working set to zero */
3004 /* Swap the process out of physical RAM */
3009 /***********************************************************************
3010 * GetProcessWorkingSetSize (KERNEL32.@)
3012 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3015 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3016 /* 32 MB working set size */
3017 if (minset) *minset = 32*1024*1024;
3018 if (maxset) *maxset = 32*1024*1024;
3023 /***********************************************************************
3024 * SetProcessShutdownParameters (KERNEL32.@)
3026 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3028 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3029 shutdown_flags = flags;
3030 shutdown_priority = level;
3035 /***********************************************************************
3036 * GetProcessShutdownParameters (KERNEL32.@)
3039 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3041 *lpdwLevel = shutdown_priority;
3042 *lpdwFlags = shutdown_flags;
3047 /***********************************************************************
3048 * GetProcessPriorityBoost (KERNEL32.@)
3050 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3052 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3054 /* Report that no boost is present.. */
3055 *pDisablePriorityBoost = FALSE;
3060 /***********************************************************************
3061 * SetProcessPriorityBoost (KERNEL32.@)
3063 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3065 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3066 /* Say we can do it. I doubt the program will notice that we don't. */
3071 /***********************************************************************
3072 * ReadProcessMemory (KERNEL32.@)
3074 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3075 SIZE_T *bytes_read )
3077 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3078 if (status) SetLastError( RtlNtStatusToDosError(status) );
3083 /***********************************************************************
3084 * WriteProcessMemory (KERNEL32.@)
3086 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3087 SIZE_T *bytes_written )
3089 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3090 if (status) SetLastError( RtlNtStatusToDosError(status) );
3095 /****************************************************************************
3096 * FlushInstructionCache (KERNEL32.@)
3098 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3101 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3102 if (status) SetLastError( RtlNtStatusToDosError(status) );
3107 /******************************************************************
3108 * GetProcessIoCounters (KERNEL32.@)
3110 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3114 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3115 ioc, sizeof(*ioc), NULL);
3116 if (status) SetLastError( RtlNtStatusToDosError(status) );
3120 /******************************************************************
3121 * GetProcessHandleCount (KERNEL32.@)
3123 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3127 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3128 cnt, sizeof(*cnt), NULL);
3129 if (status) SetLastError( RtlNtStatusToDosError(status) );
3133 /******************************************************************
3134 * QueryFullProcessImageNameA (KERNEL32.@)
3136 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3139 DWORD pdwSizeW = *pdwSize;
3140 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3142 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3145 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3146 lpExeName, *pdwSize, NULL, NULL));
3148 *pdwSize = strlen(lpExeName);
3150 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3154 /******************************************************************
3155 * QueryFullProcessImageNameW (KERNEL32.@)
3157 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3159 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3160 UNICODE_STRING *dynamic_buffer = NULL;
3161 UNICODE_STRING nt_path;
3162 UNICODE_STRING *result = NULL;
3166 RtlInitUnicodeStringEx(&nt_path, NULL);
3167 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3168 * as this is on Wine. */
3169 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3170 sizeof(buffer) - sizeof(WCHAR), &needed);
3171 if (status == STATUS_INFO_LENGTH_MISMATCH)
3173 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3174 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3175 result = dynamic_buffer;
3178 result = (PUNICODE_STRING)buffer;
3180 if (status) goto cleanup;
3182 if (dwFlags & PROCESS_NAME_NATIVE)
3184 result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3185 if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3187 status = STATUS_OBJECT_PATH_NOT_FOUND;
3193 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3195 status = STATUS_BUFFER_TOO_SMALL;
3199 *pdwSize = result->Length/sizeof(WCHAR);
3200 memcpy( lpExeName, result->Buffer, result->Length );
3201 lpExeName[*pdwSize] = 0;
3204 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3205 RtlFreeUnicodeString(&nt_path);
3206 if (status) SetLastError( RtlNtStatusToDosError(status) );
3210 /***********************************************************************
3211 * ProcessIdToSessionId (KERNEL32.@)
3212 * This function is available on Terminal Server 4SP4 and Windows 2000
3214 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3216 /* According to MSDN, if the calling process is not in a terminal
3217 * services environment, then the sessionid returned is zero.
3224 /***********************************************************************
3225 * RegisterServiceProcess (KERNEL32.@)
3227 * A service process calls this function to ensure that it continues to run
3228 * even after a user logged off.
3230 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3232 /* I don't think that Wine needs to do anything in this function */
3233 return 1; /* success */
3237 /**********************************************************************
3238 * IsWow64Process (KERNEL32.@)
3240 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3245 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3247 if (status != STATUS_SUCCESS)
3249 SetLastError( RtlNtStatusToDosError( status ) );
3252 *Wow64Process = (pbi != 0);
3257 /***********************************************************************
3258 * GetCurrentProcess (KERNEL32.@)
3260 * Get a handle to the current process.
3266 * A handle representing the current process.
3268 #undef GetCurrentProcess
3269 HANDLE WINAPI GetCurrentProcess(void)
3271 return (HANDLE)~(ULONG_PTR)0;
3274 /***********************************************************************
3275 * CmdBatNotification (KERNEL32.@)
3277 * Notifies the system that a batch file has started or finished.
3280 * bBatchRunning [I] TRUE if a batch file has started or
3281 * FALSE if a batch file has finished executing.
3286 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3288 FIXME("%d\n", bBatchRunning);
3293 /***********************************************************************
3294 * RegisterApplicationRestart (KERNEL32.@)
3296 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3298 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3303 /**********************************************************************
3304 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3306 DWORD WINAPI WTSGetActiveConsoleSessionId(void)