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