4 * Copyright 1996, 1998 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "wine/port.h"
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
40 #ifdef HAVE_SYS_PRCTL_H
41 # include <sys/prctl.h>
43 #include <sys/types.h>
46 #define WIN32_NO_STATUS
48 #include "kernel_private.h"
49 #include "wine/library.h"
50 #include "wine/server.h"
51 #include "wine/unicode.h"
52 #include "wine/debug.h"
54 WINE_DEFAULT_DEBUG_CHANNEL(process);
55 WINE_DECLARE_DEBUG_CHANNEL(file);
56 WINE_DECLARE_DEBUG_CHANNEL(relay);
59 extern char **__wine_get_main_environment(void);
61 extern char **__wine_main_environ;
62 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
73 static UINT process_error_mode;
75 static DWORD shutdown_flags = 0;
76 static DWORD shutdown_priority = 0x280;
79 HMODULE kernel32_handle = 0;
81 const WCHAR *DIR_Windows = NULL;
82 const WCHAR *DIR_System = NULL;
83 const WCHAR *DIR_SysWow64 = NULL;
86 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
87 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
88 #define PDB32_DOS_PROC 0x0010 /* Dos process */
89 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
90 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
91 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
93 static const WCHAR exeW[] = {'.','e','x','e',0};
94 static const WCHAR comW[] = {'.','c','o','m',0};
95 static const WCHAR batW[] = {'.','b','a','t',0};
96 static const WCHAR cmdW[] = {'.','c','m','d',0};
97 static const WCHAR pifW[] = {'.','p','i','f',0};
98 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
100 static void exec_process( LPCWSTR name );
102 extern void SHELL_LoadRegistry(void);
105 /***********************************************************************
108 static inline int contains_path( LPCWSTR name )
110 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
114 /***********************************************************************
117 * Check if an environment variable needs to be handled specially when
118 * passed through the Unix environment (i.e. prefixed with "WINE").
120 static inline int is_special_env_var( const char *var )
122 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
123 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
124 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
125 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
126 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
130 /***********************************************************************
133 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
135 unsigned int len = strlenW( prefix );
137 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
138 while (filename[len] == '\\') len++;
143 /***************************************************************************
146 * Get the path of a builtin module when the native file does not exist.
148 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
149 UINT size, struct binary_info *binary_info )
153 void *redir_disabled = 0;
154 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
156 /* builtin names cannot be empty or contain spaces */
157 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
159 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
160 Wow64RevertWow64FsRedirection( redir_disabled );
162 if (contains_path( libname ))
164 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
165 filename, &file_part ) > size * sizeof(WCHAR))
166 return FALSE; /* too long */
168 if ((len = is_path_prefix( DIR_System, filename )))
170 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
172 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
178 if (filename + len != file_part) return FALSE;
182 len = strlenW( DIR_System );
183 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
184 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
185 file_part = filename + len;
186 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
187 strcpyW( file_part, libname );
188 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
190 if (ext && !strchrW( file_part, '.' ))
192 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
193 return FALSE; /* too long */
194 strcatW( file_part, ext );
196 binary_info->type = BINARY_UNIX_LIB;
197 binary_info->flags = flags;
198 binary_info->res_start = NULL;
199 binary_info->res_end = NULL;
204 /***********************************************************************
207 * Open a specific exe file, taking load order into account.
208 * Returns the file handle or 0 for a builtin exe.
210 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
214 TRACE("looking for %s\n", debugstr_w(name) );
216 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
217 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
219 WCHAR buffer[MAX_PATH];
220 /* file doesn't exist, check for builtin */
221 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
224 else MODULE_get_binary_info( handle, binary_info );
230 /***********************************************************************
233 * Open an exe file, and return the full name and file handle.
234 * Returns FALSE if file could not be found.
235 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
236 * If file is a builtin exe, returns TRUE and sets handle to 0.
238 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
239 HANDLE *handle, struct binary_info *binary_info )
241 TRACE("looking for %s\n", debugstr_w(name) );
243 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ))
245 if (contains_path( name ) && get_builtin_path( name, exeW, buffer, buflen, binary_info ))
250 /* no builtin found, try native without extension in case it is a Unix app */
251 if (!SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
254 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
255 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
256 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
258 MODULE_get_binary_info( *handle, binary_info );
265 /***********************************************************************
266 * build_initial_environment
268 * Build the Win32 environment from the Unix environment
270 static BOOL build_initial_environment(void)
276 char **env = __wine_get_main_environment();
278 /* Compute the total size of the Unix environment */
279 for (e = env; *e; e++)
281 if (is_special_env_var( *e )) continue;
282 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
284 size *= sizeof(WCHAR);
286 /* Now allocate the environment */
288 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
289 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
292 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
293 endptr = p + size / sizeof(WCHAR);
295 /* And fill it with the Unix environment */
296 for (e = env; *e; e++)
300 /* skip Unix special variables and use the Wine variants instead */
301 if (!strncmp( str, "WINE", 4 ))
303 if (is_special_env_var( str + 4 )) str += 4;
304 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
306 else if (is_special_env_var( str )) continue; /* skip it */
308 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
316 /***********************************************************************
317 * set_registry_variables
319 * Set environment variables by enumerating the values of a key;
320 * helper for set_registry_environment().
321 * Note that Windows happily truncates the value if it's too big.
323 static void set_registry_variables( HANDLE hkey, ULONG type )
325 static const WCHAR pathW[] = {'P','A','T','H'};
326 static const WCHAR sep[] = {';',0};
327 UNICODE_STRING env_name, env_value;
331 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
334 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
337 tmp.MaximumLength = sizeof(tmpbuf);
339 for (index = 0; ; index++)
341 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
342 buffer, sizeof(buffer), &size );
343 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
345 if (info->Type != type)
347 env_name.Buffer = info->Name;
348 env_name.Length = env_name.MaximumLength = info->NameLength;
349 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
350 env_value.Length = info->DataLength;
351 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
352 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
353 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
354 if (!env_value.Length) continue;
355 if (info->Type == REG_EXPAND_SZ)
357 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
358 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
359 RtlCopyUnicodeString( &env_value, &tmp );
362 if (env_name.Length == sizeof(pathW) &&
363 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
364 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
366 RtlAppendUnicodeToString( &tmp, sep );
367 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
368 RtlCopyUnicodeString( &env_value, &tmp );
370 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
375 /***********************************************************************
376 * set_registry_environment
378 * Set the environment variables specified in the registry.
380 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
381 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
382 * on the order in which the variables are processed. But on Windows it
383 * does not really matter since they only use %SystemDrive% and
384 * %SystemRoot% which are predefined. But Wine defines these in the
385 * registry, so we need two passes.
387 static BOOL set_registry_environment( BOOL volatile_only )
389 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
390 'S','y','s','t','e','m','\\',
391 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
392 'C','o','n','t','r','o','l','\\',
393 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
394 'E','n','v','i','r','o','n','m','e','n','t',0};
395 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
396 static const WCHAR volatile_envW[] = {'V','o','l','a','t','i','l','e',' ','E','n','v','i','r','o','n','m','e','n','t',0};
398 OBJECT_ATTRIBUTES attr;
399 UNICODE_STRING nameW;
403 attr.Length = sizeof(attr);
404 attr.RootDirectory = 0;
405 attr.ObjectName = &nameW;
407 attr.SecurityDescriptor = NULL;
408 attr.SecurityQualityOfService = NULL;
410 /* first the system environment variables */
411 RtlInitUnicodeString( &nameW, env_keyW );
412 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
414 set_registry_variables( hkey, REG_SZ );
415 set_registry_variables( hkey, REG_EXPAND_SZ );
420 /* then the ones for the current user */
421 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
422 RtlInitUnicodeString( &nameW, envW );
423 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
425 set_registry_variables( hkey, REG_SZ );
426 set_registry_variables( hkey, REG_EXPAND_SZ );
430 RtlInitUnicodeString( &nameW, volatile_envW );
431 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
433 set_registry_variables( hkey, REG_SZ );
434 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 allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
502 OBJECT_ATTRIBUTES attr;
503 UNICODE_STRING nameW;
504 WCHAR *profile_dir = NULL, *all_users_dir = NULL;
508 /* set the ALLUSERSPROFILE variables */
510 attr.Length = sizeof(attr);
511 attr.RootDirectory = 0;
512 attr.ObjectName = &nameW;
514 attr.SecurityDescriptor = NULL;
515 attr.SecurityQualityOfService = NULL;
516 RtlInitUnicodeString( &nameW, profile_keyW );
517 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
519 profile_dir = get_reg_value( hkey, profiles_valueW );
520 all_users_dir = get_reg_value( hkey, all_users_valueW );
524 if (profile_dir && all_users_dir)
528 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
529 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
530 strcpyW( value, profile_dir );
531 p = value + strlenW(value);
532 if (p > value && p[-1] != '\\') *p++ = '\\';
533 strcpyW( p, all_users_dir );
534 SetEnvironmentVariableW( allusersW, value );
535 HeapFree( GetProcessHeap(), 0, value );
538 HeapFree( GetProcessHeap(), 0, all_users_dir );
539 HeapFree( GetProcessHeap(), 0, profile_dir );
542 /***********************************************************************
545 * Set the Wine library Unicode argv global variables.
547 static void set_library_wargv( char **argv )
555 for (argc = 0; argv[argc]; argc++)
556 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
558 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
559 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
560 p = (WCHAR *)(wargv + argc + 1);
561 for (argc = 0; argv[argc]; argc++)
563 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
570 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
572 for (argc = 0; wargv[argc]; argc++)
573 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
575 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
576 q = (char *)(argv + argc + 1);
577 for (argc = 0; wargv[argc]; argc++)
579 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
586 __wine_main_argc = argc;
587 __wine_main_argv = argv;
588 __wine_main_wargv = wargv;
592 /***********************************************************************
593 * update_library_argv0
595 * Update the argv[0] global variable with the binary we have found.
597 static void update_library_argv0( const WCHAR *argv0 )
599 DWORD len = strlenW( argv0 );
601 if (len > strlenW( __wine_main_wargv[0] ))
603 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
605 strcpyW( __wine_main_wargv[0], argv0 );
607 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
608 if (len > strlen( __wine_main_argv[0] ) + 1)
610 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
612 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
616 /***********************************************************************
619 * Build the command line of a process from the argv array.
621 * Note that it does NOT necessarily include the file name.
622 * Sometimes we don't even have any command line options at all.
624 * We must quote and escape characters so that the argv array can be rebuilt
625 * from the command line:
626 * - spaces and tabs must be quoted
628 * - quotes must be escaped
630 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
631 * resulting in an odd number of '\' followed by a '"'
634 * - '\'s that are not followed by a '"' can be left as is
638 static BOOL build_command_line( WCHAR **argv )
643 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
645 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
648 for (arg = argv; *arg; arg++)
650 int has_space,bcount;
656 if( !*a ) has_space=1;
661 if (*a==' ' || *a=='\t') {
663 } else if (*a=='"') {
664 /* doubling of '\' preceding a '"',
665 * plus escaping of said '"'
673 len+=(a-*arg)+1 /* for the separating space */;
675 len+=2; /* for the quotes */
678 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
681 p = rupp->CommandLine.Buffer;
682 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
683 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
684 for (arg = argv; *arg; arg++)
686 int has_space,has_quote;
689 /* Check for quotes and spaces in this argument */
690 has_space=has_quote=0;
692 if( !*a ) has_space=1;
694 if (*a==' ' || *a=='\t') {
698 } else if (*a=='"') {
706 /* Now transfer it to the command line */
723 /* Double all the '\\' preceding this '"', plus one */
724 for (i=0;i<=bcount;i++)
736 while ((*p=*x++)) p++;
742 if (p > rupp->CommandLine.Buffer)
743 p--; /* remove last space */
750 /***********************************************************************
751 * init_current_directory
753 * Initialize the current directory from the Unix cwd or the parent info.
755 static void init_current_directory( CURDIR *cur_dir )
757 UNICODE_STRING dir_str;
762 /* if we received a cur dir from the parent, try this first */
764 if (cur_dir->DosPath.Length)
766 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
769 /* now try to get it from the Unix cwd */
771 for (size = 256; ; size *= 2)
773 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
774 if (getcwd( cwd, size )) break;
775 HeapFree( GetProcessHeap(), 0, cwd );
776 if (errno == ERANGE) continue;
781 /* try to use PWD if it is valid, so that we don't resolve symlinks */
783 pwd = getenv( "PWD" );
786 struct stat st1, st2;
788 if (!pwd || stat( pwd, &st1 ) == -1 ||
789 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
795 ANSI_STRING unix_name;
796 UNICODE_STRING nt_name;
797 RtlInitAnsiString( &unix_name, pwd );
798 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
800 UNICODE_STRING dos_path;
801 /* skip the \??\ prefix, nt_name is 0 terminated */
802 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
803 RtlSetCurrentDirectory_U( &dos_path );
804 RtlFreeUnicodeString( &nt_name );
808 if (!cur_dir->DosPath.Length) /* still not initialized */
810 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
811 "starting in the Windows directory.\n", cwd ? cwd : "" );
812 RtlInitUnicodeString( &dir_str, DIR_Windows );
813 RtlSetCurrentDirectory_U( &dir_str );
815 HeapFree( GetProcessHeap(), 0, cwd );
818 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
819 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
823 /***********************************************************************
826 * Initialize the windows and system directories from the environment.
828 static void init_windows_dirs(void)
830 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
832 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
833 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
834 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
835 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
836 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
841 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
843 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
844 GetEnvironmentVariableW( windirW, buffer, len );
845 DIR_Windows = buffer;
847 else DIR_Windows = default_windirW;
849 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
851 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
852 GetEnvironmentVariableW( winsysdirW, buffer, len );
857 len = strlenW( DIR_Windows );
858 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
859 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
860 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
864 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
865 ERR( "directory %s could not be created, error %u\n",
866 debugstr_w(DIR_Windows), GetLastError() );
867 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
868 ERR( "directory %s could not be created, error %u\n",
869 debugstr_w(DIR_System), GetLastError() );
871 #ifndef _WIN64 /* SysWow64 is always defined on 64-bit */
875 len = strlenW( DIR_Windows );
876 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
877 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
878 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
879 DIR_SysWow64 = buffer;
880 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
881 ERR( "directory %s could not be created, error %u\n",
882 debugstr_w(DIR_SysWow64), GetLastError() );
885 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
886 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
888 /* set the directories in ntdll too */
889 __wine_init_windows_dir( DIR_Windows, DIR_System );
893 /***********************************************************************
896 * Start the wineboot process if necessary. Return the handles to wait on.
898 static void start_wineboot( HANDLE handles[2] )
900 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
903 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
905 ERR( "failed to create wineboot event, expect trouble\n" );
908 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
910 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
911 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
912 const DWORD expected_type = (sizeof(void*) > sizeof(int) || is_wow64) ?
913 SCS_64BIT_BINARY : SCS_32BIT_BINARY;
915 PROCESS_INFORMATION pi;
919 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
921 memset( &si, 0, sizeof(si) );
923 si.dwFlags = STARTF_USESTDHANDLES;
926 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
928 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
929 lstrcatW( app, wineboot );
931 Wow64DisableWow64FsRedirection( &redir );
932 if (GetBinaryTypeW( app, &type ) && type != expected_type)
934 if (type == SCS_64BIT_BINARY)
935 MESSAGE( "wine: '%s' is a 64-bit prefix, it cannot be used with 32-bit Wine.\n",
936 wine_get_config_dir() );
938 MESSAGE( "wine: '%s' is a 32-bit prefix, it cannot be used with %s Wine.\n",
939 wine_get_config_dir(), is_wow64 ? "wow64" : "64-bit" );
943 strcpyW( cmdline, app );
944 strcatW( cmdline, args );
945 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
947 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
948 CloseHandle( pi.hThread );
949 handles[1] = pi.hProcess;
953 ERR( "failed to start wineboot, err %u\n", GetLastError() );
954 CloseHandle( handles[0] );
957 Wow64RevertWow64FsRedirection( redir );
962 /***********************************************************************
965 * Startup routine of a new process. Runs on the new process stack.
967 static DWORD WINAPI start_process( PEB *peb )
969 IMAGE_NT_HEADERS *nt;
970 LPTHREAD_START_ROUTINE entry;
972 nt = RtlImageNtHeader( peb->ImageBaseAddress );
973 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
974 nt->OptionalHeader.AddressOfEntryPoint);
976 if (!nt->OptionalHeader.AddressOfEntryPoint)
978 ERR( "%s doesn't have an entry point, it cannot be executed\n",
979 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
984 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
985 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
987 SetLastError( 0 ); /* clear error code */
988 if (peb->BeingDebugged) DbgBreakPoint();
993 /***********************************************************************
996 * Change the process name in the ps output.
998 static void set_process_name( int argc, char *argv[] )
1000 #ifdef HAVE_SETPROCTITLE
1001 setproctitle("-%s", argv[1]);
1006 char *p, *prctl_name = argv[1];
1007 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1010 # define PR_SET_NAME 15
1013 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1014 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1016 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1018 offset = argv[1] - argv[0];
1019 memmove( argv[1] - offset, argv[1], end - argv[1] );
1020 memset( end - offset, 0, offset );
1021 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1025 #endif /* HAVE_PRCTL */
1027 /* remove argv[0] */
1028 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1033 /***********************************************************************
1034 * __wine_kernel_init
1036 * Wine initialisation: load and start the main exe file.
1038 void CDECL __wine_kernel_init(void)
1040 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1041 static const WCHAR dotW[] = {'.',0};
1043 WCHAR *p, main_exe_name[MAX_PATH+1];
1044 PEB *peb = NtCurrentTeb()->Peb;
1045 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1046 HANDLE boot_events[2];
1047 BOOL got_environment = TRUE;
1049 /* Initialize everything */
1051 setbuf(stdout,NULL);
1052 setbuf(stderr,NULL);
1053 kernel32_handle = GetModuleHandleW(kernel32W);
1054 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1058 if (!params->Environment)
1060 /* Copy the parent environment */
1061 if (!build_initial_environment()) exit(1);
1063 /* convert old configuration to new format */
1064 convert_old_config();
1066 got_environment = set_registry_environment( FALSE );
1067 set_additional_environment();
1070 init_windows_dirs();
1071 init_current_directory( ¶ms->CurrentDirectory );
1073 set_process_name( __wine_main_argc, __wine_main_argv );
1074 set_library_wargv( __wine_main_argv );
1075 boot_events[0] = boot_events[1] = 0;
1077 if (peb->ProcessParameters->ImagePathName.Buffer)
1079 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1083 struct binary_info binary_info;
1085 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1086 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1088 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1089 ExitProcess( GetLastError() );
1091 update_library_argv0( main_exe_name );
1092 if (!build_command_line( __wine_main_wargv )) goto error;
1093 start_wineboot( boot_events );
1096 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1097 p = strrchrW( main_exe_name, '.' );
1098 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1100 TRACE( "starting process name=%s argv[0]=%s\n",
1101 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1103 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1104 MODULE_get_dll_load_path(main_exe_name) );
1108 DWORD timeout = 30000, count = 1;
1110 if (boot_events[1]) count++;
1111 if (!got_environment) timeout = 300000; /* initial prefix creation can take longer */
1112 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1113 ERR( "boot event wait timed out\n" );
1114 CloseHandle( boot_events[0] );
1115 if (boot_events[1]) CloseHandle( boot_events[1] );
1116 /* reload environment now that wineboot has run */
1117 set_registry_environment( got_environment );
1118 set_additional_environment();
1121 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1126 DWORD error = GetLastError();
1128 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1129 if (error == ERROR_BAD_EXE_FORMAT ||
1130 error == ERROR_INVALID_ADDRESS ||
1131 error == ERROR_NOT_ENOUGH_MEMORY)
1133 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1134 /* if we get back here, it failed */
1136 else if (error == ERROR_MOD_NOT_FOUND)
1138 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1139 else p = main_exe_name;
1140 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1142 /* args 1 and 2 are --app-name full_path */
1143 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1144 debugstr_w(__wine_main_wargv[3]) );
1145 ExitProcess( ERROR_BAD_EXE_FORMAT );
1147 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1148 ExitProcess( ERROR_FILE_NOT_FOUND );
1150 args[0] = (DWORD_PTR)main_exe_name;
1151 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1152 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1153 WideCharToMultiByte( CP_ACP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1154 MESSAGE( "wine: %s", msg );
1155 ExitProcess( error );
1158 LdrInitializeThunk( start_process, 0, 0, 0 );
1161 ExitProcess( GetLastError() );
1165 /***********************************************************************
1168 * Build an argv array from a command-line.
1169 * 'reserved' is the number of args to reserve before the first one.
1171 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1175 char *arg,*s,*d,*cmdline;
1176 int in_quotes,bcount,len;
1178 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1179 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1180 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1187 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1190 /* skip the remaining spaces */
1191 while (*s==' ' || *s=='\t') {
1198 } else if (*s=='\\') {
1199 /* '\', count them */
1201 } else if ((*s=='"') && ((bcount & 1)==0)) {
1203 in_quotes=!in_quotes;
1206 /* a regular character */
1211 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1213 HeapFree( GetProcessHeap(), 0, cmdline );
1217 arg = d = s = (char *)(argv + argc);
1218 memcpy( d, cmdline, len );
1223 if ((*s==' ' || *s=='\t') && !in_quotes) {
1224 /* Close the argument and copy it */
1228 /* skip the remaining spaces */
1231 } while (*s==' ' || *s=='\t');
1233 /* Start with a new argument */
1236 } else if (*s=='\\') {
1240 } else if (*s=='"') {
1242 if ((bcount & 1)==0) {
1243 /* Preceded by an even number of '\', this is half that
1244 * number of '\', plus a '"' which we discard.
1248 in_quotes=!in_quotes;
1250 /* Preceded by an odd number of '\', this is half that
1251 * number of '\' followed by a '"'
1259 /* a regular character */
1270 HeapFree( GetProcessHeap(), 0, cmdline );
1275 /***********************************************************************
1278 * Build the environment of a new child process.
1280 static char **build_envp( const WCHAR *envW )
1282 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1287 int count = 1, length;
1290 for (end = envW; *end; count++) end += strlenW(end) + 1;
1292 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1293 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1294 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1296 for (p = env; *p; p += strlen(p) + 1)
1297 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1299 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1301 if (!(p = getenv(unix_vars[i]))) continue;
1302 length += strlen(unix_vars[i]) + strlen(p) + 2;
1306 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1308 char **envptr = envp;
1309 char *dst = (char *)(envp + count);
1311 /* some variables must not be modified, so we get them directly from the unix env */
1312 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1314 if (!(p = getenv(unix_vars[i]))) continue;
1315 *envptr++ = strcpy( dst, unix_vars[i] );
1318 dst += strlen(dst) + 1;
1321 /* now put the Windows environment strings */
1322 for (p = env; *p; p += strlen(p) + 1)
1324 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1325 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1326 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1327 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1328 if (is_special_env_var( p )) /* prefix it with "WINE" */
1330 *envptr++ = strcpy( dst, "WINE" );
1335 *envptr++ = strcpy( dst, p );
1337 dst += strlen(dst) + 1;
1341 HeapFree( GetProcessHeap(), 0, env );
1346 /***********************************************************************
1349 * Fork and exec a new Unix binary, checking for errors.
1351 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1352 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1354 int fd[2], stdin_fd = -1, stdout_fd = -1;
1356 char **argv, **envp;
1358 if (!env) env = GetEnvironmentStringsW();
1361 if (pipe2( fd, O_CLOEXEC ) == -1)
1366 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1369 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1370 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1373 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1375 HANDLE hstdin, hstdout;
1377 if (startup->dwFlags & STARTF_USESTDHANDLES)
1379 hstdin = startup->hStdInput;
1380 hstdout = startup->hStdOutput;
1384 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1385 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1388 if (is_console_handle( hstdin ))
1389 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1390 if (is_console_handle( hstdout ))
1391 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1392 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1393 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1396 argv = build_argv( cmdline, 0 );
1397 envp = build_envp( env );
1399 if (!(pid = fork())) /* child */
1403 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1406 if (!(pid = fork()))
1408 int fd = open( "/dev/null", O_RDWR );
1410 /* close stdin and stdout */
1418 else if (pid != -1) _exit(0); /* parent */
1424 dup2( stdin_fd, 0 );
1427 if (stdout_fd != -1)
1429 dup2( stdout_fd, 1 );
1434 /* Reset signals that we previously set to SIG_IGN */
1435 signal( SIGPIPE, SIG_DFL );
1436 signal( SIGCHLD, SIG_DFL );
1438 if (newdir) chdir(newdir);
1440 if (argv && envp) execve( filename, argv, envp );
1442 write( fd[1], &err, sizeof(err) );
1445 HeapFree( GetProcessHeap(), 0, argv );
1446 HeapFree( GetProcessHeap(), 0, envp );
1447 if (stdin_fd != -1) close( stdin_fd );
1448 if (stdout_fd != -1) close( stdout_fd );
1450 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1455 if (pid == -1) FILE_SetDosError();
1461 static inline DWORD append_string( void **ptr, const WCHAR *str )
1463 DWORD len = strlenW( str );
1464 memcpy( *ptr, str, len * sizeof(WCHAR) );
1465 *ptr = (WCHAR *)*ptr + len;
1466 return len * sizeof(WCHAR);
1469 /***********************************************************************
1470 * create_startup_info
1472 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1473 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1474 const STARTUPINFOW *startup, DWORD *info_size )
1476 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1477 startup_info_t *info;
1480 UNICODE_STRING newdir;
1481 WCHAR imagepath[MAX_PATH];
1482 HANDLE hstdin, hstdout, hstderr;
1484 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1485 lstrcpynW( imagepath, filename, MAX_PATH );
1486 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1487 lstrcpynW( imagepath, filename, MAX_PATH );
1489 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1491 newdir.Buffer = NULL;
1494 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1495 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1501 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1502 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1504 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1507 size = sizeof(*info);
1508 size += strlenW( cur_dir ) * sizeof(WCHAR);
1509 size += cur_params->DllPath.Length;
1510 size += strlenW( imagepath ) * sizeof(WCHAR);
1511 size += strlenW( cmdline ) * sizeof(WCHAR);
1512 if (startup->lpTitle) size += strlenW( startup->lpTitle ) * sizeof(WCHAR);
1513 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1514 /* FIXME: shellinfo */
1515 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1516 size = (size + 1) & ~1;
1519 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1521 info->console_flags = cur_params->ConsoleFlags;
1522 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1523 if (flags & CREATE_NEW_CONSOLE) info->console = (obj_handle_t)1; /* FIXME: cf. kernel_main.c */
1525 if (startup->dwFlags & STARTF_USESTDHANDLES)
1527 hstdin = startup->hStdInput;
1528 hstdout = startup->hStdOutput;
1529 hstderr = startup->hStdError;
1533 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1534 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1535 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1537 info->hstdin = wine_server_obj_handle( hstdin );
1538 info->hstdout = wine_server_obj_handle( hstdout );
1539 info->hstderr = wine_server_obj_handle( hstderr );
1540 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1542 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1543 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1544 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1545 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1549 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1550 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1551 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1554 info->x = startup->dwX;
1555 info->y = startup->dwY;
1556 info->xsize = startup->dwXSize;
1557 info->ysize = startup->dwYSize;
1558 info->xchars = startup->dwXCountChars;
1559 info->ychars = startup->dwYCountChars;
1560 info->attribute = startup->dwFillAttribute;
1561 info->flags = startup->dwFlags;
1562 info->show = startup->wShowWindow;
1565 info->curdir_len = append_string( &ptr, cur_dir );
1566 info->dllpath_len = cur_params->DllPath.Length;
1567 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1568 ptr = (char *)ptr + cur_params->DllPath.Length;
1569 info->imagepath_len = append_string( &ptr, imagepath );
1570 info->cmdline_len = append_string( &ptr, cmdline );
1571 if (startup->lpTitle) info->title_len = append_string( &ptr, startup->lpTitle );
1572 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1573 if (startup->lpReserved2 && startup->cbReserved2)
1575 info->runtime_len = startup->cbReserved2;
1576 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1580 RtlFreeUnicodeString( &newdir );
1585 /***********************************************************************
1588 * Create a new process. If hFile is a valid handle we have an exe
1589 * file, otherwise it is a Winelib app.
1591 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1592 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1593 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1594 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1595 const struct binary_info *binary_info, int exec_only )
1597 BOOL ret, success = FALSE;
1598 HANDLE process_info;
1600 char *winedebug = NULL;
1602 startup_info_t *startup_info;
1603 DWORD startup_info_size;
1604 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1608 if (sizeof(void *) == sizeof(int) && !is_wow64 && (binary_info->flags & BINARY_FLAG_64BIT))
1610 ERR( "starting 64-bit process %s not supported on this platform\n", debugstr_w(filename) );
1611 SetLastError( ERROR_BAD_EXE_FORMAT );
1615 RtlAcquirePebLock();
1617 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1618 &startup_info_size )))
1620 RtlReleasePebLock();
1623 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
1627 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1628 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1630 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1631 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1632 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1634 env_end += strlenW(env_end) + 1;
1638 /* create the socket for the new process */
1640 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1642 RtlReleasePebLock();
1643 HeapFree( GetProcessHeap(), 0, winedebug );
1644 HeapFree( GetProcessHeap(), 0, startup_info );
1645 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1648 wine_server_send_fd( socketfd[1] );
1649 close( socketfd[1] );
1651 /* create the process on the server side */
1653 SERVER_START_REQ( new_process )
1655 req->inherit_all = inherit;
1656 req->create_flags = flags;
1657 req->socket_fd = socketfd[1];
1658 req->exe_file = wine_server_obj_handle( hFile );
1659 req->process_access = PROCESS_ALL_ACCESS;
1660 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1661 req->thread_access = THREAD_ALL_ACCESS;
1662 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1663 req->info_size = startup_info_size;
1665 wine_server_add_data( req, startup_info, startup_info_size );
1666 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
1667 if ((ret = !wine_server_call_err( req )))
1669 info->dwProcessId = (DWORD)reply->pid;
1670 info->dwThreadId = (DWORD)reply->tid;
1671 info->hProcess = wine_server_ptr_handle( reply->phandle );
1672 info->hThread = wine_server_ptr_handle( reply->thandle );
1674 process_info = wine_server_ptr_handle( reply->info );
1678 RtlReleasePebLock();
1681 close( socketfd[0] );
1682 HeapFree( GetProcessHeap(), 0, startup_info );
1683 HeapFree( GetProcessHeap(), 0, winedebug );
1687 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1689 if (startup_info->hstdin)
1690 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
1691 FILE_READ_DATA, &stdin_fd, NULL );
1692 if (startup_info->hstdout)
1693 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
1694 FILE_WRITE_DATA, &stdout_fd, NULL );
1696 HeapFree( GetProcessHeap(), 0, startup_info );
1698 /* create the child process */
1699 argv = build_argv( cmd_line, 1 );
1701 if (exec_only || !(pid = fork())) /* child */
1703 char preloader_reserve[64], socket_env[64];
1705 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1707 if (!(pid = fork()))
1709 int fd = open( "/dev/null", O_RDWR );
1711 /* close stdin and stdout */
1719 else if (pid != -1) _exit(0); /* parent */
1723 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1724 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1727 if (stdin_fd != -1) close( stdin_fd );
1728 if (stdout_fd != -1) close( stdout_fd );
1730 /* Reset signals that we previously set to SIG_IGN */
1731 signal( SIGPIPE, SIG_DFL );
1732 signal( SIGCHLD, SIG_DFL );
1734 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1735 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1736 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1738 putenv( preloader_reserve );
1739 putenv( socket_env );
1740 if (winedebug) putenv( winedebug );
1741 if (unixdir) chdir(unixdir);
1743 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1747 /* this is the parent */
1749 if (stdin_fd != -1) close( stdin_fd );
1750 if (stdout_fd != -1) close( stdout_fd );
1751 close( socketfd[0] );
1752 HeapFree( GetProcessHeap(), 0, argv );
1753 HeapFree( GetProcessHeap(), 0, winedebug );
1760 /* wait for the new process info to be ready */
1762 WaitForSingleObject( process_info, INFINITE );
1763 SERVER_START_REQ( get_new_process_info )
1765 req->info = wine_server_obj_handle( process_info );
1766 wine_server_call( req );
1767 success = reply->success;
1768 err = reply->exit_code;
1774 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1777 CloseHandle( process_info );
1781 CloseHandle( process_info );
1782 CloseHandle( info->hProcess );
1783 CloseHandle( info->hThread );
1784 info->hProcess = info->hThread = 0;
1785 info->dwProcessId = info->dwThreadId = 0;
1790 /***********************************************************************
1791 * create_vdm_process
1793 * Create a new VDM process for a 16-bit or DOS application.
1795 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1796 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1797 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1798 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1799 const struct binary_info *binary_info, int exec_only )
1801 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1804 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1805 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1809 SetLastError( ERROR_OUTOFMEMORY );
1812 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1813 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1814 flags, startup, info, unixdir, binary_info, exec_only );
1815 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1820 /***********************************************************************
1821 * create_cmd_process
1823 * Create a new cmd shell process for a .BAT file.
1825 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1826 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1827 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1828 LPPROCESS_INFORMATION info )
1831 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1832 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1833 WCHAR comspec[MAX_PATH];
1837 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1839 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1840 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1843 strcpyW( newcmdline, comspec );
1844 strcatW( newcmdline, slashcW );
1845 strcatW( newcmdline, cmd_line );
1846 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1847 flags, env, cur_dir, startup, info );
1848 HeapFree( GetProcessHeap(), 0, newcmdline );
1853 /*************************************************************************
1856 * Helper for CreateProcess: retrieve the file name to load from the
1857 * app name and command line. Store the file name in buffer, and
1858 * return a possibly modified command line.
1859 * Also returns a handle to the opened file if it's a Windows binary.
1861 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1862 int buflen, HANDLE *handle, struct binary_info *binary_info )
1864 static const WCHAR quotesW[] = {'"','%','s','"',0};
1866 WCHAR *name, *pos, *first_space, *ret = NULL;
1869 /* if we have an app name, everything is easy */
1873 /* use the unmodified app name as file name */
1874 lstrcpynW( buffer, appname, buflen );
1875 *handle = open_exe_file( buffer, binary_info );
1876 if (!(ret = cmdline) || !cmdline[0])
1878 /* no command-line, create one */
1879 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1880 sprintfW( ret, quotesW, appname );
1885 /* first check for a quoted file name */
1887 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1889 int len = p - cmdline - 1;
1890 /* extract the quoted portion as file name */
1891 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1892 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1895 if (!find_exe_file( name, buffer, buflen, handle, binary_info ))
1897 if (!get_builtin_path( name, exeW, buffer, buflen, binary_info )) goto done;
1900 ret = cmdline; /* no change necessary */
1904 /* now try the command-line word by word */
1906 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1914 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
1916 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
1921 if (!(*pos++ = *p++)) break;
1922 if (!first_space) first_space = pos;
1927 if (first_space) *first_space = 0; /* try only the first word as a builtin */
1928 if (get_builtin_path( name, exeW, buffer, buflen, binary_info ))
1933 else SetLastError( ERROR_FILE_NOT_FOUND );
1935 else if (first_space) /* build a new command-line with quotes */
1937 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1939 sprintfW( ret, quotesW, name );
1944 HeapFree( GetProcessHeap(), 0, name );
1949 /**********************************************************************
1950 * CreateProcessA (KERNEL32.@)
1952 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1953 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1954 DWORD flags, LPVOID env, LPCSTR cur_dir,
1955 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1958 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1959 UNICODE_STRING desktopW, titleW;
1962 desktopW.Buffer = NULL;
1963 titleW.Buffer = NULL;
1964 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1965 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1966 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1968 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1969 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1971 memcpy( &infoW, startup_info, sizeof(infoW) );
1972 infoW.lpDesktop = desktopW.Buffer;
1973 infoW.lpTitle = titleW.Buffer;
1975 if (startup_info->lpReserved)
1976 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1977 debugstr_a(startup_info->lpReserved));
1979 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1980 inherit, flags, env, cur_dirW, &infoW, info );
1982 HeapFree( GetProcessHeap(), 0, app_nameW );
1983 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1984 HeapFree( GetProcessHeap(), 0, cur_dirW );
1985 RtlFreeUnicodeString( &desktopW );
1986 RtlFreeUnicodeString( &titleW );
1991 /**********************************************************************
1992 * CreateProcessW (KERNEL32.@)
1994 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1995 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1996 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1997 LPPROCESS_INFORMATION info )
2001 char *unixdir = NULL;
2002 WCHAR name[MAX_PATH];
2003 WCHAR *tidy_cmdline, *p, *envW = env;
2004 struct binary_info binary_info;
2006 /* Process the AppName and/or CmdLine to get module name and path */
2008 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2010 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2011 &hFile, &binary_info )))
2013 if (hFile == INVALID_HANDLE_VALUE) goto done;
2015 /* Warn if unsupported features are used */
2017 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2018 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2019 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2020 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2021 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2025 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2027 SetLastError(ERROR_DIRECTORY);
2033 WCHAR buf[MAX_PATH];
2034 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2037 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2042 while (*p) p += strlen(p) + 1;
2043 p++; /* final null */
2044 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
2045 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2046 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
2047 flags |= CREATE_UNICODE_ENVIRONMENT;
2050 info->hThread = info->hProcess = 0;
2051 info->dwProcessId = info->dwThreadId = 0;
2053 if (binary_info.flags & BINARY_FLAG_DLL)
2055 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2056 SetLastError( ERROR_BAD_EXE_FORMAT );
2058 else switch (binary_info.type)
2061 TRACE( "starting %s as Win32 binary (%p-%p)\n",
2062 debugstr_w(name), binary_info.res_start, binary_info.res_end );
2063 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2064 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2069 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2070 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2071 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2073 case BINARY_UNIX_LIB:
2074 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
2075 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2076 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2078 case BINARY_UNKNOWN:
2079 /* check for .com or .bat extension */
2080 if ((p = strrchrW( name, '.' )))
2082 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2084 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2085 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2086 inherit, flags, startup_info, info, unixdir,
2087 &binary_info, FALSE );
2090 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2092 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2093 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2094 inherit, flags, startup_info, info );
2099 case BINARY_UNIX_EXE:
2101 /* unknown file, try as unix executable */
2104 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2106 if ((unix_name = wine_get_unix_file_name( name )))
2108 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2109 HeapFree( GetProcessHeap(), 0, unix_name );
2114 if (hFile) CloseHandle( hFile );
2117 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2118 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2119 HeapFree( GetProcessHeap(), 0, unixdir );
2121 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2126 /**********************************************************************
2129 static void exec_process( LPCWSTR name )
2133 STARTUPINFOW startup_info;
2134 PROCESS_INFORMATION info;
2135 struct binary_info binary_info;
2137 hFile = open_exe_file( name, &binary_info );
2138 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2140 memset( &startup_info, 0, sizeof(startup_info) );
2141 startup_info.cb = sizeof(startup_info);
2143 /* Determine executable type */
2145 if (binary_info.flags & BINARY_FLAG_DLL) return;
2146 switch (binary_info.type)
2149 TRACE( "starting %s as Win32 binary (%p-%p)\n",
2150 debugstr_w(name), binary_info.res_start, binary_info.res_end );
2151 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2152 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2154 case BINARY_UNIX_LIB:
2155 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2156 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2157 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2159 case BINARY_UNKNOWN:
2160 /* check for .com or .pif extension */
2161 if (!(p = strrchrW( name, '.' ))) break;
2162 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2167 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2168 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2169 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2174 CloseHandle( hFile );
2178 /***********************************************************************
2181 * Wrapper to call WaitForInputIdle USER function
2183 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2185 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2187 HMODULE mod = GetModuleHandleA( "user32.dll" );
2190 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2191 if (ptr) return ptr( process, timeout );
2197 /***********************************************************************
2198 * WinExec (KERNEL32.@)
2200 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2202 PROCESS_INFORMATION info;
2203 STARTUPINFOA startup;
2207 memset( &startup, 0, sizeof(startup) );
2208 startup.cb = sizeof(startup);
2209 startup.dwFlags = STARTF_USESHOWWINDOW;
2210 startup.wShowWindow = nCmdShow;
2212 /* cmdline needs to be writable for CreateProcess */
2213 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2214 strcpy( cmdline, lpCmdLine );
2216 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2217 0, NULL, NULL, &startup, &info ))
2219 /* Give 30 seconds to the app to come up */
2220 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2221 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2223 /* Close off the handles */
2224 CloseHandle( info.hThread );
2225 CloseHandle( info.hProcess );
2227 else if ((ret = GetLastError()) >= 32)
2229 FIXME("Strange error set by CreateProcess: %d\n", ret );
2232 HeapFree( GetProcessHeap(), 0, cmdline );
2237 /**********************************************************************
2238 * LoadModule (KERNEL32.@)
2240 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2242 LOADPARMS32 *params = paramBlock;
2243 PROCESS_INFORMATION info;
2244 STARTUPINFOA startup;
2245 HINSTANCE hInstance;
2247 char filename[MAX_PATH];
2250 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2252 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2253 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2254 return ULongToHandle(GetLastError());
2256 len = (BYTE)params->lpCmdLine[0];
2257 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2258 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2260 strcpy( cmdline, filename );
2261 p = cmdline + strlen(cmdline);
2263 memcpy( p, params->lpCmdLine + 1, len );
2266 memset( &startup, 0, sizeof(startup) );
2267 startup.cb = sizeof(startup);
2268 if (params->lpCmdShow)
2270 startup.dwFlags = STARTF_USESHOWWINDOW;
2271 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2274 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2275 params->lpEnvAddress, NULL, &startup, &info ))
2277 /* Give 30 seconds to the app to come up */
2278 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2279 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2280 hInstance = (HINSTANCE)33;
2281 /* Close off the handles */
2282 CloseHandle( info.hThread );
2283 CloseHandle( info.hProcess );
2285 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2287 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2288 hInstance = (HINSTANCE)11;
2291 HeapFree( GetProcessHeap(), 0, cmdline );
2296 /******************************************************************************
2297 * TerminateProcess (KERNEL32.@)
2299 * Terminates a process.
2302 * handle [I] Process to terminate.
2303 * exit_code [I] Exit code.
2307 * Failure: FALSE, check GetLastError().
2309 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2311 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2312 if (status) SetLastError( RtlNtStatusToDosError(status) );
2316 /***********************************************************************
2317 * ExitProcess (KERNEL32.@)
2319 * Exits the current process.
2322 * status [I] Status code to exit with.
2328 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2330 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2331 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2332 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2334 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2338 void WINAPI process_ExitProcess( DWORD status )
2340 LdrShutdownProcess();
2341 NtTerminateProcess(GetCurrentProcess(), status);
2347 void WINAPI ExitProcess( DWORD status )
2349 LdrShutdownProcess();
2350 NtTerminateProcess(GetCurrentProcess(), status);
2356 /***********************************************************************
2357 * GetExitCodeProcess [KERNEL32.@]
2359 * Gets termination status of specified process.
2362 * hProcess [in] Handle to the process.
2363 * lpExitCode [out] Address to receive termination status.
2369 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2372 PROCESS_BASIC_INFORMATION pbi;
2374 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2376 if (status == STATUS_SUCCESS)
2378 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2381 SetLastError( RtlNtStatusToDosError(status) );
2386 /***********************************************************************
2387 * SetErrorMode (KERNEL32.@)
2389 UINT WINAPI SetErrorMode( UINT mode )
2391 UINT old = process_error_mode;
2392 process_error_mode = mode;
2396 /***********************************************************************
2397 * GetErrorMode (KERNEL32.@)
2399 UINT WINAPI GetErrorMode( void )
2401 return process_error_mode;
2404 /**********************************************************************
2405 * TlsAlloc [KERNEL32.@]
2407 * Allocates a thread local storage index.
2410 * Success: TLS index.
2411 * Failure: 0xFFFFFFFF
2413 DWORD WINAPI TlsAlloc( void )
2416 PEB * const peb = NtCurrentTeb()->Peb;
2418 RtlAcquirePebLock();
2419 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2420 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2423 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2426 if (!NtCurrentTeb()->TlsExpansionSlots &&
2427 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2428 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2430 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2432 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2436 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2437 index += TLS_MINIMUM_AVAILABLE;
2440 else SetLastError( ERROR_NO_MORE_ITEMS );
2442 RtlReleasePebLock();
2447 /**********************************************************************
2448 * TlsFree [KERNEL32.@]
2450 * Releases a thread local storage index, making it available for reuse.
2453 * index [in] TLS index to free.
2459 BOOL WINAPI TlsFree( DWORD index )
2463 RtlAcquirePebLock();
2464 if (index >= TLS_MINIMUM_AVAILABLE)
2466 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2467 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2471 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2472 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2474 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2475 else SetLastError( ERROR_INVALID_PARAMETER );
2476 RtlReleasePebLock();
2481 /**********************************************************************
2482 * TlsGetValue [KERNEL32.@]
2484 * Gets value in a thread's TLS slot.
2487 * index [in] TLS index to retrieve value for.
2490 * Success: Value stored in calling thread's TLS slot for index.
2491 * Failure: 0 and GetLastError() returns NO_ERROR.
2493 LPVOID WINAPI TlsGetValue( DWORD index )
2497 if (index < TLS_MINIMUM_AVAILABLE)
2499 ret = NtCurrentTeb()->TlsSlots[index];
2503 index -= TLS_MINIMUM_AVAILABLE;
2504 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2506 SetLastError( ERROR_INVALID_PARAMETER );
2509 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2510 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2512 SetLastError( ERROR_SUCCESS );
2517 /**********************************************************************
2518 * TlsSetValue [KERNEL32.@]
2520 * Stores a value in the thread's TLS slot.
2523 * index [in] TLS index to set value for.
2524 * value [in] Value to be stored.
2530 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2532 if (index < TLS_MINIMUM_AVAILABLE)
2534 NtCurrentTeb()->TlsSlots[index] = value;
2538 index -= TLS_MINIMUM_AVAILABLE;
2539 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2541 SetLastError( ERROR_INVALID_PARAMETER );
2544 if (!NtCurrentTeb()->TlsExpansionSlots &&
2545 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2546 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2548 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2551 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2557 /***********************************************************************
2558 * GetProcessFlags (KERNEL32.@)
2560 DWORD WINAPI GetProcessFlags( DWORD processid )
2562 IMAGE_NT_HEADERS *nt;
2565 if (processid && processid != GetCurrentProcessId()) return 0;
2567 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2569 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2570 flags |= PDB32_CONSOLE_PROC;
2572 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2573 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2578 /***********************************************************************
2579 * GetProcessDword (KERNEL32.18)
2581 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2583 FIXME( "(%d, %d): not supported\n", dwProcessID, offset );
2588 /*********************************************************************
2589 * OpenProcess (KERNEL32.@)
2591 * Opens a handle to a process.
2594 * access [I] Desired access rights assigned to the returned handle.
2595 * inherit [I] Determines whether or not child processes will inherit the handle.
2596 * id [I] Process identifier of the process to get a handle to.
2599 * Success: Valid handle to the specified process.
2600 * Failure: NULL, check GetLastError().
2602 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2606 OBJECT_ATTRIBUTES attr;
2609 cid.UniqueProcess = ULongToHandle(id);
2610 cid.UniqueThread = 0; /* FIXME ? */
2612 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2613 attr.RootDirectory = NULL;
2614 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2615 attr.SecurityDescriptor = NULL;
2616 attr.SecurityQualityOfService = NULL;
2617 attr.ObjectName = NULL;
2619 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2621 status = NtOpenProcess(&handle, access, &attr, &cid);
2622 if (status != STATUS_SUCCESS)
2624 SetLastError( RtlNtStatusToDosError(status) );
2631 /*********************************************************************
2632 * GetProcessId (KERNEL32.@)
2634 * Gets the a unique identifier of a process.
2637 * hProcess [I] Handle to the process.
2641 * Failure: FALSE, check GetLastError().
2645 * The identifier is unique only on the machine and only until the process
2646 * exits (including system shutdown).
2648 DWORD WINAPI GetProcessId( HANDLE hProcess )
2651 PROCESS_BASIC_INFORMATION pbi;
2653 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2655 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2656 SetLastError( RtlNtStatusToDosError(status) );
2661 /*********************************************************************
2662 * CloseHandle (KERNEL32.@)
2667 * handle [I] Handle to close.
2671 * Failure: FALSE, check GetLastError().
2673 BOOL WINAPI CloseHandle( HANDLE handle )
2677 /* stdio handles need special treatment */
2678 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2679 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2680 (handle == (HANDLE)STD_ERROR_HANDLE))
2681 handle = GetStdHandle( HandleToULong(handle) );
2683 if (is_console_handle(handle))
2684 return CloseConsoleHandle(handle);
2686 status = NtClose( handle );
2687 if (status) SetLastError( RtlNtStatusToDosError(status) );
2692 /*********************************************************************
2693 * GetHandleInformation (KERNEL32.@)
2695 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2697 OBJECT_DATA_INFORMATION info;
2698 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2700 if (status) SetLastError( RtlNtStatusToDosError(status) );
2704 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2705 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2711 /*********************************************************************
2712 * SetHandleInformation (KERNEL32.@)
2714 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2716 OBJECT_DATA_INFORMATION info;
2719 /* if not setting both fields, retrieve current value first */
2720 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2721 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2723 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2725 SetLastError( RtlNtStatusToDosError(status) );
2729 if (mask & HANDLE_FLAG_INHERIT)
2730 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2731 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2732 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2734 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2735 if (status) SetLastError( RtlNtStatusToDosError(status) );
2740 /*********************************************************************
2741 * DuplicateHandle (KERNEL32.@)
2743 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2744 HANDLE dest_process, HANDLE *dest,
2745 DWORD access, BOOL inherit, DWORD options )
2749 if (is_console_handle(source))
2751 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2752 if (source_process != dest_process ||
2753 source_process != GetCurrentProcess())
2755 SetLastError(ERROR_INVALID_PARAMETER);
2758 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2759 return (*dest != INVALID_HANDLE_VALUE);
2761 status = NtDuplicateObject( source_process, source, dest_process, dest,
2762 access, inherit ? OBJ_INHERIT : 0, options );
2763 if (status) SetLastError( RtlNtStatusToDosError(status) );
2768 /***********************************************************************
2769 * ConvertToGlobalHandle (KERNEL32.@)
2771 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2773 HANDLE ret = INVALID_HANDLE_VALUE;
2774 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2775 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2780 /***********************************************************************
2781 * SetHandleContext (KERNEL32.@)
2783 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2785 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2786 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2787 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2792 /***********************************************************************
2793 * GetHandleContext (KERNEL32.@)
2795 DWORD WINAPI GetHandleContext(HANDLE hnd)
2797 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2798 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2799 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2804 /***********************************************************************
2805 * CreateSocketHandle (KERNEL32.@)
2807 HANDLE WINAPI CreateSocketHandle(void)
2809 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2810 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2811 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2812 return INVALID_HANDLE_VALUE;
2816 /***********************************************************************
2817 * SetPriorityClass (KERNEL32.@)
2819 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2822 PROCESS_PRIORITY_CLASS ppc;
2824 ppc.Foreground = FALSE;
2825 switch (priorityclass)
2827 case IDLE_PRIORITY_CLASS:
2828 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2829 case BELOW_NORMAL_PRIORITY_CLASS:
2830 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2831 case NORMAL_PRIORITY_CLASS:
2832 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2833 case ABOVE_NORMAL_PRIORITY_CLASS:
2834 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2835 case HIGH_PRIORITY_CLASS:
2836 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2837 case REALTIME_PRIORITY_CLASS:
2838 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2840 SetLastError(ERROR_INVALID_PARAMETER);
2844 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2847 if (status != STATUS_SUCCESS)
2849 SetLastError( RtlNtStatusToDosError(status) );
2856 /***********************************************************************
2857 * GetPriorityClass (KERNEL32.@)
2859 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2862 PROCESS_BASIC_INFORMATION pbi;
2864 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2866 if (status != STATUS_SUCCESS)
2868 SetLastError( RtlNtStatusToDosError(status) );
2871 switch (pbi.BasePriority)
2873 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2874 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2875 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2876 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2877 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2878 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2880 SetLastError( ERROR_INVALID_PARAMETER );
2885 /***********************************************************************
2886 * SetProcessAffinityMask (KERNEL32.@)
2888 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2892 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2893 &affmask, sizeof(DWORD_PTR));
2896 SetLastError( RtlNtStatusToDosError(status) );
2903 /**********************************************************************
2904 * GetProcessAffinityMask (KERNEL32.@)
2906 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2907 PDWORD_PTR lpProcessAffinityMask,
2908 PDWORD_PTR lpSystemAffinityMask )
2910 PROCESS_BASIC_INFORMATION pbi;
2913 status = NtQueryInformationProcess(hProcess,
2914 ProcessBasicInformation,
2915 &pbi, sizeof(pbi), NULL);
2918 SetLastError( RtlNtStatusToDosError(status) );
2921 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2922 if (lpSystemAffinityMask) *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2927 /***********************************************************************
2928 * GetProcessVersion (KERNEL32.@)
2930 DWORD WINAPI GetProcessVersion( DWORD pid )
2934 PROCESS_BASIC_INFORMATION pbi;
2937 IMAGE_DOS_HEADER dos;
2938 IMAGE_NT_HEADERS nt;
2941 if (!pid || pid == GetCurrentProcessId())
2943 IMAGE_NT_HEADERS *nt;
2945 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2946 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2947 nt->OptionalHeader.MinorSubsystemVersion);
2951 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
2952 if (!process) return 0;
2954 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
2955 if (status) goto err;
2957 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
2958 if (status || count != sizeof(peb)) goto err;
2960 memset(&dos, 0, sizeof(dos));
2961 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
2962 if (status || count != sizeof(dos)) goto err;
2963 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
2965 memset(&nt, 0, sizeof(nt));
2966 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
2967 if (status || count != sizeof(nt)) goto err;
2968 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
2970 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
2973 CloseHandle(process);
2975 if (status != STATUS_SUCCESS)
2976 SetLastError(RtlNtStatusToDosError(status));
2982 /***********************************************************************
2983 * SetProcessWorkingSetSize [KERNEL32.@]
2984 * Sets the min/max working set sizes for a specified process.
2987 * hProcess [I] Handle to the process of interest
2988 * minset [I] Specifies minimum working set size
2989 * maxset [I] Specifies maximum working set size
2995 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2998 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2999 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3000 /* Trim the working set to zero */
3001 /* Swap the process out of physical RAM */
3006 /***********************************************************************
3007 * GetProcessWorkingSetSize (KERNEL32.@)
3009 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3012 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3013 /* 32 MB working set size */
3014 if (minset) *minset = 32*1024*1024;
3015 if (maxset) *maxset = 32*1024*1024;
3020 /***********************************************************************
3021 * SetProcessShutdownParameters (KERNEL32.@)
3023 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3025 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3026 shutdown_flags = flags;
3027 shutdown_priority = level;
3032 /***********************************************************************
3033 * GetProcessShutdownParameters (KERNEL32.@)
3036 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3038 *lpdwLevel = shutdown_priority;
3039 *lpdwFlags = shutdown_flags;
3044 /***********************************************************************
3045 * GetProcessPriorityBoost (KERNEL32.@)
3047 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3049 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3051 /* Report that no boost is present.. */
3052 *pDisablePriorityBoost = FALSE;
3057 /***********************************************************************
3058 * SetProcessPriorityBoost (KERNEL32.@)
3060 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3062 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3063 /* Say we can do it. I doubt the program will notice that we don't. */
3068 /***********************************************************************
3069 * ReadProcessMemory (KERNEL32.@)
3071 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3072 SIZE_T *bytes_read )
3074 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3075 if (status) SetLastError( RtlNtStatusToDosError(status) );
3080 /***********************************************************************
3081 * WriteProcessMemory (KERNEL32.@)
3083 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3084 SIZE_T *bytes_written )
3086 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3087 if (status) SetLastError( RtlNtStatusToDosError(status) );
3092 /****************************************************************************
3093 * FlushInstructionCache (KERNEL32.@)
3095 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3098 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3099 if (status) SetLastError( RtlNtStatusToDosError(status) );
3104 /******************************************************************
3105 * GetProcessIoCounters (KERNEL32.@)
3107 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3111 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3112 ioc, sizeof(*ioc), NULL);
3113 if (status) SetLastError( RtlNtStatusToDosError(status) );
3117 /******************************************************************
3118 * GetProcessHandleCount (KERNEL32.@)
3120 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3124 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3125 cnt, sizeof(*cnt), NULL);
3126 if (status) SetLastError( RtlNtStatusToDosError(status) );
3130 /******************************************************************
3131 * QueryFullProcessImageNameA (KERNEL32.@)
3133 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3136 DWORD pdwSizeW = *pdwSize;
3137 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3139 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3142 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3143 lpExeName, *pdwSize, NULL, NULL));
3145 *pdwSize = strlen(lpExeName);
3147 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3151 /******************************************************************
3152 * QueryFullProcessImageNameW (KERNEL32.@)
3154 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3156 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3157 UNICODE_STRING *dynamic_buffer = NULL;
3158 UNICODE_STRING nt_path;
3159 UNICODE_STRING *result = NULL;
3163 RtlInitUnicodeStringEx(&nt_path, NULL);
3164 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3165 * as this is on Wine. */
3166 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3167 sizeof(buffer) - sizeof(WCHAR), &needed);
3168 if (status == STATUS_INFO_LENGTH_MISMATCH)
3170 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3171 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3172 result = dynamic_buffer;
3175 result = (PUNICODE_STRING)buffer;
3177 if (status) goto cleanup;
3179 if (dwFlags & PROCESS_NAME_NATIVE)
3181 result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3182 if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3184 status = STATUS_OBJECT_PATH_NOT_FOUND;
3190 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3192 status = STATUS_BUFFER_TOO_SMALL;
3196 *pdwSize = result->Length/sizeof(WCHAR);
3197 memcpy( lpExeName, result->Buffer, result->Length );
3198 lpExeName[*pdwSize] = 0;
3201 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3202 RtlFreeUnicodeString(&nt_path);
3203 if (status) SetLastError( RtlNtStatusToDosError(status) );
3207 /***********************************************************************
3208 * ProcessIdToSessionId (KERNEL32.@)
3209 * This function is available on Terminal Server 4SP4 and Windows 2000
3211 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3213 /* According to MSDN, if the calling process is not in a terminal
3214 * services environment, then the sessionid returned is zero.
3221 /***********************************************************************
3222 * RegisterServiceProcess (KERNEL32.@)
3224 * A service process calls this function to ensure that it continues to run
3225 * even after a user logged off.
3227 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3229 /* I don't think that Wine needs to do anything in this function */
3230 return 1; /* success */
3234 /**********************************************************************
3235 * IsWow64Process (KERNEL32.@)
3237 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3242 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3244 if (status != STATUS_SUCCESS)
3246 SetLastError( RtlNtStatusToDosError( status ) );
3249 *Wow64Process = (pbi != 0);
3254 /***********************************************************************
3255 * GetCurrentProcess (KERNEL32.@)
3257 * Get a handle to the current process.
3263 * A handle representing the current process.
3265 #undef GetCurrentProcess
3266 HANDLE WINAPI GetCurrentProcess(void)
3268 return (HANDLE)~(ULONG_PTR)0;
3271 /***********************************************************************
3272 * CmdBatNotification (KERNEL32.@)
3274 * Notifies the system that a batch file has started or finished.
3277 * bBatchRunning [I] TRUE if a batch file has started or
3278 * FALSE if a batch file has finished executing.
3283 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3285 FIXME("%d\n", bBatchRunning);
3290 /***********************************************************************
3291 * RegisterApplicationRestart (KERNEL32.@)
3293 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3295 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3300 /**********************************************************************
3301 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3303 DWORD WINAPI WTSGetActiveConsoleSessionId(void)