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"
50 #include "wine/library.h"
51 #include "wine/server.h"
52 #include "wine/unicode.h"
53 #include "wine/debug.h"
55 WINE_DEFAULT_DEBUG_CHANNEL(process);
56 WINE_DECLARE_DEBUG_CHANNEL(file);
57 WINE_DECLARE_DEBUG_CHANNEL(relay);
60 #include <CoreFoundation/CoreFoundation.h>
63 extern char **__wine_get_main_environment(void);
65 extern char **__wine_main_environ;
66 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
77 static DWORD shutdown_flags = 0;
78 static DWORD shutdown_priority = 0x280;
80 static const int is_win64 = (sizeof(void *) > sizeof(int));
82 HMODULE kernel32_handle = 0;
84 const WCHAR *DIR_Windows = NULL;
85 const WCHAR *DIR_System = NULL;
86 const WCHAR *DIR_SysWow64 = NULL;
89 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
90 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
91 #define PDB32_DOS_PROC 0x0010 /* Dos process */
92 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
93 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
94 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
96 static const WCHAR exeW[] = {'.','e','x','e',0};
97 static const WCHAR comW[] = {'.','c','o','m',0};
98 static const WCHAR batW[] = {'.','b','a','t',0};
99 static const WCHAR cmdW[] = {'.','c','m','d',0};
100 static const WCHAR pifW[] = {'.','p','i','f',0};
101 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
103 static void exec_process( LPCWSTR name );
105 extern void SHELL_LoadRegistry(void);
108 /***********************************************************************
111 static inline int contains_path( LPCWSTR name )
113 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
117 /***********************************************************************
120 * Check if an environment variable needs to be handled specially when
121 * passed through the Unix environment (i.e. prefixed with "WINE").
123 static inline int is_special_env_var( const char *var )
125 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
126 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
127 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
128 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
129 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
133 /***********************************************************************
136 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
138 unsigned int len = strlenW( prefix );
140 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
141 while (filename[len] == '\\') len++;
146 /***************************************************************************
149 * Get the path of a builtin module when the native file does not exist.
151 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
152 UINT size, struct binary_info *binary_info )
156 void *redir_disabled = 0;
157 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
159 /* builtin names cannot be empty or contain spaces */
160 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
162 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
163 Wow64RevertWow64FsRedirection( redir_disabled );
165 if (contains_path( libname ))
167 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
168 filename, &file_part ) > size * sizeof(WCHAR))
169 return FALSE; /* too long */
171 if ((len = is_path_prefix( DIR_System, filename )))
173 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
175 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
181 if (filename + len != file_part) return FALSE;
185 len = strlenW( DIR_System );
186 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
187 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
188 file_part = filename + len;
189 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
190 strcpyW( file_part, libname );
191 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
193 if (ext && !strchrW( file_part, '.' ))
195 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
196 return FALSE; /* too long */
197 strcatW( file_part, ext );
199 binary_info->type = BINARY_UNIX_LIB;
200 binary_info->flags = flags;
201 binary_info->res_start = NULL;
202 binary_info->res_end = NULL;
207 /***********************************************************************
210 * Open a specific exe file, taking load order into account.
211 * Returns the file handle or 0 for a builtin exe.
213 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
217 TRACE("looking for %s\n", debugstr_w(name) );
219 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
220 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
222 WCHAR buffer[MAX_PATH];
223 /* file doesn't exist, check for builtin */
224 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
227 else MODULE_get_binary_info( handle, binary_info );
233 /***********************************************************************
236 * Open an exe file, and return the full name and file handle.
237 * Returns FALSE if file could not be found.
238 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
239 * If file is a builtin exe, returns TRUE and sets handle to 0.
241 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
242 HANDLE *handle, struct binary_info *binary_info )
244 TRACE("looking for %s\n", debugstr_w(name) );
246 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ))
248 if (contains_path( name ) && get_builtin_path( name, exeW, buffer, buflen, binary_info ))
253 /* no builtin found, try native without extension in case it is a Unix app */
254 if (!SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
257 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
258 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
259 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
261 MODULE_get_binary_info( *handle, binary_info );
268 /***********************************************************************
269 * build_initial_environment
271 * Build the Win32 environment from the Unix environment
273 static BOOL build_initial_environment(void)
279 char **env = __wine_get_main_environment();
281 /* Compute the total size of the Unix environment */
282 for (e = env; *e; e++)
284 if (is_special_env_var( *e )) continue;
285 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
287 size *= sizeof(WCHAR);
289 /* Now allocate the environment */
291 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
292 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
295 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
296 endptr = p + size / sizeof(WCHAR);
298 /* And fill it with the Unix environment */
299 for (e = env; *e; e++)
303 /* skip Unix special variables and use the Wine variants instead */
304 if (!strncmp( str, "WINE", 4 ))
306 if (is_special_env_var( str + 4 )) str += 4;
307 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
309 else if (is_special_env_var( str )) continue; /* skip it */
311 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
319 /***********************************************************************
320 * set_registry_variables
322 * Set environment variables by enumerating the values of a key;
323 * helper for set_registry_environment().
324 * Note that Windows happily truncates the value if it's too big.
326 static void set_registry_variables( HANDLE hkey, ULONG type )
328 static const WCHAR pathW[] = {'P','A','T','H'};
329 static const WCHAR sep[] = {';',0};
330 UNICODE_STRING env_name, env_value;
334 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
337 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
340 tmp.MaximumLength = sizeof(tmpbuf);
342 for (index = 0; ; index++)
344 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
345 buffer, sizeof(buffer), &size );
346 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
348 if (info->Type != type)
350 env_name.Buffer = info->Name;
351 env_name.Length = env_name.MaximumLength = info->NameLength;
352 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
353 env_value.Length = info->DataLength;
354 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
355 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
356 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
357 if (!env_value.Length) continue;
358 if (info->Type == REG_EXPAND_SZ)
360 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
361 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
362 RtlCopyUnicodeString( &env_value, &tmp );
365 if (env_name.Length == sizeof(pathW) &&
366 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
367 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
369 RtlAppendUnicodeToString( &tmp, sep );
370 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
371 RtlCopyUnicodeString( &env_value, &tmp );
373 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
378 /***********************************************************************
379 * set_registry_environment
381 * Set the environment variables specified in the registry.
383 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
384 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
385 * on the order in which the variables are processed. But on Windows it
386 * does not really matter since they only use %SystemDrive% and
387 * %SystemRoot% which are predefined. But Wine defines these in the
388 * registry, so we need two passes.
390 static BOOL set_registry_environment( BOOL volatile_only )
392 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
393 'S','y','s','t','e','m','\\',
394 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
395 'C','o','n','t','r','o','l','\\',
396 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
397 'E','n','v','i','r','o','n','m','e','n','t',0};
398 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
399 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};
401 OBJECT_ATTRIBUTES attr;
402 UNICODE_STRING nameW;
406 attr.Length = sizeof(attr);
407 attr.RootDirectory = 0;
408 attr.ObjectName = &nameW;
410 attr.SecurityDescriptor = NULL;
411 attr.SecurityQualityOfService = NULL;
413 /* first the system environment variables */
414 RtlInitUnicodeString( &nameW, env_keyW );
415 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
417 set_registry_variables( hkey, REG_SZ );
418 set_registry_variables( hkey, REG_EXPAND_SZ );
423 /* then the ones for the current user */
424 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
425 RtlInitUnicodeString( &nameW, envW );
426 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
428 set_registry_variables( hkey, REG_SZ );
429 set_registry_variables( hkey, REG_EXPAND_SZ );
433 RtlInitUnicodeString( &nameW, volatile_envW );
434 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
436 set_registry_variables( hkey, REG_SZ );
437 set_registry_variables( hkey, REG_EXPAND_SZ );
441 NtClose( attr.RootDirectory );
446 /***********************************************************************
449 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
451 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
452 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
453 DWORD len, size = sizeof(buffer);
455 UNICODE_STRING nameW;
457 RtlInitUnicodeString( &nameW, name );
458 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
461 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
462 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
464 if (info->Type == REG_EXPAND_SZ)
466 UNICODE_STRING value, expanded;
468 value.MaximumLength = len * sizeof(WCHAR);
469 value.Buffer = (WCHAR *)info->Data;
470 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
471 value.Length = len * sizeof(WCHAR);
472 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
473 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
474 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
475 else RtlFreeUnicodeString( &expanded );
477 else if (info->Type == REG_SZ)
479 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
481 memcpy( ret, info->Data, len * sizeof(WCHAR) );
489 /***********************************************************************
490 * set_additional_environment
492 * Set some additional environment variables not specified in the registry.
494 static void set_additional_environment(void)
496 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
497 'S','o','f','t','w','a','r','e','\\',
498 'M','i','c','r','o','s','o','f','t','\\',
499 'W','i','n','d','o','w','s',' ','N','T','\\',
500 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
501 'P','r','o','f','i','l','e','L','i','s','t',0};
502 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
503 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
504 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
505 OBJECT_ATTRIBUTES attr;
506 UNICODE_STRING nameW;
507 WCHAR *profile_dir = NULL, *all_users_dir = NULL;
511 /* set the ALLUSERSPROFILE variables */
513 attr.Length = sizeof(attr);
514 attr.RootDirectory = 0;
515 attr.ObjectName = &nameW;
517 attr.SecurityDescriptor = NULL;
518 attr.SecurityQualityOfService = NULL;
519 RtlInitUnicodeString( &nameW, profile_keyW );
520 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
522 profile_dir = get_reg_value( hkey, profiles_valueW );
523 all_users_dir = get_reg_value( hkey, all_users_valueW );
527 if (profile_dir && all_users_dir)
531 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
532 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
533 strcpyW( value, profile_dir );
534 p = value + strlenW(value);
535 if (p > value && p[-1] != '\\') *p++ = '\\';
536 strcpyW( p, all_users_dir );
537 SetEnvironmentVariableW( allusersW, value );
538 HeapFree( GetProcessHeap(), 0, value );
541 HeapFree( GetProcessHeap(), 0, all_users_dir );
542 HeapFree( GetProcessHeap(), 0, profile_dir );
545 /***********************************************************************
546 * set_wow64_environment
548 * Set the environment variables that change across 32/64/Wow64.
550 static void set_wow64_environment(void)
552 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};
553 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};
554 static const WCHAR x86W[] = {'x','8','6',0};
555 static const WCHAR versionW[] = {'M','a','c','h','i','n','e','\\',
556 'S','o','f','t','w','a','r','e','\\',
557 'M','i','c','r','o','s','o','f','t','\\',
558 'W','i','n','d','o','w','s','\\',
559 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
560 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
561 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
562 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
563 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
564 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
565 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
566 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
567 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
569 OBJECT_ATTRIBUTES attr;
570 UNICODE_STRING nameW;
575 /* set the PROCESSOR_ARCHITECTURE variable */
577 if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
581 SetEnvironmentVariableW( archW, arch );
582 SetEnvironmentVariableW( arch6432W, NULL );
585 else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
589 SetEnvironmentVariableW( arch6432W, arch );
590 SetEnvironmentVariableW( archW, x86W );
594 attr.Length = sizeof(attr);
595 attr.RootDirectory = 0;
596 attr.ObjectName = &nameW;
598 attr.SecurityDescriptor = NULL;
599 attr.SecurityQualityOfService = NULL;
600 RtlInitUnicodeString( &nameW, versionW );
601 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
603 /* set the ProgramFiles variables */
605 if ((value = get_reg_value( hkey, progdirW )))
607 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
608 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
609 HeapFree( GetProcessHeap(), 0, value );
611 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
613 SetEnvironmentVariableW( progfilesW, value );
614 HeapFree( GetProcessHeap(), 0, value );
617 /* set the CommonProgramFiles variables */
619 if ((value = get_reg_value( hkey, commondirW )))
621 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
622 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
623 HeapFree( GetProcessHeap(), 0, value );
625 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
627 SetEnvironmentVariableW( commonfilesW, value );
628 HeapFree( GetProcessHeap(), 0, value );
634 /***********************************************************************
637 * Set the Wine library Unicode argv global variables.
639 static void set_library_wargv( char **argv )
647 for (argc = 0; argv[argc]; argc++)
648 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
650 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
651 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
652 p = (WCHAR *)(wargv + argc + 1);
653 for (argc = 0; argv[argc]; argc++)
655 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
662 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
664 for (argc = 0; wargv[argc]; argc++)
665 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
667 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
668 q = (char *)(argv + argc + 1);
669 for (argc = 0; wargv[argc]; argc++)
671 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
678 __wine_main_argc = argc;
679 __wine_main_argv = argv;
680 __wine_main_wargv = wargv;
684 /***********************************************************************
685 * update_library_argv0
687 * Update the argv[0] global variable with the binary we have found.
689 static void update_library_argv0( const WCHAR *argv0 )
691 DWORD len = strlenW( argv0 );
693 if (len > strlenW( __wine_main_wargv[0] ))
695 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
697 strcpyW( __wine_main_wargv[0], argv0 );
699 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
700 if (len > strlen( __wine_main_argv[0] ) + 1)
702 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
704 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
708 /***********************************************************************
711 * Build the command line of a process from the argv array.
713 * Note that it does NOT necessarily include the file name.
714 * Sometimes we don't even have any command line options at all.
716 * We must quote and escape characters so that the argv array can be rebuilt
717 * from the command line:
718 * - spaces and tabs must be quoted
720 * - quotes must be escaped
722 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
723 * resulting in an odd number of '\' followed by a '"'
726 * - '\'s that are not followed by a '"' can be left as is
730 static BOOL build_command_line( WCHAR **argv )
735 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
737 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
740 for (arg = argv; *arg; arg++)
742 int has_space,bcount;
748 if( !*a ) has_space=1;
753 if (*a==' ' || *a=='\t') {
755 } else if (*a=='"') {
756 /* doubling of '\' preceding a '"',
757 * plus escaping of said '"'
765 len+=(a-*arg)+1 /* for the separating space */;
767 len+=2; /* for the quotes */
770 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
773 p = rupp->CommandLine.Buffer;
774 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
775 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
776 for (arg = argv; *arg; arg++)
778 int has_space,has_quote;
781 /* Check for quotes and spaces in this argument */
782 has_space=has_quote=0;
784 if( !*a ) has_space=1;
786 if (*a==' ' || *a=='\t') {
790 } else if (*a=='"') {
798 /* Now transfer it to the command line */
815 /* Double all the '\\' preceding this '"', plus one */
816 for (i=0;i<=bcount;i++)
828 while ((*p=*x++)) p++;
834 if (p > rupp->CommandLine.Buffer)
835 p--; /* remove last space */
842 /***********************************************************************
843 * init_current_directory
845 * Initialize the current directory from the Unix cwd or the parent info.
847 static void init_current_directory( CURDIR *cur_dir )
849 UNICODE_STRING dir_str;
854 /* if we received a cur dir from the parent, try this first */
856 if (cur_dir->DosPath.Length)
858 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
861 /* now try to get it from the Unix cwd */
863 for (size = 256; ; size *= 2)
865 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
866 if (getcwd( cwd, size )) break;
867 HeapFree( GetProcessHeap(), 0, cwd );
868 if (errno == ERANGE) continue;
873 /* try to use PWD if it is valid, so that we don't resolve symlinks */
875 pwd = getenv( "PWD" );
878 struct stat st1, st2;
880 if (!pwd || stat( pwd, &st1 ) == -1 ||
881 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
887 ANSI_STRING unix_name;
888 UNICODE_STRING nt_name;
889 RtlInitAnsiString( &unix_name, pwd );
890 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
892 UNICODE_STRING dos_path;
893 /* skip the \??\ prefix, nt_name is 0 terminated */
894 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
895 RtlSetCurrentDirectory_U( &dos_path );
896 RtlFreeUnicodeString( &nt_name );
900 if (!cur_dir->DosPath.Length) /* still not initialized */
902 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
903 "starting in the Windows directory.\n", cwd ? cwd : "" );
904 RtlInitUnicodeString( &dir_str, DIR_Windows );
905 RtlSetCurrentDirectory_U( &dir_str );
907 HeapFree( GetProcessHeap(), 0, cwd );
910 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
911 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
915 /***********************************************************************
918 * Initialize the windows and system directories from the environment.
920 static void init_windows_dirs(void)
922 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
924 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
925 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
926 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
927 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
928 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
933 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
935 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
936 GetEnvironmentVariableW( windirW, buffer, len );
937 DIR_Windows = buffer;
939 else DIR_Windows = default_windirW;
941 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
943 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
944 GetEnvironmentVariableW( winsysdirW, buffer, len );
949 len = strlenW( DIR_Windows );
950 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
951 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
952 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
956 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
957 ERR( "directory %s could not be created, error %u\n",
958 debugstr_w(DIR_Windows), GetLastError() );
959 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
960 ERR( "directory %s could not be created, error %u\n",
961 debugstr_w(DIR_System), GetLastError() );
963 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
965 len = strlenW( DIR_Windows );
966 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
967 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
968 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
969 DIR_SysWow64 = buffer;
970 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
971 ERR( "directory %s could not be created, error %u\n",
972 debugstr_w(DIR_SysWow64), GetLastError() );
975 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
976 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
978 /* set the directories in ntdll too */
979 __wine_init_windows_dir( DIR_Windows, DIR_System );
983 /***********************************************************************
986 * Start the wineboot process if necessary. Return the handles to wait on.
988 static void start_wineboot( HANDLE handles[2] )
990 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
993 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
995 ERR( "failed to create wineboot event, expect trouble\n" );
998 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
1000 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1001 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1003 PROCESS_INFORMATION pi;
1005 WCHAR app[MAX_PATH];
1006 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1008 memset( &si, 0, sizeof(si) );
1010 si.dwFlags = STARTF_USESTDHANDLES;
1013 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1015 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1016 lstrcatW( app, wineboot );
1018 Wow64DisableWow64FsRedirection( &redir );
1019 strcpyW( cmdline, app );
1020 strcatW( cmdline, args );
1021 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1023 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1024 CloseHandle( pi.hThread );
1025 handles[1] = pi.hProcess;
1029 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1030 CloseHandle( handles[0] );
1033 Wow64RevertWow64FsRedirection( redir );
1039 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1040 __ASM_GLOBAL_FUNC( call_process_entry,
1042 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1043 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1044 "movl %esp,%ebp\n\t"
1045 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1046 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1048 "call *12(%ebp)\n\t"
1050 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1051 __ASM_CFI(".cfi_same_value %ebp\n\t")
1054 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1056 return entry( peb );
1060 /***********************************************************************
1063 * Startup routine of a new process. Runs on the new process stack.
1065 static DWORD WINAPI start_process( PEB *peb )
1067 IMAGE_NT_HEADERS *nt;
1068 LPTHREAD_START_ROUTINE entry;
1070 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1071 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1072 nt->OptionalHeader.AddressOfEntryPoint);
1074 if (!nt->OptionalHeader.AddressOfEntryPoint)
1076 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1077 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1081 if (TRACE_ON(relay))
1082 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1083 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1085 SetLastError( 0 ); /* clear error code */
1086 if (peb->BeingDebugged) DbgBreakPoint();
1087 return call_process_entry( peb, entry );
1091 /***********************************************************************
1094 * Change the process name in the ps output.
1096 static void set_process_name( int argc, char *argv[] )
1098 #ifdef HAVE_SETPROCTITLE
1099 setproctitle("-%s", argv[1]);
1104 char *p, *prctl_name = argv[1];
1105 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1108 # define PR_SET_NAME 15
1111 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1112 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1114 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1116 offset = argv[1] - argv[0];
1117 memmove( argv[1] - offset, argv[1], end - argv[1] );
1118 memset( end - offset, 0, offset );
1119 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1123 #endif /* HAVE_PRCTL */
1125 /* remove argv[0] */
1126 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1131 /***********************************************************************
1132 * __wine_kernel_init
1134 * Wine initialisation: load and start the main exe file.
1136 void CDECL __wine_kernel_init(void)
1138 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1139 static const WCHAR dotW[] = {'.',0};
1141 WCHAR *p, main_exe_name[MAX_PATH+1];
1142 PEB *peb = NtCurrentTeb()->Peb;
1143 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1144 HANDLE boot_events[2];
1145 BOOL got_environment = TRUE;
1147 /* Initialize everything */
1149 setbuf(stdout,NULL);
1150 setbuf(stderr,NULL);
1151 kernel32_handle = GetModuleHandleW(kernel32W);
1152 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1156 if (!params->Environment)
1158 /* Copy the parent environment */
1159 if (!build_initial_environment()) exit(1);
1161 /* convert old configuration to new format */
1162 convert_old_config();
1164 got_environment = set_registry_environment( FALSE );
1165 set_additional_environment();
1168 init_windows_dirs();
1169 init_current_directory( ¶ms->CurrentDirectory );
1171 set_process_name( __wine_main_argc, __wine_main_argv );
1172 set_library_wargv( __wine_main_argv );
1173 boot_events[0] = boot_events[1] = 0;
1175 if (peb->ProcessParameters->ImagePathName.Buffer)
1177 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1181 struct binary_info binary_info;
1183 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1184 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1186 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1187 ExitProcess( GetLastError() );
1189 update_library_argv0( main_exe_name );
1190 if (!build_command_line( __wine_main_wargv )) goto error;
1191 start_wineboot( boot_events );
1194 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1195 p = strrchrW( main_exe_name, '.' );
1196 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1198 TRACE( "starting process name=%s argv[0]=%s\n",
1199 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1201 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1202 MODULE_get_dll_load_path(main_exe_name) );
1206 DWORD timeout = 2 * 60 * 1000, count = 1;
1208 if (boot_events[1]) count++;
1209 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1210 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1211 ERR( "boot event wait timed out\n" );
1212 CloseHandle( boot_events[0] );
1213 if (boot_events[1]) CloseHandle( boot_events[1] );
1214 /* reload environment now that wineboot has run */
1215 set_registry_environment( got_environment );
1216 set_additional_environment();
1218 set_wow64_environment();
1220 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1225 DWORD error = GetLastError();
1227 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1228 if (error == ERROR_BAD_EXE_FORMAT ||
1229 error == ERROR_INVALID_ADDRESS ||
1230 error == ERROR_NOT_ENOUGH_MEMORY)
1232 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1233 /* if we get back here, it failed */
1235 else if (error == ERROR_MOD_NOT_FOUND)
1237 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1238 else p = main_exe_name;
1239 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1241 /* args 1 and 2 are --app-name full_path */
1242 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1243 debugstr_w(__wine_main_wargv[3]) );
1244 ExitProcess( ERROR_BAD_EXE_FORMAT );
1246 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1247 ExitProcess( ERROR_FILE_NOT_FOUND );
1249 args[0] = (DWORD_PTR)main_exe_name;
1250 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1251 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1252 WideCharToMultiByte( CP_ACP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1253 MESSAGE( "wine: %s", msg );
1254 ExitProcess( error );
1257 LdrInitializeThunk( start_process, 0, 0, 0 );
1260 ExitProcess( GetLastError() );
1264 /***********************************************************************
1267 * Build an argv array from a command-line.
1268 * 'reserved' is the number of args to reserve before the first one.
1270 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1274 char *arg,*s,*d,*cmdline;
1275 int in_quotes,bcount,len;
1277 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1278 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1279 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1286 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1289 /* skip the remaining spaces */
1290 while (*s==' ' || *s=='\t') {
1297 } else if (*s=='\\') {
1298 /* '\', count them */
1300 } else if ((*s=='"') && ((bcount & 1)==0)) {
1302 in_quotes=!in_quotes;
1305 /* a regular character */
1310 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1312 HeapFree( GetProcessHeap(), 0, cmdline );
1316 arg = d = s = (char *)(argv + argc);
1317 memcpy( d, cmdline, len );
1322 if ((*s==' ' || *s=='\t') && !in_quotes) {
1323 /* Close the argument and copy it */
1327 /* skip the remaining spaces */
1330 } while (*s==' ' || *s=='\t');
1332 /* Start with a new argument */
1335 } else if (*s=='\\') {
1339 } else if (*s=='"') {
1341 if ((bcount & 1)==0) {
1342 /* Preceded by an even number of '\', this is half that
1343 * number of '\', plus a '"' which we discard.
1347 in_quotes=!in_quotes;
1349 /* Preceded by an odd number of '\', this is half that
1350 * number of '\' followed by a '"'
1358 /* a regular character */
1369 HeapFree( GetProcessHeap(), 0, cmdline );
1374 /***********************************************************************
1377 * Build the environment of a new child process.
1379 static char **build_envp( const WCHAR *envW )
1381 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1386 int count = 1, length;
1389 for (end = envW; *end; count++) end += strlenW(end) + 1;
1391 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1392 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1393 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1395 for (p = env; *p; p += strlen(p) + 1)
1396 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1398 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1400 if (!(p = getenv(unix_vars[i]))) continue;
1401 length += strlen(unix_vars[i]) + strlen(p) + 2;
1405 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1407 char **envptr = envp;
1408 char *dst = (char *)(envp + count);
1410 /* some variables must not be modified, so we get them directly from the unix env */
1411 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1413 if (!(p = getenv(unix_vars[i]))) continue;
1414 *envptr++ = strcpy( dst, unix_vars[i] );
1417 dst += strlen(dst) + 1;
1420 /* now put the Windows environment strings */
1421 for (p = env; *p; p += strlen(p) + 1)
1423 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1424 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1425 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1426 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1427 if (is_special_env_var( p )) /* prefix it with "WINE" */
1429 *envptr++ = strcpy( dst, "WINE" );
1434 *envptr++ = strcpy( dst, p );
1436 dst += strlen(dst) + 1;
1440 HeapFree( GetProcessHeap(), 0, env );
1445 /***********************************************************************
1448 * Fork and exec a new Unix binary, checking for errors.
1450 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1451 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1453 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1455 char **argv, **envp;
1457 if (!env) env = GetEnvironmentStringsW();
1460 if (pipe2( fd, O_CLOEXEC ) == -1)
1465 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1468 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1469 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1472 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1474 HANDLE hstdin, hstdout, hstderr;
1476 if (startup->dwFlags & STARTF_USESTDHANDLES)
1478 hstdin = startup->hStdInput;
1479 hstdout = startup->hStdOutput;
1480 hstderr = startup->hStdError;
1484 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1485 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1486 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1489 if (is_console_handle( hstdin ))
1490 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1491 if (is_console_handle( hstdout ))
1492 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1493 if (is_console_handle( hstderr ))
1494 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1495 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1496 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1497 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1500 argv = build_argv( cmdline, 0 );
1501 envp = build_envp( env );
1503 if (!(pid = fork())) /* child */
1507 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1510 if (!(pid = fork()))
1512 int fd = open( "/dev/null", O_RDWR );
1514 /* close stdin and stdout */
1522 else if (pid != -1) _exit(0); /* parent */
1528 dup2( stdin_fd, 0 );
1531 if (stdout_fd != -1)
1533 dup2( stdout_fd, 1 );
1536 if (stderr_fd != -1)
1538 dup2( stderr_fd, 2 );
1543 /* Reset signals that we previously set to SIG_IGN */
1544 signal( SIGPIPE, SIG_DFL );
1545 signal( SIGCHLD, SIG_DFL );
1547 if (newdir) chdir(newdir);
1549 if (argv && envp) execve( filename, argv, envp );
1551 write( fd[1], &err, sizeof(err) );
1554 HeapFree( GetProcessHeap(), 0, argv );
1555 HeapFree( GetProcessHeap(), 0, envp );
1556 if (stdin_fd != -1) close( stdin_fd );
1557 if (stdout_fd != -1) close( stdout_fd );
1558 if (stderr_fd != -1) close( stderr_fd );
1560 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1565 if (pid == -1) FILE_SetDosError();
1571 static inline DWORD append_string( void **ptr, const WCHAR *str )
1573 DWORD len = strlenW( str );
1574 memcpy( *ptr, str, len * sizeof(WCHAR) );
1575 *ptr = (WCHAR *)*ptr + len;
1576 return len * sizeof(WCHAR);
1579 /***********************************************************************
1580 * create_startup_info
1582 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1583 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1584 const STARTUPINFOW *startup, DWORD *info_size )
1586 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1588 startup_info_t *info;
1591 UNICODE_STRING newdir;
1592 WCHAR imagepath[MAX_PATH];
1593 HANDLE hstdin, hstdout, hstderr;
1595 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1596 lstrcpynW( imagepath, filename, MAX_PATH );
1597 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1598 lstrcpynW( imagepath, filename, MAX_PATH );
1600 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1602 newdir.Buffer = NULL;
1605 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1606 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1612 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1613 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1615 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1617 title = startup->lpTitle ? startup->lpTitle : imagepath;
1619 size = sizeof(*info);
1620 size += strlenW( cur_dir ) * sizeof(WCHAR);
1621 size += cur_params->DllPath.Length;
1622 size += strlenW( imagepath ) * sizeof(WCHAR);
1623 size += strlenW( cmdline ) * sizeof(WCHAR);
1624 size += strlenW( title ) * sizeof(WCHAR);
1625 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1626 /* FIXME: shellinfo */
1627 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1628 size = (size + 1) & ~1;
1631 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1633 info->console_flags = cur_params->ConsoleFlags;
1634 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1635 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1637 if (startup->dwFlags & STARTF_USESTDHANDLES)
1639 hstdin = startup->hStdInput;
1640 hstdout = startup->hStdOutput;
1641 hstderr = startup->hStdError;
1645 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1646 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1647 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1649 info->hstdin = wine_server_obj_handle( hstdin );
1650 info->hstdout = wine_server_obj_handle( hstdout );
1651 info->hstderr = wine_server_obj_handle( hstderr );
1652 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1654 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1655 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1656 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1657 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1661 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1662 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1663 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1666 info->x = startup->dwX;
1667 info->y = startup->dwY;
1668 info->xsize = startup->dwXSize;
1669 info->ysize = startup->dwYSize;
1670 info->xchars = startup->dwXCountChars;
1671 info->ychars = startup->dwYCountChars;
1672 info->attribute = startup->dwFillAttribute;
1673 info->flags = startup->dwFlags;
1674 info->show = startup->wShowWindow;
1677 info->curdir_len = append_string( &ptr, cur_dir );
1678 info->dllpath_len = cur_params->DllPath.Length;
1679 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1680 ptr = (char *)ptr + cur_params->DllPath.Length;
1681 info->imagepath_len = append_string( &ptr, imagepath );
1682 info->cmdline_len = append_string( &ptr, cmdline );
1683 info->title_len = append_string( &ptr, title );
1684 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1685 if (startup->lpReserved2 && startup->cbReserved2)
1687 info->runtime_len = startup->cbReserved2;
1688 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1692 RtlFreeUnicodeString( &newdir );
1696 /***********************************************************************
1697 * get_alternate_loader
1699 * Get the name of the alternate (32 or 64 bit) Wine loader.
1701 static const char *get_alternate_loader( char **ret_env )
1704 const char *loader = NULL;
1705 const char *loader_env = getenv( "WINELOADER" );
1709 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1713 int len = strlen( loader_env );
1716 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1717 strcpy( env, "WINELOADER=" );
1718 strcat( env, loader_env );
1719 strcat( env, "64" );
1723 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1724 strcpy( env, "WINELOADER=" );
1725 strcat( env, loader_env );
1726 len += sizeof("WINELOADER=") - 1;
1727 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1731 if ((loader = strrchr( env, '/' ))) loader++;
1736 if (!loader) loader = is_win64 ? "wine" : "wine64";
1741 /***********************************************************************
1742 * terminate_main_thread
1744 * On some versions of Mac OS X, the execve system call fails with
1745 * ENOTSUP if the process has multiple threads. Wine is always multi-
1746 * threaded on Mac OS X because it specifically reserves the main thread
1747 * for use by the system frameworks (see apple_main_thread() in
1748 * libs/wine/loader.c). So, when we need to exec without first forking,
1749 * we need to terminate the main thread first. We do this by installing
1750 * a custom run loop source onto the main run loop and signaling it.
1751 * The source's "perform" callback is pthread_exit and it will be
1752 * executed on the main thread, terminating it.
1754 * Returns TRUE if there's still hope the main thread has terminated or
1755 * will soon. Return FALSE if we've given up.
1757 static BOOL terminate_main_thread(void)
1763 CFRunLoopSourceContext source_context = { 0 };
1764 CFRunLoopSourceRef source;
1766 source_context.perform = pthread_exit;
1767 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1770 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1771 CFRunLoopSourceSignal( source );
1772 CFRunLoopWakeUp( CFRunLoopGetMain() );
1773 CFRelease( source );
1781 usleep(delayms * 1000);
1788 /***********************************************************************
1791 static pid_t exec_loader( LPCWSTR cmd_line, unsigned int flags, int socketfd,
1792 int stdin_fd, int stdout_fd, const char *unixdir, char *winedebug,
1793 const struct binary_info *binary_info, int exec_only )
1796 char *wineloader = NULL;
1797 const char *loader = NULL;
1800 argv = build_argv( cmd_line, 1 );
1802 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1803 loader = get_alternate_loader( &wineloader );
1805 if (exec_only || !(pid = fork())) /* child */
1807 char preloader_reserve[64], socket_env[64];
1809 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1811 if (!(pid = fork()))
1813 int fd = open( "/dev/null", O_RDWR );
1815 /* close stdin and stdout */
1823 else if (pid != -1) _exit(0); /* parent */
1827 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1828 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1831 if (stdin_fd != -1) close( stdin_fd );
1832 if (stdout_fd != -1) close( stdout_fd );
1834 /* Reset signals that we previously set to SIG_IGN */
1835 signal( SIGPIPE, SIG_DFL );
1836 signal( SIGCHLD, SIG_DFL );
1838 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
1839 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1840 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1842 putenv( preloader_reserve );
1843 putenv( socket_env );
1844 if (winedebug) putenv( winedebug );
1845 if (wineloader) putenv( wineloader );
1846 if (unixdir) chdir(unixdir);
1852 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1855 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1862 HeapFree( GetProcessHeap(), 0, wineloader );
1863 HeapFree( GetProcessHeap(), 0, argv );
1867 /***********************************************************************
1870 * Create a new process. If hFile is a valid handle we have an exe
1871 * file, otherwise it is a Winelib app.
1873 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1874 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1875 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1876 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1877 const struct binary_info *binary_info, int exec_only )
1879 BOOL ret, success = FALSE;
1880 HANDLE process_info;
1882 char *winedebug = NULL;
1883 startup_info_t *startup_info;
1884 DWORD startup_info_size;
1885 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1889 if (!is_win64 && !is_wow64 && (binary_info->flags & BINARY_FLAG_64BIT))
1891 ERR( "starting 64-bit process %s not supported in 32-bit wineprefix\n", debugstr_w(filename) );
1892 SetLastError( ERROR_BAD_EXE_FORMAT );
1896 /* create the socket for the new process */
1898 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1900 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1904 if (exec_only) /* things are much simpler in this case */
1906 wine_server_send_fd( socketfd[1] );
1907 close( socketfd[1] );
1908 SERVER_START_REQ( new_process )
1910 req->create_flags = flags;
1911 req->socket_fd = socketfd[1];
1912 req->exe_file = wine_server_obj_handle( hFile );
1913 ret = !wine_server_call_err( req );
1917 if (ret) exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
1918 winedebug, binary_info, TRUE );
1920 close( socketfd[0] );
1924 RtlAcquirePebLock();
1926 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1927 &startup_info_size )))
1929 RtlReleasePebLock();
1930 close( socketfd[0] );
1931 close( socketfd[1] );
1934 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
1938 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1939 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1941 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1942 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1943 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1945 env_end += strlenW(env_end) + 1;
1949 wine_server_send_fd( socketfd[1] );
1950 close( socketfd[1] );
1952 /* create the process on the server side */
1954 SERVER_START_REQ( new_process )
1956 req->inherit_all = inherit;
1957 req->create_flags = flags;
1958 req->socket_fd = socketfd[1];
1959 req->exe_file = wine_server_obj_handle( hFile );
1960 req->process_access = PROCESS_ALL_ACCESS;
1961 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1962 req->thread_access = THREAD_ALL_ACCESS;
1963 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1964 req->info_size = startup_info_size;
1966 wine_server_add_data( req, startup_info, startup_info_size );
1967 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
1968 if ((ret = !wine_server_call_err( req )))
1970 info->dwProcessId = (DWORD)reply->pid;
1971 info->dwThreadId = (DWORD)reply->tid;
1972 info->hProcess = wine_server_ptr_handle( reply->phandle );
1973 info->hThread = wine_server_ptr_handle( reply->thandle );
1975 process_info = wine_server_ptr_handle( reply->info );
1979 RtlReleasePebLock();
1982 close( socketfd[0] );
1983 HeapFree( GetProcessHeap(), 0, startup_info );
1984 HeapFree( GetProcessHeap(), 0, winedebug );
1988 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1990 if (startup_info->hstdin)
1991 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
1992 FILE_READ_DATA, &stdin_fd, NULL );
1993 if (startup_info->hstdout)
1994 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
1995 FILE_WRITE_DATA, &stdout_fd, NULL );
1997 HeapFree( GetProcessHeap(), 0, startup_info );
1999 /* create the child process */
2001 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2002 winedebug, binary_info, FALSE );
2004 if (stdin_fd != -1) close( stdin_fd );
2005 if (stdout_fd != -1) close( stdout_fd );
2006 close( socketfd[0] );
2007 HeapFree( GetProcessHeap(), 0, winedebug );
2014 /* wait for the new process info to be ready */
2016 WaitForSingleObject( process_info, INFINITE );
2017 SERVER_START_REQ( get_new_process_info )
2019 req->info = wine_server_obj_handle( process_info );
2020 wine_server_call( req );
2021 success = reply->success;
2022 err = reply->exit_code;
2028 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2031 CloseHandle( process_info );
2035 CloseHandle( process_info );
2036 CloseHandle( info->hProcess );
2037 CloseHandle( info->hThread );
2038 info->hProcess = info->hThread = 0;
2039 info->dwProcessId = info->dwThreadId = 0;
2044 /***********************************************************************
2045 * create_vdm_process
2047 * Create a new VDM process for a 16-bit or DOS application.
2049 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2050 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2051 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2052 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2053 const struct binary_info *binary_info, int exec_only )
2055 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2058 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
2059 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
2063 SetLastError( ERROR_OUTOFMEMORY );
2066 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
2067 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2068 flags, startup, info, unixdir, binary_info, exec_only );
2069 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2074 /***********************************************************************
2075 * create_cmd_process
2077 * Create a new cmd shell process for a .BAT file.
2079 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2080 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2081 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2082 LPPROCESS_INFORMATION info )
2085 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2086 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2087 WCHAR comspec[MAX_PATH];
2091 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2093 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2094 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2097 strcpyW( newcmdline, comspec );
2098 strcatW( newcmdline, slashcW );
2099 strcatW( newcmdline, cmd_line );
2100 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2101 flags, env, cur_dir, startup, info );
2102 HeapFree( GetProcessHeap(), 0, newcmdline );
2107 /*************************************************************************
2110 * Helper for CreateProcess: retrieve the file name to load from the
2111 * app name and command line. Store the file name in buffer, and
2112 * return a possibly modified command line.
2113 * Also returns a handle to the opened file if it's a Windows binary.
2115 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2116 int buflen, HANDLE *handle, struct binary_info *binary_info )
2118 static const WCHAR quotesW[] = {'"','%','s','"',0};
2120 WCHAR *name, *pos, *first_space, *ret = NULL;
2123 /* if we have an app name, everything is easy */
2127 /* use the unmodified app name as file name */
2128 lstrcpynW( buffer, appname, buflen );
2129 *handle = open_exe_file( buffer, binary_info );
2130 if (!(ret = cmdline) || !cmdline[0])
2132 /* no command-line, create one */
2133 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2134 sprintfW( ret, quotesW, appname );
2139 /* first check for a quoted file name */
2141 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2143 int len = p - cmdline - 1;
2144 /* extract the quoted portion as file name */
2145 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2146 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2149 if (!find_exe_file( name, buffer, buflen, handle, binary_info ))
2151 if (!get_builtin_path( name, exeW, buffer, buflen, binary_info )) goto done;
2154 ret = cmdline; /* no change necessary */
2158 /* now try the command-line word by word */
2160 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2168 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2170 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2175 if (!first_space) first_space = pos;
2176 if (!(*pos++ = *p++)) break;
2181 if (first_space) *first_space = 0; /* try only the first word as a builtin */
2182 if (get_builtin_path( name, exeW, buffer, buflen, binary_info ))
2187 else SetLastError( ERROR_FILE_NOT_FOUND );
2189 else if (first_space) /* build a new command-line with quotes */
2191 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2193 sprintfW( ret, quotesW, name );
2198 HeapFree( GetProcessHeap(), 0, name );
2203 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2204 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2205 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2206 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2207 LPPROCESS_INFORMATION info )
2211 char *unixdir = NULL;
2212 WCHAR name[MAX_PATH];
2213 WCHAR *tidy_cmdline, *p, *envW = env;
2214 struct binary_info binary_info;
2216 /* Process the AppName and/or CmdLine to get module name and path */
2218 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2220 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2221 &hFile, &binary_info )))
2223 if (hFile == INVALID_HANDLE_VALUE) goto done;
2225 /* Warn if unsupported features are used */
2227 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2228 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2229 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2230 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2231 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2235 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2237 SetLastError(ERROR_DIRECTORY);
2243 WCHAR buf[MAX_PATH];
2244 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2247 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2252 while (*p) p += strlen(p) + 1;
2253 p++; /* final null */
2254 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
2255 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2256 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
2257 flags |= CREATE_UNICODE_ENVIRONMENT;
2260 info->hThread = info->hProcess = 0;
2261 info->dwProcessId = info->dwThreadId = 0;
2263 if (binary_info.flags & BINARY_FLAG_DLL)
2265 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2266 SetLastError( ERROR_BAD_EXE_FORMAT );
2268 else switch (binary_info.type)
2271 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2272 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2273 binary_info.res_start, binary_info.res_end );
2274 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2275 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2280 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2281 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2282 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2284 case BINARY_UNIX_LIB:
2285 TRACE( "starting %s as %d-bit Winelib app\n",
2286 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2287 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2288 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2290 case BINARY_UNKNOWN:
2291 /* check for .com or .bat extension */
2292 if ((p = strrchrW( name, '.' )))
2294 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2296 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2297 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2298 inherit, flags, startup_info, info, unixdir,
2299 &binary_info, FALSE );
2302 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2304 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2305 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2306 inherit, flags, startup_info, info );
2311 case BINARY_UNIX_EXE:
2313 /* unknown file, try as unix executable */
2316 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2318 if ((unix_name = wine_get_unix_file_name( name )))
2320 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2321 HeapFree( GetProcessHeap(), 0, unix_name );
2326 if (hFile) CloseHandle( hFile );
2329 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2330 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2331 HeapFree( GetProcessHeap(), 0, unixdir );
2333 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2338 /**********************************************************************
2339 * CreateProcessA (KERNEL32.@)
2341 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2342 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2343 DWORD flags, LPVOID env, LPCSTR cur_dir,
2344 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2347 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2348 UNICODE_STRING desktopW, titleW;
2351 desktopW.Buffer = NULL;
2352 titleW.Buffer = NULL;
2353 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2354 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2355 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2357 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2358 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2360 memcpy( &infoW, startup_info, sizeof(infoW) );
2361 infoW.lpDesktop = desktopW.Buffer;
2362 infoW.lpTitle = titleW.Buffer;
2364 if (startup_info->lpReserved)
2365 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2366 debugstr_a(startup_info->lpReserved));
2368 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2369 inherit, flags, env, cur_dirW, &infoW, info );
2371 HeapFree( GetProcessHeap(), 0, app_nameW );
2372 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2373 HeapFree( GetProcessHeap(), 0, cur_dirW );
2374 RtlFreeUnicodeString( &desktopW );
2375 RtlFreeUnicodeString( &titleW );
2380 /**********************************************************************
2381 * CreateProcessW (KERNEL32.@)
2383 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2384 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2385 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2386 LPPROCESS_INFORMATION info )
2388 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2389 inherit, flags, env, cur_dir, startup_info, info);
2393 /**********************************************************************
2396 static void exec_process( LPCWSTR name )
2400 STARTUPINFOW startup_info;
2401 PROCESS_INFORMATION info;
2402 struct binary_info binary_info;
2404 hFile = open_exe_file( name, &binary_info );
2405 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2407 memset( &startup_info, 0, sizeof(startup_info) );
2408 startup_info.cb = sizeof(startup_info);
2410 /* Determine executable type */
2412 if (binary_info.flags & BINARY_FLAG_DLL) return;
2413 switch (binary_info.type)
2416 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2417 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2418 binary_info.res_start, binary_info.res_end );
2419 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2420 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2422 case BINARY_UNIX_LIB:
2423 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2424 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2425 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2427 case BINARY_UNKNOWN:
2428 /* check for .com or .pif extension */
2429 if (!(p = strrchrW( name, '.' ))) break;
2430 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2435 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2436 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2437 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2442 CloseHandle( hFile );
2446 /***********************************************************************
2449 * Wrapper to call WaitForInputIdle USER function
2451 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2453 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2455 HMODULE mod = GetModuleHandleA( "user32.dll" );
2458 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2459 if (ptr) return ptr( process, timeout );
2465 /***********************************************************************
2466 * WinExec (KERNEL32.@)
2468 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2470 PROCESS_INFORMATION info;
2471 STARTUPINFOA startup;
2475 memset( &startup, 0, sizeof(startup) );
2476 startup.cb = sizeof(startup);
2477 startup.dwFlags = STARTF_USESHOWWINDOW;
2478 startup.wShowWindow = nCmdShow;
2480 /* cmdline needs to be writable for CreateProcess */
2481 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2482 strcpy( cmdline, lpCmdLine );
2484 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2485 0, NULL, NULL, &startup, &info ))
2487 /* Give 30 seconds to the app to come up */
2488 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2489 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2491 /* Close off the handles */
2492 CloseHandle( info.hThread );
2493 CloseHandle( info.hProcess );
2495 else if ((ret = GetLastError()) >= 32)
2497 FIXME("Strange error set by CreateProcess: %d\n", ret );
2500 HeapFree( GetProcessHeap(), 0, cmdline );
2505 /**********************************************************************
2506 * LoadModule (KERNEL32.@)
2508 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2510 LOADPARMS32 *params = paramBlock;
2511 PROCESS_INFORMATION info;
2512 STARTUPINFOA startup;
2515 char filename[MAX_PATH];
2518 if (!name) return ERROR_FILE_NOT_FOUND;
2520 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2521 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2522 return GetLastError();
2524 len = (BYTE)params->lpCmdLine[0];
2525 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2526 return ERROR_NOT_ENOUGH_MEMORY;
2528 strcpy( cmdline, filename );
2529 p = cmdline + strlen(cmdline);
2531 memcpy( p, params->lpCmdLine + 1, len );
2534 memset( &startup, 0, sizeof(startup) );
2535 startup.cb = sizeof(startup);
2536 if (params->lpCmdShow)
2538 startup.dwFlags = STARTF_USESHOWWINDOW;
2539 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2542 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2543 params->lpEnvAddress, NULL, &startup, &info ))
2545 /* Give 30 seconds to the app to come up */
2546 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2547 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2549 /* Close off the handles */
2550 CloseHandle( info.hThread );
2551 CloseHandle( info.hProcess );
2553 else if ((ret = GetLastError()) >= 32)
2555 FIXME("Strange error set by CreateProcess: %u\n", ret );
2559 HeapFree( GetProcessHeap(), 0, cmdline );
2564 /******************************************************************************
2565 * TerminateProcess (KERNEL32.@)
2567 * Terminates a process.
2570 * handle [I] Process to terminate.
2571 * exit_code [I] Exit code.
2575 * Failure: FALSE, check GetLastError().
2577 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2579 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2580 if (status) SetLastError( RtlNtStatusToDosError(status) );
2584 /***********************************************************************
2585 * ExitProcess (KERNEL32.@)
2587 * Exits the current process.
2590 * status [I] Status code to exit with.
2596 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2598 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2599 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2600 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2602 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2606 void WINAPI process_ExitProcess( DWORD status )
2608 LdrShutdownProcess();
2609 NtTerminateProcess(GetCurrentProcess(), status);
2615 void WINAPI ExitProcess( DWORD status )
2617 LdrShutdownProcess();
2618 NtTerminateProcess(GetCurrentProcess(), status);
2624 /***********************************************************************
2625 * GetExitCodeProcess [KERNEL32.@]
2627 * Gets termination status of specified process.
2630 * hProcess [in] Handle to the process.
2631 * lpExitCode [out] Address to receive termination status.
2637 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2640 PROCESS_BASIC_INFORMATION pbi;
2642 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2644 if (status == STATUS_SUCCESS)
2646 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2649 SetLastError( RtlNtStatusToDosError(status) );
2654 /***********************************************************************
2655 * SetErrorMode (KERNEL32.@)
2657 UINT WINAPI SetErrorMode( UINT mode )
2661 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2662 &old, sizeof(old), NULL );
2663 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2664 &mode, sizeof(mode) );
2668 /***********************************************************************
2669 * GetErrorMode (KERNEL32.@)
2671 UINT WINAPI GetErrorMode( void )
2675 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2676 &mode, sizeof(mode), NULL );
2680 /**********************************************************************
2681 * TlsAlloc [KERNEL32.@]
2683 * Allocates a thread local storage index.
2686 * Success: TLS index.
2687 * Failure: 0xFFFFFFFF
2689 DWORD WINAPI TlsAlloc( void )
2692 PEB * const peb = NtCurrentTeb()->Peb;
2694 RtlAcquirePebLock();
2695 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2696 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2699 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2702 if (!NtCurrentTeb()->TlsExpansionSlots &&
2703 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2704 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2706 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2708 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2712 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2713 index += TLS_MINIMUM_AVAILABLE;
2716 else SetLastError( ERROR_NO_MORE_ITEMS );
2718 RtlReleasePebLock();
2723 /**********************************************************************
2724 * TlsFree [KERNEL32.@]
2726 * Releases a thread local storage index, making it available for reuse.
2729 * index [in] TLS index to free.
2735 BOOL WINAPI TlsFree( DWORD index )
2739 RtlAcquirePebLock();
2740 if (index >= TLS_MINIMUM_AVAILABLE)
2742 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2743 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2747 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2748 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2750 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2751 else SetLastError( ERROR_INVALID_PARAMETER );
2752 RtlReleasePebLock();
2757 /**********************************************************************
2758 * TlsGetValue [KERNEL32.@]
2760 * Gets value in a thread's TLS slot.
2763 * index [in] TLS index to retrieve value for.
2766 * Success: Value stored in calling thread's TLS slot for index.
2767 * Failure: 0 and GetLastError() returns NO_ERROR.
2769 LPVOID WINAPI TlsGetValue( DWORD index )
2773 if (index < TLS_MINIMUM_AVAILABLE)
2775 ret = NtCurrentTeb()->TlsSlots[index];
2779 index -= TLS_MINIMUM_AVAILABLE;
2780 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2782 SetLastError( ERROR_INVALID_PARAMETER );
2785 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2786 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2788 SetLastError( ERROR_SUCCESS );
2793 /**********************************************************************
2794 * TlsSetValue [KERNEL32.@]
2796 * Stores a value in the thread's TLS slot.
2799 * index [in] TLS index to set value for.
2800 * value [in] Value to be stored.
2806 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2808 if (index < TLS_MINIMUM_AVAILABLE)
2810 NtCurrentTeb()->TlsSlots[index] = value;
2814 index -= TLS_MINIMUM_AVAILABLE;
2815 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2817 SetLastError( ERROR_INVALID_PARAMETER );
2820 if (!NtCurrentTeb()->TlsExpansionSlots &&
2821 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2822 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2824 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2827 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2833 /***********************************************************************
2834 * GetProcessFlags (KERNEL32.@)
2836 DWORD WINAPI GetProcessFlags( DWORD processid )
2838 IMAGE_NT_HEADERS *nt;
2841 if (processid && processid != GetCurrentProcessId()) return 0;
2843 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2845 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2846 flags |= PDB32_CONSOLE_PROC;
2848 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2849 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2854 /*********************************************************************
2855 * OpenProcess (KERNEL32.@)
2857 * Opens a handle to a process.
2860 * access [I] Desired access rights assigned to the returned handle.
2861 * inherit [I] Determines whether or not child processes will inherit the handle.
2862 * id [I] Process identifier of the process to get a handle to.
2865 * Success: Valid handle to the specified process.
2866 * Failure: NULL, check GetLastError().
2868 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2872 OBJECT_ATTRIBUTES attr;
2875 cid.UniqueProcess = ULongToHandle(id);
2876 cid.UniqueThread = 0; /* FIXME ? */
2878 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2879 attr.RootDirectory = NULL;
2880 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2881 attr.SecurityDescriptor = NULL;
2882 attr.SecurityQualityOfService = NULL;
2883 attr.ObjectName = NULL;
2885 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2887 status = NtOpenProcess(&handle, access, &attr, &cid);
2888 if (status != STATUS_SUCCESS)
2890 SetLastError( RtlNtStatusToDosError(status) );
2897 /*********************************************************************
2898 * GetProcessId (KERNEL32.@)
2900 * Gets the a unique identifier of a process.
2903 * hProcess [I] Handle to the process.
2907 * Failure: FALSE, check GetLastError().
2911 * The identifier is unique only on the machine and only until the process
2912 * exits (including system shutdown).
2914 DWORD WINAPI GetProcessId( HANDLE hProcess )
2917 PROCESS_BASIC_INFORMATION pbi;
2919 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2921 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2922 SetLastError( RtlNtStatusToDosError(status) );
2927 /*********************************************************************
2928 * CloseHandle (KERNEL32.@)
2933 * handle [I] Handle to close.
2937 * Failure: FALSE, check GetLastError().
2939 BOOL WINAPI CloseHandle( HANDLE handle )
2943 /* stdio handles need special treatment */
2944 if (handle == (HANDLE)STD_INPUT_HANDLE)
2945 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
2946 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
2947 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
2948 else if (handle == (HANDLE)STD_ERROR_HANDLE)
2949 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
2951 if (is_console_handle(handle))
2952 return CloseConsoleHandle(handle);
2954 status = NtClose( handle );
2955 if (status) SetLastError( RtlNtStatusToDosError(status) );
2960 /*********************************************************************
2961 * GetHandleInformation (KERNEL32.@)
2963 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2965 OBJECT_DATA_INFORMATION info;
2966 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2968 if (status) SetLastError( RtlNtStatusToDosError(status) );
2972 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2973 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2979 /*********************************************************************
2980 * SetHandleInformation (KERNEL32.@)
2982 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2984 OBJECT_DATA_INFORMATION info;
2987 /* if not setting both fields, retrieve current value first */
2988 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2989 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2991 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2993 SetLastError( RtlNtStatusToDosError(status) );
2997 if (mask & HANDLE_FLAG_INHERIT)
2998 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2999 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3000 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3002 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3003 if (status) SetLastError( RtlNtStatusToDosError(status) );
3008 /*********************************************************************
3009 * DuplicateHandle (KERNEL32.@)
3011 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3012 HANDLE dest_process, HANDLE *dest,
3013 DWORD access, BOOL inherit, DWORD options )
3017 if (is_console_handle(source))
3019 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3020 if (source_process != dest_process ||
3021 source_process != GetCurrentProcess())
3023 SetLastError(ERROR_INVALID_PARAMETER);
3026 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3027 return (*dest != INVALID_HANDLE_VALUE);
3029 status = NtDuplicateObject( source_process, source, dest_process, dest,
3030 access, inherit ? OBJ_INHERIT : 0, options );
3031 if (status) SetLastError( RtlNtStatusToDosError(status) );
3036 /***********************************************************************
3037 * ConvertToGlobalHandle (KERNEL32.@)
3039 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3041 HANDLE ret = INVALID_HANDLE_VALUE;
3042 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3043 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3048 /***********************************************************************
3049 * SetHandleContext (KERNEL32.@)
3051 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3053 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3054 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3055 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3060 /***********************************************************************
3061 * GetHandleContext (KERNEL32.@)
3063 DWORD WINAPI GetHandleContext(HANDLE hnd)
3065 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3066 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3067 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3072 /***********************************************************************
3073 * CreateSocketHandle (KERNEL32.@)
3075 HANDLE WINAPI CreateSocketHandle(void)
3077 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3078 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3079 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3080 return INVALID_HANDLE_VALUE;
3084 /***********************************************************************
3085 * SetPriorityClass (KERNEL32.@)
3087 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3090 PROCESS_PRIORITY_CLASS ppc;
3092 ppc.Foreground = FALSE;
3093 switch (priorityclass)
3095 case IDLE_PRIORITY_CLASS:
3096 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3097 case BELOW_NORMAL_PRIORITY_CLASS:
3098 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3099 case NORMAL_PRIORITY_CLASS:
3100 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3101 case ABOVE_NORMAL_PRIORITY_CLASS:
3102 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3103 case HIGH_PRIORITY_CLASS:
3104 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3105 case REALTIME_PRIORITY_CLASS:
3106 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3108 SetLastError(ERROR_INVALID_PARAMETER);
3112 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3115 if (status != STATUS_SUCCESS)
3117 SetLastError( RtlNtStatusToDosError(status) );
3124 /***********************************************************************
3125 * GetPriorityClass (KERNEL32.@)
3127 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3130 PROCESS_BASIC_INFORMATION pbi;
3132 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3134 if (status != STATUS_SUCCESS)
3136 SetLastError( RtlNtStatusToDosError(status) );
3139 switch (pbi.BasePriority)
3141 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3142 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3143 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3144 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3145 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3146 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3148 SetLastError( ERROR_INVALID_PARAMETER );
3153 /***********************************************************************
3154 * SetProcessAffinityMask (KERNEL32.@)
3156 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3160 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3161 &affmask, sizeof(DWORD_PTR));
3164 SetLastError( RtlNtStatusToDosError(status) );
3171 /**********************************************************************
3172 * GetProcessAffinityMask (KERNEL32.@)
3174 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3176 NTSTATUS status = STATUS_SUCCESS;
3178 if (system_mask) *system_mask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
3181 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3182 process_mask, sizeof(*process_mask), NULL )))
3183 SetLastError( RtlNtStatusToDosError(status) );
3189 /***********************************************************************
3190 * GetProcessVersion (KERNEL32.@)
3192 DWORD WINAPI GetProcessVersion( DWORD pid )
3196 PROCESS_BASIC_INFORMATION pbi;
3199 IMAGE_DOS_HEADER dos;
3200 IMAGE_NT_HEADERS nt;
3203 if (!pid || pid == GetCurrentProcessId())
3205 IMAGE_NT_HEADERS *nt;
3207 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3208 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
3209 nt->OptionalHeader.MinorSubsystemVersion);
3213 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3214 if (!process) return 0;
3216 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3217 if (status) goto err;
3219 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3220 if (status || count != sizeof(peb)) goto err;
3222 memset(&dos, 0, sizeof(dos));
3223 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3224 if (status || count != sizeof(dos)) goto err;
3225 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3227 memset(&nt, 0, sizeof(nt));
3228 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3229 if (status || count != sizeof(nt)) goto err;
3230 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3232 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3235 CloseHandle(process);
3237 if (status != STATUS_SUCCESS)
3238 SetLastError(RtlNtStatusToDosError(status));
3244 /***********************************************************************
3245 * SetProcessWorkingSetSize [KERNEL32.@]
3246 * Sets the min/max working set sizes for a specified process.
3249 * hProcess [I] Handle to the process of interest
3250 * minset [I] Specifies minimum working set size
3251 * maxset [I] Specifies maximum working set size
3257 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3260 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3261 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3262 /* Trim the working set to zero */
3263 /* Swap the process out of physical RAM */
3268 /***********************************************************************
3269 * K32EmptyWorkingSet (KERNEL32.@)
3271 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3273 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3276 /***********************************************************************
3277 * GetProcessWorkingSetSize (KERNEL32.@)
3279 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3282 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3283 /* 32 MB working set size */
3284 if (minset) *minset = 32*1024*1024;
3285 if (maxset) *maxset = 32*1024*1024;
3290 /***********************************************************************
3291 * SetProcessShutdownParameters (KERNEL32.@)
3293 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3295 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3296 shutdown_flags = flags;
3297 shutdown_priority = level;
3302 /***********************************************************************
3303 * GetProcessShutdownParameters (KERNEL32.@)
3306 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3308 *lpdwLevel = shutdown_priority;
3309 *lpdwFlags = shutdown_flags;
3314 /***********************************************************************
3315 * GetProcessPriorityBoost (KERNEL32.@)
3317 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3319 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3321 /* Report that no boost is present.. */
3322 *pDisablePriorityBoost = FALSE;
3327 /***********************************************************************
3328 * SetProcessPriorityBoost (KERNEL32.@)
3330 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3332 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3333 /* Say we can do it. I doubt the program will notice that we don't. */
3338 /***********************************************************************
3339 * ReadProcessMemory (KERNEL32.@)
3341 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3342 SIZE_T *bytes_read )
3344 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3345 if (status) SetLastError( RtlNtStatusToDosError(status) );
3350 /***********************************************************************
3351 * WriteProcessMemory (KERNEL32.@)
3353 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3354 SIZE_T *bytes_written )
3356 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3357 if (status) SetLastError( RtlNtStatusToDosError(status) );
3362 /****************************************************************************
3363 * FlushInstructionCache (KERNEL32.@)
3365 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3368 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3369 if (status) SetLastError( RtlNtStatusToDosError(status) );
3374 /******************************************************************
3375 * GetProcessIoCounters (KERNEL32.@)
3377 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3381 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3382 ioc, sizeof(*ioc), NULL);
3383 if (status) SetLastError( RtlNtStatusToDosError(status) );
3387 /******************************************************************
3388 * GetProcessHandleCount (KERNEL32.@)
3390 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3394 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3395 cnt, sizeof(*cnt), NULL);
3396 if (status) SetLastError( RtlNtStatusToDosError(status) );
3400 /******************************************************************
3401 * QueryFullProcessImageNameA (KERNEL32.@)
3403 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3406 DWORD pdwSizeW = *pdwSize;
3407 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3409 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3412 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3413 lpExeName, *pdwSize, NULL, NULL));
3415 *pdwSize = strlen(lpExeName);
3417 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3421 /******************************************************************
3422 * QueryFullProcessImageNameW (KERNEL32.@)
3424 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3426 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3427 UNICODE_STRING *dynamic_buffer = NULL;
3428 UNICODE_STRING nt_path;
3429 UNICODE_STRING *result = NULL;
3433 RtlInitUnicodeStringEx(&nt_path, NULL);
3434 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3435 * as this is on Wine. */
3436 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3437 sizeof(buffer) - sizeof(WCHAR), &needed);
3438 if (status == STATUS_INFO_LENGTH_MISMATCH)
3440 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3441 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3442 result = dynamic_buffer;
3445 result = (PUNICODE_STRING)buffer;
3447 if (status) goto cleanup;
3449 if (dwFlags & PROCESS_NAME_NATIVE)
3451 result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3452 if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3454 status = STATUS_OBJECT_PATH_NOT_FOUND;
3460 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3462 status = STATUS_BUFFER_TOO_SMALL;
3466 *pdwSize = result->Length/sizeof(WCHAR);
3467 memcpy( lpExeName, result->Buffer, result->Length );
3468 lpExeName[*pdwSize] = 0;
3471 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3472 RtlFreeUnicodeString(&nt_path);
3473 if (status) SetLastError( RtlNtStatusToDosError(status) );
3477 /***********************************************************************
3478 * K32GetProcessImageFileNameA (KERNEL32.@)
3480 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3482 FIXME("(%p, %p, %d) stub\n", process, file, size );
3486 /***********************************************************************
3487 * K32GetProcessImageFileNameW (KERNEL32.@)
3489 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3491 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3494 /***********************************************************************
3495 * K32EnumProcesses (KERNEL32.@)
3497 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3499 SYSTEM_PROCESS_INFORMATION *spi;
3500 ULONG size = 0x4000;
3506 HeapFree(GetProcessHeap(), 0, buf);
3507 buf = HeapAlloc(GetProcessHeap(), 0, size);
3511 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3512 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3514 if (status != STATUS_SUCCESS)
3516 HeapFree(GetProcessHeap(), 0, buf);
3517 SetLastError(RtlNtStatusToDosError(status));
3523 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3525 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3526 *lpcbUsed += sizeof(DWORD);
3528 if (spi->NextEntryOffset == 0)
3531 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3534 HeapFree(GetProcessHeap(), 0, buf);
3538 /***********************************************************************
3539 * K32QueryWorkingSet (KERNEL32.@)
3541 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3545 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3547 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3551 SetLastError( RtlNtStatusToDosError( status ) );
3557 /***********************************************************************
3558 * K32QueryWorkingSetEx (KERNEL32.@)
3560 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3564 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3566 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3570 SetLastError( RtlNtStatusToDosError( status ) );
3576 /***********************************************************************
3577 * K32GetProcessMemoryInfo (KERNEL32.@)
3579 * Retrieve memory usage information for a given process
3582 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3583 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3588 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3590 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3594 status = NtQueryInformationProcess(process, ProcessVmCounters,
3595 &vmc, sizeof(vmc), NULL);
3599 SetLastError(RtlNtStatusToDosError(status));
3603 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3604 pmc->PageFaultCount = vmc.PageFaultCount;
3605 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3606 pmc->WorkingSetSize = vmc.WorkingSetSize;
3607 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3608 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3609 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3610 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3611 pmc->PagefileUsage = vmc.PagefileUsage;
3612 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3617 /***********************************************************************
3618 * ProcessIdToSessionId (KERNEL32.@)
3619 * This function is available on Terminal Server 4SP4 and Windows 2000
3621 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3623 /* According to MSDN, if the calling process is not in a terminal
3624 * services environment, then the sessionid returned is zero.
3631 /***********************************************************************
3632 * RegisterServiceProcess (KERNEL32.@)
3634 * A service process calls this function to ensure that it continues to run
3635 * even after a user logged off.
3637 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3639 /* I don't think that Wine needs to do anything in this function */
3640 return 1; /* success */
3644 /**********************************************************************
3645 * IsWow64Process (KERNEL32.@)
3647 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3652 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3654 if (status != STATUS_SUCCESS)
3656 SetLastError( RtlNtStatusToDosError( status ) );
3659 *Wow64Process = (pbi != 0);
3664 /***********************************************************************
3665 * GetCurrentProcess (KERNEL32.@)
3667 * Get a handle to the current process.
3673 * A handle representing the current process.
3675 #undef GetCurrentProcess
3676 HANDLE WINAPI GetCurrentProcess(void)
3678 return (HANDLE)~(ULONG_PTR)0;
3681 /***********************************************************************
3682 * GetLogicalProcessorInformation (KERNEL32.@)
3684 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3686 FIXME("(%p,%p): stub\n", buffer, pBufLen);
3687 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3691 /***********************************************************************
3692 * GetLogicalProcessorInformationEx (KERNEL32.@)
3694 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer, PDWORD pBufLen)
3696 FIXME("(%u,%p,%p): stub\n", relationship, buffer, pBufLen);
3697 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3701 /***********************************************************************
3702 * CmdBatNotification (KERNEL32.@)
3704 * Notifies the system that a batch file has started or finished.
3707 * bBatchRunning [I] TRUE if a batch file has started or
3708 * FALSE if a batch file has finished executing.
3713 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3715 FIXME("%d\n", bBatchRunning);
3720 /***********************************************************************
3721 * RegisterApplicationRestart (KERNEL32.@)
3723 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3725 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3730 /**********************************************************************
3731 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3733 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3739 /**********************************************************************
3740 * GetSystemDEPPolicy (KERNEL32.@)
3742 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3748 /**********************************************************************
3749 * SetProcessDEPPolicy (KERNEL32.@)
3751 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3753 FIXME("(%d): stub\n", newDEP);
3754 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3758 /**********************************************************************
3759 * ApplicationRecoveryFinished (KERNEL32.@)
3761 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
3764 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3767 /**********************************************************************
3768 * ApplicationRecoveryInProgress (KERNEL32.@)
3770 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
3772 FIXME(":%p stub\n", canceled);
3773 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3777 /**********************************************************************
3778 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3780 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
3782 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
3783 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3787 /**********************************************************************
3788 * GetNumaHighestNodeNumber (KERNEL32.@)
3790 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
3792 FIXME("(%p): stub\n", highestnode);
3793 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3797 /**********************************************************************
3798 * GetNumaNodeProcessorMask (KERNEL32.@)
3800 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
3802 FIXME("(%c %p): stub\n", node, mask);
3803 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3807 /**********************************************************************
3808 * GetNumaAvailableMemoryNode (KERNEL32.@)
3810 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
3812 FIXME("(%c %p): stub\n", node, available_bytes);
3813 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);