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