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>
44 #ifdef HAVE_SYS_WAIT_H
45 # include <sys/wait.h>
51 #include <CoreFoundation/CoreFoundation.h>
56 #define WIN32_NO_STATUS
58 #include "kernel_private.h"
60 #include "wine/library.h"
61 #include "wine/server.h"
62 #include "wine/unicode.h"
63 #include "wine/debug.h"
65 WINE_DEFAULT_DEBUG_CHANNEL(process);
66 WINE_DECLARE_DEBUG_CHANNEL(file);
67 WINE_DECLARE_DEBUG_CHANNEL(relay);
70 extern char **__wine_get_main_environment(void);
72 extern char **__wine_main_environ;
73 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
84 static DWORD shutdown_flags = 0;
85 static DWORD shutdown_priority = 0x280;
87 static const int is_win64 = (sizeof(void *) > sizeof(int));
89 HMODULE kernel32_handle = 0;
91 const WCHAR *DIR_Windows = NULL;
92 const WCHAR *DIR_System = NULL;
93 const WCHAR *DIR_SysWow64 = NULL;
96 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
97 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
98 #define PDB32_DOS_PROC 0x0010 /* Dos process */
99 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
100 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
101 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
103 static const WCHAR exeW[] = {'.','e','x','e',0};
104 static const WCHAR comW[] = {'.','c','o','m',0};
105 static const WCHAR batW[] = {'.','b','a','t',0};
106 static const WCHAR cmdW[] = {'.','c','m','d',0};
107 static const WCHAR pifW[] = {'.','p','i','f',0};
108 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
110 static void exec_process( LPCWSTR name );
112 extern void SHELL_LoadRegistry(void);
115 /***********************************************************************
118 static inline int contains_path( LPCWSTR name )
120 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
124 /***********************************************************************
127 * Check if an environment variable needs to be handled specially when
128 * passed through the Unix environment (i.e. prefixed with "WINE").
130 static inline int is_special_env_var( const char *var )
132 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
133 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
134 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
135 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
136 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
140 /***********************************************************************
143 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
145 unsigned int len = strlenW( prefix );
147 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
148 while (filename[len] == '\\') len++;
153 /***************************************************************************
156 * Get the path of a builtin module when the native file does not exist.
158 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
159 UINT size, struct binary_info *binary_info )
163 void *redir_disabled = 0;
164 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
166 /* builtin names cannot be empty or contain spaces */
167 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
169 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
170 Wow64RevertWow64FsRedirection( redir_disabled );
172 if (contains_path( libname ))
174 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
175 filename, &file_part ) > size * sizeof(WCHAR))
176 return FALSE; /* too long */
178 if ((len = is_path_prefix( DIR_System, filename )))
180 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
182 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
188 if (filename + len != file_part) return FALSE;
192 len = strlenW( DIR_System );
193 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
194 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
195 file_part = filename + len;
196 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
197 strcpyW( file_part, libname );
198 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
200 if (ext && !strchrW( file_part, '.' ))
202 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
203 return FALSE; /* too long */
204 strcatW( file_part, ext );
206 binary_info->type = BINARY_UNIX_LIB;
207 binary_info->flags = flags;
208 binary_info->res_start = NULL;
209 binary_info->res_end = NULL;
214 /***********************************************************************
217 * Open a specific exe file, taking load order into account.
218 * Returns the file handle or 0 for a builtin exe.
220 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
224 TRACE("looking for %s\n", debugstr_w(name) );
226 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
227 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
229 WCHAR buffer[MAX_PATH];
230 /* file doesn't exist, check for builtin */
231 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
234 else MODULE_get_binary_info( handle, binary_info );
240 /***********************************************************************
243 * Open an exe file, and return the full name and file handle.
244 * Returns FALSE if file could not be found.
245 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
246 * If file is a builtin exe, returns TRUE and sets handle to 0.
248 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
249 HANDLE *handle, struct binary_info *binary_info )
251 TRACE("looking for %s\n", debugstr_w(name) );
253 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ))
255 if (contains_path( name ) && get_builtin_path( name, exeW, buffer, buflen, binary_info ))
260 /* no builtin found, try native without extension in case it is a Unix app */
261 if (!SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
264 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
265 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
266 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
268 MODULE_get_binary_info( *handle, binary_info );
275 /***********************************************************************
276 * build_initial_environment
278 * Build the Win32 environment from the Unix environment
280 static BOOL build_initial_environment(void)
286 char **env = __wine_get_main_environment();
288 /* Compute the total size of the Unix environment */
289 for (e = env; *e; e++)
291 if (is_special_env_var( *e )) continue;
292 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
294 size *= sizeof(WCHAR);
296 /* Now allocate the environment */
298 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
299 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
302 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
303 endptr = p + size / sizeof(WCHAR);
305 /* And fill it with the Unix environment */
306 for (e = env; *e; e++)
310 /* skip Unix special variables and use the Wine variants instead */
311 if (!strncmp( str, "WINE", 4 ))
313 if (is_special_env_var( str + 4 )) str += 4;
314 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
316 else if (is_special_env_var( str )) continue; /* skip it */
318 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
326 /***********************************************************************
327 * set_registry_variables
329 * Set environment variables by enumerating the values of a key;
330 * helper for set_registry_environment().
331 * Note that Windows happily truncates the value if it's too big.
333 static void set_registry_variables( HANDLE hkey, ULONG type )
335 static const WCHAR pathW[] = {'P','A','T','H'};
336 static const WCHAR sep[] = {';',0};
337 UNICODE_STRING env_name, env_value;
341 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
344 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
347 tmp.MaximumLength = sizeof(tmpbuf);
349 for (index = 0; ; index++)
351 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
352 buffer, sizeof(buffer), &size );
353 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
355 if (info->Type != type)
357 env_name.Buffer = info->Name;
358 env_name.Length = env_name.MaximumLength = info->NameLength;
359 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
360 env_value.Length = info->DataLength;
361 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
362 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
363 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
364 if (!env_value.Length) continue;
365 if (info->Type == REG_EXPAND_SZ)
367 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
368 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
369 RtlCopyUnicodeString( &env_value, &tmp );
372 if (env_name.Length == sizeof(pathW) &&
373 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
374 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
376 RtlAppendUnicodeToString( &tmp, sep );
377 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
378 RtlCopyUnicodeString( &env_value, &tmp );
380 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
385 /***********************************************************************
386 * set_registry_environment
388 * Set the environment variables specified in the registry.
390 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
391 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
392 * on the order in which the variables are processed. But on Windows it
393 * does not really matter since they only use %SystemDrive% and
394 * %SystemRoot% which are predefined. But Wine defines these in the
395 * registry, so we need two passes.
397 static BOOL set_registry_environment( BOOL volatile_only )
399 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
400 'S','y','s','t','e','m','\\',
401 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
402 'C','o','n','t','r','o','l','\\',
403 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
404 'E','n','v','i','r','o','n','m','e','n','t',0};
405 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
406 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};
408 OBJECT_ATTRIBUTES attr;
409 UNICODE_STRING nameW;
413 attr.Length = sizeof(attr);
414 attr.RootDirectory = 0;
415 attr.ObjectName = &nameW;
417 attr.SecurityDescriptor = NULL;
418 attr.SecurityQualityOfService = NULL;
420 /* first the system environment variables */
421 RtlInitUnicodeString( &nameW, env_keyW );
422 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
424 set_registry_variables( hkey, REG_SZ );
425 set_registry_variables( hkey, REG_EXPAND_SZ );
430 /* then the ones for the current user */
431 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
432 RtlInitUnicodeString( &nameW, envW );
433 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
435 set_registry_variables( hkey, REG_SZ );
436 set_registry_variables( hkey, REG_EXPAND_SZ );
440 RtlInitUnicodeString( &nameW, volatile_envW );
441 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
443 set_registry_variables( hkey, REG_SZ );
444 set_registry_variables( hkey, REG_EXPAND_SZ );
448 NtClose( attr.RootDirectory );
453 /***********************************************************************
456 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
458 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
459 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
460 DWORD len, size = sizeof(buffer);
462 UNICODE_STRING nameW;
464 RtlInitUnicodeString( &nameW, name );
465 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
468 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
469 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
471 if (info->Type == REG_EXPAND_SZ)
473 UNICODE_STRING value, expanded;
475 value.MaximumLength = len * sizeof(WCHAR);
476 value.Buffer = (WCHAR *)info->Data;
477 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
478 value.Length = len * sizeof(WCHAR);
479 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
480 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
481 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
482 else RtlFreeUnicodeString( &expanded );
484 else if (info->Type == REG_SZ)
486 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
488 memcpy( ret, info->Data, len * sizeof(WCHAR) );
496 /***********************************************************************
497 * set_additional_environment
499 * Set some additional environment variables not specified in the registry.
501 static void set_additional_environment(void)
503 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
504 'S','o','f','t','w','a','r','e','\\',
505 'M','i','c','r','o','s','o','f','t','\\',
506 'W','i','n','d','o','w','s',' ','N','T','\\',
507 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
508 'P','r','o','f','i','l','e','L','i','s','t',0};
509 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
510 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
511 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
512 OBJECT_ATTRIBUTES attr;
513 UNICODE_STRING nameW;
514 WCHAR *profile_dir = NULL, *all_users_dir = NULL;
518 /* set the ALLUSERSPROFILE variables */
520 attr.Length = sizeof(attr);
521 attr.RootDirectory = 0;
522 attr.ObjectName = &nameW;
524 attr.SecurityDescriptor = NULL;
525 attr.SecurityQualityOfService = NULL;
526 RtlInitUnicodeString( &nameW, profile_keyW );
527 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
529 profile_dir = get_reg_value( hkey, profiles_valueW );
530 all_users_dir = get_reg_value( hkey, all_users_valueW );
534 if (profile_dir && all_users_dir)
538 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
539 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
540 strcpyW( value, profile_dir );
541 p = value + strlenW(value);
542 if (p > value && p[-1] != '\\') *p++ = '\\';
543 strcpyW( p, all_users_dir );
544 SetEnvironmentVariableW( allusersW, value );
545 HeapFree( GetProcessHeap(), 0, value );
548 HeapFree( GetProcessHeap(), 0, all_users_dir );
549 HeapFree( GetProcessHeap(), 0, profile_dir );
552 /***********************************************************************
553 * set_wow64_environment
555 * Set the environment variables that change across 32/64/Wow64.
557 static void set_wow64_environment(void)
559 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};
560 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};
561 static const WCHAR x86W[] = {'x','8','6',0};
562 static const WCHAR versionW[] = {'M','a','c','h','i','n','e','\\',
563 'S','o','f','t','w','a','r','e','\\',
564 'M','i','c','r','o','s','o','f','t','\\',
565 'W','i','n','d','o','w','s','\\',
566 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
567 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
568 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
569 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
570 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
571 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
572 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
573 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
574 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
576 OBJECT_ATTRIBUTES attr;
577 UNICODE_STRING nameW;
582 /* set the PROCESSOR_ARCHITECTURE variable */
584 if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
588 SetEnvironmentVariableW( archW, arch );
589 SetEnvironmentVariableW( arch6432W, NULL );
592 else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
596 SetEnvironmentVariableW( arch6432W, arch );
597 SetEnvironmentVariableW( archW, x86W );
601 attr.Length = sizeof(attr);
602 attr.RootDirectory = 0;
603 attr.ObjectName = &nameW;
605 attr.SecurityDescriptor = NULL;
606 attr.SecurityQualityOfService = NULL;
607 RtlInitUnicodeString( &nameW, versionW );
608 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
610 /* set the ProgramFiles variables */
612 if ((value = get_reg_value( hkey, progdirW )))
614 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
615 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
616 HeapFree( GetProcessHeap(), 0, value );
618 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
620 SetEnvironmentVariableW( progfilesW, value );
621 HeapFree( GetProcessHeap(), 0, value );
624 /* set the CommonProgramFiles variables */
626 if ((value = get_reg_value( hkey, commondirW )))
628 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
629 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
630 HeapFree( GetProcessHeap(), 0, value );
632 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
634 SetEnvironmentVariableW( commonfilesW, value );
635 HeapFree( GetProcessHeap(), 0, value );
641 /***********************************************************************
644 * Set the Wine library Unicode argv global variables.
646 static void set_library_wargv( char **argv )
654 for (argc = 0; argv[argc]; argc++)
655 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
657 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
658 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
659 p = (WCHAR *)(wargv + argc + 1);
660 for (argc = 0; argv[argc]; argc++)
662 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
669 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
671 for (argc = 0; wargv[argc]; argc++)
672 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
674 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
675 q = (char *)(argv + argc + 1);
676 for (argc = 0; wargv[argc]; argc++)
678 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
685 __wine_main_argc = argc;
686 __wine_main_argv = argv;
687 __wine_main_wargv = wargv;
691 /***********************************************************************
692 * update_library_argv0
694 * Update the argv[0] global variable with the binary we have found.
696 static void update_library_argv0( const WCHAR *argv0 )
698 DWORD len = strlenW( argv0 );
700 if (len > strlenW( __wine_main_wargv[0] ))
702 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
704 strcpyW( __wine_main_wargv[0], argv0 );
706 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
707 if (len > strlen( __wine_main_argv[0] ) + 1)
709 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
711 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
715 /***********************************************************************
718 * Build the command line of a process from the argv array.
720 * Note that it does NOT necessarily include the file name.
721 * Sometimes we don't even have any command line options at all.
723 * We must quote and escape characters so that the argv array can be rebuilt
724 * from the command line:
725 * - spaces and tabs must be quoted
727 * - quotes must be escaped
729 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
730 * resulting in an odd number of '\' followed by a '"'
733 * - '\'s that are not followed by a '"' can be left as is
737 static BOOL build_command_line( WCHAR **argv )
742 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
744 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
747 for (arg = argv; *arg; arg++)
749 int has_space,bcount;
755 if( !*a ) has_space=1;
760 if (*a==' ' || *a=='\t') {
762 } else if (*a=='"') {
763 /* doubling of '\' preceding a '"',
764 * plus escaping of said '"'
772 len+=(a-*arg)+1 /* for the separating space */;
774 len+=2; /* for the quotes */
777 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
780 p = rupp->CommandLine.Buffer;
781 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
782 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
783 for (arg = argv; *arg; arg++)
785 int has_space,has_quote;
788 /* Check for quotes and spaces in this argument */
789 has_space=has_quote=0;
791 if( !*a ) has_space=1;
793 if (*a==' ' || *a=='\t') {
797 } else if (*a=='"') {
805 /* Now transfer it to the command line */
821 /* Double all the '\\' preceding this '"', plus one */
822 for (i=0;i<=bcount;i++)
834 while ((*p=*x++)) p++;
840 if (p > rupp->CommandLine.Buffer)
841 p--; /* remove last space */
848 /***********************************************************************
849 * init_current_directory
851 * Initialize the current directory from the Unix cwd or the parent info.
853 static void init_current_directory( CURDIR *cur_dir )
855 UNICODE_STRING dir_str;
860 /* if we received a cur dir from the parent, try this first */
862 if (cur_dir->DosPath.Length)
864 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
867 /* now try to get it from the Unix cwd */
869 for (size = 256; ; size *= 2)
871 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
872 if (getcwd( cwd, size )) break;
873 HeapFree( GetProcessHeap(), 0, cwd );
874 if (errno == ERANGE) continue;
879 /* try to use PWD if it is valid, so that we don't resolve symlinks */
881 pwd = getenv( "PWD" );
884 struct stat st1, st2;
886 if (!pwd || stat( pwd, &st1 ) == -1 ||
887 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
893 ANSI_STRING unix_name;
894 UNICODE_STRING nt_name;
895 RtlInitAnsiString( &unix_name, pwd );
896 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
898 UNICODE_STRING dos_path;
899 /* skip the \??\ prefix, nt_name is 0 terminated */
900 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
901 RtlSetCurrentDirectory_U( &dos_path );
902 RtlFreeUnicodeString( &nt_name );
906 if (!cur_dir->DosPath.Length) /* still not initialized */
908 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
909 "starting in the Windows directory.\n", cwd ? cwd : "" );
910 RtlInitUnicodeString( &dir_str, DIR_Windows );
911 RtlSetCurrentDirectory_U( &dir_str );
913 HeapFree( GetProcessHeap(), 0, cwd );
916 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
917 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
921 /***********************************************************************
924 * Initialize the windows and system directories from the environment.
926 static void init_windows_dirs(void)
928 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
930 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
931 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
932 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
933 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
934 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
939 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
941 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
942 GetEnvironmentVariableW( windirW, buffer, len );
943 DIR_Windows = buffer;
945 else DIR_Windows = default_windirW;
947 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
949 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
950 GetEnvironmentVariableW( winsysdirW, buffer, len );
955 len = strlenW( DIR_Windows );
956 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
957 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
958 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
962 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
963 ERR( "directory %s could not be created, error %u\n",
964 debugstr_w(DIR_Windows), GetLastError() );
965 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
966 ERR( "directory %s could not be created, error %u\n",
967 debugstr_w(DIR_System), GetLastError() );
969 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
971 len = strlenW( DIR_Windows );
972 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
973 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
974 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
975 DIR_SysWow64 = buffer;
976 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
977 ERR( "directory %s could not be created, error %u\n",
978 debugstr_w(DIR_SysWow64), GetLastError() );
981 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
982 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
984 /* set the directories in ntdll too */
985 __wine_init_windows_dir( DIR_Windows, DIR_System );
989 /***********************************************************************
992 * Start the wineboot process if necessary. Return the handles to wait on.
994 static void start_wineboot( HANDLE handles[2] )
996 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
999 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
1001 ERR( "failed to create wineboot event, expect trouble\n" );
1004 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
1006 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1007 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1009 PROCESS_INFORMATION pi;
1011 WCHAR app[MAX_PATH];
1012 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1014 memset( &si, 0, sizeof(si) );
1016 si.dwFlags = STARTF_USESTDHANDLES;
1019 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1021 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1022 lstrcatW( app, wineboot );
1024 Wow64DisableWow64FsRedirection( &redir );
1025 strcpyW( cmdline, app );
1026 strcatW( cmdline, args );
1027 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1029 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1030 CloseHandle( pi.hThread );
1031 handles[1] = pi.hProcess;
1035 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1036 CloseHandle( handles[0] );
1039 Wow64RevertWow64FsRedirection( redir );
1045 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1046 __ASM_GLOBAL_FUNC( call_process_entry,
1048 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1049 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1050 "movl %esp,%ebp\n\t"
1051 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1052 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1054 "call *12(%ebp)\n\t"
1056 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1057 __ASM_CFI(".cfi_same_value %ebp\n\t")
1060 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1062 return entry( peb );
1066 /***********************************************************************
1069 * Startup routine of a new process. Runs on the new process stack.
1071 static DWORD WINAPI start_process( PEB *peb )
1073 IMAGE_NT_HEADERS *nt;
1074 LPTHREAD_START_ROUTINE entry;
1076 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1077 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1078 nt->OptionalHeader.AddressOfEntryPoint);
1080 if (!nt->OptionalHeader.AddressOfEntryPoint)
1082 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1083 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1087 if (TRACE_ON(relay))
1088 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1089 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1091 SetLastError( 0 ); /* clear error code */
1092 if (peb->BeingDebugged) DbgBreakPoint();
1093 return call_process_entry( peb, entry );
1097 /***********************************************************************
1100 * Change the process name in the ps output.
1102 static void set_process_name( int argc, char *argv[] )
1104 #ifdef HAVE_SETPROCTITLE
1105 setproctitle("-%s", argv[1]);
1110 char *p, *prctl_name = argv[1];
1111 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1114 # define PR_SET_NAME 15
1117 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1118 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1120 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1122 offset = argv[1] - argv[0];
1123 memmove( argv[1] - offset, argv[1], end - argv[1] );
1124 memset( end - offset, 0, offset );
1125 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1129 #endif /* HAVE_PRCTL */
1131 /* remove argv[0] */
1132 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1137 /***********************************************************************
1138 * __wine_kernel_init
1140 * Wine initialisation: load and start the main exe file.
1142 void CDECL __wine_kernel_init(void)
1144 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1145 static const WCHAR dotW[] = {'.',0};
1147 WCHAR *p, main_exe_name[MAX_PATH+1];
1148 PEB *peb = NtCurrentTeb()->Peb;
1149 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1150 HANDLE boot_events[2];
1151 BOOL got_environment = TRUE;
1153 /* Initialize everything */
1155 setbuf(stdout,NULL);
1156 setbuf(stderr,NULL);
1157 kernel32_handle = GetModuleHandleW(kernel32W);
1158 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1162 if (!params->Environment)
1164 /* Copy the parent environment */
1165 if (!build_initial_environment()) exit(1);
1167 /* convert old configuration to new format */
1168 convert_old_config();
1170 got_environment = set_registry_environment( FALSE );
1171 set_additional_environment();
1174 init_windows_dirs();
1175 init_current_directory( ¶ms->CurrentDirectory );
1177 set_process_name( __wine_main_argc, __wine_main_argv );
1178 set_library_wargv( __wine_main_argv );
1179 boot_events[0] = boot_events[1] = 0;
1181 if (peb->ProcessParameters->ImagePathName.Buffer)
1183 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1187 struct binary_info binary_info;
1189 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1190 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1192 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1193 ExitProcess( GetLastError() );
1195 update_library_argv0( main_exe_name );
1196 if (!build_command_line( __wine_main_wargv )) goto error;
1197 start_wineboot( boot_events );
1200 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1201 p = strrchrW( main_exe_name, '.' );
1202 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1204 TRACE( "starting process name=%s argv[0]=%s\n",
1205 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1207 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1208 MODULE_get_dll_load_path(main_exe_name) );
1212 DWORD timeout = 2 * 60 * 1000, count = 1;
1214 if (boot_events[1]) count++;
1215 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1216 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1217 ERR( "boot event wait timed out\n" );
1218 CloseHandle( boot_events[0] );
1219 if (boot_events[1]) CloseHandle( boot_events[1] );
1220 /* reload environment now that wineboot has run */
1221 set_registry_environment( got_environment );
1222 set_additional_environment();
1224 set_wow64_environment();
1226 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1231 DWORD error = GetLastError();
1233 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1234 if (error == ERROR_BAD_EXE_FORMAT ||
1235 error == ERROR_INVALID_ADDRESS ||
1236 error == ERROR_NOT_ENOUGH_MEMORY)
1238 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1239 /* if we get back here, it failed */
1241 else if (error == ERROR_MOD_NOT_FOUND)
1243 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1244 else p = main_exe_name;
1245 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1247 /* args 1 and 2 are --app-name full_path */
1248 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1249 debugstr_w(__wine_main_wargv[3]) );
1250 ExitProcess( ERROR_BAD_EXE_FORMAT );
1252 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1253 ExitProcess( ERROR_FILE_NOT_FOUND );
1255 args[0] = (DWORD_PTR)main_exe_name;
1256 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1257 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1258 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1259 MESSAGE( "wine: %s", msg );
1260 ExitProcess( error );
1263 LdrInitializeThunk( start_process, 0, 0, 0 );
1266 ExitProcess( GetLastError() );
1270 /***********************************************************************
1273 * Build an argv array from a command-line.
1274 * 'reserved' is the number of args to reserve before the first one.
1276 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1280 char *arg,*s,*d,*cmdline;
1281 int in_quotes,bcount,len;
1283 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1284 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1285 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1292 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1295 /* skip the remaining spaces */
1296 while (*s==' ' || *s=='\t') {
1303 } else if (*s=='\\') {
1304 /* '\', count them */
1306 } else if ((*s=='"') && ((bcount & 1)==0)) {
1308 in_quotes=!in_quotes;
1311 /* a regular character */
1316 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1318 HeapFree( GetProcessHeap(), 0, cmdline );
1322 arg = d = s = (char *)(argv + argc);
1323 memcpy( d, cmdline, len );
1328 if ((*s==' ' || *s=='\t') && !in_quotes) {
1329 /* Close the argument and copy it */
1333 /* skip the remaining spaces */
1336 } while (*s==' ' || *s=='\t');
1338 /* Start with a new argument */
1341 } else if (*s=='\\') {
1345 } else if (*s=='"') {
1347 if ((bcount & 1)==0) {
1348 /* Preceded by an even number of '\', this is half that
1349 * number of '\', plus a '"' which we discard.
1353 in_quotes=!in_quotes;
1355 /* Preceded by an odd number of '\', this is half that
1356 * number of '\' followed by a '"'
1364 /* a regular character */
1375 HeapFree( GetProcessHeap(), 0, cmdline );
1380 /***********************************************************************
1383 * Build the environment of a new child process.
1385 static char **build_envp( const WCHAR *envW )
1387 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1392 int count = 1, length;
1395 for (end = envW; *end; count++) end += strlenW(end) + 1;
1397 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1398 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1399 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1401 for (p = env; *p; p += strlen(p) + 1)
1402 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1404 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1406 if (!(p = getenv(unix_vars[i]))) continue;
1407 length += strlen(unix_vars[i]) + strlen(p) + 2;
1411 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1413 char **envptr = envp;
1414 char *dst = (char *)(envp + count);
1416 /* some variables must not be modified, so we get them directly from the unix env */
1417 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1419 if (!(p = getenv(unix_vars[i]))) continue;
1420 *envptr++ = strcpy( dst, unix_vars[i] );
1423 dst += strlen(dst) + 1;
1426 /* now put the Windows environment strings */
1427 for (p = env; *p; p += strlen(p) + 1)
1429 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1430 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1431 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1432 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1433 if (is_special_env_var( p )) /* prefix it with "WINE" */
1435 *envptr++ = strcpy( dst, "WINE" );
1440 *envptr++ = strcpy( dst, p );
1442 dst += strlen(dst) + 1;
1446 HeapFree( GetProcessHeap(), 0, env );
1451 /***********************************************************************
1454 * Fork and exec a new Unix binary, checking for errors.
1456 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1457 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1459 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1461 char **argv, **envp;
1463 if (!env) env = GetEnvironmentStringsW();
1466 if (pipe2( fd, O_CLOEXEC ) == -1)
1471 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1474 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1475 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1478 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1480 HANDLE hstdin, hstdout, hstderr;
1482 if (startup->dwFlags & STARTF_USESTDHANDLES)
1484 hstdin = startup->hStdInput;
1485 hstdout = startup->hStdOutput;
1486 hstderr = startup->hStdError;
1490 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1491 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1492 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1495 if (is_console_handle( hstdin ))
1496 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1497 if (is_console_handle( hstdout ))
1498 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1499 if (is_console_handle( hstderr ))
1500 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1501 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1502 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1503 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1506 argv = build_argv( cmdline, 0 );
1507 envp = build_envp( env );
1509 if (!(pid = fork())) /* child */
1511 if (!(pid = fork())) /* grandchild */
1515 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1517 int nullfd = open( "/dev/null", O_RDWR );
1519 /* close stdin and stdout */
1531 dup2( stdin_fd, 0 );
1534 if (stdout_fd != -1)
1536 dup2( stdout_fd, 1 );
1539 if (stderr_fd != -1)
1541 dup2( stderr_fd, 2 );
1546 /* Reset signals that we previously set to SIG_IGN */
1547 signal( SIGPIPE, SIG_DFL );
1549 if (newdir) chdir(newdir);
1551 if (argv && envp) execve( filename, argv, envp );
1554 if (pid <= 0) /* grandchild if exec failed or child if fork failed */
1557 write( fd[1], &err, sizeof(err) );
1561 _exit(0); /* child if fork succeeded */
1563 HeapFree( GetProcessHeap(), 0, argv );
1564 HeapFree( GetProcessHeap(), 0, envp );
1565 if (stdin_fd != -1) close( stdin_fd );
1566 if (stdout_fd != -1) close( stdout_fd );
1567 if (stderr_fd != -1) close( stderr_fd );
1573 err = waitpid(pid, NULL, 0);
1574 } while (err < 0 && errno == EINTR);
1576 if (read( fd[0], &err, sizeof(err) ) > 0) /* exec or second fork failed */
1582 if (pid == -1) FILE_SetDosError();
1588 static inline DWORD append_string( void **ptr, const WCHAR *str )
1590 DWORD len = strlenW( str );
1591 memcpy( *ptr, str, len * sizeof(WCHAR) );
1592 *ptr = (WCHAR *)*ptr + len;
1593 return len * sizeof(WCHAR);
1596 /***********************************************************************
1597 * create_startup_info
1599 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1600 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1601 const STARTUPINFOW *startup, DWORD *info_size )
1603 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1605 startup_info_t *info;
1608 UNICODE_STRING newdir;
1609 WCHAR imagepath[MAX_PATH];
1610 HANDLE hstdin, hstdout, hstderr;
1612 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1613 lstrcpynW( imagepath, filename, MAX_PATH );
1614 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1615 lstrcpynW( imagepath, filename, MAX_PATH );
1617 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1619 newdir.Buffer = NULL;
1622 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1623 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1629 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1630 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1632 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1634 title = startup->lpTitle ? startup->lpTitle : imagepath;
1636 size = sizeof(*info);
1637 size += strlenW( cur_dir ) * sizeof(WCHAR);
1638 size += cur_params->DllPath.Length;
1639 size += strlenW( imagepath ) * sizeof(WCHAR);
1640 size += strlenW( cmdline ) * sizeof(WCHAR);
1641 size += strlenW( title ) * sizeof(WCHAR);
1642 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1643 /* FIXME: shellinfo */
1644 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1645 size = (size + 1) & ~1;
1648 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1650 info->console_flags = cur_params->ConsoleFlags;
1651 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1652 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1654 if (startup->dwFlags & STARTF_USESTDHANDLES)
1656 hstdin = startup->hStdInput;
1657 hstdout = startup->hStdOutput;
1658 hstderr = startup->hStdError;
1662 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1663 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1664 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1666 info->hstdin = wine_server_obj_handle( hstdin );
1667 info->hstdout = wine_server_obj_handle( hstdout );
1668 info->hstderr = wine_server_obj_handle( hstderr );
1669 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1671 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1672 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1673 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1674 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1678 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1679 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1680 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1683 info->x = startup->dwX;
1684 info->y = startup->dwY;
1685 info->xsize = startup->dwXSize;
1686 info->ysize = startup->dwYSize;
1687 info->xchars = startup->dwXCountChars;
1688 info->ychars = startup->dwYCountChars;
1689 info->attribute = startup->dwFillAttribute;
1690 info->flags = startup->dwFlags;
1691 info->show = startup->wShowWindow;
1694 info->curdir_len = append_string( &ptr, cur_dir );
1695 info->dllpath_len = cur_params->DllPath.Length;
1696 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1697 ptr = (char *)ptr + cur_params->DllPath.Length;
1698 info->imagepath_len = append_string( &ptr, imagepath );
1699 info->cmdline_len = append_string( &ptr, cmdline );
1700 info->title_len = append_string( &ptr, title );
1701 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1702 if (startup->lpReserved2 && startup->cbReserved2)
1704 info->runtime_len = startup->cbReserved2;
1705 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1709 RtlFreeUnicodeString( &newdir );
1713 /***********************************************************************
1714 * get_alternate_loader
1716 * Get the name of the alternate (32 or 64 bit) Wine loader.
1718 static const char *get_alternate_loader( char **ret_env )
1721 const char *loader = NULL;
1722 const char *loader_env = getenv( "WINELOADER" );
1726 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1730 int len = strlen( loader_env );
1733 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1734 strcpy( env, "WINELOADER=" );
1735 strcat( env, loader_env );
1736 strcat( env, "64" );
1740 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1741 strcpy( env, "WINELOADER=" );
1742 strcat( env, loader_env );
1743 len += sizeof("WINELOADER=") - 1;
1744 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1748 if ((loader = strrchr( env, '/' ))) loader++;
1753 if (!loader) loader = is_win64 ? "wine" : "wine64";
1758 /***********************************************************************
1759 * terminate_main_thread
1761 * On some versions of Mac OS X, the execve system call fails with
1762 * ENOTSUP if the process has multiple threads. Wine is always multi-
1763 * threaded on Mac OS X because it specifically reserves the main thread
1764 * for use by the system frameworks (see apple_main_thread() in
1765 * libs/wine/loader.c). So, when we need to exec without first forking,
1766 * we need to terminate the main thread first. We do this by installing
1767 * a custom run loop source onto the main run loop and signaling it.
1768 * The source's "perform" callback is pthread_exit and it will be
1769 * executed on the main thread, terminating it.
1771 * Returns TRUE if there's still hope the main thread has terminated or
1772 * will soon. Return FALSE if we've given up.
1774 static BOOL terminate_main_thread(void)
1780 CFRunLoopSourceContext source_context = { 0 };
1781 CFRunLoopSourceRef source;
1783 source_context.perform = pthread_exit;
1784 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1787 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1788 CFRunLoopSourceSignal( source );
1789 CFRunLoopWakeUp( CFRunLoopGetMain() );
1790 CFRelease( source );
1798 usleep(delayms * 1000);
1805 /***********************************************************************
1808 static pid_t exec_loader( LPCWSTR cmd_line, unsigned int flags, int socketfd,
1809 int stdin_fd, int stdout_fd, const char *unixdir, char *winedebug,
1810 const struct binary_info *binary_info, int exec_only )
1813 char *wineloader = NULL;
1814 const char *loader = NULL;
1817 argv = build_argv( cmd_line, 1 );
1819 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1820 loader = get_alternate_loader( &wineloader );
1822 if (exec_only || !(pid = fork())) /* child */
1824 if (exec_only || !(pid = fork())) /* grandchild */
1826 char preloader_reserve[64], socket_env[64];
1828 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1830 int fd = open( "/dev/null", O_RDWR );
1832 /* close stdin and stdout */
1842 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1843 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1846 if (stdin_fd != -1) close( stdin_fd );
1847 if (stdout_fd != -1) close( stdout_fd );
1849 /* Reset signals that we previously set to SIG_IGN */
1850 signal( SIGPIPE, SIG_DFL );
1852 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
1853 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1854 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1856 putenv( preloader_reserve );
1857 putenv( socket_env );
1858 if (winedebug) putenv( winedebug );
1859 if (wineloader) putenv( wineloader );
1860 if (unixdir) chdir(unixdir);
1866 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1869 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1885 wret = waitpid(pid, NULL, 0);
1886 } while (wret < 0 && errno == EINTR);
1889 HeapFree( GetProcessHeap(), 0, wineloader );
1890 HeapFree( GetProcessHeap(), 0, argv );
1894 /***********************************************************************
1897 * Create a new process. If hFile is a valid handle we have an exe
1898 * file, otherwise it is a Winelib app.
1900 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1901 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1902 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1903 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1904 const struct binary_info *binary_info, int exec_only )
1906 BOOL ret, success = FALSE;
1907 HANDLE process_info;
1909 char *winedebug = NULL;
1910 startup_info_t *startup_info;
1911 DWORD startup_info_size;
1912 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1916 if (!is_win64 && !is_wow64 && (binary_info->flags & BINARY_FLAG_64BIT))
1918 ERR( "starting 64-bit process %s not supported in 32-bit wineprefix\n", debugstr_w(filename) );
1919 SetLastError( ERROR_BAD_EXE_FORMAT );
1923 /* create the socket for the new process */
1925 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1927 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1931 if (exec_only) /* things are much simpler in this case */
1933 wine_server_send_fd( socketfd[1] );
1934 close( socketfd[1] );
1935 SERVER_START_REQ( new_process )
1937 req->create_flags = flags;
1938 req->socket_fd = socketfd[1];
1939 req->exe_file = wine_server_obj_handle( hFile );
1940 ret = !wine_server_call_err( req );
1944 if (ret) exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
1945 winedebug, binary_info, TRUE );
1947 close( socketfd[0] );
1951 RtlAcquirePebLock();
1953 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1954 &startup_info_size )))
1956 RtlReleasePebLock();
1957 close( socketfd[0] );
1958 close( socketfd[1] );
1961 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
1965 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1966 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1968 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1969 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1970 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1972 env_end += strlenW(env_end) + 1;
1976 wine_server_send_fd( socketfd[1] );
1977 close( socketfd[1] );
1979 /* create the process on the server side */
1981 SERVER_START_REQ( new_process )
1983 req->inherit_all = inherit;
1984 req->create_flags = flags;
1985 req->socket_fd = socketfd[1];
1986 req->exe_file = wine_server_obj_handle( hFile );
1987 req->process_access = PROCESS_ALL_ACCESS;
1988 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1989 req->thread_access = THREAD_ALL_ACCESS;
1990 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1991 req->info_size = startup_info_size;
1993 wine_server_add_data( req, startup_info, startup_info_size );
1994 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
1995 if ((ret = !wine_server_call_err( req )))
1997 info->dwProcessId = (DWORD)reply->pid;
1998 info->dwThreadId = (DWORD)reply->tid;
1999 info->hProcess = wine_server_ptr_handle( reply->phandle );
2000 info->hThread = wine_server_ptr_handle( reply->thandle );
2002 process_info = wine_server_ptr_handle( reply->info );
2006 RtlReleasePebLock();
2009 close( socketfd[0] );
2010 HeapFree( GetProcessHeap(), 0, startup_info );
2011 HeapFree( GetProcessHeap(), 0, winedebug );
2015 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
2017 if (startup_info->hstdin)
2018 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
2019 FILE_READ_DATA, &stdin_fd, NULL );
2020 if (startup_info->hstdout)
2021 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
2022 FILE_WRITE_DATA, &stdout_fd, NULL );
2024 HeapFree( GetProcessHeap(), 0, startup_info );
2026 /* create the child process */
2028 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2029 winedebug, binary_info, FALSE );
2031 if (stdin_fd != -1) close( stdin_fd );
2032 if (stdout_fd != -1) close( stdout_fd );
2033 close( socketfd[0] );
2034 HeapFree( GetProcessHeap(), 0, winedebug );
2041 /* wait for the new process info to be ready */
2043 WaitForSingleObject( process_info, INFINITE );
2044 SERVER_START_REQ( get_new_process_info )
2046 req->info = wine_server_obj_handle( process_info );
2047 wine_server_call( req );
2048 success = reply->success;
2049 err = reply->exit_code;
2055 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2058 CloseHandle( process_info );
2062 CloseHandle( process_info );
2063 CloseHandle( info->hProcess );
2064 CloseHandle( info->hThread );
2065 info->hProcess = info->hThread = 0;
2066 info->dwProcessId = info->dwThreadId = 0;
2071 /***********************************************************************
2072 * create_vdm_process
2074 * Create a new VDM process for a 16-bit or DOS application.
2076 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2077 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2078 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2079 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2080 const struct binary_info *binary_info, int exec_only )
2082 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2085 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
2086 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
2090 SetLastError( ERROR_OUTOFMEMORY );
2093 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
2094 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2095 flags, startup, info, unixdir, binary_info, exec_only );
2096 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2101 /***********************************************************************
2102 * create_cmd_process
2104 * Create a new cmd shell process for a .BAT file.
2106 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2107 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2108 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2109 LPPROCESS_INFORMATION info )
2112 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2113 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2114 WCHAR comspec[MAX_PATH];
2118 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2120 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2121 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2124 strcpyW( newcmdline, comspec );
2125 strcatW( newcmdline, slashcW );
2126 strcatW( newcmdline, cmd_line );
2127 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2128 flags, env, cur_dir, startup, info );
2129 HeapFree( GetProcessHeap(), 0, newcmdline );
2134 /*************************************************************************
2137 * Helper for CreateProcess: retrieve the file name to load from the
2138 * app name and command line. Store the file name in buffer, and
2139 * return a possibly modified command line.
2140 * Also returns a handle to the opened file if it's a Windows binary.
2142 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2143 int buflen, HANDLE *handle, struct binary_info *binary_info )
2145 static const WCHAR quotesW[] = {'"','%','s','"',0};
2147 WCHAR *name, *pos, *first_space, *ret = NULL;
2150 /* if we have an app name, everything is easy */
2154 /* use the unmodified app name as file name */
2155 lstrcpynW( buffer, appname, buflen );
2156 *handle = open_exe_file( buffer, binary_info );
2157 if (!(ret = cmdline) || !cmdline[0])
2159 /* no command-line, create one */
2160 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2161 sprintfW( ret, quotesW, appname );
2166 /* first check for a quoted file name */
2168 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2170 int len = p - cmdline - 1;
2171 /* extract the quoted portion as file name */
2172 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2173 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2176 if (!find_exe_file( name, buffer, buflen, handle, binary_info ))
2178 if (!get_builtin_path( name, exeW, buffer, buflen, binary_info )) goto done;
2181 ret = cmdline; /* no change necessary */
2185 /* now try the command-line word by word */
2187 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2195 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2197 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2202 if (!first_space) first_space = pos;
2203 if (!(*pos++ = *p++)) break;
2208 if (first_space) *first_space = 0; /* try only the first word as a builtin */
2209 if (get_builtin_path( name, exeW, buffer, buflen, binary_info ))
2214 else SetLastError( ERROR_FILE_NOT_FOUND );
2216 else if (first_space) /* build a new command-line with quotes */
2218 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2220 sprintfW( ret, quotesW, name );
2225 HeapFree( GetProcessHeap(), 0, name );
2230 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2231 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2232 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2233 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2234 LPPROCESS_INFORMATION info )
2238 char *unixdir = NULL;
2239 WCHAR name[MAX_PATH];
2240 WCHAR *tidy_cmdline, *p, *envW = env;
2241 struct binary_info binary_info;
2243 /* Process the AppName and/or CmdLine to get module name and path */
2245 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2247 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2248 &hFile, &binary_info )))
2250 if (hFile == INVALID_HANDLE_VALUE) goto done;
2252 /* Warn if unsupported features are used */
2254 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2255 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2256 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2257 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2258 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2262 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2264 SetLastError(ERROR_DIRECTORY);
2270 WCHAR buf[MAX_PATH];
2271 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2274 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2279 while (*e) e += strlen(e) + 1;
2280 e++; /* final null */
2281 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, NULL, 0 );
2282 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2283 MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, envW, lenW );
2284 flags |= CREATE_UNICODE_ENVIRONMENT;
2287 info->hThread = info->hProcess = 0;
2288 info->dwProcessId = info->dwThreadId = 0;
2290 if (binary_info.flags & BINARY_FLAG_DLL)
2292 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2293 SetLastError( ERROR_BAD_EXE_FORMAT );
2295 else switch (binary_info.type)
2298 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2299 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2300 binary_info.res_start, binary_info.res_end );
2301 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2302 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2307 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2308 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2309 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2311 case BINARY_UNIX_LIB:
2312 TRACE( "starting %s as %d-bit Winelib app\n",
2313 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2314 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2315 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2317 case BINARY_UNKNOWN:
2318 /* check for .com or .bat extension */
2319 if ((p = strrchrW( name, '.' )))
2321 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2323 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2324 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2325 inherit, flags, startup_info, info, unixdir,
2326 &binary_info, FALSE );
2329 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2331 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2332 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2333 inherit, flags, startup_info, info );
2338 case BINARY_UNIX_EXE:
2340 /* unknown file, try as unix executable */
2343 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2345 if ((unix_name = wine_get_unix_file_name( name )))
2347 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2348 HeapFree( GetProcessHeap(), 0, unix_name );
2353 if (hFile) CloseHandle( hFile );
2356 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2357 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2358 HeapFree( GetProcessHeap(), 0, unixdir );
2360 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2365 /**********************************************************************
2366 * CreateProcessA (KERNEL32.@)
2368 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2369 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2370 DWORD flags, LPVOID env, LPCSTR cur_dir,
2371 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2374 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2375 UNICODE_STRING desktopW, titleW;
2378 desktopW.Buffer = NULL;
2379 titleW.Buffer = NULL;
2380 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2381 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2382 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2384 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2385 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2387 memcpy( &infoW, startup_info, sizeof(infoW) );
2388 infoW.lpDesktop = desktopW.Buffer;
2389 infoW.lpTitle = titleW.Buffer;
2391 if (startup_info->lpReserved)
2392 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2393 debugstr_a(startup_info->lpReserved));
2395 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2396 inherit, flags, env, cur_dirW, &infoW, info );
2398 HeapFree( GetProcessHeap(), 0, app_nameW );
2399 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2400 HeapFree( GetProcessHeap(), 0, cur_dirW );
2401 RtlFreeUnicodeString( &desktopW );
2402 RtlFreeUnicodeString( &titleW );
2407 /**********************************************************************
2408 * CreateProcessW (KERNEL32.@)
2410 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2411 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2412 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2413 LPPROCESS_INFORMATION info )
2415 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2416 inherit, flags, env, cur_dir, startup_info, info);
2420 /**********************************************************************
2423 static void exec_process( LPCWSTR name )
2427 STARTUPINFOW startup_info;
2428 PROCESS_INFORMATION info;
2429 struct binary_info binary_info;
2431 hFile = open_exe_file( name, &binary_info );
2432 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2434 memset( &startup_info, 0, sizeof(startup_info) );
2435 startup_info.cb = sizeof(startup_info);
2437 /* Determine executable type */
2439 if (binary_info.flags & BINARY_FLAG_DLL) return;
2440 switch (binary_info.type)
2443 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2444 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2445 binary_info.res_start, binary_info.res_end );
2446 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2447 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2449 case BINARY_UNIX_LIB:
2450 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2451 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2452 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2454 case BINARY_UNKNOWN:
2455 /* check for .com or .pif extension */
2456 if (!(p = strrchrW( name, '.' ))) break;
2457 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2462 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2463 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2464 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2469 CloseHandle( hFile );
2473 /***********************************************************************
2476 * Wrapper to call WaitForInputIdle USER function
2478 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2480 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2482 HMODULE mod = GetModuleHandleA( "user32.dll" );
2485 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2486 if (ptr) return ptr( process, timeout );
2492 /***********************************************************************
2493 * WinExec (KERNEL32.@)
2495 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2497 PROCESS_INFORMATION info;
2498 STARTUPINFOA startup;
2502 memset( &startup, 0, sizeof(startup) );
2503 startup.cb = sizeof(startup);
2504 startup.dwFlags = STARTF_USESHOWWINDOW;
2505 startup.wShowWindow = nCmdShow;
2507 /* cmdline needs to be writable for CreateProcess */
2508 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2509 strcpy( cmdline, lpCmdLine );
2511 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2512 0, NULL, NULL, &startup, &info ))
2514 /* Give 30 seconds to the app to come up */
2515 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2516 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2518 /* Close off the handles */
2519 CloseHandle( info.hThread );
2520 CloseHandle( info.hProcess );
2522 else if ((ret = GetLastError()) >= 32)
2524 FIXME("Strange error set by CreateProcess: %d\n", ret );
2527 HeapFree( GetProcessHeap(), 0, cmdline );
2532 /**********************************************************************
2533 * LoadModule (KERNEL32.@)
2535 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2537 LOADPARMS32 *params = paramBlock;
2538 PROCESS_INFORMATION info;
2539 STARTUPINFOA startup;
2542 char filename[MAX_PATH];
2545 if (!name) return ERROR_FILE_NOT_FOUND;
2547 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2548 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2549 return GetLastError();
2551 len = (BYTE)params->lpCmdLine[0];
2552 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2553 return ERROR_NOT_ENOUGH_MEMORY;
2555 strcpy( cmdline, filename );
2556 p = cmdline + strlen(cmdline);
2558 memcpy( p, params->lpCmdLine + 1, len );
2561 memset( &startup, 0, sizeof(startup) );
2562 startup.cb = sizeof(startup);
2563 if (params->lpCmdShow)
2565 startup.dwFlags = STARTF_USESHOWWINDOW;
2566 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2569 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2570 params->lpEnvAddress, NULL, &startup, &info ))
2572 /* Give 30 seconds to the app to come up */
2573 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2574 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2576 /* Close off the handles */
2577 CloseHandle( info.hThread );
2578 CloseHandle( info.hProcess );
2580 else if ((ret = GetLastError()) >= 32)
2582 FIXME("Strange error set by CreateProcess: %u\n", ret );
2586 HeapFree( GetProcessHeap(), 0, cmdline );
2591 /******************************************************************************
2592 * TerminateProcess (KERNEL32.@)
2594 * Terminates a process.
2597 * handle [I] Process to terminate.
2598 * exit_code [I] Exit code.
2602 * Failure: FALSE, check GetLastError().
2604 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2606 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2607 if (status) SetLastError( RtlNtStatusToDosError(status) );
2611 /***********************************************************************
2612 * ExitProcess (KERNEL32.@)
2614 * Exits the current process.
2617 * status [I] Status code to exit with.
2623 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2625 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2626 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2627 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2629 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2633 void WINAPI process_ExitProcess( DWORD status )
2635 LdrShutdownProcess();
2636 NtTerminateProcess(GetCurrentProcess(), status);
2642 void WINAPI ExitProcess( DWORD status )
2644 LdrShutdownProcess();
2645 NtTerminateProcess(GetCurrentProcess(), status);
2651 /***********************************************************************
2652 * GetExitCodeProcess [KERNEL32.@]
2654 * Gets termination status of specified process.
2657 * hProcess [in] Handle to the process.
2658 * lpExitCode [out] Address to receive termination status.
2664 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2667 PROCESS_BASIC_INFORMATION pbi;
2669 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2671 if (status == STATUS_SUCCESS)
2673 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2676 SetLastError( RtlNtStatusToDosError(status) );
2681 /***********************************************************************
2682 * SetErrorMode (KERNEL32.@)
2684 UINT WINAPI SetErrorMode( UINT mode )
2688 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2689 &old, sizeof(old), NULL );
2690 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2691 &mode, sizeof(mode) );
2695 /***********************************************************************
2696 * GetErrorMode (KERNEL32.@)
2698 UINT WINAPI GetErrorMode( void )
2702 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2703 &mode, sizeof(mode), NULL );
2707 /**********************************************************************
2708 * TlsAlloc [KERNEL32.@]
2710 * Allocates a thread local storage index.
2713 * Success: TLS index.
2714 * Failure: 0xFFFFFFFF
2716 DWORD WINAPI TlsAlloc( void )
2719 PEB * const peb = NtCurrentTeb()->Peb;
2721 RtlAcquirePebLock();
2722 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2723 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2726 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2729 if (!NtCurrentTeb()->TlsExpansionSlots &&
2730 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2731 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2733 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2735 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2739 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2740 index += TLS_MINIMUM_AVAILABLE;
2743 else SetLastError( ERROR_NO_MORE_ITEMS );
2745 RtlReleasePebLock();
2750 /**********************************************************************
2751 * TlsFree [KERNEL32.@]
2753 * Releases a thread local storage index, making it available for reuse.
2756 * index [in] TLS index to free.
2762 BOOL WINAPI TlsFree( DWORD index )
2766 RtlAcquirePebLock();
2767 if (index >= TLS_MINIMUM_AVAILABLE)
2769 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2770 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2774 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2775 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2777 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2778 else SetLastError( ERROR_INVALID_PARAMETER );
2779 RtlReleasePebLock();
2784 /**********************************************************************
2785 * TlsGetValue [KERNEL32.@]
2787 * Gets value in a thread's TLS slot.
2790 * index [in] TLS index to retrieve value for.
2793 * Success: Value stored in calling thread's TLS slot for index.
2794 * Failure: 0 and GetLastError() returns NO_ERROR.
2796 LPVOID WINAPI TlsGetValue( DWORD index )
2800 if (index < TLS_MINIMUM_AVAILABLE)
2802 ret = NtCurrentTeb()->TlsSlots[index];
2806 index -= TLS_MINIMUM_AVAILABLE;
2807 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2809 SetLastError( ERROR_INVALID_PARAMETER );
2812 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2813 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2815 SetLastError( ERROR_SUCCESS );
2820 /**********************************************************************
2821 * TlsSetValue [KERNEL32.@]
2823 * Stores a value in the thread's TLS slot.
2826 * index [in] TLS index to set value for.
2827 * value [in] Value to be stored.
2833 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2835 if (index < TLS_MINIMUM_AVAILABLE)
2837 NtCurrentTeb()->TlsSlots[index] = value;
2841 index -= TLS_MINIMUM_AVAILABLE;
2842 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2844 SetLastError( ERROR_INVALID_PARAMETER );
2847 if (!NtCurrentTeb()->TlsExpansionSlots &&
2848 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2849 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2851 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2854 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2860 /***********************************************************************
2861 * GetProcessFlags (KERNEL32.@)
2863 DWORD WINAPI GetProcessFlags( DWORD processid )
2865 IMAGE_NT_HEADERS *nt;
2868 if (processid && processid != GetCurrentProcessId()) return 0;
2870 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2872 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2873 flags |= PDB32_CONSOLE_PROC;
2875 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2876 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2881 /*********************************************************************
2882 * OpenProcess (KERNEL32.@)
2884 * Opens a handle to a process.
2887 * access [I] Desired access rights assigned to the returned handle.
2888 * inherit [I] Determines whether or not child processes will inherit the handle.
2889 * id [I] Process identifier of the process to get a handle to.
2892 * Success: Valid handle to the specified process.
2893 * Failure: NULL, check GetLastError().
2895 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2899 OBJECT_ATTRIBUTES attr;
2902 cid.UniqueProcess = ULongToHandle(id);
2903 cid.UniqueThread = 0; /* FIXME ? */
2905 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2906 attr.RootDirectory = NULL;
2907 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2908 attr.SecurityDescriptor = NULL;
2909 attr.SecurityQualityOfService = NULL;
2910 attr.ObjectName = NULL;
2912 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2914 status = NtOpenProcess(&handle, access, &attr, &cid);
2915 if (status != STATUS_SUCCESS)
2917 SetLastError( RtlNtStatusToDosError(status) );
2924 /*********************************************************************
2925 * GetProcessId (KERNEL32.@)
2927 * Gets the a unique identifier of a process.
2930 * hProcess [I] Handle to the process.
2934 * Failure: FALSE, check GetLastError().
2938 * The identifier is unique only on the machine and only until the process
2939 * exits (including system shutdown).
2941 DWORD WINAPI GetProcessId( HANDLE hProcess )
2944 PROCESS_BASIC_INFORMATION pbi;
2946 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2948 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2949 SetLastError( RtlNtStatusToDosError(status) );
2954 /*********************************************************************
2955 * CloseHandle (KERNEL32.@)
2960 * handle [I] Handle to close.
2964 * Failure: FALSE, check GetLastError().
2966 BOOL WINAPI CloseHandle( HANDLE handle )
2970 /* stdio handles need special treatment */
2971 if (handle == (HANDLE)STD_INPUT_HANDLE)
2972 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
2973 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
2974 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
2975 else if (handle == (HANDLE)STD_ERROR_HANDLE)
2976 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
2978 if (is_console_handle(handle))
2979 return CloseConsoleHandle(handle);
2981 status = NtClose( handle );
2982 if (status) SetLastError( RtlNtStatusToDosError(status) );
2987 /*********************************************************************
2988 * GetHandleInformation (KERNEL32.@)
2990 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2992 OBJECT_DATA_INFORMATION info;
2993 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2995 if (status) SetLastError( RtlNtStatusToDosError(status) );
2999 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3000 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3006 /*********************************************************************
3007 * SetHandleInformation (KERNEL32.@)
3009 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3011 OBJECT_DATA_INFORMATION info;
3014 /* if not setting both fields, retrieve current value first */
3015 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3016 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3018 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3020 SetLastError( RtlNtStatusToDosError(status) );
3024 if (mask & HANDLE_FLAG_INHERIT)
3025 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3026 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3027 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3029 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3030 if (status) SetLastError( RtlNtStatusToDosError(status) );
3035 /*********************************************************************
3036 * DuplicateHandle (KERNEL32.@)
3038 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3039 HANDLE dest_process, HANDLE *dest,
3040 DWORD access, BOOL inherit, DWORD options )
3044 if (is_console_handle(source))
3046 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3047 if (source_process != dest_process ||
3048 source_process != GetCurrentProcess())
3050 SetLastError(ERROR_INVALID_PARAMETER);
3053 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3054 return (*dest != INVALID_HANDLE_VALUE);
3056 status = NtDuplicateObject( source_process, source, dest_process, dest,
3057 access, inherit ? OBJ_INHERIT : 0, options );
3058 if (status) SetLastError( RtlNtStatusToDosError(status) );
3063 /***********************************************************************
3064 * ConvertToGlobalHandle (KERNEL32.@)
3066 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3068 HANDLE ret = INVALID_HANDLE_VALUE;
3069 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3070 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3075 /***********************************************************************
3076 * SetHandleContext (KERNEL32.@)
3078 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3080 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3081 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3082 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3087 /***********************************************************************
3088 * GetHandleContext (KERNEL32.@)
3090 DWORD WINAPI GetHandleContext(HANDLE hnd)
3092 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3093 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3094 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3099 /***********************************************************************
3100 * CreateSocketHandle (KERNEL32.@)
3102 HANDLE WINAPI CreateSocketHandle(void)
3104 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3105 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3106 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3107 return INVALID_HANDLE_VALUE;
3111 /***********************************************************************
3112 * SetPriorityClass (KERNEL32.@)
3114 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3117 PROCESS_PRIORITY_CLASS ppc;
3119 ppc.Foreground = FALSE;
3120 switch (priorityclass)
3122 case IDLE_PRIORITY_CLASS:
3123 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3124 case BELOW_NORMAL_PRIORITY_CLASS:
3125 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3126 case NORMAL_PRIORITY_CLASS:
3127 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3128 case ABOVE_NORMAL_PRIORITY_CLASS:
3129 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3130 case HIGH_PRIORITY_CLASS:
3131 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3132 case REALTIME_PRIORITY_CLASS:
3133 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3135 SetLastError(ERROR_INVALID_PARAMETER);
3139 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3142 if (status != STATUS_SUCCESS)
3144 SetLastError( RtlNtStatusToDosError(status) );
3151 /***********************************************************************
3152 * GetPriorityClass (KERNEL32.@)
3154 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3157 PROCESS_BASIC_INFORMATION pbi;
3159 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3161 if (status != STATUS_SUCCESS)
3163 SetLastError( RtlNtStatusToDosError(status) );
3166 switch (pbi.BasePriority)
3168 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3169 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3170 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3171 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3172 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3173 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3175 SetLastError( ERROR_INVALID_PARAMETER );
3180 /***********************************************************************
3181 * SetProcessAffinityMask (KERNEL32.@)
3183 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3187 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3188 &affmask, sizeof(DWORD_PTR));
3191 SetLastError( RtlNtStatusToDosError(status) );
3198 /**********************************************************************
3199 * GetProcessAffinityMask (KERNEL32.@)
3201 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3203 NTSTATUS status = STATUS_SUCCESS;
3205 if (system_mask) *system_mask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
3208 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3209 process_mask, sizeof(*process_mask), NULL )))
3210 SetLastError( RtlNtStatusToDosError(status) );
3216 /***********************************************************************
3217 * GetProcessVersion (KERNEL32.@)
3219 DWORD WINAPI GetProcessVersion( DWORD pid )
3223 PROCESS_BASIC_INFORMATION pbi;
3226 IMAGE_DOS_HEADER dos;
3227 IMAGE_NT_HEADERS nt;
3230 if (!pid || pid == GetCurrentProcessId())
3232 IMAGE_NT_HEADERS *pnt;
3234 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3235 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3236 pnt->OptionalHeader.MinorSubsystemVersion);
3240 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3241 if (!process) return 0;
3243 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3244 if (status) goto err;
3246 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3247 if (status || count != sizeof(peb)) goto err;
3249 memset(&dos, 0, sizeof(dos));
3250 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3251 if (status || count != sizeof(dos)) goto err;
3252 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3254 memset(&nt, 0, sizeof(nt));
3255 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3256 if (status || count != sizeof(nt)) goto err;
3257 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3259 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3262 CloseHandle(process);
3264 if (status != STATUS_SUCCESS)
3265 SetLastError(RtlNtStatusToDosError(status));
3271 /***********************************************************************
3272 * SetProcessWorkingSetSize [KERNEL32.@]
3273 * Sets the min/max working set sizes for a specified process.
3276 * hProcess [I] Handle to the process of interest
3277 * minset [I] Specifies minimum working set size
3278 * maxset [I] Specifies maximum working set size
3284 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3287 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3288 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3289 /* Trim the working set to zero */
3290 /* Swap the process out of physical RAM */
3295 /***********************************************************************
3296 * K32EmptyWorkingSet (KERNEL32.@)
3298 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3300 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3303 /***********************************************************************
3304 * GetProcessWorkingSetSize (KERNEL32.@)
3306 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3309 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3310 /* 32 MB working set size */
3311 if (minset) *minset = 32*1024*1024;
3312 if (maxset) *maxset = 32*1024*1024;
3317 /***********************************************************************
3318 * SetProcessShutdownParameters (KERNEL32.@)
3320 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3322 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3323 shutdown_flags = flags;
3324 shutdown_priority = level;
3329 /***********************************************************************
3330 * GetProcessShutdownParameters (KERNEL32.@)
3333 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3335 *lpdwLevel = shutdown_priority;
3336 *lpdwFlags = shutdown_flags;
3341 /***********************************************************************
3342 * GetProcessPriorityBoost (KERNEL32.@)
3344 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3346 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3348 /* Report that no boost is present.. */
3349 *pDisablePriorityBoost = FALSE;
3354 /***********************************************************************
3355 * SetProcessPriorityBoost (KERNEL32.@)
3357 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3359 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3360 /* Say we can do it. I doubt the program will notice that we don't. */
3365 /***********************************************************************
3366 * ReadProcessMemory (KERNEL32.@)
3368 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3369 SIZE_T *bytes_read )
3371 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3372 if (status) SetLastError( RtlNtStatusToDosError(status) );
3377 /***********************************************************************
3378 * WriteProcessMemory (KERNEL32.@)
3380 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3381 SIZE_T *bytes_written )
3383 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3384 if (status) SetLastError( RtlNtStatusToDosError(status) );
3389 /****************************************************************************
3390 * FlushInstructionCache (KERNEL32.@)
3392 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3395 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3396 if (status) SetLastError( RtlNtStatusToDosError(status) );
3401 /******************************************************************
3402 * GetProcessIoCounters (KERNEL32.@)
3404 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3408 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3409 ioc, sizeof(*ioc), NULL);
3410 if (status) SetLastError( RtlNtStatusToDosError(status) );
3414 /******************************************************************
3415 * GetProcessHandleCount (KERNEL32.@)
3417 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3421 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3422 cnt, sizeof(*cnt), NULL);
3423 if (status) SetLastError( RtlNtStatusToDosError(status) );
3427 /******************************************************************
3428 * QueryFullProcessImageNameA (KERNEL32.@)
3430 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3433 DWORD pdwSizeW = *pdwSize;
3434 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3436 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3439 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3440 lpExeName, *pdwSize, NULL, NULL));
3442 *pdwSize = strlen(lpExeName);
3444 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3448 /******************************************************************
3449 * QueryFullProcessImageNameW (KERNEL32.@)
3451 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3453 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3454 UNICODE_STRING *dynamic_buffer = NULL;
3455 UNICODE_STRING *result = NULL;
3459 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3460 * is a DOS path and we depend on this. */
3461 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3462 sizeof(buffer) - sizeof(WCHAR), &needed);
3463 if (status == STATUS_INFO_LENGTH_MISMATCH)
3465 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3466 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3467 result = dynamic_buffer;
3470 result = (PUNICODE_STRING)buffer;
3472 if (status) goto cleanup;
3474 if (dwFlags & PROCESS_NAME_NATIVE)
3478 DWORD ntlen, devlen;
3480 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3482 /* We cannot convert it to an NT device path so fail */
3483 status = STATUS_NO_SUCH_DEVICE;
3487 /* Find this drive's NT device path */
3488 drive[0] = result->Buffer[0];
3491 if (!QueryDosDeviceW(drive, device, sizeof(device)/sizeof(*device)))
3493 status = STATUS_NO_SUCH_DEVICE;
3497 devlen = lstrlenW(device);
3498 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3499 if (ntlen + 1 > *pdwSize)
3501 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3506 memcpy(lpExeName, device, devlen * sizeof(*device));
3507 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3508 lpExeName[*pdwSize] = 0;
3509 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3513 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3515 status = STATUS_BUFFER_TOO_SMALL;
3519 *pdwSize = result->Length/sizeof(WCHAR);
3520 memcpy( lpExeName, result->Buffer, result->Length );
3521 lpExeName[*pdwSize] = 0;
3525 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3526 if (status) SetLastError( RtlNtStatusToDosError(status) );
3530 /***********************************************************************
3531 * K32GetProcessImageFileNameA (KERNEL32.@)
3533 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3535 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3538 /***********************************************************************
3539 * K32GetProcessImageFileNameW (KERNEL32.@)
3541 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3543 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3546 /***********************************************************************
3547 * K32EnumProcesses (KERNEL32.@)
3549 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3551 SYSTEM_PROCESS_INFORMATION *spi;
3552 ULONG size = 0x4000;
3558 HeapFree(GetProcessHeap(), 0, buf);
3559 buf = HeapAlloc(GetProcessHeap(), 0, size);
3563 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3564 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3566 if (status != STATUS_SUCCESS)
3568 HeapFree(GetProcessHeap(), 0, buf);
3569 SetLastError(RtlNtStatusToDosError(status));
3575 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3577 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3578 *lpcbUsed += sizeof(DWORD);
3580 if (spi->NextEntryOffset == 0)
3583 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3586 HeapFree(GetProcessHeap(), 0, buf);
3590 /***********************************************************************
3591 * K32QueryWorkingSet (KERNEL32.@)
3593 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3597 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3599 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3603 SetLastError( RtlNtStatusToDosError( status ) );
3609 /***********************************************************************
3610 * K32QueryWorkingSetEx (KERNEL32.@)
3612 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3616 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3618 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3622 SetLastError( RtlNtStatusToDosError( status ) );
3628 /***********************************************************************
3629 * K32GetProcessMemoryInfo (KERNEL32.@)
3631 * Retrieve memory usage information for a given process
3634 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3635 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3640 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3642 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3646 status = NtQueryInformationProcess(process, ProcessVmCounters,
3647 &vmc, sizeof(vmc), NULL);
3651 SetLastError(RtlNtStatusToDosError(status));
3655 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3656 pmc->PageFaultCount = vmc.PageFaultCount;
3657 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3658 pmc->WorkingSetSize = vmc.WorkingSetSize;
3659 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3660 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3661 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3662 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3663 pmc->PagefileUsage = vmc.PagefileUsage;
3664 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3669 /***********************************************************************
3670 * ProcessIdToSessionId (KERNEL32.@)
3671 * This function is available on Terminal Server 4SP4 and Windows 2000
3673 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3675 /* According to MSDN, if the calling process is not in a terminal
3676 * services environment, then the sessionid returned is zero.
3683 /***********************************************************************
3684 * RegisterServiceProcess (KERNEL32.@)
3686 * A service process calls this function to ensure that it continues to run
3687 * even after a user logged off.
3689 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3691 /* I don't think that Wine needs to do anything in this function */
3692 return 1; /* success */
3696 /**********************************************************************
3697 * IsWow64Process (KERNEL32.@)
3699 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3704 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3706 if (status != STATUS_SUCCESS)
3708 SetLastError( RtlNtStatusToDosError( status ) );
3711 *Wow64Process = (pbi != 0);
3716 /***********************************************************************
3717 * GetCurrentProcess (KERNEL32.@)
3719 * Get a handle to the current process.
3725 * A handle representing the current process.
3727 #undef GetCurrentProcess
3728 HANDLE WINAPI GetCurrentProcess(void)
3730 return (HANDLE)~(ULONG_PTR)0;
3733 /***********************************************************************
3734 * GetLogicalProcessorInformation (KERNEL32.@)
3736 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3738 FIXME("(%p,%p): stub\n", buffer, pBufLen);
3739 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3743 /***********************************************************************
3744 * GetLogicalProcessorInformationEx (KERNEL32.@)
3746 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer, PDWORD pBufLen)
3748 FIXME("(%u,%p,%p): stub\n", relationship, buffer, pBufLen);
3749 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3753 /***********************************************************************
3754 * CmdBatNotification (KERNEL32.@)
3756 * Notifies the system that a batch file has started or finished.
3759 * bBatchRunning [I] TRUE if a batch file has started or
3760 * FALSE if a batch file has finished executing.
3765 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3767 FIXME("%d\n", bBatchRunning);
3772 /***********************************************************************
3773 * RegisterApplicationRestart (KERNEL32.@)
3775 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3777 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3782 /**********************************************************************
3783 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3785 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3791 /**********************************************************************
3792 * GetSystemDEPPolicy (KERNEL32.@)
3794 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3800 /**********************************************************************
3801 * SetProcessDEPPolicy (KERNEL32.@)
3803 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3805 FIXME("(%d): stub\n", newDEP);
3806 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3810 /**********************************************************************
3811 * ApplicationRecoveryFinished (KERNEL32.@)
3813 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
3816 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3819 /**********************************************************************
3820 * ApplicationRecoveryInProgress (KERNEL32.@)
3822 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
3824 FIXME(":%p stub\n", canceled);
3825 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3829 /**********************************************************************
3830 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3832 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
3834 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
3835 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3839 /**********************************************************************
3840 * GetNumaHighestNodeNumber (KERNEL32.@)
3842 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
3844 FIXME("(%p): stub\n", highestnode);
3845 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3849 /**********************************************************************
3850 * GetNumaNodeProcessorMask (KERNEL32.@)
3852 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
3854 FIXME("(%c %p): stub\n", node, mask);
3855 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3859 /**********************************************************************
3860 * GetNumaAvailableMemoryNode (KERNEL32.@)
3862 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
3864 FIXME("(%c %p): stub\n", node, available_bytes);
3865 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3869 /**********************************************************************
3870 * GetProcessDEPPolicy (KERNEL32.@)
3872 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
3874 FIXME("(%p %p %p): stub\n", process, flags, permanent);
3875 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);