kernel32: Fix some memory leaks in set_wow64_environment().
[wine] / dlls / kernel32 / process.c
1 /*
2  * Win32 processes
3  *
4  * Copyright 1996, 1998 Alexandre Julliard
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
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
45 #include "ntstatus.h"
46 #define WIN32_NO_STATUS
47 #include "winternl.h"
48 #include "kernel_private.h"
49 #include "wine/library.h"
50 #include "wine/server.h"
51 #include "wine/unicode.h"
52 #include "wine/debug.h"
53
54 WINE_DEFAULT_DEBUG_CHANNEL(process);
55 WINE_DECLARE_DEBUG_CHANNEL(file);
56 WINE_DECLARE_DEBUG_CHANNEL(relay);
57
58 #ifdef __APPLE__
59 #include <CoreFoundation/CoreFoundation.h>
60 #include <pthread.h>
61 #include <unistd.h>
62 extern char **__wine_get_main_environment(void);
63 #else
64 extern char **__wine_main_environ;
65 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
66 #endif
67
68 typedef struct
69 {
70     LPSTR lpEnvAddress;
71     LPSTR lpCmdLine;
72     LPSTR lpCmdShow;
73     DWORD dwReserved;
74 } LOADPARMS32;
75
76 static DWORD shutdown_flags = 0;
77 static DWORD shutdown_priority = 0x280;
78 static BOOL is_wow64;
79 static const int is_win64 = (sizeof(void *) > sizeof(int));
80
81 HMODULE kernel32_handle = 0;
82
83 const WCHAR *DIR_Windows = NULL;
84 const WCHAR *DIR_System = NULL;
85 const WCHAR *DIR_SysWow64 = NULL;
86
87 /* Process flags */
88 #define PDB32_DEBUGGED      0x0001  /* Process is being debugged */
89 #define PDB32_WIN16_PROC    0x0008  /* Win16 process */
90 #define PDB32_DOS_PROC      0x0010  /* Dos process */
91 #define PDB32_CONSOLE_PROC  0x0020  /* Console process */
92 #define PDB32_FILE_APIS_OEM 0x0040  /* File APIs are OEM */
93 #define PDB32_WIN32S_PROC   0x8000  /* Win32s process */
94
95 static const WCHAR exeW[] = {'.','e','x','e',0};
96 static const WCHAR comW[] = {'.','c','o','m',0};
97 static const WCHAR batW[] = {'.','b','a','t',0};
98 static const WCHAR cmdW[] = {'.','c','m','d',0};
99 static const WCHAR pifW[] = {'.','p','i','f',0};
100 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
101
102 static void exec_process( LPCWSTR name );
103
104 extern void SHELL_LoadRegistry(void);
105
106
107 /***********************************************************************
108  *           contains_path
109  */
110 static inline int contains_path( LPCWSTR name )
111 {
112     return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
113 }
114
115
116 /***********************************************************************
117  *           is_special_env_var
118  *
119  * Check if an environment variable needs to be handled specially when
120  * passed through the Unix environment (i.e. prefixed with "WINE").
121  */
122 static inline int is_special_env_var( const char *var )
123 {
124     return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
125             !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
126             !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
127             !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
128             !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
129 }
130
131
132 /***********************************************************************
133  *           is_path_prefix
134  */
135 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
136 {
137     unsigned int len = strlenW( prefix );
138
139     if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
140     while (filename[len] == '\\') len++;
141     return len;
142 }
143
144
145 /***************************************************************************
146  *      get_builtin_path
147  *
148  * Get the path of a builtin module when the native file does not exist.
149  */
150 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
151                               UINT size, struct binary_info *binary_info )
152 {
153     WCHAR *file_part;
154     UINT len;
155     void *redir_disabled = 0;
156     unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
157
158     /* builtin names cannot be empty or contain spaces */
159     if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
160
161     if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
162         Wow64RevertWow64FsRedirection( redir_disabled );
163
164     if (contains_path( libname ))
165     {
166         if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
167                                   filename, &file_part ) > size * sizeof(WCHAR))
168             return FALSE;  /* too long */
169
170         if ((len = is_path_prefix( DIR_System, filename )))
171         {
172             if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
173         }
174         else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
175         {
176             flags = 0;
177         }
178         else return FALSE;
179
180         if (filename + len != file_part) return FALSE;
181     }
182     else
183     {
184         len = strlenW( DIR_System );
185         if (strlenW(libname) + len + 2 >= size) return FALSE;  /* too long */
186         memcpy( filename, DIR_System, len * sizeof(WCHAR) );
187         file_part = filename + len;
188         if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
189         strcpyW( file_part, libname );
190         if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
191     }
192     if (ext && !strchrW( file_part, '.' ))
193     {
194         if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
195             return FALSE;  /* too long */
196         strcatW( file_part, ext );
197     }
198     binary_info->type = BINARY_UNIX_LIB;
199     binary_info->flags = flags;
200     binary_info->res_start = NULL;
201     binary_info->res_end = NULL;
202     return TRUE;
203 }
204
205
206 /***********************************************************************
207  *           open_exe_file
208  *
209  * Open a specific exe file, taking load order into account.
210  * Returns the file handle or 0 for a builtin exe.
211  */
212 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
213 {
214     HANDLE handle;
215
216     TRACE("looking for %s\n", debugstr_w(name) );
217
218     if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
219                                NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
220     {
221         WCHAR buffer[MAX_PATH];
222         /* file doesn't exist, check for builtin */
223         if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
224             handle = 0;
225     }
226     else MODULE_get_binary_info( handle, binary_info );
227
228     return handle;
229 }
230
231
232 /***********************************************************************
233  *           find_exe_file
234  *
235  * Open an exe file, and return the full name and file handle.
236  * Returns FALSE if file could not be found.
237  * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
238  * If file is a builtin exe, returns TRUE and sets handle to 0.
239  */
240 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
241                            HANDLE *handle, struct binary_info *binary_info )
242 {
243     TRACE("looking for %s\n", debugstr_w(name) );
244
245     if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ))
246     {
247         if (contains_path( name ) && get_builtin_path( name, exeW, buffer, buflen, binary_info ))
248         {
249             *handle = 0;
250             return TRUE;
251         }
252         /* no builtin found, try native without extension in case it is a Unix app */
253         if (!SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
254     }
255
256     TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
257     if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
258                                 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
259     {
260         MODULE_get_binary_info( *handle, binary_info );
261         return TRUE;
262     }
263     return FALSE;
264 }
265
266
267 /***********************************************************************
268  *           build_initial_environment
269  *
270  * Build the Win32 environment from the Unix environment
271  */
272 static BOOL build_initial_environment(void)
273 {
274     SIZE_T size = 1;
275     char **e;
276     WCHAR *p, *endptr;
277     void *ptr;
278     char **env = __wine_get_main_environment();
279
280     /* Compute the total size of the Unix environment */
281     for (e = env; *e; e++)
282     {
283         if (is_special_env_var( *e )) continue;
284         size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
285     }
286     size *= sizeof(WCHAR);
287
288     /* Now allocate the environment */
289     ptr = NULL;
290     if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
291                                 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
292         return FALSE;
293
294     NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
295     endptr = p + size / sizeof(WCHAR);
296
297     /* And fill it with the Unix environment */
298     for (e = env; *e; e++)
299     {
300         char *str = *e;
301
302         /* skip Unix special variables and use the Wine variants instead */
303         if (!strncmp( str, "WINE", 4 ))
304         {
305             if (is_special_env_var( str + 4 )) str += 4;
306             else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue;  /* skip it */
307         }
308         else if (is_special_env_var( str )) continue;  /* skip it */
309
310         MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
311         p += strlenW(p) + 1;
312     }
313     *p = 0;
314     return TRUE;
315 }
316
317
318 /***********************************************************************
319  *           set_registry_variables
320  *
321  * Set environment variables by enumerating the values of a key;
322  * helper for set_registry_environment().
323  * Note that Windows happily truncates the value if it's too big.
324  */
325 static void set_registry_variables( HANDLE hkey, ULONG type )
326 {
327     static const WCHAR pathW[] = {'P','A','T','H'};
328     static const WCHAR sep[] = {';',0};
329     UNICODE_STRING env_name, env_value;
330     NTSTATUS status;
331     DWORD size;
332     int index;
333     char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
334     WCHAR tmpbuf[1024];
335     UNICODE_STRING tmp;
336     KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
337
338     tmp.Buffer = tmpbuf;
339     tmp.MaximumLength = sizeof(tmpbuf);
340
341     for (index = 0; ; index++)
342     {
343         status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
344                                       buffer, sizeof(buffer), &size );
345         if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
346             break;
347         if (info->Type != type)
348             continue;
349         env_name.Buffer = info->Name;
350         env_name.Length = env_name.MaximumLength = info->NameLength;
351         env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
352         env_value.Length = info->DataLength;
353         env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
354         if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
355             env_value.Length -= sizeof(WCHAR);  /* don't count terminating null if any */
356         if (!env_value.Length) continue;
357         if (info->Type == REG_EXPAND_SZ)
358         {
359             status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
360             if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
361             RtlCopyUnicodeString( &env_value, &tmp );
362         }
363         /* PATH is magic */
364         if (env_name.Length == sizeof(pathW) &&
365             !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
366             !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
367         {
368             RtlAppendUnicodeToString( &tmp, sep );
369             if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
370             RtlCopyUnicodeString( &env_value, &tmp );
371         }
372         RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
373     }
374 }
375
376
377 /***********************************************************************
378  *           set_registry_environment
379  *
380  * Set the environment variables specified in the registry.
381  *
382  * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
383  * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
384  * on the order in which the variables are processed. But on Windows it
385  * does not really matter since they only use %SystemDrive% and
386  * %SystemRoot% which are predefined. But Wine defines these in the
387  * registry, so we need two passes.
388  */
389 static BOOL set_registry_environment( BOOL volatile_only )
390 {
391     static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
392                                      'S','y','s','t','e','m','\\',
393                                      'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
394                                      'C','o','n','t','r','o','l','\\',
395                                      'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
396                                      'E','n','v','i','r','o','n','m','e','n','t',0};
397     static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
398     static const WCHAR volatile_envW[] = {'V','o','l','a','t','i','l','e',' ','E','n','v','i','r','o','n','m','e','n','t',0};
399
400     OBJECT_ATTRIBUTES attr;
401     UNICODE_STRING nameW;
402     HANDLE hkey;
403     BOOL ret = FALSE;
404
405     attr.Length = sizeof(attr);
406     attr.RootDirectory = 0;
407     attr.ObjectName = &nameW;
408     attr.Attributes = 0;
409     attr.SecurityDescriptor = NULL;
410     attr.SecurityQualityOfService = NULL;
411
412     /* first the system environment variables */
413     RtlInitUnicodeString( &nameW, env_keyW );
414     if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
415     {
416         set_registry_variables( hkey, REG_SZ );
417         set_registry_variables( hkey, REG_EXPAND_SZ );
418         NtClose( hkey );
419         ret = TRUE;
420     }
421
422     /* then the ones for the current user */
423     if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
424     RtlInitUnicodeString( &nameW, envW );
425     if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
426     {
427         set_registry_variables( hkey, REG_SZ );
428         set_registry_variables( hkey, REG_EXPAND_SZ );
429         NtClose( hkey );
430     }
431
432     RtlInitUnicodeString( &nameW, volatile_envW );
433     if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
434     {
435         set_registry_variables( hkey, REG_SZ );
436         set_registry_variables( hkey, REG_EXPAND_SZ );
437         NtClose( hkey );
438     }
439
440     NtClose( attr.RootDirectory );
441     return ret;
442 }
443
444
445 /***********************************************************************
446  *           get_reg_value
447  */
448 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
449 {
450     char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
451     KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
452     DWORD len, size = sizeof(buffer);
453     WCHAR *ret = NULL;
454     UNICODE_STRING nameW;
455
456     RtlInitUnicodeString( &nameW, name );
457     if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
458         return NULL;
459
460     if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
461     len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
462
463     if (info->Type == REG_EXPAND_SZ)
464     {
465         UNICODE_STRING value, expanded;
466
467         value.MaximumLength = len * sizeof(WCHAR);
468         value.Buffer = (WCHAR *)info->Data;
469         if (!value.Buffer[len - 1]) len--;  /* don't count terminating null if any */
470         value.Length = len * sizeof(WCHAR);
471         expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
472         if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
473         if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
474         else RtlFreeUnicodeString( &expanded );
475     }
476     else if (info->Type == REG_SZ)
477     {
478         if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
479         {
480             memcpy( ret, info->Data, len * sizeof(WCHAR) );
481             ret[len] = 0;
482         }
483     }
484     return ret;
485 }
486
487
488 /***********************************************************************
489  *           set_additional_environment
490  *
491  * Set some additional environment variables not specified in the registry.
492  */
493 static void set_additional_environment(void)
494 {
495     static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
496                                          'S','o','f','t','w','a','r','e','\\',
497                                          'M','i','c','r','o','s','o','f','t','\\',
498                                          'W','i','n','d','o','w','s',' ','N','T','\\',
499                                          'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
500                                          'P','r','o','f','i','l','e','L','i','s','t',0};
501     static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
502     static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
503     static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
504     OBJECT_ATTRIBUTES attr;
505     UNICODE_STRING nameW;
506     WCHAR *profile_dir = NULL, *all_users_dir = NULL;
507     HANDLE hkey;
508     DWORD len;
509
510     /* set the ALLUSERSPROFILE variables */
511
512     attr.Length = sizeof(attr);
513     attr.RootDirectory = 0;
514     attr.ObjectName = &nameW;
515     attr.Attributes = 0;
516     attr.SecurityDescriptor = NULL;
517     attr.SecurityQualityOfService = NULL;
518     RtlInitUnicodeString( &nameW, profile_keyW );
519     if (!NtOpenKey( &hkey, KEY_READ, &attr ))
520     {
521         profile_dir = get_reg_value( hkey, profiles_valueW );
522         all_users_dir = get_reg_value( hkey, all_users_valueW );
523         NtClose( hkey );
524     }
525
526     if (profile_dir && all_users_dir)
527     {
528         WCHAR *value, *p;
529
530         len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
531         value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
532         strcpyW( value, profile_dir );
533         p = value + strlenW(value);
534         if (p > value && p[-1] != '\\') *p++ = '\\';
535         strcpyW( p, all_users_dir );
536         SetEnvironmentVariableW( allusersW, value );
537         HeapFree( GetProcessHeap(), 0, value );
538     }
539
540     HeapFree( GetProcessHeap(), 0, all_users_dir );
541     HeapFree( GetProcessHeap(), 0, profile_dir );
542 }
543
544 /***********************************************************************
545  *           set_wow64_environment
546  *
547  * Set the environment variables that change across 32/64/Wow64.
548  */
549 static void set_wow64_environment(void)
550 {
551     static const WCHAR archW[]    = {'P','R','O','C','E','S','S','O','R','_','A','R','C','H','I','T','E','C','T','U','R','E',0};
552     static const WCHAR arch6432W[] = {'P','R','O','C','E','S','S','O','R','_','A','R','C','H','I','T','E','W','6','4','3','2',0};
553     static const WCHAR x86W[] = {'x','8','6',0};
554     static const WCHAR versionW[] = {'M','a','c','h','i','n','e','\\',
555                                      'S','o','f','t','w','a','r','e','\\',
556                                      'M','i','c','r','o','s','o','f','t','\\',
557                                      'W','i','n','d','o','w','s','\\',
558                                      'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
559     static const WCHAR progdirW[]   = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
560     static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
561     static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
562     static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
563     static const WCHAR commondirW[]   = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
564     static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
565     static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
566     static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
567
568     OBJECT_ATTRIBUTES attr;
569     UNICODE_STRING nameW;
570     WCHAR arch[64];
571     WCHAR *value;
572     HANDLE hkey;
573
574     /* set the PROCESSOR_ARCHITECTURE variable */
575
576     if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
577     {
578         if (is_win64)
579         {
580             SetEnvironmentVariableW( archW, arch );
581             SetEnvironmentVariableW( arch6432W, NULL );
582         }
583     }
584     else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
585     {
586         if (is_wow64)
587         {
588             SetEnvironmentVariableW( arch6432W, arch );
589             SetEnvironmentVariableW( archW, x86W );
590         }
591     }
592
593     attr.Length = sizeof(attr);
594     attr.RootDirectory = 0;
595     attr.ObjectName = &nameW;
596     attr.Attributes = 0;
597     attr.SecurityDescriptor = NULL;
598     attr.SecurityQualityOfService = NULL;
599     RtlInitUnicodeString( &nameW, versionW );
600     if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
601
602     /* set the ProgramFiles variables */
603
604     if ((value = get_reg_value( hkey, progdirW )))
605     {
606         if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
607         if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
608         HeapFree( GetProcessHeap(), 0, value );
609     }
610     if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
611     {
612         SetEnvironmentVariableW( progfilesW, value );
613         HeapFree( GetProcessHeap(), 0, value );
614     }
615
616     /* set the CommonProgramFiles variables */
617
618     if ((value = get_reg_value( hkey, commondirW )))
619     {
620         if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
621         if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
622         HeapFree( GetProcessHeap(), 0, value );
623     }
624     if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
625     {
626         SetEnvironmentVariableW( commonfilesW, value );
627         HeapFree( GetProcessHeap(), 0, value );
628     }
629
630     NtClose( hkey );
631 }
632
633 /***********************************************************************
634  *              set_library_wargv
635  *
636  * Set the Wine library Unicode argv global variables.
637  */
638 static void set_library_wargv( char **argv )
639 {
640     int argc;
641     char *q;
642     WCHAR *p;
643     WCHAR **wargv;
644     DWORD total = 0;
645
646     for (argc = 0; argv[argc]; argc++)
647         total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
648
649     wargv = RtlAllocateHeap( GetProcessHeap(), 0,
650                              total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
651     p = (WCHAR *)(wargv + argc + 1);
652     for (argc = 0; argv[argc]; argc++)
653     {
654         DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
655         wargv[argc] = p;
656         p += reslen;
657         total -= reslen;
658     }
659     wargv[argc] = NULL;
660
661     /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
662
663     for (argc = 0; wargv[argc]; argc++)
664         total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
665
666     argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
667     q = (char *)(argv + argc + 1);
668     for (argc = 0; wargv[argc]; argc++)
669     {
670         DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
671         argv[argc] = q;
672         q += reslen;
673         total -= reslen;
674     }
675     argv[argc] = NULL;
676
677     __wine_main_argc = argc;
678     __wine_main_argv = argv;
679     __wine_main_wargv = wargv;
680 }
681
682
683 /***********************************************************************
684  *              update_library_argv0
685  *
686  * Update the argv[0] global variable with the binary we have found.
687  */
688 static void update_library_argv0( const WCHAR *argv0 )
689 {
690     DWORD len = strlenW( argv0 );
691
692     if (len > strlenW( __wine_main_wargv[0] ))
693     {
694         __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
695     }
696     strcpyW( __wine_main_wargv[0], argv0 );
697
698     len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
699     if (len > strlen( __wine_main_argv[0] ) + 1)
700     {
701         __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
702     }
703     WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
704 }
705
706
707 /***********************************************************************
708  *           build_command_line
709  *
710  * Build the command line of a process from the argv array.
711  *
712  * Note that it does NOT necessarily include the file name.
713  * Sometimes we don't even have any command line options at all.
714  *
715  * We must quote and escape characters so that the argv array can be rebuilt
716  * from the command line:
717  * - spaces and tabs must be quoted
718  *   'a b'   -> '"a b"'
719  * - quotes must be escaped
720  *   '"'     -> '\"'
721  * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
722  *   resulting in an odd number of '\' followed by a '"'
723  *   '\"'    -> '\\\"'
724  *   '\\"'   -> '\\\\\"'
725  * - '\'s that are not followed by a '"' can be left as is
726  *   'a\b'   == 'a\b'
727  *   'a\\b'  == 'a\\b'
728  */
729 static BOOL build_command_line( WCHAR **argv )
730 {
731     int len;
732     WCHAR **arg;
733     LPWSTR p;
734     RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
735
736     if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
737
738     len = 0;
739     for (arg = argv; *arg; arg++)
740     {
741         int has_space,bcount;
742         WCHAR* a;
743
744         has_space=0;
745         bcount=0;
746         a=*arg;
747         if( !*a ) has_space=1;
748         while (*a!='\0') {
749             if (*a=='\\') {
750                 bcount++;
751             } else {
752                 if (*a==' ' || *a=='\t') {
753                     has_space=1;
754                 } else if (*a=='"') {
755                     /* doubling of '\' preceding a '"',
756                      * plus escaping of said '"'
757                      */
758                     len+=2*bcount+1;
759                 }
760                 bcount=0;
761             }
762             a++;
763         }
764         len+=(a-*arg)+1 /* for the separating space */;
765         if (has_space)
766             len+=2; /* for the quotes */
767     }
768
769     if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
770         return FALSE;
771
772     p = rupp->CommandLine.Buffer;
773     rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
774     rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
775     for (arg = argv; *arg; arg++)
776     {
777         int has_space,has_quote;
778         WCHAR* a;
779
780         /* Check for quotes and spaces in this argument */
781         has_space=has_quote=0;
782         a=*arg;
783         if( !*a ) has_space=1;
784         while (*a!='\0') {
785             if (*a==' ' || *a=='\t') {
786                 has_space=1;
787                 if (has_quote)
788                     break;
789             } else if (*a=='"') {
790                 has_quote=1;
791                 if (has_space)
792                     break;
793             }
794             a++;
795         }
796
797         /* Now transfer it to the command line */
798         if (has_space)
799             *p++='"';
800         if (has_quote) {
801             int bcount;
802             WCHAR* a;
803
804             bcount=0;
805             a=*arg;
806             while (*a!='\0') {
807                 if (*a=='\\') {
808                     *p++=*a;
809                     bcount++;
810                 } else {
811                     if (*a=='"') {
812                         int i;
813
814                         /* Double all the '\\' preceding this '"', plus one */
815                         for (i=0;i<=bcount;i++)
816                             *p++='\\';
817                         *p++='"';
818                     } else {
819                         *p++=*a;
820                     }
821                     bcount=0;
822                 }
823                 a++;
824             }
825         } else {
826             WCHAR* x = *arg;
827             while ((*p=*x++)) p++;
828         }
829         if (has_space)
830             *p++='"';
831         *p++=' ';
832     }
833     if (p > rupp->CommandLine.Buffer)
834         p--;  /* remove last space */
835     *p = '\0';
836
837     return TRUE;
838 }
839
840
841 /***********************************************************************
842  *           init_current_directory
843  *
844  * Initialize the current directory from the Unix cwd or the parent info.
845  */
846 static void init_current_directory( CURDIR *cur_dir )
847 {
848     UNICODE_STRING dir_str;
849     const char *pwd;
850     char *cwd;
851     int size;
852
853     /* if we received a cur dir from the parent, try this first */
854
855     if (cur_dir->DosPath.Length)
856     {
857         if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
858     }
859
860     /* now try to get it from the Unix cwd */
861
862     for (size = 256; ; size *= 2)
863     {
864         if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
865         if (getcwd( cwd, size )) break;
866         HeapFree( GetProcessHeap(), 0, cwd );
867         if (errno == ERANGE) continue;
868         cwd = NULL;
869         break;
870     }
871
872     /* try to use PWD if it is valid, so that we don't resolve symlinks */
873
874     pwd = getenv( "PWD" );
875     if (cwd)
876     {
877         struct stat st1, st2;
878
879         if (!pwd || stat( pwd, &st1 ) == -1 ||
880             (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
881             pwd = cwd;
882     }
883
884     if (pwd)
885     {
886         ANSI_STRING unix_name;
887         UNICODE_STRING nt_name;
888         RtlInitAnsiString( &unix_name, pwd );
889         if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
890         {
891             UNICODE_STRING dos_path;
892             /* skip the \??\ prefix, nt_name is 0 terminated */
893             RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
894             RtlSetCurrentDirectory_U( &dos_path );
895             RtlFreeUnicodeString( &nt_name );
896         }
897     }
898
899     if (!cur_dir->DosPath.Length)  /* still not initialized */
900     {
901         MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
902                 "starting in the Windows directory.\n", cwd ? cwd : "" );
903         RtlInitUnicodeString( &dir_str, DIR_Windows );
904         RtlSetCurrentDirectory_U( &dir_str );
905     }
906     HeapFree( GetProcessHeap(), 0, cwd );
907
908 done:
909     if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
910     TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
911 }
912
913
914 /***********************************************************************
915  *           init_windows_dirs
916  *
917  * Initialize the windows and system directories from the environment.
918  */
919 static void init_windows_dirs(void)
920 {
921     extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
922
923     static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
924     static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
925     static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
926     static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
927     static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
928
929     DWORD len;
930     WCHAR *buffer;
931
932     if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
933     {
934         buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
935         GetEnvironmentVariableW( windirW, buffer, len );
936         DIR_Windows = buffer;
937     }
938     else DIR_Windows = default_windirW;
939
940     if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
941     {
942         buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
943         GetEnvironmentVariableW( winsysdirW, buffer, len );
944         DIR_System = buffer;
945     }
946     else
947     {
948         len = strlenW( DIR_Windows );
949         buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
950         memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
951         memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
952         DIR_System = buffer;
953     }
954
955     if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
956         ERR( "directory %s could not be created, error %u\n",
957              debugstr_w(DIR_Windows), GetLastError() );
958     if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
959         ERR( "directory %s could not be created, error %u\n",
960              debugstr_w(DIR_System), GetLastError() );
961
962     if (is_win64 || is_wow64)   /* SysWow64 is always defined on 64-bit */
963     {
964         len = strlenW( DIR_Windows );
965         buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
966         memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
967         memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
968         DIR_SysWow64 = buffer;
969         if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
970             ERR( "directory %s could not be created, error %u\n",
971                  debugstr_w(DIR_SysWow64), GetLastError() );
972     }
973
974     TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
975     TRACE_(file)( "SystemDir  = %s\n", debugstr_w(DIR_System) );
976
977     /* set the directories in ntdll too */
978     __wine_init_windows_dir( DIR_Windows, DIR_System );
979 }
980
981
982 /***********************************************************************
983  *           start_wineboot
984  *
985  * Start the wineboot process if necessary. Return the handles to wait on.
986  */
987 static void start_wineboot( HANDLE handles[2] )
988 {
989     static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
990
991     handles[1] = 0;
992     if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
993     {
994         ERR( "failed to create wineboot event, expect trouble\n" );
995         return;
996     }
997     if (GetLastError() != ERROR_ALREADY_EXISTS)  /* we created it */
998     {
999         static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1000         static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1001         STARTUPINFOW si;
1002         PROCESS_INFORMATION pi;
1003         void *redir;
1004         WCHAR app[MAX_PATH];
1005         WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1006
1007         memset( &si, 0, sizeof(si) );
1008         si.cb = sizeof(si);
1009         si.dwFlags = STARTF_USESTDHANDLES;
1010         si.hStdInput  = 0;
1011         si.hStdOutput = 0;
1012         si.hStdError  = GetStdHandle( STD_ERROR_HANDLE );
1013
1014         GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1015         lstrcatW( app, wineboot );
1016
1017         Wow64DisableWow64FsRedirection( &redir );
1018         strcpyW( cmdline, app );
1019         strcatW( cmdline, args );
1020         if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1021         {
1022             TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1023             CloseHandle( pi.hThread );
1024             handles[1] = pi.hProcess;
1025         }
1026         else
1027         {
1028             ERR( "failed to start wineboot, err %u\n", GetLastError() );
1029             CloseHandle( handles[0] );
1030             handles[0] = 0;
1031         }
1032         Wow64RevertWow64FsRedirection( redir );
1033     }
1034 }
1035
1036
1037 #ifdef __i386__
1038 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1039 __ASM_GLOBAL_FUNC( call_process_entry,
1040                     "pushl %ebp\n\t"
1041                     __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1042                     __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1043                     "movl %esp,%ebp\n\t"
1044                     __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1045                     "subl $12,%esp\n\t"  /* deliberately mis-align the stack by 8, Doom 3 needs this */
1046                     "pushl 8(%ebp)\n\t"
1047                     "call *12(%ebp)\n\t"
1048                     "leave\n\t"
1049                     __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1050                     __ASM_CFI(".cfi_same_value %ebp\n\t")
1051                     "ret" )
1052 #else
1053 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1054 {
1055     return entry( peb );
1056 }
1057 #endif
1058
1059 /***********************************************************************
1060  *           start_process
1061  *
1062  * Startup routine of a new process. Runs on the new process stack.
1063  */
1064 static DWORD WINAPI start_process( PEB *peb )
1065 {
1066     IMAGE_NT_HEADERS *nt;
1067     LPTHREAD_START_ROUTINE entry;
1068
1069     nt = RtlImageNtHeader( peb->ImageBaseAddress );
1070     entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1071                                      nt->OptionalHeader.AddressOfEntryPoint);
1072
1073     if (!nt->OptionalHeader.AddressOfEntryPoint)
1074     {
1075         ERR( "%s doesn't have an entry point, it cannot be executed\n",
1076              debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1077         ExitThread( 1 );
1078     }
1079
1080     if (TRACE_ON(relay))
1081         DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1082                  debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1083
1084     SetLastError( 0 );  /* clear error code */
1085     if (peb->BeingDebugged) DbgBreakPoint();
1086     return call_process_entry( peb, entry );
1087 }
1088
1089
1090 /***********************************************************************
1091  *           set_process_name
1092  *
1093  * Change the process name in the ps output.
1094  */
1095 static void set_process_name( int argc, char *argv[] )
1096 {
1097 #ifdef HAVE_SETPROCTITLE
1098     setproctitle("-%s", argv[1]);
1099 #endif
1100
1101 #ifdef HAVE_PRCTL
1102     int i, offset;
1103     char *p, *prctl_name = argv[1];
1104     char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1105
1106 #ifndef PR_SET_NAME
1107 # define PR_SET_NAME 15
1108 #endif
1109
1110     if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1111     if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1112
1113     if (prctl( PR_SET_NAME, prctl_name ) != -1)
1114     {
1115         offset = argv[1] - argv[0];
1116         memmove( argv[1] - offset, argv[1], end - argv[1] );
1117         memset( end - offset, 0, offset );
1118         for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1119         argv[i-1] = NULL;
1120     }
1121     else
1122 #endif  /* HAVE_PRCTL */
1123     {
1124         /* remove argv[0] */
1125         memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1126     }
1127 }
1128
1129
1130 /***********************************************************************
1131  *           __wine_kernel_init
1132  *
1133  * Wine initialisation: load and start the main exe file.
1134  */
1135 void CDECL __wine_kernel_init(void)
1136 {
1137     static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1138     static const WCHAR dotW[] = {'.',0};
1139
1140     WCHAR *p, main_exe_name[MAX_PATH+1];
1141     PEB *peb = NtCurrentTeb()->Peb;
1142     RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1143     HANDLE boot_events[2];
1144     BOOL got_environment = TRUE;
1145
1146     /* Initialize everything */
1147
1148     setbuf(stdout,NULL);
1149     setbuf(stderr,NULL);
1150     kernel32_handle = GetModuleHandleW(kernel32W);
1151     IsWow64Process( GetCurrentProcess(), &is_wow64 );
1152
1153     LOCALE_Init();
1154
1155     if (!params->Environment)
1156     {
1157         /* Copy the parent environment */
1158         if (!build_initial_environment()) exit(1);
1159
1160         /* convert old configuration to new format */
1161         convert_old_config();
1162
1163         got_environment = set_registry_environment( FALSE );
1164         set_additional_environment();
1165     }
1166
1167     init_windows_dirs();
1168     init_current_directory( &params->CurrentDirectory );
1169
1170     set_process_name( __wine_main_argc, __wine_main_argv );
1171     set_library_wargv( __wine_main_argv );
1172     boot_events[0] = boot_events[1] = 0;
1173
1174     if (peb->ProcessParameters->ImagePathName.Buffer)
1175     {
1176         strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1177     }
1178     else
1179     {
1180         struct binary_info binary_info;
1181
1182         if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1183             !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1184         {
1185             MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1186             ExitProcess( GetLastError() );
1187         }
1188         update_library_argv0( main_exe_name );
1189         if (!build_command_line( __wine_main_wargv )) goto error;
1190         start_wineboot( boot_events );
1191     }
1192
1193     /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1194     p = strrchrW( main_exe_name, '.' );
1195     if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1196
1197     TRACE( "starting process name=%s argv[0]=%s\n",
1198            debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1199
1200     RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1201                           MODULE_get_dll_load_path(main_exe_name) );
1202
1203     if (boot_events[0])
1204     {
1205         DWORD timeout = 2 * 60 * 1000, count = 1;
1206
1207         if (boot_events[1]) count++;
1208         if (!got_environment) timeout = 5 * 60 * 1000;  /* initial prefix creation can take longer */
1209         if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1210             ERR( "boot event wait timed out\n" );
1211         CloseHandle( boot_events[0] );
1212         if (boot_events[1]) CloseHandle( boot_events[1] );
1213         /* reload environment now that wineboot has run */
1214         set_registry_environment( got_environment );
1215         set_additional_environment();
1216     }
1217     set_wow64_environment();
1218
1219     if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1220     {
1221         DWORD_PTR args[1];
1222         WCHAR msgW[1024];
1223         char msg[1024];
1224         DWORD error = GetLastError();
1225
1226         /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1227         if (error == ERROR_BAD_EXE_FORMAT ||
1228             error == ERROR_INVALID_ADDRESS ||
1229             error == ERROR_NOT_ENOUGH_MEMORY)
1230         {
1231             if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1232             /* if we get back here, it failed */
1233         }
1234         else if (error == ERROR_MOD_NOT_FOUND)
1235         {
1236             if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1237             else p = main_exe_name;
1238             if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1239             {
1240                 /* args 1 and 2 are --app-name full_path */
1241                 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1242                          debugstr_w(__wine_main_wargv[3]) );
1243                 ExitProcess( ERROR_BAD_EXE_FORMAT );
1244             }
1245             MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1246             ExitProcess( ERROR_FILE_NOT_FOUND );
1247         }
1248         args[0] = (DWORD_PTR)main_exe_name;
1249         FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1250                         NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1251         WideCharToMultiByte( CP_ACP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1252         MESSAGE( "wine: %s", msg );
1253         ExitProcess( error );
1254     }
1255
1256     LdrInitializeThunk( start_process, 0, 0, 0 );
1257
1258  error:
1259     ExitProcess( GetLastError() );
1260 }
1261
1262
1263 /***********************************************************************
1264  *           build_argv
1265  *
1266  * Build an argv array from a command-line.
1267  * 'reserved' is the number of args to reserve before the first one.
1268  */
1269 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1270 {
1271     int argc;
1272     char** argv;
1273     char *arg,*s,*d,*cmdline;
1274     int in_quotes,bcount,len;
1275
1276     len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1277     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1278     WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1279
1280     argc=reserved+1;
1281     bcount=0;
1282     in_quotes=0;
1283     s=cmdline;
1284     while (1) {
1285         if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1286             /* space */
1287             argc++;
1288             /* skip the remaining spaces */
1289             while (*s==' ' || *s=='\t') {
1290                 s++;
1291             }
1292             if (*s=='\0')
1293                 break;
1294             bcount=0;
1295             continue;
1296         } else if (*s=='\\') {
1297             /* '\', count them */
1298             bcount++;
1299         } else if ((*s=='"') && ((bcount & 1)==0)) {
1300             /* unescaped '"' */
1301             in_quotes=!in_quotes;
1302             bcount=0;
1303         } else {
1304             /* a regular character */
1305             bcount=0;
1306         }
1307         s++;
1308     }
1309     if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1310     {
1311         HeapFree( GetProcessHeap(), 0, cmdline );
1312         return NULL;
1313     }
1314
1315     arg = d = s = (char *)(argv + argc);
1316     memcpy( d, cmdline, len );
1317     bcount=0;
1318     in_quotes=0;
1319     argc=reserved;
1320     while (*s) {
1321         if ((*s==' ' || *s=='\t') && !in_quotes) {
1322             /* Close the argument and copy it */
1323             *d=0;
1324             argv[argc++]=arg;
1325
1326             /* skip the remaining spaces */
1327             do {
1328                 s++;
1329             } while (*s==' ' || *s=='\t');
1330
1331             /* Start with a new argument */
1332             arg=d=s;
1333             bcount=0;
1334         } else if (*s=='\\') {
1335             /* '\\' */
1336             *d++=*s++;
1337             bcount++;
1338         } else if (*s=='"') {
1339             /* '"' */
1340             if ((bcount & 1)==0) {
1341                 /* Preceded by an even number of '\', this is half that
1342                  * number of '\', plus a '"' which we discard.
1343                  */
1344                 d-=bcount/2;
1345                 s++;
1346                 in_quotes=!in_quotes;
1347             } else {
1348                 /* Preceded by an odd number of '\', this is half that
1349                  * number of '\' followed by a '"'
1350                  */
1351                 d=d-bcount/2-1;
1352                 *d++='"';
1353                 s++;
1354             }
1355             bcount=0;
1356         } else {
1357             /* a regular character */
1358             *d++=*s++;
1359             bcount=0;
1360         }
1361     }
1362     if (*arg) {
1363         *d='\0';
1364         argv[argc++]=arg;
1365     }
1366     argv[argc]=NULL;
1367
1368     HeapFree( GetProcessHeap(), 0, cmdline );
1369     return argv;
1370 }
1371
1372
1373 /***********************************************************************
1374  *           build_envp
1375  *
1376  * Build the environment of a new child process.
1377  */
1378 static char **build_envp( const WCHAR *envW )
1379 {
1380     static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1381
1382     const WCHAR *end;
1383     char **envp;
1384     char *env, *p;
1385     int count = 1, length;
1386     unsigned int i;
1387
1388     for (end = envW; *end; count++) end += strlenW(end) + 1;
1389     end++;
1390     length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1391     if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1392     WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1393
1394     for (p = env; *p; p += strlen(p) + 1)
1395         if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1396
1397     for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1398     {
1399         if (!(p = getenv(unix_vars[i]))) continue;
1400         length += strlen(unix_vars[i]) + strlen(p) + 2;
1401         count++;
1402     }
1403
1404     if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1405     {
1406         char **envptr = envp;
1407         char *dst = (char *)(envp + count);
1408
1409         /* some variables must not be modified, so we get them directly from the unix env */
1410         for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1411         {
1412             if (!(p = getenv(unix_vars[i]))) continue;
1413             *envptr++ = strcpy( dst, unix_vars[i] );
1414             strcat( dst, "=" );
1415             strcat( dst, p );
1416             dst += strlen(dst) + 1;
1417         }
1418
1419         /* now put the Windows environment strings */
1420         for (p = env; *p; p += strlen(p) + 1)
1421         {
1422             if (*p == '=') continue;  /* skip drive curdirs, this crashes some unix apps */
1423             if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1424             if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1425             if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1426             if (is_special_env_var( p ))  /* prefix it with "WINE" */
1427             {
1428                 *envptr++ = strcpy( dst, "WINE" );
1429                 strcat( dst, p );
1430             }
1431             else
1432             {
1433                 *envptr++ = strcpy( dst, p );
1434             }
1435             dst += strlen(dst) + 1;
1436         }
1437         *envptr = 0;
1438     }
1439     HeapFree( GetProcessHeap(), 0, env );
1440     return envp;
1441 }
1442
1443
1444 /***********************************************************************
1445  *           fork_and_exec
1446  *
1447  * Fork and exec a new Unix binary, checking for errors.
1448  */
1449 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1450                           const char *newdir, DWORD flags, STARTUPINFOW *startup )
1451 {
1452     int fd[2], stdin_fd = -1, stdout_fd = -1;
1453     int pid, err;
1454     char **argv, **envp;
1455
1456     if (!env) env = GetEnvironmentStringsW();
1457
1458 #ifdef HAVE_PIPE2
1459     if (pipe2( fd, O_CLOEXEC ) == -1)
1460 #endif
1461     {
1462         if (pipe(fd) == -1)
1463         {
1464             SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1465             return -1;
1466         }
1467         fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1468         fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1469     }
1470
1471     if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1472     {
1473         HANDLE hstdin, hstdout;
1474
1475         if (startup->dwFlags & STARTF_USESTDHANDLES)
1476         {
1477             hstdin = startup->hStdInput;
1478             hstdout = startup->hStdOutput;
1479         }
1480         else
1481         {
1482             hstdin = GetStdHandle(STD_INPUT_HANDLE);
1483             hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1484         }
1485
1486         if (is_console_handle( hstdin ))
1487             hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1488         if (is_console_handle( hstdout ))
1489             hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1490         wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1491         wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1492     }
1493
1494     argv = build_argv( cmdline, 0 );
1495     envp = build_envp( env );
1496
1497     if (!(pid = fork()))  /* child */
1498     {
1499         close( fd[0] );
1500
1501         if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1502         {
1503             int pid;
1504             if (!(pid = fork()))
1505             {
1506                 int fd = open( "/dev/null", O_RDWR );
1507                 setsid();
1508                 /* close stdin and stdout */
1509                 if (fd != -1)
1510                 {
1511                     dup2( fd, 0 );
1512                     dup2( fd, 1 );
1513                     close( fd );
1514                 }
1515             }
1516             else if (pid != -1) _exit(0);  /* parent */
1517         }
1518         else
1519         {
1520             if (stdin_fd != -1)
1521             {
1522                 dup2( stdin_fd, 0 );
1523                 close( stdin_fd );
1524             }
1525             if (stdout_fd != -1)
1526             {
1527                 dup2( stdout_fd, 1 );
1528                 close( stdout_fd );
1529             }
1530         }
1531
1532         /* Reset signals that we previously set to SIG_IGN */
1533         signal( SIGPIPE, SIG_DFL );
1534         signal( SIGCHLD, SIG_DFL );
1535
1536         if (newdir) chdir(newdir);
1537
1538         if (argv && envp) execve( filename, argv, envp );
1539         err = errno;
1540         write( fd[1], &err, sizeof(err) );
1541         _exit(1);
1542     }
1543     HeapFree( GetProcessHeap(), 0, argv );
1544     HeapFree( GetProcessHeap(), 0, envp );
1545     if (stdin_fd != -1) close( stdin_fd );
1546     if (stdout_fd != -1) close( stdout_fd );
1547     close( fd[1] );
1548     if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0))  /* exec failed */
1549     {
1550         errno = err;
1551         pid = -1;
1552     }
1553     if (pid == -1) FILE_SetDosError();
1554     close( fd[0] );
1555     return pid;
1556 }
1557
1558
1559 static inline DWORD append_string( void **ptr, const WCHAR *str )
1560 {
1561     DWORD len = strlenW( str );
1562     memcpy( *ptr, str, len * sizeof(WCHAR) );
1563     *ptr = (WCHAR *)*ptr + len;
1564     return len * sizeof(WCHAR);
1565 }
1566
1567 /***********************************************************************
1568  *           create_startup_info
1569  */
1570 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1571                                             LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1572                                             const STARTUPINFOW *startup, DWORD *info_size )
1573 {
1574     const RTL_USER_PROCESS_PARAMETERS *cur_params;
1575     const WCHAR *title;
1576     startup_info_t *info;
1577     DWORD size;
1578     void *ptr;
1579     UNICODE_STRING newdir;
1580     WCHAR imagepath[MAX_PATH];
1581     HANDLE hstdin, hstdout, hstderr;
1582
1583     if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1584         lstrcpynW( imagepath, filename, MAX_PATH );
1585     if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1586         lstrcpynW( imagepath, filename, MAX_PATH );
1587
1588     cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1589
1590     newdir.Buffer = NULL;
1591     if (cur_dir)
1592     {
1593         if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1594             cur_dir = newdir.Buffer + 4;  /* skip \??\ prefix */
1595         else
1596             cur_dir = NULL;
1597     }
1598     if (!cur_dir)
1599     {
1600         if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
1601             cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1602         else
1603             cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1604     }
1605     title = startup->lpTitle ? startup->lpTitle : imagepath;
1606
1607     size = sizeof(*info);
1608     size += strlenW( cur_dir ) * sizeof(WCHAR);
1609     size += cur_params->DllPath.Length;
1610     size += strlenW( imagepath ) * sizeof(WCHAR);
1611     size += strlenW( cmdline ) * sizeof(WCHAR);
1612     size += strlenW( title ) * sizeof(WCHAR);
1613     if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1614     /* FIXME: shellinfo */
1615     if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1616     size = (size + 1) & ~1;
1617     *info_size = size;
1618
1619     if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1620
1621     info->console_flags = cur_params->ConsoleFlags;
1622     if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1623     if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1624
1625     if (startup->dwFlags & STARTF_USESTDHANDLES)
1626     {
1627         hstdin  = startup->hStdInput;
1628         hstdout = startup->hStdOutput;
1629         hstderr = startup->hStdError;
1630     }
1631     else
1632     {
1633         hstdin  = GetStdHandle( STD_INPUT_HANDLE );
1634         hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1635         hstderr = GetStdHandle( STD_ERROR_HANDLE );
1636     }
1637     info->hstdin  = wine_server_obj_handle( hstdin );
1638     info->hstdout = wine_server_obj_handle( hstdout );
1639     info->hstderr = wine_server_obj_handle( hstderr );
1640     if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1641     {
1642         /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1643         if (is_console_handle(hstdin))  info->hstdin  = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1644         if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1645         if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1646     }
1647     else
1648     {
1649         if (is_console_handle(hstdin))  info->hstdin  = console_handle_unmap(hstdin);
1650         if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1651         if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1652     }
1653
1654     info->x         = startup->dwX;
1655     info->y         = startup->dwY;
1656     info->xsize     = startup->dwXSize;
1657     info->ysize     = startup->dwYSize;
1658     info->xchars    = startup->dwXCountChars;
1659     info->ychars    = startup->dwYCountChars;
1660     info->attribute = startup->dwFillAttribute;
1661     info->flags     = startup->dwFlags;
1662     info->show      = startup->wShowWindow;
1663
1664     ptr = info + 1;
1665     info->curdir_len = append_string( &ptr, cur_dir );
1666     info->dllpath_len = cur_params->DllPath.Length;
1667     memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1668     ptr = (char *)ptr + cur_params->DllPath.Length;
1669     info->imagepath_len = append_string( &ptr, imagepath );
1670     info->cmdline_len = append_string( &ptr, cmdline );
1671     info->title_len = append_string( &ptr, title );
1672     if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1673     if (startup->lpReserved2 && startup->cbReserved2)
1674     {
1675         info->runtime_len = startup->cbReserved2;
1676         memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1677     }
1678
1679 done:
1680     RtlFreeUnicodeString( &newdir );
1681     return info;
1682 }
1683
1684 /***********************************************************************
1685  *           get_alternate_loader
1686  *
1687  * Get the name of the alternate (32 or 64 bit) Wine loader.
1688  */
1689 static const char *get_alternate_loader( char **ret_env )
1690 {
1691     char *env;
1692     const char *loader = NULL;
1693     const char *loader_env = getenv( "WINELOADER" );
1694
1695     *ret_env = NULL;
1696
1697     if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1698
1699     if (loader_env)
1700     {
1701         int len = strlen( loader_env );
1702         if (!is_win64)
1703         {
1704             if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1705             strcpy( env, "WINELOADER=" );
1706             strcat( env, loader_env );
1707             strcat( env, "64" );
1708         }
1709         else
1710         {
1711             if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1712             strcpy( env, "WINELOADER=" );
1713             strcat( env, loader_env );
1714             len += sizeof("WINELOADER=") - 1;
1715             if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1716         }
1717         if (!loader)
1718         {
1719             if ((loader = strrchr( env, '/' ))) loader++;
1720             else loader = env;
1721         }
1722         *ret_env = env;
1723     }
1724     if (!loader) loader = is_win64 ? "wine" : "wine64";
1725     return loader;
1726 }
1727
1728 #ifdef __APPLE__
1729 /***********************************************************************
1730  *           terminate_main_thread
1731  *
1732  * On some versions of Mac OS X, the execve system call fails with
1733  * ENOTSUP if the process has multiple threads.  Wine is always multi-
1734  * threaded on Mac OS X because it specifically reserves the main thread
1735  * for use by the system frameworks (see apple_main_thread() in
1736  * libs/wine/loader.c).  So, when we need to exec without first forking,
1737  * we need to terminate the main thread first.  We do this by installing
1738  * a custom run loop source onto the main run loop and signaling it.
1739  * The source's "perform" callback is pthread_exit and it will be
1740  * executed on the main thread, terminating it.
1741  *
1742  * Returns TRUE if there's still hope the main thread has terminated or
1743  * will soon.  Return FALSE if we've given up.
1744  */
1745 static BOOL terminate_main_thread(void)
1746 {
1747     static int delayms;
1748
1749     if (!delayms)
1750     {
1751         CFRunLoopSourceContext source_context = { 0 };
1752         CFRunLoopSourceRef source;
1753
1754         source_context.perform = pthread_exit;
1755         if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1756             return FALSE;
1757
1758         CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1759         CFRunLoopSourceSignal( source );
1760         CFRunLoopWakeUp( CFRunLoopGetMain() );
1761         CFRelease( source );
1762
1763         delayms = 20;
1764     }
1765
1766     if (delayms > 1000)
1767         return FALSE;
1768
1769     usleep(delayms * 1000);
1770     delayms *= 2;
1771
1772     return TRUE;
1773 }
1774 #endif
1775
1776 /***********************************************************************
1777  *           create_process
1778  *
1779  * Create a new process. If hFile is a valid handle we have an exe
1780  * file, otherwise it is a Winelib app.
1781  */
1782 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1783                             LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1784                             BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1785                             LPPROCESS_INFORMATION info, LPCSTR unixdir,
1786                             const struct binary_info *binary_info, int exec_only )
1787 {
1788     BOOL ret, success = FALSE;
1789     HANDLE process_info;
1790     WCHAR *env_end;
1791     char *winedebug = NULL;
1792     char *wineloader = NULL;
1793     const char *loader = NULL;
1794     char **argv;
1795     startup_info_t *startup_info;
1796     DWORD startup_info_size;
1797     int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1798     pid_t pid;
1799     int err;
1800
1801     if (!is_win64 && !is_wow64 && (binary_info->flags & BINARY_FLAG_64BIT))
1802     {
1803         ERR( "starting 64-bit process %s not supported in 32-bit wineprefix\n", debugstr_w(filename) );
1804         SetLastError( ERROR_BAD_EXE_FORMAT );
1805         return FALSE;
1806     }
1807
1808     RtlAcquirePebLock();
1809
1810     if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1811                                               &startup_info_size )))
1812     {
1813         RtlReleasePebLock();
1814         return FALSE;
1815     }
1816     if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
1817     env_end = env;
1818     while (*env_end)
1819     {
1820         static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1821         if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1822         {
1823             DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1824             if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1825                 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1826         }
1827         env_end += strlenW(env_end) + 1;
1828     }
1829     env_end++;
1830
1831     /* create the socket for the new process */
1832
1833     if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1834     {
1835         RtlReleasePebLock();
1836         HeapFree( GetProcessHeap(), 0, winedebug );
1837         HeapFree( GetProcessHeap(), 0, startup_info );
1838         SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1839         return FALSE;
1840     }
1841     wine_server_send_fd( socketfd[1] );
1842     close( socketfd[1] );
1843
1844     /* create the process on the server side */
1845
1846     SERVER_START_REQ( new_process )
1847     {
1848         req->inherit_all    = inherit;
1849         req->create_flags   = flags;
1850         req->socket_fd      = socketfd[1];
1851         req->exe_file       = wine_server_obj_handle( hFile );
1852         req->process_access = PROCESS_ALL_ACCESS;
1853         req->process_attr   = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1854         req->thread_access  = THREAD_ALL_ACCESS;
1855         req->thread_attr    = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1856         req->info_size      = startup_info_size;
1857
1858         wine_server_add_data( req, startup_info, startup_info_size );
1859         wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
1860         if ((ret = !wine_server_call_err( req )))
1861         {
1862             info->dwProcessId = (DWORD)reply->pid;
1863             info->dwThreadId  = (DWORD)reply->tid;
1864             info->hProcess    = wine_server_ptr_handle( reply->phandle );
1865             info->hThread     = wine_server_ptr_handle( reply->thandle );
1866         }
1867         process_info = wine_server_ptr_handle( reply->info );
1868     }
1869     SERVER_END_REQ;
1870
1871     RtlReleasePebLock();
1872     if (!ret)
1873     {
1874         close( socketfd[0] );
1875         HeapFree( GetProcessHeap(), 0, startup_info );
1876         HeapFree( GetProcessHeap(), 0, winedebug );
1877         return FALSE;
1878     }
1879
1880     if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1881     {
1882         if (startup_info->hstdin)
1883             wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
1884                                       FILE_READ_DATA, &stdin_fd, NULL );
1885         if (startup_info->hstdout)
1886             wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
1887                                       FILE_WRITE_DATA, &stdout_fd, NULL );
1888     }
1889     HeapFree( GetProcessHeap(), 0, startup_info );
1890
1891     /* create the child process */
1892     argv = build_argv( cmd_line, 1 );
1893
1894     if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1895         loader = get_alternate_loader( &wineloader );
1896
1897     if (exec_only || !(pid = fork()))  /* child */
1898     {
1899         char preloader_reserve[64], socket_env[64];
1900
1901         if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1902         {
1903             if (!(pid = fork()))
1904             {
1905                 int fd = open( "/dev/null", O_RDWR );
1906                 setsid();
1907                 /* close stdin and stdout */
1908                 if (fd != -1)
1909                 {
1910                     dup2( fd, 0 );
1911                     dup2( fd, 1 );
1912                     close( fd );
1913                 }
1914             }
1915             else if (pid != -1) _exit(0);  /* parent */
1916         }
1917         else
1918         {
1919             if (stdin_fd != -1) dup2( stdin_fd, 0 );
1920             if (stdout_fd != -1) dup2( stdout_fd, 1 );
1921         }
1922
1923         if (stdin_fd != -1) close( stdin_fd );
1924         if (stdout_fd != -1) close( stdout_fd );
1925
1926         /* Reset signals that we previously set to SIG_IGN */
1927         signal( SIGPIPE, SIG_DFL );
1928         signal( SIGCHLD, SIG_DFL );
1929
1930         sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1931         sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1932                  (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1933
1934         putenv( preloader_reserve );
1935         putenv( socket_env );
1936         if (winedebug) putenv( winedebug );
1937         if (wineloader) putenv( wineloader );
1938         if (unixdir) chdir(unixdir);
1939
1940         if (argv)
1941         {
1942             do
1943             {
1944                 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1945             }
1946 #ifdef __APPLE__
1947             while (errno == ENOTSUP && exec_only && terminate_main_thread());
1948 #else
1949             while (0);
1950 #endif
1951         }
1952         _exit(1);
1953     }
1954
1955     /* this is the parent */
1956
1957     if (stdin_fd != -1) close( stdin_fd );
1958     if (stdout_fd != -1) close( stdout_fd );
1959     close( socketfd[0] );
1960     HeapFree( GetProcessHeap(), 0, argv );
1961     HeapFree( GetProcessHeap(), 0, winedebug );
1962     HeapFree( GetProcessHeap(), 0, wineloader );
1963     if (pid == -1)
1964     {
1965         FILE_SetDosError();
1966         goto error;
1967     }
1968
1969     /* wait for the new process info to be ready */
1970
1971     WaitForSingleObject( process_info, INFINITE );
1972     SERVER_START_REQ( get_new_process_info )
1973     {
1974         req->info = wine_server_obj_handle( process_info );
1975         wine_server_call( req );
1976         success = reply->success;
1977         err = reply->exit_code;
1978     }
1979     SERVER_END_REQ;
1980
1981     if (!success)
1982     {
1983         SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1984         goto error;
1985     }
1986     CloseHandle( process_info );
1987     return success;
1988
1989 error:
1990     CloseHandle( process_info );
1991     CloseHandle( info->hProcess );
1992     CloseHandle( info->hThread );
1993     info->hProcess = info->hThread = 0;
1994     info->dwProcessId = info->dwThreadId = 0;
1995     return FALSE;
1996 }
1997
1998
1999 /***********************************************************************
2000  *           create_vdm_process
2001  *
2002  * Create a new VDM process for a 16-bit or DOS application.
2003  */
2004 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2005                                 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2006                                 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2007                                 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2008                                 const struct binary_info *binary_info, int exec_only )
2009 {
2010     static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2011
2012     BOOL ret;
2013     LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
2014                                      (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
2015
2016     if (!new_cmd_line)
2017     {
2018         SetLastError( ERROR_OUTOFMEMORY );
2019         return FALSE;
2020     }
2021     sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
2022     ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2023                           flags, startup, info, unixdir, binary_info, exec_only );
2024     HeapFree( GetProcessHeap(), 0, new_cmd_line );
2025     return ret;
2026 }
2027
2028
2029 /***********************************************************************
2030  *           create_cmd_process
2031  *
2032  * Create a new cmd shell process for a .BAT file.
2033  */
2034 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2035                                 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2036                                 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2037                                 LPPROCESS_INFORMATION info )
2038
2039 {
2040     static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2041     static const WCHAR slashcW[] = {' ','/','c',' ',0};
2042     WCHAR comspec[MAX_PATH];
2043     WCHAR *newcmdline;
2044     BOOL ret;
2045
2046     if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2047         return FALSE;
2048     if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2049                                   (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2050         return FALSE;
2051
2052     strcpyW( newcmdline, comspec );
2053     strcatW( newcmdline, slashcW );
2054     strcatW( newcmdline, cmd_line );
2055     ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2056                           flags, env, cur_dir, startup, info );
2057     HeapFree( GetProcessHeap(), 0, newcmdline );
2058     return ret;
2059 }
2060
2061
2062 /*************************************************************************
2063  *               get_file_name
2064  *
2065  * Helper for CreateProcess: retrieve the file name to load from the
2066  * app name and command line. Store the file name in buffer, and
2067  * return a possibly modified command line.
2068  * Also returns a handle to the opened file if it's a Windows binary.
2069  */
2070 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2071                              int buflen, HANDLE *handle, struct binary_info *binary_info )
2072 {
2073     static const WCHAR quotesW[] = {'"','%','s','"',0};
2074
2075     WCHAR *name, *pos, *first_space, *ret = NULL;
2076     const WCHAR *p;
2077
2078     /* if we have an app name, everything is easy */
2079
2080     if (appname)
2081     {
2082         /* use the unmodified app name as file name */
2083         lstrcpynW( buffer, appname, buflen );
2084         *handle = open_exe_file( buffer, binary_info );
2085         if (!(ret = cmdline) || !cmdline[0])
2086         {
2087             /* no command-line, create one */
2088             if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2089                 sprintfW( ret, quotesW, appname );
2090         }
2091         return ret;
2092     }
2093
2094     /* first check for a quoted file name */
2095
2096     if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2097     {
2098         int len = p - cmdline - 1;
2099         /* extract the quoted portion as file name */
2100         if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2101         memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2102         name[len] = 0;
2103
2104         if (!find_exe_file( name, buffer, buflen, handle, binary_info ))
2105         {
2106             if (!get_builtin_path( name, exeW, buffer, buflen, binary_info )) goto done;
2107             *handle = 0;
2108         }
2109         ret = cmdline;  /* no change necessary */
2110         goto done;
2111     }
2112
2113     /* now try the command-line word by word */
2114
2115     if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2116         return NULL;
2117     pos = name;
2118     p = cmdline;
2119     first_space = NULL;
2120
2121     for (;;)
2122     {
2123         while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2124         *pos = 0;
2125         if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2126         {
2127             ret = cmdline;
2128             break;
2129         }
2130         if (!first_space) first_space = pos;
2131         if (!(*pos++ = *p++)) break;
2132     }
2133
2134     if (!ret)
2135     {
2136         if (first_space) *first_space = 0;  /* try only the first word as a builtin */
2137         if (get_builtin_path( name, exeW, buffer, buflen, binary_info ))
2138         {
2139             *handle = 0;
2140             ret = cmdline;
2141         }
2142         else SetLastError( ERROR_FILE_NOT_FOUND );
2143     }
2144     else if (first_space)  /* build a new command-line with quotes */
2145     {
2146         if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2147             goto done;
2148         sprintfW( ret, quotesW, name );
2149         strcatW( ret, p );
2150     }
2151
2152  done:
2153     HeapFree( GetProcessHeap(), 0, name );
2154     return ret;
2155 }
2156
2157
2158 /**********************************************************************
2159  *       CreateProcessA          (KERNEL32.@)
2160  */
2161 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2162                                               LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2163                                               DWORD flags, LPVOID env, LPCSTR cur_dir,
2164                                               LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2165 {
2166     BOOL ret = FALSE;
2167     WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2168     UNICODE_STRING desktopW, titleW;
2169     STARTUPINFOW infoW;
2170
2171     desktopW.Buffer = NULL;
2172     titleW.Buffer = NULL;
2173     if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2174     if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2175     if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2176
2177     if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2178     if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2179
2180     memcpy( &infoW, startup_info, sizeof(infoW) );
2181     infoW.lpDesktop = desktopW.Buffer;
2182     infoW.lpTitle = titleW.Buffer;
2183
2184     if (startup_info->lpReserved)
2185       FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2186             debugstr_a(startup_info->lpReserved));
2187
2188     ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
2189                           inherit, flags, env, cur_dirW, &infoW, info );
2190 done:
2191     HeapFree( GetProcessHeap(), 0, app_nameW );
2192     HeapFree( GetProcessHeap(), 0, cmd_lineW );
2193     HeapFree( GetProcessHeap(), 0, cur_dirW );
2194     RtlFreeUnicodeString( &desktopW );
2195     RtlFreeUnicodeString( &titleW );
2196     return ret;
2197 }
2198
2199
2200 /**********************************************************************
2201  *       CreateProcessW          (KERNEL32.@)
2202  */
2203 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2204                                               LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2205                                               LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2206                                               LPPROCESS_INFORMATION info )
2207 {
2208     BOOL retv = FALSE;
2209     HANDLE hFile = 0;
2210     char *unixdir = NULL;
2211     WCHAR name[MAX_PATH];
2212     WCHAR *tidy_cmdline, *p, *envW = env;
2213     struct binary_info binary_info;
2214
2215     /* Process the AppName and/or CmdLine to get module name and path */
2216
2217     TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2218
2219     if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2220                                         &hFile, &binary_info )))
2221         return FALSE;
2222     if (hFile == INVALID_HANDLE_VALUE) goto done;
2223
2224     /* Warn if unsupported features are used */
2225
2226     if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2227                  CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2228                  CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2229                  PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2230         WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2231
2232     if (cur_dir)
2233     {
2234         if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2235         {
2236             SetLastError(ERROR_DIRECTORY);
2237             goto done;
2238         }
2239     }
2240     else
2241     {
2242         WCHAR buf[MAX_PATH];
2243         if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2244     }
2245
2246     if (env && !(flags & CREATE_UNICODE_ENVIRONMENT))  /* convert environment to unicode */
2247     {
2248         char *p = env;
2249         DWORD lenW;
2250
2251         while (*p) p += strlen(p) + 1;
2252         p++;  /* final null */
2253         lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
2254         envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2255         MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
2256         flags |= CREATE_UNICODE_ENVIRONMENT;
2257     }
2258
2259     info->hThread = info->hProcess = 0;
2260     info->dwProcessId = info->dwThreadId = 0;
2261
2262     if (binary_info.flags & BINARY_FLAG_DLL)
2263     {
2264         TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2265         SetLastError( ERROR_BAD_EXE_FORMAT );
2266     }
2267     else switch (binary_info.type)
2268     {
2269     case BINARY_PE:
2270         TRACE( "starting %s as Win%d binary (%p-%p)\n",
2271                debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2272                binary_info.res_start, binary_info.res_end );
2273         retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2274                                inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2275         break;
2276     case BINARY_OS216:
2277     case BINARY_WIN16:
2278     case BINARY_DOS:
2279         TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2280         retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2281                                    inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2282         break;
2283     case BINARY_UNIX_LIB:
2284         TRACE( "starting %s as %d-bit Winelib app\n",
2285                debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2286         retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2287                                inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2288         break;
2289     case BINARY_UNKNOWN:
2290         /* check for .com or .bat extension */
2291         if ((p = strrchrW( name, '.' )))
2292         {
2293             if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2294             {
2295                 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2296                 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2297                                            inherit, flags, startup_info, info, unixdir,
2298                                            &binary_info, FALSE );
2299                 break;
2300             }
2301             if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2302             {
2303                 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2304                 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2305                                            inherit, flags, startup_info, info );
2306                 break;
2307             }
2308         }
2309         /* fall through */
2310     case BINARY_UNIX_EXE:
2311         {
2312             /* unknown file, try as unix executable */
2313             char *unix_name;
2314
2315             TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2316
2317             if ((unix_name = wine_get_unix_file_name( name )))
2318             {
2319                 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2320                 HeapFree( GetProcessHeap(), 0, unix_name );
2321             }
2322         }
2323         break;
2324     }
2325     if (hFile) CloseHandle( hFile );
2326
2327  done:
2328     if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2329     if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2330     HeapFree( GetProcessHeap(), 0, unixdir );
2331     if (retv)
2332         TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2333     return retv;
2334 }
2335
2336
2337 /**********************************************************************
2338  *       exec_process
2339  */
2340 static void exec_process( LPCWSTR name )
2341 {
2342     HANDLE hFile;
2343     WCHAR *p;
2344     STARTUPINFOW startup_info;
2345     PROCESS_INFORMATION info;
2346     struct binary_info binary_info;
2347
2348     hFile = open_exe_file( name, &binary_info );
2349     if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2350
2351     memset( &startup_info, 0, sizeof(startup_info) );
2352     startup_info.cb = sizeof(startup_info);
2353
2354     /* Determine executable type */
2355
2356     if (binary_info.flags & BINARY_FLAG_DLL) return;
2357     switch (binary_info.type)
2358     {
2359     case BINARY_PE:
2360         TRACE( "starting %s as Win%d binary (%p-%p)\n",
2361                debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2362                binary_info.res_start, binary_info.res_end );
2363         create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2364                         FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2365         break;
2366     case BINARY_UNIX_LIB:
2367         TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2368         create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2369                         FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2370         break;
2371     case BINARY_UNKNOWN:
2372         /* check for .com or .pif extension */
2373         if (!(p = strrchrW( name, '.' ))) break;
2374         if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2375         /* fall through */
2376     case BINARY_OS216:
2377     case BINARY_WIN16:
2378     case BINARY_DOS:
2379         TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2380         create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2381                             FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2382         break;
2383     default:
2384         break;
2385     }
2386     CloseHandle( hFile );
2387 }
2388
2389
2390 /***********************************************************************
2391  *           wait_input_idle
2392  *
2393  * Wrapper to call WaitForInputIdle USER function
2394  */
2395 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2396
2397 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2398 {
2399     HMODULE mod = GetModuleHandleA( "user32.dll" );
2400     if (mod)
2401     {
2402         WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2403         if (ptr) return ptr( process, timeout );
2404     }
2405     return 0;
2406 }
2407
2408
2409 /***********************************************************************
2410  *           WinExec   (KERNEL32.@)
2411  */
2412 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2413 {
2414     PROCESS_INFORMATION info;
2415     STARTUPINFOA startup;
2416     char *cmdline;
2417     UINT ret;
2418
2419     memset( &startup, 0, sizeof(startup) );
2420     startup.cb = sizeof(startup);
2421     startup.dwFlags = STARTF_USESHOWWINDOW;
2422     startup.wShowWindow = nCmdShow;
2423
2424     /* cmdline needs to be writable for CreateProcess */
2425     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2426     strcpy( cmdline, lpCmdLine );
2427
2428     if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2429                         0, NULL, NULL, &startup, &info ))
2430     {
2431         /* Give 30 seconds to the app to come up */
2432         if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2433             WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2434         ret = 33;
2435         /* Close off the handles */
2436         CloseHandle( info.hThread );
2437         CloseHandle( info.hProcess );
2438     }
2439     else if ((ret = GetLastError()) >= 32)
2440     {
2441         FIXME("Strange error set by CreateProcess: %d\n", ret );
2442         ret = 11;
2443     }
2444     HeapFree( GetProcessHeap(), 0, cmdline );
2445     return ret;
2446 }
2447
2448
2449 /**********************************************************************
2450  *          LoadModule    (KERNEL32.@)
2451  */
2452 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2453 {
2454     LOADPARMS32 *params = paramBlock;
2455     PROCESS_INFORMATION info;
2456     STARTUPINFOA startup;
2457     DWORD ret;
2458     LPSTR cmdline, p;
2459     char filename[MAX_PATH];
2460     BYTE len;
2461
2462     if (!name) return ERROR_FILE_NOT_FOUND;
2463
2464     if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2465         !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2466         return GetLastError();
2467
2468     len = (BYTE)params->lpCmdLine[0];
2469     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2470         return ERROR_NOT_ENOUGH_MEMORY;
2471
2472     strcpy( cmdline, filename );
2473     p = cmdline + strlen(cmdline);
2474     *p++ = ' ';
2475     memcpy( p, params->lpCmdLine + 1, len );
2476     p[len] = 0;
2477
2478     memset( &startup, 0, sizeof(startup) );
2479     startup.cb = sizeof(startup);
2480     if (params->lpCmdShow)
2481     {
2482         startup.dwFlags = STARTF_USESHOWWINDOW;
2483         startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2484     }
2485
2486     if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2487                         params->lpEnvAddress, NULL, &startup, &info ))
2488     {
2489         /* Give 30 seconds to the app to come up */
2490         if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2491             WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2492         ret = 33;
2493         /* Close off the handles */
2494         CloseHandle( info.hThread );
2495         CloseHandle( info.hProcess );
2496     }
2497     else if ((ret = GetLastError()) >= 32)
2498     {
2499         FIXME("Strange error set by CreateProcess: %u\n", ret );
2500         ret = 11;
2501     }
2502
2503     HeapFree( GetProcessHeap(), 0, cmdline );
2504     return ret;
2505 }
2506
2507
2508 /******************************************************************************
2509  *           TerminateProcess   (KERNEL32.@)
2510  *
2511  * Terminates a process.
2512  *
2513  * PARAMS
2514  *  handle    [I] Process to terminate.
2515  *  exit_code [I] Exit code.
2516  *
2517  * RETURNS
2518  *  Success: TRUE.
2519  *  Failure: FALSE, check GetLastError().
2520  */
2521 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2522 {
2523     NTSTATUS status = NtTerminateProcess( handle, exit_code );
2524     if (status) SetLastError( RtlNtStatusToDosError(status) );
2525     return !status;
2526 }
2527
2528 /***********************************************************************
2529  *           ExitProcess   (KERNEL32.@)
2530  *
2531  * Exits the current process.
2532  *
2533  * PARAMS
2534  *  status [I] Status code to exit with.
2535  *
2536  * RETURNS
2537  *  Nothing.
2538  */
2539 #ifdef __i386__
2540 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2541                    "pushl %ebp\n\t"
2542                    ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2543                    ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2544                    ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2545                    "pushl 8(%ebp)\n\t"
2546                    "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2547                    "leave\n\t"
2548                    "ret $4" )
2549
2550 void WINAPI process_ExitProcess( DWORD status )
2551 {
2552     LdrShutdownProcess();
2553     NtTerminateProcess(GetCurrentProcess(), status);
2554     exit(status);
2555 }
2556
2557 #else
2558
2559 void WINAPI ExitProcess( DWORD status )
2560 {
2561     LdrShutdownProcess();
2562     NtTerminateProcess(GetCurrentProcess(), status);
2563     exit(status);
2564 }
2565
2566 #endif
2567
2568 /***********************************************************************
2569  * GetExitCodeProcess           [KERNEL32.@]
2570  *
2571  * Gets termination status of specified process.
2572  *
2573  * PARAMS
2574  *   hProcess   [in]  Handle to the process.
2575  *   lpExitCode [out] Address to receive termination status.
2576  *
2577  * RETURNS
2578  *   Success: TRUE
2579  *   Failure: FALSE
2580  */
2581 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2582 {
2583     NTSTATUS status;
2584     PROCESS_BASIC_INFORMATION pbi;
2585
2586     status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2587                                        sizeof(pbi), NULL);
2588     if (status == STATUS_SUCCESS)
2589     {
2590         if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2591         return TRUE;
2592     }
2593     SetLastError( RtlNtStatusToDosError(status) );
2594     return FALSE;
2595 }
2596
2597
2598 /***********************************************************************
2599  *           SetErrorMode   (KERNEL32.@)
2600  */
2601 UINT WINAPI SetErrorMode( UINT mode )
2602 {
2603     UINT old;
2604
2605     NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2606                                &old, sizeof(old), NULL );
2607     NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2608                              &mode, sizeof(mode) );
2609     return old;
2610 }
2611
2612 /***********************************************************************
2613  *           GetErrorMode   (KERNEL32.@)
2614  */
2615 UINT WINAPI GetErrorMode( void )
2616 {
2617     UINT mode;
2618
2619     NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2620                                &mode, sizeof(mode), NULL );
2621     return mode;
2622 }
2623
2624 /**********************************************************************
2625  * TlsAlloc             [KERNEL32.@]
2626  *
2627  * Allocates a thread local storage index.
2628  *
2629  * RETURNS
2630  *    Success: TLS index.
2631  *    Failure: 0xFFFFFFFF
2632  */
2633 DWORD WINAPI TlsAlloc( void )
2634 {
2635     DWORD index;
2636     PEB * const peb = NtCurrentTeb()->Peb;
2637
2638     RtlAcquirePebLock();
2639     index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2640     if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2641     else
2642     {
2643         index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2644         if (index != ~0U)
2645         {
2646             if (!NtCurrentTeb()->TlsExpansionSlots &&
2647                 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2648                                          8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2649             {
2650                 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2651                 index = ~0U;
2652                 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2653             }
2654             else
2655             {
2656                 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2657                 index += TLS_MINIMUM_AVAILABLE;
2658             }
2659         }
2660         else SetLastError( ERROR_NO_MORE_ITEMS );
2661     }
2662     RtlReleasePebLock();
2663     return index;
2664 }
2665
2666
2667 /**********************************************************************
2668  * TlsFree              [KERNEL32.@]
2669  *
2670  * Releases a thread local storage index, making it available for reuse.
2671  *
2672  * PARAMS
2673  *    index [in] TLS index to free.
2674  *
2675  * RETURNS
2676  *    Success: TRUE
2677  *    Failure: FALSE
2678  */
2679 BOOL WINAPI TlsFree( DWORD index )
2680 {
2681     BOOL ret;
2682
2683     RtlAcquirePebLock();
2684     if (index >= TLS_MINIMUM_AVAILABLE)
2685     {
2686         ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2687         if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2688     }
2689     else
2690     {
2691         ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2692         if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2693     }
2694     if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2695     else SetLastError( ERROR_INVALID_PARAMETER );
2696     RtlReleasePebLock();
2697     return ret;
2698 }
2699
2700
2701 /**********************************************************************
2702  * TlsGetValue          [KERNEL32.@]
2703  *
2704  * Gets value in a thread's TLS slot.
2705  *
2706  * PARAMS
2707  *    index [in] TLS index to retrieve value for.
2708  *
2709  * RETURNS
2710  *    Success: Value stored in calling thread's TLS slot for index.
2711  *    Failure: 0 and GetLastError() returns NO_ERROR.
2712  */
2713 LPVOID WINAPI TlsGetValue( DWORD index )
2714 {
2715     LPVOID ret;
2716
2717     if (index < TLS_MINIMUM_AVAILABLE)
2718     {
2719         ret = NtCurrentTeb()->TlsSlots[index];
2720     }
2721     else
2722     {
2723         index -= TLS_MINIMUM_AVAILABLE;
2724         if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2725         {
2726             SetLastError( ERROR_INVALID_PARAMETER );
2727             return NULL;
2728         }
2729         if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2730         else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2731     }
2732     SetLastError( ERROR_SUCCESS );
2733     return ret;
2734 }
2735
2736
2737 /**********************************************************************
2738  * TlsSetValue          [KERNEL32.@]
2739  *
2740  * Stores a value in the thread's TLS slot.
2741  *
2742  * PARAMS
2743  *    index [in] TLS index to set value for.
2744  *    value [in] Value to be stored.
2745  *
2746  * RETURNS
2747  *    Success: TRUE
2748  *    Failure: FALSE
2749  */
2750 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2751 {
2752     if (index < TLS_MINIMUM_AVAILABLE)
2753     {
2754         NtCurrentTeb()->TlsSlots[index] = value;
2755     }
2756     else
2757     {
2758         index -= TLS_MINIMUM_AVAILABLE;
2759         if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2760         {
2761             SetLastError( ERROR_INVALID_PARAMETER );
2762             return FALSE;
2763         }
2764         if (!NtCurrentTeb()->TlsExpansionSlots &&
2765             !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2766                          8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2767         {
2768             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2769             return FALSE;
2770         }
2771         NtCurrentTeb()->TlsExpansionSlots[index] = value;
2772     }
2773     return TRUE;
2774 }
2775
2776
2777 /***********************************************************************
2778  *           GetProcessFlags    (KERNEL32.@)
2779  */
2780 DWORD WINAPI GetProcessFlags( DWORD processid )
2781 {
2782     IMAGE_NT_HEADERS *nt;
2783     DWORD flags = 0;
2784
2785     if (processid && processid != GetCurrentProcessId()) return 0;
2786
2787     if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2788     {
2789         if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2790             flags |= PDB32_CONSOLE_PROC;
2791     }
2792     if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2793     if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2794     return flags;
2795 }
2796
2797
2798 /*********************************************************************
2799  *           OpenProcess   (KERNEL32.@)
2800  *
2801  * Opens a handle to a process.
2802  *
2803  * PARAMS
2804  *  access  [I] Desired access rights assigned to the returned handle.
2805  *  inherit [I] Determines whether or not child processes will inherit the handle.
2806  *  id      [I] Process identifier of the process to get a handle to.
2807  *
2808  * RETURNS
2809  *  Success: Valid handle to the specified process.
2810  *  Failure: NULL, check GetLastError().
2811  */
2812 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2813 {
2814     NTSTATUS            status;
2815     HANDLE              handle;
2816     OBJECT_ATTRIBUTES   attr;
2817     CLIENT_ID           cid;
2818
2819     cid.UniqueProcess = ULongToHandle(id);
2820     cid.UniqueThread = 0; /* FIXME ? */
2821
2822     attr.Length = sizeof(OBJECT_ATTRIBUTES);
2823     attr.RootDirectory = NULL;
2824     attr.Attributes = inherit ? OBJ_INHERIT : 0;
2825     attr.SecurityDescriptor = NULL;
2826     attr.SecurityQualityOfService = NULL;
2827     attr.ObjectName = NULL;
2828
2829     if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2830
2831     status = NtOpenProcess(&handle, access, &attr, &cid);
2832     if (status != STATUS_SUCCESS)
2833     {
2834         SetLastError( RtlNtStatusToDosError(status) );
2835         return NULL;
2836     }
2837     return handle;
2838 }
2839
2840
2841 /*********************************************************************
2842  *           GetProcessId       (KERNEL32.@)
2843  *
2844  * Gets the a unique identifier of a process.
2845  *
2846  * PARAMS
2847  *  hProcess [I] Handle to the process.
2848  *
2849  * RETURNS
2850  *  Success: TRUE.
2851  *  Failure: FALSE, check GetLastError().
2852  *
2853  * NOTES
2854  *
2855  * The identifier is unique only on the machine and only until the process
2856  * exits (including system shutdown).
2857  */
2858 DWORD WINAPI GetProcessId( HANDLE hProcess )
2859 {
2860     NTSTATUS status;
2861     PROCESS_BASIC_INFORMATION pbi;
2862
2863     status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2864                                        sizeof(pbi), NULL);
2865     if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2866     SetLastError( RtlNtStatusToDosError(status) );
2867     return 0;
2868 }
2869
2870
2871 /*********************************************************************
2872  *           CloseHandle    (KERNEL32.@)
2873  *
2874  * Closes a handle.
2875  *
2876  * PARAMS
2877  *  handle [I] Handle to close.
2878  *
2879  * RETURNS
2880  *  Success: TRUE.
2881  *  Failure: FALSE, check GetLastError().
2882  */
2883 BOOL WINAPI CloseHandle( HANDLE handle )
2884 {
2885     NTSTATUS status;
2886
2887     /* stdio handles need special treatment */
2888     if (handle == (HANDLE)STD_INPUT_HANDLE)
2889         handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
2890     else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
2891         handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
2892     else if (handle == (HANDLE)STD_ERROR_HANDLE)
2893         handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
2894
2895     if (is_console_handle(handle))
2896         return CloseConsoleHandle(handle);
2897
2898     status = NtClose( handle );
2899     if (status) SetLastError( RtlNtStatusToDosError(status) );
2900     return !status;
2901 }
2902
2903
2904 /*********************************************************************
2905  *           GetHandleInformation   (KERNEL32.@)
2906  */
2907 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2908 {
2909     OBJECT_DATA_INFORMATION info;
2910     NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2911
2912     if (status) SetLastError( RtlNtStatusToDosError(status) );
2913     else if (flags)
2914     {
2915         *flags = 0;
2916         if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2917         if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2918     }
2919     return !status;
2920 }
2921
2922
2923 /*********************************************************************
2924  *           SetHandleInformation   (KERNEL32.@)
2925  */
2926 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2927 {
2928     OBJECT_DATA_INFORMATION info;
2929     NTSTATUS status;
2930
2931     /* if not setting both fields, retrieve current value first */
2932     if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2933         (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2934     {
2935         if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2936         {
2937             SetLastError( RtlNtStatusToDosError(status) );
2938             return FALSE;
2939         }
2940     }
2941     if (mask & HANDLE_FLAG_INHERIT)
2942         info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2943     if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2944         info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2945
2946     status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2947     if (status) SetLastError( RtlNtStatusToDosError(status) );
2948     return !status;
2949 }
2950
2951
2952 /*********************************************************************
2953  *           DuplicateHandle   (KERNEL32.@)
2954  */
2955 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2956                              HANDLE dest_process, HANDLE *dest,
2957                              DWORD access, BOOL inherit, DWORD options )
2958 {
2959     NTSTATUS status;
2960
2961     if (is_console_handle(source))
2962     {
2963         /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2964         if (source_process != dest_process ||
2965             source_process != GetCurrentProcess())
2966         {
2967             SetLastError(ERROR_INVALID_PARAMETER);
2968             return FALSE;
2969         }
2970         *dest = DuplicateConsoleHandle( source, access, inherit, options );
2971         return (*dest != INVALID_HANDLE_VALUE);
2972     }
2973     status = NtDuplicateObject( source_process, source, dest_process, dest,
2974                                 access, inherit ? OBJ_INHERIT : 0, options );
2975     if (status) SetLastError( RtlNtStatusToDosError(status) );
2976     return !status;
2977 }
2978
2979
2980 /***********************************************************************
2981  *           ConvertToGlobalHandle  (KERNEL32.@)
2982  */
2983 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2984 {
2985     HANDLE ret = INVALID_HANDLE_VALUE;
2986     DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2987                      DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2988     return ret;
2989 }
2990
2991
2992 /***********************************************************************
2993  *           SetHandleContext   (KERNEL32.@)
2994  */
2995 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2996 {
2997     FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2998           "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2999     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3000     return FALSE;
3001 }
3002
3003
3004 /***********************************************************************
3005  *           GetHandleContext   (KERNEL32.@)
3006  */
3007 DWORD WINAPI GetHandleContext(HANDLE hnd)
3008 {
3009     FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3010           "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3011     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3012     return 0;
3013 }
3014
3015
3016 /***********************************************************************
3017  *           CreateSocketHandle   (KERNEL32.@)
3018  */
3019 HANDLE WINAPI CreateSocketHandle(void)
3020 {
3021     FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3022           "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3023     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3024     return INVALID_HANDLE_VALUE;
3025 }
3026
3027
3028 /***********************************************************************
3029  *           SetPriorityClass   (KERNEL32.@)
3030  */
3031 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3032 {
3033     NTSTATUS                    status;
3034     PROCESS_PRIORITY_CLASS      ppc;
3035
3036     ppc.Foreground = FALSE;
3037     switch (priorityclass)
3038     {
3039     case IDLE_PRIORITY_CLASS:
3040         ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3041     case BELOW_NORMAL_PRIORITY_CLASS:
3042         ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3043     case NORMAL_PRIORITY_CLASS:
3044         ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3045     case ABOVE_NORMAL_PRIORITY_CLASS:
3046         ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3047     case HIGH_PRIORITY_CLASS:
3048         ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3049     case REALTIME_PRIORITY_CLASS:
3050         ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3051     default:
3052         SetLastError(ERROR_INVALID_PARAMETER);
3053         return FALSE;
3054     }
3055
3056     status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3057                                      &ppc, sizeof(ppc));
3058
3059     if (status != STATUS_SUCCESS)
3060     {
3061         SetLastError( RtlNtStatusToDosError(status) );
3062         return FALSE;
3063     }
3064     return TRUE;
3065 }
3066
3067
3068 /***********************************************************************
3069  *           GetPriorityClass   (KERNEL32.@)
3070  */
3071 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3072 {
3073     NTSTATUS status;
3074     PROCESS_BASIC_INFORMATION pbi;
3075
3076     status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3077                                        sizeof(pbi), NULL);
3078     if (status != STATUS_SUCCESS)
3079     {
3080         SetLastError( RtlNtStatusToDosError(status) );
3081         return 0;
3082     }
3083     switch (pbi.BasePriority)
3084     {
3085     case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3086     case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3087     case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3088     case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3089     case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3090     case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3091     }
3092     SetLastError( ERROR_INVALID_PARAMETER );
3093     return 0;
3094 }
3095
3096
3097 /***********************************************************************
3098  *          SetProcessAffinityMask   (KERNEL32.@)
3099  */
3100 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3101 {
3102     NTSTATUS status;
3103
3104     status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3105                                      &affmask, sizeof(DWORD_PTR));
3106     if (status)
3107     {
3108         SetLastError( RtlNtStatusToDosError(status) );
3109         return FALSE;
3110     }
3111     return TRUE;
3112 }
3113
3114
3115 /**********************************************************************
3116  *          GetProcessAffinityMask    (KERNEL32.@)
3117  */
3118 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
3119                                     PDWORD_PTR lpProcessAffinityMask,
3120                                     PDWORD_PTR lpSystemAffinityMask )
3121 {
3122     PROCESS_BASIC_INFORMATION   pbi;
3123     NTSTATUS                    status;
3124
3125     status = NtQueryInformationProcess(hProcess,
3126                                        ProcessBasicInformation,
3127                                        &pbi, sizeof(pbi), NULL);
3128     if (status)
3129     {
3130         SetLastError( RtlNtStatusToDosError(status) );
3131         return FALSE;
3132     }
3133     if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
3134     if (lpSystemAffinityMask)  *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
3135     return TRUE;
3136 }
3137
3138
3139 /***********************************************************************
3140  *           GetProcessVersion    (KERNEL32.@)
3141  */
3142 DWORD WINAPI GetProcessVersion( DWORD pid )
3143 {
3144     HANDLE process;
3145     NTSTATUS status;
3146     PROCESS_BASIC_INFORMATION pbi;
3147     SIZE_T count;
3148     PEB peb;
3149     IMAGE_DOS_HEADER dos;
3150     IMAGE_NT_HEADERS nt;
3151     DWORD ver = 0;
3152
3153     if (!pid || pid == GetCurrentProcessId())
3154     {
3155         IMAGE_NT_HEADERS *nt;
3156
3157         if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3158             return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
3159                     nt->OptionalHeader.MinorSubsystemVersion);
3160         return 0;
3161     }
3162
3163     process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3164     if (!process) return 0;
3165
3166     status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3167     if (status) goto err;
3168
3169     status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3170     if (status || count != sizeof(peb)) goto err;
3171
3172     memset(&dos, 0, sizeof(dos));
3173     status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3174     if (status || count != sizeof(dos)) goto err;
3175     if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3176
3177     memset(&nt, 0, sizeof(nt));
3178     status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3179     if (status || count != sizeof(nt)) goto err;
3180     if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3181
3182     ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3183
3184 err:
3185     CloseHandle(process);
3186
3187     if (status != STATUS_SUCCESS)
3188         SetLastError(RtlNtStatusToDosError(status));
3189
3190     return ver;
3191 }
3192
3193
3194 /***********************************************************************
3195  *              SetProcessWorkingSetSize        [KERNEL32.@]
3196  * Sets the min/max working set sizes for a specified process.
3197  *
3198  * PARAMS
3199  *    hProcess [I] Handle to the process of interest
3200  *    minset   [I] Specifies minimum working set size
3201  *    maxset   [I] Specifies maximum working set size
3202  *
3203  * RETURNS
3204  *  Success: TRUE
3205  *  Failure: FALSE
3206  */
3207 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3208                                      SIZE_T maxset)
3209 {
3210     WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3211     if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3212         /* Trim the working set to zero */
3213         /* Swap the process out of physical RAM */
3214     }
3215     return TRUE;
3216 }
3217
3218 /***********************************************************************
3219  *           GetProcessWorkingSetSize    (KERNEL32.@)
3220  */
3221 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3222                                      PSIZE_T maxset)
3223 {
3224     FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3225     /* 32 MB working set size */
3226     if (minset) *minset = 32*1024*1024;
3227     if (maxset) *maxset = 32*1024*1024;
3228     return TRUE;
3229 }
3230
3231
3232 /***********************************************************************
3233  *           SetProcessShutdownParameters    (KERNEL32.@)
3234  */
3235 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3236 {
3237     FIXME("(%08x, %08x): partial stub.\n", level, flags);
3238     shutdown_flags = flags;
3239     shutdown_priority = level;
3240     return TRUE;
3241 }
3242
3243
3244 /***********************************************************************
3245  * GetProcessShutdownParameters                 (KERNEL32.@)
3246  *
3247  */
3248 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3249 {
3250     *lpdwLevel = shutdown_priority;
3251     *lpdwFlags = shutdown_flags;
3252     return TRUE;
3253 }
3254
3255
3256 /***********************************************************************
3257  *           GetProcessPriorityBoost    (KERNEL32.@)
3258  */
3259 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3260 {
3261     FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3262     
3263     /* Report that no boost is present.. */
3264     *pDisablePriorityBoost = FALSE;
3265     
3266     return TRUE;
3267 }
3268
3269 /***********************************************************************
3270  *           SetProcessPriorityBoost    (KERNEL32.@)
3271  */
3272 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3273 {
3274     FIXME("(%p,%d): stub\n",hprocess,disableboost);
3275     /* Say we can do it. I doubt the program will notice that we don't. */
3276     return TRUE;
3277 }
3278
3279
3280 /***********************************************************************
3281  *              ReadProcessMemory (KERNEL32.@)
3282  */
3283 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3284                                SIZE_T *bytes_read )
3285 {
3286     NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3287     if (status) SetLastError( RtlNtStatusToDosError(status) );
3288     return !status;
3289 }
3290
3291
3292 /***********************************************************************
3293  *           WriteProcessMemory                 (KERNEL32.@)
3294  */
3295 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3296                                 SIZE_T *bytes_written )
3297 {
3298     NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3299     if (status) SetLastError( RtlNtStatusToDosError(status) );
3300     return !status;
3301 }
3302
3303
3304 /****************************************************************************
3305  *              FlushInstructionCache (KERNEL32.@)
3306  */
3307 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3308 {
3309     NTSTATUS status;
3310     status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3311     if (status) SetLastError( RtlNtStatusToDosError(status) );
3312     return !status;
3313 }
3314
3315
3316 /******************************************************************
3317  *              GetProcessIoCounters (KERNEL32.@)
3318  */
3319 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3320 {
3321     NTSTATUS    status;
3322
3323     status = NtQueryInformationProcess(hProcess, ProcessIoCounters, 
3324                                        ioc, sizeof(*ioc), NULL);
3325     if (status) SetLastError( RtlNtStatusToDosError(status) );
3326     return !status;
3327 }
3328
3329 /******************************************************************
3330  *              GetProcessHandleCount (KERNEL32.@)
3331  */
3332 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3333 {
3334     NTSTATUS status;
3335
3336     status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3337                                        cnt, sizeof(*cnt), NULL);
3338     if (status) SetLastError( RtlNtStatusToDosError(status) );
3339     return !status;
3340 }
3341
3342 /******************************************************************
3343  *              QueryFullProcessImageNameA (KERNEL32.@)
3344  */
3345 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3346 {
3347     BOOL retval;
3348     DWORD pdwSizeW = *pdwSize;
3349     LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3350
3351     retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3352
3353     if(retval)
3354         retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3355                                lpExeName, *pdwSize, NULL, NULL));
3356     if(retval)
3357         *pdwSize = strlen(lpExeName);
3358
3359     HeapFree(GetProcessHeap(), 0, lpExeNameW);
3360     return retval;
3361 }
3362
3363 /******************************************************************
3364  *              QueryFullProcessImageNameW (KERNEL32.@)
3365  */
3366 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3367 {
3368     BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)];  /* this buffer should be enough */
3369     UNICODE_STRING *dynamic_buffer = NULL;
3370     UNICODE_STRING nt_path;
3371     UNICODE_STRING *result = NULL;
3372     NTSTATUS status;
3373     DWORD needed;
3374
3375     RtlInitUnicodeStringEx(&nt_path, NULL);
3376     /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3377      * as this is on Wine. */
3378     status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3379                                        sizeof(buffer) - sizeof(WCHAR), &needed);
3380     if (status == STATUS_INFO_LENGTH_MISMATCH)
3381     {
3382         dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3383         status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3384         result = dynamic_buffer;
3385     }
3386     else
3387         result = (PUNICODE_STRING)buffer;
3388
3389     if (status) goto cleanup;
3390
3391     if (dwFlags & PROCESS_NAME_NATIVE)
3392     {
3393         result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3394         if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3395         {
3396             status = STATUS_OBJECT_PATH_NOT_FOUND;
3397             goto cleanup;
3398         }
3399         result = &nt_path;
3400     }
3401
3402     if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3403     {
3404         status = STATUS_BUFFER_TOO_SMALL;
3405         goto cleanup;
3406     }
3407
3408     *pdwSize = result->Length/sizeof(WCHAR);
3409     memcpy( lpExeName, result->Buffer, result->Length );
3410     lpExeName[*pdwSize] = 0;
3411
3412 cleanup:
3413     HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3414     RtlFreeUnicodeString(&nt_path);
3415     if (status) SetLastError( RtlNtStatusToDosError(status) );
3416     return !status;
3417 }
3418
3419 /***********************************************************************
3420  * ProcessIdToSessionId   (KERNEL32.@)
3421  * This function is available on Terminal Server 4SP4 and Windows 2000
3422  */
3423 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3424 {
3425     /* According to MSDN, if the calling process is not in a terminal
3426      * services environment, then the sessionid returned is zero.
3427      */
3428     *sessionid_ptr = 0;
3429     return TRUE;
3430 }
3431
3432
3433 /***********************************************************************
3434  *              RegisterServiceProcess (KERNEL32.@)
3435  *
3436  * A service process calls this function to ensure that it continues to run
3437  * even after a user logged off.
3438  */
3439 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3440 {
3441     /* I don't think that Wine needs to do anything in this function */
3442     return 1; /* success */
3443 }
3444
3445
3446 /**********************************************************************
3447  *           IsWow64Process         (KERNEL32.@)
3448  */
3449 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3450 {
3451     ULONG pbi;
3452     NTSTATUS status;
3453
3454     status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3455
3456     if (status != STATUS_SUCCESS)
3457     {
3458         SetLastError( RtlNtStatusToDosError( status ) );
3459         return FALSE;
3460     }
3461     *Wow64Process = (pbi != 0);
3462     return TRUE;
3463 }
3464
3465
3466 /***********************************************************************
3467  *           GetCurrentProcess   (KERNEL32.@)
3468  *
3469  * Get a handle to the current process.
3470  *
3471  * PARAMS
3472  *  None.
3473  *
3474  * RETURNS
3475  *  A handle representing the current process.
3476  */
3477 #undef GetCurrentProcess
3478 HANDLE WINAPI GetCurrentProcess(void)
3479 {
3480     return (HANDLE)~(ULONG_PTR)0;
3481 }
3482
3483 /***********************************************************************
3484  *           GetLogicalProcessorInformation     (KERNEL32.@)
3485  */
3486 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3487 {
3488     FIXME("(%p,%p): stub\n", buffer, pBufLen);
3489     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3490     return FALSE;
3491 }
3492
3493 /***********************************************************************
3494  *           GetLogicalProcessorInformationEx   (KERNEL32.@)
3495  */
3496 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer, PDWORD pBufLen)
3497 {
3498     FIXME("(%u,%p,%p): stub\n", relationship, buffer, pBufLen);
3499     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3500     return FALSE;
3501 }
3502
3503 /***********************************************************************
3504  *           CmdBatNotification   (KERNEL32.@)
3505  *
3506  * Notifies the system that a batch file has started or finished.
3507  *
3508  * PARAMS
3509  *  bBatchRunning [I]  TRUE if a batch file has started or 
3510  *                     FALSE if a batch file has finished executing.
3511  *
3512  * RETURNS
3513  *  Unknown.
3514  */
3515 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3516 {
3517     FIXME("%d\n", bBatchRunning);
3518     return FALSE;
3519 }
3520
3521
3522 /***********************************************************************
3523  *           RegisterApplicationRestart       (KERNEL32.@)
3524  */
3525 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3526 {
3527     FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3528
3529     return S_OK;
3530 }
3531
3532 /**********************************************************************
3533  *           WTSGetActiveConsoleSessionId     (KERNEL32.@)
3534  */
3535 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3536 {
3537     FIXME("stub\n");
3538     return 0;
3539 }
3540
3541 /**********************************************************************
3542  *           GetSystemDEPPolicy     (KERNEL32.@)
3543  */
3544 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3545 {
3546     FIXME("stub\n");
3547     return OptIn;
3548 }
3549 /**********************************************************************
3550  *           SetProcessDEPPolicy     (KERNEL32.@)
3551  */
3552 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3553 {
3554     FIXME("(%d): stub\n", newDEP);
3555     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3556     return FALSE;
3557 }