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