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