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 )
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) ))
220 /***********************************************************************
223 * Open an exe file, and return the full name and file handle.
224 * Returns FALSE if file could not be found.
225 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
226 * If file is a builtin exe, returns TRUE and sets handle to 0.
228 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
230 static const WCHAR exeW[] = {'.','e','x','e',0};
233 TRACE("looking for %s\n", debugstr_w(name) );
235 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
236 !get_builtin_path( name, exeW, buffer, buflen ))
238 /* no builtin found, try native without extension in case it is a Unix app */
240 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
242 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
243 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
244 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
250 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
251 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
252 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
255 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
256 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
267 /***********************************************************************
268 * build_initial_environment
270 * Build the Win32 environment from the Unix environment
272 static BOOL build_initial_environment(void)
278 char **env = __wine_get_main_environment();
280 /* Compute the total size of the Unix environment */
281 for (e = env; *e; e++)
283 if (is_special_env_var( *e )) continue;
284 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
286 size *= sizeof(WCHAR);
288 /* Now allocate the environment */
290 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
291 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
294 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
295 endptr = p + size / sizeof(WCHAR);
297 /* And fill it with the Unix environment */
298 for (e = env; *e; e++)
302 /* skip Unix special variables and use the Wine variants instead */
303 if (!strncmp( str, "WINE", 4 ))
305 if (is_special_env_var( str + 4 )) str += 4;
306 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
308 else if (is_special_env_var( str )) continue; /* skip it */
310 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
318 /***********************************************************************
319 * set_registry_variables
321 * Set environment variables by enumerating the values of a key;
322 * helper for set_registry_environment().
323 * Note that Windows happily truncates the value if it's too big.
325 static void set_registry_variables( HANDLE hkey, ULONG type )
327 UNICODE_STRING env_name, env_value;
331 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
332 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
334 for (index = 0; ; index++)
336 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
337 buffer, sizeof(buffer), &size );
338 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
340 if (info->Type != type)
342 env_name.Buffer = info->Name;
343 env_name.Length = env_name.MaximumLength = info->NameLength;
344 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
345 env_value.Length = env_value.MaximumLength = info->DataLength;
346 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
347 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
348 if (info->Type == REG_EXPAND_SZ)
350 WCHAR buf_expanded[1024];
351 UNICODE_STRING env_expanded;
352 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
353 env_expanded.Buffer=buf_expanded;
354 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
355 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
356 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
360 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
366 /***********************************************************************
367 * set_registry_environment
369 * Set the environment variables specified in the registry.
371 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
372 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
373 * on the order in which the variables are processed. But on Windows it
374 * does not really matter since they only use %SystemDrive% and
375 * %SystemRoot% which are predefined. But Wine defines these in the
376 * registry, so we need two passes.
378 static BOOL set_registry_environment(void)
380 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
381 'S','y','s','t','e','m','\\',
382 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
383 'C','o','n','t','r','o','l','\\',
384 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
385 'E','n','v','i','r','o','n','m','e','n','t',0};
386 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
388 OBJECT_ATTRIBUTES attr;
389 UNICODE_STRING nameW;
393 attr.Length = sizeof(attr);
394 attr.RootDirectory = 0;
395 attr.ObjectName = &nameW;
397 attr.SecurityDescriptor = NULL;
398 attr.SecurityQualityOfService = NULL;
400 /* first the system environment variables */
401 RtlInitUnicodeString( &nameW, env_keyW );
402 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
404 set_registry_variables( hkey, REG_SZ );
405 set_registry_variables( hkey, REG_EXPAND_SZ );
410 /* then the ones for the current user */
411 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
412 RtlInitUnicodeString( &nameW, envW );
413 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
415 set_registry_variables( hkey, REG_SZ );
416 set_registry_variables( hkey, REG_EXPAND_SZ );
419 NtClose( attr.RootDirectory );
424 /***********************************************************************
427 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
429 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
430 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
431 DWORD len, size = sizeof(buffer);
433 UNICODE_STRING nameW;
435 RtlInitUnicodeString( &nameW, name );
436 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
439 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
440 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
442 if (info->Type == REG_EXPAND_SZ)
444 UNICODE_STRING value, expanded;
446 value.MaximumLength = len * sizeof(WCHAR);
447 value.Buffer = (WCHAR *)info->Data;
448 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
449 value.Length = len * sizeof(WCHAR);
450 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
451 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
452 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
453 else RtlFreeUnicodeString( &expanded );
455 else if (info->Type == REG_SZ)
457 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
459 memcpy( ret, info->Data, len * sizeof(WCHAR) );
467 /***********************************************************************
468 * set_additional_environment
470 * Set some additional environment variables not specified in the registry.
472 static void set_additional_environment(void)
474 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
475 'S','o','f','t','w','a','r','e','\\',
476 'M','i','c','r','o','s','o','f','t','\\',
477 'W','i','n','d','o','w','s',' ','N','T','\\',
478 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
479 'P','r','o','f','i','l','e','L','i','s','t',0};
480 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
481 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
482 static const WCHAR usernameW[] = {'U','S','E','R','N','A','M','E',0};
483 static const WCHAR userprofileW[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
484 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
485 OBJECT_ATTRIBUTES attr;
486 UNICODE_STRING nameW;
487 WCHAR *user_name = NULL, *profile_dir = NULL, *all_users_dir = NULL;
489 const char *name = wine_get_user_name();
492 /* set the USERNAME variable */
494 len = MultiByteToWideChar( CP_UNIXCP, 0, name, -1, NULL, 0 );
497 user_name = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
498 MultiByteToWideChar( CP_UNIXCP, 0, name, -1, user_name, len );
499 SetEnvironmentVariableW( usernameW, user_name );
501 else WARN( "user name %s not convertible.\n", debugstr_a(name) );
503 /* set the USERPROFILE and ALLUSERSPROFILE variables */
505 attr.Length = sizeof(attr);
506 attr.RootDirectory = 0;
507 attr.ObjectName = &nameW;
509 attr.SecurityDescriptor = NULL;
510 attr.SecurityQualityOfService = NULL;
511 RtlInitUnicodeString( &nameW, profile_keyW );
512 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
514 profile_dir = get_reg_value( hkey, profiles_valueW );
515 all_users_dir = get_reg_value( hkey, all_users_valueW );
523 if (all_users_dir) len = max( len, strlenW(all_users_dir) + 1 );
524 len += strlenW(profile_dir) + 1;
525 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
526 strcpyW( value, profile_dir );
527 p = value + strlenW(value);
528 if (p > value && p[-1] != '\\') *p++ = '\\';
530 strcpyW( p, user_name );
531 SetEnvironmentVariableW( userprofileW, value );
535 strcpyW( p, all_users_dir );
536 SetEnvironmentVariableW( allusersW, value );
538 HeapFree( GetProcessHeap(), 0, value );
541 HeapFree( GetProcessHeap(), 0, all_users_dir );
542 HeapFree( GetProcessHeap(), 0, profile_dir );
543 HeapFree( GetProcessHeap(), 0, user_name );
546 /***********************************************************************
549 * Set the Wine library Unicode argv global variables.
551 static void set_library_wargv( char **argv )
559 for (argc = 0; argv[argc]; argc++)
560 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
562 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
563 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
564 p = (WCHAR *)(wargv + argc + 1);
565 for (argc = 0; argv[argc]; argc++)
567 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
574 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
576 for (argc = 0; wargv[argc]; argc++)
577 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
579 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
580 q = (char *)(argv + argc + 1);
581 for (argc = 0; wargv[argc]; argc++)
583 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
590 __wine_main_argc = argc;
591 __wine_main_argv = argv;
592 __wine_main_wargv = wargv;
596 /***********************************************************************
597 * update_library_argv0
599 * Update the argv[0] global variable with the binary we have found.
601 static void update_library_argv0( const WCHAR *argv0 )
603 DWORD len = strlenW( argv0 );
605 if (len > strlenW( __wine_main_wargv[0] ))
607 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
609 strcpyW( __wine_main_wargv[0], argv0 );
611 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
612 if (len > strlen( __wine_main_argv[0] ) + 1)
614 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
616 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
620 /***********************************************************************
623 * Build the command line of a process from the argv array.
625 * Note that it does NOT necessarily include the file name.
626 * Sometimes we don't even have any command line options at all.
628 * We must quote and escape characters so that the argv array can be rebuilt
629 * from the command line:
630 * - spaces and tabs must be quoted
632 * - quotes must be escaped
634 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
635 * resulting in an odd number of '\' followed by a '"'
638 * - '\'s that are not followed by a '"' can be left as is
642 static BOOL build_command_line( WCHAR **argv )
647 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
649 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
652 for (arg = argv; *arg; arg++)
654 int has_space,bcount;
660 if( !*a ) has_space=1;
665 if (*a==' ' || *a=='\t') {
667 } else if (*a=='"') {
668 /* doubling of '\' preceding a '"',
669 * plus escaping of said '"'
677 len+=(a-*arg)+1 /* for the separating space */;
679 len+=2; /* for the quotes */
682 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
685 p = rupp->CommandLine.Buffer;
686 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
687 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
688 for (arg = argv; *arg; arg++)
690 int has_space,has_quote;
693 /* Check for quotes and spaces in this argument */
694 has_space=has_quote=0;
696 if( !*a ) has_space=1;
698 if (*a==' ' || *a=='\t') {
702 } else if (*a=='"') {
710 /* Now transfer it to the command line */
727 /* Double all the '\\' preceding this '"', plus one */
728 for (i=0;i<=bcount;i++)
740 while ((*p=*x++)) p++;
746 if (p > rupp->CommandLine.Buffer)
747 p--; /* remove last space */
754 /***********************************************************************
755 * init_current_directory
757 * Initialize the current directory from the Unix cwd or the parent info.
759 static void init_current_directory( CURDIR *cur_dir )
761 UNICODE_STRING dir_str;
766 /* if we received a cur dir from the parent, try this first */
768 if (cur_dir->DosPath.Length)
770 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
773 /* now try to get it from the Unix cwd */
775 for (size = 256; ; size *= 2)
777 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
778 if (getcwd( cwd, size )) break;
779 HeapFree( GetProcessHeap(), 0, cwd );
780 if (errno == ERANGE) continue;
785 /* try to use PWD if it is valid, so that we don't resolve symlinks */
787 pwd = getenv( "PWD" );
790 struct stat st1, st2;
792 if (!pwd || stat( pwd, &st1 ) == -1 ||
793 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
800 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, pwd, -1, NULL, 0 );
801 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
803 MultiByteToWideChar( CP_UNIXCP, 0, pwd, -1, dirW, lenW );
804 RtlInitUnicodeString( &dir_str, dirW );
805 RtlSetCurrentDirectory_U( &dir_str );
806 RtlFreeUnicodeString( &dir_str );
810 if (!cur_dir->DosPath.Length) /* still not initialized */
812 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
813 "starting in the Windows directory.\n", cwd ? cwd : "" );
814 RtlInitUnicodeString( &dir_str, DIR_Windows );
815 RtlSetCurrentDirectory_U( &dir_str );
817 HeapFree( GetProcessHeap(), 0, cwd );
820 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
821 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
825 /***********************************************************************
828 * Initialize the windows and system directories from the environment.
830 static void init_windows_dirs(void)
832 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
834 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
835 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
836 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
837 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
838 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
843 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
845 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
846 GetEnvironmentVariableW( windirW, buffer, len );
847 DIR_Windows = buffer;
849 else DIR_Windows = default_windirW;
851 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
853 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
854 GetEnvironmentVariableW( winsysdirW, buffer, len );
859 len = strlenW( DIR_Windows );
860 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
861 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
862 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
866 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
867 ERR( "directory %s could not be created, error %u\n",
868 debugstr_w(DIR_Windows), GetLastError() );
869 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
870 ERR( "directory %s could not be created, error %u\n",
871 debugstr_w(DIR_System), GetLastError() );
873 #ifndef _WIN64 /* SysWow64 is always defined on 64-bit */
877 len = strlenW( DIR_Windows );
878 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
879 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
880 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
881 DIR_SysWow64 = buffer;
882 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
883 ERR( "directory %s could not be created, error %u\n",
884 debugstr_w(DIR_SysWow64), GetLastError() );
887 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
888 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
890 /* set the directories in ntdll too */
891 __wine_init_windows_dir( DIR_Windows, DIR_System );
895 /***********************************************************************
898 * Start the wineboot process if necessary. Return the handles to wait on.
900 static void start_wineboot( HANDLE handles[2] )
902 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
905 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
907 ERR( "failed to create wineboot event, expect trouble\n" );
910 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
912 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
913 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
914 const DWORD expected_type = (sizeof(void*) > sizeof(int) || is_wow64) ?
915 SCS_64BIT_BINARY : SCS_32BIT_BINARY;
917 PROCESS_INFORMATION pi;
921 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
923 memset( &si, 0, sizeof(si) );
925 si.dwFlags = STARTF_USESTDHANDLES;
928 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
930 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
931 lstrcatW( app, wineboot );
933 Wow64DisableWow64FsRedirection( &redir );
934 if (GetBinaryTypeW( app, &type ) && type != expected_type)
936 if (type == SCS_64BIT_BINARY)
937 MESSAGE( "wine: '%s' is a 64-bit prefix, it cannot be used with 32-bit Wine.\n",
938 wine_get_config_dir() );
940 MESSAGE( "wine: '%s' is a 32-bit prefix, it cannot be used with %s Wine.\n",
941 wine_get_config_dir(), is_wow64 ? "wow64" : "64-bit" );
945 strcpyW( cmdline, app );
946 strcatW( cmdline, args );
947 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
949 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
950 CloseHandle( pi.hThread );
951 handles[1] = pi.hProcess;
955 ERR( "failed to start wineboot, err %u\n", GetLastError() );
956 CloseHandle( handles[0] );
959 Wow64RevertWow64FsRedirection( redir );
964 /***********************************************************************
967 * Startup routine of a new process. Runs on the new process stack.
969 static DWORD WINAPI start_process( PEB *peb )
971 IMAGE_NT_HEADERS *nt;
972 LPTHREAD_START_ROUTINE entry;
974 nt = RtlImageNtHeader( peb->ImageBaseAddress );
975 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
976 nt->OptionalHeader.AddressOfEntryPoint);
978 if (!nt->OptionalHeader.AddressOfEntryPoint)
980 ERR( "%s doesn't have an entry point, it cannot be executed\n",
981 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
986 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
987 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
989 SetLastError( 0 ); /* clear error code */
990 if (peb->BeingDebugged) DbgBreakPoint();
995 /***********************************************************************
998 * Change the process name in the ps output.
1000 static void set_process_name( int argc, char *argv[] )
1002 #ifdef HAVE_SETPROCTITLE
1003 setproctitle("-%s", argv[1]);
1008 char *p, *prctl_name = argv[1];
1009 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1012 # define PR_SET_NAME 15
1015 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1016 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1018 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1020 offset = argv[1] - argv[0];
1021 memmove( argv[1] - offset, argv[1], end - argv[1] );
1022 memset( end - offset, 0, offset );
1023 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1027 #endif /* HAVE_PRCTL */
1029 /* remove argv[0] */
1030 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1035 /***********************************************************************
1036 * __wine_kernel_init
1038 * Wine initialisation: load and start the main exe file.
1040 void CDECL __wine_kernel_init(void)
1042 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1043 static const WCHAR dotW[] = {'.',0};
1044 static const WCHAR exeW[] = {'.','e','x','e',0};
1046 WCHAR *p, main_exe_name[MAX_PATH+1];
1047 PEB *peb = NtCurrentTeb()->Peb;
1048 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1049 HANDLE boot_events[2];
1050 BOOL got_environment = TRUE;
1052 /* Initialize everything */
1054 setbuf(stdout,NULL);
1055 setbuf(stderr,NULL);
1056 kernel32_handle = GetModuleHandleW(kernel32W);
1057 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1061 if (!params->Environment)
1063 /* Copy the parent environment */
1064 if (!build_initial_environment()) exit(1);
1066 /* convert old configuration to new format */
1067 convert_old_config();
1069 got_environment = set_registry_environment();
1070 set_additional_environment();
1073 init_windows_dirs();
1074 init_current_directory( ¶ms->CurrentDirectory );
1076 set_process_name( __wine_main_argc, __wine_main_argv );
1077 set_library_wargv( __wine_main_argv );
1078 boot_events[0] = boot_events[1] = 0;
1080 if (peb->ProcessParameters->ImagePathName.Buffer)
1082 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1086 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1087 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH ))
1089 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1090 ExitProcess( GetLastError() );
1092 update_library_argv0( main_exe_name );
1093 if (!build_command_line( __wine_main_wargv )) goto error;
1094 start_wineboot( boot_events );
1097 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1098 p = strrchrW( main_exe_name, '.' );
1099 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1101 TRACE( "starting process name=%s argv[0]=%s\n",
1102 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1104 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1105 MODULE_get_dll_load_path(main_exe_name) );
1109 DWORD timeout = 30000, count = 1;
1111 if (boot_events[1]) count++;
1112 if (!got_environment) timeout = 300000; /* initial prefix creation can take longer */
1113 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1114 ERR( "boot event wait timed out\n" );
1115 CloseHandle( boot_events[0] );
1116 if (boot_events[1]) CloseHandle( boot_events[1] );
1117 /* if we didn't find environment section, try again now that wineboot has run */
1118 if (!got_environment)
1120 set_registry_environment();
1121 set_additional_environment();
1125 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1128 DWORD error = GetLastError();
1130 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1131 if (error == ERROR_BAD_EXE_FORMAT ||
1132 error == ERROR_INVALID_ADDRESS ||
1133 error == ERROR_NOT_ENOUGH_MEMORY)
1135 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1136 /* if we get back here, it failed */
1138 else if (error == ERROR_MOD_NOT_FOUND)
1140 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1141 else p = main_exe_name;
1142 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1144 /* args 1 and 2 are --app-name full_path */
1145 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1146 debugstr_w(__wine_main_wargv[3]) );
1147 ExitProcess( ERROR_BAD_EXE_FORMAT );
1150 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, msg, sizeof(msg), NULL );
1151 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name), msg );
1152 ExitProcess( error );
1155 LdrInitializeThunk( start_process, 0, 0, 0 );
1158 ExitProcess( GetLastError() );
1162 /***********************************************************************
1165 * Build an argv array from a command-line.
1166 * 'reserved' is the number of args to reserve before the first one.
1168 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1172 char *arg,*s,*d,*cmdline;
1173 int in_quotes,bcount,len;
1175 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1176 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1177 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1184 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1187 /* skip the remaining spaces */
1188 while (*s==' ' || *s=='\t') {
1195 } else if (*s=='\\') {
1196 /* '\', count them */
1198 } else if ((*s=='"') && ((bcount & 1)==0)) {
1200 in_quotes=!in_quotes;
1203 /* a regular character */
1208 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1210 HeapFree( GetProcessHeap(), 0, cmdline );
1214 arg = d = s = (char *)(argv + argc);
1215 memcpy( d, cmdline, len );
1220 if ((*s==' ' || *s=='\t') && !in_quotes) {
1221 /* Close the argument and copy it */
1225 /* skip the remaining spaces */
1228 } while (*s==' ' || *s=='\t');
1230 /* Start with a new argument */
1233 } else if (*s=='\\') {
1237 } else if (*s=='"') {
1239 if ((bcount & 1)==0) {
1240 /* Preceded by an even number of '\', this is half that
1241 * number of '\', plus a '"' which we discard.
1245 in_quotes=!in_quotes;
1247 /* Preceded by an odd number of '\', this is half that
1248 * number of '\' followed by a '"'
1256 /* a regular character */
1267 HeapFree( GetProcessHeap(), 0, cmdline );
1272 /***********************************************************************
1275 * Build the environment of a new child process.
1277 static char **build_envp( const WCHAR *envW )
1279 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1284 int count = 1, length;
1287 for (end = envW; *end; count++) end += strlenW(end) + 1;
1289 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1290 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1291 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1293 for (p = env; *p; p += strlen(p) + 1)
1294 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1296 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1298 if (!(p = getenv(unix_vars[i]))) continue;
1299 length += strlen(unix_vars[i]) + strlen(p) + 2;
1303 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1305 char **envptr = envp;
1306 char *dst = (char *)(envp + count);
1308 /* some variables must not be modified, so we get them directly from the unix env */
1309 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1311 if (!(p = getenv(unix_vars[i]))) continue;
1312 *envptr++ = strcpy( dst, unix_vars[i] );
1315 dst += strlen(dst) + 1;
1318 /* now put the Windows environment strings */
1319 for (p = env; *p; p += strlen(p) + 1)
1321 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1322 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1323 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1324 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1325 if (is_special_env_var( p )) /* prefix it with "WINE" */
1327 *envptr++ = strcpy( dst, "WINE" );
1332 *envptr++ = strcpy( dst, p );
1334 dst += strlen(dst) + 1;
1338 HeapFree( GetProcessHeap(), 0, env );
1343 /***********************************************************************
1346 * Fork and exec a new Unix binary, checking for errors.
1348 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1349 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1351 int fd[2], stdin_fd = -1, stdout_fd = -1;
1353 char **argv, **envp;
1355 if (!env) env = GetEnvironmentStringsW();
1358 if (pipe2( fd, O_CLOEXEC ) == -1)
1363 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1366 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1367 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1370 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1372 HANDLE hstdin, hstdout;
1374 if (startup->dwFlags & STARTF_USESTDHANDLES)
1376 hstdin = startup->hStdInput;
1377 hstdout = startup->hStdOutput;
1381 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1382 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1385 if (is_console_handle( hstdin ))
1386 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1387 if (is_console_handle( hstdout ))
1388 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1389 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1390 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1393 argv = build_argv( cmdline, 0 );
1394 envp = build_envp( env );
1396 if (!(pid = fork())) /* child */
1400 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1403 if (!(pid = fork()))
1405 int fd = open( "/dev/null", O_RDWR );
1407 /* close stdin and stdout */
1415 else if (pid != -1) _exit(0); /* parent */
1421 dup2( stdin_fd, 0 );
1424 if (stdout_fd != -1)
1426 dup2( stdout_fd, 1 );
1431 /* Reset signals that we previously set to SIG_IGN */
1432 signal( SIGPIPE, SIG_DFL );
1433 signal( SIGCHLD, SIG_DFL );
1435 if (newdir) chdir(newdir);
1437 if (argv && envp) execve( filename, argv, envp );
1439 write( fd[1], &err, sizeof(err) );
1442 HeapFree( GetProcessHeap(), 0, argv );
1443 HeapFree( GetProcessHeap(), 0, envp );
1444 if (stdin_fd != -1) close( stdin_fd );
1445 if (stdout_fd != -1) close( stdout_fd );
1447 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1452 if (pid == -1) FILE_SetDosError();
1458 static inline DWORD append_string( void **ptr, const WCHAR *str )
1460 DWORD len = strlenW( str );
1461 memcpy( *ptr, str, len * sizeof(WCHAR) );
1462 *ptr = (WCHAR *)*ptr + len;
1463 return len * sizeof(WCHAR);
1466 /***********************************************************************
1467 * create_startup_info
1469 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1470 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1471 const STARTUPINFOW *startup, DWORD *info_size )
1473 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1474 startup_info_t *info;
1477 UNICODE_STRING newdir;
1478 WCHAR imagepath[MAX_PATH];
1479 HANDLE hstdin, hstdout, hstderr;
1481 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1482 lstrcpynW( imagepath, filename, MAX_PATH );
1483 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1484 lstrcpynW( imagepath, filename, MAX_PATH );
1486 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1488 newdir.Buffer = NULL;
1491 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1492 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1498 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1499 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1501 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1504 size = sizeof(*info);
1505 size += strlenW( cur_dir ) * sizeof(WCHAR);
1506 size += cur_params->DllPath.Length;
1507 size += strlenW( imagepath ) * sizeof(WCHAR);
1508 size += strlenW( cmdline ) * sizeof(WCHAR);
1509 if (startup->lpTitle) size += strlenW( startup->lpTitle ) * sizeof(WCHAR);
1510 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1511 /* FIXME: shellinfo */
1512 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1513 size = (size + 1) & ~1;
1516 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1518 info->console_flags = cur_params->ConsoleFlags;
1519 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1520 if (flags & CREATE_NEW_CONSOLE) info->console = (obj_handle_t)1; /* FIXME: cf. kernel_main.c */
1522 if (startup->dwFlags & STARTF_USESTDHANDLES)
1524 hstdin = startup->hStdInput;
1525 hstdout = startup->hStdOutput;
1526 hstderr = startup->hStdError;
1530 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1531 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1532 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1534 info->hstdin = wine_server_obj_handle( hstdin );
1535 info->hstdout = wine_server_obj_handle( hstdout );
1536 info->hstderr = wine_server_obj_handle( hstderr );
1537 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1539 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1540 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1541 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1542 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1546 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1547 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1548 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1551 info->x = startup->dwX;
1552 info->y = startup->dwY;
1553 info->xsize = startup->dwXSize;
1554 info->ysize = startup->dwYSize;
1555 info->xchars = startup->dwXCountChars;
1556 info->ychars = startup->dwYCountChars;
1557 info->attribute = startup->dwFillAttribute;
1558 info->flags = startup->dwFlags;
1559 info->show = startup->wShowWindow;
1562 info->curdir_len = append_string( &ptr, cur_dir );
1563 info->dllpath_len = cur_params->DllPath.Length;
1564 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1565 ptr = (char *)ptr + cur_params->DllPath.Length;
1566 info->imagepath_len = append_string( &ptr, imagepath );
1567 info->cmdline_len = append_string( &ptr, cmdline );
1568 if (startup->lpTitle) info->title_len = append_string( &ptr, startup->lpTitle );
1569 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1570 if (startup->lpReserved2 && startup->cbReserved2)
1572 info->runtime_len = startup->cbReserved2;
1573 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1577 RtlFreeUnicodeString( &newdir );
1582 /***********************************************************************
1585 * Create a new process. If hFile is a valid handle we have an exe
1586 * file, otherwise it is a Winelib app.
1588 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1589 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1590 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1591 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1592 const struct binary_info *binary_info, int exec_only )
1594 BOOL ret, success = FALSE;
1595 HANDLE process_info;
1597 char *winedebug = NULL;
1599 startup_info_t *startup_info;
1600 DWORD startup_info_size;
1601 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1605 if (sizeof(void *) == sizeof(int) && !is_wow64 && (binary_info->flags & BINARY_FLAG_64BIT))
1607 ERR( "starting 64-bit process %s not supported on this platform\n", debugstr_w(filename) );
1608 SetLastError( ERROR_BAD_EXE_FORMAT );
1612 RtlAcquirePebLock();
1614 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1615 &startup_info_size )))
1617 RtlReleasePebLock();
1620 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
1624 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1625 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1627 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1628 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1629 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1631 env_end += strlenW(env_end) + 1;
1635 /* create the socket for the new process */
1637 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1639 RtlReleasePebLock();
1640 HeapFree( GetProcessHeap(), 0, winedebug );
1641 HeapFree( GetProcessHeap(), 0, startup_info );
1642 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1645 wine_server_send_fd( socketfd[1] );
1646 close( socketfd[1] );
1648 /* create the process on the server side */
1650 SERVER_START_REQ( new_process )
1652 req->inherit_all = inherit;
1653 req->create_flags = flags;
1654 req->socket_fd = socketfd[1];
1655 req->exe_file = wine_server_obj_handle( hFile );
1656 req->process_access = PROCESS_ALL_ACCESS;
1657 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1658 req->thread_access = THREAD_ALL_ACCESS;
1659 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1660 req->info_size = startup_info_size;
1662 wine_server_add_data( req, startup_info, startup_info_size );
1663 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
1664 if ((ret = !wine_server_call_err( req )))
1666 info->dwProcessId = (DWORD)reply->pid;
1667 info->dwThreadId = (DWORD)reply->tid;
1668 info->hProcess = wine_server_ptr_handle( reply->phandle );
1669 info->hThread = wine_server_ptr_handle( reply->thandle );
1671 process_info = wine_server_ptr_handle( reply->info );
1675 RtlReleasePebLock();
1678 close( socketfd[0] );
1679 HeapFree( GetProcessHeap(), 0, startup_info );
1680 HeapFree( GetProcessHeap(), 0, winedebug );
1684 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1686 if (startup_info->hstdin)
1687 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
1688 FILE_READ_DATA, &stdin_fd, NULL );
1689 if (startup_info->hstdout)
1690 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
1691 FILE_WRITE_DATA, &stdout_fd, NULL );
1693 HeapFree( GetProcessHeap(), 0, startup_info );
1695 /* create the child process */
1696 argv = build_argv( cmd_line, 1 );
1698 if (exec_only || !(pid = fork())) /* child */
1700 char preloader_reserve[64], socket_env[64];
1702 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1704 if (!(pid = fork()))
1706 int fd = open( "/dev/null", O_RDWR );
1708 /* close stdin and stdout */
1716 else if (pid != -1) _exit(0); /* parent */
1720 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1721 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1724 if (stdin_fd != -1) close( stdin_fd );
1725 if (stdout_fd != -1) close( stdout_fd );
1727 /* Reset signals that we previously set to SIG_IGN */
1728 signal( SIGPIPE, SIG_DFL );
1729 signal( SIGCHLD, SIG_DFL );
1731 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1732 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1733 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1735 putenv( preloader_reserve );
1736 putenv( socket_env );
1737 if (winedebug) putenv( winedebug );
1738 if (unixdir) chdir(unixdir);
1740 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1744 /* this is the parent */
1746 if (stdin_fd != -1) close( stdin_fd );
1747 if (stdout_fd != -1) close( stdout_fd );
1748 close( socketfd[0] );
1749 HeapFree( GetProcessHeap(), 0, argv );
1750 HeapFree( GetProcessHeap(), 0, winedebug );
1757 /* wait for the new process info to be ready */
1759 WaitForSingleObject( process_info, INFINITE );
1760 SERVER_START_REQ( get_new_process_info )
1762 req->info = wine_server_obj_handle( process_info );
1763 wine_server_call( req );
1764 success = reply->success;
1765 err = reply->exit_code;
1771 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1774 CloseHandle( process_info );
1778 CloseHandle( process_info );
1779 CloseHandle( info->hProcess );
1780 CloseHandle( info->hThread );
1781 info->hProcess = info->hThread = 0;
1782 info->dwProcessId = info->dwThreadId = 0;
1787 /***********************************************************************
1788 * create_vdm_process
1790 * Create a new VDM process for a 16-bit or DOS application.
1792 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1793 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1794 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1795 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1796 const struct binary_info *binary_info, int exec_only )
1798 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1801 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1802 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1806 SetLastError( ERROR_OUTOFMEMORY );
1809 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1810 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1811 flags, startup, info, unixdir, binary_info, exec_only );
1812 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1817 /***********************************************************************
1818 * create_cmd_process
1820 * Create a new cmd shell process for a .BAT file.
1822 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1823 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1824 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1825 LPPROCESS_INFORMATION info )
1828 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1829 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1830 WCHAR comspec[MAX_PATH];
1834 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1836 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1837 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1840 strcpyW( newcmdline, comspec );
1841 strcatW( newcmdline, slashcW );
1842 strcatW( newcmdline, cmd_line );
1843 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1844 flags, env, cur_dir, startup, info );
1845 HeapFree( GetProcessHeap(), 0, newcmdline );
1850 /*************************************************************************
1853 * Helper for CreateProcess: retrieve the file name to load from the
1854 * app name and command line. Store the file name in buffer, and
1855 * return a possibly modified command line.
1856 * Also returns a handle to the opened file if it's a Windows binary.
1858 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1859 int buflen, HANDLE *handle )
1861 static const WCHAR quotesW[] = {'"','%','s','"',0};
1863 WCHAR *name, *pos, *ret = NULL;
1867 /* if we have an app name, everything is easy */
1871 /* use the unmodified app name as file name */
1872 lstrcpynW( buffer, appname, buflen );
1873 *handle = open_exe_file( buffer );
1874 if (!(ret = cmdline) || !cmdline[0])
1876 /* no command-line, create one */
1877 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1878 sprintfW( ret, quotesW, appname );
1883 /* first check for a quoted file name */
1885 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1887 int len = p - cmdline - 1;
1888 /* extract the quoted portion as file name */
1889 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1890 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1893 if (find_exe_file( name, buffer, buflen, handle ))
1894 ret = cmdline; /* no change necessary */
1898 /* now try the command-line word by word */
1900 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1908 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1910 if (find_exe_file( name, buffer, buflen, handle ))
1915 if (*p) got_space = TRUE;
1918 if (ret && got_space) /* now build a new command-line with quotes */
1920 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1922 sprintfW( ret, quotesW, name );
1925 else if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
1928 HeapFree( GetProcessHeap(), 0, name );
1933 /**********************************************************************
1934 * CreateProcessA (KERNEL32.@)
1936 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1937 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1938 DWORD flags, LPVOID env, LPCSTR cur_dir,
1939 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1942 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1943 UNICODE_STRING desktopW, titleW;
1946 desktopW.Buffer = NULL;
1947 titleW.Buffer = NULL;
1948 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1949 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1950 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1952 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1953 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1955 memcpy( &infoW, startup_info, sizeof(infoW) );
1956 infoW.lpDesktop = desktopW.Buffer;
1957 infoW.lpTitle = titleW.Buffer;
1959 if (startup_info->lpReserved)
1960 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1961 debugstr_a(startup_info->lpReserved));
1963 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1964 inherit, flags, env, cur_dirW, &infoW, info );
1966 HeapFree( GetProcessHeap(), 0, app_nameW );
1967 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1968 HeapFree( GetProcessHeap(), 0, cur_dirW );
1969 RtlFreeUnicodeString( &desktopW );
1970 RtlFreeUnicodeString( &titleW );
1975 /**********************************************************************
1976 * CreateProcessW (KERNEL32.@)
1978 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1979 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1980 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1981 LPPROCESS_INFORMATION info )
1985 char *unixdir = NULL;
1986 WCHAR name[MAX_PATH];
1987 WCHAR *tidy_cmdline, *p, *envW = env;
1988 struct binary_info binary_info;
1990 /* Process the AppName and/or CmdLine to get module name and path */
1992 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1994 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1996 if (hFile == INVALID_HANDLE_VALUE) goto done;
1998 /* Warn if unsupported features are used */
2000 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2001 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2002 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2003 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2004 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2008 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2010 SetLastError(ERROR_DIRECTORY);
2016 WCHAR buf[MAX_PATH];
2017 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2020 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2025 while (*p) p += strlen(p) + 1;
2026 p++; /* final null */
2027 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
2028 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2029 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
2030 flags |= CREATE_UNICODE_ENVIRONMENT;
2033 info->hThread = info->hProcess = 0;
2034 info->dwProcessId = info->dwThreadId = 0;
2036 /* Determine executable type */
2038 if (!hFile) /* builtin exe */
2040 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
2041 memset( &binary_info, 0, sizeof(binary_info) );
2042 binary_info.type = BINARY_UNIX_LIB;
2043 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2044 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2048 MODULE_get_binary_info( hFile, &binary_info );
2049 if (binary_info.flags & BINARY_FLAG_DLL)
2051 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2052 SetLastError( ERROR_BAD_EXE_FORMAT );
2054 else switch (binary_info.type)
2057 TRACE( "starting %s as Win32 binary (%p-%p)\n",
2058 debugstr_w(name), binary_info.res_start, binary_info.res_end );
2059 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2060 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2065 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2066 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2067 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2069 case BINARY_UNIX_LIB:
2070 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2071 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2072 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2074 case BINARY_UNKNOWN:
2075 /* check for .com or .bat extension */
2076 if ((p = strrchrW( name, '.' )))
2078 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2080 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2081 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2082 inherit, flags, startup_info, info, unixdir,
2083 &binary_info, FALSE );
2086 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2088 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2089 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2090 inherit, flags, startup_info, info );
2095 case BINARY_UNIX_EXE:
2097 /* unknown file, try as unix executable */
2100 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2102 if ((unix_name = wine_get_unix_file_name( name )))
2104 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2105 HeapFree( GetProcessHeap(), 0, unix_name );
2110 CloseHandle( hFile );
2113 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2114 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2115 HeapFree( GetProcessHeap(), 0, unixdir );
2117 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2122 /**********************************************************************
2125 static void exec_process( LPCWSTR name )
2129 STARTUPINFOW startup_info;
2130 PROCESS_INFORMATION info;
2131 struct binary_info binary_info;
2133 hFile = open_exe_file( name );
2134 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2136 memset( &startup_info, 0, sizeof(startup_info) );
2137 startup_info.cb = sizeof(startup_info);
2139 /* Determine executable type */
2141 MODULE_get_binary_info( hFile, &binary_info );
2142 if (binary_info.flags & BINARY_FLAG_DLL) return;
2143 switch (binary_info.type)
2146 TRACE( "starting %s as Win32 binary (%p-%p)\n",
2147 debugstr_w(name), binary_info.res_start, binary_info.res_end );
2148 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2149 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2151 case BINARY_UNIX_LIB:
2152 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2153 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2154 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2156 case BINARY_UNKNOWN:
2157 /* check for .com or .pif extension */
2158 if (!(p = strrchrW( name, '.' ))) break;
2159 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2164 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2165 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2166 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2171 CloseHandle( hFile );
2175 /***********************************************************************
2178 * Wrapper to call WaitForInputIdle USER function
2180 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2182 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2184 HMODULE mod = GetModuleHandleA( "user32.dll" );
2187 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2188 if (ptr) return ptr( process, timeout );
2194 /***********************************************************************
2195 * WinExec (KERNEL32.@)
2197 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2199 PROCESS_INFORMATION info;
2200 STARTUPINFOA startup;
2204 memset( &startup, 0, sizeof(startup) );
2205 startup.cb = sizeof(startup);
2206 startup.dwFlags = STARTF_USESHOWWINDOW;
2207 startup.wShowWindow = nCmdShow;
2209 /* cmdline needs to be writable for CreateProcess */
2210 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2211 strcpy( cmdline, lpCmdLine );
2213 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2214 0, NULL, NULL, &startup, &info ))
2216 /* Give 30 seconds to the app to come up */
2217 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2218 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2220 /* Close off the handles */
2221 CloseHandle( info.hThread );
2222 CloseHandle( info.hProcess );
2224 else if ((ret = GetLastError()) >= 32)
2226 FIXME("Strange error set by CreateProcess: %d\n", ret );
2229 HeapFree( GetProcessHeap(), 0, cmdline );
2234 /**********************************************************************
2235 * LoadModule (KERNEL32.@)
2237 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2239 LOADPARMS32 *params = paramBlock;
2240 PROCESS_INFORMATION info;
2241 STARTUPINFOA startup;
2242 HINSTANCE hInstance;
2244 char filename[MAX_PATH];
2247 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2249 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2250 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2251 return ULongToHandle(GetLastError());
2253 len = (BYTE)params->lpCmdLine[0];
2254 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2255 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2257 strcpy( cmdline, filename );
2258 p = cmdline + strlen(cmdline);
2260 memcpy( p, params->lpCmdLine + 1, len );
2263 memset( &startup, 0, sizeof(startup) );
2264 startup.cb = sizeof(startup);
2265 if (params->lpCmdShow)
2267 startup.dwFlags = STARTF_USESHOWWINDOW;
2268 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2271 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2272 params->lpEnvAddress, NULL, &startup, &info ))
2274 /* Give 30 seconds to the app to come up */
2275 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2276 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2277 hInstance = (HINSTANCE)33;
2278 /* Close off the handles */
2279 CloseHandle( info.hThread );
2280 CloseHandle( info.hProcess );
2282 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2284 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2285 hInstance = (HINSTANCE)11;
2288 HeapFree( GetProcessHeap(), 0, cmdline );
2293 /******************************************************************************
2294 * TerminateProcess (KERNEL32.@)
2296 * Terminates a process.
2299 * handle [I] Process to terminate.
2300 * exit_code [I] Exit code.
2304 * Failure: FALSE, check GetLastError().
2306 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2308 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2309 if (status) SetLastError( RtlNtStatusToDosError(status) );
2313 /***********************************************************************
2314 * ExitProcess (KERNEL32.@)
2316 * Exits the current process.
2319 * status [I] Status code to exit with.
2325 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2327 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2328 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2329 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2331 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2335 void WINAPI process_ExitProcess( DWORD status )
2337 LdrShutdownProcess();
2338 NtTerminateProcess(GetCurrentProcess(), status);
2344 void WINAPI ExitProcess( DWORD status )
2346 LdrShutdownProcess();
2347 NtTerminateProcess(GetCurrentProcess(), status);
2353 /***********************************************************************
2354 * GetExitCodeProcess [KERNEL32.@]
2356 * Gets termination status of specified process.
2359 * hProcess [in] Handle to the process.
2360 * lpExitCode [out] Address to receive termination status.
2366 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2369 PROCESS_BASIC_INFORMATION pbi;
2371 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2373 if (status == STATUS_SUCCESS)
2375 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2378 SetLastError( RtlNtStatusToDosError(status) );
2383 /***********************************************************************
2384 * SetErrorMode (KERNEL32.@)
2386 UINT WINAPI SetErrorMode( UINT mode )
2388 UINT old = process_error_mode;
2389 process_error_mode = mode;
2393 /***********************************************************************
2394 * GetErrorMode (KERNEL32.@)
2396 UINT WINAPI GetErrorMode( void )
2398 return process_error_mode;
2401 /**********************************************************************
2402 * TlsAlloc [KERNEL32.@]
2404 * Allocates a thread local storage index.
2407 * Success: TLS index.
2408 * Failure: 0xFFFFFFFF
2410 DWORD WINAPI TlsAlloc( void )
2413 PEB * const peb = NtCurrentTeb()->Peb;
2415 RtlAcquirePebLock();
2416 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2417 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2420 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2423 if (!NtCurrentTeb()->TlsExpansionSlots &&
2424 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2425 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2427 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2429 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2433 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2434 index += TLS_MINIMUM_AVAILABLE;
2437 else SetLastError( ERROR_NO_MORE_ITEMS );
2439 RtlReleasePebLock();
2444 /**********************************************************************
2445 * TlsFree [KERNEL32.@]
2447 * Releases a thread local storage index, making it available for reuse.
2450 * index [in] TLS index to free.
2456 BOOL WINAPI TlsFree( DWORD index )
2460 RtlAcquirePebLock();
2461 if (index >= TLS_MINIMUM_AVAILABLE)
2463 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2464 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2468 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2469 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2471 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2472 else SetLastError( ERROR_INVALID_PARAMETER );
2473 RtlReleasePebLock();
2478 /**********************************************************************
2479 * TlsGetValue [KERNEL32.@]
2481 * Gets value in a thread's TLS slot.
2484 * index [in] TLS index to retrieve value for.
2487 * Success: Value stored in calling thread's TLS slot for index.
2488 * Failure: 0 and GetLastError() returns NO_ERROR.
2490 LPVOID WINAPI TlsGetValue( DWORD index )
2494 if (index < TLS_MINIMUM_AVAILABLE)
2496 ret = NtCurrentTeb()->TlsSlots[index];
2500 index -= TLS_MINIMUM_AVAILABLE;
2501 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2503 SetLastError( ERROR_INVALID_PARAMETER );
2506 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2507 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2509 SetLastError( ERROR_SUCCESS );
2514 /**********************************************************************
2515 * TlsSetValue [KERNEL32.@]
2517 * Stores a value in the thread's TLS slot.
2520 * index [in] TLS index to set value for.
2521 * value [in] Value to be stored.
2527 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2529 if (index < TLS_MINIMUM_AVAILABLE)
2531 NtCurrentTeb()->TlsSlots[index] = value;
2535 index -= TLS_MINIMUM_AVAILABLE;
2536 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2538 SetLastError( ERROR_INVALID_PARAMETER );
2541 if (!NtCurrentTeb()->TlsExpansionSlots &&
2542 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2543 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2545 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2548 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2554 /***********************************************************************
2555 * GetProcessFlags (KERNEL32.@)
2557 DWORD WINAPI GetProcessFlags( DWORD processid )
2559 IMAGE_NT_HEADERS *nt;
2562 if (processid && processid != GetCurrentProcessId()) return 0;
2564 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2566 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2567 flags |= PDB32_CONSOLE_PROC;
2569 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2570 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2575 /***********************************************************************
2576 * GetProcessDword (KERNEL32.18)
2578 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2580 FIXME( "(%d, %d): not supported\n", dwProcessID, offset );
2585 /*********************************************************************
2586 * OpenProcess (KERNEL32.@)
2588 * Opens a handle to a process.
2591 * access [I] Desired access rights assigned to the returned handle.
2592 * inherit [I] Determines whether or not child processes will inherit the handle.
2593 * id [I] Process identifier of the process to get a handle to.
2596 * Success: Valid handle to the specified process.
2597 * Failure: NULL, check GetLastError().
2599 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2603 OBJECT_ATTRIBUTES attr;
2606 cid.UniqueProcess = ULongToHandle(id);
2607 cid.UniqueThread = 0; /* FIXME ? */
2609 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2610 attr.RootDirectory = NULL;
2611 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2612 attr.SecurityDescriptor = NULL;
2613 attr.SecurityQualityOfService = NULL;
2614 attr.ObjectName = NULL;
2616 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2618 status = NtOpenProcess(&handle, access, &attr, &cid);
2619 if (status != STATUS_SUCCESS)
2621 SetLastError( RtlNtStatusToDosError(status) );
2628 /*********************************************************************
2629 * GetProcessId (KERNEL32.@)
2631 * Gets the a unique identifier of a process.
2634 * hProcess [I] Handle to the process.
2638 * Failure: FALSE, check GetLastError().
2642 * The identifier is unique only on the machine and only until the process
2643 * exits (including system shutdown).
2645 DWORD WINAPI GetProcessId( HANDLE hProcess )
2648 PROCESS_BASIC_INFORMATION pbi;
2650 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2652 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2653 SetLastError( RtlNtStatusToDosError(status) );
2658 /*********************************************************************
2659 * CloseHandle (KERNEL32.@)
2664 * handle [I] Handle to close.
2668 * Failure: FALSE, check GetLastError().
2670 BOOL WINAPI CloseHandle( HANDLE handle )
2674 /* stdio handles need special treatment */
2675 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2676 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2677 (handle == (HANDLE)STD_ERROR_HANDLE))
2678 handle = GetStdHandle( HandleToULong(handle) );
2680 if (is_console_handle(handle))
2681 return CloseConsoleHandle(handle);
2683 status = NtClose( handle );
2684 if (status) SetLastError( RtlNtStatusToDosError(status) );
2689 /*********************************************************************
2690 * GetHandleInformation (KERNEL32.@)
2692 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2694 OBJECT_DATA_INFORMATION info;
2695 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2697 if (status) SetLastError( RtlNtStatusToDosError(status) );
2701 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2702 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2708 /*********************************************************************
2709 * SetHandleInformation (KERNEL32.@)
2711 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2713 OBJECT_DATA_INFORMATION info;
2716 /* if not setting both fields, retrieve current value first */
2717 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2718 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2720 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2722 SetLastError( RtlNtStatusToDosError(status) );
2726 if (mask & HANDLE_FLAG_INHERIT)
2727 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2728 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2729 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2731 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2732 if (status) SetLastError( RtlNtStatusToDosError(status) );
2737 /*********************************************************************
2738 * DuplicateHandle (KERNEL32.@)
2740 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2741 HANDLE dest_process, HANDLE *dest,
2742 DWORD access, BOOL inherit, DWORD options )
2746 if (is_console_handle(source))
2748 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2749 if (source_process != dest_process ||
2750 source_process != GetCurrentProcess())
2752 SetLastError(ERROR_INVALID_PARAMETER);
2755 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2756 return (*dest != INVALID_HANDLE_VALUE);
2758 status = NtDuplicateObject( source_process, source, dest_process, dest,
2759 access, inherit ? OBJ_INHERIT : 0, options );
2760 if (status) SetLastError( RtlNtStatusToDosError(status) );
2765 /***********************************************************************
2766 * ConvertToGlobalHandle (KERNEL32.@)
2768 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2770 HANDLE ret = INVALID_HANDLE_VALUE;
2771 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2772 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2777 /***********************************************************************
2778 * SetHandleContext (KERNEL32.@)
2780 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2782 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2783 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2784 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2789 /***********************************************************************
2790 * GetHandleContext (KERNEL32.@)
2792 DWORD WINAPI GetHandleContext(HANDLE hnd)
2794 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2795 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2796 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2801 /***********************************************************************
2802 * CreateSocketHandle (KERNEL32.@)
2804 HANDLE WINAPI CreateSocketHandle(void)
2806 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2807 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2808 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2809 return INVALID_HANDLE_VALUE;
2813 /***********************************************************************
2814 * SetPriorityClass (KERNEL32.@)
2816 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2819 PROCESS_PRIORITY_CLASS ppc;
2821 ppc.Foreground = FALSE;
2822 switch (priorityclass)
2824 case IDLE_PRIORITY_CLASS:
2825 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2826 case BELOW_NORMAL_PRIORITY_CLASS:
2827 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2828 case NORMAL_PRIORITY_CLASS:
2829 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2830 case ABOVE_NORMAL_PRIORITY_CLASS:
2831 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2832 case HIGH_PRIORITY_CLASS:
2833 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2834 case REALTIME_PRIORITY_CLASS:
2835 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2837 SetLastError(ERROR_INVALID_PARAMETER);
2841 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2844 if (status != STATUS_SUCCESS)
2846 SetLastError( RtlNtStatusToDosError(status) );
2853 /***********************************************************************
2854 * GetPriorityClass (KERNEL32.@)
2856 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2859 PROCESS_BASIC_INFORMATION pbi;
2861 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2863 if (status != STATUS_SUCCESS)
2865 SetLastError( RtlNtStatusToDosError(status) );
2868 switch (pbi.BasePriority)
2870 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2871 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2872 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2873 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2874 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2875 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2877 SetLastError( ERROR_INVALID_PARAMETER );
2882 /***********************************************************************
2883 * SetProcessAffinityMask (KERNEL32.@)
2885 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2889 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2890 &affmask, sizeof(DWORD_PTR));
2893 SetLastError( RtlNtStatusToDosError(status) );
2900 /**********************************************************************
2901 * GetProcessAffinityMask (KERNEL32.@)
2903 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2904 PDWORD_PTR lpProcessAffinityMask,
2905 PDWORD_PTR lpSystemAffinityMask )
2907 PROCESS_BASIC_INFORMATION pbi;
2910 status = NtQueryInformationProcess(hProcess,
2911 ProcessBasicInformation,
2912 &pbi, sizeof(pbi), NULL);
2915 SetLastError( RtlNtStatusToDosError(status) );
2918 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2919 if (lpSystemAffinityMask) *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2924 /***********************************************************************
2925 * GetProcessVersion (KERNEL32.@)
2927 DWORD WINAPI GetProcessVersion( DWORD pid )
2931 PROCESS_BASIC_INFORMATION pbi;
2934 IMAGE_DOS_HEADER dos;
2935 IMAGE_NT_HEADERS nt;
2938 if (!pid || pid == GetCurrentProcessId())
2940 IMAGE_NT_HEADERS *nt;
2942 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2943 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2944 nt->OptionalHeader.MinorSubsystemVersion);
2948 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
2949 if (!process) return 0;
2951 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
2952 if (status) goto err;
2954 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
2955 if (status || count != sizeof(peb)) goto err;
2957 memset(&dos, 0, sizeof(dos));
2958 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
2959 if (status || count != sizeof(dos)) goto err;
2960 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
2962 memset(&nt, 0, sizeof(nt));
2963 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
2964 if (status || count != sizeof(nt)) goto err;
2965 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
2967 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
2970 CloseHandle(process);
2972 if (status != STATUS_SUCCESS)
2973 SetLastError(RtlNtStatusToDosError(status));
2979 /***********************************************************************
2980 * SetProcessWorkingSetSize [KERNEL32.@]
2981 * Sets the min/max working set sizes for a specified process.
2984 * hProcess [I] Handle to the process of interest
2985 * minset [I] Specifies minimum working set size
2986 * maxset [I] Specifies maximum working set size
2992 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2995 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2996 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2997 /* Trim the working set to zero */
2998 /* Swap the process out of physical RAM */
3003 /***********************************************************************
3004 * GetProcessWorkingSetSize (KERNEL32.@)
3006 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3009 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3010 /* 32 MB working set size */
3011 if (minset) *minset = 32*1024*1024;
3012 if (maxset) *maxset = 32*1024*1024;
3017 /***********************************************************************
3018 * SetProcessShutdownParameters (KERNEL32.@)
3020 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3022 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3023 shutdown_flags = flags;
3024 shutdown_priority = level;
3029 /***********************************************************************
3030 * GetProcessShutdownParameters (KERNEL32.@)
3033 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3035 *lpdwLevel = shutdown_priority;
3036 *lpdwFlags = shutdown_flags;
3041 /***********************************************************************
3042 * GetProcessPriorityBoost (KERNEL32.@)
3044 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3046 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3048 /* Report that no boost is present.. */
3049 *pDisablePriorityBoost = FALSE;
3054 /***********************************************************************
3055 * SetProcessPriorityBoost (KERNEL32.@)
3057 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3059 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3060 /* Say we can do it. I doubt the program will notice that we don't. */
3065 /***********************************************************************
3066 * ReadProcessMemory (KERNEL32.@)
3068 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3069 SIZE_T *bytes_read )
3071 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3072 if (status) SetLastError( RtlNtStatusToDosError(status) );
3077 /***********************************************************************
3078 * WriteProcessMemory (KERNEL32.@)
3080 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3081 SIZE_T *bytes_written )
3083 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3084 if (status) SetLastError( RtlNtStatusToDosError(status) );
3089 /****************************************************************************
3090 * FlushInstructionCache (KERNEL32.@)
3092 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3095 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3096 if (status) SetLastError( RtlNtStatusToDosError(status) );
3101 /******************************************************************
3102 * GetProcessIoCounters (KERNEL32.@)
3104 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3108 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3109 ioc, sizeof(*ioc), NULL);
3110 if (status) SetLastError( RtlNtStatusToDosError(status) );
3114 /******************************************************************
3115 * GetProcessHandleCount (KERNEL32.@)
3117 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3121 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3122 cnt, sizeof(*cnt), NULL);
3123 if (status) SetLastError( RtlNtStatusToDosError(status) );
3127 /******************************************************************
3128 * QueryFullProcessImageNameA (KERNEL32.@)
3130 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3133 DWORD pdwSizeW = *pdwSize;
3134 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3136 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3139 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3140 lpExeName, *pdwSize, NULL, NULL));
3142 *pdwSize = strlen(lpExeName);
3144 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3148 /******************************************************************
3149 * QueryFullProcessImageNameW (KERNEL32.@)
3151 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3153 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3154 UNICODE_STRING *dynamic_buffer = NULL;
3155 UNICODE_STRING nt_path;
3156 UNICODE_STRING *result = NULL;
3160 RtlInitUnicodeStringEx(&nt_path, NULL);
3161 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3162 * as this is on Wine. */
3163 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3164 sizeof(buffer) - sizeof(WCHAR), &needed);
3165 if (status == STATUS_INFO_LENGTH_MISMATCH)
3167 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3168 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3169 result = dynamic_buffer;
3172 result = (PUNICODE_STRING)buffer;
3174 if (status) goto cleanup;
3176 if (dwFlags & PROCESS_NAME_NATIVE)
3178 result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3179 if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3181 status = STATUS_OBJECT_PATH_NOT_FOUND;
3187 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3189 status = STATUS_BUFFER_TOO_SMALL;
3193 *pdwSize = result->Length/sizeof(WCHAR);
3194 memcpy( lpExeName, result->Buffer, result->Length );
3195 lpExeName[*pdwSize] = 0;
3198 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3199 RtlFreeUnicodeString(&nt_path);
3200 if (status) SetLastError( RtlNtStatusToDosError(status) );
3204 /***********************************************************************
3205 * ProcessIdToSessionId (KERNEL32.@)
3206 * This function is available on Terminal Server 4SP4 and Windows 2000
3208 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3210 /* According to MSDN, if the calling process is not in a terminal
3211 * services environment, then the sessionid returned is zero.
3218 /***********************************************************************
3219 * RegisterServiceProcess (KERNEL32.@)
3221 * A service process calls this function to ensure that it continues to run
3222 * even after a user logged off.
3224 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3226 /* I don't think that Wine needs to do anything in this function */
3227 return 1; /* success */
3231 /**********************************************************************
3232 * IsWow64Process (KERNEL32.@)
3234 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3239 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3241 if (status != STATUS_SUCCESS)
3243 SetLastError( RtlNtStatusToDosError( status ) );
3246 *Wow64Process = (pbi != 0);
3251 /***********************************************************************
3252 * GetCurrentProcess (KERNEL32.@)
3254 * Get a handle to the current process.
3260 * A handle representing the current process.
3262 #undef GetCurrentProcess
3263 HANDLE WINAPI GetCurrentProcess(void)
3265 return (HANDLE)~(ULONG_PTR)0;
3268 /***********************************************************************
3269 * CmdBatNotification (KERNEL32.@)
3271 * Notifies the system that a batch file has started or finished.
3274 * bBatchRunning [I] TRUE if a batch file has started or
3275 * FALSE if a batch file has finished executing.
3280 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3282 FIXME("%d\n", bBatchRunning);
3287 /***********************************************************************
3288 * RegisterApplicationRestart (KERNEL32.@)
3290 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3292 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3297 /**********************************************************************
3298 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3300 DWORD WINAPI WTSGetActiveConsoleSessionId(void)