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