kernel32: Quiet a noisy FIXME.
[wine/multimedia.git] / dlls / kernel32 / process.c
blobca21e0994d31a931743f95825b092b3b7e6a2363
1 /*
2 * Win32 processes
4 * Copyright 1996, 1998 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <signal.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <time.h>
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
33 #endif
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
36 #endif
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
39 #endif
40 #ifdef HAVE_SYS_PRCTL_H
41 # include <sys/prctl.h>
42 #endif
43 #include <sys/types.h>
44 #ifdef HAVE_SYS_WAIT_H
45 # include <sys/wait.h>
46 #endif
47 #ifdef HAVE_UNISTD_H
48 # include <unistd.h>
49 #endif
50 #ifdef __APPLE__
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <pthread.h>
53 #endif
55 #include "ntstatus.h"
56 #define WIN32_NO_STATUS
57 #include "winternl.h"
58 #include "kernel_private.h"
59 #include "psapi.h"
60 #include "wine/library.h"
61 #include "wine/server.h"
62 #include "wine/unicode.h"
63 #include "wine/debug.h"
65 WINE_DEFAULT_DEBUG_CHANNEL(process);
66 WINE_DECLARE_DEBUG_CHANNEL(file);
67 WINE_DECLARE_DEBUG_CHANNEL(relay);
69 #ifdef __APPLE__
70 extern char **__wine_get_main_environment(void);
71 #else
72 extern char **__wine_main_environ;
73 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
74 #endif
76 typedef struct
78 LPSTR lpEnvAddress;
79 LPSTR lpCmdLine;
80 LPSTR lpCmdShow;
81 DWORD dwReserved;
82 } LOADPARMS32;
84 static DWORD shutdown_flags = 0;
85 static DWORD shutdown_priority = 0x280;
86 static BOOL is_wow64;
87 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
89 HMODULE kernel32_handle = 0;
90 SYSTEM_BASIC_INFORMATION system_info = { 0 };
92 const WCHAR *DIR_Windows = NULL;
93 const WCHAR *DIR_System = NULL;
94 const WCHAR *DIR_SysWow64 = NULL;
96 /* Process flags */
97 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
98 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
99 #define PDB32_DOS_PROC 0x0010 /* Dos process */
100 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
101 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
102 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
104 static const WCHAR exeW[] = {'.','e','x','e',0};
105 static const WCHAR comW[] = {'.','c','o','m',0};
106 static const WCHAR batW[] = {'.','b','a','t',0};
107 static const WCHAR cmdW[] = {'.','c','m','d',0};
108 static const WCHAR pifW[] = {'.','p','i','f',0};
109 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
111 static void exec_process( LPCWSTR name );
113 extern void SHELL_LoadRegistry(void);
116 /***********************************************************************
117 * contains_path
119 static inline BOOL contains_path( LPCWSTR name )
121 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
125 /***********************************************************************
126 * is_special_env_var
128 * Check if an environment variable needs to be handled specially when
129 * passed through the Unix environment (i.e. prefixed with "WINE").
131 static inline BOOL is_special_env_var( const char *var )
133 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
134 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
135 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
136 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
137 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
141 /***********************************************************************
142 * is_path_prefix
144 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
146 unsigned int len = strlenW( prefix );
148 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
149 while (filename[len] == '\\') len++;
150 return len;
154 /***************************************************************************
155 * get_builtin_path
157 * Get the path of a builtin module when the native file does not exist.
159 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
160 UINT size, struct binary_info *binary_info )
162 WCHAR *file_part;
163 UINT len;
164 void *redir_disabled = 0;
165 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
167 /* builtin names cannot be empty or contain spaces */
168 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
170 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
171 Wow64RevertWow64FsRedirection( redir_disabled );
173 if (contains_path( libname ))
175 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
176 filename, &file_part ) > size * sizeof(WCHAR))
177 return FALSE; /* too long */
179 if ((len = is_path_prefix( DIR_System, filename )))
181 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
183 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
185 flags = 0;
187 else return FALSE;
189 if (filename + len != file_part) return FALSE;
191 else
193 len = strlenW( DIR_System );
194 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
195 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
196 file_part = filename + len;
197 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
198 strcpyW( file_part, libname );
199 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
201 if (ext && !strchrW( file_part, '.' ))
203 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
204 return FALSE; /* too long */
205 strcatW( file_part, ext );
207 binary_info->type = BINARY_UNIX_LIB;
208 binary_info->flags = flags;
209 binary_info->res_start = NULL;
210 binary_info->res_end = NULL;
211 /* assume current arch */
212 #if defined(__i386__) || defined(__x86_64__)
213 binary_info->arch = (flags & BINARY_FLAG_64BIT) ? IMAGE_FILE_MACHINE_AMD64 : IMAGE_FILE_MACHINE_I386;
214 #elif defined(__powerpc__)
215 binary_info->arch = IMAGE_FILE_MACHINE_POWERPC;
216 #elif defined(__arm__) && !defined(__ARMEB__)
217 binary_info->arch = IMAGE_FILE_MACHINE_ARMNT;
218 #elif defined(__aarch64__)
219 binary_info->arch = IMAGE_FILE_MACHINE_ARM64;
220 #else
221 binary_info->arch = IMAGE_FILE_MACHINE_UNKNOWN;
222 #endif
223 return TRUE;
227 /***********************************************************************
228 * open_exe_file
230 * Open a specific exe file, taking load order into account.
231 * Returns the file handle or 0 for a builtin exe.
233 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
235 HANDLE handle;
237 TRACE("looking for %s\n", debugstr_w(name) );
239 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
240 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
242 WCHAR buffer[MAX_PATH];
243 /* file doesn't exist, check for builtin */
244 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
245 handle = 0;
247 else MODULE_get_binary_info( handle, binary_info );
249 return handle;
253 /***********************************************************************
254 * find_exe_file
256 * Open an exe file, and return the full name and file handle.
257 * Returns FALSE if file could not be found.
259 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
260 HANDLE *handle, struct binary_info *binary_info )
262 TRACE("looking for %s\n", debugstr_w(name) );
264 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
265 /* no builtin found, try native without extension in case it is a Unix app */
266 !SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
268 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
269 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
270 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
272 MODULE_get_binary_info( *handle, binary_info );
273 return TRUE;
275 return FALSE;
279 /***********************************************************************
280 * build_initial_environment
282 * Build the Win32 environment from the Unix environment
284 static BOOL build_initial_environment(void)
286 SIZE_T size = 1;
287 char **e;
288 WCHAR *p, *endptr;
289 void *ptr;
290 char **env = __wine_get_main_environment();
292 /* Compute the total size of the Unix environment */
293 for (e = env; *e; e++)
295 if (is_special_env_var( *e )) continue;
296 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
298 size *= sizeof(WCHAR);
300 /* Now allocate the environment */
301 ptr = NULL;
302 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
303 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
304 return FALSE;
306 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
307 endptr = p + size / sizeof(WCHAR);
309 /* And fill it with the Unix environment */
310 for (e = env; *e; e++)
312 char *str = *e;
314 /* skip Unix special variables and use the Wine variants instead */
315 if (!strncmp( str, "WINE", 4 ))
317 if (is_special_env_var( str + 4 )) str += 4;
318 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
320 else if (is_special_env_var( str )) continue; /* skip it */
322 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
323 p += strlenW(p) + 1;
325 *p = 0;
326 return TRUE;
330 /***********************************************************************
331 * set_registry_variables
333 * Set environment variables by enumerating the values of a key;
334 * helper for set_registry_environment().
335 * Note that Windows happily truncates the value if it's too big.
337 static void set_registry_variables( HANDLE hkey, ULONG type )
339 static const WCHAR pathW[] = {'P','A','T','H'};
340 static const WCHAR sep[] = {';',0};
341 UNICODE_STRING env_name, env_value;
342 NTSTATUS status;
343 DWORD size;
344 int index;
345 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
346 WCHAR tmpbuf[1024];
347 UNICODE_STRING tmp;
348 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
350 tmp.Buffer = tmpbuf;
351 tmp.MaximumLength = sizeof(tmpbuf);
353 for (index = 0; ; index++)
355 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
356 buffer, sizeof(buffer), &size );
357 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
358 break;
359 if (info->Type != type)
360 continue;
361 env_name.Buffer = info->Name;
362 env_name.Length = env_name.MaximumLength = info->NameLength;
363 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
364 env_value.Length = info->DataLength;
365 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
366 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
367 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
368 if (!env_value.Length) continue;
369 if (info->Type == REG_EXPAND_SZ)
371 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
372 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
373 RtlCopyUnicodeString( &env_value, &tmp );
375 /* PATH is magic */
376 if (env_name.Length == sizeof(pathW) &&
377 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
378 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
380 RtlAppendUnicodeToString( &tmp, sep );
381 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
382 RtlCopyUnicodeString( &env_value, &tmp );
384 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
389 /***********************************************************************
390 * set_registry_environment
392 * Set the environment variables specified in the registry.
394 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
395 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
396 * on the order in which the variables are processed. But on Windows it
397 * does not really matter since they only use %SystemDrive% and
398 * %SystemRoot% which are predefined. But Wine defines these in the
399 * registry, so we need two passes.
401 static BOOL set_registry_environment( BOOL volatile_only )
403 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
404 'S','y','s','t','e','m','\\',
405 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
406 'C','o','n','t','r','o','l','\\',
407 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
408 'E','n','v','i','r','o','n','m','e','n','t',0};
409 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
410 static const WCHAR volatile_envW[] = {'V','o','l','a','t','i','l','e',' ','E','n','v','i','r','o','n','m','e','n','t',0};
412 OBJECT_ATTRIBUTES attr;
413 UNICODE_STRING nameW;
414 HANDLE hkey;
415 BOOL ret = FALSE;
417 attr.Length = sizeof(attr);
418 attr.RootDirectory = 0;
419 attr.ObjectName = &nameW;
420 attr.Attributes = 0;
421 attr.SecurityDescriptor = NULL;
422 attr.SecurityQualityOfService = NULL;
424 /* first the system environment variables */
425 RtlInitUnicodeString( &nameW, env_keyW );
426 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
428 set_registry_variables( hkey, REG_SZ );
429 set_registry_variables( hkey, REG_EXPAND_SZ );
430 NtClose( hkey );
431 ret = TRUE;
434 /* then the ones for the current user */
435 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
436 RtlInitUnicodeString( &nameW, envW );
437 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
439 set_registry_variables( hkey, REG_SZ );
440 set_registry_variables( hkey, REG_EXPAND_SZ );
441 NtClose( hkey );
444 RtlInitUnicodeString( &nameW, volatile_envW );
445 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
447 set_registry_variables( hkey, REG_SZ );
448 set_registry_variables( hkey, REG_EXPAND_SZ );
449 NtClose( hkey );
452 NtClose( attr.RootDirectory );
453 return ret;
457 /***********************************************************************
458 * get_reg_value
460 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
462 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
463 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
464 DWORD len, size = sizeof(buffer);
465 WCHAR *ret = NULL;
466 UNICODE_STRING nameW;
468 RtlInitUnicodeString( &nameW, name );
469 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
470 return NULL;
472 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
473 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
475 if (info->Type == REG_EXPAND_SZ)
477 UNICODE_STRING value, expanded;
479 value.MaximumLength = len * sizeof(WCHAR);
480 value.Buffer = (WCHAR *)info->Data;
481 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
482 value.Length = len * sizeof(WCHAR);
483 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
484 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
485 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
486 else RtlFreeUnicodeString( &expanded );
488 else if (info->Type == REG_SZ)
490 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
492 memcpy( ret, info->Data, len * sizeof(WCHAR) );
493 ret[len] = 0;
496 return ret;
500 /***********************************************************************
501 * set_additional_environment
503 * Set some additional environment variables not specified in the registry.
505 static void set_additional_environment(void)
507 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
508 'S','o','f','t','w','a','r','e','\\',
509 'M','i','c','r','o','s','o','f','t','\\',
510 'W','i','n','d','o','w','s',' ','N','T','\\',
511 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
512 'P','r','o','f','i','l','e','L','i','s','t',0};
513 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
514 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
515 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
516 OBJECT_ATTRIBUTES attr;
517 UNICODE_STRING nameW;
518 WCHAR *profile_dir = NULL, *all_users_dir = NULL;
519 HANDLE hkey;
520 DWORD len;
522 /* set the ALLUSERSPROFILE variables */
524 attr.Length = sizeof(attr);
525 attr.RootDirectory = 0;
526 attr.ObjectName = &nameW;
527 attr.Attributes = 0;
528 attr.SecurityDescriptor = NULL;
529 attr.SecurityQualityOfService = NULL;
530 RtlInitUnicodeString( &nameW, profile_keyW );
531 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
533 profile_dir = get_reg_value( hkey, profiles_valueW );
534 all_users_dir = get_reg_value( hkey, all_users_valueW );
535 NtClose( hkey );
538 if (profile_dir && all_users_dir)
540 WCHAR *value, *p;
542 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
543 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
544 strcpyW( value, profile_dir );
545 p = value + strlenW(value);
546 if (p > value && p[-1] != '\\') *p++ = '\\';
547 strcpyW( p, all_users_dir );
548 SetEnvironmentVariableW( allusersW, value );
549 HeapFree( GetProcessHeap(), 0, value );
552 HeapFree( GetProcessHeap(), 0, all_users_dir );
553 HeapFree( GetProcessHeap(), 0, profile_dir );
556 /***********************************************************************
557 * set_wow64_environment
559 * Set the environment variables that change across 32/64/Wow64.
561 static void set_wow64_environment(void)
563 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};
564 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};
565 static const WCHAR x86W[] = {'x','8','6',0};
566 static const WCHAR versionW[] = {'M','a','c','h','i','n','e','\\',
567 'S','o','f','t','w','a','r','e','\\',
568 'M','i','c','r','o','s','o','f','t','\\',
569 'W','i','n','d','o','w','s','\\',
570 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
571 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
572 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
573 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
574 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
575 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
576 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
577 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
578 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
580 OBJECT_ATTRIBUTES attr;
581 UNICODE_STRING nameW;
582 WCHAR arch[64];
583 WCHAR *value;
584 HANDLE hkey;
586 /* set the PROCESSOR_ARCHITECTURE variable */
588 if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
590 if (is_win64)
592 SetEnvironmentVariableW( archW, arch );
593 SetEnvironmentVariableW( arch6432W, NULL );
596 else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
598 if (is_wow64)
600 SetEnvironmentVariableW( arch6432W, arch );
601 SetEnvironmentVariableW( archW, x86W );
605 attr.Length = sizeof(attr);
606 attr.RootDirectory = 0;
607 attr.ObjectName = &nameW;
608 attr.Attributes = 0;
609 attr.SecurityDescriptor = NULL;
610 attr.SecurityQualityOfService = NULL;
611 RtlInitUnicodeString( &nameW, versionW );
612 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
614 /* set the ProgramFiles variables */
616 if ((value = get_reg_value( hkey, progdirW )))
618 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
619 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
620 HeapFree( GetProcessHeap(), 0, value );
622 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
624 SetEnvironmentVariableW( progfilesW, value );
625 HeapFree( GetProcessHeap(), 0, value );
628 /* set the CommonProgramFiles variables */
630 if ((value = get_reg_value( hkey, commondirW )))
632 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
633 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
634 HeapFree( GetProcessHeap(), 0, value );
636 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
638 SetEnvironmentVariableW( commonfilesW, value );
639 HeapFree( GetProcessHeap(), 0, value );
642 NtClose( hkey );
645 /***********************************************************************
646 * set_library_wargv
648 * Set the Wine library Unicode argv global variables.
650 static void set_library_wargv( char **argv )
652 int argc;
653 char *q;
654 WCHAR *p;
655 WCHAR **wargv;
656 DWORD total = 0;
658 for (argc = 0; argv[argc]; argc++)
659 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
661 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
662 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
663 p = (WCHAR *)(wargv + argc + 1);
664 for (argc = 0; argv[argc]; argc++)
666 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
667 wargv[argc] = p;
668 p += reslen;
669 total -= reslen;
671 wargv[argc] = NULL;
673 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
675 for (argc = 0; wargv[argc]; argc++)
676 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
678 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
679 q = (char *)(argv + argc + 1);
680 for (argc = 0; wargv[argc]; argc++)
682 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
683 argv[argc] = q;
684 q += reslen;
685 total -= reslen;
687 argv[argc] = NULL;
689 __wine_main_argc = argc;
690 __wine_main_argv = argv;
691 __wine_main_wargv = wargv;
695 /***********************************************************************
696 * update_library_argv0
698 * Update the argv[0] global variable with the binary we have found.
700 static void update_library_argv0( const WCHAR *argv0 )
702 DWORD len = strlenW( argv0 );
704 if (len > strlenW( __wine_main_wargv[0] ))
706 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
708 strcpyW( __wine_main_wargv[0], argv0 );
710 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
711 if (len > strlen( __wine_main_argv[0] ) + 1)
713 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
715 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
719 /***********************************************************************
720 * build_command_line
722 * Build the command line of a process from the argv array.
724 * Note that it does NOT necessarily include the file name.
725 * Sometimes we don't even have any command line options at all.
727 * We must quote and escape characters so that the argv array can be rebuilt
728 * from the command line:
729 * - spaces and tabs must be quoted
730 * 'a b' -> '"a b"'
731 * - quotes must be escaped
732 * '"' -> '\"'
733 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
734 * resulting in an odd number of '\' followed by a '"'
735 * '\"' -> '\\\"'
736 * '\\"' -> '\\\\\"'
737 * - '\'s that are not followed by a '"' can be left as is
738 * 'a\b' == 'a\b'
739 * 'a\\b' == 'a\\b'
741 static BOOL build_command_line( WCHAR **argv )
743 int len;
744 WCHAR **arg;
745 LPWSTR p;
746 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
748 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
750 len = 0;
751 for (arg = argv; *arg; arg++)
753 BOOL has_space;
754 int bcount;
755 WCHAR* a;
757 has_space=FALSE;
758 bcount=0;
759 a=*arg;
760 if( !*a ) has_space=TRUE;
761 while (*a!='\0') {
762 if (*a=='\\') {
763 bcount++;
764 } else {
765 if (*a==' ' || *a=='\t') {
766 has_space=TRUE;
767 } else if (*a=='"') {
768 /* doubling of '\' preceding a '"',
769 * plus escaping of said '"'
771 len+=2*bcount+1;
773 bcount=0;
775 a++;
777 len+=(a-*arg)+1 /* for the separating space */;
778 if (has_space)
779 len+=2; /* for the quotes */
782 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
783 return FALSE;
785 p = rupp->CommandLine.Buffer;
786 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
787 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
788 for (arg = argv; *arg; arg++)
790 BOOL has_space,has_quote;
791 WCHAR* a;
793 /* Check for quotes and spaces in this argument */
794 has_space=has_quote=FALSE;
795 a=*arg;
796 if( !*a ) has_space=TRUE;
797 while (*a!='\0') {
798 if (*a==' ' || *a=='\t') {
799 has_space=TRUE;
800 if (has_quote)
801 break;
802 } else if (*a=='"') {
803 has_quote=TRUE;
804 if (has_space)
805 break;
807 a++;
810 /* Now transfer it to the command line */
811 if (has_space)
812 *p++='"';
813 if (has_quote) {
814 int bcount;
816 bcount=0;
817 a=*arg;
818 while (*a!='\0') {
819 if (*a=='\\') {
820 *p++=*a;
821 bcount++;
822 } else {
823 if (*a=='"') {
824 int i;
826 /* Double all the '\\' preceding this '"', plus one */
827 for (i=0;i<=bcount;i++)
828 *p++='\\';
829 *p++='"';
830 } else {
831 *p++=*a;
833 bcount=0;
835 a++;
837 } else {
838 WCHAR* x = *arg;
839 while ((*p=*x++)) p++;
841 if (has_space)
842 *p++='"';
843 *p++=' ';
845 if (p > rupp->CommandLine.Buffer)
846 p--; /* remove last space */
847 *p = '\0';
849 return TRUE;
853 /***********************************************************************
854 * init_current_directory
856 * Initialize the current directory from the Unix cwd or the parent info.
858 static void init_current_directory( CURDIR *cur_dir )
860 UNICODE_STRING dir_str;
861 const char *pwd;
862 char *cwd;
863 int size;
865 /* if we received a cur dir from the parent, try this first */
867 if (cur_dir->DosPath.Length)
869 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
872 /* now try to get it from the Unix cwd */
874 for (size = 256; ; size *= 2)
876 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
877 if (getcwd( cwd, size )) break;
878 HeapFree( GetProcessHeap(), 0, cwd );
879 if (errno == ERANGE) continue;
880 cwd = NULL;
881 break;
884 /* try to use PWD if it is valid, so that we don't resolve symlinks */
886 pwd = getenv( "PWD" );
887 if (cwd)
889 struct stat st1, st2;
891 if (!pwd || stat( pwd, &st1 ) == -1 ||
892 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
893 pwd = cwd;
896 if (pwd)
898 ANSI_STRING unix_name;
899 UNICODE_STRING nt_name;
900 RtlInitAnsiString( &unix_name, pwd );
901 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
903 UNICODE_STRING dos_path;
904 /* skip the \??\ prefix, nt_name is 0 terminated */
905 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
906 RtlSetCurrentDirectory_U( &dos_path );
907 RtlFreeUnicodeString( &nt_name );
911 if (!cur_dir->DosPath.Length) /* still not initialized */
913 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
914 "starting in the Windows directory.\n", cwd ? cwd : "" );
915 RtlInitUnicodeString( &dir_str, DIR_Windows );
916 RtlSetCurrentDirectory_U( &dir_str );
918 HeapFree( GetProcessHeap(), 0, cwd );
920 done:
921 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
925 /***********************************************************************
926 * init_windows_dirs
928 * Initialize the windows and system directories from the environment.
930 static void init_windows_dirs(void)
932 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
934 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
935 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
936 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
937 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
938 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
940 DWORD len;
941 WCHAR *buffer;
943 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
945 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
946 GetEnvironmentVariableW( windirW, buffer, len );
947 DIR_Windows = buffer;
949 else DIR_Windows = default_windirW;
951 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
953 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
954 GetEnvironmentVariableW( winsysdirW, buffer, len );
955 DIR_System = buffer;
957 else
959 len = strlenW( DIR_Windows );
960 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
961 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
962 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
963 DIR_System = buffer;
966 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
967 ERR( "directory %s could not be created, error %u\n",
968 debugstr_w(DIR_Windows), GetLastError() );
969 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
970 ERR( "directory %s could not be created, error %u\n",
971 debugstr_w(DIR_System), GetLastError() );
973 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
975 len = strlenW( DIR_Windows );
976 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
977 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
978 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
979 DIR_SysWow64 = buffer;
980 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
981 ERR( "directory %s could not be created, error %u\n",
982 debugstr_w(DIR_SysWow64), GetLastError() );
985 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
986 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
988 /* set the directories in ntdll too */
989 __wine_init_windows_dir( DIR_Windows, DIR_System );
993 /***********************************************************************
994 * start_wineboot
996 * Start the wineboot process if necessary. Return the handles to wait on.
998 static void start_wineboot( HANDLE handles[2] )
1000 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
1002 handles[1] = 0;
1003 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
1005 ERR( "failed to create wineboot event, expect trouble\n" );
1006 return;
1008 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
1010 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1011 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1012 STARTUPINFOW si;
1013 PROCESS_INFORMATION pi;
1014 void *redir;
1015 WCHAR app[MAX_PATH];
1016 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1018 memset( &si, 0, sizeof(si) );
1019 si.cb = sizeof(si);
1020 si.dwFlags = STARTF_USESTDHANDLES;
1021 si.hStdInput = 0;
1022 si.hStdOutput = 0;
1023 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1025 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1026 lstrcatW( app, wineboot );
1028 Wow64DisableWow64FsRedirection( &redir );
1029 strcpyW( cmdline, app );
1030 strcatW( cmdline, args );
1031 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1033 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1034 CloseHandle( pi.hThread );
1035 handles[1] = pi.hProcess;
1037 else
1039 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1040 CloseHandle( handles[0] );
1041 handles[0] = 0;
1043 Wow64RevertWow64FsRedirection( redir );
1048 #ifdef __i386__
1049 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1050 __ASM_GLOBAL_FUNC( call_process_entry,
1051 "pushl %ebp\n\t"
1052 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1053 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1054 "movl %esp,%ebp\n\t"
1055 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1056 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1057 "pushl 8(%ebp)\n\t"
1058 "call *12(%ebp)\n\t"
1059 "leave\n\t"
1060 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1061 __ASM_CFI(".cfi_same_value %ebp\n\t")
1062 "ret" )
1063 #else
1064 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1066 return entry( peb );
1068 #endif
1070 /***********************************************************************
1071 * start_process
1073 * Startup routine of a new process. Runs on the new process stack.
1075 static DWORD WINAPI start_process( PEB *peb )
1077 IMAGE_NT_HEADERS *nt;
1078 LPTHREAD_START_ROUTINE entry;
1080 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1081 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1082 nt->OptionalHeader.AddressOfEntryPoint);
1084 if (!nt->OptionalHeader.AddressOfEntryPoint)
1086 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1087 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1088 ExitThread( 1 );
1091 if (TRACE_ON(relay))
1092 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1093 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1095 SetLastError( 0 ); /* clear error code */
1096 if (peb->BeingDebugged) DbgBreakPoint();
1097 return call_process_entry( peb, entry );
1101 /***********************************************************************
1102 * set_process_name
1104 * Change the process name in the ps output.
1106 static void set_process_name( int argc, char *argv[] )
1108 #ifdef HAVE_SETPROCTITLE
1109 setproctitle("-%s", argv[1]);
1110 #endif
1112 #ifdef HAVE_PRCTL
1113 int i, offset;
1114 char *p, *prctl_name = argv[1];
1115 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1117 #ifndef PR_SET_NAME
1118 # define PR_SET_NAME 15
1119 #endif
1121 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1122 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1124 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1126 offset = argv[1] - argv[0];
1127 memmove( argv[1] - offset, argv[1], end - argv[1] );
1128 memset( end - offset, 0, offset );
1129 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1130 argv[i-1] = NULL;
1132 else
1133 #endif /* HAVE_PRCTL */
1135 /* remove argv[0] */
1136 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1141 /***********************************************************************
1142 * __wine_kernel_init
1144 * Wine initialisation: load and start the main exe file.
1146 void CDECL __wine_kernel_init(void)
1148 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1149 static const WCHAR dotW[] = {'.',0};
1151 WCHAR *p, main_exe_name[MAX_PATH+1];
1152 PEB *peb = NtCurrentTeb()->Peb;
1153 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1154 HANDLE boot_events[2];
1155 BOOL got_environment = TRUE;
1157 /* Initialize everything */
1159 setbuf(stdout,NULL);
1160 setbuf(stderr,NULL);
1161 kernel32_handle = GetModuleHandleW(kernel32W);
1162 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1164 LOCALE_Init();
1166 if (!params->Environment)
1168 /* Copy the parent environment */
1169 if (!build_initial_environment()) exit(1);
1171 /* convert old configuration to new format */
1172 convert_old_config();
1174 got_environment = set_registry_environment( FALSE );
1175 set_additional_environment();
1178 init_windows_dirs();
1179 init_current_directory( &params->CurrentDirectory );
1181 set_process_name( __wine_main_argc, __wine_main_argv );
1182 set_library_wargv( __wine_main_argv );
1183 boot_events[0] = boot_events[1] = 0;
1185 if (peb->ProcessParameters->ImagePathName.Buffer)
1187 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1189 else
1191 struct binary_info binary_info;
1193 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1194 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1196 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1197 ExitProcess( GetLastError() );
1199 update_library_argv0( main_exe_name );
1200 if (!build_command_line( __wine_main_wargv )) goto error;
1201 start_wineboot( boot_events );
1204 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1205 p = strrchrW( main_exe_name, '.' );
1206 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1208 TRACE( "starting process name=%s argv[0]=%s\n",
1209 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1211 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1212 MODULE_get_dll_load_path(main_exe_name) );
1214 if (boot_events[0])
1216 DWORD timeout = 2 * 60 * 1000, count = 1;
1218 if (boot_events[1]) count++;
1219 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1220 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1221 ERR( "boot event wait timed out\n" );
1222 CloseHandle( boot_events[0] );
1223 if (boot_events[1]) CloseHandle( boot_events[1] );
1224 /* reload environment now that wineboot has run */
1225 set_registry_environment( got_environment );
1226 set_additional_environment();
1228 set_wow64_environment();
1230 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1232 DWORD_PTR args[1];
1233 WCHAR msgW[1024];
1234 char msg[1024];
1235 DWORD error = GetLastError();
1237 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1238 if (error == ERROR_BAD_EXE_FORMAT ||
1239 error == ERROR_INVALID_ADDRESS ||
1240 error == ERROR_NOT_ENOUGH_MEMORY)
1242 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1243 /* if we get back here, it failed */
1245 else if (error == ERROR_MOD_NOT_FOUND)
1247 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1248 else p = main_exe_name;
1249 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1251 /* args 1 and 2 are --app-name full_path */
1252 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1253 debugstr_w(__wine_main_wargv[3]) );
1254 ExitProcess( ERROR_BAD_EXE_FORMAT );
1256 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1257 ExitProcess( ERROR_FILE_NOT_FOUND );
1259 args[0] = (DWORD_PTR)main_exe_name;
1260 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1261 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1262 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1263 MESSAGE( "wine: %s", msg );
1264 ExitProcess( error );
1267 if (!params->CurrentDirectory.Handle) chdir("/"); /* avoid locking removable devices */
1269 LdrInitializeThunk( start_process, 0, 0, 0 );
1271 error:
1272 ExitProcess( GetLastError() );
1276 /***********************************************************************
1277 * build_argv
1279 * Build an argv array from a command-line.
1280 * 'reserved' is the number of args to reserve before the first one.
1282 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1284 int argc;
1285 char** argv;
1286 char *arg,*s,*d,*cmdline;
1287 int in_quotes,bcount,len;
1289 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1290 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1291 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1293 argc=reserved+1;
1294 bcount=0;
1295 in_quotes=0;
1296 s=cmdline;
1297 while (1) {
1298 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1299 /* space */
1300 argc++;
1301 /* skip the remaining spaces */
1302 while (*s==' ' || *s=='\t') {
1303 s++;
1305 if (*s=='\0')
1306 break;
1307 bcount=0;
1308 continue;
1309 } else if (*s=='\\') {
1310 /* '\', count them */
1311 bcount++;
1312 } else if ((*s=='"') && ((bcount & 1)==0)) {
1313 /* unescaped '"' */
1314 in_quotes=!in_quotes;
1315 bcount=0;
1316 } else {
1317 /* a regular character */
1318 bcount=0;
1320 s++;
1322 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1324 HeapFree( GetProcessHeap(), 0, cmdline );
1325 return NULL;
1328 arg = d = s = (char *)(argv + argc);
1329 memcpy( d, cmdline, len );
1330 bcount=0;
1331 in_quotes=0;
1332 argc=reserved;
1333 while (*s) {
1334 if ((*s==' ' || *s=='\t') && !in_quotes) {
1335 /* Close the argument and copy it */
1336 *d=0;
1337 argv[argc++]=arg;
1339 /* skip the remaining spaces */
1340 do {
1341 s++;
1342 } while (*s==' ' || *s=='\t');
1344 /* Start with a new argument */
1345 arg=d=s;
1346 bcount=0;
1347 } else if (*s=='\\') {
1348 /* '\\' */
1349 *d++=*s++;
1350 bcount++;
1351 } else if (*s=='"') {
1352 /* '"' */
1353 if ((bcount & 1)==0) {
1354 /* Preceded by an even number of '\', this is half that
1355 * number of '\', plus a '"' which we discard.
1357 d-=bcount/2;
1358 s++;
1359 in_quotes=!in_quotes;
1360 } else {
1361 /* Preceded by an odd number of '\', this is half that
1362 * number of '\' followed by a '"'
1364 d=d-bcount/2-1;
1365 *d++='"';
1366 s++;
1368 bcount=0;
1369 } else {
1370 /* a regular character */
1371 *d++=*s++;
1372 bcount=0;
1375 if (*arg) {
1376 *d='\0';
1377 argv[argc++]=arg;
1379 argv[argc]=NULL;
1381 HeapFree( GetProcessHeap(), 0, cmdline );
1382 return argv;
1386 /***********************************************************************
1387 * build_envp
1389 * Build the environment of a new child process.
1391 static char **build_envp( const WCHAR *envW )
1393 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1395 const WCHAR *end;
1396 char **envp;
1397 char *env, *p;
1398 int count = 1, length;
1399 unsigned int i;
1401 for (end = envW; *end; count++) end += strlenW(end) + 1;
1402 end++;
1403 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1404 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1405 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1407 for (p = env; *p; p += strlen(p) + 1)
1408 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1410 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1412 if (!(p = getenv(unix_vars[i]))) continue;
1413 length += strlen(unix_vars[i]) + strlen(p) + 2;
1414 count++;
1417 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1419 char **envptr = envp;
1420 char *dst = (char *)(envp + count);
1422 /* some variables must not be modified, so we get them directly from the unix env */
1423 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1425 if (!(p = getenv(unix_vars[i]))) continue;
1426 *envptr++ = strcpy( dst, unix_vars[i] );
1427 strcat( dst, "=" );
1428 strcat( dst, p );
1429 dst += strlen(dst) + 1;
1432 /* now put the Windows environment strings */
1433 for (p = env; *p; p += strlen(p) + 1)
1435 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1436 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1437 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1438 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1439 if (is_special_env_var( p )) /* prefix it with "WINE" */
1441 *envptr++ = strcpy( dst, "WINE" );
1442 strcat( dst, p );
1444 else
1446 *envptr++ = strcpy( dst, p );
1448 dst += strlen(dst) + 1;
1450 *envptr = 0;
1452 HeapFree( GetProcessHeap(), 0, env );
1453 return envp;
1457 /***********************************************************************
1458 * fork_and_exec
1460 * Fork and exec a new Unix binary, checking for errors.
1462 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1463 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1465 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1466 int pid, err;
1467 char **argv, **envp;
1469 if (!env) env = GetEnvironmentStringsW();
1471 #ifdef HAVE_PIPE2
1472 if (pipe2( fd, O_CLOEXEC ) == -1)
1473 #endif
1475 if (pipe(fd) == -1)
1477 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1478 return -1;
1480 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1481 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1484 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1486 HANDLE hstdin, hstdout, hstderr;
1488 if (startup->dwFlags & STARTF_USESTDHANDLES)
1490 hstdin = startup->hStdInput;
1491 hstdout = startup->hStdOutput;
1492 hstderr = startup->hStdError;
1494 else
1496 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1497 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1498 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1501 if (is_console_handle( hstdin ))
1502 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1503 if (is_console_handle( hstdout ))
1504 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1505 if (is_console_handle( hstderr ))
1506 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1507 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1508 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1509 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1512 argv = build_argv( cmdline, 0 );
1513 envp = build_envp( env );
1515 if (!(pid = fork())) /* child */
1517 if (!(pid = fork())) /* grandchild */
1519 close( fd[0] );
1521 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1523 int nullfd = open( "/dev/null", O_RDWR );
1524 setsid();
1525 /* close stdin and stdout */
1526 if (nullfd != -1)
1528 dup2( nullfd, 0 );
1529 dup2( nullfd, 1 );
1530 close( nullfd );
1533 else
1535 if (stdin_fd != -1)
1537 dup2( stdin_fd, 0 );
1538 close( stdin_fd );
1540 if (stdout_fd != -1)
1542 dup2( stdout_fd, 1 );
1543 close( stdout_fd );
1545 if (stderr_fd != -1)
1547 dup2( stderr_fd, 2 );
1548 close( stderr_fd );
1552 /* Reset signals that we previously set to SIG_IGN */
1553 signal( SIGPIPE, SIG_DFL );
1555 if (newdir) chdir(newdir);
1557 if (argv && envp) execve( filename, argv, envp );
1560 if (pid <= 0) /* grandchild if exec failed or child if fork failed */
1562 err = errno;
1563 write( fd[1], &err, sizeof(err) );
1564 _exit(1);
1567 _exit(0); /* child if fork succeeded */
1569 HeapFree( GetProcessHeap(), 0, argv );
1570 HeapFree( GetProcessHeap(), 0, envp );
1571 if (stdin_fd != -1) close( stdin_fd );
1572 if (stdout_fd != -1) close( stdout_fd );
1573 if (stderr_fd != -1) close( stderr_fd );
1574 close( fd[1] );
1575 if (pid != -1)
1577 /* reap child */
1578 do {
1579 err = waitpid(pid, NULL, 0);
1580 } while (err < 0 && errno == EINTR);
1582 if (read( fd[0], &err, sizeof(err) ) > 0) /* exec or second fork failed */
1584 errno = err;
1585 pid = -1;
1588 if (pid == -1) FILE_SetDosError();
1589 close( fd[0] );
1590 return pid;
1594 static inline DWORD append_string( void **ptr, const WCHAR *str )
1596 DWORD len = strlenW( str );
1597 memcpy( *ptr, str, len * sizeof(WCHAR) );
1598 *ptr = (WCHAR *)*ptr + len;
1599 return len * sizeof(WCHAR);
1602 /***********************************************************************
1603 * create_startup_info
1605 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1606 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1607 const STARTUPINFOW *startup, DWORD *info_size )
1609 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1610 const WCHAR *title;
1611 startup_info_t *info;
1612 DWORD size;
1613 void *ptr;
1614 UNICODE_STRING newdir;
1615 WCHAR imagepath[MAX_PATH];
1616 HANDLE hstdin, hstdout, hstderr;
1618 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1619 lstrcpynW( imagepath, filename, MAX_PATH );
1620 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1621 lstrcpynW( imagepath, filename, MAX_PATH );
1623 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1625 newdir.Buffer = NULL;
1626 if (cur_dir)
1628 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1629 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1630 else
1631 cur_dir = NULL;
1633 if (!cur_dir)
1635 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1636 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1637 else
1638 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1640 title = startup->lpTitle ? startup->lpTitle : imagepath;
1642 size = sizeof(*info);
1643 size += strlenW( cur_dir ) * sizeof(WCHAR);
1644 size += cur_params->DllPath.Length;
1645 size += strlenW( imagepath ) * sizeof(WCHAR);
1646 size += strlenW( cmdline ) * sizeof(WCHAR);
1647 size += strlenW( title ) * sizeof(WCHAR);
1648 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1649 /* FIXME: shellinfo */
1650 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1651 size = (size + 1) & ~1;
1652 *info_size = size;
1654 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1656 info->console_flags = cur_params->ConsoleFlags;
1657 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1658 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1660 if (startup->dwFlags & STARTF_USESTDHANDLES)
1662 hstdin = startup->hStdInput;
1663 hstdout = startup->hStdOutput;
1664 hstderr = startup->hStdError;
1666 else
1668 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1669 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1670 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1672 info->hstdin = wine_server_obj_handle( hstdin );
1673 info->hstdout = wine_server_obj_handle( hstdout );
1674 info->hstderr = wine_server_obj_handle( hstderr );
1675 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1677 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1678 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1679 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1680 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1682 else
1684 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1685 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1686 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1689 info->x = startup->dwX;
1690 info->y = startup->dwY;
1691 info->xsize = startup->dwXSize;
1692 info->ysize = startup->dwYSize;
1693 info->xchars = startup->dwXCountChars;
1694 info->ychars = startup->dwYCountChars;
1695 info->attribute = startup->dwFillAttribute;
1696 info->flags = startup->dwFlags;
1697 info->show = startup->wShowWindow;
1699 ptr = info + 1;
1700 info->curdir_len = append_string( &ptr, cur_dir );
1701 info->dllpath_len = cur_params->DllPath.Length;
1702 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1703 ptr = (char *)ptr + cur_params->DllPath.Length;
1704 info->imagepath_len = append_string( &ptr, imagepath );
1705 info->cmdline_len = append_string( &ptr, cmdline );
1706 info->title_len = append_string( &ptr, title );
1707 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1708 if (startup->lpReserved2 && startup->cbReserved2)
1710 info->runtime_len = startup->cbReserved2;
1711 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1714 done:
1715 RtlFreeUnicodeString( &newdir );
1716 return info;
1719 /***********************************************************************
1720 * get_alternate_loader
1722 * Get the name of the alternate (32 or 64 bit) Wine loader.
1724 static const char *get_alternate_loader( char **ret_env )
1726 char *env;
1727 const char *loader = NULL;
1728 const char *loader_env = getenv( "WINELOADER" );
1730 *ret_env = NULL;
1732 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1734 if (loader_env)
1736 int len = strlen( loader_env );
1737 if (!is_win64)
1739 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1740 strcpy( env, "WINELOADER=" );
1741 strcat( env, loader_env );
1742 strcat( env, "64" );
1744 else
1746 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1747 strcpy( env, "WINELOADER=" );
1748 strcat( env, loader_env );
1749 len += sizeof("WINELOADER=") - 1;
1750 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1752 if (!loader)
1754 if ((loader = strrchr( env, '/' ))) loader++;
1755 else loader = env;
1757 *ret_env = env;
1759 if (!loader) loader = is_win64 ? "wine" : "wine64";
1760 return loader;
1763 #ifdef __APPLE__
1764 /***********************************************************************
1765 * terminate_main_thread
1767 * On some versions of Mac OS X, the execve system call fails with
1768 * ENOTSUP if the process has multiple threads. Wine is always multi-
1769 * threaded on Mac OS X because it specifically reserves the main thread
1770 * for use by the system frameworks (see apple_main_thread() in
1771 * libs/wine/loader.c). So, when we need to exec without first forking,
1772 * we need to terminate the main thread first. We do this by installing
1773 * a custom run loop source onto the main run loop and signaling it.
1774 * The source's "perform" callback is pthread_exit and it will be
1775 * executed on the main thread, terminating it.
1777 * Returns TRUE if there's still hope the main thread has terminated or
1778 * will soon. Return FALSE if we've given up.
1780 static BOOL terminate_main_thread(void)
1782 static int delayms;
1784 if (!delayms)
1786 CFRunLoopSourceContext source_context = { 0 };
1787 CFRunLoopSourceRef source;
1789 source_context.perform = pthread_exit;
1790 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1791 return FALSE;
1793 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1794 CFRunLoopSourceSignal( source );
1795 CFRunLoopWakeUp( CFRunLoopGetMain() );
1796 CFRelease( source );
1798 delayms = 20;
1801 if (delayms > 1000)
1802 return FALSE;
1804 usleep(delayms * 1000);
1805 delayms *= 2;
1807 return TRUE;
1809 #endif
1811 /***********************************************************************
1812 * get_process_cpu
1814 static int get_process_cpu( const WCHAR *filename, const struct binary_info *binary_info )
1816 switch (binary_info->arch)
1818 case IMAGE_FILE_MACHINE_I386: return CPU_x86;
1819 case IMAGE_FILE_MACHINE_AMD64: return CPU_x86_64;
1820 case IMAGE_FILE_MACHINE_POWERPC: return CPU_POWERPC;
1821 case IMAGE_FILE_MACHINE_ARM:
1822 case IMAGE_FILE_MACHINE_THUMB:
1823 case IMAGE_FILE_MACHINE_ARMNT: return CPU_ARM;
1824 case IMAGE_FILE_MACHINE_ARM64: return CPU_ARM64;
1826 ERR( "%s uses unsupported architecture (%04x)\n", debugstr_w(filename), binary_info->arch );
1827 return -1;
1830 /***********************************************************************
1831 * exec_loader
1833 static pid_t exec_loader( LPCWSTR cmd_line, unsigned int flags, int socketfd,
1834 int stdin_fd, int stdout_fd, const char *unixdir, char *winedebug,
1835 const struct binary_info *binary_info, int exec_only )
1837 pid_t pid;
1838 char *wineloader = NULL;
1839 const char *loader = NULL;
1840 char **argv;
1842 argv = build_argv( cmd_line, 1 );
1844 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1845 loader = get_alternate_loader( &wineloader );
1847 if (exec_only || !(pid = fork())) /* child */
1849 if (exec_only || !(pid = fork())) /* grandchild */
1851 char preloader_reserve[64], socket_env[64];
1853 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1855 int fd = open( "/dev/null", O_RDWR );
1856 setsid();
1857 /* close stdin and stdout */
1858 if (fd != -1)
1860 dup2( fd, 0 );
1861 dup2( fd, 1 );
1862 close( fd );
1865 else
1867 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1868 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1871 if (stdin_fd != -1) close( stdin_fd );
1872 if (stdout_fd != -1) close( stdout_fd );
1874 /* Reset signals that we previously set to SIG_IGN */
1875 signal( SIGPIPE, SIG_DFL );
1877 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
1878 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1879 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1881 putenv( preloader_reserve );
1882 putenv( socket_env );
1883 if (winedebug) putenv( winedebug );
1884 if (wineloader) putenv( wineloader );
1885 if (unixdir) chdir(unixdir);
1887 if (argv)
1891 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1893 #ifdef __APPLE__
1894 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1895 #else
1896 while (0);
1897 #endif
1899 _exit(1);
1902 _exit(pid == -1);
1905 if (pid != -1)
1907 /* reap child */
1908 pid_t wret;
1909 do {
1910 wret = waitpid(pid, NULL, 0);
1911 } while (wret < 0 && errno == EINTR);
1914 HeapFree( GetProcessHeap(), 0, wineloader );
1915 HeapFree( GetProcessHeap(), 0, argv );
1916 return pid;
1919 /***********************************************************************
1920 * create_process
1922 * Create a new process. If hFile is a valid handle we have an exe
1923 * file, otherwise it is a Winelib app.
1925 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1926 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1927 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1928 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1929 const struct binary_info *binary_info, int exec_only )
1931 static const char *cpu_names[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
1932 NTSTATUS status;
1933 BOOL success = FALSE;
1934 HANDLE process_info;
1935 WCHAR *env_end;
1936 char *winedebug = NULL;
1937 startup_info_t *startup_info;
1938 DWORD startup_info_size;
1939 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1940 pid_t pid;
1941 int err, cpu;
1943 if ((cpu = get_process_cpu( filename, binary_info )) == -1)
1945 SetLastError( ERROR_BAD_EXE_FORMAT );
1946 return FALSE;
1949 /* create the socket for the new process */
1951 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1953 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1954 return FALSE;
1956 #ifdef SO_PASSCRED
1957 else
1959 int enable = 1;
1960 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1962 #endif
1964 if (exec_only) /* things are much simpler in this case */
1966 wine_server_send_fd( socketfd[1] );
1967 close( socketfd[1] );
1968 SERVER_START_REQ( new_process )
1970 req->create_flags = flags;
1971 req->socket_fd = socketfd[1];
1972 req->exe_file = wine_server_obj_handle( hFile );
1973 req->cpu = cpu;
1974 status = wine_server_call( req );
1976 SERVER_END_REQ;
1978 switch (status)
1980 case STATUS_INVALID_IMAGE_WIN_64:
1981 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
1982 break;
1983 case STATUS_INVALID_IMAGE_FORMAT:
1984 ERR( "%s not supported on this installation (%s binary)\n",
1985 debugstr_w(filename), cpu_names[cpu] );
1986 break;
1987 case STATUS_SUCCESS:
1988 exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
1989 winedebug, binary_info, TRUE );
1991 close( socketfd[0] );
1992 SetLastError( RtlNtStatusToDosError( status ));
1993 return FALSE;
1996 RtlAcquirePebLock();
1998 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1999 &startup_info_size )))
2001 RtlReleasePebLock();
2002 close( socketfd[0] );
2003 close( socketfd[1] );
2004 return FALSE;
2006 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
2007 env_end = env;
2008 while (*env_end)
2010 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
2011 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
2013 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
2014 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
2015 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
2017 env_end += strlenW(env_end) + 1;
2019 env_end++;
2021 wine_server_send_fd( socketfd[1] );
2022 close( socketfd[1] );
2024 /* create the process on the server side */
2026 SERVER_START_REQ( new_process )
2028 req->inherit_all = inherit;
2029 req->create_flags = flags;
2030 req->socket_fd = socketfd[1];
2031 req->exe_file = wine_server_obj_handle( hFile );
2032 req->process_access = PROCESS_ALL_ACCESS;
2033 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
2034 req->thread_access = THREAD_ALL_ACCESS;
2035 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
2036 req->cpu = cpu;
2037 req->info_size = startup_info_size;
2039 wine_server_add_data( req, startup_info, startup_info_size );
2040 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
2041 if (!(status = wine_server_call( req )))
2043 info->dwProcessId = (DWORD)reply->pid;
2044 info->dwThreadId = (DWORD)reply->tid;
2045 info->hProcess = wine_server_ptr_handle( reply->phandle );
2046 info->hThread = wine_server_ptr_handle( reply->thandle );
2048 process_info = wine_server_ptr_handle( reply->info );
2050 SERVER_END_REQ;
2052 RtlReleasePebLock();
2053 if (status)
2055 switch (status)
2057 case STATUS_INVALID_IMAGE_WIN_64:
2058 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2059 break;
2060 case STATUS_INVALID_IMAGE_FORMAT:
2061 ERR( "%s not supported on this installation (%s binary)\n",
2062 debugstr_w(filename), cpu_names[cpu] );
2063 break;
2065 close( socketfd[0] );
2066 HeapFree( GetProcessHeap(), 0, startup_info );
2067 HeapFree( GetProcessHeap(), 0, winedebug );
2068 SetLastError( RtlNtStatusToDosError( status ));
2069 return FALSE;
2072 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
2074 if (startup_info->hstdin)
2075 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
2076 FILE_READ_DATA, &stdin_fd, NULL );
2077 if (startup_info->hstdout)
2078 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
2079 FILE_WRITE_DATA, &stdout_fd, NULL );
2081 HeapFree( GetProcessHeap(), 0, startup_info );
2083 /* create the child process */
2085 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2086 winedebug, binary_info, FALSE );
2088 if (stdin_fd != -1) close( stdin_fd );
2089 if (stdout_fd != -1) close( stdout_fd );
2090 close( socketfd[0] );
2091 HeapFree( GetProcessHeap(), 0, winedebug );
2092 if (pid == -1)
2094 FILE_SetDosError();
2095 goto error;
2098 /* wait for the new process info to be ready */
2100 WaitForSingleObject( process_info, INFINITE );
2101 SERVER_START_REQ( get_new_process_info )
2103 req->info = wine_server_obj_handle( process_info );
2104 wine_server_call( req );
2105 success = reply->success;
2106 err = reply->exit_code;
2108 SERVER_END_REQ;
2110 if (!success)
2112 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2113 goto error;
2115 CloseHandle( process_info );
2116 return success;
2118 error:
2119 CloseHandle( process_info );
2120 CloseHandle( info->hProcess );
2121 CloseHandle( info->hThread );
2122 info->hProcess = info->hThread = 0;
2123 info->dwProcessId = info->dwThreadId = 0;
2124 return FALSE;
2128 /***********************************************************************
2129 * create_vdm_process
2131 * Create a new VDM process for a 16-bit or DOS application.
2133 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2134 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2135 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2136 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2137 const struct binary_info *binary_info, int exec_only )
2139 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2141 BOOL ret;
2142 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
2143 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
2145 if (!new_cmd_line)
2147 SetLastError( ERROR_OUTOFMEMORY );
2148 return FALSE;
2150 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
2151 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2152 flags, startup, info, unixdir, binary_info, exec_only );
2153 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2154 return ret;
2158 /***********************************************************************
2159 * create_cmd_process
2161 * Create a new cmd shell process for a .BAT file.
2163 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2164 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2165 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2166 LPPROCESS_INFORMATION info )
2169 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2170 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2171 WCHAR comspec[MAX_PATH];
2172 WCHAR *newcmdline;
2173 BOOL ret;
2175 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2176 return FALSE;
2177 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2178 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2179 return FALSE;
2181 strcpyW( newcmdline, comspec );
2182 strcatW( newcmdline, slashcW );
2183 strcatW( newcmdline, cmd_line );
2184 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2185 flags, env, cur_dir, startup, info );
2186 HeapFree( GetProcessHeap(), 0, newcmdline );
2187 return ret;
2191 /*************************************************************************
2192 * get_file_name
2194 * Helper for CreateProcess: retrieve the file name to load from the
2195 * app name and command line. Store the file name in buffer, and
2196 * return a possibly modified command line.
2197 * Also returns a handle to the opened file if it's a Windows binary.
2199 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2200 int buflen, HANDLE *handle, struct binary_info *binary_info )
2202 static const WCHAR quotesW[] = {'"','%','s','"',0};
2204 WCHAR *name, *pos, *first_space, *ret = NULL;
2205 const WCHAR *p;
2207 /* if we have an app name, everything is easy */
2209 if (appname)
2211 /* use the unmodified app name as file name */
2212 lstrcpynW( buffer, appname, buflen );
2213 *handle = open_exe_file( buffer, binary_info );
2214 if (!(ret = cmdline) || !cmdline[0])
2216 /* no command-line, create one */
2217 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2218 sprintfW( ret, quotesW, appname );
2220 return ret;
2223 /* first check for a quoted file name */
2225 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2227 int len = p - cmdline - 1;
2228 /* extract the quoted portion as file name */
2229 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2230 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2231 name[len] = 0;
2233 if (!find_exe_file( name, buffer, buflen, handle, binary_info )) goto done;
2234 ret = cmdline; /* no change necessary */
2235 goto done;
2238 /* now try the command-line word by word */
2240 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2241 return NULL;
2242 pos = name;
2243 p = cmdline;
2244 first_space = NULL;
2246 for (;;)
2248 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2249 *pos = 0;
2250 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2252 ret = cmdline;
2253 break;
2255 if (!first_space) first_space = pos;
2256 if (!(*pos++ = *p++)) break;
2259 if (!ret)
2261 SetLastError( ERROR_FILE_NOT_FOUND );
2263 else if (first_space) /* build a new command-line with quotes */
2265 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2266 goto done;
2267 sprintfW( ret, quotesW, name );
2268 strcatW( ret, p );
2271 done:
2272 HeapFree( GetProcessHeap(), 0, name );
2273 return ret;
2277 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2278 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2279 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2280 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2281 LPPROCESS_INFORMATION info )
2283 BOOL retv = FALSE;
2284 HANDLE hFile = 0;
2285 char *unixdir = NULL;
2286 WCHAR name[MAX_PATH];
2287 WCHAR *tidy_cmdline, *p, *envW = env;
2288 struct binary_info binary_info;
2290 /* Process the AppName and/or CmdLine to get module name and path */
2292 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2294 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2295 &hFile, &binary_info )))
2296 return FALSE;
2297 if (hFile == INVALID_HANDLE_VALUE) goto done;
2299 /* Warn if unsupported features are used */
2301 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2302 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2303 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2304 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2305 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2307 if (cur_dir)
2309 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2311 SetLastError(ERROR_DIRECTORY);
2312 goto done;
2315 else
2317 WCHAR buf[MAX_PATH];
2318 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2321 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2323 char *e = env;
2324 DWORD lenW;
2326 while (*e) e += strlen(e) + 1;
2327 e++; /* final null */
2328 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, NULL, 0 );
2329 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2330 MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, envW, lenW );
2331 flags |= CREATE_UNICODE_ENVIRONMENT;
2334 info->hThread = info->hProcess = 0;
2335 info->dwProcessId = info->dwThreadId = 0;
2337 if (binary_info.flags & BINARY_FLAG_DLL)
2339 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2340 SetLastError( ERROR_BAD_EXE_FORMAT );
2342 else switch (binary_info.type)
2344 case BINARY_PE:
2345 TRACE( "starting %s as Win%d binary (%p-%p, arch %04x)\n",
2346 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2347 binary_info.res_start, binary_info.res_end, binary_info.arch );
2348 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2349 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2350 break;
2351 case BINARY_OS216:
2352 case BINARY_WIN16:
2353 case BINARY_DOS:
2354 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2355 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2356 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2357 break;
2358 case BINARY_UNIX_LIB:
2359 TRACE( "starting %s as %d-bit Winelib app\n",
2360 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2361 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2362 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2363 break;
2364 case BINARY_UNKNOWN:
2365 /* check for .com or .bat extension */
2366 if ((p = strrchrW( name, '.' )))
2368 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2370 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2371 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2372 inherit, flags, startup_info, info, unixdir,
2373 &binary_info, FALSE );
2374 break;
2376 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2378 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2379 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2380 inherit, flags, startup_info, info );
2381 break;
2384 /* fall through */
2385 case BINARY_UNIX_EXE:
2387 /* unknown file, try as unix executable */
2388 char *unix_name;
2390 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2392 if ((unix_name = wine_get_unix_file_name( name )))
2394 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2395 HeapFree( GetProcessHeap(), 0, unix_name );
2398 break;
2400 if (hFile) CloseHandle( hFile );
2402 done:
2403 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2404 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2405 HeapFree( GetProcessHeap(), 0, unixdir );
2406 if (retv)
2407 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2408 return retv;
2412 /**********************************************************************
2413 * CreateProcessA (KERNEL32.@)
2415 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2416 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2417 DWORD flags, LPVOID env, LPCSTR cur_dir,
2418 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2420 BOOL ret = FALSE;
2421 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2422 UNICODE_STRING desktopW, titleW;
2423 STARTUPINFOW infoW;
2425 desktopW.Buffer = NULL;
2426 titleW.Buffer = NULL;
2427 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2428 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2429 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2431 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2432 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2434 memcpy( &infoW, startup_info, sizeof(infoW) );
2435 infoW.lpDesktop = desktopW.Buffer;
2436 infoW.lpTitle = titleW.Buffer;
2438 if (startup_info->lpReserved)
2439 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2440 debugstr_a(startup_info->lpReserved));
2442 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2443 inherit, flags, env, cur_dirW, &infoW, info );
2444 done:
2445 HeapFree( GetProcessHeap(), 0, app_nameW );
2446 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2447 HeapFree( GetProcessHeap(), 0, cur_dirW );
2448 RtlFreeUnicodeString( &desktopW );
2449 RtlFreeUnicodeString( &titleW );
2450 return ret;
2454 /**********************************************************************
2455 * CreateProcessW (KERNEL32.@)
2457 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2458 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2459 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2460 LPPROCESS_INFORMATION info )
2462 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2463 inherit, flags, env, cur_dir, startup_info, info);
2467 /**********************************************************************
2468 * exec_process
2470 static void exec_process( LPCWSTR name )
2472 HANDLE hFile;
2473 WCHAR *p;
2474 STARTUPINFOW startup_info;
2475 PROCESS_INFORMATION info;
2476 struct binary_info binary_info;
2478 hFile = open_exe_file( name, &binary_info );
2479 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2481 memset( &startup_info, 0, sizeof(startup_info) );
2482 startup_info.cb = sizeof(startup_info);
2484 /* Determine executable type */
2486 if (binary_info.flags & BINARY_FLAG_DLL) return;
2487 switch (binary_info.type)
2489 case BINARY_PE:
2490 TRACE( "starting %s as Win%d binary (%p-%p, arch %04x)\n",
2491 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2492 binary_info.res_start, binary_info.res_end, binary_info.arch );
2493 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2494 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2495 break;
2496 case BINARY_UNIX_LIB:
2497 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2498 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2499 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2500 break;
2501 case BINARY_UNKNOWN:
2502 /* check for .com or .pif extension */
2503 if (!(p = strrchrW( name, '.' ))) break;
2504 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2505 /* fall through */
2506 case BINARY_OS216:
2507 case BINARY_WIN16:
2508 case BINARY_DOS:
2509 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2510 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2511 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2512 break;
2513 default:
2514 break;
2516 CloseHandle( hFile );
2520 /***********************************************************************
2521 * wait_input_idle
2523 * Wrapper to call WaitForInputIdle USER function
2525 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2527 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2529 HMODULE mod = GetModuleHandleA( "user32.dll" );
2530 if (mod)
2532 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2533 if (ptr) return ptr( process, timeout );
2535 return 0;
2539 /***********************************************************************
2540 * WinExec (KERNEL32.@)
2542 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2544 PROCESS_INFORMATION info;
2545 STARTUPINFOA startup;
2546 char *cmdline;
2547 UINT ret;
2549 memset( &startup, 0, sizeof(startup) );
2550 startup.cb = sizeof(startup);
2551 startup.dwFlags = STARTF_USESHOWWINDOW;
2552 startup.wShowWindow = nCmdShow;
2554 /* cmdline needs to be writable for CreateProcess */
2555 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2556 strcpy( cmdline, lpCmdLine );
2558 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2559 0, NULL, NULL, &startup, &info ))
2561 /* Give 30 seconds to the app to come up */
2562 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2563 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2564 ret = 33;
2565 /* Close off the handles */
2566 CloseHandle( info.hThread );
2567 CloseHandle( info.hProcess );
2569 else if ((ret = GetLastError()) >= 32)
2571 FIXME("Strange error set by CreateProcess: %d\n", ret );
2572 ret = 11;
2574 HeapFree( GetProcessHeap(), 0, cmdline );
2575 return ret;
2579 /**********************************************************************
2580 * LoadModule (KERNEL32.@)
2582 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2584 LOADPARMS32 *params = paramBlock;
2585 PROCESS_INFORMATION info;
2586 STARTUPINFOA startup;
2587 DWORD ret;
2588 LPSTR cmdline, p;
2589 char filename[MAX_PATH];
2590 BYTE len;
2592 if (!name) return ERROR_FILE_NOT_FOUND;
2594 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2595 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2596 return GetLastError();
2598 len = (BYTE)params->lpCmdLine[0];
2599 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2600 return ERROR_NOT_ENOUGH_MEMORY;
2602 strcpy( cmdline, filename );
2603 p = cmdline + strlen(cmdline);
2604 *p++ = ' ';
2605 memcpy( p, params->lpCmdLine + 1, len );
2606 p[len] = 0;
2608 memset( &startup, 0, sizeof(startup) );
2609 startup.cb = sizeof(startup);
2610 if (params->lpCmdShow)
2612 startup.dwFlags = STARTF_USESHOWWINDOW;
2613 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2616 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2617 params->lpEnvAddress, NULL, &startup, &info ))
2619 /* Give 30 seconds to the app to come up */
2620 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2621 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2622 ret = 33;
2623 /* Close off the handles */
2624 CloseHandle( info.hThread );
2625 CloseHandle( info.hProcess );
2627 else if ((ret = GetLastError()) >= 32)
2629 FIXME("Strange error set by CreateProcess: %u\n", ret );
2630 ret = 11;
2633 HeapFree( GetProcessHeap(), 0, cmdline );
2634 return ret;
2638 /******************************************************************************
2639 * TerminateProcess (KERNEL32.@)
2641 * Terminates a process.
2643 * PARAMS
2644 * handle [I] Process to terminate.
2645 * exit_code [I] Exit code.
2647 * RETURNS
2648 * Success: TRUE.
2649 * Failure: FALSE, check GetLastError().
2651 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2653 NTSTATUS status;
2655 if (!handle)
2657 SetLastError( ERROR_INVALID_HANDLE );
2658 return FALSE;
2661 status = NtTerminateProcess( handle, exit_code );
2662 if (status) SetLastError( RtlNtStatusToDosError(status) );
2663 return !status;
2666 /***********************************************************************
2667 * ExitProcess (KERNEL32.@)
2669 * Exits the current process.
2671 * PARAMS
2672 * status [I] Status code to exit with.
2674 * RETURNS
2675 * Nothing.
2677 #ifdef __i386__
2678 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2679 "pushl %ebp\n\t"
2680 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2681 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2682 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2683 "pushl 8(%ebp)\n\t"
2684 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
2685 "leave\n\t"
2686 "ret $4" )
2687 #else
2689 void WINAPI ExitProcess( DWORD status )
2691 RtlExitUserProcess( status );
2694 #endif
2696 /***********************************************************************
2697 * GetExitCodeProcess [KERNEL32.@]
2699 * Gets termination status of specified process.
2701 * PARAMS
2702 * hProcess [in] Handle to the process.
2703 * lpExitCode [out] Address to receive termination status.
2705 * RETURNS
2706 * Success: TRUE
2707 * Failure: FALSE
2709 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2711 NTSTATUS status;
2712 PROCESS_BASIC_INFORMATION pbi;
2714 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2715 sizeof(pbi), NULL);
2716 if (status == STATUS_SUCCESS)
2718 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2719 return TRUE;
2721 SetLastError( RtlNtStatusToDosError(status) );
2722 return FALSE;
2726 /***********************************************************************
2727 * SetErrorMode (KERNEL32.@)
2729 UINT WINAPI SetErrorMode( UINT mode )
2731 UINT old;
2733 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2734 &old, sizeof(old), NULL );
2735 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2736 &mode, sizeof(mode) );
2737 return old;
2740 /***********************************************************************
2741 * GetErrorMode (KERNEL32.@)
2743 UINT WINAPI GetErrorMode( void )
2745 UINT mode;
2747 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2748 &mode, sizeof(mode), NULL );
2749 return mode;
2752 /**********************************************************************
2753 * TlsAlloc [KERNEL32.@]
2755 * Allocates a thread local storage index.
2757 * RETURNS
2758 * Success: TLS index.
2759 * Failure: 0xFFFFFFFF
2761 DWORD WINAPI TlsAlloc( void )
2763 DWORD index;
2764 PEB * const peb = NtCurrentTeb()->Peb;
2766 RtlAcquirePebLock();
2767 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2768 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2769 else
2771 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2772 if (index != ~0U)
2774 if (!NtCurrentTeb()->TlsExpansionSlots &&
2775 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2776 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2778 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2779 index = ~0U;
2780 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2782 else
2784 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2785 index += TLS_MINIMUM_AVAILABLE;
2788 else SetLastError( ERROR_NO_MORE_ITEMS );
2790 RtlReleasePebLock();
2791 return index;
2795 /**********************************************************************
2796 * TlsFree [KERNEL32.@]
2798 * Releases a thread local storage index, making it available for reuse.
2800 * PARAMS
2801 * index [in] TLS index to free.
2803 * RETURNS
2804 * Success: TRUE
2805 * Failure: FALSE
2807 BOOL WINAPI TlsFree( DWORD index )
2809 BOOL ret;
2811 RtlAcquirePebLock();
2812 if (index >= TLS_MINIMUM_AVAILABLE)
2814 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2815 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2817 else
2819 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2820 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2822 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2823 else SetLastError( ERROR_INVALID_PARAMETER );
2824 RtlReleasePebLock();
2825 return ret;
2829 /**********************************************************************
2830 * TlsGetValue [KERNEL32.@]
2832 * Gets value in a thread's TLS slot.
2834 * PARAMS
2835 * index [in] TLS index to retrieve value for.
2837 * RETURNS
2838 * Success: Value stored in calling thread's TLS slot for index.
2839 * Failure: 0 and GetLastError() returns NO_ERROR.
2841 LPVOID WINAPI TlsGetValue( DWORD index )
2843 LPVOID ret;
2845 if (index < TLS_MINIMUM_AVAILABLE)
2847 ret = NtCurrentTeb()->TlsSlots[index];
2849 else
2851 index -= TLS_MINIMUM_AVAILABLE;
2852 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2854 SetLastError( ERROR_INVALID_PARAMETER );
2855 return NULL;
2857 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2858 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2860 SetLastError( ERROR_SUCCESS );
2861 return ret;
2865 /**********************************************************************
2866 * TlsSetValue [KERNEL32.@]
2868 * Stores a value in the thread's TLS slot.
2870 * PARAMS
2871 * index [in] TLS index to set value for.
2872 * value [in] Value to be stored.
2874 * RETURNS
2875 * Success: TRUE
2876 * Failure: FALSE
2878 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2880 if (index < TLS_MINIMUM_AVAILABLE)
2882 NtCurrentTeb()->TlsSlots[index] = value;
2884 else
2886 index -= TLS_MINIMUM_AVAILABLE;
2887 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2889 SetLastError( ERROR_INVALID_PARAMETER );
2890 return FALSE;
2892 if (!NtCurrentTeb()->TlsExpansionSlots &&
2893 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2894 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2896 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2897 return FALSE;
2899 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2901 return TRUE;
2905 /***********************************************************************
2906 * GetProcessFlags (KERNEL32.@)
2908 DWORD WINAPI GetProcessFlags( DWORD processid )
2910 IMAGE_NT_HEADERS *nt;
2911 DWORD flags = 0;
2913 if (processid && processid != GetCurrentProcessId()) return 0;
2915 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2917 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2918 flags |= PDB32_CONSOLE_PROC;
2920 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2921 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2922 return flags;
2926 /*********************************************************************
2927 * OpenProcess (KERNEL32.@)
2929 * Opens a handle to a process.
2931 * PARAMS
2932 * access [I] Desired access rights assigned to the returned handle.
2933 * inherit [I] Determines whether or not child processes will inherit the handle.
2934 * id [I] Process identifier of the process to get a handle to.
2936 * RETURNS
2937 * Success: Valid handle to the specified process.
2938 * Failure: NULL, check GetLastError().
2940 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2942 NTSTATUS status;
2943 HANDLE handle;
2944 OBJECT_ATTRIBUTES attr;
2945 CLIENT_ID cid;
2947 cid.UniqueProcess = ULongToHandle(id);
2948 cid.UniqueThread = 0; /* FIXME ? */
2950 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2951 attr.RootDirectory = NULL;
2952 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2953 attr.SecurityDescriptor = NULL;
2954 attr.SecurityQualityOfService = NULL;
2955 attr.ObjectName = NULL;
2957 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2959 status = NtOpenProcess(&handle, access, &attr, &cid);
2960 if (status != STATUS_SUCCESS)
2962 SetLastError( RtlNtStatusToDosError(status) );
2963 return NULL;
2965 return handle;
2969 /*********************************************************************
2970 * GetProcessId (KERNEL32.@)
2972 * Gets the a unique identifier of a process.
2974 * PARAMS
2975 * hProcess [I] Handle to the process.
2977 * RETURNS
2978 * Success: TRUE.
2979 * Failure: FALSE, check GetLastError().
2981 * NOTES
2983 * The identifier is unique only on the machine and only until the process
2984 * exits (including system shutdown).
2986 DWORD WINAPI GetProcessId( HANDLE hProcess )
2988 NTSTATUS status;
2989 PROCESS_BASIC_INFORMATION pbi;
2991 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2992 sizeof(pbi), NULL);
2993 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2994 SetLastError( RtlNtStatusToDosError(status) );
2995 return 0;
2999 /*********************************************************************
3000 * CloseHandle (KERNEL32.@)
3002 * Closes a handle.
3004 * PARAMS
3005 * handle [I] Handle to close.
3007 * RETURNS
3008 * Success: TRUE.
3009 * Failure: FALSE, check GetLastError().
3011 BOOL WINAPI CloseHandle( HANDLE handle )
3013 NTSTATUS status;
3015 /* stdio handles need special treatment */
3016 if (handle == (HANDLE)STD_INPUT_HANDLE)
3017 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
3018 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
3019 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
3020 else if (handle == (HANDLE)STD_ERROR_HANDLE)
3021 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
3023 if (is_console_handle(handle))
3024 return CloseConsoleHandle(handle);
3026 status = NtClose( handle );
3027 if (status) SetLastError( RtlNtStatusToDosError(status) );
3028 return !status;
3032 /*********************************************************************
3033 * GetHandleInformation (KERNEL32.@)
3035 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
3037 OBJECT_DATA_INFORMATION info;
3038 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
3040 if (status) SetLastError( RtlNtStatusToDosError(status) );
3041 else if (flags)
3043 *flags = 0;
3044 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3045 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3047 return !status;
3051 /*********************************************************************
3052 * SetHandleInformation (KERNEL32.@)
3054 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3056 OBJECT_DATA_INFORMATION info;
3057 NTSTATUS status;
3059 /* if not setting both fields, retrieve current value first */
3060 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3061 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3063 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3065 SetLastError( RtlNtStatusToDosError(status) );
3066 return FALSE;
3069 if (mask & HANDLE_FLAG_INHERIT)
3070 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3071 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3072 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3074 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3075 if (status) SetLastError( RtlNtStatusToDosError(status) );
3076 return !status;
3080 /*********************************************************************
3081 * DuplicateHandle (KERNEL32.@)
3083 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3084 HANDLE dest_process, HANDLE *dest,
3085 DWORD access, BOOL inherit, DWORD options )
3087 NTSTATUS status;
3089 if (is_console_handle(source))
3091 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3092 if (source_process != dest_process ||
3093 source_process != GetCurrentProcess())
3095 SetLastError(ERROR_INVALID_PARAMETER);
3096 return FALSE;
3098 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3099 return (*dest != INVALID_HANDLE_VALUE);
3101 status = NtDuplicateObject( source_process, source, dest_process, dest,
3102 access, inherit ? OBJ_INHERIT : 0, options );
3103 if (status) SetLastError( RtlNtStatusToDosError(status) );
3104 return !status;
3108 /***********************************************************************
3109 * ConvertToGlobalHandle (KERNEL32.@)
3111 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3113 HANDLE ret = INVALID_HANDLE_VALUE;
3114 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3115 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3116 return ret;
3120 /***********************************************************************
3121 * SetHandleContext (KERNEL32.@)
3123 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3125 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3126 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3127 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3128 return FALSE;
3132 /***********************************************************************
3133 * GetHandleContext (KERNEL32.@)
3135 DWORD WINAPI GetHandleContext(HANDLE hnd)
3137 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3138 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3139 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3140 return 0;
3144 /***********************************************************************
3145 * CreateSocketHandle (KERNEL32.@)
3147 HANDLE WINAPI CreateSocketHandle(void)
3149 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3150 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3151 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3152 return INVALID_HANDLE_VALUE;
3156 /***********************************************************************
3157 * SetPriorityClass (KERNEL32.@)
3159 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3161 NTSTATUS status;
3162 PROCESS_PRIORITY_CLASS ppc;
3164 ppc.Foreground = FALSE;
3165 switch (priorityclass)
3167 case IDLE_PRIORITY_CLASS:
3168 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3169 case BELOW_NORMAL_PRIORITY_CLASS:
3170 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3171 case NORMAL_PRIORITY_CLASS:
3172 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3173 case ABOVE_NORMAL_PRIORITY_CLASS:
3174 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3175 case HIGH_PRIORITY_CLASS:
3176 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3177 case REALTIME_PRIORITY_CLASS:
3178 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3179 default:
3180 SetLastError(ERROR_INVALID_PARAMETER);
3181 return FALSE;
3184 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3185 &ppc, sizeof(ppc));
3187 if (status != STATUS_SUCCESS)
3189 SetLastError( RtlNtStatusToDosError(status) );
3190 return FALSE;
3192 return TRUE;
3196 /***********************************************************************
3197 * GetPriorityClass (KERNEL32.@)
3199 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3201 NTSTATUS status;
3202 PROCESS_BASIC_INFORMATION pbi;
3204 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3205 sizeof(pbi), NULL);
3206 if (status != STATUS_SUCCESS)
3208 SetLastError( RtlNtStatusToDosError(status) );
3209 return 0;
3211 switch (pbi.BasePriority)
3213 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3214 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3215 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3216 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3217 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3218 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3220 SetLastError( ERROR_INVALID_PARAMETER );
3221 return 0;
3225 /***********************************************************************
3226 * SetProcessAffinityMask (KERNEL32.@)
3228 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3230 NTSTATUS status;
3232 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3233 &affmask, sizeof(DWORD_PTR));
3234 if (status)
3236 SetLastError( RtlNtStatusToDosError(status) );
3237 return FALSE;
3239 return TRUE;
3243 /**********************************************************************
3244 * GetProcessAffinityMask (KERNEL32.@)
3246 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3248 NTSTATUS status = STATUS_SUCCESS;
3250 if (system_mask) *system_mask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
3251 if (process_mask)
3253 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3254 process_mask, sizeof(*process_mask), NULL )))
3255 SetLastError( RtlNtStatusToDosError(status) );
3257 return !status;
3261 /***********************************************************************
3262 * GetProcessVersion (KERNEL32.@)
3264 DWORD WINAPI GetProcessVersion( DWORD pid )
3266 HANDLE process;
3267 NTSTATUS status;
3268 PROCESS_BASIC_INFORMATION pbi;
3269 SIZE_T count;
3270 PEB peb;
3271 IMAGE_DOS_HEADER dos;
3272 IMAGE_NT_HEADERS nt;
3273 DWORD ver = 0;
3275 if (!pid || pid == GetCurrentProcessId())
3277 IMAGE_NT_HEADERS *pnt;
3279 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3280 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3281 pnt->OptionalHeader.MinorSubsystemVersion);
3282 return 0;
3285 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3286 if (!process) return 0;
3288 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3289 if (status) goto err;
3291 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3292 if (status || count != sizeof(peb)) goto err;
3294 memset(&dos, 0, sizeof(dos));
3295 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3296 if (status || count != sizeof(dos)) goto err;
3297 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3299 memset(&nt, 0, sizeof(nt));
3300 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3301 if (status || count != sizeof(nt)) goto err;
3302 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3304 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3306 err:
3307 CloseHandle(process);
3309 if (status != STATUS_SUCCESS)
3310 SetLastError(RtlNtStatusToDosError(status));
3312 return ver;
3316 /***********************************************************************
3317 * SetProcessWorkingSetSize [KERNEL32.@]
3318 * Sets the min/max working set sizes for a specified process.
3320 * PARAMS
3321 * hProcess [I] Handle to the process of interest
3322 * minset [I] Specifies minimum working set size
3323 * maxset [I] Specifies maximum working set size
3325 * RETURNS
3326 * Success: TRUE
3327 * Failure: FALSE
3329 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3330 SIZE_T maxset)
3332 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3333 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3334 /* Trim the working set to zero */
3335 /* Swap the process out of physical RAM */
3337 return TRUE;
3340 /***********************************************************************
3341 * K32EmptyWorkingSet (KERNEL32.@)
3343 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3345 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3348 /***********************************************************************
3349 * GetProcessWorkingSetSize (KERNEL32.@)
3351 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3352 PSIZE_T maxset)
3354 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3355 /* 32 MB working set size */
3356 if (minset) *minset = 32*1024*1024;
3357 if (maxset) *maxset = 32*1024*1024;
3358 return TRUE;
3362 /***********************************************************************
3363 * SetProcessShutdownParameters (KERNEL32.@)
3365 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3367 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3368 shutdown_flags = flags;
3369 shutdown_priority = level;
3370 return TRUE;
3374 /***********************************************************************
3375 * GetProcessShutdownParameters (KERNEL32.@)
3378 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3380 *lpdwLevel = shutdown_priority;
3381 *lpdwFlags = shutdown_flags;
3382 return TRUE;
3386 /***********************************************************************
3387 * GetProcessPriorityBoost (KERNEL32.@)
3389 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3391 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3393 /* Report that no boost is present.. */
3394 *pDisablePriorityBoost = FALSE;
3396 return TRUE;
3399 /***********************************************************************
3400 * SetProcessPriorityBoost (KERNEL32.@)
3402 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3404 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3405 /* Say we can do it. I doubt the program will notice that we don't. */
3406 return TRUE;
3410 /***********************************************************************
3411 * ReadProcessMemory (KERNEL32.@)
3413 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3414 SIZE_T *bytes_read )
3416 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3417 if (status) SetLastError( RtlNtStatusToDosError(status) );
3418 return !status;
3422 /***********************************************************************
3423 * WriteProcessMemory (KERNEL32.@)
3425 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3426 SIZE_T *bytes_written )
3428 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3429 if (status) SetLastError( RtlNtStatusToDosError(status) );
3430 return !status;
3434 /****************************************************************************
3435 * FlushInstructionCache (KERNEL32.@)
3437 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3439 NTSTATUS status;
3440 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3441 if (status) SetLastError( RtlNtStatusToDosError(status) );
3442 return !status;
3446 /******************************************************************
3447 * GetProcessIoCounters (KERNEL32.@)
3449 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3451 NTSTATUS status;
3453 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3454 ioc, sizeof(*ioc), NULL);
3455 if (status) SetLastError( RtlNtStatusToDosError(status) );
3456 return !status;
3459 /******************************************************************
3460 * GetProcessHandleCount (KERNEL32.@)
3462 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3464 NTSTATUS status;
3466 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3467 cnt, sizeof(*cnt), NULL);
3468 if (status) SetLastError( RtlNtStatusToDosError(status) );
3469 return !status;
3472 /******************************************************************
3473 * QueryFullProcessImageNameA (KERNEL32.@)
3475 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3477 BOOL retval;
3478 DWORD pdwSizeW = *pdwSize;
3479 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3481 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3483 if(retval)
3484 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3485 lpExeName, *pdwSize, NULL, NULL));
3486 if(retval)
3487 *pdwSize = strlen(lpExeName);
3489 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3490 return retval;
3493 /******************************************************************
3494 * QueryFullProcessImageNameW (KERNEL32.@)
3496 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3498 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3499 UNICODE_STRING *dynamic_buffer = NULL;
3500 UNICODE_STRING *result = NULL;
3501 NTSTATUS status;
3502 DWORD needed;
3504 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3505 * is a DOS path and we depend on this. */
3506 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3507 sizeof(buffer) - sizeof(WCHAR), &needed);
3508 if (status == STATUS_INFO_LENGTH_MISMATCH)
3510 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3511 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3512 result = dynamic_buffer;
3514 else
3515 result = (PUNICODE_STRING)buffer;
3517 if (status) goto cleanup;
3519 if (dwFlags & PROCESS_NAME_NATIVE)
3521 WCHAR drive[3];
3522 WCHAR device[1024];
3523 DWORD ntlen, devlen;
3525 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3527 /* We cannot convert it to an NT device path so fail */
3528 status = STATUS_NO_SUCH_DEVICE;
3529 goto cleanup;
3532 /* Find this drive's NT device path */
3533 drive[0] = result->Buffer[0];
3534 drive[1] = ':';
3535 drive[2] = 0;
3536 if (!QueryDosDeviceW(drive, device, sizeof(device)/sizeof(*device)))
3538 status = STATUS_NO_SUCH_DEVICE;
3539 goto cleanup;
3542 devlen = lstrlenW(device);
3543 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3544 if (ntlen + 1 > *pdwSize)
3546 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3547 return 0;
3549 *pdwSize = ntlen;
3551 memcpy(lpExeName, device, devlen * sizeof(*device));
3552 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3553 lpExeName[*pdwSize] = 0;
3554 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3556 else
3558 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3560 status = STATUS_BUFFER_TOO_SMALL;
3561 goto cleanup;
3564 *pdwSize = result->Length/sizeof(WCHAR);
3565 memcpy( lpExeName, result->Buffer, result->Length );
3566 lpExeName[*pdwSize] = 0;
3569 cleanup:
3570 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3571 if (status) SetLastError( RtlNtStatusToDosError(status) );
3572 return !status;
3575 /***********************************************************************
3576 * K32GetProcessImageFileNameA (KERNEL32.@)
3578 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3580 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3583 /***********************************************************************
3584 * K32GetProcessImageFileNameW (KERNEL32.@)
3586 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3588 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3591 /***********************************************************************
3592 * K32EnumProcesses (KERNEL32.@)
3594 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3596 SYSTEM_PROCESS_INFORMATION *spi;
3597 ULONG size = 0x4000;
3598 void *buf = NULL;
3599 NTSTATUS status;
3601 do {
3602 size *= 2;
3603 HeapFree(GetProcessHeap(), 0, buf);
3604 buf = HeapAlloc(GetProcessHeap(), 0, size);
3605 if (!buf)
3606 return FALSE;
3608 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3609 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3611 if (status != STATUS_SUCCESS)
3613 HeapFree(GetProcessHeap(), 0, buf);
3614 SetLastError(RtlNtStatusToDosError(status));
3615 return FALSE;
3618 spi = buf;
3620 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3622 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3623 *lpcbUsed += sizeof(DWORD);
3625 if (spi->NextEntryOffset == 0)
3626 break;
3628 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3631 HeapFree(GetProcessHeap(), 0, buf);
3632 return TRUE;
3635 /***********************************************************************
3636 * K32QueryWorkingSet (KERNEL32.@)
3638 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3640 NTSTATUS status;
3642 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3644 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3646 if (status)
3648 SetLastError( RtlNtStatusToDosError( status ) );
3649 return FALSE;
3651 return TRUE;
3654 /***********************************************************************
3655 * K32QueryWorkingSetEx (KERNEL32.@)
3657 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3659 NTSTATUS status;
3661 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3663 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3665 if (status)
3667 SetLastError( RtlNtStatusToDosError( status ) );
3668 return FALSE;
3670 return TRUE;
3673 /***********************************************************************
3674 * K32GetProcessMemoryInfo (KERNEL32.@)
3676 * Retrieve memory usage information for a given process
3679 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3680 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3682 NTSTATUS status;
3683 VM_COUNTERS vmc;
3685 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3687 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3688 return FALSE;
3691 status = NtQueryInformationProcess(process, ProcessVmCounters,
3692 &vmc, sizeof(vmc), NULL);
3694 if (status)
3696 SetLastError(RtlNtStatusToDosError(status));
3697 return FALSE;
3700 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3701 pmc->PageFaultCount = vmc.PageFaultCount;
3702 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3703 pmc->WorkingSetSize = vmc.WorkingSetSize;
3704 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3705 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3706 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3707 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3708 pmc->PagefileUsage = vmc.PagefileUsage;
3709 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3711 return TRUE;
3714 /***********************************************************************
3715 * ProcessIdToSessionId (KERNEL32.@)
3716 * This function is available on Terminal Server 4SP4 and Windows 2000
3718 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3720 /* According to MSDN, if the calling process is not in a terminal
3721 * services environment, then the sessionid returned is zero.
3723 *sessionid_ptr = 0;
3724 return TRUE;
3728 /***********************************************************************
3729 * RegisterServiceProcess (KERNEL32.@)
3731 * A service process calls this function to ensure that it continues to run
3732 * even after a user logged off.
3734 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3736 /* I don't think that Wine needs to do anything in this function */
3737 return 1; /* success */
3741 /**********************************************************************
3742 * IsWow64Process (KERNEL32.@)
3744 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3746 ULONG pbi;
3747 NTSTATUS status;
3749 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3751 if (status != STATUS_SUCCESS)
3753 SetLastError( RtlNtStatusToDosError( status ) );
3754 return FALSE;
3756 *Wow64Process = (pbi != 0);
3757 return TRUE;
3761 /***********************************************************************
3762 * GetCurrentProcess (KERNEL32.@)
3764 * Get a handle to the current process.
3766 * PARAMS
3767 * None.
3769 * RETURNS
3770 * A handle representing the current process.
3772 #undef GetCurrentProcess
3773 HANDLE WINAPI GetCurrentProcess(void)
3775 return (HANDLE)~(ULONG_PTR)0;
3778 /***********************************************************************
3779 * GetLogicalProcessorInformation (KERNEL32.@)
3781 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3783 NTSTATUS status;
3785 TRACE("(%p,%p)\n", buffer, pBufLen);
3787 if(!pBufLen)
3789 SetLastError(ERROR_INVALID_PARAMETER);
3790 return FALSE;
3793 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
3795 if (status == STATUS_INFO_LENGTH_MISMATCH)
3797 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3798 return FALSE;
3800 if (status != STATUS_SUCCESS)
3802 SetLastError( RtlNtStatusToDosError( status ) );
3803 return FALSE;
3805 return TRUE;
3808 /***********************************************************************
3809 * GetLogicalProcessorInformationEx (KERNEL32.@)
3811 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer, PDWORD pBufLen)
3813 FIXME("(%u,%p,%p): stub\n", relationship, buffer, pBufLen);
3814 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3815 return FALSE;
3818 /***********************************************************************
3819 * CmdBatNotification (KERNEL32.@)
3821 * Notifies the system that a batch file has started or finished.
3823 * PARAMS
3824 * bBatchRunning [I] TRUE if a batch file has started or
3825 * FALSE if a batch file has finished executing.
3827 * RETURNS
3828 * Unknown.
3830 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3832 FIXME("%d\n", bBatchRunning);
3833 return FALSE;
3837 /***********************************************************************
3838 * RegisterApplicationRestart (KERNEL32.@)
3840 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3842 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3844 return S_OK;
3847 /**********************************************************************
3848 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3850 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3852 static int once;
3853 if (!once++) FIXME("stub\n");
3854 return 0;
3857 /**********************************************************************
3858 * GetSystemDEPPolicy (KERNEL32.@)
3860 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3862 FIXME("stub\n");
3863 return OptIn;
3866 /**********************************************************************
3867 * SetProcessDEPPolicy (KERNEL32.@)
3869 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3871 FIXME("(%d): stub\n", newDEP);
3872 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3873 return FALSE;
3876 /**********************************************************************
3877 * ApplicationRecoveryFinished (KERNEL32.@)
3879 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
3881 FIXME(": stub\n");
3882 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3885 /**********************************************************************
3886 * ApplicationRecoveryInProgress (KERNEL32.@)
3888 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
3890 FIXME(":%p stub\n", canceled);
3891 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3892 return E_FAIL;
3895 /**********************************************************************
3896 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3898 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
3900 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
3901 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3902 return E_FAIL;
3905 /**********************************************************************
3906 * GetNumaHighestNodeNumber (KERNEL32.@)
3908 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
3910 FIXME("(%p): stub\n", highestnode);
3911 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3912 return FALSE;
3915 /**********************************************************************
3916 * GetNumaNodeProcessorMask (KERNEL32.@)
3918 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
3920 FIXME("(%c %p): stub\n", node, mask);
3921 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3922 return FALSE;
3925 /**********************************************************************
3926 * GetNumaAvailableMemoryNode (KERNEL32.@)
3928 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
3930 FIXME("(%c %p): stub\n", node, available_bytes);
3931 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3932 return FALSE;
3935 /**********************************************************************
3936 * GetProcessDEPPolicy (KERNEL32.@)
3938 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
3940 FIXME("(%p %p %p): stub\n", process, flags, permanent);
3941 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3942 return FALSE;
3945 /**********************************************************************
3946 * FlushProcessWriteBuffers (KERNEL32.@)
3948 VOID WINAPI FlushProcessWriteBuffers(void)
3950 static int once = 0;
3952 if (!once++)
3953 FIXME(": stub\n");