riched20: Implement IsEqual() for ranges.
[wine.git] / dlls / kernel32 / process.c
blob2c8074b909626ed1264e0ecc6b8f0ae4f7a9c302
1 /*
2 * Win32 processes
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
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <signal.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <time.h>
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
33 #endif
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
36 #endif
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
39 #endif
40 #ifdef HAVE_SYS_PRCTL_H
41 # include <sys/prctl.h>
42 #endif
43 #include <sys/types.h>
44 #ifdef HAVE_SYS_WAIT_H
45 # include <sys/wait.h>
46 #endif
47 #ifdef HAVE_UNISTD_H
48 # include <unistd.h>
49 #endif
50 #ifdef __APPLE__
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <pthread.h>
53 #endif
55 #include "ntstatus.h"
56 #define WIN32_NO_STATUS
57 #include "winternl.h"
58 #include "kernel_private.h"
59 #include "psapi.h"
60 #include "wine/library.h"
61 #include "wine/server.h"
62 #include "wine/unicode.h"
63 #include "wine/debug.h"
65 WINE_DEFAULT_DEBUG_CHANNEL(process);
66 WINE_DECLARE_DEBUG_CHANNEL(file);
67 WINE_DECLARE_DEBUG_CHANNEL(relay);
69 #ifdef __APPLE__
70 extern char **__wine_get_main_environment(void);
71 #else
72 extern char **__wine_main_environ;
73 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
74 #endif
76 typedef struct
78 LPSTR lpEnvAddress;
79 LPSTR lpCmdLine;
80 LPSTR lpCmdShow;
81 DWORD dwReserved;
82 } LOADPARMS32;
84 static DWORD shutdown_flags = 0;
85 static DWORD shutdown_priority = 0x280;
86 static BOOL is_wow64;
87 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
89 HMODULE kernel32_handle = 0;
90 SYSTEM_BASIC_INFORMATION system_info = { 0 };
92 const WCHAR *DIR_Windows = NULL;
93 const WCHAR *DIR_System = NULL;
94 const WCHAR *DIR_SysWow64 = NULL;
96 /* Process flags */
97 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
98 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
99 #define PDB32_DOS_PROC 0x0010 /* Dos process */
100 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
101 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
102 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
104 static const WCHAR exeW[] = {'.','e','x','e',0};
105 static const WCHAR comW[] = {'.','c','o','m',0};
106 static const WCHAR batW[] = {'.','b','a','t',0};
107 static const WCHAR cmdW[] = {'.','c','m','d',0};
108 static const WCHAR pifW[] = {'.','p','i','f',0};
109 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
111 static void exec_process( LPCWSTR name );
113 extern void SHELL_LoadRegistry(void);
116 /***********************************************************************
117 * contains_path
119 static inline BOOL contains_path( LPCWSTR name )
121 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
125 /***********************************************************************
126 * is_special_env_var
128 * Check if an environment variable needs to be handled specially when
129 * passed through the Unix environment (i.e. prefixed with "WINE").
131 static inline BOOL is_special_env_var( const char *var )
133 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
134 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
135 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
136 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
137 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
141 /***********************************************************************
142 * is_path_prefix
144 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
146 unsigned int len = strlenW( prefix );
148 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
149 while (filename[len] == '\\') len++;
150 return len;
154 /***************************************************************************
155 * get_builtin_path
157 * Get the path of a builtin module when the native file does not exist.
159 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
160 UINT size, struct binary_info *binary_info )
162 WCHAR *file_part;
163 UINT len;
164 void *redir_disabled = 0;
165 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
167 /* builtin names cannot be empty or contain spaces */
168 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
170 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
171 Wow64RevertWow64FsRedirection( redir_disabled );
173 if (contains_path( libname ))
175 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
176 filename, &file_part ) > size * sizeof(WCHAR))
177 return FALSE; /* too long */
179 if ((len = is_path_prefix( DIR_System, filename )))
181 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
183 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
185 flags = 0;
187 else return FALSE;
189 if (filename + len != file_part) return FALSE;
191 else
193 len = strlenW( DIR_System );
194 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
195 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
196 file_part = filename + len;
197 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
198 strcpyW( file_part, libname );
199 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
201 if (ext && !strchrW( file_part, '.' ))
203 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
204 return FALSE; /* too long */
205 strcatW( file_part, ext );
207 binary_info->type = BINARY_UNIX_LIB;
208 binary_info->flags = flags;
209 binary_info->res_start = NULL;
210 binary_info->res_end = NULL;
211 /* assume current arch */
212 #if defined(__i386__) || defined(__x86_64__)
213 binary_info->arch = (flags & BINARY_FLAG_64BIT) ? IMAGE_FILE_MACHINE_AMD64 : IMAGE_FILE_MACHINE_I386;
214 #elif defined(__powerpc__)
215 binary_info->arch = IMAGE_FILE_MACHINE_POWERPC;
216 #elif defined(__arm__) && !defined(__ARMEB__)
217 binary_info->arch = IMAGE_FILE_MACHINE_ARMNT;
218 #elif defined(__aarch64__)
219 binary_info->arch = IMAGE_FILE_MACHINE_ARM64;
220 #else
221 binary_info->arch = IMAGE_FILE_MACHINE_UNKNOWN;
222 #endif
223 return TRUE;
227 /***********************************************************************
228 * open_exe_file
230 * Open a specific exe file, taking load order into account.
231 * Returns the file handle or 0 for a builtin exe.
233 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
235 HANDLE handle;
237 TRACE("looking for %s\n", debugstr_w(name) );
239 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
240 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
242 WCHAR buffer[MAX_PATH];
243 /* file doesn't exist, check for builtin */
244 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
245 handle = 0;
247 else MODULE_get_binary_info( handle, binary_info );
249 return handle;
253 /***********************************************************************
254 * find_exe_file
256 * Open an exe file, and return the full name and file handle.
257 * Returns FALSE if file could not be found.
259 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
260 HANDLE *handle, struct binary_info *binary_info )
262 TRACE("looking for %s\n", debugstr_w(name) );
264 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
265 /* no builtin found, try native without extension in case it is a Unix app */
266 !SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
268 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
269 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
270 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
272 MODULE_get_binary_info( *handle, binary_info );
273 return TRUE;
275 return FALSE;
279 /***********************************************************************
280 * build_initial_environment
282 * Build the Win32 environment from the Unix environment
284 static BOOL build_initial_environment(void)
286 SIZE_T size = 1;
287 char **e;
288 WCHAR *p, *endptr;
289 void *ptr;
290 char **env = __wine_get_main_environment();
292 /* Compute the total size of the Unix environment */
293 for (e = env; *e; e++)
295 if (is_special_env_var( *e )) continue;
296 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
298 size *= sizeof(WCHAR);
300 /* Now allocate the environment */
301 ptr = NULL;
302 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
303 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
304 return FALSE;
306 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
307 endptr = p + size / sizeof(WCHAR);
309 /* And fill it with the Unix environment */
310 for (e = env; *e; e++)
312 char *str = *e;
314 /* skip Unix special variables and use the Wine variants instead */
315 if (!strncmp( str, "WINE", 4 ))
317 if (is_special_env_var( str + 4 )) str += 4;
318 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
320 else if (is_special_env_var( str )) continue; /* skip it */
322 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
323 p += strlenW(p) + 1;
325 *p = 0;
326 return TRUE;
330 /***********************************************************************
331 * set_registry_variables
333 * Set environment variables by enumerating the values of a key;
334 * helper for set_registry_environment().
335 * Note that Windows happily truncates the value if it's too big.
337 static void set_registry_variables( HANDLE hkey, ULONG type )
339 static const WCHAR pathW[] = {'P','A','T','H'};
340 static const WCHAR sep[] = {';',0};
341 UNICODE_STRING env_name, env_value;
342 NTSTATUS status;
343 DWORD size;
344 int index;
345 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
346 WCHAR tmpbuf[1024];
347 UNICODE_STRING tmp;
348 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
350 tmp.Buffer = tmpbuf;
351 tmp.MaximumLength = sizeof(tmpbuf);
353 for (index = 0; ; index++)
355 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
356 buffer, sizeof(buffer), &size );
357 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
358 break;
359 if (info->Type != type)
360 continue;
361 env_name.Buffer = info->Name;
362 env_name.Length = env_name.MaximumLength = info->NameLength;
363 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
364 env_value.Length = info->DataLength;
365 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
366 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
367 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
368 if (!env_value.Length) continue;
369 if (info->Type == REG_EXPAND_SZ)
371 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
372 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
373 RtlCopyUnicodeString( &env_value, &tmp );
375 /* PATH is magic */
376 if (env_name.Length == sizeof(pathW) &&
377 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
378 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
380 RtlAppendUnicodeToString( &tmp, sep );
381 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
382 RtlCopyUnicodeString( &env_value, &tmp );
384 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
389 /***********************************************************************
390 * set_registry_environment
392 * Set the environment variables specified in the registry.
394 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
395 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
396 * on the order in which the variables are processed. But on Windows it
397 * does not really matter since they only use %SystemDrive% and
398 * %SystemRoot% which are predefined. But Wine defines these in the
399 * registry, so we need two passes.
401 static BOOL set_registry_environment( BOOL volatile_only )
403 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
404 'S','y','s','t','e','m','\\',
405 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
406 'C','o','n','t','r','o','l','\\',
407 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
408 'E','n','v','i','r','o','n','m','e','n','t',0};
409 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
410 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};
412 OBJECT_ATTRIBUTES attr;
413 UNICODE_STRING nameW;
414 HANDLE hkey;
415 BOOL ret = FALSE;
417 attr.Length = sizeof(attr);
418 attr.RootDirectory = 0;
419 attr.ObjectName = &nameW;
420 attr.Attributes = 0;
421 attr.SecurityDescriptor = NULL;
422 attr.SecurityQualityOfService = NULL;
424 /* first the system environment variables */
425 RtlInitUnicodeString( &nameW, env_keyW );
426 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
428 set_registry_variables( hkey, REG_SZ );
429 set_registry_variables( hkey, REG_EXPAND_SZ );
430 NtClose( hkey );
431 ret = TRUE;
434 /* then the ones for the current user */
435 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
436 RtlInitUnicodeString( &nameW, envW );
437 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
439 set_registry_variables( hkey, REG_SZ );
440 set_registry_variables( hkey, REG_EXPAND_SZ );
441 NtClose( hkey );
444 RtlInitUnicodeString( &nameW, volatile_envW );
445 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
447 set_registry_variables( hkey, REG_SZ );
448 set_registry_variables( hkey, REG_EXPAND_SZ );
449 NtClose( hkey );
452 NtClose( attr.RootDirectory );
453 return ret;
457 /***********************************************************************
458 * get_reg_value
460 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
462 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
463 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
464 DWORD len, size = sizeof(buffer);
465 WCHAR *ret = NULL;
466 UNICODE_STRING nameW;
468 RtlInitUnicodeString( &nameW, name );
469 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
470 return NULL;
472 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
473 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
475 if (info->Type == REG_EXPAND_SZ)
477 UNICODE_STRING value, expanded;
479 value.MaximumLength = len * sizeof(WCHAR);
480 value.Buffer = (WCHAR *)info->Data;
481 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
482 value.Length = len * sizeof(WCHAR);
483 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
484 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
485 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
486 else RtlFreeUnicodeString( &expanded );
488 else if (info->Type == REG_SZ)
490 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
492 memcpy( ret, info->Data, len * sizeof(WCHAR) );
493 ret[len] = 0;
496 return ret;
500 /***********************************************************************
501 * set_additional_environment
503 * Set some additional environment variables not specified in the registry.
505 static void set_additional_environment(void)
507 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
508 'S','o','f','t','w','a','r','e','\\',
509 'M','i','c','r','o','s','o','f','t','\\',
510 'W','i','n','d','o','w','s',' ','N','T','\\',
511 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
512 'P','r','o','f','i','l','e','L','i','s','t',0};
513 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
514 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
515 static const WCHAR computernameW[] = {'C','O','M','P','U','T','E','R','N','A','M','E',0};
516 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
517 OBJECT_ATTRIBUTES attr;
518 UNICODE_STRING nameW;
519 WCHAR *profile_dir = NULL, *all_users_dir = NULL;
520 WCHAR buf[MAX_COMPUTERNAME_LENGTH];
521 HANDLE hkey;
522 DWORD len;
524 /* ComputerName */
525 len = sizeof(buf) / sizeof(WCHAR);
526 if (GetComputerNameW( buf, &len ))
527 SetEnvironmentVariableW( computernameW, buf );
529 /* set the ALLUSERSPROFILE variables */
531 attr.Length = sizeof(attr);
532 attr.RootDirectory = 0;
533 attr.ObjectName = &nameW;
534 attr.Attributes = 0;
535 attr.SecurityDescriptor = NULL;
536 attr.SecurityQualityOfService = NULL;
537 RtlInitUnicodeString( &nameW, profile_keyW );
538 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
540 profile_dir = get_reg_value( hkey, profiles_valueW );
541 all_users_dir = get_reg_value( hkey, all_users_valueW );
542 NtClose( hkey );
545 if (profile_dir && all_users_dir)
547 WCHAR *value, *p;
549 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
550 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
551 strcpyW( value, profile_dir );
552 p = value + strlenW(value);
553 if (p > value && p[-1] != '\\') *p++ = '\\';
554 strcpyW( p, all_users_dir );
555 SetEnvironmentVariableW( allusersW, value );
556 HeapFree( GetProcessHeap(), 0, value );
559 HeapFree( GetProcessHeap(), 0, all_users_dir );
560 HeapFree( GetProcessHeap(), 0, profile_dir );
563 /***********************************************************************
564 * set_wow64_environment
566 * Set the environment variables that change across 32/64/Wow64.
568 static void set_wow64_environment(void)
570 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};
571 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};
572 static const WCHAR x86W[] = {'x','8','6',0};
573 static const WCHAR versionW[] = {'M','a','c','h','i','n','e','\\',
574 'S','o','f','t','w','a','r','e','\\',
575 'M','i','c','r','o','s','o','f','t','\\',
576 'W','i','n','d','o','w','s','\\',
577 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
578 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
579 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
580 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
581 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
582 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
583 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
584 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
585 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
587 OBJECT_ATTRIBUTES attr;
588 UNICODE_STRING nameW;
589 WCHAR arch[64];
590 WCHAR *value;
591 HANDLE hkey;
593 /* set the PROCESSOR_ARCHITECTURE variable */
595 if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
597 if (is_win64)
599 SetEnvironmentVariableW( archW, arch );
600 SetEnvironmentVariableW( arch6432W, NULL );
603 else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
605 if (is_wow64)
607 SetEnvironmentVariableW( arch6432W, arch );
608 SetEnvironmentVariableW( archW, x86W );
612 attr.Length = sizeof(attr);
613 attr.RootDirectory = 0;
614 attr.ObjectName = &nameW;
615 attr.Attributes = 0;
616 attr.SecurityDescriptor = NULL;
617 attr.SecurityQualityOfService = NULL;
618 RtlInitUnicodeString( &nameW, versionW );
619 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
621 /* set the ProgramFiles variables */
623 if ((value = get_reg_value( hkey, progdirW )))
625 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
626 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
627 HeapFree( GetProcessHeap(), 0, value );
629 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
631 SetEnvironmentVariableW( progfilesW, value );
632 HeapFree( GetProcessHeap(), 0, value );
635 /* set the CommonProgramFiles variables */
637 if ((value = get_reg_value( hkey, commondirW )))
639 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
640 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
641 HeapFree( GetProcessHeap(), 0, value );
643 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
645 SetEnvironmentVariableW( commonfilesW, value );
646 HeapFree( GetProcessHeap(), 0, value );
649 NtClose( hkey );
652 /***********************************************************************
653 * set_library_wargv
655 * Set the Wine library Unicode argv global variables.
657 static void set_library_wargv( char **argv )
659 int argc;
660 char *q;
661 WCHAR *p;
662 WCHAR **wargv;
663 DWORD total = 0;
665 for (argc = 0; argv[argc]; argc++)
666 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
668 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
669 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
670 p = (WCHAR *)(wargv + argc + 1);
671 for (argc = 0; argv[argc]; argc++)
673 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
674 wargv[argc] = p;
675 p += reslen;
676 total -= reslen;
678 wargv[argc] = NULL;
680 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
682 for (argc = 0; wargv[argc]; argc++)
683 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
685 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
686 q = (char *)(argv + argc + 1);
687 for (argc = 0; wargv[argc]; argc++)
689 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
690 argv[argc] = q;
691 q += reslen;
692 total -= reslen;
694 argv[argc] = NULL;
696 __wine_main_argc = argc;
697 __wine_main_argv = argv;
698 __wine_main_wargv = wargv;
702 /***********************************************************************
703 * update_library_argv0
705 * Update the argv[0] global variable with the binary we have found.
707 static void update_library_argv0( const WCHAR *argv0 )
709 DWORD len = strlenW( argv0 );
711 if (len > strlenW( __wine_main_wargv[0] ))
713 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
715 strcpyW( __wine_main_wargv[0], argv0 );
717 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
718 if (len > strlen( __wine_main_argv[0] ) + 1)
720 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
722 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
726 /***********************************************************************
727 * build_command_line
729 * Build the command line of a process from the argv array.
731 * Note that it does NOT necessarily include the file name.
732 * Sometimes we don't even have any command line options at all.
734 * We must quote and escape characters so that the argv array can be rebuilt
735 * from the command line:
736 * - spaces and tabs must be quoted
737 * 'a b' -> '"a b"'
738 * - quotes must be escaped
739 * '"' -> '\"'
740 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
741 * resulting in an odd number of '\' followed by a '"'
742 * '\"' -> '\\\"'
743 * '\\"' -> '\\\\\"'
744 * - '\'s that are not followed by a '"' can be left as is
745 * 'a\b' == 'a\b'
746 * 'a\\b' == 'a\\b'
748 static BOOL build_command_line( WCHAR **argv )
750 int len;
751 WCHAR **arg;
752 LPWSTR p;
753 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
755 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
757 len = 0;
758 for (arg = argv; *arg; arg++)
760 BOOL has_space;
761 int bcount;
762 WCHAR* a;
764 has_space=FALSE;
765 bcount=0;
766 a=*arg;
767 if( !*a ) has_space=TRUE;
768 while (*a!='\0') {
769 if (*a=='\\') {
770 bcount++;
771 } else {
772 if (*a==' ' || *a=='\t') {
773 has_space=TRUE;
774 } else if (*a=='"') {
775 /* doubling of '\' preceding a '"',
776 * plus escaping of said '"'
778 len+=2*bcount+1;
780 bcount=0;
782 a++;
784 len+=(a-*arg)+1 /* for the separating space */;
785 if (has_space)
786 len+=2; /* for the quotes */
789 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
790 return FALSE;
792 p = rupp->CommandLine.Buffer;
793 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
794 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
795 for (arg = argv; *arg; arg++)
797 BOOL has_space,has_quote;
798 WCHAR* a;
800 /* Check for quotes and spaces in this argument */
801 has_space=has_quote=FALSE;
802 a=*arg;
803 if( !*a ) has_space=TRUE;
804 while (*a!='\0') {
805 if (*a==' ' || *a=='\t') {
806 has_space=TRUE;
807 if (has_quote)
808 break;
809 } else if (*a=='"') {
810 has_quote=TRUE;
811 if (has_space)
812 break;
814 a++;
817 /* Now transfer it to the command line */
818 if (has_space)
819 *p++='"';
820 if (has_quote) {
821 int bcount;
823 bcount=0;
824 a=*arg;
825 while (*a!='\0') {
826 if (*a=='\\') {
827 *p++=*a;
828 bcount++;
829 } else {
830 if (*a=='"') {
831 int i;
833 /* Double all the '\\' preceding this '"', plus one */
834 for (i=0;i<=bcount;i++)
835 *p++='\\';
836 *p++='"';
837 } else {
838 *p++=*a;
840 bcount=0;
842 a++;
844 } else {
845 WCHAR* x = *arg;
846 while ((*p=*x++)) p++;
848 if (has_space)
849 *p++='"';
850 *p++=' ';
852 if (p > rupp->CommandLine.Buffer)
853 p--; /* remove last space */
854 *p = '\0';
856 return TRUE;
860 /***********************************************************************
861 * init_current_directory
863 * Initialize the current directory from the Unix cwd or the parent info.
865 static void init_current_directory( CURDIR *cur_dir )
867 UNICODE_STRING dir_str;
868 const char *pwd;
869 char *cwd;
870 int size;
872 /* if we received a cur dir from the parent, try this first */
874 if (cur_dir->DosPath.Length)
876 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
879 /* now try to get it from the Unix cwd */
881 for (size = 256; ; size *= 2)
883 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
884 if (getcwd( cwd, size )) break;
885 HeapFree( GetProcessHeap(), 0, cwd );
886 if (errno == ERANGE) continue;
887 cwd = NULL;
888 break;
891 /* try to use PWD if it is valid, so that we don't resolve symlinks */
893 pwd = getenv( "PWD" );
894 if (cwd)
896 struct stat st1, st2;
898 if (!pwd || stat( pwd, &st1 ) == -1 ||
899 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
900 pwd = cwd;
903 if (pwd)
905 ANSI_STRING unix_name;
906 UNICODE_STRING nt_name;
907 RtlInitAnsiString( &unix_name, pwd );
908 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
910 UNICODE_STRING dos_path;
911 /* skip the \??\ prefix, nt_name is 0 terminated */
912 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
913 RtlSetCurrentDirectory_U( &dos_path );
914 RtlFreeUnicodeString( &nt_name );
918 if (!cur_dir->DosPath.Length) /* still not initialized */
920 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
921 "starting in the Windows directory.\n", cwd ? cwd : "" );
922 RtlInitUnicodeString( &dir_str, DIR_Windows );
923 RtlSetCurrentDirectory_U( &dir_str );
925 HeapFree( GetProcessHeap(), 0, cwd );
927 done:
928 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
932 /***********************************************************************
933 * init_windows_dirs
935 * Initialize the windows and system directories from the environment.
937 static void init_windows_dirs(void)
939 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
941 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
942 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
943 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
944 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
945 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
947 DWORD len;
948 WCHAR *buffer;
950 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
952 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
953 GetEnvironmentVariableW( windirW, buffer, len );
954 DIR_Windows = buffer;
956 else DIR_Windows = default_windirW;
958 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
960 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
961 GetEnvironmentVariableW( winsysdirW, buffer, len );
962 DIR_System = buffer;
964 else
966 len = strlenW( DIR_Windows );
967 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
968 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
969 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
970 DIR_System = buffer;
973 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
974 ERR( "directory %s could not be created, error %u\n",
975 debugstr_w(DIR_Windows), GetLastError() );
976 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
977 ERR( "directory %s could not be created, error %u\n",
978 debugstr_w(DIR_System), GetLastError() );
980 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
982 len = strlenW( DIR_Windows );
983 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
984 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
985 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
986 DIR_SysWow64 = buffer;
987 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
988 ERR( "directory %s could not be created, error %u\n",
989 debugstr_w(DIR_SysWow64), GetLastError() );
992 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
993 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
995 /* set the directories in ntdll too */
996 __wine_init_windows_dir( DIR_Windows, DIR_System );
1000 /***********************************************************************
1001 * start_wineboot
1003 * Start the wineboot process if necessary. Return the handles to wait on.
1005 static void start_wineboot( HANDLE handles[2] )
1007 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
1009 handles[1] = 0;
1010 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
1012 ERR( "failed to create wineboot event, expect trouble\n" );
1013 return;
1015 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
1017 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1018 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1019 STARTUPINFOW si;
1020 PROCESS_INFORMATION pi;
1021 void *redir;
1022 WCHAR app[MAX_PATH];
1023 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1025 memset( &si, 0, sizeof(si) );
1026 si.cb = sizeof(si);
1027 si.dwFlags = STARTF_USESTDHANDLES;
1028 si.hStdInput = 0;
1029 si.hStdOutput = 0;
1030 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1032 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1033 lstrcatW( app, wineboot );
1035 Wow64DisableWow64FsRedirection( &redir );
1036 strcpyW( cmdline, app );
1037 strcatW( cmdline, args );
1038 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1040 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1041 CloseHandle( pi.hThread );
1042 handles[1] = pi.hProcess;
1044 else
1046 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1047 CloseHandle( handles[0] );
1048 handles[0] = 0;
1050 Wow64RevertWow64FsRedirection( redir );
1055 #ifdef __i386__
1056 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1057 __ASM_GLOBAL_FUNC( call_process_entry,
1058 "pushl %ebp\n\t"
1059 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1060 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1061 "movl %esp,%ebp\n\t"
1062 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1063 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1064 "pushl 8(%ebp)\n\t"
1065 "call *12(%ebp)\n\t"
1066 "leave\n\t"
1067 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1068 __ASM_CFI(".cfi_same_value %ebp\n\t")
1069 "ret" )
1070 #else
1071 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1073 return entry( peb );
1075 #endif
1077 /***********************************************************************
1078 * start_process
1080 * Startup routine of a new process. Runs on the new process stack.
1082 static DWORD WINAPI start_process( PEB *peb )
1084 IMAGE_NT_HEADERS *nt;
1085 LPTHREAD_START_ROUTINE entry;
1087 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1088 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1089 nt->OptionalHeader.AddressOfEntryPoint);
1091 if (!nt->OptionalHeader.AddressOfEntryPoint)
1093 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1094 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1095 ExitThread( 1 );
1098 if (TRACE_ON(relay))
1099 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1100 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1102 SetLastError( 0 ); /* clear error code */
1103 if (peb->BeingDebugged) DbgBreakPoint();
1104 return call_process_entry( peb, entry );
1108 /***********************************************************************
1109 * set_process_name
1111 * Change the process name in the ps output.
1113 static void set_process_name( int argc, char *argv[] )
1115 #ifdef HAVE_SETPROCTITLE
1116 setproctitle("-%s", argv[1]);
1117 #endif
1119 #ifdef HAVE_PRCTL
1120 int i, offset;
1121 char *p, *prctl_name = argv[1];
1122 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1124 #ifndef PR_SET_NAME
1125 # define PR_SET_NAME 15
1126 #endif
1128 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1129 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1131 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1133 offset = argv[1] - argv[0];
1134 memmove( argv[1] - offset, argv[1], end - argv[1] );
1135 memset( end - offset, 0, offset );
1136 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1137 argv[i-1] = NULL;
1139 else
1140 #endif /* HAVE_PRCTL */
1142 /* remove argv[0] */
1143 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1148 /***********************************************************************
1149 * __wine_kernel_init
1151 * Wine initialisation: load and start the main exe file.
1153 void CDECL __wine_kernel_init(void)
1155 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1156 static const WCHAR dotW[] = {'.',0};
1158 WCHAR *p, main_exe_name[MAX_PATH+1];
1159 PEB *peb = NtCurrentTeb()->Peb;
1160 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1161 HANDLE boot_events[2];
1162 BOOL got_environment = TRUE;
1164 /* Initialize everything */
1166 setbuf(stdout,NULL);
1167 setbuf(stderr,NULL);
1168 kernel32_handle = GetModuleHandleW(kernel32W);
1169 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1171 LOCALE_Init();
1173 if (!params->Environment)
1175 /* Copy the parent environment */
1176 if (!build_initial_environment()) exit(1);
1178 /* convert old configuration to new format */
1179 convert_old_config();
1181 got_environment = set_registry_environment( FALSE );
1182 set_additional_environment();
1185 init_windows_dirs();
1186 init_current_directory( &params->CurrentDirectory );
1188 set_process_name( __wine_main_argc, __wine_main_argv );
1189 set_library_wargv( __wine_main_argv );
1190 boot_events[0] = boot_events[1] = 0;
1192 if (peb->ProcessParameters->ImagePathName.Buffer)
1194 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1196 else
1198 struct binary_info binary_info;
1200 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1201 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1203 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1204 ExitProcess( GetLastError() );
1206 update_library_argv0( main_exe_name );
1207 if (!build_command_line( __wine_main_wargv )) goto error;
1208 start_wineboot( boot_events );
1211 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1212 p = strrchrW( main_exe_name, '.' );
1213 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1215 TRACE( "starting process name=%s argv[0]=%s\n",
1216 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1218 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1219 MODULE_get_dll_load_path(main_exe_name) );
1221 if (boot_events[0])
1223 DWORD timeout = 2 * 60 * 1000, count = 1;
1225 if (boot_events[1]) count++;
1226 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1227 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1228 ERR( "boot event wait timed out\n" );
1229 CloseHandle( boot_events[0] );
1230 if (boot_events[1]) CloseHandle( boot_events[1] );
1231 /* reload environment now that wineboot has run */
1232 set_registry_environment( got_environment );
1233 set_additional_environment();
1235 set_wow64_environment();
1237 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1239 DWORD_PTR args[1];
1240 WCHAR msgW[1024];
1241 char msg[1024];
1242 DWORD error = GetLastError();
1244 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1245 if (error == ERROR_BAD_EXE_FORMAT ||
1246 error == ERROR_INVALID_ADDRESS ||
1247 error == ERROR_NOT_ENOUGH_MEMORY)
1249 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1250 /* if we get back here, it failed */
1252 else if (error == ERROR_MOD_NOT_FOUND)
1254 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1255 else p = main_exe_name;
1256 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1258 /* args 1 and 2 are --app-name full_path */
1259 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1260 debugstr_w(__wine_main_wargv[3]) );
1261 ExitProcess( ERROR_BAD_EXE_FORMAT );
1263 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1264 ExitProcess( ERROR_FILE_NOT_FOUND );
1266 args[0] = (DWORD_PTR)main_exe_name;
1267 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1268 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1269 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1270 MESSAGE( "wine: %s", msg );
1271 ExitProcess( error );
1274 if (!params->CurrentDirectory.Handle) chdir("/"); /* avoid locking removable devices */
1276 LdrInitializeThunk( start_process, 0, 0, 0 );
1278 error:
1279 ExitProcess( GetLastError() );
1283 /***********************************************************************
1284 * build_argv
1286 * Build an argv array from a command-line.
1287 * 'reserved' is the number of args to reserve before the first one.
1289 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1291 int argc;
1292 char** argv;
1293 char *arg,*s,*d,*cmdline;
1294 int in_quotes,bcount,len;
1296 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1297 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1298 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1300 argc=reserved+1;
1301 bcount=0;
1302 in_quotes=0;
1303 s=cmdline;
1304 while (1) {
1305 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1306 /* space */
1307 argc++;
1308 /* skip the remaining spaces */
1309 while (*s==' ' || *s=='\t') {
1310 s++;
1312 if (*s=='\0')
1313 break;
1314 bcount=0;
1315 continue;
1316 } else if (*s=='\\') {
1317 /* '\', count them */
1318 bcount++;
1319 } else if ((*s=='"') && ((bcount & 1)==0)) {
1320 /* unescaped '"' */
1321 in_quotes=!in_quotes;
1322 bcount=0;
1323 } else {
1324 /* a regular character */
1325 bcount=0;
1327 s++;
1329 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1331 HeapFree( GetProcessHeap(), 0, cmdline );
1332 return NULL;
1335 arg = d = s = (char *)(argv + argc);
1336 memcpy( d, cmdline, len );
1337 bcount=0;
1338 in_quotes=0;
1339 argc=reserved;
1340 while (*s) {
1341 if ((*s==' ' || *s=='\t') && !in_quotes) {
1342 /* Close the argument and copy it */
1343 *d=0;
1344 argv[argc++]=arg;
1346 /* skip the remaining spaces */
1347 do {
1348 s++;
1349 } while (*s==' ' || *s=='\t');
1351 /* Start with a new argument */
1352 arg=d=s;
1353 bcount=0;
1354 } else if (*s=='\\') {
1355 /* '\\' */
1356 *d++=*s++;
1357 bcount++;
1358 } else if (*s=='"') {
1359 /* '"' */
1360 if ((bcount & 1)==0) {
1361 /* Preceded by an even number of '\', this is half that
1362 * number of '\', plus a '"' which we discard.
1364 d-=bcount/2;
1365 s++;
1366 in_quotes=!in_quotes;
1367 } else {
1368 /* Preceded by an odd number of '\', this is half that
1369 * number of '\' followed by a '"'
1371 d=d-bcount/2-1;
1372 *d++='"';
1373 s++;
1375 bcount=0;
1376 } else {
1377 /* a regular character */
1378 *d++=*s++;
1379 bcount=0;
1382 if (*arg) {
1383 *d='\0';
1384 argv[argc++]=arg;
1386 argv[argc]=NULL;
1388 HeapFree( GetProcessHeap(), 0, cmdline );
1389 return argv;
1393 /***********************************************************************
1394 * build_envp
1396 * Build the environment of a new child process.
1398 static char **build_envp( const WCHAR *envW )
1400 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1402 const WCHAR *end;
1403 char **envp;
1404 char *env, *p;
1405 int count = 1, length;
1406 unsigned int i;
1408 for (end = envW; *end; count++) end += strlenW(end) + 1;
1409 end++;
1410 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1411 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1412 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1414 for (p = env; *p; p += strlen(p) + 1)
1415 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1417 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1419 if (!(p = getenv(unix_vars[i]))) continue;
1420 length += strlen(unix_vars[i]) + strlen(p) + 2;
1421 count++;
1424 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1426 char **envptr = envp;
1427 char *dst = (char *)(envp + count);
1429 /* some variables must not be modified, so we get them directly from the unix env */
1430 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1432 if (!(p = getenv(unix_vars[i]))) continue;
1433 *envptr++ = strcpy( dst, unix_vars[i] );
1434 strcat( dst, "=" );
1435 strcat( dst, p );
1436 dst += strlen(dst) + 1;
1439 /* now put the Windows environment strings */
1440 for (p = env; *p; p += strlen(p) + 1)
1442 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1443 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1444 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1445 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1446 if (is_special_env_var( p )) /* prefix it with "WINE" */
1448 *envptr++ = strcpy( dst, "WINE" );
1449 strcat( dst, p );
1451 else
1453 *envptr++ = strcpy( dst, p );
1455 dst += strlen(dst) + 1;
1457 *envptr = 0;
1459 HeapFree( GetProcessHeap(), 0, env );
1460 return envp;
1464 /***********************************************************************
1465 * fork_and_exec
1467 * Fork and exec a new Unix binary, checking for errors.
1469 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1470 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1472 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1473 int pid, err;
1474 char **argv, **envp;
1476 if (!env) env = GetEnvironmentStringsW();
1478 #ifdef HAVE_PIPE2
1479 if (pipe2( fd, O_CLOEXEC ) == -1)
1480 #endif
1482 if (pipe(fd) == -1)
1484 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1485 return -1;
1487 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1488 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1491 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1493 HANDLE hstdin, hstdout, hstderr;
1495 if (startup->dwFlags & STARTF_USESTDHANDLES)
1497 hstdin = startup->hStdInput;
1498 hstdout = startup->hStdOutput;
1499 hstderr = startup->hStdError;
1501 else
1503 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1504 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1505 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1508 if (is_console_handle( hstdin ))
1509 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1510 if (is_console_handle( hstdout ))
1511 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1512 if (is_console_handle( hstderr ))
1513 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1514 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1515 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1516 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1519 argv = build_argv( cmdline, 0 );
1520 envp = build_envp( env );
1522 if (!(pid = fork())) /* child */
1524 if (!(pid = fork())) /* grandchild */
1526 close( fd[0] );
1528 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1530 int nullfd = open( "/dev/null", O_RDWR );
1531 setsid();
1532 /* close stdin and stdout */
1533 if (nullfd != -1)
1535 dup2( nullfd, 0 );
1536 dup2( nullfd, 1 );
1537 close( nullfd );
1540 else
1542 if (stdin_fd != -1)
1544 dup2( stdin_fd, 0 );
1545 close( stdin_fd );
1547 if (stdout_fd != -1)
1549 dup2( stdout_fd, 1 );
1550 close( stdout_fd );
1552 if (stderr_fd != -1)
1554 dup2( stderr_fd, 2 );
1555 close( stderr_fd );
1559 /* Reset signals that we previously set to SIG_IGN */
1560 signal( SIGPIPE, SIG_DFL );
1562 if (newdir) chdir(newdir);
1564 if (argv && envp) execve( filename, argv, envp );
1567 if (pid <= 0) /* grandchild if exec failed or child if fork failed */
1569 err = errno;
1570 write( fd[1], &err, sizeof(err) );
1571 _exit(1);
1574 _exit(0); /* child if fork succeeded */
1576 HeapFree( GetProcessHeap(), 0, argv );
1577 HeapFree( GetProcessHeap(), 0, envp );
1578 if (stdin_fd != -1) close( stdin_fd );
1579 if (stdout_fd != -1) close( stdout_fd );
1580 if (stderr_fd != -1) close( stderr_fd );
1581 close( fd[1] );
1582 if (pid != -1)
1584 /* reap child */
1585 do {
1586 err = waitpid(pid, NULL, 0);
1587 } while (err < 0 && errno == EINTR);
1589 if (read( fd[0], &err, sizeof(err) ) > 0) /* exec or second fork failed */
1591 errno = err;
1592 pid = -1;
1595 if (pid == -1) FILE_SetDosError();
1596 close( fd[0] );
1597 return pid;
1601 static inline DWORD append_string( void **ptr, const WCHAR *str )
1603 DWORD len = strlenW( str );
1604 memcpy( *ptr, str, len * sizeof(WCHAR) );
1605 *ptr = (WCHAR *)*ptr + len;
1606 return len * sizeof(WCHAR);
1609 /***********************************************************************
1610 * create_startup_info
1612 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1613 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1614 const STARTUPINFOW *startup, DWORD *info_size )
1616 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1617 const WCHAR *title;
1618 startup_info_t *info;
1619 DWORD size;
1620 void *ptr;
1621 UNICODE_STRING newdir;
1622 WCHAR imagepath[MAX_PATH];
1623 HANDLE hstdin, hstdout, hstderr;
1625 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1626 lstrcpynW( imagepath, filename, MAX_PATH );
1627 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1628 lstrcpynW( imagepath, filename, MAX_PATH );
1630 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1632 newdir.Buffer = NULL;
1633 if (cur_dir)
1635 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1636 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1637 else
1638 cur_dir = NULL;
1640 if (!cur_dir)
1642 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1643 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1644 else
1645 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1647 title = startup->lpTitle ? startup->lpTitle : imagepath;
1649 size = sizeof(*info);
1650 size += strlenW( cur_dir ) * sizeof(WCHAR);
1651 size += cur_params->DllPath.Length;
1652 size += strlenW( imagepath ) * sizeof(WCHAR);
1653 size += strlenW( cmdline ) * sizeof(WCHAR);
1654 size += strlenW( title ) * sizeof(WCHAR);
1655 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1656 /* FIXME: shellinfo */
1657 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1658 size = (size + 1) & ~1;
1659 *info_size = size;
1661 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1663 info->console_flags = cur_params->ConsoleFlags;
1664 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1665 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1667 if (startup->dwFlags & STARTF_USESTDHANDLES)
1669 hstdin = startup->hStdInput;
1670 hstdout = startup->hStdOutput;
1671 hstderr = startup->hStdError;
1673 else
1675 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1676 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1677 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1679 info->hstdin = wine_server_obj_handle( hstdin );
1680 info->hstdout = wine_server_obj_handle( hstdout );
1681 info->hstderr = wine_server_obj_handle( hstderr );
1682 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1684 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1685 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1686 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1687 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1689 else
1691 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1692 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1693 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1696 info->x = startup->dwX;
1697 info->y = startup->dwY;
1698 info->xsize = startup->dwXSize;
1699 info->ysize = startup->dwYSize;
1700 info->xchars = startup->dwXCountChars;
1701 info->ychars = startup->dwYCountChars;
1702 info->attribute = startup->dwFillAttribute;
1703 info->flags = startup->dwFlags;
1704 info->show = startup->wShowWindow;
1706 ptr = info + 1;
1707 info->curdir_len = append_string( &ptr, cur_dir );
1708 info->dllpath_len = cur_params->DllPath.Length;
1709 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1710 ptr = (char *)ptr + cur_params->DllPath.Length;
1711 info->imagepath_len = append_string( &ptr, imagepath );
1712 info->cmdline_len = append_string( &ptr, cmdline );
1713 info->title_len = append_string( &ptr, title );
1714 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1715 if (startup->lpReserved2 && startup->cbReserved2)
1717 info->runtime_len = startup->cbReserved2;
1718 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1721 done:
1722 RtlFreeUnicodeString( &newdir );
1723 return info;
1726 /***********************************************************************
1727 * get_alternate_loader
1729 * Get the name of the alternate (32 or 64 bit) Wine loader.
1731 static const char *get_alternate_loader( char **ret_env )
1733 char *env;
1734 const char *loader = NULL;
1735 const char *loader_env = getenv( "WINELOADER" );
1737 *ret_env = NULL;
1739 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1741 if (loader_env)
1743 int len = strlen( loader_env );
1744 if (!is_win64)
1746 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1747 strcpy( env, "WINELOADER=" );
1748 strcat( env, loader_env );
1749 strcat( env, "64" );
1751 else
1753 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1754 strcpy( env, "WINELOADER=" );
1755 strcat( env, loader_env );
1756 len += sizeof("WINELOADER=") - 1;
1757 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1759 if (!loader)
1761 if ((loader = strrchr( env, '/' ))) loader++;
1762 else loader = env;
1764 *ret_env = env;
1766 if (!loader) loader = is_win64 ? "wine" : "wine64";
1767 return loader;
1770 #ifdef __APPLE__
1771 /***********************************************************************
1772 * terminate_main_thread
1774 * On some versions of Mac OS X, the execve system call fails with
1775 * ENOTSUP if the process has multiple threads. Wine is always multi-
1776 * threaded on Mac OS X because it specifically reserves the main thread
1777 * for use by the system frameworks (see apple_main_thread() in
1778 * libs/wine/loader.c). So, when we need to exec without first forking,
1779 * we need to terminate the main thread first. We do this by installing
1780 * a custom run loop source onto the main run loop and signaling it.
1781 * The source's "perform" callback is pthread_exit and it will be
1782 * executed on the main thread, terminating it.
1784 * Returns TRUE if there's still hope the main thread has terminated or
1785 * will soon. Return FALSE if we've given up.
1787 static BOOL terminate_main_thread(void)
1789 static int delayms;
1791 if (!delayms)
1793 CFRunLoopSourceContext source_context = { 0 };
1794 CFRunLoopSourceRef source;
1796 source_context.perform = pthread_exit;
1797 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1798 return FALSE;
1800 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1801 CFRunLoopSourceSignal( source );
1802 CFRunLoopWakeUp( CFRunLoopGetMain() );
1803 CFRelease( source );
1805 delayms = 20;
1808 if (delayms > 1000)
1809 return FALSE;
1811 usleep(delayms * 1000);
1812 delayms *= 2;
1814 return TRUE;
1816 #endif
1818 /***********************************************************************
1819 * get_process_cpu
1821 static int get_process_cpu( const WCHAR *filename, const struct binary_info *binary_info )
1823 switch (binary_info->arch)
1825 case IMAGE_FILE_MACHINE_I386: return CPU_x86;
1826 case IMAGE_FILE_MACHINE_AMD64: return CPU_x86_64;
1827 case IMAGE_FILE_MACHINE_POWERPC: return CPU_POWERPC;
1828 case IMAGE_FILE_MACHINE_ARM:
1829 case IMAGE_FILE_MACHINE_THUMB:
1830 case IMAGE_FILE_MACHINE_ARMNT: return CPU_ARM;
1831 case IMAGE_FILE_MACHINE_ARM64: return CPU_ARM64;
1833 ERR( "%s uses unsupported architecture (%04x)\n", debugstr_w(filename), binary_info->arch );
1834 return -1;
1837 /***********************************************************************
1838 * exec_loader
1840 static pid_t exec_loader( LPCWSTR cmd_line, unsigned int flags, int socketfd,
1841 int stdin_fd, int stdout_fd, const char *unixdir, char *winedebug,
1842 const struct binary_info *binary_info, int exec_only )
1844 pid_t pid;
1845 char *wineloader = NULL;
1846 const char *loader = NULL;
1847 char **argv;
1849 argv = build_argv( cmd_line, 1 );
1851 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1852 loader = get_alternate_loader( &wineloader );
1854 if (exec_only || !(pid = fork())) /* child */
1856 if (exec_only || !(pid = fork())) /* grandchild */
1858 char preloader_reserve[64], socket_env[64];
1860 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1862 int fd = open( "/dev/null", O_RDWR );
1863 setsid();
1864 /* close stdin and stdout */
1865 if (fd != -1)
1867 dup2( fd, 0 );
1868 dup2( fd, 1 );
1869 close( fd );
1872 else
1874 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1875 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1878 if (stdin_fd != -1) close( stdin_fd );
1879 if (stdout_fd != -1) close( stdout_fd );
1881 /* Reset signals that we previously set to SIG_IGN */
1882 signal( SIGPIPE, SIG_DFL );
1884 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
1885 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1886 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1888 putenv( preloader_reserve );
1889 putenv( socket_env );
1890 if (winedebug) putenv( winedebug );
1891 if (wineloader) putenv( wineloader );
1892 if (unixdir) chdir(unixdir);
1894 if (argv)
1898 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1900 #ifdef __APPLE__
1901 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1902 #else
1903 while (0);
1904 #endif
1906 _exit(1);
1909 _exit(pid == -1);
1912 if (pid != -1)
1914 /* reap child */
1915 pid_t wret;
1916 do {
1917 wret = waitpid(pid, NULL, 0);
1918 } while (wret < 0 && errno == EINTR);
1921 HeapFree( GetProcessHeap(), 0, wineloader );
1922 HeapFree( GetProcessHeap(), 0, argv );
1923 return pid;
1926 /***********************************************************************
1927 * create_process
1929 * Create a new process. If hFile is a valid handle we have an exe
1930 * file, otherwise it is a Winelib app.
1932 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1933 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1934 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1935 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1936 const struct binary_info *binary_info, int exec_only )
1938 static const char *cpu_names[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
1939 NTSTATUS status;
1940 BOOL success = FALSE;
1941 HANDLE process_info;
1942 WCHAR *env_end;
1943 char *winedebug = NULL;
1944 startup_info_t *startup_info;
1945 DWORD startup_info_size;
1946 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1947 pid_t pid;
1948 int err, cpu;
1950 if ((cpu = get_process_cpu( filename, binary_info )) == -1)
1952 SetLastError( ERROR_BAD_EXE_FORMAT );
1953 return FALSE;
1956 /* create the socket for the new process */
1958 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1960 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1961 return FALSE;
1963 #ifdef SO_PASSCRED
1964 else
1966 int enable = 1;
1967 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1969 #endif
1971 if (exec_only) /* things are much simpler in this case */
1973 wine_server_send_fd( socketfd[1] );
1974 close( socketfd[1] );
1975 SERVER_START_REQ( new_process )
1977 req->create_flags = flags;
1978 req->socket_fd = socketfd[1];
1979 req->exe_file = wine_server_obj_handle( hFile );
1980 req->cpu = cpu;
1981 status = wine_server_call( req );
1983 SERVER_END_REQ;
1985 switch (status)
1987 case STATUS_INVALID_IMAGE_WIN_64:
1988 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
1989 break;
1990 case STATUS_INVALID_IMAGE_FORMAT:
1991 ERR( "%s not supported on this installation (%s binary)\n",
1992 debugstr_w(filename), cpu_names[cpu] );
1993 break;
1994 case STATUS_SUCCESS:
1995 exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
1996 winedebug, binary_info, TRUE );
1998 close( socketfd[0] );
1999 SetLastError( RtlNtStatusToDosError( status ));
2000 return FALSE;
2003 RtlAcquirePebLock();
2005 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
2006 &startup_info_size )))
2008 RtlReleasePebLock();
2009 close( socketfd[0] );
2010 close( socketfd[1] );
2011 return FALSE;
2013 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
2014 env_end = env;
2015 while (*env_end)
2017 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
2018 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
2020 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
2021 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
2022 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
2024 env_end += strlenW(env_end) + 1;
2026 env_end++;
2028 wine_server_send_fd( socketfd[1] );
2029 close( socketfd[1] );
2031 /* create the process on the server side */
2033 SERVER_START_REQ( new_process )
2035 req->inherit_all = inherit;
2036 req->create_flags = flags;
2037 req->socket_fd = socketfd[1];
2038 req->exe_file = wine_server_obj_handle( hFile );
2039 req->process_access = PROCESS_ALL_ACCESS;
2040 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
2041 req->thread_access = THREAD_ALL_ACCESS;
2042 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
2043 req->cpu = cpu;
2044 req->info_size = startup_info_size;
2046 wine_server_add_data( req, startup_info, startup_info_size );
2047 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
2048 if (!(status = wine_server_call( req )))
2050 info->dwProcessId = (DWORD)reply->pid;
2051 info->dwThreadId = (DWORD)reply->tid;
2052 info->hProcess = wine_server_ptr_handle( reply->phandle );
2053 info->hThread = wine_server_ptr_handle( reply->thandle );
2055 process_info = wine_server_ptr_handle( reply->info );
2057 SERVER_END_REQ;
2059 RtlReleasePebLock();
2060 if (status)
2062 switch (status)
2064 case STATUS_INVALID_IMAGE_WIN_64:
2065 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2066 break;
2067 case STATUS_INVALID_IMAGE_FORMAT:
2068 ERR( "%s not supported on this installation (%s binary)\n",
2069 debugstr_w(filename), cpu_names[cpu] );
2070 break;
2072 close( socketfd[0] );
2073 HeapFree( GetProcessHeap(), 0, startup_info );
2074 HeapFree( GetProcessHeap(), 0, winedebug );
2075 SetLastError( RtlNtStatusToDosError( status ));
2076 return FALSE;
2079 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
2081 if (startup_info->hstdin)
2082 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
2083 FILE_READ_DATA, &stdin_fd, NULL );
2084 if (startup_info->hstdout)
2085 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
2086 FILE_WRITE_DATA, &stdout_fd, NULL );
2088 HeapFree( GetProcessHeap(), 0, startup_info );
2090 /* create the child process */
2092 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2093 winedebug, binary_info, FALSE );
2095 if (stdin_fd != -1) close( stdin_fd );
2096 if (stdout_fd != -1) close( stdout_fd );
2097 close( socketfd[0] );
2098 HeapFree( GetProcessHeap(), 0, winedebug );
2099 if (pid == -1)
2101 FILE_SetDosError();
2102 goto error;
2105 /* wait for the new process info to be ready */
2107 WaitForSingleObject( process_info, INFINITE );
2108 SERVER_START_REQ( get_new_process_info )
2110 req->info = wine_server_obj_handle( process_info );
2111 wine_server_call( req );
2112 success = reply->success;
2113 err = reply->exit_code;
2115 SERVER_END_REQ;
2117 if (!success)
2119 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2120 goto error;
2122 CloseHandle( process_info );
2123 return success;
2125 error:
2126 CloseHandle( process_info );
2127 CloseHandle( info->hProcess );
2128 CloseHandle( info->hThread );
2129 info->hProcess = info->hThread = 0;
2130 info->dwProcessId = info->dwThreadId = 0;
2131 return FALSE;
2135 /***********************************************************************
2136 * create_vdm_process
2138 * Create a new VDM process for a 16-bit or DOS application.
2140 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2141 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2142 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2143 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2144 const struct binary_info *binary_info, int exec_only )
2146 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2148 BOOL ret;
2149 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
2150 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
2152 if (!new_cmd_line)
2154 SetLastError( ERROR_OUTOFMEMORY );
2155 return FALSE;
2157 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
2158 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2159 flags, startup, info, unixdir, binary_info, exec_only );
2160 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2161 return ret;
2165 /***********************************************************************
2166 * create_cmd_process
2168 * Create a new cmd shell process for a .BAT file.
2170 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2171 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2172 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2173 LPPROCESS_INFORMATION info )
2176 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2177 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2178 WCHAR comspec[MAX_PATH];
2179 WCHAR *newcmdline;
2180 BOOL ret;
2182 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2183 return FALSE;
2184 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2185 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2186 return FALSE;
2188 strcpyW( newcmdline, comspec );
2189 strcatW( newcmdline, slashcW );
2190 strcatW( newcmdline, cmd_line );
2191 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2192 flags, env, cur_dir, startup, info );
2193 HeapFree( GetProcessHeap(), 0, newcmdline );
2194 return ret;
2198 /*************************************************************************
2199 * get_file_name
2201 * Helper for CreateProcess: retrieve the file name to load from the
2202 * app name and command line. Store the file name in buffer, and
2203 * return a possibly modified command line.
2204 * Also returns a handle to the opened file if it's a Windows binary.
2206 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2207 int buflen, HANDLE *handle, struct binary_info *binary_info )
2209 static const WCHAR quotesW[] = {'"','%','s','"',0};
2211 WCHAR *name, *pos, *first_space, *ret = NULL;
2212 const WCHAR *p;
2214 /* if we have an app name, everything is easy */
2216 if (appname)
2218 /* use the unmodified app name as file name */
2219 lstrcpynW( buffer, appname, buflen );
2220 *handle = open_exe_file( buffer, binary_info );
2221 if (!(ret = cmdline) || !cmdline[0])
2223 /* no command-line, create one */
2224 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2225 sprintfW( ret, quotesW, appname );
2227 return ret;
2230 /* first check for a quoted file name */
2232 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2234 int len = p - cmdline - 1;
2235 /* extract the quoted portion as file name */
2236 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2237 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2238 name[len] = 0;
2240 if (!find_exe_file( name, buffer, buflen, handle, binary_info )) goto done;
2241 ret = cmdline; /* no change necessary */
2242 goto done;
2245 /* now try the command-line word by word */
2247 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2248 return NULL;
2249 pos = name;
2250 p = cmdline;
2251 first_space = NULL;
2253 for (;;)
2255 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2256 *pos = 0;
2257 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2259 ret = cmdline;
2260 break;
2262 if (!first_space) first_space = pos;
2263 if (!(*pos++ = *p++)) break;
2266 if (!ret)
2268 SetLastError( ERROR_FILE_NOT_FOUND );
2270 else if (first_space) /* build a new command-line with quotes */
2272 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2273 goto done;
2274 sprintfW( ret, quotesW, name );
2275 strcatW( ret, p );
2278 done:
2279 HeapFree( GetProcessHeap(), 0, name );
2280 return ret;
2284 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2285 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2286 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2287 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2288 LPPROCESS_INFORMATION info )
2290 BOOL retv = FALSE;
2291 HANDLE hFile = 0;
2292 char *unixdir = NULL;
2293 WCHAR name[MAX_PATH];
2294 WCHAR *tidy_cmdline, *p, *envW = env;
2295 struct binary_info binary_info;
2297 /* Process the AppName and/or CmdLine to get module name and path */
2299 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2301 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2302 &hFile, &binary_info )))
2303 return FALSE;
2304 if (hFile == INVALID_HANDLE_VALUE) goto done;
2306 /* Warn if unsupported features are used */
2308 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2309 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2310 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2311 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2312 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2314 if (cur_dir)
2316 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2318 SetLastError(ERROR_DIRECTORY);
2319 goto done;
2322 else
2324 WCHAR buf[MAX_PATH];
2325 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2328 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2330 char *e = env;
2331 DWORD lenW;
2333 while (*e) e += strlen(e) + 1;
2334 e++; /* final null */
2335 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, NULL, 0 );
2336 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2337 MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, envW, lenW );
2338 flags |= CREATE_UNICODE_ENVIRONMENT;
2341 info->hThread = info->hProcess = 0;
2342 info->dwProcessId = info->dwThreadId = 0;
2344 if (binary_info.flags & BINARY_FLAG_DLL)
2346 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2347 SetLastError( ERROR_BAD_EXE_FORMAT );
2349 else switch (binary_info.type)
2351 case BINARY_PE:
2352 TRACE( "starting %s as Win%d binary (%p-%p, arch %04x%s)\n",
2353 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2354 binary_info.res_start, binary_info.res_end, binary_info.arch,
2355 (binary_info.flags & BINARY_FLAG_FAKEDLL) ? ", fakedll" : "" );
2356 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2357 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2358 break;
2359 case BINARY_OS216:
2360 case BINARY_WIN16:
2361 case BINARY_DOS:
2362 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2363 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2364 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2365 break;
2366 case BINARY_UNIX_LIB:
2367 TRACE( "starting %s as %d-bit Winelib app\n",
2368 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2369 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2370 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2371 break;
2372 case BINARY_UNKNOWN:
2373 /* check for .com or .bat extension */
2374 if ((p = strrchrW( name, '.' )))
2376 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2378 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2379 binary_info.type = BINARY_DOS;
2380 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2381 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2382 inherit, flags, startup_info, info, unixdir,
2383 &binary_info, FALSE );
2384 break;
2386 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2388 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2389 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2390 inherit, flags, startup_info, info );
2391 break;
2394 /* fall through */
2395 case BINARY_UNIX_EXE:
2397 /* unknown file, try as unix executable */
2398 char *unix_name;
2400 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2402 if ((unix_name = wine_get_unix_file_name( name )))
2404 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2405 HeapFree( GetProcessHeap(), 0, unix_name );
2408 break;
2410 if (hFile) CloseHandle( hFile );
2412 done:
2413 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2414 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2415 HeapFree( GetProcessHeap(), 0, unixdir );
2416 if (retv)
2417 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2418 return retv;
2422 /**********************************************************************
2423 * CreateProcessA (KERNEL32.@)
2425 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2426 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2427 DWORD flags, LPVOID env, LPCSTR cur_dir,
2428 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2430 BOOL ret = FALSE;
2431 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2432 UNICODE_STRING desktopW, titleW;
2433 STARTUPINFOW infoW;
2435 desktopW.Buffer = NULL;
2436 titleW.Buffer = NULL;
2437 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2438 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2439 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2441 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2442 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2444 memcpy( &infoW, startup_info, sizeof(infoW) );
2445 infoW.lpDesktop = desktopW.Buffer;
2446 infoW.lpTitle = titleW.Buffer;
2448 if (startup_info->lpReserved)
2449 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2450 debugstr_a(startup_info->lpReserved));
2452 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2453 inherit, flags, env, cur_dirW, &infoW, info );
2454 done:
2455 HeapFree( GetProcessHeap(), 0, app_nameW );
2456 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2457 HeapFree( GetProcessHeap(), 0, cur_dirW );
2458 RtlFreeUnicodeString( &desktopW );
2459 RtlFreeUnicodeString( &titleW );
2460 return ret;
2464 /**********************************************************************
2465 * CreateProcessW (KERNEL32.@)
2467 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2468 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2469 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2470 LPPROCESS_INFORMATION info )
2472 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2473 inherit, flags, env, cur_dir, startup_info, info);
2477 /**********************************************************************
2478 * exec_process
2480 static void exec_process( LPCWSTR name )
2482 HANDLE hFile;
2483 WCHAR *p;
2484 STARTUPINFOW startup_info;
2485 PROCESS_INFORMATION info;
2486 struct binary_info binary_info;
2488 hFile = open_exe_file( name, &binary_info );
2489 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2491 memset( &startup_info, 0, sizeof(startup_info) );
2492 startup_info.cb = sizeof(startup_info);
2494 /* Determine executable type */
2496 if (binary_info.flags & BINARY_FLAG_DLL)
2498 CloseHandle( hFile );
2499 return;
2502 switch (binary_info.type)
2504 case BINARY_PE:
2505 TRACE( "starting %s as Win%d binary (%p-%p, arch %04x)\n",
2506 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2507 binary_info.res_start, binary_info.res_end, binary_info.arch );
2508 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2509 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2510 break;
2511 case BINARY_UNIX_LIB:
2512 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2513 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2514 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2515 break;
2516 case BINARY_UNKNOWN:
2517 /* check for .com or .pif extension */
2518 if (!(p = strrchrW( name, '.' ))) break;
2519 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2520 binary_info.type = BINARY_DOS;
2521 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2522 /* fall through */
2523 case BINARY_OS216:
2524 case BINARY_WIN16:
2525 case BINARY_DOS:
2526 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2527 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2528 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2529 break;
2530 default:
2531 break;
2533 CloseHandle( hFile );
2537 /***********************************************************************
2538 * wait_input_idle
2540 * Wrapper to call WaitForInputIdle USER function
2542 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2544 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2546 HMODULE mod = GetModuleHandleA( "user32.dll" );
2547 if (mod)
2549 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2550 if (ptr) return ptr( process, timeout );
2552 return 0;
2556 /***********************************************************************
2557 * WinExec (KERNEL32.@)
2559 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2561 PROCESS_INFORMATION info;
2562 STARTUPINFOA startup;
2563 char *cmdline;
2564 UINT ret;
2566 memset( &startup, 0, sizeof(startup) );
2567 startup.cb = sizeof(startup);
2568 startup.dwFlags = STARTF_USESHOWWINDOW;
2569 startup.wShowWindow = nCmdShow;
2571 /* cmdline needs to be writable for CreateProcess */
2572 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2573 strcpy( cmdline, lpCmdLine );
2575 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2576 0, NULL, NULL, &startup, &info ))
2578 /* Give 30 seconds to the app to come up */
2579 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2580 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2581 ret = 33;
2582 /* Close off the handles */
2583 CloseHandle( info.hThread );
2584 CloseHandle( info.hProcess );
2586 else if ((ret = GetLastError()) >= 32)
2588 FIXME("Strange error set by CreateProcess: %d\n", ret );
2589 ret = 11;
2591 HeapFree( GetProcessHeap(), 0, cmdline );
2592 return ret;
2596 /**********************************************************************
2597 * LoadModule (KERNEL32.@)
2599 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2601 LOADPARMS32 *params = paramBlock;
2602 PROCESS_INFORMATION info;
2603 STARTUPINFOA startup;
2604 DWORD ret;
2605 LPSTR cmdline, p;
2606 char filename[MAX_PATH];
2607 BYTE len;
2609 if (!name) return ERROR_FILE_NOT_FOUND;
2611 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2612 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2613 return GetLastError();
2615 len = (BYTE)params->lpCmdLine[0];
2616 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2617 return ERROR_NOT_ENOUGH_MEMORY;
2619 strcpy( cmdline, filename );
2620 p = cmdline + strlen(cmdline);
2621 *p++ = ' ';
2622 memcpy( p, params->lpCmdLine + 1, len );
2623 p[len] = 0;
2625 memset( &startup, 0, sizeof(startup) );
2626 startup.cb = sizeof(startup);
2627 if (params->lpCmdShow)
2629 startup.dwFlags = STARTF_USESHOWWINDOW;
2630 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2633 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2634 params->lpEnvAddress, NULL, &startup, &info ))
2636 /* Give 30 seconds to the app to come up */
2637 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2638 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2639 ret = 33;
2640 /* Close off the handles */
2641 CloseHandle( info.hThread );
2642 CloseHandle( info.hProcess );
2644 else if ((ret = GetLastError()) >= 32)
2646 FIXME("Strange error set by CreateProcess: %u\n", ret );
2647 ret = 11;
2650 HeapFree( GetProcessHeap(), 0, cmdline );
2651 return ret;
2655 /******************************************************************************
2656 * TerminateProcess (KERNEL32.@)
2658 * Terminates a process.
2660 * PARAMS
2661 * handle [I] Process to terminate.
2662 * exit_code [I] Exit code.
2664 * RETURNS
2665 * Success: TRUE.
2666 * Failure: FALSE, check GetLastError().
2668 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2670 NTSTATUS status;
2672 if (!handle)
2674 SetLastError( ERROR_INVALID_HANDLE );
2675 return FALSE;
2678 status = NtTerminateProcess( handle, exit_code );
2679 if (status) SetLastError( RtlNtStatusToDosError(status) );
2680 return !status;
2683 /***********************************************************************
2684 * ExitProcess (KERNEL32.@)
2686 * Exits the current process.
2688 * PARAMS
2689 * status [I] Status code to exit with.
2691 * RETURNS
2692 * Nothing.
2694 #ifdef __i386__
2695 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2696 "pushl %ebp\n\t"
2697 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2698 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2699 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2700 "pushl 8(%ebp)\n\t"
2701 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
2702 "leave\n\t"
2703 "ret $4" )
2704 #else
2706 void WINAPI ExitProcess( DWORD status )
2708 RtlExitUserProcess( status );
2711 #endif
2713 /***********************************************************************
2714 * GetExitCodeProcess [KERNEL32.@]
2716 * Gets termination status of specified process.
2718 * PARAMS
2719 * hProcess [in] Handle to the process.
2720 * lpExitCode [out] Address to receive termination status.
2722 * RETURNS
2723 * Success: TRUE
2724 * Failure: FALSE
2726 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2728 NTSTATUS status;
2729 PROCESS_BASIC_INFORMATION pbi;
2731 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2732 sizeof(pbi), NULL);
2733 if (status == STATUS_SUCCESS)
2735 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2736 return TRUE;
2738 SetLastError( RtlNtStatusToDosError(status) );
2739 return FALSE;
2743 /***********************************************************************
2744 * SetErrorMode (KERNEL32.@)
2746 UINT WINAPI SetErrorMode( UINT mode )
2748 UINT old;
2750 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2751 &old, sizeof(old), NULL );
2752 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2753 &mode, sizeof(mode) );
2754 return old;
2757 /***********************************************************************
2758 * GetErrorMode (KERNEL32.@)
2760 UINT WINAPI GetErrorMode( void )
2762 UINT mode;
2764 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2765 &mode, sizeof(mode), NULL );
2766 return mode;
2769 /**********************************************************************
2770 * TlsAlloc [KERNEL32.@]
2772 * Allocates a thread local storage index.
2774 * RETURNS
2775 * Success: TLS index.
2776 * Failure: 0xFFFFFFFF
2778 DWORD WINAPI TlsAlloc( void )
2780 DWORD index;
2781 PEB * const peb = NtCurrentTeb()->Peb;
2783 RtlAcquirePebLock();
2784 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 1 );
2785 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2786 else
2788 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2789 if (index != ~0U)
2791 if (!NtCurrentTeb()->TlsExpansionSlots &&
2792 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2793 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2795 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2796 index = ~0U;
2797 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2799 else
2801 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2802 index += TLS_MINIMUM_AVAILABLE;
2805 else SetLastError( ERROR_NO_MORE_ITEMS );
2807 RtlReleasePebLock();
2808 return index;
2812 /**********************************************************************
2813 * TlsFree [KERNEL32.@]
2815 * Releases a thread local storage index, making it available for reuse.
2817 * PARAMS
2818 * index [in] TLS index to free.
2820 * RETURNS
2821 * Success: TRUE
2822 * Failure: FALSE
2824 BOOL WINAPI TlsFree( DWORD index )
2826 BOOL ret;
2828 RtlAcquirePebLock();
2829 if (index >= TLS_MINIMUM_AVAILABLE)
2831 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2832 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2834 else
2836 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2837 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2839 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2840 else SetLastError( ERROR_INVALID_PARAMETER );
2841 RtlReleasePebLock();
2842 return ret;
2846 /**********************************************************************
2847 * TlsGetValue [KERNEL32.@]
2849 * Gets value in a thread's TLS slot.
2851 * PARAMS
2852 * index [in] TLS index to retrieve value for.
2854 * RETURNS
2855 * Success: Value stored in calling thread's TLS slot for index.
2856 * Failure: 0 and GetLastError() returns NO_ERROR.
2858 LPVOID WINAPI TlsGetValue( DWORD index )
2860 LPVOID ret;
2862 if (index < TLS_MINIMUM_AVAILABLE)
2864 ret = NtCurrentTeb()->TlsSlots[index];
2866 else
2868 index -= TLS_MINIMUM_AVAILABLE;
2869 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2871 SetLastError( ERROR_INVALID_PARAMETER );
2872 return NULL;
2874 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2875 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2877 SetLastError( ERROR_SUCCESS );
2878 return ret;
2882 /**********************************************************************
2883 * TlsSetValue [KERNEL32.@]
2885 * Stores a value in the thread's TLS slot.
2887 * PARAMS
2888 * index [in] TLS index to set value for.
2889 * value [in] Value to be stored.
2891 * RETURNS
2892 * Success: TRUE
2893 * Failure: FALSE
2895 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2897 if (index < TLS_MINIMUM_AVAILABLE)
2899 NtCurrentTeb()->TlsSlots[index] = value;
2901 else
2903 index -= TLS_MINIMUM_AVAILABLE;
2904 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2906 SetLastError( ERROR_INVALID_PARAMETER );
2907 return FALSE;
2909 if (!NtCurrentTeb()->TlsExpansionSlots &&
2910 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2911 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2913 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2914 return FALSE;
2916 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2918 return TRUE;
2922 /***********************************************************************
2923 * GetProcessFlags (KERNEL32.@)
2925 DWORD WINAPI GetProcessFlags( DWORD processid )
2927 IMAGE_NT_HEADERS *nt;
2928 DWORD flags = 0;
2930 if (processid && processid != GetCurrentProcessId()) return 0;
2932 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2934 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2935 flags |= PDB32_CONSOLE_PROC;
2937 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2938 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2939 return flags;
2943 /*********************************************************************
2944 * OpenProcess (KERNEL32.@)
2946 * Opens a handle to a process.
2948 * PARAMS
2949 * access [I] Desired access rights assigned to the returned handle.
2950 * inherit [I] Determines whether or not child processes will inherit the handle.
2951 * id [I] Process identifier of the process to get a handle to.
2953 * RETURNS
2954 * Success: Valid handle to the specified process.
2955 * Failure: NULL, check GetLastError().
2957 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2959 NTSTATUS status;
2960 HANDLE handle;
2961 OBJECT_ATTRIBUTES attr;
2962 CLIENT_ID cid;
2964 cid.UniqueProcess = ULongToHandle(id);
2965 cid.UniqueThread = 0; /* FIXME ? */
2967 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2968 attr.RootDirectory = NULL;
2969 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2970 attr.SecurityDescriptor = NULL;
2971 attr.SecurityQualityOfService = NULL;
2972 attr.ObjectName = NULL;
2974 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2976 status = NtOpenProcess(&handle, access, &attr, &cid);
2977 if (status != STATUS_SUCCESS)
2979 SetLastError( RtlNtStatusToDosError(status) );
2980 return NULL;
2982 return handle;
2986 /*********************************************************************
2987 * GetProcessId (KERNEL32.@)
2989 * Gets the a unique identifier of a process.
2991 * PARAMS
2992 * hProcess [I] Handle to the process.
2994 * RETURNS
2995 * Success: TRUE.
2996 * Failure: FALSE, check GetLastError().
2998 * NOTES
3000 * The identifier is unique only on the machine and only until the process
3001 * exits (including system shutdown).
3003 DWORD WINAPI GetProcessId( HANDLE hProcess )
3005 NTSTATUS status;
3006 PROCESS_BASIC_INFORMATION pbi;
3008 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3009 sizeof(pbi), NULL);
3010 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
3011 SetLastError( RtlNtStatusToDosError(status) );
3012 return 0;
3016 /*********************************************************************
3017 * CloseHandle (KERNEL32.@)
3019 * Closes a handle.
3021 * PARAMS
3022 * handle [I] Handle to close.
3024 * RETURNS
3025 * Success: TRUE.
3026 * Failure: FALSE, check GetLastError().
3028 BOOL WINAPI CloseHandle( HANDLE handle )
3030 NTSTATUS status;
3032 /* stdio handles need special treatment */
3033 if (handle == (HANDLE)STD_INPUT_HANDLE)
3034 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
3035 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
3036 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
3037 else if (handle == (HANDLE)STD_ERROR_HANDLE)
3038 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
3040 if (is_console_handle(handle))
3041 return CloseConsoleHandle(handle);
3043 status = NtClose( handle );
3044 if (status) SetLastError( RtlNtStatusToDosError(status) );
3045 return !status;
3049 /*********************************************************************
3050 * GetHandleInformation (KERNEL32.@)
3052 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
3054 OBJECT_DATA_INFORMATION info;
3055 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
3057 if (status) SetLastError( RtlNtStatusToDosError(status) );
3058 else if (flags)
3060 *flags = 0;
3061 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3062 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3064 return !status;
3068 /*********************************************************************
3069 * SetHandleInformation (KERNEL32.@)
3071 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3073 OBJECT_DATA_INFORMATION info;
3074 NTSTATUS status;
3076 /* if not setting both fields, retrieve current value first */
3077 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3078 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3080 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3082 SetLastError( RtlNtStatusToDosError(status) );
3083 return FALSE;
3086 if (mask & HANDLE_FLAG_INHERIT)
3087 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3088 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3089 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3091 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3092 if (status) SetLastError( RtlNtStatusToDosError(status) );
3093 return !status;
3097 /*********************************************************************
3098 * DuplicateHandle (KERNEL32.@)
3100 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3101 HANDLE dest_process, HANDLE *dest,
3102 DWORD access, BOOL inherit, DWORD options )
3104 NTSTATUS status;
3106 if (is_console_handle(source))
3108 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3109 if (source_process != dest_process ||
3110 source_process != GetCurrentProcess())
3112 SetLastError(ERROR_INVALID_PARAMETER);
3113 return FALSE;
3115 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3116 return (*dest != INVALID_HANDLE_VALUE);
3118 status = NtDuplicateObject( source_process, source, dest_process, dest,
3119 access, inherit ? OBJ_INHERIT : 0, options );
3120 if (status) SetLastError( RtlNtStatusToDosError(status) );
3121 return !status;
3125 /***********************************************************************
3126 * ConvertToGlobalHandle (KERNEL32.@)
3128 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3130 HANDLE ret = INVALID_HANDLE_VALUE;
3131 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3132 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3133 return ret;
3137 /***********************************************************************
3138 * SetHandleContext (KERNEL32.@)
3140 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3142 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3143 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3144 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3145 return FALSE;
3149 /***********************************************************************
3150 * GetHandleContext (KERNEL32.@)
3152 DWORD WINAPI GetHandleContext(HANDLE hnd)
3154 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3155 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3156 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3157 return 0;
3161 /***********************************************************************
3162 * CreateSocketHandle (KERNEL32.@)
3164 HANDLE WINAPI CreateSocketHandle(void)
3166 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3167 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3168 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3169 return INVALID_HANDLE_VALUE;
3173 /***********************************************************************
3174 * SetPriorityClass (KERNEL32.@)
3176 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3178 NTSTATUS status;
3179 PROCESS_PRIORITY_CLASS ppc;
3181 ppc.Foreground = FALSE;
3182 switch (priorityclass)
3184 case IDLE_PRIORITY_CLASS:
3185 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3186 case BELOW_NORMAL_PRIORITY_CLASS:
3187 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3188 case NORMAL_PRIORITY_CLASS:
3189 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3190 case ABOVE_NORMAL_PRIORITY_CLASS:
3191 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3192 case HIGH_PRIORITY_CLASS:
3193 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3194 case REALTIME_PRIORITY_CLASS:
3195 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3196 default:
3197 SetLastError(ERROR_INVALID_PARAMETER);
3198 return FALSE;
3201 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3202 &ppc, sizeof(ppc));
3204 if (status != STATUS_SUCCESS)
3206 SetLastError( RtlNtStatusToDosError(status) );
3207 return FALSE;
3209 return TRUE;
3213 /***********************************************************************
3214 * GetPriorityClass (KERNEL32.@)
3216 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3218 NTSTATUS status;
3219 PROCESS_BASIC_INFORMATION pbi;
3221 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3222 sizeof(pbi), NULL);
3223 if (status != STATUS_SUCCESS)
3225 SetLastError( RtlNtStatusToDosError(status) );
3226 return 0;
3228 switch (pbi.BasePriority)
3230 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3231 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3232 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3233 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3234 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3235 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3237 SetLastError( ERROR_INVALID_PARAMETER );
3238 return 0;
3242 /***********************************************************************
3243 * SetProcessAffinityMask (KERNEL32.@)
3245 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3247 NTSTATUS status;
3249 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3250 &affmask, sizeof(DWORD_PTR));
3251 if (status)
3253 SetLastError( RtlNtStatusToDosError(status) );
3254 return FALSE;
3256 return TRUE;
3260 /**********************************************************************
3261 * GetProcessAffinityMask (KERNEL32.@)
3263 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3265 NTSTATUS status = STATUS_SUCCESS;
3267 if (process_mask)
3269 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3270 process_mask, sizeof(*process_mask), NULL )))
3271 SetLastError( RtlNtStatusToDosError(status) );
3273 if (system_mask && status == STATUS_SUCCESS)
3275 SYSTEM_BASIC_INFORMATION info;
3277 if ((status = NtQuerySystemInformation( SystemBasicInformation, &info, sizeof(info), NULL )))
3278 SetLastError( RtlNtStatusToDosError(status) );
3279 else
3280 *system_mask = info.ActiveProcessorsAffinityMask;
3282 return !status;
3286 /***********************************************************************
3287 * GetProcessVersion (KERNEL32.@)
3289 DWORD WINAPI GetProcessVersion( DWORD pid )
3291 HANDLE process;
3292 NTSTATUS status;
3293 PROCESS_BASIC_INFORMATION pbi;
3294 SIZE_T count;
3295 PEB peb;
3296 IMAGE_DOS_HEADER dos;
3297 IMAGE_NT_HEADERS nt;
3298 DWORD ver = 0;
3300 if (!pid || pid == GetCurrentProcessId())
3302 IMAGE_NT_HEADERS *pnt;
3304 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3305 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3306 pnt->OptionalHeader.MinorSubsystemVersion);
3307 return 0;
3310 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3311 if (!process) return 0;
3313 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3314 if (status) goto err;
3316 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3317 if (status || count != sizeof(peb)) goto err;
3319 memset(&dos, 0, sizeof(dos));
3320 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3321 if (status || count != sizeof(dos)) goto err;
3322 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3324 memset(&nt, 0, sizeof(nt));
3325 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3326 if (status || count != sizeof(nt)) goto err;
3327 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3329 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3331 err:
3332 CloseHandle(process);
3334 if (status != STATUS_SUCCESS)
3335 SetLastError(RtlNtStatusToDosError(status));
3337 return ver;
3341 /***********************************************************************
3342 * SetProcessWorkingSetSize [KERNEL32.@]
3343 * Sets the min/max working set sizes for a specified process.
3345 * PARAMS
3346 * hProcess [I] Handle to the process of interest
3347 * minset [I] Specifies minimum working set size
3348 * maxset [I] Specifies maximum working set size
3350 * RETURNS
3351 * Success: TRUE
3352 * Failure: FALSE
3354 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3355 SIZE_T maxset)
3357 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3358 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3359 /* Trim the working set to zero */
3360 /* Swap the process out of physical RAM */
3362 return TRUE;
3365 /***********************************************************************
3366 * K32EmptyWorkingSet (KERNEL32.@)
3368 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3370 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3373 /***********************************************************************
3374 * GetProcessWorkingSetSize (KERNEL32.@)
3376 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3377 PSIZE_T maxset)
3379 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3380 /* 32 MB working set size */
3381 if (minset) *minset = 32*1024*1024;
3382 if (maxset) *maxset = 32*1024*1024;
3383 return TRUE;
3387 /***********************************************************************
3388 * SetProcessShutdownParameters (KERNEL32.@)
3390 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3392 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3393 shutdown_flags = flags;
3394 shutdown_priority = level;
3395 return TRUE;
3399 /***********************************************************************
3400 * GetProcessShutdownParameters (KERNEL32.@)
3403 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3405 *lpdwLevel = shutdown_priority;
3406 *lpdwFlags = shutdown_flags;
3407 return TRUE;
3411 /***********************************************************************
3412 * GetProcessPriorityBoost (KERNEL32.@)
3414 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3416 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3418 /* Report that no boost is present.. */
3419 *pDisablePriorityBoost = FALSE;
3421 return TRUE;
3424 /***********************************************************************
3425 * SetProcessPriorityBoost (KERNEL32.@)
3427 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3429 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3430 /* Say we can do it. I doubt the program will notice that we don't. */
3431 return TRUE;
3435 /***********************************************************************
3436 * ReadProcessMemory (KERNEL32.@)
3438 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3439 SIZE_T *bytes_read )
3441 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3442 if (status) SetLastError( RtlNtStatusToDosError(status) );
3443 return !status;
3447 /***********************************************************************
3448 * WriteProcessMemory (KERNEL32.@)
3450 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3451 SIZE_T *bytes_written )
3453 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3454 if (status) SetLastError( RtlNtStatusToDosError(status) );
3455 return !status;
3459 /****************************************************************************
3460 * FlushInstructionCache (KERNEL32.@)
3462 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3464 NTSTATUS status;
3465 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3466 if (status) SetLastError( RtlNtStatusToDosError(status) );
3467 return !status;
3471 /******************************************************************
3472 * GetProcessIoCounters (KERNEL32.@)
3474 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3476 NTSTATUS status;
3478 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3479 ioc, sizeof(*ioc), NULL);
3480 if (status) SetLastError( RtlNtStatusToDosError(status) );
3481 return !status;
3484 /******************************************************************
3485 * GetProcessHandleCount (KERNEL32.@)
3487 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3489 NTSTATUS status;
3491 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3492 cnt, sizeof(*cnt), NULL);
3493 if (status) SetLastError( RtlNtStatusToDosError(status) );
3494 return !status;
3497 /******************************************************************
3498 * QueryFullProcessImageNameA (KERNEL32.@)
3500 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3502 BOOL retval;
3503 DWORD pdwSizeW = *pdwSize;
3504 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3506 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3508 if(retval)
3509 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3510 lpExeName, *pdwSize, NULL, NULL));
3511 if(retval)
3512 *pdwSize = strlen(lpExeName);
3514 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3515 return retval;
3518 /******************************************************************
3519 * QueryFullProcessImageNameW (KERNEL32.@)
3521 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3523 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3524 UNICODE_STRING *dynamic_buffer = NULL;
3525 UNICODE_STRING *result = NULL;
3526 NTSTATUS status;
3527 DWORD needed;
3529 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3530 * is a DOS path and we depend on this. */
3531 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3532 sizeof(buffer) - sizeof(WCHAR), &needed);
3533 if (status == STATUS_INFO_LENGTH_MISMATCH)
3535 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3536 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3537 result = dynamic_buffer;
3539 else
3540 result = (PUNICODE_STRING)buffer;
3542 if (status) goto cleanup;
3544 if (dwFlags & PROCESS_NAME_NATIVE)
3546 WCHAR drive[3];
3547 WCHAR device[1024];
3548 DWORD ntlen, devlen;
3550 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3552 /* We cannot convert it to an NT device path so fail */
3553 status = STATUS_NO_SUCH_DEVICE;
3554 goto cleanup;
3557 /* Find this drive's NT device path */
3558 drive[0] = result->Buffer[0];
3559 drive[1] = ':';
3560 drive[2] = 0;
3561 if (!QueryDosDeviceW(drive, device, sizeof(device)/sizeof(*device)))
3563 status = STATUS_NO_SUCH_DEVICE;
3564 goto cleanup;
3567 devlen = lstrlenW(device);
3568 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3569 if (ntlen + 1 > *pdwSize)
3571 status = STATUS_BUFFER_TOO_SMALL;
3572 goto cleanup;
3574 *pdwSize = ntlen;
3576 memcpy(lpExeName, device, devlen * sizeof(*device));
3577 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3578 lpExeName[*pdwSize] = 0;
3579 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3581 else
3583 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3585 status = STATUS_BUFFER_TOO_SMALL;
3586 goto cleanup;
3589 *pdwSize = result->Length/sizeof(WCHAR);
3590 memcpy( lpExeName, result->Buffer, result->Length );
3591 lpExeName[*pdwSize] = 0;
3594 cleanup:
3595 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3596 if (status) SetLastError( RtlNtStatusToDosError(status) );
3597 return !status;
3600 /***********************************************************************
3601 * K32GetProcessImageFileNameA (KERNEL32.@)
3603 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3605 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3608 /***********************************************************************
3609 * K32GetProcessImageFileNameW (KERNEL32.@)
3611 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3613 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3616 /***********************************************************************
3617 * K32EnumProcesses (KERNEL32.@)
3619 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3621 SYSTEM_PROCESS_INFORMATION *spi;
3622 ULONG size = 0x4000;
3623 void *buf = NULL;
3624 NTSTATUS status;
3626 do {
3627 size *= 2;
3628 HeapFree(GetProcessHeap(), 0, buf);
3629 buf = HeapAlloc(GetProcessHeap(), 0, size);
3630 if (!buf)
3631 return FALSE;
3633 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3634 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3636 if (status != STATUS_SUCCESS)
3638 HeapFree(GetProcessHeap(), 0, buf);
3639 SetLastError(RtlNtStatusToDosError(status));
3640 return FALSE;
3643 spi = buf;
3645 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3647 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3648 *lpcbUsed += sizeof(DWORD);
3650 if (spi->NextEntryOffset == 0)
3651 break;
3653 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3656 HeapFree(GetProcessHeap(), 0, buf);
3657 return TRUE;
3660 /***********************************************************************
3661 * K32QueryWorkingSet (KERNEL32.@)
3663 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3665 NTSTATUS status;
3667 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3669 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3671 if (status)
3673 SetLastError( RtlNtStatusToDosError( status ) );
3674 return FALSE;
3676 return TRUE;
3679 /***********************************************************************
3680 * K32QueryWorkingSetEx (KERNEL32.@)
3682 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3684 NTSTATUS status;
3686 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3688 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3690 if (status)
3692 SetLastError( RtlNtStatusToDosError( status ) );
3693 return FALSE;
3695 return TRUE;
3698 /***********************************************************************
3699 * K32GetProcessMemoryInfo (KERNEL32.@)
3701 * Retrieve memory usage information for a given process
3704 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3705 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3707 NTSTATUS status;
3708 VM_COUNTERS vmc;
3710 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3712 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3713 return FALSE;
3716 status = NtQueryInformationProcess(process, ProcessVmCounters,
3717 &vmc, sizeof(vmc), NULL);
3719 if (status)
3721 SetLastError(RtlNtStatusToDosError(status));
3722 return FALSE;
3725 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3726 pmc->PageFaultCount = vmc.PageFaultCount;
3727 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3728 pmc->WorkingSetSize = vmc.WorkingSetSize;
3729 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3730 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3731 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3732 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3733 pmc->PagefileUsage = vmc.PagefileUsage;
3734 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3736 return TRUE;
3739 /***********************************************************************
3740 * ProcessIdToSessionId (KERNEL32.@)
3741 * This function is available on Terminal Server 4SP4 and Windows 2000
3743 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3745 /* According to MSDN, if the calling process is not in a terminal
3746 * services environment, then the sessionid returned is zero.
3748 *sessionid_ptr = 0;
3749 return TRUE;
3753 /***********************************************************************
3754 * RegisterServiceProcess (KERNEL32.@)
3756 * A service process calls this function to ensure that it continues to run
3757 * even after a user logged off.
3759 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3761 /* I don't think that Wine needs to do anything in this function */
3762 return 1; /* success */
3766 /**********************************************************************
3767 * IsWow64Process (KERNEL32.@)
3769 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3771 ULONG_PTR pbi;
3772 NTSTATUS status;
3774 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3776 if (status != STATUS_SUCCESS)
3778 SetLastError( RtlNtStatusToDosError( status ) );
3779 return FALSE;
3781 *Wow64Process = (pbi != 0);
3782 return TRUE;
3786 /***********************************************************************
3787 * GetCurrentProcess (KERNEL32.@)
3789 * Get a handle to the current process.
3791 * PARAMS
3792 * None.
3794 * RETURNS
3795 * A handle representing the current process.
3797 #undef GetCurrentProcess
3798 HANDLE WINAPI GetCurrentProcess(void)
3800 return (HANDLE)~(ULONG_PTR)0;
3803 /***********************************************************************
3804 * GetLogicalProcessorInformation (KERNEL32.@)
3806 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3808 NTSTATUS status;
3810 TRACE("(%p,%p)\n", buffer, pBufLen);
3812 if(!pBufLen)
3814 SetLastError(ERROR_INVALID_PARAMETER);
3815 return FALSE;
3818 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
3820 if (status == STATUS_INFO_LENGTH_MISMATCH)
3822 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3823 return FALSE;
3825 if (status != STATUS_SUCCESS)
3827 SetLastError( RtlNtStatusToDosError( status ) );
3828 return FALSE;
3830 return TRUE;
3833 /***********************************************************************
3834 * GetLogicalProcessorInformationEx (KERNEL32.@)
3836 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer, PDWORD pBufLen)
3838 FIXME("(%u,%p,%p): stub\n", relationship, buffer, pBufLen);
3839 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3840 return FALSE;
3843 /***********************************************************************
3844 * CmdBatNotification (KERNEL32.@)
3846 * Notifies the system that a batch file has started or finished.
3848 * PARAMS
3849 * bBatchRunning [I] TRUE if a batch file has started or
3850 * FALSE if a batch file has finished executing.
3852 * RETURNS
3853 * Unknown.
3855 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3857 FIXME("%d\n", bBatchRunning);
3858 return FALSE;
3862 /***********************************************************************
3863 * RegisterApplicationRestart (KERNEL32.@)
3865 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3867 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3869 return S_OK;
3872 /**********************************************************************
3873 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3875 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3877 static int once;
3878 if (!once++) FIXME("stub\n");
3879 return 0;
3882 /**********************************************************************
3883 * GetSystemDEPPolicy (KERNEL32.@)
3885 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3887 FIXME("stub\n");
3888 return OptIn;
3891 /**********************************************************************
3892 * SetProcessDEPPolicy (KERNEL32.@)
3894 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3896 FIXME("(%d): stub\n", newDEP);
3897 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3898 return FALSE;
3901 /**********************************************************************
3902 * ApplicationRecoveryFinished (KERNEL32.@)
3904 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
3906 FIXME(": stub\n");
3907 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3910 /**********************************************************************
3911 * ApplicationRecoveryInProgress (KERNEL32.@)
3913 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
3915 FIXME(":%p stub\n", canceled);
3916 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3917 return E_FAIL;
3920 /**********************************************************************
3921 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3923 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
3925 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
3926 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3927 return E_FAIL;
3930 /**********************************************************************
3931 * GetNumaHighestNodeNumber (KERNEL32.@)
3933 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
3935 *highestnode = 0;
3936 FIXME("(%p): semi-stub\n", highestnode);
3937 return TRUE;
3940 /**********************************************************************
3941 * GetNumaNodeProcessorMask (KERNEL32.@)
3943 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
3945 FIXME("(%c %p): stub\n", node, mask);
3946 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3947 return FALSE;
3950 /**********************************************************************
3951 * GetNumaAvailableMemoryNode (KERNEL32.@)
3953 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
3955 FIXME("(%c %p): stub\n", node, available_bytes);
3956 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3957 return FALSE;
3960 /**********************************************************************
3961 * GetProcessDEPPolicy (KERNEL32.@)
3963 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
3965 NTSTATUS status;
3966 ULONG dep_flags;
3968 TRACE("(%p %p %p)\n", process, flags, permanent);
3970 status = NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
3971 &dep_flags, sizeof(dep_flags), NULL );
3972 if (!status)
3975 if (flags)
3977 *flags = 0;
3978 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE)
3979 *flags |= PROCESS_DEP_ENABLE;
3980 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION)
3981 *flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
3984 if (permanent)
3985 *permanent = (dep_flags & MEM_EXECUTE_OPTION_PERMANENT) != 0;
3988 if (status) SetLastError( RtlNtStatusToDosError(status) );
3989 return !status;
3992 /**********************************************************************
3993 * FlushProcessWriteBuffers (KERNEL32.@)
3995 VOID WINAPI FlushProcessWriteBuffers(void)
3997 static int once = 0;
3999 if (!once++)
4000 FIXME(": stub\n");
4003 /***********************************************************************
4004 * UnregisterApplicationRestart (KERNEL32.@)
4006 HRESULT WINAPI UnregisterApplicationRestart(void)
4008 FIXME(": stub\n");
4009 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4010 return S_OK;
4013 /***********************************************************************
4014 * GetSystemFirmwareTable (KERNEL32.@)
4016 UINT WINAPI GetSystemFirmwareTable(DWORD provider, DWORD id, PVOID buffer, DWORD size)
4018 FIXME("(%d %d %p %d):stub\n", provider, id, buffer, size);
4019 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4020 return 0;