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