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