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