TESTING -- override pthreads to fix gstreamer v5
[wine/multimedia.git] / dlls / kernel32 / process.c
blob89ae5c489d6e8476746038eaedac8d222bed9271
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[] = {'\\','R','e','g','i','s','t','r','y','\\',
404 'M','a','c','h','i','n','e','\\',
405 'S','y','s','t','e','m','\\',
406 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
407 'C','o','n','t','r','o','l','\\',
408 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
409 'E','n','v','i','r','o','n','m','e','n','t',0};
410 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
411 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};
413 OBJECT_ATTRIBUTES attr;
414 UNICODE_STRING nameW;
415 HANDLE hkey;
416 BOOL ret = FALSE;
418 attr.Length = sizeof(attr);
419 attr.RootDirectory = 0;
420 attr.ObjectName = &nameW;
421 attr.Attributes = 0;
422 attr.SecurityDescriptor = NULL;
423 attr.SecurityQualityOfService = NULL;
425 /* first the system environment variables */
426 RtlInitUnicodeString( &nameW, env_keyW );
427 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
429 set_registry_variables( hkey, REG_SZ );
430 set_registry_variables( hkey, REG_EXPAND_SZ );
431 NtClose( hkey );
432 ret = TRUE;
435 /* then the ones for the current user */
436 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
437 RtlInitUnicodeString( &nameW, envW );
438 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
440 set_registry_variables( hkey, REG_SZ );
441 set_registry_variables( hkey, REG_EXPAND_SZ );
442 NtClose( hkey );
445 RtlInitUnicodeString( &nameW, volatile_envW );
446 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
448 set_registry_variables( hkey, REG_SZ );
449 set_registry_variables( hkey, REG_EXPAND_SZ );
450 NtClose( hkey );
453 NtClose( attr.RootDirectory );
454 return ret;
458 /***********************************************************************
459 * get_reg_value
461 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
463 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
464 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
465 DWORD len, size = sizeof(buffer);
466 WCHAR *ret = NULL;
467 UNICODE_STRING nameW;
469 RtlInitUnicodeString( &nameW, name );
470 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
471 return NULL;
473 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
474 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
476 if (info->Type == REG_EXPAND_SZ)
478 UNICODE_STRING value, expanded;
480 value.MaximumLength = len * sizeof(WCHAR);
481 value.Buffer = (WCHAR *)info->Data;
482 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
483 value.Length = len * sizeof(WCHAR);
484 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
485 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
486 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
487 else RtlFreeUnicodeString( &expanded );
489 else if (info->Type == REG_SZ)
491 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
493 memcpy( ret, info->Data, len * sizeof(WCHAR) );
494 ret[len] = 0;
497 return ret;
501 /***********************************************************************
502 * set_additional_environment
504 * Set some additional environment variables not specified in the registry.
506 static void set_additional_environment(void)
508 static const WCHAR profile_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
509 'M','a','c','h','i','n','e','\\',
510 'S','o','f','t','w','a','r','e','\\',
511 'M','i','c','r','o','s','o','f','t','\\',
512 'W','i','n','d','o','w','s',' ','N','T','\\',
513 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
514 'P','r','o','f','i','l','e','L','i','s','t',0};
515 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
516 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
517 static const WCHAR computernameW[] = {'C','O','M','P','U','T','E','R','N','A','M','E',0};
518 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
519 OBJECT_ATTRIBUTES attr;
520 UNICODE_STRING nameW;
521 WCHAR *profile_dir = NULL, *all_users_dir = NULL;
522 WCHAR buf[MAX_COMPUTERNAME_LENGTH+1];
523 HANDLE hkey;
524 DWORD len;
526 /* ComputerName */
527 len = sizeof(buf) / sizeof(WCHAR);
528 if (GetComputerNameW( buf, &len ))
529 SetEnvironmentVariableW( computernameW, buf );
531 /* set the ALLUSERSPROFILE variables */
533 attr.Length = sizeof(attr);
534 attr.RootDirectory = 0;
535 attr.ObjectName = &nameW;
536 attr.Attributes = 0;
537 attr.SecurityDescriptor = NULL;
538 attr.SecurityQualityOfService = NULL;
539 RtlInitUnicodeString( &nameW, profile_keyW );
540 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
542 profile_dir = get_reg_value( hkey, profiles_valueW );
543 all_users_dir = get_reg_value( hkey, all_users_valueW );
544 NtClose( hkey );
547 if (profile_dir && all_users_dir)
549 WCHAR *value, *p;
551 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
552 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
553 strcpyW( value, profile_dir );
554 p = value + strlenW(value);
555 if (p > value && p[-1] != '\\') *p++ = '\\';
556 strcpyW( p, all_users_dir );
557 SetEnvironmentVariableW( allusersW, value );
558 HeapFree( GetProcessHeap(), 0, value );
561 HeapFree( GetProcessHeap(), 0, all_users_dir );
562 HeapFree( GetProcessHeap(), 0, profile_dir );
565 /***********************************************************************
566 * set_wow64_environment
568 * Set the environment variables that change across 32/64/Wow64.
570 static void set_wow64_environment(void)
572 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};
573 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};
574 static const WCHAR x86W[] = {'x','8','6',0};
575 static const WCHAR versionW[] = {'\\','R','e','g','i','s','t','r','y','\\',
576 'M','a','c','h','i','n','e','\\',
577 'S','o','f','t','w','a','r','e','\\',
578 'M','i','c','r','o','s','o','f','t','\\',
579 'W','i','n','d','o','w','s','\\',
580 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
581 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
582 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
583 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
584 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
585 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
586 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
587 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
588 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
590 OBJECT_ATTRIBUTES attr;
591 UNICODE_STRING nameW;
592 WCHAR arch[64];
593 WCHAR *value;
594 HANDLE hkey;
596 /* set the PROCESSOR_ARCHITECTURE variable */
598 if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
600 if (is_win64)
602 SetEnvironmentVariableW( archW, arch );
603 SetEnvironmentVariableW( arch6432W, NULL );
606 else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
608 if (is_wow64)
610 SetEnvironmentVariableW( arch6432W, arch );
611 SetEnvironmentVariableW( archW, x86W );
615 attr.Length = sizeof(attr);
616 attr.RootDirectory = 0;
617 attr.ObjectName = &nameW;
618 attr.Attributes = 0;
619 attr.SecurityDescriptor = NULL;
620 attr.SecurityQualityOfService = NULL;
621 RtlInitUnicodeString( &nameW, versionW );
622 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
624 /* set the ProgramFiles variables */
626 if ((value = get_reg_value( hkey, progdirW )))
628 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
629 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
630 HeapFree( GetProcessHeap(), 0, value );
632 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
634 SetEnvironmentVariableW( progfilesW, value );
635 HeapFree( GetProcessHeap(), 0, value );
638 /* set the CommonProgramFiles variables */
640 if ((value = get_reg_value( hkey, commondirW )))
642 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
643 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
644 HeapFree( GetProcessHeap(), 0, value );
646 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
648 SetEnvironmentVariableW( commonfilesW, value );
649 HeapFree( GetProcessHeap(), 0, value );
652 NtClose( hkey );
655 /***********************************************************************
656 * set_library_wargv
658 * Set the Wine library Unicode argv global variables.
660 static void set_library_wargv( char **argv )
662 int argc;
663 char *q;
664 WCHAR *p;
665 WCHAR **wargv;
666 DWORD total = 0;
668 for (argc = 0; argv[argc]; argc++)
669 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
671 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
672 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
673 p = (WCHAR *)(wargv + argc + 1);
674 for (argc = 0; argv[argc]; argc++)
676 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
677 wargv[argc] = p;
678 p += reslen;
679 total -= reslen;
681 wargv[argc] = NULL;
683 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
685 for (argc = 0; wargv[argc]; argc++)
686 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
688 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
689 q = (char *)(argv + argc + 1);
690 for (argc = 0; wargv[argc]; argc++)
692 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
693 argv[argc] = q;
694 q += reslen;
695 total -= reslen;
697 argv[argc] = NULL;
699 __wine_main_argc = argc;
700 __wine_main_argv = argv;
701 __wine_main_wargv = wargv;
705 /***********************************************************************
706 * update_library_argv0
708 * Update the argv[0] global variable with the binary we have found.
710 static void update_library_argv0( const WCHAR *argv0 )
712 DWORD len = strlenW( argv0 );
714 if (len > strlenW( __wine_main_wargv[0] ))
716 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
718 strcpyW( __wine_main_wargv[0], argv0 );
720 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
721 if (len > strlen( __wine_main_argv[0] ) + 1)
723 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
725 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
729 /***********************************************************************
730 * build_command_line
732 * Build the command line of a process from the argv array.
734 * Note that it does NOT necessarily include the file name.
735 * Sometimes we don't even have any command line options at all.
737 * We must quote and escape characters so that the argv array can be rebuilt
738 * from the command line:
739 * - spaces and tabs must be quoted
740 * 'a b' -> '"a b"'
741 * - quotes must be escaped
742 * '"' -> '\"'
743 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
744 * resulting in an odd number of '\' followed by a '"'
745 * '\"' -> '\\\"'
746 * '\\"' -> '\\\\\"'
747 * - '\'s that are not followed by a '"' can be left as is
748 * 'a\b' == 'a\b'
749 * 'a\\b' == 'a\\b'
751 static BOOL build_command_line( WCHAR **argv )
753 int len;
754 WCHAR **arg;
755 LPWSTR p;
756 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
758 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
760 len = 0;
761 for (arg = argv; *arg; arg++)
763 BOOL has_space;
764 int bcount;
765 WCHAR* a;
767 has_space=FALSE;
768 bcount=0;
769 a=*arg;
770 if( !*a ) has_space=TRUE;
771 while (*a!='\0') {
772 if (*a=='\\') {
773 bcount++;
774 } else {
775 if (*a==' ' || *a=='\t') {
776 has_space=TRUE;
777 } else if (*a=='"') {
778 /* doubling of '\' preceding a '"',
779 * plus escaping of said '"'
781 len+=2*bcount+1;
783 bcount=0;
785 a++;
787 len+=(a-*arg)+1 /* for the separating space */;
788 if (has_space)
789 len+=2; /* for the quotes */
792 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
793 return FALSE;
795 p = rupp->CommandLine.Buffer;
796 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
797 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
798 for (arg = argv; *arg; arg++)
800 BOOL has_space,has_quote;
801 WCHAR* a;
803 /* Check for quotes and spaces in this argument */
804 has_space=has_quote=FALSE;
805 a=*arg;
806 if( !*a ) has_space=TRUE;
807 while (*a!='\0') {
808 if (*a==' ' || *a=='\t') {
809 has_space=TRUE;
810 if (has_quote)
811 break;
812 } else if (*a=='"') {
813 has_quote=TRUE;
814 if (has_space)
815 break;
817 a++;
820 /* Now transfer it to the command line */
821 if (has_space)
822 *p++='"';
823 if (has_quote) {
824 int bcount;
826 bcount=0;
827 a=*arg;
828 while (*a!='\0') {
829 if (*a=='\\') {
830 *p++=*a;
831 bcount++;
832 } else {
833 if (*a=='"') {
834 int i;
836 /* Double all the '\\' preceding this '"', plus one */
837 for (i=0;i<=bcount;i++)
838 *p++='\\';
839 *p++='"';
840 } else {
841 *p++=*a;
843 bcount=0;
845 a++;
847 } else {
848 WCHAR* x = *arg;
849 while ((*p=*x++)) p++;
851 if (has_space)
852 *p++='"';
853 *p++=' ';
855 if (p > rupp->CommandLine.Buffer)
856 p--; /* remove last space */
857 *p = '\0';
859 return TRUE;
863 /***********************************************************************
864 * init_current_directory
866 * Initialize the current directory from the Unix cwd or the parent info.
868 static void init_current_directory( CURDIR *cur_dir )
870 UNICODE_STRING dir_str;
871 const char *pwd;
872 char *cwd;
873 int size;
875 /* if we received a cur dir from the parent, try this first */
877 if (cur_dir->DosPath.Length)
879 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
882 /* now try to get it from the Unix cwd */
884 for (size = 256; ; size *= 2)
886 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
887 if (getcwd( cwd, size )) break;
888 HeapFree( GetProcessHeap(), 0, cwd );
889 if (errno == ERANGE) continue;
890 cwd = NULL;
891 break;
894 /* try to use PWD if it is valid, so that we don't resolve symlinks */
896 pwd = getenv( "PWD" );
897 if (cwd)
899 struct stat st1, st2;
901 if (!pwd || stat( pwd, &st1 ) == -1 ||
902 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
903 pwd = cwd;
906 if (pwd)
908 ANSI_STRING unix_name;
909 UNICODE_STRING nt_name;
910 RtlInitAnsiString( &unix_name, pwd );
911 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
913 UNICODE_STRING dos_path;
914 /* skip the \??\ prefix, nt_name is 0 terminated */
915 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
916 RtlSetCurrentDirectory_U( &dos_path );
917 RtlFreeUnicodeString( &nt_name );
921 if (!cur_dir->DosPath.Length) /* still not initialized */
923 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
924 "starting in the Windows directory.\n", cwd ? cwd : "" );
925 RtlInitUnicodeString( &dir_str, DIR_Windows );
926 RtlSetCurrentDirectory_U( &dir_str );
928 HeapFree( GetProcessHeap(), 0, cwd );
930 done:
931 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
935 /***********************************************************************
936 * init_windows_dirs
938 * Initialize the windows and system directories from the environment.
940 static void init_windows_dirs(void)
942 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
944 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
945 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
946 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
947 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
948 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
950 DWORD len;
951 WCHAR *buffer;
953 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
955 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
956 GetEnvironmentVariableW( windirW, buffer, len );
957 DIR_Windows = buffer;
959 else DIR_Windows = default_windirW;
961 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
963 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
964 GetEnvironmentVariableW( winsysdirW, buffer, len );
965 DIR_System = buffer;
967 else
969 len = strlenW( DIR_Windows );
970 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
971 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
972 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
973 DIR_System = buffer;
976 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
977 ERR( "directory %s could not be created, error %u\n",
978 debugstr_w(DIR_Windows), GetLastError() );
979 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
980 ERR( "directory %s could not be created, error %u\n",
981 debugstr_w(DIR_System), GetLastError() );
983 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
985 len = strlenW( DIR_Windows );
986 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
987 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
988 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
989 DIR_SysWow64 = buffer;
990 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
991 ERR( "directory %s could not be created, error %u\n",
992 debugstr_w(DIR_SysWow64), GetLastError() );
995 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
996 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
998 /* set the directories in ntdll too */
999 __wine_init_windows_dir( DIR_Windows, DIR_System );
1003 /***********************************************************************
1004 * start_wineboot
1006 * Start the wineboot process if necessary. Return the handles to wait on.
1008 static void start_wineboot( HANDLE handles[2] )
1010 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
1012 handles[1] = 0;
1013 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
1015 ERR( "failed to create wineboot event, expect trouble\n" );
1016 return;
1018 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
1020 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1021 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1022 STARTUPINFOW si;
1023 PROCESS_INFORMATION pi;
1024 void *redir;
1025 WCHAR app[MAX_PATH];
1026 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1028 memset( &si, 0, sizeof(si) );
1029 si.cb = sizeof(si);
1030 si.dwFlags = STARTF_USESTDHANDLES;
1031 si.hStdInput = 0;
1032 si.hStdOutput = 0;
1033 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1035 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1036 lstrcatW( app, wineboot );
1038 Wow64DisableWow64FsRedirection( &redir );
1039 strcpyW( cmdline, app );
1040 strcatW( cmdline, args );
1041 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1043 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1044 CloseHandle( pi.hThread );
1045 handles[1] = pi.hProcess;
1047 else
1049 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1050 CloseHandle( handles[0] );
1051 handles[0] = 0;
1053 Wow64RevertWow64FsRedirection( redir );
1058 #ifdef __i386__
1059 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1060 __ASM_GLOBAL_FUNC( call_process_entry,
1061 "pushl %ebp\n\t"
1062 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1063 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1064 "movl %esp,%ebp\n\t"
1065 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1066 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1067 "pushl 8(%ebp)\n\t"
1068 "call *12(%ebp)\n\t"
1069 "leave\n\t"
1070 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1071 __ASM_CFI(".cfi_same_value %ebp\n\t")
1072 "ret" )
1073 #else
1074 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1076 return entry( peb );
1078 #endif
1080 /***********************************************************************
1081 * start_process
1083 * Startup routine of a new process. Runs on the new process stack.
1085 static DWORD WINAPI start_process( PEB *peb )
1087 IMAGE_NT_HEADERS *nt;
1088 LPTHREAD_START_ROUTINE entry;
1090 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1091 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1092 nt->OptionalHeader.AddressOfEntryPoint);
1094 if (!nt->OptionalHeader.AddressOfEntryPoint)
1096 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1097 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1098 ExitThread( 1 );
1101 if (TRACE_ON(relay))
1102 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1103 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1105 SetLastError( 0 ); /* clear error code */
1106 if (peb->BeingDebugged) DbgBreakPoint();
1107 return call_process_entry( peb, entry );
1111 /***********************************************************************
1112 * set_process_name
1114 * Change the process name in the ps output.
1116 static void set_process_name( int argc, char *argv[] )
1118 #ifdef HAVE_SETPROCTITLE
1119 setproctitle("-%s", argv[1]);
1120 #endif
1122 #ifdef HAVE_PRCTL
1123 int i, offset;
1124 char *p, *prctl_name = argv[1];
1125 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1127 #ifndef PR_SET_NAME
1128 # define PR_SET_NAME 15
1129 #endif
1131 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1132 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1134 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1136 offset = argv[1] - argv[0];
1137 memmove( argv[1] - offset, argv[1], end - argv[1] );
1138 memset( end - offset, 0, offset );
1139 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1140 argv[i-1] = NULL;
1142 else
1143 #endif /* HAVE_PRCTL */
1145 /* remove argv[0] */
1146 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1151 /***********************************************************************
1152 * __wine_kernel_init
1154 * Wine initialisation: load and start the main exe file.
1156 void CDECL __wine_kernel_init(void)
1158 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1159 static const WCHAR dotW[] = {'.',0};
1161 WCHAR *p, main_exe_name[MAX_PATH+1];
1162 PEB *peb = NtCurrentTeb()->Peb;
1163 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1164 HANDLE boot_events[2];
1165 BOOL got_environment = TRUE;
1167 /* Initialize everything */
1169 setbuf(stdout,NULL);
1170 setbuf(stderr,NULL);
1171 kernel32_handle = GetModuleHandleW(kernel32W);
1172 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1174 LOCALE_Init();
1176 if (!params->Environment)
1178 /* Copy the parent environment */
1179 if (!build_initial_environment()) exit(1);
1181 /* convert old configuration to new format */
1182 convert_old_config();
1184 got_environment = set_registry_environment( FALSE );
1185 set_additional_environment();
1188 init_windows_dirs();
1189 init_current_directory( &params->CurrentDirectory );
1191 set_process_name( __wine_main_argc, __wine_main_argv );
1192 set_library_wargv( __wine_main_argv );
1193 boot_events[0] = boot_events[1] = 0;
1195 if (peb->ProcessParameters->ImagePathName.Buffer)
1197 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1199 else
1201 struct binary_info binary_info;
1203 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1204 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1206 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1207 ExitProcess( GetLastError() );
1209 update_library_argv0( main_exe_name );
1210 if (!build_command_line( __wine_main_wargv )) goto error;
1211 start_wineboot( boot_events );
1214 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1215 p = strrchrW( main_exe_name, '.' );
1216 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1218 TRACE( "starting process name=%s argv[0]=%s\n",
1219 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1221 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1222 MODULE_get_dll_load_path(main_exe_name) );
1224 if (boot_events[0])
1226 DWORD timeout = 2 * 60 * 1000, count = 1;
1228 if (boot_events[1]) count++;
1229 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1230 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1231 ERR( "boot event wait timed out\n" );
1232 CloseHandle( boot_events[0] );
1233 if (boot_events[1]) CloseHandle( boot_events[1] );
1234 /* reload environment now that wineboot has run */
1235 set_registry_environment( got_environment );
1236 set_additional_environment();
1238 set_wow64_environment();
1240 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1242 DWORD_PTR args[1];
1243 WCHAR msgW[1024];
1244 char msg[1024];
1245 DWORD error = GetLastError();
1247 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1248 if (error == ERROR_BAD_EXE_FORMAT ||
1249 error == ERROR_INVALID_ADDRESS ||
1250 error == ERROR_NOT_ENOUGH_MEMORY)
1252 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1253 /* if we get back here, it failed */
1255 else if (error == ERROR_MOD_NOT_FOUND)
1257 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1258 else p = main_exe_name;
1259 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1261 /* args 1 and 2 are --app-name full_path */
1262 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1263 debugstr_w(__wine_main_wargv[3]) );
1264 ExitProcess( ERROR_BAD_EXE_FORMAT );
1266 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1267 ExitProcess( ERROR_FILE_NOT_FOUND );
1269 args[0] = (DWORD_PTR)main_exe_name;
1270 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1271 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1272 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1273 MESSAGE( "wine: %s", msg );
1274 ExitProcess( error );
1277 if (!params->CurrentDirectory.Handle) chdir("/"); /* avoid locking removable devices */
1279 LdrInitializeThunk( start_process, 0, 0, 0 );
1281 error:
1282 ExitProcess( GetLastError() );
1286 /***********************************************************************
1287 * build_argv
1289 * Build an argv array from a command-line.
1290 * 'reserved' is the number of args to reserve before the first one.
1292 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1294 int argc;
1295 char** argv;
1296 char *arg,*s,*d,*cmdline;
1297 int in_quotes,bcount,len;
1299 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1300 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1301 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1303 argc=reserved+1;
1304 bcount=0;
1305 in_quotes=0;
1306 s=cmdline;
1307 while (1) {
1308 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1309 /* space */
1310 argc++;
1311 /* skip the remaining spaces */
1312 while (*s==' ' || *s=='\t') {
1313 s++;
1315 if (*s=='\0')
1316 break;
1317 bcount=0;
1318 continue;
1319 } else if (*s=='\\') {
1320 /* '\', count them */
1321 bcount++;
1322 } else if ((*s=='"') && ((bcount & 1)==0)) {
1323 /* unescaped '"' */
1324 in_quotes=!in_quotes;
1325 bcount=0;
1326 } else {
1327 /* a regular character */
1328 bcount=0;
1330 s++;
1332 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1334 HeapFree( GetProcessHeap(), 0, cmdline );
1335 return NULL;
1338 arg = d = s = (char *)(argv + argc);
1339 memcpy( d, cmdline, len );
1340 bcount=0;
1341 in_quotes=0;
1342 argc=reserved;
1343 while (*s) {
1344 if ((*s==' ' || *s=='\t') && !in_quotes) {
1345 /* Close the argument and copy it */
1346 *d=0;
1347 argv[argc++]=arg;
1349 /* skip the remaining spaces */
1350 do {
1351 s++;
1352 } while (*s==' ' || *s=='\t');
1354 /* Start with a new argument */
1355 arg=d=s;
1356 bcount=0;
1357 } else if (*s=='\\') {
1358 /* '\\' */
1359 *d++=*s++;
1360 bcount++;
1361 } else if (*s=='"') {
1362 /* '"' */
1363 if ((bcount & 1)==0) {
1364 /* Preceded by an even number of '\', this is half that
1365 * number of '\', plus a '"' which we discard.
1367 d-=bcount/2;
1368 s++;
1369 in_quotes=!in_quotes;
1370 } else {
1371 /* Preceded by an odd number of '\', this is half that
1372 * number of '\' followed by a '"'
1374 d=d-bcount/2-1;
1375 *d++='"';
1376 s++;
1378 bcount=0;
1379 } else {
1380 /* a regular character */
1381 *d++=*s++;
1382 bcount=0;
1385 if (*arg) {
1386 *d='\0';
1387 argv[argc++]=arg;
1389 argv[argc]=NULL;
1391 HeapFree( GetProcessHeap(), 0, cmdline );
1392 return argv;
1396 /***********************************************************************
1397 * build_envp
1399 * Build the environment of a new child process.
1401 static char **build_envp( const WCHAR *envW )
1403 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1405 const WCHAR *end;
1406 char **envp;
1407 char *env, *p;
1408 int count = 1, length;
1409 unsigned int i;
1411 for (end = envW; *end; count++) end += strlenW(end) + 1;
1412 end++;
1413 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1414 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1415 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1417 for (p = env; *p; p += strlen(p) + 1)
1418 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1420 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1422 if (!(p = getenv(unix_vars[i]))) continue;
1423 length += strlen(unix_vars[i]) + strlen(p) + 2;
1424 count++;
1427 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1429 char **envptr = envp;
1430 char *dst = (char *)(envp + count);
1432 /* some variables must not be modified, so we get them directly from the unix env */
1433 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1435 if (!(p = getenv(unix_vars[i]))) continue;
1436 *envptr++ = strcpy( dst, unix_vars[i] );
1437 strcat( dst, "=" );
1438 strcat( dst, p );
1439 dst += strlen(dst) + 1;
1442 /* now put the Windows environment strings */
1443 for (p = env; *p; p += strlen(p) + 1)
1445 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1446 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1447 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1448 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1449 if (is_special_env_var( p )) /* prefix it with "WINE" */
1451 *envptr++ = strcpy( dst, "WINE" );
1452 strcat( dst, p );
1454 else
1456 *envptr++ = strcpy( dst, p );
1458 dst += strlen(dst) + 1;
1460 *envptr = 0;
1462 HeapFree( GetProcessHeap(), 0, env );
1463 return envp;
1467 /***********************************************************************
1468 * fork_and_exec
1470 * Fork and exec a new Unix binary, checking for errors.
1472 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1473 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1475 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1476 int pid, err;
1477 char **argv, **envp;
1479 if (!env) env = GetEnvironmentStringsW();
1481 #ifdef HAVE_PIPE2
1482 if (pipe2( fd, O_CLOEXEC ) == -1)
1483 #endif
1485 if (pipe(fd) == -1)
1487 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1488 return -1;
1490 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1491 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1494 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1496 HANDLE hstdin, hstdout, hstderr;
1498 if (startup->dwFlags & STARTF_USESTDHANDLES)
1500 hstdin = startup->hStdInput;
1501 hstdout = startup->hStdOutput;
1502 hstderr = startup->hStdError;
1504 else
1506 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1507 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1508 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1511 if (is_console_handle( hstdin ))
1512 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1513 if (is_console_handle( hstdout ))
1514 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1515 if (is_console_handle( hstderr ))
1516 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1517 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1518 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1519 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1522 argv = build_argv( cmdline, 0 );
1523 envp = build_envp( env );
1525 if (!(pid = fork())) /* child */
1527 if (!(pid = fork())) /* grandchild */
1529 close( fd[0] );
1531 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1533 int nullfd = open( "/dev/null", O_RDWR );
1534 setsid();
1535 /* close stdin and stdout */
1536 if (nullfd != -1)
1538 dup2( nullfd, 0 );
1539 dup2( nullfd, 1 );
1540 close( nullfd );
1543 else
1545 if (stdin_fd != -1)
1547 dup2( stdin_fd, 0 );
1548 close( stdin_fd );
1550 if (stdout_fd != -1)
1552 dup2( stdout_fd, 1 );
1553 close( stdout_fd );
1555 if (stderr_fd != -1)
1557 dup2( stderr_fd, 2 );
1558 close( stderr_fd );
1562 /* Reset signals that we previously set to SIG_IGN */
1563 signal( SIGPIPE, SIG_DFL );
1565 if (newdir) chdir(newdir);
1567 if (argv && envp) execve( filename, argv, envp );
1570 if (pid <= 0) /* grandchild if exec failed or child if fork failed */
1572 err = errno;
1573 write( fd[1], &err, sizeof(err) );
1574 _exit(1);
1577 _exit(0); /* child if fork succeeded */
1579 HeapFree( GetProcessHeap(), 0, argv );
1580 HeapFree( GetProcessHeap(), 0, envp );
1581 if (stdin_fd != -1) close( stdin_fd );
1582 if (stdout_fd != -1) close( stdout_fd );
1583 if (stderr_fd != -1) close( stderr_fd );
1584 close( fd[1] );
1585 if (pid != -1)
1587 /* reap child */
1588 do {
1589 err = waitpid(pid, NULL, 0);
1590 } while (err < 0 && errno == EINTR);
1592 if (read( fd[0], &err, sizeof(err) ) > 0) /* exec or second fork failed */
1594 errno = err;
1595 pid = -1;
1598 if (pid == -1) FILE_SetDosError();
1599 close( fd[0] );
1600 return pid;
1604 static inline DWORD append_string( void **ptr, const WCHAR *str )
1606 DWORD len = strlenW( str );
1607 memcpy( *ptr, str, len * sizeof(WCHAR) );
1608 *ptr = (WCHAR *)*ptr + len;
1609 return len * sizeof(WCHAR);
1612 /***********************************************************************
1613 * create_startup_info
1615 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1616 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1617 const STARTUPINFOW *startup, DWORD *info_size )
1619 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1620 const WCHAR *title;
1621 startup_info_t *info;
1622 DWORD size;
1623 void *ptr;
1624 UNICODE_STRING newdir;
1625 WCHAR imagepath[MAX_PATH];
1626 HANDLE hstdin, hstdout, hstderr;
1628 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1629 lstrcpynW( imagepath, filename, MAX_PATH );
1630 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1631 lstrcpynW( imagepath, filename, MAX_PATH );
1633 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1635 newdir.Buffer = NULL;
1636 if (cur_dir)
1638 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1639 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1640 else
1641 cur_dir = NULL;
1643 if (!cur_dir)
1645 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1646 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1647 else
1648 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1650 title = startup->lpTitle ? startup->lpTitle : imagepath;
1652 size = sizeof(*info);
1653 size += strlenW( cur_dir ) * sizeof(WCHAR);
1654 size += cur_params->DllPath.Length;
1655 size += strlenW( imagepath ) * sizeof(WCHAR);
1656 size += strlenW( cmdline ) * sizeof(WCHAR);
1657 size += strlenW( title ) * sizeof(WCHAR);
1658 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1659 /* FIXME: shellinfo */
1660 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1661 size = (size + 1) & ~1;
1662 *info_size = size;
1664 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1666 info->console_flags = cur_params->ConsoleFlags;
1667 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1668 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1670 if (startup->dwFlags & STARTF_USESTDHANDLES)
1672 hstdin = startup->hStdInput;
1673 hstdout = startup->hStdOutput;
1674 hstderr = startup->hStdError;
1676 else
1678 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1679 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1680 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1682 info->hstdin = wine_server_obj_handle( hstdin );
1683 info->hstdout = wine_server_obj_handle( hstdout );
1684 info->hstderr = wine_server_obj_handle( hstderr );
1685 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1687 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1688 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1689 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1690 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1692 else
1694 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1695 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1696 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1699 info->x = startup->dwX;
1700 info->y = startup->dwY;
1701 info->xsize = startup->dwXSize;
1702 info->ysize = startup->dwYSize;
1703 info->xchars = startup->dwXCountChars;
1704 info->ychars = startup->dwYCountChars;
1705 info->attribute = startup->dwFillAttribute;
1706 info->flags = startup->dwFlags;
1707 info->show = startup->wShowWindow;
1709 ptr = info + 1;
1710 info->curdir_len = append_string( &ptr, cur_dir );
1711 info->dllpath_len = cur_params->DllPath.Length;
1712 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1713 ptr = (char *)ptr + cur_params->DllPath.Length;
1714 info->imagepath_len = append_string( &ptr, imagepath );
1715 info->cmdline_len = append_string( &ptr, cmdline );
1716 info->title_len = append_string( &ptr, title );
1717 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1718 if (startup->lpReserved2 && startup->cbReserved2)
1720 info->runtime_len = startup->cbReserved2;
1721 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1724 done:
1725 RtlFreeUnicodeString( &newdir );
1726 return info;
1729 /***********************************************************************
1730 * get_alternate_loader
1732 * Get the name of the alternate (32 or 64 bit) Wine loader.
1734 static const char *get_alternate_loader( char **ret_env )
1736 char *env;
1737 const char *loader = NULL;
1738 const char *loader_env = getenv( "WINELOADER" );
1740 *ret_env = NULL;
1742 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1744 if (loader_env)
1746 int len = strlen( loader_env );
1747 if (!is_win64)
1749 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1750 strcpy( env, "WINELOADER=" );
1751 strcat( env, loader_env );
1752 strcat( env, "64" );
1754 else
1756 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1757 strcpy( env, "WINELOADER=" );
1758 strcat( env, loader_env );
1759 len += sizeof("WINELOADER=") - 1;
1760 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1762 if (!loader)
1764 if ((loader = strrchr( env, '/' ))) loader++;
1765 else loader = env;
1767 *ret_env = env;
1769 if (!loader) loader = is_win64 ? "wine" : "wine64";
1770 return loader;
1773 #ifdef __APPLE__
1774 /***********************************************************************
1775 * terminate_main_thread
1777 * On some versions of Mac OS X, the execve system call fails with
1778 * ENOTSUP if the process has multiple threads. Wine is always multi-
1779 * threaded on Mac OS X because it specifically reserves the main thread
1780 * for use by the system frameworks (see apple_main_thread() in
1781 * libs/wine/loader.c). So, when we need to exec without first forking,
1782 * we need to terminate the main thread first. We do this by installing
1783 * a custom run loop source onto the main run loop and signaling it.
1784 * The source's "perform" callback is pthread_exit and it will be
1785 * executed on the main thread, terminating it.
1787 * Returns TRUE if there's still hope the main thread has terminated or
1788 * will soon. Return FALSE if we've given up.
1790 static BOOL terminate_main_thread(void)
1792 static int delayms;
1794 if (!delayms)
1796 CFRunLoopSourceContext source_context = { 0 };
1797 CFRunLoopSourceRef source;
1799 source_context.perform = pthread_exit;
1800 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1801 return FALSE;
1803 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1804 CFRunLoopSourceSignal( source );
1805 CFRunLoopWakeUp( CFRunLoopGetMain() );
1806 CFRelease( source );
1808 delayms = 20;
1811 if (delayms > 1000)
1812 return FALSE;
1814 usleep(delayms * 1000);
1815 delayms *= 2;
1817 return TRUE;
1819 #endif
1821 /***********************************************************************
1822 * get_process_cpu
1824 static int get_process_cpu( const WCHAR *filename, const struct binary_info *binary_info )
1826 switch (binary_info->arch)
1828 case IMAGE_FILE_MACHINE_I386: return CPU_x86;
1829 case IMAGE_FILE_MACHINE_AMD64: return CPU_x86_64;
1830 case IMAGE_FILE_MACHINE_POWERPC: return CPU_POWERPC;
1831 case IMAGE_FILE_MACHINE_ARM:
1832 case IMAGE_FILE_MACHINE_THUMB:
1833 case IMAGE_FILE_MACHINE_ARMNT: return CPU_ARM;
1834 case IMAGE_FILE_MACHINE_ARM64: return CPU_ARM64;
1836 ERR( "%s uses unsupported architecture (%04x)\n", debugstr_w(filename), binary_info->arch );
1837 return -1;
1840 /***********************************************************************
1841 * exec_loader
1843 static pid_t exec_loader( LPCWSTR cmd_line, unsigned int flags, int socketfd,
1844 int stdin_fd, int stdout_fd, const char *unixdir, char *winedebug,
1845 const struct binary_info *binary_info, int exec_only )
1847 pid_t pid;
1848 char *wineloader = NULL;
1849 const char *loader = NULL;
1850 char **argv;
1852 argv = build_argv( cmd_line, 1 );
1854 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1855 loader = get_alternate_loader( &wineloader );
1857 if (exec_only || !(pid = fork())) /* child */
1859 if (exec_only || !(pid = fork())) /* grandchild */
1861 char preloader_reserve[64], socket_env[64];
1863 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1865 int fd = open( "/dev/null", O_RDWR );
1866 setsid();
1867 /* close stdin and stdout */
1868 if (fd != -1)
1870 dup2( fd, 0 );
1871 dup2( fd, 1 );
1872 close( fd );
1875 else
1877 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1878 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1881 if (stdin_fd != -1) close( stdin_fd );
1882 if (stdout_fd != -1) close( stdout_fd );
1884 /* Reset signals that we previously set to SIG_IGN */
1885 signal( SIGPIPE, SIG_DFL );
1887 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
1888 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1889 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1891 putenv( preloader_reserve );
1892 putenv( socket_env );
1893 if (winedebug) putenv( winedebug );
1894 if (wineloader) putenv( wineloader );
1895 if (unixdir) chdir(unixdir);
1897 if (argv)
1901 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1903 #ifdef __APPLE__
1904 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1905 #else
1906 while (0);
1907 #endif
1909 _exit(1);
1912 _exit(pid == -1);
1915 if (pid != -1)
1917 /* reap child */
1918 pid_t wret;
1919 do {
1920 wret = waitpid(pid, NULL, 0);
1921 } while (wret < 0 && errno == EINTR);
1924 HeapFree( GetProcessHeap(), 0, wineloader );
1925 HeapFree( GetProcessHeap(), 0, argv );
1926 return pid;
1929 /***********************************************************************
1930 * create_process
1932 * Create a new process. If hFile is a valid handle we have an exe
1933 * file, otherwise it is a Winelib app.
1935 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1936 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1937 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1938 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1939 const struct binary_info *binary_info, int exec_only )
1941 static const char *cpu_names[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
1942 NTSTATUS status;
1943 BOOL success = FALSE;
1944 HANDLE process_info;
1945 WCHAR *env_end;
1946 char *winedebug = NULL;
1947 startup_info_t *startup_info;
1948 DWORD startup_info_size;
1949 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1950 pid_t pid;
1951 int err, cpu;
1953 if ((cpu = get_process_cpu( filename, binary_info )) == -1)
1955 SetLastError( ERROR_BAD_EXE_FORMAT );
1956 return FALSE;
1959 /* create the socket for the new process */
1961 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1963 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1964 return FALSE;
1966 #ifdef SO_PASSCRED
1967 else
1969 int enable = 1;
1970 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1972 #endif
1974 if (exec_only) /* things are much simpler in this case */
1976 wine_server_send_fd( socketfd[1] );
1977 close( socketfd[1] );
1978 SERVER_START_REQ( new_process )
1980 req->create_flags = flags;
1981 req->socket_fd = socketfd[1];
1982 req->exe_file = wine_server_obj_handle( hFile );
1983 req->cpu = cpu;
1984 status = wine_server_call( req );
1986 SERVER_END_REQ;
1988 switch (status)
1990 case STATUS_INVALID_IMAGE_WIN_64:
1991 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
1992 break;
1993 case STATUS_INVALID_IMAGE_FORMAT:
1994 ERR( "%s not supported on this installation (%s binary)\n",
1995 debugstr_w(filename), cpu_names[cpu] );
1996 break;
1997 case STATUS_SUCCESS:
1998 exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
1999 winedebug, binary_info, TRUE );
2001 close( socketfd[0] );
2002 SetLastError( RtlNtStatusToDosError( status ));
2003 return FALSE;
2006 RtlAcquirePebLock();
2008 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
2009 &startup_info_size )))
2011 RtlReleasePebLock();
2012 close( socketfd[0] );
2013 close( socketfd[1] );
2014 return FALSE;
2016 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
2017 env_end = env;
2018 while (*env_end)
2020 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
2021 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
2023 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
2024 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
2025 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
2027 env_end += strlenW(env_end) + 1;
2029 env_end++;
2031 wine_server_send_fd( socketfd[1] );
2032 close( socketfd[1] );
2034 /* create the process on the server side */
2036 SERVER_START_REQ( new_process )
2038 req->inherit_all = inherit;
2039 req->create_flags = flags;
2040 req->socket_fd = socketfd[1];
2041 req->exe_file = wine_server_obj_handle( hFile );
2042 req->process_access = PROCESS_ALL_ACCESS;
2043 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
2044 req->thread_access = THREAD_ALL_ACCESS;
2045 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
2046 req->cpu = cpu;
2047 req->info_size = startup_info_size;
2049 wine_server_add_data( req, startup_info, startup_info_size );
2050 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
2051 if (!(status = wine_server_call( req )))
2053 info->dwProcessId = (DWORD)reply->pid;
2054 info->dwThreadId = (DWORD)reply->tid;
2055 info->hProcess = wine_server_ptr_handle( reply->phandle );
2056 info->hThread = wine_server_ptr_handle( reply->thandle );
2058 process_info = wine_server_ptr_handle( reply->info );
2060 SERVER_END_REQ;
2062 RtlReleasePebLock();
2063 if (status)
2065 switch (status)
2067 case STATUS_INVALID_IMAGE_WIN_64:
2068 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2069 break;
2070 case STATUS_INVALID_IMAGE_FORMAT:
2071 ERR( "%s not supported on this installation (%s binary)\n",
2072 debugstr_w(filename), cpu_names[cpu] );
2073 break;
2075 close( socketfd[0] );
2076 HeapFree( GetProcessHeap(), 0, startup_info );
2077 HeapFree( GetProcessHeap(), 0, winedebug );
2078 SetLastError( RtlNtStatusToDosError( status ));
2079 return FALSE;
2082 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
2084 if (startup_info->hstdin)
2085 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
2086 FILE_READ_DATA, &stdin_fd, NULL );
2087 if (startup_info->hstdout)
2088 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
2089 FILE_WRITE_DATA, &stdout_fd, NULL );
2091 HeapFree( GetProcessHeap(), 0, startup_info );
2093 /* create the child process */
2095 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2096 winedebug, binary_info, FALSE );
2098 if (stdin_fd != -1) close( stdin_fd );
2099 if (stdout_fd != -1) close( stdout_fd );
2100 close( socketfd[0] );
2101 HeapFree( GetProcessHeap(), 0, winedebug );
2102 if (pid == -1)
2104 FILE_SetDosError();
2105 goto error;
2108 /* wait for the new process info to be ready */
2110 WaitForSingleObject( process_info, INFINITE );
2111 SERVER_START_REQ( get_new_process_info )
2113 req->info = wine_server_obj_handle( process_info );
2114 wine_server_call( req );
2115 success = reply->success;
2116 err = reply->exit_code;
2118 SERVER_END_REQ;
2120 if (!success)
2122 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2123 goto error;
2125 CloseHandle( process_info );
2126 return success;
2128 error:
2129 CloseHandle( process_info );
2130 CloseHandle( info->hProcess );
2131 CloseHandle( info->hThread );
2132 info->hProcess = info->hThread = 0;
2133 info->dwProcessId = info->dwThreadId = 0;
2134 return FALSE;
2138 /***********************************************************************
2139 * create_vdm_process
2141 * Create a new VDM process for a 16-bit or DOS application.
2143 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2144 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2145 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2146 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2147 const struct binary_info *binary_info, int exec_only )
2149 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2151 BOOL ret;
2152 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
2153 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
2155 if (!new_cmd_line)
2157 SetLastError( ERROR_OUTOFMEMORY );
2158 return FALSE;
2160 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
2161 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2162 flags, startup, info, unixdir, binary_info, exec_only );
2163 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2164 return ret;
2168 /***********************************************************************
2169 * create_cmd_process
2171 * Create a new cmd shell process for a .BAT file.
2173 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2174 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2175 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2176 LPPROCESS_INFORMATION info )
2179 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2180 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2181 WCHAR comspec[MAX_PATH];
2182 WCHAR *newcmdline;
2183 BOOL ret;
2185 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2186 return FALSE;
2187 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2188 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2189 return FALSE;
2191 strcpyW( newcmdline, comspec );
2192 strcatW( newcmdline, slashcW );
2193 strcatW( newcmdline, cmd_line );
2194 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2195 flags, env, cur_dir, startup, info );
2196 HeapFree( GetProcessHeap(), 0, newcmdline );
2197 return ret;
2201 /*************************************************************************
2202 * get_file_name
2204 * Helper for CreateProcess: retrieve the file name to load from the
2205 * app name and command line. Store the file name in buffer, and
2206 * return a possibly modified command line.
2207 * Also returns a handle to the opened file if it's a Windows binary.
2209 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2210 int buflen, HANDLE *handle, struct binary_info *binary_info )
2212 static const WCHAR quotesW[] = {'"','%','s','"',0};
2214 WCHAR *name, *pos, *first_space, *ret = NULL;
2215 const WCHAR *p;
2217 /* if we have an app name, everything is easy */
2219 if (appname)
2221 /* use the unmodified app name as file name */
2222 lstrcpynW( buffer, appname, buflen );
2223 *handle = open_exe_file( buffer, binary_info );
2224 if (!(ret = cmdline) || !cmdline[0])
2226 /* no command-line, create one */
2227 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2228 sprintfW( ret, quotesW, appname );
2230 return ret;
2233 /* first check for a quoted file name */
2235 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2237 int len = p - cmdline - 1;
2238 /* extract the quoted portion as file name */
2239 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2240 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2241 name[len] = 0;
2243 if (!find_exe_file( name, buffer, buflen, handle, binary_info )) goto done;
2244 ret = cmdline; /* no change necessary */
2245 goto done;
2248 /* now try the command-line word by word */
2250 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2251 return NULL;
2252 pos = name;
2253 p = cmdline;
2254 first_space = NULL;
2256 for (;;)
2258 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2259 *pos = 0;
2260 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2262 ret = cmdline;
2263 break;
2265 if (!first_space) first_space = pos;
2266 if (!(*pos++ = *p++)) break;
2269 if (!ret)
2271 SetLastError( ERROR_FILE_NOT_FOUND );
2273 else if (first_space) /* build a new command-line with quotes */
2275 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2276 goto done;
2277 sprintfW( ret, quotesW, name );
2278 strcatW( ret, p );
2281 done:
2282 HeapFree( GetProcessHeap(), 0, name );
2283 return ret;
2287 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2288 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2289 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2290 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2291 LPPROCESS_INFORMATION info )
2293 BOOL retv = FALSE;
2294 HANDLE hFile = 0;
2295 char *unixdir = NULL;
2296 WCHAR name[MAX_PATH];
2297 WCHAR *tidy_cmdline, *p, *envW = env;
2298 struct binary_info binary_info;
2300 /* Process the AppName and/or CmdLine to get module name and path */
2302 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2304 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2305 &hFile, &binary_info )))
2306 return FALSE;
2307 if (hFile == INVALID_HANDLE_VALUE) goto done;
2309 /* Warn if unsupported features are used */
2311 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2312 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2313 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2314 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2315 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2317 if (cur_dir)
2319 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2321 SetLastError(ERROR_DIRECTORY);
2322 goto done;
2325 else
2327 WCHAR buf[MAX_PATH];
2328 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2331 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2333 char *e = env;
2334 DWORD lenW;
2336 while (*e) e += strlen(e) + 1;
2337 e++; /* final null */
2338 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, NULL, 0 );
2339 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2340 MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, envW, lenW );
2341 flags |= CREATE_UNICODE_ENVIRONMENT;
2344 info->hThread = info->hProcess = 0;
2345 info->dwProcessId = info->dwThreadId = 0;
2347 if (binary_info.flags & BINARY_FLAG_DLL)
2349 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2350 SetLastError( ERROR_BAD_EXE_FORMAT );
2352 else switch (binary_info.type)
2354 case BINARY_PE:
2355 TRACE( "starting %s as Win%d binary (%p-%p, arch %04x%s)\n",
2356 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2357 binary_info.res_start, binary_info.res_end, binary_info.arch,
2358 (binary_info.flags & BINARY_FLAG_FAKEDLL) ? ", fakedll" : "" );
2359 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2360 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2361 break;
2362 case BINARY_OS216:
2363 case BINARY_WIN16:
2364 case BINARY_DOS:
2365 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2366 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2367 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2368 break;
2369 case BINARY_UNIX_LIB:
2370 TRACE( "starting %s as %d-bit Winelib app\n",
2371 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2372 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2373 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2374 break;
2375 case BINARY_UNKNOWN:
2376 /* check for .com or .bat extension */
2377 if ((p = strrchrW( name, '.' )))
2379 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2381 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2382 binary_info.type = BINARY_DOS;
2383 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2384 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2385 inherit, flags, startup_info, info, unixdir,
2386 &binary_info, FALSE );
2387 break;
2389 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2391 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2392 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2393 inherit, flags, startup_info, info );
2394 break;
2397 /* fall through */
2398 case BINARY_UNIX_EXE:
2400 /* unknown file, try as unix executable */
2401 char *unix_name;
2403 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2405 if ((unix_name = wine_get_unix_file_name( name )))
2407 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2408 HeapFree( GetProcessHeap(), 0, unix_name );
2411 break;
2413 if (hFile) CloseHandle( hFile );
2415 done:
2416 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2417 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2418 HeapFree( GetProcessHeap(), 0, unixdir );
2419 if (retv)
2420 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2421 return retv;
2425 /**********************************************************************
2426 * CreateProcessA (KERNEL32.@)
2428 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2429 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2430 DWORD flags, LPVOID env, LPCSTR cur_dir,
2431 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2433 BOOL ret = FALSE;
2434 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2435 UNICODE_STRING desktopW, titleW;
2436 STARTUPINFOW infoW;
2438 desktopW.Buffer = NULL;
2439 titleW.Buffer = NULL;
2440 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2441 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2442 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2444 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2445 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2447 memcpy( &infoW, startup_info, sizeof(infoW) );
2448 infoW.lpDesktop = desktopW.Buffer;
2449 infoW.lpTitle = titleW.Buffer;
2451 if (startup_info->lpReserved)
2452 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2453 debugstr_a(startup_info->lpReserved));
2455 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2456 inherit, flags, env, cur_dirW, &infoW, info );
2457 done:
2458 HeapFree( GetProcessHeap(), 0, app_nameW );
2459 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2460 HeapFree( GetProcessHeap(), 0, cur_dirW );
2461 RtlFreeUnicodeString( &desktopW );
2462 RtlFreeUnicodeString( &titleW );
2463 return ret;
2467 /**********************************************************************
2468 * CreateProcessW (KERNEL32.@)
2470 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2471 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2472 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2473 LPPROCESS_INFORMATION info )
2475 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2476 inherit, flags, env, cur_dir, startup_info, info);
2480 /**********************************************************************
2481 * exec_process
2483 static void exec_process( LPCWSTR name )
2485 HANDLE hFile;
2486 WCHAR *p;
2487 STARTUPINFOW startup_info;
2488 PROCESS_INFORMATION info;
2489 struct binary_info binary_info;
2491 hFile = open_exe_file( name, &binary_info );
2492 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2494 memset( &startup_info, 0, sizeof(startup_info) );
2495 startup_info.cb = sizeof(startup_info);
2497 /* Determine executable type */
2499 if (binary_info.flags & BINARY_FLAG_DLL)
2501 CloseHandle( hFile );
2502 return;
2505 switch (binary_info.type)
2507 case BINARY_PE:
2508 TRACE( "starting %s as Win%d binary (%p-%p, arch %04x)\n",
2509 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2510 binary_info.res_start, binary_info.res_end, binary_info.arch );
2511 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2512 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2513 break;
2514 case BINARY_UNIX_LIB:
2515 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2516 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2517 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2518 break;
2519 case BINARY_UNKNOWN:
2520 /* check for .com or .pif extension */
2521 if (!(p = strrchrW( name, '.' ))) break;
2522 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2523 binary_info.type = BINARY_DOS;
2524 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2525 /* fall through */
2526 case BINARY_OS216:
2527 case BINARY_WIN16:
2528 case BINARY_DOS:
2529 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2530 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2531 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2532 break;
2533 default:
2534 break;
2536 CloseHandle( hFile );
2540 /***********************************************************************
2541 * wait_input_idle
2543 * Wrapper to call WaitForInputIdle USER function
2545 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2547 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2549 HMODULE mod = GetModuleHandleA( "user32.dll" );
2550 if (mod)
2552 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2553 if (ptr) return ptr( process, timeout );
2555 return 0;
2559 /***********************************************************************
2560 * WinExec (KERNEL32.@)
2562 UINT WINAPI DECLSPEC_HOTPATCH WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2564 PROCESS_INFORMATION info;
2565 STARTUPINFOA startup;
2566 char *cmdline;
2567 UINT ret;
2569 memset( &startup, 0, sizeof(startup) );
2570 startup.cb = sizeof(startup);
2571 startup.dwFlags = STARTF_USESHOWWINDOW;
2572 startup.wShowWindow = nCmdShow;
2574 /* cmdline needs to be writable for CreateProcess */
2575 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2576 strcpy( cmdline, lpCmdLine );
2578 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2579 0, NULL, NULL, &startup, &info ))
2581 /* Give 30 seconds to the app to come up */
2582 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2583 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2584 ret = 33;
2585 /* Close off the handles */
2586 CloseHandle( info.hThread );
2587 CloseHandle( info.hProcess );
2589 else if ((ret = GetLastError()) >= 32)
2591 FIXME("Strange error set by CreateProcess: %d\n", ret );
2592 ret = 11;
2594 HeapFree( GetProcessHeap(), 0, cmdline );
2595 return ret;
2599 /**********************************************************************
2600 * LoadModule (KERNEL32.@)
2602 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2604 LOADPARMS32 *params = paramBlock;
2605 PROCESS_INFORMATION info;
2606 STARTUPINFOA startup;
2607 DWORD ret;
2608 LPSTR cmdline, p;
2609 char filename[MAX_PATH];
2610 BYTE len;
2612 if (!name) return ERROR_FILE_NOT_FOUND;
2614 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2615 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2616 return GetLastError();
2618 len = (BYTE)params->lpCmdLine[0];
2619 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2620 return ERROR_NOT_ENOUGH_MEMORY;
2622 strcpy( cmdline, filename );
2623 p = cmdline + strlen(cmdline);
2624 *p++ = ' ';
2625 memcpy( p, params->lpCmdLine + 1, len );
2626 p[len] = 0;
2628 memset( &startup, 0, sizeof(startup) );
2629 startup.cb = sizeof(startup);
2630 if (params->lpCmdShow)
2632 startup.dwFlags = STARTF_USESHOWWINDOW;
2633 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2636 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2637 params->lpEnvAddress, NULL, &startup, &info ))
2639 /* Give 30 seconds to the app to come up */
2640 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2641 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2642 ret = 33;
2643 /* Close off the handles */
2644 CloseHandle( info.hThread );
2645 CloseHandle( info.hProcess );
2647 else if ((ret = GetLastError()) >= 32)
2649 FIXME("Strange error set by CreateProcess: %u\n", ret );
2650 ret = 11;
2653 HeapFree( GetProcessHeap(), 0, cmdline );
2654 return ret;
2658 /******************************************************************************
2659 * TerminateProcess (KERNEL32.@)
2661 * Terminates a process.
2663 * PARAMS
2664 * handle [I] Process to terminate.
2665 * exit_code [I] Exit code.
2667 * RETURNS
2668 * Success: TRUE.
2669 * Failure: FALSE, check GetLastError().
2671 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2673 NTSTATUS status;
2675 if (!handle)
2677 SetLastError( ERROR_INVALID_HANDLE );
2678 return FALSE;
2681 status = NtTerminateProcess( handle, exit_code );
2682 if (status) SetLastError( RtlNtStatusToDosError(status) );
2683 return !status;
2686 /***********************************************************************
2687 * ExitProcess (KERNEL32.@)
2689 * Exits the current process.
2691 * PARAMS
2692 * status [I] Status code to exit with.
2694 * RETURNS
2695 * Nothing.
2697 #ifdef __i386__
2698 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2699 "pushl %ebp\n\t"
2700 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2701 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2702 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2703 "pushl 8(%ebp)\n\t"
2704 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
2705 "leave\n\t"
2706 "ret $4" )
2707 #else
2709 void WINAPI ExitProcess( DWORD status )
2711 RtlExitUserProcess( status );
2714 #endif
2716 /***********************************************************************
2717 * GetExitCodeProcess [KERNEL32.@]
2719 * Gets termination status of specified process.
2721 * PARAMS
2722 * hProcess [in] Handle to the process.
2723 * lpExitCode [out] Address to receive termination status.
2725 * RETURNS
2726 * Success: TRUE
2727 * Failure: FALSE
2729 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2731 NTSTATUS status;
2732 PROCESS_BASIC_INFORMATION pbi;
2734 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2735 sizeof(pbi), NULL);
2736 if (status == STATUS_SUCCESS)
2738 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2739 return TRUE;
2741 SetLastError( RtlNtStatusToDosError(status) );
2742 return FALSE;
2746 /***********************************************************************
2747 * SetErrorMode (KERNEL32.@)
2749 UINT WINAPI SetErrorMode( UINT mode )
2751 UINT old;
2753 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2754 &old, sizeof(old), NULL );
2755 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2756 &mode, sizeof(mode) );
2757 return old;
2760 /***********************************************************************
2761 * GetErrorMode (KERNEL32.@)
2763 UINT WINAPI GetErrorMode( void )
2765 UINT mode;
2767 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2768 &mode, sizeof(mode), NULL );
2769 return mode;
2772 /**********************************************************************
2773 * TlsAlloc [KERNEL32.@]
2775 * Allocates a thread local storage index.
2777 * RETURNS
2778 * Success: TLS index.
2779 * Failure: 0xFFFFFFFF
2781 DWORD WINAPI TlsAlloc( void )
2783 DWORD index;
2784 PEB * const peb = NtCurrentTeb()->Peb;
2786 RtlAcquirePebLock();
2787 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 1 );
2788 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2789 else
2791 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2792 if (index != ~0U)
2794 if (!NtCurrentTeb()->TlsExpansionSlots &&
2795 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2796 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2798 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2799 index = ~0U;
2800 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2802 else
2804 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2805 index += TLS_MINIMUM_AVAILABLE;
2808 else SetLastError( ERROR_NO_MORE_ITEMS );
2810 RtlReleasePebLock();
2811 return index;
2815 /**********************************************************************
2816 * TlsFree [KERNEL32.@]
2818 * Releases a thread local storage index, making it available for reuse.
2820 * PARAMS
2821 * index [in] TLS index to free.
2823 * RETURNS
2824 * Success: TRUE
2825 * Failure: FALSE
2827 BOOL WINAPI TlsFree( DWORD index )
2829 BOOL ret;
2831 RtlAcquirePebLock();
2832 if (index >= TLS_MINIMUM_AVAILABLE)
2834 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2835 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2837 else
2839 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2840 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2842 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2843 else SetLastError( ERROR_INVALID_PARAMETER );
2844 RtlReleasePebLock();
2845 return ret;
2849 /**********************************************************************
2850 * TlsGetValue [KERNEL32.@]
2852 * Gets value in a thread's TLS slot.
2854 * PARAMS
2855 * index [in] TLS index to retrieve value for.
2857 * RETURNS
2858 * Success: Value stored in calling thread's TLS slot for index.
2859 * Failure: 0 and GetLastError() returns NO_ERROR.
2861 LPVOID WINAPI TlsGetValue( DWORD index )
2863 LPVOID ret;
2865 if (index < TLS_MINIMUM_AVAILABLE)
2867 ret = NtCurrentTeb()->TlsSlots[index];
2869 else
2871 index -= TLS_MINIMUM_AVAILABLE;
2872 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2874 SetLastError( ERROR_INVALID_PARAMETER );
2875 return NULL;
2877 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2878 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2880 SetLastError( ERROR_SUCCESS );
2881 return ret;
2885 /**********************************************************************
2886 * TlsSetValue [KERNEL32.@]
2888 * Stores a value in the thread's TLS slot.
2890 * PARAMS
2891 * index [in] TLS index to set value for.
2892 * value [in] Value to be stored.
2894 * RETURNS
2895 * Success: TRUE
2896 * Failure: FALSE
2898 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2900 if (index < TLS_MINIMUM_AVAILABLE)
2902 NtCurrentTeb()->TlsSlots[index] = value;
2904 else
2906 index -= TLS_MINIMUM_AVAILABLE;
2907 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2909 SetLastError( ERROR_INVALID_PARAMETER );
2910 return FALSE;
2912 if (!NtCurrentTeb()->TlsExpansionSlots &&
2913 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2914 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2916 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2917 return FALSE;
2919 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2921 return TRUE;
2925 /***********************************************************************
2926 * GetProcessFlags (KERNEL32.@)
2928 DWORD WINAPI GetProcessFlags( DWORD processid )
2930 IMAGE_NT_HEADERS *nt;
2931 DWORD flags = 0;
2933 if (processid && processid != GetCurrentProcessId()) return 0;
2935 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2937 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2938 flags |= PDB32_CONSOLE_PROC;
2940 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2941 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2942 return flags;
2946 /*********************************************************************
2947 * OpenProcess (KERNEL32.@)
2949 * Opens a handle to a process.
2951 * PARAMS
2952 * access [I] Desired access rights assigned to the returned handle.
2953 * inherit [I] Determines whether or not child processes will inherit the handle.
2954 * id [I] Process identifier of the process to get a handle to.
2956 * RETURNS
2957 * Success: Valid handle to the specified process.
2958 * Failure: NULL, check GetLastError().
2960 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2962 NTSTATUS status;
2963 HANDLE handle;
2964 OBJECT_ATTRIBUTES attr;
2965 CLIENT_ID cid;
2967 cid.UniqueProcess = ULongToHandle(id);
2968 cid.UniqueThread = 0; /* FIXME ? */
2970 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2971 attr.RootDirectory = NULL;
2972 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2973 attr.SecurityDescriptor = NULL;
2974 attr.SecurityQualityOfService = NULL;
2975 attr.ObjectName = NULL;
2977 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2979 status = NtOpenProcess(&handle, access, &attr, &cid);
2980 if (status != STATUS_SUCCESS)
2982 SetLastError( RtlNtStatusToDosError(status) );
2983 return NULL;
2985 return handle;
2989 /*********************************************************************
2990 * GetProcessId (KERNEL32.@)
2992 * Gets the a unique identifier of a process.
2994 * PARAMS
2995 * hProcess [I] Handle to the process.
2997 * RETURNS
2998 * Success: TRUE.
2999 * Failure: FALSE, check GetLastError().
3001 * NOTES
3003 * The identifier is unique only on the machine and only until the process
3004 * exits (including system shutdown).
3006 DWORD WINAPI GetProcessId( HANDLE hProcess )
3008 NTSTATUS status;
3009 PROCESS_BASIC_INFORMATION pbi;
3011 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3012 sizeof(pbi), NULL);
3013 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
3014 SetLastError( RtlNtStatusToDosError(status) );
3015 return 0;
3019 /*********************************************************************
3020 * CloseHandle (KERNEL32.@)
3022 * Closes a handle.
3024 * PARAMS
3025 * handle [I] Handle to close.
3027 * RETURNS
3028 * Success: TRUE.
3029 * Failure: FALSE, check GetLastError().
3031 BOOL WINAPI CloseHandle( HANDLE handle )
3033 NTSTATUS status;
3035 /* stdio handles need special treatment */
3036 if (handle == (HANDLE)STD_INPUT_HANDLE)
3037 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
3038 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
3039 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
3040 else if (handle == (HANDLE)STD_ERROR_HANDLE)
3041 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
3043 if (is_console_handle(handle))
3044 return CloseConsoleHandle(handle);
3046 status = NtClose( handle );
3047 if (status) SetLastError( RtlNtStatusToDosError(status) );
3048 return !status;
3052 /*********************************************************************
3053 * GetHandleInformation (KERNEL32.@)
3055 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
3057 OBJECT_DATA_INFORMATION info;
3058 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
3060 if (status) SetLastError( RtlNtStatusToDosError(status) );
3061 else if (flags)
3063 *flags = 0;
3064 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3065 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3067 return !status;
3071 /*********************************************************************
3072 * SetHandleInformation (KERNEL32.@)
3074 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3076 OBJECT_DATA_INFORMATION info;
3077 NTSTATUS status;
3079 /* if not setting both fields, retrieve current value first */
3080 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3081 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3083 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3085 SetLastError( RtlNtStatusToDosError(status) );
3086 return FALSE;
3089 if (mask & HANDLE_FLAG_INHERIT)
3090 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3091 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3092 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3094 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3095 if (status) SetLastError( RtlNtStatusToDosError(status) );
3096 return !status;
3100 /*********************************************************************
3101 * DuplicateHandle (KERNEL32.@)
3103 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3104 HANDLE dest_process, HANDLE *dest,
3105 DWORD access, BOOL inherit, DWORD options )
3107 NTSTATUS status;
3109 if (is_console_handle(source))
3111 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3112 if (source_process != dest_process ||
3113 source_process != GetCurrentProcess())
3115 SetLastError(ERROR_INVALID_PARAMETER);
3116 return FALSE;
3118 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3119 return (*dest != INVALID_HANDLE_VALUE);
3121 status = NtDuplicateObject( source_process, source, dest_process, dest,
3122 access, inherit ? OBJ_INHERIT : 0, options );
3123 if (status) SetLastError( RtlNtStatusToDosError(status) );
3124 return !status;
3128 /***********************************************************************
3129 * ConvertToGlobalHandle (KERNEL32.@)
3131 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3133 HANDLE ret = INVALID_HANDLE_VALUE;
3134 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3135 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3136 return ret;
3140 /***********************************************************************
3141 * SetHandleContext (KERNEL32.@)
3143 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3145 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3146 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3147 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3148 return FALSE;
3152 /***********************************************************************
3153 * GetHandleContext (KERNEL32.@)
3155 DWORD WINAPI GetHandleContext(HANDLE hnd)
3157 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3158 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3159 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3160 return 0;
3164 /***********************************************************************
3165 * CreateSocketHandle (KERNEL32.@)
3167 HANDLE WINAPI CreateSocketHandle(void)
3169 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3170 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3171 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3172 return INVALID_HANDLE_VALUE;
3176 /***********************************************************************
3177 * SetPriorityClass (KERNEL32.@)
3179 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3181 NTSTATUS status;
3182 PROCESS_PRIORITY_CLASS ppc;
3184 ppc.Foreground = FALSE;
3185 switch (priorityclass)
3187 case IDLE_PRIORITY_CLASS:
3188 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3189 case BELOW_NORMAL_PRIORITY_CLASS:
3190 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3191 case NORMAL_PRIORITY_CLASS:
3192 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3193 case ABOVE_NORMAL_PRIORITY_CLASS:
3194 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3195 case HIGH_PRIORITY_CLASS:
3196 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3197 case REALTIME_PRIORITY_CLASS:
3198 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3199 default:
3200 SetLastError(ERROR_INVALID_PARAMETER);
3201 return FALSE;
3204 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3205 &ppc, sizeof(ppc));
3207 if (status != STATUS_SUCCESS)
3209 SetLastError( RtlNtStatusToDosError(status) );
3210 return FALSE;
3212 return TRUE;
3216 /***********************************************************************
3217 * GetPriorityClass (KERNEL32.@)
3219 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3221 NTSTATUS status;
3222 PROCESS_BASIC_INFORMATION pbi;
3224 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3225 sizeof(pbi), NULL);
3226 if (status != STATUS_SUCCESS)
3228 SetLastError( RtlNtStatusToDosError(status) );
3229 return 0;
3231 switch (pbi.BasePriority)
3233 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3234 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3235 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3236 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3237 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3238 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3240 SetLastError( ERROR_INVALID_PARAMETER );
3241 return 0;
3245 /***********************************************************************
3246 * SetProcessAffinityMask (KERNEL32.@)
3248 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3250 NTSTATUS status;
3252 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3253 &affmask, sizeof(DWORD_PTR));
3254 if (status)
3256 SetLastError( RtlNtStatusToDosError(status) );
3257 return FALSE;
3259 return TRUE;
3263 /**********************************************************************
3264 * GetProcessAffinityMask (KERNEL32.@)
3266 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3268 NTSTATUS status = STATUS_SUCCESS;
3270 if (process_mask)
3272 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3273 process_mask, sizeof(*process_mask), NULL )))
3274 SetLastError( RtlNtStatusToDosError(status) );
3276 if (system_mask && status == STATUS_SUCCESS)
3278 SYSTEM_BASIC_INFORMATION info;
3280 if ((status = NtQuerySystemInformation( SystemBasicInformation, &info, sizeof(info), NULL )))
3281 SetLastError( RtlNtStatusToDosError(status) );
3282 else
3283 *system_mask = info.ActiveProcessorsAffinityMask;
3285 return !status;
3289 /***********************************************************************
3290 * GetProcessVersion (KERNEL32.@)
3292 DWORD WINAPI GetProcessVersion( DWORD pid )
3294 HANDLE process;
3295 NTSTATUS status;
3296 PROCESS_BASIC_INFORMATION pbi;
3297 SIZE_T count;
3298 PEB peb;
3299 IMAGE_DOS_HEADER dos;
3300 IMAGE_NT_HEADERS nt;
3301 DWORD ver = 0;
3303 if (!pid || pid == GetCurrentProcessId())
3305 IMAGE_NT_HEADERS *pnt;
3307 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3308 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3309 pnt->OptionalHeader.MinorSubsystemVersion);
3310 return 0;
3313 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3314 if (!process) return 0;
3316 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3317 if (status) goto err;
3319 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3320 if (status || count != sizeof(peb)) goto err;
3322 memset(&dos, 0, sizeof(dos));
3323 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3324 if (status || count != sizeof(dos)) goto err;
3325 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3327 memset(&nt, 0, sizeof(nt));
3328 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3329 if (status || count != sizeof(nt)) goto err;
3330 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3332 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3334 err:
3335 CloseHandle(process);
3337 if (status != STATUS_SUCCESS)
3338 SetLastError(RtlNtStatusToDosError(status));
3340 return ver;
3344 /***********************************************************************
3345 * SetProcessWorkingSetSize [KERNEL32.@]
3346 * Sets the min/max working set sizes for a specified process.
3348 * PARAMS
3349 * hProcess [I] Handle to the process of interest
3350 * minset [I] Specifies minimum working set size
3351 * maxset [I] Specifies maximum working set size
3353 * RETURNS
3354 * Success: TRUE
3355 * Failure: FALSE
3357 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3358 SIZE_T maxset)
3360 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3361 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3362 /* Trim the working set to zero */
3363 /* Swap the process out of physical RAM */
3365 return TRUE;
3368 /***********************************************************************
3369 * K32EmptyWorkingSet (KERNEL32.@)
3371 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3373 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3376 /***********************************************************************
3377 * GetProcessWorkingSetSize (KERNEL32.@)
3379 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3380 PSIZE_T maxset)
3382 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3383 /* 32 MB working set size */
3384 if (minset) *minset = 32*1024*1024;
3385 if (maxset) *maxset = 32*1024*1024;
3386 return TRUE;
3390 /***********************************************************************
3391 * SetProcessShutdownParameters (KERNEL32.@)
3393 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3395 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3396 shutdown_flags = flags;
3397 shutdown_priority = level;
3398 return TRUE;
3402 /***********************************************************************
3403 * GetProcessShutdownParameters (KERNEL32.@)
3406 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3408 *lpdwLevel = shutdown_priority;
3409 *lpdwFlags = shutdown_flags;
3410 return TRUE;
3414 /***********************************************************************
3415 * GetProcessPriorityBoost (KERNEL32.@)
3417 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3419 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3421 /* Report that no boost is present.. */
3422 *pDisablePriorityBoost = FALSE;
3424 return TRUE;
3427 /***********************************************************************
3428 * SetProcessPriorityBoost (KERNEL32.@)
3430 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3432 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3433 /* Say we can do it. I doubt the program will notice that we don't. */
3434 return TRUE;
3438 /***********************************************************************
3439 * ReadProcessMemory (KERNEL32.@)
3441 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3442 SIZE_T *bytes_read )
3444 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3445 if (status) SetLastError( RtlNtStatusToDosError(status) );
3446 return !status;
3450 /***********************************************************************
3451 * WriteProcessMemory (KERNEL32.@)
3453 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3454 SIZE_T *bytes_written )
3456 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3457 if (status) SetLastError( RtlNtStatusToDosError(status) );
3458 return !status;
3462 /****************************************************************************
3463 * FlushInstructionCache (KERNEL32.@)
3465 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3467 NTSTATUS status;
3468 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3469 if (status) SetLastError( RtlNtStatusToDosError(status) );
3470 return !status;
3474 /******************************************************************
3475 * GetProcessIoCounters (KERNEL32.@)
3477 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3479 NTSTATUS status;
3481 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3482 ioc, sizeof(*ioc), NULL);
3483 if (status) SetLastError( RtlNtStatusToDosError(status) );
3484 return !status;
3487 /******************************************************************
3488 * GetProcessHandleCount (KERNEL32.@)
3490 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3492 NTSTATUS status;
3494 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3495 cnt, sizeof(*cnt), NULL);
3496 if (status) SetLastError( RtlNtStatusToDosError(status) );
3497 return !status;
3500 /******************************************************************
3501 * QueryFullProcessImageNameA (KERNEL32.@)
3503 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3505 BOOL retval;
3506 DWORD pdwSizeW = *pdwSize;
3507 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3509 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3511 if(retval)
3512 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3513 lpExeName, *pdwSize, NULL, NULL));
3514 if(retval)
3515 *pdwSize = strlen(lpExeName);
3517 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3518 return retval;
3521 /******************************************************************
3522 * QueryFullProcessImageNameW (KERNEL32.@)
3524 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3526 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3527 UNICODE_STRING *dynamic_buffer = NULL;
3528 UNICODE_STRING *result = NULL;
3529 NTSTATUS status;
3530 DWORD needed;
3532 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3533 * is a DOS path and we depend on this. */
3534 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3535 sizeof(buffer) - sizeof(WCHAR), &needed);
3536 if (status == STATUS_INFO_LENGTH_MISMATCH)
3538 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3539 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3540 result = dynamic_buffer;
3542 else
3543 result = (PUNICODE_STRING)buffer;
3545 if (status) goto cleanup;
3547 if (dwFlags & PROCESS_NAME_NATIVE)
3549 WCHAR drive[3];
3550 WCHAR device[1024];
3551 DWORD ntlen, devlen;
3553 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3555 /* We cannot convert it to an NT device path so fail */
3556 status = STATUS_NO_SUCH_DEVICE;
3557 goto cleanup;
3560 /* Find this drive's NT device path */
3561 drive[0] = result->Buffer[0];
3562 drive[1] = ':';
3563 drive[2] = 0;
3564 if (!QueryDosDeviceW(drive, device, sizeof(device)/sizeof(*device)))
3566 status = STATUS_NO_SUCH_DEVICE;
3567 goto cleanup;
3570 devlen = lstrlenW(device);
3571 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3572 if (ntlen + 1 > *pdwSize)
3574 status = STATUS_BUFFER_TOO_SMALL;
3575 goto cleanup;
3577 *pdwSize = ntlen;
3579 memcpy(lpExeName, device, devlen * sizeof(*device));
3580 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3581 lpExeName[*pdwSize] = 0;
3582 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3584 else
3586 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3588 status = STATUS_BUFFER_TOO_SMALL;
3589 goto cleanup;
3592 *pdwSize = result->Length/sizeof(WCHAR);
3593 memcpy( lpExeName, result->Buffer, result->Length );
3594 lpExeName[*pdwSize] = 0;
3597 cleanup:
3598 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3599 if (status) SetLastError( RtlNtStatusToDosError(status) );
3600 return !status;
3603 /***********************************************************************
3604 * K32GetProcessImageFileNameA (KERNEL32.@)
3606 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3608 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3611 /***********************************************************************
3612 * K32GetProcessImageFileNameW (KERNEL32.@)
3614 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3616 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3619 /***********************************************************************
3620 * K32EnumProcesses (KERNEL32.@)
3622 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3624 SYSTEM_PROCESS_INFORMATION *spi;
3625 ULONG size = 0x4000;
3626 void *buf = NULL;
3627 NTSTATUS status;
3629 do {
3630 size *= 2;
3631 HeapFree(GetProcessHeap(), 0, buf);
3632 buf = HeapAlloc(GetProcessHeap(), 0, size);
3633 if (!buf)
3634 return FALSE;
3636 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3637 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3639 if (status != STATUS_SUCCESS)
3641 HeapFree(GetProcessHeap(), 0, buf);
3642 SetLastError(RtlNtStatusToDosError(status));
3643 return FALSE;
3646 spi = buf;
3648 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3650 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3651 *lpcbUsed += sizeof(DWORD);
3653 if (spi->NextEntryOffset == 0)
3654 break;
3656 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3659 HeapFree(GetProcessHeap(), 0, buf);
3660 return TRUE;
3663 /***********************************************************************
3664 * K32QueryWorkingSet (KERNEL32.@)
3666 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3668 NTSTATUS status;
3670 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3672 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3674 if (status)
3676 SetLastError( RtlNtStatusToDosError( status ) );
3677 return FALSE;
3679 return TRUE;
3682 /***********************************************************************
3683 * K32QueryWorkingSetEx (KERNEL32.@)
3685 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3687 NTSTATUS status;
3689 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3691 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3693 if (status)
3695 SetLastError( RtlNtStatusToDosError( status ) );
3696 return FALSE;
3698 return TRUE;
3701 /***********************************************************************
3702 * K32GetProcessMemoryInfo (KERNEL32.@)
3704 * Retrieve memory usage information for a given process
3707 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3708 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3710 NTSTATUS status;
3711 VM_COUNTERS vmc;
3713 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3715 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3716 return FALSE;
3719 status = NtQueryInformationProcess(process, ProcessVmCounters,
3720 &vmc, sizeof(vmc), NULL);
3722 if (status)
3724 SetLastError(RtlNtStatusToDosError(status));
3725 return FALSE;
3728 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3729 pmc->PageFaultCount = vmc.PageFaultCount;
3730 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3731 pmc->WorkingSetSize = vmc.WorkingSetSize;
3732 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3733 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3734 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3735 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3736 pmc->PagefileUsage = vmc.PagefileUsage;
3737 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3739 return TRUE;
3742 /***********************************************************************
3743 * ProcessIdToSessionId (KERNEL32.@)
3744 * This function is available on Terminal Server 4SP4 and Windows 2000
3746 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3748 if (procid != GetCurrentProcessId())
3749 FIXME("Unsupported for other processes.\n");
3751 *sessionid_ptr = NtCurrentTeb()->Peb->SessionId;
3752 return TRUE;
3756 /***********************************************************************
3757 * RegisterServiceProcess (KERNEL32.@)
3759 * A service process calls this function to ensure that it continues to run
3760 * even after a user logged off.
3762 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3764 /* I don't think that Wine needs to do anything in this function */
3765 return 1; /* success */
3769 /**********************************************************************
3770 * IsWow64Process (KERNEL32.@)
3772 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3774 ULONG_PTR pbi;
3775 NTSTATUS status;
3777 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3779 if (status != STATUS_SUCCESS)
3781 SetLastError( RtlNtStatusToDosError( status ) );
3782 return FALSE;
3784 *Wow64Process = (pbi != 0);
3785 return TRUE;
3789 /***********************************************************************
3790 * GetCurrentProcess (KERNEL32.@)
3792 * Get a handle to the current process.
3794 * PARAMS
3795 * None.
3797 * RETURNS
3798 * A handle representing the current process.
3800 #undef GetCurrentProcess
3801 HANDLE WINAPI GetCurrentProcess(void)
3803 return (HANDLE)~(ULONG_PTR)0;
3806 /***********************************************************************
3807 * GetLogicalProcessorInformation (KERNEL32.@)
3809 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3811 NTSTATUS status;
3813 TRACE("(%p,%p)\n", buffer, pBufLen);
3815 if(!pBufLen)
3817 SetLastError(ERROR_INVALID_PARAMETER);
3818 return FALSE;
3821 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
3823 if (status == STATUS_INFO_LENGTH_MISMATCH)
3825 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3826 return FALSE;
3828 if (status != STATUS_SUCCESS)
3830 SetLastError( RtlNtStatusToDosError( status ) );
3831 return FALSE;
3833 return TRUE;
3836 /***********************************************************************
3837 * GetLogicalProcessorInformationEx (KERNEL32.@)
3839 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer, PDWORD pBufLen)
3841 FIXME("(%u,%p,%p): stub\n", relationship, buffer, pBufLen);
3842 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3843 return FALSE;
3846 /***********************************************************************
3847 * CmdBatNotification (KERNEL32.@)
3849 * Notifies the system that a batch file has started or finished.
3851 * PARAMS
3852 * bBatchRunning [I] TRUE if a batch file has started or
3853 * FALSE if a batch file has finished executing.
3855 * RETURNS
3856 * Unknown.
3858 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3860 FIXME("%d\n", bBatchRunning);
3861 return FALSE;
3865 /***********************************************************************
3866 * RegisterApplicationRestart (KERNEL32.@)
3868 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3870 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3872 return S_OK;
3875 /**********************************************************************
3876 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3878 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3880 static int once;
3881 if (!once++) FIXME("stub\n");
3882 /* Return current session id. */
3883 return NtCurrentTeb()->Peb->SessionId;
3886 /**********************************************************************
3887 * GetSystemDEPPolicy (KERNEL32.@)
3889 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3891 FIXME("stub\n");
3892 return OptIn;
3895 /**********************************************************************
3896 * SetProcessDEPPolicy (KERNEL32.@)
3898 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3900 FIXME("(%d): stub\n", newDEP);
3901 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3902 return FALSE;
3905 /**********************************************************************
3906 * ApplicationRecoveryFinished (KERNEL32.@)
3908 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
3910 FIXME(": stub\n");
3911 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3914 /**********************************************************************
3915 * ApplicationRecoveryInProgress (KERNEL32.@)
3917 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
3919 FIXME(":%p stub\n", canceled);
3920 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3921 return E_FAIL;
3924 /**********************************************************************
3925 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3927 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
3929 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
3930 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3931 return E_FAIL;
3934 /**********************************************************************
3935 * GetNumaHighestNodeNumber (KERNEL32.@)
3937 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
3939 *highestnode = 0;
3940 FIXME("(%p): semi-stub\n", highestnode);
3941 return TRUE;
3944 /**********************************************************************
3945 * GetNumaNodeProcessorMask (KERNEL32.@)
3947 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
3949 FIXME("(%c %p): stub\n", node, mask);
3950 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3951 return FALSE;
3954 /**********************************************************************
3955 * GetNumaAvailableMemoryNode (KERNEL32.@)
3957 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
3959 FIXME("(%c %p): stub\n", node, available_bytes);
3960 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3961 return FALSE;
3964 /***********************************************************************
3965 * GetNumaProcessorNode (KERNEL32.@)
3967 BOOL WINAPI GetNumaProcessorNode(UCHAR processor, PUCHAR node)
3969 SYSTEM_INFO si;
3971 TRACE("(%d, %p)\n", processor, node);
3973 GetSystemInfo( &si );
3974 if (processor < si.dwNumberOfProcessors)
3976 *node = 0;
3977 return TRUE;
3980 *node = 0xFF;
3981 SetLastError(ERROR_INVALID_PARAMETER);
3982 return FALSE;
3985 /**********************************************************************
3986 * GetProcessDEPPolicy (KERNEL32.@)
3988 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
3990 NTSTATUS status;
3991 ULONG dep_flags;
3993 TRACE("(%p %p %p)\n", process, flags, permanent);
3995 status = NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
3996 &dep_flags, sizeof(dep_flags), NULL );
3997 if (!status)
4000 if (flags)
4002 *flags = 0;
4003 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE)
4004 *flags |= PROCESS_DEP_ENABLE;
4005 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION)
4006 *flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
4009 if (permanent)
4010 *permanent = (dep_flags & MEM_EXECUTE_OPTION_PERMANENT) != 0;
4013 if (status) SetLastError( RtlNtStatusToDosError(status) );
4014 return !status;
4017 /**********************************************************************
4018 * FlushProcessWriteBuffers (KERNEL32.@)
4020 VOID WINAPI FlushProcessWriteBuffers(void)
4022 static int once = 0;
4024 if (!once++)
4025 FIXME(": stub\n");
4028 /***********************************************************************
4029 * UnregisterApplicationRestart (KERNEL32.@)
4031 HRESULT WINAPI UnregisterApplicationRestart(void)
4033 FIXME(": stub\n");
4034 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4035 return S_OK;
4038 /***********************************************************************
4039 * GetSystemFirmwareTable (KERNEL32.@)
4041 UINT WINAPI GetSystemFirmwareTable(DWORD provider, DWORD id, PVOID buffer, DWORD size)
4043 FIXME("(%d %d %p %d):stub\n", provider, id, buffer, size);
4044 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4045 return 0;