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