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