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