kernel32: Also set the preloader range for 64-bit binaries.
[wine.git] / dlls / kernel32 / process.c
blobf9e3f7eb7b509eedc292a8a833302a3651118798
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 = 0;
211 binary_info->res_end = 0;
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 static const WCHAR programdataW[] = {'P','r','o','g','r','a','m','D','a','t','a',0};
521 OBJECT_ATTRIBUTES attr;
522 UNICODE_STRING nameW;
523 WCHAR *profile_dir = NULL, *all_users_dir = NULL, *program_data_dir = NULL;
524 WCHAR buf[MAX_COMPUTERNAME_LENGTH+1];
525 HANDLE hkey;
526 DWORD len;
528 /* ComputerName */
529 len = sizeof(buf) / sizeof(WCHAR);
530 if (GetComputerNameW( buf, &len ))
531 SetEnvironmentVariableW( computernameW, buf );
533 /* set the ALLUSERSPROFILE variables */
535 attr.Length = sizeof(attr);
536 attr.RootDirectory = 0;
537 attr.ObjectName = &nameW;
538 attr.Attributes = 0;
539 attr.SecurityDescriptor = NULL;
540 attr.SecurityQualityOfService = NULL;
541 RtlInitUnicodeString( &nameW, profile_keyW );
542 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
544 profile_dir = get_reg_value( hkey, profiles_valueW );
545 all_users_dir = get_reg_value( hkey, all_users_valueW );
546 program_data_dir = get_reg_value( hkey, programdataW );
547 NtClose( hkey );
550 if (profile_dir && all_users_dir)
552 WCHAR *value, *p;
554 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
555 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
556 strcpyW( value, profile_dir );
557 p = value + strlenW(value);
558 if (p > value && p[-1] != '\\') *p++ = '\\';
559 strcpyW( p, all_users_dir );
560 SetEnvironmentVariableW( allusersW, value );
561 HeapFree( GetProcessHeap(), 0, value );
564 if (program_data_dir)
566 SetEnvironmentVariableW( programdataW, program_data_dir );
569 HeapFree( GetProcessHeap(), 0, all_users_dir );
570 HeapFree( GetProcessHeap(), 0, profile_dir );
571 HeapFree( GetProcessHeap(), 0, program_data_dir );
574 /***********************************************************************
575 * set_wow64_environment
577 * Set the environment variables that change across 32/64/Wow64.
579 static void set_wow64_environment(void)
581 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};
582 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};
583 static const WCHAR x86W[] = {'x','8','6',0};
584 static const WCHAR versionW[] = {'\\','R','e','g','i','s','t','r','y','\\',
585 'M','a','c','h','i','n','e','\\',
586 'S','o','f','t','w','a','r','e','\\',
587 'M','i','c','r','o','s','o','f','t','\\',
588 'W','i','n','d','o','w','s','\\',
589 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
590 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
591 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
592 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
593 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
594 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
595 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
596 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
597 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
599 OBJECT_ATTRIBUTES attr;
600 UNICODE_STRING nameW;
601 WCHAR arch[64];
602 WCHAR *value;
603 HANDLE hkey;
605 /* set the PROCESSOR_ARCHITECTURE variable */
607 if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
609 if (is_win64)
611 SetEnvironmentVariableW( archW, arch );
612 SetEnvironmentVariableW( arch6432W, NULL );
615 else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
617 if (is_wow64)
619 SetEnvironmentVariableW( arch6432W, arch );
620 SetEnvironmentVariableW( archW, x86W );
624 attr.Length = sizeof(attr);
625 attr.RootDirectory = 0;
626 attr.ObjectName = &nameW;
627 attr.Attributes = 0;
628 attr.SecurityDescriptor = NULL;
629 attr.SecurityQualityOfService = NULL;
630 RtlInitUnicodeString( &nameW, versionW );
631 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
633 /* set the ProgramFiles variables */
635 if ((value = get_reg_value( hkey, progdirW )))
637 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
638 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
639 HeapFree( GetProcessHeap(), 0, value );
641 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
643 SetEnvironmentVariableW( progfilesW, value );
644 HeapFree( GetProcessHeap(), 0, value );
647 /* set the CommonProgramFiles variables */
649 if ((value = get_reg_value( hkey, commondirW )))
651 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
652 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
653 HeapFree( GetProcessHeap(), 0, value );
655 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
657 SetEnvironmentVariableW( commonfilesW, value );
658 HeapFree( GetProcessHeap(), 0, value );
661 NtClose( hkey );
664 /***********************************************************************
665 * set_library_wargv
667 * Set the Wine library Unicode argv global variables.
669 static void set_library_wargv( char **argv )
671 int argc;
672 char *q;
673 WCHAR *p;
674 WCHAR **wargv;
675 DWORD total = 0;
677 for (argc = 0; argv[argc]; argc++)
678 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
680 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
681 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
682 p = (WCHAR *)(wargv + argc + 1);
683 for (argc = 0; argv[argc]; argc++)
685 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
686 wargv[argc] = p;
687 p += reslen;
688 total -= reslen;
690 wargv[argc] = NULL;
692 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
694 for (argc = 0; wargv[argc]; argc++)
695 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
697 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
698 q = (char *)(argv + argc + 1);
699 for (argc = 0; wargv[argc]; argc++)
701 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
702 argv[argc] = q;
703 q += reslen;
704 total -= reslen;
706 argv[argc] = NULL;
708 __wine_main_argc = argc;
709 __wine_main_argv = argv;
710 __wine_main_wargv = wargv;
714 /***********************************************************************
715 * update_library_argv0
717 * Update the argv[0] global variable with the binary we have found.
719 static void update_library_argv0( const WCHAR *argv0 )
721 DWORD len = strlenW( argv0 );
723 if (len > strlenW( __wine_main_wargv[0] ))
725 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
727 strcpyW( __wine_main_wargv[0], argv0 );
729 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
730 if (len > strlen( __wine_main_argv[0] ) + 1)
732 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
734 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
738 /***********************************************************************
739 * build_command_line
741 * Build the command line of a process from the argv array.
743 * Note that it does NOT necessarily include the file name.
744 * Sometimes we don't even have any command line options at all.
746 * We must quote and escape characters so that the argv array can be rebuilt
747 * from the command line:
748 * - spaces and tabs must be quoted
749 * 'a b' -> '"a b"'
750 * - quotes must be escaped
751 * '"' -> '\"'
752 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
753 * resulting in an odd number of '\' followed by a '"'
754 * '\"' -> '\\\"'
755 * '\\"' -> '\\\\\"'
756 * - '\'s are followed by the closing '"' must be doubled,
757 * resulting in an even number of '\' followed by a '"'
758 * ' \' -> '" \\"'
759 * ' \\' -> '" \\\\"'
760 * - '\'s that are not followed by a '"' can be left as is
761 * 'a\b' == 'a\b'
762 * 'a\\b' == 'a\\b'
764 static BOOL build_command_line( WCHAR **argv )
766 int len;
767 WCHAR **arg;
768 LPWSTR p;
769 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
771 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
773 len = 0;
774 for (arg = argv; *arg; arg++)
776 BOOL has_space;
777 int bcount;
778 WCHAR* a;
780 has_space=FALSE;
781 bcount=0;
782 a=*arg;
783 if( !*a ) has_space=TRUE;
784 while (*a!='\0') {
785 if (*a=='\\') {
786 bcount++;
787 } else {
788 if (*a==' ' || *a=='\t') {
789 has_space=TRUE;
790 } else if (*a=='"') {
791 /* doubling of '\' preceding a '"',
792 * plus escaping of said '"'
794 len+=2*bcount+1;
796 bcount=0;
798 a++;
800 len+=(a-*arg)+1 /* for the separating space */;
801 if (has_space)
802 len+=2+bcount; /* for the quotes and doubling of '\' preceding the closing quote */
805 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
806 return FALSE;
808 p = rupp->CommandLine.Buffer;
809 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
810 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
811 for (arg = argv; *arg; arg++)
813 BOOL has_space,has_quote;
814 WCHAR* a;
815 int bcount;
817 /* Check for quotes and spaces in this argument */
818 has_space=has_quote=FALSE;
819 a=*arg;
820 if( !*a ) has_space=TRUE;
821 while (*a!='\0') {
822 if (*a==' ' || *a=='\t') {
823 has_space=TRUE;
824 if (has_quote)
825 break;
826 } else if (*a=='"') {
827 has_quote=TRUE;
828 if (has_space)
829 break;
831 a++;
834 /* Now transfer it to the command line */
835 if (has_space)
836 *p++='"';
837 if (has_quote || has_space) {
838 bcount=0;
839 a=*arg;
840 while (*a!='\0') {
841 if (*a=='\\') {
842 *p++=*a;
843 bcount++;
844 } else {
845 if (*a=='"') {
846 int i;
848 /* Double all the '\\' preceding this '"', plus one */
849 for (i=0;i<=bcount;i++)
850 *p++='\\';
851 *p++='"';
852 } else {
853 *p++=*a;
855 bcount=0;
857 a++;
859 } else {
860 WCHAR* x = *arg;
861 while ((*p=*x++)) p++;
863 if (has_space) {
864 int i;
866 /* Double all the '\' preceding the closing quote */
867 for (i=0;i<bcount;i++)
868 *p++='\\';
869 *p++='"';
871 *p++=' ';
873 if (p > rupp->CommandLine.Buffer)
874 p--; /* remove last space */
875 *p = '\0';
877 return TRUE;
881 /***********************************************************************
882 * init_current_directory
884 * Initialize the current directory from the Unix cwd or the parent info.
886 static void init_current_directory( CURDIR *cur_dir )
888 UNICODE_STRING dir_str;
889 const char *pwd;
890 char *cwd;
891 int size;
893 /* if we received a cur dir from the parent, try this first */
895 if (cur_dir->DosPath.Length)
897 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
900 /* now try to get it from the Unix cwd */
902 for (size = 256; ; size *= 2)
904 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
905 if (getcwd( cwd, size )) break;
906 HeapFree( GetProcessHeap(), 0, cwd );
907 if (errno == ERANGE) continue;
908 cwd = NULL;
909 break;
912 /* try to use PWD if it is valid, so that we don't resolve symlinks */
914 pwd = getenv( "PWD" );
915 if (cwd)
917 struct stat st1, st2;
919 if (!pwd || stat( pwd, &st1 ) == -1 ||
920 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
921 pwd = cwd;
924 if (pwd)
926 ANSI_STRING unix_name;
927 UNICODE_STRING nt_name;
928 RtlInitAnsiString( &unix_name, pwd );
929 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
931 UNICODE_STRING dos_path;
932 /* skip the \??\ prefix, nt_name is 0 terminated */
933 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
934 RtlSetCurrentDirectory_U( &dos_path );
935 RtlFreeUnicodeString( &nt_name );
939 if (!cur_dir->DosPath.Length) /* still not initialized */
941 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
942 "starting in the Windows directory.\n", cwd ? cwd : "" );
943 RtlInitUnicodeString( &dir_str, DIR_Windows );
944 RtlSetCurrentDirectory_U( &dir_str );
946 HeapFree( GetProcessHeap(), 0, cwd );
948 done:
949 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
953 /***********************************************************************
954 * init_windows_dirs
956 * Initialize the windows and system directories from the environment.
958 static void init_windows_dirs(void)
960 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
962 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
963 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
964 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
965 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
966 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
968 DWORD len;
969 WCHAR *buffer;
971 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
973 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
974 GetEnvironmentVariableW( windirW, buffer, len );
975 DIR_Windows = buffer;
977 else DIR_Windows = default_windirW;
979 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
981 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
982 GetEnvironmentVariableW( winsysdirW, buffer, len );
983 DIR_System = buffer;
985 else
987 len = strlenW( DIR_Windows );
988 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
989 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
990 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
991 DIR_System = buffer;
994 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
995 ERR( "directory %s could not be created, error %u\n",
996 debugstr_w(DIR_Windows), GetLastError() );
997 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
998 ERR( "directory %s could not be created, error %u\n",
999 debugstr_w(DIR_System), GetLastError() );
1001 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
1003 len = strlenW( DIR_Windows );
1004 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
1005 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
1006 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
1007 DIR_SysWow64 = buffer;
1008 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
1009 ERR( "directory %s could not be created, error %u\n",
1010 debugstr_w(DIR_SysWow64), GetLastError() );
1013 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
1014 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
1016 /* set the directories in ntdll too */
1017 __wine_init_windows_dir( DIR_Windows, DIR_System );
1021 /***********************************************************************
1022 * start_wineboot
1024 * Start the wineboot process if necessary. Return the handles to wait on.
1026 static void start_wineboot( HANDLE handles[2] )
1028 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
1030 handles[1] = 0;
1031 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
1033 ERR( "failed to create wineboot event, expect trouble\n" );
1034 return;
1036 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
1038 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1039 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1040 STARTUPINFOW si;
1041 PROCESS_INFORMATION pi;
1042 void *redir;
1043 WCHAR app[MAX_PATH];
1044 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1046 memset( &si, 0, sizeof(si) );
1047 si.cb = sizeof(si);
1048 si.dwFlags = STARTF_USESTDHANDLES;
1049 si.hStdInput = 0;
1050 si.hStdOutput = 0;
1051 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1053 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1054 lstrcatW( app, wineboot );
1056 Wow64DisableWow64FsRedirection( &redir );
1057 strcpyW( cmdline, app );
1058 strcatW( cmdline, args );
1059 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1061 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1062 CloseHandle( pi.hThread );
1063 handles[1] = pi.hProcess;
1065 else
1067 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1068 CloseHandle( handles[0] );
1069 handles[0] = 0;
1071 Wow64RevertWow64FsRedirection( redir );
1076 #ifdef __i386__
1077 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1078 __ASM_GLOBAL_FUNC( call_process_entry,
1079 "pushl %ebp\n\t"
1080 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1081 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1082 "movl %esp,%ebp\n\t"
1083 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1084 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1085 "pushl 8(%ebp)\n\t"
1086 "call *12(%ebp)\n\t"
1087 "leave\n\t"
1088 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1089 __ASM_CFI(".cfi_same_value %ebp\n\t")
1090 "ret" )
1091 #else
1092 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1094 return entry( peb );
1096 #endif
1098 /***********************************************************************
1099 * start_process
1101 * Startup routine of a new process. Runs on the new process stack.
1103 static DWORD WINAPI start_process( LPTHREAD_START_ROUTINE entry )
1105 BOOL being_debugged;
1106 PEB *peb = NtCurrentTeb()->Peb;
1108 if (!entry)
1110 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1111 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1112 ExitThread( 1 );
1115 if (TRACE_ON(relay))
1116 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1117 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1119 if (!CheckRemoteDebuggerPresent( GetCurrentProcess(), &being_debugged ))
1120 being_debugged = FALSE;
1122 SetLastError( 0 ); /* clear error code */
1123 if (being_debugged) DbgBreakPoint();
1124 return call_process_entry( peb, entry );
1128 /***********************************************************************
1129 * set_process_name
1131 * Change the process name in the ps output.
1133 static void set_process_name( int argc, char *argv[] )
1135 BOOL shift_strings;
1136 char *p, *name;
1137 int i;
1139 #ifdef HAVE_SETPROCTITLE
1140 setproctitle("-%s", argv[1]);
1141 shift_strings = FALSE;
1142 #else
1143 p = argv[0];
1145 shift_strings = (argc >= 2);
1146 for (i = 1; i < argc; i++)
1148 p += strlen(p) + 1;
1149 if (p != argv[i])
1151 shift_strings = FALSE;
1152 break;
1155 #endif
1157 if (shift_strings)
1159 int offset = argv[1] - argv[0];
1160 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1161 memmove( argv[0], argv[1], end - argv[1] );
1162 memset( end - offset, 0, offset );
1163 for (i = 1; i < argc; i++)
1164 argv[i-1] = argv[i] - offset;
1165 argv[i-1] = NULL;
1167 else
1169 /* remove argv[0] */
1170 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1173 name = argv[0];
1174 if ((p = strrchr( name, '\\' ))) name = p + 1;
1175 if ((p = strrchr( name, '/' ))) name = p + 1;
1177 #if defined(HAVE_SETPROGNAME)
1178 setprogname( name );
1179 #endif
1181 #ifdef HAVE_PRCTL
1182 #ifndef PR_SET_NAME
1183 # define PR_SET_NAME 15
1184 #endif
1185 prctl( PR_SET_NAME, name );
1186 #endif /* HAVE_PRCTL */
1190 /***********************************************************************
1191 * __wine_kernel_init
1193 * Wine initialisation: load and start the main exe file.
1195 void CDECL __wine_kernel_init(void)
1197 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1198 static const WCHAR dotW[] = {'.',0};
1200 WCHAR *p, main_exe_name[MAX_PATH+1];
1201 PEB *peb = NtCurrentTeb()->Peb;
1202 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1203 HANDLE boot_events[2];
1204 BOOL got_environment = TRUE;
1206 /* Initialize everything */
1208 setbuf(stdout,NULL);
1209 setbuf(stderr,NULL);
1210 kernel32_handle = GetModuleHandleW(kernel32W);
1211 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1213 LOCALE_Init();
1215 if (!params->Environment)
1217 /* Copy the parent environment */
1218 if (!build_initial_environment()) exit(1);
1220 /* convert old configuration to new format */
1221 convert_old_config();
1223 got_environment = set_registry_environment( FALSE );
1224 set_additional_environment();
1227 init_windows_dirs();
1228 init_current_directory( &params->CurrentDirectory );
1230 set_process_name( __wine_main_argc, __wine_main_argv );
1231 set_library_wargv( __wine_main_argv );
1232 boot_events[0] = boot_events[1] = 0;
1234 if (peb->ProcessParameters->ImagePathName.Buffer)
1236 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1238 else
1240 struct binary_info binary_info;
1242 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1243 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1245 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1246 ExitProcess( GetLastError() );
1248 update_library_argv0( main_exe_name );
1249 if (!build_command_line( __wine_main_wargv )) goto error;
1250 start_wineboot( boot_events );
1253 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1254 p = strrchrW( main_exe_name, '.' );
1255 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1257 TRACE( "starting process name=%s argv[0]=%s\n",
1258 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1260 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1261 MODULE_get_dll_load_path( main_exe_name, -1 ));
1263 if (boot_events[0])
1265 DWORD timeout = 2 * 60 * 1000, count = 1;
1267 if (boot_events[1]) count++;
1268 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1269 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1270 ERR( "boot event wait timed out\n" );
1271 CloseHandle( boot_events[0] );
1272 if (boot_events[1]) CloseHandle( boot_events[1] );
1273 /* reload environment now that wineboot has run */
1274 set_registry_environment( got_environment );
1275 set_additional_environment();
1277 set_wow64_environment();
1279 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1281 DWORD_PTR args[1];
1282 WCHAR msgW[1024];
1283 char msg[1024];
1284 DWORD error = GetLastError();
1286 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1287 if (error == ERROR_BAD_EXE_FORMAT ||
1288 error == ERROR_INVALID_ADDRESS ||
1289 error == ERROR_NOT_ENOUGH_MEMORY)
1291 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1292 /* if we get back here, it failed */
1294 else if (error == ERROR_MOD_NOT_FOUND)
1296 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1297 else p = main_exe_name;
1298 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1300 /* args 1 and 2 are --app-name full_path */
1301 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1302 debugstr_w(__wine_main_wargv[3]) );
1303 ExitProcess( ERROR_BAD_EXE_FORMAT );
1305 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1306 ExitProcess( ERROR_FILE_NOT_FOUND );
1308 args[0] = (DWORD_PTR)main_exe_name;
1309 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1310 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1311 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1312 MESSAGE( "wine: %s", msg );
1313 ExitProcess( error );
1316 if (!params->CurrentDirectory.Handle) chdir("/"); /* avoid locking removable devices */
1318 LdrInitializeThunk( start_process, 0, 0, 0 );
1320 error:
1321 ExitProcess( GetLastError() );
1325 /***********************************************************************
1326 * build_argv
1328 * Build an argv array from a command-line.
1329 * 'reserved' is the number of args to reserve before the first one.
1331 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1333 int argc;
1334 char** argv;
1335 char *arg,*s,*d,*cmdline;
1336 int in_quotes,bcount,len;
1338 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1339 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1340 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1342 argc=reserved+1;
1343 bcount=0;
1344 in_quotes=0;
1345 s=cmdline;
1346 while (1) {
1347 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1348 /* space */
1349 argc++;
1350 /* skip the remaining spaces */
1351 while (*s==' ' || *s=='\t') {
1352 s++;
1354 if (*s=='\0')
1355 break;
1356 bcount=0;
1357 continue;
1358 } else if (*s=='\\') {
1359 /* '\', count them */
1360 bcount++;
1361 } else if ((*s=='"') && ((bcount & 1)==0)) {
1362 /* unescaped '"' */
1363 in_quotes=!in_quotes;
1364 bcount=0;
1365 } else {
1366 /* a regular character */
1367 bcount=0;
1369 s++;
1371 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1373 HeapFree( GetProcessHeap(), 0, cmdline );
1374 return NULL;
1377 arg = d = s = (char *)(argv + argc);
1378 memcpy( d, cmdline, len );
1379 bcount=0;
1380 in_quotes=0;
1381 argc=reserved;
1382 while (*s) {
1383 if ((*s==' ' || *s=='\t') && !in_quotes) {
1384 /* Close the argument and copy it */
1385 *d=0;
1386 argv[argc++]=arg;
1388 /* skip the remaining spaces */
1389 do {
1390 s++;
1391 } while (*s==' ' || *s=='\t');
1393 /* Start with a new argument */
1394 arg=d=s;
1395 bcount=0;
1396 } else if (*s=='\\') {
1397 /* '\\' */
1398 *d++=*s++;
1399 bcount++;
1400 } else if (*s=='"') {
1401 /* '"' */
1402 if ((bcount & 1)==0) {
1403 /* Preceded by an even number of '\', this is half that
1404 * number of '\', plus a '"' which we discard.
1406 d-=bcount/2;
1407 s++;
1408 in_quotes=!in_quotes;
1409 } else {
1410 /* Preceded by an odd number of '\', this is half that
1411 * number of '\' followed by a '"'
1413 d=d-bcount/2-1;
1414 *d++='"';
1415 s++;
1417 bcount=0;
1418 } else {
1419 /* a regular character */
1420 *d++=*s++;
1421 bcount=0;
1424 if (*arg) {
1425 *d='\0';
1426 argv[argc++]=arg;
1428 argv[argc]=NULL;
1430 HeapFree( GetProcessHeap(), 0, cmdline );
1431 return argv;
1435 /***********************************************************************
1436 * build_envp
1438 * Build the environment of a new child process.
1440 static char **build_envp( const WCHAR *envW )
1442 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1444 const WCHAR *end;
1445 char **envp;
1446 char *env, *p;
1447 int count = 1, length;
1448 unsigned int i;
1450 for (end = envW; *end; count++) end += strlenW(end) + 1;
1451 end++;
1452 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1453 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1454 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1456 for (p = env; *p; p += strlen(p) + 1)
1457 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1459 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1461 if (!(p = getenv(unix_vars[i]))) continue;
1462 length += strlen(unix_vars[i]) + strlen(p) + 2;
1463 count++;
1466 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1468 char **envptr = envp;
1469 char *dst = (char *)(envp + count);
1471 /* some variables must not be modified, so we get them directly from the unix env */
1472 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1474 if (!(p = getenv(unix_vars[i]))) continue;
1475 *envptr++ = strcpy( dst, unix_vars[i] );
1476 strcat( dst, "=" );
1477 strcat( dst, p );
1478 dst += strlen(dst) + 1;
1481 /* now put the Windows environment strings */
1482 for (p = env; *p; p += strlen(p) + 1)
1484 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1485 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1486 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1487 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1488 if (is_special_env_var( p )) /* prefix it with "WINE" */
1490 *envptr++ = strcpy( dst, "WINE" );
1491 strcat( dst, p );
1493 else
1495 *envptr++ = strcpy( dst, p );
1497 dst += strlen(dst) + 1;
1499 *envptr = 0;
1501 HeapFree( GetProcessHeap(), 0, env );
1502 return envp;
1506 /***********************************************************************
1507 * fork_and_exec
1509 * Fork and exec a new Unix binary, checking for errors.
1511 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1512 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1514 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1515 int pid, err;
1516 char **argv, **envp;
1518 if (!env) env = GetEnvironmentStringsW();
1520 #ifdef HAVE_PIPE2
1521 if (pipe2( fd, O_CLOEXEC ) == -1)
1522 #endif
1524 if (pipe(fd) == -1)
1526 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1527 return -1;
1529 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1530 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1533 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1535 HANDLE hstdin, hstdout, hstderr;
1537 if (startup->dwFlags & STARTF_USESTDHANDLES)
1539 hstdin = startup->hStdInput;
1540 hstdout = startup->hStdOutput;
1541 hstderr = startup->hStdError;
1543 else
1545 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1546 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1547 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1550 if (is_console_handle( hstdin ))
1551 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1552 if (is_console_handle( hstdout ))
1553 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1554 if (is_console_handle( hstderr ))
1555 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1556 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1557 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1558 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1561 argv = build_argv( cmdline, 0 );
1562 envp = build_envp( env );
1564 if (!(pid = fork())) /* child */
1566 if (!(pid = fork())) /* grandchild */
1568 close( fd[0] );
1570 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1572 int nullfd = open( "/dev/null", O_RDWR );
1573 setsid();
1574 /* close stdin and stdout */
1575 if (nullfd != -1)
1577 dup2( nullfd, 0 );
1578 dup2( nullfd, 1 );
1579 close( nullfd );
1582 else
1584 if (stdin_fd != -1)
1586 dup2( stdin_fd, 0 );
1587 close( stdin_fd );
1589 if (stdout_fd != -1)
1591 dup2( stdout_fd, 1 );
1592 close( stdout_fd );
1594 if (stderr_fd != -1)
1596 dup2( stderr_fd, 2 );
1597 close( stderr_fd );
1601 /* Reset signals that we previously set to SIG_IGN */
1602 signal( SIGPIPE, SIG_DFL );
1604 if (newdir) chdir(newdir);
1606 if (argv && envp) execve( filename, argv, envp );
1609 if (pid <= 0) /* grandchild if exec failed or child if fork failed */
1611 err = errno;
1612 write( fd[1], &err, sizeof(err) );
1613 _exit(1);
1616 _exit(0); /* child if fork succeeded */
1618 HeapFree( GetProcessHeap(), 0, argv );
1619 HeapFree( GetProcessHeap(), 0, envp );
1620 if (stdin_fd != -1) close( stdin_fd );
1621 if (stdout_fd != -1) close( stdout_fd );
1622 if (stderr_fd != -1) close( stderr_fd );
1623 close( fd[1] );
1624 if (pid != -1)
1626 /* reap child */
1627 do {
1628 err = waitpid(pid, NULL, 0);
1629 } while (err < 0 && errno == EINTR);
1631 if (read( fd[0], &err, sizeof(err) ) > 0) /* exec or second fork failed */
1633 errno = err;
1634 pid = -1;
1637 if (pid == -1) FILE_SetDosError();
1638 close( fd[0] );
1639 return pid;
1643 static inline DWORD append_string( void **ptr, const WCHAR *str )
1645 DWORD len = strlenW( str );
1646 memcpy( *ptr, str, len * sizeof(WCHAR) );
1647 *ptr = (WCHAR *)*ptr + len;
1648 return len * sizeof(WCHAR);
1651 /***********************************************************************
1652 * create_startup_info
1654 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1655 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1656 const STARTUPINFOW *startup, DWORD *info_size )
1658 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1659 const WCHAR *title;
1660 startup_info_t *info;
1661 DWORD size;
1662 void *ptr;
1663 UNICODE_STRING newdir;
1664 WCHAR imagepath[MAX_PATH];
1665 HANDLE hstdin, hstdout, hstderr;
1667 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1668 lstrcpynW( imagepath, filename, MAX_PATH );
1669 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1670 lstrcpynW( imagepath, filename, MAX_PATH );
1672 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1674 newdir.Buffer = NULL;
1675 if (cur_dir)
1677 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1678 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1679 else
1680 cur_dir = NULL;
1682 if (!cur_dir)
1684 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1685 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1686 else
1687 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1689 title = startup->lpTitle ? startup->lpTitle : imagepath;
1691 size = sizeof(*info);
1692 size += strlenW( cur_dir ) * sizeof(WCHAR);
1693 size += cur_params->DllPath.Length;
1694 size += strlenW( imagepath ) * sizeof(WCHAR);
1695 size += strlenW( cmdline ) * sizeof(WCHAR);
1696 size += strlenW( title ) * sizeof(WCHAR);
1697 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1698 /* FIXME: shellinfo */
1699 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1700 size = (size + 1) & ~1;
1701 *info_size = size;
1703 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1705 info->console_flags = cur_params->ConsoleFlags;
1706 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1707 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1709 if (startup->dwFlags & STARTF_USESTDHANDLES)
1711 hstdin = startup->hStdInput;
1712 hstdout = startup->hStdOutput;
1713 hstderr = startup->hStdError;
1715 else if (flags & DETACHED_PROCESS)
1717 hstdin = INVALID_HANDLE_VALUE;
1718 hstdout = INVALID_HANDLE_VALUE;
1719 hstderr = INVALID_HANDLE_VALUE;
1721 else
1723 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1724 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1725 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1727 info->hstdin = wine_server_obj_handle( hstdin );
1728 info->hstdout = wine_server_obj_handle( hstdout );
1729 info->hstderr = wine_server_obj_handle( hstderr );
1730 if ((flags & CREATE_NEW_CONSOLE) != 0)
1732 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1733 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1734 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1735 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1737 else
1739 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1740 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1741 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1744 info->x = startup->dwX;
1745 info->y = startup->dwY;
1746 info->xsize = startup->dwXSize;
1747 info->ysize = startup->dwYSize;
1748 info->xchars = startup->dwXCountChars;
1749 info->ychars = startup->dwYCountChars;
1750 info->attribute = startup->dwFillAttribute;
1751 info->flags = startup->dwFlags;
1752 info->show = startup->wShowWindow;
1754 ptr = info + 1;
1755 info->curdir_len = append_string( &ptr, cur_dir );
1756 info->dllpath_len = cur_params->DllPath.Length;
1757 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1758 ptr = (char *)ptr + cur_params->DllPath.Length;
1759 info->imagepath_len = append_string( &ptr, imagepath );
1760 info->cmdline_len = append_string( &ptr, cmdline );
1761 info->title_len = append_string( &ptr, title );
1762 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1763 if (startup->lpReserved2 && startup->cbReserved2)
1765 info->runtime_len = startup->cbReserved2;
1766 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1769 done:
1770 RtlFreeUnicodeString( &newdir );
1771 return info;
1774 /***********************************************************************
1775 * get_alternate_loader
1777 * Get the name of the alternate (32 or 64 bit) Wine loader.
1779 static const char *get_alternate_loader( char **ret_env )
1781 char *env;
1782 const char *loader = NULL;
1783 const char *loader_env = getenv( "WINELOADER" );
1785 *ret_env = NULL;
1787 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1789 if (loader_env)
1791 int len = strlen( loader_env );
1792 if (!is_win64)
1794 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1795 strcpy( env, "WINELOADER=" );
1796 strcat( env, loader_env );
1797 strcat( env, "64" );
1799 else
1801 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1802 strcpy( env, "WINELOADER=" );
1803 strcat( env, loader_env );
1804 len += sizeof("WINELOADER=") - 1;
1805 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1807 if (!loader)
1809 if ((loader = strrchr( env, '/' ))) loader++;
1810 else loader = env;
1812 *ret_env = env;
1814 if (!loader) loader = is_win64 ? "wine" : "wine64";
1815 return loader;
1818 #ifdef __APPLE__
1819 /***********************************************************************
1820 * terminate_main_thread
1822 * On some versions of Mac OS X, the execve system call fails with
1823 * ENOTSUP if the process has multiple threads. Wine is always multi-
1824 * threaded on Mac OS X because it specifically reserves the main thread
1825 * for use by the system frameworks (see apple_main_thread() in
1826 * libs/wine/loader.c). So, when we need to exec without first forking,
1827 * we need to terminate the main thread first. We do this by installing
1828 * a custom run loop source onto the main run loop and signaling it.
1829 * The source's "perform" callback is pthread_exit and it will be
1830 * executed on the main thread, terminating it.
1832 * Returns TRUE if there's still hope the main thread has terminated or
1833 * will soon. Return FALSE if we've given up.
1835 static BOOL terminate_main_thread(void)
1837 static int delayms;
1839 if (!delayms)
1841 CFRunLoopSourceContext source_context = { 0 };
1842 CFRunLoopSourceRef source;
1844 source_context.perform = pthread_exit;
1845 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1846 return FALSE;
1848 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1849 CFRunLoopSourceSignal( source );
1850 CFRunLoopWakeUp( CFRunLoopGetMain() );
1851 CFRelease( source );
1853 delayms = 20;
1856 if (delayms > 1000)
1857 return FALSE;
1859 usleep(delayms * 1000);
1860 delayms *= 2;
1862 return TRUE;
1864 #endif
1866 /***********************************************************************
1867 * get_process_cpu
1869 static int get_process_cpu( const WCHAR *filename, const struct binary_info *binary_info )
1871 switch (binary_info->arch)
1873 case IMAGE_FILE_MACHINE_I386: return CPU_x86;
1874 case IMAGE_FILE_MACHINE_AMD64: return CPU_x86_64;
1875 case IMAGE_FILE_MACHINE_POWERPC: return CPU_POWERPC;
1876 case IMAGE_FILE_MACHINE_ARM:
1877 case IMAGE_FILE_MACHINE_THUMB:
1878 case IMAGE_FILE_MACHINE_ARMNT: return CPU_ARM;
1879 case IMAGE_FILE_MACHINE_ARM64: return CPU_ARM64;
1881 ERR( "%s uses unsupported architecture (%04x)\n", debugstr_w(filename), binary_info->arch );
1882 return -1;
1885 /***********************************************************************
1886 * exec_loader
1888 static pid_t exec_loader( LPCWSTR cmd_line, unsigned int flags, int socketfd,
1889 int stdin_fd, int stdout_fd, const char *unixdir, char *winedebug,
1890 const struct binary_info *binary_info, int exec_only )
1892 pid_t pid;
1893 char *wineloader = NULL;
1894 const char *loader = NULL;
1895 char **argv;
1897 argv = build_argv( cmd_line, 1 );
1899 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1900 loader = get_alternate_loader( &wineloader );
1902 if (exec_only || !(pid = fork())) /* child */
1904 if (exec_only || !(pid = fork())) /* grandchild */
1906 char preloader_reserve[64], socket_env[64];
1908 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1910 int fd = open( "/dev/null", O_RDWR );
1911 setsid();
1912 /* close stdin and stdout */
1913 if (fd != -1)
1915 dup2( fd, 0 );
1916 dup2( fd, 1 );
1917 close( fd );
1920 else
1922 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1923 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1926 if (stdin_fd != -1) close( stdin_fd );
1927 if (stdout_fd != -1) close( stdout_fd );
1929 /* Reset signals that we previously set to SIG_IGN */
1930 signal( SIGPIPE, SIG_DFL );
1932 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
1933 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%x%08x-%x%08x",
1934 (ULONG)(binary_info->res_start >> 32), (ULONG)binary_info->res_start,
1935 (ULONG)(binary_info->res_end >> 32), (ULONG)binary_info->res_end );
1937 putenv( preloader_reserve );
1938 putenv( socket_env );
1939 if (winedebug) putenv( winedebug );
1940 if (wineloader) putenv( wineloader );
1941 if (unixdir) chdir(unixdir);
1943 if (argv)
1947 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1949 #ifdef __APPLE__
1950 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1951 #else
1952 while (0);
1953 #endif
1955 _exit(1);
1958 _exit(pid == -1);
1961 if (pid != -1)
1963 /* reap child */
1964 pid_t wret;
1965 do {
1966 wret = waitpid(pid, NULL, 0);
1967 } while (wret < 0 && errno == EINTR);
1970 HeapFree( GetProcessHeap(), 0, wineloader );
1971 HeapFree( GetProcessHeap(), 0, argv );
1972 return pid;
1975 /***********************************************************************
1976 * create_process
1978 * Create a new process. If hFile is a valid handle we have an exe
1979 * file, otherwise it is a Winelib app.
1981 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1982 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1983 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1984 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1985 const struct binary_info *binary_info, int exec_only )
1987 static const char *cpu_names[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
1988 NTSTATUS status;
1989 BOOL success = FALSE;
1990 HANDLE process_info;
1991 WCHAR *env_end;
1992 char *winedebug = NULL;
1993 startup_info_t *startup_info;
1994 DWORD startup_info_size;
1995 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1996 pid_t pid;
1997 int err, cpu;
1999 if ((cpu = get_process_cpu( filename, binary_info )) == -1)
2001 SetLastError( ERROR_BAD_EXE_FORMAT );
2002 return FALSE;
2005 /* create the socket for the new process */
2007 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
2009 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
2010 return FALSE;
2012 #ifdef SO_PASSCRED
2013 else
2015 int enable = 1;
2016 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
2018 #endif
2020 if (exec_only) /* things are much simpler in this case */
2022 wine_server_send_fd( socketfd[1] );
2023 close( socketfd[1] );
2024 SERVER_START_REQ( new_process )
2026 req->create_flags = flags;
2027 req->socket_fd = socketfd[1];
2028 req->exe_file = wine_server_obj_handle( hFile );
2029 req->cpu = cpu;
2030 status = wine_server_call( req );
2032 SERVER_END_REQ;
2034 switch (status)
2036 case STATUS_INVALID_IMAGE_WIN_64:
2037 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2038 break;
2039 case STATUS_INVALID_IMAGE_FORMAT:
2040 ERR( "%s not supported on this installation (%s binary)\n",
2041 debugstr_w(filename), cpu_names[cpu] );
2042 break;
2043 case STATUS_SUCCESS:
2044 exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2045 winedebug, binary_info, TRUE );
2047 close( socketfd[0] );
2048 SetLastError( RtlNtStatusToDosError( status ));
2049 return FALSE;
2052 RtlAcquirePebLock();
2054 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
2055 &startup_info_size )))
2057 RtlReleasePebLock();
2058 close( socketfd[0] );
2059 close( socketfd[1] );
2060 return FALSE;
2062 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
2063 env_end = env;
2064 while (*env_end)
2066 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
2067 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
2069 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
2070 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
2071 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
2073 env_end += strlenW(env_end) + 1;
2075 env_end++;
2077 wine_server_send_fd( socketfd[1] );
2078 close( socketfd[1] );
2080 /* create the process on the server side */
2082 SERVER_START_REQ( new_process )
2084 req->inherit_all = inherit;
2085 req->create_flags = flags;
2086 req->socket_fd = socketfd[1];
2087 req->exe_file = wine_server_obj_handle( hFile );
2088 req->process_access = PROCESS_ALL_ACCESS;
2089 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
2090 req->thread_access = THREAD_ALL_ACCESS;
2091 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
2092 req->cpu = cpu;
2093 req->info_size = startup_info_size;
2095 wine_server_add_data( req, startup_info, startup_info_size );
2096 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
2097 if (!(status = wine_server_call( req )))
2099 info->dwProcessId = (DWORD)reply->pid;
2100 info->dwThreadId = (DWORD)reply->tid;
2101 info->hProcess = wine_server_ptr_handle( reply->phandle );
2102 info->hThread = wine_server_ptr_handle( reply->thandle );
2104 process_info = wine_server_ptr_handle( reply->info );
2106 SERVER_END_REQ;
2108 RtlReleasePebLock();
2109 if (status)
2111 switch (status)
2113 case STATUS_INVALID_IMAGE_WIN_64:
2114 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2115 break;
2116 case STATUS_INVALID_IMAGE_FORMAT:
2117 ERR( "%s not supported on this installation (%s binary)\n",
2118 debugstr_w(filename), cpu_names[cpu] );
2119 break;
2121 close( socketfd[0] );
2122 HeapFree( GetProcessHeap(), 0, startup_info );
2123 HeapFree( GetProcessHeap(), 0, winedebug );
2124 SetLastError( RtlNtStatusToDosError( status ));
2125 return FALSE;
2128 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
2130 if (startup_info->hstdin)
2131 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
2132 FILE_READ_DATA, &stdin_fd, NULL );
2133 if (startup_info->hstdout)
2134 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
2135 FILE_WRITE_DATA, &stdout_fd, NULL );
2137 HeapFree( GetProcessHeap(), 0, startup_info );
2139 /* create the child process */
2141 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2142 winedebug, binary_info, FALSE );
2144 if (stdin_fd != -1) close( stdin_fd );
2145 if (stdout_fd != -1) close( stdout_fd );
2146 close( socketfd[0] );
2147 HeapFree( GetProcessHeap(), 0, winedebug );
2148 if (pid == -1)
2150 FILE_SetDosError();
2151 goto error;
2154 /* wait for the new process info to be ready */
2156 WaitForSingleObject( process_info, INFINITE );
2157 SERVER_START_REQ( get_new_process_info )
2159 req->info = wine_server_obj_handle( process_info );
2160 wine_server_call( req );
2161 success = reply->success;
2162 err = reply->exit_code;
2164 SERVER_END_REQ;
2166 if (!success)
2168 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2169 goto error;
2171 CloseHandle( process_info );
2172 return success;
2174 error:
2175 CloseHandle( process_info );
2176 CloseHandle( info->hProcess );
2177 CloseHandle( info->hThread );
2178 info->hProcess = info->hThread = 0;
2179 info->dwProcessId = info->dwThreadId = 0;
2180 return FALSE;
2184 /***********************************************************************
2185 * create_vdm_process
2187 * Create a new VDM process for a 16-bit or DOS application.
2189 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2190 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2191 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2192 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2193 const struct binary_info *binary_info, int exec_only )
2195 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2197 BOOL ret;
2198 WCHAR buffer[MAX_PATH];
2199 LPWSTR new_cmd_line;
2201 if (!(ret = GetFullPathNameW(filename, MAX_PATH, buffer, NULL)))
2202 return FALSE;
2204 new_cmd_line = HeapAlloc(GetProcessHeap(), 0,
2205 (strlenW(buffer) + strlenW(cmd_line) + 30) * sizeof(WCHAR));
2207 if (!new_cmd_line)
2209 SetLastError( ERROR_OUTOFMEMORY );
2210 return FALSE;
2212 sprintfW(new_cmd_line, argsW, winevdmW, buffer, cmd_line);
2213 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2214 flags, startup, info, unixdir, binary_info, exec_only );
2215 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2216 return ret;
2220 /***********************************************************************
2221 * create_cmd_process
2223 * Create a new cmd shell process for a .BAT file.
2225 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2226 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2227 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2228 LPPROCESS_INFORMATION info )
2231 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2232 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2233 WCHAR comspec[MAX_PATH];
2234 WCHAR *newcmdline;
2235 BOOL ret;
2237 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2238 return FALSE;
2239 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2240 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2241 return FALSE;
2243 strcpyW( newcmdline, comspec );
2244 strcatW( newcmdline, slashcW );
2245 strcatW( newcmdline, cmd_line );
2246 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2247 flags, env, cur_dir, startup, info );
2248 HeapFree( GetProcessHeap(), 0, newcmdline );
2249 return ret;
2253 /*************************************************************************
2254 * get_file_name
2256 * Helper for CreateProcess: retrieve the file name to load from the
2257 * app name and command line. Store the file name in buffer, and
2258 * return a possibly modified command line.
2259 * Also returns a handle to the opened file if it's a Windows binary.
2261 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2262 int buflen, HANDLE *handle, struct binary_info *binary_info )
2264 static const WCHAR quotesW[] = {'"','%','s','"',0};
2266 WCHAR *name, *pos, *first_space, *ret = NULL;
2267 const WCHAR *p;
2269 /* if we have an app name, everything is easy */
2271 if (appname)
2273 /* use the unmodified app name as file name */
2274 lstrcpynW( buffer, appname, buflen );
2275 *handle = open_exe_file( buffer, binary_info );
2276 if (!(ret = cmdline) || !cmdline[0])
2278 /* no command-line, create one */
2279 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2280 sprintfW( ret, quotesW, appname );
2282 return ret;
2285 /* first check for a quoted file name */
2287 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2289 int len = p - cmdline - 1;
2290 /* extract the quoted portion as file name */
2291 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2292 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2293 name[len] = 0;
2295 if (!find_exe_file( name, buffer, buflen, handle, binary_info )) goto done;
2296 ret = cmdline; /* no change necessary */
2297 goto done;
2300 /* now try the command-line word by word */
2302 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2303 return NULL;
2304 pos = name;
2305 p = cmdline;
2306 first_space = NULL;
2308 for (;;)
2310 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2311 *pos = 0;
2312 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2314 ret = cmdline;
2315 break;
2317 if (!first_space) first_space = pos;
2318 if (!(*pos++ = *p++)) break;
2321 if (!ret)
2323 SetLastError( ERROR_FILE_NOT_FOUND );
2325 else if (first_space) /* build a new command-line with quotes */
2327 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2328 goto done;
2329 sprintfW( ret, quotesW, name );
2330 strcatW( ret, p );
2333 done:
2334 HeapFree( GetProcessHeap(), 0, name );
2335 return ret;
2339 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2340 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2341 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2342 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2343 LPPROCESS_INFORMATION info )
2345 BOOL retv = FALSE;
2346 HANDLE hFile = 0;
2347 char *unixdir = NULL;
2348 WCHAR name[MAX_PATH];
2349 WCHAR *tidy_cmdline, *p, *envW = env;
2350 struct binary_info binary_info;
2352 /* Process the AppName and/or CmdLine to get module name and path */
2354 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2356 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2357 &hFile, &binary_info )))
2358 return FALSE;
2359 if (hFile == INVALID_HANDLE_VALUE) goto done;
2361 /* Warn if unsupported features are used */
2363 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2364 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2365 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2366 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2367 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2369 if (cur_dir)
2371 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2373 SetLastError(ERROR_DIRECTORY);
2374 goto done;
2377 else
2379 WCHAR buf[MAX_PATH];
2380 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2383 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2385 char *e = env;
2386 DWORD lenW;
2388 while (*e) e += strlen(e) + 1;
2389 e++; /* final null */
2390 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, NULL, 0 );
2391 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2392 MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, envW, lenW );
2393 flags |= CREATE_UNICODE_ENVIRONMENT;
2396 info->hThread = info->hProcess = 0;
2397 info->dwProcessId = info->dwThreadId = 0;
2399 if (binary_info.flags & BINARY_FLAG_DLL)
2401 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2402 SetLastError( ERROR_BAD_EXE_FORMAT );
2404 else switch (binary_info.type)
2406 case BINARY_PE:
2407 TRACE( "starting %s as Win%d binary (%s-%s, arch %04x%s)\n",
2408 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2409 wine_dbgstr_longlong(binary_info.res_start), wine_dbgstr_longlong(binary_info.res_end),
2410 binary_info.arch, (binary_info.flags & BINARY_FLAG_FAKEDLL) ? ", fakedll" : "" );
2411 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2412 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2413 break;
2414 case BINARY_OS216:
2415 case BINARY_WIN16:
2416 case BINARY_DOS:
2417 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2418 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2419 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2420 break;
2421 case BINARY_UNIX_LIB:
2422 TRACE( "starting %s as %d-bit Winelib app\n",
2423 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2424 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2425 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2426 break;
2427 case BINARY_UNKNOWN:
2428 /* check for .com or .bat extension */
2429 if ((p = strrchrW( name, '.' )))
2431 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2433 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2434 binary_info.type = BINARY_DOS;
2435 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2436 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2437 inherit, flags, startup_info, info, unixdir,
2438 &binary_info, FALSE );
2439 break;
2441 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2443 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2444 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2445 inherit, flags, startup_info, info );
2446 break;
2449 /* fall through */
2450 case BINARY_UNIX_EXE:
2452 /* unknown file, try as unix executable */
2453 char *unix_name;
2455 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2457 if ((unix_name = wine_get_unix_file_name( name )))
2459 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2460 HeapFree( GetProcessHeap(), 0, unix_name );
2463 break;
2465 if (hFile) CloseHandle( hFile );
2467 done:
2468 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2469 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2470 HeapFree( GetProcessHeap(), 0, unixdir );
2471 if (retv)
2472 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2473 return retv;
2477 /**********************************************************************
2478 * CreateProcessA (KERNEL32.@)
2480 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2481 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2482 DWORD flags, LPVOID env, LPCSTR cur_dir,
2483 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2485 BOOL ret = FALSE;
2486 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2487 UNICODE_STRING desktopW, titleW;
2488 STARTUPINFOW infoW;
2490 desktopW.Buffer = NULL;
2491 titleW.Buffer = NULL;
2492 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2493 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2494 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2496 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2497 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2499 memcpy( &infoW, startup_info, sizeof(infoW) );
2500 infoW.lpDesktop = desktopW.Buffer;
2501 infoW.lpTitle = titleW.Buffer;
2503 if (startup_info->lpReserved)
2504 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2505 debugstr_a(startup_info->lpReserved));
2507 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2508 inherit, flags, env, cur_dirW, &infoW, info );
2509 done:
2510 HeapFree( GetProcessHeap(), 0, app_nameW );
2511 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2512 HeapFree( GetProcessHeap(), 0, cur_dirW );
2513 RtlFreeUnicodeString( &desktopW );
2514 RtlFreeUnicodeString( &titleW );
2515 return ret;
2519 /**********************************************************************
2520 * CreateProcessW (KERNEL32.@)
2522 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2523 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2524 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2525 LPPROCESS_INFORMATION info )
2527 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2528 inherit, flags, env, cur_dir, startup_info, info);
2532 /**********************************************************************
2533 * exec_process
2535 static void exec_process( LPCWSTR name )
2537 HANDLE hFile;
2538 WCHAR *p;
2539 STARTUPINFOW startup_info;
2540 PROCESS_INFORMATION info;
2541 struct binary_info binary_info;
2543 hFile = open_exe_file( name, &binary_info );
2544 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2546 memset( &startup_info, 0, sizeof(startup_info) );
2547 startup_info.cb = sizeof(startup_info);
2549 /* Determine executable type */
2551 if (binary_info.flags & BINARY_FLAG_DLL)
2553 CloseHandle( hFile );
2554 return;
2557 switch (binary_info.type)
2559 case BINARY_PE:
2560 TRACE( "starting %s as Win%d binary (%s-%s, arch %04x)\n",
2561 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2562 wine_dbgstr_longlong(binary_info.res_start), wine_dbgstr_longlong(binary_info.res_end),
2563 binary_info.arch );
2564 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2565 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2566 break;
2567 case BINARY_UNIX_LIB:
2568 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2569 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2570 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2571 break;
2572 case BINARY_UNKNOWN:
2573 /* check for .com or .pif extension */
2574 if (!(p = strrchrW( name, '.' ))) break;
2575 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2576 binary_info.type = BINARY_DOS;
2577 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2578 /* fall through */
2579 case BINARY_OS216:
2580 case BINARY_WIN16:
2581 case BINARY_DOS:
2582 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2583 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2584 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2585 break;
2586 default:
2587 break;
2589 CloseHandle( hFile );
2593 /***********************************************************************
2594 * wait_input_idle
2596 * Wrapper to call WaitForInputIdle USER function
2598 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2600 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2602 HMODULE mod = GetModuleHandleA( "user32.dll" );
2603 if (mod)
2605 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2606 if (ptr) return ptr( process, timeout );
2608 return 0;
2612 /***********************************************************************
2613 * WinExec (KERNEL32.@)
2615 UINT WINAPI DECLSPEC_HOTPATCH WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2617 PROCESS_INFORMATION info;
2618 STARTUPINFOA startup;
2619 char *cmdline;
2620 UINT ret;
2622 memset( &startup, 0, sizeof(startup) );
2623 startup.cb = sizeof(startup);
2624 startup.dwFlags = STARTF_USESHOWWINDOW;
2625 startup.wShowWindow = nCmdShow;
2627 /* cmdline needs to be writable for CreateProcess */
2628 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2629 strcpy( cmdline, lpCmdLine );
2631 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2632 0, NULL, NULL, &startup, &info ))
2634 /* Give 30 seconds to the app to come up */
2635 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2636 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2637 ret = 33;
2638 /* Close off the handles */
2639 CloseHandle( info.hThread );
2640 CloseHandle( info.hProcess );
2642 else if ((ret = GetLastError()) >= 32)
2644 FIXME("Strange error set by CreateProcess: %d\n", ret );
2645 ret = 11;
2647 HeapFree( GetProcessHeap(), 0, cmdline );
2648 return ret;
2652 /**********************************************************************
2653 * LoadModule (KERNEL32.@)
2655 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2657 LOADPARMS32 *params = paramBlock;
2658 PROCESS_INFORMATION info;
2659 STARTUPINFOA startup;
2660 DWORD ret;
2661 LPSTR cmdline, p;
2662 char filename[MAX_PATH];
2663 BYTE len;
2665 if (!name) return ERROR_FILE_NOT_FOUND;
2667 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2668 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2669 return GetLastError();
2671 len = (BYTE)params->lpCmdLine[0];
2672 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2673 return ERROR_NOT_ENOUGH_MEMORY;
2675 strcpy( cmdline, filename );
2676 p = cmdline + strlen(cmdline);
2677 *p++ = ' ';
2678 memcpy( p, params->lpCmdLine + 1, len );
2679 p[len] = 0;
2681 memset( &startup, 0, sizeof(startup) );
2682 startup.cb = sizeof(startup);
2683 if (params->lpCmdShow)
2685 startup.dwFlags = STARTF_USESHOWWINDOW;
2686 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2689 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2690 params->lpEnvAddress, NULL, &startup, &info ))
2692 /* Give 30 seconds to the app to come up */
2693 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2694 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2695 ret = 33;
2696 /* Close off the handles */
2697 CloseHandle( info.hThread );
2698 CloseHandle( info.hProcess );
2700 else if ((ret = GetLastError()) >= 32)
2702 FIXME("Strange error set by CreateProcess: %u\n", ret );
2703 ret = 11;
2706 HeapFree( GetProcessHeap(), 0, cmdline );
2707 return ret;
2711 /******************************************************************************
2712 * TerminateProcess (KERNEL32.@)
2714 * Terminates a process.
2716 * PARAMS
2717 * handle [I] Process to terminate.
2718 * exit_code [I] Exit code.
2720 * RETURNS
2721 * Success: TRUE.
2722 * Failure: FALSE, check GetLastError().
2724 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2726 NTSTATUS status;
2728 if (!handle)
2730 SetLastError( ERROR_INVALID_HANDLE );
2731 return FALSE;
2734 status = NtTerminateProcess( handle, exit_code );
2735 if (status) SetLastError( RtlNtStatusToDosError(status) );
2736 return !status;
2739 /***********************************************************************
2740 * ExitProcess (KERNEL32.@)
2742 * Exits the current process.
2744 * PARAMS
2745 * status [I] Status code to exit with.
2747 * RETURNS
2748 * Nothing.
2750 #ifdef __i386__
2751 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2752 "pushl %ebp\n\t"
2753 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2754 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2755 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2756 "pushl 8(%ebp)\n\t"
2757 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
2758 "leave\n\t"
2759 "ret $4" )
2760 #else
2762 void WINAPI ExitProcess( DWORD status )
2764 RtlExitUserProcess( status );
2767 #endif
2769 /***********************************************************************
2770 * GetExitCodeProcess [KERNEL32.@]
2772 * Gets termination status of specified process.
2774 * PARAMS
2775 * hProcess [in] Handle to the process.
2776 * lpExitCode [out] Address to receive termination status.
2778 * RETURNS
2779 * Success: TRUE
2780 * Failure: FALSE
2782 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2784 NTSTATUS status;
2785 PROCESS_BASIC_INFORMATION pbi;
2787 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2788 sizeof(pbi), NULL);
2789 if (status == STATUS_SUCCESS)
2791 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2792 return TRUE;
2794 SetLastError( RtlNtStatusToDosError(status) );
2795 return FALSE;
2799 /***********************************************************************
2800 * SetErrorMode (KERNEL32.@)
2802 UINT WINAPI SetErrorMode( UINT mode )
2804 UINT old;
2806 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2807 &old, sizeof(old), NULL );
2808 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2809 &mode, sizeof(mode) );
2810 return old;
2813 /***********************************************************************
2814 * GetErrorMode (KERNEL32.@)
2816 UINT WINAPI GetErrorMode( void )
2818 UINT mode;
2820 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2821 &mode, sizeof(mode), NULL );
2822 return mode;
2825 /**********************************************************************
2826 * TlsAlloc [KERNEL32.@]
2828 * Allocates a thread local storage index.
2830 * RETURNS
2831 * Success: TLS index.
2832 * Failure: 0xFFFFFFFF
2834 DWORD WINAPI TlsAlloc( void )
2836 DWORD index;
2837 PEB * const peb = NtCurrentTeb()->Peb;
2839 RtlAcquirePebLock();
2840 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 1 );
2841 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2842 else
2844 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2845 if (index != ~0U)
2847 if (!NtCurrentTeb()->TlsExpansionSlots &&
2848 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2849 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2851 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2852 index = ~0U;
2853 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2855 else
2857 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2858 index += TLS_MINIMUM_AVAILABLE;
2861 else SetLastError( ERROR_NO_MORE_ITEMS );
2863 RtlReleasePebLock();
2864 return index;
2868 /**********************************************************************
2869 * TlsFree [KERNEL32.@]
2871 * Releases a thread local storage index, making it available for reuse.
2873 * PARAMS
2874 * index [in] TLS index to free.
2876 * RETURNS
2877 * Success: TRUE
2878 * Failure: FALSE
2880 BOOL WINAPI TlsFree( DWORD index )
2882 BOOL ret;
2884 RtlAcquirePebLock();
2885 if (index >= TLS_MINIMUM_AVAILABLE)
2887 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2888 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2890 else
2892 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2893 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2895 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2896 else SetLastError( ERROR_INVALID_PARAMETER );
2897 RtlReleasePebLock();
2898 return ret;
2902 /**********************************************************************
2903 * TlsGetValue [KERNEL32.@]
2905 * Gets value in a thread's TLS slot.
2907 * PARAMS
2908 * index [in] TLS index to retrieve value for.
2910 * RETURNS
2911 * Success: Value stored in calling thread's TLS slot for index.
2912 * Failure: 0 and GetLastError() returns NO_ERROR.
2914 LPVOID WINAPI TlsGetValue( DWORD index )
2916 LPVOID ret;
2918 if (index < TLS_MINIMUM_AVAILABLE)
2920 ret = NtCurrentTeb()->TlsSlots[index];
2922 else
2924 index -= TLS_MINIMUM_AVAILABLE;
2925 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2927 SetLastError( ERROR_INVALID_PARAMETER );
2928 return NULL;
2930 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2931 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2933 SetLastError( ERROR_SUCCESS );
2934 return ret;
2938 /**********************************************************************
2939 * TlsSetValue [KERNEL32.@]
2941 * Stores a value in the thread's TLS slot.
2943 * PARAMS
2944 * index [in] TLS index to set value for.
2945 * value [in] Value to be stored.
2947 * RETURNS
2948 * Success: TRUE
2949 * Failure: FALSE
2951 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2953 if (index < TLS_MINIMUM_AVAILABLE)
2955 NtCurrentTeb()->TlsSlots[index] = value;
2957 else
2959 index -= TLS_MINIMUM_AVAILABLE;
2960 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2962 SetLastError( ERROR_INVALID_PARAMETER );
2963 return FALSE;
2965 if (!NtCurrentTeb()->TlsExpansionSlots &&
2966 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2967 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2969 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2970 return FALSE;
2972 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2974 return TRUE;
2978 /***********************************************************************
2979 * GetProcessFlags (KERNEL32.@)
2981 DWORD WINAPI GetProcessFlags( DWORD processid )
2983 IMAGE_NT_HEADERS *nt;
2984 DWORD flags = 0;
2986 if (processid && processid != GetCurrentProcessId()) return 0;
2988 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2990 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2991 flags |= PDB32_CONSOLE_PROC;
2993 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2994 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2995 return flags;
2999 /*********************************************************************
3000 * OpenProcess (KERNEL32.@)
3002 * Opens a handle to a process.
3004 * PARAMS
3005 * access [I] Desired access rights assigned to the returned handle.
3006 * inherit [I] Determines whether or not child processes will inherit the handle.
3007 * id [I] Process identifier of the process to get a handle to.
3009 * RETURNS
3010 * Success: Valid handle to the specified process.
3011 * Failure: NULL, check GetLastError().
3013 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
3015 NTSTATUS status;
3016 HANDLE handle;
3017 OBJECT_ATTRIBUTES attr;
3018 CLIENT_ID cid;
3020 cid.UniqueProcess = ULongToHandle(id);
3021 cid.UniqueThread = 0; /* FIXME ? */
3023 attr.Length = sizeof(OBJECT_ATTRIBUTES);
3024 attr.RootDirectory = NULL;
3025 attr.Attributes = inherit ? OBJ_INHERIT : 0;
3026 attr.SecurityDescriptor = NULL;
3027 attr.SecurityQualityOfService = NULL;
3028 attr.ObjectName = NULL;
3030 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
3032 status = NtOpenProcess(&handle, access, &attr, &cid);
3033 if (status != STATUS_SUCCESS)
3035 SetLastError( RtlNtStatusToDosError(status) );
3036 return NULL;
3038 return handle;
3042 /*********************************************************************
3043 * GetProcessId (KERNEL32.@)
3045 * Gets the a unique identifier of a process.
3047 * PARAMS
3048 * hProcess [I] Handle to the process.
3050 * RETURNS
3051 * Success: TRUE.
3052 * Failure: FALSE, check GetLastError().
3054 * NOTES
3056 * The identifier is unique only on the machine and only until the process
3057 * exits (including system shutdown).
3059 DWORD WINAPI GetProcessId( HANDLE hProcess )
3061 NTSTATUS status;
3062 PROCESS_BASIC_INFORMATION pbi;
3064 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3065 sizeof(pbi), NULL);
3066 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
3067 SetLastError( RtlNtStatusToDosError(status) );
3068 return 0;
3072 /*********************************************************************
3073 * CloseHandle (KERNEL32.@)
3075 * Closes a handle.
3077 * PARAMS
3078 * handle [I] Handle to close.
3080 * RETURNS
3081 * Success: TRUE.
3082 * Failure: FALSE, check GetLastError().
3084 BOOL WINAPI CloseHandle( HANDLE handle )
3086 NTSTATUS status;
3088 /* stdio handles need special treatment */
3089 if (handle == (HANDLE)STD_INPUT_HANDLE)
3090 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
3091 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
3092 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
3093 else if (handle == (HANDLE)STD_ERROR_HANDLE)
3094 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
3096 if (is_console_handle(handle))
3097 return CloseConsoleHandle(handle);
3099 status = NtClose( handle );
3100 if (status) SetLastError( RtlNtStatusToDosError(status) );
3101 return !status;
3105 /*********************************************************************
3106 * GetHandleInformation (KERNEL32.@)
3108 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
3110 OBJECT_DATA_INFORMATION info;
3111 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
3113 if (status) SetLastError( RtlNtStatusToDosError(status) );
3114 else if (flags)
3116 *flags = 0;
3117 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3118 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3120 return !status;
3124 /*********************************************************************
3125 * SetHandleInformation (KERNEL32.@)
3127 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3129 OBJECT_DATA_INFORMATION info;
3130 NTSTATUS status;
3132 /* if not setting both fields, retrieve current value first */
3133 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3134 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3136 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3138 SetLastError( RtlNtStatusToDosError(status) );
3139 return FALSE;
3142 if (mask & HANDLE_FLAG_INHERIT)
3143 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3144 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3145 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3147 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3148 if (status) SetLastError( RtlNtStatusToDosError(status) );
3149 return !status;
3153 /*********************************************************************
3154 * DuplicateHandle (KERNEL32.@)
3156 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3157 HANDLE dest_process, HANDLE *dest,
3158 DWORD access, BOOL inherit, DWORD options )
3160 NTSTATUS status;
3162 if (is_console_handle(source))
3164 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3165 if (source_process != dest_process ||
3166 source_process != GetCurrentProcess())
3168 SetLastError(ERROR_INVALID_PARAMETER);
3169 return FALSE;
3171 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3172 return (*dest != INVALID_HANDLE_VALUE);
3174 status = NtDuplicateObject( source_process, source, dest_process, dest,
3175 access, inherit ? OBJ_INHERIT : 0, options );
3176 if (status) SetLastError( RtlNtStatusToDosError(status) );
3177 return !status;
3181 /***********************************************************************
3182 * ConvertToGlobalHandle (KERNEL32.@)
3184 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3186 HANDLE ret = INVALID_HANDLE_VALUE;
3187 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3188 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3189 return ret;
3193 /***********************************************************************
3194 * SetHandleContext (KERNEL32.@)
3196 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3198 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3199 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3200 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3201 return FALSE;
3205 /***********************************************************************
3206 * GetHandleContext (KERNEL32.@)
3208 DWORD WINAPI GetHandleContext(HANDLE hnd)
3210 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3211 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3212 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3213 return 0;
3217 /***********************************************************************
3218 * CreateSocketHandle (KERNEL32.@)
3220 HANDLE WINAPI CreateSocketHandle(void)
3222 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3223 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3224 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3225 return INVALID_HANDLE_VALUE;
3229 /***********************************************************************
3230 * SetPriorityClass (KERNEL32.@)
3232 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3234 NTSTATUS status;
3235 PROCESS_PRIORITY_CLASS ppc;
3237 ppc.Foreground = FALSE;
3238 switch (priorityclass)
3240 case IDLE_PRIORITY_CLASS:
3241 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3242 case BELOW_NORMAL_PRIORITY_CLASS:
3243 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3244 case NORMAL_PRIORITY_CLASS:
3245 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3246 case ABOVE_NORMAL_PRIORITY_CLASS:
3247 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3248 case HIGH_PRIORITY_CLASS:
3249 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3250 case REALTIME_PRIORITY_CLASS:
3251 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3252 default:
3253 SetLastError(ERROR_INVALID_PARAMETER);
3254 return FALSE;
3257 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3258 &ppc, sizeof(ppc));
3260 if (status != STATUS_SUCCESS)
3262 SetLastError( RtlNtStatusToDosError(status) );
3263 return FALSE;
3265 return TRUE;
3269 /***********************************************************************
3270 * GetPriorityClass (KERNEL32.@)
3272 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3274 NTSTATUS status;
3275 PROCESS_BASIC_INFORMATION pbi;
3277 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3278 sizeof(pbi), NULL);
3279 if (status != STATUS_SUCCESS)
3281 SetLastError( RtlNtStatusToDosError(status) );
3282 return 0;
3284 switch (pbi.BasePriority)
3286 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3287 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3288 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3289 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3290 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3291 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3293 SetLastError( ERROR_INVALID_PARAMETER );
3294 return 0;
3298 /***********************************************************************
3299 * SetProcessAffinityMask (KERNEL32.@)
3301 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3303 NTSTATUS status;
3305 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3306 &affmask, sizeof(DWORD_PTR));
3307 if (status)
3309 SetLastError( RtlNtStatusToDosError(status) );
3310 return FALSE;
3312 return TRUE;
3316 /**********************************************************************
3317 * GetProcessAffinityMask (KERNEL32.@)
3319 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3321 NTSTATUS status = STATUS_SUCCESS;
3323 if (process_mask)
3325 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3326 process_mask, sizeof(*process_mask), NULL )))
3327 SetLastError( RtlNtStatusToDosError(status) );
3329 if (system_mask && status == STATUS_SUCCESS)
3331 SYSTEM_BASIC_INFORMATION info;
3333 if ((status = NtQuerySystemInformation( SystemBasicInformation, &info, sizeof(info), NULL )))
3334 SetLastError( RtlNtStatusToDosError(status) );
3335 else
3336 *system_mask = info.ActiveProcessorsAffinityMask;
3338 return !status;
3342 /***********************************************************************
3343 * GetProcessVersion (KERNEL32.@)
3345 DWORD WINAPI GetProcessVersion( DWORD pid )
3347 HANDLE process;
3348 NTSTATUS status;
3349 PROCESS_BASIC_INFORMATION pbi;
3350 SIZE_T count;
3351 PEB peb;
3352 IMAGE_DOS_HEADER dos;
3353 IMAGE_NT_HEADERS nt;
3354 DWORD ver = 0;
3356 if (!pid || pid == GetCurrentProcessId())
3358 IMAGE_NT_HEADERS *pnt;
3360 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3361 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3362 pnt->OptionalHeader.MinorSubsystemVersion);
3363 return 0;
3366 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3367 if (!process) return 0;
3369 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3370 if (status) goto err;
3372 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3373 if (status || count != sizeof(peb)) goto err;
3375 memset(&dos, 0, sizeof(dos));
3376 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3377 if (status || count != sizeof(dos)) goto err;
3378 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3380 memset(&nt, 0, sizeof(nt));
3381 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3382 if (status || count != sizeof(nt)) goto err;
3383 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3385 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3387 err:
3388 CloseHandle(process);
3390 if (status != STATUS_SUCCESS)
3391 SetLastError(RtlNtStatusToDosError(status));
3393 return ver;
3397 /***********************************************************************
3398 * SetProcessWorkingSetSize [KERNEL32.@]
3399 * Sets the min/max working set sizes for a specified process.
3401 * PARAMS
3402 * hProcess [I] Handle to the process of interest
3403 * minset [I] Specifies minimum working set size
3404 * maxset [I] Specifies maximum working set size
3406 * RETURNS
3407 * Success: TRUE
3408 * Failure: FALSE
3410 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3411 SIZE_T maxset)
3413 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3414 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3415 /* Trim the working set to zero */
3416 /* Swap the process out of physical RAM */
3418 return TRUE;
3421 /***********************************************************************
3422 * K32EmptyWorkingSet (KERNEL32.@)
3424 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3426 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3430 /***********************************************************************
3431 * GetProcessWorkingSetSizeEx (KERNEL32.@)
3433 BOOL WINAPI GetProcessWorkingSetSizeEx(HANDLE process, SIZE_T *minset,
3434 SIZE_T *maxset, DWORD *flags)
3436 FIXME("(%p,%p,%p,%p): stub\n", process, minset, maxset, flags);
3437 /* 32 MB working set size */
3438 if (minset) *minset = 32*1024*1024;
3439 if (maxset) *maxset = 32*1024*1024;
3440 if (flags) *flags = QUOTA_LIMITS_HARDWS_MIN_DISABLE |
3441 QUOTA_LIMITS_HARDWS_MAX_DISABLE;
3442 return TRUE;
3446 /***********************************************************************
3447 * GetProcessWorkingSetSize (KERNEL32.@)
3449 BOOL WINAPI GetProcessWorkingSetSize(HANDLE process, SIZE_T *minset, SIZE_T *maxset)
3451 return GetProcessWorkingSetSizeEx(process, minset, maxset, NULL);
3455 /***********************************************************************
3456 * SetProcessShutdownParameters (KERNEL32.@)
3458 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3460 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3461 shutdown_flags = flags;
3462 shutdown_priority = level;
3463 return TRUE;
3467 /***********************************************************************
3468 * GetProcessShutdownParameters (KERNEL32.@)
3471 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3473 *lpdwLevel = shutdown_priority;
3474 *lpdwFlags = shutdown_flags;
3475 return TRUE;
3479 /***********************************************************************
3480 * GetProcessPriorityBoost (KERNEL32.@)
3482 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3484 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3486 /* Report that no boost is present.. */
3487 *pDisablePriorityBoost = FALSE;
3489 return TRUE;
3492 /***********************************************************************
3493 * SetProcessPriorityBoost (KERNEL32.@)
3495 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3497 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3498 /* Say we can do it. I doubt the program will notice that we don't. */
3499 return TRUE;
3503 /***********************************************************************
3504 * ReadProcessMemory (KERNEL32.@)
3506 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3507 SIZE_T *bytes_read )
3509 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3510 if (status) SetLastError( RtlNtStatusToDosError(status) );
3511 return !status;
3515 /***********************************************************************
3516 * WriteProcessMemory (KERNEL32.@)
3518 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3519 SIZE_T *bytes_written )
3521 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3522 if (status) SetLastError( RtlNtStatusToDosError(status) );
3523 return !status;
3527 /****************************************************************************
3528 * FlushInstructionCache (KERNEL32.@)
3530 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3532 NTSTATUS status;
3533 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3534 if (status) SetLastError( RtlNtStatusToDosError(status) );
3535 return !status;
3539 /******************************************************************
3540 * GetProcessIoCounters (KERNEL32.@)
3542 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3544 NTSTATUS status;
3546 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3547 ioc, sizeof(*ioc), NULL);
3548 if (status) SetLastError( RtlNtStatusToDosError(status) );
3549 return !status;
3552 /******************************************************************
3553 * GetProcessHandleCount (KERNEL32.@)
3555 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3557 NTSTATUS status;
3559 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3560 cnt, sizeof(*cnt), NULL);
3561 if (status) SetLastError( RtlNtStatusToDosError(status) );
3562 return !status;
3565 /******************************************************************
3566 * QueryFullProcessImageNameA (KERNEL32.@)
3568 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3570 BOOL retval;
3571 DWORD pdwSizeW = *pdwSize;
3572 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3574 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3576 if(retval)
3577 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3578 lpExeName, *pdwSize, NULL, NULL));
3579 if(retval)
3580 *pdwSize = strlen(lpExeName);
3582 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3583 return retval;
3586 /******************************************************************
3587 * QueryFullProcessImageNameW (KERNEL32.@)
3589 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3591 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3592 UNICODE_STRING *dynamic_buffer = NULL;
3593 UNICODE_STRING *result = NULL;
3594 NTSTATUS status;
3595 DWORD needed;
3597 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3598 * is a DOS path and we depend on this. */
3599 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3600 sizeof(buffer) - sizeof(WCHAR), &needed);
3601 if (status == STATUS_INFO_LENGTH_MISMATCH)
3603 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3604 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3605 result = dynamic_buffer;
3607 else
3608 result = (PUNICODE_STRING)buffer;
3610 if (status) goto cleanup;
3612 if (dwFlags & PROCESS_NAME_NATIVE)
3614 WCHAR drive[3];
3615 WCHAR device[1024];
3616 DWORD ntlen, devlen;
3618 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3620 /* We cannot convert it to an NT device path so fail */
3621 status = STATUS_NO_SUCH_DEVICE;
3622 goto cleanup;
3625 /* Find this drive's NT device path */
3626 drive[0] = result->Buffer[0];
3627 drive[1] = ':';
3628 drive[2] = 0;
3629 if (!QueryDosDeviceW(drive, device, sizeof(device)/sizeof(*device)))
3631 status = STATUS_NO_SUCH_DEVICE;
3632 goto cleanup;
3635 devlen = lstrlenW(device);
3636 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3637 if (ntlen + 1 > *pdwSize)
3639 status = STATUS_BUFFER_TOO_SMALL;
3640 goto cleanup;
3642 *pdwSize = ntlen;
3644 memcpy(lpExeName, device, devlen * sizeof(*device));
3645 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3646 lpExeName[*pdwSize] = 0;
3647 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3649 else
3651 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3653 status = STATUS_BUFFER_TOO_SMALL;
3654 goto cleanup;
3657 *pdwSize = result->Length/sizeof(WCHAR);
3658 memcpy( lpExeName, result->Buffer, result->Length );
3659 lpExeName[*pdwSize] = 0;
3662 cleanup:
3663 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3664 if (status) SetLastError( RtlNtStatusToDosError(status) );
3665 return !status;
3668 /***********************************************************************
3669 * K32GetProcessImageFileNameA (KERNEL32.@)
3671 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3673 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3676 /***********************************************************************
3677 * K32GetProcessImageFileNameW (KERNEL32.@)
3679 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3681 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3684 /***********************************************************************
3685 * K32EnumProcesses (KERNEL32.@)
3687 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3689 SYSTEM_PROCESS_INFORMATION *spi;
3690 ULONG size = 0x4000;
3691 void *buf = NULL;
3692 NTSTATUS status;
3694 do {
3695 size *= 2;
3696 HeapFree(GetProcessHeap(), 0, buf);
3697 buf = HeapAlloc(GetProcessHeap(), 0, size);
3698 if (!buf)
3699 return FALSE;
3701 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3702 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3704 if (status != STATUS_SUCCESS)
3706 HeapFree(GetProcessHeap(), 0, buf);
3707 SetLastError(RtlNtStatusToDosError(status));
3708 return FALSE;
3711 spi = buf;
3713 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3715 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3716 *lpcbUsed += sizeof(DWORD);
3718 if (spi->NextEntryOffset == 0)
3719 break;
3721 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3724 HeapFree(GetProcessHeap(), 0, buf);
3725 return TRUE;
3728 /***********************************************************************
3729 * K32QueryWorkingSet (KERNEL32.@)
3731 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3733 NTSTATUS status;
3735 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3737 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3739 if (status)
3741 SetLastError( RtlNtStatusToDosError( status ) );
3742 return FALSE;
3744 return TRUE;
3747 /***********************************************************************
3748 * K32QueryWorkingSetEx (KERNEL32.@)
3750 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3752 NTSTATUS status;
3754 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3756 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3758 if (status)
3760 SetLastError( RtlNtStatusToDosError( status ) );
3761 return FALSE;
3763 return TRUE;
3766 /***********************************************************************
3767 * K32GetProcessMemoryInfo (KERNEL32.@)
3769 * Retrieve memory usage information for a given process
3772 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3773 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3775 NTSTATUS status;
3776 VM_COUNTERS vmc;
3778 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3780 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3781 return FALSE;
3784 status = NtQueryInformationProcess(process, ProcessVmCounters,
3785 &vmc, sizeof(vmc), NULL);
3787 if (status)
3789 SetLastError(RtlNtStatusToDosError(status));
3790 return FALSE;
3793 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3794 pmc->PageFaultCount = vmc.PageFaultCount;
3795 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3796 pmc->WorkingSetSize = vmc.WorkingSetSize;
3797 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3798 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3799 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3800 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3801 pmc->PagefileUsage = vmc.PagefileUsage;
3802 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3804 return TRUE;
3807 /***********************************************************************
3808 * ProcessIdToSessionId (KERNEL32.@)
3809 * This function is available on Terminal Server 4SP4 and Windows 2000
3811 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3813 if (procid != GetCurrentProcessId())
3814 FIXME("Unsupported for other processes.\n");
3816 *sessionid_ptr = NtCurrentTeb()->Peb->SessionId;
3817 return TRUE;
3821 /***********************************************************************
3822 * RegisterServiceProcess (KERNEL32.@)
3824 * A service process calls this function to ensure that it continues to run
3825 * even after a user logged off.
3827 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3829 /* I don't think that Wine needs to do anything in this function */
3830 return 1; /* success */
3834 /**********************************************************************
3835 * IsWow64Process (KERNEL32.@)
3837 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3839 ULONG_PTR pbi;
3840 NTSTATUS status;
3842 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3844 if (status != STATUS_SUCCESS)
3846 SetLastError( RtlNtStatusToDosError( status ) );
3847 return FALSE;
3849 *Wow64Process = (pbi != 0);
3850 return TRUE;
3854 /***********************************************************************
3855 * GetCurrentProcess (KERNEL32.@)
3857 * Get a handle to the current process.
3859 * PARAMS
3860 * None.
3862 * RETURNS
3863 * A handle representing the current process.
3865 #undef GetCurrentProcess
3866 HANDLE WINAPI GetCurrentProcess(void)
3868 return (HANDLE)~(ULONG_PTR)0;
3871 /***********************************************************************
3872 * GetLogicalProcessorInformation (KERNEL32.@)
3874 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3876 NTSTATUS status;
3878 TRACE("(%p,%p)\n", buffer, pBufLen);
3880 if(!pBufLen)
3882 SetLastError(ERROR_INVALID_PARAMETER);
3883 return FALSE;
3886 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
3888 if (status == STATUS_INFO_LENGTH_MISMATCH)
3890 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3891 return FALSE;
3893 if (status != STATUS_SUCCESS)
3895 SetLastError( RtlNtStatusToDosError( status ) );
3896 return FALSE;
3898 return TRUE;
3901 /***********************************************************************
3902 * GetLogicalProcessorInformationEx (KERNEL32.@)
3904 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, DWORD *len)
3906 NTSTATUS status;
3908 TRACE("(%u,%p,%p)\n", relationship, buffer, len);
3910 if (!len)
3912 SetLastError( ERROR_INVALID_PARAMETER );
3913 return FALSE;
3916 status = NtQuerySystemInformationEx( SystemLogicalProcessorInformationEx, &relationship, sizeof(relationship),
3917 buffer, *len, len );
3918 if (status == STATUS_INFO_LENGTH_MISMATCH)
3920 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3921 return FALSE;
3923 if (status != STATUS_SUCCESS)
3925 SetLastError( RtlNtStatusToDosError( status ) );
3926 return FALSE;
3928 return TRUE;
3931 /***********************************************************************
3932 * CmdBatNotification (KERNEL32.@)
3934 * Notifies the system that a batch file has started or finished.
3936 * PARAMS
3937 * bBatchRunning [I] TRUE if a batch file has started or
3938 * FALSE if a batch file has finished executing.
3940 * RETURNS
3941 * Unknown.
3943 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3945 FIXME("%d\n", bBatchRunning);
3946 return FALSE;
3950 /***********************************************************************
3951 * RegisterApplicationRestart (KERNEL32.@)
3953 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3955 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3957 return S_OK;
3960 /**********************************************************************
3961 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3963 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3965 static int once;
3966 if (!once++) FIXME("stub\n");
3967 /* Return current session id. */
3968 return NtCurrentTeb()->Peb->SessionId;
3971 /**********************************************************************
3972 * GetSystemDEPPolicy (KERNEL32.@)
3974 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3976 FIXME("stub\n");
3977 return OptIn;
3980 /**********************************************************************
3981 * SetProcessDEPPolicy (KERNEL32.@)
3983 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3985 FIXME("(%d): stub\n", newDEP);
3986 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3987 return FALSE;
3990 /**********************************************************************
3991 * ApplicationRecoveryFinished (KERNEL32.@)
3993 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
3995 FIXME(": stub\n");
3996 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3999 /**********************************************************************
4000 * ApplicationRecoveryInProgress (KERNEL32.@)
4002 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
4004 FIXME(":%p stub\n", canceled);
4005 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4006 return E_FAIL;
4009 /**********************************************************************
4010 * RegisterApplicationRecoveryCallback (KERNEL32.@)
4012 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
4014 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
4015 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4016 return E_FAIL;
4019 /**********************************************************************
4020 * GetNumaHighestNodeNumber (KERNEL32.@)
4022 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
4024 *highestnode = 0;
4025 FIXME("(%p): semi-stub\n", highestnode);
4026 return TRUE;
4029 /**********************************************************************
4030 * GetNumaNodeProcessorMask (KERNEL32.@)
4032 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
4034 FIXME("(%c %p): stub\n", node, mask);
4035 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4036 return FALSE;
4039 /**********************************************************************
4040 * GetNumaAvailableMemoryNode (KERNEL32.@)
4042 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
4044 FIXME("(%c %p): stub\n", node, available_bytes);
4045 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4046 return FALSE;
4049 /***********************************************************************
4050 * GetNumaProcessorNode (KERNEL32.@)
4052 BOOL WINAPI GetNumaProcessorNode(UCHAR processor, PUCHAR node)
4054 SYSTEM_INFO si;
4056 TRACE("(%d, %p)\n", processor, node);
4058 GetSystemInfo( &si );
4059 if (processor < si.dwNumberOfProcessors)
4061 *node = 0;
4062 return TRUE;
4065 *node = 0xFF;
4066 SetLastError(ERROR_INVALID_PARAMETER);
4067 return FALSE;
4070 /**********************************************************************
4071 * GetProcessDEPPolicy (KERNEL32.@)
4073 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
4075 NTSTATUS status;
4076 ULONG dep_flags;
4078 TRACE("(%p %p %p)\n", process, flags, permanent);
4080 status = NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
4081 &dep_flags, sizeof(dep_flags), NULL );
4082 if (!status)
4085 if (flags)
4087 *flags = 0;
4088 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE)
4089 *flags |= PROCESS_DEP_ENABLE;
4090 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION)
4091 *flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
4094 if (permanent)
4095 *permanent = (dep_flags & MEM_EXECUTE_OPTION_PERMANENT) != 0;
4098 if (status) SetLastError( RtlNtStatusToDosError(status) );
4099 return !status;
4102 /**********************************************************************
4103 * FlushProcessWriteBuffers (KERNEL32.@)
4105 VOID WINAPI FlushProcessWriteBuffers(void)
4107 static int once = 0;
4109 if (!once++)
4110 FIXME(": stub\n");
4113 /***********************************************************************
4114 * UnregisterApplicationRestart (KERNEL32.@)
4116 HRESULT WINAPI UnregisterApplicationRestart(void)
4118 FIXME(": stub\n");
4119 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4120 return S_OK;
4123 /***********************************************************************
4124 * GetSystemFirmwareTable (KERNEL32.@)
4126 UINT WINAPI GetSystemFirmwareTable(DWORD provider, DWORD id, PVOID buffer, DWORD size)
4128 FIXME("(%d %d %p %d):stub\n", provider, id, buffer, size);
4129 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4130 return 0;
4133 struct proc_thread_attr
4135 DWORD_PTR attr;
4136 SIZE_T size;
4137 void *value;
4140 struct _PROC_THREAD_ATTRIBUTE_LIST
4142 DWORD mask; /* bitmask of items in list */
4143 DWORD size; /* max number of items in list */
4144 DWORD count; /* number of items in list */
4145 DWORD pad;
4146 DWORD_PTR unk;
4147 struct proc_thread_attr attrs[1];
4150 /***********************************************************************
4151 * InitializeProcThreadAttributeList (KERNEL32.@)
4153 BOOL WINAPI InitializeProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4154 DWORD count, DWORD flags, SIZE_T *size)
4156 SIZE_T needed;
4157 BOOL ret = FALSE;
4159 TRACE("(%p %d %x %p)\n", list, count, flags, size);
4161 needed = FIELD_OFFSET(struct _PROC_THREAD_ATTRIBUTE_LIST, attrs[count]);
4162 if (list && *size >= needed)
4164 list->mask = 0;
4165 list->size = count;
4166 list->count = 0;
4167 list->unk = 0;
4168 ret = TRUE;
4170 else
4171 SetLastError(ERROR_INSUFFICIENT_BUFFER);
4173 *size = needed;
4174 return ret;
4177 /***********************************************************************
4178 * UpdateProcThreadAttribute (KERNEL32.@)
4180 BOOL WINAPI UpdateProcThreadAttribute(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4181 DWORD flags, DWORD_PTR attr, void *value, SIZE_T size,
4182 void *prev_ret, SIZE_T *size_ret)
4184 DWORD mask;
4185 struct proc_thread_attr *entry;
4187 TRACE("(%p %x %08lx %p %ld %p %p)\n", list, flags, attr, value, size, prev_ret, size_ret);
4189 if (list->count >= list->size)
4191 SetLastError(ERROR_GEN_FAILURE);
4192 return FALSE;
4195 switch (attr)
4197 case PROC_THREAD_ATTRIBUTE_PARENT_PROCESS:
4198 if (size != sizeof(HANDLE))
4200 SetLastError(ERROR_BAD_LENGTH);
4201 return FALSE;
4203 break;
4205 case PROC_THREAD_ATTRIBUTE_HANDLE_LIST:
4206 if ((size / sizeof(HANDLE)) * sizeof(HANDLE) != size)
4208 SetLastError(ERROR_BAD_LENGTH);
4209 return FALSE;
4211 break;
4213 case PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR:
4214 if (size != sizeof(PROCESSOR_NUMBER))
4216 SetLastError(ERROR_BAD_LENGTH);
4217 return FALSE;
4219 break;
4221 default:
4222 SetLastError(ERROR_NOT_SUPPORTED);
4223 return FALSE;
4226 mask = 1 << (attr & PROC_THREAD_ATTRIBUTE_NUMBER);
4228 if (list->mask & mask)
4230 SetLastError(ERROR_OBJECT_NAME_EXISTS);
4231 return FALSE;
4234 list->mask |= mask;
4236 entry = list->attrs + list->count;
4237 entry->attr = attr;
4238 entry->size = size;
4239 entry->value = value;
4240 list->count++;
4242 return TRUE;
4245 /***********************************************************************
4246 * DeleteProcThreadAttributeList (KERNEL32.@)
4248 void WINAPI DeleteProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list)
4250 return;
4253 /**********************************************************************
4254 * BaseFlushAppcompatCache (KERNEL32.@)
4256 BOOL WINAPI BaseFlushAppcompatCache(void)
4258 FIXME(": stub\n");
4259 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4260 return FALSE;