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