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