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