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