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