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