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