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