usp10: Don't modify psa->fNoGlyphIndex in ScriptShapeOpenType().
[wine.git] / dlls / kernel32 / process.c
blob4771108a3207243604ce3aad36ec45d7eb5eb0b3
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 ) ||
138 !strncmp( var, "QT_", sizeof("QT_")-1 ));
142 /***********************************************************************
143 * is_path_prefix
145 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
147 unsigned int len = strlenW( prefix );
149 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
150 while (filename[len] == '\\') len++;
151 return len;
155 /***************************************************************************
156 * get_builtin_path
158 * Get the path of a builtin module when the native file does not exist.
160 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
161 UINT size, struct binary_info *binary_info )
163 WCHAR *file_part;
164 UINT len;
165 void *redir_disabled = 0;
166 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
168 /* builtin names cannot be empty or contain spaces */
169 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
171 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
172 Wow64RevertWow64FsRedirection( redir_disabled );
174 if (contains_path( libname ))
176 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
177 filename, &file_part ) > size * sizeof(WCHAR))
178 return FALSE; /* too long */
180 if ((len = is_path_prefix( DIR_System, filename )))
182 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
184 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
186 flags = 0;
188 else return FALSE;
190 if (filename + len != file_part) return FALSE;
192 else
194 len = strlenW( DIR_System );
195 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
196 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
197 file_part = filename + len;
198 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
199 strcpyW( file_part, libname );
200 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
202 if (ext && !strchrW( file_part, '.' ))
204 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
205 return FALSE; /* too long */
206 strcatW( file_part, ext );
208 binary_info->type = BINARY_UNIX_LIB;
209 binary_info->flags = flags;
210 binary_info->res_start = NULL;
211 binary_info->res_end = NULL;
212 /* assume current arch */
213 #if defined(__i386__) || defined(__x86_64__)
214 binary_info->arch = (flags & BINARY_FLAG_64BIT) ? IMAGE_FILE_MACHINE_AMD64 : IMAGE_FILE_MACHINE_I386;
215 #elif defined(__powerpc__)
216 binary_info->arch = IMAGE_FILE_MACHINE_POWERPC;
217 #elif defined(__arm__) && !defined(__ARMEB__)
218 binary_info->arch = IMAGE_FILE_MACHINE_ARMNT;
219 #elif defined(__aarch64__)
220 binary_info->arch = IMAGE_FILE_MACHINE_ARM64;
221 #else
222 binary_info->arch = IMAGE_FILE_MACHINE_UNKNOWN;
223 #endif
224 return TRUE;
228 /***********************************************************************
229 * open_exe_file
231 * Open a specific exe file, taking load order into account.
232 * Returns the file handle or 0 for a builtin exe.
234 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
236 HANDLE handle;
238 TRACE("looking for %s\n", debugstr_w(name) );
240 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
241 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
243 WCHAR buffer[MAX_PATH];
244 /* file doesn't exist, check for builtin */
245 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
246 handle = 0;
248 else MODULE_get_binary_info( handle, binary_info );
250 return handle;
254 /***********************************************************************
255 * find_exe_file
257 * Open an exe file, and return the full name and file handle.
258 * Returns FALSE if file could not be found.
260 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
261 HANDLE *handle, struct binary_info *binary_info )
263 TRACE("looking for %s\n", debugstr_w(name) );
265 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
266 /* no builtin found, try native without extension in case it is a Unix app */
267 !SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
269 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
270 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
271 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
273 MODULE_get_binary_info( *handle, binary_info );
274 return TRUE;
276 return FALSE;
280 /***********************************************************************
281 * build_initial_environment
283 * Build the Win32 environment from the Unix environment
285 static BOOL build_initial_environment(void)
287 SIZE_T size = 1;
288 char **e;
289 WCHAR *p, *endptr;
290 void *ptr;
291 char **env = __wine_get_main_environment();
293 /* Compute the total size of the Unix environment */
294 for (e = env; *e; e++)
296 if (is_special_env_var( *e )) continue;
297 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
299 size *= sizeof(WCHAR);
301 /* Now allocate the environment */
302 ptr = NULL;
303 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
304 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
305 return FALSE;
307 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
308 endptr = p + size / sizeof(WCHAR);
310 /* And fill it with the Unix environment */
311 for (e = env; *e; e++)
313 char *str = *e;
315 /* skip Unix special variables and use the Wine variants instead */
316 if (!strncmp( str, "WINE", 4 ))
318 if (is_special_env_var( str + 4 )) str += 4;
319 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
321 else if (is_special_env_var( str )) continue; /* skip it */
323 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
324 p += strlenW(p) + 1;
326 *p = 0;
327 return TRUE;
331 /***********************************************************************
332 * set_registry_variables
334 * Set environment variables by enumerating the values of a key;
335 * helper for set_registry_environment().
336 * Note that Windows happily truncates the value if it's too big.
338 static void set_registry_variables( HANDLE hkey, ULONG type )
340 static const WCHAR pathW[] = {'P','A','T','H'};
341 static const WCHAR sep[] = {';',0};
342 UNICODE_STRING env_name, env_value;
343 NTSTATUS status;
344 DWORD size;
345 int index;
346 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
347 WCHAR tmpbuf[1024];
348 UNICODE_STRING tmp;
349 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
351 tmp.Buffer = tmpbuf;
352 tmp.MaximumLength = sizeof(tmpbuf);
354 for (index = 0; ; index++)
356 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
357 buffer, sizeof(buffer), &size );
358 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
359 break;
360 if (info->Type != type)
361 continue;
362 env_name.Buffer = info->Name;
363 env_name.Length = env_name.MaximumLength = info->NameLength;
364 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
365 env_value.Length = info->DataLength;
366 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
367 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
368 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
369 if (!env_value.Length) continue;
370 if (info->Type == REG_EXPAND_SZ)
372 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
373 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
374 RtlCopyUnicodeString( &env_value, &tmp );
376 /* PATH is magic */
377 if (env_name.Length == sizeof(pathW) &&
378 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
379 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
381 RtlAppendUnicodeToString( &tmp, sep );
382 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
383 RtlCopyUnicodeString( &env_value, &tmp );
385 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
390 /***********************************************************************
391 * set_registry_environment
393 * Set the environment variables specified in the registry.
395 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
396 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
397 * on the order in which the variables are processed. But on Windows it
398 * does not really matter since they only use %SystemDrive% and
399 * %SystemRoot% which are predefined. But Wine defines these in the
400 * registry, so we need two passes.
402 static BOOL set_registry_environment( BOOL volatile_only )
404 static const WCHAR env_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
405 'M','a','c','h','i','n','e','\\',
406 'S','y','s','t','e','m','\\',
407 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
408 'C','o','n','t','r','o','l','\\',
409 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
410 'E','n','v','i','r','o','n','m','e','n','t',0};
411 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
412 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};
414 OBJECT_ATTRIBUTES attr;
415 UNICODE_STRING nameW;
416 HANDLE hkey;
417 BOOL ret = FALSE;
419 attr.Length = sizeof(attr);
420 attr.RootDirectory = 0;
421 attr.ObjectName = &nameW;
422 attr.Attributes = 0;
423 attr.SecurityDescriptor = NULL;
424 attr.SecurityQualityOfService = NULL;
426 /* first the system environment variables */
427 RtlInitUnicodeString( &nameW, env_keyW );
428 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
430 set_registry_variables( hkey, REG_SZ );
431 set_registry_variables( hkey, REG_EXPAND_SZ );
432 NtClose( hkey );
433 ret = TRUE;
436 /* then the ones for the current user */
437 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
438 RtlInitUnicodeString( &nameW, envW );
439 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
441 set_registry_variables( hkey, REG_SZ );
442 set_registry_variables( hkey, REG_EXPAND_SZ );
443 NtClose( hkey );
446 RtlInitUnicodeString( &nameW, volatile_envW );
447 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
449 set_registry_variables( hkey, REG_SZ );
450 set_registry_variables( hkey, REG_EXPAND_SZ );
451 NtClose( hkey );
454 NtClose( attr.RootDirectory );
455 return ret;
459 /***********************************************************************
460 * get_reg_value
462 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
464 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
465 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
466 DWORD len, size = sizeof(buffer);
467 WCHAR *ret = NULL;
468 UNICODE_STRING nameW;
470 RtlInitUnicodeString( &nameW, name );
471 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
472 return NULL;
474 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
475 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
477 if (info->Type == REG_EXPAND_SZ)
479 UNICODE_STRING value, expanded;
481 value.MaximumLength = len * sizeof(WCHAR);
482 value.Buffer = (WCHAR *)info->Data;
483 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
484 value.Length = len * sizeof(WCHAR);
485 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
486 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
487 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
488 else RtlFreeUnicodeString( &expanded );
490 else if (info->Type == REG_SZ)
492 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
494 memcpy( ret, info->Data, len * sizeof(WCHAR) );
495 ret[len] = 0;
498 return ret;
502 /***********************************************************************
503 * set_additional_environment
505 * Set some additional environment variables not specified in the registry.
507 static void set_additional_environment(void)
509 static const WCHAR profile_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
510 'M','a','c','h','i','n','e','\\',
511 'S','o','f','t','w','a','r','e','\\',
512 'M','i','c','r','o','s','o','f','t','\\',
513 'W','i','n','d','o','w','s',' ','N','T','\\',
514 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
515 'P','r','o','f','i','l','e','L','i','s','t',0};
516 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
517 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
518 static const WCHAR computernameW[] = {'C','O','M','P','U','T','E','R','N','A','M','E',0};
519 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
520 OBJECT_ATTRIBUTES attr;
521 UNICODE_STRING nameW;
522 WCHAR *profile_dir = NULL, *all_users_dir = NULL;
523 WCHAR buf[MAX_COMPUTERNAME_LENGTH+1];
524 HANDLE hkey;
525 DWORD len;
527 /* ComputerName */
528 len = sizeof(buf) / sizeof(WCHAR);
529 if (GetComputerNameW( buf, &len ))
530 SetEnvironmentVariableW( computernameW, buf );
532 /* set the ALLUSERSPROFILE variables */
534 attr.Length = sizeof(attr);
535 attr.RootDirectory = 0;
536 attr.ObjectName = &nameW;
537 attr.Attributes = 0;
538 attr.SecurityDescriptor = NULL;
539 attr.SecurityQualityOfService = NULL;
540 RtlInitUnicodeString( &nameW, profile_keyW );
541 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
543 profile_dir = get_reg_value( hkey, profiles_valueW );
544 all_users_dir = get_reg_value( hkey, all_users_valueW );
545 NtClose( hkey );
548 if (profile_dir && all_users_dir)
550 WCHAR *value, *p;
552 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
553 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
554 strcpyW( value, profile_dir );
555 p = value + strlenW(value);
556 if (p > value && p[-1] != '\\') *p++ = '\\';
557 strcpyW( p, all_users_dir );
558 SetEnvironmentVariableW( allusersW, value );
559 HeapFree( GetProcessHeap(), 0, value );
562 HeapFree( GetProcessHeap(), 0, all_users_dir );
563 HeapFree( GetProcessHeap(), 0, profile_dir );
566 /***********************************************************************
567 * set_wow64_environment
569 * Set the environment variables that change across 32/64/Wow64.
571 static void set_wow64_environment(void)
573 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};
574 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};
575 static const WCHAR x86W[] = {'x','8','6',0};
576 static const WCHAR versionW[] = {'\\','R','e','g','i','s','t','r','y','\\',
577 'M','a','c','h','i','n','e','\\',
578 'S','o','f','t','w','a','r','e','\\',
579 'M','i','c','r','o','s','o','f','t','\\',
580 'W','i','n','d','o','w','s','\\',
581 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
582 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
583 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
584 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
585 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
586 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
587 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
588 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
589 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
591 OBJECT_ATTRIBUTES attr;
592 UNICODE_STRING nameW;
593 WCHAR arch[64];
594 WCHAR *value;
595 HANDLE hkey;
597 /* set the PROCESSOR_ARCHITECTURE variable */
599 if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
601 if (is_win64)
603 SetEnvironmentVariableW( archW, arch );
604 SetEnvironmentVariableW( arch6432W, NULL );
607 else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
609 if (is_wow64)
611 SetEnvironmentVariableW( arch6432W, arch );
612 SetEnvironmentVariableW( archW, x86W );
616 attr.Length = sizeof(attr);
617 attr.RootDirectory = 0;
618 attr.ObjectName = &nameW;
619 attr.Attributes = 0;
620 attr.SecurityDescriptor = NULL;
621 attr.SecurityQualityOfService = NULL;
622 RtlInitUnicodeString( &nameW, versionW );
623 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
625 /* set the ProgramFiles variables */
627 if ((value = get_reg_value( hkey, progdirW )))
629 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
630 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
631 HeapFree( GetProcessHeap(), 0, value );
633 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
635 SetEnvironmentVariableW( progfilesW, value );
636 HeapFree( GetProcessHeap(), 0, value );
639 /* set the CommonProgramFiles variables */
641 if ((value = get_reg_value( hkey, commondirW )))
643 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
644 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
645 HeapFree( GetProcessHeap(), 0, value );
647 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
649 SetEnvironmentVariableW( commonfilesW, value );
650 HeapFree( GetProcessHeap(), 0, value );
653 NtClose( hkey );
656 /***********************************************************************
657 * set_library_wargv
659 * Set the Wine library Unicode argv global variables.
661 static void set_library_wargv( char **argv )
663 int argc;
664 char *q;
665 WCHAR *p;
666 WCHAR **wargv;
667 DWORD total = 0;
669 for (argc = 0; argv[argc]; argc++)
670 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
672 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
673 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
674 p = (WCHAR *)(wargv + argc + 1);
675 for (argc = 0; argv[argc]; argc++)
677 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
678 wargv[argc] = p;
679 p += reslen;
680 total -= reslen;
682 wargv[argc] = NULL;
684 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
686 for (argc = 0; wargv[argc]; argc++)
687 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
689 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
690 q = (char *)(argv + argc + 1);
691 for (argc = 0; wargv[argc]; argc++)
693 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
694 argv[argc] = q;
695 q += reslen;
696 total -= reslen;
698 argv[argc] = NULL;
700 __wine_main_argc = argc;
701 __wine_main_argv = argv;
702 __wine_main_wargv = wargv;
706 /***********************************************************************
707 * update_library_argv0
709 * Update the argv[0] global variable with the binary we have found.
711 static void update_library_argv0( const WCHAR *argv0 )
713 DWORD len = strlenW( argv0 );
715 if (len > strlenW( __wine_main_wargv[0] ))
717 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
719 strcpyW( __wine_main_wargv[0], argv0 );
721 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
722 if (len > strlen( __wine_main_argv[0] ) + 1)
724 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
726 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
730 /***********************************************************************
731 * build_command_line
733 * Build the command line of a process from the argv array.
735 * Note that it does NOT necessarily include the file name.
736 * Sometimes we don't even have any command line options at all.
738 * We must quote and escape characters so that the argv array can be rebuilt
739 * from the command line:
740 * - spaces and tabs must be quoted
741 * 'a b' -> '"a b"'
742 * - quotes must be escaped
743 * '"' -> '\"'
744 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
745 * resulting in an odd number of '\' followed by a '"'
746 * '\"' -> '\\\"'
747 * '\\"' -> '\\\\\"'
748 * - '\'s that are not followed by a '"' can be left as is
749 * 'a\b' == 'a\b'
750 * 'a\\b' == 'a\\b'
752 static BOOL build_command_line( WCHAR **argv )
754 int len;
755 WCHAR **arg;
756 LPWSTR p;
757 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
759 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
761 len = 0;
762 for (arg = argv; *arg; arg++)
764 BOOL has_space;
765 int bcount;
766 WCHAR* a;
768 has_space=FALSE;
769 bcount=0;
770 a=*arg;
771 if( !*a ) has_space=TRUE;
772 while (*a!='\0') {
773 if (*a=='\\') {
774 bcount++;
775 } else {
776 if (*a==' ' || *a=='\t') {
777 has_space=TRUE;
778 } else if (*a=='"') {
779 /* doubling of '\' preceding a '"',
780 * plus escaping of said '"'
782 len+=2*bcount+1;
784 bcount=0;
786 a++;
788 len+=(a-*arg)+1 /* for the separating space */;
789 if (has_space)
790 len+=2; /* for the quotes */
793 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
794 return FALSE;
796 p = rupp->CommandLine.Buffer;
797 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
798 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
799 for (arg = argv; *arg; arg++)
801 BOOL has_space,has_quote;
802 WCHAR* a;
804 /* Check for quotes and spaces in this argument */
805 has_space=has_quote=FALSE;
806 a=*arg;
807 if( !*a ) has_space=TRUE;
808 while (*a!='\0') {
809 if (*a==' ' || *a=='\t') {
810 has_space=TRUE;
811 if (has_quote)
812 break;
813 } else if (*a=='"') {
814 has_quote=TRUE;
815 if (has_space)
816 break;
818 a++;
821 /* Now transfer it to the command line */
822 if (has_space)
823 *p++='"';
824 if (has_quote) {
825 int bcount;
827 bcount=0;
828 a=*arg;
829 while (*a!='\0') {
830 if (*a=='\\') {
831 *p++=*a;
832 bcount++;
833 } else {
834 if (*a=='"') {
835 int i;
837 /* Double all the '\\' preceding this '"', plus one */
838 for (i=0;i<=bcount;i++)
839 *p++='\\';
840 *p++='"';
841 } else {
842 *p++=*a;
844 bcount=0;
846 a++;
848 } else {
849 WCHAR* x = *arg;
850 while ((*p=*x++)) p++;
852 if (has_space)
853 *p++='"';
854 *p++=' ';
856 if (p > rupp->CommandLine.Buffer)
857 p--; /* remove last space */
858 *p = '\0';
860 return TRUE;
864 /***********************************************************************
865 * init_current_directory
867 * Initialize the current directory from the Unix cwd or the parent info.
869 static void init_current_directory( CURDIR *cur_dir )
871 UNICODE_STRING dir_str;
872 const char *pwd;
873 char *cwd;
874 int size;
876 /* if we received a cur dir from the parent, try this first */
878 if (cur_dir->DosPath.Length)
880 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
883 /* now try to get it from the Unix cwd */
885 for (size = 256; ; size *= 2)
887 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
888 if (getcwd( cwd, size )) break;
889 HeapFree( GetProcessHeap(), 0, cwd );
890 if (errno == ERANGE) continue;
891 cwd = NULL;
892 break;
895 /* try to use PWD if it is valid, so that we don't resolve symlinks */
897 pwd = getenv( "PWD" );
898 if (cwd)
900 struct stat st1, st2;
902 if (!pwd || stat( pwd, &st1 ) == -1 ||
903 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
904 pwd = cwd;
907 if (pwd)
909 ANSI_STRING unix_name;
910 UNICODE_STRING nt_name;
911 RtlInitAnsiString( &unix_name, pwd );
912 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
914 UNICODE_STRING dos_path;
915 /* skip the \??\ prefix, nt_name is 0 terminated */
916 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
917 RtlSetCurrentDirectory_U( &dos_path );
918 RtlFreeUnicodeString( &nt_name );
922 if (!cur_dir->DosPath.Length) /* still not initialized */
924 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
925 "starting in the Windows directory.\n", cwd ? cwd : "" );
926 RtlInitUnicodeString( &dir_str, DIR_Windows );
927 RtlSetCurrentDirectory_U( &dir_str );
929 HeapFree( GetProcessHeap(), 0, cwd );
931 done:
932 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
936 /***********************************************************************
937 * init_windows_dirs
939 * Initialize the windows and system directories from the environment.
941 static void init_windows_dirs(void)
943 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
945 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
946 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
947 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
948 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
949 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
951 DWORD len;
952 WCHAR *buffer;
954 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
956 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
957 GetEnvironmentVariableW( windirW, buffer, len );
958 DIR_Windows = buffer;
960 else DIR_Windows = default_windirW;
962 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
964 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
965 GetEnvironmentVariableW( winsysdirW, buffer, len );
966 DIR_System = buffer;
968 else
970 len = strlenW( DIR_Windows );
971 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
972 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
973 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
974 DIR_System = buffer;
977 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
978 ERR( "directory %s could not be created, error %u\n",
979 debugstr_w(DIR_Windows), GetLastError() );
980 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
981 ERR( "directory %s could not be created, error %u\n",
982 debugstr_w(DIR_System), GetLastError() );
984 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
986 len = strlenW( DIR_Windows );
987 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
988 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
989 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
990 DIR_SysWow64 = buffer;
991 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
992 ERR( "directory %s could not be created, error %u\n",
993 debugstr_w(DIR_SysWow64), GetLastError() );
996 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
997 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
999 /* set the directories in ntdll too */
1000 __wine_init_windows_dir( DIR_Windows, DIR_System );
1004 /***********************************************************************
1005 * start_wineboot
1007 * Start the wineboot process if necessary. Return the handles to wait on.
1009 static void start_wineboot( HANDLE handles[2] )
1011 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
1013 handles[1] = 0;
1014 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
1016 ERR( "failed to create wineboot event, expect trouble\n" );
1017 return;
1019 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
1021 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1022 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1023 STARTUPINFOW si;
1024 PROCESS_INFORMATION pi;
1025 void *redir;
1026 WCHAR app[MAX_PATH];
1027 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1029 memset( &si, 0, sizeof(si) );
1030 si.cb = sizeof(si);
1031 si.dwFlags = STARTF_USESTDHANDLES;
1032 si.hStdInput = 0;
1033 si.hStdOutput = 0;
1034 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1036 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1037 lstrcatW( app, wineboot );
1039 Wow64DisableWow64FsRedirection( &redir );
1040 strcpyW( cmdline, app );
1041 strcatW( cmdline, args );
1042 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1044 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1045 CloseHandle( pi.hThread );
1046 handles[1] = pi.hProcess;
1048 else
1050 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1051 CloseHandle( handles[0] );
1052 handles[0] = 0;
1054 Wow64RevertWow64FsRedirection( redir );
1059 #ifdef __i386__
1060 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1061 __ASM_GLOBAL_FUNC( call_process_entry,
1062 "pushl %ebp\n\t"
1063 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1064 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1065 "movl %esp,%ebp\n\t"
1066 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1067 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1068 "pushl 8(%ebp)\n\t"
1069 "call *12(%ebp)\n\t"
1070 "leave\n\t"
1071 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1072 __ASM_CFI(".cfi_same_value %ebp\n\t")
1073 "ret" )
1074 #else
1075 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1077 return entry( peb );
1079 #endif
1081 /***********************************************************************
1082 * start_process
1084 * Startup routine of a new process. Runs on the new process stack.
1086 static DWORD WINAPI start_process( PEB *peb )
1088 IMAGE_NT_HEADERS *nt;
1089 LPTHREAD_START_ROUTINE entry;
1091 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1092 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1093 nt->OptionalHeader.AddressOfEntryPoint);
1095 if (!nt->OptionalHeader.AddressOfEntryPoint)
1097 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1098 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1099 ExitThread( 1 );
1102 if (TRACE_ON(relay))
1103 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1104 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1106 SetLastError( 0 ); /* clear error code */
1107 if (peb->BeingDebugged) DbgBreakPoint();
1108 return call_process_entry( peb, entry );
1112 /***********************************************************************
1113 * set_process_name
1115 * Change the process name in the ps output.
1117 static void set_process_name( int argc, char *argv[] )
1119 #ifdef HAVE_SETPROCTITLE
1120 setproctitle("-%s", argv[1]);
1121 /* remove argv[0] */
1122 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1123 #elif defined(HAVE_SETPROGNAME)
1124 int i, offset;
1125 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1127 offset = argv[1] - argv[0];
1128 memmove( argv[1] - offset, argv[1], end - argv[1] );
1129 memset( end - offset, 0, offset );
1130 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1131 argv[i-1] = NULL;
1133 setprogname( argv[0] );
1134 #elif defined(HAVE_PRCTL)
1135 int i, offset;
1136 char *p, *prctl_name = argv[1];
1137 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1139 #ifndef PR_SET_NAME
1140 # define PR_SET_NAME 15
1141 #endif
1143 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1144 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1146 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1148 offset = argv[1] - argv[0];
1149 memmove( argv[1] - offset, argv[1], end - argv[1] );
1150 memset( end - offset, 0, offset );
1151 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1152 argv[i-1] = NULL;
1154 else
1156 /* remove argv[0] */
1157 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1159 #endif /* HAVE_PRCTL */
1163 /***********************************************************************
1164 * __wine_kernel_init
1166 * Wine initialisation: load and start the main exe file.
1168 void CDECL __wine_kernel_init(void)
1170 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1171 static const WCHAR dotW[] = {'.',0};
1173 WCHAR *p, main_exe_name[MAX_PATH+1];
1174 PEB *peb = NtCurrentTeb()->Peb;
1175 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1176 HANDLE boot_events[2];
1177 BOOL got_environment = TRUE;
1179 /* Initialize everything */
1181 setbuf(stdout,NULL);
1182 setbuf(stderr,NULL);
1183 kernel32_handle = GetModuleHandleW(kernel32W);
1184 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1186 LOCALE_Init();
1188 if (!params->Environment)
1190 /* Copy the parent environment */
1191 if (!build_initial_environment()) exit(1);
1193 /* convert old configuration to new format */
1194 convert_old_config();
1196 got_environment = set_registry_environment( FALSE );
1197 set_additional_environment();
1200 init_windows_dirs();
1201 init_current_directory( &params->CurrentDirectory );
1203 set_process_name( __wine_main_argc, __wine_main_argv );
1204 set_library_wargv( __wine_main_argv );
1205 boot_events[0] = boot_events[1] = 0;
1207 if (peb->ProcessParameters->ImagePathName.Buffer)
1209 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1211 else
1213 struct binary_info binary_info;
1215 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1216 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1218 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1219 ExitProcess( GetLastError() );
1221 update_library_argv0( main_exe_name );
1222 if (!build_command_line( __wine_main_wargv )) goto error;
1223 start_wineboot( boot_events );
1226 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1227 p = strrchrW( main_exe_name, '.' );
1228 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1230 TRACE( "starting process name=%s argv[0]=%s\n",
1231 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1233 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1234 MODULE_get_dll_load_path(main_exe_name) );
1236 if (boot_events[0])
1238 DWORD timeout = 2 * 60 * 1000, count = 1;
1240 if (boot_events[1]) count++;
1241 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1242 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1243 ERR( "boot event wait timed out\n" );
1244 CloseHandle( boot_events[0] );
1245 if (boot_events[1]) CloseHandle( boot_events[1] );
1246 /* reload environment now that wineboot has run */
1247 set_registry_environment( got_environment );
1248 set_additional_environment();
1250 set_wow64_environment();
1252 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1254 DWORD_PTR args[1];
1255 WCHAR msgW[1024];
1256 char msg[1024];
1257 DWORD error = GetLastError();
1259 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1260 if (error == ERROR_BAD_EXE_FORMAT ||
1261 error == ERROR_INVALID_ADDRESS ||
1262 error == ERROR_NOT_ENOUGH_MEMORY)
1264 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1265 /* if we get back here, it failed */
1267 else if (error == ERROR_MOD_NOT_FOUND)
1269 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1270 else p = main_exe_name;
1271 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1273 /* args 1 and 2 are --app-name full_path */
1274 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1275 debugstr_w(__wine_main_wargv[3]) );
1276 ExitProcess( ERROR_BAD_EXE_FORMAT );
1278 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1279 ExitProcess( ERROR_FILE_NOT_FOUND );
1281 args[0] = (DWORD_PTR)main_exe_name;
1282 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1283 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1284 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1285 MESSAGE( "wine: %s", msg );
1286 ExitProcess( error );
1289 if (!params->CurrentDirectory.Handle) chdir("/"); /* avoid locking removable devices */
1291 LdrInitializeThunk( start_process, 0, 0, 0 );
1293 error:
1294 ExitProcess( GetLastError() );
1298 /***********************************************************************
1299 * build_argv
1301 * Build an argv array from a command-line.
1302 * 'reserved' is the number of args to reserve before the first one.
1304 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1306 int argc;
1307 char** argv;
1308 char *arg,*s,*d,*cmdline;
1309 int in_quotes,bcount,len;
1311 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1312 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1313 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1315 argc=reserved+1;
1316 bcount=0;
1317 in_quotes=0;
1318 s=cmdline;
1319 while (1) {
1320 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1321 /* space */
1322 argc++;
1323 /* skip the remaining spaces */
1324 while (*s==' ' || *s=='\t') {
1325 s++;
1327 if (*s=='\0')
1328 break;
1329 bcount=0;
1330 continue;
1331 } else if (*s=='\\') {
1332 /* '\', count them */
1333 bcount++;
1334 } else if ((*s=='"') && ((bcount & 1)==0)) {
1335 /* unescaped '"' */
1336 in_quotes=!in_quotes;
1337 bcount=0;
1338 } else {
1339 /* a regular character */
1340 bcount=0;
1342 s++;
1344 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1346 HeapFree( GetProcessHeap(), 0, cmdline );
1347 return NULL;
1350 arg = d = s = (char *)(argv + argc);
1351 memcpy( d, cmdline, len );
1352 bcount=0;
1353 in_quotes=0;
1354 argc=reserved;
1355 while (*s) {
1356 if ((*s==' ' || *s=='\t') && !in_quotes) {
1357 /* Close the argument and copy it */
1358 *d=0;
1359 argv[argc++]=arg;
1361 /* skip the remaining spaces */
1362 do {
1363 s++;
1364 } while (*s==' ' || *s=='\t');
1366 /* Start with a new argument */
1367 arg=d=s;
1368 bcount=0;
1369 } else if (*s=='\\') {
1370 /* '\\' */
1371 *d++=*s++;
1372 bcount++;
1373 } else if (*s=='"') {
1374 /* '"' */
1375 if ((bcount & 1)==0) {
1376 /* Preceded by an even number of '\', this is half that
1377 * number of '\', plus a '"' which we discard.
1379 d-=bcount/2;
1380 s++;
1381 in_quotes=!in_quotes;
1382 } else {
1383 /* Preceded by an odd number of '\', this is half that
1384 * number of '\' followed by a '"'
1386 d=d-bcount/2-1;
1387 *d++='"';
1388 s++;
1390 bcount=0;
1391 } else {
1392 /* a regular character */
1393 *d++=*s++;
1394 bcount=0;
1397 if (*arg) {
1398 *d='\0';
1399 argv[argc++]=arg;
1401 argv[argc]=NULL;
1403 HeapFree( GetProcessHeap(), 0, cmdline );
1404 return argv;
1408 /***********************************************************************
1409 * build_envp
1411 * Build the environment of a new child process.
1413 static char **build_envp( const WCHAR *envW )
1415 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1417 const WCHAR *end;
1418 char **envp;
1419 char *env, *p;
1420 int count = 1, length;
1421 unsigned int i;
1423 for (end = envW; *end; count++) end += strlenW(end) + 1;
1424 end++;
1425 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1426 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1427 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1429 for (p = env; *p; p += strlen(p) + 1)
1430 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1432 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1434 if (!(p = getenv(unix_vars[i]))) continue;
1435 length += strlen(unix_vars[i]) + strlen(p) + 2;
1436 count++;
1439 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1441 char **envptr = envp;
1442 char *dst = (char *)(envp + count);
1444 /* some variables must not be modified, so we get them directly from the unix env */
1445 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1447 if (!(p = getenv(unix_vars[i]))) continue;
1448 *envptr++ = strcpy( dst, unix_vars[i] );
1449 strcat( dst, "=" );
1450 strcat( dst, p );
1451 dst += strlen(dst) + 1;
1454 /* now put the Windows environment strings */
1455 for (p = env; *p; p += strlen(p) + 1)
1457 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1458 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1459 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1460 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1461 if (is_special_env_var( p )) /* prefix it with "WINE" */
1463 *envptr++ = strcpy( dst, "WINE" );
1464 strcat( dst, p );
1466 else
1468 *envptr++ = strcpy( dst, p );
1470 dst += strlen(dst) + 1;
1472 *envptr = 0;
1474 HeapFree( GetProcessHeap(), 0, env );
1475 return envp;
1479 /***********************************************************************
1480 * fork_and_exec
1482 * Fork and exec a new Unix binary, checking for errors.
1484 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1485 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1487 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1488 int pid, err;
1489 char **argv, **envp;
1491 if (!env) env = GetEnvironmentStringsW();
1493 #ifdef HAVE_PIPE2
1494 if (pipe2( fd, O_CLOEXEC ) == -1)
1495 #endif
1497 if (pipe(fd) == -1)
1499 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1500 return -1;
1502 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1503 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1506 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1508 HANDLE hstdin, hstdout, hstderr;
1510 if (startup->dwFlags & STARTF_USESTDHANDLES)
1512 hstdin = startup->hStdInput;
1513 hstdout = startup->hStdOutput;
1514 hstderr = startup->hStdError;
1516 else
1518 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1519 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1520 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1523 if (is_console_handle( hstdin ))
1524 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1525 if (is_console_handle( hstdout ))
1526 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1527 if (is_console_handle( hstderr ))
1528 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1529 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1530 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1531 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1534 argv = build_argv( cmdline, 0 );
1535 envp = build_envp( env );
1537 if (!(pid = fork())) /* child */
1539 if (!(pid = fork())) /* grandchild */
1541 close( fd[0] );
1543 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1545 int nullfd = open( "/dev/null", O_RDWR );
1546 setsid();
1547 /* close stdin and stdout */
1548 if (nullfd != -1)
1550 dup2( nullfd, 0 );
1551 dup2( nullfd, 1 );
1552 close( nullfd );
1555 else
1557 if (stdin_fd != -1)
1559 dup2( stdin_fd, 0 );
1560 close( stdin_fd );
1562 if (stdout_fd != -1)
1564 dup2( stdout_fd, 1 );
1565 close( stdout_fd );
1567 if (stderr_fd != -1)
1569 dup2( stderr_fd, 2 );
1570 close( stderr_fd );
1574 /* Reset signals that we previously set to SIG_IGN */
1575 signal( SIGPIPE, SIG_DFL );
1577 if (newdir) chdir(newdir);
1579 if (argv && envp) execve( filename, argv, envp );
1582 if (pid <= 0) /* grandchild if exec failed or child if fork failed */
1584 err = errno;
1585 write( fd[1], &err, sizeof(err) );
1586 _exit(1);
1589 _exit(0); /* child if fork succeeded */
1591 HeapFree( GetProcessHeap(), 0, argv );
1592 HeapFree( GetProcessHeap(), 0, envp );
1593 if (stdin_fd != -1) close( stdin_fd );
1594 if (stdout_fd != -1) close( stdout_fd );
1595 if (stderr_fd != -1) close( stderr_fd );
1596 close( fd[1] );
1597 if (pid != -1)
1599 /* reap child */
1600 do {
1601 err = waitpid(pid, NULL, 0);
1602 } while (err < 0 && errno == EINTR);
1604 if (read( fd[0], &err, sizeof(err) ) > 0) /* exec or second fork failed */
1606 errno = err;
1607 pid = -1;
1610 if (pid == -1) FILE_SetDosError();
1611 close( fd[0] );
1612 return pid;
1616 static inline DWORD append_string( void **ptr, const WCHAR *str )
1618 DWORD len = strlenW( str );
1619 memcpy( *ptr, str, len * sizeof(WCHAR) );
1620 *ptr = (WCHAR *)*ptr + len;
1621 return len * sizeof(WCHAR);
1624 /***********************************************************************
1625 * create_startup_info
1627 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1628 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1629 const STARTUPINFOW *startup, DWORD *info_size )
1631 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1632 const WCHAR *title;
1633 startup_info_t *info;
1634 DWORD size;
1635 void *ptr;
1636 UNICODE_STRING newdir;
1637 WCHAR imagepath[MAX_PATH];
1638 HANDLE hstdin, hstdout, hstderr;
1640 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1641 lstrcpynW( imagepath, filename, MAX_PATH );
1642 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1643 lstrcpynW( imagepath, filename, MAX_PATH );
1645 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1647 newdir.Buffer = NULL;
1648 if (cur_dir)
1650 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1651 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1652 else
1653 cur_dir = NULL;
1655 if (!cur_dir)
1657 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1658 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1659 else
1660 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1662 title = startup->lpTitle ? startup->lpTitle : imagepath;
1664 size = sizeof(*info);
1665 size += strlenW( cur_dir ) * sizeof(WCHAR);
1666 size += cur_params->DllPath.Length;
1667 size += strlenW( imagepath ) * sizeof(WCHAR);
1668 size += strlenW( cmdline ) * sizeof(WCHAR);
1669 size += strlenW( title ) * sizeof(WCHAR);
1670 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1671 /* FIXME: shellinfo */
1672 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1673 size = (size + 1) & ~1;
1674 *info_size = size;
1676 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1678 info->console_flags = cur_params->ConsoleFlags;
1679 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1680 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1682 if (startup->dwFlags & STARTF_USESTDHANDLES)
1684 hstdin = startup->hStdInput;
1685 hstdout = startup->hStdOutput;
1686 hstderr = startup->hStdError;
1688 else
1690 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1691 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1692 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1694 info->hstdin = wine_server_obj_handle( hstdin );
1695 info->hstdout = wine_server_obj_handle( hstdout );
1696 info->hstderr = wine_server_obj_handle( hstderr );
1697 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1699 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1700 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1701 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1702 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1704 else
1706 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1707 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1708 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1711 info->x = startup->dwX;
1712 info->y = startup->dwY;
1713 info->xsize = startup->dwXSize;
1714 info->ysize = startup->dwYSize;
1715 info->xchars = startup->dwXCountChars;
1716 info->ychars = startup->dwYCountChars;
1717 info->attribute = startup->dwFillAttribute;
1718 info->flags = startup->dwFlags;
1719 info->show = startup->wShowWindow;
1721 ptr = info + 1;
1722 info->curdir_len = append_string( &ptr, cur_dir );
1723 info->dllpath_len = cur_params->DllPath.Length;
1724 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1725 ptr = (char *)ptr + cur_params->DllPath.Length;
1726 info->imagepath_len = append_string( &ptr, imagepath );
1727 info->cmdline_len = append_string( &ptr, cmdline );
1728 info->title_len = append_string( &ptr, title );
1729 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1730 if (startup->lpReserved2 && startup->cbReserved2)
1732 info->runtime_len = startup->cbReserved2;
1733 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1736 done:
1737 RtlFreeUnicodeString( &newdir );
1738 return info;
1741 /***********************************************************************
1742 * get_alternate_loader
1744 * Get the name of the alternate (32 or 64 bit) Wine loader.
1746 static const char *get_alternate_loader( char **ret_env )
1748 char *env;
1749 const char *loader = NULL;
1750 const char *loader_env = getenv( "WINELOADER" );
1752 *ret_env = NULL;
1754 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1756 if (loader_env)
1758 int len = strlen( loader_env );
1759 if (!is_win64)
1761 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1762 strcpy( env, "WINELOADER=" );
1763 strcat( env, loader_env );
1764 strcat( env, "64" );
1766 else
1768 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1769 strcpy( env, "WINELOADER=" );
1770 strcat( env, loader_env );
1771 len += sizeof("WINELOADER=") - 1;
1772 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1774 if (!loader)
1776 if ((loader = strrchr( env, '/' ))) loader++;
1777 else loader = env;
1779 *ret_env = env;
1781 if (!loader) loader = is_win64 ? "wine" : "wine64";
1782 return loader;
1785 #ifdef __APPLE__
1786 /***********************************************************************
1787 * terminate_main_thread
1789 * On some versions of Mac OS X, the execve system call fails with
1790 * ENOTSUP if the process has multiple threads. Wine is always multi-
1791 * threaded on Mac OS X because it specifically reserves the main thread
1792 * for use by the system frameworks (see apple_main_thread() in
1793 * libs/wine/loader.c). So, when we need to exec without first forking,
1794 * we need to terminate the main thread first. We do this by installing
1795 * a custom run loop source onto the main run loop and signaling it.
1796 * The source's "perform" callback is pthread_exit and it will be
1797 * executed on the main thread, terminating it.
1799 * Returns TRUE if there's still hope the main thread has terminated or
1800 * will soon. Return FALSE if we've given up.
1802 static BOOL terminate_main_thread(void)
1804 static int delayms;
1806 if (!delayms)
1808 CFRunLoopSourceContext source_context = { 0 };
1809 CFRunLoopSourceRef source;
1811 source_context.perform = pthread_exit;
1812 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1813 return FALSE;
1815 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1816 CFRunLoopSourceSignal( source );
1817 CFRunLoopWakeUp( CFRunLoopGetMain() );
1818 CFRelease( source );
1820 delayms = 20;
1823 if (delayms > 1000)
1824 return FALSE;
1826 usleep(delayms * 1000);
1827 delayms *= 2;
1829 return TRUE;
1831 #endif
1833 /***********************************************************************
1834 * get_process_cpu
1836 static int get_process_cpu( const WCHAR *filename, const struct binary_info *binary_info )
1838 switch (binary_info->arch)
1840 case IMAGE_FILE_MACHINE_I386: return CPU_x86;
1841 case IMAGE_FILE_MACHINE_AMD64: return CPU_x86_64;
1842 case IMAGE_FILE_MACHINE_POWERPC: return CPU_POWERPC;
1843 case IMAGE_FILE_MACHINE_ARM:
1844 case IMAGE_FILE_MACHINE_THUMB:
1845 case IMAGE_FILE_MACHINE_ARMNT: return CPU_ARM;
1846 case IMAGE_FILE_MACHINE_ARM64: return CPU_ARM64;
1848 ERR( "%s uses unsupported architecture (%04x)\n", debugstr_w(filename), binary_info->arch );
1849 return -1;
1852 /***********************************************************************
1853 * exec_loader
1855 static pid_t exec_loader( LPCWSTR cmd_line, unsigned int flags, int socketfd,
1856 int stdin_fd, int stdout_fd, const char *unixdir, char *winedebug,
1857 const struct binary_info *binary_info, int exec_only )
1859 pid_t pid;
1860 char *wineloader = NULL;
1861 const char *loader = NULL;
1862 char **argv;
1864 argv = build_argv( cmd_line, 1 );
1866 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1867 loader = get_alternate_loader( &wineloader );
1869 if (exec_only || !(pid = fork())) /* child */
1871 if (exec_only || !(pid = fork())) /* grandchild */
1873 char preloader_reserve[64], socket_env[64];
1875 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1877 int fd = open( "/dev/null", O_RDWR );
1878 setsid();
1879 /* close stdin and stdout */
1880 if (fd != -1)
1882 dup2( fd, 0 );
1883 dup2( fd, 1 );
1884 close( fd );
1887 else
1889 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1890 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1893 if (stdin_fd != -1) close( stdin_fd );
1894 if (stdout_fd != -1) close( stdout_fd );
1896 /* Reset signals that we previously set to SIG_IGN */
1897 signal( SIGPIPE, SIG_DFL );
1899 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
1900 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1901 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1903 putenv( preloader_reserve );
1904 putenv( socket_env );
1905 if (winedebug) putenv( winedebug );
1906 if (wineloader) putenv( wineloader );
1907 if (unixdir) chdir(unixdir);
1909 if (argv)
1913 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1915 #ifdef __APPLE__
1916 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1917 #else
1918 while (0);
1919 #endif
1921 _exit(1);
1924 _exit(pid == -1);
1927 if (pid != -1)
1929 /* reap child */
1930 pid_t wret;
1931 do {
1932 wret = waitpid(pid, NULL, 0);
1933 } while (wret < 0 && errno == EINTR);
1936 HeapFree( GetProcessHeap(), 0, wineloader );
1937 HeapFree( GetProcessHeap(), 0, argv );
1938 return pid;
1941 /***********************************************************************
1942 * create_process
1944 * Create a new process. If hFile is a valid handle we have an exe
1945 * file, otherwise it is a Winelib app.
1947 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1948 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1949 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1950 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1951 const struct binary_info *binary_info, int exec_only )
1953 static const char *cpu_names[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
1954 NTSTATUS status;
1955 BOOL success = FALSE;
1956 HANDLE process_info;
1957 WCHAR *env_end;
1958 char *winedebug = NULL;
1959 startup_info_t *startup_info;
1960 DWORD startup_info_size;
1961 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1962 pid_t pid;
1963 int err, cpu;
1965 if ((cpu = get_process_cpu( filename, binary_info )) == -1)
1967 SetLastError( ERROR_BAD_EXE_FORMAT );
1968 return FALSE;
1971 /* create the socket for the new process */
1973 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1975 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1976 return FALSE;
1978 #ifdef SO_PASSCRED
1979 else
1981 int enable = 1;
1982 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1984 #endif
1986 if (exec_only) /* things are much simpler in this case */
1988 wine_server_send_fd( socketfd[1] );
1989 close( socketfd[1] );
1990 SERVER_START_REQ( new_process )
1992 req->create_flags = flags;
1993 req->socket_fd = socketfd[1];
1994 req->exe_file = wine_server_obj_handle( hFile );
1995 req->cpu = cpu;
1996 status = wine_server_call( req );
1998 SERVER_END_REQ;
2000 switch (status)
2002 case STATUS_INVALID_IMAGE_WIN_64:
2003 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2004 break;
2005 case STATUS_INVALID_IMAGE_FORMAT:
2006 ERR( "%s not supported on this installation (%s binary)\n",
2007 debugstr_w(filename), cpu_names[cpu] );
2008 break;
2009 case STATUS_SUCCESS:
2010 exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2011 winedebug, binary_info, TRUE );
2013 close( socketfd[0] );
2014 SetLastError( RtlNtStatusToDosError( status ));
2015 return FALSE;
2018 RtlAcquirePebLock();
2020 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
2021 &startup_info_size )))
2023 RtlReleasePebLock();
2024 close( socketfd[0] );
2025 close( socketfd[1] );
2026 return FALSE;
2028 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
2029 env_end = env;
2030 while (*env_end)
2032 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
2033 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
2035 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
2036 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
2037 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
2039 env_end += strlenW(env_end) + 1;
2041 env_end++;
2043 wine_server_send_fd( socketfd[1] );
2044 close( socketfd[1] );
2046 /* create the process on the server side */
2048 SERVER_START_REQ( new_process )
2050 req->inherit_all = inherit;
2051 req->create_flags = flags;
2052 req->socket_fd = socketfd[1];
2053 req->exe_file = wine_server_obj_handle( hFile );
2054 req->process_access = PROCESS_ALL_ACCESS;
2055 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
2056 req->thread_access = THREAD_ALL_ACCESS;
2057 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
2058 req->cpu = cpu;
2059 req->info_size = startup_info_size;
2061 wine_server_add_data( req, startup_info, startup_info_size );
2062 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
2063 if (!(status = wine_server_call( req )))
2065 info->dwProcessId = (DWORD)reply->pid;
2066 info->dwThreadId = (DWORD)reply->tid;
2067 info->hProcess = wine_server_ptr_handle( reply->phandle );
2068 info->hThread = wine_server_ptr_handle( reply->thandle );
2070 process_info = wine_server_ptr_handle( reply->info );
2072 SERVER_END_REQ;
2074 RtlReleasePebLock();
2075 if (status)
2077 switch (status)
2079 case STATUS_INVALID_IMAGE_WIN_64:
2080 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2081 break;
2082 case STATUS_INVALID_IMAGE_FORMAT:
2083 ERR( "%s not supported on this installation (%s binary)\n",
2084 debugstr_w(filename), cpu_names[cpu] );
2085 break;
2087 close( socketfd[0] );
2088 HeapFree( GetProcessHeap(), 0, startup_info );
2089 HeapFree( GetProcessHeap(), 0, winedebug );
2090 SetLastError( RtlNtStatusToDosError( status ));
2091 return FALSE;
2094 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
2096 if (startup_info->hstdin)
2097 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
2098 FILE_READ_DATA, &stdin_fd, NULL );
2099 if (startup_info->hstdout)
2100 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
2101 FILE_WRITE_DATA, &stdout_fd, NULL );
2103 HeapFree( GetProcessHeap(), 0, startup_info );
2105 /* create the child process */
2107 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2108 winedebug, binary_info, FALSE );
2110 if (stdin_fd != -1) close( stdin_fd );
2111 if (stdout_fd != -1) close( stdout_fd );
2112 close( socketfd[0] );
2113 HeapFree( GetProcessHeap(), 0, winedebug );
2114 if (pid == -1)
2116 FILE_SetDosError();
2117 goto error;
2120 /* wait for the new process info to be ready */
2122 WaitForSingleObject( process_info, INFINITE );
2123 SERVER_START_REQ( get_new_process_info )
2125 req->info = wine_server_obj_handle( process_info );
2126 wine_server_call( req );
2127 success = reply->success;
2128 err = reply->exit_code;
2130 SERVER_END_REQ;
2132 if (!success)
2134 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2135 goto error;
2137 CloseHandle( process_info );
2138 return success;
2140 error:
2141 CloseHandle( process_info );
2142 CloseHandle( info->hProcess );
2143 CloseHandle( info->hThread );
2144 info->hProcess = info->hThread = 0;
2145 info->dwProcessId = info->dwThreadId = 0;
2146 return FALSE;
2150 /***********************************************************************
2151 * create_vdm_process
2153 * Create a new VDM process for a 16-bit or DOS application.
2155 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2156 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2157 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2158 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2159 const struct binary_info *binary_info, int exec_only )
2161 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2163 BOOL ret;
2164 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
2165 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
2167 if (!new_cmd_line)
2169 SetLastError( ERROR_OUTOFMEMORY );
2170 return FALSE;
2172 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
2173 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2174 flags, startup, info, unixdir, binary_info, exec_only );
2175 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2176 return ret;
2180 /***********************************************************************
2181 * create_cmd_process
2183 * Create a new cmd shell process for a .BAT file.
2185 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2186 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2187 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2188 LPPROCESS_INFORMATION info )
2191 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2192 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2193 WCHAR comspec[MAX_PATH];
2194 WCHAR *newcmdline;
2195 BOOL ret;
2197 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2198 return FALSE;
2199 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2200 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2201 return FALSE;
2203 strcpyW( newcmdline, comspec );
2204 strcatW( newcmdline, slashcW );
2205 strcatW( newcmdline, cmd_line );
2206 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2207 flags, env, cur_dir, startup, info );
2208 HeapFree( GetProcessHeap(), 0, newcmdline );
2209 return ret;
2213 /*************************************************************************
2214 * get_file_name
2216 * Helper for CreateProcess: retrieve the file name to load from the
2217 * app name and command line. Store the file name in buffer, and
2218 * return a possibly modified command line.
2219 * Also returns a handle to the opened file if it's a Windows binary.
2221 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2222 int buflen, HANDLE *handle, struct binary_info *binary_info )
2224 static const WCHAR quotesW[] = {'"','%','s','"',0};
2226 WCHAR *name, *pos, *first_space, *ret = NULL;
2227 const WCHAR *p;
2229 /* if we have an app name, everything is easy */
2231 if (appname)
2233 /* use the unmodified app name as file name */
2234 lstrcpynW( buffer, appname, buflen );
2235 *handle = open_exe_file( buffer, binary_info );
2236 if (!(ret = cmdline) || !cmdline[0])
2238 /* no command-line, create one */
2239 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2240 sprintfW( ret, quotesW, appname );
2242 return ret;
2245 /* first check for a quoted file name */
2247 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2249 int len = p - cmdline - 1;
2250 /* extract the quoted portion as file name */
2251 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2252 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2253 name[len] = 0;
2255 if (!find_exe_file( name, buffer, buflen, handle, binary_info )) goto done;
2256 ret = cmdline; /* no change necessary */
2257 goto done;
2260 /* now try the command-line word by word */
2262 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2263 return NULL;
2264 pos = name;
2265 p = cmdline;
2266 first_space = NULL;
2268 for (;;)
2270 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2271 *pos = 0;
2272 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2274 ret = cmdline;
2275 break;
2277 if (!first_space) first_space = pos;
2278 if (!(*pos++ = *p++)) break;
2281 if (!ret)
2283 SetLastError( ERROR_FILE_NOT_FOUND );
2285 else if (first_space) /* build a new command-line with quotes */
2287 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2288 goto done;
2289 sprintfW( ret, quotesW, name );
2290 strcatW( ret, p );
2293 done:
2294 HeapFree( GetProcessHeap(), 0, name );
2295 return ret;
2299 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2300 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2301 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2302 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2303 LPPROCESS_INFORMATION info )
2305 BOOL retv = FALSE;
2306 HANDLE hFile = 0;
2307 char *unixdir = NULL;
2308 WCHAR name[MAX_PATH];
2309 WCHAR *tidy_cmdline, *p, *envW = env;
2310 struct binary_info binary_info;
2312 /* Process the AppName and/or CmdLine to get module name and path */
2314 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2316 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2317 &hFile, &binary_info )))
2318 return FALSE;
2319 if (hFile == INVALID_HANDLE_VALUE) goto done;
2321 /* Warn if unsupported features are used */
2323 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2324 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2325 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2326 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2327 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2329 if (cur_dir)
2331 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2333 SetLastError(ERROR_DIRECTORY);
2334 goto done;
2337 else
2339 WCHAR buf[MAX_PATH];
2340 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2343 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2345 char *e = env;
2346 DWORD lenW;
2348 while (*e) e += strlen(e) + 1;
2349 e++; /* final null */
2350 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, NULL, 0 );
2351 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2352 MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, envW, lenW );
2353 flags |= CREATE_UNICODE_ENVIRONMENT;
2356 info->hThread = info->hProcess = 0;
2357 info->dwProcessId = info->dwThreadId = 0;
2359 if (binary_info.flags & BINARY_FLAG_DLL)
2361 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2362 SetLastError( ERROR_BAD_EXE_FORMAT );
2364 else switch (binary_info.type)
2366 case BINARY_PE:
2367 TRACE( "starting %s as Win%d binary (%p-%p, arch %04x%s)\n",
2368 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2369 binary_info.res_start, binary_info.res_end, binary_info.arch,
2370 (binary_info.flags & BINARY_FLAG_FAKEDLL) ? ", fakedll" : "" );
2371 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2372 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2373 break;
2374 case BINARY_OS216:
2375 case BINARY_WIN16:
2376 case BINARY_DOS:
2377 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2378 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2379 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2380 break;
2381 case BINARY_UNIX_LIB:
2382 TRACE( "starting %s as %d-bit Winelib app\n",
2383 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2384 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2385 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2386 break;
2387 case BINARY_UNKNOWN:
2388 /* check for .com or .bat extension */
2389 if ((p = strrchrW( name, '.' )))
2391 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2393 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2394 binary_info.type = BINARY_DOS;
2395 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2396 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2397 inherit, flags, startup_info, info, unixdir,
2398 &binary_info, FALSE );
2399 break;
2401 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2403 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2404 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2405 inherit, flags, startup_info, info );
2406 break;
2409 /* fall through */
2410 case BINARY_UNIX_EXE:
2412 /* unknown file, try as unix executable */
2413 char *unix_name;
2415 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2417 if ((unix_name = wine_get_unix_file_name( name )))
2419 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2420 HeapFree( GetProcessHeap(), 0, unix_name );
2423 break;
2425 if (hFile) CloseHandle( hFile );
2427 done:
2428 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2429 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2430 HeapFree( GetProcessHeap(), 0, unixdir );
2431 if (retv)
2432 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2433 return retv;
2437 /**********************************************************************
2438 * CreateProcessA (KERNEL32.@)
2440 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2441 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2442 DWORD flags, LPVOID env, LPCSTR cur_dir,
2443 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2445 BOOL ret = FALSE;
2446 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2447 UNICODE_STRING desktopW, titleW;
2448 STARTUPINFOW infoW;
2450 desktopW.Buffer = NULL;
2451 titleW.Buffer = NULL;
2452 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2453 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2454 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2456 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2457 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2459 memcpy( &infoW, startup_info, sizeof(infoW) );
2460 infoW.lpDesktop = desktopW.Buffer;
2461 infoW.lpTitle = titleW.Buffer;
2463 if (startup_info->lpReserved)
2464 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2465 debugstr_a(startup_info->lpReserved));
2467 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2468 inherit, flags, env, cur_dirW, &infoW, info );
2469 done:
2470 HeapFree( GetProcessHeap(), 0, app_nameW );
2471 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2472 HeapFree( GetProcessHeap(), 0, cur_dirW );
2473 RtlFreeUnicodeString( &desktopW );
2474 RtlFreeUnicodeString( &titleW );
2475 return ret;
2479 /**********************************************************************
2480 * CreateProcessW (KERNEL32.@)
2482 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2483 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2484 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2485 LPPROCESS_INFORMATION info )
2487 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2488 inherit, flags, env, cur_dir, startup_info, info);
2492 /**********************************************************************
2493 * exec_process
2495 static void exec_process( LPCWSTR name )
2497 HANDLE hFile;
2498 WCHAR *p;
2499 STARTUPINFOW startup_info;
2500 PROCESS_INFORMATION info;
2501 struct binary_info binary_info;
2503 hFile = open_exe_file( name, &binary_info );
2504 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2506 memset( &startup_info, 0, sizeof(startup_info) );
2507 startup_info.cb = sizeof(startup_info);
2509 /* Determine executable type */
2511 if (binary_info.flags & BINARY_FLAG_DLL)
2513 CloseHandle( hFile );
2514 return;
2517 switch (binary_info.type)
2519 case BINARY_PE:
2520 TRACE( "starting %s as Win%d binary (%p-%p, arch %04x)\n",
2521 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2522 binary_info.res_start, binary_info.res_end, binary_info.arch );
2523 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2524 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2525 break;
2526 case BINARY_UNIX_LIB:
2527 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2528 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2529 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2530 break;
2531 case BINARY_UNKNOWN:
2532 /* check for .com or .pif extension */
2533 if (!(p = strrchrW( name, '.' ))) break;
2534 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2535 binary_info.type = BINARY_DOS;
2536 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2537 /* fall through */
2538 case BINARY_OS216:
2539 case BINARY_WIN16:
2540 case BINARY_DOS:
2541 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2542 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2543 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2544 break;
2545 default:
2546 break;
2548 CloseHandle( hFile );
2552 /***********************************************************************
2553 * wait_input_idle
2555 * Wrapper to call WaitForInputIdle USER function
2557 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2559 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2561 HMODULE mod = GetModuleHandleA( "user32.dll" );
2562 if (mod)
2564 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2565 if (ptr) return ptr( process, timeout );
2567 return 0;
2571 /***********************************************************************
2572 * WinExec (KERNEL32.@)
2574 UINT WINAPI DECLSPEC_HOTPATCH WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2576 PROCESS_INFORMATION info;
2577 STARTUPINFOA startup;
2578 char *cmdline;
2579 UINT ret;
2581 memset( &startup, 0, sizeof(startup) );
2582 startup.cb = sizeof(startup);
2583 startup.dwFlags = STARTF_USESHOWWINDOW;
2584 startup.wShowWindow = nCmdShow;
2586 /* cmdline needs to be writable for CreateProcess */
2587 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2588 strcpy( cmdline, lpCmdLine );
2590 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2591 0, NULL, NULL, &startup, &info ))
2593 /* Give 30 seconds to the app to come up */
2594 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2595 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2596 ret = 33;
2597 /* Close off the handles */
2598 CloseHandle( info.hThread );
2599 CloseHandle( info.hProcess );
2601 else if ((ret = GetLastError()) >= 32)
2603 FIXME("Strange error set by CreateProcess: %d\n", ret );
2604 ret = 11;
2606 HeapFree( GetProcessHeap(), 0, cmdline );
2607 return ret;
2611 /**********************************************************************
2612 * LoadModule (KERNEL32.@)
2614 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2616 LOADPARMS32 *params = paramBlock;
2617 PROCESS_INFORMATION info;
2618 STARTUPINFOA startup;
2619 DWORD ret;
2620 LPSTR cmdline, p;
2621 char filename[MAX_PATH];
2622 BYTE len;
2624 if (!name) return ERROR_FILE_NOT_FOUND;
2626 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2627 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2628 return GetLastError();
2630 len = (BYTE)params->lpCmdLine[0];
2631 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2632 return ERROR_NOT_ENOUGH_MEMORY;
2634 strcpy( cmdline, filename );
2635 p = cmdline + strlen(cmdline);
2636 *p++ = ' ';
2637 memcpy( p, params->lpCmdLine + 1, len );
2638 p[len] = 0;
2640 memset( &startup, 0, sizeof(startup) );
2641 startup.cb = sizeof(startup);
2642 if (params->lpCmdShow)
2644 startup.dwFlags = STARTF_USESHOWWINDOW;
2645 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2648 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2649 params->lpEnvAddress, NULL, &startup, &info ))
2651 /* Give 30 seconds to the app to come up */
2652 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2653 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2654 ret = 33;
2655 /* Close off the handles */
2656 CloseHandle( info.hThread );
2657 CloseHandle( info.hProcess );
2659 else if ((ret = GetLastError()) >= 32)
2661 FIXME("Strange error set by CreateProcess: %u\n", ret );
2662 ret = 11;
2665 HeapFree( GetProcessHeap(), 0, cmdline );
2666 return ret;
2670 /******************************************************************************
2671 * TerminateProcess (KERNEL32.@)
2673 * Terminates a process.
2675 * PARAMS
2676 * handle [I] Process to terminate.
2677 * exit_code [I] Exit code.
2679 * RETURNS
2680 * Success: TRUE.
2681 * Failure: FALSE, check GetLastError().
2683 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2685 NTSTATUS status;
2687 if (!handle)
2689 SetLastError( ERROR_INVALID_HANDLE );
2690 return FALSE;
2693 status = NtTerminateProcess( handle, exit_code );
2694 if (status) SetLastError( RtlNtStatusToDosError(status) );
2695 return !status;
2698 /***********************************************************************
2699 * ExitProcess (KERNEL32.@)
2701 * Exits the current process.
2703 * PARAMS
2704 * status [I] Status code to exit with.
2706 * RETURNS
2707 * Nothing.
2709 #ifdef __i386__
2710 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2711 "pushl %ebp\n\t"
2712 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2713 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2714 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2715 "pushl 8(%ebp)\n\t"
2716 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
2717 "leave\n\t"
2718 "ret $4" )
2719 #else
2721 void WINAPI ExitProcess( DWORD status )
2723 RtlExitUserProcess( status );
2726 #endif
2728 /***********************************************************************
2729 * GetExitCodeProcess [KERNEL32.@]
2731 * Gets termination status of specified process.
2733 * PARAMS
2734 * hProcess [in] Handle to the process.
2735 * lpExitCode [out] Address to receive termination status.
2737 * RETURNS
2738 * Success: TRUE
2739 * Failure: FALSE
2741 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2743 NTSTATUS status;
2744 PROCESS_BASIC_INFORMATION pbi;
2746 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2747 sizeof(pbi), NULL);
2748 if (status == STATUS_SUCCESS)
2750 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2751 return TRUE;
2753 SetLastError( RtlNtStatusToDosError(status) );
2754 return FALSE;
2758 /***********************************************************************
2759 * SetErrorMode (KERNEL32.@)
2761 UINT WINAPI SetErrorMode( UINT mode )
2763 UINT old;
2765 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2766 &old, sizeof(old), NULL );
2767 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2768 &mode, sizeof(mode) );
2769 return old;
2772 /***********************************************************************
2773 * GetErrorMode (KERNEL32.@)
2775 UINT WINAPI GetErrorMode( void )
2777 UINT mode;
2779 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2780 &mode, sizeof(mode), NULL );
2781 return mode;
2784 /**********************************************************************
2785 * TlsAlloc [KERNEL32.@]
2787 * Allocates a thread local storage index.
2789 * RETURNS
2790 * Success: TLS index.
2791 * Failure: 0xFFFFFFFF
2793 DWORD WINAPI TlsAlloc( void )
2795 DWORD index;
2796 PEB * const peb = NtCurrentTeb()->Peb;
2798 RtlAcquirePebLock();
2799 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 1 );
2800 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2801 else
2803 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2804 if (index != ~0U)
2806 if (!NtCurrentTeb()->TlsExpansionSlots &&
2807 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2808 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2810 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2811 index = ~0U;
2812 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2814 else
2816 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2817 index += TLS_MINIMUM_AVAILABLE;
2820 else SetLastError( ERROR_NO_MORE_ITEMS );
2822 RtlReleasePebLock();
2823 return index;
2827 /**********************************************************************
2828 * TlsFree [KERNEL32.@]
2830 * Releases a thread local storage index, making it available for reuse.
2832 * PARAMS
2833 * index [in] TLS index to free.
2835 * RETURNS
2836 * Success: TRUE
2837 * Failure: FALSE
2839 BOOL WINAPI TlsFree( DWORD index )
2841 BOOL ret;
2843 RtlAcquirePebLock();
2844 if (index >= TLS_MINIMUM_AVAILABLE)
2846 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2847 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2849 else
2851 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2852 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2854 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2855 else SetLastError( ERROR_INVALID_PARAMETER );
2856 RtlReleasePebLock();
2857 return ret;
2861 /**********************************************************************
2862 * TlsGetValue [KERNEL32.@]
2864 * Gets value in a thread's TLS slot.
2866 * PARAMS
2867 * index [in] TLS index to retrieve value for.
2869 * RETURNS
2870 * Success: Value stored in calling thread's TLS slot for index.
2871 * Failure: 0 and GetLastError() returns NO_ERROR.
2873 LPVOID WINAPI TlsGetValue( DWORD index )
2875 LPVOID ret;
2877 if (index < TLS_MINIMUM_AVAILABLE)
2879 ret = NtCurrentTeb()->TlsSlots[index];
2881 else
2883 index -= TLS_MINIMUM_AVAILABLE;
2884 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2886 SetLastError( ERROR_INVALID_PARAMETER );
2887 return NULL;
2889 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2890 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2892 SetLastError( ERROR_SUCCESS );
2893 return ret;
2897 /**********************************************************************
2898 * TlsSetValue [KERNEL32.@]
2900 * Stores a value in the thread's TLS slot.
2902 * PARAMS
2903 * index [in] TLS index to set value for.
2904 * value [in] Value to be stored.
2906 * RETURNS
2907 * Success: TRUE
2908 * Failure: FALSE
2910 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2912 if (index < TLS_MINIMUM_AVAILABLE)
2914 NtCurrentTeb()->TlsSlots[index] = value;
2916 else
2918 index -= TLS_MINIMUM_AVAILABLE;
2919 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2921 SetLastError( ERROR_INVALID_PARAMETER );
2922 return FALSE;
2924 if (!NtCurrentTeb()->TlsExpansionSlots &&
2925 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2926 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2928 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2929 return FALSE;
2931 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2933 return TRUE;
2937 /***********************************************************************
2938 * GetProcessFlags (KERNEL32.@)
2940 DWORD WINAPI GetProcessFlags( DWORD processid )
2942 IMAGE_NT_HEADERS *nt;
2943 DWORD flags = 0;
2945 if (processid && processid != GetCurrentProcessId()) return 0;
2947 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2949 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2950 flags |= PDB32_CONSOLE_PROC;
2952 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2953 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2954 return flags;
2958 /*********************************************************************
2959 * OpenProcess (KERNEL32.@)
2961 * Opens a handle to a process.
2963 * PARAMS
2964 * access [I] Desired access rights assigned to the returned handle.
2965 * inherit [I] Determines whether or not child processes will inherit the handle.
2966 * id [I] Process identifier of the process to get a handle to.
2968 * RETURNS
2969 * Success: Valid handle to the specified process.
2970 * Failure: NULL, check GetLastError().
2972 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2974 NTSTATUS status;
2975 HANDLE handle;
2976 OBJECT_ATTRIBUTES attr;
2977 CLIENT_ID cid;
2979 cid.UniqueProcess = ULongToHandle(id);
2980 cid.UniqueThread = 0; /* FIXME ? */
2982 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2983 attr.RootDirectory = NULL;
2984 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2985 attr.SecurityDescriptor = NULL;
2986 attr.SecurityQualityOfService = NULL;
2987 attr.ObjectName = NULL;
2989 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2991 status = NtOpenProcess(&handle, access, &attr, &cid);
2992 if (status != STATUS_SUCCESS)
2994 SetLastError( RtlNtStatusToDosError(status) );
2995 return NULL;
2997 return handle;
3001 /*********************************************************************
3002 * GetProcessId (KERNEL32.@)
3004 * Gets the a unique identifier of a process.
3006 * PARAMS
3007 * hProcess [I] Handle to the process.
3009 * RETURNS
3010 * Success: TRUE.
3011 * Failure: FALSE, check GetLastError().
3013 * NOTES
3015 * The identifier is unique only on the machine and only until the process
3016 * exits (including system shutdown).
3018 DWORD WINAPI GetProcessId( HANDLE hProcess )
3020 NTSTATUS status;
3021 PROCESS_BASIC_INFORMATION pbi;
3023 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3024 sizeof(pbi), NULL);
3025 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
3026 SetLastError( RtlNtStatusToDosError(status) );
3027 return 0;
3031 /*********************************************************************
3032 * CloseHandle (KERNEL32.@)
3034 * Closes a handle.
3036 * PARAMS
3037 * handle [I] Handle to close.
3039 * RETURNS
3040 * Success: TRUE.
3041 * Failure: FALSE, check GetLastError().
3043 BOOL WINAPI CloseHandle( HANDLE handle )
3045 NTSTATUS status;
3047 /* stdio handles need special treatment */
3048 if (handle == (HANDLE)STD_INPUT_HANDLE)
3049 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
3050 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
3051 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
3052 else if (handle == (HANDLE)STD_ERROR_HANDLE)
3053 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
3055 if (is_console_handle(handle))
3056 return CloseConsoleHandle(handle);
3058 status = NtClose( handle );
3059 if (status) SetLastError( RtlNtStatusToDosError(status) );
3060 return !status;
3064 /*********************************************************************
3065 * GetHandleInformation (KERNEL32.@)
3067 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
3069 OBJECT_DATA_INFORMATION info;
3070 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
3072 if (status) SetLastError( RtlNtStatusToDosError(status) );
3073 else if (flags)
3075 *flags = 0;
3076 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3077 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3079 return !status;
3083 /*********************************************************************
3084 * SetHandleInformation (KERNEL32.@)
3086 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3088 OBJECT_DATA_INFORMATION info;
3089 NTSTATUS status;
3091 /* if not setting both fields, retrieve current value first */
3092 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3093 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3095 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3097 SetLastError( RtlNtStatusToDosError(status) );
3098 return FALSE;
3101 if (mask & HANDLE_FLAG_INHERIT)
3102 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3103 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3104 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3106 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3107 if (status) SetLastError( RtlNtStatusToDosError(status) );
3108 return !status;
3112 /*********************************************************************
3113 * DuplicateHandle (KERNEL32.@)
3115 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3116 HANDLE dest_process, HANDLE *dest,
3117 DWORD access, BOOL inherit, DWORD options )
3119 NTSTATUS status;
3121 if (is_console_handle(source))
3123 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3124 if (source_process != dest_process ||
3125 source_process != GetCurrentProcess())
3127 SetLastError(ERROR_INVALID_PARAMETER);
3128 return FALSE;
3130 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3131 return (*dest != INVALID_HANDLE_VALUE);
3133 status = NtDuplicateObject( source_process, source, dest_process, dest,
3134 access, inherit ? OBJ_INHERIT : 0, options );
3135 if (status) SetLastError( RtlNtStatusToDosError(status) );
3136 return !status;
3140 /***********************************************************************
3141 * ConvertToGlobalHandle (KERNEL32.@)
3143 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3145 HANDLE ret = INVALID_HANDLE_VALUE;
3146 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3147 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3148 return ret;
3152 /***********************************************************************
3153 * SetHandleContext (KERNEL32.@)
3155 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3157 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3158 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3159 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3160 return FALSE;
3164 /***********************************************************************
3165 * GetHandleContext (KERNEL32.@)
3167 DWORD WINAPI GetHandleContext(HANDLE hnd)
3169 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3170 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3171 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3172 return 0;
3176 /***********************************************************************
3177 * CreateSocketHandle (KERNEL32.@)
3179 HANDLE WINAPI CreateSocketHandle(void)
3181 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3182 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3183 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3184 return INVALID_HANDLE_VALUE;
3188 /***********************************************************************
3189 * SetPriorityClass (KERNEL32.@)
3191 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3193 NTSTATUS status;
3194 PROCESS_PRIORITY_CLASS ppc;
3196 ppc.Foreground = FALSE;
3197 switch (priorityclass)
3199 case IDLE_PRIORITY_CLASS:
3200 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3201 case BELOW_NORMAL_PRIORITY_CLASS:
3202 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3203 case NORMAL_PRIORITY_CLASS:
3204 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3205 case ABOVE_NORMAL_PRIORITY_CLASS:
3206 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3207 case HIGH_PRIORITY_CLASS:
3208 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3209 case REALTIME_PRIORITY_CLASS:
3210 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3211 default:
3212 SetLastError(ERROR_INVALID_PARAMETER);
3213 return FALSE;
3216 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3217 &ppc, sizeof(ppc));
3219 if (status != STATUS_SUCCESS)
3221 SetLastError( RtlNtStatusToDosError(status) );
3222 return FALSE;
3224 return TRUE;
3228 /***********************************************************************
3229 * GetPriorityClass (KERNEL32.@)
3231 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3233 NTSTATUS status;
3234 PROCESS_BASIC_INFORMATION pbi;
3236 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3237 sizeof(pbi), NULL);
3238 if (status != STATUS_SUCCESS)
3240 SetLastError( RtlNtStatusToDosError(status) );
3241 return 0;
3243 switch (pbi.BasePriority)
3245 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3246 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3247 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3248 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3249 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3250 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3252 SetLastError( ERROR_INVALID_PARAMETER );
3253 return 0;
3257 /***********************************************************************
3258 * SetProcessAffinityMask (KERNEL32.@)
3260 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3262 NTSTATUS status;
3264 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3265 &affmask, sizeof(DWORD_PTR));
3266 if (status)
3268 SetLastError( RtlNtStatusToDosError(status) );
3269 return FALSE;
3271 return TRUE;
3275 /**********************************************************************
3276 * GetProcessAffinityMask (KERNEL32.@)
3278 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3280 NTSTATUS status = STATUS_SUCCESS;
3282 if (process_mask)
3284 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3285 process_mask, sizeof(*process_mask), NULL )))
3286 SetLastError( RtlNtStatusToDosError(status) );
3288 if (system_mask && status == STATUS_SUCCESS)
3290 SYSTEM_BASIC_INFORMATION info;
3292 if ((status = NtQuerySystemInformation( SystemBasicInformation, &info, sizeof(info), NULL )))
3293 SetLastError( RtlNtStatusToDosError(status) );
3294 else
3295 *system_mask = info.ActiveProcessorsAffinityMask;
3297 return !status;
3301 /***********************************************************************
3302 * GetProcessVersion (KERNEL32.@)
3304 DWORD WINAPI GetProcessVersion( DWORD pid )
3306 HANDLE process;
3307 NTSTATUS status;
3308 PROCESS_BASIC_INFORMATION pbi;
3309 SIZE_T count;
3310 PEB peb;
3311 IMAGE_DOS_HEADER dos;
3312 IMAGE_NT_HEADERS nt;
3313 DWORD ver = 0;
3315 if (!pid || pid == GetCurrentProcessId())
3317 IMAGE_NT_HEADERS *pnt;
3319 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3320 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3321 pnt->OptionalHeader.MinorSubsystemVersion);
3322 return 0;
3325 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3326 if (!process) return 0;
3328 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3329 if (status) goto err;
3331 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3332 if (status || count != sizeof(peb)) goto err;
3334 memset(&dos, 0, sizeof(dos));
3335 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3336 if (status || count != sizeof(dos)) goto err;
3337 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3339 memset(&nt, 0, sizeof(nt));
3340 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3341 if (status || count != sizeof(nt)) goto err;
3342 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3344 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3346 err:
3347 CloseHandle(process);
3349 if (status != STATUS_SUCCESS)
3350 SetLastError(RtlNtStatusToDosError(status));
3352 return ver;
3356 /***********************************************************************
3357 * SetProcessWorkingSetSize [KERNEL32.@]
3358 * Sets the min/max working set sizes for a specified process.
3360 * PARAMS
3361 * hProcess [I] Handle to the process of interest
3362 * minset [I] Specifies minimum working set size
3363 * maxset [I] Specifies maximum working set size
3365 * RETURNS
3366 * Success: TRUE
3367 * Failure: FALSE
3369 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3370 SIZE_T maxset)
3372 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3373 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3374 /* Trim the working set to zero */
3375 /* Swap the process out of physical RAM */
3377 return TRUE;
3380 /***********************************************************************
3381 * K32EmptyWorkingSet (KERNEL32.@)
3383 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3385 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3388 /***********************************************************************
3389 * GetProcessWorkingSetSize (KERNEL32.@)
3391 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3392 PSIZE_T maxset)
3394 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3395 /* 32 MB working set size */
3396 if (minset) *minset = 32*1024*1024;
3397 if (maxset) *maxset = 32*1024*1024;
3398 return TRUE;
3402 /***********************************************************************
3403 * SetProcessShutdownParameters (KERNEL32.@)
3405 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3407 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3408 shutdown_flags = flags;
3409 shutdown_priority = level;
3410 return TRUE;
3414 /***********************************************************************
3415 * GetProcessShutdownParameters (KERNEL32.@)
3418 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3420 *lpdwLevel = shutdown_priority;
3421 *lpdwFlags = shutdown_flags;
3422 return TRUE;
3426 /***********************************************************************
3427 * GetProcessPriorityBoost (KERNEL32.@)
3429 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3431 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3433 /* Report that no boost is present.. */
3434 *pDisablePriorityBoost = FALSE;
3436 return TRUE;
3439 /***********************************************************************
3440 * SetProcessPriorityBoost (KERNEL32.@)
3442 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3444 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3445 /* Say we can do it. I doubt the program will notice that we don't. */
3446 return TRUE;
3450 /***********************************************************************
3451 * ReadProcessMemory (KERNEL32.@)
3453 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3454 SIZE_T *bytes_read )
3456 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3457 if (status) SetLastError( RtlNtStatusToDosError(status) );
3458 return !status;
3462 /***********************************************************************
3463 * WriteProcessMemory (KERNEL32.@)
3465 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3466 SIZE_T *bytes_written )
3468 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3469 if (status) SetLastError( RtlNtStatusToDosError(status) );
3470 return !status;
3474 /****************************************************************************
3475 * FlushInstructionCache (KERNEL32.@)
3477 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3479 NTSTATUS status;
3480 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3481 if (status) SetLastError( RtlNtStatusToDosError(status) );
3482 return !status;
3486 /******************************************************************
3487 * GetProcessIoCounters (KERNEL32.@)
3489 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3491 NTSTATUS status;
3493 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3494 ioc, sizeof(*ioc), NULL);
3495 if (status) SetLastError( RtlNtStatusToDosError(status) );
3496 return !status;
3499 /******************************************************************
3500 * GetProcessHandleCount (KERNEL32.@)
3502 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3504 NTSTATUS status;
3506 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3507 cnt, sizeof(*cnt), NULL);
3508 if (status) SetLastError( RtlNtStatusToDosError(status) );
3509 return !status;
3512 /******************************************************************
3513 * QueryFullProcessImageNameA (KERNEL32.@)
3515 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3517 BOOL retval;
3518 DWORD pdwSizeW = *pdwSize;
3519 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3521 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3523 if(retval)
3524 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3525 lpExeName, *pdwSize, NULL, NULL));
3526 if(retval)
3527 *pdwSize = strlen(lpExeName);
3529 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3530 return retval;
3533 /******************************************************************
3534 * QueryFullProcessImageNameW (KERNEL32.@)
3536 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3538 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3539 UNICODE_STRING *dynamic_buffer = NULL;
3540 UNICODE_STRING *result = NULL;
3541 NTSTATUS status;
3542 DWORD needed;
3544 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3545 * is a DOS path and we depend on this. */
3546 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3547 sizeof(buffer) - sizeof(WCHAR), &needed);
3548 if (status == STATUS_INFO_LENGTH_MISMATCH)
3550 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3551 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3552 result = dynamic_buffer;
3554 else
3555 result = (PUNICODE_STRING)buffer;
3557 if (status) goto cleanup;
3559 if (dwFlags & PROCESS_NAME_NATIVE)
3561 WCHAR drive[3];
3562 WCHAR device[1024];
3563 DWORD ntlen, devlen;
3565 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3567 /* We cannot convert it to an NT device path so fail */
3568 status = STATUS_NO_SUCH_DEVICE;
3569 goto cleanup;
3572 /* Find this drive's NT device path */
3573 drive[0] = result->Buffer[0];
3574 drive[1] = ':';
3575 drive[2] = 0;
3576 if (!QueryDosDeviceW(drive, device, sizeof(device)/sizeof(*device)))
3578 status = STATUS_NO_SUCH_DEVICE;
3579 goto cleanup;
3582 devlen = lstrlenW(device);
3583 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3584 if (ntlen + 1 > *pdwSize)
3586 status = STATUS_BUFFER_TOO_SMALL;
3587 goto cleanup;
3589 *pdwSize = ntlen;
3591 memcpy(lpExeName, device, devlen * sizeof(*device));
3592 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3593 lpExeName[*pdwSize] = 0;
3594 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3596 else
3598 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3600 status = STATUS_BUFFER_TOO_SMALL;
3601 goto cleanup;
3604 *pdwSize = result->Length/sizeof(WCHAR);
3605 memcpy( lpExeName, result->Buffer, result->Length );
3606 lpExeName[*pdwSize] = 0;
3609 cleanup:
3610 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3611 if (status) SetLastError( RtlNtStatusToDosError(status) );
3612 return !status;
3615 /***********************************************************************
3616 * K32GetProcessImageFileNameA (KERNEL32.@)
3618 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3620 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3623 /***********************************************************************
3624 * K32GetProcessImageFileNameW (KERNEL32.@)
3626 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3628 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3631 /***********************************************************************
3632 * K32EnumProcesses (KERNEL32.@)
3634 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3636 SYSTEM_PROCESS_INFORMATION *spi;
3637 ULONG size = 0x4000;
3638 void *buf = NULL;
3639 NTSTATUS status;
3641 do {
3642 size *= 2;
3643 HeapFree(GetProcessHeap(), 0, buf);
3644 buf = HeapAlloc(GetProcessHeap(), 0, size);
3645 if (!buf)
3646 return FALSE;
3648 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3649 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3651 if (status != STATUS_SUCCESS)
3653 HeapFree(GetProcessHeap(), 0, buf);
3654 SetLastError(RtlNtStatusToDosError(status));
3655 return FALSE;
3658 spi = buf;
3660 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3662 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3663 *lpcbUsed += sizeof(DWORD);
3665 if (spi->NextEntryOffset == 0)
3666 break;
3668 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3671 HeapFree(GetProcessHeap(), 0, buf);
3672 return TRUE;
3675 /***********************************************************************
3676 * K32QueryWorkingSet (KERNEL32.@)
3678 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3680 NTSTATUS status;
3682 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3684 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3686 if (status)
3688 SetLastError( RtlNtStatusToDosError( status ) );
3689 return FALSE;
3691 return TRUE;
3694 /***********************************************************************
3695 * K32QueryWorkingSetEx (KERNEL32.@)
3697 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3699 NTSTATUS status;
3701 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3703 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3705 if (status)
3707 SetLastError( RtlNtStatusToDosError( status ) );
3708 return FALSE;
3710 return TRUE;
3713 /***********************************************************************
3714 * K32GetProcessMemoryInfo (KERNEL32.@)
3716 * Retrieve memory usage information for a given process
3719 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3720 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3722 NTSTATUS status;
3723 VM_COUNTERS vmc;
3725 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3727 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3728 return FALSE;
3731 status = NtQueryInformationProcess(process, ProcessVmCounters,
3732 &vmc, sizeof(vmc), NULL);
3734 if (status)
3736 SetLastError(RtlNtStatusToDosError(status));
3737 return FALSE;
3740 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3741 pmc->PageFaultCount = vmc.PageFaultCount;
3742 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3743 pmc->WorkingSetSize = vmc.WorkingSetSize;
3744 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3745 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3746 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3747 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3748 pmc->PagefileUsage = vmc.PagefileUsage;
3749 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3751 return TRUE;
3754 /***********************************************************************
3755 * ProcessIdToSessionId (KERNEL32.@)
3756 * This function is available on Terminal Server 4SP4 and Windows 2000
3758 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3760 if (procid != GetCurrentProcessId())
3761 FIXME("Unsupported for other processes.\n");
3763 *sessionid_ptr = NtCurrentTeb()->Peb->SessionId;
3764 return TRUE;
3768 /***********************************************************************
3769 * RegisterServiceProcess (KERNEL32.@)
3771 * A service process calls this function to ensure that it continues to run
3772 * even after a user logged off.
3774 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3776 /* I don't think that Wine needs to do anything in this function */
3777 return 1; /* success */
3781 /**********************************************************************
3782 * IsWow64Process (KERNEL32.@)
3784 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3786 ULONG_PTR pbi;
3787 NTSTATUS status;
3789 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3791 if (status != STATUS_SUCCESS)
3793 SetLastError( RtlNtStatusToDosError( status ) );
3794 return FALSE;
3796 *Wow64Process = (pbi != 0);
3797 return TRUE;
3801 /***********************************************************************
3802 * GetCurrentProcess (KERNEL32.@)
3804 * Get a handle to the current process.
3806 * PARAMS
3807 * None.
3809 * RETURNS
3810 * A handle representing the current process.
3812 #undef GetCurrentProcess
3813 HANDLE WINAPI GetCurrentProcess(void)
3815 return (HANDLE)~(ULONG_PTR)0;
3818 /***********************************************************************
3819 * GetLogicalProcessorInformation (KERNEL32.@)
3821 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3823 NTSTATUS status;
3825 TRACE("(%p,%p)\n", buffer, pBufLen);
3827 if(!pBufLen)
3829 SetLastError(ERROR_INVALID_PARAMETER);
3830 return FALSE;
3833 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
3835 if (status == STATUS_INFO_LENGTH_MISMATCH)
3837 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3838 return FALSE;
3840 if (status != STATUS_SUCCESS)
3842 SetLastError( RtlNtStatusToDosError( status ) );
3843 return FALSE;
3845 return TRUE;
3848 /***********************************************************************
3849 * GetLogicalProcessorInformationEx (KERNEL32.@)
3851 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, DWORD *len)
3853 NTSTATUS status;
3855 TRACE("(%u,%p,%p)\n", relationship, buffer, len);
3857 if (!len)
3859 SetLastError( ERROR_INVALID_PARAMETER );
3860 return FALSE;
3863 status = NtQuerySystemInformationEx( SystemLogicalProcessorInformationEx, &relationship, sizeof(relationship),
3864 buffer, *len, len );
3865 if (status == STATUS_INFO_LENGTH_MISMATCH)
3867 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3868 return FALSE;
3870 if (status != STATUS_SUCCESS)
3872 SetLastError( RtlNtStatusToDosError( status ) );
3873 return FALSE;
3875 return TRUE;
3878 /***********************************************************************
3879 * CmdBatNotification (KERNEL32.@)
3881 * Notifies the system that a batch file has started or finished.
3883 * PARAMS
3884 * bBatchRunning [I] TRUE if a batch file has started or
3885 * FALSE if a batch file has finished executing.
3887 * RETURNS
3888 * Unknown.
3890 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3892 FIXME("%d\n", bBatchRunning);
3893 return FALSE;
3897 /***********************************************************************
3898 * RegisterApplicationRestart (KERNEL32.@)
3900 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3902 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3904 return S_OK;
3907 /**********************************************************************
3908 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3910 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3912 static int once;
3913 if (!once++) FIXME("stub\n");
3914 /* Return current session id. */
3915 return NtCurrentTeb()->Peb->SessionId;
3918 /**********************************************************************
3919 * GetSystemDEPPolicy (KERNEL32.@)
3921 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3923 FIXME("stub\n");
3924 return OptIn;
3927 /**********************************************************************
3928 * SetProcessDEPPolicy (KERNEL32.@)
3930 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3932 FIXME("(%d): stub\n", newDEP);
3933 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3934 return FALSE;
3937 /**********************************************************************
3938 * ApplicationRecoveryFinished (KERNEL32.@)
3940 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
3942 FIXME(": stub\n");
3943 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3946 /**********************************************************************
3947 * ApplicationRecoveryInProgress (KERNEL32.@)
3949 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
3951 FIXME(":%p stub\n", canceled);
3952 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3953 return E_FAIL;
3956 /**********************************************************************
3957 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3959 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
3961 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
3962 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3963 return E_FAIL;
3966 /**********************************************************************
3967 * GetNumaHighestNodeNumber (KERNEL32.@)
3969 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
3971 *highestnode = 0;
3972 FIXME("(%p): semi-stub\n", highestnode);
3973 return TRUE;
3976 /**********************************************************************
3977 * GetNumaNodeProcessorMask (KERNEL32.@)
3979 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
3981 FIXME("(%c %p): stub\n", node, mask);
3982 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3983 return FALSE;
3986 /**********************************************************************
3987 * GetNumaAvailableMemoryNode (KERNEL32.@)
3989 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
3991 FIXME("(%c %p): stub\n", node, available_bytes);
3992 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3993 return FALSE;
3996 /***********************************************************************
3997 * GetNumaProcessorNode (KERNEL32.@)
3999 BOOL WINAPI GetNumaProcessorNode(UCHAR processor, PUCHAR node)
4001 SYSTEM_INFO si;
4003 TRACE("(%d, %p)\n", processor, node);
4005 GetSystemInfo( &si );
4006 if (processor < si.dwNumberOfProcessors)
4008 *node = 0;
4009 return TRUE;
4012 *node = 0xFF;
4013 SetLastError(ERROR_INVALID_PARAMETER);
4014 return FALSE;
4017 /**********************************************************************
4018 * GetProcessDEPPolicy (KERNEL32.@)
4020 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
4022 NTSTATUS status;
4023 ULONG dep_flags;
4025 TRACE("(%p %p %p)\n", process, flags, permanent);
4027 status = NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
4028 &dep_flags, sizeof(dep_flags), NULL );
4029 if (!status)
4032 if (flags)
4034 *flags = 0;
4035 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE)
4036 *flags |= PROCESS_DEP_ENABLE;
4037 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION)
4038 *flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
4041 if (permanent)
4042 *permanent = (dep_flags & MEM_EXECUTE_OPTION_PERMANENT) != 0;
4045 if (status) SetLastError( RtlNtStatusToDosError(status) );
4046 return !status;
4049 /**********************************************************************
4050 * FlushProcessWriteBuffers (KERNEL32.@)
4052 VOID WINAPI FlushProcessWriteBuffers(void)
4054 static int once = 0;
4056 if (!once++)
4057 FIXME(": stub\n");
4060 /***********************************************************************
4061 * UnregisterApplicationRestart (KERNEL32.@)
4063 HRESULT WINAPI UnregisterApplicationRestart(void)
4065 FIXME(": stub\n");
4066 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4067 return S_OK;
4070 /***********************************************************************
4071 * GetSystemFirmwareTable (KERNEL32.@)
4073 UINT WINAPI GetSystemFirmwareTable(DWORD provider, DWORD id, PVOID buffer, DWORD size)
4075 FIXME("(%d %d %p %d):stub\n", provider, id, buffer, size);
4076 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4077 return 0;