kernel32: Add a stub for RegisterApplicationRecoveryCallback.
[wine.git] / dlls / kernel32 / process.c
blob6b8ff9957b7231cb78cc10ae7e4b89eb6d624480
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>
45 #include "ntstatus.h"
46 #define WIN32_NO_STATUS
47 #include "winternl.h"
48 #include "kernel_private.h"
49 #include "psapi.h"
50 #include "wine/library.h"
51 #include "wine/server.h"
52 #include "wine/unicode.h"
53 #include "wine/debug.h"
55 WINE_DEFAULT_DEBUG_CHANNEL(process);
56 WINE_DECLARE_DEBUG_CHANNEL(file);
57 WINE_DECLARE_DEBUG_CHANNEL(relay);
59 #ifdef __APPLE__
60 #include <CoreFoundation/CoreFoundation.h>
61 #include <pthread.h>
62 #include <unistd.h>
63 extern char **__wine_get_main_environment(void);
64 #else
65 extern char **__wine_main_environ;
66 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
67 #endif
69 typedef struct
71 LPSTR lpEnvAddress;
72 LPSTR lpCmdLine;
73 LPSTR lpCmdShow;
74 DWORD dwReserved;
75 } LOADPARMS32;
77 static DWORD shutdown_flags = 0;
78 static DWORD shutdown_priority = 0x280;
79 static BOOL is_wow64;
80 static const int is_win64 = (sizeof(void *) > sizeof(int));
82 HMODULE kernel32_handle = 0;
84 const WCHAR *DIR_Windows = NULL;
85 const WCHAR *DIR_System = NULL;
86 const WCHAR *DIR_SysWow64 = NULL;
88 /* Process flags */
89 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
90 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
91 #define PDB32_DOS_PROC 0x0010 /* Dos process */
92 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
93 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
94 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
96 static const WCHAR exeW[] = {'.','e','x','e',0};
97 static const WCHAR comW[] = {'.','c','o','m',0};
98 static const WCHAR batW[] = {'.','b','a','t',0};
99 static const WCHAR cmdW[] = {'.','c','m','d',0};
100 static const WCHAR pifW[] = {'.','p','i','f',0};
101 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
103 static void exec_process( LPCWSTR name );
105 extern void SHELL_LoadRegistry(void);
108 /***********************************************************************
109 * contains_path
111 static inline int contains_path( LPCWSTR name )
113 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
117 /***********************************************************************
118 * is_special_env_var
120 * Check if an environment variable needs to be handled specially when
121 * passed through the Unix environment (i.e. prefixed with "WINE").
123 static inline int is_special_env_var( const char *var )
125 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
126 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
127 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
128 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
129 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
133 /***********************************************************************
134 * is_path_prefix
136 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
138 unsigned int len = strlenW( prefix );
140 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
141 while (filename[len] == '\\') len++;
142 return len;
146 /***************************************************************************
147 * get_builtin_path
149 * Get the path of a builtin module when the native file does not exist.
151 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
152 UINT size, struct binary_info *binary_info )
154 WCHAR *file_part;
155 UINT len;
156 void *redir_disabled = 0;
157 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
159 /* builtin names cannot be empty or contain spaces */
160 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
162 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
163 Wow64RevertWow64FsRedirection( redir_disabled );
165 if (contains_path( libname ))
167 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
168 filename, &file_part ) > size * sizeof(WCHAR))
169 return FALSE; /* too long */
171 if ((len = is_path_prefix( DIR_System, filename )))
173 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
175 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
177 flags = 0;
179 else return FALSE;
181 if (filename + len != file_part) return FALSE;
183 else
185 len = strlenW( DIR_System );
186 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
187 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
188 file_part = filename + len;
189 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
190 strcpyW( file_part, libname );
191 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
193 if (ext && !strchrW( file_part, '.' ))
195 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
196 return FALSE; /* too long */
197 strcatW( file_part, ext );
199 binary_info->type = BINARY_UNIX_LIB;
200 binary_info->flags = flags;
201 binary_info->res_start = NULL;
202 binary_info->res_end = NULL;
203 return TRUE;
207 /***********************************************************************
208 * open_exe_file
210 * Open a specific exe file, taking load order into account.
211 * Returns the file handle or 0 for a builtin exe.
213 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
215 HANDLE handle;
217 TRACE("looking for %s\n", debugstr_w(name) );
219 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
220 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
222 WCHAR buffer[MAX_PATH];
223 /* file doesn't exist, check for builtin */
224 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
225 handle = 0;
227 else MODULE_get_binary_info( handle, binary_info );
229 return handle;
233 /***********************************************************************
234 * find_exe_file
236 * Open an exe file, and return the full name and file handle.
237 * Returns FALSE if file could not be found.
238 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
239 * If file is a builtin exe, returns TRUE and sets handle to 0.
241 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
242 HANDLE *handle, struct binary_info *binary_info )
244 TRACE("looking for %s\n", debugstr_w(name) );
246 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ))
248 if (contains_path( name ) && get_builtin_path( name, exeW, buffer, buflen, binary_info ))
250 *handle = 0;
251 return TRUE;
253 /* no builtin found, try native without extension in case it is a Unix app */
254 if (!SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
257 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
258 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
259 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
261 MODULE_get_binary_info( *handle, binary_info );
262 return TRUE;
264 return FALSE;
268 /***********************************************************************
269 * build_initial_environment
271 * Build the Win32 environment from the Unix environment
273 static BOOL build_initial_environment(void)
275 SIZE_T size = 1;
276 char **e;
277 WCHAR *p, *endptr;
278 void *ptr;
279 char **env = __wine_get_main_environment();
281 /* Compute the total size of the Unix environment */
282 for (e = env; *e; e++)
284 if (is_special_env_var( *e )) continue;
285 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
287 size *= sizeof(WCHAR);
289 /* Now allocate the environment */
290 ptr = NULL;
291 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
292 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
293 return FALSE;
295 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
296 endptr = p + size / sizeof(WCHAR);
298 /* And fill it with the Unix environment */
299 for (e = env; *e; e++)
301 char *str = *e;
303 /* skip Unix special variables and use the Wine variants instead */
304 if (!strncmp( str, "WINE", 4 ))
306 if (is_special_env_var( str + 4 )) str += 4;
307 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
309 else if (is_special_env_var( str )) continue; /* skip it */
311 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
312 p += strlenW(p) + 1;
314 *p = 0;
315 return TRUE;
319 /***********************************************************************
320 * set_registry_variables
322 * Set environment variables by enumerating the values of a key;
323 * helper for set_registry_environment().
324 * Note that Windows happily truncates the value if it's too big.
326 static void set_registry_variables( HANDLE hkey, ULONG type )
328 static const WCHAR pathW[] = {'P','A','T','H'};
329 static const WCHAR sep[] = {';',0};
330 UNICODE_STRING env_name, env_value;
331 NTSTATUS status;
332 DWORD size;
333 int index;
334 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
335 WCHAR tmpbuf[1024];
336 UNICODE_STRING tmp;
337 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
339 tmp.Buffer = tmpbuf;
340 tmp.MaximumLength = sizeof(tmpbuf);
342 for (index = 0; ; index++)
344 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
345 buffer, sizeof(buffer), &size );
346 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
347 break;
348 if (info->Type != type)
349 continue;
350 env_name.Buffer = info->Name;
351 env_name.Length = env_name.MaximumLength = info->NameLength;
352 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
353 env_value.Length = info->DataLength;
354 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
355 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
356 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
357 if (!env_value.Length) continue;
358 if (info->Type == REG_EXPAND_SZ)
360 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
361 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
362 RtlCopyUnicodeString( &env_value, &tmp );
364 /* PATH is magic */
365 if (env_name.Length == sizeof(pathW) &&
366 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
367 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
369 RtlAppendUnicodeToString( &tmp, sep );
370 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
371 RtlCopyUnicodeString( &env_value, &tmp );
373 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
378 /***********************************************************************
379 * set_registry_environment
381 * Set the environment variables specified in the registry.
383 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
384 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
385 * on the order in which the variables are processed. But on Windows it
386 * does not really matter since they only use %SystemDrive% and
387 * %SystemRoot% which are predefined. But Wine defines these in the
388 * registry, so we need two passes.
390 static BOOL set_registry_environment( BOOL volatile_only )
392 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
393 'S','y','s','t','e','m','\\',
394 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
395 'C','o','n','t','r','o','l','\\',
396 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
397 'E','n','v','i','r','o','n','m','e','n','t',0};
398 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
399 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};
401 OBJECT_ATTRIBUTES attr;
402 UNICODE_STRING nameW;
403 HANDLE hkey;
404 BOOL ret = FALSE;
406 attr.Length = sizeof(attr);
407 attr.RootDirectory = 0;
408 attr.ObjectName = &nameW;
409 attr.Attributes = 0;
410 attr.SecurityDescriptor = NULL;
411 attr.SecurityQualityOfService = NULL;
413 /* first the system environment variables */
414 RtlInitUnicodeString( &nameW, env_keyW );
415 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
417 set_registry_variables( hkey, REG_SZ );
418 set_registry_variables( hkey, REG_EXPAND_SZ );
419 NtClose( hkey );
420 ret = TRUE;
423 /* then the ones for the current user */
424 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
425 RtlInitUnicodeString( &nameW, envW );
426 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
428 set_registry_variables( hkey, REG_SZ );
429 set_registry_variables( hkey, REG_EXPAND_SZ );
430 NtClose( hkey );
433 RtlInitUnicodeString( &nameW, volatile_envW );
434 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
436 set_registry_variables( hkey, REG_SZ );
437 set_registry_variables( hkey, REG_EXPAND_SZ );
438 NtClose( hkey );
441 NtClose( attr.RootDirectory );
442 return ret;
446 /***********************************************************************
447 * get_reg_value
449 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
451 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
452 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
453 DWORD len, size = sizeof(buffer);
454 WCHAR *ret = NULL;
455 UNICODE_STRING nameW;
457 RtlInitUnicodeString( &nameW, name );
458 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
459 return NULL;
461 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
462 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
464 if (info->Type == REG_EXPAND_SZ)
466 UNICODE_STRING value, expanded;
468 value.MaximumLength = len * sizeof(WCHAR);
469 value.Buffer = (WCHAR *)info->Data;
470 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
471 value.Length = len * sizeof(WCHAR);
472 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
473 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
474 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
475 else RtlFreeUnicodeString( &expanded );
477 else if (info->Type == REG_SZ)
479 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
481 memcpy( ret, info->Data, len * sizeof(WCHAR) );
482 ret[len] = 0;
485 return ret;
489 /***********************************************************************
490 * set_additional_environment
492 * Set some additional environment variables not specified in the registry.
494 static void set_additional_environment(void)
496 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
497 'S','o','f','t','w','a','r','e','\\',
498 'M','i','c','r','o','s','o','f','t','\\',
499 'W','i','n','d','o','w','s',' ','N','T','\\',
500 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
501 'P','r','o','f','i','l','e','L','i','s','t',0};
502 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
503 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
504 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
505 OBJECT_ATTRIBUTES attr;
506 UNICODE_STRING nameW;
507 WCHAR *profile_dir = NULL, *all_users_dir = NULL;
508 HANDLE hkey;
509 DWORD len;
511 /* set the ALLUSERSPROFILE variables */
513 attr.Length = sizeof(attr);
514 attr.RootDirectory = 0;
515 attr.ObjectName = &nameW;
516 attr.Attributes = 0;
517 attr.SecurityDescriptor = NULL;
518 attr.SecurityQualityOfService = NULL;
519 RtlInitUnicodeString( &nameW, profile_keyW );
520 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
522 profile_dir = get_reg_value( hkey, profiles_valueW );
523 all_users_dir = get_reg_value( hkey, all_users_valueW );
524 NtClose( hkey );
527 if (profile_dir && all_users_dir)
529 WCHAR *value, *p;
531 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
532 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
533 strcpyW( value, profile_dir );
534 p = value + strlenW(value);
535 if (p > value && p[-1] != '\\') *p++ = '\\';
536 strcpyW( p, all_users_dir );
537 SetEnvironmentVariableW( allusersW, value );
538 HeapFree( GetProcessHeap(), 0, value );
541 HeapFree( GetProcessHeap(), 0, all_users_dir );
542 HeapFree( GetProcessHeap(), 0, profile_dir );
545 /***********************************************************************
546 * set_wow64_environment
548 * Set the environment variables that change across 32/64/Wow64.
550 static void set_wow64_environment(void)
552 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};
553 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};
554 static const WCHAR x86W[] = {'x','8','6',0};
555 static const WCHAR versionW[] = {'M','a','c','h','i','n','e','\\',
556 'S','o','f','t','w','a','r','e','\\',
557 'M','i','c','r','o','s','o','f','t','\\',
558 'W','i','n','d','o','w','s','\\',
559 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
560 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
561 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
562 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
563 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
564 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
565 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
566 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
567 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
569 OBJECT_ATTRIBUTES attr;
570 UNICODE_STRING nameW;
571 WCHAR arch[64];
572 WCHAR *value;
573 HANDLE hkey;
575 /* set the PROCESSOR_ARCHITECTURE variable */
577 if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
579 if (is_win64)
581 SetEnvironmentVariableW( archW, arch );
582 SetEnvironmentVariableW( arch6432W, NULL );
585 else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
587 if (is_wow64)
589 SetEnvironmentVariableW( arch6432W, arch );
590 SetEnvironmentVariableW( archW, x86W );
594 attr.Length = sizeof(attr);
595 attr.RootDirectory = 0;
596 attr.ObjectName = &nameW;
597 attr.Attributes = 0;
598 attr.SecurityDescriptor = NULL;
599 attr.SecurityQualityOfService = NULL;
600 RtlInitUnicodeString( &nameW, versionW );
601 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
603 /* set the ProgramFiles variables */
605 if ((value = get_reg_value( hkey, progdirW )))
607 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
608 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
609 HeapFree( GetProcessHeap(), 0, value );
611 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
613 SetEnvironmentVariableW( progfilesW, value );
614 HeapFree( GetProcessHeap(), 0, value );
617 /* set the CommonProgramFiles variables */
619 if ((value = get_reg_value( hkey, commondirW )))
621 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
622 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
623 HeapFree( GetProcessHeap(), 0, value );
625 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
627 SetEnvironmentVariableW( commonfilesW, value );
628 HeapFree( GetProcessHeap(), 0, value );
631 NtClose( hkey );
634 /***********************************************************************
635 * set_library_wargv
637 * Set the Wine library Unicode argv global variables.
639 static void set_library_wargv( char **argv )
641 int argc;
642 char *q;
643 WCHAR *p;
644 WCHAR **wargv;
645 DWORD total = 0;
647 for (argc = 0; argv[argc]; argc++)
648 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
650 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
651 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
652 p = (WCHAR *)(wargv + argc + 1);
653 for (argc = 0; argv[argc]; argc++)
655 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
656 wargv[argc] = p;
657 p += reslen;
658 total -= reslen;
660 wargv[argc] = NULL;
662 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
664 for (argc = 0; wargv[argc]; argc++)
665 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
667 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
668 q = (char *)(argv + argc + 1);
669 for (argc = 0; wargv[argc]; argc++)
671 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
672 argv[argc] = q;
673 q += reslen;
674 total -= reslen;
676 argv[argc] = NULL;
678 __wine_main_argc = argc;
679 __wine_main_argv = argv;
680 __wine_main_wargv = wargv;
684 /***********************************************************************
685 * update_library_argv0
687 * Update the argv[0] global variable with the binary we have found.
689 static void update_library_argv0( const WCHAR *argv0 )
691 DWORD len = strlenW( argv0 );
693 if (len > strlenW( __wine_main_wargv[0] ))
695 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
697 strcpyW( __wine_main_wargv[0], argv0 );
699 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
700 if (len > strlen( __wine_main_argv[0] ) + 1)
702 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
704 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
708 /***********************************************************************
709 * build_command_line
711 * Build the command line of a process from the argv array.
713 * Note that it does NOT necessarily include the file name.
714 * Sometimes we don't even have any command line options at all.
716 * We must quote and escape characters so that the argv array can be rebuilt
717 * from the command line:
718 * - spaces and tabs must be quoted
719 * 'a b' -> '"a b"'
720 * - quotes must be escaped
721 * '"' -> '\"'
722 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
723 * resulting in an odd number of '\' followed by a '"'
724 * '\"' -> '\\\"'
725 * '\\"' -> '\\\\\"'
726 * - '\'s that are not followed by a '"' can be left as is
727 * 'a\b' == 'a\b'
728 * 'a\\b' == 'a\\b'
730 static BOOL build_command_line( WCHAR **argv )
732 int len;
733 WCHAR **arg;
734 LPWSTR p;
735 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
737 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
739 len = 0;
740 for (arg = argv; *arg; arg++)
742 int has_space,bcount;
743 WCHAR* a;
745 has_space=0;
746 bcount=0;
747 a=*arg;
748 if( !*a ) has_space=1;
749 while (*a!='\0') {
750 if (*a=='\\') {
751 bcount++;
752 } else {
753 if (*a==' ' || *a=='\t') {
754 has_space=1;
755 } else if (*a=='"') {
756 /* doubling of '\' preceding a '"',
757 * plus escaping of said '"'
759 len+=2*bcount+1;
761 bcount=0;
763 a++;
765 len+=(a-*arg)+1 /* for the separating space */;
766 if (has_space)
767 len+=2; /* for the quotes */
770 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
771 return FALSE;
773 p = rupp->CommandLine.Buffer;
774 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
775 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
776 for (arg = argv; *arg; arg++)
778 int has_space,has_quote;
779 WCHAR* a;
781 /* Check for quotes and spaces in this argument */
782 has_space=has_quote=0;
783 a=*arg;
784 if( !*a ) has_space=1;
785 while (*a!='\0') {
786 if (*a==' ' || *a=='\t') {
787 has_space=1;
788 if (has_quote)
789 break;
790 } else if (*a=='"') {
791 has_quote=1;
792 if (has_space)
793 break;
795 a++;
798 /* Now transfer it to the command line */
799 if (has_space)
800 *p++='"';
801 if (has_quote) {
802 int bcount;
803 WCHAR* a;
805 bcount=0;
806 a=*arg;
807 while (*a!='\0') {
808 if (*a=='\\') {
809 *p++=*a;
810 bcount++;
811 } else {
812 if (*a=='"') {
813 int i;
815 /* Double all the '\\' preceding this '"', plus one */
816 for (i=0;i<=bcount;i++)
817 *p++='\\';
818 *p++='"';
819 } else {
820 *p++=*a;
822 bcount=0;
824 a++;
826 } else {
827 WCHAR* x = *arg;
828 while ((*p=*x++)) p++;
830 if (has_space)
831 *p++='"';
832 *p++=' ';
834 if (p > rupp->CommandLine.Buffer)
835 p--; /* remove last space */
836 *p = '\0';
838 return TRUE;
842 /***********************************************************************
843 * init_current_directory
845 * Initialize the current directory from the Unix cwd or the parent info.
847 static void init_current_directory( CURDIR *cur_dir )
849 UNICODE_STRING dir_str;
850 const char *pwd;
851 char *cwd;
852 int size;
854 /* if we received a cur dir from the parent, try this first */
856 if (cur_dir->DosPath.Length)
858 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
861 /* now try to get it from the Unix cwd */
863 for (size = 256; ; size *= 2)
865 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
866 if (getcwd( cwd, size )) break;
867 HeapFree( GetProcessHeap(), 0, cwd );
868 if (errno == ERANGE) continue;
869 cwd = NULL;
870 break;
873 /* try to use PWD if it is valid, so that we don't resolve symlinks */
875 pwd = getenv( "PWD" );
876 if (cwd)
878 struct stat st1, st2;
880 if (!pwd || stat( pwd, &st1 ) == -1 ||
881 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
882 pwd = cwd;
885 if (pwd)
887 ANSI_STRING unix_name;
888 UNICODE_STRING nt_name;
889 RtlInitAnsiString( &unix_name, pwd );
890 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
892 UNICODE_STRING dos_path;
893 /* skip the \??\ prefix, nt_name is 0 terminated */
894 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
895 RtlSetCurrentDirectory_U( &dos_path );
896 RtlFreeUnicodeString( &nt_name );
900 if (!cur_dir->DosPath.Length) /* still not initialized */
902 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
903 "starting in the Windows directory.\n", cwd ? cwd : "" );
904 RtlInitUnicodeString( &dir_str, DIR_Windows );
905 RtlSetCurrentDirectory_U( &dir_str );
907 HeapFree( GetProcessHeap(), 0, cwd );
909 done:
910 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
911 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
915 /***********************************************************************
916 * init_windows_dirs
918 * Initialize the windows and system directories from the environment.
920 static void init_windows_dirs(void)
922 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
924 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
925 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
926 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
927 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
928 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
930 DWORD len;
931 WCHAR *buffer;
933 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
935 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
936 GetEnvironmentVariableW( windirW, buffer, len );
937 DIR_Windows = buffer;
939 else DIR_Windows = default_windirW;
941 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
943 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
944 GetEnvironmentVariableW( winsysdirW, buffer, len );
945 DIR_System = buffer;
947 else
949 len = strlenW( DIR_Windows );
950 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
951 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
952 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
953 DIR_System = buffer;
956 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
957 ERR( "directory %s could not be created, error %u\n",
958 debugstr_w(DIR_Windows), GetLastError() );
959 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
960 ERR( "directory %s could not be created, error %u\n",
961 debugstr_w(DIR_System), GetLastError() );
963 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
965 len = strlenW( DIR_Windows );
966 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
967 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
968 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
969 DIR_SysWow64 = buffer;
970 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
971 ERR( "directory %s could not be created, error %u\n",
972 debugstr_w(DIR_SysWow64), GetLastError() );
975 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
976 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
978 /* set the directories in ntdll too */
979 __wine_init_windows_dir( DIR_Windows, DIR_System );
983 /***********************************************************************
984 * start_wineboot
986 * Start the wineboot process if necessary. Return the handles to wait on.
988 static void start_wineboot( HANDLE handles[2] )
990 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
992 handles[1] = 0;
993 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
995 ERR( "failed to create wineboot event, expect trouble\n" );
996 return;
998 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
1000 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1001 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1002 STARTUPINFOW si;
1003 PROCESS_INFORMATION pi;
1004 void *redir;
1005 WCHAR app[MAX_PATH];
1006 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1008 memset( &si, 0, sizeof(si) );
1009 si.cb = sizeof(si);
1010 si.dwFlags = STARTF_USESTDHANDLES;
1011 si.hStdInput = 0;
1012 si.hStdOutput = 0;
1013 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1015 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1016 lstrcatW( app, wineboot );
1018 Wow64DisableWow64FsRedirection( &redir );
1019 strcpyW( cmdline, app );
1020 strcatW( cmdline, args );
1021 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1023 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1024 CloseHandle( pi.hThread );
1025 handles[1] = pi.hProcess;
1027 else
1029 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1030 CloseHandle( handles[0] );
1031 handles[0] = 0;
1033 Wow64RevertWow64FsRedirection( redir );
1038 #ifdef __i386__
1039 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1040 __ASM_GLOBAL_FUNC( call_process_entry,
1041 "pushl %ebp\n\t"
1042 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1043 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1044 "movl %esp,%ebp\n\t"
1045 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1046 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1047 "pushl 8(%ebp)\n\t"
1048 "call *12(%ebp)\n\t"
1049 "leave\n\t"
1050 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1051 __ASM_CFI(".cfi_same_value %ebp\n\t")
1052 "ret" )
1053 #else
1054 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1056 return entry( peb );
1058 #endif
1060 /***********************************************************************
1061 * start_process
1063 * Startup routine of a new process. Runs on the new process stack.
1065 static DWORD WINAPI start_process( PEB *peb )
1067 IMAGE_NT_HEADERS *nt;
1068 LPTHREAD_START_ROUTINE entry;
1070 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1071 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1072 nt->OptionalHeader.AddressOfEntryPoint);
1074 if (!nt->OptionalHeader.AddressOfEntryPoint)
1076 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1077 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1078 ExitThread( 1 );
1081 if (TRACE_ON(relay))
1082 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1083 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1085 SetLastError( 0 ); /* clear error code */
1086 if (peb->BeingDebugged) DbgBreakPoint();
1087 return call_process_entry( peb, entry );
1091 /***********************************************************************
1092 * set_process_name
1094 * Change the process name in the ps output.
1096 static void set_process_name( int argc, char *argv[] )
1098 #ifdef HAVE_SETPROCTITLE
1099 setproctitle("-%s", argv[1]);
1100 #endif
1102 #ifdef HAVE_PRCTL
1103 int i, offset;
1104 char *p, *prctl_name = argv[1];
1105 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1107 #ifndef PR_SET_NAME
1108 # define PR_SET_NAME 15
1109 #endif
1111 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1112 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1114 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1116 offset = argv[1] - argv[0];
1117 memmove( argv[1] - offset, argv[1], end - argv[1] );
1118 memset( end - offset, 0, offset );
1119 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1120 argv[i-1] = NULL;
1122 else
1123 #endif /* HAVE_PRCTL */
1125 /* remove argv[0] */
1126 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1131 /***********************************************************************
1132 * __wine_kernel_init
1134 * Wine initialisation: load and start the main exe file.
1136 void CDECL __wine_kernel_init(void)
1138 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1139 static const WCHAR dotW[] = {'.',0};
1141 WCHAR *p, main_exe_name[MAX_PATH+1];
1142 PEB *peb = NtCurrentTeb()->Peb;
1143 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1144 HANDLE boot_events[2];
1145 BOOL got_environment = TRUE;
1147 /* Initialize everything */
1149 setbuf(stdout,NULL);
1150 setbuf(stderr,NULL);
1151 kernel32_handle = GetModuleHandleW(kernel32W);
1152 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1154 LOCALE_Init();
1156 if (!params->Environment)
1158 /* Copy the parent environment */
1159 if (!build_initial_environment()) exit(1);
1161 /* convert old configuration to new format */
1162 convert_old_config();
1164 got_environment = set_registry_environment( FALSE );
1165 set_additional_environment();
1168 init_windows_dirs();
1169 init_current_directory( &params->CurrentDirectory );
1171 set_process_name( __wine_main_argc, __wine_main_argv );
1172 set_library_wargv( __wine_main_argv );
1173 boot_events[0] = boot_events[1] = 0;
1175 if (peb->ProcessParameters->ImagePathName.Buffer)
1177 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1179 else
1181 struct binary_info binary_info;
1183 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1184 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1186 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1187 ExitProcess( GetLastError() );
1189 update_library_argv0( main_exe_name );
1190 if (!build_command_line( __wine_main_wargv )) goto error;
1191 start_wineboot( boot_events );
1194 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1195 p = strrchrW( main_exe_name, '.' );
1196 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1198 TRACE( "starting process name=%s argv[0]=%s\n",
1199 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1201 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1202 MODULE_get_dll_load_path(main_exe_name) );
1204 if (boot_events[0])
1206 DWORD timeout = 2 * 60 * 1000, count = 1;
1208 if (boot_events[1]) count++;
1209 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1210 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1211 ERR( "boot event wait timed out\n" );
1212 CloseHandle( boot_events[0] );
1213 if (boot_events[1]) CloseHandle( boot_events[1] );
1214 /* reload environment now that wineboot has run */
1215 set_registry_environment( got_environment );
1216 set_additional_environment();
1218 set_wow64_environment();
1220 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1222 DWORD_PTR args[1];
1223 WCHAR msgW[1024];
1224 char msg[1024];
1225 DWORD error = GetLastError();
1227 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1228 if (error == ERROR_BAD_EXE_FORMAT ||
1229 error == ERROR_INVALID_ADDRESS ||
1230 error == ERROR_NOT_ENOUGH_MEMORY)
1232 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1233 /* if we get back here, it failed */
1235 else if (error == ERROR_MOD_NOT_FOUND)
1237 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1238 else p = main_exe_name;
1239 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1241 /* args 1 and 2 are --app-name full_path */
1242 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1243 debugstr_w(__wine_main_wargv[3]) );
1244 ExitProcess( ERROR_BAD_EXE_FORMAT );
1246 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1247 ExitProcess( ERROR_FILE_NOT_FOUND );
1249 args[0] = (DWORD_PTR)main_exe_name;
1250 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1251 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1252 WideCharToMultiByte( CP_ACP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1253 MESSAGE( "wine: %s", msg );
1254 ExitProcess( error );
1257 LdrInitializeThunk( start_process, 0, 0, 0 );
1259 error:
1260 ExitProcess( GetLastError() );
1264 /***********************************************************************
1265 * build_argv
1267 * Build an argv array from a command-line.
1268 * 'reserved' is the number of args to reserve before the first one.
1270 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1272 int argc;
1273 char** argv;
1274 char *arg,*s,*d,*cmdline;
1275 int in_quotes,bcount,len;
1277 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1278 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1279 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1281 argc=reserved+1;
1282 bcount=0;
1283 in_quotes=0;
1284 s=cmdline;
1285 while (1) {
1286 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1287 /* space */
1288 argc++;
1289 /* skip the remaining spaces */
1290 while (*s==' ' || *s=='\t') {
1291 s++;
1293 if (*s=='\0')
1294 break;
1295 bcount=0;
1296 continue;
1297 } else if (*s=='\\') {
1298 /* '\', count them */
1299 bcount++;
1300 } else if ((*s=='"') && ((bcount & 1)==0)) {
1301 /* unescaped '"' */
1302 in_quotes=!in_quotes;
1303 bcount=0;
1304 } else {
1305 /* a regular character */
1306 bcount=0;
1308 s++;
1310 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1312 HeapFree( GetProcessHeap(), 0, cmdline );
1313 return NULL;
1316 arg = d = s = (char *)(argv + argc);
1317 memcpy( d, cmdline, len );
1318 bcount=0;
1319 in_quotes=0;
1320 argc=reserved;
1321 while (*s) {
1322 if ((*s==' ' || *s=='\t') && !in_quotes) {
1323 /* Close the argument and copy it */
1324 *d=0;
1325 argv[argc++]=arg;
1327 /* skip the remaining spaces */
1328 do {
1329 s++;
1330 } while (*s==' ' || *s=='\t');
1332 /* Start with a new argument */
1333 arg=d=s;
1334 bcount=0;
1335 } else if (*s=='\\') {
1336 /* '\\' */
1337 *d++=*s++;
1338 bcount++;
1339 } else if (*s=='"') {
1340 /* '"' */
1341 if ((bcount & 1)==0) {
1342 /* Preceded by an even number of '\', this is half that
1343 * number of '\', plus a '"' which we discard.
1345 d-=bcount/2;
1346 s++;
1347 in_quotes=!in_quotes;
1348 } else {
1349 /* Preceded by an odd number of '\', this is half that
1350 * number of '\' followed by a '"'
1352 d=d-bcount/2-1;
1353 *d++='"';
1354 s++;
1356 bcount=0;
1357 } else {
1358 /* a regular character */
1359 *d++=*s++;
1360 bcount=0;
1363 if (*arg) {
1364 *d='\0';
1365 argv[argc++]=arg;
1367 argv[argc]=NULL;
1369 HeapFree( GetProcessHeap(), 0, cmdline );
1370 return argv;
1374 /***********************************************************************
1375 * build_envp
1377 * Build the environment of a new child process.
1379 static char **build_envp( const WCHAR *envW )
1381 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1383 const WCHAR *end;
1384 char **envp;
1385 char *env, *p;
1386 int count = 1, length;
1387 unsigned int i;
1389 for (end = envW; *end; count++) end += strlenW(end) + 1;
1390 end++;
1391 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1392 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1393 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1395 for (p = env; *p; p += strlen(p) + 1)
1396 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1398 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1400 if (!(p = getenv(unix_vars[i]))) continue;
1401 length += strlen(unix_vars[i]) + strlen(p) + 2;
1402 count++;
1405 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1407 char **envptr = envp;
1408 char *dst = (char *)(envp + count);
1410 /* some variables must not be modified, so we get them directly from the unix env */
1411 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1413 if (!(p = getenv(unix_vars[i]))) continue;
1414 *envptr++ = strcpy( dst, unix_vars[i] );
1415 strcat( dst, "=" );
1416 strcat( dst, p );
1417 dst += strlen(dst) + 1;
1420 /* now put the Windows environment strings */
1421 for (p = env; *p; p += strlen(p) + 1)
1423 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1424 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1425 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1426 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1427 if (is_special_env_var( p )) /* prefix it with "WINE" */
1429 *envptr++ = strcpy( dst, "WINE" );
1430 strcat( dst, p );
1432 else
1434 *envptr++ = strcpy( dst, p );
1436 dst += strlen(dst) + 1;
1438 *envptr = 0;
1440 HeapFree( GetProcessHeap(), 0, env );
1441 return envp;
1445 /***********************************************************************
1446 * fork_and_exec
1448 * Fork and exec a new Unix binary, checking for errors.
1450 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1451 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1453 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1454 int pid, err;
1455 char **argv, **envp;
1457 if (!env) env = GetEnvironmentStringsW();
1459 #ifdef HAVE_PIPE2
1460 if (pipe2( fd, O_CLOEXEC ) == -1)
1461 #endif
1463 if (pipe(fd) == -1)
1465 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1466 return -1;
1468 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1469 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1472 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1474 HANDLE hstdin, hstdout, hstderr;
1476 if (startup->dwFlags & STARTF_USESTDHANDLES)
1478 hstdin = startup->hStdInput;
1479 hstdout = startup->hStdOutput;
1480 hstderr = startup->hStdError;
1482 else
1484 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1485 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1486 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1489 if (is_console_handle( hstdin ))
1490 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1491 if (is_console_handle( hstdout ))
1492 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1493 if (is_console_handle( hstderr ))
1494 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1495 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1496 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1497 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1500 argv = build_argv( cmdline, 0 );
1501 envp = build_envp( env );
1503 if (!(pid = fork())) /* child */
1505 close( fd[0] );
1507 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1509 int pid;
1510 if (!(pid = fork()))
1512 int fd = open( "/dev/null", O_RDWR );
1513 setsid();
1514 /* close stdin and stdout */
1515 if (fd != -1)
1517 dup2( fd, 0 );
1518 dup2( fd, 1 );
1519 close( fd );
1522 else if (pid != -1) _exit(0); /* parent */
1524 else
1526 if (stdin_fd != -1)
1528 dup2( stdin_fd, 0 );
1529 close( stdin_fd );
1531 if (stdout_fd != -1)
1533 dup2( stdout_fd, 1 );
1534 close( stdout_fd );
1536 if (stderr_fd != -1)
1538 dup2( stderr_fd, 2 );
1539 close( stderr_fd );
1543 /* Reset signals that we previously set to SIG_IGN */
1544 signal( SIGPIPE, SIG_DFL );
1545 signal( SIGCHLD, SIG_DFL );
1547 if (newdir) chdir(newdir);
1549 if (argv && envp) execve( filename, argv, envp );
1550 err = errno;
1551 write( fd[1], &err, sizeof(err) );
1552 _exit(1);
1554 HeapFree( GetProcessHeap(), 0, argv );
1555 HeapFree( GetProcessHeap(), 0, envp );
1556 if (stdin_fd != -1) close( stdin_fd );
1557 if (stdout_fd != -1) close( stdout_fd );
1558 if (stderr_fd != -1) close( stderr_fd );
1559 close( fd[1] );
1560 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1562 errno = err;
1563 pid = -1;
1565 if (pid == -1) FILE_SetDosError();
1566 close( fd[0] );
1567 return pid;
1571 static inline DWORD append_string( void **ptr, const WCHAR *str )
1573 DWORD len = strlenW( str );
1574 memcpy( *ptr, str, len * sizeof(WCHAR) );
1575 *ptr = (WCHAR *)*ptr + len;
1576 return len * sizeof(WCHAR);
1579 /***********************************************************************
1580 * create_startup_info
1582 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1583 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1584 const STARTUPINFOW *startup, DWORD *info_size )
1586 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1587 const WCHAR *title;
1588 startup_info_t *info;
1589 DWORD size;
1590 void *ptr;
1591 UNICODE_STRING newdir;
1592 WCHAR imagepath[MAX_PATH];
1593 HANDLE hstdin, hstdout, hstderr;
1595 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1596 lstrcpynW( imagepath, filename, MAX_PATH );
1597 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1598 lstrcpynW( imagepath, filename, MAX_PATH );
1600 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1602 newdir.Buffer = NULL;
1603 if (cur_dir)
1605 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1606 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1607 else
1608 cur_dir = NULL;
1610 if (!cur_dir)
1612 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1613 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1614 else
1615 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1617 title = startup->lpTitle ? startup->lpTitle : imagepath;
1619 size = sizeof(*info);
1620 size += strlenW( cur_dir ) * sizeof(WCHAR);
1621 size += cur_params->DllPath.Length;
1622 size += strlenW( imagepath ) * sizeof(WCHAR);
1623 size += strlenW( cmdline ) * sizeof(WCHAR);
1624 size += strlenW( title ) * sizeof(WCHAR);
1625 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1626 /* FIXME: shellinfo */
1627 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1628 size = (size + 1) & ~1;
1629 *info_size = size;
1631 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1633 info->console_flags = cur_params->ConsoleFlags;
1634 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1635 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1637 if (startup->dwFlags & STARTF_USESTDHANDLES)
1639 hstdin = startup->hStdInput;
1640 hstdout = startup->hStdOutput;
1641 hstderr = startup->hStdError;
1643 else
1645 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1646 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1647 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1649 info->hstdin = wine_server_obj_handle( hstdin );
1650 info->hstdout = wine_server_obj_handle( hstdout );
1651 info->hstderr = wine_server_obj_handle( hstderr );
1652 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1654 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1655 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1656 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1657 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1659 else
1661 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1662 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1663 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1666 info->x = startup->dwX;
1667 info->y = startup->dwY;
1668 info->xsize = startup->dwXSize;
1669 info->ysize = startup->dwYSize;
1670 info->xchars = startup->dwXCountChars;
1671 info->ychars = startup->dwYCountChars;
1672 info->attribute = startup->dwFillAttribute;
1673 info->flags = startup->dwFlags;
1674 info->show = startup->wShowWindow;
1676 ptr = info + 1;
1677 info->curdir_len = append_string( &ptr, cur_dir );
1678 info->dllpath_len = cur_params->DllPath.Length;
1679 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1680 ptr = (char *)ptr + cur_params->DllPath.Length;
1681 info->imagepath_len = append_string( &ptr, imagepath );
1682 info->cmdline_len = append_string( &ptr, cmdline );
1683 info->title_len = append_string( &ptr, title );
1684 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1685 if (startup->lpReserved2 && startup->cbReserved2)
1687 info->runtime_len = startup->cbReserved2;
1688 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1691 done:
1692 RtlFreeUnicodeString( &newdir );
1693 return info;
1696 /***********************************************************************
1697 * get_alternate_loader
1699 * Get the name of the alternate (32 or 64 bit) Wine loader.
1701 static const char *get_alternate_loader( char **ret_env )
1703 char *env;
1704 const char *loader = NULL;
1705 const char *loader_env = getenv( "WINELOADER" );
1707 *ret_env = NULL;
1709 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1711 if (loader_env)
1713 int len = strlen( loader_env );
1714 if (!is_win64)
1716 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1717 strcpy( env, "WINELOADER=" );
1718 strcat( env, loader_env );
1719 strcat( env, "64" );
1721 else
1723 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1724 strcpy( env, "WINELOADER=" );
1725 strcat( env, loader_env );
1726 len += sizeof("WINELOADER=") - 1;
1727 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1729 if (!loader)
1731 if ((loader = strrchr( env, '/' ))) loader++;
1732 else loader = env;
1734 *ret_env = env;
1736 if (!loader) loader = is_win64 ? "wine" : "wine64";
1737 return loader;
1740 #ifdef __APPLE__
1741 /***********************************************************************
1742 * terminate_main_thread
1744 * On some versions of Mac OS X, the execve system call fails with
1745 * ENOTSUP if the process has multiple threads. Wine is always multi-
1746 * threaded on Mac OS X because it specifically reserves the main thread
1747 * for use by the system frameworks (see apple_main_thread() in
1748 * libs/wine/loader.c). So, when we need to exec without first forking,
1749 * we need to terminate the main thread first. We do this by installing
1750 * a custom run loop source onto the main run loop and signaling it.
1751 * The source's "perform" callback is pthread_exit and it will be
1752 * executed on the main thread, terminating it.
1754 * Returns TRUE if there's still hope the main thread has terminated or
1755 * will soon. Return FALSE if we've given up.
1757 static BOOL terminate_main_thread(void)
1759 static int delayms;
1761 if (!delayms)
1763 CFRunLoopSourceContext source_context = { 0 };
1764 CFRunLoopSourceRef source;
1766 source_context.perform = pthread_exit;
1767 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1768 return FALSE;
1770 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1771 CFRunLoopSourceSignal( source );
1772 CFRunLoopWakeUp( CFRunLoopGetMain() );
1773 CFRelease( source );
1775 delayms = 20;
1778 if (delayms > 1000)
1779 return FALSE;
1781 usleep(delayms * 1000);
1782 delayms *= 2;
1784 return TRUE;
1786 #endif
1788 /***********************************************************************
1789 * create_process
1791 * Create a new process. If hFile is a valid handle we have an exe
1792 * file, otherwise it is a Winelib app.
1794 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1795 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1796 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1797 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1798 const struct binary_info *binary_info, int exec_only )
1800 BOOL ret, success = FALSE;
1801 HANDLE process_info;
1802 WCHAR *env_end;
1803 char *winedebug = NULL;
1804 char *wineloader = NULL;
1805 const char *loader = NULL;
1806 char **argv;
1807 startup_info_t *startup_info;
1808 DWORD startup_info_size;
1809 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1810 pid_t pid;
1811 int err;
1813 if (!is_win64 && !is_wow64 && (binary_info->flags & BINARY_FLAG_64BIT))
1815 ERR( "starting 64-bit process %s not supported in 32-bit wineprefix\n", debugstr_w(filename) );
1816 SetLastError( ERROR_BAD_EXE_FORMAT );
1817 return FALSE;
1820 RtlAcquirePebLock();
1822 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1823 &startup_info_size )))
1825 RtlReleasePebLock();
1826 return FALSE;
1828 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
1829 env_end = env;
1830 while (*env_end)
1832 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1833 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1835 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1836 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1837 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1839 env_end += strlenW(env_end) + 1;
1841 env_end++;
1843 /* create the socket for the new process */
1845 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1847 RtlReleasePebLock();
1848 HeapFree( GetProcessHeap(), 0, winedebug );
1849 HeapFree( GetProcessHeap(), 0, startup_info );
1850 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1851 return FALSE;
1853 wine_server_send_fd( socketfd[1] );
1854 close( socketfd[1] );
1856 /* create the process on the server side */
1858 SERVER_START_REQ( new_process )
1860 req->inherit_all = inherit;
1861 req->create_flags = flags;
1862 req->socket_fd = socketfd[1];
1863 req->exe_file = wine_server_obj_handle( hFile );
1864 req->process_access = PROCESS_ALL_ACCESS;
1865 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1866 req->thread_access = THREAD_ALL_ACCESS;
1867 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1868 req->info_size = startup_info_size;
1870 wine_server_add_data( req, startup_info, startup_info_size );
1871 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
1872 if ((ret = !wine_server_call_err( req )))
1874 info->dwProcessId = (DWORD)reply->pid;
1875 info->dwThreadId = (DWORD)reply->tid;
1876 info->hProcess = wine_server_ptr_handle( reply->phandle );
1877 info->hThread = wine_server_ptr_handle( reply->thandle );
1879 process_info = wine_server_ptr_handle( reply->info );
1881 SERVER_END_REQ;
1883 RtlReleasePebLock();
1884 if (!ret)
1886 close( socketfd[0] );
1887 HeapFree( GetProcessHeap(), 0, startup_info );
1888 HeapFree( GetProcessHeap(), 0, winedebug );
1889 return FALSE;
1892 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1894 if (startup_info->hstdin)
1895 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
1896 FILE_READ_DATA, &stdin_fd, NULL );
1897 if (startup_info->hstdout)
1898 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
1899 FILE_WRITE_DATA, &stdout_fd, NULL );
1901 HeapFree( GetProcessHeap(), 0, startup_info );
1903 /* create the child process */
1904 argv = build_argv( cmd_line, 1 );
1906 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1907 loader = get_alternate_loader( &wineloader );
1909 if (exec_only || !(pid = fork())) /* child */
1911 char preloader_reserve[64], socket_env[64];
1913 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1915 if (!(pid = fork()))
1917 int fd = open( "/dev/null", O_RDWR );
1918 setsid();
1919 /* close stdin and stdout */
1920 if (fd != -1)
1922 dup2( fd, 0 );
1923 dup2( fd, 1 );
1924 close( fd );
1927 else if (pid != -1) _exit(0); /* parent */
1929 else
1931 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1932 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1935 if (stdin_fd != -1) close( stdin_fd );
1936 if (stdout_fd != -1) close( stdout_fd );
1938 /* Reset signals that we previously set to SIG_IGN */
1939 signal( SIGPIPE, SIG_DFL );
1940 signal( SIGCHLD, SIG_DFL );
1942 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1943 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1944 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1946 putenv( preloader_reserve );
1947 putenv( socket_env );
1948 if (winedebug) putenv( winedebug );
1949 if (wineloader) putenv( wineloader );
1950 if (unixdir) chdir(unixdir);
1952 if (argv)
1956 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1958 #ifdef __APPLE__
1959 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1960 #else
1961 while (0);
1962 #endif
1964 _exit(1);
1967 /* this is the parent */
1969 if (stdin_fd != -1) close( stdin_fd );
1970 if (stdout_fd != -1) close( stdout_fd );
1971 close( socketfd[0] );
1972 HeapFree( GetProcessHeap(), 0, argv );
1973 HeapFree( GetProcessHeap(), 0, winedebug );
1974 HeapFree( GetProcessHeap(), 0, wineloader );
1975 if (pid == -1)
1977 FILE_SetDosError();
1978 goto error;
1981 /* wait for the new process info to be ready */
1983 WaitForSingleObject( process_info, INFINITE );
1984 SERVER_START_REQ( get_new_process_info )
1986 req->info = wine_server_obj_handle( process_info );
1987 wine_server_call( req );
1988 success = reply->success;
1989 err = reply->exit_code;
1991 SERVER_END_REQ;
1993 if (!success)
1995 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1996 goto error;
1998 CloseHandle( process_info );
1999 return success;
2001 error:
2002 CloseHandle( process_info );
2003 CloseHandle( info->hProcess );
2004 CloseHandle( info->hThread );
2005 info->hProcess = info->hThread = 0;
2006 info->dwProcessId = info->dwThreadId = 0;
2007 return FALSE;
2011 /***********************************************************************
2012 * create_vdm_process
2014 * Create a new VDM process for a 16-bit or DOS application.
2016 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2017 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2018 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2019 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2020 const struct binary_info *binary_info, int exec_only )
2022 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2024 BOOL ret;
2025 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
2026 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
2028 if (!new_cmd_line)
2030 SetLastError( ERROR_OUTOFMEMORY );
2031 return FALSE;
2033 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
2034 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2035 flags, startup, info, unixdir, binary_info, exec_only );
2036 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2037 return ret;
2041 /***********************************************************************
2042 * create_cmd_process
2044 * Create a new cmd shell process for a .BAT file.
2046 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2047 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2048 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2049 LPPROCESS_INFORMATION info )
2052 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2053 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2054 WCHAR comspec[MAX_PATH];
2055 WCHAR *newcmdline;
2056 BOOL ret;
2058 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2059 return FALSE;
2060 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2061 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2062 return FALSE;
2064 strcpyW( newcmdline, comspec );
2065 strcatW( newcmdline, slashcW );
2066 strcatW( newcmdline, cmd_line );
2067 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2068 flags, env, cur_dir, startup, info );
2069 HeapFree( GetProcessHeap(), 0, newcmdline );
2070 return ret;
2074 /*************************************************************************
2075 * get_file_name
2077 * Helper for CreateProcess: retrieve the file name to load from the
2078 * app name and command line. Store the file name in buffer, and
2079 * return a possibly modified command line.
2080 * Also returns a handle to the opened file if it's a Windows binary.
2082 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2083 int buflen, HANDLE *handle, struct binary_info *binary_info )
2085 static const WCHAR quotesW[] = {'"','%','s','"',0};
2087 WCHAR *name, *pos, *first_space, *ret = NULL;
2088 const WCHAR *p;
2090 /* if we have an app name, everything is easy */
2092 if (appname)
2094 /* use the unmodified app name as file name */
2095 lstrcpynW( buffer, appname, buflen );
2096 *handle = open_exe_file( buffer, binary_info );
2097 if (!(ret = cmdline) || !cmdline[0])
2099 /* no command-line, create one */
2100 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2101 sprintfW( ret, quotesW, appname );
2103 return ret;
2106 /* first check for a quoted file name */
2108 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2110 int len = p - cmdline - 1;
2111 /* extract the quoted portion as file name */
2112 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2113 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2114 name[len] = 0;
2116 if (!find_exe_file( name, buffer, buflen, handle, binary_info ))
2118 if (!get_builtin_path( name, exeW, buffer, buflen, binary_info )) goto done;
2119 *handle = 0;
2121 ret = cmdline; /* no change necessary */
2122 goto done;
2125 /* now try the command-line word by word */
2127 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2128 return NULL;
2129 pos = name;
2130 p = cmdline;
2131 first_space = NULL;
2133 for (;;)
2135 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2136 *pos = 0;
2137 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2139 ret = cmdline;
2140 break;
2142 if (!first_space) first_space = pos;
2143 if (!(*pos++ = *p++)) break;
2146 if (!ret)
2148 if (first_space) *first_space = 0; /* try only the first word as a builtin */
2149 if (get_builtin_path( name, exeW, buffer, buflen, binary_info ))
2151 *handle = 0;
2152 ret = cmdline;
2154 else SetLastError( ERROR_FILE_NOT_FOUND );
2156 else if (first_space) /* build a new command-line with quotes */
2158 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2159 goto done;
2160 sprintfW( ret, quotesW, name );
2161 strcatW( ret, p );
2164 done:
2165 HeapFree( GetProcessHeap(), 0, name );
2166 return ret;
2170 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2171 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2172 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2173 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2174 LPPROCESS_INFORMATION info )
2176 BOOL retv = FALSE;
2177 HANDLE hFile = 0;
2178 char *unixdir = NULL;
2179 WCHAR name[MAX_PATH];
2180 WCHAR *tidy_cmdline, *p, *envW = env;
2181 struct binary_info binary_info;
2183 /* Process the AppName and/or CmdLine to get module name and path */
2185 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2187 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2188 &hFile, &binary_info )))
2189 return FALSE;
2190 if (hFile == INVALID_HANDLE_VALUE) goto done;
2192 /* Warn if unsupported features are used */
2194 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2195 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2196 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2197 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2198 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2200 if (cur_dir)
2202 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2204 SetLastError(ERROR_DIRECTORY);
2205 goto done;
2208 else
2210 WCHAR buf[MAX_PATH];
2211 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2214 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2216 char *p = env;
2217 DWORD lenW;
2219 while (*p) p += strlen(p) + 1;
2220 p++; /* final null */
2221 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
2222 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2223 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
2224 flags |= CREATE_UNICODE_ENVIRONMENT;
2227 info->hThread = info->hProcess = 0;
2228 info->dwProcessId = info->dwThreadId = 0;
2230 if (binary_info.flags & BINARY_FLAG_DLL)
2232 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2233 SetLastError( ERROR_BAD_EXE_FORMAT );
2235 else switch (binary_info.type)
2237 case BINARY_PE:
2238 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2239 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2240 binary_info.res_start, binary_info.res_end );
2241 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2242 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2243 break;
2244 case BINARY_OS216:
2245 case BINARY_WIN16:
2246 case BINARY_DOS:
2247 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2248 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2249 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2250 break;
2251 case BINARY_UNIX_LIB:
2252 TRACE( "starting %s as %d-bit Winelib app\n",
2253 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2254 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2255 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2256 break;
2257 case BINARY_UNKNOWN:
2258 /* check for .com or .bat extension */
2259 if ((p = strrchrW( name, '.' )))
2261 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2263 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2264 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2265 inherit, flags, startup_info, info, unixdir,
2266 &binary_info, FALSE );
2267 break;
2269 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2271 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2272 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2273 inherit, flags, startup_info, info );
2274 break;
2277 /* fall through */
2278 case BINARY_UNIX_EXE:
2280 /* unknown file, try as unix executable */
2281 char *unix_name;
2283 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2285 if ((unix_name = wine_get_unix_file_name( name )))
2287 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2288 HeapFree( GetProcessHeap(), 0, unix_name );
2291 break;
2293 if (hFile) CloseHandle( hFile );
2295 done:
2296 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2297 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2298 HeapFree( GetProcessHeap(), 0, unixdir );
2299 if (retv)
2300 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2301 return retv;
2305 /**********************************************************************
2306 * CreateProcessA (KERNEL32.@)
2308 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2309 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2310 DWORD flags, LPVOID env, LPCSTR cur_dir,
2311 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2313 BOOL ret = FALSE;
2314 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2315 UNICODE_STRING desktopW, titleW;
2316 STARTUPINFOW infoW;
2318 desktopW.Buffer = NULL;
2319 titleW.Buffer = NULL;
2320 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2321 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2322 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2324 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2325 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2327 memcpy( &infoW, startup_info, sizeof(infoW) );
2328 infoW.lpDesktop = desktopW.Buffer;
2329 infoW.lpTitle = titleW.Buffer;
2331 if (startup_info->lpReserved)
2332 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2333 debugstr_a(startup_info->lpReserved));
2335 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2336 inherit, flags, env, cur_dirW, &infoW, info );
2337 done:
2338 HeapFree( GetProcessHeap(), 0, app_nameW );
2339 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2340 HeapFree( GetProcessHeap(), 0, cur_dirW );
2341 RtlFreeUnicodeString( &desktopW );
2342 RtlFreeUnicodeString( &titleW );
2343 return ret;
2347 /**********************************************************************
2348 * CreateProcessW (KERNEL32.@)
2350 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2351 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2352 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2353 LPPROCESS_INFORMATION info )
2355 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2356 inherit, flags, env, cur_dir, startup_info, info);
2360 /**********************************************************************
2361 * exec_process
2363 static void exec_process( LPCWSTR name )
2365 HANDLE hFile;
2366 WCHAR *p;
2367 STARTUPINFOW startup_info;
2368 PROCESS_INFORMATION info;
2369 struct binary_info binary_info;
2371 hFile = open_exe_file( name, &binary_info );
2372 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2374 memset( &startup_info, 0, sizeof(startup_info) );
2375 startup_info.cb = sizeof(startup_info);
2377 /* Determine executable type */
2379 if (binary_info.flags & BINARY_FLAG_DLL) return;
2380 switch (binary_info.type)
2382 case BINARY_PE:
2383 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2384 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2385 binary_info.res_start, binary_info.res_end );
2386 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2387 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2388 break;
2389 case BINARY_UNIX_LIB:
2390 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2391 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2392 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2393 break;
2394 case BINARY_UNKNOWN:
2395 /* check for .com or .pif extension */
2396 if (!(p = strrchrW( name, '.' ))) break;
2397 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2398 /* fall through */
2399 case BINARY_OS216:
2400 case BINARY_WIN16:
2401 case BINARY_DOS:
2402 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2403 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2404 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2405 break;
2406 default:
2407 break;
2409 CloseHandle( hFile );
2413 /***********************************************************************
2414 * wait_input_idle
2416 * Wrapper to call WaitForInputIdle USER function
2418 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2420 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2422 HMODULE mod = GetModuleHandleA( "user32.dll" );
2423 if (mod)
2425 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2426 if (ptr) return ptr( process, timeout );
2428 return 0;
2432 /***********************************************************************
2433 * WinExec (KERNEL32.@)
2435 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2437 PROCESS_INFORMATION info;
2438 STARTUPINFOA startup;
2439 char *cmdline;
2440 UINT ret;
2442 memset( &startup, 0, sizeof(startup) );
2443 startup.cb = sizeof(startup);
2444 startup.dwFlags = STARTF_USESHOWWINDOW;
2445 startup.wShowWindow = nCmdShow;
2447 /* cmdline needs to be writable for CreateProcess */
2448 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2449 strcpy( cmdline, lpCmdLine );
2451 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2452 0, NULL, NULL, &startup, &info ))
2454 /* Give 30 seconds to the app to come up */
2455 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2456 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2457 ret = 33;
2458 /* Close off the handles */
2459 CloseHandle( info.hThread );
2460 CloseHandle( info.hProcess );
2462 else if ((ret = GetLastError()) >= 32)
2464 FIXME("Strange error set by CreateProcess: %d\n", ret );
2465 ret = 11;
2467 HeapFree( GetProcessHeap(), 0, cmdline );
2468 return ret;
2472 /**********************************************************************
2473 * LoadModule (KERNEL32.@)
2475 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2477 LOADPARMS32 *params = paramBlock;
2478 PROCESS_INFORMATION info;
2479 STARTUPINFOA startup;
2480 DWORD ret;
2481 LPSTR cmdline, p;
2482 char filename[MAX_PATH];
2483 BYTE len;
2485 if (!name) return ERROR_FILE_NOT_FOUND;
2487 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2488 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2489 return GetLastError();
2491 len = (BYTE)params->lpCmdLine[0];
2492 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2493 return ERROR_NOT_ENOUGH_MEMORY;
2495 strcpy( cmdline, filename );
2496 p = cmdline + strlen(cmdline);
2497 *p++ = ' ';
2498 memcpy( p, params->lpCmdLine + 1, len );
2499 p[len] = 0;
2501 memset( &startup, 0, sizeof(startup) );
2502 startup.cb = sizeof(startup);
2503 if (params->lpCmdShow)
2505 startup.dwFlags = STARTF_USESHOWWINDOW;
2506 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2509 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2510 params->lpEnvAddress, NULL, &startup, &info ))
2512 /* Give 30 seconds to the app to come up */
2513 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2514 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2515 ret = 33;
2516 /* Close off the handles */
2517 CloseHandle( info.hThread );
2518 CloseHandle( info.hProcess );
2520 else if ((ret = GetLastError()) >= 32)
2522 FIXME("Strange error set by CreateProcess: %u\n", ret );
2523 ret = 11;
2526 HeapFree( GetProcessHeap(), 0, cmdline );
2527 return ret;
2531 /******************************************************************************
2532 * TerminateProcess (KERNEL32.@)
2534 * Terminates a process.
2536 * PARAMS
2537 * handle [I] Process to terminate.
2538 * exit_code [I] Exit code.
2540 * RETURNS
2541 * Success: TRUE.
2542 * Failure: FALSE, check GetLastError().
2544 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2546 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2547 if (status) SetLastError( RtlNtStatusToDosError(status) );
2548 return !status;
2551 /***********************************************************************
2552 * ExitProcess (KERNEL32.@)
2554 * Exits the current process.
2556 * PARAMS
2557 * status [I] Status code to exit with.
2559 * RETURNS
2560 * Nothing.
2562 #ifdef __i386__
2563 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2564 "pushl %ebp\n\t"
2565 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2566 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2567 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2568 "pushl 8(%ebp)\n\t"
2569 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2570 "leave\n\t"
2571 "ret $4" )
2573 void WINAPI process_ExitProcess( DWORD status )
2575 LdrShutdownProcess();
2576 NtTerminateProcess(GetCurrentProcess(), status);
2577 exit(status);
2580 #else
2582 void WINAPI ExitProcess( DWORD status )
2584 LdrShutdownProcess();
2585 NtTerminateProcess(GetCurrentProcess(), status);
2586 exit(status);
2589 #endif
2591 /***********************************************************************
2592 * GetExitCodeProcess [KERNEL32.@]
2594 * Gets termination status of specified process.
2596 * PARAMS
2597 * hProcess [in] Handle to the process.
2598 * lpExitCode [out] Address to receive termination status.
2600 * RETURNS
2601 * Success: TRUE
2602 * Failure: FALSE
2604 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2606 NTSTATUS status;
2607 PROCESS_BASIC_INFORMATION pbi;
2609 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2610 sizeof(pbi), NULL);
2611 if (status == STATUS_SUCCESS)
2613 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2614 return TRUE;
2616 SetLastError( RtlNtStatusToDosError(status) );
2617 return FALSE;
2621 /***********************************************************************
2622 * SetErrorMode (KERNEL32.@)
2624 UINT WINAPI SetErrorMode( UINT mode )
2626 UINT old;
2628 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2629 &old, sizeof(old), NULL );
2630 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2631 &mode, sizeof(mode) );
2632 return old;
2635 /***********************************************************************
2636 * GetErrorMode (KERNEL32.@)
2638 UINT WINAPI GetErrorMode( void )
2640 UINT mode;
2642 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2643 &mode, sizeof(mode), NULL );
2644 return mode;
2647 /**********************************************************************
2648 * TlsAlloc [KERNEL32.@]
2650 * Allocates a thread local storage index.
2652 * RETURNS
2653 * Success: TLS index.
2654 * Failure: 0xFFFFFFFF
2656 DWORD WINAPI TlsAlloc( void )
2658 DWORD index;
2659 PEB * const peb = NtCurrentTeb()->Peb;
2661 RtlAcquirePebLock();
2662 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2663 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2664 else
2666 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2667 if (index != ~0U)
2669 if (!NtCurrentTeb()->TlsExpansionSlots &&
2670 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2671 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2673 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2674 index = ~0U;
2675 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2677 else
2679 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2680 index += TLS_MINIMUM_AVAILABLE;
2683 else SetLastError( ERROR_NO_MORE_ITEMS );
2685 RtlReleasePebLock();
2686 return index;
2690 /**********************************************************************
2691 * TlsFree [KERNEL32.@]
2693 * Releases a thread local storage index, making it available for reuse.
2695 * PARAMS
2696 * index [in] TLS index to free.
2698 * RETURNS
2699 * Success: TRUE
2700 * Failure: FALSE
2702 BOOL WINAPI TlsFree( DWORD index )
2704 BOOL ret;
2706 RtlAcquirePebLock();
2707 if (index >= TLS_MINIMUM_AVAILABLE)
2709 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2710 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2712 else
2714 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2715 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2717 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2718 else SetLastError( ERROR_INVALID_PARAMETER );
2719 RtlReleasePebLock();
2720 return ret;
2724 /**********************************************************************
2725 * TlsGetValue [KERNEL32.@]
2727 * Gets value in a thread's TLS slot.
2729 * PARAMS
2730 * index [in] TLS index to retrieve value for.
2732 * RETURNS
2733 * Success: Value stored in calling thread's TLS slot for index.
2734 * Failure: 0 and GetLastError() returns NO_ERROR.
2736 LPVOID WINAPI TlsGetValue( DWORD index )
2738 LPVOID ret;
2740 if (index < TLS_MINIMUM_AVAILABLE)
2742 ret = NtCurrentTeb()->TlsSlots[index];
2744 else
2746 index -= TLS_MINIMUM_AVAILABLE;
2747 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2749 SetLastError( ERROR_INVALID_PARAMETER );
2750 return NULL;
2752 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2753 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2755 SetLastError( ERROR_SUCCESS );
2756 return ret;
2760 /**********************************************************************
2761 * TlsSetValue [KERNEL32.@]
2763 * Stores a value in the thread's TLS slot.
2765 * PARAMS
2766 * index [in] TLS index to set value for.
2767 * value [in] Value to be stored.
2769 * RETURNS
2770 * Success: TRUE
2771 * Failure: FALSE
2773 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2775 if (index < TLS_MINIMUM_AVAILABLE)
2777 NtCurrentTeb()->TlsSlots[index] = value;
2779 else
2781 index -= TLS_MINIMUM_AVAILABLE;
2782 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2784 SetLastError( ERROR_INVALID_PARAMETER );
2785 return FALSE;
2787 if (!NtCurrentTeb()->TlsExpansionSlots &&
2788 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2789 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2791 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2792 return FALSE;
2794 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2796 return TRUE;
2800 /***********************************************************************
2801 * GetProcessFlags (KERNEL32.@)
2803 DWORD WINAPI GetProcessFlags( DWORD processid )
2805 IMAGE_NT_HEADERS *nt;
2806 DWORD flags = 0;
2808 if (processid && processid != GetCurrentProcessId()) return 0;
2810 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2812 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2813 flags |= PDB32_CONSOLE_PROC;
2815 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2816 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2817 return flags;
2821 /*********************************************************************
2822 * OpenProcess (KERNEL32.@)
2824 * Opens a handle to a process.
2826 * PARAMS
2827 * access [I] Desired access rights assigned to the returned handle.
2828 * inherit [I] Determines whether or not child processes will inherit the handle.
2829 * id [I] Process identifier of the process to get a handle to.
2831 * RETURNS
2832 * Success: Valid handle to the specified process.
2833 * Failure: NULL, check GetLastError().
2835 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2837 NTSTATUS status;
2838 HANDLE handle;
2839 OBJECT_ATTRIBUTES attr;
2840 CLIENT_ID cid;
2842 cid.UniqueProcess = ULongToHandle(id);
2843 cid.UniqueThread = 0; /* FIXME ? */
2845 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2846 attr.RootDirectory = NULL;
2847 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2848 attr.SecurityDescriptor = NULL;
2849 attr.SecurityQualityOfService = NULL;
2850 attr.ObjectName = NULL;
2852 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2854 status = NtOpenProcess(&handle, access, &attr, &cid);
2855 if (status != STATUS_SUCCESS)
2857 SetLastError( RtlNtStatusToDosError(status) );
2858 return NULL;
2860 return handle;
2864 /*********************************************************************
2865 * GetProcessId (KERNEL32.@)
2867 * Gets the a unique identifier of a process.
2869 * PARAMS
2870 * hProcess [I] Handle to the process.
2872 * RETURNS
2873 * Success: TRUE.
2874 * Failure: FALSE, check GetLastError().
2876 * NOTES
2878 * The identifier is unique only on the machine and only until the process
2879 * exits (including system shutdown).
2881 DWORD WINAPI GetProcessId( HANDLE hProcess )
2883 NTSTATUS status;
2884 PROCESS_BASIC_INFORMATION pbi;
2886 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2887 sizeof(pbi), NULL);
2888 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2889 SetLastError( RtlNtStatusToDosError(status) );
2890 return 0;
2894 /*********************************************************************
2895 * CloseHandle (KERNEL32.@)
2897 * Closes a handle.
2899 * PARAMS
2900 * handle [I] Handle to close.
2902 * RETURNS
2903 * Success: TRUE.
2904 * Failure: FALSE, check GetLastError().
2906 BOOL WINAPI CloseHandle( HANDLE handle )
2908 NTSTATUS status;
2910 /* stdio handles need special treatment */
2911 if (handle == (HANDLE)STD_INPUT_HANDLE)
2912 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
2913 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
2914 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
2915 else if (handle == (HANDLE)STD_ERROR_HANDLE)
2916 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
2918 if (is_console_handle(handle))
2919 return CloseConsoleHandle(handle);
2921 status = NtClose( handle );
2922 if (status) SetLastError( RtlNtStatusToDosError(status) );
2923 return !status;
2927 /*********************************************************************
2928 * GetHandleInformation (KERNEL32.@)
2930 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2932 OBJECT_DATA_INFORMATION info;
2933 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2935 if (status) SetLastError( RtlNtStatusToDosError(status) );
2936 else if (flags)
2938 *flags = 0;
2939 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2940 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2942 return !status;
2946 /*********************************************************************
2947 * SetHandleInformation (KERNEL32.@)
2949 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2951 OBJECT_DATA_INFORMATION info;
2952 NTSTATUS status;
2954 /* if not setting both fields, retrieve current value first */
2955 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2956 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2958 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2960 SetLastError( RtlNtStatusToDosError(status) );
2961 return FALSE;
2964 if (mask & HANDLE_FLAG_INHERIT)
2965 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2966 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2967 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2969 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2970 if (status) SetLastError( RtlNtStatusToDosError(status) );
2971 return !status;
2975 /*********************************************************************
2976 * DuplicateHandle (KERNEL32.@)
2978 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2979 HANDLE dest_process, HANDLE *dest,
2980 DWORD access, BOOL inherit, DWORD options )
2982 NTSTATUS status;
2984 if (is_console_handle(source))
2986 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2987 if (source_process != dest_process ||
2988 source_process != GetCurrentProcess())
2990 SetLastError(ERROR_INVALID_PARAMETER);
2991 return FALSE;
2993 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2994 return (*dest != INVALID_HANDLE_VALUE);
2996 status = NtDuplicateObject( source_process, source, dest_process, dest,
2997 access, inherit ? OBJ_INHERIT : 0, options );
2998 if (status) SetLastError( RtlNtStatusToDosError(status) );
2999 return !status;
3003 /***********************************************************************
3004 * ConvertToGlobalHandle (KERNEL32.@)
3006 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3008 HANDLE ret = INVALID_HANDLE_VALUE;
3009 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3010 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3011 return ret;
3015 /***********************************************************************
3016 * SetHandleContext (KERNEL32.@)
3018 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3020 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3021 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3022 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3023 return FALSE;
3027 /***********************************************************************
3028 * GetHandleContext (KERNEL32.@)
3030 DWORD WINAPI GetHandleContext(HANDLE hnd)
3032 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3033 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3034 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3035 return 0;
3039 /***********************************************************************
3040 * CreateSocketHandle (KERNEL32.@)
3042 HANDLE WINAPI CreateSocketHandle(void)
3044 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3045 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3046 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3047 return INVALID_HANDLE_VALUE;
3051 /***********************************************************************
3052 * SetPriorityClass (KERNEL32.@)
3054 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3056 NTSTATUS status;
3057 PROCESS_PRIORITY_CLASS ppc;
3059 ppc.Foreground = FALSE;
3060 switch (priorityclass)
3062 case IDLE_PRIORITY_CLASS:
3063 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3064 case BELOW_NORMAL_PRIORITY_CLASS:
3065 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3066 case NORMAL_PRIORITY_CLASS:
3067 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3068 case ABOVE_NORMAL_PRIORITY_CLASS:
3069 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3070 case HIGH_PRIORITY_CLASS:
3071 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3072 case REALTIME_PRIORITY_CLASS:
3073 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3074 default:
3075 SetLastError(ERROR_INVALID_PARAMETER);
3076 return FALSE;
3079 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3080 &ppc, sizeof(ppc));
3082 if (status != STATUS_SUCCESS)
3084 SetLastError( RtlNtStatusToDosError(status) );
3085 return FALSE;
3087 return TRUE;
3091 /***********************************************************************
3092 * GetPriorityClass (KERNEL32.@)
3094 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3096 NTSTATUS status;
3097 PROCESS_BASIC_INFORMATION pbi;
3099 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3100 sizeof(pbi), NULL);
3101 if (status != STATUS_SUCCESS)
3103 SetLastError( RtlNtStatusToDosError(status) );
3104 return 0;
3106 switch (pbi.BasePriority)
3108 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3109 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3110 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3111 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3112 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3113 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3115 SetLastError( ERROR_INVALID_PARAMETER );
3116 return 0;
3120 /***********************************************************************
3121 * SetProcessAffinityMask (KERNEL32.@)
3123 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3125 NTSTATUS status;
3127 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3128 &affmask, sizeof(DWORD_PTR));
3129 if (status)
3131 SetLastError( RtlNtStatusToDosError(status) );
3132 return FALSE;
3134 return TRUE;
3138 /**********************************************************************
3139 * GetProcessAffinityMask (KERNEL32.@)
3141 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3143 NTSTATUS status = STATUS_SUCCESS;
3145 if (system_mask) *system_mask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
3146 if (process_mask)
3148 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3149 process_mask, sizeof(*process_mask), NULL )))
3150 SetLastError( RtlNtStatusToDosError(status) );
3152 return !status;
3156 /***********************************************************************
3157 * GetProcessVersion (KERNEL32.@)
3159 DWORD WINAPI GetProcessVersion( DWORD pid )
3161 HANDLE process;
3162 NTSTATUS status;
3163 PROCESS_BASIC_INFORMATION pbi;
3164 SIZE_T count;
3165 PEB peb;
3166 IMAGE_DOS_HEADER dos;
3167 IMAGE_NT_HEADERS nt;
3168 DWORD ver = 0;
3170 if (!pid || pid == GetCurrentProcessId())
3172 IMAGE_NT_HEADERS *nt;
3174 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3175 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
3176 nt->OptionalHeader.MinorSubsystemVersion);
3177 return 0;
3180 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3181 if (!process) return 0;
3183 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3184 if (status) goto err;
3186 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3187 if (status || count != sizeof(peb)) goto err;
3189 memset(&dos, 0, sizeof(dos));
3190 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3191 if (status || count != sizeof(dos)) goto err;
3192 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3194 memset(&nt, 0, sizeof(nt));
3195 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3196 if (status || count != sizeof(nt)) goto err;
3197 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3199 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3201 err:
3202 CloseHandle(process);
3204 if (status != STATUS_SUCCESS)
3205 SetLastError(RtlNtStatusToDosError(status));
3207 return ver;
3211 /***********************************************************************
3212 * SetProcessWorkingSetSize [KERNEL32.@]
3213 * Sets the min/max working set sizes for a specified process.
3215 * PARAMS
3216 * hProcess [I] Handle to the process of interest
3217 * minset [I] Specifies minimum working set size
3218 * maxset [I] Specifies maximum working set size
3220 * RETURNS
3221 * Success: TRUE
3222 * Failure: FALSE
3224 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3225 SIZE_T maxset)
3227 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3228 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3229 /* Trim the working set to zero */
3230 /* Swap the process out of physical RAM */
3232 return TRUE;
3235 /***********************************************************************
3236 * K32EmptyWorkingSet (KERNEL32.@)
3238 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3240 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3243 /***********************************************************************
3244 * GetProcessWorkingSetSize (KERNEL32.@)
3246 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3247 PSIZE_T maxset)
3249 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3250 /* 32 MB working set size */
3251 if (minset) *minset = 32*1024*1024;
3252 if (maxset) *maxset = 32*1024*1024;
3253 return TRUE;
3257 /***********************************************************************
3258 * SetProcessShutdownParameters (KERNEL32.@)
3260 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3262 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3263 shutdown_flags = flags;
3264 shutdown_priority = level;
3265 return TRUE;
3269 /***********************************************************************
3270 * GetProcessShutdownParameters (KERNEL32.@)
3273 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3275 *lpdwLevel = shutdown_priority;
3276 *lpdwFlags = shutdown_flags;
3277 return TRUE;
3281 /***********************************************************************
3282 * GetProcessPriorityBoost (KERNEL32.@)
3284 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3286 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3288 /* Report that no boost is present.. */
3289 *pDisablePriorityBoost = FALSE;
3291 return TRUE;
3294 /***********************************************************************
3295 * SetProcessPriorityBoost (KERNEL32.@)
3297 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3299 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3300 /* Say we can do it. I doubt the program will notice that we don't. */
3301 return TRUE;
3305 /***********************************************************************
3306 * ReadProcessMemory (KERNEL32.@)
3308 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3309 SIZE_T *bytes_read )
3311 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3312 if (status) SetLastError( RtlNtStatusToDosError(status) );
3313 return !status;
3317 /***********************************************************************
3318 * WriteProcessMemory (KERNEL32.@)
3320 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3321 SIZE_T *bytes_written )
3323 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3324 if (status) SetLastError( RtlNtStatusToDosError(status) );
3325 return !status;
3329 /****************************************************************************
3330 * FlushInstructionCache (KERNEL32.@)
3332 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3334 NTSTATUS status;
3335 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3336 if (status) SetLastError( RtlNtStatusToDosError(status) );
3337 return !status;
3341 /******************************************************************
3342 * GetProcessIoCounters (KERNEL32.@)
3344 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3346 NTSTATUS status;
3348 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3349 ioc, sizeof(*ioc), NULL);
3350 if (status) SetLastError( RtlNtStatusToDosError(status) );
3351 return !status;
3354 /******************************************************************
3355 * GetProcessHandleCount (KERNEL32.@)
3357 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3359 NTSTATUS status;
3361 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3362 cnt, sizeof(*cnt), NULL);
3363 if (status) SetLastError( RtlNtStatusToDosError(status) );
3364 return !status;
3367 /******************************************************************
3368 * QueryFullProcessImageNameA (KERNEL32.@)
3370 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3372 BOOL retval;
3373 DWORD pdwSizeW = *pdwSize;
3374 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3376 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3378 if(retval)
3379 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3380 lpExeName, *pdwSize, NULL, NULL));
3381 if(retval)
3382 *pdwSize = strlen(lpExeName);
3384 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3385 return retval;
3388 /******************************************************************
3389 * QueryFullProcessImageNameW (KERNEL32.@)
3391 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3393 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3394 UNICODE_STRING *dynamic_buffer = NULL;
3395 UNICODE_STRING nt_path;
3396 UNICODE_STRING *result = NULL;
3397 NTSTATUS status;
3398 DWORD needed;
3400 RtlInitUnicodeStringEx(&nt_path, NULL);
3401 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3402 * as this is on Wine. */
3403 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3404 sizeof(buffer) - sizeof(WCHAR), &needed);
3405 if (status == STATUS_INFO_LENGTH_MISMATCH)
3407 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3408 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3409 result = dynamic_buffer;
3411 else
3412 result = (PUNICODE_STRING)buffer;
3414 if (status) goto cleanup;
3416 if (dwFlags & PROCESS_NAME_NATIVE)
3418 result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3419 if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3421 status = STATUS_OBJECT_PATH_NOT_FOUND;
3422 goto cleanup;
3424 result = &nt_path;
3427 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3429 status = STATUS_BUFFER_TOO_SMALL;
3430 goto cleanup;
3433 *pdwSize = result->Length/sizeof(WCHAR);
3434 memcpy( lpExeName, result->Buffer, result->Length );
3435 lpExeName[*pdwSize] = 0;
3437 cleanup:
3438 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3439 RtlFreeUnicodeString(&nt_path);
3440 if (status) SetLastError( RtlNtStatusToDosError(status) );
3441 return !status;
3444 /***********************************************************************
3445 * K32GetProcessImageFileNameA (KERNEL32.@)
3447 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3449 FIXME("(%p, %p, %d) stub\n", process, file, size );
3450 return 0;
3453 /***********************************************************************
3454 * K32GetProcessImageFileNameW (KERNEL32.@)
3456 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3458 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3461 /***********************************************************************
3462 * K32EnumProcesses (KERNEL32.@)
3464 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3466 SYSTEM_PROCESS_INFORMATION *spi;
3467 ULONG size = 0x4000;
3468 void *buf = NULL;
3469 NTSTATUS status;
3471 do {
3472 size *= 2;
3473 HeapFree(GetProcessHeap(), 0, buf);
3474 buf = HeapAlloc(GetProcessHeap(), 0, size);
3475 if (!buf)
3476 return FALSE;
3478 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3479 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3481 if (status != STATUS_SUCCESS)
3483 HeapFree(GetProcessHeap(), 0, buf);
3484 SetLastError(RtlNtStatusToDosError(status));
3485 return FALSE;
3488 spi = buf;
3490 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3492 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3493 *lpcbUsed += sizeof(DWORD);
3495 if (spi->NextEntryOffset == 0)
3496 break;
3498 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3501 HeapFree(GetProcessHeap(), 0, buf);
3502 return TRUE;
3505 /***********************************************************************
3506 * K32QueryWorkingSet (KERNEL32.@)
3508 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3510 NTSTATUS status;
3512 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3514 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3516 if (status)
3518 SetLastError( RtlNtStatusToDosError( status ) );
3519 return FALSE;
3521 return TRUE;
3524 /***********************************************************************
3525 * K32QueryWorkingSetEx (KERNEL32.@)
3527 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3529 NTSTATUS status;
3531 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3533 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3535 if (status)
3537 SetLastError( RtlNtStatusToDosError( status ) );
3538 return FALSE;
3540 return TRUE;
3543 /***********************************************************************
3544 * K32GetProcessMemoryInfo (KERNEL32.@)
3546 * Retrieve memory usage information for a given process
3549 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3550 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3552 NTSTATUS status;
3553 VM_COUNTERS vmc;
3555 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3557 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3558 return FALSE;
3561 status = NtQueryInformationProcess(process, ProcessVmCounters,
3562 &vmc, sizeof(vmc), NULL);
3564 if (status)
3566 SetLastError(RtlNtStatusToDosError(status));
3567 return FALSE;
3570 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3571 pmc->PageFaultCount = vmc.PageFaultCount;
3572 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3573 pmc->WorkingSetSize = vmc.WorkingSetSize;
3574 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3575 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3576 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3577 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3578 pmc->PagefileUsage = vmc.PagefileUsage;
3579 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3581 return TRUE;
3584 /***********************************************************************
3585 * ProcessIdToSessionId (KERNEL32.@)
3586 * This function is available on Terminal Server 4SP4 and Windows 2000
3588 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3590 /* According to MSDN, if the calling process is not in a terminal
3591 * services environment, then the sessionid returned is zero.
3593 *sessionid_ptr = 0;
3594 return TRUE;
3598 /***********************************************************************
3599 * RegisterServiceProcess (KERNEL32.@)
3601 * A service process calls this function to ensure that it continues to run
3602 * even after a user logged off.
3604 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3606 /* I don't think that Wine needs to do anything in this function */
3607 return 1; /* success */
3611 /**********************************************************************
3612 * IsWow64Process (KERNEL32.@)
3614 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3616 ULONG pbi;
3617 NTSTATUS status;
3619 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3621 if (status != STATUS_SUCCESS)
3623 SetLastError( RtlNtStatusToDosError( status ) );
3624 return FALSE;
3626 *Wow64Process = (pbi != 0);
3627 return TRUE;
3631 /***********************************************************************
3632 * GetCurrentProcess (KERNEL32.@)
3634 * Get a handle to the current process.
3636 * PARAMS
3637 * None.
3639 * RETURNS
3640 * A handle representing the current process.
3642 #undef GetCurrentProcess
3643 HANDLE WINAPI GetCurrentProcess(void)
3645 return (HANDLE)~(ULONG_PTR)0;
3648 /***********************************************************************
3649 * GetLogicalProcessorInformation (KERNEL32.@)
3651 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3653 FIXME("(%p,%p): stub\n", buffer, pBufLen);
3654 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3655 return FALSE;
3658 /***********************************************************************
3659 * GetLogicalProcessorInformationEx (KERNEL32.@)
3661 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer, PDWORD pBufLen)
3663 FIXME("(%u,%p,%p): stub\n", relationship, buffer, pBufLen);
3664 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3665 return FALSE;
3668 /***********************************************************************
3669 * CmdBatNotification (KERNEL32.@)
3671 * Notifies the system that a batch file has started or finished.
3673 * PARAMS
3674 * bBatchRunning [I] TRUE if a batch file has started or
3675 * FALSE if a batch file has finished executing.
3677 * RETURNS
3678 * Unknown.
3680 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3682 FIXME("%d\n", bBatchRunning);
3683 return FALSE;
3687 /***********************************************************************
3688 * RegisterApplicationRestart (KERNEL32.@)
3690 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3692 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3694 return S_OK;
3697 /**********************************************************************
3698 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3700 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3702 FIXME("stub\n");
3703 return 0;
3706 /**********************************************************************
3707 * GetSystemDEPPolicy (KERNEL32.@)
3709 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3711 FIXME("stub\n");
3712 return OptIn;
3715 /**********************************************************************
3716 * SetProcessDEPPolicy (KERNEL32.@)
3718 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3720 FIXME("(%d): stub\n", newDEP);
3721 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3722 return FALSE;
3725 /**********************************************************************
3726 * ApplicationRecoveryFinished (KERNEL32.@)
3728 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
3730 FIXME(": stub\n");
3731 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3734 /**********************************************************************
3735 * ApplicationRecoveryInProgress (KERNEL32.@)
3737 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
3739 FIXME(":%p stub\n", canceled);
3740 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3741 return E_FAIL;
3744 /**********************************************************************
3745 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3747 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
3749 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
3750 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3751 return E_FAIL;