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