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