wined3d: Pass a wined3d_resource_desc structure to wined3d_texture_create_3d().
[wine/multimedia.git] / dlls / kernel32 / process.c
blobd07065c273abbbff7a3832ee65f0fb6686e6f43c
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;
90 SYSTEM_BASIC_INFORMATION system_info = { 0 };
92 const WCHAR *DIR_Windows = NULL;
93 const WCHAR *DIR_System = NULL;
94 const WCHAR *DIR_SysWow64 = NULL;
96 /* Process flags */
97 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
98 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
99 #define PDB32_DOS_PROC 0x0010 /* Dos process */
100 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
101 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
102 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
104 static const WCHAR exeW[] = {'.','e','x','e',0};
105 static const WCHAR comW[] = {'.','c','o','m',0};
106 static const WCHAR batW[] = {'.','b','a','t',0};
107 static const WCHAR cmdW[] = {'.','c','m','d',0};
108 static const WCHAR pifW[] = {'.','p','i','f',0};
109 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
111 static void exec_process( LPCWSTR name );
113 extern void SHELL_LoadRegistry(void);
116 /***********************************************************************
117 * contains_path
119 static inline int contains_path( LPCWSTR name )
121 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
125 /***********************************************************************
126 * is_special_env_var
128 * Check if an environment variable needs to be handled specially when
129 * passed through the Unix environment (i.e. prefixed with "WINE").
131 static inline int is_special_env_var( const char *var )
133 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
134 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
135 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
136 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
137 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
141 /***********************************************************************
142 * is_path_prefix
144 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
146 unsigned int len = strlenW( prefix );
148 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
149 while (filename[len] == '\\') len++;
150 return len;
154 /***************************************************************************
155 * get_builtin_path
157 * Get the path of a builtin module when the native file does not exist.
159 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
160 UINT size, struct binary_info *binary_info )
162 WCHAR *file_part;
163 UINT len;
164 void *redir_disabled = 0;
165 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
167 /* builtin names cannot be empty or contain spaces */
168 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
170 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
171 Wow64RevertWow64FsRedirection( redir_disabled );
173 if (contains_path( libname ))
175 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
176 filename, &file_part ) > size * sizeof(WCHAR))
177 return FALSE; /* too long */
179 if ((len = is_path_prefix( DIR_System, filename )))
181 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
183 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
185 flags = 0;
187 else return FALSE;
189 if (filename + len != file_part) return FALSE;
191 else
193 len = strlenW( DIR_System );
194 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
195 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
196 file_part = filename + len;
197 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
198 strcpyW( file_part, libname );
199 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
201 if (ext && !strchrW( file_part, '.' ))
203 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
204 return FALSE; /* too long */
205 strcatW( file_part, ext );
207 binary_info->type = BINARY_UNIX_LIB;
208 binary_info->flags = flags;
209 binary_info->res_start = NULL;
210 binary_info->res_end = NULL;
211 return TRUE;
215 /***********************************************************************
216 * open_exe_file
218 * Open a specific exe file, taking load order into account.
219 * Returns the file handle or 0 for a builtin exe.
221 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
223 HANDLE handle;
225 TRACE("looking for %s\n", debugstr_w(name) );
227 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
228 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
230 WCHAR buffer[MAX_PATH];
231 /* file doesn't exist, check for builtin */
232 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
233 handle = 0;
235 else MODULE_get_binary_info( handle, binary_info );
237 return handle;
241 /***********************************************************************
242 * find_exe_file
244 * Open an exe file, and return the full name and file handle.
245 * Returns FALSE if file could not be found.
247 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
248 HANDLE *handle, struct binary_info *binary_info )
250 TRACE("looking for %s\n", debugstr_w(name) );
252 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
253 /* no builtin found, try native without extension in case it is a Unix app */
254 !SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
256 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
257 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
258 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
260 MODULE_get_binary_info( *handle, binary_info );
261 return TRUE;
263 return FALSE;
267 /***********************************************************************
268 * build_initial_environment
270 * Build the Win32 environment from the Unix environment
272 static BOOL build_initial_environment(void)
274 SIZE_T size = 1;
275 char **e;
276 WCHAR *p, *endptr;
277 void *ptr;
278 char **env = __wine_get_main_environment();
280 /* Compute the total size of the Unix environment */
281 for (e = env; *e; e++)
283 if (is_special_env_var( *e )) continue;
284 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
286 size *= sizeof(WCHAR);
288 /* Now allocate the environment */
289 ptr = NULL;
290 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
291 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
292 return FALSE;
294 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
295 endptr = p + size / sizeof(WCHAR);
297 /* And fill it with the Unix environment */
298 for (e = env; *e; e++)
300 char *str = *e;
302 /* skip Unix special variables and use the Wine variants instead */
303 if (!strncmp( str, "WINE", 4 ))
305 if (is_special_env_var( str + 4 )) str += 4;
306 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
308 else if (is_special_env_var( str )) continue; /* skip it */
310 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
311 p += strlenW(p) + 1;
313 *p = 0;
314 return TRUE;
318 /***********************************************************************
319 * set_registry_variables
321 * Set environment variables by enumerating the values of a key;
322 * helper for set_registry_environment().
323 * Note that Windows happily truncates the value if it's too big.
325 static void set_registry_variables( HANDLE hkey, ULONG type )
327 static const WCHAR pathW[] = {'P','A','T','H'};
328 static const WCHAR sep[] = {';',0};
329 UNICODE_STRING env_name, env_value;
330 NTSTATUS status;
331 DWORD size;
332 int index;
333 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
334 WCHAR tmpbuf[1024];
335 UNICODE_STRING tmp;
336 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
338 tmp.Buffer = tmpbuf;
339 tmp.MaximumLength = sizeof(tmpbuf);
341 for (index = 0; ; index++)
343 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
344 buffer, sizeof(buffer), &size );
345 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
346 break;
347 if (info->Type != type)
348 continue;
349 env_name.Buffer = info->Name;
350 env_name.Length = env_name.MaximumLength = info->NameLength;
351 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
352 env_value.Length = info->DataLength;
353 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
354 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
355 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
356 if (!env_value.Length) continue;
357 if (info->Type == REG_EXPAND_SZ)
359 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
360 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
361 RtlCopyUnicodeString( &env_value, &tmp );
363 /* PATH is magic */
364 if (env_name.Length == sizeof(pathW) &&
365 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
366 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
368 RtlAppendUnicodeToString( &tmp, sep );
369 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
370 RtlCopyUnicodeString( &env_value, &tmp );
372 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
377 /***********************************************************************
378 * set_registry_environment
380 * Set the environment variables specified in the registry.
382 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
383 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
384 * on the order in which the variables are processed. But on Windows it
385 * does not really matter since they only use %SystemDrive% and
386 * %SystemRoot% which are predefined. But Wine defines these in the
387 * registry, so we need two passes.
389 static BOOL set_registry_environment( BOOL volatile_only )
391 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
392 'S','y','s','t','e','m','\\',
393 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
394 'C','o','n','t','r','o','l','\\',
395 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
396 'E','n','v','i','r','o','n','m','e','n','t',0};
397 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
398 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};
400 OBJECT_ATTRIBUTES attr;
401 UNICODE_STRING nameW;
402 HANDLE hkey;
403 BOOL ret = FALSE;
405 attr.Length = sizeof(attr);
406 attr.RootDirectory = 0;
407 attr.ObjectName = &nameW;
408 attr.Attributes = 0;
409 attr.SecurityDescriptor = NULL;
410 attr.SecurityQualityOfService = NULL;
412 /* first the system environment variables */
413 RtlInitUnicodeString( &nameW, env_keyW );
414 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
416 set_registry_variables( hkey, REG_SZ );
417 set_registry_variables( hkey, REG_EXPAND_SZ );
418 NtClose( hkey );
419 ret = TRUE;
422 /* then the ones for the current user */
423 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
424 RtlInitUnicodeString( &nameW, envW );
425 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
427 set_registry_variables( hkey, REG_SZ );
428 set_registry_variables( hkey, REG_EXPAND_SZ );
429 NtClose( hkey );
432 RtlInitUnicodeString( &nameW, volatile_envW );
433 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
435 set_registry_variables( hkey, REG_SZ );
436 set_registry_variables( hkey, REG_EXPAND_SZ );
437 NtClose( hkey );
440 NtClose( attr.RootDirectory );
441 return ret;
445 /***********************************************************************
446 * get_reg_value
448 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
450 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
451 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
452 DWORD len, size = sizeof(buffer);
453 WCHAR *ret = NULL;
454 UNICODE_STRING nameW;
456 RtlInitUnicodeString( &nameW, name );
457 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
458 return NULL;
460 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
461 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
463 if (info->Type == REG_EXPAND_SZ)
465 UNICODE_STRING value, expanded;
467 value.MaximumLength = len * sizeof(WCHAR);
468 value.Buffer = (WCHAR *)info->Data;
469 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
470 value.Length = len * sizeof(WCHAR);
471 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
472 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
473 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
474 else RtlFreeUnicodeString( &expanded );
476 else if (info->Type == REG_SZ)
478 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
480 memcpy( ret, info->Data, len * sizeof(WCHAR) );
481 ret[len] = 0;
484 return ret;
488 /***********************************************************************
489 * set_additional_environment
491 * Set some additional environment variables not specified in the registry.
493 static void set_additional_environment(void)
495 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
496 'S','o','f','t','w','a','r','e','\\',
497 'M','i','c','r','o','s','o','f','t','\\',
498 'W','i','n','d','o','w','s',' ','N','T','\\',
499 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
500 'P','r','o','f','i','l','e','L','i','s','t',0};
501 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
502 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
503 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
504 OBJECT_ATTRIBUTES attr;
505 UNICODE_STRING nameW;
506 WCHAR *profile_dir = NULL, *all_users_dir = NULL;
507 HANDLE hkey;
508 DWORD len;
510 /* set the ALLUSERSPROFILE variables */
512 attr.Length = sizeof(attr);
513 attr.RootDirectory = 0;
514 attr.ObjectName = &nameW;
515 attr.Attributes = 0;
516 attr.SecurityDescriptor = NULL;
517 attr.SecurityQualityOfService = NULL;
518 RtlInitUnicodeString( &nameW, profile_keyW );
519 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
521 profile_dir = get_reg_value( hkey, profiles_valueW );
522 all_users_dir = get_reg_value( hkey, all_users_valueW );
523 NtClose( hkey );
526 if (profile_dir && all_users_dir)
528 WCHAR *value, *p;
530 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
531 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
532 strcpyW( value, profile_dir );
533 p = value + strlenW(value);
534 if (p > value && p[-1] != '\\') *p++ = '\\';
535 strcpyW( p, all_users_dir );
536 SetEnvironmentVariableW( allusersW, value );
537 HeapFree( GetProcessHeap(), 0, value );
540 HeapFree( GetProcessHeap(), 0, all_users_dir );
541 HeapFree( GetProcessHeap(), 0, profile_dir );
544 /***********************************************************************
545 * set_wow64_environment
547 * Set the environment variables that change across 32/64/Wow64.
549 static void set_wow64_environment(void)
551 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};
552 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};
553 static const WCHAR x86W[] = {'x','8','6',0};
554 static const WCHAR versionW[] = {'M','a','c','h','i','n','e','\\',
555 'S','o','f','t','w','a','r','e','\\',
556 'M','i','c','r','o','s','o','f','t','\\',
557 'W','i','n','d','o','w','s','\\',
558 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
559 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
560 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
561 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
562 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
563 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
564 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
565 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
566 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
568 OBJECT_ATTRIBUTES attr;
569 UNICODE_STRING nameW;
570 WCHAR arch[64];
571 WCHAR *value;
572 HANDLE hkey;
574 /* set the PROCESSOR_ARCHITECTURE variable */
576 if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
578 if (is_win64)
580 SetEnvironmentVariableW( archW, arch );
581 SetEnvironmentVariableW( arch6432W, NULL );
584 else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
586 if (is_wow64)
588 SetEnvironmentVariableW( arch6432W, arch );
589 SetEnvironmentVariableW( archW, x86W );
593 attr.Length = sizeof(attr);
594 attr.RootDirectory = 0;
595 attr.ObjectName = &nameW;
596 attr.Attributes = 0;
597 attr.SecurityDescriptor = NULL;
598 attr.SecurityQualityOfService = NULL;
599 RtlInitUnicodeString( &nameW, versionW );
600 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
602 /* set the ProgramFiles variables */
604 if ((value = get_reg_value( hkey, progdirW )))
606 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
607 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
608 HeapFree( GetProcessHeap(), 0, value );
610 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
612 SetEnvironmentVariableW( progfilesW, value );
613 HeapFree( GetProcessHeap(), 0, value );
616 /* set the CommonProgramFiles variables */
618 if ((value = get_reg_value( hkey, commondirW )))
620 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
621 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
622 HeapFree( GetProcessHeap(), 0, value );
624 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
626 SetEnvironmentVariableW( commonfilesW, value );
627 HeapFree( GetProcessHeap(), 0, value );
630 NtClose( hkey );
633 /***********************************************************************
634 * set_library_wargv
636 * Set the Wine library Unicode argv global variables.
638 static void set_library_wargv( char **argv )
640 int argc;
641 char *q;
642 WCHAR *p;
643 WCHAR **wargv;
644 DWORD total = 0;
646 for (argc = 0; argv[argc]; argc++)
647 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
649 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
650 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
651 p = (WCHAR *)(wargv + argc + 1);
652 for (argc = 0; argv[argc]; argc++)
654 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
655 wargv[argc] = p;
656 p += reslen;
657 total -= reslen;
659 wargv[argc] = NULL;
661 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
663 for (argc = 0; wargv[argc]; argc++)
664 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
666 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
667 q = (char *)(argv + argc + 1);
668 for (argc = 0; wargv[argc]; argc++)
670 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
671 argv[argc] = q;
672 q += reslen;
673 total -= reslen;
675 argv[argc] = NULL;
677 __wine_main_argc = argc;
678 __wine_main_argv = argv;
679 __wine_main_wargv = wargv;
683 /***********************************************************************
684 * update_library_argv0
686 * Update the argv[0] global variable with the binary we have found.
688 static void update_library_argv0( const WCHAR *argv0 )
690 DWORD len = strlenW( argv0 );
692 if (len > strlenW( __wine_main_wargv[0] ))
694 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
696 strcpyW( __wine_main_wargv[0], argv0 );
698 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
699 if (len > strlen( __wine_main_argv[0] ) + 1)
701 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
703 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
707 /***********************************************************************
708 * build_command_line
710 * Build the command line of a process from the argv array.
712 * Note that it does NOT necessarily include the file name.
713 * Sometimes we don't even have any command line options at all.
715 * We must quote and escape characters so that the argv array can be rebuilt
716 * from the command line:
717 * - spaces and tabs must be quoted
718 * 'a b' -> '"a b"'
719 * - quotes must be escaped
720 * '"' -> '\"'
721 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
722 * resulting in an odd number of '\' followed by a '"'
723 * '\"' -> '\\\"'
724 * '\\"' -> '\\\\\"'
725 * - '\'s that are not followed by a '"' can be left as is
726 * 'a\b' == 'a\b'
727 * 'a\\b' == 'a\\b'
729 static BOOL build_command_line( WCHAR **argv )
731 int len;
732 WCHAR **arg;
733 LPWSTR p;
734 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
736 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
738 len = 0;
739 for (arg = argv; *arg; arg++)
741 int has_space,bcount;
742 WCHAR* a;
744 has_space=0;
745 bcount=0;
746 a=*arg;
747 if( !*a ) has_space=1;
748 while (*a!='\0') {
749 if (*a=='\\') {
750 bcount++;
751 } else {
752 if (*a==' ' || *a=='\t') {
753 has_space=1;
754 } else if (*a=='"') {
755 /* doubling of '\' preceding a '"',
756 * plus escaping of said '"'
758 len+=2*bcount+1;
760 bcount=0;
762 a++;
764 len+=(a-*arg)+1 /* for the separating space */;
765 if (has_space)
766 len+=2; /* for the quotes */
769 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
770 return FALSE;
772 p = rupp->CommandLine.Buffer;
773 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
774 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
775 for (arg = argv; *arg; arg++)
777 int has_space,has_quote;
778 WCHAR* a;
780 /* Check for quotes and spaces in this argument */
781 has_space=has_quote=0;
782 a=*arg;
783 if( !*a ) has_space=1;
784 while (*a!='\0') {
785 if (*a==' ' || *a=='\t') {
786 has_space=1;
787 if (has_quote)
788 break;
789 } else if (*a=='"') {
790 has_quote=1;
791 if (has_space)
792 break;
794 a++;
797 /* Now transfer it to the command line */
798 if (has_space)
799 *p++='"';
800 if (has_quote) {
801 int bcount;
803 bcount=0;
804 a=*arg;
805 while (*a!='\0') {
806 if (*a=='\\') {
807 *p++=*a;
808 bcount++;
809 } else {
810 if (*a=='"') {
811 int i;
813 /* Double all the '\\' preceding this '"', plus one */
814 for (i=0;i<=bcount;i++)
815 *p++='\\';
816 *p++='"';
817 } else {
818 *p++=*a;
820 bcount=0;
822 a++;
824 } else {
825 WCHAR* x = *arg;
826 while ((*p=*x++)) p++;
828 if (has_space)
829 *p++='"';
830 *p++=' ';
832 if (p > rupp->CommandLine.Buffer)
833 p--; /* remove last space */
834 *p = '\0';
836 return TRUE;
840 /***********************************************************************
841 * init_current_directory
843 * Initialize the current directory from the Unix cwd or the parent info.
845 static void init_current_directory( CURDIR *cur_dir )
847 UNICODE_STRING dir_str;
848 const char *pwd;
849 char *cwd;
850 int size;
852 /* if we received a cur dir from the parent, try this first */
854 if (cur_dir->DosPath.Length)
856 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
859 /* now try to get it from the Unix cwd */
861 for (size = 256; ; size *= 2)
863 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
864 if (getcwd( cwd, size )) break;
865 HeapFree( GetProcessHeap(), 0, cwd );
866 if (errno == ERANGE) continue;
867 cwd = NULL;
868 break;
871 /* try to use PWD if it is valid, so that we don't resolve symlinks */
873 pwd = getenv( "PWD" );
874 if (cwd)
876 struct stat st1, st2;
878 if (!pwd || stat( pwd, &st1 ) == -1 ||
879 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
880 pwd = cwd;
883 if (pwd)
885 ANSI_STRING unix_name;
886 UNICODE_STRING nt_name;
887 RtlInitAnsiString( &unix_name, pwd );
888 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
890 UNICODE_STRING dos_path;
891 /* skip the \??\ prefix, nt_name is 0 terminated */
892 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
893 RtlSetCurrentDirectory_U( &dos_path );
894 RtlFreeUnicodeString( &nt_name );
898 if (!cur_dir->DosPath.Length) /* still not initialized */
900 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
901 "starting in the Windows directory.\n", cwd ? cwd : "" );
902 RtlInitUnicodeString( &dir_str, DIR_Windows );
903 RtlSetCurrentDirectory_U( &dir_str );
905 HeapFree( GetProcessHeap(), 0, cwd );
907 done:
908 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
912 /***********************************************************************
913 * init_windows_dirs
915 * Initialize the windows and system directories from the environment.
917 static void init_windows_dirs(void)
919 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
921 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
922 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
923 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
924 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
925 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
927 DWORD len;
928 WCHAR *buffer;
930 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
932 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
933 GetEnvironmentVariableW( windirW, buffer, len );
934 DIR_Windows = buffer;
936 else DIR_Windows = default_windirW;
938 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
940 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
941 GetEnvironmentVariableW( winsysdirW, buffer, len );
942 DIR_System = buffer;
944 else
946 len = strlenW( DIR_Windows );
947 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
948 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
949 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
950 DIR_System = buffer;
953 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
954 ERR( "directory %s could not be created, error %u\n",
955 debugstr_w(DIR_Windows), GetLastError() );
956 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
957 ERR( "directory %s could not be created, error %u\n",
958 debugstr_w(DIR_System), GetLastError() );
960 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
962 len = strlenW( DIR_Windows );
963 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
964 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
965 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
966 DIR_SysWow64 = buffer;
967 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
968 ERR( "directory %s could not be created, error %u\n",
969 debugstr_w(DIR_SysWow64), GetLastError() );
972 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
973 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
975 /* set the directories in ntdll too */
976 __wine_init_windows_dir( DIR_Windows, DIR_System );
980 /***********************************************************************
981 * start_wineboot
983 * Start the wineboot process if necessary. Return the handles to wait on.
985 static void start_wineboot( HANDLE handles[2] )
987 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
989 handles[1] = 0;
990 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
992 ERR( "failed to create wineboot event, expect trouble\n" );
993 return;
995 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
997 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
998 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
999 STARTUPINFOW si;
1000 PROCESS_INFORMATION pi;
1001 void *redir;
1002 WCHAR app[MAX_PATH];
1003 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1005 memset( &si, 0, sizeof(si) );
1006 si.cb = sizeof(si);
1007 si.dwFlags = STARTF_USESTDHANDLES;
1008 si.hStdInput = 0;
1009 si.hStdOutput = 0;
1010 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1012 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1013 lstrcatW( app, wineboot );
1015 Wow64DisableWow64FsRedirection( &redir );
1016 strcpyW( cmdline, app );
1017 strcatW( cmdline, args );
1018 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1020 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1021 CloseHandle( pi.hThread );
1022 handles[1] = pi.hProcess;
1024 else
1026 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1027 CloseHandle( handles[0] );
1028 handles[0] = 0;
1030 Wow64RevertWow64FsRedirection( redir );
1035 #ifdef __i386__
1036 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1037 __ASM_GLOBAL_FUNC( call_process_entry,
1038 "pushl %ebp\n\t"
1039 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1040 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1041 "movl %esp,%ebp\n\t"
1042 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1043 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1044 "pushl 8(%ebp)\n\t"
1045 "call *12(%ebp)\n\t"
1046 "leave\n\t"
1047 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1048 __ASM_CFI(".cfi_same_value %ebp\n\t")
1049 "ret" )
1050 #else
1051 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1053 return entry( peb );
1055 #endif
1057 /***********************************************************************
1058 * start_process
1060 * Startup routine of a new process. Runs on the new process stack.
1062 static DWORD WINAPI start_process( PEB *peb )
1064 IMAGE_NT_HEADERS *nt;
1065 LPTHREAD_START_ROUTINE entry;
1067 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1068 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1069 nt->OptionalHeader.AddressOfEntryPoint);
1071 if (!nt->OptionalHeader.AddressOfEntryPoint)
1073 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1074 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1075 ExitThread( 1 );
1078 if (TRACE_ON(relay))
1079 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1080 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1082 SetLastError( 0 ); /* clear error code */
1083 if (peb->BeingDebugged) DbgBreakPoint();
1084 return call_process_entry( peb, entry );
1088 /***********************************************************************
1089 * set_process_name
1091 * Change the process name in the ps output.
1093 static void set_process_name( int argc, char *argv[] )
1095 #ifdef HAVE_SETPROCTITLE
1096 setproctitle("-%s", argv[1]);
1097 #endif
1099 #ifdef HAVE_PRCTL
1100 int i, offset;
1101 char *p, *prctl_name = argv[1];
1102 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1104 #ifndef PR_SET_NAME
1105 # define PR_SET_NAME 15
1106 #endif
1108 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1109 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1111 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1113 offset = argv[1] - argv[0];
1114 memmove( argv[1] - offset, argv[1], end - argv[1] );
1115 memset( end - offset, 0, offset );
1116 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1117 argv[i-1] = NULL;
1119 else
1120 #endif /* HAVE_PRCTL */
1122 /* remove argv[0] */
1123 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1128 /***********************************************************************
1129 * __wine_kernel_init
1131 * Wine initialisation: load and start the main exe file.
1133 void CDECL __wine_kernel_init(void)
1135 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1136 static const WCHAR dotW[] = {'.',0};
1138 WCHAR *p, main_exe_name[MAX_PATH+1];
1139 PEB *peb = NtCurrentTeb()->Peb;
1140 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1141 HANDLE boot_events[2];
1142 BOOL got_environment = TRUE;
1144 /* Initialize everything */
1146 setbuf(stdout,NULL);
1147 setbuf(stderr,NULL);
1148 kernel32_handle = GetModuleHandleW(kernel32W);
1149 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1151 LOCALE_Init();
1153 if (!params->Environment)
1155 /* Copy the parent environment */
1156 if (!build_initial_environment()) exit(1);
1158 /* convert old configuration to new format */
1159 convert_old_config();
1161 got_environment = set_registry_environment( FALSE );
1162 set_additional_environment();
1165 init_windows_dirs();
1166 init_current_directory( &params->CurrentDirectory );
1168 set_process_name( __wine_main_argc, __wine_main_argv );
1169 set_library_wargv( __wine_main_argv );
1170 boot_events[0] = boot_events[1] = 0;
1172 if (peb->ProcessParameters->ImagePathName.Buffer)
1174 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1176 else
1178 struct binary_info binary_info;
1180 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1181 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1183 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1184 ExitProcess( GetLastError() );
1186 update_library_argv0( main_exe_name );
1187 if (!build_command_line( __wine_main_wargv )) goto error;
1188 start_wineboot( boot_events );
1191 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1192 p = strrchrW( main_exe_name, '.' );
1193 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1195 TRACE( "starting process name=%s argv[0]=%s\n",
1196 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1198 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1199 MODULE_get_dll_load_path(main_exe_name) );
1201 if (boot_events[0])
1203 DWORD timeout = 2 * 60 * 1000, count = 1;
1205 if (boot_events[1]) count++;
1206 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1207 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1208 ERR( "boot event wait timed out\n" );
1209 CloseHandle( boot_events[0] );
1210 if (boot_events[1]) CloseHandle( boot_events[1] );
1211 /* reload environment now that wineboot has run */
1212 set_registry_environment( got_environment );
1213 set_additional_environment();
1215 set_wow64_environment();
1217 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1219 DWORD_PTR args[1];
1220 WCHAR msgW[1024];
1221 char msg[1024];
1222 DWORD error = GetLastError();
1224 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1225 if (error == ERROR_BAD_EXE_FORMAT ||
1226 error == ERROR_INVALID_ADDRESS ||
1227 error == ERROR_NOT_ENOUGH_MEMORY)
1229 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1230 /* if we get back here, it failed */
1232 else if (error == ERROR_MOD_NOT_FOUND)
1234 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1235 else p = main_exe_name;
1236 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1238 /* args 1 and 2 are --app-name full_path */
1239 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1240 debugstr_w(__wine_main_wargv[3]) );
1241 ExitProcess( ERROR_BAD_EXE_FORMAT );
1243 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1244 ExitProcess( ERROR_FILE_NOT_FOUND );
1246 args[0] = (DWORD_PTR)main_exe_name;
1247 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1248 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1249 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1250 MESSAGE( "wine: %s", msg );
1251 ExitProcess( error );
1254 if (!params->CurrentDirectory.Handle) chdir("/"); /* avoid locking removable devices */
1256 LdrInitializeThunk( start_process, 0, 0, 0 );
1258 error:
1259 ExitProcess( GetLastError() );
1263 /***********************************************************************
1264 * build_argv
1266 * Build an argv array from a command-line.
1267 * 'reserved' is the number of args to reserve before the first one.
1269 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1271 int argc;
1272 char** argv;
1273 char *arg,*s,*d,*cmdline;
1274 int in_quotes,bcount,len;
1276 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1277 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1278 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1280 argc=reserved+1;
1281 bcount=0;
1282 in_quotes=0;
1283 s=cmdline;
1284 while (1) {
1285 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1286 /* space */
1287 argc++;
1288 /* skip the remaining spaces */
1289 while (*s==' ' || *s=='\t') {
1290 s++;
1292 if (*s=='\0')
1293 break;
1294 bcount=0;
1295 continue;
1296 } else if (*s=='\\') {
1297 /* '\', count them */
1298 bcount++;
1299 } else if ((*s=='"') && ((bcount & 1)==0)) {
1300 /* unescaped '"' */
1301 in_quotes=!in_quotes;
1302 bcount=0;
1303 } else {
1304 /* a regular character */
1305 bcount=0;
1307 s++;
1309 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1311 HeapFree( GetProcessHeap(), 0, cmdline );
1312 return NULL;
1315 arg = d = s = (char *)(argv + argc);
1316 memcpy( d, cmdline, len );
1317 bcount=0;
1318 in_quotes=0;
1319 argc=reserved;
1320 while (*s) {
1321 if ((*s==' ' || *s=='\t') && !in_quotes) {
1322 /* Close the argument and copy it */
1323 *d=0;
1324 argv[argc++]=arg;
1326 /* skip the remaining spaces */
1327 do {
1328 s++;
1329 } while (*s==' ' || *s=='\t');
1331 /* Start with a new argument */
1332 arg=d=s;
1333 bcount=0;
1334 } else if (*s=='\\') {
1335 /* '\\' */
1336 *d++=*s++;
1337 bcount++;
1338 } else if (*s=='"') {
1339 /* '"' */
1340 if ((bcount & 1)==0) {
1341 /* Preceded by an even number of '\', this is half that
1342 * number of '\', plus a '"' which we discard.
1344 d-=bcount/2;
1345 s++;
1346 in_quotes=!in_quotes;
1347 } else {
1348 /* Preceded by an odd number of '\', this is half that
1349 * number of '\' followed by a '"'
1351 d=d-bcount/2-1;
1352 *d++='"';
1353 s++;
1355 bcount=0;
1356 } else {
1357 /* a regular character */
1358 *d++=*s++;
1359 bcount=0;
1362 if (*arg) {
1363 *d='\0';
1364 argv[argc++]=arg;
1366 argv[argc]=NULL;
1368 HeapFree( GetProcessHeap(), 0, cmdline );
1369 return argv;
1373 /***********************************************************************
1374 * build_envp
1376 * Build the environment of a new child process.
1378 static char **build_envp( const WCHAR *envW )
1380 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1382 const WCHAR *end;
1383 char **envp;
1384 char *env, *p;
1385 int count = 1, length;
1386 unsigned int i;
1388 for (end = envW; *end; count++) end += strlenW(end) + 1;
1389 end++;
1390 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1391 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1392 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1394 for (p = env; *p; p += strlen(p) + 1)
1395 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1397 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1399 if (!(p = getenv(unix_vars[i]))) continue;
1400 length += strlen(unix_vars[i]) + strlen(p) + 2;
1401 count++;
1404 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1406 char **envptr = envp;
1407 char *dst = (char *)(envp + count);
1409 /* some variables must not be modified, so we get them directly from the unix env */
1410 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1412 if (!(p = getenv(unix_vars[i]))) continue;
1413 *envptr++ = strcpy( dst, unix_vars[i] );
1414 strcat( dst, "=" );
1415 strcat( dst, p );
1416 dst += strlen(dst) + 1;
1419 /* now put the Windows environment strings */
1420 for (p = env; *p; p += strlen(p) + 1)
1422 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1423 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1424 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1425 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1426 if (is_special_env_var( p )) /* prefix it with "WINE" */
1428 *envptr++ = strcpy( dst, "WINE" );
1429 strcat( dst, p );
1431 else
1433 *envptr++ = strcpy( dst, p );
1435 dst += strlen(dst) + 1;
1437 *envptr = 0;
1439 HeapFree( GetProcessHeap(), 0, env );
1440 return envp;
1444 /***********************************************************************
1445 * fork_and_exec
1447 * Fork and exec a new Unix binary, checking for errors.
1449 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1450 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1452 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1453 int pid, err;
1454 char **argv, **envp;
1456 if (!env) env = GetEnvironmentStringsW();
1458 #ifdef HAVE_PIPE2
1459 if (pipe2( fd, O_CLOEXEC ) == -1)
1460 #endif
1462 if (pipe(fd) == -1)
1464 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1465 return -1;
1467 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1468 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1471 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1473 HANDLE hstdin, hstdout, hstderr;
1475 if (startup->dwFlags & STARTF_USESTDHANDLES)
1477 hstdin = startup->hStdInput;
1478 hstdout = startup->hStdOutput;
1479 hstderr = startup->hStdError;
1481 else
1483 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1484 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1485 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1488 if (is_console_handle( hstdin ))
1489 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1490 if (is_console_handle( hstdout ))
1491 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1492 if (is_console_handle( hstderr ))
1493 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1494 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1495 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1496 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1499 argv = build_argv( cmdline, 0 );
1500 envp = build_envp( env );
1502 if (!(pid = fork())) /* child */
1504 if (!(pid = fork())) /* grandchild */
1506 close( fd[0] );
1508 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1510 int nullfd = open( "/dev/null", O_RDWR );
1511 setsid();
1512 /* close stdin and stdout */
1513 if (nullfd != -1)
1515 dup2( nullfd, 0 );
1516 dup2( nullfd, 1 );
1517 close( nullfd );
1520 else
1522 if (stdin_fd != -1)
1524 dup2( stdin_fd, 0 );
1525 close( stdin_fd );
1527 if (stdout_fd != -1)
1529 dup2( stdout_fd, 1 );
1530 close( stdout_fd );
1532 if (stderr_fd != -1)
1534 dup2( stderr_fd, 2 );
1535 close( stderr_fd );
1539 /* Reset signals that we previously set to SIG_IGN */
1540 signal( SIGPIPE, SIG_DFL );
1542 if (newdir) chdir(newdir);
1544 if (argv && envp) execve( filename, argv, envp );
1547 if (pid <= 0) /* grandchild if exec failed or child if fork failed */
1549 err = errno;
1550 write( fd[1], &err, sizeof(err) );
1551 _exit(1);
1554 _exit(0); /* child if fork succeeded */
1556 HeapFree( GetProcessHeap(), 0, argv );
1557 HeapFree( GetProcessHeap(), 0, envp );
1558 if (stdin_fd != -1) close( stdin_fd );
1559 if (stdout_fd != -1) close( stdout_fd );
1560 if (stderr_fd != -1) close( stderr_fd );
1561 close( fd[1] );
1562 if (pid != -1)
1564 /* reap child */
1565 do {
1566 err = waitpid(pid, NULL, 0);
1567 } while (err < 0 && errno == EINTR);
1569 if (read( fd[0], &err, sizeof(err) ) > 0) /* exec or second fork failed */
1571 errno = err;
1572 pid = -1;
1575 if (pid == -1) FILE_SetDosError();
1576 close( fd[0] );
1577 return pid;
1581 static inline DWORD append_string( void **ptr, const WCHAR *str )
1583 DWORD len = strlenW( str );
1584 memcpy( *ptr, str, len * sizeof(WCHAR) );
1585 *ptr = (WCHAR *)*ptr + len;
1586 return len * sizeof(WCHAR);
1589 /***********************************************************************
1590 * create_startup_info
1592 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1593 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1594 const STARTUPINFOW *startup, DWORD *info_size )
1596 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1597 const WCHAR *title;
1598 startup_info_t *info;
1599 DWORD size;
1600 void *ptr;
1601 UNICODE_STRING newdir;
1602 WCHAR imagepath[MAX_PATH];
1603 HANDLE hstdin, hstdout, hstderr;
1605 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1606 lstrcpynW( imagepath, filename, MAX_PATH );
1607 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1608 lstrcpynW( imagepath, filename, MAX_PATH );
1610 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1612 newdir.Buffer = NULL;
1613 if (cur_dir)
1615 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1616 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1617 else
1618 cur_dir = NULL;
1620 if (!cur_dir)
1622 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1623 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1624 else
1625 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1627 title = startup->lpTitle ? startup->lpTitle : imagepath;
1629 size = sizeof(*info);
1630 size += strlenW( cur_dir ) * sizeof(WCHAR);
1631 size += cur_params->DllPath.Length;
1632 size += strlenW( imagepath ) * sizeof(WCHAR);
1633 size += strlenW( cmdline ) * sizeof(WCHAR);
1634 size += strlenW( title ) * sizeof(WCHAR);
1635 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1636 /* FIXME: shellinfo */
1637 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1638 size = (size + 1) & ~1;
1639 *info_size = size;
1641 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1643 info->console_flags = cur_params->ConsoleFlags;
1644 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1645 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1647 if (startup->dwFlags & STARTF_USESTDHANDLES)
1649 hstdin = startup->hStdInput;
1650 hstdout = startup->hStdOutput;
1651 hstderr = startup->hStdError;
1653 else
1655 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1656 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1657 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1659 info->hstdin = wine_server_obj_handle( hstdin );
1660 info->hstdout = wine_server_obj_handle( hstdout );
1661 info->hstderr = wine_server_obj_handle( hstderr );
1662 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1664 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1665 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1666 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1667 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1669 else
1671 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1672 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1673 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1676 info->x = startup->dwX;
1677 info->y = startup->dwY;
1678 info->xsize = startup->dwXSize;
1679 info->ysize = startup->dwYSize;
1680 info->xchars = startup->dwXCountChars;
1681 info->ychars = startup->dwYCountChars;
1682 info->attribute = startup->dwFillAttribute;
1683 info->flags = startup->dwFlags;
1684 info->show = startup->wShowWindow;
1686 ptr = info + 1;
1687 info->curdir_len = append_string( &ptr, cur_dir );
1688 info->dllpath_len = cur_params->DllPath.Length;
1689 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1690 ptr = (char *)ptr + cur_params->DllPath.Length;
1691 info->imagepath_len = append_string( &ptr, imagepath );
1692 info->cmdline_len = append_string( &ptr, cmdline );
1693 info->title_len = append_string( &ptr, title );
1694 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1695 if (startup->lpReserved2 && startup->cbReserved2)
1697 info->runtime_len = startup->cbReserved2;
1698 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1701 done:
1702 RtlFreeUnicodeString( &newdir );
1703 return info;
1706 /***********************************************************************
1707 * get_alternate_loader
1709 * Get the name of the alternate (32 or 64 bit) Wine loader.
1711 static const char *get_alternate_loader( char **ret_env )
1713 char *env;
1714 const char *loader = NULL;
1715 const char *loader_env = getenv( "WINELOADER" );
1717 *ret_env = NULL;
1719 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1721 if (loader_env)
1723 int len = strlen( loader_env );
1724 if (!is_win64)
1726 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1727 strcpy( env, "WINELOADER=" );
1728 strcat( env, loader_env );
1729 strcat( env, "64" );
1731 else
1733 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1734 strcpy( env, "WINELOADER=" );
1735 strcat( env, loader_env );
1736 len += sizeof("WINELOADER=") - 1;
1737 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1739 if (!loader)
1741 if ((loader = strrchr( env, '/' ))) loader++;
1742 else loader = env;
1744 *ret_env = env;
1746 if (!loader) loader = is_win64 ? "wine" : "wine64";
1747 return loader;
1750 #ifdef __APPLE__
1751 /***********************************************************************
1752 * terminate_main_thread
1754 * On some versions of Mac OS X, the execve system call fails with
1755 * ENOTSUP if the process has multiple threads. Wine is always multi-
1756 * threaded on Mac OS X because it specifically reserves the main thread
1757 * for use by the system frameworks (see apple_main_thread() in
1758 * libs/wine/loader.c). So, when we need to exec without first forking,
1759 * we need to terminate the main thread first. We do this by installing
1760 * a custom run loop source onto the main run loop and signaling it.
1761 * The source's "perform" callback is pthread_exit and it will be
1762 * executed on the main thread, terminating it.
1764 * Returns TRUE if there's still hope the main thread has terminated or
1765 * will soon. Return FALSE if we've given up.
1767 static BOOL terminate_main_thread(void)
1769 static int delayms;
1771 if (!delayms)
1773 CFRunLoopSourceContext source_context = { 0 };
1774 CFRunLoopSourceRef source;
1776 source_context.perform = pthread_exit;
1777 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1778 return FALSE;
1780 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1781 CFRunLoopSourceSignal( source );
1782 CFRunLoopWakeUp( CFRunLoopGetMain() );
1783 CFRelease( source );
1785 delayms = 20;
1788 if (delayms > 1000)
1789 return FALSE;
1791 usleep(delayms * 1000);
1792 delayms *= 2;
1794 return TRUE;
1796 #endif
1798 /***********************************************************************
1799 * exec_loader
1801 static pid_t exec_loader( LPCWSTR cmd_line, unsigned int flags, int socketfd,
1802 int stdin_fd, int stdout_fd, const char *unixdir, char *winedebug,
1803 const struct binary_info *binary_info, int exec_only )
1805 pid_t pid;
1806 char *wineloader = NULL;
1807 const char *loader = NULL;
1808 char **argv;
1810 argv = build_argv( cmd_line, 1 );
1812 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1813 loader = get_alternate_loader( &wineloader );
1815 if (exec_only || !(pid = fork())) /* child */
1817 if (exec_only || !(pid = fork())) /* grandchild */
1819 char preloader_reserve[64], socket_env[64];
1821 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1823 int fd = open( "/dev/null", O_RDWR );
1824 setsid();
1825 /* close stdin and stdout */
1826 if (fd != -1)
1828 dup2( fd, 0 );
1829 dup2( fd, 1 );
1830 close( fd );
1833 else
1835 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1836 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1839 if (stdin_fd != -1) close( stdin_fd );
1840 if (stdout_fd != -1) close( stdout_fd );
1842 /* Reset signals that we previously set to SIG_IGN */
1843 signal( SIGPIPE, SIG_DFL );
1845 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
1846 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1847 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1849 putenv( preloader_reserve );
1850 putenv( socket_env );
1851 if (winedebug) putenv( winedebug );
1852 if (wineloader) putenv( wineloader );
1853 if (unixdir) chdir(unixdir);
1855 if (argv)
1859 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1861 #ifdef __APPLE__
1862 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1863 #else
1864 while (0);
1865 #endif
1867 _exit(1);
1870 _exit(pid == -1);
1873 if (pid != -1)
1875 /* reap child */
1876 pid_t wret;
1877 do {
1878 wret = waitpid(pid, NULL, 0);
1879 } while (wret < 0 && errno == EINTR);
1882 HeapFree( GetProcessHeap(), 0, wineloader );
1883 HeapFree( GetProcessHeap(), 0, argv );
1884 return pid;
1887 /***********************************************************************
1888 * create_process
1890 * Create a new process. If hFile is a valid handle we have an exe
1891 * file, otherwise it is a Winelib app.
1893 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1894 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1895 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1896 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1897 const struct binary_info *binary_info, int exec_only )
1899 BOOL ret, success = FALSE;
1900 HANDLE process_info;
1901 WCHAR *env_end;
1902 char *winedebug = NULL;
1903 startup_info_t *startup_info;
1904 DWORD startup_info_size;
1905 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1906 pid_t pid;
1907 int err;
1909 if (!is_win64 && !is_wow64 && (binary_info->flags & BINARY_FLAG_64BIT))
1911 ERR( "starting 64-bit process %s not supported in 32-bit wineprefix\n", debugstr_w(filename) );
1912 SetLastError( ERROR_BAD_EXE_FORMAT );
1913 return FALSE;
1916 /* create the socket for the new process */
1918 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1920 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1921 return FALSE;
1923 #ifdef SO_PASSCRED
1924 else
1926 int enable = 1;
1927 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1929 #endif
1931 if (exec_only) /* things are much simpler in this case */
1933 wine_server_send_fd( socketfd[1] );
1934 close( socketfd[1] );
1935 SERVER_START_REQ( new_process )
1937 req->create_flags = flags;
1938 req->socket_fd = socketfd[1];
1939 req->exe_file = wine_server_obj_handle( hFile );
1940 ret = !wine_server_call_err( req );
1942 SERVER_END_REQ;
1944 if (ret) exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
1945 winedebug, binary_info, TRUE );
1947 close( socketfd[0] );
1948 return FALSE;
1951 RtlAcquirePebLock();
1953 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1954 &startup_info_size )))
1956 RtlReleasePebLock();
1957 close( socketfd[0] );
1958 close( socketfd[1] );
1959 return FALSE;
1961 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
1962 env_end = env;
1963 while (*env_end)
1965 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1966 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1968 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1969 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1970 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1972 env_end += strlenW(env_end) + 1;
1974 env_end++;
1976 wine_server_send_fd( socketfd[1] );
1977 close( socketfd[1] );
1979 /* create the process on the server side */
1981 SERVER_START_REQ( new_process )
1983 req->inherit_all = inherit;
1984 req->create_flags = flags;
1985 req->socket_fd = socketfd[1];
1986 req->exe_file = wine_server_obj_handle( hFile );
1987 req->process_access = PROCESS_ALL_ACCESS;
1988 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1989 req->thread_access = THREAD_ALL_ACCESS;
1990 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1991 req->info_size = startup_info_size;
1993 wine_server_add_data( req, startup_info, startup_info_size );
1994 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
1995 if ((ret = !wine_server_call_err( req )))
1997 info->dwProcessId = (DWORD)reply->pid;
1998 info->dwThreadId = (DWORD)reply->tid;
1999 info->hProcess = wine_server_ptr_handle( reply->phandle );
2000 info->hThread = wine_server_ptr_handle( reply->thandle );
2002 process_info = wine_server_ptr_handle( reply->info );
2004 SERVER_END_REQ;
2006 RtlReleasePebLock();
2007 if (!ret)
2009 close( socketfd[0] );
2010 HeapFree( GetProcessHeap(), 0, startup_info );
2011 HeapFree( GetProcessHeap(), 0, winedebug );
2012 return FALSE;
2015 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
2017 if (startup_info->hstdin)
2018 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
2019 FILE_READ_DATA, &stdin_fd, NULL );
2020 if (startup_info->hstdout)
2021 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
2022 FILE_WRITE_DATA, &stdout_fd, NULL );
2024 HeapFree( GetProcessHeap(), 0, startup_info );
2026 /* create the child process */
2028 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2029 winedebug, binary_info, FALSE );
2031 if (stdin_fd != -1) close( stdin_fd );
2032 if (stdout_fd != -1) close( stdout_fd );
2033 close( socketfd[0] );
2034 HeapFree( GetProcessHeap(), 0, winedebug );
2035 if (pid == -1)
2037 FILE_SetDosError();
2038 goto error;
2041 /* wait for the new process info to be ready */
2043 WaitForSingleObject( process_info, INFINITE );
2044 SERVER_START_REQ( get_new_process_info )
2046 req->info = wine_server_obj_handle( process_info );
2047 wine_server_call( req );
2048 success = reply->success;
2049 err = reply->exit_code;
2051 SERVER_END_REQ;
2053 if (!success)
2055 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2056 goto error;
2058 CloseHandle( process_info );
2059 return success;
2061 error:
2062 CloseHandle( process_info );
2063 CloseHandle( info->hProcess );
2064 CloseHandle( info->hThread );
2065 info->hProcess = info->hThread = 0;
2066 info->dwProcessId = info->dwThreadId = 0;
2067 return FALSE;
2071 /***********************************************************************
2072 * create_vdm_process
2074 * Create a new VDM process for a 16-bit or DOS application.
2076 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2077 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2078 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2079 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2080 const struct binary_info *binary_info, int exec_only )
2082 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2084 BOOL ret;
2085 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
2086 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
2088 if (!new_cmd_line)
2090 SetLastError( ERROR_OUTOFMEMORY );
2091 return FALSE;
2093 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
2094 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2095 flags, startup, info, unixdir, binary_info, exec_only );
2096 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2097 return ret;
2101 /***********************************************************************
2102 * create_cmd_process
2104 * Create a new cmd shell process for a .BAT file.
2106 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2107 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2108 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2109 LPPROCESS_INFORMATION info )
2112 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2113 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2114 WCHAR comspec[MAX_PATH];
2115 WCHAR *newcmdline;
2116 BOOL ret;
2118 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2119 return FALSE;
2120 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2121 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2122 return FALSE;
2124 strcpyW( newcmdline, comspec );
2125 strcatW( newcmdline, slashcW );
2126 strcatW( newcmdline, cmd_line );
2127 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2128 flags, env, cur_dir, startup, info );
2129 HeapFree( GetProcessHeap(), 0, newcmdline );
2130 return ret;
2134 /*************************************************************************
2135 * get_file_name
2137 * Helper for CreateProcess: retrieve the file name to load from the
2138 * app name and command line. Store the file name in buffer, and
2139 * return a possibly modified command line.
2140 * Also returns a handle to the opened file if it's a Windows binary.
2142 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2143 int buflen, HANDLE *handle, struct binary_info *binary_info )
2145 static const WCHAR quotesW[] = {'"','%','s','"',0};
2147 WCHAR *name, *pos, *first_space, *ret = NULL;
2148 const WCHAR *p;
2150 /* if we have an app name, everything is easy */
2152 if (appname)
2154 /* use the unmodified app name as file name */
2155 lstrcpynW( buffer, appname, buflen );
2156 *handle = open_exe_file( buffer, binary_info );
2157 if (!(ret = cmdline) || !cmdline[0])
2159 /* no command-line, create one */
2160 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2161 sprintfW( ret, quotesW, appname );
2163 return ret;
2166 /* first check for a quoted file name */
2168 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2170 int len = p - cmdline - 1;
2171 /* extract the quoted portion as file name */
2172 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2173 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2174 name[len] = 0;
2176 if (!find_exe_file( name, buffer, buflen, handle, binary_info )) goto done;
2177 ret = cmdline; /* no change necessary */
2178 goto done;
2181 /* now try the command-line word by word */
2183 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2184 return NULL;
2185 pos = name;
2186 p = cmdline;
2187 first_space = NULL;
2189 for (;;)
2191 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2192 *pos = 0;
2193 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2195 ret = cmdline;
2196 break;
2198 if (!first_space) first_space = pos;
2199 if (!(*pos++ = *p++)) break;
2202 if (!ret)
2204 SetLastError( ERROR_FILE_NOT_FOUND );
2206 else if (first_space) /* build a new command-line with quotes */
2208 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2209 goto done;
2210 sprintfW( ret, quotesW, name );
2211 strcatW( ret, p );
2214 done:
2215 HeapFree( GetProcessHeap(), 0, name );
2216 return ret;
2220 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2221 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2222 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2223 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2224 LPPROCESS_INFORMATION info )
2226 BOOL retv = FALSE;
2227 HANDLE hFile = 0;
2228 char *unixdir = NULL;
2229 WCHAR name[MAX_PATH];
2230 WCHAR *tidy_cmdline, *p, *envW = env;
2231 struct binary_info binary_info;
2233 /* Process the AppName and/or CmdLine to get module name and path */
2235 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2237 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2238 &hFile, &binary_info )))
2239 return FALSE;
2240 if (hFile == INVALID_HANDLE_VALUE) goto done;
2242 /* Warn if unsupported features are used */
2244 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2245 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2246 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2247 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2248 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2250 if (cur_dir)
2252 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2254 SetLastError(ERROR_DIRECTORY);
2255 goto done;
2258 else
2260 WCHAR buf[MAX_PATH];
2261 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2264 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2266 char *e = env;
2267 DWORD lenW;
2269 while (*e) e += strlen(e) + 1;
2270 e++; /* final null */
2271 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, NULL, 0 );
2272 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2273 MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, envW, lenW );
2274 flags |= CREATE_UNICODE_ENVIRONMENT;
2277 info->hThread = info->hProcess = 0;
2278 info->dwProcessId = info->dwThreadId = 0;
2280 if (binary_info.flags & BINARY_FLAG_DLL)
2282 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2283 SetLastError( ERROR_BAD_EXE_FORMAT );
2285 else switch (binary_info.type)
2287 case BINARY_PE:
2288 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2289 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2290 binary_info.res_start, binary_info.res_end );
2291 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2292 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2293 break;
2294 case BINARY_OS216:
2295 case BINARY_WIN16:
2296 case BINARY_DOS:
2297 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2298 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2299 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2300 break;
2301 case BINARY_UNIX_LIB:
2302 TRACE( "starting %s as %d-bit Winelib app\n",
2303 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2304 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2305 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2306 break;
2307 case BINARY_UNKNOWN:
2308 /* check for .com or .bat extension */
2309 if ((p = strrchrW( name, '.' )))
2311 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2313 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2314 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2315 inherit, flags, startup_info, info, unixdir,
2316 &binary_info, FALSE );
2317 break;
2319 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2321 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2322 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2323 inherit, flags, startup_info, info );
2324 break;
2327 /* fall through */
2328 case BINARY_UNIX_EXE:
2330 /* unknown file, try as unix executable */
2331 char *unix_name;
2333 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2335 if ((unix_name = wine_get_unix_file_name( name )))
2337 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2338 HeapFree( GetProcessHeap(), 0, unix_name );
2341 break;
2343 if (hFile) CloseHandle( hFile );
2345 done:
2346 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2347 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2348 HeapFree( GetProcessHeap(), 0, unixdir );
2349 if (retv)
2350 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2351 return retv;
2355 /**********************************************************************
2356 * CreateProcessA (KERNEL32.@)
2358 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2359 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2360 DWORD flags, LPVOID env, LPCSTR cur_dir,
2361 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2363 BOOL ret = FALSE;
2364 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2365 UNICODE_STRING desktopW, titleW;
2366 STARTUPINFOW infoW;
2368 desktopW.Buffer = NULL;
2369 titleW.Buffer = NULL;
2370 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2371 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2372 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2374 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2375 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2377 memcpy( &infoW, startup_info, sizeof(infoW) );
2378 infoW.lpDesktop = desktopW.Buffer;
2379 infoW.lpTitle = titleW.Buffer;
2381 if (startup_info->lpReserved)
2382 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2383 debugstr_a(startup_info->lpReserved));
2385 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2386 inherit, flags, env, cur_dirW, &infoW, info );
2387 done:
2388 HeapFree( GetProcessHeap(), 0, app_nameW );
2389 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2390 HeapFree( GetProcessHeap(), 0, cur_dirW );
2391 RtlFreeUnicodeString( &desktopW );
2392 RtlFreeUnicodeString( &titleW );
2393 return ret;
2397 /**********************************************************************
2398 * CreateProcessW (KERNEL32.@)
2400 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2401 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2402 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2403 LPPROCESS_INFORMATION info )
2405 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2406 inherit, flags, env, cur_dir, startup_info, info);
2410 /**********************************************************************
2411 * exec_process
2413 static void exec_process( LPCWSTR name )
2415 HANDLE hFile;
2416 WCHAR *p;
2417 STARTUPINFOW startup_info;
2418 PROCESS_INFORMATION info;
2419 struct binary_info binary_info;
2421 hFile = open_exe_file( name, &binary_info );
2422 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2424 memset( &startup_info, 0, sizeof(startup_info) );
2425 startup_info.cb = sizeof(startup_info);
2427 /* Determine executable type */
2429 if (binary_info.flags & BINARY_FLAG_DLL) return;
2430 switch (binary_info.type)
2432 case BINARY_PE:
2433 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2434 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2435 binary_info.res_start, binary_info.res_end );
2436 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2437 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2438 break;
2439 case BINARY_UNIX_LIB:
2440 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2441 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2442 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2443 break;
2444 case BINARY_UNKNOWN:
2445 /* check for .com or .pif extension */
2446 if (!(p = strrchrW( name, '.' ))) break;
2447 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2448 /* fall through */
2449 case BINARY_OS216:
2450 case BINARY_WIN16:
2451 case BINARY_DOS:
2452 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2453 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2454 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2455 break;
2456 default:
2457 break;
2459 CloseHandle( hFile );
2463 /***********************************************************************
2464 * wait_input_idle
2466 * Wrapper to call WaitForInputIdle USER function
2468 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2470 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2472 HMODULE mod = GetModuleHandleA( "user32.dll" );
2473 if (mod)
2475 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2476 if (ptr) return ptr( process, timeout );
2478 return 0;
2482 /***********************************************************************
2483 * WinExec (KERNEL32.@)
2485 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2487 PROCESS_INFORMATION info;
2488 STARTUPINFOA startup;
2489 char *cmdline;
2490 UINT ret;
2492 memset( &startup, 0, sizeof(startup) );
2493 startup.cb = sizeof(startup);
2494 startup.dwFlags = STARTF_USESHOWWINDOW;
2495 startup.wShowWindow = nCmdShow;
2497 /* cmdline needs to be writable for CreateProcess */
2498 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2499 strcpy( cmdline, lpCmdLine );
2501 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2502 0, NULL, NULL, &startup, &info ))
2504 /* Give 30 seconds to the app to come up */
2505 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2506 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2507 ret = 33;
2508 /* Close off the handles */
2509 CloseHandle( info.hThread );
2510 CloseHandle( info.hProcess );
2512 else if ((ret = GetLastError()) >= 32)
2514 FIXME("Strange error set by CreateProcess: %d\n", ret );
2515 ret = 11;
2517 HeapFree( GetProcessHeap(), 0, cmdline );
2518 return ret;
2522 /**********************************************************************
2523 * LoadModule (KERNEL32.@)
2525 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2527 LOADPARMS32 *params = paramBlock;
2528 PROCESS_INFORMATION info;
2529 STARTUPINFOA startup;
2530 DWORD ret;
2531 LPSTR cmdline, p;
2532 char filename[MAX_PATH];
2533 BYTE len;
2535 if (!name) return ERROR_FILE_NOT_FOUND;
2537 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2538 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2539 return GetLastError();
2541 len = (BYTE)params->lpCmdLine[0];
2542 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2543 return ERROR_NOT_ENOUGH_MEMORY;
2545 strcpy( cmdline, filename );
2546 p = cmdline + strlen(cmdline);
2547 *p++ = ' ';
2548 memcpy( p, params->lpCmdLine + 1, len );
2549 p[len] = 0;
2551 memset( &startup, 0, sizeof(startup) );
2552 startup.cb = sizeof(startup);
2553 if (params->lpCmdShow)
2555 startup.dwFlags = STARTF_USESHOWWINDOW;
2556 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2559 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2560 params->lpEnvAddress, NULL, &startup, &info ))
2562 /* Give 30 seconds to the app to come up */
2563 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2564 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2565 ret = 33;
2566 /* Close off the handles */
2567 CloseHandle( info.hThread );
2568 CloseHandle( info.hProcess );
2570 else if ((ret = GetLastError()) >= 32)
2572 FIXME("Strange error set by CreateProcess: %u\n", ret );
2573 ret = 11;
2576 HeapFree( GetProcessHeap(), 0, cmdline );
2577 return ret;
2581 /******************************************************************************
2582 * TerminateProcess (KERNEL32.@)
2584 * Terminates a process.
2586 * PARAMS
2587 * handle [I] Process to terminate.
2588 * exit_code [I] Exit code.
2590 * RETURNS
2591 * Success: TRUE.
2592 * Failure: FALSE, check GetLastError().
2594 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2596 NTSTATUS status;
2598 if (!handle)
2600 SetLastError( ERROR_INVALID_HANDLE );
2601 return FALSE;
2604 status = NtTerminateProcess( handle, exit_code );
2605 if (status) SetLastError( RtlNtStatusToDosError(status) );
2606 return !status;
2609 /***********************************************************************
2610 * ExitProcess (KERNEL32.@)
2612 * Exits the current process.
2614 * PARAMS
2615 * status [I] Status code to exit with.
2617 * RETURNS
2618 * Nothing.
2620 #ifdef __i386__
2621 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2622 "pushl %ebp\n\t"
2623 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2624 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2625 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2626 "pushl 8(%ebp)\n\t"
2627 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2628 "leave\n\t"
2629 "ret $4" )
2631 void WINAPI process_ExitProcess( DWORD status )
2633 RtlAcquirePebLock();
2634 NtTerminateProcess(0, status);
2635 LdrShutdownProcess();
2636 NtTerminateProcess(GetCurrentProcess(), status);
2637 exit(status);
2640 #else
2642 void WINAPI ExitProcess( DWORD status )
2644 RtlAcquirePebLock();
2645 NtTerminateProcess(0, status);
2646 LdrShutdownProcess();
2647 NtTerminateProcess(GetCurrentProcess(), status);
2648 exit(status);
2651 #endif
2653 /***********************************************************************
2654 * GetExitCodeProcess [KERNEL32.@]
2656 * Gets termination status of specified process.
2658 * PARAMS
2659 * hProcess [in] Handle to the process.
2660 * lpExitCode [out] Address to receive termination status.
2662 * RETURNS
2663 * Success: TRUE
2664 * Failure: FALSE
2666 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2668 NTSTATUS status;
2669 PROCESS_BASIC_INFORMATION pbi;
2671 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2672 sizeof(pbi), NULL);
2673 if (status == STATUS_SUCCESS)
2675 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2676 return TRUE;
2678 SetLastError( RtlNtStatusToDosError(status) );
2679 return FALSE;
2683 /***********************************************************************
2684 * SetErrorMode (KERNEL32.@)
2686 UINT WINAPI SetErrorMode( UINT mode )
2688 UINT old;
2690 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2691 &old, sizeof(old), NULL );
2692 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2693 &mode, sizeof(mode) );
2694 return old;
2697 /***********************************************************************
2698 * GetErrorMode (KERNEL32.@)
2700 UINT WINAPI GetErrorMode( void )
2702 UINT mode;
2704 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2705 &mode, sizeof(mode), NULL );
2706 return mode;
2709 /**********************************************************************
2710 * TlsAlloc [KERNEL32.@]
2712 * Allocates a thread local storage index.
2714 * RETURNS
2715 * Success: TLS index.
2716 * Failure: 0xFFFFFFFF
2718 DWORD WINAPI TlsAlloc( void )
2720 DWORD index;
2721 PEB * const peb = NtCurrentTeb()->Peb;
2723 RtlAcquirePebLock();
2724 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2725 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2726 else
2728 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2729 if (index != ~0U)
2731 if (!NtCurrentTeb()->TlsExpansionSlots &&
2732 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2733 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2735 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2736 index = ~0U;
2737 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2739 else
2741 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2742 index += TLS_MINIMUM_AVAILABLE;
2745 else SetLastError( ERROR_NO_MORE_ITEMS );
2747 RtlReleasePebLock();
2748 return index;
2752 /**********************************************************************
2753 * TlsFree [KERNEL32.@]
2755 * Releases a thread local storage index, making it available for reuse.
2757 * PARAMS
2758 * index [in] TLS index to free.
2760 * RETURNS
2761 * Success: TRUE
2762 * Failure: FALSE
2764 BOOL WINAPI TlsFree( DWORD index )
2766 BOOL ret;
2768 RtlAcquirePebLock();
2769 if (index >= TLS_MINIMUM_AVAILABLE)
2771 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2772 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2774 else
2776 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2777 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2779 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2780 else SetLastError( ERROR_INVALID_PARAMETER );
2781 RtlReleasePebLock();
2782 return ret;
2786 /**********************************************************************
2787 * TlsGetValue [KERNEL32.@]
2789 * Gets value in a thread's TLS slot.
2791 * PARAMS
2792 * index [in] TLS index to retrieve value for.
2794 * RETURNS
2795 * Success: Value stored in calling thread's TLS slot for index.
2796 * Failure: 0 and GetLastError() returns NO_ERROR.
2798 LPVOID WINAPI TlsGetValue( DWORD index )
2800 LPVOID ret;
2802 if (index < TLS_MINIMUM_AVAILABLE)
2804 ret = NtCurrentTeb()->TlsSlots[index];
2806 else
2808 index -= TLS_MINIMUM_AVAILABLE;
2809 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2811 SetLastError( ERROR_INVALID_PARAMETER );
2812 return NULL;
2814 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2815 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2817 SetLastError( ERROR_SUCCESS );
2818 return ret;
2822 /**********************************************************************
2823 * TlsSetValue [KERNEL32.@]
2825 * Stores a value in the thread's TLS slot.
2827 * PARAMS
2828 * index [in] TLS index to set value for.
2829 * value [in] Value to be stored.
2831 * RETURNS
2832 * Success: TRUE
2833 * Failure: FALSE
2835 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2837 if (index < TLS_MINIMUM_AVAILABLE)
2839 NtCurrentTeb()->TlsSlots[index] = value;
2841 else
2843 index -= TLS_MINIMUM_AVAILABLE;
2844 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2846 SetLastError( ERROR_INVALID_PARAMETER );
2847 return FALSE;
2849 if (!NtCurrentTeb()->TlsExpansionSlots &&
2850 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2851 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2853 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2854 return FALSE;
2856 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2858 return TRUE;
2862 /***********************************************************************
2863 * GetProcessFlags (KERNEL32.@)
2865 DWORD WINAPI GetProcessFlags( DWORD processid )
2867 IMAGE_NT_HEADERS *nt;
2868 DWORD flags = 0;
2870 if (processid && processid != GetCurrentProcessId()) return 0;
2872 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2874 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2875 flags |= PDB32_CONSOLE_PROC;
2877 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2878 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2879 return flags;
2883 /*********************************************************************
2884 * OpenProcess (KERNEL32.@)
2886 * Opens a handle to a process.
2888 * PARAMS
2889 * access [I] Desired access rights assigned to the returned handle.
2890 * inherit [I] Determines whether or not child processes will inherit the handle.
2891 * id [I] Process identifier of the process to get a handle to.
2893 * RETURNS
2894 * Success: Valid handle to the specified process.
2895 * Failure: NULL, check GetLastError().
2897 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2899 NTSTATUS status;
2900 HANDLE handle;
2901 OBJECT_ATTRIBUTES attr;
2902 CLIENT_ID cid;
2904 cid.UniqueProcess = ULongToHandle(id);
2905 cid.UniqueThread = 0; /* FIXME ? */
2907 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2908 attr.RootDirectory = NULL;
2909 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2910 attr.SecurityDescriptor = NULL;
2911 attr.SecurityQualityOfService = NULL;
2912 attr.ObjectName = NULL;
2914 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2916 status = NtOpenProcess(&handle, access, &attr, &cid);
2917 if (status != STATUS_SUCCESS)
2919 SetLastError( RtlNtStatusToDosError(status) );
2920 return NULL;
2922 return handle;
2926 /*********************************************************************
2927 * GetProcessId (KERNEL32.@)
2929 * Gets the a unique identifier of a process.
2931 * PARAMS
2932 * hProcess [I] Handle to the process.
2934 * RETURNS
2935 * Success: TRUE.
2936 * Failure: FALSE, check GetLastError().
2938 * NOTES
2940 * The identifier is unique only on the machine and only until the process
2941 * exits (including system shutdown).
2943 DWORD WINAPI GetProcessId( HANDLE hProcess )
2945 NTSTATUS status;
2946 PROCESS_BASIC_INFORMATION pbi;
2948 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2949 sizeof(pbi), NULL);
2950 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2951 SetLastError( RtlNtStatusToDosError(status) );
2952 return 0;
2956 /*********************************************************************
2957 * CloseHandle (KERNEL32.@)
2959 * Closes a handle.
2961 * PARAMS
2962 * handle [I] Handle to close.
2964 * RETURNS
2965 * Success: TRUE.
2966 * Failure: FALSE, check GetLastError().
2968 BOOL WINAPI CloseHandle( HANDLE handle )
2970 NTSTATUS status;
2972 /* stdio handles need special treatment */
2973 if (handle == (HANDLE)STD_INPUT_HANDLE)
2974 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
2975 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
2976 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
2977 else if (handle == (HANDLE)STD_ERROR_HANDLE)
2978 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
2980 if (is_console_handle(handle))
2981 return CloseConsoleHandle(handle);
2983 status = NtClose( handle );
2984 if (status) SetLastError( RtlNtStatusToDosError(status) );
2985 return !status;
2989 /*********************************************************************
2990 * GetHandleInformation (KERNEL32.@)
2992 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2994 OBJECT_DATA_INFORMATION info;
2995 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2997 if (status) SetLastError( RtlNtStatusToDosError(status) );
2998 else if (flags)
3000 *flags = 0;
3001 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3002 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3004 return !status;
3008 /*********************************************************************
3009 * SetHandleInformation (KERNEL32.@)
3011 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3013 OBJECT_DATA_INFORMATION info;
3014 NTSTATUS status;
3016 /* if not setting both fields, retrieve current value first */
3017 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3018 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3020 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3022 SetLastError( RtlNtStatusToDosError(status) );
3023 return FALSE;
3026 if (mask & HANDLE_FLAG_INHERIT)
3027 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3028 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3029 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3031 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3032 if (status) SetLastError( RtlNtStatusToDosError(status) );
3033 return !status;
3037 /*********************************************************************
3038 * DuplicateHandle (KERNEL32.@)
3040 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3041 HANDLE dest_process, HANDLE *dest,
3042 DWORD access, BOOL inherit, DWORD options )
3044 NTSTATUS status;
3046 if (is_console_handle(source))
3048 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3049 if (source_process != dest_process ||
3050 source_process != GetCurrentProcess())
3052 SetLastError(ERROR_INVALID_PARAMETER);
3053 return FALSE;
3055 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3056 return (*dest != INVALID_HANDLE_VALUE);
3058 status = NtDuplicateObject( source_process, source, dest_process, dest,
3059 access, inherit ? OBJ_INHERIT : 0, options );
3060 if (status) SetLastError( RtlNtStatusToDosError(status) );
3061 return !status;
3065 /***********************************************************************
3066 * ConvertToGlobalHandle (KERNEL32.@)
3068 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3070 HANDLE ret = INVALID_HANDLE_VALUE;
3071 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3072 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3073 return ret;
3077 /***********************************************************************
3078 * SetHandleContext (KERNEL32.@)
3080 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3082 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3083 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3084 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3085 return FALSE;
3089 /***********************************************************************
3090 * GetHandleContext (KERNEL32.@)
3092 DWORD WINAPI GetHandleContext(HANDLE hnd)
3094 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3095 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3096 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3097 return 0;
3101 /***********************************************************************
3102 * CreateSocketHandle (KERNEL32.@)
3104 HANDLE WINAPI CreateSocketHandle(void)
3106 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3107 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3108 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3109 return INVALID_HANDLE_VALUE;
3113 /***********************************************************************
3114 * SetPriorityClass (KERNEL32.@)
3116 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3118 NTSTATUS status;
3119 PROCESS_PRIORITY_CLASS ppc;
3121 ppc.Foreground = FALSE;
3122 switch (priorityclass)
3124 case IDLE_PRIORITY_CLASS:
3125 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3126 case BELOW_NORMAL_PRIORITY_CLASS:
3127 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3128 case NORMAL_PRIORITY_CLASS:
3129 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3130 case ABOVE_NORMAL_PRIORITY_CLASS:
3131 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3132 case HIGH_PRIORITY_CLASS:
3133 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3134 case REALTIME_PRIORITY_CLASS:
3135 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3136 default:
3137 SetLastError(ERROR_INVALID_PARAMETER);
3138 return FALSE;
3141 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3142 &ppc, sizeof(ppc));
3144 if (status != STATUS_SUCCESS)
3146 SetLastError( RtlNtStatusToDosError(status) );
3147 return FALSE;
3149 return TRUE;
3153 /***********************************************************************
3154 * GetPriorityClass (KERNEL32.@)
3156 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3158 NTSTATUS status;
3159 PROCESS_BASIC_INFORMATION pbi;
3161 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3162 sizeof(pbi), NULL);
3163 if (status != STATUS_SUCCESS)
3165 SetLastError( RtlNtStatusToDosError(status) );
3166 return 0;
3168 switch (pbi.BasePriority)
3170 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3171 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3172 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3173 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3174 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3175 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3177 SetLastError( ERROR_INVALID_PARAMETER );
3178 return 0;
3182 /***********************************************************************
3183 * SetProcessAffinityMask (KERNEL32.@)
3185 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3187 NTSTATUS status;
3189 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3190 &affmask, sizeof(DWORD_PTR));
3191 if (status)
3193 SetLastError( RtlNtStatusToDosError(status) );
3194 return FALSE;
3196 return TRUE;
3200 /**********************************************************************
3201 * GetProcessAffinityMask (KERNEL32.@)
3203 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3205 NTSTATUS status = STATUS_SUCCESS;
3207 if (system_mask) *system_mask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
3208 if (process_mask)
3210 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3211 process_mask, sizeof(*process_mask), NULL )))
3212 SetLastError( RtlNtStatusToDosError(status) );
3214 return !status;
3218 /***********************************************************************
3219 * GetProcessVersion (KERNEL32.@)
3221 DWORD WINAPI GetProcessVersion( DWORD pid )
3223 HANDLE process;
3224 NTSTATUS status;
3225 PROCESS_BASIC_INFORMATION pbi;
3226 SIZE_T count;
3227 PEB peb;
3228 IMAGE_DOS_HEADER dos;
3229 IMAGE_NT_HEADERS nt;
3230 DWORD ver = 0;
3232 if (!pid || pid == GetCurrentProcessId())
3234 IMAGE_NT_HEADERS *pnt;
3236 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3237 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3238 pnt->OptionalHeader.MinorSubsystemVersion);
3239 return 0;
3242 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3243 if (!process) return 0;
3245 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3246 if (status) goto err;
3248 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3249 if (status || count != sizeof(peb)) goto err;
3251 memset(&dos, 0, sizeof(dos));
3252 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3253 if (status || count != sizeof(dos)) goto err;
3254 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3256 memset(&nt, 0, sizeof(nt));
3257 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3258 if (status || count != sizeof(nt)) goto err;
3259 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3261 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3263 err:
3264 CloseHandle(process);
3266 if (status != STATUS_SUCCESS)
3267 SetLastError(RtlNtStatusToDosError(status));
3269 return ver;
3273 /***********************************************************************
3274 * SetProcessWorkingSetSize [KERNEL32.@]
3275 * Sets the min/max working set sizes for a specified process.
3277 * PARAMS
3278 * hProcess [I] Handle to the process of interest
3279 * minset [I] Specifies minimum working set size
3280 * maxset [I] Specifies maximum working set size
3282 * RETURNS
3283 * Success: TRUE
3284 * Failure: FALSE
3286 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3287 SIZE_T maxset)
3289 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3290 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3291 /* Trim the working set to zero */
3292 /* Swap the process out of physical RAM */
3294 return TRUE;
3297 /***********************************************************************
3298 * K32EmptyWorkingSet (KERNEL32.@)
3300 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3302 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3305 /***********************************************************************
3306 * GetProcessWorkingSetSize (KERNEL32.@)
3308 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3309 PSIZE_T maxset)
3311 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3312 /* 32 MB working set size */
3313 if (minset) *minset = 32*1024*1024;
3314 if (maxset) *maxset = 32*1024*1024;
3315 return TRUE;
3319 /***********************************************************************
3320 * SetProcessShutdownParameters (KERNEL32.@)
3322 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3324 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3325 shutdown_flags = flags;
3326 shutdown_priority = level;
3327 return TRUE;
3331 /***********************************************************************
3332 * GetProcessShutdownParameters (KERNEL32.@)
3335 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3337 *lpdwLevel = shutdown_priority;
3338 *lpdwFlags = shutdown_flags;
3339 return TRUE;
3343 /***********************************************************************
3344 * GetProcessPriorityBoost (KERNEL32.@)
3346 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3348 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3350 /* Report that no boost is present.. */
3351 *pDisablePriorityBoost = FALSE;
3353 return TRUE;
3356 /***********************************************************************
3357 * SetProcessPriorityBoost (KERNEL32.@)
3359 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3361 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3362 /* Say we can do it. I doubt the program will notice that we don't. */
3363 return TRUE;
3367 /***********************************************************************
3368 * ReadProcessMemory (KERNEL32.@)
3370 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3371 SIZE_T *bytes_read )
3373 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3374 if (status) SetLastError( RtlNtStatusToDosError(status) );
3375 return !status;
3379 /***********************************************************************
3380 * WriteProcessMemory (KERNEL32.@)
3382 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3383 SIZE_T *bytes_written )
3385 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3386 if (status) SetLastError( RtlNtStatusToDosError(status) );
3387 return !status;
3391 /****************************************************************************
3392 * FlushInstructionCache (KERNEL32.@)
3394 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3396 NTSTATUS status;
3397 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3398 if (status) SetLastError( RtlNtStatusToDosError(status) );
3399 return !status;
3403 /******************************************************************
3404 * GetProcessIoCounters (KERNEL32.@)
3406 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3408 NTSTATUS status;
3410 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3411 ioc, sizeof(*ioc), NULL);
3412 if (status) SetLastError( RtlNtStatusToDosError(status) );
3413 return !status;
3416 /******************************************************************
3417 * GetProcessHandleCount (KERNEL32.@)
3419 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3421 NTSTATUS status;
3423 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3424 cnt, sizeof(*cnt), NULL);
3425 if (status) SetLastError( RtlNtStatusToDosError(status) );
3426 return !status;
3429 /******************************************************************
3430 * QueryFullProcessImageNameA (KERNEL32.@)
3432 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3434 BOOL retval;
3435 DWORD pdwSizeW = *pdwSize;
3436 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3438 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3440 if(retval)
3441 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3442 lpExeName, *pdwSize, NULL, NULL));
3443 if(retval)
3444 *pdwSize = strlen(lpExeName);
3446 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3447 return retval;
3450 /******************************************************************
3451 * QueryFullProcessImageNameW (KERNEL32.@)
3453 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3455 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3456 UNICODE_STRING *dynamic_buffer = NULL;
3457 UNICODE_STRING *result = NULL;
3458 NTSTATUS status;
3459 DWORD needed;
3461 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3462 * is a DOS path and we depend on this. */
3463 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3464 sizeof(buffer) - sizeof(WCHAR), &needed);
3465 if (status == STATUS_INFO_LENGTH_MISMATCH)
3467 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3468 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3469 result = dynamic_buffer;
3471 else
3472 result = (PUNICODE_STRING)buffer;
3474 if (status) goto cleanup;
3476 if (dwFlags & PROCESS_NAME_NATIVE)
3478 WCHAR drive[3];
3479 WCHAR device[1024];
3480 DWORD ntlen, devlen;
3482 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3484 /* We cannot convert it to an NT device path so fail */
3485 status = STATUS_NO_SUCH_DEVICE;
3486 goto cleanup;
3489 /* Find this drive's NT device path */
3490 drive[0] = result->Buffer[0];
3491 drive[1] = ':';
3492 drive[2] = 0;
3493 if (!QueryDosDeviceW(drive, device, sizeof(device)/sizeof(*device)))
3495 status = STATUS_NO_SUCH_DEVICE;
3496 goto cleanup;
3499 devlen = lstrlenW(device);
3500 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3501 if (ntlen + 1 > *pdwSize)
3503 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3504 return 0;
3506 *pdwSize = ntlen;
3508 memcpy(lpExeName, device, devlen * sizeof(*device));
3509 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3510 lpExeName[*pdwSize] = 0;
3511 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3513 else
3515 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3517 status = STATUS_BUFFER_TOO_SMALL;
3518 goto cleanup;
3521 *pdwSize = result->Length/sizeof(WCHAR);
3522 memcpy( lpExeName, result->Buffer, result->Length );
3523 lpExeName[*pdwSize] = 0;
3526 cleanup:
3527 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3528 if (status) SetLastError( RtlNtStatusToDosError(status) );
3529 return !status;
3532 /***********************************************************************
3533 * K32GetProcessImageFileNameA (KERNEL32.@)
3535 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3537 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3540 /***********************************************************************
3541 * K32GetProcessImageFileNameW (KERNEL32.@)
3543 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3545 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3548 /***********************************************************************
3549 * K32EnumProcesses (KERNEL32.@)
3551 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3553 SYSTEM_PROCESS_INFORMATION *spi;
3554 ULONG size = 0x4000;
3555 void *buf = NULL;
3556 NTSTATUS status;
3558 do {
3559 size *= 2;
3560 HeapFree(GetProcessHeap(), 0, buf);
3561 buf = HeapAlloc(GetProcessHeap(), 0, size);
3562 if (!buf)
3563 return FALSE;
3565 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3566 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3568 if (status != STATUS_SUCCESS)
3570 HeapFree(GetProcessHeap(), 0, buf);
3571 SetLastError(RtlNtStatusToDosError(status));
3572 return FALSE;
3575 spi = buf;
3577 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3579 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3580 *lpcbUsed += sizeof(DWORD);
3582 if (spi->NextEntryOffset == 0)
3583 break;
3585 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3588 HeapFree(GetProcessHeap(), 0, buf);
3589 return TRUE;
3592 /***********************************************************************
3593 * K32QueryWorkingSet (KERNEL32.@)
3595 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3597 NTSTATUS status;
3599 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3601 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3603 if (status)
3605 SetLastError( RtlNtStatusToDosError( status ) );
3606 return FALSE;
3608 return TRUE;
3611 /***********************************************************************
3612 * K32QueryWorkingSetEx (KERNEL32.@)
3614 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3616 NTSTATUS status;
3618 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3620 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3622 if (status)
3624 SetLastError( RtlNtStatusToDosError( status ) );
3625 return FALSE;
3627 return TRUE;
3630 /***********************************************************************
3631 * K32GetProcessMemoryInfo (KERNEL32.@)
3633 * Retrieve memory usage information for a given process
3636 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3637 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3639 NTSTATUS status;
3640 VM_COUNTERS vmc;
3642 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3644 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3645 return FALSE;
3648 status = NtQueryInformationProcess(process, ProcessVmCounters,
3649 &vmc, sizeof(vmc), NULL);
3651 if (status)
3653 SetLastError(RtlNtStatusToDosError(status));
3654 return FALSE;
3657 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3658 pmc->PageFaultCount = vmc.PageFaultCount;
3659 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3660 pmc->WorkingSetSize = vmc.WorkingSetSize;
3661 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3662 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3663 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3664 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3665 pmc->PagefileUsage = vmc.PagefileUsage;
3666 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3668 return TRUE;
3671 /***********************************************************************
3672 * ProcessIdToSessionId (KERNEL32.@)
3673 * This function is available on Terminal Server 4SP4 and Windows 2000
3675 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3677 /* According to MSDN, if the calling process is not in a terminal
3678 * services environment, then the sessionid returned is zero.
3680 *sessionid_ptr = 0;
3681 return TRUE;
3685 /***********************************************************************
3686 * RegisterServiceProcess (KERNEL32.@)
3688 * A service process calls this function to ensure that it continues to run
3689 * even after a user logged off.
3691 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3693 /* I don't think that Wine needs to do anything in this function */
3694 return 1; /* success */
3698 /**********************************************************************
3699 * IsWow64Process (KERNEL32.@)
3701 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3703 ULONG pbi;
3704 NTSTATUS status;
3706 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3708 if (status != STATUS_SUCCESS)
3710 SetLastError( RtlNtStatusToDosError( status ) );
3711 return FALSE;
3713 *Wow64Process = (pbi != 0);
3714 return TRUE;
3718 /***********************************************************************
3719 * GetCurrentProcess (KERNEL32.@)
3721 * Get a handle to the current process.
3723 * PARAMS
3724 * None.
3726 * RETURNS
3727 * A handle representing the current process.
3729 #undef GetCurrentProcess
3730 HANDLE WINAPI GetCurrentProcess(void)
3732 return (HANDLE)~(ULONG_PTR)0;
3735 /***********************************************************************
3736 * GetLogicalProcessorInformation (KERNEL32.@)
3738 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3740 NTSTATUS status;
3742 TRACE("(%p,%p)\n", buffer, pBufLen);
3744 if(!pBufLen)
3746 SetLastError(ERROR_INVALID_PARAMETER);
3747 return FALSE;
3750 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
3752 if (status == STATUS_INFO_LENGTH_MISMATCH)
3754 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3755 return FALSE;
3757 if (status != STATUS_SUCCESS)
3759 SetLastError( RtlNtStatusToDosError( status ) );
3760 return FALSE;
3762 return TRUE;
3765 /***********************************************************************
3766 * GetLogicalProcessorInformationEx (KERNEL32.@)
3768 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer, PDWORD pBufLen)
3770 FIXME("(%u,%p,%p): stub\n", relationship, buffer, pBufLen);
3771 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3772 return FALSE;
3775 /***********************************************************************
3776 * CmdBatNotification (KERNEL32.@)
3778 * Notifies the system that a batch file has started or finished.
3780 * PARAMS
3781 * bBatchRunning [I] TRUE if a batch file has started or
3782 * FALSE if a batch file has finished executing.
3784 * RETURNS
3785 * Unknown.
3787 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3789 FIXME("%d\n", bBatchRunning);
3790 return FALSE;
3794 /***********************************************************************
3795 * RegisterApplicationRestart (KERNEL32.@)
3797 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3799 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3801 return S_OK;
3804 /**********************************************************************
3805 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3807 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3809 FIXME("stub\n");
3810 return 0;
3813 /**********************************************************************
3814 * GetSystemDEPPolicy (KERNEL32.@)
3816 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3818 FIXME("stub\n");
3819 return OptIn;
3822 /**********************************************************************
3823 * SetProcessDEPPolicy (KERNEL32.@)
3825 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3827 FIXME("(%d): stub\n", newDEP);
3828 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3829 return FALSE;
3832 /**********************************************************************
3833 * ApplicationRecoveryFinished (KERNEL32.@)
3835 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
3837 FIXME(": stub\n");
3838 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3841 /**********************************************************************
3842 * ApplicationRecoveryInProgress (KERNEL32.@)
3844 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
3846 FIXME(":%p stub\n", canceled);
3847 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3848 return E_FAIL;
3851 /**********************************************************************
3852 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3854 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
3856 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
3857 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3858 return E_FAIL;
3861 /**********************************************************************
3862 * GetNumaHighestNodeNumber (KERNEL32.@)
3864 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
3866 FIXME("(%p): stub\n", highestnode);
3867 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3868 return FALSE;
3871 /**********************************************************************
3872 * GetNumaNodeProcessorMask (KERNEL32.@)
3874 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
3876 FIXME("(%c %p): stub\n", node, mask);
3877 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3878 return FALSE;
3881 /**********************************************************************
3882 * GetNumaAvailableMemoryNode (KERNEL32.@)
3884 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
3886 FIXME("(%c %p): stub\n", node, available_bytes);
3887 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3888 return FALSE;
3891 /**********************************************************************
3892 * GetProcessDEPPolicy (KERNEL32.@)
3894 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
3896 FIXME("(%p %p %p): stub\n", process, flags, permanent);
3897 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3898 return FALSE;
3901 /**********************************************************************
3902 * FlushProcessWriteBuffers (KERNEL32.@)
3904 VOID WINAPI FlushProcessWriteBuffers(void)
3906 static int once = 0;
3908 if (!once++)
3909 FIXME(": stub\n");