hhctrl.ocx: Open a specific topic when requested.
[wine/multimedia.git] / dlls / kernel32 / process.c
blob3c6ae636c5d8629ad883e3afbdf8653d25e13919
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_UNISTD_H
45 # include <unistd.h>
46 #endif
47 #ifdef __APPLE__
48 #include <CoreFoundation/CoreFoundation.h>
49 #include <pthread.h>
50 #endif
52 #include "ntstatus.h"
53 #define WIN32_NO_STATUS
54 #include "winternl.h"
55 #include "kernel_private.h"
56 #include "psapi.h"
57 #include "wine/library.h"
58 #include "wine/server.h"
59 #include "wine/unicode.h"
60 #include "wine/debug.h"
62 WINE_DEFAULT_DEBUG_CHANNEL(process);
63 WINE_DECLARE_DEBUG_CHANNEL(file);
64 WINE_DECLARE_DEBUG_CHANNEL(relay);
66 #ifdef __APPLE__
67 extern char **__wine_get_main_environment(void);
68 #else
69 extern char **__wine_main_environ;
70 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
71 #endif
73 typedef struct
75 LPSTR lpEnvAddress;
76 LPSTR lpCmdLine;
77 LPSTR lpCmdShow;
78 DWORD dwReserved;
79 } LOADPARMS32;
81 static DWORD shutdown_flags = 0;
82 static DWORD shutdown_priority = 0x280;
83 static BOOL is_wow64;
84 static const int is_win64 = (sizeof(void *) > sizeof(int));
86 HMODULE kernel32_handle = 0;
88 const WCHAR *DIR_Windows = NULL;
89 const WCHAR *DIR_System = NULL;
90 const WCHAR *DIR_SysWow64 = NULL;
92 /* Process flags */
93 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
94 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
95 #define PDB32_DOS_PROC 0x0010 /* Dos process */
96 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
97 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
98 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
100 static const WCHAR exeW[] = {'.','e','x','e',0};
101 static const WCHAR comW[] = {'.','c','o','m',0};
102 static const WCHAR batW[] = {'.','b','a','t',0};
103 static const WCHAR cmdW[] = {'.','c','m','d',0};
104 static const WCHAR pifW[] = {'.','p','i','f',0};
105 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
107 static void exec_process( LPCWSTR name );
109 extern void SHELL_LoadRegistry(void);
112 /***********************************************************************
113 * contains_path
115 static inline int contains_path( LPCWSTR name )
117 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
121 /***********************************************************************
122 * is_special_env_var
124 * Check if an environment variable needs to be handled specially when
125 * passed through the Unix environment (i.e. prefixed with "WINE").
127 static inline int is_special_env_var( const char *var )
129 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
130 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
131 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
132 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
133 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
137 /***********************************************************************
138 * is_path_prefix
140 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
142 unsigned int len = strlenW( prefix );
144 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
145 while (filename[len] == '\\') len++;
146 return len;
150 /***************************************************************************
151 * get_builtin_path
153 * Get the path of a builtin module when the native file does not exist.
155 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
156 UINT size, struct binary_info *binary_info )
158 WCHAR *file_part;
159 UINT len;
160 void *redir_disabled = 0;
161 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
163 /* builtin names cannot be empty or contain spaces */
164 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
166 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
167 Wow64RevertWow64FsRedirection( redir_disabled );
169 if (contains_path( libname ))
171 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
172 filename, &file_part ) > size * sizeof(WCHAR))
173 return FALSE; /* too long */
175 if ((len = is_path_prefix( DIR_System, filename )))
177 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
179 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
181 flags = 0;
183 else return FALSE;
185 if (filename + len != file_part) return FALSE;
187 else
189 len = strlenW( DIR_System );
190 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
191 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
192 file_part = filename + len;
193 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
194 strcpyW( file_part, libname );
195 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
197 if (ext && !strchrW( file_part, '.' ))
199 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
200 return FALSE; /* too long */
201 strcatW( file_part, ext );
203 binary_info->type = BINARY_UNIX_LIB;
204 binary_info->flags = flags;
205 binary_info->res_start = NULL;
206 binary_info->res_end = NULL;
207 return TRUE;
211 /***********************************************************************
212 * open_exe_file
214 * Open a specific exe file, taking load order into account.
215 * Returns the file handle or 0 for a builtin exe.
217 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
219 HANDLE handle;
221 TRACE("looking for %s\n", debugstr_w(name) );
223 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
224 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
226 WCHAR buffer[MAX_PATH];
227 /* file doesn't exist, check for builtin */
228 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
229 handle = 0;
231 else MODULE_get_binary_info( handle, binary_info );
233 return handle;
237 /***********************************************************************
238 * find_exe_file
240 * Open an exe file, and return the full name and file handle.
241 * Returns FALSE if file could not be found.
242 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
243 * If file is a builtin exe, returns TRUE and sets handle to 0.
245 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
246 HANDLE *handle, struct binary_info *binary_info )
248 TRACE("looking for %s\n", debugstr_w(name) );
250 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ))
252 if (contains_path( name ) && get_builtin_path( name, exeW, buffer, buflen, binary_info ))
254 *handle = 0;
255 return TRUE;
257 /* no builtin found, try native without extension in case it is a Unix app */
258 if (!SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
261 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
262 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
263 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
265 MODULE_get_binary_info( *handle, binary_info );
266 return TRUE;
268 return FALSE;
272 /***********************************************************************
273 * build_initial_environment
275 * Build the Win32 environment from the Unix environment
277 static BOOL build_initial_environment(void)
279 SIZE_T size = 1;
280 char **e;
281 WCHAR *p, *endptr;
282 void *ptr;
283 char **env = __wine_get_main_environment();
285 /* Compute the total size of the Unix environment */
286 for (e = env; *e; e++)
288 if (is_special_env_var( *e )) continue;
289 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
291 size *= sizeof(WCHAR);
293 /* Now allocate the environment */
294 ptr = NULL;
295 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
296 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
297 return FALSE;
299 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
300 endptr = p + size / sizeof(WCHAR);
302 /* And fill it with the Unix environment */
303 for (e = env; *e; e++)
305 char *str = *e;
307 /* skip Unix special variables and use the Wine variants instead */
308 if (!strncmp( str, "WINE", 4 ))
310 if (is_special_env_var( str + 4 )) str += 4;
311 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
313 else if (is_special_env_var( str )) continue; /* skip it */
315 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
316 p += strlenW(p) + 1;
318 *p = 0;
319 return TRUE;
323 /***********************************************************************
324 * set_registry_variables
326 * Set environment variables by enumerating the values of a key;
327 * helper for set_registry_environment().
328 * Note that Windows happily truncates the value if it's too big.
330 static void set_registry_variables( HANDLE hkey, ULONG type )
332 static const WCHAR pathW[] = {'P','A','T','H'};
333 static const WCHAR sep[] = {';',0};
334 UNICODE_STRING env_name, env_value;
335 NTSTATUS status;
336 DWORD size;
337 int index;
338 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
339 WCHAR tmpbuf[1024];
340 UNICODE_STRING tmp;
341 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
343 tmp.Buffer = tmpbuf;
344 tmp.MaximumLength = sizeof(tmpbuf);
346 for (index = 0; ; index++)
348 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
349 buffer, sizeof(buffer), &size );
350 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
351 break;
352 if (info->Type != type)
353 continue;
354 env_name.Buffer = info->Name;
355 env_name.Length = env_name.MaximumLength = info->NameLength;
356 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
357 env_value.Length = info->DataLength;
358 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
359 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
360 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
361 if (!env_value.Length) continue;
362 if (info->Type == REG_EXPAND_SZ)
364 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
365 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
366 RtlCopyUnicodeString( &env_value, &tmp );
368 /* PATH is magic */
369 if (env_name.Length == sizeof(pathW) &&
370 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
371 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
373 RtlAppendUnicodeToString( &tmp, sep );
374 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
375 RtlCopyUnicodeString( &env_value, &tmp );
377 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
382 /***********************************************************************
383 * set_registry_environment
385 * Set the environment variables specified in the registry.
387 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
388 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
389 * on the order in which the variables are processed. But on Windows it
390 * does not really matter since they only use %SystemDrive% and
391 * %SystemRoot% which are predefined. But Wine defines these in the
392 * registry, so we need two passes.
394 static BOOL set_registry_environment( BOOL volatile_only )
396 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
397 'S','y','s','t','e','m','\\',
398 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
399 'C','o','n','t','r','o','l','\\',
400 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
401 'E','n','v','i','r','o','n','m','e','n','t',0};
402 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
403 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};
405 OBJECT_ATTRIBUTES attr;
406 UNICODE_STRING nameW;
407 HANDLE hkey;
408 BOOL ret = FALSE;
410 attr.Length = sizeof(attr);
411 attr.RootDirectory = 0;
412 attr.ObjectName = &nameW;
413 attr.Attributes = 0;
414 attr.SecurityDescriptor = NULL;
415 attr.SecurityQualityOfService = NULL;
417 /* first the system environment variables */
418 RtlInitUnicodeString( &nameW, env_keyW );
419 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
421 set_registry_variables( hkey, REG_SZ );
422 set_registry_variables( hkey, REG_EXPAND_SZ );
423 NtClose( hkey );
424 ret = TRUE;
427 /* then the ones for the current user */
428 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
429 RtlInitUnicodeString( &nameW, envW );
430 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
432 set_registry_variables( hkey, REG_SZ );
433 set_registry_variables( hkey, REG_EXPAND_SZ );
434 NtClose( hkey );
437 RtlInitUnicodeString( &nameW, volatile_envW );
438 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
440 set_registry_variables( hkey, REG_SZ );
441 set_registry_variables( hkey, REG_EXPAND_SZ );
442 NtClose( hkey );
445 NtClose( attr.RootDirectory );
446 return ret;
450 /***********************************************************************
451 * get_reg_value
453 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
455 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
456 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
457 DWORD len, size = sizeof(buffer);
458 WCHAR *ret = NULL;
459 UNICODE_STRING nameW;
461 RtlInitUnicodeString( &nameW, name );
462 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
463 return NULL;
465 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
466 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
468 if (info->Type == REG_EXPAND_SZ)
470 UNICODE_STRING value, expanded;
472 value.MaximumLength = len * sizeof(WCHAR);
473 value.Buffer = (WCHAR *)info->Data;
474 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
475 value.Length = len * sizeof(WCHAR);
476 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
477 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
478 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
479 else RtlFreeUnicodeString( &expanded );
481 else if (info->Type == REG_SZ)
483 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
485 memcpy( ret, info->Data, len * sizeof(WCHAR) );
486 ret[len] = 0;
489 return ret;
493 /***********************************************************************
494 * set_additional_environment
496 * Set some additional environment variables not specified in the registry.
498 static void set_additional_environment(void)
500 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
501 'S','o','f','t','w','a','r','e','\\',
502 'M','i','c','r','o','s','o','f','t','\\',
503 'W','i','n','d','o','w','s',' ','N','T','\\',
504 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
505 'P','r','o','f','i','l','e','L','i','s','t',0};
506 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
507 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
508 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
509 OBJECT_ATTRIBUTES attr;
510 UNICODE_STRING nameW;
511 WCHAR *profile_dir = NULL, *all_users_dir = NULL;
512 HANDLE hkey;
513 DWORD len;
515 /* set the ALLUSERSPROFILE variables */
517 attr.Length = sizeof(attr);
518 attr.RootDirectory = 0;
519 attr.ObjectName = &nameW;
520 attr.Attributes = 0;
521 attr.SecurityDescriptor = NULL;
522 attr.SecurityQualityOfService = NULL;
523 RtlInitUnicodeString( &nameW, profile_keyW );
524 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
526 profile_dir = get_reg_value( hkey, profiles_valueW );
527 all_users_dir = get_reg_value( hkey, all_users_valueW );
528 NtClose( hkey );
531 if (profile_dir && all_users_dir)
533 WCHAR *value, *p;
535 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
536 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
537 strcpyW( value, profile_dir );
538 p = value + strlenW(value);
539 if (p > value && p[-1] != '\\') *p++ = '\\';
540 strcpyW( p, all_users_dir );
541 SetEnvironmentVariableW( allusersW, value );
542 HeapFree( GetProcessHeap(), 0, value );
545 HeapFree( GetProcessHeap(), 0, all_users_dir );
546 HeapFree( GetProcessHeap(), 0, profile_dir );
549 /***********************************************************************
550 * set_wow64_environment
552 * Set the environment variables that change across 32/64/Wow64.
554 static void set_wow64_environment(void)
556 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};
557 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};
558 static const WCHAR x86W[] = {'x','8','6',0};
559 static const WCHAR versionW[] = {'M','a','c','h','i','n','e','\\',
560 'S','o','f','t','w','a','r','e','\\',
561 'M','i','c','r','o','s','o','f','t','\\',
562 'W','i','n','d','o','w','s','\\',
563 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
564 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
565 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
566 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
567 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
568 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
569 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
570 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
571 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
573 OBJECT_ATTRIBUTES attr;
574 UNICODE_STRING nameW;
575 WCHAR arch[64];
576 WCHAR *value;
577 HANDLE hkey;
579 /* set the PROCESSOR_ARCHITECTURE variable */
581 if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
583 if (is_win64)
585 SetEnvironmentVariableW( archW, arch );
586 SetEnvironmentVariableW( arch6432W, NULL );
589 else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
591 if (is_wow64)
593 SetEnvironmentVariableW( arch6432W, arch );
594 SetEnvironmentVariableW( archW, x86W );
598 attr.Length = sizeof(attr);
599 attr.RootDirectory = 0;
600 attr.ObjectName = &nameW;
601 attr.Attributes = 0;
602 attr.SecurityDescriptor = NULL;
603 attr.SecurityQualityOfService = NULL;
604 RtlInitUnicodeString( &nameW, versionW );
605 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
607 /* set the ProgramFiles variables */
609 if ((value = get_reg_value( hkey, progdirW )))
611 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
612 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
613 HeapFree( GetProcessHeap(), 0, value );
615 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
617 SetEnvironmentVariableW( progfilesW, value );
618 HeapFree( GetProcessHeap(), 0, value );
621 /* set the CommonProgramFiles variables */
623 if ((value = get_reg_value( hkey, commondirW )))
625 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
626 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
627 HeapFree( GetProcessHeap(), 0, value );
629 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
631 SetEnvironmentVariableW( commonfilesW, value );
632 HeapFree( GetProcessHeap(), 0, value );
635 NtClose( hkey );
638 /***********************************************************************
639 * set_library_wargv
641 * Set the Wine library Unicode argv global variables.
643 static void set_library_wargv( char **argv )
645 int argc;
646 char *q;
647 WCHAR *p;
648 WCHAR **wargv;
649 DWORD total = 0;
651 for (argc = 0; argv[argc]; argc++)
652 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
654 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
655 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
656 p = (WCHAR *)(wargv + argc + 1);
657 for (argc = 0; argv[argc]; argc++)
659 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
660 wargv[argc] = p;
661 p += reslen;
662 total -= reslen;
664 wargv[argc] = NULL;
666 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
668 for (argc = 0; wargv[argc]; argc++)
669 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
671 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
672 q = (char *)(argv + argc + 1);
673 for (argc = 0; wargv[argc]; argc++)
675 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
676 argv[argc] = q;
677 q += reslen;
678 total -= reslen;
680 argv[argc] = NULL;
682 __wine_main_argc = argc;
683 __wine_main_argv = argv;
684 __wine_main_wargv = wargv;
688 /***********************************************************************
689 * update_library_argv0
691 * Update the argv[0] global variable with the binary we have found.
693 static void update_library_argv0( const WCHAR *argv0 )
695 DWORD len = strlenW( argv0 );
697 if (len > strlenW( __wine_main_wargv[0] ))
699 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
701 strcpyW( __wine_main_wargv[0], argv0 );
703 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
704 if (len > strlen( __wine_main_argv[0] ) + 1)
706 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
708 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
712 /***********************************************************************
713 * build_command_line
715 * Build the command line of a process from the argv array.
717 * Note that it does NOT necessarily include the file name.
718 * Sometimes we don't even have any command line options at all.
720 * We must quote and escape characters so that the argv array can be rebuilt
721 * from the command line:
722 * - spaces and tabs must be quoted
723 * 'a b' -> '"a b"'
724 * - quotes must be escaped
725 * '"' -> '\"'
726 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
727 * resulting in an odd number of '\' followed by a '"'
728 * '\"' -> '\\\"'
729 * '\\"' -> '\\\\\"'
730 * - '\'s that are not followed by a '"' can be left as is
731 * 'a\b' == 'a\b'
732 * 'a\\b' == 'a\\b'
734 static BOOL build_command_line( WCHAR **argv )
736 int len;
737 WCHAR **arg;
738 LPWSTR p;
739 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
741 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
743 len = 0;
744 for (arg = argv; *arg; arg++)
746 int has_space,bcount;
747 WCHAR* a;
749 has_space=0;
750 bcount=0;
751 a=*arg;
752 if( !*a ) has_space=1;
753 while (*a!='\0') {
754 if (*a=='\\') {
755 bcount++;
756 } else {
757 if (*a==' ' || *a=='\t') {
758 has_space=1;
759 } else if (*a=='"') {
760 /* doubling of '\' preceding a '"',
761 * plus escaping of said '"'
763 len+=2*bcount+1;
765 bcount=0;
767 a++;
769 len+=(a-*arg)+1 /* for the separating space */;
770 if (has_space)
771 len+=2; /* for the quotes */
774 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
775 return FALSE;
777 p = rupp->CommandLine.Buffer;
778 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
779 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
780 for (arg = argv; *arg; arg++)
782 int has_space,has_quote;
783 WCHAR* a;
785 /* Check for quotes and spaces in this argument */
786 has_space=has_quote=0;
787 a=*arg;
788 if( !*a ) has_space=1;
789 while (*a!='\0') {
790 if (*a==' ' || *a=='\t') {
791 has_space=1;
792 if (has_quote)
793 break;
794 } else if (*a=='"') {
795 has_quote=1;
796 if (has_space)
797 break;
799 a++;
802 /* Now transfer it to the command line */
803 if (has_space)
804 *p++='"';
805 if (has_quote) {
806 int bcount;
807 WCHAR* a;
809 bcount=0;
810 a=*arg;
811 while (*a!='\0') {
812 if (*a=='\\') {
813 *p++=*a;
814 bcount++;
815 } else {
816 if (*a=='"') {
817 int i;
819 /* Double all the '\\' preceding this '"', plus one */
820 for (i=0;i<=bcount;i++)
821 *p++='\\';
822 *p++='"';
823 } else {
824 *p++=*a;
826 bcount=0;
828 a++;
830 } else {
831 WCHAR* x = *arg;
832 while ((*p=*x++)) p++;
834 if (has_space)
835 *p++='"';
836 *p++=' ';
838 if (p > rupp->CommandLine.Buffer)
839 p--; /* remove last space */
840 *p = '\0';
842 return TRUE;
846 /***********************************************************************
847 * init_current_directory
849 * Initialize the current directory from the Unix cwd or the parent info.
851 static void init_current_directory( CURDIR *cur_dir )
853 UNICODE_STRING dir_str;
854 const char *pwd;
855 char *cwd;
856 int size;
858 /* if we received a cur dir from the parent, try this first */
860 if (cur_dir->DosPath.Length)
862 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
865 /* now try to get it from the Unix cwd */
867 for (size = 256; ; size *= 2)
869 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
870 if (getcwd( cwd, size )) break;
871 HeapFree( GetProcessHeap(), 0, cwd );
872 if (errno == ERANGE) continue;
873 cwd = NULL;
874 break;
877 /* try to use PWD if it is valid, so that we don't resolve symlinks */
879 pwd = getenv( "PWD" );
880 if (cwd)
882 struct stat st1, st2;
884 if (!pwd || stat( pwd, &st1 ) == -1 ||
885 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
886 pwd = cwd;
889 if (pwd)
891 ANSI_STRING unix_name;
892 UNICODE_STRING nt_name;
893 RtlInitAnsiString( &unix_name, pwd );
894 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
896 UNICODE_STRING dos_path;
897 /* skip the \??\ prefix, nt_name is 0 terminated */
898 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
899 RtlSetCurrentDirectory_U( &dos_path );
900 RtlFreeUnicodeString( &nt_name );
904 if (!cur_dir->DosPath.Length) /* still not initialized */
906 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
907 "starting in the Windows directory.\n", cwd ? cwd : "" );
908 RtlInitUnicodeString( &dir_str, DIR_Windows );
909 RtlSetCurrentDirectory_U( &dir_str );
911 HeapFree( GetProcessHeap(), 0, cwd );
913 done:
914 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
915 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
919 /***********************************************************************
920 * init_windows_dirs
922 * Initialize the windows and system directories from the environment.
924 static void init_windows_dirs(void)
926 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
928 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
929 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
930 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
931 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
932 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
934 DWORD len;
935 WCHAR *buffer;
937 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
939 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
940 GetEnvironmentVariableW( windirW, buffer, len );
941 DIR_Windows = buffer;
943 else DIR_Windows = default_windirW;
945 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
947 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
948 GetEnvironmentVariableW( winsysdirW, buffer, len );
949 DIR_System = buffer;
951 else
953 len = strlenW( DIR_Windows );
954 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
955 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
956 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
957 DIR_System = buffer;
960 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
961 ERR( "directory %s could not be created, error %u\n",
962 debugstr_w(DIR_Windows), GetLastError() );
963 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
964 ERR( "directory %s could not be created, error %u\n",
965 debugstr_w(DIR_System), GetLastError() );
967 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
969 len = strlenW( DIR_Windows );
970 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
971 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
972 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
973 DIR_SysWow64 = buffer;
974 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
975 ERR( "directory %s could not be created, error %u\n",
976 debugstr_w(DIR_SysWow64), GetLastError() );
979 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
980 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
982 /* set the directories in ntdll too */
983 __wine_init_windows_dir( DIR_Windows, DIR_System );
987 /***********************************************************************
988 * start_wineboot
990 * Start the wineboot process if necessary. Return the handles to wait on.
992 static void start_wineboot( HANDLE handles[2] )
994 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
996 handles[1] = 0;
997 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
999 ERR( "failed to create wineboot event, expect trouble\n" );
1000 return;
1002 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
1004 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1005 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1006 STARTUPINFOW si;
1007 PROCESS_INFORMATION pi;
1008 void *redir;
1009 WCHAR app[MAX_PATH];
1010 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1012 memset( &si, 0, sizeof(si) );
1013 si.cb = sizeof(si);
1014 si.dwFlags = STARTF_USESTDHANDLES;
1015 si.hStdInput = 0;
1016 si.hStdOutput = 0;
1017 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1019 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1020 lstrcatW( app, wineboot );
1022 Wow64DisableWow64FsRedirection( &redir );
1023 strcpyW( cmdline, app );
1024 strcatW( cmdline, args );
1025 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1027 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1028 CloseHandle( pi.hThread );
1029 handles[1] = pi.hProcess;
1031 else
1033 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1034 CloseHandle( handles[0] );
1035 handles[0] = 0;
1037 Wow64RevertWow64FsRedirection( redir );
1042 #ifdef __i386__
1043 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1044 __ASM_GLOBAL_FUNC( call_process_entry,
1045 "pushl %ebp\n\t"
1046 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1047 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1048 "movl %esp,%ebp\n\t"
1049 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1050 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1051 "pushl 8(%ebp)\n\t"
1052 "call *12(%ebp)\n\t"
1053 "leave\n\t"
1054 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1055 __ASM_CFI(".cfi_same_value %ebp\n\t")
1056 "ret" )
1057 #else
1058 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1060 return entry( peb );
1062 #endif
1064 /***********************************************************************
1065 * start_process
1067 * Startup routine of a new process. Runs on the new process stack.
1069 static DWORD WINAPI start_process( PEB *peb )
1071 IMAGE_NT_HEADERS *nt;
1072 LPTHREAD_START_ROUTINE entry;
1074 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1075 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1076 nt->OptionalHeader.AddressOfEntryPoint);
1078 if (!nt->OptionalHeader.AddressOfEntryPoint)
1080 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1081 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1082 ExitThread( 1 );
1085 if (TRACE_ON(relay))
1086 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1087 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1089 SetLastError( 0 ); /* clear error code */
1090 if (peb->BeingDebugged) DbgBreakPoint();
1091 return call_process_entry( peb, entry );
1095 /***********************************************************************
1096 * set_process_name
1098 * Change the process name in the ps output.
1100 static void set_process_name( int argc, char *argv[] )
1102 #ifdef HAVE_SETPROCTITLE
1103 setproctitle("-%s", argv[1]);
1104 #endif
1106 #ifdef HAVE_PRCTL
1107 int i, offset;
1108 char *p, *prctl_name = argv[1];
1109 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1111 #ifndef PR_SET_NAME
1112 # define PR_SET_NAME 15
1113 #endif
1115 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1116 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1118 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1120 offset = argv[1] - argv[0];
1121 memmove( argv[1] - offset, argv[1], end - argv[1] );
1122 memset( end - offset, 0, offset );
1123 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1124 argv[i-1] = NULL;
1126 else
1127 #endif /* HAVE_PRCTL */
1129 /* remove argv[0] */
1130 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1135 /***********************************************************************
1136 * __wine_kernel_init
1138 * Wine initialisation: load and start the main exe file.
1140 void CDECL __wine_kernel_init(void)
1142 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1143 static const WCHAR dotW[] = {'.',0};
1145 WCHAR *p, main_exe_name[MAX_PATH+1];
1146 PEB *peb = NtCurrentTeb()->Peb;
1147 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1148 HANDLE boot_events[2];
1149 BOOL got_environment = TRUE;
1151 /* Initialize everything */
1153 setbuf(stdout,NULL);
1154 setbuf(stderr,NULL);
1155 kernel32_handle = GetModuleHandleW(kernel32W);
1156 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1158 LOCALE_Init();
1160 if (!params->Environment)
1162 /* Copy the parent environment */
1163 if (!build_initial_environment()) exit(1);
1165 /* convert old configuration to new format */
1166 convert_old_config();
1168 got_environment = set_registry_environment( FALSE );
1169 set_additional_environment();
1172 init_windows_dirs();
1173 init_current_directory( &params->CurrentDirectory );
1175 set_process_name( __wine_main_argc, __wine_main_argv );
1176 set_library_wargv( __wine_main_argv );
1177 boot_events[0] = boot_events[1] = 0;
1179 if (peb->ProcessParameters->ImagePathName.Buffer)
1181 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1183 else
1185 struct binary_info binary_info;
1187 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1188 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1190 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1191 ExitProcess( GetLastError() );
1193 update_library_argv0( main_exe_name );
1194 if (!build_command_line( __wine_main_wargv )) goto error;
1195 start_wineboot( boot_events );
1198 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1199 p = strrchrW( main_exe_name, '.' );
1200 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1202 TRACE( "starting process name=%s argv[0]=%s\n",
1203 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1205 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1206 MODULE_get_dll_load_path(main_exe_name) );
1208 if (boot_events[0])
1210 DWORD timeout = 2 * 60 * 1000, count = 1;
1212 if (boot_events[1]) count++;
1213 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1214 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1215 ERR( "boot event wait timed out\n" );
1216 CloseHandle( boot_events[0] );
1217 if (boot_events[1]) CloseHandle( boot_events[1] );
1218 /* reload environment now that wineboot has run */
1219 set_registry_environment( got_environment );
1220 set_additional_environment();
1222 set_wow64_environment();
1224 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1226 DWORD_PTR args[1];
1227 WCHAR msgW[1024];
1228 char msg[1024];
1229 DWORD error = GetLastError();
1231 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1232 if (error == ERROR_BAD_EXE_FORMAT ||
1233 error == ERROR_INVALID_ADDRESS ||
1234 error == ERROR_NOT_ENOUGH_MEMORY)
1236 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1237 /* if we get back here, it failed */
1239 else if (error == ERROR_MOD_NOT_FOUND)
1241 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1242 else p = main_exe_name;
1243 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1245 /* args 1 and 2 are --app-name full_path */
1246 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1247 debugstr_w(__wine_main_wargv[3]) );
1248 ExitProcess( ERROR_BAD_EXE_FORMAT );
1250 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1251 ExitProcess( ERROR_FILE_NOT_FOUND );
1253 args[0] = (DWORD_PTR)main_exe_name;
1254 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1255 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1256 WideCharToMultiByte( CP_ACP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1257 MESSAGE( "wine: %s", msg );
1258 ExitProcess( error );
1261 LdrInitializeThunk( start_process, 0, 0, 0 );
1263 error:
1264 ExitProcess( GetLastError() );
1268 /***********************************************************************
1269 * build_argv
1271 * Build an argv array from a command-line.
1272 * 'reserved' is the number of args to reserve before the first one.
1274 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1276 int argc;
1277 char** argv;
1278 char *arg,*s,*d,*cmdline;
1279 int in_quotes,bcount,len;
1281 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1282 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1283 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1285 argc=reserved+1;
1286 bcount=0;
1287 in_quotes=0;
1288 s=cmdline;
1289 while (1) {
1290 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1291 /* space */
1292 argc++;
1293 /* skip the remaining spaces */
1294 while (*s==' ' || *s=='\t') {
1295 s++;
1297 if (*s=='\0')
1298 break;
1299 bcount=0;
1300 continue;
1301 } else if (*s=='\\') {
1302 /* '\', count them */
1303 bcount++;
1304 } else if ((*s=='"') && ((bcount & 1)==0)) {
1305 /* unescaped '"' */
1306 in_quotes=!in_quotes;
1307 bcount=0;
1308 } else {
1309 /* a regular character */
1310 bcount=0;
1312 s++;
1314 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1316 HeapFree( GetProcessHeap(), 0, cmdline );
1317 return NULL;
1320 arg = d = s = (char *)(argv + argc);
1321 memcpy( d, cmdline, len );
1322 bcount=0;
1323 in_quotes=0;
1324 argc=reserved;
1325 while (*s) {
1326 if ((*s==' ' || *s=='\t') && !in_quotes) {
1327 /* Close the argument and copy it */
1328 *d=0;
1329 argv[argc++]=arg;
1331 /* skip the remaining spaces */
1332 do {
1333 s++;
1334 } while (*s==' ' || *s=='\t');
1336 /* Start with a new argument */
1337 arg=d=s;
1338 bcount=0;
1339 } else if (*s=='\\') {
1340 /* '\\' */
1341 *d++=*s++;
1342 bcount++;
1343 } else if (*s=='"') {
1344 /* '"' */
1345 if ((bcount & 1)==0) {
1346 /* Preceded by an even number of '\', this is half that
1347 * number of '\', plus a '"' which we discard.
1349 d-=bcount/2;
1350 s++;
1351 in_quotes=!in_quotes;
1352 } else {
1353 /* Preceded by an odd number of '\', this is half that
1354 * number of '\' followed by a '"'
1356 d=d-bcount/2-1;
1357 *d++='"';
1358 s++;
1360 bcount=0;
1361 } else {
1362 /* a regular character */
1363 *d++=*s++;
1364 bcount=0;
1367 if (*arg) {
1368 *d='\0';
1369 argv[argc++]=arg;
1371 argv[argc]=NULL;
1373 HeapFree( GetProcessHeap(), 0, cmdline );
1374 return argv;
1378 /***********************************************************************
1379 * build_envp
1381 * Build the environment of a new child process.
1383 static char **build_envp( const WCHAR *envW )
1385 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1387 const WCHAR *end;
1388 char **envp;
1389 char *env, *p;
1390 int count = 1, length;
1391 unsigned int i;
1393 for (end = envW; *end; count++) end += strlenW(end) + 1;
1394 end++;
1395 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1396 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1397 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1399 for (p = env; *p; p += strlen(p) + 1)
1400 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1402 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1404 if (!(p = getenv(unix_vars[i]))) continue;
1405 length += strlen(unix_vars[i]) + strlen(p) + 2;
1406 count++;
1409 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1411 char **envptr = envp;
1412 char *dst = (char *)(envp + count);
1414 /* some variables must not be modified, so we get them directly from the unix env */
1415 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1417 if (!(p = getenv(unix_vars[i]))) continue;
1418 *envptr++ = strcpy( dst, unix_vars[i] );
1419 strcat( dst, "=" );
1420 strcat( dst, p );
1421 dst += strlen(dst) + 1;
1424 /* now put the Windows environment strings */
1425 for (p = env; *p; p += strlen(p) + 1)
1427 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1428 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1429 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1430 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1431 if (is_special_env_var( p )) /* prefix it with "WINE" */
1433 *envptr++ = strcpy( dst, "WINE" );
1434 strcat( dst, p );
1436 else
1438 *envptr++ = strcpy( dst, p );
1440 dst += strlen(dst) + 1;
1442 *envptr = 0;
1444 HeapFree( GetProcessHeap(), 0, env );
1445 return envp;
1449 /***********************************************************************
1450 * fork_and_exec
1452 * Fork and exec a new Unix binary, checking for errors.
1454 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1455 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1457 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1458 int pid, err;
1459 char **argv, **envp;
1461 if (!env) env = GetEnvironmentStringsW();
1463 #ifdef HAVE_PIPE2
1464 if (pipe2( fd, O_CLOEXEC ) == -1)
1465 #endif
1467 if (pipe(fd) == -1)
1469 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1470 return -1;
1472 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1473 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1476 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1478 HANDLE hstdin, hstdout, hstderr;
1480 if (startup->dwFlags & STARTF_USESTDHANDLES)
1482 hstdin = startup->hStdInput;
1483 hstdout = startup->hStdOutput;
1484 hstderr = startup->hStdError;
1486 else
1488 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1489 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1490 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1493 if (is_console_handle( hstdin ))
1494 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1495 if (is_console_handle( hstdout ))
1496 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1497 if (is_console_handle( hstderr ))
1498 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1499 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1500 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1501 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1504 argv = build_argv( cmdline, 0 );
1505 envp = build_envp( env );
1507 if (!(pid = fork())) /* child */
1509 close( fd[0] );
1511 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1513 int pid;
1514 if (!(pid = fork()))
1516 int fd = open( "/dev/null", O_RDWR );
1517 setsid();
1518 /* close stdin and stdout */
1519 if (fd != -1)
1521 dup2( fd, 0 );
1522 dup2( fd, 1 );
1523 close( fd );
1526 else if (pid != -1) _exit(0); /* parent */
1528 else
1530 if (stdin_fd != -1)
1532 dup2( stdin_fd, 0 );
1533 close( stdin_fd );
1535 if (stdout_fd != -1)
1537 dup2( stdout_fd, 1 );
1538 close( stdout_fd );
1540 if (stderr_fd != -1)
1542 dup2( stderr_fd, 2 );
1543 close( stderr_fd );
1547 /* Reset signals that we previously set to SIG_IGN */
1548 signal( SIGPIPE, SIG_DFL );
1549 signal( SIGCHLD, SIG_DFL );
1551 if (newdir) chdir(newdir);
1553 if (argv && envp) execve( filename, argv, envp );
1554 err = errno;
1555 write( fd[1], &err, sizeof(err) );
1556 _exit(1);
1558 HeapFree( GetProcessHeap(), 0, argv );
1559 HeapFree( GetProcessHeap(), 0, envp );
1560 if (stdin_fd != -1) close( stdin_fd );
1561 if (stdout_fd != -1) close( stdout_fd );
1562 if (stderr_fd != -1) close( stderr_fd );
1563 close( fd[1] );
1564 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1566 errno = err;
1567 pid = -1;
1569 if (pid == -1) FILE_SetDosError();
1570 close( fd[0] );
1571 return pid;
1575 static inline DWORD append_string( void **ptr, const WCHAR *str )
1577 DWORD len = strlenW( str );
1578 memcpy( *ptr, str, len * sizeof(WCHAR) );
1579 *ptr = (WCHAR *)*ptr + len;
1580 return len * sizeof(WCHAR);
1583 /***********************************************************************
1584 * create_startup_info
1586 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1587 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1588 const STARTUPINFOW *startup, DWORD *info_size )
1590 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1591 const WCHAR *title;
1592 startup_info_t *info;
1593 DWORD size;
1594 void *ptr;
1595 UNICODE_STRING newdir;
1596 WCHAR imagepath[MAX_PATH];
1597 HANDLE hstdin, hstdout, hstderr;
1599 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1600 lstrcpynW( imagepath, filename, MAX_PATH );
1601 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1602 lstrcpynW( imagepath, filename, MAX_PATH );
1604 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1606 newdir.Buffer = NULL;
1607 if (cur_dir)
1609 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1610 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1611 else
1612 cur_dir = NULL;
1614 if (!cur_dir)
1616 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1617 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1618 else
1619 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1621 title = startup->lpTitle ? startup->lpTitle : imagepath;
1623 size = sizeof(*info);
1624 size += strlenW( cur_dir ) * sizeof(WCHAR);
1625 size += cur_params->DllPath.Length;
1626 size += strlenW( imagepath ) * sizeof(WCHAR);
1627 size += strlenW( cmdline ) * sizeof(WCHAR);
1628 size += strlenW( title ) * sizeof(WCHAR);
1629 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1630 /* FIXME: shellinfo */
1631 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1632 size = (size + 1) & ~1;
1633 *info_size = size;
1635 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1637 info->console_flags = cur_params->ConsoleFlags;
1638 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1639 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1641 if (startup->dwFlags & STARTF_USESTDHANDLES)
1643 hstdin = startup->hStdInput;
1644 hstdout = startup->hStdOutput;
1645 hstderr = startup->hStdError;
1647 else
1649 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1650 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1651 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1653 info->hstdin = wine_server_obj_handle( hstdin );
1654 info->hstdout = wine_server_obj_handle( hstdout );
1655 info->hstderr = wine_server_obj_handle( hstderr );
1656 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1658 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1659 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1660 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1661 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1663 else
1665 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1666 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1667 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1670 info->x = startup->dwX;
1671 info->y = startup->dwY;
1672 info->xsize = startup->dwXSize;
1673 info->ysize = startup->dwYSize;
1674 info->xchars = startup->dwXCountChars;
1675 info->ychars = startup->dwYCountChars;
1676 info->attribute = startup->dwFillAttribute;
1677 info->flags = startup->dwFlags;
1678 info->show = startup->wShowWindow;
1680 ptr = info + 1;
1681 info->curdir_len = append_string( &ptr, cur_dir );
1682 info->dllpath_len = cur_params->DllPath.Length;
1683 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1684 ptr = (char *)ptr + cur_params->DllPath.Length;
1685 info->imagepath_len = append_string( &ptr, imagepath );
1686 info->cmdline_len = append_string( &ptr, cmdline );
1687 info->title_len = append_string( &ptr, title );
1688 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1689 if (startup->lpReserved2 && startup->cbReserved2)
1691 info->runtime_len = startup->cbReserved2;
1692 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1695 done:
1696 RtlFreeUnicodeString( &newdir );
1697 return info;
1700 /***********************************************************************
1701 * get_alternate_loader
1703 * Get the name of the alternate (32 or 64 bit) Wine loader.
1705 static const char *get_alternate_loader( char **ret_env )
1707 char *env;
1708 const char *loader = NULL;
1709 const char *loader_env = getenv( "WINELOADER" );
1711 *ret_env = NULL;
1713 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1715 if (loader_env)
1717 int len = strlen( loader_env );
1718 if (!is_win64)
1720 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1721 strcpy( env, "WINELOADER=" );
1722 strcat( env, loader_env );
1723 strcat( env, "64" );
1725 else
1727 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1728 strcpy( env, "WINELOADER=" );
1729 strcat( env, loader_env );
1730 len += sizeof("WINELOADER=") - 1;
1731 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1733 if (!loader)
1735 if ((loader = strrchr( env, '/' ))) loader++;
1736 else loader = env;
1738 *ret_env = env;
1740 if (!loader) loader = is_win64 ? "wine" : "wine64";
1741 return loader;
1744 #ifdef __APPLE__
1745 /***********************************************************************
1746 * terminate_main_thread
1748 * On some versions of Mac OS X, the execve system call fails with
1749 * ENOTSUP if the process has multiple threads. Wine is always multi-
1750 * threaded on Mac OS X because it specifically reserves the main thread
1751 * for use by the system frameworks (see apple_main_thread() in
1752 * libs/wine/loader.c). So, when we need to exec without first forking,
1753 * we need to terminate the main thread first. We do this by installing
1754 * a custom run loop source onto the main run loop and signaling it.
1755 * The source's "perform" callback is pthread_exit and it will be
1756 * executed on the main thread, terminating it.
1758 * Returns TRUE if there's still hope the main thread has terminated or
1759 * will soon. Return FALSE if we've given up.
1761 static BOOL terminate_main_thread(void)
1763 static int delayms;
1765 if (!delayms)
1767 CFRunLoopSourceContext source_context = { 0 };
1768 CFRunLoopSourceRef source;
1770 source_context.perform = pthread_exit;
1771 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1772 return FALSE;
1774 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1775 CFRunLoopSourceSignal( source );
1776 CFRunLoopWakeUp( CFRunLoopGetMain() );
1777 CFRelease( source );
1779 delayms = 20;
1782 if (delayms > 1000)
1783 return FALSE;
1785 usleep(delayms * 1000);
1786 delayms *= 2;
1788 return TRUE;
1790 #endif
1792 /***********************************************************************
1793 * exec_loader
1795 static pid_t exec_loader( LPCWSTR cmd_line, unsigned int flags, int socketfd,
1796 int stdin_fd, int stdout_fd, const char *unixdir, char *winedebug,
1797 const struct binary_info *binary_info, int exec_only )
1799 pid_t pid;
1800 char *wineloader = NULL;
1801 const char *loader = NULL;
1802 char **argv;
1804 argv = build_argv( cmd_line, 1 );
1806 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1807 loader = get_alternate_loader( &wineloader );
1809 if (exec_only || !(pid = fork())) /* child */
1811 char preloader_reserve[64], socket_env[64];
1813 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1815 if (!(pid = fork()))
1817 int fd = open( "/dev/null", O_RDWR );
1818 setsid();
1819 /* close stdin and stdout */
1820 if (fd != -1)
1822 dup2( fd, 0 );
1823 dup2( fd, 1 );
1824 close( fd );
1827 else if (pid != -1) _exit(0); /* parent */
1829 else
1831 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1832 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1835 if (stdin_fd != -1) close( stdin_fd );
1836 if (stdout_fd != -1) close( stdout_fd );
1838 /* Reset signals that we previously set to SIG_IGN */
1839 signal( SIGPIPE, SIG_DFL );
1840 signal( SIGCHLD, SIG_DFL );
1842 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
1843 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1844 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1846 putenv( preloader_reserve );
1847 putenv( socket_env );
1848 if (winedebug) putenv( winedebug );
1849 if (wineloader) putenv( wineloader );
1850 if (unixdir) chdir(unixdir);
1852 if (argv)
1856 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1858 #ifdef __APPLE__
1859 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1860 #else
1861 while (0);
1862 #endif
1864 _exit(1);
1866 HeapFree( GetProcessHeap(), 0, wineloader );
1867 HeapFree( GetProcessHeap(), 0, argv );
1868 return pid;
1871 /***********************************************************************
1872 * create_process
1874 * Create a new process. If hFile is a valid handle we have an exe
1875 * file, otherwise it is a Winelib app.
1877 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1878 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1879 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1880 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1881 const struct binary_info *binary_info, int exec_only )
1883 BOOL ret, success = FALSE;
1884 HANDLE process_info;
1885 WCHAR *env_end;
1886 char *winedebug = NULL;
1887 startup_info_t *startup_info;
1888 DWORD startup_info_size;
1889 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1890 pid_t pid;
1891 int err;
1893 if (!is_win64 && !is_wow64 && (binary_info->flags & BINARY_FLAG_64BIT))
1895 ERR( "starting 64-bit process %s not supported in 32-bit wineprefix\n", debugstr_w(filename) );
1896 SetLastError( ERROR_BAD_EXE_FORMAT );
1897 return FALSE;
1900 /* create the socket for the new process */
1902 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1904 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1905 return FALSE;
1908 if (exec_only) /* things are much simpler in this case */
1910 wine_server_send_fd( socketfd[1] );
1911 close( socketfd[1] );
1912 SERVER_START_REQ( new_process )
1914 req->create_flags = flags;
1915 req->socket_fd = socketfd[1];
1916 req->exe_file = wine_server_obj_handle( hFile );
1917 ret = !wine_server_call_err( req );
1919 SERVER_END_REQ;
1921 if (ret) exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
1922 winedebug, binary_info, TRUE );
1924 close( socketfd[0] );
1925 return FALSE;
1928 RtlAcquirePebLock();
1930 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1931 &startup_info_size )))
1933 RtlReleasePebLock();
1934 close( socketfd[0] );
1935 close( socketfd[1] );
1936 return FALSE;
1938 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
1939 env_end = env;
1940 while (*env_end)
1942 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1943 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1945 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1946 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1947 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1949 env_end += strlenW(env_end) + 1;
1951 env_end++;
1953 wine_server_send_fd( socketfd[1] );
1954 close( socketfd[1] );
1956 /* create the process on the server side */
1958 SERVER_START_REQ( new_process )
1960 req->inherit_all = inherit;
1961 req->create_flags = flags;
1962 req->socket_fd = socketfd[1];
1963 req->exe_file = wine_server_obj_handle( hFile );
1964 req->process_access = PROCESS_ALL_ACCESS;
1965 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1966 req->thread_access = THREAD_ALL_ACCESS;
1967 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1968 req->info_size = startup_info_size;
1970 wine_server_add_data( req, startup_info, startup_info_size );
1971 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
1972 if ((ret = !wine_server_call_err( req )))
1974 info->dwProcessId = (DWORD)reply->pid;
1975 info->dwThreadId = (DWORD)reply->tid;
1976 info->hProcess = wine_server_ptr_handle( reply->phandle );
1977 info->hThread = wine_server_ptr_handle( reply->thandle );
1979 process_info = wine_server_ptr_handle( reply->info );
1981 SERVER_END_REQ;
1983 RtlReleasePebLock();
1984 if (!ret)
1986 close( socketfd[0] );
1987 HeapFree( GetProcessHeap(), 0, startup_info );
1988 HeapFree( GetProcessHeap(), 0, winedebug );
1989 return FALSE;
1992 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1994 if (startup_info->hstdin)
1995 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
1996 FILE_READ_DATA, &stdin_fd, NULL );
1997 if (startup_info->hstdout)
1998 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
1999 FILE_WRITE_DATA, &stdout_fd, NULL );
2001 HeapFree( GetProcessHeap(), 0, startup_info );
2003 /* create the child process */
2005 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2006 winedebug, binary_info, FALSE );
2008 if (stdin_fd != -1) close( stdin_fd );
2009 if (stdout_fd != -1) close( stdout_fd );
2010 close( socketfd[0] );
2011 HeapFree( GetProcessHeap(), 0, winedebug );
2012 if (pid == -1)
2014 FILE_SetDosError();
2015 goto error;
2018 /* wait for the new process info to be ready */
2020 WaitForSingleObject( process_info, INFINITE );
2021 SERVER_START_REQ( get_new_process_info )
2023 req->info = wine_server_obj_handle( process_info );
2024 wine_server_call( req );
2025 success = reply->success;
2026 err = reply->exit_code;
2028 SERVER_END_REQ;
2030 if (!success)
2032 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2033 goto error;
2035 CloseHandle( process_info );
2036 return success;
2038 error:
2039 CloseHandle( process_info );
2040 CloseHandle( info->hProcess );
2041 CloseHandle( info->hThread );
2042 info->hProcess = info->hThread = 0;
2043 info->dwProcessId = info->dwThreadId = 0;
2044 return FALSE;
2048 /***********************************************************************
2049 * create_vdm_process
2051 * Create a new VDM process for a 16-bit or DOS application.
2053 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2054 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2055 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2056 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2057 const struct binary_info *binary_info, int exec_only )
2059 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2061 BOOL ret;
2062 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
2063 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
2065 if (!new_cmd_line)
2067 SetLastError( ERROR_OUTOFMEMORY );
2068 return FALSE;
2070 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
2071 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2072 flags, startup, info, unixdir, binary_info, exec_only );
2073 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2074 return ret;
2078 /***********************************************************************
2079 * create_cmd_process
2081 * Create a new cmd shell process for a .BAT file.
2083 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2084 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2085 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2086 LPPROCESS_INFORMATION info )
2089 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2090 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2091 WCHAR comspec[MAX_PATH];
2092 WCHAR *newcmdline;
2093 BOOL ret;
2095 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2096 return FALSE;
2097 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2098 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2099 return FALSE;
2101 strcpyW( newcmdline, comspec );
2102 strcatW( newcmdline, slashcW );
2103 strcatW( newcmdline, cmd_line );
2104 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2105 flags, env, cur_dir, startup, info );
2106 HeapFree( GetProcessHeap(), 0, newcmdline );
2107 return ret;
2111 /*************************************************************************
2112 * get_file_name
2114 * Helper for CreateProcess: retrieve the file name to load from the
2115 * app name and command line. Store the file name in buffer, and
2116 * return a possibly modified command line.
2117 * Also returns a handle to the opened file if it's a Windows binary.
2119 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2120 int buflen, HANDLE *handle, struct binary_info *binary_info )
2122 static const WCHAR quotesW[] = {'"','%','s','"',0};
2124 WCHAR *name, *pos, *first_space, *ret = NULL;
2125 const WCHAR *p;
2127 /* if we have an app name, everything is easy */
2129 if (appname)
2131 /* use the unmodified app name as file name */
2132 lstrcpynW( buffer, appname, buflen );
2133 *handle = open_exe_file( buffer, binary_info );
2134 if (!(ret = cmdline) || !cmdline[0])
2136 /* no command-line, create one */
2137 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2138 sprintfW( ret, quotesW, appname );
2140 return ret;
2143 /* first check for a quoted file name */
2145 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2147 int len = p - cmdline - 1;
2148 /* extract the quoted portion as file name */
2149 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2150 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2151 name[len] = 0;
2153 if (!find_exe_file( name, buffer, buflen, handle, binary_info ))
2155 if (!get_builtin_path( name, exeW, buffer, buflen, binary_info )) goto done;
2156 *handle = 0;
2158 ret = cmdline; /* no change necessary */
2159 goto done;
2162 /* now try the command-line word by word */
2164 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2165 return NULL;
2166 pos = name;
2167 p = cmdline;
2168 first_space = NULL;
2170 for (;;)
2172 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2173 *pos = 0;
2174 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2176 ret = cmdline;
2177 break;
2179 if (!first_space) first_space = pos;
2180 if (!(*pos++ = *p++)) break;
2183 if (!ret)
2185 if (first_space) *first_space = 0; /* try only the first word as a builtin */
2186 if (get_builtin_path( name, exeW, buffer, buflen, binary_info ))
2188 *handle = 0;
2189 ret = cmdline;
2191 else SetLastError( ERROR_FILE_NOT_FOUND );
2193 else if (first_space) /* build a new command-line with quotes */
2195 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2196 goto done;
2197 sprintfW( ret, quotesW, name );
2198 strcatW( ret, p );
2201 done:
2202 HeapFree( GetProcessHeap(), 0, name );
2203 return ret;
2207 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2208 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2209 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2210 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2211 LPPROCESS_INFORMATION info )
2213 BOOL retv = FALSE;
2214 HANDLE hFile = 0;
2215 char *unixdir = NULL;
2216 WCHAR name[MAX_PATH];
2217 WCHAR *tidy_cmdline, *p, *envW = env;
2218 struct binary_info binary_info;
2220 /* Process the AppName and/or CmdLine to get module name and path */
2222 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2224 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2225 &hFile, &binary_info )))
2226 return FALSE;
2227 if (hFile == INVALID_HANDLE_VALUE) goto done;
2229 /* Warn if unsupported features are used */
2231 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2232 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2233 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2234 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2235 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2237 if (cur_dir)
2239 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2241 SetLastError(ERROR_DIRECTORY);
2242 goto done;
2245 else
2247 WCHAR buf[MAX_PATH];
2248 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2251 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2253 char *p = env;
2254 DWORD lenW;
2256 while (*p) p += strlen(p) + 1;
2257 p++; /* final null */
2258 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
2259 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2260 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
2261 flags |= CREATE_UNICODE_ENVIRONMENT;
2264 info->hThread = info->hProcess = 0;
2265 info->dwProcessId = info->dwThreadId = 0;
2267 if (binary_info.flags & BINARY_FLAG_DLL)
2269 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2270 SetLastError( ERROR_BAD_EXE_FORMAT );
2272 else switch (binary_info.type)
2274 case BINARY_PE:
2275 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2276 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2277 binary_info.res_start, binary_info.res_end );
2278 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2279 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2280 break;
2281 case BINARY_OS216:
2282 case BINARY_WIN16:
2283 case BINARY_DOS:
2284 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2285 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2286 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2287 break;
2288 case BINARY_UNIX_LIB:
2289 TRACE( "starting %s as %d-bit Winelib app\n",
2290 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
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_UNKNOWN:
2295 /* check for .com or .bat extension */
2296 if ((p = strrchrW( name, '.' )))
2298 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2300 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2301 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2302 inherit, flags, startup_info, info, unixdir,
2303 &binary_info, FALSE );
2304 break;
2306 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2308 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2309 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2310 inherit, flags, startup_info, info );
2311 break;
2314 /* fall through */
2315 case BINARY_UNIX_EXE:
2317 /* unknown file, try as unix executable */
2318 char *unix_name;
2320 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2322 if ((unix_name = wine_get_unix_file_name( name )))
2324 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2325 HeapFree( GetProcessHeap(), 0, unix_name );
2328 break;
2330 if (hFile) CloseHandle( hFile );
2332 done:
2333 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2334 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2335 HeapFree( GetProcessHeap(), 0, unixdir );
2336 if (retv)
2337 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2338 return retv;
2342 /**********************************************************************
2343 * CreateProcessA (KERNEL32.@)
2345 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2346 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2347 DWORD flags, LPVOID env, LPCSTR cur_dir,
2348 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2350 BOOL ret = FALSE;
2351 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2352 UNICODE_STRING desktopW, titleW;
2353 STARTUPINFOW infoW;
2355 desktopW.Buffer = NULL;
2356 titleW.Buffer = NULL;
2357 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2358 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2359 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2361 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2362 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2364 memcpy( &infoW, startup_info, sizeof(infoW) );
2365 infoW.lpDesktop = desktopW.Buffer;
2366 infoW.lpTitle = titleW.Buffer;
2368 if (startup_info->lpReserved)
2369 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2370 debugstr_a(startup_info->lpReserved));
2372 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2373 inherit, flags, env, cur_dirW, &infoW, info );
2374 done:
2375 HeapFree( GetProcessHeap(), 0, app_nameW );
2376 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2377 HeapFree( GetProcessHeap(), 0, cur_dirW );
2378 RtlFreeUnicodeString( &desktopW );
2379 RtlFreeUnicodeString( &titleW );
2380 return ret;
2384 /**********************************************************************
2385 * CreateProcessW (KERNEL32.@)
2387 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2388 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2389 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2390 LPPROCESS_INFORMATION info )
2392 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2393 inherit, flags, env, cur_dir, startup_info, info);
2397 /**********************************************************************
2398 * exec_process
2400 static void exec_process( LPCWSTR name )
2402 HANDLE hFile;
2403 WCHAR *p;
2404 STARTUPINFOW startup_info;
2405 PROCESS_INFORMATION info;
2406 struct binary_info binary_info;
2408 hFile = open_exe_file( name, &binary_info );
2409 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2411 memset( &startup_info, 0, sizeof(startup_info) );
2412 startup_info.cb = sizeof(startup_info);
2414 /* Determine executable type */
2416 if (binary_info.flags & BINARY_FLAG_DLL) return;
2417 switch (binary_info.type)
2419 case BINARY_PE:
2420 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2421 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2422 binary_info.res_start, binary_info.res_end );
2423 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2424 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2425 break;
2426 case BINARY_UNIX_LIB:
2427 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2428 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2429 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2430 break;
2431 case BINARY_UNKNOWN:
2432 /* check for .com or .pif extension */
2433 if (!(p = strrchrW( name, '.' ))) break;
2434 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2435 /* fall through */
2436 case BINARY_OS216:
2437 case BINARY_WIN16:
2438 case BINARY_DOS:
2439 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2440 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2441 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2442 break;
2443 default:
2444 break;
2446 CloseHandle( hFile );
2450 /***********************************************************************
2451 * wait_input_idle
2453 * Wrapper to call WaitForInputIdle USER function
2455 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2457 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2459 HMODULE mod = GetModuleHandleA( "user32.dll" );
2460 if (mod)
2462 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2463 if (ptr) return ptr( process, timeout );
2465 return 0;
2469 /***********************************************************************
2470 * WinExec (KERNEL32.@)
2472 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2474 PROCESS_INFORMATION info;
2475 STARTUPINFOA startup;
2476 char *cmdline;
2477 UINT ret;
2479 memset( &startup, 0, sizeof(startup) );
2480 startup.cb = sizeof(startup);
2481 startup.dwFlags = STARTF_USESHOWWINDOW;
2482 startup.wShowWindow = nCmdShow;
2484 /* cmdline needs to be writable for CreateProcess */
2485 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2486 strcpy( cmdline, lpCmdLine );
2488 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2489 0, NULL, NULL, &startup, &info ))
2491 /* Give 30 seconds to the app to come up */
2492 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2493 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2494 ret = 33;
2495 /* Close off the handles */
2496 CloseHandle( info.hThread );
2497 CloseHandle( info.hProcess );
2499 else if ((ret = GetLastError()) >= 32)
2501 FIXME("Strange error set by CreateProcess: %d\n", ret );
2502 ret = 11;
2504 HeapFree( GetProcessHeap(), 0, cmdline );
2505 return ret;
2509 /**********************************************************************
2510 * LoadModule (KERNEL32.@)
2512 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2514 LOADPARMS32 *params = paramBlock;
2515 PROCESS_INFORMATION info;
2516 STARTUPINFOA startup;
2517 DWORD ret;
2518 LPSTR cmdline, p;
2519 char filename[MAX_PATH];
2520 BYTE len;
2522 if (!name) return ERROR_FILE_NOT_FOUND;
2524 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2525 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2526 return GetLastError();
2528 len = (BYTE)params->lpCmdLine[0];
2529 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2530 return ERROR_NOT_ENOUGH_MEMORY;
2532 strcpy( cmdline, filename );
2533 p = cmdline + strlen(cmdline);
2534 *p++ = ' ';
2535 memcpy( p, params->lpCmdLine + 1, len );
2536 p[len] = 0;
2538 memset( &startup, 0, sizeof(startup) );
2539 startup.cb = sizeof(startup);
2540 if (params->lpCmdShow)
2542 startup.dwFlags = STARTF_USESHOWWINDOW;
2543 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2546 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2547 params->lpEnvAddress, NULL, &startup, &info ))
2549 /* Give 30 seconds to the app to come up */
2550 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2551 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2552 ret = 33;
2553 /* Close off the handles */
2554 CloseHandle( info.hThread );
2555 CloseHandle( info.hProcess );
2557 else if ((ret = GetLastError()) >= 32)
2559 FIXME("Strange error set by CreateProcess: %u\n", ret );
2560 ret = 11;
2563 HeapFree( GetProcessHeap(), 0, cmdline );
2564 return ret;
2568 /******************************************************************************
2569 * TerminateProcess (KERNEL32.@)
2571 * Terminates a process.
2573 * PARAMS
2574 * handle [I] Process to terminate.
2575 * exit_code [I] Exit code.
2577 * RETURNS
2578 * Success: TRUE.
2579 * Failure: FALSE, check GetLastError().
2581 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2583 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2584 if (status) SetLastError( RtlNtStatusToDosError(status) );
2585 return !status;
2588 /***********************************************************************
2589 * ExitProcess (KERNEL32.@)
2591 * Exits the current process.
2593 * PARAMS
2594 * status [I] Status code to exit with.
2596 * RETURNS
2597 * Nothing.
2599 #ifdef __i386__
2600 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2601 "pushl %ebp\n\t"
2602 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2603 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2604 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2605 "pushl 8(%ebp)\n\t"
2606 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2607 "leave\n\t"
2608 "ret $4" )
2610 void WINAPI process_ExitProcess( DWORD status )
2612 LdrShutdownProcess();
2613 NtTerminateProcess(GetCurrentProcess(), status);
2614 exit(status);
2617 #else
2619 void WINAPI ExitProcess( DWORD status )
2621 LdrShutdownProcess();
2622 NtTerminateProcess(GetCurrentProcess(), status);
2623 exit(status);
2626 #endif
2628 /***********************************************************************
2629 * GetExitCodeProcess [KERNEL32.@]
2631 * Gets termination status of specified process.
2633 * PARAMS
2634 * hProcess [in] Handle to the process.
2635 * lpExitCode [out] Address to receive termination status.
2637 * RETURNS
2638 * Success: TRUE
2639 * Failure: FALSE
2641 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2643 NTSTATUS status;
2644 PROCESS_BASIC_INFORMATION pbi;
2646 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2647 sizeof(pbi), NULL);
2648 if (status == STATUS_SUCCESS)
2650 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2651 return TRUE;
2653 SetLastError( RtlNtStatusToDosError(status) );
2654 return FALSE;
2658 /***********************************************************************
2659 * SetErrorMode (KERNEL32.@)
2661 UINT WINAPI SetErrorMode( UINT mode )
2663 UINT old;
2665 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2666 &old, sizeof(old), NULL );
2667 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2668 &mode, sizeof(mode) );
2669 return old;
2672 /***********************************************************************
2673 * GetErrorMode (KERNEL32.@)
2675 UINT WINAPI GetErrorMode( void )
2677 UINT mode;
2679 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2680 &mode, sizeof(mode), NULL );
2681 return mode;
2684 /**********************************************************************
2685 * TlsAlloc [KERNEL32.@]
2687 * Allocates a thread local storage index.
2689 * RETURNS
2690 * Success: TLS index.
2691 * Failure: 0xFFFFFFFF
2693 DWORD WINAPI TlsAlloc( void )
2695 DWORD index;
2696 PEB * const peb = NtCurrentTeb()->Peb;
2698 RtlAcquirePebLock();
2699 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2700 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2701 else
2703 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2704 if (index != ~0U)
2706 if (!NtCurrentTeb()->TlsExpansionSlots &&
2707 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2708 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2710 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2711 index = ~0U;
2712 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2714 else
2716 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2717 index += TLS_MINIMUM_AVAILABLE;
2720 else SetLastError( ERROR_NO_MORE_ITEMS );
2722 RtlReleasePebLock();
2723 return index;
2727 /**********************************************************************
2728 * TlsFree [KERNEL32.@]
2730 * Releases a thread local storage index, making it available for reuse.
2732 * PARAMS
2733 * index [in] TLS index to free.
2735 * RETURNS
2736 * Success: TRUE
2737 * Failure: FALSE
2739 BOOL WINAPI TlsFree( DWORD index )
2741 BOOL ret;
2743 RtlAcquirePebLock();
2744 if (index >= TLS_MINIMUM_AVAILABLE)
2746 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2747 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2749 else
2751 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2752 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2754 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2755 else SetLastError( ERROR_INVALID_PARAMETER );
2756 RtlReleasePebLock();
2757 return ret;
2761 /**********************************************************************
2762 * TlsGetValue [KERNEL32.@]
2764 * Gets value in a thread's TLS slot.
2766 * PARAMS
2767 * index [in] TLS index to retrieve value for.
2769 * RETURNS
2770 * Success: Value stored in calling thread's TLS slot for index.
2771 * Failure: 0 and GetLastError() returns NO_ERROR.
2773 LPVOID WINAPI TlsGetValue( DWORD index )
2775 LPVOID ret;
2777 if (index < TLS_MINIMUM_AVAILABLE)
2779 ret = NtCurrentTeb()->TlsSlots[index];
2781 else
2783 index -= TLS_MINIMUM_AVAILABLE;
2784 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2786 SetLastError( ERROR_INVALID_PARAMETER );
2787 return NULL;
2789 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2790 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2792 SetLastError( ERROR_SUCCESS );
2793 return ret;
2797 /**********************************************************************
2798 * TlsSetValue [KERNEL32.@]
2800 * Stores a value in the thread's TLS slot.
2802 * PARAMS
2803 * index [in] TLS index to set value for.
2804 * value [in] Value to be stored.
2806 * RETURNS
2807 * Success: TRUE
2808 * Failure: FALSE
2810 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2812 if (index < TLS_MINIMUM_AVAILABLE)
2814 NtCurrentTeb()->TlsSlots[index] = value;
2816 else
2818 index -= TLS_MINIMUM_AVAILABLE;
2819 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2821 SetLastError( ERROR_INVALID_PARAMETER );
2822 return FALSE;
2824 if (!NtCurrentTeb()->TlsExpansionSlots &&
2825 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2826 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2828 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2829 return FALSE;
2831 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2833 return TRUE;
2837 /***********************************************************************
2838 * GetProcessFlags (KERNEL32.@)
2840 DWORD WINAPI GetProcessFlags( DWORD processid )
2842 IMAGE_NT_HEADERS *nt;
2843 DWORD flags = 0;
2845 if (processid && processid != GetCurrentProcessId()) return 0;
2847 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2849 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2850 flags |= PDB32_CONSOLE_PROC;
2852 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2853 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2854 return flags;
2858 /*********************************************************************
2859 * OpenProcess (KERNEL32.@)
2861 * Opens a handle to a process.
2863 * PARAMS
2864 * access [I] Desired access rights assigned to the returned handle.
2865 * inherit [I] Determines whether or not child processes will inherit the handle.
2866 * id [I] Process identifier of the process to get a handle to.
2868 * RETURNS
2869 * Success: Valid handle to the specified process.
2870 * Failure: NULL, check GetLastError().
2872 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2874 NTSTATUS status;
2875 HANDLE handle;
2876 OBJECT_ATTRIBUTES attr;
2877 CLIENT_ID cid;
2879 cid.UniqueProcess = ULongToHandle(id);
2880 cid.UniqueThread = 0; /* FIXME ? */
2882 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2883 attr.RootDirectory = NULL;
2884 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2885 attr.SecurityDescriptor = NULL;
2886 attr.SecurityQualityOfService = NULL;
2887 attr.ObjectName = NULL;
2889 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2891 status = NtOpenProcess(&handle, access, &attr, &cid);
2892 if (status != STATUS_SUCCESS)
2894 SetLastError( RtlNtStatusToDosError(status) );
2895 return NULL;
2897 return handle;
2901 /*********************************************************************
2902 * GetProcessId (KERNEL32.@)
2904 * Gets the a unique identifier of a process.
2906 * PARAMS
2907 * hProcess [I] Handle to the process.
2909 * RETURNS
2910 * Success: TRUE.
2911 * Failure: FALSE, check GetLastError().
2913 * NOTES
2915 * The identifier is unique only on the machine and only until the process
2916 * exits (including system shutdown).
2918 DWORD WINAPI GetProcessId( HANDLE hProcess )
2920 NTSTATUS status;
2921 PROCESS_BASIC_INFORMATION pbi;
2923 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2924 sizeof(pbi), NULL);
2925 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2926 SetLastError( RtlNtStatusToDosError(status) );
2927 return 0;
2931 /*********************************************************************
2932 * CloseHandle (KERNEL32.@)
2934 * Closes a handle.
2936 * PARAMS
2937 * handle [I] Handle to close.
2939 * RETURNS
2940 * Success: TRUE.
2941 * Failure: FALSE, check GetLastError().
2943 BOOL WINAPI CloseHandle( HANDLE handle )
2945 NTSTATUS status;
2947 /* stdio handles need special treatment */
2948 if (handle == (HANDLE)STD_INPUT_HANDLE)
2949 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
2950 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
2951 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
2952 else if (handle == (HANDLE)STD_ERROR_HANDLE)
2953 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
2955 if (is_console_handle(handle))
2956 return CloseConsoleHandle(handle);
2958 status = NtClose( handle );
2959 if (status) SetLastError( RtlNtStatusToDosError(status) );
2960 return !status;
2964 /*********************************************************************
2965 * GetHandleInformation (KERNEL32.@)
2967 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2969 OBJECT_DATA_INFORMATION info;
2970 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2972 if (status) SetLastError( RtlNtStatusToDosError(status) );
2973 else if (flags)
2975 *flags = 0;
2976 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2977 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2979 return !status;
2983 /*********************************************************************
2984 * SetHandleInformation (KERNEL32.@)
2986 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2988 OBJECT_DATA_INFORMATION info;
2989 NTSTATUS status;
2991 /* if not setting both fields, retrieve current value first */
2992 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2993 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2995 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2997 SetLastError( RtlNtStatusToDosError(status) );
2998 return FALSE;
3001 if (mask & HANDLE_FLAG_INHERIT)
3002 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3003 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3004 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3006 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3007 if (status) SetLastError( RtlNtStatusToDosError(status) );
3008 return !status;
3012 /*********************************************************************
3013 * DuplicateHandle (KERNEL32.@)
3015 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3016 HANDLE dest_process, HANDLE *dest,
3017 DWORD access, BOOL inherit, DWORD options )
3019 NTSTATUS status;
3021 if (is_console_handle(source))
3023 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3024 if (source_process != dest_process ||
3025 source_process != GetCurrentProcess())
3027 SetLastError(ERROR_INVALID_PARAMETER);
3028 return FALSE;
3030 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3031 return (*dest != INVALID_HANDLE_VALUE);
3033 status = NtDuplicateObject( source_process, source, dest_process, dest,
3034 access, inherit ? OBJ_INHERIT : 0, options );
3035 if (status) SetLastError( RtlNtStatusToDosError(status) );
3036 return !status;
3040 /***********************************************************************
3041 * ConvertToGlobalHandle (KERNEL32.@)
3043 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3045 HANDLE ret = INVALID_HANDLE_VALUE;
3046 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3047 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3048 return ret;
3052 /***********************************************************************
3053 * SetHandleContext (KERNEL32.@)
3055 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3057 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3058 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3059 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3060 return FALSE;
3064 /***********************************************************************
3065 * GetHandleContext (KERNEL32.@)
3067 DWORD WINAPI GetHandleContext(HANDLE hnd)
3069 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3070 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3071 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3072 return 0;
3076 /***********************************************************************
3077 * CreateSocketHandle (KERNEL32.@)
3079 HANDLE WINAPI CreateSocketHandle(void)
3081 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3082 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3083 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3084 return INVALID_HANDLE_VALUE;
3088 /***********************************************************************
3089 * SetPriorityClass (KERNEL32.@)
3091 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3093 NTSTATUS status;
3094 PROCESS_PRIORITY_CLASS ppc;
3096 ppc.Foreground = FALSE;
3097 switch (priorityclass)
3099 case IDLE_PRIORITY_CLASS:
3100 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3101 case BELOW_NORMAL_PRIORITY_CLASS:
3102 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3103 case NORMAL_PRIORITY_CLASS:
3104 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3105 case ABOVE_NORMAL_PRIORITY_CLASS:
3106 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3107 case HIGH_PRIORITY_CLASS:
3108 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3109 case REALTIME_PRIORITY_CLASS:
3110 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3111 default:
3112 SetLastError(ERROR_INVALID_PARAMETER);
3113 return FALSE;
3116 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3117 &ppc, sizeof(ppc));
3119 if (status != STATUS_SUCCESS)
3121 SetLastError( RtlNtStatusToDosError(status) );
3122 return FALSE;
3124 return TRUE;
3128 /***********************************************************************
3129 * GetPriorityClass (KERNEL32.@)
3131 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3133 NTSTATUS status;
3134 PROCESS_BASIC_INFORMATION pbi;
3136 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3137 sizeof(pbi), NULL);
3138 if (status != STATUS_SUCCESS)
3140 SetLastError( RtlNtStatusToDosError(status) );
3141 return 0;
3143 switch (pbi.BasePriority)
3145 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3146 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3147 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3148 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3149 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3150 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3152 SetLastError( ERROR_INVALID_PARAMETER );
3153 return 0;
3157 /***********************************************************************
3158 * SetProcessAffinityMask (KERNEL32.@)
3160 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3162 NTSTATUS status;
3164 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3165 &affmask, sizeof(DWORD_PTR));
3166 if (status)
3168 SetLastError( RtlNtStatusToDosError(status) );
3169 return FALSE;
3171 return TRUE;
3175 /**********************************************************************
3176 * GetProcessAffinityMask (KERNEL32.@)
3178 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3180 NTSTATUS status = STATUS_SUCCESS;
3182 if (system_mask) *system_mask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
3183 if (process_mask)
3185 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3186 process_mask, sizeof(*process_mask), NULL )))
3187 SetLastError( RtlNtStatusToDosError(status) );
3189 return !status;
3193 /***********************************************************************
3194 * GetProcessVersion (KERNEL32.@)
3196 DWORD WINAPI GetProcessVersion( DWORD pid )
3198 HANDLE process;
3199 NTSTATUS status;
3200 PROCESS_BASIC_INFORMATION pbi;
3201 SIZE_T count;
3202 PEB peb;
3203 IMAGE_DOS_HEADER dos;
3204 IMAGE_NT_HEADERS nt;
3205 DWORD ver = 0;
3207 if (!pid || pid == GetCurrentProcessId())
3209 IMAGE_NT_HEADERS *nt;
3211 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3212 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
3213 nt->OptionalHeader.MinorSubsystemVersion);
3214 return 0;
3217 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3218 if (!process) return 0;
3220 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3221 if (status) goto err;
3223 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3224 if (status || count != sizeof(peb)) goto err;
3226 memset(&dos, 0, sizeof(dos));
3227 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3228 if (status || count != sizeof(dos)) goto err;
3229 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3231 memset(&nt, 0, sizeof(nt));
3232 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3233 if (status || count != sizeof(nt)) goto err;
3234 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3236 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3238 err:
3239 CloseHandle(process);
3241 if (status != STATUS_SUCCESS)
3242 SetLastError(RtlNtStatusToDosError(status));
3244 return ver;
3248 /***********************************************************************
3249 * SetProcessWorkingSetSize [KERNEL32.@]
3250 * Sets the min/max working set sizes for a specified process.
3252 * PARAMS
3253 * hProcess [I] Handle to the process of interest
3254 * minset [I] Specifies minimum working set size
3255 * maxset [I] Specifies maximum working set size
3257 * RETURNS
3258 * Success: TRUE
3259 * Failure: FALSE
3261 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3262 SIZE_T maxset)
3264 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3265 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3266 /* Trim the working set to zero */
3267 /* Swap the process out of physical RAM */
3269 return TRUE;
3272 /***********************************************************************
3273 * K32EmptyWorkingSet (KERNEL32.@)
3275 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3277 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3280 /***********************************************************************
3281 * GetProcessWorkingSetSize (KERNEL32.@)
3283 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3284 PSIZE_T maxset)
3286 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3287 /* 32 MB working set size */
3288 if (minset) *minset = 32*1024*1024;
3289 if (maxset) *maxset = 32*1024*1024;
3290 return TRUE;
3294 /***********************************************************************
3295 * SetProcessShutdownParameters (KERNEL32.@)
3297 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3299 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3300 shutdown_flags = flags;
3301 shutdown_priority = level;
3302 return TRUE;
3306 /***********************************************************************
3307 * GetProcessShutdownParameters (KERNEL32.@)
3310 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3312 *lpdwLevel = shutdown_priority;
3313 *lpdwFlags = shutdown_flags;
3314 return TRUE;
3318 /***********************************************************************
3319 * GetProcessPriorityBoost (KERNEL32.@)
3321 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3323 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3325 /* Report that no boost is present.. */
3326 *pDisablePriorityBoost = FALSE;
3328 return TRUE;
3331 /***********************************************************************
3332 * SetProcessPriorityBoost (KERNEL32.@)
3334 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3336 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3337 /* Say we can do it. I doubt the program will notice that we don't. */
3338 return TRUE;
3342 /***********************************************************************
3343 * ReadProcessMemory (KERNEL32.@)
3345 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3346 SIZE_T *bytes_read )
3348 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3349 if (status) SetLastError( RtlNtStatusToDosError(status) );
3350 return !status;
3354 /***********************************************************************
3355 * WriteProcessMemory (KERNEL32.@)
3357 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3358 SIZE_T *bytes_written )
3360 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3361 if (status) SetLastError( RtlNtStatusToDosError(status) );
3362 return !status;
3366 /****************************************************************************
3367 * FlushInstructionCache (KERNEL32.@)
3369 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3371 NTSTATUS status;
3372 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3373 if (status) SetLastError( RtlNtStatusToDosError(status) );
3374 return !status;
3378 /******************************************************************
3379 * GetProcessIoCounters (KERNEL32.@)
3381 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3383 NTSTATUS status;
3385 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3386 ioc, sizeof(*ioc), NULL);
3387 if (status) SetLastError( RtlNtStatusToDosError(status) );
3388 return !status;
3391 /******************************************************************
3392 * GetProcessHandleCount (KERNEL32.@)
3394 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3396 NTSTATUS status;
3398 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3399 cnt, sizeof(*cnt), NULL);
3400 if (status) SetLastError( RtlNtStatusToDosError(status) );
3401 return !status;
3404 /******************************************************************
3405 * QueryFullProcessImageNameA (KERNEL32.@)
3407 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3409 BOOL retval;
3410 DWORD pdwSizeW = *pdwSize;
3411 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3413 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3415 if(retval)
3416 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3417 lpExeName, *pdwSize, NULL, NULL));
3418 if(retval)
3419 *pdwSize = strlen(lpExeName);
3421 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3422 return retval;
3425 /******************************************************************
3426 * QueryFullProcessImageNameW (KERNEL32.@)
3428 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3430 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3431 UNICODE_STRING *dynamic_buffer = NULL;
3432 UNICODE_STRING nt_path;
3433 UNICODE_STRING *result = NULL;
3434 NTSTATUS status;
3435 DWORD needed;
3437 RtlInitUnicodeStringEx(&nt_path, NULL);
3438 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3439 * as this is on Wine. */
3440 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3441 sizeof(buffer) - sizeof(WCHAR), &needed);
3442 if (status == STATUS_INFO_LENGTH_MISMATCH)
3444 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3445 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3446 result = dynamic_buffer;
3448 else
3449 result = (PUNICODE_STRING)buffer;
3451 if (status) goto cleanup;
3453 if (dwFlags & PROCESS_NAME_NATIVE)
3455 result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3456 if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3458 status = STATUS_OBJECT_PATH_NOT_FOUND;
3459 goto cleanup;
3461 result = &nt_path;
3464 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3466 status = STATUS_BUFFER_TOO_SMALL;
3467 goto cleanup;
3470 *pdwSize = result->Length/sizeof(WCHAR);
3471 memcpy( lpExeName, result->Buffer, result->Length );
3472 lpExeName[*pdwSize] = 0;
3474 cleanup:
3475 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3476 RtlFreeUnicodeString(&nt_path);
3477 if (status) SetLastError( RtlNtStatusToDosError(status) );
3478 return !status;
3481 /***********************************************************************
3482 * K32GetProcessImageFileNameA (KERNEL32.@)
3484 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3486 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3489 /***********************************************************************
3490 * K32GetProcessImageFileNameW (KERNEL32.@)
3492 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3494 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3497 /***********************************************************************
3498 * K32EnumProcesses (KERNEL32.@)
3500 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3502 SYSTEM_PROCESS_INFORMATION *spi;
3503 ULONG size = 0x4000;
3504 void *buf = NULL;
3505 NTSTATUS status;
3507 do {
3508 size *= 2;
3509 HeapFree(GetProcessHeap(), 0, buf);
3510 buf = HeapAlloc(GetProcessHeap(), 0, size);
3511 if (!buf)
3512 return FALSE;
3514 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3515 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3517 if (status != STATUS_SUCCESS)
3519 HeapFree(GetProcessHeap(), 0, buf);
3520 SetLastError(RtlNtStatusToDosError(status));
3521 return FALSE;
3524 spi = buf;
3526 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3528 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3529 *lpcbUsed += sizeof(DWORD);
3531 if (spi->NextEntryOffset == 0)
3532 break;
3534 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3537 HeapFree(GetProcessHeap(), 0, buf);
3538 return TRUE;
3541 /***********************************************************************
3542 * K32QueryWorkingSet (KERNEL32.@)
3544 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3546 NTSTATUS status;
3548 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3550 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3552 if (status)
3554 SetLastError( RtlNtStatusToDosError( status ) );
3555 return FALSE;
3557 return TRUE;
3560 /***********************************************************************
3561 * K32QueryWorkingSetEx (KERNEL32.@)
3563 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3565 NTSTATUS status;
3567 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3569 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3571 if (status)
3573 SetLastError( RtlNtStatusToDosError( status ) );
3574 return FALSE;
3576 return TRUE;
3579 /***********************************************************************
3580 * K32GetProcessMemoryInfo (KERNEL32.@)
3582 * Retrieve memory usage information for a given process
3585 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3586 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3588 NTSTATUS status;
3589 VM_COUNTERS vmc;
3591 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3593 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3594 return FALSE;
3597 status = NtQueryInformationProcess(process, ProcessVmCounters,
3598 &vmc, sizeof(vmc), NULL);
3600 if (status)
3602 SetLastError(RtlNtStatusToDosError(status));
3603 return FALSE;
3606 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3607 pmc->PageFaultCount = vmc.PageFaultCount;
3608 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3609 pmc->WorkingSetSize = vmc.WorkingSetSize;
3610 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3611 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3612 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3613 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3614 pmc->PagefileUsage = vmc.PagefileUsage;
3615 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3617 return TRUE;
3620 /***********************************************************************
3621 * ProcessIdToSessionId (KERNEL32.@)
3622 * This function is available on Terminal Server 4SP4 and Windows 2000
3624 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3626 /* According to MSDN, if the calling process is not in a terminal
3627 * services environment, then the sessionid returned is zero.
3629 *sessionid_ptr = 0;
3630 return TRUE;
3634 /***********************************************************************
3635 * RegisterServiceProcess (KERNEL32.@)
3637 * A service process calls this function to ensure that it continues to run
3638 * even after a user logged off.
3640 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3642 /* I don't think that Wine needs to do anything in this function */
3643 return 1; /* success */
3647 /**********************************************************************
3648 * IsWow64Process (KERNEL32.@)
3650 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3652 ULONG pbi;
3653 NTSTATUS status;
3655 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3657 if (status != STATUS_SUCCESS)
3659 SetLastError( RtlNtStatusToDosError( status ) );
3660 return FALSE;
3662 *Wow64Process = (pbi != 0);
3663 return TRUE;
3667 /***********************************************************************
3668 * GetCurrentProcess (KERNEL32.@)
3670 * Get a handle to the current process.
3672 * PARAMS
3673 * None.
3675 * RETURNS
3676 * A handle representing the current process.
3678 #undef GetCurrentProcess
3679 HANDLE WINAPI GetCurrentProcess(void)
3681 return (HANDLE)~(ULONG_PTR)0;
3684 /***********************************************************************
3685 * GetLogicalProcessorInformation (KERNEL32.@)
3687 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3689 FIXME("(%p,%p): stub\n", buffer, pBufLen);
3690 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3691 return FALSE;
3694 /***********************************************************************
3695 * GetLogicalProcessorInformationEx (KERNEL32.@)
3697 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer, PDWORD pBufLen)
3699 FIXME("(%u,%p,%p): stub\n", relationship, buffer, pBufLen);
3700 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3701 return FALSE;
3704 /***********************************************************************
3705 * CmdBatNotification (KERNEL32.@)
3707 * Notifies the system that a batch file has started or finished.
3709 * PARAMS
3710 * bBatchRunning [I] TRUE if a batch file has started or
3711 * FALSE if a batch file has finished executing.
3713 * RETURNS
3714 * Unknown.
3716 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3718 FIXME("%d\n", bBatchRunning);
3719 return FALSE;
3723 /***********************************************************************
3724 * RegisterApplicationRestart (KERNEL32.@)
3726 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3728 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3730 return S_OK;
3733 /**********************************************************************
3734 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3736 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3738 FIXME("stub\n");
3739 return 0;
3742 /**********************************************************************
3743 * GetSystemDEPPolicy (KERNEL32.@)
3745 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3747 FIXME("stub\n");
3748 return OptIn;
3751 /**********************************************************************
3752 * SetProcessDEPPolicy (KERNEL32.@)
3754 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3756 FIXME("(%d): stub\n", newDEP);
3757 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3758 return FALSE;
3761 /**********************************************************************
3762 * ApplicationRecoveryFinished (KERNEL32.@)
3764 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
3766 FIXME(": stub\n");
3767 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3770 /**********************************************************************
3771 * ApplicationRecoveryInProgress (KERNEL32.@)
3773 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
3775 FIXME(":%p stub\n", canceled);
3776 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3777 return E_FAIL;
3780 /**********************************************************************
3781 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3783 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
3785 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
3786 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3787 return E_FAIL;
3790 /**********************************************************************
3791 * GetNumaHighestNodeNumber (KERNEL32.@)
3793 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
3795 FIXME("(%p): stub\n", highestnode);
3796 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3797 return FALSE;
3800 /**********************************************************************
3801 * GetNumaNodeProcessorMask (KERNEL32.@)
3803 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
3805 FIXME("(%c %p): stub\n", node, mask);
3806 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3807 return FALSE;
3810 /**********************************************************************
3811 * GetNumaAvailableMemoryNode (KERNEL32.@)
3813 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
3815 FIXME("(%c %p): stub\n", node, available_bytes);
3816 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3817 return FALSE;