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