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