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