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