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