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>
48 #include <CoreFoundation/CoreFoundation.h>
53 #define WIN32_NO_STATUS
55 #include "kernel_private.h"
57 #include "wine/library.h"
58 #include "wine/server.h"
59 #include "wine/unicode.h"
60 #include "wine/debug.h"
62 WINE_DEFAULT_DEBUG_CHANNEL(process);
63 WINE_DECLARE_DEBUG_CHANNEL(file);
64 WINE_DECLARE_DEBUG_CHANNEL(relay);
67 extern char **__wine_get_main_environment(void);
69 extern char **__wine_main_environ;
70 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
81 static DWORD shutdown_flags = 0;
82 static DWORD shutdown_priority = 0x280;
84 static const int is_win64 = (sizeof(void *) > sizeof(int));
86 HMODULE kernel32_handle = 0;
88 const WCHAR *DIR_Windows = NULL;
89 const WCHAR *DIR_System = NULL;
90 const WCHAR *DIR_SysWow64 = NULL;
93 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
94 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
95 #define PDB32_DOS_PROC 0x0010 /* Dos process */
96 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
97 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
98 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
100 static const WCHAR exeW[] = {'.','e','x','e',0};
101 static const WCHAR comW[] = {'.','c','o','m',0};
102 static const WCHAR batW[] = {'.','b','a','t',0};
103 static const WCHAR cmdW[] = {'.','c','m','d',0};
104 static const WCHAR pifW[] = {'.','p','i','f',0};
105 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
107 static void exec_process( LPCWSTR name );
109 extern void SHELL_LoadRegistry(void);
112 /***********************************************************************
115 static inline int contains_path( LPCWSTR name )
117 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
121 /***********************************************************************
124 * Check if an environment variable needs to be handled specially when
125 * passed through the Unix environment (i.e. prefixed with "WINE").
127 static inline int is_special_env_var( const char *var )
129 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
130 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
131 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
132 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
133 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
137 /***********************************************************************
140 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
142 unsigned int len = strlenW( prefix );
144 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
145 while (filename[len] == '\\') len++;
150 /***************************************************************************
153 * Get the path of a builtin module when the native file does not exist.
155 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
156 UINT size, struct binary_info *binary_info )
160 void *redir_disabled = 0;
161 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
163 /* builtin names cannot be empty or contain spaces */
164 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
166 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
167 Wow64RevertWow64FsRedirection( redir_disabled );
169 if (contains_path( libname ))
171 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
172 filename, &file_part ) > size * sizeof(WCHAR))
173 return FALSE; /* too long */
175 if ((len = is_path_prefix( DIR_System, filename )))
177 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
179 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
185 if (filename + len != file_part) return FALSE;
189 len = strlenW( DIR_System );
190 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
191 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
192 file_part = filename + len;
193 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
194 strcpyW( file_part, libname );
195 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
197 if (ext && !strchrW( file_part, '.' ))
199 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
200 return FALSE; /* too long */
201 strcatW( file_part, ext );
203 binary_info->type = BINARY_UNIX_LIB;
204 binary_info->flags = flags;
205 binary_info->res_start = NULL;
206 binary_info->res_end = NULL;
211 /***********************************************************************
214 * Open a specific exe file, taking load order into account.
215 * Returns the file handle or 0 for a builtin exe.
217 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
221 TRACE("looking for %s\n", debugstr_w(name) );
223 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
224 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
226 WCHAR buffer[MAX_PATH];
227 /* file doesn't exist, check for builtin */
228 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
231 else MODULE_get_binary_info( handle, binary_info );
237 /***********************************************************************
240 * Open an exe file, and return the full name and file handle.
241 * Returns FALSE if file could not be found.
242 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
243 * If file is a builtin exe, returns TRUE and sets handle to 0.
245 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
246 HANDLE *handle, struct binary_info *binary_info )
248 TRACE("looking for %s\n", debugstr_w(name) );
250 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ))
252 if (contains_path( name ) && get_builtin_path( name, exeW, buffer, buflen, binary_info ))
257 /* no builtin found, try native without extension in case it is a Unix app */
258 if (!SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
261 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
262 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
263 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
265 MODULE_get_binary_info( *handle, binary_info );
272 /***********************************************************************
273 * build_initial_environment
275 * Build the Win32 environment from the Unix environment
277 static BOOL build_initial_environment(void)
283 char **env = __wine_get_main_environment();
285 /* Compute the total size of the Unix environment */
286 for (e = env; *e; e++)
288 if (is_special_env_var( *e )) continue;
289 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
291 size *= sizeof(WCHAR);
293 /* Now allocate the environment */
295 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
296 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
299 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
300 endptr = p + size / sizeof(WCHAR);
302 /* And fill it with the Unix environment */
303 for (e = env; *e; e++)
307 /* skip Unix special variables and use the Wine variants instead */
308 if (!strncmp( str, "WINE", 4 ))
310 if (is_special_env_var( str + 4 )) str += 4;
311 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
313 else if (is_special_env_var( str )) continue; /* skip it */
315 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
323 /***********************************************************************
324 * set_registry_variables
326 * Set environment variables by enumerating the values of a key;
327 * helper for set_registry_environment().
328 * Note that Windows happily truncates the value if it's too big.
330 static void set_registry_variables( HANDLE hkey, ULONG type )
332 static const WCHAR pathW[] = {'P','A','T','H'};
333 static const WCHAR sep[] = {';',0};
334 UNICODE_STRING env_name, env_value;
338 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
341 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
344 tmp.MaximumLength = sizeof(tmpbuf);
346 for (index = 0; ; index++)
348 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
349 buffer, sizeof(buffer), &size );
350 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
352 if (info->Type != type)
354 env_name.Buffer = info->Name;
355 env_name.Length = env_name.MaximumLength = info->NameLength;
356 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
357 env_value.Length = info->DataLength;
358 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
359 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
360 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
361 if (!env_value.Length) continue;
362 if (info->Type == REG_EXPAND_SZ)
364 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
365 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
366 RtlCopyUnicodeString( &env_value, &tmp );
369 if (env_name.Length == sizeof(pathW) &&
370 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
371 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
373 RtlAppendUnicodeToString( &tmp, sep );
374 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
375 RtlCopyUnicodeString( &env_value, &tmp );
377 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
382 /***********************************************************************
383 * set_registry_environment
385 * Set the environment variables specified in the registry.
387 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
388 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
389 * on the order in which the variables are processed. But on Windows it
390 * does not really matter since they only use %SystemDrive% and
391 * %SystemRoot% which are predefined. But Wine defines these in the
392 * registry, so we need two passes.
394 static BOOL set_registry_environment( BOOL volatile_only )
396 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
397 'S','y','s','t','e','m','\\',
398 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
399 'C','o','n','t','r','o','l','\\',
400 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
401 'E','n','v','i','r','o','n','m','e','n','t',0};
402 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
403 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};
405 OBJECT_ATTRIBUTES attr;
406 UNICODE_STRING nameW;
410 attr.Length = sizeof(attr);
411 attr.RootDirectory = 0;
412 attr.ObjectName = &nameW;
414 attr.SecurityDescriptor = NULL;
415 attr.SecurityQualityOfService = NULL;
417 /* first the system environment variables */
418 RtlInitUnicodeString( &nameW, env_keyW );
419 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
421 set_registry_variables( hkey, REG_SZ );
422 set_registry_variables( hkey, REG_EXPAND_SZ );
427 /* then the ones for the current user */
428 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
429 RtlInitUnicodeString( &nameW, envW );
430 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
432 set_registry_variables( hkey, REG_SZ );
433 set_registry_variables( hkey, REG_EXPAND_SZ );
437 RtlInitUnicodeString( &nameW, volatile_envW );
438 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
440 set_registry_variables( hkey, REG_SZ );
441 set_registry_variables( hkey, REG_EXPAND_SZ );
445 NtClose( attr.RootDirectory );
450 /***********************************************************************
453 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
455 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
456 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
457 DWORD len, size = sizeof(buffer);
459 UNICODE_STRING nameW;
461 RtlInitUnicodeString( &nameW, name );
462 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
465 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
466 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
468 if (info->Type == REG_EXPAND_SZ)
470 UNICODE_STRING value, expanded;
472 value.MaximumLength = len * sizeof(WCHAR);
473 value.Buffer = (WCHAR *)info->Data;
474 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
475 value.Length = len * sizeof(WCHAR);
476 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
477 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
478 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
479 else RtlFreeUnicodeString( &expanded );
481 else if (info->Type == REG_SZ)
483 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
485 memcpy( ret, info->Data, len * sizeof(WCHAR) );
493 /***********************************************************************
494 * set_additional_environment
496 * Set some additional environment variables not specified in the registry.
498 static void set_additional_environment(void)
500 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
501 'S','o','f','t','w','a','r','e','\\',
502 'M','i','c','r','o','s','o','f','t','\\',
503 'W','i','n','d','o','w','s',' ','N','T','\\',
504 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
505 'P','r','o','f','i','l','e','L','i','s','t',0};
506 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
507 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
508 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
509 OBJECT_ATTRIBUTES attr;
510 UNICODE_STRING nameW;
511 WCHAR *profile_dir = NULL, *all_users_dir = NULL;
515 /* set the ALLUSERSPROFILE variables */
517 attr.Length = sizeof(attr);
518 attr.RootDirectory = 0;
519 attr.ObjectName = &nameW;
521 attr.SecurityDescriptor = NULL;
522 attr.SecurityQualityOfService = NULL;
523 RtlInitUnicodeString( &nameW, profile_keyW );
524 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
526 profile_dir = get_reg_value( hkey, profiles_valueW );
527 all_users_dir = get_reg_value( hkey, all_users_valueW );
531 if (profile_dir && all_users_dir)
535 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
536 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
537 strcpyW( value, profile_dir );
538 p = value + strlenW(value);
539 if (p > value && p[-1] != '\\') *p++ = '\\';
540 strcpyW( p, all_users_dir );
541 SetEnvironmentVariableW( allusersW, value );
542 HeapFree( GetProcessHeap(), 0, value );
545 HeapFree( GetProcessHeap(), 0, all_users_dir );
546 HeapFree( GetProcessHeap(), 0, profile_dir );
549 /***********************************************************************
550 * set_wow64_environment
552 * Set the environment variables that change across 32/64/Wow64.
554 static void set_wow64_environment(void)
556 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};
557 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};
558 static const WCHAR x86W[] = {'x','8','6',0};
559 static const WCHAR versionW[] = {'M','a','c','h','i','n','e','\\',
560 'S','o','f','t','w','a','r','e','\\',
561 'M','i','c','r','o','s','o','f','t','\\',
562 'W','i','n','d','o','w','s','\\',
563 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
564 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
565 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
566 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
567 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
568 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
569 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
570 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
571 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
573 OBJECT_ATTRIBUTES attr;
574 UNICODE_STRING nameW;
579 /* set the PROCESSOR_ARCHITECTURE variable */
581 if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
585 SetEnvironmentVariableW( archW, arch );
586 SetEnvironmentVariableW( arch6432W, NULL );
589 else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
593 SetEnvironmentVariableW( arch6432W, arch );
594 SetEnvironmentVariableW( archW, x86W );
598 attr.Length = sizeof(attr);
599 attr.RootDirectory = 0;
600 attr.ObjectName = &nameW;
602 attr.SecurityDescriptor = NULL;
603 attr.SecurityQualityOfService = NULL;
604 RtlInitUnicodeString( &nameW, versionW );
605 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
607 /* set the ProgramFiles variables */
609 if ((value = get_reg_value( hkey, progdirW )))
611 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
612 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
613 HeapFree( GetProcessHeap(), 0, value );
615 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
617 SetEnvironmentVariableW( progfilesW, value );
618 HeapFree( GetProcessHeap(), 0, value );
621 /* set the CommonProgramFiles variables */
623 if ((value = get_reg_value( hkey, commondirW )))
625 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
626 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
627 HeapFree( GetProcessHeap(), 0, value );
629 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
631 SetEnvironmentVariableW( commonfilesW, value );
632 HeapFree( GetProcessHeap(), 0, value );
638 /***********************************************************************
641 * Set the Wine library Unicode argv global variables.
643 static void set_library_wargv( char **argv )
651 for (argc = 0; argv[argc]; argc++)
652 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
654 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
655 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
656 p = (WCHAR *)(wargv + argc + 1);
657 for (argc = 0; argv[argc]; argc++)
659 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
666 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
668 for (argc = 0; wargv[argc]; argc++)
669 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
671 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
672 q = (char *)(argv + argc + 1);
673 for (argc = 0; wargv[argc]; argc++)
675 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
682 __wine_main_argc = argc;
683 __wine_main_argv = argv;
684 __wine_main_wargv = wargv;
688 /***********************************************************************
689 * update_library_argv0
691 * Update the argv[0] global variable with the binary we have found.
693 static void update_library_argv0( const WCHAR *argv0 )
695 DWORD len = strlenW( argv0 );
697 if (len > strlenW( __wine_main_wargv[0] ))
699 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
701 strcpyW( __wine_main_wargv[0], argv0 );
703 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
704 if (len > strlen( __wine_main_argv[0] ) + 1)
706 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
708 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
712 /***********************************************************************
715 * Build the command line of a process from the argv array.
717 * Note that it does NOT necessarily include the file name.
718 * Sometimes we don't even have any command line options at all.
720 * We must quote and escape characters so that the argv array can be rebuilt
721 * from the command line:
722 * - spaces and tabs must be quoted
724 * - quotes must be escaped
726 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
727 * resulting in an odd number of '\' followed by a '"'
730 * - '\'s that are not followed by a '"' can be left as is
734 static BOOL build_command_line( WCHAR **argv )
739 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
741 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
744 for (arg = argv; *arg; arg++)
746 int has_space,bcount;
752 if( !*a ) has_space=1;
757 if (*a==' ' || *a=='\t') {
759 } else if (*a=='"') {
760 /* doubling of '\' preceding a '"',
761 * plus escaping of said '"'
769 len+=(a-*arg)+1 /* for the separating space */;
771 len+=2; /* for the quotes */
774 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
777 p = rupp->CommandLine.Buffer;
778 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
779 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
780 for (arg = argv; *arg; arg++)
782 int has_space,has_quote;
785 /* Check for quotes and spaces in this argument */
786 has_space=has_quote=0;
788 if( !*a ) has_space=1;
790 if (*a==' ' || *a=='\t') {
794 } else if (*a=='"') {
802 /* Now transfer it to the command line */
818 /* Double all the '\\' preceding this '"', plus one */
819 for (i=0;i<=bcount;i++)
831 while ((*p=*x++)) p++;
837 if (p > rupp->CommandLine.Buffer)
838 p--; /* remove last space */
845 /***********************************************************************
846 * init_current_directory
848 * Initialize the current directory from the Unix cwd or the parent info.
850 static void init_current_directory( CURDIR *cur_dir )
852 UNICODE_STRING dir_str;
857 /* if we received a cur dir from the parent, try this first */
859 if (cur_dir->DosPath.Length)
861 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
864 /* now try to get it from the Unix cwd */
866 for (size = 256; ; size *= 2)
868 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
869 if (getcwd( cwd, size )) break;
870 HeapFree( GetProcessHeap(), 0, cwd );
871 if (errno == ERANGE) continue;
876 /* try to use PWD if it is valid, so that we don't resolve symlinks */
878 pwd = getenv( "PWD" );
881 struct stat st1, st2;
883 if (!pwd || stat( pwd, &st1 ) == -1 ||
884 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
890 ANSI_STRING unix_name;
891 UNICODE_STRING nt_name;
892 RtlInitAnsiString( &unix_name, pwd );
893 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
895 UNICODE_STRING dos_path;
896 /* skip the \??\ prefix, nt_name is 0 terminated */
897 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
898 RtlSetCurrentDirectory_U( &dos_path );
899 RtlFreeUnicodeString( &nt_name );
903 if (!cur_dir->DosPath.Length) /* still not initialized */
905 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
906 "starting in the Windows directory.\n", cwd ? cwd : "" );
907 RtlInitUnicodeString( &dir_str, DIR_Windows );
908 RtlSetCurrentDirectory_U( &dir_str );
910 HeapFree( GetProcessHeap(), 0, cwd );
913 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
914 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
918 /***********************************************************************
921 * Initialize the windows and system directories from the environment.
923 static void init_windows_dirs(void)
925 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
927 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
928 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
929 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
930 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
931 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
936 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
938 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
939 GetEnvironmentVariableW( windirW, buffer, len );
940 DIR_Windows = buffer;
942 else DIR_Windows = default_windirW;
944 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
946 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
947 GetEnvironmentVariableW( winsysdirW, buffer, len );
952 len = strlenW( DIR_Windows );
953 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
954 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
955 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
959 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
960 ERR( "directory %s could not be created, error %u\n",
961 debugstr_w(DIR_Windows), GetLastError() );
962 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
963 ERR( "directory %s could not be created, error %u\n",
964 debugstr_w(DIR_System), GetLastError() );
966 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
968 len = strlenW( DIR_Windows );
969 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
970 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
971 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
972 DIR_SysWow64 = buffer;
973 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
974 ERR( "directory %s could not be created, error %u\n",
975 debugstr_w(DIR_SysWow64), GetLastError() );
978 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
979 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
981 /* set the directories in ntdll too */
982 __wine_init_windows_dir( DIR_Windows, DIR_System );
986 /***********************************************************************
989 * Start the wineboot process if necessary. Return the handles to wait on.
991 static void start_wineboot( HANDLE handles[2] )
993 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
996 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
998 ERR( "failed to create wineboot event, expect trouble\n" );
1001 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
1003 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1004 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1006 PROCESS_INFORMATION pi;
1008 WCHAR app[MAX_PATH];
1009 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1011 memset( &si, 0, sizeof(si) );
1013 si.dwFlags = STARTF_USESTDHANDLES;
1016 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1018 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1019 lstrcatW( app, wineboot );
1021 Wow64DisableWow64FsRedirection( &redir );
1022 strcpyW( cmdline, app );
1023 strcatW( cmdline, args );
1024 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1026 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1027 CloseHandle( pi.hThread );
1028 handles[1] = pi.hProcess;
1032 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1033 CloseHandle( handles[0] );
1036 Wow64RevertWow64FsRedirection( redir );
1042 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1043 __ASM_GLOBAL_FUNC( call_process_entry,
1045 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1046 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1047 "movl %esp,%ebp\n\t"
1048 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1049 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1051 "call *12(%ebp)\n\t"
1053 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1054 __ASM_CFI(".cfi_same_value %ebp\n\t")
1057 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1059 return entry( peb );
1063 /***********************************************************************
1066 * Startup routine of a new process. Runs on the new process stack.
1068 static DWORD WINAPI start_process( PEB *peb )
1070 IMAGE_NT_HEADERS *nt;
1071 LPTHREAD_START_ROUTINE entry;
1073 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1074 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1075 nt->OptionalHeader.AddressOfEntryPoint);
1077 if (!nt->OptionalHeader.AddressOfEntryPoint)
1079 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1080 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1084 if (TRACE_ON(relay))
1085 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1086 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1088 SetLastError( 0 ); /* clear error code */
1089 if (peb->BeingDebugged) DbgBreakPoint();
1090 return call_process_entry( peb, entry );
1094 /***********************************************************************
1097 * Change the process name in the ps output.
1099 static void set_process_name( int argc, char *argv[] )
1101 #ifdef HAVE_SETPROCTITLE
1102 setproctitle("-%s", argv[1]);
1107 char *p, *prctl_name = argv[1];
1108 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1111 # define PR_SET_NAME 15
1114 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1115 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1117 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1119 offset = argv[1] - argv[0];
1120 memmove( argv[1] - offset, argv[1], end - argv[1] );
1121 memset( end - offset, 0, offset );
1122 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1126 #endif /* HAVE_PRCTL */
1128 /* remove argv[0] */
1129 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1134 /***********************************************************************
1135 * __wine_kernel_init
1137 * Wine initialisation: load and start the main exe file.
1139 void CDECL __wine_kernel_init(void)
1141 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1142 static const WCHAR dotW[] = {'.',0};
1144 WCHAR *p, main_exe_name[MAX_PATH+1];
1145 PEB *peb = NtCurrentTeb()->Peb;
1146 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1147 HANDLE boot_events[2];
1148 BOOL got_environment = TRUE;
1150 /* Initialize everything */
1152 setbuf(stdout,NULL);
1153 setbuf(stderr,NULL);
1154 kernel32_handle = GetModuleHandleW(kernel32W);
1155 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1159 if (!params->Environment)
1161 /* Copy the parent environment */
1162 if (!build_initial_environment()) exit(1);
1164 /* convert old configuration to new format */
1165 convert_old_config();
1167 got_environment = set_registry_environment( FALSE );
1168 set_additional_environment();
1171 init_windows_dirs();
1172 init_current_directory( ¶ms->CurrentDirectory );
1174 set_process_name( __wine_main_argc, __wine_main_argv );
1175 set_library_wargv( __wine_main_argv );
1176 boot_events[0] = boot_events[1] = 0;
1178 if (peb->ProcessParameters->ImagePathName.Buffer)
1180 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1184 struct binary_info binary_info;
1186 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1187 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1189 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1190 ExitProcess( GetLastError() );
1192 update_library_argv0( main_exe_name );
1193 if (!build_command_line( __wine_main_wargv )) goto error;
1194 start_wineboot( boot_events );
1197 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1198 p = strrchrW( main_exe_name, '.' );
1199 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1201 TRACE( "starting process name=%s argv[0]=%s\n",
1202 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1204 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1205 MODULE_get_dll_load_path(main_exe_name) );
1209 DWORD timeout = 2 * 60 * 1000, count = 1;
1211 if (boot_events[1]) count++;
1212 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1213 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1214 ERR( "boot event wait timed out\n" );
1215 CloseHandle( boot_events[0] );
1216 if (boot_events[1]) CloseHandle( boot_events[1] );
1217 /* reload environment now that wineboot has run */
1218 set_registry_environment( got_environment );
1219 set_additional_environment();
1221 set_wow64_environment();
1223 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1228 DWORD error = GetLastError();
1230 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1231 if (error == ERROR_BAD_EXE_FORMAT ||
1232 error == ERROR_INVALID_ADDRESS ||
1233 error == ERROR_NOT_ENOUGH_MEMORY)
1235 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1236 /* if we get back here, it failed */
1238 else if (error == ERROR_MOD_NOT_FOUND)
1240 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1241 else p = main_exe_name;
1242 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1244 /* args 1 and 2 are --app-name full_path */
1245 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1246 debugstr_w(__wine_main_wargv[3]) );
1247 ExitProcess( ERROR_BAD_EXE_FORMAT );
1249 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1250 ExitProcess( ERROR_FILE_NOT_FOUND );
1252 args[0] = (DWORD_PTR)main_exe_name;
1253 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1254 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1255 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1256 MESSAGE( "wine: %s", msg );
1257 ExitProcess( error );
1260 LdrInitializeThunk( start_process, 0, 0, 0 );
1263 ExitProcess( GetLastError() );
1267 /***********************************************************************
1270 * Build an argv array from a command-line.
1271 * 'reserved' is the number of args to reserve before the first one.
1273 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1277 char *arg,*s,*d,*cmdline;
1278 int in_quotes,bcount,len;
1280 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1281 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1282 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1289 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1292 /* skip the remaining spaces */
1293 while (*s==' ' || *s=='\t') {
1300 } else if (*s=='\\') {
1301 /* '\', count them */
1303 } else if ((*s=='"') && ((bcount & 1)==0)) {
1305 in_quotes=!in_quotes;
1308 /* a regular character */
1313 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1315 HeapFree( GetProcessHeap(), 0, cmdline );
1319 arg = d = s = (char *)(argv + argc);
1320 memcpy( d, cmdline, len );
1325 if ((*s==' ' || *s=='\t') && !in_quotes) {
1326 /* Close the argument and copy it */
1330 /* skip the remaining spaces */
1333 } while (*s==' ' || *s=='\t');
1335 /* Start with a new argument */
1338 } else if (*s=='\\') {
1342 } else if (*s=='"') {
1344 if ((bcount & 1)==0) {
1345 /* Preceded by an even number of '\', this is half that
1346 * number of '\', plus a '"' which we discard.
1350 in_quotes=!in_quotes;
1352 /* Preceded by an odd number of '\', this is half that
1353 * number of '\' followed by a '"'
1361 /* a regular character */
1372 HeapFree( GetProcessHeap(), 0, cmdline );
1377 /***********************************************************************
1380 * Build the environment of a new child process.
1382 static char **build_envp( const WCHAR *envW )
1384 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1389 int count = 1, length;
1392 for (end = envW; *end; count++) end += strlenW(end) + 1;
1394 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1395 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1396 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1398 for (p = env; *p; p += strlen(p) + 1)
1399 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1401 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1403 if (!(p = getenv(unix_vars[i]))) continue;
1404 length += strlen(unix_vars[i]) + strlen(p) + 2;
1408 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1410 char **envptr = envp;
1411 char *dst = (char *)(envp + count);
1413 /* some variables must not be modified, so we get them directly from the unix env */
1414 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1416 if (!(p = getenv(unix_vars[i]))) continue;
1417 *envptr++ = strcpy( dst, unix_vars[i] );
1420 dst += strlen(dst) + 1;
1423 /* now put the Windows environment strings */
1424 for (p = env; *p; p += strlen(p) + 1)
1426 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1427 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1428 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1429 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1430 if (is_special_env_var( p )) /* prefix it with "WINE" */
1432 *envptr++ = strcpy( dst, "WINE" );
1437 *envptr++ = strcpy( dst, p );
1439 dst += strlen(dst) + 1;
1443 HeapFree( GetProcessHeap(), 0, env );
1448 /***********************************************************************
1451 * Fork and exec a new Unix binary, checking for errors.
1453 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1454 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1456 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1458 char **argv, **envp;
1460 if (!env) env = GetEnvironmentStringsW();
1463 if (pipe2( fd, O_CLOEXEC ) == -1)
1468 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1471 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1472 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1475 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1477 HANDLE hstdin, hstdout, hstderr;
1479 if (startup->dwFlags & STARTF_USESTDHANDLES)
1481 hstdin = startup->hStdInput;
1482 hstdout = startup->hStdOutput;
1483 hstderr = startup->hStdError;
1487 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1488 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1489 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1492 if (is_console_handle( hstdin ))
1493 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1494 if (is_console_handle( hstdout ))
1495 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1496 if (is_console_handle( hstderr ))
1497 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1498 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1499 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1500 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1503 argv = build_argv( cmdline, 0 );
1504 envp = build_envp( env );
1506 if (!(pid = fork())) /* child */
1510 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1512 if (!(pid = fork()))
1514 int nullfd = open( "/dev/null", O_RDWR );
1516 /* close stdin and stdout */
1524 else if (pid != -1) _exit(0); /* parent */
1530 dup2( stdin_fd, 0 );
1533 if (stdout_fd != -1)
1535 dup2( stdout_fd, 1 );
1538 if (stderr_fd != -1)
1540 dup2( stderr_fd, 2 );
1545 /* Reset signals that we previously set to SIG_IGN */
1546 signal( SIGPIPE, SIG_DFL );
1547 signal( SIGCHLD, SIG_DFL );
1549 if (newdir) chdir(newdir);
1551 if (argv && envp) execve( filename, argv, envp );
1553 write( fd[1], &err, sizeof(err) );
1556 HeapFree( GetProcessHeap(), 0, argv );
1557 HeapFree( GetProcessHeap(), 0, envp );
1558 if (stdin_fd != -1) close( stdin_fd );
1559 if (stdout_fd != -1) close( stdout_fd );
1560 if (stderr_fd != -1) close( stderr_fd );
1562 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1567 if (pid == -1) FILE_SetDosError();
1573 static inline DWORD append_string( void **ptr, const WCHAR *str )
1575 DWORD len = strlenW( str );
1576 memcpy( *ptr, str, len * sizeof(WCHAR) );
1577 *ptr = (WCHAR *)*ptr + len;
1578 return len * sizeof(WCHAR);
1581 /***********************************************************************
1582 * create_startup_info
1584 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1585 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1586 const STARTUPINFOW *startup, DWORD *info_size )
1588 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1590 startup_info_t *info;
1593 UNICODE_STRING newdir;
1594 WCHAR imagepath[MAX_PATH];
1595 HANDLE hstdin, hstdout, hstderr;
1597 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1598 lstrcpynW( imagepath, filename, MAX_PATH );
1599 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1600 lstrcpynW( imagepath, filename, MAX_PATH );
1602 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1604 newdir.Buffer = NULL;
1607 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1608 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1614 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1615 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1617 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1619 title = startup->lpTitle ? startup->lpTitle : imagepath;
1621 size = sizeof(*info);
1622 size += strlenW( cur_dir ) * sizeof(WCHAR);
1623 size += cur_params->DllPath.Length;
1624 size += strlenW( imagepath ) * sizeof(WCHAR);
1625 size += strlenW( cmdline ) * sizeof(WCHAR);
1626 size += strlenW( title ) * sizeof(WCHAR);
1627 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1628 /* FIXME: shellinfo */
1629 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1630 size = (size + 1) & ~1;
1633 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1635 info->console_flags = cur_params->ConsoleFlags;
1636 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1637 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1639 if (startup->dwFlags & STARTF_USESTDHANDLES)
1641 hstdin = startup->hStdInput;
1642 hstdout = startup->hStdOutput;
1643 hstderr = startup->hStdError;
1647 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1648 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1649 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1651 info->hstdin = wine_server_obj_handle( hstdin );
1652 info->hstdout = wine_server_obj_handle( hstdout );
1653 info->hstderr = wine_server_obj_handle( hstderr );
1654 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1656 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1657 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1658 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1659 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1663 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1664 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1665 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1668 info->x = startup->dwX;
1669 info->y = startup->dwY;
1670 info->xsize = startup->dwXSize;
1671 info->ysize = startup->dwYSize;
1672 info->xchars = startup->dwXCountChars;
1673 info->ychars = startup->dwYCountChars;
1674 info->attribute = startup->dwFillAttribute;
1675 info->flags = startup->dwFlags;
1676 info->show = startup->wShowWindow;
1679 info->curdir_len = append_string( &ptr, cur_dir );
1680 info->dllpath_len = cur_params->DllPath.Length;
1681 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1682 ptr = (char *)ptr + cur_params->DllPath.Length;
1683 info->imagepath_len = append_string( &ptr, imagepath );
1684 info->cmdline_len = append_string( &ptr, cmdline );
1685 info->title_len = append_string( &ptr, title );
1686 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1687 if (startup->lpReserved2 && startup->cbReserved2)
1689 info->runtime_len = startup->cbReserved2;
1690 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1694 RtlFreeUnicodeString( &newdir );
1698 /***********************************************************************
1699 * get_alternate_loader
1701 * Get the name of the alternate (32 or 64 bit) Wine loader.
1703 static const char *get_alternate_loader( char **ret_env )
1706 const char *loader = NULL;
1707 const char *loader_env = getenv( "WINELOADER" );
1711 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1715 int len = strlen( loader_env );
1718 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1719 strcpy( env, "WINELOADER=" );
1720 strcat( env, loader_env );
1721 strcat( env, "64" );
1725 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1726 strcpy( env, "WINELOADER=" );
1727 strcat( env, loader_env );
1728 len += sizeof("WINELOADER=") - 1;
1729 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1733 if ((loader = strrchr( env, '/' ))) loader++;
1738 if (!loader) loader = is_win64 ? "wine" : "wine64";
1743 /***********************************************************************
1744 * terminate_main_thread
1746 * On some versions of Mac OS X, the execve system call fails with
1747 * ENOTSUP if the process has multiple threads. Wine is always multi-
1748 * threaded on Mac OS X because it specifically reserves the main thread
1749 * for use by the system frameworks (see apple_main_thread() in
1750 * libs/wine/loader.c). So, when we need to exec without first forking,
1751 * we need to terminate the main thread first. We do this by installing
1752 * a custom run loop source onto the main run loop and signaling it.
1753 * The source's "perform" callback is pthread_exit and it will be
1754 * executed on the main thread, terminating it.
1756 * Returns TRUE if there's still hope the main thread has terminated or
1757 * will soon. Return FALSE if we've given up.
1759 static BOOL terminate_main_thread(void)
1765 CFRunLoopSourceContext source_context = { 0 };
1766 CFRunLoopSourceRef source;
1768 source_context.perform = pthread_exit;
1769 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1772 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1773 CFRunLoopSourceSignal( source );
1774 CFRunLoopWakeUp( CFRunLoopGetMain() );
1775 CFRelease( source );
1783 usleep(delayms * 1000);
1790 /***********************************************************************
1793 static pid_t exec_loader( LPCWSTR cmd_line, unsigned int flags, int socketfd,
1794 int stdin_fd, int stdout_fd, const char *unixdir, char *winedebug,
1795 const struct binary_info *binary_info, int exec_only )
1798 char *wineloader = NULL;
1799 const char *loader = NULL;
1802 argv = build_argv( cmd_line, 1 );
1804 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1805 loader = get_alternate_loader( &wineloader );
1807 if (exec_only || !(pid = fork())) /* child */
1809 char preloader_reserve[64], socket_env[64];
1811 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1813 if (!(pid = fork()))
1815 int fd = open( "/dev/null", O_RDWR );
1817 /* close stdin and stdout */
1825 else if (pid != -1) _exit(0); /* parent */
1829 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1830 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1833 if (stdin_fd != -1) close( stdin_fd );
1834 if (stdout_fd != -1) close( stdout_fd );
1836 /* Reset signals that we previously set to SIG_IGN */
1837 signal( SIGPIPE, SIG_DFL );
1838 signal( SIGCHLD, SIG_DFL );
1840 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
1841 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1842 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1844 putenv( preloader_reserve );
1845 putenv( socket_env );
1846 if (winedebug) putenv( winedebug );
1847 if (wineloader) putenv( wineloader );
1848 if (unixdir) chdir(unixdir);
1854 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1857 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1864 HeapFree( GetProcessHeap(), 0, wineloader );
1865 HeapFree( GetProcessHeap(), 0, argv );
1869 /***********************************************************************
1872 * Create a new process. If hFile is a valid handle we have an exe
1873 * file, otherwise it is a Winelib app.
1875 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1876 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1877 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1878 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1879 const struct binary_info *binary_info, int exec_only )
1881 BOOL ret, success = FALSE;
1882 HANDLE process_info;
1884 char *winedebug = NULL;
1885 startup_info_t *startup_info;
1886 DWORD startup_info_size;
1887 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1891 if (!is_win64 && !is_wow64 && (binary_info->flags & BINARY_FLAG_64BIT))
1893 ERR( "starting 64-bit process %s not supported in 32-bit wineprefix\n", debugstr_w(filename) );
1894 SetLastError( ERROR_BAD_EXE_FORMAT );
1898 /* create the socket for the new process */
1900 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1902 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1906 if (exec_only) /* things are much simpler in this case */
1908 wine_server_send_fd( socketfd[1] );
1909 close( socketfd[1] );
1910 SERVER_START_REQ( new_process )
1912 req->create_flags = flags;
1913 req->socket_fd = socketfd[1];
1914 req->exe_file = wine_server_obj_handle( hFile );
1915 ret = !wine_server_call_err( req );
1919 if (ret) exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
1920 winedebug, binary_info, TRUE );
1922 close( socketfd[0] );
1926 RtlAcquirePebLock();
1928 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1929 &startup_info_size )))
1931 RtlReleasePebLock();
1932 close( socketfd[0] );
1933 close( socketfd[1] );
1936 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
1940 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1941 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1943 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1944 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1945 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1947 env_end += strlenW(env_end) + 1;
1951 wine_server_send_fd( socketfd[1] );
1952 close( socketfd[1] );
1954 /* create the process on the server side */
1956 SERVER_START_REQ( new_process )
1958 req->inherit_all = inherit;
1959 req->create_flags = flags;
1960 req->socket_fd = socketfd[1];
1961 req->exe_file = wine_server_obj_handle( hFile );
1962 req->process_access = PROCESS_ALL_ACCESS;
1963 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1964 req->thread_access = THREAD_ALL_ACCESS;
1965 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1966 req->info_size = startup_info_size;
1968 wine_server_add_data( req, startup_info, startup_info_size );
1969 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
1970 if ((ret = !wine_server_call_err( req )))
1972 info->dwProcessId = (DWORD)reply->pid;
1973 info->dwThreadId = (DWORD)reply->tid;
1974 info->hProcess = wine_server_ptr_handle( reply->phandle );
1975 info->hThread = wine_server_ptr_handle( reply->thandle );
1977 process_info = wine_server_ptr_handle( reply->info );
1981 RtlReleasePebLock();
1984 close( socketfd[0] );
1985 HeapFree( GetProcessHeap(), 0, startup_info );
1986 HeapFree( GetProcessHeap(), 0, winedebug );
1990 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1992 if (startup_info->hstdin)
1993 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
1994 FILE_READ_DATA, &stdin_fd, NULL );
1995 if (startup_info->hstdout)
1996 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
1997 FILE_WRITE_DATA, &stdout_fd, NULL );
1999 HeapFree( GetProcessHeap(), 0, startup_info );
2001 /* create the child process */
2003 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2004 winedebug, binary_info, FALSE );
2006 if (stdin_fd != -1) close( stdin_fd );
2007 if (stdout_fd != -1) close( stdout_fd );
2008 close( socketfd[0] );
2009 HeapFree( GetProcessHeap(), 0, winedebug );
2016 /* wait for the new process info to be ready */
2018 WaitForSingleObject( process_info, INFINITE );
2019 SERVER_START_REQ( get_new_process_info )
2021 req->info = wine_server_obj_handle( process_info );
2022 wine_server_call( req );
2023 success = reply->success;
2024 err = reply->exit_code;
2030 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2033 CloseHandle( process_info );
2037 CloseHandle( process_info );
2038 CloseHandle( info->hProcess );
2039 CloseHandle( info->hThread );
2040 info->hProcess = info->hThread = 0;
2041 info->dwProcessId = info->dwThreadId = 0;
2046 /***********************************************************************
2047 * create_vdm_process
2049 * Create a new VDM process for a 16-bit or DOS application.
2051 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2052 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2053 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2054 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2055 const struct binary_info *binary_info, int exec_only )
2057 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2060 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
2061 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
2065 SetLastError( ERROR_OUTOFMEMORY );
2068 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
2069 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2070 flags, startup, info, unixdir, binary_info, exec_only );
2071 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2076 /***********************************************************************
2077 * create_cmd_process
2079 * Create a new cmd shell process for a .BAT file.
2081 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2082 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2083 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2084 LPPROCESS_INFORMATION info )
2087 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2088 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2089 WCHAR comspec[MAX_PATH];
2093 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2095 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2096 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2099 strcpyW( newcmdline, comspec );
2100 strcatW( newcmdline, slashcW );
2101 strcatW( newcmdline, cmd_line );
2102 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2103 flags, env, cur_dir, startup, info );
2104 HeapFree( GetProcessHeap(), 0, newcmdline );
2109 /*************************************************************************
2112 * Helper for CreateProcess: retrieve the file name to load from the
2113 * app name and command line. Store the file name in buffer, and
2114 * return a possibly modified command line.
2115 * Also returns a handle to the opened file if it's a Windows binary.
2117 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2118 int buflen, HANDLE *handle, struct binary_info *binary_info )
2120 static const WCHAR quotesW[] = {'"','%','s','"',0};
2122 WCHAR *name, *pos, *first_space, *ret = NULL;
2125 /* if we have an app name, everything is easy */
2129 /* use the unmodified app name as file name */
2130 lstrcpynW( buffer, appname, buflen );
2131 *handle = open_exe_file( buffer, binary_info );
2132 if (!(ret = cmdline) || !cmdline[0])
2134 /* no command-line, create one */
2135 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2136 sprintfW( ret, quotesW, appname );
2141 /* first check for a quoted file name */
2143 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2145 int len = p - cmdline - 1;
2146 /* extract the quoted portion as file name */
2147 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2148 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2151 if (!find_exe_file( name, buffer, buflen, handle, binary_info ))
2153 if (!get_builtin_path( name, exeW, buffer, buflen, binary_info )) goto done;
2156 ret = cmdline; /* no change necessary */
2160 /* now try the command-line word by word */
2162 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2170 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2172 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2177 if (!first_space) first_space = pos;
2178 if (!(*pos++ = *p++)) break;
2183 if (first_space) *first_space = 0; /* try only the first word as a builtin */
2184 if (get_builtin_path( name, exeW, buffer, buflen, binary_info ))
2189 else SetLastError( ERROR_FILE_NOT_FOUND );
2191 else if (first_space) /* build a new command-line with quotes */
2193 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2195 sprintfW( ret, quotesW, name );
2200 HeapFree( GetProcessHeap(), 0, name );
2205 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2206 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2207 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2208 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2209 LPPROCESS_INFORMATION info )
2213 char *unixdir = NULL;
2214 WCHAR name[MAX_PATH];
2215 WCHAR *tidy_cmdline, *p, *envW = env;
2216 struct binary_info binary_info;
2218 /* Process the AppName and/or CmdLine to get module name and path */
2220 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2222 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2223 &hFile, &binary_info )))
2225 if (hFile == INVALID_HANDLE_VALUE) goto done;
2227 /* Warn if unsupported features are used */
2229 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2230 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2231 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2232 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2233 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2237 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2239 SetLastError(ERROR_DIRECTORY);
2245 WCHAR buf[MAX_PATH];
2246 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2249 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2254 while (*e) e += strlen(e) + 1;
2255 e++; /* final null */
2256 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, NULL, 0 );
2257 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2258 MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, envW, lenW );
2259 flags |= CREATE_UNICODE_ENVIRONMENT;
2262 info->hThread = info->hProcess = 0;
2263 info->dwProcessId = info->dwThreadId = 0;
2265 if (binary_info.flags & BINARY_FLAG_DLL)
2267 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2268 SetLastError( ERROR_BAD_EXE_FORMAT );
2270 else switch (binary_info.type)
2273 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2274 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2275 binary_info.res_start, binary_info.res_end );
2276 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2277 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2282 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2283 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2284 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2286 case BINARY_UNIX_LIB:
2287 TRACE( "starting %s as %d-bit Winelib app\n",
2288 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2289 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2290 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2292 case BINARY_UNKNOWN:
2293 /* check for .com or .bat extension */
2294 if ((p = strrchrW( name, '.' )))
2296 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2298 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2299 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2300 inherit, flags, startup_info, info, unixdir,
2301 &binary_info, FALSE );
2304 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2306 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2307 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2308 inherit, flags, startup_info, info );
2313 case BINARY_UNIX_EXE:
2315 /* unknown file, try as unix executable */
2318 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2320 if ((unix_name = wine_get_unix_file_name( name )))
2322 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2323 HeapFree( GetProcessHeap(), 0, unix_name );
2328 if (hFile) CloseHandle( hFile );
2331 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2332 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2333 HeapFree( GetProcessHeap(), 0, unixdir );
2335 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2340 /**********************************************************************
2341 * CreateProcessA (KERNEL32.@)
2343 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2344 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2345 DWORD flags, LPVOID env, LPCSTR cur_dir,
2346 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2349 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2350 UNICODE_STRING desktopW, titleW;
2353 desktopW.Buffer = NULL;
2354 titleW.Buffer = NULL;
2355 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2356 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2357 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2359 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2360 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2362 memcpy( &infoW, startup_info, sizeof(infoW) );
2363 infoW.lpDesktop = desktopW.Buffer;
2364 infoW.lpTitle = titleW.Buffer;
2366 if (startup_info->lpReserved)
2367 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2368 debugstr_a(startup_info->lpReserved));
2370 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2371 inherit, flags, env, cur_dirW, &infoW, info );
2373 HeapFree( GetProcessHeap(), 0, app_nameW );
2374 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2375 HeapFree( GetProcessHeap(), 0, cur_dirW );
2376 RtlFreeUnicodeString( &desktopW );
2377 RtlFreeUnicodeString( &titleW );
2382 /**********************************************************************
2383 * CreateProcessW (KERNEL32.@)
2385 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2386 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2387 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2388 LPPROCESS_INFORMATION info )
2390 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2391 inherit, flags, env, cur_dir, startup_info, info);
2395 /**********************************************************************
2398 static void exec_process( LPCWSTR name )
2402 STARTUPINFOW startup_info;
2403 PROCESS_INFORMATION info;
2404 struct binary_info binary_info;
2406 hFile = open_exe_file( name, &binary_info );
2407 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2409 memset( &startup_info, 0, sizeof(startup_info) );
2410 startup_info.cb = sizeof(startup_info);
2412 /* Determine executable type */
2414 if (binary_info.flags & BINARY_FLAG_DLL) return;
2415 switch (binary_info.type)
2418 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2419 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2420 binary_info.res_start, binary_info.res_end );
2421 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2422 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2424 case BINARY_UNIX_LIB:
2425 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2426 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2427 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2429 case BINARY_UNKNOWN:
2430 /* check for .com or .pif extension */
2431 if (!(p = strrchrW( name, '.' ))) break;
2432 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2437 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2438 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2439 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2444 CloseHandle( hFile );
2448 /***********************************************************************
2451 * Wrapper to call WaitForInputIdle USER function
2453 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2455 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2457 HMODULE mod = GetModuleHandleA( "user32.dll" );
2460 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2461 if (ptr) return ptr( process, timeout );
2467 /***********************************************************************
2468 * WinExec (KERNEL32.@)
2470 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2472 PROCESS_INFORMATION info;
2473 STARTUPINFOA startup;
2477 memset( &startup, 0, sizeof(startup) );
2478 startup.cb = sizeof(startup);
2479 startup.dwFlags = STARTF_USESHOWWINDOW;
2480 startup.wShowWindow = nCmdShow;
2482 /* cmdline needs to be writable for CreateProcess */
2483 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2484 strcpy( cmdline, lpCmdLine );
2486 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2487 0, NULL, NULL, &startup, &info ))
2489 /* Give 30 seconds to the app to come up */
2490 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2491 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2493 /* Close off the handles */
2494 CloseHandle( info.hThread );
2495 CloseHandle( info.hProcess );
2497 else if ((ret = GetLastError()) >= 32)
2499 FIXME("Strange error set by CreateProcess: %d\n", ret );
2502 HeapFree( GetProcessHeap(), 0, cmdline );
2507 /**********************************************************************
2508 * LoadModule (KERNEL32.@)
2510 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2512 LOADPARMS32 *params = paramBlock;
2513 PROCESS_INFORMATION info;
2514 STARTUPINFOA startup;
2517 char filename[MAX_PATH];
2520 if (!name) return ERROR_FILE_NOT_FOUND;
2522 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2523 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2524 return GetLastError();
2526 len = (BYTE)params->lpCmdLine[0];
2527 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2528 return ERROR_NOT_ENOUGH_MEMORY;
2530 strcpy( cmdline, filename );
2531 p = cmdline + strlen(cmdline);
2533 memcpy( p, params->lpCmdLine + 1, len );
2536 memset( &startup, 0, sizeof(startup) );
2537 startup.cb = sizeof(startup);
2538 if (params->lpCmdShow)
2540 startup.dwFlags = STARTF_USESHOWWINDOW;
2541 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2544 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2545 params->lpEnvAddress, NULL, &startup, &info ))
2547 /* Give 30 seconds to the app to come up */
2548 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2549 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2551 /* Close off the handles */
2552 CloseHandle( info.hThread );
2553 CloseHandle( info.hProcess );
2555 else if ((ret = GetLastError()) >= 32)
2557 FIXME("Strange error set by CreateProcess: %u\n", ret );
2561 HeapFree( GetProcessHeap(), 0, cmdline );
2566 /******************************************************************************
2567 * TerminateProcess (KERNEL32.@)
2569 * Terminates a process.
2572 * handle [I] Process to terminate.
2573 * exit_code [I] Exit code.
2577 * Failure: FALSE, check GetLastError().
2579 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2581 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2582 if (status) SetLastError( RtlNtStatusToDosError(status) );
2586 /***********************************************************************
2587 * ExitProcess (KERNEL32.@)
2589 * Exits the current process.
2592 * status [I] Status code to exit with.
2598 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2600 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2601 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2602 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2604 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2608 void WINAPI process_ExitProcess( DWORD status )
2610 LdrShutdownProcess();
2611 NtTerminateProcess(GetCurrentProcess(), status);
2617 void WINAPI ExitProcess( DWORD status )
2619 LdrShutdownProcess();
2620 NtTerminateProcess(GetCurrentProcess(), status);
2626 /***********************************************************************
2627 * GetExitCodeProcess [KERNEL32.@]
2629 * Gets termination status of specified process.
2632 * hProcess [in] Handle to the process.
2633 * lpExitCode [out] Address to receive termination status.
2639 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2642 PROCESS_BASIC_INFORMATION pbi;
2644 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2646 if (status == STATUS_SUCCESS)
2648 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2651 SetLastError( RtlNtStatusToDosError(status) );
2656 /***********************************************************************
2657 * SetErrorMode (KERNEL32.@)
2659 UINT WINAPI SetErrorMode( UINT mode )
2663 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2664 &old, sizeof(old), NULL );
2665 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2666 &mode, sizeof(mode) );
2670 /***********************************************************************
2671 * GetErrorMode (KERNEL32.@)
2673 UINT WINAPI GetErrorMode( void )
2677 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2678 &mode, sizeof(mode), NULL );
2682 /**********************************************************************
2683 * TlsAlloc [KERNEL32.@]
2685 * Allocates a thread local storage index.
2688 * Success: TLS index.
2689 * Failure: 0xFFFFFFFF
2691 DWORD WINAPI TlsAlloc( void )
2694 PEB * const peb = NtCurrentTeb()->Peb;
2696 RtlAcquirePebLock();
2697 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2698 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2701 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2704 if (!NtCurrentTeb()->TlsExpansionSlots &&
2705 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2706 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2708 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2710 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2714 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2715 index += TLS_MINIMUM_AVAILABLE;
2718 else SetLastError( ERROR_NO_MORE_ITEMS );
2720 RtlReleasePebLock();
2725 /**********************************************************************
2726 * TlsFree [KERNEL32.@]
2728 * Releases a thread local storage index, making it available for reuse.
2731 * index [in] TLS index to free.
2737 BOOL WINAPI TlsFree( DWORD index )
2741 RtlAcquirePebLock();
2742 if (index >= TLS_MINIMUM_AVAILABLE)
2744 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2745 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2749 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2750 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2752 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2753 else SetLastError( ERROR_INVALID_PARAMETER );
2754 RtlReleasePebLock();
2759 /**********************************************************************
2760 * TlsGetValue [KERNEL32.@]
2762 * Gets value in a thread's TLS slot.
2765 * index [in] TLS index to retrieve value for.
2768 * Success: Value stored in calling thread's TLS slot for index.
2769 * Failure: 0 and GetLastError() returns NO_ERROR.
2771 LPVOID WINAPI TlsGetValue( DWORD index )
2775 if (index < TLS_MINIMUM_AVAILABLE)
2777 ret = NtCurrentTeb()->TlsSlots[index];
2781 index -= TLS_MINIMUM_AVAILABLE;
2782 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2784 SetLastError( ERROR_INVALID_PARAMETER );
2787 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2788 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2790 SetLastError( ERROR_SUCCESS );
2795 /**********************************************************************
2796 * TlsSetValue [KERNEL32.@]
2798 * Stores a value in the thread's TLS slot.
2801 * index [in] TLS index to set value for.
2802 * value [in] Value to be stored.
2808 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2810 if (index < TLS_MINIMUM_AVAILABLE)
2812 NtCurrentTeb()->TlsSlots[index] = value;
2816 index -= TLS_MINIMUM_AVAILABLE;
2817 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2819 SetLastError( ERROR_INVALID_PARAMETER );
2822 if (!NtCurrentTeb()->TlsExpansionSlots &&
2823 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2824 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2826 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2829 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2835 /***********************************************************************
2836 * GetProcessFlags (KERNEL32.@)
2838 DWORD WINAPI GetProcessFlags( DWORD processid )
2840 IMAGE_NT_HEADERS *nt;
2843 if (processid && processid != GetCurrentProcessId()) return 0;
2845 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2847 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2848 flags |= PDB32_CONSOLE_PROC;
2850 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2851 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2856 /*********************************************************************
2857 * OpenProcess (KERNEL32.@)
2859 * Opens a handle to a process.
2862 * access [I] Desired access rights assigned to the returned handle.
2863 * inherit [I] Determines whether or not child processes will inherit the handle.
2864 * id [I] Process identifier of the process to get a handle to.
2867 * Success: Valid handle to the specified process.
2868 * Failure: NULL, check GetLastError().
2870 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2874 OBJECT_ATTRIBUTES attr;
2877 cid.UniqueProcess = ULongToHandle(id);
2878 cid.UniqueThread = 0; /* FIXME ? */
2880 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2881 attr.RootDirectory = NULL;
2882 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2883 attr.SecurityDescriptor = NULL;
2884 attr.SecurityQualityOfService = NULL;
2885 attr.ObjectName = NULL;
2887 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2889 status = NtOpenProcess(&handle, access, &attr, &cid);
2890 if (status != STATUS_SUCCESS)
2892 SetLastError( RtlNtStatusToDosError(status) );
2899 /*********************************************************************
2900 * GetProcessId (KERNEL32.@)
2902 * Gets the a unique identifier of a process.
2905 * hProcess [I] Handle to the process.
2909 * Failure: FALSE, check GetLastError().
2913 * The identifier is unique only on the machine and only until the process
2914 * exits (including system shutdown).
2916 DWORD WINAPI GetProcessId( HANDLE hProcess )
2919 PROCESS_BASIC_INFORMATION pbi;
2921 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2923 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2924 SetLastError( RtlNtStatusToDosError(status) );
2929 /*********************************************************************
2930 * CloseHandle (KERNEL32.@)
2935 * handle [I] Handle to close.
2939 * Failure: FALSE, check GetLastError().
2941 BOOL WINAPI CloseHandle( HANDLE handle )
2945 /* stdio handles need special treatment */
2946 if (handle == (HANDLE)STD_INPUT_HANDLE)
2947 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
2948 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
2949 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
2950 else if (handle == (HANDLE)STD_ERROR_HANDLE)
2951 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
2953 if (is_console_handle(handle))
2954 return CloseConsoleHandle(handle);
2956 status = NtClose( handle );
2957 if (status) SetLastError( RtlNtStatusToDosError(status) );
2962 /*********************************************************************
2963 * GetHandleInformation (KERNEL32.@)
2965 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2967 OBJECT_DATA_INFORMATION info;
2968 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2970 if (status) SetLastError( RtlNtStatusToDosError(status) );
2974 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2975 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2981 /*********************************************************************
2982 * SetHandleInformation (KERNEL32.@)
2984 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2986 OBJECT_DATA_INFORMATION info;
2989 /* if not setting both fields, retrieve current value first */
2990 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2991 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2993 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2995 SetLastError( RtlNtStatusToDosError(status) );
2999 if (mask & HANDLE_FLAG_INHERIT)
3000 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3001 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3002 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3004 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3005 if (status) SetLastError( RtlNtStatusToDosError(status) );
3010 /*********************************************************************
3011 * DuplicateHandle (KERNEL32.@)
3013 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3014 HANDLE dest_process, HANDLE *dest,
3015 DWORD access, BOOL inherit, DWORD options )
3019 if (is_console_handle(source))
3021 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3022 if (source_process != dest_process ||
3023 source_process != GetCurrentProcess())
3025 SetLastError(ERROR_INVALID_PARAMETER);
3028 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3029 return (*dest != INVALID_HANDLE_VALUE);
3031 status = NtDuplicateObject( source_process, source, dest_process, dest,
3032 access, inherit ? OBJ_INHERIT : 0, options );
3033 if (status) SetLastError( RtlNtStatusToDosError(status) );
3038 /***********************************************************************
3039 * ConvertToGlobalHandle (KERNEL32.@)
3041 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3043 HANDLE ret = INVALID_HANDLE_VALUE;
3044 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3045 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3050 /***********************************************************************
3051 * SetHandleContext (KERNEL32.@)
3053 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3055 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3056 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3057 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3062 /***********************************************************************
3063 * GetHandleContext (KERNEL32.@)
3065 DWORD WINAPI GetHandleContext(HANDLE hnd)
3067 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3068 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3069 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3074 /***********************************************************************
3075 * CreateSocketHandle (KERNEL32.@)
3077 HANDLE WINAPI CreateSocketHandle(void)
3079 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3080 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3081 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3082 return INVALID_HANDLE_VALUE;
3086 /***********************************************************************
3087 * SetPriorityClass (KERNEL32.@)
3089 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3092 PROCESS_PRIORITY_CLASS ppc;
3094 ppc.Foreground = FALSE;
3095 switch (priorityclass)
3097 case IDLE_PRIORITY_CLASS:
3098 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3099 case BELOW_NORMAL_PRIORITY_CLASS:
3100 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3101 case NORMAL_PRIORITY_CLASS:
3102 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3103 case ABOVE_NORMAL_PRIORITY_CLASS:
3104 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3105 case HIGH_PRIORITY_CLASS:
3106 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3107 case REALTIME_PRIORITY_CLASS:
3108 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3110 SetLastError(ERROR_INVALID_PARAMETER);
3114 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3117 if (status != STATUS_SUCCESS)
3119 SetLastError( RtlNtStatusToDosError(status) );
3126 /***********************************************************************
3127 * GetPriorityClass (KERNEL32.@)
3129 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3132 PROCESS_BASIC_INFORMATION pbi;
3134 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3136 if (status != STATUS_SUCCESS)
3138 SetLastError( RtlNtStatusToDosError(status) );
3141 switch (pbi.BasePriority)
3143 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3144 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3145 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3146 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3147 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3148 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3150 SetLastError( ERROR_INVALID_PARAMETER );
3155 /***********************************************************************
3156 * SetProcessAffinityMask (KERNEL32.@)
3158 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3162 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3163 &affmask, sizeof(DWORD_PTR));
3166 SetLastError( RtlNtStatusToDosError(status) );
3173 /**********************************************************************
3174 * GetProcessAffinityMask (KERNEL32.@)
3176 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3178 NTSTATUS status = STATUS_SUCCESS;
3180 if (system_mask) *system_mask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
3183 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3184 process_mask, sizeof(*process_mask), NULL )))
3185 SetLastError( RtlNtStatusToDosError(status) );
3191 /***********************************************************************
3192 * GetProcessVersion (KERNEL32.@)
3194 DWORD WINAPI GetProcessVersion( DWORD pid )
3198 PROCESS_BASIC_INFORMATION pbi;
3201 IMAGE_DOS_HEADER dos;
3202 IMAGE_NT_HEADERS nt;
3205 if (!pid || pid == GetCurrentProcessId())
3207 IMAGE_NT_HEADERS *pnt;
3209 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3210 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3211 pnt->OptionalHeader.MinorSubsystemVersion);
3215 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3216 if (!process) return 0;
3218 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3219 if (status) goto err;
3221 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3222 if (status || count != sizeof(peb)) goto err;
3224 memset(&dos, 0, sizeof(dos));
3225 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3226 if (status || count != sizeof(dos)) goto err;
3227 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3229 memset(&nt, 0, sizeof(nt));
3230 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3231 if (status || count != sizeof(nt)) goto err;
3232 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3234 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3237 CloseHandle(process);
3239 if (status != STATUS_SUCCESS)
3240 SetLastError(RtlNtStatusToDosError(status));
3246 /***********************************************************************
3247 * SetProcessWorkingSetSize [KERNEL32.@]
3248 * Sets the min/max working set sizes for a specified process.
3251 * hProcess [I] Handle to the process of interest
3252 * minset [I] Specifies minimum working set size
3253 * maxset [I] Specifies maximum working set size
3259 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3262 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3263 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3264 /* Trim the working set to zero */
3265 /* Swap the process out of physical RAM */
3270 /***********************************************************************
3271 * K32EmptyWorkingSet (KERNEL32.@)
3273 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3275 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3278 /***********************************************************************
3279 * GetProcessWorkingSetSize (KERNEL32.@)
3281 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3284 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3285 /* 32 MB working set size */
3286 if (minset) *minset = 32*1024*1024;
3287 if (maxset) *maxset = 32*1024*1024;
3292 /***********************************************************************
3293 * SetProcessShutdownParameters (KERNEL32.@)
3295 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3297 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3298 shutdown_flags = flags;
3299 shutdown_priority = level;
3304 /***********************************************************************
3305 * GetProcessShutdownParameters (KERNEL32.@)
3308 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3310 *lpdwLevel = shutdown_priority;
3311 *lpdwFlags = shutdown_flags;
3316 /***********************************************************************
3317 * GetProcessPriorityBoost (KERNEL32.@)
3319 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3321 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3323 /* Report that no boost is present.. */
3324 *pDisablePriorityBoost = FALSE;
3329 /***********************************************************************
3330 * SetProcessPriorityBoost (KERNEL32.@)
3332 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3334 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3335 /* Say we can do it. I doubt the program will notice that we don't. */
3340 /***********************************************************************
3341 * ReadProcessMemory (KERNEL32.@)
3343 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3344 SIZE_T *bytes_read )
3346 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3347 if (status) SetLastError( RtlNtStatusToDosError(status) );
3352 /***********************************************************************
3353 * WriteProcessMemory (KERNEL32.@)
3355 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3356 SIZE_T *bytes_written )
3358 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3359 if (status) SetLastError( RtlNtStatusToDosError(status) );
3364 /****************************************************************************
3365 * FlushInstructionCache (KERNEL32.@)
3367 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3370 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3371 if (status) SetLastError( RtlNtStatusToDosError(status) );
3376 /******************************************************************
3377 * GetProcessIoCounters (KERNEL32.@)
3379 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3383 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3384 ioc, sizeof(*ioc), NULL);
3385 if (status) SetLastError( RtlNtStatusToDosError(status) );
3389 /******************************************************************
3390 * GetProcessHandleCount (KERNEL32.@)
3392 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3396 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3397 cnt, sizeof(*cnt), NULL);
3398 if (status) SetLastError( RtlNtStatusToDosError(status) );
3402 /******************************************************************
3403 * QueryFullProcessImageNameA (KERNEL32.@)
3405 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3408 DWORD pdwSizeW = *pdwSize;
3409 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3411 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3414 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3415 lpExeName, *pdwSize, NULL, NULL));
3417 *pdwSize = strlen(lpExeName);
3419 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3423 /******************************************************************
3424 * QueryFullProcessImageNameW (KERNEL32.@)
3426 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3428 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3429 UNICODE_STRING *dynamic_buffer = NULL;
3430 UNICODE_STRING *result = NULL;
3434 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3435 * is a DOS path and we depend on this. */
3436 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3437 sizeof(buffer) - sizeof(WCHAR), &needed);
3438 if (status == STATUS_INFO_LENGTH_MISMATCH)
3440 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3441 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3442 result = dynamic_buffer;
3445 result = (PUNICODE_STRING)buffer;
3447 if (status) goto cleanup;
3449 if (dwFlags & PROCESS_NAME_NATIVE)
3453 DWORD ntlen, devlen;
3455 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3457 /* We cannot convert it to an NT device path so fail */
3458 status = STATUS_NO_SUCH_DEVICE;
3462 /* Find this drive's NT device path */
3463 drive[0] = result->Buffer[0];
3466 if (!QueryDosDeviceW(drive, device, sizeof(device)/sizeof(*device)))
3468 status = STATUS_NO_SUCH_DEVICE;
3472 devlen = lstrlenW(device);
3473 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3474 if (ntlen + 1 > *pdwSize)
3476 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3481 memcpy(lpExeName, device, devlen * sizeof(*device));
3482 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3483 lpExeName[*pdwSize] = 0;
3484 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3488 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3490 status = STATUS_BUFFER_TOO_SMALL;
3494 *pdwSize = result->Length/sizeof(WCHAR);
3495 memcpy( lpExeName, result->Buffer, result->Length );
3496 lpExeName[*pdwSize] = 0;
3500 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3501 if (status) SetLastError( RtlNtStatusToDosError(status) );
3505 /***********************************************************************
3506 * K32GetProcessImageFileNameA (KERNEL32.@)
3508 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3510 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3513 /***********************************************************************
3514 * K32GetProcessImageFileNameW (KERNEL32.@)
3516 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3518 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3521 /***********************************************************************
3522 * K32EnumProcesses (KERNEL32.@)
3524 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3526 SYSTEM_PROCESS_INFORMATION *spi;
3527 ULONG size = 0x4000;
3533 HeapFree(GetProcessHeap(), 0, buf);
3534 buf = HeapAlloc(GetProcessHeap(), 0, size);
3538 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3539 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3541 if (status != STATUS_SUCCESS)
3543 HeapFree(GetProcessHeap(), 0, buf);
3544 SetLastError(RtlNtStatusToDosError(status));
3550 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3552 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3553 *lpcbUsed += sizeof(DWORD);
3555 if (spi->NextEntryOffset == 0)
3558 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3561 HeapFree(GetProcessHeap(), 0, buf);
3565 /***********************************************************************
3566 * K32QueryWorkingSet (KERNEL32.@)
3568 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3572 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3574 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3578 SetLastError( RtlNtStatusToDosError( status ) );
3584 /***********************************************************************
3585 * K32QueryWorkingSetEx (KERNEL32.@)
3587 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3591 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3593 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3597 SetLastError( RtlNtStatusToDosError( status ) );
3603 /***********************************************************************
3604 * K32GetProcessMemoryInfo (KERNEL32.@)
3606 * Retrieve memory usage information for a given process
3609 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3610 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3615 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3617 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3621 status = NtQueryInformationProcess(process, ProcessVmCounters,
3622 &vmc, sizeof(vmc), NULL);
3626 SetLastError(RtlNtStatusToDosError(status));
3630 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3631 pmc->PageFaultCount = vmc.PageFaultCount;
3632 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3633 pmc->WorkingSetSize = vmc.WorkingSetSize;
3634 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3635 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3636 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3637 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3638 pmc->PagefileUsage = vmc.PagefileUsage;
3639 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3644 /***********************************************************************
3645 * ProcessIdToSessionId (KERNEL32.@)
3646 * This function is available on Terminal Server 4SP4 and Windows 2000
3648 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3650 /* According to MSDN, if the calling process is not in a terminal
3651 * services environment, then the sessionid returned is zero.
3658 /***********************************************************************
3659 * RegisterServiceProcess (KERNEL32.@)
3661 * A service process calls this function to ensure that it continues to run
3662 * even after a user logged off.
3664 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3666 /* I don't think that Wine needs to do anything in this function */
3667 return 1; /* success */
3671 /**********************************************************************
3672 * IsWow64Process (KERNEL32.@)
3674 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3679 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3681 if (status != STATUS_SUCCESS)
3683 SetLastError( RtlNtStatusToDosError( status ) );
3686 *Wow64Process = (pbi != 0);
3691 /***********************************************************************
3692 * GetCurrentProcess (KERNEL32.@)
3694 * Get a handle to the current process.
3700 * A handle representing the current process.
3702 #undef GetCurrentProcess
3703 HANDLE WINAPI GetCurrentProcess(void)
3705 return (HANDLE)~(ULONG_PTR)0;
3708 /***********************************************************************
3709 * GetLogicalProcessorInformation (KERNEL32.@)
3711 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3713 FIXME("(%p,%p): stub\n", buffer, pBufLen);
3714 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3718 /***********************************************************************
3719 * GetLogicalProcessorInformationEx (KERNEL32.@)
3721 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer, PDWORD pBufLen)
3723 FIXME("(%u,%p,%p): stub\n", relationship, buffer, pBufLen);
3724 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3728 /***********************************************************************
3729 * CmdBatNotification (KERNEL32.@)
3731 * Notifies the system that a batch file has started or finished.
3734 * bBatchRunning [I] TRUE if a batch file has started or
3735 * FALSE if a batch file has finished executing.
3740 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3742 FIXME("%d\n", bBatchRunning);
3747 /***********************************************************************
3748 * RegisterApplicationRestart (KERNEL32.@)
3750 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3752 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3757 /**********************************************************************
3758 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3760 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3766 /**********************************************************************
3767 * GetSystemDEPPolicy (KERNEL32.@)
3769 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3775 /**********************************************************************
3776 * SetProcessDEPPolicy (KERNEL32.@)
3778 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3780 FIXME("(%d): stub\n", newDEP);
3781 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3785 /**********************************************************************
3786 * ApplicationRecoveryFinished (KERNEL32.@)
3788 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
3791 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3794 /**********************************************************************
3795 * ApplicationRecoveryInProgress (KERNEL32.@)
3797 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
3799 FIXME(":%p stub\n", canceled);
3800 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3804 /**********************************************************************
3805 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3807 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
3809 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
3810 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3814 /**********************************************************************
3815 * GetNumaHighestNodeNumber (KERNEL32.@)
3817 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
3819 FIXME("(%p): stub\n", highestnode);
3820 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3824 /**********************************************************************
3825 * GetNumaNodeProcessorMask (KERNEL32.@)
3827 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
3829 FIXME("(%c %p): stub\n", node, mask);
3830 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3834 /**********************************************************************
3835 * GetNumaAvailableMemoryNode (KERNEL32.@)
3837 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
3839 FIXME("(%c %p): stub\n", node, available_bytes);
3840 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3844 /**********************************************************************
3845 * GetProcessDEPPolicy (KERNEL32.@)
3847 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
3849 FIXME("(%p %p %p): stub\n", process, flags, permanent);
3850 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);