kernel32/tests: Also test wrong architecture with matching 32/64 bitness.
[wine.git] / dlls / kernel32 / process.c
blob62dc815c93521146ada6d265696ed4f502bf6f76
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/exception.h"
61 #include "wine/library.h"
62 #include "wine/server.h"
63 #include "wine/unicode.h"
64 #include "wine/debug.h"
66 WINE_DEFAULT_DEBUG_CHANNEL(process);
67 WINE_DECLARE_DEBUG_CHANNEL(file);
68 WINE_DECLARE_DEBUG_CHANNEL(relay);
70 #ifdef __APPLE__
71 extern char **__wine_get_main_environment(void);
72 #else
73 extern char **__wine_main_environ;
74 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
75 #endif
77 typedef struct
79 LPSTR lpEnvAddress;
80 LPSTR lpCmdLine;
81 LPSTR lpCmdShow;
82 DWORD dwReserved;
83 } LOADPARMS32;
85 static DWORD shutdown_flags = 0;
86 static DWORD shutdown_priority = 0x280;
87 static BOOL is_wow64;
88 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
90 HMODULE kernel32_handle = 0;
91 SYSTEM_BASIC_INFORMATION system_info = { 0 };
93 const WCHAR *DIR_Windows = NULL;
94 const WCHAR *DIR_System = NULL;
95 const WCHAR *DIR_SysWow64 = NULL;
97 /* Process flags */
98 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
99 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
100 #define PDB32_DOS_PROC 0x0010 /* Dos process */
101 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
102 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
103 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
105 static const WCHAR exeW[] = {'.','e','x','e',0};
106 static const WCHAR comW[] = {'.','c','o','m',0};
107 static const WCHAR batW[] = {'.','b','a','t',0};
108 static const WCHAR cmdW[] = {'.','c','m','d',0};
109 static const WCHAR pifW[] = {'.','p','i','f',0};
110 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
112 static void exec_process( LPCWSTR name );
114 extern void SHELL_LoadRegistry(void);
117 /***********************************************************************
118 * contains_path
120 static inline BOOL contains_path( LPCWSTR name )
122 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
126 /***********************************************************************
127 * is_special_env_var
129 * Check if an environment variable needs to be handled specially when
130 * passed through the Unix environment (i.e. prefixed with "WINE").
132 static inline BOOL is_special_env_var( const char *var )
134 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
135 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
136 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
137 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
138 !strncmp( var, "TMP=", sizeof("TMP=")-1 ) ||
139 !strncmp( var, "QT_", sizeof("QT_")-1 ));
143 /***********************************************************************
144 * is_path_prefix
146 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
148 unsigned int len = strlenW( prefix );
150 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
151 while (filename[len] == '\\') len++;
152 return len;
156 /***************************************************************************
157 * get_builtin_path
159 * Get the path of a builtin module when the native file does not exist.
161 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
162 UINT size, struct binary_info *binary_info )
164 WCHAR *file_part;
165 UINT len;
166 void *redir_disabled = 0;
167 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
169 /* builtin names cannot be empty or contain spaces */
170 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
172 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
173 Wow64RevertWow64FsRedirection( redir_disabled );
175 if (contains_path( libname ))
177 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
178 filename, &file_part ) > size * sizeof(WCHAR))
179 return FALSE; /* too long */
181 if ((len = is_path_prefix( DIR_System, filename )))
183 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
185 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
187 flags = 0;
189 else return FALSE;
191 if (filename + len != file_part) return FALSE;
193 else
195 len = strlenW( DIR_System );
196 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
197 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
198 file_part = filename + len;
199 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
200 strcpyW( file_part, libname );
201 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
203 if (ext && !strchrW( file_part, '.' ))
205 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
206 return FALSE; /* too long */
207 strcatW( file_part, ext );
209 binary_info->type = BINARY_UNIX_LIB;
210 binary_info->flags = flags;
211 binary_info->res_start = 0;
212 binary_info->res_end = 0;
213 /* assume current arch */
214 #if defined(__i386__) || defined(__x86_64__)
215 binary_info->arch = (flags & BINARY_FLAG_64BIT) ? IMAGE_FILE_MACHINE_AMD64 : IMAGE_FILE_MACHINE_I386;
216 #elif defined(__powerpc__)
217 binary_info->arch = IMAGE_FILE_MACHINE_POWERPC;
218 #elif defined(__arm__) && !defined(__ARMEB__)
219 binary_info->arch = IMAGE_FILE_MACHINE_ARMNT;
220 #elif defined(__aarch64__)
221 binary_info->arch = IMAGE_FILE_MACHINE_ARM64;
222 #else
223 binary_info->arch = IMAGE_FILE_MACHINE_UNKNOWN;
224 #endif
225 return TRUE;
229 /***********************************************************************
230 * open_exe_file
232 * Open a specific exe file, taking load order into account.
233 * Returns the file handle or 0 for a builtin exe.
235 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
237 HANDLE handle;
239 TRACE("looking for %s\n", debugstr_w(name) );
241 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
242 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
244 WCHAR buffer[MAX_PATH];
245 /* file doesn't exist, check for builtin */
246 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
247 handle = 0;
249 else MODULE_get_binary_info( handle, binary_info );
251 return handle;
255 /***********************************************************************
256 * find_exe_file
258 * Open an exe file, and return the full name and file handle.
259 * Returns FALSE if file could not be found.
261 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
262 HANDLE *handle, struct binary_info *binary_info )
264 TRACE("looking for %s\n", debugstr_w(name) );
266 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
267 /* no builtin found, try native without extension in case it is a Unix app */
268 !SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
270 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
271 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
272 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
274 MODULE_get_binary_info( *handle, binary_info );
275 return TRUE;
277 return FALSE;
281 /***********************************************************************
282 * build_initial_environment
284 * Build the Win32 environment from the Unix environment
286 static BOOL build_initial_environment(void)
288 SIZE_T size = 1;
289 char **e;
290 WCHAR *p, *endptr;
291 void *ptr;
292 char **env = __wine_get_main_environment();
294 /* Compute the total size of the Unix environment */
295 for (e = env; *e; e++)
297 if (is_special_env_var( *e )) continue;
298 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
300 size *= sizeof(WCHAR);
302 /* Now allocate the environment */
303 ptr = NULL;
304 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
305 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
306 return FALSE;
308 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
309 endptr = p + size / sizeof(WCHAR);
311 /* And fill it with the Unix environment */
312 for (e = env; *e; e++)
314 char *str = *e;
316 /* skip Unix special variables and use the Wine variants instead */
317 if (!strncmp( str, "WINE", 4 ))
319 if (is_special_env_var( str + 4 )) str += 4;
320 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
322 else if (is_special_env_var( str )) continue; /* skip it */
324 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
325 p += strlenW(p) + 1;
327 *p = 0;
328 return TRUE;
332 /***********************************************************************
333 * set_registry_variables
335 * Set environment variables by enumerating the values of a key;
336 * helper for set_registry_environment().
337 * Note that Windows happily truncates the value if it's too big.
339 static void set_registry_variables( HANDLE hkey, ULONG type )
341 static const WCHAR pathW[] = {'P','A','T','H'};
342 static const WCHAR sep[] = {';',0};
343 UNICODE_STRING env_name, env_value;
344 NTSTATUS status;
345 DWORD size;
346 int index;
347 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
348 WCHAR tmpbuf[1024];
349 UNICODE_STRING tmp;
350 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
352 tmp.Buffer = tmpbuf;
353 tmp.MaximumLength = sizeof(tmpbuf);
355 for (index = 0; ; index++)
357 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
358 buffer, sizeof(buffer), &size );
359 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
360 break;
361 if (info->Type != type)
362 continue;
363 env_name.Buffer = info->Name;
364 env_name.Length = env_name.MaximumLength = info->NameLength;
365 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
366 env_value.Length = info->DataLength;
367 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
368 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
369 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
370 if (!env_value.Length) continue;
371 if (info->Type == REG_EXPAND_SZ)
373 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
374 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
375 RtlCopyUnicodeString( &env_value, &tmp );
377 /* PATH is magic */
378 if (env_name.Length == sizeof(pathW) &&
379 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
380 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
382 RtlAppendUnicodeToString( &tmp, sep );
383 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
384 RtlCopyUnicodeString( &env_value, &tmp );
386 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
391 /***********************************************************************
392 * set_registry_environment
394 * Set the environment variables specified in the registry.
396 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
397 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
398 * on the order in which the variables are processed. But on Windows it
399 * does not really matter since they only use %SystemDrive% and
400 * %SystemRoot% which are predefined. But Wine defines these in the
401 * registry, so we need two passes.
403 static BOOL set_registry_environment( BOOL volatile_only )
405 static const WCHAR env_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
406 'M','a','c','h','i','n','e','\\',
407 'S','y','s','t','e','m','\\',
408 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
409 'C','o','n','t','r','o','l','\\',
410 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
411 'E','n','v','i','r','o','n','m','e','n','t',0};
412 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
413 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};
415 OBJECT_ATTRIBUTES attr;
416 UNICODE_STRING nameW;
417 HANDLE hkey;
418 BOOL ret = FALSE;
420 attr.Length = sizeof(attr);
421 attr.RootDirectory = 0;
422 attr.ObjectName = &nameW;
423 attr.Attributes = 0;
424 attr.SecurityDescriptor = NULL;
425 attr.SecurityQualityOfService = NULL;
427 /* first the system environment variables */
428 RtlInitUnicodeString( &nameW, env_keyW );
429 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
431 set_registry_variables( hkey, REG_SZ );
432 set_registry_variables( hkey, REG_EXPAND_SZ );
433 NtClose( hkey );
434 ret = TRUE;
437 /* then the ones for the current user */
438 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
439 RtlInitUnicodeString( &nameW, envW );
440 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
442 set_registry_variables( hkey, REG_SZ );
443 set_registry_variables( hkey, REG_EXPAND_SZ );
444 NtClose( hkey );
447 RtlInitUnicodeString( &nameW, volatile_envW );
448 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
450 set_registry_variables( hkey, REG_SZ );
451 set_registry_variables( hkey, REG_EXPAND_SZ );
452 NtClose( hkey );
455 NtClose( attr.RootDirectory );
456 return ret;
460 /***********************************************************************
461 * get_reg_value
463 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
465 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
466 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
467 DWORD len, size = sizeof(buffer);
468 WCHAR *ret = NULL;
469 UNICODE_STRING nameW;
471 RtlInitUnicodeString( &nameW, name );
472 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
473 return NULL;
475 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
476 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
478 if (info->Type == REG_EXPAND_SZ)
480 UNICODE_STRING value, expanded;
482 value.MaximumLength = len * sizeof(WCHAR);
483 value.Buffer = (WCHAR *)info->Data;
484 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
485 value.Length = len * sizeof(WCHAR);
486 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
487 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
488 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
489 else RtlFreeUnicodeString( &expanded );
491 else if (info->Type == REG_SZ)
493 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
495 memcpy( ret, info->Data, len * sizeof(WCHAR) );
496 ret[len] = 0;
499 return ret;
503 /***********************************************************************
504 * set_additional_environment
506 * Set some additional environment variables not specified in the registry.
508 static void set_additional_environment(void)
510 static const WCHAR profile_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
511 'M','a','c','h','i','n','e','\\',
512 'S','o','f','t','w','a','r','e','\\',
513 'M','i','c','r','o','s','o','f','t','\\',
514 'W','i','n','d','o','w','s',' ','N','T','\\',
515 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
516 'P','r','o','f','i','l','e','L','i','s','t',0};
517 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
518 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
519 static const WCHAR computernameW[] = {'C','O','M','P','U','T','E','R','N','A','M','E',0};
520 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
521 static const WCHAR programdataW[] = {'P','r','o','g','r','a','m','D','a','t','a',0};
522 OBJECT_ATTRIBUTES attr;
523 UNICODE_STRING nameW;
524 WCHAR *profile_dir = NULL, *all_users_dir = NULL, *program_data_dir = NULL;
525 WCHAR buf[MAX_COMPUTERNAME_LENGTH+1];
526 HANDLE hkey;
527 DWORD len;
529 /* ComputerName */
530 len = sizeof(buf) / sizeof(WCHAR);
531 if (GetComputerNameW( buf, &len ))
532 SetEnvironmentVariableW( computernameW, buf );
534 /* set the ALLUSERSPROFILE variables */
536 attr.Length = sizeof(attr);
537 attr.RootDirectory = 0;
538 attr.ObjectName = &nameW;
539 attr.Attributes = 0;
540 attr.SecurityDescriptor = NULL;
541 attr.SecurityQualityOfService = NULL;
542 RtlInitUnicodeString( &nameW, profile_keyW );
543 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
545 profile_dir = get_reg_value( hkey, profiles_valueW );
546 all_users_dir = get_reg_value( hkey, all_users_valueW );
547 program_data_dir = get_reg_value( hkey, programdataW );
548 NtClose( hkey );
551 if (profile_dir && all_users_dir)
553 WCHAR *value, *p;
555 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
556 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
557 strcpyW( value, profile_dir );
558 p = value + strlenW(value);
559 if (p > value && p[-1] != '\\') *p++ = '\\';
560 strcpyW( p, all_users_dir );
561 SetEnvironmentVariableW( allusersW, value );
562 HeapFree( GetProcessHeap(), 0, value );
565 if (program_data_dir)
567 SetEnvironmentVariableW( programdataW, program_data_dir );
570 HeapFree( GetProcessHeap(), 0, all_users_dir );
571 HeapFree( GetProcessHeap(), 0, profile_dir );
572 HeapFree( GetProcessHeap(), 0, program_data_dir );
575 /***********************************************************************
576 * set_wow64_environment
578 * Set the environment variables that change across 32/64/Wow64.
580 static void set_wow64_environment(void)
582 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};
583 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};
584 static const WCHAR x86W[] = {'x','8','6',0};
585 static const WCHAR versionW[] = {'\\','R','e','g','i','s','t','r','y','\\',
586 'M','a','c','h','i','n','e','\\',
587 'S','o','f','t','w','a','r','e','\\',
588 'M','i','c','r','o','s','o','f','t','\\',
589 'W','i','n','d','o','w','s','\\',
590 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
591 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
592 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
593 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
594 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
595 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
596 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
597 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
598 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
600 OBJECT_ATTRIBUTES attr;
601 UNICODE_STRING nameW;
602 WCHAR arch[64];
603 WCHAR *value;
604 HANDLE hkey;
606 /* set the PROCESSOR_ARCHITECTURE variable */
608 if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
610 if (is_win64)
612 SetEnvironmentVariableW( archW, arch );
613 SetEnvironmentVariableW( arch6432W, NULL );
616 else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
618 if (is_wow64)
620 SetEnvironmentVariableW( arch6432W, arch );
621 SetEnvironmentVariableW( archW, x86W );
625 attr.Length = sizeof(attr);
626 attr.RootDirectory = 0;
627 attr.ObjectName = &nameW;
628 attr.Attributes = 0;
629 attr.SecurityDescriptor = NULL;
630 attr.SecurityQualityOfService = NULL;
631 RtlInitUnicodeString( &nameW, versionW );
632 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
634 /* set the ProgramFiles variables */
636 if ((value = get_reg_value( hkey, progdirW )))
638 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
639 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
640 HeapFree( GetProcessHeap(), 0, value );
642 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
644 SetEnvironmentVariableW( progfilesW, value );
645 HeapFree( GetProcessHeap(), 0, value );
648 /* set the CommonProgramFiles variables */
650 if ((value = get_reg_value( hkey, commondirW )))
652 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
653 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
654 HeapFree( GetProcessHeap(), 0, value );
656 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
658 SetEnvironmentVariableW( commonfilesW, value );
659 HeapFree( GetProcessHeap(), 0, value );
662 NtClose( hkey );
665 /***********************************************************************
666 * set_library_wargv
668 * Set the Wine library Unicode argv global variables.
670 static void set_library_wargv( char **argv )
672 int argc;
673 char *q;
674 WCHAR *p;
675 WCHAR **wargv;
676 DWORD total = 0;
678 for (argc = 0; argv[argc]; argc++)
679 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
681 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
682 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
683 p = (WCHAR *)(wargv + argc + 1);
684 for (argc = 0; argv[argc]; argc++)
686 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
687 wargv[argc] = p;
688 p += reslen;
689 total -= reslen;
691 wargv[argc] = NULL;
693 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
695 for (argc = 0; wargv[argc]; argc++)
696 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
698 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
699 q = (char *)(argv + argc + 1);
700 for (argc = 0; wargv[argc]; argc++)
702 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
703 argv[argc] = q;
704 q += reslen;
705 total -= reslen;
707 argv[argc] = NULL;
709 __wine_main_argc = argc;
710 __wine_main_argv = argv;
711 __wine_main_wargv = wargv;
715 /***********************************************************************
716 * update_library_argv0
718 * Update the argv[0] global variable with the binary we have found.
720 static void update_library_argv0( const WCHAR *argv0 )
722 DWORD len = strlenW( argv0 );
724 if (len > strlenW( __wine_main_wargv[0] ))
726 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
728 strcpyW( __wine_main_wargv[0], argv0 );
730 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
731 if (len > strlen( __wine_main_argv[0] ) + 1)
733 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
735 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
739 /***********************************************************************
740 * build_command_line
742 * Build the command line of a process from the argv array.
744 * Note that it does NOT necessarily include the file name.
745 * Sometimes we don't even have any command line options at all.
747 * We must quote and escape characters so that the argv array can be rebuilt
748 * from the command line:
749 * - spaces and tabs must be quoted
750 * 'a b' -> '"a b"'
751 * - quotes must be escaped
752 * '"' -> '\"'
753 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
754 * resulting in an odd number of '\' followed by a '"'
755 * '\"' -> '\\\"'
756 * '\\"' -> '\\\\\"'
757 * - '\'s are followed by the closing '"' must be doubled,
758 * resulting in an even number of '\' followed by a '"'
759 * ' \' -> '" \\"'
760 * ' \\' -> '" \\\\"'
761 * - '\'s that are not followed by a '"' can be left as is
762 * 'a\b' == 'a\b'
763 * 'a\\b' == 'a\\b'
765 static BOOL build_command_line( WCHAR **argv )
767 int len;
768 WCHAR **arg;
769 LPWSTR p;
770 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
772 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
774 len = 0;
775 for (arg = argv; *arg; arg++)
777 BOOL has_space;
778 int bcount;
779 WCHAR* a;
781 has_space=FALSE;
782 bcount=0;
783 a=*arg;
784 if( !*a ) has_space=TRUE;
785 while (*a!='\0') {
786 if (*a=='\\') {
787 bcount++;
788 } else {
789 if (*a==' ' || *a=='\t') {
790 has_space=TRUE;
791 } else if (*a=='"') {
792 /* doubling of '\' preceding a '"',
793 * plus escaping of said '"'
795 len+=2*bcount+1;
797 bcount=0;
799 a++;
801 len+=(a-*arg)+1 /* for the separating space */;
802 if (has_space)
803 len+=2+bcount; /* for the quotes and doubling of '\' preceding the closing quote */
806 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
807 return FALSE;
809 p = rupp->CommandLine.Buffer;
810 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
811 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
812 for (arg = argv; *arg; arg++)
814 BOOL has_space,has_quote;
815 WCHAR* a;
816 int bcount;
818 /* Check for quotes and spaces in this argument */
819 has_space=has_quote=FALSE;
820 a=*arg;
821 if( !*a ) has_space=TRUE;
822 while (*a!='\0') {
823 if (*a==' ' || *a=='\t') {
824 has_space=TRUE;
825 if (has_quote)
826 break;
827 } else if (*a=='"') {
828 has_quote=TRUE;
829 if (has_space)
830 break;
832 a++;
835 /* Now transfer it to the command line */
836 if (has_space)
837 *p++='"';
838 if (has_quote || has_space) {
839 bcount=0;
840 a=*arg;
841 while (*a!='\0') {
842 if (*a=='\\') {
843 *p++=*a;
844 bcount++;
845 } else {
846 if (*a=='"') {
847 int i;
849 /* Double all the '\\' preceding this '"', plus one */
850 for (i=0;i<=bcount;i++)
851 *p++='\\';
852 *p++='"';
853 } else {
854 *p++=*a;
856 bcount=0;
858 a++;
860 } else {
861 WCHAR* x = *arg;
862 while ((*p=*x++)) p++;
864 if (has_space) {
865 int i;
867 /* Double all the '\' preceding the closing quote */
868 for (i=0;i<bcount;i++)
869 *p++='\\';
870 *p++='"';
872 *p++=' ';
874 if (p > rupp->CommandLine.Buffer)
875 p--; /* remove last space */
876 *p = '\0';
878 return TRUE;
882 /***********************************************************************
883 * init_current_directory
885 * Initialize the current directory from the Unix cwd or the parent info.
887 static void init_current_directory( CURDIR *cur_dir )
889 UNICODE_STRING dir_str;
890 const char *pwd;
891 char *cwd;
892 int size;
894 /* if we received a cur dir from the parent, try this first */
896 if (cur_dir->DosPath.Length)
898 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
901 /* now try to get it from the Unix cwd */
903 for (size = 256; ; size *= 2)
905 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
906 if (getcwd( cwd, size )) break;
907 HeapFree( GetProcessHeap(), 0, cwd );
908 if (errno == ERANGE) continue;
909 cwd = NULL;
910 break;
913 /* try to use PWD if it is valid, so that we don't resolve symlinks */
915 pwd = getenv( "PWD" );
916 if (cwd)
918 struct stat st1, st2;
920 if (!pwd || stat( pwd, &st1 ) == -1 ||
921 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
922 pwd = cwd;
925 if (pwd)
927 ANSI_STRING unix_name;
928 UNICODE_STRING nt_name;
929 RtlInitAnsiString( &unix_name, pwd );
930 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
932 UNICODE_STRING dos_path;
933 /* skip the \??\ prefix, nt_name is 0 terminated */
934 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
935 RtlSetCurrentDirectory_U( &dos_path );
936 RtlFreeUnicodeString( &nt_name );
940 if (!cur_dir->DosPath.Length) /* still not initialized */
942 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
943 "starting in the Windows directory.\n", cwd ? cwd : "" );
944 RtlInitUnicodeString( &dir_str, DIR_Windows );
945 RtlSetCurrentDirectory_U( &dir_str );
947 HeapFree( GetProcessHeap(), 0, cwd );
949 done:
950 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
954 /***********************************************************************
955 * init_windows_dirs
957 * Initialize the windows and system directories from the environment.
959 static void init_windows_dirs(void)
961 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
963 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
964 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
965 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
966 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
967 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
969 DWORD len;
970 WCHAR *buffer;
972 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
974 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
975 GetEnvironmentVariableW( windirW, buffer, len );
976 DIR_Windows = buffer;
978 else DIR_Windows = default_windirW;
980 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
982 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
983 GetEnvironmentVariableW( winsysdirW, buffer, len );
984 DIR_System = buffer;
986 else
988 len = strlenW( DIR_Windows );
989 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
990 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
991 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
992 DIR_System = buffer;
995 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
996 ERR( "directory %s could not be created, error %u\n",
997 debugstr_w(DIR_Windows), GetLastError() );
998 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
999 ERR( "directory %s could not be created, error %u\n",
1000 debugstr_w(DIR_System), GetLastError() );
1002 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
1004 len = strlenW( DIR_Windows );
1005 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
1006 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
1007 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
1008 DIR_SysWow64 = buffer;
1009 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
1010 ERR( "directory %s could not be created, error %u\n",
1011 debugstr_w(DIR_SysWow64), GetLastError() );
1014 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
1015 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
1017 /* set the directories in ntdll too */
1018 __wine_init_windows_dir( DIR_Windows, DIR_System );
1022 /***********************************************************************
1023 * start_wineboot
1025 * Start the wineboot process if necessary. Return the handles to wait on.
1027 static void start_wineboot( HANDLE handles[2] )
1029 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
1031 handles[1] = 0;
1032 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
1034 ERR( "failed to create wineboot event, expect trouble\n" );
1035 return;
1037 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
1039 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1040 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1041 STARTUPINFOW si;
1042 PROCESS_INFORMATION pi;
1043 void *redir;
1044 WCHAR app[MAX_PATH];
1045 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1047 memset( &si, 0, sizeof(si) );
1048 si.cb = sizeof(si);
1049 si.dwFlags = STARTF_USESTDHANDLES;
1050 si.hStdInput = 0;
1051 si.hStdOutput = 0;
1052 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1054 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1055 lstrcatW( app, wineboot );
1057 Wow64DisableWow64FsRedirection( &redir );
1058 strcpyW( cmdline, app );
1059 strcatW( cmdline, args );
1060 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1062 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1063 CloseHandle( pi.hThread );
1064 handles[1] = pi.hProcess;
1066 else
1068 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1069 CloseHandle( handles[0] );
1070 handles[0] = 0;
1072 Wow64RevertWow64FsRedirection( redir );
1077 #ifdef __i386__
1078 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1079 __ASM_GLOBAL_FUNC( call_process_entry,
1080 "pushl %ebp\n\t"
1081 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1082 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1083 "movl %esp,%ebp\n\t"
1084 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1085 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1086 "pushl 8(%ebp)\n\t"
1087 "call *12(%ebp)\n\t"
1088 "leave\n\t"
1089 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1090 __ASM_CFI(".cfi_same_value %ebp\n\t")
1091 "ret" )
1093 extern void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb ) DECLSPEC_HIDDEN;
1094 extern void WINAPI start_process_wrapper(void) DECLSPEC_HIDDEN;
1095 __ASM_GLOBAL_FUNC( start_process_wrapper,
1096 "pushl %ebp\n\t"
1097 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1098 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1099 "movl %esp,%ebp\n\t"
1100 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1101 "pushl %ebx\n\t" /* arg */
1102 "pushl %eax\n\t" /* entry */
1103 "call " __ASM_NAME("start_process") )
1104 #else
1105 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1107 return entry( peb );
1109 static void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb );
1110 #define start_process_wrapper start_process
1111 #endif
1113 /***********************************************************************
1114 * start_process
1116 * Startup routine of a new process. Runs on the new process stack.
1118 void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb )
1120 BOOL being_debugged;
1122 if (!entry)
1124 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1125 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1126 ExitThread( 1 );
1129 TRACE_(relay)( "\1Starting process %s (entryproc=%p)\n",
1130 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1132 __TRY
1134 if (!CheckRemoteDebuggerPresent( GetCurrentProcess(), &being_debugged ))
1135 being_debugged = FALSE;
1137 SetLastError( 0 ); /* clear error code */
1138 if (being_debugged) DbgBreakPoint();
1139 ExitThread( call_process_entry( peb, entry ));
1141 __EXCEPT(UnhandledExceptionFilter)
1143 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1145 __ENDTRY
1146 abort(); /* should not be reached */
1150 /***********************************************************************
1151 * set_process_name
1153 * Change the process name in the ps output.
1155 static void set_process_name( int argc, char *argv[] )
1157 BOOL shift_strings;
1158 char *p, *name;
1159 int i;
1161 #ifdef HAVE_SETPROCTITLE
1162 setproctitle("-%s", argv[1]);
1163 shift_strings = FALSE;
1164 #else
1165 p = argv[0];
1167 shift_strings = (argc >= 2);
1168 for (i = 1; i < argc; i++)
1170 p += strlen(p) + 1;
1171 if (p != argv[i])
1173 shift_strings = FALSE;
1174 break;
1177 #endif
1179 if (shift_strings)
1181 int offset = argv[1] - argv[0];
1182 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1183 memmove( argv[0], argv[1], end - argv[1] );
1184 memset( end - offset, 0, offset );
1185 for (i = 1; i < argc; i++)
1186 argv[i-1] = argv[i] - offset;
1187 argv[i-1] = NULL;
1189 else
1191 /* remove argv[0] */
1192 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1195 name = argv[0];
1196 if ((p = strrchr( name, '\\' ))) name = p + 1;
1197 if ((p = strrchr( name, '/' ))) name = p + 1;
1199 #if defined(HAVE_SETPROGNAME)
1200 setprogname( name );
1201 #endif
1203 #ifdef HAVE_PRCTL
1204 #ifndef PR_SET_NAME
1205 # define PR_SET_NAME 15
1206 #endif
1207 prctl( PR_SET_NAME, name );
1208 #endif /* HAVE_PRCTL */
1212 /***********************************************************************
1213 * __wine_kernel_init
1215 * Wine initialisation: load and start the main exe file.
1217 void CDECL __wine_kernel_init(void)
1219 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1220 static const WCHAR dotW[] = {'.',0};
1222 WCHAR *p, main_exe_name[MAX_PATH+1];
1223 PEB *peb = NtCurrentTeb()->Peb;
1224 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1225 HANDLE boot_events[2];
1226 BOOL got_environment = TRUE;
1228 /* Initialize everything */
1230 setbuf(stdout,NULL);
1231 setbuf(stderr,NULL);
1232 kernel32_handle = GetModuleHandleW(kernel32W);
1233 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1235 LOCALE_Init();
1237 if (!params->Environment)
1239 /* Copy the parent environment */
1240 if (!build_initial_environment()) exit(1);
1242 /* convert old configuration to new format */
1243 convert_old_config();
1245 got_environment = set_registry_environment( FALSE );
1246 set_additional_environment();
1249 init_windows_dirs();
1250 init_current_directory( &params->CurrentDirectory );
1252 set_process_name( __wine_main_argc, __wine_main_argv );
1253 set_library_wargv( __wine_main_argv );
1254 boot_events[0] = boot_events[1] = 0;
1256 if (peb->ProcessParameters->ImagePathName.Buffer)
1258 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1260 else
1262 struct binary_info binary_info;
1264 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1265 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1267 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1268 ExitProcess( GetLastError() );
1270 update_library_argv0( main_exe_name );
1271 if (!build_command_line( __wine_main_wargv )) goto error;
1272 start_wineboot( boot_events );
1275 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1276 p = strrchrW( main_exe_name, '.' );
1277 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1279 TRACE( "starting process name=%s argv[0]=%s\n",
1280 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1282 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1283 MODULE_get_dll_load_path( main_exe_name, -1 ));
1285 if (boot_events[0])
1287 DWORD timeout = 2 * 60 * 1000, count = 1;
1289 if (boot_events[1]) count++;
1290 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1291 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1292 ERR( "boot event wait timed out\n" );
1293 CloseHandle( boot_events[0] );
1294 if (boot_events[1]) CloseHandle( boot_events[1] );
1295 /* reload environment now that wineboot has run */
1296 set_registry_environment( got_environment );
1297 set_additional_environment();
1299 set_wow64_environment();
1301 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1303 DWORD_PTR args[1];
1304 WCHAR msgW[1024];
1305 char msg[1024];
1306 DWORD error = GetLastError();
1308 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1309 if (error == ERROR_BAD_EXE_FORMAT ||
1310 error == ERROR_INVALID_ADDRESS ||
1311 error == ERROR_NOT_ENOUGH_MEMORY)
1313 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1314 /* if we get back here, it failed */
1316 else if (error == ERROR_MOD_NOT_FOUND)
1318 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1319 else p = main_exe_name;
1320 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1322 /* args 1 and 2 are --app-name full_path */
1323 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1324 debugstr_w(__wine_main_wargv[3]) );
1325 ExitProcess( ERROR_BAD_EXE_FORMAT );
1327 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1328 ExitProcess( ERROR_FILE_NOT_FOUND );
1330 args[0] = (DWORD_PTR)main_exe_name;
1331 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1332 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1333 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1334 MESSAGE( "wine: %s", msg );
1335 ExitProcess( error );
1338 if (!params->CurrentDirectory.Handle) chdir("/"); /* avoid locking removable devices */
1340 LdrInitializeThunk( start_process_wrapper, 0, 0, 0 );
1342 error:
1343 ExitProcess( GetLastError() );
1347 /***********************************************************************
1348 * build_argv
1350 * Build an argv array from a command-line.
1351 * 'reserved' is the number of args to reserve before the first one.
1353 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1355 int argc;
1356 char** argv;
1357 char *arg,*s,*d,*cmdline;
1358 int in_quotes,bcount,len;
1360 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1361 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1362 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1364 argc=reserved+1;
1365 bcount=0;
1366 in_quotes=0;
1367 s=cmdline;
1368 while (1) {
1369 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1370 /* space */
1371 argc++;
1372 /* skip the remaining spaces */
1373 while (*s==' ' || *s=='\t') {
1374 s++;
1376 if (*s=='\0')
1377 break;
1378 bcount=0;
1379 continue;
1380 } else if (*s=='\\') {
1381 /* '\', count them */
1382 bcount++;
1383 } else if ((*s=='"') && ((bcount & 1)==0)) {
1384 /* unescaped '"' */
1385 in_quotes=!in_quotes;
1386 bcount=0;
1387 } else {
1388 /* a regular character */
1389 bcount=0;
1391 s++;
1393 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1395 HeapFree( GetProcessHeap(), 0, cmdline );
1396 return NULL;
1399 arg = d = s = (char *)(argv + argc);
1400 memcpy( d, cmdline, len );
1401 bcount=0;
1402 in_quotes=0;
1403 argc=reserved;
1404 while (*s) {
1405 if ((*s==' ' || *s=='\t') && !in_quotes) {
1406 /* Close the argument and copy it */
1407 *d=0;
1408 argv[argc++]=arg;
1410 /* skip the remaining spaces */
1411 do {
1412 s++;
1413 } while (*s==' ' || *s=='\t');
1415 /* Start with a new argument */
1416 arg=d=s;
1417 bcount=0;
1418 } else if (*s=='\\') {
1419 /* '\\' */
1420 *d++=*s++;
1421 bcount++;
1422 } else if (*s=='"') {
1423 /* '"' */
1424 if ((bcount & 1)==0) {
1425 /* Preceded by an even number of '\', this is half that
1426 * number of '\', plus a '"' which we discard.
1428 d-=bcount/2;
1429 s++;
1430 in_quotes=!in_quotes;
1431 } else {
1432 /* Preceded by an odd number of '\', this is half that
1433 * number of '\' followed by a '"'
1435 d=d-bcount/2-1;
1436 *d++='"';
1437 s++;
1439 bcount=0;
1440 } else {
1441 /* a regular character */
1442 *d++=*s++;
1443 bcount=0;
1446 if (*arg) {
1447 *d='\0';
1448 argv[argc++]=arg;
1450 argv[argc]=NULL;
1452 HeapFree( GetProcessHeap(), 0, cmdline );
1453 return argv;
1457 /***********************************************************************
1458 * build_envp
1460 * Build the environment of a new child process.
1462 static char **build_envp( const WCHAR *envW )
1464 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1466 const WCHAR *end;
1467 char **envp;
1468 char *env, *p;
1469 int count = 1, length;
1470 unsigned int i;
1472 for (end = envW; *end; count++) end += strlenW(end) + 1;
1473 end++;
1474 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1475 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1476 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1478 for (p = env; *p; p += strlen(p) + 1)
1479 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1481 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1483 if (!(p = getenv(unix_vars[i]))) continue;
1484 length += strlen(unix_vars[i]) + strlen(p) + 2;
1485 count++;
1488 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1490 char **envptr = envp;
1491 char *dst = (char *)(envp + count);
1493 /* some variables must not be modified, so we get them directly from the unix env */
1494 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1496 if (!(p = getenv(unix_vars[i]))) continue;
1497 *envptr++ = strcpy( dst, unix_vars[i] );
1498 strcat( dst, "=" );
1499 strcat( dst, p );
1500 dst += strlen(dst) + 1;
1503 /* now put the Windows environment strings */
1504 for (p = env; *p; p += strlen(p) + 1)
1506 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1507 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1508 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1509 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1510 if (is_special_env_var( p )) /* prefix it with "WINE" */
1512 *envptr++ = strcpy( dst, "WINE" );
1513 strcat( dst, p );
1515 else
1517 *envptr++ = strcpy( dst, p );
1519 dst += strlen(dst) + 1;
1521 *envptr = 0;
1523 HeapFree( GetProcessHeap(), 0, env );
1524 return envp;
1528 /***********************************************************************
1529 * fork_and_exec
1531 * Fork and exec a new Unix binary, checking for errors.
1533 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1534 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1536 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1537 int pid, err;
1538 char **argv, **envp;
1540 if (!env) env = GetEnvironmentStringsW();
1542 #ifdef HAVE_PIPE2
1543 if (pipe2( fd, O_CLOEXEC ) == -1)
1544 #endif
1546 if (pipe(fd) == -1)
1548 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1549 return -1;
1551 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1552 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1555 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1557 HANDLE hstdin, hstdout, hstderr;
1559 if (startup->dwFlags & STARTF_USESTDHANDLES)
1561 hstdin = startup->hStdInput;
1562 hstdout = startup->hStdOutput;
1563 hstderr = startup->hStdError;
1565 else
1567 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1568 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1569 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1572 if (is_console_handle( hstdin ))
1573 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1574 if (is_console_handle( hstdout ))
1575 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1576 if (is_console_handle( hstderr ))
1577 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1578 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1579 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1580 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1583 argv = build_argv( cmdline, 0 );
1584 envp = build_envp( env );
1586 if (!(pid = fork())) /* child */
1588 if (!(pid = fork())) /* grandchild */
1590 close( fd[0] );
1592 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1594 int nullfd = open( "/dev/null", O_RDWR );
1595 setsid();
1596 /* close stdin and stdout */
1597 if (nullfd != -1)
1599 dup2( nullfd, 0 );
1600 dup2( nullfd, 1 );
1601 close( nullfd );
1604 else
1606 if (stdin_fd != -1)
1608 dup2( stdin_fd, 0 );
1609 close( stdin_fd );
1611 if (stdout_fd != -1)
1613 dup2( stdout_fd, 1 );
1614 close( stdout_fd );
1616 if (stderr_fd != -1)
1618 dup2( stderr_fd, 2 );
1619 close( stderr_fd );
1623 /* Reset signals that we previously set to SIG_IGN */
1624 signal( SIGPIPE, SIG_DFL );
1626 if (newdir) chdir(newdir);
1628 if (argv && envp) execve( filename, argv, envp );
1631 if (pid <= 0) /* grandchild if exec failed or child if fork failed */
1633 err = errno;
1634 write( fd[1], &err, sizeof(err) );
1635 _exit(1);
1638 _exit(0); /* child if fork succeeded */
1640 HeapFree( GetProcessHeap(), 0, argv );
1641 HeapFree( GetProcessHeap(), 0, envp );
1642 if (stdin_fd != -1) close( stdin_fd );
1643 if (stdout_fd != -1) close( stdout_fd );
1644 if (stderr_fd != -1) close( stderr_fd );
1645 close( fd[1] );
1646 if (pid != -1)
1648 /* reap child */
1649 do {
1650 err = waitpid(pid, NULL, 0);
1651 } while (err < 0 && errno == EINTR);
1653 if (read( fd[0], &err, sizeof(err) ) > 0) /* exec or second fork failed */
1655 errno = err;
1656 pid = -1;
1659 if (pid == -1) FILE_SetDosError();
1660 close( fd[0] );
1661 return pid;
1665 static inline DWORD append_string( void **ptr, const WCHAR *str )
1667 DWORD len = strlenW( str );
1668 memcpy( *ptr, str, len * sizeof(WCHAR) );
1669 *ptr = (WCHAR *)*ptr + len;
1670 return len * sizeof(WCHAR);
1673 /***********************************************************************
1674 * create_startup_info
1676 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1677 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1678 const STARTUPINFOW *startup, DWORD *info_size )
1680 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1681 const WCHAR *title;
1682 startup_info_t *info;
1683 DWORD size;
1684 void *ptr;
1685 UNICODE_STRING newdir;
1686 WCHAR imagepath[MAX_PATH];
1687 HANDLE hstdin, hstdout, hstderr;
1689 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1690 lstrcpynW( imagepath, filename, MAX_PATH );
1691 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1692 lstrcpynW( imagepath, filename, MAX_PATH );
1694 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1696 newdir.Buffer = NULL;
1697 if (cur_dir)
1699 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1700 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1701 else
1702 cur_dir = NULL;
1704 if (!cur_dir)
1706 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1707 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1708 else
1709 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1711 title = startup->lpTitle ? startup->lpTitle : imagepath;
1713 size = sizeof(*info);
1714 size += strlenW( cur_dir ) * sizeof(WCHAR);
1715 size += cur_params->DllPath.Length;
1716 size += strlenW( imagepath ) * sizeof(WCHAR);
1717 size += strlenW( cmdline ) * sizeof(WCHAR);
1718 size += strlenW( title ) * sizeof(WCHAR);
1719 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1720 /* FIXME: shellinfo */
1721 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1722 size = (size + 1) & ~1;
1723 *info_size = size;
1725 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1727 info->console_flags = cur_params->ConsoleFlags;
1728 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1729 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1731 if (startup->dwFlags & STARTF_USESTDHANDLES)
1733 hstdin = startup->hStdInput;
1734 hstdout = startup->hStdOutput;
1735 hstderr = startup->hStdError;
1737 else if (flags & DETACHED_PROCESS)
1739 hstdin = INVALID_HANDLE_VALUE;
1740 hstdout = INVALID_HANDLE_VALUE;
1741 hstderr = INVALID_HANDLE_VALUE;
1743 else
1745 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1746 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1747 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1749 info->hstdin = wine_server_obj_handle( hstdin );
1750 info->hstdout = wine_server_obj_handle( hstdout );
1751 info->hstderr = wine_server_obj_handle( hstderr );
1752 if ((flags & CREATE_NEW_CONSOLE) != 0)
1754 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1755 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1756 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1757 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1759 else
1761 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1762 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1763 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1766 info->x = startup->dwX;
1767 info->y = startup->dwY;
1768 info->xsize = startup->dwXSize;
1769 info->ysize = startup->dwYSize;
1770 info->xchars = startup->dwXCountChars;
1771 info->ychars = startup->dwYCountChars;
1772 info->attribute = startup->dwFillAttribute;
1773 info->flags = startup->dwFlags;
1774 info->show = startup->wShowWindow;
1776 ptr = info + 1;
1777 info->curdir_len = append_string( &ptr, cur_dir );
1778 info->dllpath_len = cur_params->DllPath.Length;
1779 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1780 ptr = (char *)ptr + cur_params->DllPath.Length;
1781 info->imagepath_len = append_string( &ptr, imagepath );
1782 info->cmdline_len = append_string( &ptr, cmdline );
1783 info->title_len = append_string( &ptr, title );
1784 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1785 if (startup->lpReserved2 && startup->cbReserved2)
1787 info->runtime_len = startup->cbReserved2;
1788 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1791 done:
1792 RtlFreeUnicodeString( &newdir );
1793 return info;
1796 /***********************************************************************
1797 * get_alternate_loader
1799 * Get the name of the alternate (32 or 64 bit) Wine loader.
1801 static const char *get_alternate_loader( char **ret_env )
1803 char *env;
1804 const char *loader = NULL;
1805 const char *loader_env = getenv( "WINELOADER" );
1807 *ret_env = NULL;
1809 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1811 if (loader_env)
1813 int len = strlen( loader_env );
1814 if (!is_win64)
1816 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1817 strcpy( env, "WINELOADER=" );
1818 strcat( env, loader_env );
1819 strcat( env, "64" );
1821 else
1823 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1824 strcpy( env, "WINELOADER=" );
1825 strcat( env, loader_env );
1826 len += sizeof("WINELOADER=") - 1;
1827 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1829 if (!loader)
1831 if ((loader = strrchr( env, '/' ))) loader++;
1832 else loader = env;
1834 *ret_env = env;
1836 if (!loader) loader = is_win64 ? "wine" : "wine64";
1837 return loader;
1840 #ifdef __APPLE__
1841 /***********************************************************************
1842 * terminate_main_thread
1844 * On some versions of Mac OS X, the execve system call fails with
1845 * ENOTSUP if the process has multiple threads. Wine is always multi-
1846 * threaded on Mac OS X because it specifically reserves the main thread
1847 * for use by the system frameworks (see apple_main_thread() in
1848 * libs/wine/loader.c). So, when we need to exec without first forking,
1849 * we need to terminate the main thread first. We do this by installing
1850 * a custom run loop source onto the main run loop and signaling it.
1851 * The source's "perform" callback is pthread_exit and it will be
1852 * executed on the main thread, terminating it.
1854 * Returns TRUE if there's still hope the main thread has terminated or
1855 * will soon. Return FALSE if we've given up.
1857 static BOOL terminate_main_thread(void)
1859 static int delayms;
1861 if (!delayms)
1863 CFRunLoopSourceContext source_context = { 0 };
1864 CFRunLoopSourceRef source;
1866 source_context.perform = pthread_exit;
1867 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1868 return FALSE;
1870 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1871 CFRunLoopSourceSignal( source );
1872 CFRunLoopWakeUp( CFRunLoopGetMain() );
1873 CFRelease( source );
1875 delayms = 20;
1878 if (delayms > 1000)
1879 return FALSE;
1881 usleep(delayms * 1000);
1882 delayms *= 2;
1884 return TRUE;
1886 #endif
1888 /***********************************************************************
1889 * get_process_cpu
1891 static int get_process_cpu( const WCHAR *filename, const struct binary_info *binary_info )
1893 switch (binary_info->arch)
1895 case IMAGE_FILE_MACHINE_I386: return CPU_x86;
1896 case IMAGE_FILE_MACHINE_AMD64: return CPU_x86_64;
1897 case IMAGE_FILE_MACHINE_POWERPC: return CPU_POWERPC;
1898 case IMAGE_FILE_MACHINE_ARM:
1899 case IMAGE_FILE_MACHINE_THUMB:
1900 case IMAGE_FILE_MACHINE_ARMNT: return CPU_ARM;
1901 case IMAGE_FILE_MACHINE_ARM64: return CPU_ARM64;
1903 ERR( "%s uses unsupported architecture (%04x)\n", debugstr_w(filename), binary_info->arch );
1904 return -1;
1907 /***********************************************************************
1908 * exec_loader
1910 static pid_t exec_loader( LPCWSTR cmd_line, unsigned int flags, int socketfd,
1911 int stdin_fd, int stdout_fd, const char *unixdir, char *winedebug,
1912 const struct binary_info *binary_info, int exec_only )
1914 pid_t pid;
1915 char *wineloader = NULL;
1916 const char *loader = NULL;
1917 char **argv;
1919 argv = build_argv( cmd_line, 1 );
1921 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1922 loader = get_alternate_loader( &wineloader );
1924 if (exec_only || !(pid = fork())) /* child */
1926 if (exec_only || !(pid = fork())) /* grandchild */
1928 char preloader_reserve[64], socket_env[64];
1930 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1932 int fd = open( "/dev/null", O_RDWR );
1933 setsid();
1934 /* close stdin and stdout */
1935 if (fd != -1)
1937 dup2( fd, 0 );
1938 dup2( fd, 1 );
1939 close( fd );
1942 else
1944 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1945 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1948 if (stdin_fd != -1) close( stdin_fd );
1949 if (stdout_fd != -1) close( stdout_fd );
1951 /* Reset signals that we previously set to SIG_IGN */
1952 signal( SIGPIPE, SIG_DFL );
1954 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
1955 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%x%08x-%x%08x",
1956 (ULONG)(binary_info->res_start >> 32), (ULONG)binary_info->res_start,
1957 (ULONG)(binary_info->res_end >> 32), (ULONG)binary_info->res_end );
1959 putenv( preloader_reserve );
1960 putenv( socket_env );
1961 if (winedebug) putenv( winedebug );
1962 if (wineloader) putenv( wineloader );
1963 if (unixdir) chdir(unixdir);
1965 if (argv)
1969 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1971 #ifdef __APPLE__
1972 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1973 #else
1974 while (0);
1975 #endif
1977 _exit(1);
1980 _exit(pid == -1);
1983 if (pid != -1)
1985 /* reap child */
1986 pid_t wret;
1987 do {
1988 wret = waitpid(pid, NULL, 0);
1989 } while (wret < 0 && errno == EINTR);
1992 HeapFree( GetProcessHeap(), 0, wineloader );
1993 HeapFree( GetProcessHeap(), 0, argv );
1994 return pid;
1997 /***********************************************************************
1998 * create_process
2000 * Create a new process. If hFile is a valid handle we have an exe
2001 * file, otherwise it is a Winelib app.
2003 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
2004 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2005 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2006 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2007 const struct binary_info *binary_info, int exec_only )
2009 static const char *cpu_names[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
2010 NTSTATUS status;
2011 BOOL success = FALSE;
2012 HANDLE process_info;
2013 WCHAR *env_end;
2014 char *winedebug = NULL;
2015 startup_info_t *startup_info;
2016 DWORD startup_info_size;
2017 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
2018 pid_t pid;
2019 int err, cpu;
2021 if ((cpu = get_process_cpu( filename, binary_info )) == -1)
2023 SetLastError( ERROR_BAD_EXE_FORMAT );
2024 return FALSE;
2027 /* create the socket for the new process */
2029 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
2031 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
2032 return FALSE;
2034 #ifdef SO_PASSCRED
2035 else
2037 int enable = 1;
2038 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
2040 #endif
2042 if (exec_only) /* things are much simpler in this case */
2044 wine_server_send_fd( socketfd[1] );
2045 close( socketfd[1] );
2046 SERVER_START_REQ( new_process )
2048 req->create_flags = flags;
2049 req->socket_fd = socketfd[1];
2050 req->exe_file = wine_server_obj_handle( hFile );
2051 req->cpu = cpu;
2052 status = wine_server_call( req );
2054 SERVER_END_REQ;
2056 switch (status)
2058 case STATUS_INVALID_IMAGE_WIN_64:
2059 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2060 break;
2061 case STATUS_INVALID_IMAGE_FORMAT:
2062 ERR( "%s not supported on this installation (%s binary)\n",
2063 debugstr_w(filename), cpu_names[cpu] );
2064 break;
2065 case STATUS_SUCCESS:
2066 exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2067 winedebug, binary_info, TRUE );
2069 close( socketfd[0] );
2070 SetLastError( RtlNtStatusToDosError( status ));
2071 return FALSE;
2074 RtlAcquirePebLock();
2076 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
2077 &startup_info_size )))
2079 RtlReleasePebLock();
2080 close( socketfd[0] );
2081 close( socketfd[1] );
2082 return FALSE;
2084 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
2085 env_end = env;
2086 while (*env_end)
2088 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
2089 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
2091 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
2092 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
2093 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
2095 env_end += strlenW(env_end) + 1;
2097 env_end++;
2099 wine_server_send_fd( socketfd[1] );
2100 close( socketfd[1] );
2102 /* create the process on the server side */
2104 SERVER_START_REQ( new_process )
2106 req->inherit_all = inherit;
2107 req->create_flags = flags;
2108 req->socket_fd = socketfd[1];
2109 req->exe_file = wine_server_obj_handle( hFile );
2110 req->process_access = PROCESS_ALL_ACCESS;
2111 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
2112 req->thread_access = THREAD_ALL_ACCESS;
2113 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
2114 req->cpu = cpu;
2115 req->info_size = startup_info_size;
2117 wine_server_add_data( req, startup_info, startup_info_size );
2118 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
2119 if (!(status = wine_server_call( req )))
2121 info->dwProcessId = (DWORD)reply->pid;
2122 info->dwThreadId = (DWORD)reply->tid;
2123 info->hProcess = wine_server_ptr_handle( reply->phandle );
2124 info->hThread = wine_server_ptr_handle( reply->thandle );
2126 process_info = wine_server_ptr_handle( reply->info );
2128 SERVER_END_REQ;
2130 RtlReleasePebLock();
2131 if (status)
2133 switch (status)
2135 case STATUS_INVALID_IMAGE_WIN_64:
2136 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2137 break;
2138 case STATUS_INVALID_IMAGE_FORMAT:
2139 ERR( "%s not supported on this installation (%s binary)\n",
2140 debugstr_w(filename), cpu_names[cpu] );
2141 break;
2143 close( socketfd[0] );
2144 HeapFree( GetProcessHeap(), 0, startup_info );
2145 HeapFree( GetProcessHeap(), 0, winedebug );
2146 SetLastError( RtlNtStatusToDosError( status ));
2147 return FALSE;
2150 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
2152 if (startup_info->hstdin)
2153 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
2154 FILE_READ_DATA, &stdin_fd, NULL );
2155 if (startup_info->hstdout)
2156 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
2157 FILE_WRITE_DATA, &stdout_fd, NULL );
2159 HeapFree( GetProcessHeap(), 0, startup_info );
2161 /* create the child process */
2163 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2164 winedebug, binary_info, FALSE );
2166 if (stdin_fd != -1) close( stdin_fd );
2167 if (stdout_fd != -1) close( stdout_fd );
2168 close( socketfd[0] );
2169 HeapFree( GetProcessHeap(), 0, winedebug );
2170 if (pid == -1)
2172 FILE_SetDosError();
2173 goto error;
2176 /* wait for the new process info to be ready */
2178 WaitForSingleObject( process_info, INFINITE );
2179 SERVER_START_REQ( get_new_process_info )
2181 req->info = wine_server_obj_handle( process_info );
2182 wine_server_call( req );
2183 success = reply->success;
2184 err = reply->exit_code;
2186 SERVER_END_REQ;
2188 if (!success)
2190 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2191 goto error;
2193 CloseHandle( process_info );
2194 return success;
2196 error:
2197 CloseHandle( process_info );
2198 CloseHandle( info->hProcess );
2199 CloseHandle( info->hThread );
2200 info->hProcess = info->hThread = 0;
2201 info->dwProcessId = info->dwThreadId = 0;
2202 return FALSE;
2206 /***********************************************************************
2207 * create_vdm_process
2209 * Create a new VDM process for a 16-bit or DOS application.
2211 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2212 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2213 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2214 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2215 const struct binary_info *binary_info, int exec_only )
2217 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2219 BOOL ret;
2220 WCHAR buffer[MAX_PATH];
2221 LPWSTR new_cmd_line;
2223 if (!(ret = GetFullPathNameW(filename, MAX_PATH, buffer, NULL)))
2224 return FALSE;
2226 new_cmd_line = HeapAlloc(GetProcessHeap(), 0,
2227 (strlenW(buffer) + strlenW(cmd_line) + 30) * sizeof(WCHAR));
2229 if (!new_cmd_line)
2231 SetLastError( ERROR_OUTOFMEMORY );
2232 return FALSE;
2234 sprintfW(new_cmd_line, argsW, winevdmW, buffer, cmd_line);
2235 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2236 flags, startup, info, unixdir, binary_info, exec_only );
2237 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2238 return ret;
2242 /***********************************************************************
2243 * create_cmd_process
2245 * Create a new cmd shell process for a .BAT file.
2247 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2248 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2249 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2250 LPPROCESS_INFORMATION info )
2253 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2254 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2255 WCHAR comspec[MAX_PATH];
2256 WCHAR *newcmdline;
2257 BOOL ret;
2259 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2260 return FALSE;
2261 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2262 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2263 return FALSE;
2265 strcpyW( newcmdline, comspec );
2266 strcatW( newcmdline, slashcW );
2267 strcatW( newcmdline, cmd_line );
2268 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2269 flags, env, cur_dir, startup, info );
2270 HeapFree( GetProcessHeap(), 0, newcmdline );
2271 return ret;
2275 /*************************************************************************
2276 * get_file_name
2278 * Helper for CreateProcess: retrieve the file name to load from the
2279 * app name and command line. Store the file name in buffer, and
2280 * return a possibly modified command line.
2281 * Also returns a handle to the opened file if it's a Windows binary.
2283 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2284 int buflen, HANDLE *handle, struct binary_info *binary_info )
2286 static const WCHAR quotesW[] = {'"','%','s','"',0};
2288 WCHAR *name, *pos, *first_space, *ret = NULL;
2289 const WCHAR *p;
2291 /* if we have an app name, everything is easy */
2293 if (appname)
2295 /* use the unmodified app name as file name */
2296 lstrcpynW( buffer, appname, buflen );
2297 *handle = open_exe_file( buffer, binary_info );
2298 if (!(ret = cmdline) || !cmdline[0])
2300 /* no command-line, create one */
2301 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2302 sprintfW( ret, quotesW, appname );
2304 return ret;
2307 /* first check for a quoted file name */
2309 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2311 int len = p - cmdline - 1;
2312 /* extract the quoted portion as file name */
2313 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2314 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2315 name[len] = 0;
2317 if (!find_exe_file( name, buffer, buflen, handle, binary_info )) goto done;
2318 ret = cmdline; /* no change necessary */
2319 goto done;
2322 /* now try the command-line word by word */
2324 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2325 return NULL;
2326 pos = name;
2327 p = cmdline;
2328 first_space = NULL;
2330 for (;;)
2332 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2333 *pos = 0;
2334 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2336 ret = cmdline;
2337 break;
2339 if (!first_space) first_space = pos;
2340 if (!(*pos++ = *p++)) break;
2343 if (!ret)
2345 SetLastError( ERROR_FILE_NOT_FOUND );
2347 else if (first_space) /* build a new command-line with quotes */
2349 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2350 goto done;
2351 sprintfW( ret, quotesW, name );
2352 strcatW( ret, p );
2355 done:
2356 HeapFree( GetProcessHeap(), 0, name );
2357 return ret;
2361 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2362 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2363 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2364 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2365 LPPROCESS_INFORMATION info )
2367 BOOL retv = FALSE;
2368 HANDLE hFile = 0;
2369 char *unixdir = NULL;
2370 WCHAR name[MAX_PATH];
2371 WCHAR *tidy_cmdline, *p, *envW = env;
2372 struct binary_info binary_info;
2374 /* Process the AppName and/or CmdLine to get module name and path */
2376 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2378 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2379 &hFile, &binary_info )))
2380 return FALSE;
2381 if (hFile == INVALID_HANDLE_VALUE) goto done;
2383 /* Warn if unsupported features are used */
2385 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2386 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2387 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2388 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2389 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2391 if (cur_dir)
2393 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2395 SetLastError(ERROR_DIRECTORY);
2396 goto done;
2399 else
2401 WCHAR buf[MAX_PATH];
2402 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2405 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2407 char *e = env;
2408 DWORD lenW;
2410 while (*e) e += strlen(e) + 1;
2411 e++; /* final null */
2412 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, NULL, 0 );
2413 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2414 MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, envW, lenW );
2415 flags |= CREATE_UNICODE_ENVIRONMENT;
2418 info->hThread = info->hProcess = 0;
2419 info->dwProcessId = info->dwThreadId = 0;
2421 if (binary_info.flags & BINARY_FLAG_DLL)
2423 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2424 SetLastError( ERROR_BAD_EXE_FORMAT );
2426 else switch (binary_info.type)
2428 case BINARY_PE:
2429 TRACE( "starting %s as Win%d binary (%s-%s, arch %04x%s)\n",
2430 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2431 wine_dbgstr_longlong(binary_info.res_start), wine_dbgstr_longlong(binary_info.res_end),
2432 binary_info.arch, (binary_info.flags & BINARY_FLAG_FAKEDLL) ? ", fakedll" : "" );
2433 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2434 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2435 break;
2436 case BINARY_OS216:
2437 case BINARY_WIN16:
2438 case BINARY_DOS:
2439 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2440 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2441 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2442 break;
2443 case BINARY_UNIX_LIB:
2444 TRACE( "starting %s as %d-bit Winelib app\n",
2445 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2446 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2447 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2448 break;
2449 case BINARY_UNKNOWN:
2450 /* check for .com or .bat extension */
2451 if ((p = strrchrW( name, '.' )))
2453 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2455 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2456 binary_info.type = BINARY_DOS;
2457 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2458 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2459 inherit, flags, startup_info, info, unixdir,
2460 &binary_info, FALSE );
2461 break;
2463 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2465 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2466 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2467 inherit, flags, startup_info, info );
2468 break;
2471 /* fall through */
2472 case BINARY_UNIX_EXE:
2474 /* unknown file, try as unix executable */
2475 char *unix_name;
2477 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2479 if ((unix_name = wine_get_unix_file_name( name )))
2481 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2482 HeapFree( GetProcessHeap(), 0, unix_name );
2485 break;
2487 if (hFile) CloseHandle( hFile );
2489 done:
2490 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2491 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2492 HeapFree( GetProcessHeap(), 0, unixdir );
2493 if (retv)
2494 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2495 return retv;
2499 /**********************************************************************
2500 * CreateProcessA (KERNEL32.@)
2502 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2503 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2504 DWORD flags, LPVOID env, LPCSTR cur_dir,
2505 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2507 BOOL ret = FALSE;
2508 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2509 UNICODE_STRING desktopW, titleW;
2510 STARTUPINFOW infoW;
2512 desktopW.Buffer = NULL;
2513 titleW.Buffer = NULL;
2514 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2515 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2516 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2518 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2519 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2521 memcpy( &infoW, startup_info, sizeof(infoW) );
2522 infoW.lpDesktop = desktopW.Buffer;
2523 infoW.lpTitle = titleW.Buffer;
2525 if (startup_info->lpReserved)
2526 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2527 debugstr_a(startup_info->lpReserved));
2529 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2530 inherit, flags, env, cur_dirW, &infoW, info );
2531 done:
2532 HeapFree( GetProcessHeap(), 0, app_nameW );
2533 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2534 HeapFree( GetProcessHeap(), 0, cur_dirW );
2535 RtlFreeUnicodeString( &desktopW );
2536 RtlFreeUnicodeString( &titleW );
2537 return ret;
2541 /**********************************************************************
2542 * CreateProcessW (KERNEL32.@)
2544 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2545 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2546 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2547 LPPROCESS_INFORMATION info )
2549 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2550 inherit, flags, env, cur_dir, startup_info, info);
2554 /**********************************************************************
2555 * exec_process
2557 static void exec_process( LPCWSTR name )
2559 HANDLE hFile;
2560 WCHAR *p;
2561 STARTUPINFOW startup_info;
2562 PROCESS_INFORMATION info;
2563 struct binary_info binary_info;
2565 hFile = open_exe_file( name, &binary_info );
2566 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2568 memset( &startup_info, 0, sizeof(startup_info) );
2569 startup_info.cb = sizeof(startup_info);
2571 /* Determine executable type */
2573 if (binary_info.flags & BINARY_FLAG_DLL)
2575 CloseHandle( hFile );
2576 return;
2579 switch (binary_info.type)
2581 case BINARY_PE:
2582 TRACE( "starting %s as Win%d binary (%s-%s, arch %04x)\n",
2583 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2584 wine_dbgstr_longlong(binary_info.res_start), wine_dbgstr_longlong(binary_info.res_end),
2585 binary_info.arch );
2586 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2587 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2588 break;
2589 case BINARY_UNIX_LIB:
2590 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2591 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2592 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2593 break;
2594 case BINARY_UNKNOWN:
2595 /* check for .com or .pif extension */
2596 if (!(p = strrchrW( name, '.' ))) break;
2597 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2598 binary_info.type = BINARY_DOS;
2599 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2600 /* fall through */
2601 case BINARY_OS216:
2602 case BINARY_WIN16:
2603 case BINARY_DOS:
2604 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2605 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2606 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2607 break;
2608 default:
2609 break;
2611 CloseHandle( hFile );
2615 /***********************************************************************
2616 * wait_input_idle
2618 * Wrapper to call WaitForInputIdle USER function
2620 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2622 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2624 HMODULE mod = GetModuleHandleA( "user32.dll" );
2625 if (mod)
2627 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2628 if (ptr) return ptr( process, timeout );
2630 return 0;
2634 /***********************************************************************
2635 * WinExec (KERNEL32.@)
2637 UINT WINAPI DECLSPEC_HOTPATCH WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2639 PROCESS_INFORMATION info;
2640 STARTUPINFOA startup;
2641 char *cmdline;
2642 UINT ret;
2644 memset( &startup, 0, sizeof(startup) );
2645 startup.cb = sizeof(startup);
2646 startup.dwFlags = STARTF_USESHOWWINDOW;
2647 startup.wShowWindow = nCmdShow;
2649 /* cmdline needs to be writable for CreateProcess */
2650 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2651 strcpy( cmdline, lpCmdLine );
2653 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2654 0, NULL, NULL, &startup, &info ))
2656 /* Give 30 seconds to the app to come up */
2657 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2658 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2659 ret = 33;
2660 /* Close off the handles */
2661 CloseHandle( info.hThread );
2662 CloseHandle( info.hProcess );
2664 else if ((ret = GetLastError()) >= 32)
2666 FIXME("Strange error set by CreateProcess: %d\n", ret );
2667 ret = 11;
2669 HeapFree( GetProcessHeap(), 0, cmdline );
2670 return ret;
2674 /**********************************************************************
2675 * LoadModule (KERNEL32.@)
2677 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2679 LOADPARMS32 *params = paramBlock;
2680 PROCESS_INFORMATION info;
2681 STARTUPINFOA startup;
2682 DWORD ret;
2683 LPSTR cmdline, p;
2684 char filename[MAX_PATH];
2685 BYTE len;
2687 if (!name) return ERROR_FILE_NOT_FOUND;
2689 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2690 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2691 return GetLastError();
2693 len = (BYTE)params->lpCmdLine[0];
2694 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2695 return ERROR_NOT_ENOUGH_MEMORY;
2697 strcpy( cmdline, filename );
2698 p = cmdline + strlen(cmdline);
2699 *p++ = ' ';
2700 memcpy( p, params->lpCmdLine + 1, len );
2701 p[len] = 0;
2703 memset( &startup, 0, sizeof(startup) );
2704 startup.cb = sizeof(startup);
2705 if (params->lpCmdShow)
2707 startup.dwFlags = STARTF_USESHOWWINDOW;
2708 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2711 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2712 params->lpEnvAddress, NULL, &startup, &info ))
2714 /* Give 30 seconds to the app to come up */
2715 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2716 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2717 ret = 33;
2718 /* Close off the handles */
2719 CloseHandle( info.hThread );
2720 CloseHandle( info.hProcess );
2722 else if ((ret = GetLastError()) >= 32)
2724 FIXME("Strange error set by CreateProcess: %u\n", ret );
2725 ret = 11;
2728 HeapFree( GetProcessHeap(), 0, cmdline );
2729 return ret;
2733 /******************************************************************************
2734 * TerminateProcess (KERNEL32.@)
2736 * Terminates a process.
2738 * PARAMS
2739 * handle [I] Process to terminate.
2740 * exit_code [I] Exit code.
2742 * RETURNS
2743 * Success: TRUE.
2744 * Failure: FALSE, check GetLastError().
2746 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2748 NTSTATUS status;
2750 if (!handle)
2752 SetLastError( ERROR_INVALID_HANDLE );
2753 return FALSE;
2756 status = NtTerminateProcess( handle, exit_code );
2757 if (status) SetLastError( RtlNtStatusToDosError(status) );
2758 return !status;
2761 /***********************************************************************
2762 * ExitProcess (KERNEL32.@)
2764 * Exits the current process.
2766 * PARAMS
2767 * status [I] Status code to exit with.
2769 * RETURNS
2770 * Nothing.
2772 #ifdef __i386__
2773 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2774 "pushl %ebp\n\t"
2775 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2776 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2777 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2778 "pushl 8(%ebp)\n\t"
2779 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
2780 "leave\n\t"
2781 "ret $4" )
2782 #else
2784 void WINAPI ExitProcess( DWORD status )
2786 RtlExitUserProcess( status );
2789 #endif
2791 /***********************************************************************
2792 * GetExitCodeProcess [KERNEL32.@]
2794 * Gets termination status of specified process.
2796 * PARAMS
2797 * hProcess [in] Handle to the process.
2798 * lpExitCode [out] Address to receive termination status.
2800 * RETURNS
2801 * Success: TRUE
2802 * Failure: FALSE
2804 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2806 NTSTATUS status;
2807 PROCESS_BASIC_INFORMATION pbi;
2809 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2810 sizeof(pbi), NULL);
2811 if (status == STATUS_SUCCESS)
2813 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2814 return TRUE;
2816 SetLastError( RtlNtStatusToDosError(status) );
2817 return FALSE;
2821 /***********************************************************************
2822 * SetErrorMode (KERNEL32.@)
2824 UINT WINAPI SetErrorMode( UINT mode )
2826 UINT old;
2828 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2829 &old, sizeof(old), NULL );
2830 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2831 &mode, sizeof(mode) );
2832 return old;
2835 /***********************************************************************
2836 * GetErrorMode (KERNEL32.@)
2838 UINT WINAPI GetErrorMode( void )
2840 UINT mode;
2842 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2843 &mode, sizeof(mode), NULL );
2844 return mode;
2847 /**********************************************************************
2848 * TlsAlloc [KERNEL32.@]
2850 * Allocates a thread local storage index.
2852 * RETURNS
2853 * Success: TLS index.
2854 * Failure: 0xFFFFFFFF
2856 DWORD WINAPI TlsAlloc( void )
2858 DWORD index;
2859 PEB * const peb = NtCurrentTeb()->Peb;
2861 RtlAcquirePebLock();
2862 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 1 );
2863 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2864 else
2866 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2867 if (index != ~0U)
2869 if (!NtCurrentTeb()->TlsExpansionSlots &&
2870 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2871 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2873 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2874 index = ~0U;
2875 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2877 else
2879 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2880 index += TLS_MINIMUM_AVAILABLE;
2883 else SetLastError( ERROR_NO_MORE_ITEMS );
2885 RtlReleasePebLock();
2886 return index;
2890 /**********************************************************************
2891 * TlsFree [KERNEL32.@]
2893 * Releases a thread local storage index, making it available for reuse.
2895 * PARAMS
2896 * index [in] TLS index to free.
2898 * RETURNS
2899 * Success: TRUE
2900 * Failure: FALSE
2902 BOOL WINAPI TlsFree( DWORD index )
2904 BOOL ret;
2906 RtlAcquirePebLock();
2907 if (index >= TLS_MINIMUM_AVAILABLE)
2909 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2910 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2912 else
2914 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2915 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2917 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2918 else SetLastError( ERROR_INVALID_PARAMETER );
2919 RtlReleasePebLock();
2920 return ret;
2924 /**********************************************************************
2925 * TlsGetValue [KERNEL32.@]
2927 * Gets value in a thread's TLS slot.
2929 * PARAMS
2930 * index [in] TLS index to retrieve value for.
2932 * RETURNS
2933 * Success: Value stored in calling thread's TLS slot for index.
2934 * Failure: 0 and GetLastError() returns NO_ERROR.
2936 LPVOID WINAPI TlsGetValue( DWORD index )
2938 LPVOID ret;
2940 if (index < TLS_MINIMUM_AVAILABLE)
2942 ret = NtCurrentTeb()->TlsSlots[index];
2944 else
2946 index -= TLS_MINIMUM_AVAILABLE;
2947 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2949 SetLastError( ERROR_INVALID_PARAMETER );
2950 return NULL;
2952 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2953 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2955 SetLastError( ERROR_SUCCESS );
2956 return ret;
2960 /**********************************************************************
2961 * TlsSetValue [KERNEL32.@]
2963 * Stores a value in the thread's TLS slot.
2965 * PARAMS
2966 * index [in] TLS index to set value for.
2967 * value [in] Value to be stored.
2969 * RETURNS
2970 * Success: TRUE
2971 * Failure: FALSE
2973 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2975 if (index < TLS_MINIMUM_AVAILABLE)
2977 NtCurrentTeb()->TlsSlots[index] = value;
2979 else
2981 index -= TLS_MINIMUM_AVAILABLE;
2982 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2984 SetLastError( ERROR_INVALID_PARAMETER );
2985 return FALSE;
2987 if (!NtCurrentTeb()->TlsExpansionSlots &&
2988 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2989 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2991 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2992 return FALSE;
2994 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2996 return TRUE;
3000 /***********************************************************************
3001 * GetProcessFlags (KERNEL32.@)
3003 DWORD WINAPI GetProcessFlags( DWORD processid )
3005 IMAGE_NT_HEADERS *nt;
3006 DWORD flags = 0;
3008 if (processid && processid != GetCurrentProcessId()) return 0;
3010 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3012 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
3013 flags |= PDB32_CONSOLE_PROC;
3015 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
3016 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
3017 return flags;
3021 /*********************************************************************
3022 * OpenProcess (KERNEL32.@)
3024 * Opens a handle to a process.
3026 * PARAMS
3027 * access [I] Desired access rights assigned to the returned handle.
3028 * inherit [I] Determines whether or not child processes will inherit the handle.
3029 * id [I] Process identifier of the process to get a handle to.
3031 * RETURNS
3032 * Success: Valid handle to the specified process.
3033 * Failure: NULL, check GetLastError().
3035 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
3037 NTSTATUS status;
3038 HANDLE handle;
3039 OBJECT_ATTRIBUTES attr;
3040 CLIENT_ID cid;
3042 cid.UniqueProcess = ULongToHandle(id);
3043 cid.UniqueThread = 0; /* FIXME ? */
3045 attr.Length = sizeof(OBJECT_ATTRIBUTES);
3046 attr.RootDirectory = NULL;
3047 attr.Attributes = inherit ? OBJ_INHERIT : 0;
3048 attr.SecurityDescriptor = NULL;
3049 attr.SecurityQualityOfService = NULL;
3050 attr.ObjectName = NULL;
3052 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
3054 status = NtOpenProcess(&handle, access, &attr, &cid);
3055 if (status != STATUS_SUCCESS)
3057 SetLastError( RtlNtStatusToDosError(status) );
3058 return NULL;
3060 return handle;
3064 /*********************************************************************
3065 * GetProcessId (KERNEL32.@)
3067 * Gets the a unique identifier of a process.
3069 * PARAMS
3070 * hProcess [I] Handle to the process.
3072 * RETURNS
3073 * Success: TRUE.
3074 * Failure: FALSE, check GetLastError().
3076 * NOTES
3078 * The identifier is unique only on the machine and only until the process
3079 * exits (including system shutdown).
3081 DWORD WINAPI GetProcessId( HANDLE hProcess )
3083 NTSTATUS status;
3084 PROCESS_BASIC_INFORMATION pbi;
3086 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3087 sizeof(pbi), NULL);
3088 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
3089 SetLastError( RtlNtStatusToDosError(status) );
3090 return 0;
3094 /*********************************************************************
3095 * CloseHandle (KERNEL32.@)
3097 * Closes a handle.
3099 * PARAMS
3100 * handle [I] Handle to close.
3102 * RETURNS
3103 * Success: TRUE.
3104 * Failure: FALSE, check GetLastError().
3106 BOOL WINAPI CloseHandle( HANDLE handle )
3108 NTSTATUS status;
3110 /* stdio handles need special treatment */
3111 if (handle == (HANDLE)STD_INPUT_HANDLE)
3112 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
3113 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
3114 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
3115 else if (handle == (HANDLE)STD_ERROR_HANDLE)
3116 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
3118 if (is_console_handle(handle))
3119 return CloseConsoleHandle(handle);
3121 status = NtClose( handle );
3122 if (status) SetLastError( RtlNtStatusToDosError(status) );
3123 return !status;
3127 /*********************************************************************
3128 * GetHandleInformation (KERNEL32.@)
3130 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
3132 OBJECT_DATA_INFORMATION info;
3133 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
3135 if (status) SetLastError( RtlNtStatusToDosError(status) );
3136 else if (flags)
3138 *flags = 0;
3139 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3140 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3142 return !status;
3146 /*********************************************************************
3147 * SetHandleInformation (KERNEL32.@)
3149 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3151 OBJECT_DATA_INFORMATION info;
3152 NTSTATUS status;
3154 /* if not setting both fields, retrieve current value first */
3155 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3156 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3158 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3160 SetLastError( RtlNtStatusToDosError(status) );
3161 return FALSE;
3164 if (mask & HANDLE_FLAG_INHERIT)
3165 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3166 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3167 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3169 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3170 if (status) SetLastError( RtlNtStatusToDosError(status) );
3171 return !status;
3175 /*********************************************************************
3176 * DuplicateHandle (KERNEL32.@)
3178 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3179 HANDLE dest_process, HANDLE *dest,
3180 DWORD access, BOOL inherit, DWORD options )
3182 NTSTATUS status;
3184 if (is_console_handle(source))
3186 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3187 if (source_process != dest_process ||
3188 source_process != GetCurrentProcess())
3190 SetLastError(ERROR_INVALID_PARAMETER);
3191 return FALSE;
3193 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3194 return (*dest != INVALID_HANDLE_VALUE);
3196 status = NtDuplicateObject( source_process, source, dest_process, dest,
3197 access, inherit ? OBJ_INHERIT : 0, options );
3198 if (status) SetLastError( RtlNtStatusToDosError(status) );
3199 return !status;
3203 /***********************************************************************
3204 * ConvertToGlobalHandle (KERNEL32.@)
3206 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3208 HANDLE ret = INVALID_HANDLE_VALUE;
3209 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3210 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3211 return ret;
3215 /***********************************************************************
3216 * SetHandleContext (KERNEL32.@)
3218 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3220 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3221 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3222 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3223 return FALSE;
3227 /***********************************************************************
3228 * GetHandleContext (KERNEL32.@)
3230 DWORD WINAPI GetHandleContext(HANDLE hnd)
3232 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3233 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3234 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3235 return 0;
3239 /***********************************************************************
3240 * CreateSocketHandle (KERNEL32.@)
3242 HANDLE WINAPI CreateSocketHandle(void)
3244 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3245 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3246 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3247 return INVALID_HANDLE_VALUE;
3251 /***********************************************************************
3252 * SetPriorityClass (KERNEL32.@)
3254 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3256 NTSTATUS status;
3257 PROCESS_PRIORITY_CLASS ppc;
3259 ppc.Foreground = FALSE;
3260 switch (priorityclass)
3262 case IDLE_PRIORITY_CLASS:
3263 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3264 case BELOW_NORMAL_PRIORITY_CLASS:
3265 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3266 case NORMAL_PRIORITY_CLASS:
3267 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3268 case ABOVE_NORMAL_PRIORITY_CLASS:
3269 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3270 case HIGH_PRIORITY_CLASS:
3271 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3272 case REALTIME_PRIORITY_CLASS:
3273 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3274 default:
3275 SetLastError(ERROR_INVALID_PARAMETER);
3276 return FALSE;
3279 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3280 &ppc, sizeof(ppc));
3282 if (status != STATUS_SUCCESS)
3284 SetLastError( RtlNtStatusToDosError(status) );
3285 return FALSE;
3287 return TRUE;
3291 /***********************************************************************
3292 * GetPriorityClass (KERNEL32.@)
3294 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3296 NTSTATUS status;
3297 PROCESS_BASIC_INFORMATION pbi;
3299 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3300 sizeof(pbi), NULL);
3301 if (status != STATUS_SUCCESS)
3303 SetLastError( RtlNtStatusToDosError(status) );
3304 return 0;
3306 switch (pbi.BasePriority)
3308 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3309 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3310 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3311 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3312 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3313 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3315 SetLastError( ERROR_INVALID_PARAMETER );
3316 return 0;
3320 /***********************************************************************
3321 * SetProcessAffinityMask (KERNEL32.@)
3323 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3325 NTSTATUS status;
3327 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3328 &affmask, sizeof(DWORD_PTR));
3329 if (status)
3331 SetLastError( RtlNtStatusToDosError(status) );
3332 return FALSE;
3334 return TRUE;
3338 /**********************************************************************
3339 * GetProcessAffinityMask (KERNEL32.@)
3341 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3343 NTSTATUS status = STATUS_SUCCESS;
3345 if (process_mask)
3347 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3348 process_mask, sizeof(*process_mask), NULL )))
3349 SetLastError( RtlNtStatusToDosError(status) );
3351 if (system_mask && status == STATUS_SUCCESS)
3353 SYSTEM_BASIC_INFORMATION info;
3355 if ((status = NtQuerySystemInformation( SystemBasicInformation, &info, sizeof(info), NULL )))
3356 SetLastError( RtlNtStatusToDosError(status) );
3357 else
3358 *system_mask = info.ActiveProcessorsAffinityMask;
3360 return !status;
3364 /***********************************************************************
3365 * GetProcessVersion (KERNEL32.@)
3367 DWORD WINAPI GetProcessVersion( DWORD pid )
3369 HANDLE process;
3370 NTSTATUS status;
3371 PROCESS_BASIC_INFORMATION pbi;
3372 SIZE_T count;
3373 PEB peb;
3374 IMAGE_DOS_HEADER dos;
3375 IMAGE_NT_HEADERS nt;
3376 DWORD ver = 0;
3378 if (!pid || pid == GetCurrentProcessId())
3380 IMAGE_NT_HEADERS *pnt;
3382 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3383 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3384 pnt->OptionalHeader.MinorSubsystemVersion);
3385 return 0;
3388 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3389 if (!process) return 0;
3391 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3392 if (status) goto err;
3394 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3395 if (status || count != sizeof(peb)) goto err;
3397 memset(&dos, 0, sizeof(dos));
3398 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3399 if (status || count != sizeof(dos)) goto err;
3400 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3402 memset(&nt, 0, sizeof(nt));
3403 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3404 if (status || count != sizeof(nt)) goto err;
3405 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3407 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3409 err:
3410 CloseHandle(process);
3412 if (status != STATUS_SUCCESS)
3413 SetLastError(RtlNtStatusToDosError(status));
3415 return ver;
3419 /***********************************************************************
3420 * SetProcessWorkingSetSize [KERNEL32.@]
3421 * Sets the min/max working set sizes for a specified process.
3423 * PARAMS
3424 * hProcess [I] Handle to the process of interest
3425 * minset [I] Specifies minimum working set size
3426 * maxset [I] Specifies maximum working set size
3428 * RETURNS
3429 * Success: TRUE
3430 * Failure: FALSE
3432 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3433 SIZE_T maxset)
3435 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3436 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3437 /* Trim the working set to zero */
3438 /* Swap the process out of physical RAM */
3440 return TRUE;
3443 /***********************************************************************
3444 * K32EmptyWorkingSet (KERNEL32.@)
3446 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3448 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3452 /***********************************************************************
3453 * GetProcessWorkingSetSizeEx (KERNEL32.@)
3455 BOOL WINAPI GetProcessWorkingSetSizeEx(HANDLE process, SIZE_T *minset,
3456 SIZE_T *maxset, DWORD *flags)
3458 FIXME("(%p,%p,%p,%p): stub\n", process, minset, maxset, flags);
3459 /* 32 MB working set size */
3460 if (minset) *minset = 32*1024*1024;
3461 if (maxset) *maxset = 32*1024*1024;
3462 if (flags) *flags = QUOTA_LIMITS_HARDWS_MIN_DISABLE |
3463 QUOTA_LIMITS_HARDWS_MAX_DISABLE;
3464 return TRUE;
3468 /***********************************************************************
3469 * GetProcessWorkingSetSize (KERNEL32.@)
3471 BOOL WINAPI GetProcessWorkingSetSize(HANDLE process, SIZE_T *minset, SIZE_T *maxset)
3473 return GetProcessWorkingSetSizeEx(process, minset, maxset, NULL);
3477 /***********************************************************************
3478 * SetProcessShutdownParameters (KERNEL32.@)
3480 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3482 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3483 shutdown_flags = flags;
3484 shutdown_priority = level;
3485 return TRUE;
3489 /***********************************************************************
3490 * GetProcessShutdownParameters (KERNEL32.@)
3493 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3495 *lpdwLevel = shutdown_priority;
3496 *lpdwFlags = shutdown_flags;
3497 return TRUE;
3501 /***********************************************************************
3502 * GetProcessPriorityBoost (KERNEL32.@)
3504 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3506 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3508 /* Report that no boost is present.. */
3509 *pDisablePriorityBoost = FALSE;
3511 return TRUE;
3514 /***********************************************************************
3515 * SetProcessPriorityBoost (KERNEL32.@)
3517 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3519 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3520 /* Say we can do it. I doubt the program will notice that we don't. */
3521 return TRUE;
3525 /***********************************************************************
3526 * ReadProcessMemory (KERNEL32.@)
3528 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3529 SIZE_T *bytes_read )
3531 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3532 if (status) SetLastError( RtlNtStatusToDosError(status) );
3533 return !status;
3537 /***********************************************************************
3538 * WriteProcessMemory (KERNEL32.@)
3540 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3541 SIZE_T *bytes_written )
3543 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3544 if (status) SetLastError( RtlNtStatusToDosError(status) );
3545 return !status;
3549 /****************************************************************************
3550 * FlushInstructionCache (KERNEL32.@)
3552 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3554 NTSTATUS status;
3555 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3556 if (status) SetLastError( RtlNtStatusToDosError(status) );
3557 return !status;
3561 /******************************************************************
3562 * GetProcessIoCounters (KERNEL32.@)
3564 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3566 NTSTATUS status;
3568 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3569 ioc, sizeof(*ioc), NULL);
3570 if (status) SetLastError( RtlNtStatusToDosError(status) );
3571 return !status;
3574 /******************************************************************
3575 * GetProcessHandleCount (KERNEL32.@)
3577 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3579 NTSTATUS status;
3581 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3582 cnt, sizeof(*cnt), NULL);
3583 if (status) SetLastError( RtlNtStatusToDosError(status) );
3584 return !status;
3587 /******************************************************************
3588 * QueryFullProcessImageNameA (KERNEL32.@)
3590 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3592 BOOL retval;
3593 DWORD pdwSizeW = *pdwSize;
3594 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3596 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3598 if(retval)
3599 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3600 lpExeName, *pdwSize, NULL, NULL));
3601 if(retval)
3602 *pdwSize = strlen(lpExeName);
3604 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3605 return retval;
3608 /******************************************************************
3609 * QueryFullProcessImageNameW (KERNEL32.@)
3611 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3613 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3614 UNICODE_STRING *dynamic_buffer = NULL;
3615 UNICODE_STRING *result = NULL;
3616 NTSTATUS status;
3617 DWORD needed;
3619 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3620 * is a DOS path and we depend on this. */
3621 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3622 sizeof(buffer) - sizeof(WCHAR), &needed);
3623 if (status == STATUS_INFO_LENGTH_MISMATCH)
3625 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3626 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3627 result = dynamic_buffer;
3629 else
3630 result = (PUNICODE_STRING)buffer;
3632 if (status) goto cleanup;
3634 if (dwFlags & PROCESS_NAME_NATIVE)
3636 WCHAR drive[3];
3637 WCHAR device[1024];
3638 DWORD ntlen, devlen;
3640 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3642 /* We cannot convert it to an NT device path so fail */
3643 status = STATUS_NO_SUCH_DEVICE;
3644 goto cleanup;
3647 /* Find this drive's NT device path */
3648 drive[0] = result->Buffer[0];
3649 drive[1] = ':';
3650 drive[2] = 0;
3651 if (!QueryDosDeviceW(drive, device, sizeof(device)/sizeof(*device)))
3653 status = STATUS_NO_SUCH_DEVICE;
3654 goto cleanup;
3657 devlen = lstrlenW(device);
3658 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3659 if (ntlen + 1 > *pdwSize)
3661 status = STATUS_BUFFER_TOO_SMALL;
3662 goto cleanup;
3664 *pdwSize = ntlen;
3666 memcpy(lpExeName, device, devlen * sizeof(*device));
3667 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3668 lpExeName[*pdwSize] = 0;
3669 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3671 else
3673 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3675 status = STATUS_BUFFER_TOO_SMALL;
3676 goto cleanup;
3679 *pdwSize = result->Length/sizeof(WCHAR);
3680 memcpy( lpExeName, result->Buffer, result->Length );
3681 lpExeName[*pdwSize] = 0;
3684 cleanup:
3685 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3686 if (status) SetLastError( RtlNtStatusToDosError(status) );
3687 return !status;
3690 /***********************************************************************
3691 * K32GetProcessImageFileNameA (KERNEL32.@)
3693 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3695 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3698 /***********************************************************************
3699 * K32GetProcessImageFileNameW (KERNEL32.@)
3701 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3703 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3706 /***********************************************************************
3707 * K32EnumProcesses (KERNEL32.@)
3709 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3711 SYSTEM_PROCESS_INFORMATION *spi;
3712 ULONG size = 0x4000;
3713 void *buf = NULL;
3714 NTSTATUS status;
3716 do {
3717 size *= 2;
3718 HeapFree(GetProcessHeap(), 0, buf);
3719 buf = HeapAlloc(GetProcessHeap(), 0, size);
3720 if (!buf)
3721 return FALSE;
3723 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3724 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3726 if (status != STATUS_SUCCESS)
3728 HeapFree(GetProcessHeap(), 0, buf);
3729 SetLastError(RtlNtStatusToDosError(status));
3730 return FALSE;
3733 spi = buf;
3735 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3737 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3738 *lpcbUsed += sizeof(DWORD);
3740 if (spi->NextEntryOffset == 0)
3741 break;
3743 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3746 HeapFree(GetProcessHeap(), 0, buf);
3747 return TRUE;
3750 /***********************************************************************
3751 * K32QueryWorkingSet (KERNEL32.@)
3753 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3755 NTSTATUS status;
3757 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3759 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3761 if (status)
3763 SetLastError( RtlNtStatusToDosError( status ) );
3764 return FALSE;
3766 return TRUE;
3769 /***********************************************************************
3770 * K32QueryWorkingSetEx (KERNEL32.@)
3772 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3774 NTSTATUS status;
3776 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3778 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3780 if (status)
3782 SetLastError( RtlNtStatusToDosError( status ) );
3783 return FALSE;
3785 return TRUE;
3788 /***********************************************************************
3789 * K32GetProcessMemoryInfo (KERNEL32.@)
3791 * Retrieve memory usage information for a given process
3794 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3795 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3797 NTSTATUS status;
3798 VM_COUNTERS vmc;
3800 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3802 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3803 return FALSE;
3806 status = NtQueryInformationProcess(process, ProcessVmCounters,
3807 &vmc, sizeof(vmc), NULL);
3809 if (status)
3811 SetLastError(RtlNtStatusToDosError(status));
3812 return FALSE;
3815 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3816 pmc->PageFaultCount = vmc.PageFaultCount;
3817 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3818 pmc->WorkingSetSize = vmc.WorkingSetSize;
3819 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3820 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3821 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3822 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3823 pmc->PagefileUsage = vmc.PagefileUsage;
3824 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3826 return TRUE;
3829 /***********************************************************************
3830 * ProcessIdToSessionId (KERNEL32.@)
3831 * This function is available on Terminal Server 4SP4 and Windows 2000
3833 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3835 if (procid != GetCurrentProcessId())
3836 FIXME("Unsupported for other processes.\n");
3838 *sessionid_ptr = NtCurrentTeb()->Peb->SessionId;
3839 return TRUE;
3843 /***********************************************************************
3844 * RegisterServiceProcess (KERNEL32.@)
3846 * A service process calls this function to ensure that it continues to run
3847 * even after a user logged off.
3849 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3851 /* I don't think that Wine needs to do anything in this function */
3852 return 1; /* success */
3856 /**********************************************************************
3857 * IsWow64Process (KERNEL32.@)
3859 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3861 ULONG_PTR pbi;
3862 NTSTATUS status;
3864 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3866 if (status != STATUS_SUCCESS)
3868 SetLastError( RtlNtStatusToDosError( status ) );
3869 return FALSE;
3871 *Wow64Process = (pbi != 0);
3872 return TRUE;
3876 /***********************************************************************
3877 * GetCurrentProcess (KERNEL32.@)
3879 * Get a handle to the current process.
3881 * PARAMS
3882 * None.
3884 * RETURNS
3885 * A handle representing the current process.
3887 #undef GetCurrentProcess
3888 HANDLE WINAPI GetCurrentProcess(void)
3890 return (HANDLE)~(ULONG_PTR)0;
3893 /***********************************************************************
3894 * GetLogicalProcessorInformation (KERNEL32.@)
3896 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3898 NTSTATUS status;
3900 TRACE("(%p,%p)\n", buffer, pBufLen);
3902 if(!pBufLen)
3904 SetLastError(ERROR_INVALID_PARAMETER);
3905 return FALSE;
3908 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
3910 if (status == STATUS_INFO_LENGTH_MISMATCH)
3912 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3913 return FALSE;
3915 if (status != STATUS_SUCCESS)
3917 SetLastError( RtlNtStatusToDosError( status ) );
3918 return FALSE;
3920 return TRUE;
3923 /***********************************************************************
3924 * GetLogicalProcessorInformationEx (KERNEL32.@)
3926 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, DWORD *len)
3928 NTSTATUS status;
3930 TRACE("(%u,%p,%p)\n", relationship, buffer, len);
3932 if (!len)
3934 SetLastError( ERROR_INVALID_PARAMETER );
3935 return FALSE;
3938 status = NtQuerySystemInformationEx( SystemLogicalProcessorInformationEx, &relationship, sizeof(relationship),
3939 buffer, *len, len );
3940 if (status == STATUS_INFO_LENGTH_MISMATCH)
3942 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3943 return FALSE;
3945 if (status != STATUS_SUCCESS)
3947 SetLastError( RtlNtStatusToDosError( status ) );
3948 return FALSE;
3950 return TRUE;
3953 /***********************************************************************
3954 * CmdBatNotification (KERNEL32.@)
3956 * Notifies the system that a batch file has started or finished.
3958 * PARAMS
3959 * bBatchRunning [I] TRUE if a batch file has started or
3960 * FALSE if a batch file has finished executing.
3962 * RETURNS
3963 * Unknown.
3965 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3967 FIXME("%d\n", bBatchRunning);
3968 return FALSE;
3972 /***********************************************************************
3973 * RegisterApplicationRestart (KERNEL32.@)
3975 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3977 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3979 return S_OK;
3982 /**********************************************************************
3983 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3985 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3987 static int once;
3988 if (!once++) FIXME("stub\n");
3989 /* Return current session id. */
3990 return NtCurrentTeb()->Peb->SessionId;
3993 /**********************************************************************
3994 * GetSystemDEPPolicy (KERNEL32.@)
3996 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3998 FIXME("stub\n");
3999 return OptIn;
4002 /**********************************************************************
4003 * SetProcessDEPPolicy (KERNEL32.@)
4005 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
4007 FIXME("(%d): stub\n", newDEP);
4008 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4009 return FALSE;
4012 /**********************************************************************
4013 * ApplicationRecoveryFinished (KERNEL32.@)
4015 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
4017 FIXME(": stub\n");
4018 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4021 /**********************************************************************
4022 * ApplicationRecoveryInProgress (KERNEL32.@)
4024 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
4026 FIXME(":%p stub\n", canceled);
4027 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4028 return E_FAIL;
4031 /**********************************************************************
4032 * RegisterApplicationRecoveryCallback (KERNEL32.@)
4034 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
4036 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
4037 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4038 return E_FAIL;
4041 /**********************************************************************
4042 * GetNumaHighestNodeNumber (KERNEL32.@)
4044 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
4046 *highestnode = 0;
4047 FIXME("(%p): semi-stub\n", highestnode);
4048 return TRUE;
4051 /**********************************************************************
4052 * GetNumaNodeProcessorMask (KERNEL32.@)
4054 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
4056 FIXME("(%c %p): stub\n", node, mask);
4057 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4058 return FALSE;
4061 /**********************************************************************
4062 * GetNumaAvailableMemoryNode (KERNEL32.@)
4064 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
4066 FIXME("(%c %p): stub\n", node, available_bytes);
4067 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4068 return FALSE;
4071 /***********************************************************************
4072 * GetNumaProcessorNode (KERNEL32.@)
4074 BOOL WINAPI GetNumaProcessorNode(UCHAR processor, PUCHAR node)
4076 SYSTEM_INFO si;
4078 TRACE("(%d, %p)\n", processor, node);
4080 GetSystemInfo( &si );
4081 if (processor < si.dwNumberOfProcessors)
4083 *node = 0;
4084 return TRUE;
4087 *node = 0xFF;
4088 SetLastError(ERROR_INVALID_PARAMETER);
4089 return FALSE;
4092 /**********************************************************************
4093 * GetProcessDEPPolicy (KERNEL32.@)
4095 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
4097 NTSTATUS status;
4098 ULONG dep_flags;
4100 TRACE("(%p %p %p)\n", process, flags, permanent);
4102 status = NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
4103 &dep_flags, sizeof(dep_flags), NULL );
4104 if (!status)
4107 if (flags)
4109 *flags = 0;
4110 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE)
4111 *flags |= PROCESS_DEP_ENABLE;
4112 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION)
4113 *flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
4116 if (permanent)
4117 *permanent = (dep_flags & MEM_EXECUTE_OPTION_PERMANENT) != 0;
4120 if (status) SetLastError( RtlNtStatusToDosError(status) );
4121 return !status;
4124 /**********************************************************************
4125 * FlushProcessWriteBuffers (KERNEL32.@)
4127 VOID WINAPI FlushProcessWriteBuffers(void)
4129 static int once = 0;
4131 if (!once++)
4132 FIXME(": stub\n");
4135 /***********************************************************************
4136 * UnregisterApplicationRestart (KERNEL32.@)
4138 HRESULT WINAPI UnregisterApplicationRestart(void)
4140 FIXME(": stub\n");
4141 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4142 return S_OK;
4145 /***********************************************************************
4146 * GetSystemFirmwareTable (KERNEL32.@)
4148 UINT WINAPI GetSystemFirmwareTable(DWORD provider, DWORD id, PVOID buffer, DWORD size)
4150 FIXME("(%d %d %p %d):stub\n", provider, id, buffer, size);
4151 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4152 return 0;
4155 struct proc_thread_attr
4157 DWORD_PTR attr;
4158 SIZE_T size;
4159 void *value;
4162 struct _PROC_THREAD_ATTRIBUTE_LIST
4164 DWORD mask; /* bitmask of items in list */
4165 DWORD size; /* max number of items in list */
4166 DWORD count; /* number of items in list */
4167 DWORD pad;
4168 DWORD_PTR unk;
4169 struct proc_thread_attr attrs[1];
4172 /***********************************************************************
4173 * InitializeProcThreadAttributeList (KERNEL32.@)
4175 BOOL WINAPI InitializeProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4176 DWORD count, DWORD flags, SIZE_T *size)
4178 SIZE_T needed;
4179 BOOL ret = FALSE;
4181 TRACE("(%p %d %x %p)\n", list, count, flags, size);
4183 needed = FIELD_OFFSET(struct _PROC_THREAD_ATTRIBUTE_LIST, attrs[count]);
4184 if (list && *size >= needed)
4186 list->mask = 0;
4187 list->size = count;
4188 list->count = 0;
4189 list->unk = 0;
4190 ret = TRUE;
4192 else
4193 SetLastError(ERROR_INSUFFICIENT_BUFFER);
4195 *size = needed;
4196 return ret;
4199 /***********************************************************************
4200 * UpdateProcThreadAttribute (KERNEL32.@)
4202 BOOL WINAPI UpdateProcThreadAttribute(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4203 DWORD flags, DWORD_PTR attr, void *value, SIZE_T size,
4204 void *prev_ret, SIZE_T *size_ret)
4206 DWORD mask;
4207 struct proc_thread_attr *entry;
4209 TRACE("(%p %x %08lx %p %ld %p %p)\n", list, flags, attr, value, size, prev_ret, size_ret);
4211 if (list->count >= list->size)
4213 SetLastError(ERROR_GEN_FAILURE);
4214 return FALSE;
4217 switch (attr)
4219 case PROC_THREAD_ATTRIBUTE_PARENT_PROCESS:
4220 if (size != sizeof(HANDLE))
4222 SetLastError(ERROR_BAD_LENGTH);
4223 return FALSE;
4225 break;
4227 case PROC_THREAD_ATTRIBUTE_HANDLE_LIST:
4228 if ((size / sizeof(HANDLE)) * sizeof(HANDLE) != size)
4230 SetLastError(ERROR_BAD_LENGTH);
4231 return FALSE;
4233 break;
4235 case PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR:
4236 if (size != sizeof(PROCESSOR_NUMBER))
4238 SetLastError(ERROR_BAD_LENGTH);
4239 return FALSE;
4241 break;
4243 default:
4244 SetLastError(ERROR_NOT_SUPPORTED);
4245 return FALSE;
4248 mask = 1 << (attr & PROC_THREAD_ATTRIBUTE_NUMBER);
4250 if (list->mask & mask)
4252 SetLastError(ERROR_OBJECT_NAME_EXISTS);
4253 return FALSE;
4256 list->mask |= mask;
4258 entry = list->attrs + list->count;
4259 entry->attr = attr;
4260 entry->size = size;
4261 entry->value = value;
4262 list->count++;
4264 return TRUE;
4267 /***********************************************************************
4268 * DeleteProcThreadAttributeList (KERNEL32.@)
4270 void WINAPI DeleteProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list)
4272 return;
4275 /**********************************************************************
4276 * BaseFlushAppcompatCache (KERNEL32.@)
4278 BOOL WINAPI BaseFlushAppcompatCache(void)
4280 FIXME(": stub\n");
4281 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4282 return FALSE;