server: Distinguish between a directory and a file changing in
[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) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1485
1486         err = errno;
1487         write( execfd[1], &err, sizeof(err) );
1488         _exit(1);
1489     }
1490
1491     /* this is the parent */
1492
1493     close( startfd[0] );
1494     close( execfd[1] );
1495     HeapFree( GetProcessHeap(), 0, winedebug );
1496     if (pid == -1)
1497     {
1498         if (!env) RtlReleasePebLock();
1499         close( startfd[1] );
1500         close( execfd[0] );
1501         FILE_SetDosError();
1502         RtlDestroyProcessParameters( params );
1503         return FALSE;
1504     }
1505
1506     /* create the process on the server side */
1507
1508     SERVER_START_REQ( new_process )
1509     {
1510         req->inherit_all  = inherit;
1511         req->create_flags = flags;
1512         req->unix_pid     = pid;
1513         req->exe_file     = hFile;
1514         if (startup->dwFlags & STARTF_USESTDHANDLES)
1515         {
1516             req->hstdin  = startup->hStdInput;
1517             req->hstdout = startup->hStdOutput;
1518             req->hstderr = startup->hStdError;
1519         }
1520         else
1521         {
1522             req->hstdin  = GetStdHandle( STD_INPUT_HANDLE );
1523             req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1524             req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1525         }
1526
1527         if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1528         {
1529             /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1530             if (is_console_handle(req->hstdin))  req->hstdin  = INVALID_HANDLE_VALUE;
1531             if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1532             if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1533         }
1534         else
1535         {
1536             if (is_console_handle(req->hstdin))  req->hstdin  = console_handle_unmap(req->hstdin);
1537             if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1538             if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1539         }
1540
1541         wine_server_add_data( req, params, params->Size );
1542         wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1543         ret = !wine_server_call_err( req );
1544         process_info = reply->info;
1545     }
1546     SERVER_END_REQ;
1547
1548     if (!env) RtlReleasePebLock();
1549     RtlDestroyProcessParameters( params );
1550     if (!ret)
1551     {
1552         close( startfd[1] );
1553         close( execfd[0] );
1554         return FALSE;
1555     }
1556
1557     /* tell child to start and wait for it to exec */
1558
1559     write( startfd[1], &dummy, 1 );
1560     close( startfd[1] );
1561
1562     if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1563     {
1564         errno = err;
1565         FILE_SetDosError();
1566         close( execfd[0] );
1567         CloseHandle( process_info );
1568         return FALSE;
1569     }
1570     close( execfd[0] );
1571
1572     /* wait for the new process info to be ready */
1573
1574     WaitForSingleObject( process_info, INFINITE );
1575     SERVER_START_REQ( get_new_process_info )
1576     {
1577         req->info           = process_info;
1578         req->process_access = PROCESS_ALL_ACCESS;
1579         req->process_attr   = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1580         req->thread_access  = THREAD_ALL_ACCESS;
1581         req->thread_attr    = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1582         if ((ret = !wine_server_call_err( req )))
1583         {
1584             info->dwProcessId = (DWORD)reply->pid;
1585             info->dwThreadId  = (DWORD)reply->tid;
1586             info->hProcess    = reply->phandle;
1587             info->hThread     = reply->thandle;
1588             success           = reply->success;
1589         }
1590     }
1591     SERVER_END_REQ;
1592
1593     if (ret && !success)  /* new process failed to start */
1594     {
1595         DWORD exitcode;
1596         if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1597         CloseHandle( info->hThread );
1598         CloseHandle( info->hProcess );
1599         ret = FALSE;
1600     }
1601     CloseHandle( process_info );
1602     return ret;
1603 }
1604
1605
1606 /***********************************************************************
1607  *           create_vdm_process
1608  *
1609  * Create a new VDM process for a 16-bit or DOS application.
1610  */
1611 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1612                                 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1613                                 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1614                                 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1615 {
1616     static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1617
1618     BOOL ret;
1619     LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1620                                      (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1621
1622     if (!new_cmd_line)
1623     {
1624         SetLastError( ERROR_OUTOFMEMORY );
1625         return FALSE;
1626     }
1627     sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1628     ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1629                           flags, startup, info, unixdir, NULL, NULL );
1630     HeapFree( GetProcessHeap(), 0, new_cmd_line );
1631     return ret;
1632 }
1633
1634
1635 /***********************************************************************
1636  *           create_cmd_process
1637  *
1638  * Create a new cmd shell process for a .BAT file.
1639  */
1640 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1641                                 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1642                                 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1643                                 LPPROCESS_INFORMATION info )
1644
1645 {
1646     static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1647     static const WCHAR slashcW[] = {' ','/','c',' ',0};
1648     WCHAR comspec[MAX_PATH];
1649     WCHAR *newcmdline;
1650     BOOL ret;
1651
1652     if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1653         return FALSE;
1654     if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1655                                   (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1656         return FALSE;
1657
1658     strcpyW( newcmdline, comspec );
1659     strcatW( newcmdline, slashcW );
1660     strcatW( newcmdline, cmd_line );
1661     ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1662                           flags, env, cur_dir, startup, info );
1663     HeapFree( GetProcessHeap(), 0, newcmdline );
1664     return ret;
1665 }
1666
1667
1668 /*************************************************************************
1669  *               get_file_name
1670  *
1671  * Helper for CreateProcess: retrieve the file name to load from the
1672  * app name and command line. Store the file name in buffer, and
1673  * return a possibly modified command line.
1674  * Also returns a handle to the opened file if it's a Windows binary.
1675  */
1676 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1677                              int buflen, HANDLE *handle )
1678 {
1679     static const WCHAR quotesW[] = {'"','%','s','"',0};
1680
1681     WCHAR *name, *pos, *ret = NULL;
1682     const WCHAR *p;
1683     BOOL got_space;
1684
1685     /* if we have an app name, everything is easy */
1686
1687     if (appname)
1688     {
1689         /* use the unmodified app name as file name */
1690         lstrcpynW( buffer, appname, buflen );
1691         *handle = open_exe_file( buffer );
1692         if (!(ret = cmdline) || !cmdline[0])
1693         {
1694             /* no command-line, create one */
1695             if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1696                 sprintfW( ret, quotesW, appname );
1697         }
1698         return ret;
1699     }
1700
1701     if (!cmdline)
1702     {
1703         SetLastError( ERROR_INVALID_PARAMETER );
1704         return NULL;
1705     }
1706
1707     /* first check for a quoted file name */
1708
1709     if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1710     {
1711         int len = p - cmdline - 1;
1712         /* extract the quoted portion as file name */
1713         if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1714         memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1715         name[len] = 0;
1716
1717         if (find_exe_file( name, buffer, buflen, handle ))
1718             ret = cmdline;  /* no change necessary */
1719         goto done;
1720     }
1721
1722     /* now try the command-line word by word */
1723
1724     if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1725         return NULL;
1726     pos = name;
1727     p = cmdline;
1728     got_space = FALSE;
1729
1730     while (*p)
1731     {
1732         do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1733         *pos = 0;
1734         if (find_exe_file( name, buffer, buflen, handle ))
1735         {
1736             ret = cmdline;
1737             break;
1738         }
1739         if (*p) got_space = TRUE;
1740     }
1741
1742     if (ret && got_space)  /* now build a new command-line with quotes */
1743     {
1744         if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1745             goto done;
1746         sprintfW( ret, quotesW, name );
1747         strcatW( ret, p );
1748     }
1749
1750  done:
1751     HeapFree( GetProcessHeap(), 0, name );
1752     return ret;
1753 }
1754
1755
1756 /**********************************************************************
1757  *       CreateProcessA          (KERNEL32.@)
1758  */
1759 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1760                             LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1761                             DWORD flags, LPVOID env, LPCSTR cur_dir,
1762                             LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1763 {
1764     BOOL ret = FALSE;
1765     WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1766     UNICODE_STRING desktopW, titleW;
1767     STARTUPINFOW infoW;
1768
1769     desktopW.Buffer = NULL;
1770     titleW.Buffer = NULL;
1771     if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1772     if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1773     if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1774
1775     if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1776     if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1777
1778     memcpy( &infoW, startup_info, sizeof(infoW) );
1779     infoW.lpDesktop = desktopW.Buffer;
1780     infoW.lpTitle = titleW.Buffer;
1781
1782     if (startup_info->lpReserved)
1783       FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1784             debugstr_a(startup_info->lpReserved));
1785
1786     ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1787                           inherit, flags, env, cur_dirW, &infoW, info );
1788 done:
1789     HeapFree( GetProcessHeap(), 0, app_nameW );
1790     HeapFree( GetProcessHeap(), 0, cmd_lineW );
1791     HeapFree( GetProcessHeap(), 0, cur_dirW );
1792     RtlFreeUnicodeString( &desktopW );
1793     RtlFreeUnicodeString( &titleW );
1794     return ret;
1795 }
1796
1797
1798 /**********************************************************************
1799  *       CreateProcessW          (KERNEL32.@)
1800  */
1801 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1802                             LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1803                             LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1804                             LPPROCESS_INFORMATION info )
1805 {
1806     BOOL retv = FALSE;
1807     HANDLE hFile = 0;
1808     char *unixdir = NULL;
1809     WCHAR name[MAX_PATH];
1810     WCHAR *tidy_cmdline, *p, *envW = env;
1811     void *res_start, *res_end;
1812
1813     /* Process the AppName and/or CmdLine to get module name and path */
1814
1815     TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1816
1817     if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1818         return FALSE;
1819     if (hFile == INVALID_HANDLE_VALUE) goto done;
1820
1821     /* Warn if unsupported features are used */
1822
1823     if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1824                  CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1825                  CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1826                  PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1827         WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1828
1829     if (cur_dir)
1830     {
1831         unixdir = wine_get_unix_file_name( cur_dir );
1832     }
1833     else
1834     {
1835         WCHAR buf[MAX_PATH];
1836         if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1837     }
1838
1839     if (env && !(flags & CREATE_UNICODE_ENVIRONMENT))  /* convert environment to unicode */
1840     {
1841         char *p = env;
1842         DWORD lenW;
1843
1844         while (*p) p += strlen(p) + 1;
1845         p++;  /* final null */
1846         lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1847         envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1848         MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1849         flags |= CREATE_UNICODE_ENVIRONMENT;
1850     }
1851
1852     info->hThread = info->hProcess = 0;
1853     info->dwProcessId = info->dwThreadId = 0;
1854
1855     /* Determine executable type */
1856
1857     if (!hFile)  /* builtin exe */
1858     {
1859         TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1860         retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1861                                inherit, flags, startup_info, info, unixdir, NULL, NULL );
1862         goto done;
1863     }
1864
1865     switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1866     {
1867     case BINARY_PE_EXE:
1868         TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1869         retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1870                                inherit, flags, startup_info, info, unixdir, res_start, res_end );
1871         break;
1872     case BINARY_OS216:
1873     case BINARY_WIN16:
1874     case BINARY_DOS:
1875         TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1876         retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1877                                    inherit, flags, startup_info, info, unixdir );
1878         break;
1879     case BINARY_PE_DLL:
1880         TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1881         SetLastError( ERROR_BAD_EXE_FORMAT );
1882         break;
1883     case BINARY_UNIX_LIB:
1884         TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1885         retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1886                                inherit, flags, startup_info, info, unixdir, NULL, NULL );
1887         break;
1888     case BINARY_UNKNOWN:
1889         /* check for .com or .bat extension */
1890         if ((p = strrchrW( name, '.' )))
1891         {
1892             if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1893             {
1894                 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1895                 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1896                                            inherit, flags, startup_info, info, unixdir );
1897                 break;
1898             }
1899             if (!strcmpiW( p, batW ))
1900             {
1901                 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1902                 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1903                                            inherit, flags, startup_info, info );
1904                 break;
1905             }
1906         }
1907         /* fall through */
1908     case BINARY_UNIX_EXE:
1909         {
1910             /* unknown file, try as unix executable */
1911             char *unix_name;
1912
1913             TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1914
1915             if ((unix_name = wine_get_unix_file_name( name )))
1916             {
1917                 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1918                 HeapFree( GetProcessHeap(), 0, unix_name );
1919             }
1920         }
1921         break;
1922     }
1923     CloseHandle( hFile );
1924
1925  done:
1926     if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1927     if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1928     HeapFree( GetProcessHeap(), 0, unixdir );
1929     return retv;
1930 }
1931
1932
1933 /***********************************************************************
1934  *           wait_input_idle
1935  *
1936  * Wrapper to call WaitForInputIdle USER function
1937  */
1938 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1939
1940 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1941 {
1942     HMODULE mod = GetModuleHandleA( "user32.dll" );
1943     if (mod)
1944     {
1945         WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1946         if (ptr) return ptr( process, timeout );
1947     }
1948     return 0;
1949 }
1950
1951
1952 /***********************************************************************
1953  *           WinExec   (KERNEL32.@)
1954  */
1955 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1956 {
1957     PROCESS_INFORMATION info;
1958     STARTUPINFOA startup;
1959     char *cmdline;
1960     UINT ret;
1961
1962     memset( &startup, 0, sizeof(startup) );
1963     startup.cb = sizeof(startup);
1964     startup.dwFlags = STARTF_USESHOWWINDOW;
1965     startup.wShowWindow = nCmdShow;
1966
1967     /* cmdline needs to be writeable for CreateProcess */
1968     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1969     strcpy( cmdline, lpCmdLine );
1970
1971     if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1972                         0, NULL, NULL, &startup, &info ))
1973     {
1974         /* Give 30 seconds to the app to come up */
1975         if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1976             WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1977         ret = 33;
1978         /* Close off the handles */
1979         CloseHandle( info.hThread );
1980         CloseHandle( info.hProcess );
1981     }
1982     else if ((ret = GetLastError()) >= 32)
1983     {
1984         FIXME("Strange error set by CreateProcess: %d\n", ret );
1985         ret = 11;
1986     }
1987     HeapFree( GetProcessHeap(), 0, cmdline );
1988     return ret;
1989 }
1990
1991
1992 /**********************************************************************
1993  *          LoadModule    (KERNEL32.@)
1994  */
1995 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1996 {
1997     LOADPARMS32 *params = paramBlock;
1998     PROCESS_INFORMATION info;
1999     STARTUPINFOA startup;
2000     HINSTANCE hInstance;
2001     LPSTR cmdline, p;
2002     char filename[MAX_PATH];
2003     BYTE len;
2004
2005     if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2006
2007     if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2008         !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2009         return (HINSTANCE)GetLastError();
2010
2011     len = (BYTE)params->lpCmdLine[0];
2012     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2013         return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2014
2015     strcpy( cmdline, filename );
2016     p = cmdline + strlen(cmdline);
2017     *p++ = ' ';
2018     memcpy( p, params->lpCmdLine + 1, len );
2019     p[len] = 0;
2020
2021     memset( &startup, 0, sizeof(startup) );
2022     startup.cb = sizeof(startup);
2023     if (params->lpCmdShow)
2024     {
2025         startup.dwFlags = STARTF_USESHOWWINDOW;
2026         startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2027     }
2028
2029     if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2030                         params->lpEnvAddress, NULL, &startup, &info ))
2031     {
2032         /* Give 30 seconds to the app to come up */
2033         if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2034             WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2035         hInstance = (HINSTANCE)33;
2036         /* Close off the handles */
2037         CloseHandle( info.hThread );
2038         CloseHandle( info.hProcess );
2039     }
2040     else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
2041     {
2042         FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2043         hInstance = (HINSTANCE)11;
2044     }
2045
2046     HeapFree( GetProcessHeap(), 0, cmdline );
2047     return hInstance;
2048 }
2049
2050
2051 /******************************************************************************
2052  *           TerminateProcess   (KERNEL32.@)
2053  */
2054 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2055 {
2056     NTSTATUS status = NtTerminateProcess( handle, exit_code );
2057     if (status) SetLastError( RtlNtStatusToDosError(status) );
2058     return !status;
2059 }
2060
2061
2062 /***********************************************************************
2063  *           ExitProcess   (KERNEL32.@)
2064  */
2065 void WINAPI ExitProcess( DWORD status )
2066 {
2067     LdrShutdownProcess();
2068     NtTerminateProcess(GetCurrentProcess(), status);
2069     exit(status);
2070 }
2071
2072
2073 /***********************************************************************
2074  * GetExitCodeProcess           [KERNEL32.@]
2075  *
2076  * Gets termination status of specified process.
2077  *
2078  * PARAMS
2079  *   hProcess   [in]  Handle to the process.
2080  *   lpExitCode [out] Address to receive termination status.
2081  *
2082  * RETURNS
2083  *   Success: TRUE
2084  *   Failure: FALSE
2085  */
2086 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2087 {
2088     NTSTATUS status;
2089     PROCESS_BASIC_INFORMATION pbi;
2090
2091     status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2092                                        sizeof(pbi), NULL);
2093     if (status == STATUS_SUCCESS)
2094     {
2095         if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2096         return TRUE;
2097     }
2098     SetLastError( RtlNtStatusToDosError(status) );
2099     return FALSE;
2100 }
2101
2102
2103 /***********************************************************************
2104  *           SetErrorMode   (KERNEL32.@)
2105  */
2106 UINT WINAPI SetErrorMode( UINT mode )
2107 {
2108     UINT old = process_error_mode;
2109     process_error_mode = mode;
2110     return old;
2111 }
2112
2113
2114 /**********************************************************************
2115  * TlsAlloc             [KERNEL32.@]
2116  *
2117  * Allocates a thread local storage index.
2118  *
2119  * RETURNS
2120  *    Success: TLS index.
2121  *    Failure: 0xFFFFFFFF
2122  */
2123 DWORD WINAPI TlsAlloc( void )
2124 {
2125     DWORD index;
2126     PEB * const peb = NtCurrentTeb()->Peb;
2127
2128     RtlAcquirePebLock();
2129     index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2130     if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2131     else
2132     {
2133         index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2134         if (index != ~0U)
2135         {
2136             if (!NtCurrentTeb()->TlsExpansionSlots &&
2137                 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2138                                          8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2139             {
2140                 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2141                 index = ~0U;
2142                 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2143             }
2144             else
2145             {
2146                 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2147                 index += TLS_MINIMUM_AVAILABLE;
2148             }
2149         }
2150         else SetLastError( ERROR_NO_MORE_ITEMS );
2151     }
2152     RtlReleasePebLock();
2153     return index;
2154 }
2155
2156
2157 /**********************************************************************
2158  * TlsFree              [KERNEL32.@]
2159  *
2160  * Releases a thread local storage index, making it available for reuse.
2161  *
2162  * PARAMS
2163  *    index [in] TLS index to free.
2164  *
2165  * RETURNS
2166  *    Success: TRUE
2167  *    Failure: FALSE
2168  */
2169 BOOL WINAPI TlsFree( DWORD index )
2170 {
2171     BOOL ret;
2172
2173     RtlAcquirePebLock();
2174     if (index >= TLS_MINIMUM_AVAILABLE)
2175     {
2176         ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2177         if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2178     }
2179     else
2180     {
2181         ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2182         if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2183     }
2184     if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2185     else SetLastError( ERROR_INVALID_PARAMETER );
2186     RtlReleasePebLock();
2187     return TRUE;
2188 }
2189
2190
2191 /**********************************************************************
2192  * TlsGetValue          [KERNEL32.@]
2193  *
2194  * Gets value in a thread's TLS slot.
2195  *
2196  * PARAMS
2197  *    index [in] TLS index to retrieve value for.
2198  *
2199  * RETURNS
2200  *    Success: Value stored in calling thread's TLS slot for index.
2201  *    Failure: 0 and GetLastError() returns NO_ERROR.
2202  */
2203 LPVOID WINAPI TlsGetValue( DWORD index )
2204 {
2205     LPVOID ret;
2206
2207     if (index < TLS_MINIMUM_AVAILABLE)
2208     {
2209         ret = NtCurrentTeb()->TlsSlots[index];
2210     }
2211     else
2212     {
2213         index -= TLS_MINIMUM_AVAILABLE;
2214         if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2215         {
2216             SetLastError( ERROR_INVALID_PARAMETER );
2217             return NULL;
2218         }
2219         if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2220         else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2221     }
2222     SetLastError( ERROR_SUCCESS );
2223     return ret;
2224 }
2225
2226
2227 /**********************************************************************
2228  * TlsSetValue          [KERNEL32.@]
2229  *
2230  * Stores a value in the thread's TLS slot.
2231  *
2232  * PARAMS
2233  *    index [in] TLS index to set value for.
2234  *    value [in] Value to be stored.
2235  *
2236  * RETURNS
2237  *    Success: TRUE
2238  *    Failure: FALSE
2239  */
2240 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2241 {
2242     if (index < TLS_MINIMUM_AVAILABLE)
2243     {
2244         NtCurrentTeb()->TlsSlots[index] = value;
2245     }
2246     else
2247     {
2248         index -= TLS_MINIMUM_AVAILABLE;
2249         if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2250         {
2251             SetLastError( ERROR_INVALID_PARAMETER );
2252             return FALSE;
2253         }
2254         if (!NtCurrentTeb()->TlsExpansionSlots &&
2255             !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2256                          8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2257         {
2258             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2259             return FALSE;
2260         }
2261         NtCurrentTeb()->TlsExpansionSlots[index] = value;
2262     }
2263     return TRUE;
2264 }
2265
2266
2267 /***********************************************************************
2268  *           GetProcessFlags    (KERNEL32.@)
2269  */
2270 DWORD WINAPI GetProcessFlags( DWORD processid )
2271 {
2272     IMAGE_NT_HEADERS *nt;
2273     DWORD flags = 0;
2274
2275     if (processid && processid != GetCurrentProcessId()) return 0;
2276
2277     if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2278     {
2279         if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2280             flags |= PDB32_CONSOLE_PROC;
2281     }
2282     if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2283     if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2284     return flags;
2285 }
2286
2287
2288 /***********************************************************************
2289  *           GetProcessDword    (KERNEL.485)
2290  *           GetProcessDword    (KERNEL32.18)
2291  * 'Of course you cannot directly access Windows internal structures'
2292  */
2293 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2294 {
2295     DWORD               x, y;
2296     STARTUPINFOW        siw;
2297
2298     TRACE("(%ld, %d)\n", dwProcessID, offset );
2299
2300     if (dwProcessID && dwProcessID != GetCurrentProcessId())
2301     {
2302         ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2303         return 0;
2304     }
2305
2306     switch ( offset )
2307     {
2308     case GPD_APP_COMPAT_FLAGS:
2309         return GetAppCompatFlags16(0);
2310     case GPD_LOAD_DONE_EVENT:
2311         return 0;
2312     case GPD_HINSTANCE16:
2313         return GetTaskDS16();
2314     case GPD_WINDOWS_VERSION:
2315         return GetExeVersion16();
2316     case GPD_THDB:
2317         return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2318     case GPD_PDB:
2319         return (DWORD)NtCurrentTeb()->Peb;
2320     case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2321         GetStartupInfoW(&siw);
2322         return (DWORD)siw.hStdOutput;
2323     case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2324         GetStartupInfoW(&siw);
2325         return (DWORD)siw.hStdInput;
2326     case GPD_STARTF_SHOWWINDOW:
2327         GetStartupInfoW(&siw);
2328         return siw.wShowWindow;
2329     case GPD_STARTF_SIZE:
2330         GetStartupInfoW(&siw);
2331         x = siw.dwXSize;
2332         if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2333         y = siw.dwYSize;
2334         if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2335         return MAKELONG( x, y );
2336     case GPD_STARTF_POSITION:
2337         GetStartupInfoW(&siw);
2338         x = siw.dwX;
2339         if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2340         y = siw.dwY;
2341         if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2342         return MAKELONG( x, y );
2343     case GPD_STARTF_FLAGS:
2344         GetStartupInfoW(&siw);
2345         return siw.dwFlags;
2346     case GPD_PARENT:
2347         return 0;
2348     case GPD_FLAGS:
2349         return GetProcessFlags(0);
2350     case GPD_USERDATA:
2351         return process_dword;
2352     default:
2353         ERR("Unknown offset %d\n", offset );
2354         return 0;
2355     }
2356 }
2357
2358 /***********************************************************************
2359  *           SetProcessDword    (KERNEL.484)
2360  * 'Of course you cannot directly access Windows internal structures'
2361  */
2362 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2363 {
2364     TRACE("(%ld, %d)\n", dwProcessID, offset );
2365
2366     if (dwProcessID && dwProcessID != GetCurrentProcessId())
2367     {
2368         ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2369         return;
2370     }
2371
2372     switch ( offset )
2373     {
2374     case GPD_APP_COMPAT_FLAGS:
2375     case GPD_LOAD_DONE_EVENT:
2376     case GPD_HINSTANCE16:
2377     case GPD_WINDOWS_VERSION:
2378     case GPD_THDB:
2379     case GPD_PDB:
2380     case GPD_STARTF_SHELLDATA:
2381     case GPD_STARTF_HOTKEY:
2382     case GPD_STARTF_SHOWWINDOW:
2383     case GPD_STARTF_SIZE:
2384     case GPD_STARTF_POSITION:
2385     case GPD_STARTF_FLAGS:
2386     case GPD_PARENT:
2387     case GPD_FLAGS:
2388         ERR("Not allowed to modify offset %d\n", offset );
2389         break;
2390     case GPD_USERDATA:
2391         process_dword = value;
2392         break;
2393     default:
2394         ERR("Unknown offset %d\n", offset );
2395         break;
2396     }
2397 }
2398
2399
2400 /***********************************************************************
2401  *           ExitProcess   (KERNEL.466)
2402  */
2403 void WINAPI ExitProcess16( WORD status )
2404 {
2405     DWORD count;
2406     ReleaseThunkLock( &count );
2407     ExitProcess( status );
2408 }
2409
2410
2411 /*********************************************************************
2412  *           OpenProcess   (KERNEL32.@)
2413  */
2414 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2415 {
2416     NTSTATUS            status;
2417     HANDLE              handle;
2418     OBJECT_ATTRIBUTES   attr;
2419     CLIENT_ID           cid;
2420
2421     cid.UniqueProcess = (HANDLE)id;
2422     cid.UniqueThread = 0; /* FIXME ? */
2423
2424     attr.Length = sizeof(OBJECT_ATTRIBUTES);
2425     attr.RootDirectory = NULL;
2426     attr.Attributes = inherit ? OBJ_INHERIT : 0;
2427     attr.SecurityDescriptor = NULL;
2428     attr.SecurityQualityOfService = NULL;
2429     attr.ObjectName = NULL;
2430
2431     status = NtOpenProcess(&handle, access, &attr, &cid);
2432     if (status != STATUS_SUCCESS)
2433     {
2434         SetLastError( RtlNtStatusToDosError(status) );
2435         return NULL;
2436     }
2437     return handle;
2438 }
2439
2440
2441 /*********************************************************************
2442  *           MapProcessHandle   (KERNEL.483)
2443  *           GetProcessId       (KERNEL32.@)
2444  */
2445 DWORD WINAPI GetProcessId( HANDLE hProcess )
2446 {
2447     NTSTATUS status;
2448     PROCESS_BASIC_INFORMATION pbi;
2449
2450     status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2451                                        sizeof(pbi), NULL);
2452     if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2453     SetLastError( RtlNtStatusToDosError(status) );
2454     return 0;
2455 }
2456
2457
2458 /*********************************************************************
2459  *           CloseW32Handle (KERNEL.474)
2460  *           CloseHandle    (KERNEL32.@)
2461  */
2462 BOOL WINAPI CloseHandle( HANDLE handle )
2463 {
2464     NTSTATUS status;
2465
2466     /* stdio handles need special treatment */
2467     if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2468         (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2469         (handle == (HANDLE)STD_ERROR_HANDLE))
2470         handle = GetStdHandle( (DWORD)handle );
2471
2472     if (is_console_handle(handle))
2473         return CloseConsoleHandle(handle);
2474
2475     status = NtClose( handle );
2476     if (status) SetLastError( RtlNtStatusToDosError(status) );
2477     return !status;
2478 }
2479
2480
2481 /*********************************************************************
2482  *           GetHandleInformation   (KERNEL32.@)
2483  */
2484 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2485 {
2486     OBJECT_DATA_INFORMATION info;
2487     NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2488
2489     if (status) SetLastError( RtlNtStatusToDosError(status) );
2490     else if (flags)
2491     {
2492         *flags = 0;
2493         if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2494         if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2495     }
2496     return !status;
2497 }
2498
2499
2500 /*********************************************************************
2501  *           SetHandleInformation   (KERNEL32.@)
2502  */
2503 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2504 {
2505     OBJECT_DATA_INFORMATION info;
2506     NTSTATUS status;
2507
2508     /* if not setting both fields, retrieve current value first */
2509     if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2510         (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2511     {
2512         if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2513         {
2514             SetLastError( RtlNtStatusToDosError(status) );
2515             return FALSE;
2516         }
2517     }
2518     if (mask & HANDLE_FLAG_INHERIT)
2519         info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2520     if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2521         info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2522
2523     status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2524     if (status) SetLastError( RtlNtStatusToDosError(status) );
2525     return !status;
2526 }
2527
2528
2529 /*********************************************************************
2530  *           DuplicateHandle   (KERNEL32.@)
2531  */
2532 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2533                              HANDLE dest_process, HANDLE *dest,
2534                              DWORD access, BOOL inherit, DWORD options )
2535 {
2536     NTSTATUS status;
2537
2538     if (is_console_handle(source))
2539     {
2540         /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2541         if (source_process != dest_process ||
2542             source_process != GetCurrentProcess())
2543         {
2544             SetLastError(ERROR_INVALID_PARAMETER);
2545             return FALSE;
2546         }
2547         *dest = DuplicateConsoleHandle( source, access, inherit, options );
2548         return (*dest != INVALID_HANDLE_VALUE);
2549     }
2550     status = NtDuplicateObject( source_process, source, dest_process, dest,
2551                                 access, inherit ? OBJ_INHERIT : 0, options );
2552     if (status) SetLastError( RtlNtStatusToDosError(status) );
2553     return !status;
2554 }
2555
2556
2557 /***********************************************************************
2558  *           ConvertToGlobalHandle   (KERNEL.476)
2559  *           ConvertToGlobalHandle  (KERNEL32.@)
2560  */
2561 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2562 {
2563     HANDLE ret = INVALID_HANDLE_VALUE;
2564     DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2565                      DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2566     return ret;
2567 }
2568
2569
2570 /***********************************************************************
2571  *           SetHandleContext   (KERNEL32.@)
2572  */
2573 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2574 {
2575     FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2576           "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2577     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2578     return FALSE;
2579 }
2580
2581
2582 /***********************************************************************
2583  *           GetHandleContext   (KERNEL32.@)
2584  */
2585 DWORD WINAPI GetHandleContext(HANDLE hnd)
2586 {
2587     FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2588           "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2589     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2590     return 0;
2591 }
2592
2593
2594 /***********************************************************************
2595  *           CreateSocketHandle   (KERNEL32.@)
2596  */
2597 HANDLE WINAPI CreateSocketHandle(void)
2598 {
2599     FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2600           "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2601     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2602     return INVALID_HANDLE_VALUE;
2603 }
2604
2605
2606 /***********************************************************************
2607  *           SetPriorityClass   (KERNEL32.@)
2608  */
2609 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2610 {
2611     NTSTATUS                    status;
2612     PROCESS_PRIORITY_CLASS      ppc;
2613
2614     ppc.Foreground = FALSE;
2615     switch (priorityclass)
2616     {
2617     case IDLE_PRIORITY_CLASS:
2618         ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2619     case BELOW_NORMAL_PRIORITY_CLASS:
2620         ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2621     case NORMAL_PRIORITY_CLASS:
2622         ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2623     case ABOVE_NORMAL_PRIORITY_CLASS:
2624         ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2625     case HIGH_PRIORITY_CLASS:
2626         ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2627     case REALTIME_PRIORITY_CLASS:
2628         ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2629     default:
2630         SetLastError(ERROR_INVALID_PARAMETER);
2631         return FALSE;
2632     }
2633
2634     status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2635                                      &ppc, sizeof(ppc));
2636
2637     if (status != STATUS_SUCCESS)
2638     {
2639         SetLastError( RtlNtStatusToDosError(status) );
2640         return FALSE;
2641     }
2642     return TRUE;
2643 }
2644
2645
2646 /***********************************************************************
2647  *           GetPriorityClass   (KERNEL32.@)
2648  */
2649 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2650 {
2651     NTSTATUS status;
2652     PROCESS_BASIC_INFORMATION pbi;
2653
2654     status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2655                                        sizeof(pbi), NULL);
2656     if (status != STATUS_SUCCESS)
2657     {
2658         SetLastError( RtlNtStatusToDosError(status) );
2659         return 0;
2660     }
2661     switch (pbi.BasePriority)
2662     {
2663     case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2664     case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2665     case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2666     case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2667     case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2668     case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2669     }
2670     SetLastError( ERROR_INVALID_PARAMETER );
2671     return 0;
2672 }
2673
2674
2675 /***********************************************************************
2676  *          SetProcessAffinityMask   (KERNEL32.@)
2677  */
2678 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2679 {
2680     NTSTATUS status;
2681
2682     status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2683                                      &affmask, sizeof(DWORD_PTR));
2684     if (!status)
2685     {
2686         SetLastError( RtlNtStatusToDosError(status) );
2687         return FALSE;
2688     }
2689     return TRUE;
2690 }
2691
2692
2693 /**********************************************************************
2694  *          GetProcessAffinityMask    (KERNEL32.@)
2695  */
2696 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2697                                     PDWORD_PTR lpProcessAffinityMask,
2698                                     PDWORD_PTR lpSystemAffinityMask )
2699 {
2700     PROCESS_BASIC_INFORMATION   pbi;
2701     NTSTATUS                    status;
2702
2703     status = NtQueryInformationProcess(hProcess,
2704                                        ProcessBasicInformation,
2705                                        &pbi, sizeof(pbi), NULL);
2706     if (status)
2707     {
2708         SetLastError( RtlNtStatusToDosError(status) );
2709         return FALSE;
2710     }
2711     if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2712     /* FIXME */
2713     if (lpSystemAffinityMask)  *lpSystemAffinityMask = 1;
2714     return TRUE;
2715 }
2716
2717
2718 /***********************************************************************
2719  *           GetProcessVersion    (KERNEL32.@)
2720  */
2721 DWORD WINAPI GetProcessVersion( DWORD processid )
2722 {
2723     IMAGE_NT_HEADERS *nt;
2724
2725     if (processid && processid != GetCurrentProcessId())
2726     {
2727         FIXME("should use ReadProcessMemory\n");
2728         return 0;
2729     }
2730     if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2731         return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2732                 nt->OptionalHeader.MinorSubsystemVersion);
2733     return 0;
2734 }
2735
2736
2737 /***********************************************************************
2738  *              SetProcessWorkingSetSize        [KERNEL32.@]
2739  * Sets the min/max working set sizes for a specified process.
2740  *
2741  * PARAMS
2742  *    hProcess [I] Handle to the process of interest
2743  *    minset   [I] Specifies minimum working set size
2744  *    maxset   [I] Specifies maximum working set size
2745  *
2746  * RETURNS
2747  *  Success: TRUE
2748  *  Failure: FALSE
2749  */
2750 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2751                                      SIZE_T maxset)
2752 {
2753     FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2754     if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2755         /* Trim the working set to zero */
2756         /* Swap the process out of physical RAM */
2757     }
2758     return TRUE;
2759 }
2760
2761 /***********************************************************************
2762  *           GetProcessWorkingSetSize    (KERNEL32.@)
2763  */
2764 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2765                                      PSIZE_T maxset)
2766 {
2767     FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2768     /* 32 MB working set size */
2769     if (minset) *minset = 32*1024*1024;
2770     if (maxset) *maxset = 32*1024*1024;
2771     return TRUE;
2772 }
2773
2774
2775 /***********************************************************************
2776  *           SetProcessShutdownParameters    (KERNEL32.@)
2777  */
2778 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2779 {
2780     FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2781     shutdown_flags = flags;
2782     shutdown_priority = level;
2783     return TRUE;
2784 }
2785
2786
2787 /***********************************************************************
2788  * GetProcessShutdownParameters                 (KERNEL32.@)
2789  *
2790  */
2791 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2792 {
2793     *lpdwLevel = shutdown_priority;
2794     *lpdwFlags = shutdown_flags;
2795     return TRUE;
2796 }
2797
2798
2799 /***********************************************************************
2800  *           GetProcessPriorityBoost    (KERNEL32.@)
2801  */
2802 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2803 {
2804     FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2805     
2806     /* Report that no boost is present.. */
2807     *pDisablePriorityBoost = FALSE;
2808     
2809     return TRUE;
2810 }
2811
2812 /***********************************************************************
2813  *           SetProcessPriorityBoost    (KERNEL32.@)
2814  */
2815 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2816 {
2817     FIXME("(%p,%d): stub\n",hprocess,disableboost);
2818     /* Say we can do it. I doubt the program will notice that we don't. */
2819     return TRUE;
2820 }
2821
2822
2823 /***********************************************************************
2824  *              ReadProcessMemory (KERNEL32.@)
2825  */
2826 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2827                                SIZE_T *bytes_read )
2828 {
2829     NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2830     if (status) SetLastError( RtlNtStatusToDosError(status) );
2831     return !status;
2832 }
2833
2834
2835 /***********************************************************************
2836  *           WriteProcessMemory                 (KERNEL32.@)
2837  */
2838 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2839                                 SIZE_T *bytes_written )
2840 {
2841     NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2842     if (status) SetLastError( RtlNtStatusToDosError(status) );
2843     return !status;
2844 }
2845
2846
2847 /****************************************************************************
2848  *              FlushInstructionCache (KERNEL32.@)
2849  */
2850 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2851 {
2852     NTSTATUS status;
2853     if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2854     status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2855     if (status) SetLastError( RtlNtStatusToDosError(status) );
2856     return !status;
2857 }
2858
2859
2860 /******************************************************************
2861  *              GetProcessIoCounters (KERNEL32.@)
2862  */
2863 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2864 {
2865     NTSTATUS    status;
2866
2867     status = NtQueryInformationProcess(hProcess, ProcessIoCounters, 
2868                                        ioc, sizeof(*ioc), NULL);
2869     if (status) SetLastError( RtlNtStatusToDosError(status) );
2870     return !status;
2871 }
2872
2873 /***********************************************************************
2874  * ProcessIdToSessionId   (KERNEL32.@)
2875  * This function is available on Terminal Server 4SP4 and Windows 2000
2876  */
2877 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2878 {
2879     /* According to MSDN, if the calling process is not in a terminal
2880      * services environment, then the sessionid returned is zero.
2881      */
2882     *sessionid_ptr = 0;
2883     return TRUE;
2884 }
2885
2886
2887 /***********************************************************************
2888  *              RegisterServiceProcess (KERNEL.491)
2889  *              RegisterServiceProcess (KERNEL32.@)
2890  *
2891  * A service process calls this function to ensure that it continues to run
2892  * even after a user logged off.
2893  */
2894 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2895 {
2896     /* I don't think that Wine needs to do anything in this function */
2897     return 1; /* success */
2898 }
2899
2900
2901 /***********************************************************************
2902  *           GetCurrentProcess   (KERNEL32.@)
2903  *
2904  * Get a handle to the current process.
2905  *
2906  * PARAMS
2907  *  None.
2908  *
2909  * RETURNS
2910  *  A handle representing the current process.
2911  */
2912 #undef GetCurrentProcess
2913 HANDLE WINAPI GetCurrentProcess(void)
2914 {
2915     return (HANDLE)0xffffffff;
2916 }