d3d8: Get rid of the format switching code in d3d8_device_CopyRects().
[wine.git] / dlls / kernel32 / process.c
blob301c64abe4cf858642134d421dffe2fd9ca56780
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%s)\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 (binary_info.flags & BINARY_FLAG_FAKEDLL) ? ", fakedll" : "" );
2349 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2350 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2351 break;
2352 case BINARY_OS216:
2353 case BINARY_WIN16:
2354 case BINARY_DOS:
2355 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2356 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2357 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2358 break;
2359 case BINARY_UNIX_LIB:
2360 TRACE( "starting %s as %d-bit Winelib app\n",
2361 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2362 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2363 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2364 break;
2365 case BINARY_UNKNOWN:
2366 /* check for .com or .bat extension */
2367 if ((p = strrchrW( name, '.' )))
2369 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2371 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2372 binary_info.type = BINARY_DOS;
2373 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2374 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2375 inherit, flags, startup_info, info, unixdir,
2376 &binary_info, FALSE );
2377 break;
2379 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2381 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2382 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2383 inherit, flags, startup_info, info );
2384 break;
2387 /* fall through */
2388 case BINARY_UNIX_EXE:
2390 /* unknown file, try as unix executable */
2391 char *unix_name;
2393 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2395 if ((unix_name = wine_get_unix_file_name( name )))
2397 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2398 HeapFree( GetProcessHeap(), 0, unix_name );
2401 break;
2403 if (hFile) CloseHandle( hFile );
2405 done:
2406 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2407 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2408 HeapFree( GetProcessHeap(), 0, unixdir );
2409 if (retv)
2410 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2411 return retv;
2415 /**********************************************************************
2416 * CreateProcessA (KERNEL32.@)
2418 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2419 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2420 DWORD flags, LPVOID env, LPCSTR cur_dir,
2421 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2423 BOOL ret = FALSE;
2424 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2425 UNICODE_STRING desktopW, titleW;
2426 STARTUPINFOW infoW;
2428 desktopW.Buffer = NULL;
2429 titleW.Buffer = NULL;
2430 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2431 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2432 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2434 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2435 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2437 memcpy( &infoW, startup_info, sizeof(infoW) );
2438 infoW.lpDesktop = desktopW.Buffer;
2439 infoW.lpTitle = titleW.Buffer;
2441 if (startup_info->lpReserved)
2442 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2443 debugstr_a(startup_info->lpReserved));
2445 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2446 inherit, flags, env, cur_dirW, &infoW, info );
2447 done:
2448 HeapFree( GetProcessHeap(), 0, app_nameW );
2449 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2450 HeapFree( GetProcessHeap(), 0, cur_dirW );
2451 RtlFreeUnicodeString( &desktopW );
2452 RtlFreeUnicodeString( &titleW );
2453 return ret;
2457 /**********************************************************************
2458 * CreateProcessW (KERNEL32.@)
2460 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2461 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2462 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2463 LPPROCESS_INFORMATION info )
2465 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2466 inherit, flags, env, cur_dir, startup_info, info);
2470 /**********************************************************************
2471 * exec_process
2473 static void exec_process( LPCWSTR name )
2475 HANDLE hFile;
2476 WCHAR *p;
2477 STARTUPINFOW startup_info;
2478 PROCESS_INFORMATION info;
2479 struct binary_info binary_info;
2481 hFile = open_exe_file( name, &binary_info );
2482 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2484 memset( &startup_info, 0, sizeof(startup_info) );
2485 startup_info.cb = sizeof(startup_info);
2487 /* Determine executable type */
2489 if (binary_info.flags & BINARY_FLAG_DLL) return;
2490 switch (binary_info.type)
2492 case BINARY_PE:
2493 TRACE( "starting %s as Win%d binary (%p-%p, arch %04x)\n",
2494 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2495 binary_info.res_start, binary_info.res_end, binary_info.arch );
2496 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2497 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2498 break;
2499 case BINARY_UNIX_LIB:
2500 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2501 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2502 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2503 break;
2504 case BINARY_UNKNOWN:
2505 /* check for .com or .pif extension */
2506 if (!(p = strrchrW( name, '.' ))) break;
2507 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2508 binary_info.type = BINARY_DOS;
2509 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2510 /* fall through */
2511 case BINARY_OS216:
2512 case BINARY_WIN16:
2513 case BINARY_DOS:
2514 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2515 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2516 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2517 break;
2518 default:
2519 break;
2521 CloseHandle( hFile );
2525 /***********************************************************************
2526 * wait_input_idle
2528 * Wrapper to call WaitForInputIdle USER function
2530 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2532 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2534 HMODULE mod = GetModuleHandleA( "user32.dll" );
2535 if (mod)
2537 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2538 if (ptr) return ptr( process, timeout );
2540 return 0;
2544 /***********************************************************************
2545 * WinExec (KERNEL32.@)
2547 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2549 PROCESS_INFORMATION info;
2550 STARTUPINFOA startup;
2551 char *cmdline;
2552 UINT ret;
2554 memset( &startup, 0, sizeof(startup) );
2555 startup.cb = sizeof(startup);
2556 startup.dwFlags = STARTF_USESHOWWINDOW;
2557 startup.wShowWindow = nCmdShow;
2559 /* cmdline needs to be writable for CreateProcess */
2560 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2561 strcpy( cmdline, lpCmdLine );
2563 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2564 0, NULL, NULL, &startup, &info ))
2566 /* Give 30 seconds to the app to come up */
2567 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2568 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2569 ret = 33;
2570 /* Close off the handles */
2571 CloseHandle( info.hThread );
2572 CloseHandle( info.hProcess );
2574 else if ((ret = GetLastError()) >= 32)
2576 FIXME("Strange error set by CreateProcess: %d\n", ret );
2577 ret = 11;
2579 HeapFree( GetProcessHeap(), 0, cmdline );
2580 return ret;
2584 /**********************************************************************
2585 * LoadModule (KERNEL32.@)
2587 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2589 LOADPARMS32 *params = paramBlock;
2590 PROCESS_INFORMATION info;
2591 STARTUPINFOA startup;
2592 DWORD ret;
2593 LPSTR cmdline, p;
2594 char filename[MAX_PATH];
2595 BYTE len;
2597 if (!name) return ERROR_FILE_NOT_FOUND;
2599 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2600 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2601 return GetLastError();
2603 len = (BYTE)params->lpCmdLine[0];
2604 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2605 return ERROR_NOT_ENOUGH_MEMORY;
2607 strcpy( cmdline, filename );
2608 p = cmdline + strlen(cmdline);
2609 *p++ = ' ';
2610 memcpy( p, params->lpCmdLine + 1, len );
2611 p[len] = 0;
2613 memset( &startup, 0, sizeof(startup) );
2614 startup.cb = sizeof(startup);
2615 if (params->lpCmdShow)
2617 startup.dwFlags = STARTF_USESHOWWINDOW;
2618 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2621 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2622 params->lpEnvAddress, NULL, &startup, &info ))
2624 /* Give 30 seconds to the app to come up */
2625 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2626 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2627 ret = 33;
2628 /* Close off the handles */
2629 CloseHandle( info.hThread );
2630 CloseHandle( info.hProcess );
2632 else if ((ret = GetLastError()) >= 32)
2634 FIXME("Strange error set by CreateProcess: %u\n", ret );
2635 ret = 11;
2638 HeapFree( GetProcessHeap(), 0, cmdline );
2639 return ret;
2643 /******************************************************************************
2644 * TerminateProcess (KERNEL32.@)
2646 * Terminates a process.
2648 * PARAMS
2649 * handle [I] Process to terminate.
2650 * exit_code [I] Exit code.
2652 * RETURNS
2653 * Success: TRUE.
2654 * Failure: FALSE, check GetLastError().
2656 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2658 NTSTATUS status;
2660 if (!handle)
2662 SetLastError( ERROR_INVALID_HANDLE );
2663 return FALSE;
2666 status = NtTerminateProcess( handle, exit_code );
2667 if (status) SetLastError( RtlNtStatusToDosError(status) );
2668 return !status;
2671 /***********************************************************************
2672 * ExitProcess (KERNEL32.@)
2674 * Exits the current process.
2676 * PARAMS
2677 * status [I] Status code to exit with.
2679 * RETURNS
2680 * Nothing.
2682 #ifdef __i386__
2683 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2684 "pushl %ebp\n\t"
2685 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2686 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2687 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2688 "pushl 8(%ebp)\n\t"
2689 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
2690 "leave\n\t"
2691 "ret $4" )
2692 #else
2694 void WINAPI ExitProcess( DWORD status )
2696 RtlExitUserProcess( status );
2699 #endif
2701 /***********************************************************************
2702 * GetExitCodeProcess [KERNEL32.@]
2704 * Gets termination status of specified process.
2706 * PARAMS
2707 * hProcess [in] Handle to the process.
2708 * lpExitCode [out] Address to receive termination status.
2710 * RETURNS
2711 * Success: TRUE
2712 * Failure: FALSE
2714 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2716 NTSTATUS status;
2717 PROCESS_BASIC_INFORMATION pbi;
2719 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2720 sizeof(pbi), NULL);
2721 if (status == STATUS_SUCCESS)
2723 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2724 return TRUE;
2726 SetLastError( RtlNtStatusToDosError(status) );
2727 return FALSE;
2731 /***********************************************************************
2732 * SetErrorMode (KERNEL32.@)
2734 UINT WINAPI SetErrorMode( UINT mode )
2736 UINT old;
2738 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2739 &old, sizeof(old), NULL );
2740 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2741 &mode, sizeof(mode) );
2742 return old;
2745 /***********************************************************************
2746 * GetErrorMode (KERNEL32.@)
2748 UINT WINAPI GetErrorMode( void )
2750 UINT mode;
2752 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2753 &mode, sizeof(mode), NULL );
2754 return mode;
2757 /**********************************************************************
2758 * TlsAlloc [KERNEL32.@]
2760 * Allocates a thread local storage index.
2762 * RETURNS
2763 * Success: TLS index.
2764 * Failure: 0xFFFFFFFF
2766 DWORD WINAPI TlsAlloc( void )
2768 DWORD index;
2769 PEB * const peb = NtCurrentTeb()->Peb;
2771 RtlAcquirePebLock();
2772 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 1 );
2773 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2774 else
2776 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2777 if (index != ~0U)
2779 if (!NtCurrentTeb()->TlsExpansionSlots &&
2780 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2781 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2783 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2784 index = ~0U;
2785 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2787 else
2789 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2790 index += TLS_MINIMUM_AVAILABLE;
2793 else SetLastError( ERROR_NO_MORE_ITEMS );
2795 RtlReleasePebLock();
2796 return index;
2800 /**********************************************************************
2801 * TlsFree [KERNEL32.@]
2803 * Releases a thread local storage index, making it available for reuse.
2805 * PARAMS
2806 * index [in] TLS index to free.
2808 * RETURNS
2809 * Success: TRUE
2810 * Failure: FALSE
2812 BOOL WINAPI TlsFree( DWORD index )
2814 BOOL ret;
2816 RtlAcquirePebLock();
2817 if (index >= TLS_MINIMUM_AVAILABLE)
2819 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2820 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2822 else
2824 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2825 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2827 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2828 else SetLastError( ERROR_INVALID_PARAMETER );
2829 RtlReleasePebLock();
2830 return ret;
2834 /**********************************************************************
2835 * TlsGetValue [KERNEL32.@]
2837 * Gets value in a thread's TLS slot.
2839 * PARAMS
2840 * index [in] TLS index to retrieve value for.
2842 * RETURNS
2843 * Success: Value stored in calling thread's TLS slot for index.
2844 * Failure: 0 and GetLastError() returns NO_ERROR.
2846 LPVOID WINAPI TlsGetValue( DWORD index )
2848 LPVOID ret;
2850 if (index < TLS_MINIMUM_AVAILABLE)
2852 ret = NtCurrentTeb()->TlsSlots[index];
2854 else
2856 index -= TLS_MINIMUM_AVAILABLE;
2857 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2859 SetLastError( ERROR_INVALID_PARAMETER );
2860 return NULL;
2862 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2863 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2865 SetLastError( ERROR_SUCCESS );
2866 return ret;
2870 /**********************************************************************
2871 * TlsSetValue [KERNEL32.@]
2873 * Stores a value in the thread's TLS slot.
2875 * PARAMS
2876 * index [in] TLS index to set value for.
2877 * value [in] Value to be stored.
2879 * RETURNS
2880 * Success: TRUE
2881 * Failure: FALSE
2883 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2885 if (index < TLS_MINIMUM_AVAILABLE)
2887 NtCurrentTeb()->TlsSlots[index] = value;
2889 else
2891 index -= TLS_MINIMUM_AVAILABLE;
2892 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2894 SetLastError( ERROR_INVALID_PARAMETER );
2895 return FALSE;
2897 if (!NtCurrentTeb()->TlsExpansionSlots &&
2898 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2899 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2901 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2902 return FALSE;
2904 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2906 return TRUE;
2910 /***********************************************************************
2911 * GetProcessFlags (KERNEL32.@)
2913 DWORD WINAPI GetProcessFlags( DWORD processid )
2915 IMAGE_NT_HEADERS *nt;
2916 DWORD flags = 0;
2918 if (processid && processid != GetCurrentProcessId()) return 0;
2920 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2922 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2923 flags |= PDB32_CONSOLE_PROC;
2925 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2926 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2927 return flags;
2931 /*********************************************************************
2932 * OpenProcess (KERNEL32.@)
2934 * Opens a handle to a process.
2936 * PARAMS
2937 * access [I] Desired access rights assigned to the returned handle.
2938 * inherit [I] Determines whether or not child processes will inherit the handle.
2939 * id [I] Process identifier of the process to get a handle to.
2941 * RETURNS
2942 * Success: Valid handle to the specified process.
2943 * Failure: NULL, check GetLastError().
2945 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2947 NTSTATUS status;
2948 HANDLE handle;
2949 OBJECT_ATTRIBUTES attr;
2950 CLIENT_ID cid;
2952 cid.UniqueProcess = ULongToHandle(id);
2953 cid.UniqueThread = 0; /* FIXME ? */
2955 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2956 attr.RootDirectory = NULL;
2957 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2958 attr.SecurityDescriptor = NULL;
2959 attr.SecurityQualityOfService = NULL;
2960 attr.ObjectName = NULL;
2962 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2964 status = NtOpenProcess(&handle, access, &attr, &cid);
2965 if (status != STATUS_SUCCESS)
2967 SetLastError( RtlNtStatusToDosError(status) );
2968 return NULL;
2970 return handle;
2974 /*********************************************************************
2975 * GetProcessId (KERNEL32.@)
2977 * Gets the a unique identifier of a process.
2979 * PARAMS
2980 * hProcess [I] Handle to the process.
2982 * RETURNS
2983 * Success: TRUE.
2984 * Failure: FALSE, check GetLastError().
2986 * NOTES
2988 * The identifier is unique only on the machine and only until the process
2989 * exits (including system shutdown).
2991 DWORD WINAPI GetProcessId( HANDLE hProcess )
2993 NTSTATUS status;
2994 PROCESS_BASIC_INFORMATION pbi;
2996 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2997 sizeof(pbi), NULL);
2998 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2999 SetLastError( RtlNtStatusToDosError(status) );
3000 return 0;
3004 /*********************************************************************
3005 * CloseHandle (KERNEL32.@)
3007 * Closes a handle.
3009 * PARAMS
3010 * handle [I] Handle to close.
3012 * RETURNS
3013 * Success: TRUE.
3014 * Failure: FALSE, check GetLastError().
3016 BOOL WINAPI CloseHandle( HANDLE handle )
3018 NTSTATUS status;
3020 /* stdio handles need special treatment */
3021 if (handle == (HANDLE)STD_INPUT_HANDLE)
3022 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
3023 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
3024 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
3025 else if (handle == (HANDLE)STD_ERROR_HANDLE)
3026 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
3028 if (is_console_handle(handle))
3029 return CloseConsoleHandle(handle);
3031 status = NtClose( handle );
3032 if (status) SetLastError( RtlNtStatusToDosError(status) );
3033 return !status;
3037 /*********************************************************************
3038 * GetHandleInformation (KERNEL32.@)
3040 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
3042 OBJECT_DATA_INFORMATION info;
3043 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
3045 if (status) SetLastError( RtlNtStatusToDosError(status) );
3046 else if (flags)
3048 *flags = 0;
3049 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3050 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3052 return !status;
3056 /*********************************************************************
3057 * SetHandleInformation (KERNEL32.@)
3059 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3061 OBJECT_DATA_INFORMATION info;
3062 NTSTATUS status;
3064 /* if not setting both fields, retrieve current value first */
3065 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3066 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3068 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3070 SetLastError( RtlNtStatusToDosError(status) );
3071 return FALSE;
3074 if (mask & HANDLE_FLAG_INHERIT)
3075 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3076 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3077 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3079 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3080 if (status) SetLastError( RtlNtStatusToDosError(status) );
3081 return !status;
3085 /*********************************************************************
3086 * DuplicateHandle (KERNEL32.@)
3088 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3089 HANDLE dest_process, HANDLE *dest,
3090 DWORD access, BOOL inherit, DWORD options )
3092 NTSTATUS status;
3094 if (is_console_handle(source))
3096 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3097 if (source_process != dest_process ||
3098 source_process != GetCurrentProcess())
3100 SetLastError(ERROR_INVALID_PARAMETER);
3101 return FALSE;
3103 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3104 return (*dest != INVALID_HANDLE_VALUE);
3106 status = NtDuplicateObject( source_process, source, dest_process, dest,
3107 access, inherit ? OBJ_INHERIT : 0, options );
3108 if (status) SetLastError( RtlNtStatusToDosError(status) );
3109 return !status;
3113 /***********************************************************************
3114 * ConvertToGlobalHandle (KERNEL32.@)
3116 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3118 HANDLE ret = INVALID_HANDLE_VALUE;
3119 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3120 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3121 return ret;
3125 /***********************************************************************
3126 * SetHandleContext (KERNEL32.@)
3128 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3130 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3131 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3132 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3133 return FALSE;
3137 /***********************************************************************
3138 * GetHandleContext (KERNEL32.@)
3140 DWORD WINAPI GetHandleContext(HANDLE hnd)
3142 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3143 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3144 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3145 return 0;
3149 /***********************************************************************
3150 * CreateSocketHandle (KERNEL32.@)
3152 HANDLE WINAPI CreateSocketHandle(void)
3154 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3155 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3156 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3157 return INVALID_HANDLE_VALUE;
3161 /***********************************************************************
3162 * SetPriorityClass (KERNEL32.@)
3164 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3166 NTSTATUS status;
3167 PROCESS_PRIORITY_CLASS ppc;
3169 ppc.Foreground = FALSE;
3170 switch (priorityclass)
3172 case IDLE_PRIORITY_CLASS:
3173 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3174 case BELOW_NORMAL_PRIORITY_CLASS:
3175 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3176 case NORMAL_PRIORITY_CLASS:
3177 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3178 case ABOVE_NORMAL_PRIORITY_CLASS:
3179 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3180 case HIGH_PRIORITY_CLASS:
3181 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3182 case REALTIME_PRIORITY_CLASS:
3183 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3184 default:
3185 SetLastError(ERROR_INVALID_PARAMETER);
3186 return FALSE;
3189 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3190 &ppc, sizeof(ppc));
3192 if (status != STATUS_SUCCESS)
3194 SetLastError( RtlNtStatusToDosError(status) );
3195 return FALSE;
3197 return TRUE;
3201 /***********************************************************************
3202 * GetPriorityClass (KERNEL32.@)
3204 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3206 NTSTATUS status;
3207 PROCESS_BASIC_INFORMATION pbi;
3209 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3210 sizeof(pbi), NULL);
3211 if (status != STATUS_SUCCESS)
3213 SetLastError( RtlNtStatusToDosError(status) );
3214 return 0;
3216 switch (pbi.BasePriority)
3218 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3219 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3220 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3221 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3222 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3223 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3225 SetLastError( ERROR_INVALID_PARAMETER );
3226 return 0;
3230 /***********************************************************************
3231 * SetProcessAffinityMask (KERNEL32.@)
3233 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3235 NTSTATUS status;
3237 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3238 &affmask, sizeof(DWORD_PTR));
3239 if (status)
3241 SetLastError( RtlNtStatusToDosError(status) );
3242 return FALSE;
3244 return TRUE;
3248 /**********************************************************************
3249 * GetProcessAffinityMask (KERNEL32.@)
3251 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3253 NTSTATUS status = STATUS_SUCCESS;
3255 if (system_mask) *system_mask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
3256 if (process_mask)
3258 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3259 process_mask, sizeof(*process_mask), NULL )))
3260 SetLastError( RtlNtStatusToDosError(status) );
3262 return !status;
3266 /***********************************************************************
3267 * GetProcessVersion (KERNEL32.@)
3269 DWORD WINAPI GetProcessVersion( DWORD pid )
3271 HANDLE process;
3272 NTSTATUS status;
3273 PROCESS_BASIC_INFORMATION pbi;
3274 SIZE_T count;
3275 PEB peb;
3276 IMAGE_DOS_HEADER dos;
3277 IMAGE_NT_HEADERS nt;
3278 DWORD ver = 0;
3280 if (!pid || pid == GetCurrentProcessId())
3282 IMAGE_NT_HEADERS *pnt;
3284 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3285 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3286 pnt->OptionalHeader.MinorSubsystemVersion);
3287 return 0;
3290 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3291 if (!process) return 0;
3293 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3294 if (status) goto err;
3296 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3297 if (status || count != sizeof(peb)) goto err;
3299 memset(&dos, 0, sizeof(dos));
3300 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3301 if (status || count != sizeof(dos)) goto err;
3302 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3304 memset(&nt, 0, sizeof(nt));
3305 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3306 if (status || count != sizeof(nt)) goto err;
3307 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3309 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3311 err:
3312 CloseHandle(process);
3314 if (status != STATUS_SUCCESS)
3315 SetLastError(RtlNtStatusToDosError(status));
3317 return ver;
3321 /***********************************************************************
3322 * SetProcessWorkingSetSize [KERNEL32.@]
3323 * Sets the min/max working set sizes for a specified process.
3325 * PARAMS
3326 * hProcess [I] Handle to the process of interest
3327 * minset [I] Specifies minimum working set size
3328 * maxset [I] Specifies maximum working set size
3330 * RETURNS
3331 * Success: TRUE
3332 * Failure: FALSE
3334 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3335 SIZE_T maxset)
3337 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3338 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3339 /* Trim the working set to zero */
3340 /* Swap the process out of physical RAM */
3342 return TRUE;
3345 /***********************************************************************
3346 * K32EmptyWorkingSet (KERNEL32.@)
3348 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3350 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3353 /***********************************************************************
3354 * GetProcessWorkingSetSize (KERNEL32.@)
3356 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3357 PSIZE_T maxset)
3359 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3360 /* 32 MB working set size */
3361 if (minset) *minset = 32*1024*1024;
3362 if (maxset) *maxset = 32*1024*1024;
3363 return TRUE;
3367 /***********************************************************************
3368 * SetProcessShutdownParameters (KERNEL32.@)
3370 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3372 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3373 shutdown_flags = flags;
3374 shutdown_priority = level;
3375 return TRUE;
3379 /***********************************************************************
3380 * GetProcessShutdownParameters (KERNEL32.@)
3383 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3385 *lpdwLevel = shutdown_priority;
3386 *lpdwFlags = shutdown_flags;
3387 return TRUE;
3391 /***********************************************************************
3392 * GetProcessPriorityBoost (KERNEL32.@)
3394 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3396 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3398 /* Report that no boost is present.. */
3399 *pDisablePriorityBoost = FALSE;
3401 return TRUE;
3404 /***********************************************************************
3405 * SetProcessPriorityBoost (KERNEL32.@)
3407 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3409 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3410 /* Say we can do it. I doubt the program will notice that we don't. */
3411 return TRUE;
3415 /***********************************************************************
3416 * ReadProcessMemory (KERNEL32.@)
3418 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3419 SIZE_T *bytes_read )
3421 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3422 if (status) SetLastError( RtlNtStatusToDosError(status) );
3423 return !status;
3427 /***********************************************************************
3428 * WriteProcessMemory (KERNEL32.@)
3430 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3431 SIZE_T *bytes_written )
3433 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3434 if (status) SetLastError( RtlNtStatusToDosError(status) );
3435 return !status;
3439 /****************************************************************************
3440 * FlushInstructionCache (KERNEL32.@)
3442 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3444 NTSTATUS status;
3445 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3446 if (status) SetLastError( RtlNtStatusToDosError(status) );
3447 return !status;
3451 /******************************************************************
3452 * GetProcessIoCounters (KERNEL32.@)
3454 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3456 NTSTATUS status;
3458 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3459 ioc, sizeof(*ioc), NULL);
3460 if (status) SetLastError( RtlNtStatusToDosError(status) );
3461 return !status;
3464 /******************************************************************
3465 * GetProcessHandleCount (KERNEL32.@)
3467 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3469 NTSTATUS status;
3471 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3472 cnt, sizeof(*cnt), NULL);
3473 if (status) SetLastError( RtlNtStatusToDosError(status) );
3474 return !status;
3477 /******************************************************************
3478 * QueryFullProcessImageNameA (KERNEL32.@)
3480 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3482 BOOL retval;
3483 DWORD pdwSizeW = *pdwSize;
3484 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3486 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3488 if(retval)
3489 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3490 lpExeName, *pdwSize, NULL, NULL));
3491 if(retval)
3492 *pdwSize = strlen(lpExeName);
3494 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3495 return retval;
3498 /******************************************************************
3499 * QueryFullProcessImageNameW (KERNEL32.@)
3501 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3503 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3504 UNICODE_STRING *dynamic_buffer = NULL;
3505 UNICODE_STRING *result = NULL;
3506 NTSTATUS status;
3507 DWORD needed;
3509 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3510 * is a DOS path and we depend on this. */
3511 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3512 sizeof(buffer) - sizeof(WCHAR), &needed);
3513 if (status == STATUS_INFO_LENGTH_MISMATCH)
3515 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3516 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3517 result = dynamic_buffer;
3519 else
3520 result = (PUNICODE_STRING)buffer;
3522 if (status) goto cleanup;
3524 if (dwFlags & PROCESS_NAME_NATIVE)
3526 WCHAR drive[3];
3527 WCHAR device[1024];
3528 DWORD ntlen, devlen;
3530 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3532 /* We cannot convert it to an NT device path so fail */
3533 status = STATUS_NO_SUCH_DEVICE;
3534 goto cleanup;
3537 /* Find this drive's NT device path */
3538 drive[0] = result->Buffer[0];
3539 drive[1] = ':';
3540 drive[2] = 0;
3541 if (!QueryDosDeviceW(drive, device, sizeof(device)/sizeof(*device)))
3543 status = STATUS_NO_SUCH_DEVICE;
3544 goto cleanup;
3547 devlen = lstrlenW(device);
3548 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3549 if (ntlen + 1 > *pdwSize)
3551 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3552 return FALSE;
3554 *pdwSize = ntlen;
3556 memcpy(lpExeName, device, devlen * sizeof(*device));
3557 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3558 lpExeName[*pdwSize] = 0;
3559 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3561 else
3563 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3565 status = STATUS_BUFFER_TOO_SMALL;
3566 goto cleanup;
3569 *pdwSize = result->Length/sizeof(WCHAR);
3570 memcpy( lpExeName, result->Buffer, result->Length );
3571 lpExeName[*pdwSize] = 0;
3574 cleanup:
3575 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3576 if (status) SetLastError( RtlNtStatusToDosError(status) );
3577 return !status;
3580 /***********************************************************************
3581 * K32GetProcessImageFileNameA (KERNEL32.@)
3583 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3585 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3588 /***********************************************************************
3589 * K32GetProcessImageFileNameW (KERNEL32.@)
3591 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3593 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3596 /***********************************************************************
3597 * K32EnumProcesses (KERNEL32.@)
3599 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3601 SYSTEM_PROCESS_INFORMATION *spi;
3602 ULONG size = 0x4000;
3603 void *buf = NULL;
3604 NTSTATUS status;
3606 do {
3607 size *= 2;
3608 HeapFree(GetProcessHeap(), 0, buf);
3609 buf = HeapAlloc(GetProcessHeap(), 0, size);
3610 if (!buf)
3611 return FALSE;
3613 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3614 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3616 if (status != STATUS_SUCCESS)
3618 HeapFree(GetProcessHeap(), 0, buf);
3619 SetLastError(RtlNtStatusToDosError(status));
3620 return FALSE;
3623 spi = buf;
3625 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3627 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3628 *lpcbUsed += sizeof(DWORD);
3630 if (spi->NextEntryOffset == 0)
3631 break;
3633 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3636 HeapFree(GetProcessHeap(), 0, buf);
3637 return TRUE;
3640 /***********************************************************************
3641 * K32QueryWorkingSet (KERNEL32.@)
3643 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3645 NTSTATUS status;
3647 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3649 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3651 if (status)
3653 SetLastError( RtlNtStatusToDosError( status ) );
3654 return FALSE;
3656 return TRUE;
3659 /***********************************************************************
3660 * K32QueryWorkingSetEx (KERNEL32.@)
3662 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3664 NTSTATUS status;
3666 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3668 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3670 if (status)
3672 SetLastError( RtlNtStatusToDosError( status ) );
3673 return FALSE;
3675 return TRUE;
3678 /***********************************************************************
3679 * K32GetProcessMemoryInfo (KERNEL32.@)
3681 * Retrieve memory usage information for a given process
3684 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3685 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3687 NTSTATUS status;
3688 VM_COUNTERS vmc;
3690 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3692 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3693 return FALSE;
3696 status = NtQueryInformationProcess(process, ProcessVmCounters,
3697 &vmc, sizeof(vmc), NULL);
3699 if (status)
3701 SetLastError(RtlNtStatusToDosError(status));
3702 return FALSE;
3705 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3706 pmc->PageFaultCount = vmc.PageFaultCount;
3707 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3708 pmc->WorkingSetSize = vmc.WorkingSetSize;
3709 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3710 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3711 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3712 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3713 pmc->PagefileUsage = vmc.PagefileUsage;
3714 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3716 return TRUE;
3719 /***********************************************************************
3720 * ProcessIdToSessionId (KERNEL32.@)
3721 * This function is available on Terminal Server 4SP4 and Windows 2000
3723 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3725 /* According to MSDN, if the calling process is not in a terminal
3726 * services environment, then the sessionid returned is zero.
3728 *sessionid_ptr = 0;
3729 return TRUE;
3733 /***********************************************************************
3734 * RegisterServiceProcess (KERNEL32.@)
3736 * A service process calls this function to ensure that it continues to run
3737 * even after a user logged off.
3739 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3741 /* I don't think that Wine needs to do anything in this function */
3742 return 1; /* success */
3746 /**********************************************************************
3747 * IsWow64Process (KERNEL32.@)
3749 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3751 ULONG pbi;
3752 NTSTATUS status;
3754 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3756 if (status != STATUS_SUCCESS)
3758 SetLastError( RtlNtStatusToDosError( status ) );
3759 return FALSE;
3761 *Wow64Process = (pbi != 0);
3762 return TRUE;
3766 /***********************************************************************
3767 * GetCurrentProcess (KERNEL32.@)
3769 * Get a handle to the current process.
3771 * PARAMS
3772 * None.
3774 * RETURNS
3775 * A handle representing the current process.
3777 #undef GetCurrentProcess
3778 HANDLE WINAPI GetCurrentProcess(void)
3780 return (HANDLE)~(ULONG_PTR)0;
3783 /***********************************************************************
3784 * GetLogicalProcessorInformation (KERNEL32.@)
3786 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3788 NTSTATUS status;
3790 TRACE("(%p,%p)\n", buffer, pBufLen);
3792 if(!pBufLen)
3794 SetLastError(ERROR_INVALID_PARAMETER);
3795 return FALSE;
3798 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
3800 if (status == STATUS_INFO_LENGTH_MISMATCH)
3802 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3803 return FALSE;
3805 if (status != STATUS_SUCCESS)
3807 SetLastError( RtlNtStatusToDosError( status ) );
3808 return FALSE;
3810 return TRUE;
3813 /***********************************************************************
3814 * GetLogicalProcessorInformationEx (KERNEL32.@)
3816 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer, PDWORD pBufLen)
3818 FIXME("(%u,%p,%p): stub\n", relationship, buffer, pBufLen);
3819 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3820 return FALSE;
3823 /***********************************************************************
3824 * CmdBatNotification (KERNEL32.@)
3826 * Notifies the system that a batch file has started or finished.
3828 * PARAMS
3829 * bBatchRunning [I] TRUE if a batch file has started or
3830 * FALSE if a batch file has finished executing.
3832 * RETURNS
3833 * Unknown.
3835 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3837 FIXME("%d\n", bBatchRunning);
3838 return FALSE;
3842 /***********************************************************************
3843 * RegisterApplicationRestart (KERNEL32.@)
3845 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3847 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3849 return S_OK;
3852 /**********************************************************************
3853 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3855 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3857 static int once;
3858 if (!once++) FIXME("stub\n");
3859 return 0;
3862 /**********************************************************************
3863 * GetSystemDEPPolicy (KERNEL32.@)
3865 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3867 FIXME("stub\n");
3868 return OptIn;
3871 /**********************************************************************
3872 * SetProcessDEPPolicy (KERNEL32.@)
3874 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3876 FIXME("(%d): stub\n", newDEP);
3877 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3878 return FALSE;
3881 /**********************************************************************
3882 * ApplicationRecoveryFinished (KERNEL32.@)
3884 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
3886 FIXME(": stub\n");
3887 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3890 /**********************************************************************
3891 * ApplicationRecoveryInProgress (KERNEL32.@)
3893 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
3895 FIXME(":%p stub\n", canceled);
3896 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3897 return E_FAIL;
3900 /**********************************************************************
3901 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3903 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
3905 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
3906 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3907 return E_FAIL;
3910 /**********************************************************************
3911 * GetNumaHighestNodeNumber (KERNEL32.@)
3913 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
3915 *highestnode = 0;
3916 FIXME("(%p): semi-stub\n", highestnode);
3917 return TRUE;
3920 /**********************************************************************
3921 * GetNumaNodeProcessorMask (KERNEL32.@)
3923 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
3925 FIXME("(%c %p): stub\n", node, mask);
3926 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3927 return FALSE;
3930 /**********************************************************************
3931 * GetNumaAvailableMemoryNode (KERNEL32.@)
3933 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
3935 FIXME("(%c %p): stub\n", node, available_bytes);
3936 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3937 return FALSE;
3940 /**********************************************************************
3941 * GetProcessDEPPolicy (KERNEL32.@)
3943 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
3945 FIXME("(%p %p %p): stub\n", process, flags, permanent);
3946 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3947 return FALSE;
3950 /**********************************************************************
3951 * FlushProcessWriteBuffers (KERNEL32.@)
3953 VOID WINAPI FlushProcessWriteBuffers(void)
3955 static int once = 0;
3957 if (!once++)
3958 FIXME(": stub\n");
3961 /***********************************************************************
3962 * UnregisterApplicationRestart (KERNEL32.@)
3964 HRESULT WINAPI UnregisterApplicationRestart(void)
3966 FIXME(": stub\n");
3967 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3968 return S_OK;