ddraw/tests: Test d3d2 and 3 drawing with non-standard viewports.
[wine.git] / dlls / kernel32 / process.c
blob5b584accae3b33761aedd90cf3af0e356a665df1
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 BOOL shift_strings;
1120 char *p, *name;
1121 int i;
1123 #ifdef HAVE_SETPROCTITLE
1124 setproctitle("-%s", argv[1]);
1125 shift_strings = FALSE;
1126 #else
1127 p = argv[0];
1129 shift_strings = (argc >= 2);
1130 for (i = 1; i < argc; i++)
1132 p += strlen(p) + 1;
1133 if (p != argv[i])
1135 shift_strings = FALSE;
1136 break;
1139 #endif
1141 if (shift_strings)
1143 int offset = argv[1] - argv[0];
1144 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1145 memmove( argv[0], argv[1], end - argv[1] );
1146 memset( end - offset, 0, offset );
1147 for (i = 1; i < argc; i++)
1148 argv[i-1] = argv[i] - offset;
1149 argv[i-1] = NULL;
1151 else
1153 /* remove argv[0] */
1154 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1157 name = argv[0];
1158 if ((p = strrchr( name, '\\' ))) name = p + 1;
1159 if ((p = strrchr( name, '/' ))) name = p + 1;
1161 #if defined(HAVE_SETPROGNAME)
1162 setprogname( name );
1163 #endif
1165 #ifdef HAVE_PRCTL
1166 #ifndef PR_SET_NAME
1167 # define PR_SET_NAME 15
1168 #endif
1169 prctl( PR_SET_NAME, name );
1170 #endif /* HAVE_PRCTL */
1174 /***********************************************************************
1175 * __wine_kernel_init
1177 * Wine initialisation: load and start the main exe file.
1179 void CDECL __wine_kernel_init(void)
1181 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1182 static const WCHAR dotW[] = {'.',0};
1184 WCHAR *p, main_exe_name[MAX_PATH+1];
1185 PEB *peb = NtCurrentTeb()->Peb;
1186 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1187 HANDLE boot_events[2];
1188 BOOL got_environment = TRUE;
1190 /* Initialize everything */
1192 setbuf(stdout,NULL);
1193 setbuf(stderr,NULL);
1194 kernel32_handle = GetModuleHandleW(kernel32W);
1195 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1197 LOCALE_Init();
1199 if (!params->Environment)
1201 /* Copy the parent environment */
1202 if (!build_initial_environment()) exit(1);
1204 /* convert old configuration to new format */
1205 convert_old_config();
1207 got_environment = set_registry_environment( FALSE );
1208 set_additional_environment();
1211 init_windows_dirs();
1212 init_current_directory( &params->CurrentDirectory );
1214 set_process_name( __wine_main_argc, __wine_main_argv );
1215 set_library_wargv( __wine_main_argv );
1216 boot_events[0] = boot_events[1] = 0;
1218 if (peb->ProcessParameters->ImagePathName.Buffer)
1220 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1222 else
1224 struct binary_info binary_info;
1226 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1227 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1229 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1230 ExitProcess( GetLastError() );
1232 update_library_argv0( main_exe_name );
1233 if (!build_command_line( __wine_main_wargv )) goto error;
1234 start_wineboot( boot_events );
1237 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1238 p = strrchrW( main_exe_name, '.' );
1239 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1241 TRACE( "starting process name=%s argv[0]=%s\n",
1242 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1244 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1245 MODULE_get_dll_load_path(main_exe_name) );
1247 if (boot_events[0])
1249 DWORD timeout = 2 * 60 * 1000, count = 1;
1251 if (boot_events[1]) count++;
1252 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1253 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1254 ERR( "boot event wait timed out\n" );
1255 CloseHandle( boot_events[0] );
1256 if (boot_events[1]) CloseHandle( boot_events[1] );
1257 /* reload environment now that wineboot has run */
1258 set_registry_environment( got_environment );
1259 set_additional_environment();
1261 set_wow64_environment();
1263 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1265 DWORD_PTR args[1];
1266 WCHAR msgW[1024];
1267 char msg[1024];
1268 DWORD error = GetLastError();
1270 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1271 if (error == ERROR_BAD_EXE_FORMAT ||
1272 error == ERROR_INVALID_ADDRESS ||
1273 error == ERROR_NOT_ENOUGH_MEMORY)
1275 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1276 /* if we get back here, it failed */
1278 else if (error == ERROR_MOD_NOT_FOUND)
1280 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1281 else p = main_exe_name;
1282 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1284 /* args 1 and 2 are --app-name full_path */
1285 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1286 debugstr_w(__wine_main_wargv[3]) );
1287 ExitProcess( ERROR_BAD_EXE_FORMAT );
1289 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1290 ExitProcess( ERROR_FILE_NOT_FOUND );
1292 args[0] = (DWORD_PTR)main_exe_name;
1293 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1294 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1295 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1296 MESSAGE( "wine: %s", msg );
1297 ExitProcess( error );
1300 if (!params->CurrentDirectory.Handle) chdir("/"); /* avoid locking removable devices */
1302 LdrInitializeThunk( start_process, 0, 0, 0 );
1304 error:
1305 ExitProcess( GetLastError() );
1309 /***********************************************************************
1310 * build_argv
1312 * Build an argv array from a command-line.
1313 * 'reserved' is the number of args to reserve before the first one.
1315 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1317 int argc;
1318 char** argv;
1319 char *arg,*s,*d,*cmdline;
1320 int in_quotes,bcount,len;
1322 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1323 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1324 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1326 argc=reserved+1;
1327 bcount=0;
1328 in_quotes=0;
1329 s=cmdline;
1330 while (1) {
1331 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1332 /* space */
1333 argc++;
1334 /* skip the remaining spaces */
1335 while (*s==' ' || *s=='\t') {
1336 s++;
1338 if (*s=='\0')
1339 break;
1340 bcount=0;
1341 continue;
1342 } else if (*s=='\\') {
1343 /* '\', count them */
1344 bcount++;
1345 } else if ((*s=='"') && ((bcount & 1)==0)) {
1346 /* unescaped '"' */
1347 in_quotes=!in_quotes;
1348 bcount=0;
1349 } else {
1350 /* a regular character */
1351 bcount=0;
1353 s++;
1355 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1357 HeapFree( GetProcessHeap(), 0, cmdline );
1358 return NULL;
1361 arg = d = s = (char *)(argv + argc);
1362 memcpy( d, cmdline, len );
1363 bcount=0;
1364 in_quotes=0;
1365 argc=reserved;
1366 while (*s) {
1367 if ((*s==' ' || *s=='\t') && !in_quotes) {
1368 /* Close the argument and copy it */
1369 *d=0;
1370 argv[argc++]=arg;
1372 /* skip the remaining spaces */
1373 do {
1374 s++;
1375 } while (*s==' ' || *s=='\t');
1377 /* Start with a new argument */
1378 arg=d=s;
1379 bcount=0;
1380 } else if (*s=='\\') {
1381 /* '\\' */
1382 *d++=*s++;
1383 bcount++;
1384 } else if (*s=='"') {
1385 /* '"' */
1386 if ((bcount & 1)==0) {
1387 /* Preceded by an even number of '\', this is half that
1388 * number of '\', plus a '"' which we discard.
1390 d-=bcount/2;
1391 s++;
1392 in_quotes=!in_quotes;
1393 } else {
1394 /* Preceded by an odd number of '\', this is half that
1395 * number of '\' followed by a '"'
1397 d=d-bcount/2-1;
1398 *d++='"';
1399 s++;
1401 bcount=0;
1402 } else {
1403 /* a regular character */
1404 *d++=*s++;
1405 bcount=0;
1408 if (*arg) {
1409 *d='\0';
1410 argv[argc++]=arg;
1412 argv[argc]=NULL;
1414 HeapFree( GetProcessHeap(), 0, cmdline );
1415 return argv;
1419 /***********************************************************************
1420 * build_envp
1422 * Build the environment of a new child process.
1424 static char **build_envp( const WCHAR *envW )
1426 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1428 const WCHAR *end;
1429 char **envp;
1430 char *env, *p;
1431 int count = 1, length;
1432 unsigned int i;
1434 for (end = envW; *end; count++) end += strlenW(end) + 1;
1435 end++;
1436 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1437 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1438 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1440 for (p = env; *p; p += strlen(p) + 1)
1441 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1443 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1445 if (!(p = getenv(unix_vars[i]))) continue;
1446 length += strlen(unix_vars[i]) + strlen(p) + 2;
1447 count++;
1450 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1452 char **envptr = envp;
1453 char *dst = (char *)(envp + count);
1455 /* some variables must not be modified, so we get them directly from the unix env */
1456 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1458 if (!(p = getenv(unix_vars[i]))) continue;
1459 *envptr++ = strcpy( dst, unix_vars[i] );
1460 strcat( dst, "=" );
1461 strcat( dst, p );
1462 dst += strlen(dst) + 1;
1465 /* now put the Windows environment strings */
1466 for (p = env; *p; p += strlen(p) + 1)
1468 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1469 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1470 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1471 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1472 if (is_special_env_var( p )) /* prefix it with "WINE" */
1474 *envptr++ = strcpy( dst, "WINE" );
1475 strcat( dst, p );
1477 else
1479 *envptr++ = strcpy( dst, p );
1481 dst += strlen(dst) + 1;
1483 *envptr = 0;
1485 HeapFree( GetProcessHeap(), 0, env );
1486 return envp;
1490 /***********************************************************************
1491 * fork_and_exec
1493 * Fork and exec a new Unix binary, checking for errors.
1495 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1496 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1498 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1499 int pid, err;
1500 char **argv, **envp;
1502 if (!env) env = GetEnvironmentStringsW();
1504 #ifdef HAVE_PIPE2
1505 if (pipe2( fd, O_CLOEXEC ) == -1)
1506 #endif
1508 if (pipe(fd) == -1)
1510 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1511 return -1;
1513 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1514 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1517 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1519 HANDLE hstdin, hstdout, hstderr;
1521 if (startup->dwFlags & STARTF_USESTDHANDLES)
1523 hstdin = startup->hStdInput;
1524 hstdout = startup->hStdOutput;
1525 hstderr = startup->hStdError;
1527 else
1529 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1530 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1531 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1534 if (is_console_handle( hstdin ))
1535 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1536 if (is_console_handle( hstdout ))
1537 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1538 if (is_console_handle( hstderr ))
1539 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1540 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1541 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1542 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1545 argv = build_argv( cmdline, 0 );
1546 envp = build_envp( env );
1548 if (!(pid = fork())) /* child */
1550 if (!(pid = fork())) /* grandchild */
1552 close( fd[0] );
1554 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1556 int nullfd = open( "/dev/null", O_RDWR );
1557 setsid();
1558 /* close stdin and stdout */
1559 if (nullfd != -1)
1561 dup2( nullfd, 0 );
1562 dup2( nullfd, 1 );
1563 close( nullfd );
1566 else
1568 if (stdin_fd != -1)
1570 dup2( stdin_fd, 0 );
1571 close( stdin_fd );
1573 if (stdout_fd != -1)
1575 dup2( stdout_fd, 1 );
1576 close( stdout_fd );
1578 if (stderr_fd != -1)
1580 dup2( stderr_fd, 2 );
1581 close( stderr_fd );
1585 /* Reset signals that we previously set to SIG_IGN */
1586 signal( SIGPIPE, SIG_DFL );
1588 if (newdir) chdir(newdir);
1590 if (argv && envp) execve( filename, argv, envp );
1593 if (pid <= 0) /* grandchild if exec failed or child if fork failed */
1595 err = errno;
1596 write( fd[1], &err, sizeof(err) );
1597 _exit(1);
1600 _exit(0); /* child if fork succeeded */
1602 HeapFree( GetProcessHeap(), 0, argv );
1603 HeapFree( GetProcessHeap(), 0, envp );
1604 if (stdin_fd != -1) close( stdin_fd );
1605 if (stdout_fd != -1) close( stdout_fd );
1606 if (stderr_fd != -1) close( stderr_fd );
1607 close( fd[1] );
1608 if (pid != -1)
1610 /* reap child */
1611 do {
1612 err = waitpid(pid, NULL, 0);
1613 } while (err < 0 && errno == EINTR);
1615 if (read( fd[0], &err, sizeof(err) ) > 0) /* exec or second fork failed */
1617 errno = err;
1618 pid = -1;
1621 if (pid == -1) FILE_SetDosError();
1622 close( fd[0] );
1623 return pid;
1627 static inline DWORD append_string( void **ptr, const WCHAR *str )
1629 DWORD len = strlenW( str );
1630 memcpy( *ptr, str, len * sizeof(WCHAR) );
1631 *ptr = (WCHAR *)*ptr + len;
1632 return len * sizeof(WCHAR);
1635 /***********************************************************************
1636 * create_startup_info
1638 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1639 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1640 const STARTUPINFOW *startup, DWORD *info_size )
1642 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1643 const WCHAR *title;
1644 startup_info_t *info;
1645 DWORD size;
1646 void *ptr;
1647 UNICODE_STRING newdir;
1648 WCHAR imagepath[MAX_PATH];
1649 HANDLE hstdin, hstdout, hstderr;
1651 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1652 lstrcpynW( imagepath, filename, MAX_PATH );
1653 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1654 lstrcpynW( imagepath, filename, MAX_PATH );
1656 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1658 newdir.Buffer = NULL;
1659 if (cur_dir)
1661 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1662 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1663 else
1664 cur_dir = NULL;
1666 if (!cur_dir)
1668 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1669 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1670 else
1671 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1673 title = startup->lpTitle ? startup->lpTitle : imagepath;
1675 size = sizeof(*info);
1676 size += strlenW( cur_dir ) * sizeof(WCHAR);
1677 size += cur_params->DllPath.Length;
1678 size += strlenW( imagepath ) * sizeof(WCHAR);
1679 size += strlenW( cmdline ) * sizeof(WCHAR);
1680 size += strlenW( title ) * sizeof(WCHAR);
1681 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1682 /* FIXME: shellinfo */
1683 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1684 size = (size + 1) & ~1;
1685 *info_size = size;
1687 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1689 info->console_flags = cur_params->ConsoleFlags;
1690 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1691 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1693 if (startup->dwFlags & STARTF_USESTDHANDLES)
1695 hstdin = startup->hStdInput;
1696 hstdout = startup->hStdOutput;
1697 hstderr = startup->hStdError;
1699 else
1701 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1702 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1703 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1705 info->hstdin = wine_server_obj_handle( hstdin );
1706 info->hstdout = wine_server_obj_handle( hstdout );
1707 info->hstderr = wine_server_obj_handle( hstderr );
1708 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1710 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1711 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1712 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1713 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1715 else
1717 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1718 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1719 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1722 info->x = startup->dwX;
1723 info->y = startup->dwY;
1724 info->xsize = startup->dwXSize;
1725 info->ysize = startup->dwYSize;
1726 info->xchars = startup->dwXCountChars;
1727 info->ychars = startup->dwYCountChars;
1728 info->attribute = startup->dwFillAttribute;
1729 info->flags = startup->dwFlags;
1730 info->show = startup->wShowWindow;
1732 ptr = info + 1;
1733 info->curdir_len = append_string( &ptr, cur_dir );
1734 info->dllpath_len = cur_params->DllPath.Length;
1735 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1736 ptr = (char *)ptr + cur_params->DllPath.Length;
1737 info->imagepath_len = append_string( &ptr, imagepath );
1738 info->cmdline_len = append_string( &ptr, cmdline );
1739 info->title_len = append_string( &ptr, title );
1740 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1741 if (startup->lpReserved2 && startup->cbReserved2)
1743 info->runtime_len = startup->cbReserved2;
1744 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1747 done:
1748 RtlFreeUnicodeString( &newdir );
1749 return info;
1752 /***********************************************************************
1753 * get_alternate_loader
1755 * Get the name of the alternate (32 or 64 bit) Wine loader.
1757 static const char *get_alternate_loader( char **ret_env )
1759 char *env;
1760 const char *loader = NULL;
1761 const char *loader_env = getenv( "WINELOADER" );
1763 *ret_env = NULL;
1765 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1767 if (loader_env)
1769 int len = strlen( loader_env );
1770 if (!is_win64)
1772 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1773 strcpy( env, "WINELOADER=" );
1774 strcat( env, loader_env );
1775 strcat( env, "64" );
1777 else
1779 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1780 strcpy( env, "WINELOADER=" );
1781 strcat( env, loader_env );
1782 len += sizeof("WINELOADER=") - 1;
1783 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1785 if (!loader)
1787 if ((loader = strrchr( env, '/' ))) loader++;
1788 else loader = env;
1790 *ret_env = env;
1792 if (!loader) loader = is_win64 ? "wine" : "wine64";
1793 return loader;
1796 #ifdef __APPLE__
1797 /***********************************************************************
1798 * terminate_main_thread
1800 * On some versions of Mac OS X, the execve system call fails with
1801 * ENOTSUP if the process has multiple threads. Wine is always multi-
1802 * threaded on Mac OS X because it specifically reserves the main thread
1803 * for use by the system frameworks (see apple_main_thread() in
1804 * libs/wine/loader.c). So, when we need to exec without first forking,
1805 * we need to terminate the main thread first. We do this by installing
1806 * a custom run loop source onto the main run loop and signaling it.
1807 * The source's "perform" callback is pthread_exit and it will be
1808 * executed on the main thread, terminating it.
1810 * Returns TRUE if there's still hope the main thread has terminated or
1811 * will soon. Return FALSE if we've given up.
1813 static BOOL terminate_main_thread(void)
1815 static int delayms;
1817 if (!delayms)
1819 CFRunLoopSourceContext source_context = { 0 };
1820 CFRunLoopSourceRef source;
1822 source_context.perform = pthread_exit;
1823 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1824 return FALSE;
1826 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1827 CFRunLoopSourceSignal( source );
1828 CFRunLoopWakeUp( CFRunLoopGetMain() );
1829 CFRelease( source );
1831 delayms = 20;
1834 if (delayms > 1000)
1835 return FALSE;
1837 usleep(delayms * 1000);
1838 delayms *= 2;
1840 return TRUE;
1842 #endif
1844 /***********************************************************************
1845 * get_process_cpu
1847 static int get_process_cpu( const WCHAR *filename, const struct binary_info *binary_info )
1849 switch (binary_info->arch)
1851 case IMAGE_FILE_MACHINE_I386: return CPU_x86;
1852 case IMAGE_FILE_MACHINE_AMD64: return CPU_x86_64;
1853 case IMAGE_FILE_MACHINE_POWERPC: return CPU_POWERPC;
1854 case IMAGE_FILE_MACHINE_ARM:
1855 case IMAGE_FILE_MACHINE_THUMB:
1856 case IMAGE_FILE_MACHINE_ARMNT: return CPU_ARM;
1857 case IMAGE_FILE_MACHINE_ARM64: return CPU_ARM64;
1859 ERR( "%s uses unsupported architecture (%04x)\n", debugstr_w(filename), binary_info->arch );
1860 return -1;
1863 /***********************************************************************
1864 * exec_loader
1866 static pid_t exec_loader( LPCWSTR cmd_line, unsigned int flags, int socketfd,
1867 int stdin_fd, int stdout_fd, const char *unixdir, char *winedebug,
1868 const struct binary_info *binary_info, int exec_only )
1870 pid_t pid;
1871 char *wineloader = NULL;
1872 const char *loader = NULL;
1873 char **argv;
1875 argv = build_argv( cmd_line, 1 );
1877 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1878 loader = get_alternate_loader( &wineloader );
1880 if (exec_only || !(pid = fork())) /* child */
1882 if (exec_only || !(pid = fork())) /* grandchild */
1884 char preloader_reserve[64], socket_env[64];
1886 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1888 int fd = open( "/dev/null", O_RDWR );
1889 setsid();
1890 /* close stdin and stdout */
1891 if (fd != -1)
1893 dup2( fd, 0 );
1894 dup2( fd, 1 );
1895 close( fd );
1898 else
1900 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1901 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1904 if (stdin_fd != -1) close( stdin_fd );
1905 if (stdout_fd != -1) close( stdout_fd );
1907 /* Reset signals that we previously set to SIG_IGN */
1908 signal( SIGPIPE, SIG_DFL );
1910 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
1911 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1912 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1914 putenv( preloader_reserve );
1915 putenv( socket_env );
1916 if (winedebug) putenv( winedebug );
1917 if (wineloader) putenv( wineloader );
1918 if (unixdir) chdir(unixdir);
1920 if (argv)
1924 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1926 #ifdef __APPLE__
1927 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1928 #else
1929 while (0);
1930 #endif
1932 _exit(1);
1935 _exit(pid == -1);
1938 if (pid != -1)
1940 /* reap child */
1941 pid_t wret;
1942 do {
1943 wret = waitpid(pid, NULL, 0);
1944 } while (wret < 0 && errno == EINTR);
1947 HeapFree( GetProcessHeap(), 0, wineloader );
1948 HeapFree( GetProcessHeap(), 0, argv );
1949 return pid;
1952 /***********************************************************************
1953 * create_process
1955 * Create a new process. If hFile is a valid handle we have an exe
1956 * file, otherwise it is a Winelib app.
1958 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1959 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1960 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1961 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1962 const struct binary_info *binary_info, int exec_only )
1964 static const char *cpu_names[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
1965 NTSTATUS status;
1966 BOOL success = FALSE;
1967 HANDLE process_info;
1968 WCHAR *env_end;
1969 char *winedebug = NULL;
1970 startup_info_t *startup_info;
1971 DWORD startup_info_size;
1972 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1973 pid_t pid;
1974 int err, cpu;
1976 if ((cpu = get_process_cpu( filename, binary_info )) == -1)
1978 SetLastError( ERROR_BAD_EXE_FORMAT );
1979 return FALSE;
1982 /* create the socket for the new process */
1984 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1986 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1987 return FALSE;
1989 #ifdef SO_PASSCRED
1990 else
1992 int enable = 1;
1993 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1995 #endif
1997 if (exec_only) /* things are much simpler in this case */
1999 wine_server_send_fd( socketfd[1] );
2000 close( socketfd[1] );
2001 SERVER_START_REQ( new_process )
2003 req->create_flags = flags;
2004 req->socket_fd = socketfd[1];
2005 req->exe_file = wine_server_obj_handle( hFile );
2006 req->cpu = cpu;
2007 status = wine_server_call( req );
2009 SERVER_END_REQ;
2011 switch (status)
2013 case STATUS_INVALID_IMAGE_WIN_64:
2014 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2015 break;
2016 case STATUS_INVALID_IMAGE_FORMAT:
2017 ERR( "%s not supported on this installation (%s binary)\n",
2018 debugstr_w(filename), cpu_names[cpu] );
2019 break;
2020 case STATUS_SUCCESS:
2021 exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2022 winedebug, binary_info, TRUE );
2024 close( socketfd[0] );
2025 SetLastError( RtlNtStatusToDosError( status ));
2026 return FALSE;
2029 RtlAcquirePebLock();
2031 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
2032 &startup_info_size )))
2034 RtlReleasePebLock();
2035 close( socketfd[0] );
2036 close( socketfd[1] );
2037 return FALSE;
2039 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
2040 env_end = env;
2041 while (*env_end)
2043 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
2044 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
2046 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
2047 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
2048 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
2050 env_end += strlenW(env_end) + 1;
2052 env_end++;
2054 wine_server_send_fd( socketfd[1] );
2055 close( socketfd[1] );
2057 /* create the process on the server side */
2059 SERVER_START_REQ( new_process )
2061 req->inherit_all = inherit;
2062 req->create_flags = flags;
2063 req->socket_fd = socketfd[1];
2064 req->exe_file = wine_server_obj_handle( hFile );
2065 req->process_access = PROCESS_ALL_ACCESS;
2066 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
2067 req->thread_access = THREAD_ALL_ACCESS;
2068 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
2069 req->cpu = cpu;
2070 req->info_size = startup_info_size;
2072 wine_server_add_data( req, startup_info, startup_info_size );
2073 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
2074 if (!(status = wine_server_call( req )))
2076 info->dwProcessId = (DWORD)reply->pid;
2077 info->dwThreadId = (DWORD)reply->tid;
2078 info->hProcess = wine_server_ptr_handle( reply->phandle );
2079 info->hThread = wine_server_ptr_handle( reply->thandle );
2081 process_info = wine_server_ptr_handle( reply->info );
2083 SERVER_END_REQ;
2085 RtlReleasePebLock();
2086 if (status)
2088 switch (status)
2090 case STATUS_INVALID_IMAGE_WIN_64:
2091 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2092 break;
2093 case STATUS_INVALID_IMAGE_FORMAT:
2094 ERR( "%s not supported on this installation (%s binary)\n",
2095 debugstr_w(filename), cpu_names[cpu] );
2096 break;
2098 close( socketfd[0] );
2099 HeapFree( GetProcessHeap(), 0, startup_info );
2100 HeapFree( GetProcessHeap(), 0, winedebug );
2101 SetLastError( RtlNtStatusToDosError( status ));
2102 return FALSE;
2105 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
2107 if (startup_info->hstdin)
2108 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
2109 FILE_READ_DATA, &stdin_fd, NULL );
2110 if (startup_info->hstdout)
2111 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
2112 FILE_WRITE_DATA, &stdout_fd, NULL );
2114 HeapFree( GetProcessHeap(), 0, startup_info );
2116 /* create the child process */
2118 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2119 winedebug, binary_info, FALSE );
2121 if (stdin_fd != -1) close( stdin_fd );
2122 if (stdout_fd != -1) close( stdout_fd );
2123 close( socketfd[0] );
2124 HeapFree( GetProcessHeap(), 0, winedebug );
2125 if (pid == -1)
2127 FILE_SetDosError();
2128 goto error;
2131 /* wait for the new process info to be ready */
2133 WaitForSingleObject( process_info, INFINITE );
2134 SERVER_START_REQ( get_new_process_info )
2136 req->info = wine_server_obj_handle( process_info );
2137 wine_server_call( req );
2138 success = reply->success;
2139 err = reply->exit_code;
2141 SERVER_END_REQ;
2143 if (!success)
2145 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2146 goto error;
2148 CloseHandle( process_info );
2149 return success;
2151 error:
2152 CloseHandle( process_info );
2153 CloseHandle( info->hProcess );
2154 CloseHandle( info->hThread );
2155 info->hProcess = info->hThread = 0;
2156 info->dwProcessId = info->dwThreadId = 0;
2157 return FALSE;
2161 /***********************************************************************
2162 * create_vdm_process
2164 * Create a new VDM process for a 16-bit or DOS application.
2166 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2167 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2168 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2169 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2170 const struct binary_info *binary_info, int exec_only )
2172 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2174 BOOL ret;
2175 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
2176 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
2178 if (!new_cmd_line)
2180 SetLastError( ERROR_OUTOFMEMORY );
2181 return FALSE;
2183 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
2184 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2185 flags, startup, info, unixdir, binary_info, exec_only );
2186 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2187 return ret;
2191 /***********************************************************************
2192 * create_cmd_process
2194 * Create a new cmd shell process for a .BAT file.
2196 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2197 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2198 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2199 LPPROCESS_INFORMATION info )
2202 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2203 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2204 WCHAR comspec[MAX_PATH];
2205 WCHAR *newcmdline;
2206 BOOL ret;
2208 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2209 return FALSE;
2210 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2211 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2212 return FALSE;
2214 strcpyW( newcmdline, comspec );
2215 strcatW( newcmdline, slashcW );
2216 strcatW( newcmdline, cmd_line );
2217 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2218 flags, env, cur_dir, startup, info );
2219 HeapFree( GetProcessHeap(), 0, newcmdline );
2220 return ret;
2224 /*************************************************************************
2225 * get_file_name
2227 * Helper for CreateProcess: retrieve the file name to load from the
2228 * app name and command line. Store the file name in buffer, and
2229 * return a possibly modified command line.
2230 * Also returns a handle to the opened file if it's a Windows binary.
2232 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2233 int buflen, HANDLE *handle, struct binary_info *binary_info )
2235 static const WCHAR quotesW[] = {'"','%','s','"',0};
2237 WCHAR *name, *pos, *first_space, *ret = NULL;
2238 const WCHAR *p;
2240 /* if we have an app name, everything is easy */
2242 if (appname)
2244 /* use the unmodified app name as file name */
2245 lstrcpynW( buffer, appname, buflen );
2246 *handle = open_exe_file( buffer, binary_info );
2247 if (!(ret = cmdline) || !cmdline[0])
2249 /* no command-line, create one */
2250 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2251 sprintfW( ret, quotesW, appname );
2253 return ret;
2256 /* first check for a quoted file name */
2258 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2260 int len = p - cmdline - 1;
2261 /* extract the quoted portion as file name */
2262 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2263 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2264 name[len] = 0;
2266 if (!find_exe_file( name, buffer, buflen, handle, binary_info )) goto done;
2267 ret = cmdline; /* no change necessary */
2268 goto done;
2271 /* now try the command-line word by word */
2273 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2274 return NULL;
2275 pos = name;
2276 p = cmdline;
2277 first_space = NULL;
2279 for (;;)
2281 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2282 *pos = 0;
2283 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2285 ret = cmdline;
2286 break;
2288 if (!first_space) first_space = pos;
2289 if (!(*pos++ = *p++)) break;
2292 if (!ret)
2294 SetLastError( ERROR_FILE_NOT_FOUND );
2296 else if (first_space) /* build a new command-line with quotes */
2298 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2299 goto done;
2300 sprintfW( ret, quotesW, name );
2301 strcatW( ret, p );
2304 done:
2305 HeapFree( GetProcessHeap(), 0, name );
2306 return ret;
2310 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2311 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2312 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2313 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2314 LPPROCESS_INFORMATION info )
2316 BOOL retv = FALSE;
2317 HANDLE hFile = 0;
2318 char *unixdir = NULL;
2319 WCHAR name[MAX_PATH];
2320 WCHAR *tidy_cmdline, *p, *envW = env;
2321 struct binary_info binary_info;
2323 /* Process the AppName and/or CmdLine to get module name and path */
2325 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2327 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2328 &hFile, &binary_info )))
2329 return FALSE;
2330 if (hFile == INVALID_HANDLE_VALUE) goto done;
2332 /* Warn if unsupported features are used */
2334 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2335 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2336 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2337 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2338 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2340 if (cur_dir)
2342 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2344 SetLastError(ERROR_DIRECTORY);
2345 goto done;
2348 else
2350 WCHAR buf[MAX_PATH];
2351 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2354 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2356 char *e = env;
2357 DWORD lenW;
2359 while (*e) e += strlen(e) + 1;
2360 e++; /* final null */
2361 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, NULL, 0 );
2362 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2363 MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, envW, lenW );
2364 flags |= CREATE_UNICODE_ENVIRONMENT;
2367 info->hThread = info->hProcess = 0;
2368 info->dwProcessId = info->dwThreadId = 0;
2370 if (binary_info.flags & BINARY_FLAG_DLL)
2372 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2373 SetLastError( ERROR_BAD_EXE_FORMAT );
2375 else switch (binary_info.type)
2377 case BINARY_PE:
2378 TRACE( "starting %s as Win%d binary (%p-%p, arch %04x%s)\n",
2379 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2380 binary_info.res_start, binary_info.res_end, binary_info.arch,
2381 (binary_info.flags & BINARY_FLAG_FAKEDLL) ? ", fakedll" : "" );
2382 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2383 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2384 break;
2385 case BINARY_OS216:
2386 case BINARY_WIN16:
2387 case BINARY_DOS:
2388 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2389 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2390 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2391 break;
2392 case BINARY_UNIX_LIB:
2393 TRACE( "starting %s as %d-bit Winelib app\n",
2394 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2395 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2396 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2397 break;
2398 case BINARY_UNKNOWN:
2399 /* check for .com or .bat extension */
2400 if ((p = strrchrW( name, '.' )))
2402 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2404 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2405 binary_info.type = BINARY_DOS;
2406 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2407 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2408 inherit, flags, startup_info, info, unixdir,
2409 &binary_info, FALSE );
2410 break;
2412 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2414 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2415 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2416 inherit, flags, startup_info, info );
2417 break;
2420 /* fall through */
2421 case BINARY_UNIX_EXE:
2423 /* unknown file, try as unix executable */
2424 char *unix_name;
2426 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2428 if ((unix_name = wine_get_unix_file_name( name )))
2430 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2431 HeapFree( GetProcessHeap(), 0, unix_name );
2434 break;
2436 if (hFile) CloseHandle( hFile );
2438 done:
2439 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2440 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2441 HeapFree( GetProcessHeap(), 0, unixdir );
2442 if (retv)
2443 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2444 return retv;
2448 /**********************************************************************
2449 * CreateProcessA (KERNEL32.@)
2451 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2452 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2453 DWORD flags, LPVOID env, LPCSTR cur_dir,
2454 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2456 BOOL ret = FALSE;
2457 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2458 UNICODE_STRING desktopW, titleW;
2459 STARTUPINFOW infoW;
2461 desktopW.Buffer = NULL;
2462 titleW.Buffer = NULL;
2463 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2464 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2465 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2467 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2468 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2470 memcpy( &infoW, startup_info, sizeof(infoW) );
2471 infoW.lpDesktop = desktopW.Buffer;
2472 infoW.lpTitle = titleW.Buffer;
2474 if (startup_info->lpReserved)
2475 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2476 debugstr_a(startup_info->lpReserved));
2478 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2479 inherit, flags, env, cur_dirW, &infoW, info );
2480 done:
2481 HeapFree( GetProcessHeap(), 0, app_nameW );
2482 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2483 HeapFree( GetProcessHeap(), 0, cur_dirW );
2484 RtlFreeUnicodeString( &desktopW );
2485 RtlFreeUnicodeString( &titleW );
2486 return ret;
2490 /**********************************************************************
2491 * CreateProcessW (KERNEL32.@)
2493 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2494 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2495 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2496 LPPROCESS_INFORMATION info )
2498 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2499 inherit, flags, env, cur_dir, startup_info, info);
2503 /**********************************************************************
2504 * exec_process
2506 static void exec_process( LPCWSTR name )
2508 HANDLE hFile;
2509 WCHAR *p;
2510 STARTUPINFOW startup_info;
2511 PROCESS_INFORMATION info;
2512 struct binary_info binary_info;
2514 hFile = open_exe_file( name, &binary_info );
2515 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2517 memset( &startup_info, 0, sizeof(startup_info) );
2518 startup_info.cb = sizeof(startup_info);
2520 /* Determine executable type */
2522 if (binary_info.flags & BINARY_FLAG_DLL)
2524 CloseHandle( hFile );
2525 return;
2528 switch (binary_info.type)
2530 case BINARY_PE:
2531 TRACE( "starting %s as Win%d binary (%p-%p, arch %04x)\n",
2532 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2533 binary_info.res_start, binary_info.res_end, binary_info.arch );
2534 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2535 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2536 break;
2537 case BINARY_UNIX_LIB:
2538 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2539 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2540 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2541 break;
2542 case BINARY_UNKNOWN:
2543 /* check for .com or .pif extension */
2544 if (!(p = strrchrW( name, '.' ))) break;
2545 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2546 binary_info.type = BINARY_DOS;
2547 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2548 /* fall through */
2549 case BINARY_OS216:
2550 case BINARY_WIN16:
2551 case BINARY_DOS:
2552 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2553 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2554 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2555 break;
2556 default:
2557 break;
2559 CloseHandle( hFile );
2563 /***********************************************************************
2564 * wait_input_idle
2566 * Wrapper to call WaitForInputIdle USER function
2568 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2570 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2572 HMODULE mod = GetModuleHandleA( "user32.dll" );
2573 if (mod)
2575 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2576 if (ptr) return ptr( process, timeout );
2578 return 0;
2582 /***********************************************************************
2583 * WinExec (KERNEL32.@)
2585 UINT WINAPI DECLSPEC_HOTPATCH WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2587 PROCESS_INFORMATION info;
2588 STARTUPINFOA startup;
2589 char *cmdline;
2590 UINT ret;
2592 memset( &startup, 0, sizeof(startup) );
2593 startup.cb = sizeof(startup);
2594 startup.dwFlags = STARTF_USESHOWWINDOW;
2595 startup.wShowWindow = nCmdShow;
2597 /* cmdline needs to be writable for CreateProcess */
2598 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2599 strcpy( cmdline, lpCmdLine );
2601 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2602 0, NULL, NULL, &startup, &info ))
2604 /* Give 30 seconds to the app to come up */
2605 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2606 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2607 ret = 33;
2608 /* Close off the handles */
2609 CloseHandle( info.hThread );
2610 CloseHandle( info.hProcess );
2612 else if ((ret = GetLastError()) >= 32)
2614 FIXME("Strange error set by CreateProcess: %d\n", ret );
2615 ret = 11;
2617 HeapFree( GetProcessHeap(), 0, cmdline );
2618 return ret;
2622 /**********************************************************************
2623 * LoadModule (KERNEL32.@)
2625 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2627 LOADPARMS32 *params = paramBlock;
2628 PROCESS_INFORMATION info;
2629 STARTUPINFOA startup;
2630 DWORD ret;
2631 LPSTR cmdline, p;
2632 char filename[MAX_PATH];
2633 BYTE len;
2635 if (!name) return ERROR_FILE_NOT_FOUND;
2637 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2638 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2639 return GetLastError();
2641 len = (BYTE)params->lpCmdLine[0];
2642 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2643 return ERROR_NOT_ENOUGH_MEMORY;
2645 strcpy( cmdline, filename );
2646 p = cmdline + strlen(cmdline);
2647 *p++ = ' ';
2648 memcpy( p, params->lpCmdLine + 1, len );
2649 p[len] = 0;
2651 memset( &startup, 0, sizeof(startup) );
2652 startup.cb = sizeof(startup);
2653 if (params->lpCmdShow)
2655 startup.dwFlags = STARTF_USESHOWWINDOW;
2656 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2659 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2660 params->lpEnvAddress, NULL, &startup, &info ))
2662 /* Give 30 seconds to the app to come up */
2663 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2664 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2665 ret = 33;
2666 /* Close off the handles */
2667 CloseHandle( info.hThread );
2668 CloseHandle( info.hProcess );
2670 else if ((ret = GetLastError()) >= 32)
2672 FIXME("Strange error set by CreateProcess: %u\n", ret );
2673 ret = 11;
2676 HeapFree( GetProcessHeap(), 0, cmdline );
2677 return ret;
2681 /******************************************************************************
2682 * TerminateProcess (KERNEL32.@)
2684 * Terminates a process.
2686 * PARAMS
2687 * handle [I] Process to terminate.
2688 * exit_code [I] Exit code.
2690 * RETURNS
2691 * Success: TRUE.
2692 * Failure: FALSE, check GetLastError().
2694 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2696 NTSTATUS status;
2698 if (!handle)
2700 SetLastError( ERROR_INVALID_HANDLE );
2701 return FALSE;
2704 status = NtTerminateProcess( handle, exit_code );
2705 if (status) SetLastError( RtlNtStatusToDosError(status) );
2706 return !status;
2709 /***********************************************************************
2710 * ExitProcess (KERNEL32.@)
2712 * Exits the current process.
2714 * PARAMS
2715 * status [I] Status code to exit with.
2717 * RETURNS
2718 * Nothing.
2720 #ifdef __i386__
2721 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2722 "pushl %ebp\n\t"
2723 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2724 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2725 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2726 "pushl 8(%ebp)\n\t"
2727 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
2728 "leave\n\t"
2729 "ret $4" )
2730 #else
2732 void WINAPI ExitProcess( DWORD status )
2734 RtlExitUserProcess( status );
2737 #endif
2739 /***********************************************************************
2740 * GetExitCodeProcess [KERNEL32.@]
2742 * Gets termination status of specified process.
2744 * PARAMS
2745 * hProcess [in] Handle to the process.
2746 * lpExitCode [out] Address to receive termination status.
2748 * RETURNS
2749 * Success: TRUE
2750 * Failure: FALSE
2752 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2754 NTSTATUS status;
2755 PROCESS_BASIC_INFORMATION pbi;
2757 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2758 sizeof(pbi), NULL);
2759 if (status == STATUS_SUCCESS)
2761 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2762 return TRUE;
2764 SetLastError( RtlNtStatusToDosError(status) );
2765 return FALSE;
2769 /***********************************************************************
2770 * SetErrorMode (KERNEL32.@)
2772 UINT WINAPI SetErrorMode( UINT mode )
2774 UINT old;
2776 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2777 &old, sizeof(old), NULL );
2778 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2779 &mode, sizeof(mode) );
2780 return old;
2783 /***********************************************************************
2784 * GetErrorMode (KERNEL32.@)
2786 UINT WINAPI GetErrorMode( void )
2788 UINT mode;
2790 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2791 &mode, sizeof(mode), NULL );
2792 return mode;
2795 /**********************************************************************
2796 * TlsAlloc [KERNEL32.@]
2798 * Allocates a thread local storage index.
2800 * RETURNS
2801 * Success: TLS index.
2802 * Failure: 0xFFFFFFFF
2804 DWORD WINAPI TlsAlloc( void )
2806 DWORD index;
2807 PEB * const peb = NtCurrentTeb()->Peb;
2809 RtlAcquirePebLock();
2810 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 1 );
2811 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2812 else
2814 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2815 if (index != ~0U)
2817 if (!NtCurrentTeb()->TlsExpansionSlots &&
2818 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2819 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2821 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2822 index = ~0U;
2823 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2825 else
2827 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2828 index += TLS_MINIMUM_AVAILABLE;
2831 else SetLastError( ERROR_NO_MORE_ITEMS );
2833 RtlReleasePebLock();
2834 return index;
2838 /**********************************************************************
2839 * TlsFree [KERNEL32.@]
2841 * Releases a thread local storage index, making it available for reuse.
2843 * PARAMS
2844 * index [in] TLS index to free.
2846 * RETURNS
2847 * Success: TRUE
2848 * Failure: FALSE
2850 BOOL WINAPI TlsFree( DWORD index )
2852 BOOL ret;
2854 RtlAcquirePebLock();
2855 if (index >= TLS_MINIMUM_AVAILABLE)
2857 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2858 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2860 else
2862 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2863 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2865 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2866 else SetLastError( ERROR_INVALID_PARAMETER );
2867 RtlReleasePebLock();
2868 return ret;
2872 /**********************************************************************
2873 * TlsGetValue [KERNEL32.@]
2875 * Gets value in a thread's TLS slot.
2877 * PARAMS
2878 * index [in] TLS index to retrieve value for.
2880 * RETURNS
2881 * Success: Value stored in calling thread's TLS slot for index.
2882 * Failure: 0 and GetLastError() returns NO_ERROR.
2884 LPVOID WINAPI TlsGetValue( DWORD index )
2886 LPVOID ret;
2888 if (index < TLS_MINIMUM_AVAILABLE)
2890 ret = NtCurrentTeb()->TlsSlots[index];
2892 else
2894 index -= TLS_MINIMUM_AVAILABLE;
2895 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2897 SetLastError( ERROR_INVALID_PARAMETER );
2898 return NULL;
2900 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2901 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2903 SetLastError( ERROR_SUCCESS );
2904 return ret;
2908 /**********************************************************************
2909 * TlsSetValue [KERNEL32.@]
2911 * Stores a value in the thread's TLS slot.
2913 * PARAMS
2914 * index [in] TLS index to set value for.
2915 * value [in] Value to be stored.
2917 * RETURNS
2918 * Success: TRUE
2919 * Failure: FALSE
2921 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2923 if (index < TLS_MINIMUM_AVAILABLE)
2925 NtCurrentTeb()->TlsSlots[index] = value;
2927 else
2929 index -= TLS_MINIMUM_AVAILABLE;
2930 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2932 SetLastError( ERROR_INVALID_PARAMETER );
2933 return FALSE;
2935 if (!NtCurrentTeb()->TlsExpansionSlots &&
2936 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2937 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2939 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2940 return FALSE;
2942 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2944 return TRUE;
2948 /***********************************************************************
2949 * GetProcessFlags (KERNEL32.@)
2951 DWORD WINAPI GetProcessFlags( DWORD processid )
2953 IMAGE_NT_HEADERS *nt;
2954 DWORD flags = 0;
2956 if (processid && processid != GetCurrentProcessId()) return 0;
2958 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2960 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2961 flags |= PDB32_CONSOLE_PROC;
2963 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2964 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2965 return flags;
2969 /*********************************************************************
2970 * OpenProcess (KERNEL32.@)
2972 * Opens a handle to a process.
2974 * PARAMS
2975 * access [I] Desired access rights assigned to the returned handle.
2976 * inherit [I] Determines whether or not child processes will inherit the handle.
2977 * id [I] Process identifier of the process to get a handle to.
2979 * RETURNS
2980 * Success: Valid handle to the specified process.
2981 * Failure: NULL, check GetLastError().
2983 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2985 NTSTATUS status;
2986 HANDLE handle;
2987 OBJECT_ATTRIBUTES attr;
2988 CLIENT_ID cid;
2990 cid.UniqueProcess = ULongToHandle(id);
2991 cid.UniqueThread = 0; /* FIXME ? */
2993 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2994 attr.RootDirectory = NULL;
2995 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2996 attr.SecurityDescriptor = NULL;
2997 attr.SecurityQualityOfService = NULL;
2998 attr.ObjectName = NULL;
3000 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
3002 status = NtOpenProcess(&handle, access, &attr, &cid);
3003 if (status != STATUS_SUCCESS)
3005 SetLastError( RtlNtStatusToDosError(status) );
3006 return NULL;
3008 return handle;
3012 /*********************************************************************
3013 * GetProcessId (KERNEL32.@)
3015 * Gets the a unique identifier of a process.
3017 * PARAMS
3018 * hProcess [I] Handle to the process.
3020 * RETURNS
3021 * Success: TRUE.
3022 * Failure: FALSE, check GetLastError().
3024 * NOTES
3026 * The identifier is unique only on the machine and only until the process
3027 * exits (including system shutdown).
3029 DWORD WINAPI GetProcessId( HANDLE hProcess )
3031 NTSTATUS status;
3032 PROCESS_BASIC_INFORMATION pbi;
3034 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3035 sizeof(pbi), NULL);
3036 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
3037 SetLastError( RtlNtStatusToDosError(status) );
3038 return 0;
3042 /*********************************************************************
3043 * CloseHandle (KERNEL32.@)
3045 * Closes a handle.
3047 * PARAMS
3048 * handle [I] Handle to close.
3050 * RETURNS
3051 * Success: TRUE.
3052 * Failure: FALSE, check GetLastError().
3054 BOOL WINAPI CloseHandle( HANDLE handle )
3056 NTSTATUS status;
3058 /* stdio handles need special treatment */
3059 if (handle == (HANDLE)STD_INPUT_HANDLE)
3060 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
3061 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
3062 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
3063 else if (handle == (HANDLE)STD_ERROR_HANDLE)
3064 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
3066 if (is_console_handle(handle))
3067 return CloseConsoleHandle(handle);
3069 status = NtClose( handle );
3070 if (status) SetLastError( RtlNtStatusToDosError(status) );
3071 return !status;
3075 /*********************************************************************
3076 * GetHandleInformation (KERNEL32.@)
3078 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
3080 OBJECT_DATA_INFORMATION info;
3081 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
3083 if (status) SetLastError( RtlNtStatusToDosError(status) );
3084 else if (flags)
3086 *flags = 0;
3087 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3088 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3090 return !status;
3094 /*********************************************************************
3095 * SetHandleInformation (KERNEL32.@)
3097 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3099 OBJECT_DATA_INFORMATION info;
3100 NTSTATUS status;
3102 /* if not setting both fields, retrieve current value first */
3103 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3104 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3106 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3108 SetLastError( RtlNtStatusToDosError(status) );
3109 return FALSE;
3112 if (mask & HANDLE_FLAG_INHERIT)
3113 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3114 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3115 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3117 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3118 if (status) SetLastError( RtlNtStatusToDosError(status) );
3119 return !status;
3123 /*********************************************************************
3124 * DuplicateHandle (KERNEL32.@)
3126 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3127 HANDLE dest_process, HANDLE *dest,
3128 DWORD access, BOOL inherit, DWORD options )
3130 NTSTATUS status;
3132 if (is_console_handle(source))
3134 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3135 if (source_process != dest_process ||
3136 source_process != GetCurrentProcess())
3138 SetLastError(ERROR_INVALID_PARAMETER);
3139 return FALSE;
3141 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3142 return (*dest != INVALID_HANDLE_VALUE);
3144 status = NtDuplicateObject( source_process, source, dest_process, dest,
3145 access, inherit ? OBJ_INHERIT : 0, options );
3146 if (status) SetLastError( RtlNtStatusToDosError(status) );
3147 return !status;
3151 /***********************************************************************
3152 * ConvertToGlobalHandle (KERNEL32.@)
3154 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3156 HANDLE ret = INVALID_HANDLE_VALUE;
3157 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3158 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3159 return ret;
3163 /***********************************************************************
3164 * SetHandleContext (KERNEL32.@)
3166 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3168 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3169 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3170 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3171 return FALSE;
3175 /***********************************************************************
3176 * GetHandleContext (KERNEL32.@)
3178 DWORD WINAPI GetHandleContext(HANDLE hnd)
3180 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3181 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3182 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3183 return 0;
3187 /***********************************************************************
3188 * CreateSocketHandle (KERNEL32.@)
3190 HANDLE WINAPI CreateSocketHandle(void)
3192 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3193 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3194 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3195 return INVALID_HANDLE_VALUE;
3199 /***********************************************************************
3200 * SetPriorityClass (KERNEL32.@)
3202 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3204 NTSTATUS status;
3205 PROCESS_PRIORITY_CLASS ppc;
3207 ppc.Foreground = FALSE;
3208 switch (priorityclass)
3210 case IDLE_PRIORITY_CLASS:
3211 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3212 case BELOW_NORMAL_PRIORITY_CLASS:
3213 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3214 case NORMAL_PRIORITY_CLASS:
3215 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3216 case ABOVE_NORMAL_PRIORITY_CLASS:
3217 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3218 case HIGH_PRIORITY_CLASS:
3219 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3220 case REALTIME_PRIORITY_CLASS:
3221 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3222 default:
3223 SetLastError(ERROR_INVALID_PARAMETER);
3224 return FALSE;
3227 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3228 &ppc, sizeof(ppc));
3230 if (status != STATUS_SUCCESS)
3232 SetLastError( RtlNtStatusToDosError(status) );
3233 return FALSE;
3235 return TRUE;
3239 /***********************************************************************
3240 * GetPriorityClass (KERNEL32.@)
3242 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3244 NTSTATUS status;
3245 PROCESS_BASIC_INFORMATION pbi;
3247 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3248 sizeof(pbi), NULL);
3249 if (status != STATUS_SUCCESS)
3251 SetLastError( RtlNtStatusToDosError(status) );
3252 return 0;
3254 switch (pbi.BasePriority)
3256 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3257 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3258 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3259 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3260 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3261 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3263 SetLastError( ERROR_INVALID_PARAMETER );
3264 return 0;
3268 /***********************************************************************
3269 * SetProcessAffinityMask (KERNEL32.@)
3271 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3273 NTSTATUS status;
3275 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3276 &affmask, sizeof(DWORD_PTR));
3277 if (status)
3279 SetLastError( RtlNtStatusToDosError(status) );
3280 return FALSE;
3282 return TRUE;
3286 /**********************************************************************
3287 * GetProcessAffinityMask (KERNEL32.@)
3289 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3291 NTSTATUS status = STATUS_SUCCESS;
3293 if (process_mask)
3295 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3296 process_mask, sizeof(*process_mask), NULL )))
3297 SetLastError( RtlNtStatusToDosError(status) );
3299 if (system_mask && status == STATUS_SUCCESS)
3301 SYSTEM_BASIC_INFORMATION info;
3303 if ((status = NtQuerySystemInformation( SystemBasicInformation, &info, sizeof(info), NULL )))
3304 SetLastError( RtlNtStatusToDosError(status) );
3305 else
3306 *system_mask = info.ActiveProcessorsAffinityMask;
3308 return !status;
3312 /***********************************************************************
3313 * GetProcessVersion (KERNEL32.@)
3315 DWORD WINAPI GetProcessVersion( DWORD pid )
3317 HANDLE process;
3318 NTSTATUS status;
3319 PROCESS_BASIC_INFORMATION pbi;
3320 SIZE_T count;
3321 PEB peb;
3322 IMAGE_DOS_HEADER dos;
3323 IMAGE_NT_HEADERS nt;
3324 DWORD ver = 0;
3326 if (!pid || pid == GetCurrentProcessId())
3328 IMAGE_NT_HEADERS *pnt;
3330 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3331 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3332 pnt->OptionalHeader.MinorSubsystemVersion);
3333 return 0;
3336 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3337 if (!process) return 0;
3339 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3340 if (status) goto err;
3342 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3343 if (status || count != sizeof(peb)) goto err;
3345 memset(&dos, 0, sizeof(dos));
3346 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3347 if (status || count != sizeof(dos)) goto err;
3348 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3350 memset(&nt, 0, sizeof(nt));
3351 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3352 if (status || count != sizeof(nt)) goto err;
3353 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3355 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3357 err:
3358 CloseHandle(process);
3360 if (status != STATUS_SUCCESS)
3361 SetLastError(RtlNtStatusToDosError(status));
3363 return ver;
3367 /***********************************************************************
3368 * SetProcessWorkingSetSize [KERNEL32.@]
3369 * Sets the min/max working set sizes for a specified process.
3371 * PARAMS
3372 * hProcess [I] Handle to the process of interest
3373 * minset [I] Specifies minimum working set size
3374 * maxset [I] Specifies maximum working set size
3376 * RETURNS
3377 * Success: TRUE
3378 * Failure: FALSE
3380 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3381 SIZE_T maxset)
3383 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3384 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3385 /* Trim the working set to zero */
3386 /* Swap the process out of physical RAM */
3388 return TRUE;
3391 /***********************************************************************
3392 * K32EmptyWorkingSet (KERNEL32.@)
3394 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3396 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3399 /***********************************************************************
3400 * GetProcessWorkingSetSize (KERNEL32.@)
3402 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3403 PSIZE_T maxset)
3405 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3406 /* 32 MB working set size */
3407 if (minset) *minset = 32*1024*1024;
3408 if (maxset) *maxset = 32*1024*1024;
3409 return TRUE;
3413 /***********************************************************************
3414 * SetProcessShutdownParameters (KERNEL32.@)
3416 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3418 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3419 shutdown_flags = flags;
3420 shutdown_priority = level;
3421 return TRUE;
3425 /***********************************************************************
3426 * GetProcessShutdownParameters (KERNEL32.@)
3429 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3431 *lpdwLevel = shutdown_priority;
3432 *lpdwFlags = shutdown_flags;
3433 return TRUE;
3437 /***********************************************************************
3438 * GetProcessPriorityBoost (KERNEL32.@)
3440 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3442 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3444 /* Report that no boost is present.. */
3445 *pDisablePriorityBoost = FALSE;
3447 return TRUE;
3450 /***********************************************************************
3451 * SetProcessPriorityBoost (KERNEL32.@)
3453 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3455 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3456 /* Say we can do it. I doubt the program will notice that we don't. */
3457 return TRUE;
3461 /***********************************************************************
3462 * ReadProcessMemory (KERNEL32.@)
3464 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3465 SIZE_T *bytes_read )
3467 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3468 if (status) SetLastError( RtlNtStatusToDosError(status) );
3469 return !status;
3473 /***********************************************************************
3474 * WriteProcessMemory (KERNEL32.@)
3476 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3477 SIZE_T *bytes_written )
3479 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3480 if (status) SetLastError( RtlNtStatusToDosError(status) );
3481 return !status;
3485 /****************************************************************************
3486 * FlushInstructionCache (KERNEL32.@)
3488 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3490 NTSTATUS status;
3491 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3492 if (status) SetLastError( RtlNtStatusToDosError(status) );
3493 return !status;
3497 /******************************************************************
3498 * GetProcessIoCounters (KERNEL32.@)
3500 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3502 NTSTATUS status;
3504 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3505 ioc, sizeof(*ioc), NULL);
3506 if (status) SetLastError( RtlNtStatusToDosError(status) );
3507 return !status;
3510 /******************************************************************
3511 * GetProcessHandleCount (KERNEL32.@)
3513 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3515 NTSTATUS status;
3517 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3518 cnt, sizeof(*cnt), NULL);
3519 if (status) SetLastError( RtlNtStatusToDosError(status) );
3520 return !status;
3523 /******************************************************************
3524 * QueryFullProcessImageNameA (KERNEL32.@)
3526 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3528 BOOL retval;
3529 DWORD pdwSizeW = *pdwSize;
3530 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3532 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3534 if(retval)
3535 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3536 lpExeName, *pdwSize, NULL, NULL));
3537 if(retval)
3538 *pdwSize = strlen(lpExeName);
3540 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3541 return retval;
3544 /******************************************************************
3545 * QueryFullProcessImageNameW (KERNEL32.@)
3547 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3549 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3550 UNICODE_STRING *dynamic_buffer = NULL;
3551 UNICODE_STRING *result = NULL;
3552 NTSTATUS status;
3553 DWORD needed;
3555 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3556 * is a DOS path and we depend on this. */
3557 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3558 sizeof(buffer) - sizeof(WCHAR), &needed);
3559 if (status == STATUS_INFO_LENGTH_MISMATCH)
3561 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3562 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3563 result = dynamic_buffer;
3565 else
3566 result = (PUNICODE_STRING)buffer;
3568 if (status) goto cleanup;
3570 if (dwFlags & PROCESS_NAME_NATIVE)
3572 WCHAR drive[3];
3573 WCHAR device[1024];
3574 DWORD ntlen, devlen;
3576 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3578 /* We cannot convert it to an NT device path so fail */
3579 status = STATUS_NO_SUCH_DEVICE;
3580 goto cleanup;
3583 /* Find this drive's NT device path */
3584 drive[0] = result->Buffer[0];
3585 drive[1] = ':';
3586 drive[2] = 0;
3587 if (!QueryDosDeviceW(drive, device, sizeof(device)/sizeof(*device)))
3589 status = STATUS_NO_SUCH_DEVICE;
3590 goto cleanup;
3593 devlen = lstrlenW(device);
3594 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3595 if (ntlen + 1 > *pdwSize)
3597 status = STATUS_BUFFER_TOO_SMALL;
3598 goto cleanup;
3600 *pdwSize = ntlen;
3602 memcpy(lpExeName, device, devlen * sizeof(*device));
3603 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3604 lpExeName[*pdwSize] = 0;
3605 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3607 else
3609 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3611 status = STATUS_BUFFER_TOO_SMALL;
3612 goto cleanup;
3615 *pdwSize = result->Length/sizeof(WCHAR);
3616 memcpy( lpExeName, result->Buffer, result->Length );
3617 lpExeName[*pdwSize] = 0;
3620 cleanup:
3621 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3622 if (status) SetLastError( RtlNtStatusToDosError(status) );
3623 return !status;
3626 /***********************************************************************
3627 * K32GetProcessImageFileNameA (KERNEL32.@)
3629 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3631 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3634 /***********************************************************************
3635 * K32GetProcessImageFileNameW (KERNEL32.@)
3637 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3639 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3642 /***********************************************************************
3643 * K32EnumProcesses (KERNEL32.@)
3645 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3647 SYSTEM_PROCESS_INFORMATION *spi;
3648 ULONG size = 0x4000;
3649 void *buf = NULL;
3650 NTSTATUS status;
3652 do {
3653 size *= 2;
3654 HeapFree(GetProcessHeap(), 0, buf);
3655 buf = HeapAlloc(GetProcessHeap(), 0, size);
3656 if (!buf)
3657 return FALSE;
3659 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3660 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3662 if (status != STATUS_SUCCESS)
3664 HeapFree(GetProcessHeap(), 0, buf);
3665 SetLastError(RtlNtStatusToDosError(status));
3666 return FALSE;
3669 spi = buf;
3671 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3673 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3674 *lpcbUsed += sizeof(DWORD);
3676 if (spi->NextEntryOffset == 0)
3677 break;
3679 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3682 HeapFree(GetProcessHeap(), 0, buf);
3683 return TRUE;
3686 /***********************************************************************
3687 * K32QueryWorkingSet (KERNEL32.@)
3689 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3691 NTSTATUS status;
3693 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3695 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3697 if (status)
3699 SetLastError( RtlNtStatusToDosError( status ) );
3700 return FALSE;
3702 return TRUE;
3705 /***********************************************************************
3706 * K32QueryWorkingSetEx (KERNEL32.@)
3708 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3710 NTSTATUS status;
3712 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3714 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3716 if (status)
3718 SetLastError( RtlNtStatusToDosError( status ) );
3719 return FALSE;
3721 return TRUE;
3724 /***********************************************************************
3725 * K32GetProcessMemoryInfo (KERNEL32.@)
3727 * Retrieve memory usage information for a given process
3730 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3731 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3733 NTSTATUS status;
3734 VM_COUNTERS vmc;
3736 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3738 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3739 return FALSE;
3742 status = NtQueryInformationProcess(process, ProcessVmCounters,
3743 &vmc, sizeof(vmc), NULL);
3745 if (status)
3747 SetLastError(RtlNtStatusToDosError(status));
3748 return FALSE;
3751 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3752 pmc->PageFaultCount = vmc.PageFaultCount;
3753 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3754 pmc->WorkingSetSize = vmc.WorkingSetSize;
3755 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3756 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3757 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3758 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3759 pmc->PagefileUsage = vmc.PagefileUsage;
3760 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3762 return TRUE;
3765 /***********************************************************************
3766 * ProcessIdToSessionId (KERNEL32.@)
3767 * This function is available on Terminal Server 4SP4 and Windows 2000
3769 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3771 if (procid != GetCurrentProcessId())
3772 FIXME("Unsupported for other processes.\n");
3774 *sessionid_ptr = NtCurrentTeb()->Peb->SessionId;
3775 return TRUE;
3779 /***********************************************************************
3780 * RegisterServiceProcess (KERNEL32.@)
3782 * A service process calls this function to ensure that it continues to run
3783 * even after a user logged off.
3785 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3787 /* I don't think that Wine needs to do anything in this function */
3788 return 1; /* success */
3792 /**********************************************************************
3793 * IsWow64Process (KERNEL32.@)
3795 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3797 ULONG_PTR pbi;
3798 NTSTATUS status;
3800 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3802 if (status != STATUS_SUCCESS)
3804 SetLastError( RtlNtStatusToDosError( status ) );
3805 return FALSE;
3807 *Wow64Process = (pbi != 0);
3808 return TRUE;
3812 /***********************************************************************
3813 * GetCurrentProcess (KERNEL32.@)
3815 * Get a handle to the current process.
3817 * PARAMS
3818 * None.
3820 * RETURNS
3821 * A handle representing the current process.
3823 #undef GetCurrentProcess
3824 HANDLE WINAPI GetCurrentProcess(void)
3826 return (HANDLE)~(ULONG_PTR)0;
3829 /***********************************************************************
3830 * GetLogicalProcessorInformation (KERNEL32.@)
3832 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3834 NTSTATUS status;
3836 TRACE("(%p,%p)\n", buffer, pBufLen);
3838 if(!pBufLen)
3840 SetLastError(ERROR_INVALID_PARAMETER);
3841 return FALSE;
3844 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
3846 if (status == STATUS_INFO_LENGTH_MISMATCH)
3848 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3849 return FALSE;
3851 if (status != STATUS_SUCCESS)
3853 SetLastError( RtlNtStatusToDosError( status ) );
3854 return FALSE;
3856 return TRUE;
3859 /***********************************************************************
3860 * GetLogicalProcessorInformationEx (KERNEL32.@)
3862 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, DWORD *len)
3864 NTSTATUS status;
3866 TRACE("(%u,%p,%p)\n", relationship, buffer, len);
3868 if (!len)
3870 SetLastError( ERROR_INVALID_PARAMETER );
3871 return FALSE;
3874 status = NtQuerySystemInformationEx( SystemLogicalProcessorInformationEx, &relationship, sizeof(relationship),
3875 buffer, *len, len );
3876 if (status == STATUS_INFO_LENGTH_MISMATCH)
3878 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3879 return FALSE;
3881 if (status != STATUS_SUCCESS)
3883 SetLastError( RtlNtStatusToDosError( status ) );
3884 return FALSE;
3886 return TRUE;
3889 /***********************************************************************
3890 * CmdBatNotification (KERNEL32.@)
3892 * Notifies the system that a batch file has started or finished.
3894 * PARAMS
3895 * bBatchRunning [I] TRUE if a batch file has started or
3896 * FALSE if a batch file has finished executing.
3898 * RETURNS
3899 * Unknown.
3901 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3903 FIXME("%d\n", bBatchRunning);
3904 return FALSE;
3908 /***********************************************************************
3909 * RegisterApplicationRestart (KERNEL32.@)
3911 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3913 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3915 return S_OK;
3918 /**********************************************************************
3919 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3921 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3923 static int once;
3924 if (!once++) FIXME("stub\n");
3925 /* Return current session id. */
3926 return NtCurrentTeb()->Peb->SessionId;
3929 /**********************************************************************
3930 * GetSystemDEPPolicy (KERNEL32.@)
3932 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3934 FIXME("stub\n");
3935 return OptIn;
3938 /**********************************************************************
3939 * SetProcessDEPPolicy (KERNEL32.@)
3941 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3943 FIXME("(%d): stub\n", newDEP);
3944 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3945 return FALSE;
3948 /**********************************************************************
3949 * ApplicationRecoveryFinished (KERNEL32.@)
3951 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
3953 FIXME(": stub\n");
3954 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3957 /**********************************************************************
3958 * ApplicationRecoveryInProgress (KERNEL32.@)
3960 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
3962 FIXME(":%p stub\n", canceled);
3963 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3964 return E_FAIL;
3967 /**********************************************************************
3968 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3970 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
3972 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
3973 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3974 return E_FAIL;
3977 /**********************************************************************
3978 * GetNumaHighestNodeNumber (KERNEL32.@)
3980 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
3982 *highestnode = 0;
3983 FIXME("(%p): semi-stub\n", highestnode);
3984 return TRUE;
3987 /**********************************************************************
3988 * GetNumaNodeProcessorMask (KERNEL32.@)
3990 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
3992 FIXME("(%c %p): stub\n", node, mask);
3993 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3994 return FALSE;
3997 /**********************************************************************
3998 * GetNumaAvailableMemoryNode (KERNEL32.@)
4000 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
4002 FIXME("(%c %p): stub\n", node, available_bytes);
4003 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4004 return FALSE;
4007 /***********************************************************************
4008 * GetNumaProcessorNode (KERNEL32.@)
4010 BOOL WINAPI GetNumaProcessorNode(UCHAR processor, PUCHAR node)
4012 SYSTEM_INFO si;
4014 TRACE("(%d, %p)\n", processor, node);
4016 GetSystemInfo( &si );
4017 if (processor < si.dwNumberOfProcessors)
4019 *node = 0;
4020 return TRUE;
4023 *node = 0xFF;
4024 SetLastError(ERROR_INVALID_PARAMETER);
4025 return FALSE;
4028 /**********************************************************************
4029 * GetProcessDEPPolicy (KERNEL32.@)
4031 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
4033 NTSTATUS status;
4034 ULONG dep_flags;
4036 TRACE("(%p %p %p)\n", process, flags, permanent);
4038 status = NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
4039 &dep_flags, sizeof(dep_flags), NULL );
4040 if (!status)
4043 if (flags)
4045 *flags = 0;
4046 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE)
4047 *flags |= PROCESS_DEP_ENABLE;
4048 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION)
4049 *flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
4052 if (permanent)
4053 *permanent = (dep_flags & MEM_EXECUTE_OPTION_PERMANENT) != 0;
4056 if (status) SetLastError( RtlNtStatusToDosError(status) );
4057 return !status;
4060 /**********************************************************************
4061 * FlushProcessWriteBuffers (KERNEL32.@)
4063 VOID WINAPI FlushProcessWriteBuffers(void)
4065 static int once = 0;
4067 if (!once++)
4068 FIXME(": stub\n");
4071 /***********************************************************************
4072 * UnregisterApplicationRestart (KERNEL32.@)
4074 HRESULT WINAPI UnregisterApplicationRestart(void)
4076 FIXME(": stub\n");
4077 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4078 return S_OK;
4081 /***********************************************************************
4082 * GetSystemFirmwareTable (KERNEL32.@)
4084 UINT WINAPI GetSystemFirmwareTable(DWORD provider, DWORD id, PVOID buffer, DWORD size)
4086 FIXME("(%d %d %p %d):stub\n", provider, id, buffer, size);
4087 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4088 return 0;