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