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 #include <CoreFoundation/CoreFoundation.h>
62 extern char **__wine_get_main_environment(void);
64 extern char **__wine_main_environ;
65 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
76 static DWORD shutdown_flags = 0;
77 static DWORD shutdown_priority = 0x280;
79 static const int is_win64 = (sizeof(void *) > sizeof(int));
81 HMODULE kernel32_handle = 0;
83 const WCHAR *DIR_Windows = NULL;
84 const WCHAR *DIR_System = NULL;
85 const WCHAR *DIR_SysWow64 = NULL;
88 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
89 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
90 #define PDB32_DOS_PROC 0x0010 /* Dos process */
91 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
92 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
93 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
95 static const WCHAR exeW[] = {'.','e','x','e',0};
96 static const WCHAR comW[] = {'.','c','o','m',0};
97 static const WCHAR batW[] = {'.','b','a','t',0};
98 static const WCHAR cmdW[] = {'.','c','m','d',0};
99 static const WCHAR pifW[] = {'.','p','i','f',0};
100 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
102 static void exec_process( LPCWSTR name );
104 extern void SHELL_LoadRegistry(void);
107 /***********************************************************************
110 static inline int contains_path( LPCWSTR name )
112 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
116 /***********************************************************************
119 * Check if an environment variable needs to be handled specially when
120 * passed through the Unix environment (i.e. prefixed with "WINE").
122 static inline int is_special_env_var( const char *var )
124 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
125 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
126 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
127 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
128 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
132 /***********************************************************************
135 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
137 unsigned int len = strlenW( prefix );
139 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
140 while (filename[len] == '\\') len++;
145 /***************************************************************************
148 * Get the path of a builtin module when the native file does not exist.
150 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
151 UINT size, struct binary_info *binary_info )
155 void *redir_disabled = 0;
156 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
158 /* builtin names cannot be empty or contain spaces */
159 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
161 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
162 Wow64RevertWow64FsRedirection( redir_disabled );
164 if (contains_path( libname ))
166 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
167 filename, &file_part ) > size * sizeof(WCHAR))
168 return FALSE; /* too long */
170 if ((len = is_path_prefix( DIR_System, filename )))
172 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
174 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
180 if (filename + len != file_part) return FALSE;
184 len = strlenW( DIR_System );
185 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
186 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
187 file_part = filename + len;
188 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
189 strcpyW( file_part, libname );
190 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
192 if (ext && !strchrW( file_part, '.' ))
194 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
195 return FALSE; /* too long */
196 strcatW( file_part, ext );
198 binary_info->type = BINARY_UNIX_LIB;
199 binary_info->flags = flags;
200 binary_info->res_start = NULL;
201 binary_info->res_end = NULL;
206 /***********************************************************************
209 * Open a specific exe file, taking load order into account.
210 * Returns the file handle or 0 for a builtin exe.
212 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
216 TRACE("looking for %s\n", debugstr_w(name) );
218 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
219 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
221 WCHAR buffer[MAX_PATH];
222 /* file doesn't exist, check for builtin */
223 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
226 else MODULE_get_binary_info( handle, binary_info );
232 /***********************************************************************
235 * Open an exe file, and return the full name and file handle.
236 * Returns FALSE if file could not be found.
237 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
238 * If file is a builtin exe, returns TRUE and sets handle to 0.
240 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
241 HANDLE *handle, struct binary_info *binary_info )
243 TRACE("looking for %s\n", debugstr_w(name) );
245 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ))
247 if (contains_path( name ) && get_builtin_path( name, exeW, buffer, buflen, binary_info ))
252 /* no builtin found, try native without extension in case it is a Unix app */
253 if (!SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
256 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
257 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
258 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
260 MODULE_get_binary_info( *handle, binary_info );
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 static const WCHAR pathW[] = {'P','A','T','H'};
328 static const WCHAR sep[] = {';',0};
329 UNICODE_STRING env_name, env_value;
333 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
336 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
339 tmp.MaximumLength = sizeof(tmpbuf);
341 for (index = 0; ; index++)
343 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
344 buffer, sizeof(buffer), &size );
345 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
347 if (info->Type != type)
349 env_name.Buffer = info->Name;
350 env_name.Length = env_name.MaximumLength = info->NameLength;
351 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
352 env_value.Length = info->DataLength;
353 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
354 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
355 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
356 if (!env_value.Length) continue;
357 if (info->Type == REG_EXPAND_SZ)
359 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
360 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
361 RtlCopyUnicodeString( &env_value, &tmp );
364 if (env_name.Length == sizeof(pathW) &&
365 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
366 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
368 RtlAppendUnicodeToString( &tmp, sep );
369 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
370 RtlCopyUnicodeString( &env_value, &tmp );
372 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
377 /***********************************************************************
378 * set_registry_environment
380 * Set the environment variables specified in the registry.
382 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
383 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
384 * on the order in which the variables are processed. But on Windows it
385 * does not really matter since they only use %SystemDrive% and
386 * %SystemRoot% which are predefined. But Wine defines these in the
387 * registry, so we need two passes.
389 static BOOL set_registry_environment( BOOL volatile_only )
391 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
392 'S','y','s','t','e','m','\\',
393 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
394 'C','o','n','t','r','o','l','\\',
395 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
396 'E','n','v','i','r','o','n','m','e','n','t',0};
397 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
398 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};
400 OBJECT_ATTRIBUTES attr;
401 UNICODE_STRING nameW;
405 attr.Length = sizeof(attr);
406 attr.RootDirectory = 0;
407 attr.ObjectName = &nameW;
409 attr.SecurityDescriptor = NULL;
410 attr.SecurityQualityOfService = NULL;
412 /* first the system environment variables */
413 RtlInitUnicodeString( &nameW, env_keyW );
414 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
416 set_registry_variables( hkey, REG_SZ );
417 set_registry_variables( hkey, REG_EXPAND_SZ );
422 /* then the ones for the current user */
423 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
424 RtlInitUnicodeString( &nameW, envW );
425 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
427 set_registry_variables( hkey, REG_SZ );
428 set_registry_variables( hkey, REG_EXPAND_SZ );
432 RtlInitUnicodeString( &nameW, volatile_envW );
433 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
435 set_registry_variables( hkey, REG_SZ );
436 set_registry_variables( hkey, REG_EXPAND_SZ );
440 NtClose( attr.RootDirectory );
445 /***********************************************************************
448 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
450 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
451 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
452 DWORD len, size = sizeof(buffer);
454 UNICODE_STRING nameW;
456 RtlInitUnicodeString( &nameW, name );
457 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
460 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
461 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
463 if (info->Type == REG_EXPAND_SZ)
465 UNICODE_STRING value, expanded;
467 value.MaximumLength = len * sizeof(WCHAR);
468 value.Buffer = (WCHAR *)info->Data;
469 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
470 value.Length = len * sizeof(WCHAR);
471 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
472 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
473 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
474 else RtlFreeUnicodeString( &expanded );
476 else if (info->Type == REG_SZ)
478 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
480 memcpy( ret, info->Data, len * sizeof(WCHAR) );
488 /***********************************************************************
489 * set_additional_environment
491 * Set some additional environment variables not specified in the registry.
493 static void set_additional_environment(void)
495 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
496 'S','o','f','t','w','a','r','e','\\',
497 'M','i','c','r','o','s','o','f','t','\\',
498 'W','i','n','d','o','w','s',' ','N','T','\\',
499 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
500 'P','r','o','f','i','l','e','L','i','s','t',0};
501 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
502 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
503 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
504 OBJECT_ATTRIBUTES attr;
505 UNICODE_STRING nameW;
506 WCHAR *profile_dir = NULL, *all_users_dir = NULL;
510 /* set the ALLUSERSPROFILE variables */
512 attr.Length = sizeof(attr);
513 attr.RootDirectory = 0;
514 attr.ObjectName = &nameW;
516 attr.SecurityDescriptor = NULL;
517 attr.SecurityQualityOfService = NULL;
518 RtlInitUnicodeString( &nameW, profile_keyW );
519 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
521 profile_dir = get_reg_value( hkey, profiles_valueW );
522 all_users_dir = get_reg_value( hkey, all_users_valueW );
526 if (profile_dir && all_users_dir)
530 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
531 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
532 strcpyW( value, profile_dir );
533 p = value + strlenW(value);
534 if (p > value && p[-1] != '\\') *p++ = '\\';
535 strcpyW( p, all_users_dir );
536 SetEnvironmentVariableW( allusersW, value );
537 HeapFree( GetProcessHeap(), 0, value );
540 HeapFree( GetProcessHeap(), 0, all_users_dir );
541 HeapFree( GetProcessHeap(), 0, profile_dir );
544 /***********************************************************************
545 * set_wow64_environment
547 * Set the environment variables that change across 32/64/Wow64.
549 static void set_wow64_environment(void)
551 static const WCHAR archW[] = {'P','R','O','C','E','S','S','O','R','_','A','R','C','H','I','T','E','C','T','U','R','E',0};
552 static const WCHAR arch6432W[] = {'P','R','O','C','E','S','S','O','R','_','A','R','C','H','I','T','E','W','6','4','3','2',0};
553 static const WCHAR x86W[] = {'x','8','6',0};
554 static const WCHAR versionW[] = {'M','a','c','h','i','n','e','\\',
555 'S','o','f','t','w','a','r','e','\\',
556 'M','i','c','r','o','s','o','f','t','\\',
557 'W','i','n','d','o','w','s','\\',
558 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
559 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
560 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
561 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
562 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
563 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
564 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
565 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
566 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
568 OBJECT_ATTRIBUTES attr;
569 UNICODE_STRING nameW;
574 /* set the PROCESSOR_ARCHITECTURE variable */
576 if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
580 SetEnvironmentVariableW( archW, arch );
581 SetEnvironmentVariableW( arch6432W, NULL );
584 else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
588 SetEnvironmentVariableW( arch6432W, arch );
589 SetEnvironmentVariableW( archW, x86W );
593 attr.Length = sizeof(attr);
594 attr.RootDirectory = 0;
595 attr.ObjectName = &nameW;
597 attr.SecurityDescriptor = NULL;
598 attr.SecurityQualityOfService = NULL;
599 RtlInitUnicodeString( &nameW, versionW );
600 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
602 /* set the ProgramFiles variables */
604 if ((value = get_reg_value( hkey, progdirW )))
606 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
607 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
608 HeapFree( GetProcessHeap(), 0, value );
610 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
612 SetEnvironmentVariableW( progfilesW, value );
613 HeapFree( GetProcessHeap(), 0, value );
616 /* set the CommonProgramFiles variables */
618 if ((value = get_reg_value( hkey, commondirW )))
620 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
621 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
622 HeapFree( GetProcessHeap(), 0, value );
624 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
626 SetEnvironmentVariableW( commonfilesW, value );
627 HeapFree( GetProcessHeap(), 0, value );
633 /***********************************************************************
636 * Set the Wine library Unicode argv global variables.
638 static void set_library_wargv( char **argv )
646 for (argc = 0; argv[argc]; argc++)
647 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
649 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
650 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
651 p = (WCHAR *)(wargv + argc + 1);
652 for (argc = 0; argv[argc]; argc++)
654 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
661 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
663 for (argc = 0; wargv[argc]; argc++)
664 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
666 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
667 q = (char *)(argv + argc + 1);
668 for (argc = 0; wargv[argc]; argc++)
670 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
677 __wine_main_argc = argc;
678 __wine_main_argv = argv;
679 __wine_main_wargv = wargv;
683 /***********************************************************************
684 * update_library_argv0
686 * Update the argv[0] global variable with the binary we have found.
688 static void update_library_argv0( const WCHAR *argv0 )
690 DWORD len = strlenW( argv0 );
692 if (len > strlenW( __wine_main_wargv[0] ))
694 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
696 strcpyW( __wine_main_wargv[0], argv0 );
698 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
699 if (len > strlen( __wine_main_argv[0] ) + 1)
701 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
703 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
707 /***********************************************************************
710 * Build the command line of a process from the argv array.
712 * Note that it does NOT necessarily include the file name.
713 * Sometimes we don't even have any command line options at all.
715 * We must quote and escape characters so that the argv array can be rebuilt
716 * from the command line:
717 * - spaces and tabs must be quoted
719 * - quotes must be escaped
721 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
722 * resulting in an odd number of '\' followed by a '"'
725 * - '\'s that are not followed by a '"' can be left as is
729 static BOOL build_command_line( WCHAR **argv )
734 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
736 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
739 for (arg = argv; *arg; arg++)
741 int has_space,bcount;
747 if( !*a ) has_space=1;
752 if (*a==' ' || *a=='\t') {
754 } else if (*a=='"') {
755 /* doubling of '\' preceding a '"',
756 * plus escaping of said '"'
764 len+=(a-*arg)+1 /* for the separating space */;
766 len+=2; /* for the quotes */
769 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
772 p = rupp->CommandLine.Buffer;
773 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
774 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
775 for (arg = argv; *arg; arg++)
777 int has_space,has_quote;
780 /* Check for quotes and spaces in this argument */
781 has_space=has_quote=0;
783 if( !*a ) has_space=1;
785 if (*a==' ' || *a=='\t') {
789 } else if (*a=='"') {
797 /* Now transfer it to the command line */
814 /* Double all the '\\' preceding this '"', plus one */
815 for (i=0;i<=bcount;i++)
827 while ((*p=*x++)) p++;
833 if (p > rupp->CommandLine.Buffer)
834 p--; /* remove last space */
841 /***********************************************************************
842 * init_current_directory
844 * Initialize the current directory from the Unix cwd or the parent info.
846 static void init_current_directory( CURDIR *cur_dir )
848 UNICODE_STRING dir_str;
853 /* if we received a cur dir from the parent, try this first */
855 if (cur_dir->DosPath.Length)
857 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
860 /* now try to get it from the Unix cwd */
862 for (size = 256; ; size *= 2)
864 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
865 if (getcwd( cwd, size )) break;
866 HeapFree( GetProcessHeap(), 0, cwd );
867 if (errno == ERANGE) continue;
872 /* try to use PWD if it is valid, so that we don't resolve symlinks */
874 pwd = getenv( "PWD" );
877 struct stat st1, st2;
879 if (!pwd || stat( pwd, &st1 ) == -1 ||
880 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
886 ANSI_STRING unix_name;
887 UNICODE_STRING nt_name;
888 RtlInitAnsiString( &unix_name, pwd );
889 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
891 UNICODE_STRING dos_path;
892 /* skip the \??\ prefix, nt_name is 0 terminated */
893 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
894 RtlSetCurrentDirectory_U( &dos_path );
895 RtlFreeUnicodeString( &nt_name );
899 if (!cur_dir->DosPath.Length) /* still not initialized */
901 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
902 "starting in the Windows directory.\n", cwd ? cwd : "" );
903 RtlInitUnicodeString( &dir_str, DIR_Windows );
904 RtlSetCurrentDirectory_U( &dir_str );
906 HeapFree( GetProcessHeap(), 0, cwd );
909 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
910 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
914 /***********************************************************************
917 * Initialize the windows and system directories from the environment.
919 static void init_windows_dirs(void)
921 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
923 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
924 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
925 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
926 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
927 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
932 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
934 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
935 GetEnvironmentVariableW( windirW, buffer, len );
936 DIR_Windows = buffer;
938 else DIR_Windows = default_windirW;
940 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
942 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
943 GetEnvironmentVariableW( winsysdirW, buffer, len );
948 len = strlenW( DIR_Windows );
949 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
950 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
951 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
955 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
956 ERR( "directory %s could not be created, error %u\n",
957 debugstr_w(DIR_Windows), GetLastError() );
958 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
959 ERR( "directory %s could not be created, error %u\n",
960 debugstr_w(DIR_System), GetLastError() );
962 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
964 len = strlenW( DIR_Windows );
965 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
966 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
967 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
968 DIR_SysWow64 = buffer;
969 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
970 ERR( "directory %s could not be created, error %u\n",
971 debugstr_w(DIR_SysWow64), GetLastError() );
974 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
975 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
977 /* set the directories in ntdll too */
978 __wine_init_windows_dir( DIR_Windows, DIR_System );
982 /***********************************************************************
985 * Start the wineboot process if necessary. Return the handles to wait on.
987 static void start_wineboot( HANDLE handles[2] )
989 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
992 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
994 ERR( "failed to create wineboot event, expect trouble\n" );
997 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
999 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1000 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1002 PROCESS_INFORMATION pi;
1004 WCHAR app[MAX_PATH];
1005 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1007 memset( &si, 0, sizeof(si) );
1009 si.dwFlags = STARTF_USESTDHANDLES;
1012 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1014 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1015 lstrcatW( app, wineboot );
1017 Wow64DisableWow64FsRedirection( &redir );
1018 strcpyW( cmdline, app );
1019 strcatW( cmdline, args );
1020 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1022 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1023 CloseHandle( pi.hThread );
1024 handles[1] = pi.hProcess;
1028 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1029 CloseHandle( handles[0] );
1032 Wow64RevertWow64FsRedirection( redir );
1038 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1039 __ASM_GLOBAL_FUNC( call_process_entry,
1041 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1042 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1043 "movl %esp,%ebp\n\t"
1044 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1045 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1047 "call *12(%ebp)\n\t"
1049 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1050 __ASM_CFI(".cfi_same_value %ebp\n\t")
1053 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1055 return entry( peb );
1059 /***********************************************************************
1062 * Startup routine of a new process. Runs on the new process stack.
1064 static DWORD WINAPI start_process( PEB *peb )
1066 IMAGE_NT_HEADERS *nt;
1067 LPTHREAD_START_ROUTINE entry;
1069 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1070 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1071 nt->OptionalHeader.AddressOfEntryPoint);
1073 if (!nt->OptionalHeader.AddressOfEntryPoint)
1075 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1076 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1080 if (TRACE_ON(relay))
1081 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1082 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1084 SetLastError( 0 ); /* clear error code */
1085 if (peb->BeingDebugged) DbgBreakPoint();
1086 return call_process_entry( peb, entry );
1090 /***********************************************************************
1093 * Change the process name in the ps output.
1095 static void set_process_name( int argc, char *argv[] )
1097 #ifdef HAVE_SETPROCTITLE
1098 setproctitle("-%s", argv[1]);
1103 char *p, *prctl_name = argv[1];
1104 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1107 # define PR_SET_NAME 15
1110 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1111 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1113 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1115 offset = argv[1] - argv[0];
1116 memmove( argv[1] - offset, argv[1], end - argv[1] );
1117 memset( end - offset, 0, offset );
1118 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1122 #endif /* HAVE_PRCTL */
1124 /* remove argv[0] */
1125 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1130 /***********************************************************************
1131 * __wine_kernel_init
1133 * Wine initialisation: load and start the main exe file.
1135 void CDECL __wine_kernel_init(void)
1137 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1138 static const WCHAR dotW[] = {'.',0};
1140 WCHAR *p, main_exe_name[MAX_PATH+1];
1141 PEB *peb = NtCurrentTeb()->Peb;
1142 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1143 HANDLE boot_events[2];
1144 BOOL got_environment = TRUE;
1146 /* Initialize everything */
1148 setbuf(stdout,NULL);
1149 setbuf(stderr,NULL);
1150 kernel32_handle = GetModuleHandleW(kernel32W);
1151 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1155 if (!params->Environment)
1157 /* Copy the parent environment */
1158 if (!build_initial_environment()) exit(1);
1160 /* convert old configuration to new format */
1161 convert_old_config();
1163 got_environment = set_registry_environment( FALSE );
1164 set_additional_environment();
1167 init_windows_dirs();
1168 init_current_directory( ¶ms->CurrentDirectory );
1170 set_process_name( __wine_main_argc, __wine_main_argv );
1171 set_library_wargv( __wine_main_argv );
1172 boot_events[0] = boot_events[1] = 0;
1174 if (peb->ProcessParameters->ImagePathName.Buffer)
1176 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1180 struct binary_info binary_info;
1182 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1183 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1185 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1186 ExitProcess( GetLastError() );
1188 update_library_argv0( main_exe_name );
1189 if (!build_command_line( __wine_main_wargv )) goto error;
1190 start_wineboot( boot_events );
1193 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1194 p = strrchrW( main_exe_name, '.' );
1195 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1197 TRACE( "starting process name=%s argv[0]=%s\n",
1198 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1200 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1201 MODULE_get_dll_load_path(main_exe_name) );
1205 DWORD timeout = 2 * 60 * 1000, count = 1;
1207 if (boot_events[1]) count++;
1208 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1209 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1210 ERR( "boot event wait timed out\n" );
1211 CloseHandle( boot_events[0] );
1212 if (boot_events[1]) CloseHandle( boot_events[1] );
1213 /* reload environment now that wineboot has run */
1214 set_registry_environment( got_environment );
1215 set_additional_environment();
1217 set_wow64_environment();
1219 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1224 DWORD error = GetLastError();
1226 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1227 if (error == ERROR_BAD_EXE_FORMAT ||
1228 error == ERROR_INVALID_ADDRESS ||
1229 error == ERROR_NOT_ENOUGH_MEMORY)
1231 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1232 /* if we get back here, it failed */
1234 else if (error == ERROR_MOD_NOT_FOUND)
1236 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1237 else p = main_exe_name;
1238 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1240 /* args 1 and 2 are --app-name full_path */
1241 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1242 debugstr_w(__wine_main_wargv[3]) );
1243 ExitProcess( ERROR_BAD_EXE_FORMAT );
1245 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1246 ExitProcess( ERROR_FILE_NOT_FOUND );
1248 args[0] = (DWORD_PTR)main_exe_name;
1249 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1250 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1251 WideCharToMultiByte( CP_ACP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1252 MESSAGE( "wine: %s", msg );
1253 ExitProcess( error );
1256 LdrInitializeThunk( start_process, 0, 0, 0 );
1259 ExitProcess( GetLastError() );
1263 /***********************************************************************
1266 * Build an argv array from a command-line.
1267 * 'reserved' is the number of args to reserve before the first one.
1269 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1273 char *arg,*s,*d,*cmdline;
1274 int in_quotes,bcount,len;
1276 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1277 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1278 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1285 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1288 /* skip the remaining spaces */
1289 while (*s==' ' || *s=='\t') {
1296 } else if (*s=='\\') {
1297 /* '\', count them */
1299 } else if ((*s=='"') && ((bcount & 1)==0)) {
1301 in_quotes=!in_quotes;
1304 /* a regular character */
1309 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1311 HeapFree( GetProcessHeap(), 0, cmdline );
1315 arg = d = s = (char *)(argv + argc);
1316 memcpy( d, cmdline, len );
1321 if ((*s==' ' || *s=='\t') && !in_quotes) {
1322 /* Close the argument and copy it */
1326 /* skip the remaining spaces */
1329 } while (*s==' ' || *s=='\t');
1331 /* Start with a new argument */
1334 } else if (*s=='\\') {
1338 } else if (*s=='"') {
1340 if ((bcount & 1)==0) {
1341 /* Preceded by an even number of '\', this is half that
1342 * number of '\', plus a '"' which we discard.
1346 in_quotes=!in_quotes;
1348 /* Preceded by an odd number of '\', this is half that
1349 * number of '\' followed by a '"'
1357 /* a regular character */
1368 HeapFree( GetProcessHeap(), 0, cmdline );
1373 /***********************************************************************
1376 * Build the environment of a new child process.
1378 static char **build_envp( const WCHAR *envW )
1380 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1385 int count = 1, length;
1388 for (end = envW; *end; count++) end += strlenW(end) + 1;
1390 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1391 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1392 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1394 for (p = env; *p; p += strlen(p) + 1)
1395 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1397 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1399 if (!(p = getenv(unix_vars[i]))) continue;
1400 length += strlen(unix_vars[i]) + strlen(p) + 2;
1404 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1406 char **envptr = envp;
1407 char *dst = (char *)(envp + count);
1409 /* some variables must not be modified, so we get them directly from the unix env */
1410 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1412 if (!(p = getenv(unix_vars[i]))) continue;
1413 *envptr++ = strcpy( dst, unix_vars[i] );
1416 dst += strlen(dst) + 1;
1419 /* now put the Windows environment strings */
1420 for (p = env; *p; p += strlen(p) + 1)
1422 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1423 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1424 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1425 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1426 if (is_special_env_var( p )) /* prefix it with "WINE" */
1428 *envptr++ = strcpy( dst, "WINE" );
1433 *envptr++ = strcpy( dst, p );
1435 dst += strlen(dst) + 1;
1439 HeapFree( GetProcessHeap(), 0, env );
1444 /***********************************************************************
1447 * Fork and exec a new Unix binary, checking for errors.
1449 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1450 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1452 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1454 char **argv, **envp;
1456 if (!env) env = GetEnvironmentStringsW();
1459 if (pipe2( fd, O_CLOEXEC ) == -1)
1464 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1467 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1468 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1471 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1473 HANDLE hstdin, hstdout, hstderr;
1475 if (startup->dwFlags & STARTF_USESTDHANDLES)
1477 hstdin = startup->hStdInput;
1478 hstdout = startup->hStdOutput;
1479 hstderr = startup->hStdError;
1483 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1484 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1485 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1488 if (is_console_handle( hstdin ))
1489 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1490 if (is_console_handle( hstdout ))
1491 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1492 if (is_console_handle( hstderr ))
1493 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1494 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1495 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1496 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1499 argv = build_argv( cmdline, 0 );
1500 envp = build_envp( env );
1502 if (!(pid = fork())) /* child */
1506 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1509 if (!(pid = fork()))
1511 int fd = open( "/dev/null", O_RDWR );
1513 /* close stdin and stdout */
1521 else if (pid != -1) _exit(0); /* parent */
1527 dup2( stdin_fd, 0 );
1530 if (stdout_fd != -1)
1532 dup2( stdout_fd, 1 );
1535 if (stderr_fd != -1)
1537 dup2( stderr_fd, 2 );
1542 /* Reset signals that we previously set to SIG_IGN */
1543 signal( SIGPIPE, SIG_DFL );
1544 signal( SIGCHLD, SIG_DFL );
1546 if (newdir) chdir(newdir);
1548 if (argv && envp) execve( filename, argv, envp );
1550 write( fd[1], &err, sizeof(err) );
1553 HeapFree( GetProcessHeap(), 0, argv );
1554 HeapFree( GetProcessHeap(), 0, envp );
1555 if (stdin_fd != -1) close( stdin_fd );
1556 if (stdout_fd != -1) close( stdout_fd );
1557 if (stderr_fd != -1) close( stderr_fd );
1559 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1564 if (pid == -1) FILE_SetDosError();
1570 static inline DWORD append_string( void **ptr, const WCHAR *str )
1572 DWORD len = strlenW( str );
1573 memcpy( *ptr, str, len * sizeof(WCHAR) );
1574 *ptr = (WCHAR *)*ptr + len;
1575 return len * sizeof(WCHAR);
1578 /***********************************************************************
1579 * create_startup_info
1581 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1582 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1583 const STARTUPINFOW *startup, DWORD *info_size )
1585 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1587 startup_info_t *info;
1590 UNICODE_STRING newdir;
1591 WCHAR imagepath[MAX_PATH];
1592 HANDLE hstdin, hstdout, hstderr;
1594 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1595 lstrcpynW( imagepath, filename, MAX_PATH );
1596 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1597 lstrcpynW( imagepath, filename, MAX_PATH );
1599 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1601 newdir.Buffer = NULL;
1604 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1605 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1611 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1612 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1614 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1616 title = startup->lpTitle ? startup->lpTitle : imagepath;
1618 size = sizeof(*info);
1619 size += strlenW( cur_dir ) * sizeof(WCHAR);
1620 size += cur_params->DllPath.Length;
1621 size += strlenW( imagepath ) * sizeof(WCHAR);
1622 size += strlenW( cmdline ) * sizeof(WCHAR);
1623 size += strlenW( title ) * sizeof(WCHAR);
1624 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1625 /* FIXME: shellinfo */
1626 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1627 size = (size + 1) & ~1;
1630 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1632 info->console_flags = cur_params->ConsoleFlags;
1633 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1634 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1636 if (startup->dwFlags & STARTF_USESTDHANDLES)
1638 hstdin = startup->hStdInput;
1639 hstdout = startup->hStdOutput;
1640 hstderr = startup->hStdError;
1644 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1645 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1646 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1648 info->hstdin = wine_server_obj_handle( hstdin );
1649 info->hstdout = wine_server_obj_handle( hstdout );
1650 info->hstderr = wine_server_obj_handle( hstderr );
1651 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1653 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1654 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1655 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1656 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1660 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1661 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1662 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1665 info->x = startup->dwX;
1666 info->y = startup->dwY;
1667 info->xsize = startup->dwXSize;
1668 info->ysize = startup->dwYSize;
1669 info->xchars = startup->dwXCountChars;
1670 info->ychars = startup->dwYCountChars;
1671 info->attribute = startup->dwFillAttribute;
1672 info->flags = startup->dwFlags;
1673 info->show = startup->wShowWindow;
1676 info->curdir_len = append_string( &ptr, cur_dir );
1677 info->dllpath_len = cur_params->DllPath.Length;
1678 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1679 ptr = (char *)ptr + cur_params->DllPath.Length;
1680 info->imagepath_len = append_string( &ptr, imagepath );
1681 info->cmdline_len = append_string( &ptr, cmdline );
1682 info->title_len = append_string( &ptr, title );
1683 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1684 if (startup->lpReserved2 && startup->cbReserved2)
1686 info->runtime_len = startup->cbReserved2;
1687 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1691 RtlFreeUnicodeString( &newdir );
1695 /***********************************************************************
1696 * get_alternate_loader
1698 * Get the name of the alternate (32 or 64 bit) Wine loader.
1700 static const char *get_alternate_loader( char **ret_env )
1703 const char *loader = NULL;
1704 const char *loader_env = getenv( "WINELOADER" );
1708 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1712 int len = strlen( loader_env );
1715 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1716 strcpy( env, "WINELOADER=" );
1717 strcat( env, loader_env );
1718 strcat( env, "64" );
1722 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1723 strcpy( env, "WINELOADER=" );
1724 strcat( env, loader_env );
1725 len += sizeof("WINELOADER=") - 1;
1726 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1730 if ((loader = strrchr( env, '/' ))) loader++;
1735 if (!loader) loader = is_win64 ? "wine" : "wine64";
1740 /***********************************************************************
1741 * terminate_main_thread
1743 * On some versions of Mac OS X, the execve system call fails with
1744 * ENOTSUP if the process has multiple threads. Wine is always multi-
1745 * threaded on Mac OS X because it specifically reserves the main thread
1746 * for use by the system frameworks (see apple_main_thread() in
1747 * libs/wine/loader.c). So, when we need to exec without first forking,
1748 * we need to terminate the main thread first. We do this by installing
1749 * a custom run loop source onto the main run loop and signaling it.
1750 * The source's "perform" callback is pthread_exit and it will be
1751 * executed on the main thread, terminating it.
1753 * Returns TRUE if there's still hope the main thread has terminated or
1754 * will soon. Return FALSE if we've given up.
1756 static BOOL terminate_main_thread(void)
1762 CFRunLoopSourceContext source_context = { 0 };
1763 CFRunLoopSourceRef source;
1765 source_context.perform = pthread_exit;
1766 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1769 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1770 CFRunLoopSourceSignal( source );
1771 CFRunLoopWakeUp( CFRunLoopGetMain() );
1772 CFRelease( source );
1780 usleep(delayms * 1000);
1787 /***********************************************************************
1790 * Create a new process. If hFile is a valid handle we have an exe
1791 * file, otherwise it is a Winelib app.
1793 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1794 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1795 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1796 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1797 const struct binary_info *binary_info, int exec_only )
1799 BOOL ret, success = FALSE;
1800 HANDLE process_info;
1802 char *winedebug = NULL;
1803 char *wineloader = NULL;
1804 const char *loader = NULL;
1806 startup_info_t *startup_info;
1807 DWORD startup_info_size;
1808 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1812 if (!is_win64 && !is_wow64 && (binary_info->flags & BINARY_FLAG_64BIT))
1814 ERR( "starting 64-bit process %s not supported in 32-bit wineprefix\n", debugstr_w(filename) );
1815 SetLastError( ERROR_BAD_EXE_FORMAT );
1819 RtlAcquirePebLock();
1821 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1822 &startup_info_size )))
1824 RtlReleasePebLock();
1827 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
1831 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1832 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1834 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1835 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1836 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1838 env_end += strlenW(env_end) + 1;
1842 /* create the socket for the new process */
1844 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1846 RtlReleasePebLock();
1847 HeapFree( GetProcessHeap(), 0, winedebug );
1848 HeapFree( GetProcessHeap(), 0, startup_info );
1849 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1852 wine_server_send_fd( socketfd[1] );
1853 close( socketfd[1] );
1855 /* create the process on the server side */
1857 SERVER_START_REQ( new_process )
1859 req->inherit_all = inherit;
1860 req->create_flags = flags;
1861 req->socket_fd = socketfd[1];
1862 req->exe_file = wine_server_obj_handle( hFile );
1863 req->process_access = PROCESS_ALL_ACCESS;
1864 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1865 req->thread_access = THREAD_ALL_ACCESS;
1866 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1867 req->info_size = startup_info_size;
1869 wine_server_add_data( req, startup_info, startup_info_size );
1870 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
1871 if ((ret = !wine_server_call_err( req )))
1873 info->dwProcessId = (DWORD)reply->pid;
1874 info->dwThreadId = (DWORD)reply->tid;
1875 info->hProcess = wine_server_ptr_handle( reply->phandle );
1876 info->hThread = wine_server_ptr_handle( reply->thandle );
1878 process_info = wine_server_ptr_handle( reply->info );
1882 RtlReleasePebLock();
1885 close( socketfd[0] );
1886 HeapFree( GetProcessHeap(), 0, startup_info );
1887 HeapFree( GetProcessHeap(), 0, winedebug );
1891 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1893 if (startup_info->hstdin)
1894 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
1895 FILE_READ_DATA, &stdin_fd, NULL );
1896 if (startup_info->hstdout)
1897 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
1898 FILE_WRITE_DATA, &stdout_fd, NULL );
1900 HeapFree( GetProcessHeap(), 0, startup_info );
1902 /* create the child process */
1903 argv = build_argv( cmd_line, 1 );
1905 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1906 loader = get_alternate_loader( &wineloader );
1908 if (exec_only || !(pid = fork())) /* child */
1910 char preloader_reserve[64], socket_env[64];
1912 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1914 if (!(pid = fork()))
1916 int fd = open( "/dev/null", O_RDWR );
1918 /* close stdin and stdout */
1926 else if (pid != -1) _exit(0); /* parent */
1930 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1931 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1934 if (stdin_fd != -1) close( stdin_fd );
1935 if (stdout_fd != -1) close( stdout_fd );
1937 /* Reset signals that we previously set to SIG_IGN */
1938 signal( SIGPIPE, SIG_DFL );
1939 signal( SIGCHLD, SIG_DFL );
1941 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1942 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1943 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1945 putenv( preloader_reserve );
1946 putenv( socket_env );
1947 if (winedebug) putenv( winedebug );
1948 if (wineloader) putenv( wineloader );
1949 if (unixdir) chdir(unixdir);
1955 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1958 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1966 /* this is the parent */
1968 if (stdin_fd != -1) close( stdin_fd );
1969 if (stdout_fd != -1) close( stdout_fd );
1970 close( socketfd[0] );
1971 HeapFree( GetProcessHeap(), 0, argv );
1972 HeapFree( GetProcessHeap(), 0, winedebug );
1973 HeapFree( GetProcessHeap(), 0, wineloader );
1980 /* wait for the new process info to be ready */
1982 WaitForSingleObject( process_info, INFINITE );
1983 SERVER_START_REQ( get_new_process_info )
1985 req->info = wine_server_obj_handle( process_info );
1986 wine_server_call( req );
1987 success = reply->success;
1988 err = reply->exit_code;
1994 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1997 CloseHandle( process_info );
2001 CloseHandle( process_info );
2002 CloseHandle( info->hProcess );
2003 CloseHandle( info->hThread );
2004 info->hProcess = info->hThread = 0;
2005 info->dwProcessId = info->dwThreadId = 0;
2010 /***********************************************************************
2011 * create_vdm_process
2013 * Create a new VDM process for a 16-bit or DOS application.
2015 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2016 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2017 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2018 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2019 const struct binary_info *binary_info, int exec_only )
2021 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2024 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
2025 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
2029 SetLastError( ERROR_OUTOFMEMORY );
2032 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
2033 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2034 flags, startup, info, unixdir, binary_info, exec_only );
2035 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2040 /***********************************************************************
2041 * create_cmd_process
2043 * Create a new cmd shell process for a .BAT file.
2045 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2046 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2047 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2048 LPPROCESS_INFORMATION info )
2051 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2052 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2053 WCHAR comspec[MAX_PATH];
2057 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2059 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2060 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2063 strcpyW( newcmdline, comspec );
2064 strcatW( newcmdline, slashcW );
2065 strcatW( newcmdline, cmd_line );
2066 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2067 flags, env, cur_dir, startup, info );
2068 HeapFree( GetProcessHeap(), 0, newcmdline );
2073 /*************************************************************************
2076 * Helper for CreateProcess: retrieve the file name to load from the
2077 * app name and command line. Store the file name in buffer, and
2078 * return a possibly modified command line.
2079 * Also returns a handle to the opened file if it's a Windows binary.
2081 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2082 int buflen, HANDLE *handle, struct binary_info *binary_info )
2084 static const WCHAR quotesW[] = {'"','%','s','"',0};
2086 WCHAR *name, *pos, *first_space, *ret = NULL;
2089 /* if we have an app name, everything is easy */
2093 /* use the unmodified app name as file name */
2094 lstrcpynW( buffer, appname, buflen );
2095 *handle = open_exe_file( buffer, binary_info );
2096 if (!(ret = cmdline) || !cmdline[0])
2098 /* no command-line, create one */
2099 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2100 sprintfW( ret, quotesW, appname );
2105 /* first check for a quoted file name */
2107 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2109 int len = p - cmdline - 1;
2110 /* extract the quoted portion as file name */
2111 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2112 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2115 if (!find_exe_file( name, buffer, buflen, handle, binary_info ))
2117 if (!get_builtin_path( name, exeW, buffer, buflen, binary_info )) goto done;
2120 ret = cmdline; /* no change necessary */
2124 /* now try the command-line word by word */
2126 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2134 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2136 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2141 if (!first_space) first_space = pos;
2142 if (!(*pos++ = *p++)) break;
2147 if (first_space) *first_space = 0; /* try only the first word as a builtin */
2148 if (get_builtin_path( name, exeW, buffer, buflen, binary_info ))
2153 else SetLastError( ERROR_FILE_NOT_FOUND );
2155 else if (first_space) /* build a new command-line with quotes */
2157 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2159 sprintfW( ret, quotesW, name );
2164 HeapFree( GetProcessHeap(), 0, name );
2169 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2170 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2171 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2172 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2173 LPPROCESS_INFORMATION info )
2177 char *unixdir = NULL;
2178 WCHAR name[MAX_PATH];
2179 WCHAR *tidy_cmdline, *p, *envW = env;
2180 struct binary_info binary_info;
2182 /* Process the AppName and/or CmdLine to get module name and path */
2184 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2186 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2187 &hFile, &binary_info )))
2189 if (hFile == INVALID_HANDLE_VALUE) goto done;
2191 /* Warn if unsupported features are used */
2193 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2194 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2195 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2196 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2197 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2201 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2203 SetLastError(ERROR_DIRECTORY);
2209 WCHAR buf[MAX_PATH];
2210 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2213 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2218 while (*p) p += strlen(p) + 1;
2219 p++; /* final null */
2220 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
2221 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2222 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
2223 flags |= CREATE_UNICODE_ENVIRONMENT;
2226 info->hThread = info->hProcess = 0;
2227 info->dwProcessId = info->dwThreadId = 0;
2229 if (binary_info.flags & BINARY_FLAG_DLL)
2231 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2232 SetLastError( ERROR_BAD_EXE_FORMAT );
2234 else switch (binary_info.type)
2237 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2238 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2239 binary_info.res_start, binary_info.res_end );
2240 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2241 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2246 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2247 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2248 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2250 case BINARY_UNIX_LIB:
2251 TRACE( "starting %s as %d-bit Winelib app\n",
2252 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2253 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2254 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2256 case BINARY_UNKNOWN:
2257 /* check for .com or .bat extension */
2258 if ((p = strrchrW( name, '.' )))
2260 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2262 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2263 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2264 inherit, flags, startup_info, info, unixdir,
2265 &binary_info, FALSE );
2268 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2270 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2271 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2272 inherit, flags, startup_info, info );
2277 case BINARY_UNIX_EXE:
2279 /* unknown file, try as unix executable */
2282 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2284 if ((unix_name = wine_get_unix_file_name( name )))
2286 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2287 HeapFree( GetProcessHeap(), 0, unix_name );
2292 if (hFile) CloseHandle( hFile );
2295 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2296 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2297 HeapFree( GetProcessHeap(), 0, unixdir );
2299 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2304 /**********************************************************************
2305 * CreateProcessA (KERNEL32.@)
2307 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2308 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2309 DWORD flags, LPVOID env, LPCSTR cur_dir,
2310 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2313 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2314 UNICODE_STRING desktopW, titleW;
2317 desktopW.Buffer = NULL;
2318 titleW.Buffer = NULL;
2319 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2320 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2321 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2323 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2324 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2326 memcpy( &infoW, startup_info, sizeof(infoW) );
2327 infoW.lpDesktop = desktopW.Buffer;
2328 infoW.lpTitle = titleW.Buffer;
2330 if (startup_info->lpReserved)
2331 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2332 debugstr_a(startup_info->lpReserved));
2334 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2335 inherit, flags, env, cur_dirW, &infoW, info );
2337 HeapFree( GetProcessHeap(), 0, app_nameW );
2338 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2339 HeapFree( GetProcessHeap(), 0, cur_dirW );
2340 RtlFreeUnicodeString( &desktopW );
2341 RtlFreeUnicodeString( &titleW );
2346 /**********************************************************************
2347 * CreateProcessW (KERNEL32.@)
2349 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2350 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2351 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2352 LPPROCESS_INFORMATION info )
2354 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2355 inherit, flags, env, cur_dir, startup_info, info);
2359 /**********************************************************************
2362 static void exec_process( LPCWSTR name )
2366 STARTUPINFOW startup_info;
2367 PROCESS_INFORMATION info;
2368 struct binary_info binary_info;
2370 hFile = open_exe_file( name, &binary_info );
2371 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2373 memset( &startup_info, 0, sizeof(startup_info) );
2374 startup_info.cb = sizeof(startup_info);
2376 /* Determine executable type */
2378 if (binary_info.flags & BINARY_FLAG_DLL) return;
2379 switch (binary_info.type)
2382 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2383 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2384 binary_info.res_start, binary_info.res_end );
2385 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2386 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2388 case BINARY_UNIX_LIB:
2389 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2390 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2391 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2393 case BINARY_UNKNOWN:
2394 /* check for .com or .pif extension */
2395 if (!(p = strrchrW( name, '.' ))) break;
2396 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2401 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2402 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2403 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2408 CloseHandle( hFile );
2412 /***********************************************************************
2415 * Wrapper to call WaitForInputIdle USER function
2417 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2419 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2421 HMODULE mod = GetModuleHandleA( "user32.dll" );
2424 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2425 if (ptr) return ptr( process, timeout );
2431 /***********************************************************************
2432 * WinExec (KERNEL32.@)
2434 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2436 PROCESS_INFORMATION info;
2437 STARTUPINFOA startup;
2441 memset( &startup, 0, sizeof(startup) );
2442 startup.cb = sizeof(startup);
2443 startup.dwFlags = STARTF_USESHOWWINDOW;
2444 startup.wShowWindow = nCmdShow;
2446 /* cmdline needs to be writable for CreateProcess */
2447 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2448 strcpy( cmdline, lpCmdLine );
2450 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2451 0, NULL, NULL, &startup, &info ))
2453 /* Give 30 seconds to the app to come up */
2454 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2455 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2457 /* Close off the handles */
2458 CloseHandle( info.hThread );
2459 CloseHandle( info.hProcess );
2461 else if ((ret = GetLastError()) >= 32)
2463 FIXME("Strange error set by CreateProcess: %d\n", ret );
2466 HeapFree( GetProcessHeap(), 0, cmdline );
2471 /**********************************************************************
2472 * LoadModule (KERNEL32.@)
2474 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2476 LOADPARMS32 *params = paramBlock;
2477 PROCESS_INFORMATION info;
2478 STARTUPINFOA startup;
2481 char filename[MAX_PATH];
2484 if (!name) return ERROR_FILE_NOT_FOUND;
2486 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2487 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2488 return GetLastError();
2490 len = (BYTE)params->lpCmdLine[0];
2491 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2492 return ERROR_NOT_ENOUGH_MEMORY;
2494 strcpy( cmdline, filename );
2495 p = cmdline + strlen(cmdline);
2497 memcpy( p, params->lpCmdLine + 1, len );
2500 memset( &startup, 0, sizeof(startup) );
2501 startup.cb = sizeof(startup);
2502 if (params->lpCmdShow)
2504 startup.dwFlags = STARTF_USESHOWWINDOW;
2505 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2508 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2509 params->lpEnvAddress, NULL, &startup, &info ))
2511 /* Give 30 seconds to the app to come up */
2512 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2513 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2515 /* Close off the handles */
2516 CloseHandle( info.hThread );
2517 CloseHandle( info.hProcess );
2519 else if ((ret = GetLastError()) >= 32)
2521 FIXME("Strange error set by CreateProcess: %u\n", ret );
2525 HeapFree( GetProcessHeap(), 0, cmdline );
2530 /******************************************************************************
2531 * TerminateProcess (KERNEL32.@)
2533 * Terminates a process.
2536 * handle [I] Process to terminate.
2537 * exit_code [I] Exit code.
2541 * Failure: FALSE, check GetLastError().
2543 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2545 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2546 if (status) SetLastError( RtlNtStatusToDosError(status) );
2550 /***********************************************************************
2551 * ExitProcess (KERNEL32.@)
2553 * Exits the current process.
2556 * status [I] Status code to exit with.
2562 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2564 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2565 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2566 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2568 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2572 void WINAPI process_ExitProcess( DWORD status )
2574 LdrShutdownProcess();
2575 NtTerminateProcess(GetCurrentProcess(), status);
2581 void WINAPI ExitProcess( DWORD status )
2583 LdrShutdownProcess();
2584 NtTerminateProcess(GetCurrentProcess(), status);
2590 /***********************************************************************
2591 * GetExitCodeProcess [KERNEL32.@]
2593 * Gets termination status of specified process.
2596 * hProcess [in] Handle to the process.
2597 * lpExitCode [out] Address to receive termination status.
2603 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2606 PROCESS_BASIC_INFORMATION pbi;
2608 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2610 if (status == STATUS_SUCCESS)
2612 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2615 SetLastError( RtlNtStatusToDosError(status) );
2620 /***********************************************************************
2621 * SetErrorMode (KERNEL32.@)
2623 UINT WINAPI SetErrorMode( UINT mode )
2627 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2628 &old, sizeof(old), NULL );
2629 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2630 &mode, sizeof(mode) );
2634 /***********************************************************************
2635 * GetErrorMode (KERNEL32.@)
2637 UINT WINAPI GetErrorMode( void )
2641 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2642 &mode, sizeof(mode), NULL );
2646 /**********************************************************************
2647 * TlsAlloc [KERNEL32.@]
2649 * Allocates a thread local storage index.
2652 * Success: TLS index.
2653 * Failure: 0xFFFFFFFF
2655 DWORD WINAPI TlsAlloc( void )
2658 PEB * const peb = NtCurrentTeb()->Peb;
2660 RtlAcquirePebLock();
2661 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2662 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2665 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2668 if (!NtCurrentTeb()->TlsExpansionSlots &&
2669 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2670 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2672 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2674 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2678 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2679 index += TLS_MINIMUM_AVAILABLE;
2682 else SetLastError( ERROR_NO_MORE_ITEMS );
2684 RtlReleasePebLock();
2689 /**********************************************************************
2690 * TlsFree [KERNEL32.@]
2692 * Releases a thread local storage index, making it available for reuse.
2695 * index [in] TLS index to free.
2701 BOOL WINAPI TlsFree( DWORD index )
2705 RtlAcquirePebLock();
2706 if (index >= TLS_MINIMUM_AVAILABLE)
2708 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2709 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2713 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2714 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2716 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2717 else SetLastError( ERROR_INVALID_PARAMETER );
2718 RtlReleasePebLock();
2723 /**********************************************************************
2724 * TlsGetValue [KERNEL32.@]
2726 * Gets value in a thread's TLS slot.
2729 * index [in] TLS index to retrieve value for.
2732 * Success: Value stored in calling thread's TLS slot for index.
2733 * Failure: 0 and GetLastError() returns NO_ERROR.
2735 LPVOID WINAPI TlsGetValue( DWORD index )
2739 if (index < TLS_MINIMUM_AVAILABLE)
2741 ret = NtCurrentTeb()->TlsSlots[index];
2745 index -= TLS_MINIMUM_AVAILABLE;
2746 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2748 SetLastError( ERROR_INVALID_PARAMETER );
2751 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2752 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2754 SetLastError( ERROR_SUCCESS );
2759 /**********************************************************************
2760 * TlsSetValue [KERNEL32.@]
2762 * Stores a value in the thread's TLS slot.
2765 * index [in] TLS index to set value for.
2766 * value [in] Value to be stored.
2772 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2774 if (index < TLS_MINIMUM_AVAILABLE)
2776 NtCurrentTeb()->TlsSlots[index] = value;
2780 index -= TLS_MINIMUM_AVAILABLE;
2781 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2783 SetLastError( ERROR_INVALID_PARAMETER );
2786 if (!NtCurrentTeb()->TlsExpansionSlots &&
2787 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2788 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2790 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2793 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2799 /***********************************************************************
2800 * GetProcessFlags (KERNEL32.@)
2802 DWORD WINAPI GetProcessFlags( DWORD processid )
2804 IMAGE_NT_HEADERS *nt;
2807 if (processid && processid != GetCurrentProcessId()) return 0;
2809 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2811 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2812 flags |= PDB32_CONSOLE_PROC;
2814 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2815 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2820 /*********************************************************************
2821 * OpenProcess (KERNEL32.@)
2823 * Opens a handle to a process.
2826 * access [I] Desired access rights assigned to the returned handle.
2827 * inherit [I] Determines whether or not child processes will inherit the handle.
2828 * id [I] Process identifier of the process to get a handle to.
2831 * Success: Valid handle to the specified process.
2832 * Failure: NULL, check GetLastError().
2834 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2838 OBJECT_ATTRIBUTES attr;
2841 cid.UniqueProcess = ULongToHandle(id);
2842 cid.UniqueThread = 0; /* FIXME ? */
2844 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2845 attr.RootDirectory = NULL;
2846 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2847 attr.SecurityDescriptor = NULL;
2848 attr.SecurityQualityOfService = NULL;
2849 attr.ObjectName = NULL;
2851 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2853 status = NtOpenProcess(&handle, access, &attr, &cid);
2854 if (status != STATUS_SUCCESS)
2856 SetLastError( RtlNtStatusToDosError(status) );
2863 /*********************************************************************
2864 * GetProcessId (KERNEL32.@)
2866 * Gets the a unique identifier of a process.
2869 * hProcess [I] Handle to the process.
2873 * Failure: FALSE, check GetLastError().
2877 * The identifier is unique only on the machine and only until the process
2878 * exits (including system shutdown).
2880 DWORD WINAPI GetProcessId( HANDLE hProcess )
2883 PROCESS_BASIC_INFORMATION pbi;
2885 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2887 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2888 SetLastError( RtlNtStatusToDosError(status) );
2893 /*********************************************************************
2894 * CloseHandle (KERNEL32.@)
2899 * handle [I] Handle to close.
2903 * Failure: FALSE, check GetLastError().
2905 BOOL WINAPI CloseHandle( HANDLE handle )
2909 /* stdio handles need special treatment */
2910 if (handle == (HANDLE)STD_INPUT_HANDLE)
2911 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
2912 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
2913 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
2914 else if (handle == (HANDLE)STD_ERROR_HANDLE)
2915 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
2917 if (is_console_handle(handle))
2918 return CloseConsoleHandle(handle);
2920 status = NtClose( handle );
2921 if (status) SetLastError( RtlNtStatusToDosError(status) );
2926 /*********************************************************************
2927 * GetHandleInformation (KERNEL32.@)
2929 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2931 OBJECT_DATA_INFORMATION info;
2932 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2934 if (status) SetLastError( RtlNtStatusToDosError(status) );
2938 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2939 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2945 /*********************************************************************
2946 * SetHandleInformation (KERNEL32.@)
2948 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2950 OBJECT_DATA_INFORMATION info;
2953 /* if not setting both fields, retrieve current value first */
2954 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2955 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2957 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2959 SetLastError( RtlNtStatusToDosError(status) );
2963 if (mask & HANDLE_FLAG_INHERIT)
2964 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2965 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2966 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2968 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2969 if (status) SetLastError( RtlNtStatusToDosError(status) );
2974 /*********************************************************************
2975 * DuplicateHandle (KERNEL32.@)
2977 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2978 HANDLE dest_process, HANDLE *dest,
2979 DWORD access, BOOL inherit, DWORD options )
2983 if (is_console_handle(source))
2985 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2986 if (source_process != dest_process ||
2987 source_process != GetCurrentProcess())
2989 SetLastError(ERROR_INVALID_PARAMETER);
2992 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2993 return (*dest != INVALID_HANDLE_VALUE);
2995 status = NtDuplicateObject( source_process, source, dest_process, dest,
2996 access, inherit ? OBJ_INHERIT : 0, options );
2997 if (status) SetLastError( RtlNtStatusToDosError(status) );
3002 /***********************************************************************
3003 * ConvertToGlobalHandle (KERNEL32.@)
3005 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3007 HANDLE ret = INVALID_HANDLE_VALUE;
3008 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3009 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3014 /***********************************************************************
3015 * SetHandleContext (KERNEL32.@)
3017 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3019 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3020 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3021 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3026 /***********************************************************************
3027 * GetHandleContext (KERNEL32.@)
3029 DWORD WINAPI GetHandleContext(HANDLE hnd)
3031 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3032 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3033 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3038 /***********************************************************************
3039 * CreateSocketHandle (KERNEL32.@)
3041 HANDLE WINAPI CreateSocketHandle(void)
3043 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3044 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3045 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3046 return INVALID_HANDLE_VALUE;
3050 /***********************************************************************
3051 * SetPriorityClass (KERNEL32.@)
3053 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3056 PROCESS_PRIORITY_CLASS ppc;
3058 ppc.Foreground = FALSE;
3059 switch (priorityclass)
3061 case IDLE_PRIORITY_CLASS:
3062 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3063 case BELOW_NORMAL_PRIORITY_CLASS:
3064 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3065 case NORMAL_PRIORITY_CLASS:
3066 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3067 case ABOVE_NORMAL_PRIORITY_CLASS:
3068 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3069 case HIGH_PRIORITY_CLASS:
3070 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3071 case REALTIME_PRIORITY_CLASS:
3072 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3074 SetLastError(ERROR_INVALID_PARAMETER);
3078 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3081 if (status != STATUS_SUCCESS)
3083 SetLastError( RtlNtStatusToDosError(status) );
3090 /***********************************************************************
3091 * GetPriorityClass (KERNEL32.@)
3093 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3096 PROCESS_BASIC_INFORMATION pbi;
3098 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3100 if (status != STATUS_SUCCESS)
3102 SetLastError( RtlNtStatusToDosError(status) );
3105 switch (pbi.BasePriority)
3107 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3108 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3109 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3110 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3111 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3112 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3114 SetLastError( ERROR_INVALID_PARAMETER );
3119 /***********************************************************************
3120 * SetProcessAffinityMask (KERNEL32.@)
3122 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3126 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3127 &affmask, sizeof(DWORD_PTR));
3130 SetLastError( RtlNtStatusToDosError(status) );
3137 /**********************************************************************
3138 * GetProcessAffinityMask (KERNEL32.@)
3140 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3142 NTSTATUS status = STATUS_SUCCESS;
3144 if (system_mask) *system_mask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
3147 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3148 process_mask, sizeof(*process_mask), NULL )))
3149 SetLastError( RtlNtStatusToDosError(status) );
3155 /***********************************************************************
3156 * GetProcessVersion (KERNEL32.@)
3158 DWORD WINAPI GetProcessVersion( DWORD pid )
3162 PROCESS_BASIC_INFORMATION pbi;
3165 IMAGE_DOS_HEADER dos;
3166 IMAGE_NT_HEADERS nt;
3169 if (!pid || pid == GetCurrentProcessId())
3171 IMAGE_NT_HEADERS *nt;
3173 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3174 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
3175 nt->OptionalHeader.MinorSubsystemVersion);
3179 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3180 if (!process) return 0;
3182 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3183 if (status) goto err;
3185 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3186 if (status || count != sizeof(peb)) goto err;
3188 memset(&dos, 0, sizeof(dos));
3189 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3190 if (status || count != sizeof(dos)) goto err;
3191 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3193 memset(&nt, 0, sizeof(nt));
3194 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3195 if (status || count != sizeof(nt)) goto err;
3196 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3198 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3201 CloseHandle(process);
3203 if (status != STATUS_SUCCESS)
3204 SetLastError(RtlNtStatusToDosError(status));
3210 /***********************************************************************
3211 * SetProcessWorkingSetSize [KERNEL32.@]
3212 * Sets the min/max working set sizes for a specified process.
3215 * hProcess [I] Handle to the process of interest
3216 * minset [I] Specifies minimum working set size
3217 * maxset [I] Specifies maximum working set size
3223 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3226 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3227 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3228 /* Trim the working set to zero */
3229 /* Swap the process out of physical RAM */
3234 /***********************************************************************
3235 * K32EmptyWorkingSet (KERNEL32.@)
3237 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3239 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3242 /***********************************************************************
3243 * GetProcessWorkingSetSize (KERNEL32.@)
3245 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3248 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3249 /* 32 MB working set size */
3250 if (minset) *minset = 32*1024*1024;
3251 if (maxset) *maxset = 32*1024*1024;
3256 /***********************************************************************
3257 * SetProcessShutdownParameters (KERNEL32.@)
3259 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3261 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3262 shutdown_flags = flags;
3263 shutdown_priority = level;
3268 /***********************************************************************
3269 * GetProcessShutdownParameters (KERNEL32.@)
3272 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3274 *lpdwLevel = shutdown_priority;
3275 *lpdwFlags = shutdown_flags;
3280 /***********************************************************************
3281 * GetProcessPriorityBoost (KERNEL32.@)
3283 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3285 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3287 /* Report that no boost is present.. */
3288 *pDisablePriorityBoost = FALSE;
3293 /***********************************************************************
3294 * SetProcessPriorityBoost (KERNEL32.@)
3296 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3298 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3299 /* Say we can do it. I doubt the program will notice that we don't. */
3304 /***********************************************************************
3305 * ReadProcessMemory (KERNEL32.@)
3307 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3308 SIZE_T *bytes_read )
3310 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3311 if (status) SetLastError( RtlNtStatusToDosError(status) );
3316 /***********************************************************************
3317 * WriteProcessMemory (KERNEL32.@)
3319 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3320 SIZE_T *bytes_written )
3322 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3323 if (status) SetLastError( RtlNtStatusToDosError(status) );
3328 /****************************************************************************
3329 * FlushInstructionCache (KERNEL32.@)
3331 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3334 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3335 if (status) SetLastError( RtlNtStatusToDosError(status) );
3340 /******************************************************************
3341 * GetProcessIoCounters (KERNEL32.@)
3343 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3347 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3348 ioc, sizeof(*ioc), NULL);
3349 if (status) SetLastError( RtlNtStatusToDosError(status) );
3353 /******************************************************************
3354 * GetProcessHandleCount (KERNEL32.@)
3356 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3360 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3361 cnt, sizeof(*cnt), NULL);
3362 if (status) SetLastError( RtlNtStatusToDosError(status) );
3366 /******************************************************************
3367 * QueryFullProcessImageNameA (KERNEL32.@)
3369 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3372 DWORD pdwSizeW = *pdwSize;
3373 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3375 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3378 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3379 lpExeName, *pdwSize, NULL, NULL));
3381 *pdwSize = strlen(lpExeName);
3383 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3387 /******************************************************************
3388 * QueryFullProcessImageNameW (KERNEL32.@)
3390 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3392 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3393 UNICODE_STRING *dynamic_buffer = NULL;
3394 UNICODE_STRING nt_path;
3395 UNICODE_STRING *result = NULL;
3399 RtlInitUnicodeStringEx(&nt_path, NULL);
3400 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3401 * as this is on Wine. */
3402 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3403 sizeof(buffer) - sizeof(WCHAR), &needed);
3404 if (status == STATUS_INFO_LENGTH_MISMATCH)
3406 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3407 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3408 result = dynamic_buffer;
3411 result = (PUNICODE_STRING)buffer;
3413 if (status) goto cleanup;
3415 if (dwFlags & PROCESS_NAME_NATIVE)
3417 result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3418 if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3420 status = STATUS_OBJECT_PATH_NOT_FOUND;
3426 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3428 status = STATUS_BUFFER_TOO_SMALL;
3432 *pdwSize = result->Length/sizeof(WCHAR);
3433 memcpy( lpExeName, result->Buffer, result->Length );
3434 lpExeName[*pdwSize] = 0;
3437 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3438 RtlFreeUnicodeString(&nt_path);
3439 if (status) SetLastError( RtlNtStatusToDosError(status) );
3443 /***********************************************************************
3444 * K32GetProcessImageFileNameA (KERNEL32.@)
3446 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3448 FIXME("(%p, %p, %d) stub\n", process, file, size );
3452 /***********************************************************************
3453 * K32GetProcessImageFileNameW (KERNEL32.@)
3455 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3457 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3460 /***********************************************************************
3461 * ProcessIdToSessionId (KERNEL32.@)
3462 * This function is available on Terminal Server 4SP4 and Windows 2000
3464 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3466 /* According to MSDN, if the calling process is not in a terminal
3467 * services environment, then the sessionid returned is zero.
3474 /***********************************************************************
3475 * RegisterServiceProcess (KERNEL32.@)
3477 * A service process calls this function to ensure that it continues to run
3478 * even after a user logged off.
3480 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3482 /* I don't think that Wine needs to do anything in this function */
3483 return 1; /* success */
3487 /**********************************************************************
3488 * IsWow64Process (KERNEL32.@)
3490 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3495 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3497 if (status != STATUS_SUCCESS)
3499 SetLastError( RtlNtStatusToDosError( status ) );
3502 *Wow64Process = (pbi != 0);
3507 /***********************************************************************
3508 * GetCurrentProcess (KERNEL32.@)
3510 * Get a handle to the current process.
3516 * A handle representing the current process.
3518 #undef GetCurrentProcess
3519 HANDLE WINAPI GetCurrentProcess(void)
3521 return (HANDLE)~(ULONG_PTR)0;
3524 /***********************************************************************
3525 * GetLogicalProcessorInformation (KERNEL32.@)
3527 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3529 FIXME("(%p,%p): stub\n", buffer, pBufLen);
3530 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3534 /***********************************************************************
3535 * GetLogicalProcessorInformationEx (KERNEL32.@)
3537 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer, PDWORD pBufLen)
3539 FIXME("(%u,%p,%p): stub\n", relationship, buffer, pBufLen);
3540 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3544 /***********************************************************************
3545 * CmdBatNotification (KERNEL32.@)
3547 * Notifies the system that a batch file has started or finished.
3550 * bBatchRunning [I] TRUE if a batch file has started or
3551 * FALSE if a batch file has finished executing.
3556 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3558 FIXME("%d\n", bBatchRunning);
3563 /***********************************************************************
3564 * RegisterApplicationRestart (KERNEL32.@)
3566 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3568 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3573 /**********************************************************************
3574 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3576 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3582 /**********************************************************************
3583 * GetSystemDEPPolicy (KERNEL32.@)
3585 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3590 /**********************************************************************
3591 * SetProcessDEPPolicy (KERNEL32.@)
3593 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3595 FIXME("(%d): stub\n", newDEP);
3596 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);