dsound: Add eax properties
[wine/multimedia.git] / dlls / kernel32 / process.c
blob1edf9ea4c9b13e7bb1238084e0b434cffb0d9798
1 /*
2 * Win32 processes
4 * Copyright 1996, 1998 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <signal.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <time.h>
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
33 #endif
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
36 #endif
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
39 #endif
40 #ifdef HAVE_SYS_PRCTL_H
41 # include <sys/prctl.h>
42 #endif
43 #include <sys/types.h>
44 #ifdef HAVE_SYS_WAIT_H
45 # include <sys/wait.h>
46 #endif
47 #ifdef HAVE_UNISTD_H
48 # include <unistd.h>
49 #endif
50 #ifdef __APPLE__
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <pthread.h>
53 #endif
55 #include "ntstatus.h"
56 #define WIN32_NO_STATUS
57 #include "winternl.h"
58 #include "kernel_private.h"
59 #include "psapi.h"
60 #include "wine/library.h"
61 #include "wine/server.h"
62 #include "wine/unicode.h"
63 #include "wine/debug.h"
65 WINE_DEFAULT_DEBUG_CHANNEL(process);
66 WINE_DECLARE_DEBUG_CHANNEL(file);
67 WINE_DECLARE_DEBUG_CHANNEL(relay);
69 #ifdef __APPLE__
70 extern char **__wine_get_main_environment(void);
71 #else
72 extern char **__wine_main_environ;
73 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
74 #endif
76 typedef struct
78 LPSTR lpEnvAddress;
79 LPSTR lpCmdLine;
80 LPSTR lpCmdShow;
81 DWORD dwReserved;
82 } LOADPARMS32;
84 static DWORD shutdown_flags = 0;
85 static DWORD shutdown_priority = 0x280;
86 static BOOL is_wow64;
87 static const int is_win64 = (sizeof(void *) > sizeof(int));
89 HMODULE kernel32_handle = 0;
91 const WCHAR *DIR_Windows = NULL;
92 const WCHAR *DIR_System = NULL;
93 const WCHAR *DIR_SysWow64 = NULL;
95 /* Process flags */
96 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
97 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
98 #define PDB32_DOS_PROC 0x0010 /* Dos process */
99 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
100 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
101 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
103 static const WCHAR exeW[] = {'.','e','x','e',0};
104 static const WCHAR comW[] = {'.','c','o','m',0};
105 static const WCHAR batW[] = {'.','b','a','t',0};
106 static const WCHAR cmdW[] = {'.','c','m','d',0};
107 static const WCHAR pifW[] = {'.','p','i','f',0};
108 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
110 static void exec_process( LPCWSTR name );
112 extern void SHELL_LoadRegistry(void);
115 /***********************************************************************
116 * contains_path
118 static inline int contains_path( LPCWSTR name )
120 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
124 /***********************************************************************
125 * is_special_env_var
127 * Check if an environment variable needs to be handled specially when
128 * passed through the Unix environment (i.e. prefixed with "WINE").
130 static inline int is_special_env_var( const char *var )
132 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
133 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
134 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
135 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
136 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
140 /***********************************************************************
141 * is_path_prefix
143 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
145 unsigned int len = strlenW( prefix );
147 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
148 while (filename[len] == '\\') len++;
149 return len;
153 /***************************************************************************
154 * get_builtin_path
156 * Get the path of a builtin module when the native file does not exist.
158 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
159 UINT size, struct binary_info *binary_info )
161 WCHAR *file_part;
162 UINT len;
163 void *redir_disabled = 0;
164 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
166 /* builtin names cannot be empty or contain spaces */
167 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
169 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
170 Wow64RevertWow64FsRedirection( redir_disabled );
172 if (contains_path( libname ))
174 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
175 filename, &file_part ) > size * sizeof(WCHAR))
176 return FALSE; /* too long */
178 if ((len = is_path_prefix( DIR_System, filename )))
180 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
182 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
184 flags = 0;
186 else return FALSE;
188 if (filename + len != file_part) return FALSE;
190 else
192 len = strlenW( DIR_System );
193 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
194 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
195 file_part = filename + len;
196 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
197 strcpyW( file_part, libname );
198 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
200 if (ext && !strchrW( file_part, '.' ))
202 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
203 return FALSE; /* too long */
204 strcatW( file_part, ext );
206 binary_info->type = BINARY_UNIX_LIB;
207 binary_info->flags = flags;
208 binary_info->res_start = NULL;
209 binary_info->res_end = NULL;
210 return TRUE;
214 /***********************************************************************
215 * open_exe_file
217 * Open a specific exe file, taking load order into account.
218 * Returns the file handle or 0 for a builtin exe.
220 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
222 HANDLE handle;
224 TRACE("looking for %s\n", debugstr_w(name) );
226 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
227 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
229 WCHAR buffer[MAX_PATH];
230 /* file doesn't exist, check for builtin */
231 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
232 handle = 0;
234 else MODULE_get_binary_info( handle, binary_info );
236 return handle;
240 /***********************************************************************
241 * find_exe_file
243 * Open an exe file, and return the full name and file handle.
244 * Returns FALSE if file could not be found.
246 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
247 HANDLE *handle, struct binary_info *binary_info )
249 TRACE("looking for %s\n", debugstr_w(name) );
251 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
252 /* no builtin found, try native without extension in case it is a Unix app */
253 !SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
255 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
256 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
257 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
259 MODULE_get_binary_info( *handle, binary_info );
260 return TRUE;
262 return FALSE;
266 /***********************************************************************
267 * build_initial_environment
269 * Build the Win32 environment from the Unix environment
271 static BOOL build_initial_environment(void)
273 SIZE_T size = 1;
274 char **e;
275 WCHAR *p, *endptr;
276 void *ptr;
277 char **env = __wine_get_main_environment();
279 /* Compute the total size of the Unix environment */
280 for (e = env; *e; e++)
282 if (is_special_env_var( *e )) continue;
283 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
285 size *= sizeof(WCHAR);
287 /* Now allocate the environment */
288 ptr = NULL;
289 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
290 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
291 return FALSE;
293 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
294 endptr = p + size / sizeof(WCHAR);
296 /* And fill it with the Unix environment */
297 for (e = env; *e; e++)
299 char *str = *e;
301 /* skip Unix special variables and use the Wine variants instead */
302 if (!strncmp( str, "WINE", 4 ))
304 if (is_special_env_var( str + 4 )) str += 4;
305 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
307 else if (is_special_env_var( str )) continue; /* skip it */
309 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
310 p += strlenW(p) + 1;
312 *p = 0;
313 return TRUE;
317 /***********************************************************************
318 * set_registry_variables
320 * Set environment variables by enumerating the values of a key;
321 * helper for set_registry_environment().
322 * Note that Windows happily truncates the value if it's too big.
324 static void set_registry_variables( HANDLE hkey, ULONG type )
326 static const WCHAR pathW[] = {'P','A','T','H'};
327 static const WCHAR sep[] = {';',0};
328 UNICODE_STRING env_name, env_value;
329 NTSTATUS status;
330 DWORD size;
331 int index;
332 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
333 WCHAR tmpbuf[1024];
334 UNICODE_STRING tmp;
335 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
337 tmp.Buffer = tmpbuf;
338 tmp.MaximumLength = sizeof(tmpbuf);
340 for (index = 0; ; index++)
342 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
343 buffer, sizeof(buffer), &size );
344 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
345 break;
346 if (info->Type != type)
347 continue;
348 env_name.Buffer = info->Name;
349 env_name.Length = env_name.MaximumLength = info->NameLength;
350 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
351 env_value.Length = info->DataLength;
352 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
353 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
354 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
355 if (!env_value.Length) continue;
356 if (info->Type == REG_EXPAND_SZ)
358 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
359 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
360 RtlCopyUnicodeString( &env_value, &tmp );
362 /* PATH is magic */
363 if (env_name.Length == sizeof(pathW) &&
364 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
365 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
367 RtlAppendUnicodeToString( &tmp, sep );
368 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
369 RtlCopyUnicodeString( &env_value, &tmp );
371 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
376 /***********************************************************************
377 * set_registry_environment
379 * Set the environment variables specified in the registry.
381 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
382 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
383 * on the order in which the variables are processed. But on Windows it
384 * does not really matter since they only use %SystemDrive% and
385 * %SystemRoot% which are predefined. But Wine defines these in the
386 * registry, so we need two passes.
388 static BOOL set_registry_environment( BOOL volatile_only )
390 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
391 'S','y','s','t','e','m','\\',
392 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
393 'C','o','n','t','r','o','l','\\',
394 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
395 'E','n','v','i','r','o','n','m','e','n','t',0};
396 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
397 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};
399 OBJECT_ATTRIBUTES attr;
400 UNICODE_STRING nameW;
401 HANDLE hkey;
402 BOOL ret = FALSE;
404 attr.Length = sizeof(attr);
405 attr.RootDirectory = 0;
406 attr.ObjectName = &nameW;
407 attr.Attributes = 0;
408 attr.SecurityDescriptor = NULL;
409 attr.SecurityQualityOfService = NULL;
411 /* first the system environment variables */
412 RtlInitUnicodeString( &nameW, env_keyW );
413 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
415 set_registry_variables( hkey, REG_SZ );
416 set_registry_variables( hkey, REG_EXPAND_SZ );
417 NtClose( hkey );
418 ret = TRUE;
421 /* then the ones for the current user */
422 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
423 RtlInitUnicodeString( &nameW, envW );
424 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
426 set_registry_variables( hkey, REG_SZ );
427 set_registry_variables( hkey, REG_EXPAND_SZ );
428 NtClose( hkey );
431 RtlInitUnicodeString( &nameW, volatile_envW );
432 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
434 set_registry_variables( hkey, REG_SZ );
435 set_registry_variables( hkey, REG_EXPAND_SZ );
436 NtClose( hkey );
439 NtClose( attr.RootDirectory );
440 return ret;
444 /***********************************************************************
445 * get_reg_value
447 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
449 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
450 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
451 DWORD len, size = sizeof(buffer);
452 WCHAR *ret = NULL;
453 UNICODE_STRING nameW;
455 RtlInitUnicodeString( &nameW, name );
456 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
457 return NULL;
459 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
460 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
462 if (info->Type == REG_EXPAND_SZ)
464 UNICODE_STRING value, expanded;
466 value.MaximumLength = len * sizeof(WCHAR);
467 value.Buffer = (WCHAR *)info->Data;
468 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
469 value.Length = len * sizeof(WCHAR);
470 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
471 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
472 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
473 else RtlFreeUnicodeString( &expanded );
475 else if (info->Type == REG_SZ)
477 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
479 memcpy( ret, info->Data, len * sizeof(WCHAR) );
480 ret[len] = 0;
483 return ret;
487 /***********************************************************************
488 * set_additional_environment
490 * Set some additional environment variables not specified in the registry.
492 static void set_additional_environment(void)
494 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
495 'S','o','f','t','w','a','r','e','\\',
496 'M','i','c','r','o','s','o','f','t','\\',
497 'W','i','n','d','o','w','s',' ','N','T','\\',
498 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
499 'P','r','o','f','i','l','e','L','i','s','t',0};
500 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
501 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
502 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
503 OBJECT_ATTRIBUTES attr;
504 UNICODE_STRING nameW;
505 WCHAR *profile_dir = NULL, *all_users_dir = NULL;
506 HANDLE hkey;
507 DWORD len;
509 /* set the ALLUSERSPROFILE variables */
511 attr.Length = sizeof(attr);
512 attr.RootDirectory = 0;
513 attr.ObjectName = &nameW;
514 attr.Attributes = 0;
515 attr.SecurityDescriptor = NULL;
516 attr.SecurityQualityOfService = NULL;
517 RtlInitUnicodeString( &nameW, profile_keyW );
518 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
520 profile_dir = get_reg_value( hkey, profiles_valueW );
521 all_users_dir = get_reg_value( hkey, all_users_valueW );
522 NtClose( hkey );
525 if (profile_dir && all_users_dir)
527 WCHAR *value, *p;
529 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
530 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
531 strcpyW( value, profile_dir );
532 p = value + strlenW(value);
533 if (p > value && p[-1] != '\\') *p++ = '\\';
534 strcpyW( p, all_users_dir );
535 SetEnvironmentVariableW( allusersW, value );
536 HeapFree( GetProcessHeap(), 0, value );
539 HeapFree( GetProcessHeap(), 0, all_users_dir );
540 HeapFree( GetProcessHeap(), 0, profile_dir );
543 /***********************************************************************
544 * set_wow64_environment
546 * Set the environment variables that change across 32/64/Wow64.
548 static void set_wow64_environment(void)
550 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};
551 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};
552 static const WCHAR x86W[] = {'x','8','6',0};
553 static const WCHAR versionW[] = {'M','a','c','h','i','n','e','\\',
554 'S','o','f','t','w','a','r','e','\\',
555 'M','i','c','r','o','s','o','f','t','\\',
556 'W','i','n','d','o','w','s','\\',
557 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
558 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
559 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
560 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
561 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
562 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
563 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
564 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
565 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
567 OBJECT_ATTRIBUTES attr;
568 UNICODE_STRING nameW;
569 WCHAR arch[64];
570 WCHAR *value;
571 HANDLE hkey;
573 /* set the PROCESSOR_ARCHITECTURE variable */
575 if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
577 if (is_win64)
579 SetEnvironmentVariableW( archW, arch );
580 SetEnvironmentVariableW( arch6432W, NULL );
583 else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
585 if (is_wow64)
587 SetEnvironmentVariableW( arch6432W, arch );
588 SetEnvironmentVariableW( archW, x86W );
592 attr.Length = sizeof(attr);
593 attr.RootDirectory = 0;
594 attr.ObjectName = &nameW;
595 attr.Attributes = 0;
596 attr.SecurityDescriptor = NULL;
597 attr.SecurityQualityOfService = NULL;
598 RtlInitUnicodeString( &nameW, versionW );
599 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
601 /* set the ProgramFiles variables */
603 if ((value = get_reg_value( hkey, progdirW )))
605 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
606 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
607 HeapFree( GetProcessHeap(), 0, value );
609 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
611 SetEnvironmentVariableW( progfilesW, value );
612 HeapFree( GetProcessHeap(), 0, value );
615 /* set the CommonProgramFiles variables */
617 if ((value = get_reg_value( hkey, commondirW )))
619 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
620 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
621 HeapFree( GetProcessHeap(), 0, value );
623 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
625 SetEnvironmentVariableW( commonfilesW, value );
626 HeapFree( GetProcessHeap(), 0, value );
629 NtClose( hkey );
632 /***********************************************************************
633 * set_library_wargv
635 * Set the Wine library Unicode argv global variables.
637 static void set_library_wargv( char **argv )
639 int argc;
640 char *q;
641 WCHAR *p;
642 WCHAR **wargv;
643 DWORD total = 0;
645 for (argc = 0; argv[argc]; argc++)
646 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
648 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
649 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
650 p = (WCHAR *)(wargv + argc + 1);
651 for (argc = 0; argv[argc]; argc++)
653 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
654 wargv[argc] = p;
655 p += reslen;
656 total -= reslen;
658 wargv[argc] = NULL;
660 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
662 for (argc = 0; wargv[argc]; argc++)
663 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
665 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
666 q = (char *)(argv + argc + 1);
667 for (argc = 0; wargv[argc]; argc++)
669 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
670 argv[argc] = q;
671 q += reslen;
672 total -= reslen;
674 argv[argc] = NULL;
676 __wine_main_argc = argc;
677 __wine_main_argv = argv;
678 __wine_main_wargv = wargv;
682 /***********************************************************************
683 * update_library_argv0
685 * Update the argv[0] global variable with the binary we have found.
687 static void update_library_argv0( const WCHAR *argv0 )
689 DWORD len = strlenW( argv0 );
691 if (len > strlenW( __wine_main_wargv[0] ))
693 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
695 strcpyW( __wine_main_wargv[0], argv0 );
697 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
698 if (len > strlen( __wine_main_argv[0] ) + 1)
700 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
702 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
706 /***********************************************************************
707 * build_command_line
709 * Build the command line of a process from the argv array.
711 * Note that it does NOT necessarily include the file name.
712 * Sometimes we don't even have any command line options at all.
714 * We must quote and escape characters so that the argv array can be rebuilt
715 * from the command line:
716 * - spaces and tabs must be quoted
717 * 'a b' -> '"a b"'
718 * - quotes must be escaped
719 * '"' -> '\"'
720 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
721 * resulting in an odd number of '\' followed by a '"'
722 * '\"' -> '\\\"'
723 * '\\"' -> '\\\\\"'
724 * - '\'s that are not followed by a '"' can be left as is
725 * 'a\b' == 'a\b'
726 * 'a\\b' == 'a\\b'
728 static BOOL build_command_line( WCHAR **argv )
730 int len;
731 WCHAR **arg;
732 LPWSTR p;
733 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
735 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
737 len = 0;
738 for (arg = argv; *arg; arg++)
740 int has_space,bcount;
741 WCHAR* a;
743 has_space=0;
744 bcount=0;
745 a=*arg;
746 if( !*a ) has_space=1;
747 while (*a!='\0') {
748 if (*a=='\\') {
749 bcount++;
750 } else {
751 if (*a==' ' || *a=='\t') {
752 has_space=1;
753 } else if (*a=='"') {
754 /* doubling of '\' preceding a '"',
755 * plus escaping of said '"'
757 len+=2*bcount+1;
759 bcount=0;
761 a++;
763 len+=(a-*arg)+1 /* for the separating space */;
764 if (has_space)
765 len+=2; /* for the quotes */
768 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
769 return FALSE;
771 p = rupp->CommandLine.Buffer;
772 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
773 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
774 for (arg = argv; *arg; arg++)
776 int has_space,has_quote;
777 WCHAR* a;
779 /* Check for quotes and spaces in this argument */
780 has_space=has_quote=0;
781 a=*arg;
782 if( !*a ) has_space=1;
783 while (*a!='\0') {
784 if (*a==' ' || *a=='\t') {
785 has_space=1;
786 if (has_quote)
787 break;
788 } else if (*a=='"') {
789 has_quote=1;
790 if (has_space)
791 break;
793 a++;
796 /* Now transfer it to the command line */
797 if (has_space)
798 *p++='"';
799 if (has_quote) {
800 int bcount;
802 bcount=0;
803 a=*arg;
804 while (*a!='\0') {
805 if (*a=='\\') {
806 *p++=*a;
807 bcount++;
808 } else {
809 if (*a=='"') {
810 int i;
812 /* Double all the '\\' preceding this '"', plus one */
813 for (i=0;i<=bcount;i++)
814 *p++='\\';
815 *p++='"';
816 } else {
817 *p++=*a;
819 bcount=0;
821 a++;
823 } else {
824 WCHAR* x = *arg;
825 while ((*p=*x++)) p++;
827 if (has_space)
828 *p++='"';
829 *p++=' ';
831 if (p > rupp->CommandLine.Buffer)
832 p--; /* remove last space */
833 *p = '\0';
835 return TRUE;
839 /***********************************************************************
840 * init_current_directory
842 * Initialize the current directory from the Unix cwd or the parent info.
844 static void init_current_directory( CURDIR *cur_dir )
846 UNICODE_STRING dir_str;
847 const char *pwd;
848 char *cwd;
849 int size;
851 /* if we received a cur dir from the parent, try this first */
853 if (cur_dir->DosPath.Length)
855 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
858 /* now try to get it from the Unix cwd */
860 for (size = 256; ; size *= 2)
862 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
863 if (getcwd( cwd, size )) break;
864 HeapFree( GetProcessHeap(), 0, cwd );
865 if (errno == ERANGE) continue;
866 cwd = NULL;
867 break;
870 /* try to use PWD if it is valid, so that we don't resolve symlinks */
872 pwd = getenv( "PWD" );
873 if (cwd)
875 struct stat st1, st2;
877 if (!pwd || stat( pwd, &st1 ) == -1 ||
878 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
879 pwd = cwd;
882 if (pwd)
884 ANSI_STRING unix_name;
885 UNICODE_STRING nt_name;
886 RtlInitAnsiString( &unix_name, pwd );
887 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
889 UNICODE_STRING dos_path;
890 /* skip the \??\ prefix, nt_name is 0 terminated */
891 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
892 RtlSetCurrentDirectory_U( &dos_path );
893 RtlFreeUnicodeString( &nt_name );
897 if (!cur_dir->DosPath.Length) /* still not initialized */
899 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
900 "starting in the Windows directory.\n", cwd ? cwd : "" );
901 RtlInitUnicodeString( &dir_str, DIR_Windows );
902 RtlSetCurrentDirectory_U( &dir_str );
904 HeapFree( GetProcessHeap(), 0, cwd );
906 done:
907 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
911 /***********************************************************************
912 * init_windows_dirs
914 * Initialize the windows and system directories from the environment.
916 static void init_windows_dirs(void)
918 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
920 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
921 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
922 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
923 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
924 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
926 DWORD len;
927 WCHAR *buffer;
929 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
931 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
932 GetEnvironmentVariableW( windirW, buffer, len );
933 DIR_Windows = buffer;
935 else DIR_Windows = default_windirW;
937 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
939 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
940 GetEnvironmentVariableW( winsysdirW, buffer, len );
941 DIR_System = buffer;
943 else
945 len = strlenW( DIR_Windows );
946 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
947 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
948 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
949 DIR_System = buffer;
952 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
953 ERR( "directory %s could not be created, error %u\n",
954 debugstr_w(DIR_Windows), GetLastError() );
955 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
956 ERR( "directory %s could not be created, error %u\n",
957 debugstr_w(DIR_System), GetLastError() );
959 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
961 len = strlenW( DIR_Windows );
962 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
963 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
964 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
965 DIR_SysWow64 = buffer;
966 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
967 ERR( "directory %s could not be created, error %u\n",
968 debugstr_w(DIR_SysWow64), GetLastError() );
971 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
972 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
974 /* set the directories in ntdll too */
975 __wine_init_windows_dir( DIR_Windows, DIR_System );
979 /***********************************************************************
980 * start_wineboot
982 * Start the wineboot process if necessary. Return the handles to wait on.
984 static void start_wineboot( HANDLE handles[2] )
986 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
988 handles[1] = 0;
989 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
991 ERR( "failed to create wineboot event, expect trouble\n" );
992 return;
994 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
996 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
997 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
998 STARTUPINFOW si;
999 PROCESS_INFORMATION pi;
1000 void *redir;
1001 WCHAR app[MAX_PATH];
1002 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1004 memset( &si, 0, sizeof(si) );
1005 si.cb = sizeof(si);
1006 si.dwFlags = STARTF_USESTDHANDLES;
1007 si.hStdInput = 0;
1008 si.hStdOutput = 0;
1009 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1011 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1012 lstrcatW( app, wineboot );
1014 Wow64DisableWow64FsRedirection( &redir );
1015 strcpyW( cmdline, app );
1016 strcatW( cmdline, args );
1017 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1019 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1020 CloseHandle( pi.hThread );
1021 handles[1] = pi.hProcess;
1023 else
1025 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1026 CloseHandle( handles[0] );
1027 handles[0] = 0;
1029 Wow64RevertWow64FsRedirection( redir );
1034 #ifdef __i386__
1035 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1036 __ASM_GLOBAL_FUNC( call_process_entry,
1037 "pushl %ebp\n\t"
1038 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1039 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1040 "movl %esp,%ebp\n\t"
1041 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1042 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1043 "pushl 8(%ebp)\n\t"
1044 "call *12(%ebp)\n\t"
1045 "leave\n\t"
1046 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1047 __ASM_CFI(".cfi_same_value %ebp\n\t")
1048 "ret" )
1049 #else
1050 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1052 return entry( peb );
1054 #endif
1056 /***********************************************************************
1057 * start_process
1059 * Startup routine of a new process. Runs on the new process stack.
1061 static DWORD WINAPI start_process( PEB *peb )
1063 IMAGE_NT_HEADERS *nt;
1064 LPTHREAD_START_ROUTINE entry;
1066 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1067 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1068 nt->OptionalHeader.AddressOfEntryPoint);
1070 if (!nt->OptionalHeader.AddressOfEntryPoint)
1072 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1073 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1074 ExitThread( 1 );
1077 if (TRACE_ON(relay))
1078 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1079 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1081 SetLastError( 0 ); /* clear error code */
1082 if (peb->BeingDebugged) DbgBreakPoint();
1083 return call_process_entry( peb, entry );
1087 /***********************************************************************
1088 * set_process_name
1090 * Change the process name in the ps output.
1092 static void set_process_name( int argc, char *argv[] )
1094 #ifdef HAVE_SETPROCTITLE
1095 setproctitle("-%s", argv[1]);
1096 #endif
1098 #ifdef HAVE_PRCTL
1099 int i, offset;
1100 char *p, *prctl_name = argv[1];
1101 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1103 #ifndef PR_SET_NAME
1104 # define PR_SET_NAME 15
1105 #endif
1107 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1108 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1110 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1112 offset = argv[1] - argv[0];
1113 memmove( argv[1] - offset, argv[1], end - argv[1] );
1114 memset( end - offset, 0, offset );
1115 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1116 argv[i-1] = NULL;
1118 else
1119 #endif /* HAVE_PRCTL */
1121 /* remove argv[0] */
1122 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1127 /***********************************************************************
1128 * __wine_kernel_init
1130 * Wine initialisation: load and start the main exe file.
1132 void CDECL __wine_kernel_init(void)
1134 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1135 static const WCHAR dotW[] = {'.',0};
1137 WCHAR *p, main_exe_name[MAX_PATH+1];
1138 PEB *peb = NtCurrentTeb()->Peb;
1139 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1140 HANDLE boot_events[2];
1141 BOOL got_environment = TRUE;
1143 /* Initialize everything */
1145 setbuf(stdout,NULL);
1146 setbuf(stderr,NULL);
1147 kernel32_handle = GetModuleHandleW(kernel32W);
1148 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1150 LOCALE_Init();
1152 if (!params->Environment)
1154 /* Copy the parent environment */
1155 if (!build_initial_environment()) exit(1);
1157 /* convert old configuration to new format */
1158 convert_old_config();
1160 got_environment = set_registry_environment( FALSE );
1161 set_additional_environment();
1164 init_windows_dirs();
1165 init_current_directory( &params->CurrentDirectory );
1167 set_process_name( __wine_main_argc, __wine_main_argv );
1168 set_library_wargv( __wine_main_argv );
1169 boot_events[0] = boot_events[1] = 0;
1171 if (peb->ProcessParameters->ImagePathName.Buffer)
1173 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1175 else
1177 struct binary_info binary_info;
1179 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1180 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1182 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1183 ExitProcess( GetLastError() );
1185 update_library_argv0( main_exe_name );
1186 if (!build_command_line( __wine_main_wargv )) goto error;
1187 start_wineboot( boot_events );
1190 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1191 p = strrchrW( main_exe_name, '.' );
1192 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1194 TRACE( "starting process name=%s argv[0]=%s\n",
1195 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1197 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1198 MODULE_get_dll_load_path(main_exe_name) );
1200 if (boot_events[0])
1202 DWORD timeout = 2 * 60 * 1000, count = 1;
1204 if (boot_events[1]) count++;
1205 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1206 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1207 ERR( "boot event wait timed out\n" );
1208 CloseHandle( boot_events[0] );
1209 if (boot_events[1]) CloseHandle( boot_events[1] );
1210 /* reload environment now that wineboot has run */
1211 set_registry_environment( got_environment );
1212 set_additional_environment();
1214 set_wow64_environment();
1216 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1218 DWORD_PTR args[1];
1219 WCHAR msgW[1024];
1220 char msg[1024];
1221 DWORD error = GetLastError();
1223 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1224 if (error == ERROR_BAD_EXE_FORMAT ||
1225 error == ERROR_INVALID_ADDRESS ||
1226 error == ERROR_NOT_ENOUGH_MEMORY)
1228 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1229 /* if we get back here, it failed */
1231 else if (error == ERROR_MOD_NOT_FOUND)
1233 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1234 else p = main_exe_name;
1235 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1237 /* args 1 and 2 are --app-name full_path */
1238 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1239 debugstr_w(__wine_main_wargv[3]) );
1240 ExitProcess( ERROR_BAD_EXE_FORMAT );
1242 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1243 ExitProcess( ERROR_FILE_NOT_FOUND );
1245 args[0] = (DWORD_PTR)main_exe_name;
1246 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1247 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1248 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1249 MESSAGE( "wine: %s", msg );
1250 ExitProcess( error );
1253 if (!params->CurrentDirectory.Handle) chdir("/"); /* avoid locking removable devices */
1255 LdrInitializeThunk( start_process, 0, 0, 0 );
1257 error:
1258 ExitProcess( GetLastError() );
1262 /***********************************************************************
1263 * build_argv
1265 * Build an argv array from a command-line.
1266 * 'reserved' is the number of args to reserve before the first one.
1268 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1270 int argc;
1271 char** argv;
1272 char *arg,*s,*d,*cmdline;
1273 int in_quotes,bcount,len;
1275 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1276 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1277 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1279 argc=reserved+1;
1280 bcount=0;
1281 in_quotes=0;
1282 s=cmdline;
1283 while (1) {
1284 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1285 /* space */
1286 argc++;
1287 /* skip the remaining spaces */
1288 while (*s==' ' || *s=='\t') {
1289 s++;
1291 if (*s=='\0')
1292 break;
1293 bcount=0;
1294 continue;
1295 } else if (*s=='\\') {
1296 /* '\', count them */
1297 bcount++;
1298 } else if ((*s=='"') && ((bcount & 1)==0)) {
1299 /* unescaped '"' */
1300 in_quotes=!in_quotes;
1301 bcount=0;
1302 } else {
1303 /* a regular character */
1304 bcount=0;
1306 s++;
1308 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1310 HeapFree( GetProcessHeap(), 0, cmdline );
1311 return NULL;
1314 arg = d = s = (char *)(argv + argc);
1315 memcpy( d, cmdline, len );
1316 bcount=0;
1317 in_quotes=0;
1318 argc=reserved;
1319 while (*s) {
1320 if ((*s==' ' || *s=='\t') && !in_quotes) {
1321 /* Close the argument and copy it */
1322 *d=0;
1323 argv[argc++]=arg;
1325 /* skip the remaining spaces */
1326 do {
1327 s++;
1328 } while (*s==' ' || *s=='\t');
1330 /* Start with a new argument */
1331 arg=d=s;
1332 bcount=0;
1333 } else if (*s=='\\') {
1334 /* '\\' */
1335 *d++=*s++;
1336 bcount++;
1337 } else if (*s=='"') {
1338 /* '"' */
1339 if ((bcount & 1)==0) {
1340 /* Preceded by an even number of '\', this is half that
1341 * number of '\', plus a '"' which we discard.
1343 d-=bcount/2;
1344 s++;
1345 in_quotes=!in_quotes;
1346 } else {
1347 /* Preceded by an odd number of '\', this is half that
1348 * number of '\' followed by a '"'
1350 d=d-bcount/2-1;
1351 *d++='"';
1352 s++;
1354 bcount=0;
1355 } else {
1356 /* a regular character */
1357 *d++=*s++;
1358 bcount=0;
1361 if (*arg) {
1362 *d='\0';
1363 argv[argc++]=arg;
1365 argv[argc]=NULL;
1367 HeapFree( GetProcessHeap(), 0, cmdline );
1368 return argv;
1372 /***********************************************************************
1373 * build_envp
1375 * Build the environment of a new child process.
1377 static char **build_envp( const WCHAR *envW )
1379 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1381 const WCHAR *end;
1382 char **envp;
1383 char *env, *p;
1384 int count = 1, length;
1385 unsigned int i;
1387 for (end = envW; *end; count++) end += strlenW(end) + 1;
1388 end++;
1389 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1390 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1391 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1393 for (p = env; *p; p += strlen(p) + 1)
1394 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1396 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1398 if (!(p = getenv(unix_vars[i]))) continue;
1399 length += strlen(unix_vars[i]) + strlen(p) + 2;
1400 count++;
1403 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1405 char **envptr = envp;
1406 char *dst = (char *)(envp + count);
1408 /* some variables must not be modified, so we get them directly from the unix env */
1409 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1411 if (!(p = getenv(unix_vars[i]))) continue;
1412 *envptr++ = strcpy( dst, unix_vars[i] );
1413 strcat( dst, "=" );
1414 strcat( dst, p );
1415 dst += strlen(dst) + 1;
1418 /* now put the Windows environment strings */
1419 for (p = env; *p; p += strlen(p) + 1)
1421 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1422 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1423 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1424 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1425 if (is_special_env_var( p )) /* prefix it with "WINE" */
1427 *envptr++ = strcpy( dst, "WINE" );
1428 strcat( dst, p );
1430 else
1432 *envptr++ = strcpy( dst, p );
1434 dst += strlen(dst) + 1;
1436 *envptr = 0;
1438 HeapFree( GetProcessHeap(), 0, env );
1439 return envp;
1443 /***********************************************************************
1444 * fork_and_exec
1446 * Fork and exec a new Unix binary, checking for errors.
1448 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1449 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1451 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1452 int pid, err;
1453 char **argv, **envp;
1455 if (!env) env = GetEnvironmentStringsW();
1457 #ifdef HAVE_PIPE2
1458 if (pipe2( fd, O_CLOEXEC ) == -1)
1459 #endif
1461 if (pipe(fd) == -1)
1463 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1464 return -1;
1466 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1467 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1470 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1472 HANDLE hstdin, hstdout, hstderr;
1474 if (startup->dwFlags & STARTF_USESTDHANDLES)
1476 hstdin = startup->hStdInput;
1477 hstdout = startup->hStdOutput;
1478 hstderr = startup->hStdError;
1480 else
1482 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1483 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1484 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1487 if (is_console_handle( hstdin ))
1488 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1489 if (is_console_handle( hstdout ))
1490 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1491 if (is_console_handle( hstderr ))
1492 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1493 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1494 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1495 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1498 argv = build_argv( cmdline, 0 );
1499 envp = build_envp( env );
1501 if (!(pid = fork())) /* child */
1503 if (!(pid = fork())) /* grandchild */
1505 close( fd[0] );
1507 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1509 int nullfd = open( "/dev/null", O_RDWR );
1510 setsid();
1511 /* close stdin and stdout */
1512 if (nullfd != -1)
1514 dup2( nullfd, 0 );
1515 dup2( nullfd, 1 );
1516 close( nullfd );
1519 else
1521 if (stdin_fd != -1)
1523 dup2( stdin_fd, 0 );
1524 close( stdin_fd );
1526 if (stdout_fd != -1)
1528 dup2( stdout_fd, 1 );
1529 close( stdout_fd );
1531 if (stderr_fd != -1)
1533 dup2( stderr_fd, 2 );
1534 close( stderr_fd );
1538 /* Reset signals that we previously set to SIG_IGN */
1539 signal( SIGPIPE, SIG_DFL );
1541 if (newdir) chdir(newdir);
1543 if (argv && envp) execve( filename, argv, envp );
1546 if (pid <= 0) /* grandchild if exec failed or child if fork failed */
1548 err = errno;
1549 write( fd[1], &err, sizeof(err) );
1550 _exit(1);
1553 _exit(0); /* child if fork succeeded */
1555 HeapFree( GetProcessHeap(), 0, argv );
1556 HeapFree( GetProcessHeap(), 0, envp );
1557 if (stdin_fd != -1) close( stdin_fd );
1558 if (stdout_fd != -1) close( stdout_fd );
1559 if (stderr_fd != -1) close( stderr_fd );
1560 close( fd[1] );
1561 if (pid != -1)
1563 /* reap child */
1564 do {
1565 err = waitpid(pid, NULL, 0);
1566 } while (err < 0 && errno == EINTR);
1568 if (read( fd[0], &err, sizeof(err) ) > 0) /* exec or second fork failed */
1570 errno = err;
1571 pid = -1;
1574 if (pid == -1) FILE_SetDosError();
1575 close( fd[0] );
1576 return pid;
1580 static inline DWORD append_string( void **ptr, const WCHAR *str )
1582 DWORD len = strlenW( str );
1583 memcpy( *ptr, str, len * sizeof(WCHAR) );
1584 *ptr = (WCHAR *)*ptr + len;
1585 return len * sizeof(WCHAR);
1588 /***********************************************************************
1589 * create_startup_info
1591 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1592 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1593 const STARTUPINFOW *startup, DWORD *info_size )
1595 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1596 const WCHAR *title;
1597 startup_info_t *info;
1598 DWORD size;
1599 void *ptr;
1600 UNICODE_STRING newdir;
1601 WCHAR imagepath[MAX_PATH];
1602 HANDLE hstdin, hstdout, hstderr;
1604 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1605 lstrcpynW( imagepath, filename, MAX_PATH );
1606 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1607 lstrcpynW( imagepath, filename, MAX_PATH );
1609 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1611 newdir.Buffer = NULL;
1612 if (cur_dir)
1614 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1615 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1616 else
1617 cur_dir = NULL;
1619 if (!cur_dir)
1621 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1622 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1623 else
1624 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1626 title = startup->lpTitle ? startup->lpTitle : imagepath;
1628 size = sizeof(*info);
1629 size += strlenW( cur_dir ) * sizeof(WCHAR);
1630 size += cur_params->DllPath.Length;
1631 size += strlenW( imagepath ) * sizeof(WCHAR);
1632 size += strlenW( cmdline ) * sizeof(WCHAR);
1633 size += strlenW( title ) * sizeof(WCHAR);
1634 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1635 /* FIXME: shellinfo */
1636 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1637 size = (size + 1) & ~1;
1638 *info_size = size;
1640 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1642 info->console_flags = cur_params->ConsoleFlags;
1643 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1644 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1646 if (startup->dwFlags & STARTF_USESTDHANDLES)
1648 hstdin = startup->hStdInput;
1649 hstdout = startup->hStdOutput;
1650 hstderr = startup->hStdError;
1652 else
1654 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1655 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1656 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1658 info->hstdin = wine_server_obj_handle( hstdin );
1659 info->hstdout = wine_server_obj_handle( hstdout );
1660 info->hstderr = wine_server_obj_handle( hstderr );
1661 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1663 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1664 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1665 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1666 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1668 else
1670 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1671 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1672 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1675 info->x = startup->dwX;
1676 info->y = startup->dwY;
1677 info->xsize = startup->dwXSize;
1678 info->ysize = startup->dwYSize;
1679 info->xchars = startup->dwXCountChars;
1680 info->ychars = startup->dwYCountChars;
1681 info->attribute = startup->dwFillAttribute;
1682 info->flags = startup->dwFlags;
1683 info->show = startup->wShowWindow;
1685 ptr = info + 1;
1686 info->curdir_len = append_string( &ptr, cur_dir );
1687 info->dllpath_len = cur_params->DllPath.Length;
1688 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1689 ptr = (char *)ptr + cur_params->DllPath.Length;
1690 info->imagepath_len = append_string( &ptr, imagepath );
1691 info->cmdline_len = append_string( &ptr, cmdline );
1692 info->title_len = append_string( &ptr, title );
1693 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1694 if (startup->lpReserved2 && startup->cbReserved2)
1696 info->runtime_len = startup->cbReserved2;
1697 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1700 done:
1701 RtlFreeUnicodeString( &newdir );
1702 return info;
1705 /***********************************************************************
1706 * get_alternate_loader
1708 * Get the name of the alternate (32 or 64 bit) Wine loader.
1710 static const char *get_alternate_loader( char **ret_env )
1712 char *env;
1713 const char *loader = NULL;
1714 const char *loader_env = getenv( "WINELOADER" );
1716 *ret_env = NULL;
1718 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1720 if (loader_env)
1722 int len = strlen( loader_env );
1723 if (!is_win64)
1725 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1726 strcpy( env, "WINELOADER=" );
1727 strcat( env, loader_env );
1728 strcat( env, "64" );
1730 else
1732 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1733 strcpy( env, "WINELOADER=" );
1734 strcat( env, loader_env );
1735 len += sizeof("WINELOADER=") - 1;
1736 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1738 if (!loader)
1740 if ((loader = strrchr( env, '/' ))) loader++;
1741 else loader = env;
1743 *ret_env = env;
1745 if (!loader) loader = is_win64 ? "wine" : "wine64";
1746 return loader;
1749 #ifdef __APPLE__
1750 /***********************************************************************
1751 * terminate_main_thread
1753 * On some versions of Mac OS X, the execve system call fails with
1754 * ENOTSUP if the process has multiple threads. Wine is always multi-
1755 * threaded on Mac OS X because it specifically reserves the main thread
1756 * for use by the system frameworks (see apple_main_thread() in
1757 * libs/wine/loader.c). So, when we need to exec without first forking,
1758 * we need to terminate the main thread first. We do this by installing
1759 * a custom run loop source onto the main run loop and signaling it.
1760 * The source's "perform" callback is pthread_exit and it will be
1761 * executed on the main thread, terminating it.
1763 * Returns TRUE if there's still hope the main thread has terminated or
1764 * will soon. Return FALSE if we've given up.
1766 static BOOL terminate_main_thread(void)
1768 static int delayms;
1770 if (!delayms)
1772 CFRunLoopSourceContext source_context = { 0 };
1773 CFRunLoopSourceRef source;
1775 source_context.perform = pthread_exit;
1776 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1777 return FALSE;
1779 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1780 CFRunLoopSourceSignal( source );
1781 CFRunLoopWakeUp( CFRunLoopGetMain() );
1782 CFRelease( source );
1784 delayms = 20;
1787 if (delayms > 1000)
1788 return FALSE;
1790 usleep(delayms * 1000);
1791 delayms *= 2;
1793 return TRUE;
1795 #endif
1797 /***********************************************************************
1798 * exec_loader
1800 static pid_t exec_loader( LPCWSTR cmd_line, unsigned int flags, int socketfd,
1801 int stdin_fd, int stdout_fd, const char *unixdir, char *winedebug,
1802 const struct binary_info *binary_info, int exec_only )
1804 pid_t pid;
1805 char *wineloader = NULL;
1806 const char *loader = NULL;
1807 char **argv;
1809 argv = build_argv( cmd_line, 1 );
1811 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1812 loader = get_alternate_loader( &wineloader );
1814 if (exec_only || !(pid = fork())) /* child */
1816 if (exec_only || !(pid = fork())) /* grandchild */
1818 char preloader_reserve[64], socket_env[64];
1820 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1822 int fd = open( "/dev/null", O_RDWR );
1823 setsid();
1824 /* close stdin and stdout */
1825 if (fd != -1)
1827 dup2( fd, 0 );
1828 dup2( fd, 1 );
1829 close( fd );
1832 else
1834 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1835 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1838 if (stdin_fd != -1) close( stdin_fd );
1839 if (stdout_fd != -1) close( stdout_fd );
1841 /* Reset signals that we previously set to SIG_IGN */
1842 signal( SIGPIPE, SIG_DFL );
1844 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
1845 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1846 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1848 putenv( preloader_reserve );
1849 putenv( socket_env );
1850 if (winedebug) putenv( winedebug );
1851 if (wineloader) putenv( wineloader );
1852 if (unixdir) chdir(unixdir);
1854 if (argv)
1858 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1860 #ifdef __APPLE__
1861 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1862 #else
1863 while (0);
1864 #endif
1866 _exit(1);
1869 _exit(pid == -1);
1872 if (pid != -1)
1874 /* reap child */
1875 pid_t wret;
1876 do {
1877 wret = waitpid(pid, NULL, 0);
1878 } while (wret < 0 && errno == EINTR);
1881 HeapFree( GetProcessHeap(), 0, wineloader );
1882 HeapFree( GetProcessHeap(), 0, argv );
1883 return pid;
1886 /***********************************************************************
1887 * create_process
1889 * Create a new process. If hFile is a valid handle we have an exe
1890 * file, otherwise it is a Winelib app.
1892 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1893 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1894 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1895 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1896 const struct binary_info *binary_info, int exec_only )
1898 BOOL ret, success = FALSE;
1899 HANDLE process_info;
1900 WCHAR *env_end;
1901 char *winedebug = NULL;
1902 startup_info_t *startup_info;
1903 DWORD startup_info_size;
1904 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1905 pid_t pid;
1906 int err;
1908 if (!is_win64 && !is_wow64 && (binary_info->flags & BINARY_FLAG_64BIT))
1910 ERR( "starting 64-bit process %s not supported in 32-bit wineprefix\n", debugstr_w(filename) );
1911 SetLastError( ERROR_BAD_EXE_FORMAT );
1912 return FALSE;
1915 /* create the socket for the new process */
1917 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1919 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1920 return FALSE;
1923 if (exec_only) /* things are much simpler in this case */
1925 wine_server_send_fd( socketfd[1] );
1926 close( socketfd[1] );
1927 SERVER_START_REQ( new_process )
1929 req->create_flags = flags;
1930 req->socket_fd = socketfd[1];
1931 req->exe_file = wine_server_obj_handle( hFile );
1932 ret = !wine_server_call_err( req );
1934 SERVER_END_REQ;
1936 if (ret) exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
1937 winedebug, binary_info, TRUE );
1939 close( socketfd[0] );
1940 return FALSE;
1943 RtlAcquirePebLock();
1945 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1946 &startup_info_size )))
1948 RtlReleasePebLock();
1949 close( socketfd[0] );
1950 close( socketfd[1] );
1951 return FALSE;
1953 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
1954 env_end = env;
1955 while (*env_end)
1957 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1958 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1960 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1961 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1962 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1964 env_end += strlenW(env_end) + 1;
1966 env_end++;
1968 wine_server_send_fd( socketfd[1] );
1969 close( socketfd[1] );
1971 /* create the process on the server side */
1973 SERVER_START_REQ( new_process )
1975 req->inherit_all = inherit;
1976 req->create_flags = flags;
1977 req->socket_fd = socketfd[1];
1978 req->exe_file = wine_server_obj_handle( hFile );
1979 req->process_access = PROCESS_ALL_ACCESS;
1980 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1981 req->thread_access = THREAD_ALL_ACCESS;
1982 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1983 req->info_size = startup_info_size;
1985 wine_server_add_data( req, startup_info, startup_info_size );
1986 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
1987 if ((ret = !wine_server_call_err( req )))
1989 info->dwProcessId = (DWORD)reply->pid;
1990 info->dwThreadId = (DWORD)reply->tid;
1991 info->hProcess = wine_server_ptr_handle( reply->phandle );
1992 info->hThread = wine_server_ptr_handle( reply->thandle );
1994 process_info = wine_server_ptr_handle( reply->info );
1996 SERVER_END_REQ;
1998 RtlReleasePebLock();
1999 if (!ret)
2001 close( socketfd[0] );
2002 HeapFree( GetProcessHeap(), 0, startup_info );
2003 HeapFree( GetProcessHeap(), 0, winedebug );
2004 return FALSE;
2007 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
2009 if (startup_info->hstdin)
2010 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
2011 FILE_READ_DATA, &stdin_fd, NULL );
2012 if (startup_info->hstdout)
2013 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
2014 FILE_WRITE_DATA, &stdout_fd, NULL );
2016 HeapFree( GetProcessHeap(), 0, startup_info );
2018 /* create the child process */
2020 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2021 winedebug, binary_info, FALSE );
2023 if (stdin_fd != -1) close( stdin_fd );
2024 if (stdout_fd != -1) close( stdout_fd );
2025 close( socketfd[0] );
2026 HeapFree( GetProcessHeap(), 0, winedebug );
2027 if (pid == -1)
2029 FILE_SetDosError();
2030 goto error;
2033 /* wait for the new process info to be ready */
2035 WaitForSingleObject( process_info, INFINITE );
2036 SERVER_START_REQ( get_new_process_info )
2038 req->info = wine_server_obj_handle( process_info );
2039 wine_server_call( req );
2040 success = reply->success;
2041 err = reply->exit_code;
2043 SERVER_END_REQ;
2045 if (!success)
2047 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2048 goto error;
2050 CloseHandle( process_info );
2051 return success;
2053 error:
2054 CloseHandle( process_info );
2055 CloseHandle( info->hProcess );
2056 CloseHandle( info->hThread );
2057 info->hProcess = info->hThread = 0;
2058 info->dwProcessId = info->dwThreadId = 0;
2059 return FALSE;
2063 /***********************************************************************
2064 * create_vdm_process
2066 * Create a new VDM process for a 16-bit or DOS application.
2068 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2069 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2070 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2071 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2072 const struct binary_info *binary_info, int exec_only )
2074 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2076 BOOL ret;
2077 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
2078 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
2080 if (!new_cmd_line)
2082 SetLastError( ERROR_OUTOFMEMORY );
2083 return FALSE;
2085 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
2086 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2087 flags, startup, info, unixdir, binary_info, exec_only );
2088 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2089 return ret;
2093 /***********************************************************************
2094 * create_cmd_process
2096 * Create a new cmd shell process for a .BAT file.
2098 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2099 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2100 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2101 LPPROCESS_INFORMATION info )
2104 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2105 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2106 WCHAR comspec[MAX_PATH];
2107 WCHAR *newcmdline;
2108 BOOL ret;
2110 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2111 return FALSE;
2112 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2113 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2114 return FALSE;
2116 strcpyW( newcmdline, comspec );
2117 strcatW( newcmdline, slashcW );
2118 strcatW( newcmdline, cmd_line );
2119 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2120 flags, env, cur_dir, startup, info );
2121 HeapFree( GetProcessHeap(), 0, newcmdline );
2122 return ret;
2126 /*************************************************************************
2127 * get_file_name
2129 * Helper for CreateProcess: retrieve the file name to load from the
2130 * app name and command line. Store the file name in buffer, and
2131 * return a possibly modified command line.
2132 * Also returns a handle to the opened file if it's a Windows binary.
2134 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2135 int buflen, HANDLE *handle, struct binary_info *binary_info )
2137 static const WCHAR quotesW[] = {'"','%','s','"',0};
2139 WCHAR *name, *pos, *first_space, *ret = NULL;
2140 const WCHAR *p;
2142 /* if we have an app name, everything is easy */
2144 if (appname)
2146 /* use the unmodified app name as file name */
2147 lstrcpynW( buffer, appname, buflen );
2148 *handle = open_exe_file( buffer, binary_info );
2149 if (!(ret = cmdline) || !cmdline[0])
2151 /* no command-line, create one */
2152 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2153 sprintfW( ret, quotesW, appname );
2155 return ret;
2158 /* first check for a quoted file name */
2160 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2162 int len = p - cmdline - 1;
2163 /* extract the quoted portion as file name */
2164 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2165 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2166 name[len] = 0;
2168 if (!find_exe_file( name, buffer, buflen, handle, binary_info )) goto done;
2169 ret = cmdline; /* no change necessary */
2170 goto done;
2173 /* now try the command-line word by word */
2175 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2176 return NULL;
2177 pos = name;
2178 p = cmdline;
2179 first_space = NULL;
2181 for (;;)
2183 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2184 *pos = 0;
2185 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2187 ret = cmdline;
2188 break;
2190 if (!first_space) first_space = pos;
2191 if (!(*pos++ = *p++)) break;
2194 if (!ret)
2196 SetLastError( ERROR_FILE_NOT_FOUND );
2198 else if (first_space) /* build a new command-line with quotes */
2200 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2201 goto done;
2202 sprintfW( ret, quotesW, name );
2203 strcatW( ret, p );
2206 done:
2207 HeapFree( GetProcessHeap(), 0, name );
2208 return ret;
2212 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2213 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2214 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2215 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2216 LPPROCESS_INFORMATION info )
2218 BOOL retv = FALSE;
2219 HANDLE hFile = 0;
2220 char *unixdir = NULL;
2221 WCHAR name[MAX_PATH];
2222 WCHAR *tidy_cmdline, *p, *envW = env;
2223 struct binary_info binary_info;
2225 /* Process the AppName and/or CmdLine to get module name and path */
2227 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2229 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2230 &hFile, &binary_info )))
2231 return FALSE;
2232 if (hFile == INVALID_HANDLE_VALUE) goto done;
2234 /* Warn if unsupported features are used */
2236 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2237 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2238 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2239 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2240 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2242 if (cur_dir)
2244 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2246 SetLastError(ERROR_DIRECTORY);
2247 goto done;
2250 else
2252 WCHAR buf[MAX_PATH];
2253 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2256 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2258 char *e = env;
2259 DWORD lenW;
2261 while (*e) e += strlen(e) + 1;
2262 e++; /* final null */
2263 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, NULL, 0 );
2264 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2265 MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, envW, lenW );
2266 flags |= CREATE_UNICODE_ENVIRONMENT;
2269 info->hThread = info->hProcess = 0;
2270 info->dwProcessId = info->dwThreadId = 0;
2272 if (binary_info.flags & BINARY_FLAG_DLL)
2274 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2275 SetLastError( ERROR_BAD_EXE_FORMAT );
2277 else switch (binary_info.type)
2279 case BINARY_PE:
2280 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2281 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2282 binary_info.res_start, binary_info.res_end );
2283 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2284 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2285 break;
2286 case BINARY_OS216:
2287 case BINARY_WIN16:
2288 case BINARY_DOS:
2289 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2290 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2291 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2292 break;
2293 case BINARY_UNIX_LIB:
2294 TRACE( "starting %s as %d-bit Winelib app\n",
2295 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2296 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2297 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2298 break;
2299 case BINARY_UNKNOWN:
2300 /* check for .com or .bat extension */
2301 if ((p = strrchrW( name, '.' )))
2303 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2305 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2306 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2307 inherit, flags, startup_info, info, unixdir,
2308 &binary_info, FALSE );
2309 break;
2311 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2313 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2314 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2315 inherit, flags, startup_info, info );
2316 break;
2319 /* fall through */
2320 case BINARY_UNIX_EXE:
2322 /* unknown file, try as unix executable */
2323 char *unix_name;
2325 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2327 if ((unix_name = wine_get_unix_file_name( name )))
2329 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2330 HeapFree( GetProcessHeap(), 0, unix_name );
2333 break;
2335 if (hFile) CloseHandle( hFile );
2337 done:
2338 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2339 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2340 HeapFree( GetProcessHeap(), 0, unixdir );
2341 if (retv)
2342 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2343 return retv;
2347 /**********************************************************************
2348 * CreateProcessA (KERNEL32.@)
2350 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2351 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2352 DWORD flags, LPVOID env, LPCSTR cur_dir,
2353 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2355 BOOL ret = FALSE;
2356 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2357 UNICODE_STRING desktopW, titleW;
2358 STARTUPINFOW infoW;
2360 desktopW.Buffer = NULL;
2361 titleW.Buffer = NULL;
2362 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2363 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2364 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2366 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2367 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2369 memcpy( &infoW, startup_info, sizeof(infoW) );
2370 infoW.lpDesktop = desktopW.Buffer;
2371 infoW.lpTitle = titleW.Buffer;
2373 if (startup_info->lpReserved)
2374 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2375 debugstr_a(startup_info->lpReserved));
2377 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2378 inherit, flags, env, cur_dirW, &infoW, info );
2379 done:
2380 HeapFree( GetProcessHeap(), 0, app_nameW );
2381 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2382 HeapFree( GetProcessHeap(), 0, cur_dirW );
2383 RtlFreeUnicodeString( &desktopW );
2384 RtlFreeUnicodeString( &titleW );
2385 return ret;
2389 /**********************************************************************
2390 * CreateProcessW (KERNEL32.@)
2392 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2393 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2394 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2395 LPPROCESS_INFORMATION info )
2397 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2398 inherit, flags, env, cur_dir, startup_info, info);
2402 /**********************************************************************
2403 * exec_process
2405 static void exec_process( LPCWSTR name )
2407 HANDLE hFile;
2408 WCHAR *p;
2409 STARTUPINFOW startup_info;
2410 PROCESS_INFORMATION info;
2411 struct binary_info binary_info;
2413 hFile = open_exe_file( name, &binary_info );
2414 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2416 memset( &startup_info, 0, sizeof(startup_info) );
2417 startup_info.cb = sizeof(startup_info);
2419 /* Determine executable type */
2421 if (binary_info.flags & BINARY_FLAG_DLL) return;
2422 switch (binary_info.type)
2424 case BINARY_PE:
2425 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2426 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2427 binary_info.res_start, binary_info.res_end );
2428 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2429 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2430 break;
2431 case BINARY_UNIX_LIB:
2432 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2433 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2434 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2435 break;
2436 case BINARY_UNKNOWN:
2437 /* check for .com or .pif extension */
2438 if (!(p = strrchrW( name, '.' ))) break;
2439 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2440 /* fall through */
2441 case BINARY_OS216:
2442 case BINARY_WIN16:
2443 case BINARY_DOS:
2444 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2445 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2446 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2447 break;
2448 default:
2449 break;
2451 CloseHandle( hFile );
2455 /***********************************************************************
2456 * wait_input_idle
2458 * Wrapper to call WaitForInputIdle USER function
2460 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2462 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2464 HMODULE mod = GetModuleHandleA( "user32.dll" );
2465 if (mod)
2467 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2468 if (ptr) return ptr( process, timeout );
2470 return 0;
2474 /***********************************************************************
2475 * WinExec (KERNEL32.@)
2477 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2479 PROCESS_INFORMATION info;
2480 STARTUPINFOA startup;
2481 char *cmdline;
2482 UINT ret;
2484 memset( &startup, 0, sizeof(startup) );
2485 startup.cb = sizeof(startup);
2486 startup.dwFlags = STARTF_USESHOWWINDOW;
2487 startup.wShowWindow = nCmdShow;
2489 /* cmdline needs to be writable for CreateProcess */
2490 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2491 strcpy( cmdline, lpCmdLine );
2493 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2494 0, NULL, NULL, &startup, &info ))
2496 /* Give 30 seconds to the app to come up */
2497 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2498 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2499 ret = 33;
2500 /* Close off the handles */
2501 CloseHandle( info.hThread );
2502 CloseHandle( info.hProcess );
2504 else if ((ret = GetLastError()) >= 32)
2506 FIXME("Strange error set by CreateProcess: %d\n", ret );
2507 ret = 11;
2509 HeapFree( GetProcessHeap(), 0, cmdline );
2510 return ret;
2514 /**********************************************************************
2515 * LoadModule (KERNEL32.@)
2517 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2519 LOADPARMS32 *params = paramBlock;
2520 PROCESS_INFORMATION info;
2521 STARTUPINFOA startup;
2522 DWORD ret;
2523 LPSTR cmdline, p;
2524 char filename[MAX_PATH];
2525 BYTE len;
2527 if (!name) return ERROR_FILE_NOT_FOUND;
2529 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2530 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2531 return GetLastError();
2533 len = (BYTE)params->lpCmdLine[0];
2534 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2535 return ERROR_NOT_ENOUGH_MEMORY;
2537 strcpy( cmdline, filename );
2538 p = cmdline + strlen(cmdline);
2539 *p++ = ' ';
2540 memcpy( p, params->lpCmdLine + 1, len );
2541 p[len] = 0;
2543 memset( &startup, 0, sizeof(startup) );
2544 startup.cb = sizeof(startup);
2545 if (params->lpCmdShow)
2547 startup.dwFlags = STARTF_USESHOWWINDOW;
2548 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2551 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2552 params->lpEnvAddress, NULL, &startup, &info ))
2554 /* Give 30 seconds to the app to come up */
2555 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2556 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2557 ret = 33;
2558 /* Close off the handles */
2559 CloseHandle( info.hThread );
2560 CloseHandle( info.hProcess );
2562 else if ((ret = GetLastError()) >= 32)
2564 FIXME("Strange error set by CreateProcess: %u\n", ret );
2565 ret = 11;
2568 HeapFree( GetProcessHeap(), 0, cmdline );
2569 return ret;
2573 /******************************************************************************
2574 * TerminateProcess (KERNEL32.@)
2576 * Terminates a process.
2578 * PARAMS
2579 * handle [I] Process to terminate.
2580 * exit_code [I] Exit code.
2582 * RETURNS
2583 * Success: TRUE.
2584 * Failure: FALSE, check GetLastError().
2586 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2588 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2589 if (status) SetLastError( RtlNtStatusToDosError(status) );
2590 return !status;
2593 /***********************************************************************
2594 * ExitProcess (KERNEL32.@)
2596 * Exits the current process.
2598 * PARAMS
2599 * status [I] Status code to exit with.
2601 * RETURNS
2602 * Nothing.
2604 #ifdef __i386__
2605 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2606 "pushl %ebp\n\t"
2607 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2608 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2609 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2610 "pushl 8(%ebp)\n\t"
2611 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2612 "leave\n\t"
2613 "ret $4" )
2615 void WINAPI process_ExitProcess( DWORD status )
2617 LdrShutdownProcess();
2618 NtTerminateProcess(GetCurrentProcess(), status);
2619 exit(status);
2622 #else
2624 void WINAPI ExitProcess( DWORD status )
2626 LdrShutdownProcess();
2627 NtTerminateProcess(GetCurrentProcess(), status);
2628 exit(status);
2631 #endif
2633 /***********************************************************************
2634 * GetExitCodeProcess [KERNEL32.@]
2636 * Gets termination status of specified process.
2638 * PARAMS
2639 * hProcess [in] Handle to the process.
2640 * lpExitCode [out] Address to receive termination status.
2642 * RETURNS
2643 * Success: TRUE
2644 * Failure: FALSE
2646 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2648 NTSTATUS status;
2649 PROCESS_BASIC_INFORMATION pbi;
2651 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2652 sizeof(pbi), NULL);
2653 if (status == STATUS_SUCCESS)
2655 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2656 return TRUE;
2658 SetLastError( RtlNtStatusToDosError(status) );
2659 return FALSE;
2663 /***********************************************************************
2664 * SetErrorMode (KERNEL32.@)
2666 UINT WINAPI SetErrorMode( UINT mode )
2668 UINT old;
2670 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2671 &old, sizeof(old), NULL );
2672 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2673 &mode, sizeof(mode) );
2674 return old;
2677 /***********************************************************************
2678 * GetErrorMode (KERNEL32.@)
2680 UINT WINAPI GetErrorMode( void )
2682 UINT mode;
2684 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2685 &mode, sizeof(mode), NULL );
2686 return mode;
2689 /**********************************************************************
2690 * TlsAlloc [KERNEL32.@]
2692 * Allocates a thread local storage index.
2694 * RETURNS
2695 * Success: TLS index.
2696 * Failure: 0xFFFFFFFF
2698 DWORD WINAPI TlsAlloc( void )
2700 DWORD index;
2701 PEB * const peb = NtCurrentTeb()->Peb;
2703 RtlAcquirePebLock();
2704 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2705 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2706 else
2708 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2709 if (index != ~0U)
2711 if (!NtCurrentTeb()->TlsExpansionSlots &&
2712 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2713 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2715 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2716 index = ~0U;
2717 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2719 else
2721 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2722 index += TLS_MINIMUM_AVAILABLE;
2725 else SetLastError( ERROR_NO_MORE_ITEMS );
2727 RtlReleasePebLock();
2728 return index;
2732 /**********************************************************************
2733 * TlsFree [KERNEL32.@]
2735 * Releases a thread local storage index, making it available for reuse.
2737 * PARAMS
2738 * index [in] TLS index to free.
2740 * RETURNS
2741 * Success: TRUE
2742 * Failure: FALSE
2744 BOOL WINAPI TlsFree( DWORD index )
2746 BOOL ret;
2748 RtlAcquirePebLock();
2749 if (index >= TLS_MINIMUM_AVAILABLE)
2751 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2752 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2754 else
2756 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2757 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2759 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2760 else SetLastError( ERROR_INVALID_PARAMETER );
2761 RtlReleasePebLock();
2762 return ret;
2766 /**********************************************************************
2767 * TlsGetValue [KERNEL32.@]
2769 * Gets value in a thread's TLS slot.
2771 * PARAMS
2772 * index [in] TLS index to retrieve value for.
2774 * RETURNS
2775 * Success: Value stored in calling thread's TLS slot for index.
2776 * Failure: 0 and GetLastError() returns NO_ERROR.
2778 LPVOID WINAPI TlsGetValue( DWORD index )
2780 LPVOID ret;
2782 if (index < TLS_MINIMUM_AVAILABLE)
2784 ret = NtCurrentTeb()->TlsSlots[index];
2786 else
2788 index -= TLS_MINIMUM_AVAILABLE;
2789 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2791 SetLastError( ERROR_INVALID_PARAMETER );
2792 return NULL;
2794 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2795 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2797 SetLastError( ERROR_SUCCESS );
2798 return ret;
2802 /**********************************************************************
2803 * TlsSetValue [KERNEL32.@]
2805 * Stores a value in the thread's TLS slot.
2807 * PARAMS
2808 * index [in] TLS index to set value for.
2809 * value [in] Value to be stored.
2811 * RETURNS
2812 * Success: TRUE
2813 * Failure: FALSE
2815 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2817 if (index < TLS_MINIMUM_AVAILABLE)
2819 NtCurrentTeb()->TlsSlots[index] = value;
2821 else
2823 index -= TLS_MINIMUM_AVAILABLE;
2824 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2826 SetLastError( ERROR_INVALID_PARAMETER );
2827 return FALSE;
2829 if (!NtCurrentTeb()->TlsExpansionSlots &&
2830 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2831 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2833 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2834 return FALSE;
2836 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2838 return TRUE;
2842 /***********************************************************************
2843 * GetProcessFlags (KERNEL32.@)
2845 DWORD WINAPI GetProcessFlags( DWORD processid )
2847 IMAGE_NT_HEADERS *nt;
2848 DWORD flags = 0;
2850 if (processid && processid != GetCurrentProcessId()) return 0;
2852 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2854 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2855 flags |= PDB32_CONSOLE_PROC;
2857 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2858 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2859 return flags;
2863 /*********************************************************************
2864 * OpenProcess (KERNEL32.@)
2866 * Opens a handle to a process.
2868 * PARAMS
2869 * access [I] Desired access rights assigned to the returned handle.
2870 * inherit [I] Determines whether or not child processes will inherit the handle.
2871 * id [I] Process identifier of the process to get a handle to.
2873 * RETURNS
2874 * Success: Valid handle to the specified process.
2875 * Failure: NULL, check GetLastError().
2877 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2879 NTSTATUS status;
2880 HANDLE handle;
2881 OBJECT_ATTRIBUTES attr;
2882 CLIENT_ID cid;
2884 cid.UniqueProcess = ULongToHandle(id);
2885 cid.UniqueThread = 0; /* FIXME ? */
2887 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2888 attr.RootDirectory = NULL;
2889 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2890 attr.SecurityDescriptor = NULL;
2891 attr.SecurityQualityOfService = NULL;
2892 attr.ObjectName = NULL;
2894 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2896 status = NtOpenProcess(&handle, access, &attr, &cid);
2897 if (status != STATUS_SUCCESS)
2899 SetLastError( RtlNtStatusToDosError(status) );
2900 return NULL;
2902 return handle;
2906 /*********************************************************************
2907 * GetProcessId (KERNEL32.@)
2909 * Gets the a unique identifier of a process.
2911 * PARAMS
2912 * hProcess [I] Handle to the process.
2914 * RETURNS
2915 * Success: TRUE.
2916 * Failure: FALSE, check GetLastError().
2918 * NOTES
2920 * The identifier is unique only on the machine and only until the process
2921 * exits (including system shutdown).
2923 DWORD WINAPI GetProcessId( HANDLE hProcess )
2925 NTSTATUS status;
2926 PROCESS_BASIC_INFORMATION pbi;
2928 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2929 sizeof(pbi), NULL);
2930 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2931 SetLastError( RtlNtStatusToDosError(status) );
2932 return 0;
2936 /*********************************************************************
2937 * CloseHandle (KERNEL32.@)
2939 * Closes a handle.
2941 * PARAMS
2942 * handle [I] Handle to close.
2944 * RETURNS
2945 * Success: TRUE.
2946 * Failure: FALSE, check GetLastError().
2948 BOOL WINAPI CloseHandle( HANDLE handle )
2950 NTSTATUS status;
2952 /* stdio handles need special treatment */
2953 if (handle == (HANDLE)STD_INPUT_HANDLE)
2954 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
2955 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
2956 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
2957 else if (handle == (HANDLE)STD_ERROR_HANDLE)
2958 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
2960 if (is_console_handle(handle))
2961 return CloseConsoleHandle(handle);
2963 status = NtClose( handle );
2964 if (status) SetLastError( RtlNtStatusToDosError(status) );
2965 return !status;
2969 /*********************************************************************
2970 * GetHandleInformation (KERNEL32.@)
2972 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2974 OBJECT_DATA_INFORMATION info;
2975 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2977 if (status) SetLastError( RtlNtStatusToDosError(status) );
2978 else if (flags)
2980 *flags = 0;
2981 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2982 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2984 return !status;
2988 /*********************************************************************
2989 * SetHandleInformation (KERNEL32.@)
2991 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2993 OBJECT_DATA_INFORMATION info;
2994 NTSTATUS status;
2996 /* if not setting both fields, retrieve current value first */
2997 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2998 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3000 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3002 SetLastError( RtlNtStatusToDosError(status) );
3003 return FALSE;
3006 if (mask & HANDLE_FLAG_INHERIT)
3007 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3008 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3009 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3011 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3012 if (status) SetLastError( RtlNtStatusToDosError(status) );
3013 return !status;
3017 /*********************************************************************
3018 * DuplicateHandle (KERNEL32.@)
3020 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3021 HANDLE dest_process, HANDLE *dest,
3022 DWORD access, BOOL inherit, DWORD options )
3024 NTSTATUS status;
3026 if (is_console_handle(source))
3028 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3029 if (source_process != dest_process ||
3030 source_process != GetCurrentProcess())
3032 SetLastError(ERROR_INVALID_PARAMETER);
3033 return FALSE;
3035 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3036 return (*dest != INVALID_HANDLE_VALUE);
3038 status = NtDuplicateObject( source_process, source, dest_process, dest,
3039 access, inherit ? OBJ_INHERIT : 0, options );
3040 if (status) SetLastError( RtlNtStatusToDosError(status) );
3041 return !status;
3045 /***********************************************************************
3046 * ConvertToGlobalHandle (KERNEL32.@)
3048 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3050 HANDLE ret = INVALID_HANDLE_VALUE;
3051 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3052 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3053 return ret;
3057 /***********************************************************************
3058 * SetHandleContext (KERNEL32.@)
3060 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3062 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3063 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3064 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3065 return FALSE;
3069 /***********************************************************************
3070 * GetHandleContext (KERNEL32.@)
3072 DWORD WINAPI GetHandleContext(HANDLE hnd)
3074 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3075 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3076 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3077 return 0;
3081 /***********************************************************************
3082 * CreateSocketHandle (KERNEL32.@)
3084 HANDLE WINAPI CreateSocketHandle(void)
3086 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3087 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3088 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3089 return INVALID_HANDLE_VALUE;
3093 /***********************************************************************
3094 * SetPriorityClass (KERNEL32.@)
3096 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3098 NTSTATUS status;
3099 PROCESS_PRIORITY_CLASS ppc;
3101 ppc.Foreground = FALSE;
3102 switch (priorityclass)
3104 case IDLE_PRIORITY_CLASS:
3105 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3106 case BELOW_NORMAL_PRIORITY_CLASS:
3107 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3108 case NORMAL_PRIORITY_CLASS:
3109 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3110 case ABOVE_NORMAL_PRIORITY_CLASS:
3111 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3112 case HIGH_PRIORITY_CLASS:
3113 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3114 case REALTIME_PRIORITY_CLASS:
3115 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3116 default:
3117 SetLastError(ERROR_INVALID_PARAMETER);
3118 return FALSE;
3121 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3122 &ppc, sizeof(ppc));
3124 if (status != STATUS_SUCCESS)
3126 SetLastError( RtlNtStatusToDosError(status) );
3127 return FALSE;
3129 return TRUE;
3133 /***********************************************************************
3134 * GetPriorityClass (KERNEL32.@)
3136 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3138 NTSTATUS status;
3139 PROCESS_BASIC_INFORMATION pbi;
3141 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3142 sizeof(pbi), NULL);
3143 if (status != STATUS_SUCCESS)
3145 SetLastError( RtlNtStatusToDosError(status) );
3146 return 0;
3148 switch (pbi.BasePriority)
3150 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3151 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3152 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3153 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3154 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3155 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3157 SetLastError( ERROR_INVALID_PARAMETER );
3158 return 0;
3162 /***********************************************************************
3163 * SetProcessAffinityMask (KERNEL32.@)
3165 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3167 NTSTATUS status;
3169 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3170 &affmask, sizeof(DWORD_PTR));
3171 if (status)
3173 SetLastError( RtlNtStatusToDosError(status) );
3174 return FALSE;
3176 return TRUE;
3180 /**********************************************************************
3181 * GetProcessAffinityMask (KERNEL32.@)
3183 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3185 NTSTATUS status = STATUS_SUCCESS;
3187 if (system_mask) *system_mask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
3188 if (process_mask)
3190 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3191 process_mask, sizeof(*process_mask), NULL )))
3192 SetLastError( RtlNtStatusToDosError(status) );
3194 return !status;
3198 /***********************************************************************
3199 * GetProcessVersion (KERNEL32.@)
3201 DWORD WINAPI GetProcessVersion( DWORD pid )
3203 HANDLE process;
3204 NTSTATUS status;
3205 PROCESS_BASIC_INFORMATION pbi;
3206 SIZE_T count;
3207 PEB peb;
3208 IMAGE_DOS_HEADER dos;
3209 IMAGE_NT_HEADERS nt;
3210 DWORD ver = 0;
3212 if (!pid || pid == GetCurrentProcessId())
3214 IMAGE_NT_HEADERS *pnt;
3216 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3217 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3218 pnt->OptionalHeader.MinorSubsystemVersion);
3219 return 0;
3222 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3223 if (!process) return 0;
3225 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3226 if (status) goto err;
3228 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3229 if (status || count != sizeof(peb)) goto err;
3231 memset(&dos, 0, sizeof(dos));
3232 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3233 if (status || count != sizeof(dos)) goto err;
3234 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3236 memset(&nt, 0, sizeof(nt));
3237 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3238 if (status || count != sizeof(nt)) goto err;
3239 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3241 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3243 err:
3244 CloseHandle(process);
3246 if (status != STATUS_SUCCESS)
3247 SetLastError(RtlNtStatusToDosError(status));
3249 return ver;
3253 /***********************************************************************
3254 * SetProcessWorkingSetSize [KERNEL32.@]
3255 * Sets the min/max working set sizes for a specified process.
3257 * PARAMS
3258 * hProcess [I] Handle to the process of interest
3259 * minset [I] Specifies minimum working set size
3260 * maxset [I] Specifies maximum working set size
3262 * RETURNS
3263 * Success: TRUE
3264 * Failure: FALSE
3266 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3267 SIZE_T maxset)
3269 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3270 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3271 /* Trim the working set to zero */
3272 /* Swap the process out of physical RAM */
3274 return TRUE;
3277 /***********************************************************************
3278 * K32EmptyWorkingSet (KERNEL32.@)
3280 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3282 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3285 /***********************************************************************
3286 * GetProcessWorkingSetSize (KERNEL32.@)
3288 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3289 PSIZE_T maxset)
3291 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3292 /* 32 MB working set size */
3293 if (minset) *minset = 32*1024*1024;
3294 if (maxset) *maxset = 32*1024*1024;
3295 return TRUE;
3299 /***********************************************************************
3300 * SetProcessShutdownParameters (KERNEL32.@)
3302 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3304 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3305 shutdown_flags = flags;
3306 shutdown_priority = level;
3307 return TRUE;
3311 /***********************************************************************
3312 * GetProcessShutdownParameters (KERNEL32.@)
3315 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3317 *lpdwLevel = shutdown_priority;
3318 *lpdwFlags = shutdown_flags;
3319 return TRUE;
3323 /***********************************************************************
3324 * GetProcessPriorityBoost (KERNEL32.@)
3326 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3328 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3330 /* Report that no boost is present.. */
3331 *pDisablePriorityBoost = FALSE;
3333 return TRUE;
3336 /***********************************************************************
3337 * SetProcessPriorityBoost (KERNEL32.@)
3339 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3341 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3342 /* Say we can do it. I doubt the program will notice that we don't. */
3343 return TRUE;
3347 /***********************************************************************
3348 * ReadProcessMemory (KERNEL32.@)
3350 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3351 SIZE_T *bytes_read )
3353 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3354 if (status) SetLastError( RtlNtStatusToDosError(status) );
3355 return !status;
3359 /***********************************************************************
3360 * WriteProcessMemory (KERNEL32.@)
3362 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3363 SIZE_T *bytes_written )
3365 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3366 if (status) SetLastError( RtlNtStatusToDosError(status) );
3367 return !status;
3371 /****************************************************************************
3372 * FlushInstructionCache (KERNEL32.@)
3374 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3376 NTSTATUS status;
3377 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3378 if (status) SetLastError( RtlNtStatusToDosError(status) );
3379 return !status;
3383 /******************************************************************
3384 * GetProcessIoCounters (KERNEL32.@)
3386 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3388 NTSTATUS status;
3390 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3391 ioc, sizeof(*ioc), NULL);
3392 if (status) SetLastError( RtlNtStatusToDosError(status) );
3393 return !status;
3396 /******************************************************************
3397 * GetProcessHandleCount (KERNEL32.@)
3399 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3401 NTSTATUS status;
3403 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3404 cnt, sizeof(*cnt), NULL);
3405 if (status) SetLastError( RtlNtStatusToDosError(status) );
3406 return !status;
3409 /******************************************************************
3410 * QueryFullProcessImageNameA (KERNEL32.@)
3412 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3414 BOOL retval;
3415 DWORD pdwSizeW = *pdwSize;
3416 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3418 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3420 if(retval)
3421 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3422 lpExeName, *pdwSize, NULL, NULL));
3423 if(retval)
3424 *pdwSize = strlen(lpExeName);
3426 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3427 return retval;
3430 /******************************************************************
3431 * QueryFullProcessImageNameW (KERNEL32.@)
3433 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3435 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3436 UNICODE_STRING *dynamic_buffer = NULL;
3437 UNICODE_STRING *result = NULL;
3438 NTSTATUS status;
3439 DWORD needed;
3441 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3442 * is a DOS path and we depend on this. */
3443 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3444 sizeof(buffer) - sizeof(WCHAR), &needed);
3445 if (status == STATUS_INFO_LENGTH_MISMATCH)
3447 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3448 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3449 result = dynamic_buffer;
3451 else
3452 result = (PUNICODE_STRING)buffer;
3454 if (status) goto cleanup;
3456 if (dwFlags & PROCESS_NAME_NATIVE)
3458 WCHAR drive[3];
3459 WCHAR device[1024];
3460 DWORD ntlen, devlen;
3462 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3464 /* We cannot convert it to an NT device path so fail */
3465 status = STATUS_NO_SUCH_DEVICE;
3466 goto cleanup;
3469 /* Find this drive's NT device path */
3470 drive[0] = result->Buffer[0];
3471 drive[1] = ':';
3472 drive[2] = 0;
3473 if (!QueryDosDeviceW(drive, device, sizeof(device)/sizeof(*device)))
3475 status = STATUS_NO_SUCH_DEVICE;
3476 goto cleanup;
3479 devlen = lstrlenW(device);
3480 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3481 if (ntlen + 1 > *pdwSize)
3483 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3484 return 0;
3486 *pdwSize = ntlen;
3488 memcpy(lpExeName, device, devlen * sizeof(*device));
3489 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3490 lpExeName[*pdwSize] = 0;
3491 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3493 else
3495 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3497 status = STATUS_BUFFER_TOO_SMALL;
3498 goto cleanup;
3501 *pdwSize = result->Length/sizeof(WCHAR);
3502 memcpy( lpExeName, result->Buffer, result->Length );
3503 lpExeName[*pdwSize] = 0;
3506 cleanup:
3507 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3508 if (status) SetLastError( RtlNtStatusToDosError(status) );
3509 return !status;
3512 /***********************************************************************
3513 * K32GetProcessImageFileNameA (KERNEL32.@)
3515 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3517 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3520 /***********************************************************************
3521 * K32GetProcessImageFileNameW (KERNEL32.@)
3523 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3525 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3528 /***********************************************************************
3529 * K32EnumProcesses (KERNEL32.@)
3531 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3533 SYSTEM_PROCESS_INFORMATION *spi;
3534 ULONG size = 0x4000;
3535 void *buf = NULL;
3536 NTSTATUS status;
3538 do {
3539 size *= 2;
3540 HeapFree(GetProcessHeap(), 0, buf);
3541 buf = HeapAlloc(GetProcessHeap(), 0, size);
3542 if (!buf)
3543 return FALSE;
3545 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3546 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3548 if (status != STATUS_SUCCESS)
3550 HeapFree(GetProcessHeap(), 0, buf);
3551 SetLastError(RtlNtStatusToDosError(status));
3552 return FALSE;
3555 spi = buf;
3557 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3559 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3560 *lpcbUsed += sizeof(DWORD);
3562 if (spi->NextEntryOffset == 0)
3563 break;
3565 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3568 HeapFree(GetProcessHeap(), 0, buf);
3569 return TRUE;
3572 /***********************************************************************
3573 * K32QueryWorkingSet (KERNEL32.@)
3575 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3577 NTSTATUS status;
3579 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3581 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3583 if (status)
3585 SetLastError( RtlNtStatusToDosError( status ) );
3586 return FALSE;
3588 return TRUE;
3591 /***********************************************************************
3592 * K32QueryWorkingSetEx (KERNEL32.@)
3594 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3596 NTSTATUS status;
3598 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3600 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3602 if (status)
3604 SetLastError( RtlNtStatusToDosError( status ) );
3605 return FALSE;
3607 return TRUE;
3610 /***********************************************************************
3611 * K32GetProcessMemoryInfo (KERNEL32.@)
3613 * Retrieve memory usage information for a given process
3616 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3617 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3619 NTSTATUS status;
3620 VM_COUNTERS vmc;
3622 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3624 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3625 return FALSE;
3628 status = NtQueryInformationProcess(process, ProcessVmCounters,
3629 &vmc, sizeof(vmc), NULL);
3631 if (status)
3633 SetLastError(RtlNtStatusToDosError(status));
3634 return FALSE;
3637 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3638 pmc->PageFaultCount = vmc.PageFaultCount;
3639 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3640 pmc->WorkingSetSize = vmc.WorkingSetSize;
3641 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3642 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3643 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3644 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3645 pmc->PagefileUsage = vmc.PagefileUsage;
3646 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3648 return TRUE;
3651 /***********************************************************************
3652 * ProcessIdToSessionId (KERNEL32.@)
3653 * This function is available on Terminal Server 4SP4 and Windows 2000
3655 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3657 /* According to MSDN, if the calling process is not in a terminal
3658 * services environment, then the sessionid returned is zero.
3660 *sessionid_ptr = 0;
3661 return TRUE;
3665 /***********************************************************************
3666 * RegisterServiceProcess (KERNEL32.@)
3668 * A service process calls this function to ensure that it continues to run
3669 * even after a user logged off.
3671 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3673 /* I don't think that Wine needs to do anything in this function */
3674 return 1; /* success */
3678 /**********************************************************************
3679 * IsWow64Process (KERNEL32.@)
3681 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3683 ULONG pbi;
3684 NTSTATUS status;
3686 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3688 if (status != STATUS_SUCCESS)
3690 SetLastError( RtlNtStatusToDosError( status ) );
3691 return FALSE;
3693 *Wow64Process = (pbi != 0);
3694 return TRUE;
3698 /***********************************************************************
3699 * GetCurrentProcess (KERNEL32.@)
3701 * Get a handle to the current process.
3703 * PARAMS
3704 * None.
3706 * RETURNS
3707 * A handle representing the current process.
3709 #undef GetCurrentProcess
3710 HANDLE WINAPI GetCurrentProcess(void)
3712 return (HANDLE)~(ULONG_PTR)0;
3715 /***********************************************************************
3716 * GetLogicalProcessorInformation (KERNEL32.@)
3718 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3720 FIXME("(%p,%p): stub\n", buffer, pBufLen);
3721 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3722 return FALSE;
3725 /***********************************************************************
3726 * GetLogicalProcessorInformationEx (KERNEL32.@)
3728 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer, PDWORD pBufLen)
3730 FIXME("(%u,%p,%p): stub\n", relationship, buffer, pBufLen);
3731 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3732 return FALSE;
3735 /***********************************************************************
3736 * CmdBatNotification (KERNEL32.@)
3738 * Notifies the system that a batch file has started or finished.
3740 * PARAMS
3741 * bBatchRunning [I] TRUE if a batch file has started or
3742 * FALSE if a batch file has finished executing.
3744 * RETURNS
3745 * Unknown.
3747 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3749 FIXME("%d\n", bBatchRunning);
3750 return FALSE;
3754 /***********************************************************************
3755 * RegisterApplicationRestart (KERNEL32.@)
3757 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3759 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3761 return S_OK;
3764 /**********************************************************************
3765 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3767 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3769 FIXME("stub\n");
3770 return 0;
3773 /**********************************************************************
3774 * GetSystemDEPPolicy (KERNEL32.@)
3776 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3778 FIXME("stub\n");
3779 return OptIn;
3782 /**********************************************************************
3783 * SetProcessDEPPolicy (KERNEL32.@)
3785 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3787 FIXME("(%d): stub\n", newDEP);
3788 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3789 return FALSE;
3792 /**********************************************************************
3793 * ApplicationRecoveryFinished (KERNEL32.@)
3795 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
3797 FIXME(": stub\n");
3798 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3801 /**********************************************************************
3802 * ApplicationRecoveryInProgress (KERNEL32.@)
3804 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
3806 FIXME(":%p stub\n", canceled);
3807 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3808 return E_FAIL;
3811 /**********************************************************************
3812 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3814 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
3816 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
3817 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3818 return E_FAIL;
3821 /**********************************************************************
3822 * GetNumaHighestNodeNumber (KERNEL32.@)
3824 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
3826 FIXME("(%p): stub\n", highestnode);
3827 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3828 return FALSE;
3831 /**********************************************************************
3832 * GetNumaNodeProcessorMask (KERNEL32.@)
3834 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
3836 FIXME("(%c %p): stub\n", node, mask);
3837 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3838 return FALSE;
3841 /**********************************************************************
3842 * GetNumaAvailableMemoryNode (KERNEL32.@)
3844 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
3846 FIXME("(%c %p): stub\n", node, available_bytes);
3847 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3848 return FALSE;
3851 /**********************************************************************
3852 * GetProcessDEPPolicy (KERNEL32.@)
3854 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
3856 FIXME("(%p %p %p): stub\n", process, flags, permanent);
3857 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3858 return FALSE;
3861 /**********************************************************************
3862 * FlushProcessWriteBuffers (KERNEL32.@)
3864 VOID WINAPI FlushProcessWriteBuffers(void)
3866 static int once = 0;
3868 if (!once++)
3869 FIXME(": stub\n");