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