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