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