Copy the vsnprintfW implementation from libunicode.so to msvcrt and
[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     /* build command line */
1120     set_library_wargv( __wine_main_argv );
1121     if (!build_command_line( __wine_main_wargv )) goto error;
1122
1123     stack_size = RtlImageNtHeader(peb->ImageBaseAddress)->OptionalHeader.SizeOfStackReserve;
1124
1125     /* allocate main thread stack */
1126     if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
1127
1128     /* switch to the new stack */
1129     wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1130
1131  error:
1132     ExitProcess( GetLastError() );
1133 }
1134
1135
1136 /***********************************************************************
1137  *           build_argv
1138  *
1139  * Build an argv array from a command-line.
1140  * 'reserved' is the number of args to reserve before the first one.
1141  */
1142 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1143 {
1144     int argc;
1145     char** argv;
1146     char *arg,*s,*d,*cmdline;
1147     int in_quotes,bcount,len;
1148
1149     len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1150     if (!(cmdline = malloc(len))) return NULL;
1151     WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1152
1153     argc=reserved+1;
1154     bcount=0;
1155     in_quotes=0;
1156     s=cmdline;
1157     while (1) {
1158         if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1159             /* space */
1160             argc++;
1161             /* skip the remaining spaces */
1162             while (*s==' ' || *s=='\t') {
1163                 s++;
1164             }
1165             if (*s=='\0')
1166                 break;
1167             bcount=0;
1168             continue;
1169         } else if (*s=='\\') {
1170             /* '\', count them */
1171             bcount++;
1172         } else if ((*s=='"') && ((bcount & 1)==0)) {
1173             /* unescaped '"' */
1174             in_quotes=!in_quotes;
1175             bcount=0;
1176         } else {
1177             /* a regular character */
1178             bcount=0;
1179         }
1180         s++;
1181     }
1182     argv=malloc(argc*sizeof(*argv));
1183     if (!argv)
1184         return NULL;
1185
1186     arg=d=s=cmdline;
1187     bcount=0;
1188     in_quotes=0;
1189     argc=reserved;
1190     while (*s) {
1191         if ((*s==' ' || *s=='\t') && !in_quotes) {
1192             /* Close the argument and copy it */
1193             *d=0;
1194             argv[argc++]=arg;
1195
1196             /* skip the remaining spaces */
1197             do {
1198                 s++;
1199             } while (*s==' ' || *s=='\t');
1200
1201             /* Start with a new argument */
1202             arg=d=s;
1203             bcount=0;
1204         } else if (*s=='\\') {
1205             /* '\\' */
1206             *d++=*s++;
1207             bcount++;
1208         } else if (*s=='"') {
1209             /* '"' */
1210             if ((bcount & 1)==0) {
1211                 /* Preceeded by an even number of '\', this is half that
1212                  * number of '\', plus a '"' which we discard.
1213                  */
1214                 d-=bcount/2;
1215                 s++;
1216                 in_quotes=!in_quotes;
1217             } else {
1218                 /* Preceeded by an odd number of '\', this is half that
1219                  * number of '\' followed by a '"'
1220                  */
1221                 d=d-bcount/2-1;
1222                 *d++='"';
1223                 s++;
1224             }
1225             bcount=0;
1226         } else {
1227             /* a regular character */
1228             *d++=*s++;
1229             bcount=0;
1230         }
1231     }
1232     if (*arg) {
1233         *d='\0';
1234         argv[argc++]=arg;
1235     }
1236     argv[argc]=NULL;
1237
1238     return argv;
1239 }
1240
1241
1242 /***********************************************************************
1243  *           alloc_env_string
1244  *
1245  * Allocate an environment string; helper for build_envp
1246  */
1247 static char *alloc_env_string( const char *name, const char *value )
1248 {
1249     char *ret = malloc( strlen(name) + strlen(value) + 1 );
1250     strcpy( ret, name );
1251     strcat( ret, value );
1252     return ret;
1253 }
1254
1255 /***********************************************************************
1256  *           build_envp
1257  *
1258  * Build the environment of a new child process.
1259  */
1260 static char **build_envp( const WCHAR *envW )
1261 {
1262     const WCHAR *p;
1263     char **envp;
1264     char *env;
1265     int count = 0, length;
1266
1267     for (p = envW; *p; count++) p += strlenW(p) + 1;
1268     p++;
1269     length = WideCharToMultiByte( CP_UNIXCP, 0, envW, p - envW, NULL, 0, NULL, NULL );
1270     if (!(env = malloc( length ))) return NULL;
1271     WideCharToMultiByte( CP_UNIXCP, 0, envW, p - envW, env, length, NULL, NULL );
1272
1273     count += 4;
1274
1275     if ((envp = malloc( count * sizeof(*envp) )))
1276     {
1277         char **envptr = envp;
1278         char *p;
1279
1280         /* then put PATH, TEMP, TMP, HOME and WINEPREFIX from the unix env */
1281         if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1282         if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1283         if ((p = getenv("TMP")))  *envptr++ = alloc_env_string( "TMP=", p );
1284         if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1285         if ((p = getenv("WINEPREFIX"))) *envptr++ = alloc_env_string( "WINEPREFIX=", p );
1286         /* now put the Windows environment strings */
1287         for (p = env; *p; p += strlen(p) + 1)
1288         {
1289             if (is_special_env_var( p ))  /* prefix it with "WINE" */
1290                 *envptr++ = alloc_env_string( "WINE", p );
1291             else if (strncmp( p, "HOME=", 5 ) &&
1292                      strncmp( p, "WINEPREFIX=", 11 )) *envptr++ = p;
1293         }
1294         *envptr = 0;
1295     }
1296     return envp;
1297 }
1298
1299
1300 /***********************************************************************
1301  *           fork_and_exec
1302  *
1303  * Fork and exec a new Unix binary, checking for errors.
1304  */
1305 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1306                           const WCHAR *env, const char *newdir )
1307 {
1308     int fd[2];
1309     int pid, err;
1310
1311     if (!env) env = GetEnvironmentStringsW();
1312
1313     if (pipe(fd) == -1)
1314     {
1315         SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1316         return -1;
1317     }
1318     fcntl( fd[1], F_SETFD, 1 );  /* set close on exec */
1319     if (!(pid = fork()))  /* child */
1320     {
1321         char **argv = build_argv( cmdline, 0 );
1322         char **envp = build_envp( env );
1323         close( fd[0] );
1324
1325         /* Reset signals that we previously set to SIG_IGN */
1326         signal( SIGPIPE, SIG_DFL );
1327         signal( SIGCHLD, SIG_DFL );
1328
1329         if (newdir) chdir(newdir);
1330
1331         if (argv && envp) execve( filename, argv, envp );
1332         err = errno;
1333         write( fd[1], &err, sizeof(err) );
1334         _exit(1);
1335     }
1336     close( fd[1] );
1337     if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0))  /* exec failed */
1338     {
1339         errno = err;
1340         pid = -1;
1341     }
1342     if (pid == -1) FILE_SetDosError();
1343     close( fd[0] );
1344     return pid;
1345 }
1346
1347
1348 /***********************************************************************
1349  *           create_user_params
1350  */
1351 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1352                                                         LPCWSTR cur_dir, const STARTUPINFOW *startup )
1353 {
1354     RTL_USER_PROCESS_PARAMETERS *params;
1355     UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title;
1356     NTSTATUS status;
1357     WCHAR buffer[MAX_PATH];
1358
1359     if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1360         lstrcpynW( buffer, filename, MAX_PATH );
1361     if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1362         lstrcpynW( buffer, filename, MAX_PATH );
1363     RtlInitUnicodeString( &image_str, buffer );
1364
1365     RtlInitUnicodeString( &cmdline_str, cmdline );
1366     if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1367     if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1368     if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1369
1370     status = RtlCreateProcessParameters( &params, &image_str, NULL,
1371                                          cur_dir ? &curdir_str : NULL,
1372                                          &cmdline_str, NULL,
1373                                          startup->lpTitle ? &title : NULL,
1374                                          startup->lpDesktop ? &desktop : NULL,
1375                                          NULL, NULL );
1376     if (status != STATUS_SUCCESS)
1377     {
1378         SetLastError( RtlNtStatusToDosError(status) );
1379         return NULL;
1380     }
1381
1382     params->Environment     = NULL;  /* we pass it through the Unix environment */
1383     params->hStdInput       = startup->hStdInput;
1384     params->hStdOutput      = startup->hStdOutput;
1385     params->hStdError       = startup->hStdError;
1386     params->dwX             = startup->dwX;
1387     params->dwY             = startup->dwY;
1388     params->dwXSize         = startup->dwXSize;
1389     params->dwYSize         = startup->dwYSize;
1390     params->dwXCountChars   = startup->dwXCountChars;
1391     params->dwYCountChars   = startup->dwYCountChars;
1392     params->dwFillAttribute = startup->dwFillAttribute;
1393     params->dwFlags         = startup->dwFlags;
1394     params->wShowWindow     = startup->wShowWindow;
1395     return params;
1396 }
1397
1398
1399 /***********************************************************************
1400  *           create_process
1401  *
1402  * Create a new process. If hFile is a valid handle we have an exe
1403  * file, otherwise it is a Winelib app.
1404  */
1405 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1406                             LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1407                             BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1408                             LPPROCESS_INFORMATION info, LPCSTR unixdir )
1409 {
1410     BOOL ret, success = FALSE;
1411     HANDLE process_info;
1412     RTL_USER_PROCESS_PARAMETERS *params;
1413     int startfd[2];
1414     int execfd[2];
1415     pid_t pid;
1416     int err;
1417     char dummy = 0;
1418
1419     if (!env) env = GetEnvironmentStringsW();
1420
1421     if (!(params = create_user_params( filename, cmd_line, cur_dir, startup )))
1422         return FALSE;
1423
1424     /* create the synchronization pipes */
1425
1426     if (pipe( startfd ) == -1)
1427     {
1428         SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1429         RtlDestroyProcessParameters( params );
1430         return FALSE;
1431     }
1432     if (pipe( execfd ) == -1)
1433     {
1434         SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1435         close( startfd[0] );
1436         close( startfd[1] );
1437         RtlDestroyProcessParameters( params );
1438         return FALSE;
1439     }
1440     fcntl( execfd[1], F_SETFD, 1 );  /* set close on exec */
1441
1442     /* create the child process */
1443
1444     if (!(pid = fork()))  /* child */
1445     {
1446         char **argv = build_argv( cmd_line, 1 );
1447         char **envp = build_envp( env );
1448
1449         close( startfd[1] );
1450         close( execfd[0] );
1451
1452         /* wait for parent to tell us to start */
1453         if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1454
1455         close( startfd[0] );
1456         /* Reset signals that we previously set to SIG_IGN */
1457         signal( SIGPIPE, SIG_DFL );
1458         signal( SIGCHLD, SIG_DFL );
1459
1460         if (unixdir) chdir(unixdir);
1461
1462         if (argv && envp)
1463         {
1464             /* first, try for a WINELOADER environment variable */
1465             const char *loader = getenv("WINELOADER");
1466             if (loader) wine_exec_wine_binary( loader, argv, envp, TRUE );
1467             /* now use the standard search strategy */
1468             wine_exec_wine_binary( NULL, argv, envp, TRUE );
1469         }
1470         err = errno;
1471         write( execfd[1], &err, sizeof(err) );
1472         _exit(1);
1473     }
1474
1475     /* this is the parent */
1476
1477     close( startfd[0] );
1478     close( execfd[1] );
1479     if (pid == -1)
1480     {
1481         close( startfd[1] );
1482         close( execfd[0] );
1483         FILE_SetDosError();
1484         RtlDestroyProcessParameters( params );
1485         return FALSE;
1486     }
1487
1488     /* create the process on the server side */
1489
1490     SERVER_START_REQ( new_process )
1491     {
1492         req->inherit_all  = inherit;
1493         req->create_flags = flags;
1494         req->unix_pid     = pid;
1495         req->exe_file     = hFile;
1496         if (startup->dwFlags & STARTF_USESTDHANDLES)
1497         {
1498             req->hstdin  = startup->hStdInput;
1499             req->hstdout = startup->hStdOutput;
1500             req->hstderr = startup->hStdError;
1501         }
1502         else
1503         {
1504             req->hstdin  = GetStdHandle( STD_INPUT_HANDLE );
1505             req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1506             req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1507         }
1508
1509         if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1510         {
1511             /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1512             if (is_console_handle(req->hstdin))  req->hstdin  = INVALID_HANDLE_VALUE;
1513             if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1514             if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1515         }
1516         else
1517         {
1518             if (is_console_handle(req->hstdin))  req->hstdin  = console_handle_unmap(req->hstdin);
1519             if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1520             if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1521         }
1522
1523         wine_server_add_data( req, params, params->Size );
1524         ret = !wine_server_call_err( req );
1525         process_info = reply->info;
1526     }
1527     SERVER_END_REQ;
1528
1529     RtlDestroyProcessParameters( params );
1530     if (!ret)
1531     {
1532         close( startfd[1] );
1533         close( execfd[0] );
1534         return FALSE;
1535     }
1536
1537     /* tell child to start and wait for it to exec */
1538
1539     write( startfd[1], &dummy, 1 );
1540     close( startfd[1] );
1541
1542     if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1543     {
1544         errno = err;
1545         FILE_SetDosError();
1546         close( execfd[0] );
1547         CloseHandle( process_info );
1548         return FALSE;
1549     }
1550     close( execfd[0] );
1551
1552     /* wait for the new process info to be ready */
1553
1554     WaitForSingleObject( process_info, INFINITE );
1555     SERVER_START_REQ( get_new_process_info )
1556     {
1557         req->info     = process_info;
1558         req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1559         req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1560         if ((ret = !wine_server_call_err( req )))
1561         {
1562             info->dwProcessId = (DWORD)reply->pid;
1563             info->dwThreadId  = (DWORD)reply->tid;
1564             info->hProcess    = reply->phandle;
1565             info->hThread     = reply->thandle;
1566             success           = reply->success;
1567         }
1568     }
1569     SERVER_END_REQ;
1570
1571     if (ret && !success)  /* new process failed to start */
1572     {
1573         DWORD exitcode;
1574         if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1575         CloseHandle( info->hThread );
1576         CloseHandle( info->hProcess );
1577         ret = FALSE;
1578     }
1579     CloseHandle( process_info );
1580     return ret;
1581 }
1582
1583
1584 /***********************************************************************
1585  *           create_vdm_process
1586  *
1587  * Create a new VDM process for a 16-bit or DOS application.
1588  */
1589 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1590                                 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1591                                 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1592                                 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1593 {
1594     static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1595
1596     BOOL ret;
1597     LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1598                                      (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1599
1600     if (!new_cmd_line)
1601     {
1602         SetLastError( ERROR_OUTOFMEMORY );
1603         return FALSE;
1604     }
1605     sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1606     ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1607                           flags, startup, info, unixdir );
1608     HeapFree( GetProcessHeap(), 0, new_cmd_line );
1609     return ret;
1610 }
1611
1612
1613 /***********************************************************************
1614  *           create_cmd_process
1615  *
1616  * Create a new cmd shell process for a .BAT file.
1617  */
1618 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1619                                 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1620                                 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1621                                 LPPROCESS_INFORMATION info )
1622
1623 {
1624     static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1625     static const WCHAR slashcW[] = {' ','/','c',' ',0};
1626     WCHAR comspec[MAX_PATH];
1627     WCHAR *newcmdline;
1628     BOOL ret;
1629
1630     if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1631         return FALSE;
1632     if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1633                                   (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1634         return FALSE;
1635
1636     strcpyW( newcmdline, comspec );
1637     strcatW( newcmdline, slashcW );
1638     strcatW( newcmdline, cmd_line );
1639     ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1640                           flags, env, cur_dir, startup, info );
1641     HeapFree( GetProcessHeap(), 0, newcmdline );
1642     return ret;
1643 }
1644
1645
1646 /*************************************************************************
1647  *               get_file_name
1648  *
1649  * Helper for CreateProcess: retrieve the file name to load from the
1650  * app name and command line. Store the file name in buffer, and
1651  * return a possibly modified command line.
1652  * Also returns a handle to the opened file if it's a Windows binary.
1653  */
1654 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1655                              int buflen, HANDLE *handle )
1656 {
1657     static const WCHAR quotesW[] = {'"','%','s','"',0};
1658
1659     WCHAR *name, *pos, *ret = NULL;
1660     const WCHAR *p;
1661
1662     /* if we have an app name, everything is easy */
1663
1664     if (appname)
1665     {
1666         /* use the unmodified app name as file name */
1667         lstrcpynW( buffer, appname, buflen );
1668         *handle = open_exe_file( buffer );
1669         if (!(ret = cmdline) || !cmdline[0])
1670         {
1671             /* no command-line, create one */
1672             if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1673                 sprintfW( ret, quotesW, appname );
1674         }
1675         return ret;
1676     }
1677
1678     if (!cmdline)
1679     {
1680         SetLastError( ERROR_INVALID_PARAMETER );
1681         return NULL;
1682     }
1683
1684     /* first check for a quoted file name */
1685
1686     if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1687     {
1688         int len = p - cmdline - 1;
1689         /* extract the quoted portion as file name */
1690         if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1691         memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1692         name[len] = 0;
1693
1694         if (find_exe_file( name, buffer, buflen, handle ))
1695             ret = cmdline;  /* no change necessary */
1696         goto done;
1697     }
1698
1699     /* now try the command-line word by word */
1700
1701     if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1702         return NULL;
1703     pos = name;
1704     p = cmdline;
1705
1706     while (*p)
1707     {
1708         do *pos++ = *p++; while (*p && *p != ' ');
1709         *pos = 0;
1710         if (find_exe_file( name, buffer, buflen, handle ))
1711         {
1712             ret = cmdline;
1713             break;
1714         }
1715     }
1716
1717     if (!ret || !strchrW( name, ' ' )) goto done;  /* no change necessary */
1718
1719     /* now build a new command-line with quotes */
1720
1721     if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1722         goto done;
1723     sprintfW( ret, quotesW, name );
1724     strcatW( ret, p );
1725
1726  done:
1727     HeapFree( GetProcessHeap(), 0, name );
1728     return ret;
1729 }
1730
1731
1732 /**********************************************************************
1733  *       CreateProcessA          (KERNEL32.@)
1734  */
1735 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1736                             LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1737                             DWORD flags, LPVOID env, LPCSTR cur_dir,
1738                             LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1739 {
1740     BOOL ret = FALSE;
1741     WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1742     UNICODE_STRING desktopW, titleW;
1743     STARTUPINFOW infoW;
1744
1745     desktopW.Buffer = NULL;
1746     titleW.Buffer = NULL;
1747     if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1748     if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1749     if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1750
1751     if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1752     if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1753
1754     memcpy( &infoW, startup_info, sizeof(infoW) );
1755     infoW.lpDesktop = desktopW.Buffer;
1756     infoW.lpTitle = titleW.Buffer;
1757
1758     if (startup_info->lpReserved)
1759       FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1760             debugstr_a(startup_info->lpReserved));
1761
1762     ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1763                           inherit, flags, env, cur_dirW, &infoW, info );
1764 done:
1765     if (app_nameW) HeapFree( GetProcessHeap(), 0, app_nameW );
1766     if (cmd_lineW) HeapFree( GetProcessHeap(), 0, cmd_lineW );
1767     if (cur_dirW) HeapFree( GetProcessHeap(), 0, cur_dirW );
1768     RtlFreeUnicodeString( &desktopW );
1769     RtlFreeUnicodeString( &titleW );
1770     return ret;
1771 }
1772
1773
1774 /**********************************************************************
1775  *       CreateProcessW          (KERNEL32.@)
1776  */
1777 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1778                             LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1779                             LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1780                             LPPROCESS_INFORMATION info )
1781 {
1782     BOOL retv = FALSE;
1783     HANDLE hFile = 0;
1784     char *unixdir = NULL;
1785     WCHAR name[MAX_PATH];
1786     WCHAR *tidy_cmdline, *p, *envW = env;
1787
1788     /* Process the AppName and/or CmdLine to get module name and path */
1789
1790     TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1791
1792     if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1793         return FALSE;
1794     if (hFile == INVALID_HANDLE_VALUE) goto done;
1795
1796     /* Warn if unsupported features are used */
1797
1798     if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1799                  CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1800                  CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1801                  PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1802         WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1803
1804     if (cur_dir)
1805     {
1806         unixdir = wine_get_unix_file_name( cur_dir );
1807     }
1808     else
1809     {
1810         WCHAR buf[MAX_PATH];
1811         if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1812     }
1813
1814     if (env && !(flags & CREATE_UNICODE_ENVIRONMENT))  /* convert environment to unicode */
1815     {
1816         char *p = env;
1817         DWORD lenW;
1818
1819         while (*p) p += strlen(p) + 1;
1820         p++;  /* final null */
1821         lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1822         envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1823         MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1824         flags |= CREATE_UNICODE_ENVIRONMENT;
1825     }
1826
1827     info->hThread = info->hProcess = 0;
1828     info->dwProcessId = info->dwThreadId = 0;
1829
1830     /* Determine executable type */
1831
1832     if (!hFile)  /* builtin exe */
1833     {
1834         TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1835         retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1836                                inherit, flags, startup_info, info, unixdir );
1837         goto done;
1838     }
1839
1840     switch( MODULE_GetBinaryType( hFile ))
1841     {
1842     case BINARY_PE_EXE:
1843         TRACE( "starting %s as Win32 binary\n", debugstr_w(name) );
1844         retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1845                                inherit, flags, startup_info, info, unixdir );
1846         break;
1847     case BINARY_WIN16:
1848     case BINARY_DOS:
1849         TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1850         retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1851                                    inherit, flags, startup_info, info, unixdir );
1852         break;
1853     case BINARY_OS216:
1854         FIXME( "%s is OS/2 binary, not supported\n", debugstr_w(name) );
1855         SetLastError( ERROR_BAD_EXE_FORMAT );
1856         break;
1857     case BINARY_PE_DLL:
1858         TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1859         SetLastError( ERROR_BAD_EXE_FORMAT );
1860         break;
1861     case BINARY_UNIX_LIB:
1862         TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1863         retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1864                                inherit, flags, startup_info, info, unixdir );
1865         break;
1866     case BINARY_UNKNOWN:
1867         /* check for .com or .bat extension */
1868         if ((p = strrchrW( name, '.' )))
1869         {
1870             if (!strcmpiW( p, comW ))
1871             {
1872                 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1873                 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1874                                            inherit, flags, startup_info, info, unixdir );
1875                 break;
1876             }
1877             if (!strcmpiW( p, batW ))
1878             {
1879                 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1880                 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1881                                            inherit, flags, startup_info, info );
1882                 break;
1883             }
1884         }
1885         /* fall through */
1886     case BINARY_UNIX_EXE:
1887         {
1888             /* unknown file, try as unix executable */
1889             char *unix_name;
1890
1891             TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1892
1893             if ((unix_name = wine_get_unix_file_name( name )))
1894             {
1895                 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1896                 HeapFree( GetProcessHeap(), 0, unix_name );
1897             }
1898         }
1899         break;
1900     }
1901     CloseHandle( hFile );
1902
1903  done:
1904     if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1905     if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1906     if (unixdir) HeapFree( GetProcessHeap(), 0, unixdir );
1907     return retv;
1908 }
1909
1910
1911 /***********************************************************************
1912  *           wait_input_idle
1913  *
1914  * Wrapper to call WaitForInputIdle USER function
1915  */
1916 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1917
1918 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1919 {
1920     HMODULE mod = GetModuleHandleA( "user32.dll" );
1921     if (mod)
1922     {
1923         WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1924         if (ptr) return ptr( process, timeout );
1925     }
1926     return 0;
1927 }
1928
1929
1930 /***********************************************************************
1931  *           WinExec   (KERNEL32.@)
1932  */
1933 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1934 {
1935     PROCESS_INFORMATION info;
1936     STARTUPINFOA startup;
1937     char *cmdline;
1938     UINT ret;
1939
1940     memset( &startup, 0, sizeof(startup) );
1941     startup.cb = sizeof(startup);
1942     startup.dwFlags = STARTF_USESHOWWINDOW;
1943     startup.wShowWindow = nCmdShow;
1944
1945     /* cmdline needs to be writeable for CreateProcess */
1946     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1947     strcpy( cmdline, lpCmdLine );
1948
1949     if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1950                         0, NULL, NULL, &startup, &info ))
1951     {
1952         /* Give 30 seconds to the app to come up */
1953         if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1954             WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1955         ret = 33;
1956         /* Close off the handles */
1957         CloseHandle( info.hThread );
1958         CloseHandle( info.hProcess );
1959     }
1960     else if ((ret = GetLastError()) >= 32)
1961     {
1962         FIXME("Strange error set by CreateProcess: %d\n", ret );
1963         ret = 11;
1964     }
1965     HeapFree( GetProcessHeap(), 0, cmdline );
1966     return ret;
1967 }
1968
1969
1970 /**********************************************************************
1971  *          LoadModule    (KERNEL32.@)
1972  */
1973 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1974 {
1975     LOADPARMS32 *params = paramBlock;
1976     PROCESS_INFORMATION info;
1977     STARTUPINFOA startup;
1978     HINSTANCE hInstance;
1979     LPSTR cmdline, p;
1980     char filename[MAX_PATH];
1981     BYTE len;
1982
1983     if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1984
1985     if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1986         !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1987         return (HINSTANCE)GetLastError();
1988
1989     len = (BYTE)params->lpCmdLine[0];
1990     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
1991         return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
1992
1993     strcpy( cmdline, filename );
1994     p = cmdline + strlen(cmdline);
1995     *p++ = ' ';
1996     memcpy( p, params->lpCmdLine + 1, len );
1997     p[len] = 0;
1998
1999     memset( &startup, 0, sizeof(startup) );
2000     startup.cb = sizeof(startup);
2001     if (params->lpCmdShow)
2002     {
2003         startup.dwFlags = STARTF_USESHOWWINDOW;
2004         startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2005     }
2006
2007     if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2008                         params->lpEnvAddress, NULL, &startup, &info ))
2009     {
2010         /* Give 30 seconds to the app to come up */
2011         if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2012             WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2013         hInstance = (HINSTANCE)33;
2014         /* Close off the handles */
2015         CloseHandle( info.hThread );
2016         CloseHandle( info.hProcess );
2017     }
2018     else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
2019     {
2020         FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2021         hInstance = (HINSTANCE)11;
2022     }
2023
2024     HeapFree( GetProcessHeap(), 0, cmdline );
2025     return hInstance;
2026 }
2027
2028
2029 /******************************************************************************
2030  *           TerminateProcess   (KERNEL32.@)
2031  */
2032 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2033 {
2034     NTSTATUS status = NtTerminateProcess( handle, exit_code );
2035     if (status) SetLastError( RtlNtStatusToDosError(status) );
2036     return !status;
2037 }
2038
2039
2040 /***********************************************************************
2041  *           ExitProcess   (KERNEL32.@)
2042  */
2043 void WINAPI ExitProcess( DWORD status )
2044 {
2045     LdrShutdownProcess();
2046     SERVER_START_REQ( terminate_process )
2047     {
2048         /* send the exit code to the server */
2049         req->handle    = GetCurrentProcess();
2050         req->exit_code = status;
2051         wine_server_call( req );
2052     }
2053     SERVER_END_REQ;
2054     exit( status );
2055 }
2056
2057
2058 /***********************************************************************
2059  * GetExitCodeProcess [KERNEL32.@]
2060  *
2061  * Gets termination status of specified process
2062  *
2063  * RETURNS
2064  *   Success: TRUE
2065  *   Failure: FALSE
2066  */
2067 BOOL WINAPI GetExitCodeProcess(
2068     HANDLE hProcess,    /* [in] handle to the process */
2069     LPDWORD lpExitCode) /* [out] address to receive termination status */
2070 {
2071     BOOL ret;
2072     SERVER_START_REQ( get_process_info )
2073     {
2074         req->handle = hProcess;
2075         ret = !wine_server_call_err( req );
2076         if (ret && lpExitCode) *lpExitCode = reply->exit_code;
2077     }
2078     SERVER_END_REQ;
2079     return ret;
2080 }
2081
2082
2083 /***********************************************************************
2084  *           SetErrorMode   (KERNEL32.@)
2085  */
2086 UINT WINAPI SetErrorMode( UINT mode )
2087 {
2088     UINT old = process_error_mode;
2089     process_error_mode = mode;
2090     return old;
2091 }
2092
2093
2094 /**********************************************************************
2095  * TlsAlloc [KERNEL32.@]  Allocates a TLS index.
2096  *
2097  * Allocates a thread local storage index
2098  *
2099  * RETURNS
2100  *    Success: TLS Index
2101  *    Failure: 0xFFFFFFFF
2102  */
2103 DWORD WINAPI TlsAlloc( void )
2104 {
2105     DWORD index;
2106
2107     RtlAcquirePebLock();
2108     index = RtlFindClearBitsAndSet( NtCurrentTeb()->Peb->TlsBitmap, 1, 0 );
2109     if (index != ~0UL) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2110     else SetLastError( ERROR_NO_MORE_ITEMS );
2111     RtlReleasePebLock();
2112     return index;
2113 }
2114
2115
2116 /**********************************************************************
2117  * TlsFree [KERNEL32.@]  Releases a TLS index.
2118  *
2119  * Releases a thread local storage index, making it available for reuse
2120  *
2121  * RETURNS
2122  *    Success: TRUE
2123  *    Failure: FALSE
2124  */
2125 BOOL WINAPI TlsFree(
2126     DWORD index) /* [in] TLS Index to free */
2127 {
2128     BOOL ret;
2129
2130     RtlAcquirePebLock();
2131     ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2132     if (ret)
2133     {
2134         RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2135         NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2136     }
2137     else SetLastError( ERROR_INVALID_PARAMETER );
2138     RtlReleasePebLock();
2139     return TRUE;
2140 }
2141
2142
2143 /**********************************************************************
2144  * TlsGetValue [KERNEL32.@]  Gets value in a thread's TLS slot
2145  *
2146  * RETURNS
2147  *    Success: Value stored in calling thread's TLS slot for index
2148  *    Failure: 0 and GetLastError returns NO_ERROR
2149  */
2150 LPVOID WINAPI TlsGetValue(
2151     DWORD index) /* [in] TLS index to retrieve value for */
2152 {
2153     if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
2154     {
2155         SetLastError( ERROR_INVALID_PARAMETER );
2156         return NULL;
2157     }
2158     SetLastError( ERROR_SUCCESS );
2159     return NtCurrentTeb()->TlsSlots[index];
2160 }
2161
2162
2163 /**********************************************************************
2164  * TlsSetValue [KERNEL32.@]  Stores a value in the thread's TLS slot.
2165  *
2166  * RETURNS
2167  *    Success: TRUE
2168  *    Failure: FALSE
2169  */
2170 BOOL WINAPI TlsSetValue(
2171     DWORD index,  /* [in] TLS index to set value for */
2172     LPVOID value) /* [in] Value to be stored */
2173 {
2174     if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
2175     {
2176         SetLastError( ERROR_INVALID_PARAMETER );
2177         return FALSE;
2178     }
2179     NtCurrentTeb()->TlsSlots[index] = value;
2180     return TRUE;
2181 }
2182
2183
2184 /***********************************************************************
2185  *           GetProcessFlags    (KERNEL32.@)
2186  */
2187 DWORD WINAPI GetProcessFlags( DWORD processid )
2188 {
2189     IMAGE_NT_HEADERS *nt;
2190     DWORD flags = 0;
2191
2192     if (processid && processid != GetCurrentProcessId()) return 0;
2193
2194     if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2195     {
2196         if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2197             flags |= PDB32_CONSOLE_PROC;
2198     }
2199     if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2200     if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2201     return flags;
2202 }
2203
2204
2205 /***********************************************************************
2206  *           GetProcessDword    (KERNEL.485)
2207  *           GetProcessDword    (KERNEL32.18)
2208  * 'Of course you cannot directly access Windows internal structures'
2209  */
2210 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2211 {
2212     DWORD               x, y;
2213     STARTUPINFOW        siw;
2214
2215     TRACE("(%ld, %d)\n", dwProcessID, offset );
2216
2217     if (dwProcessID && dwProcessID != GetCurrentProcessId())
2218     {
2219         ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2220         return 0;
2221     }
2222
2223     switch ( offset )
2224     {
2225     case GPD_APP_COMPAT_FLAGS:
2226         return GetAppCompatFlags16(0);
2227     case GPD_LOAD_DONE_EVENT:
2228         return 0;
2229     case GPD_HINSTANCE16:
2230         return GetTaskDS16();
2231     case GPD_WINDOWS_VERSION:
2232         return GetExeVersion16();
2233     case GPD_THDB:
2234         return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2235     case GPD_PDB:
2236         return (DWORD)NtCurrentTeb()->Peb;
2237     case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2238         GetStartupInfoW(&siw);
2239         return (DWORD)siw.hStdOutput;
2240     case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2241         GetStartupInfoW(&siw);
2242         return (DWORD)siw.hStdInput;
2243     case GPD_STARTF_SHOWWINDOW:
2244         GetStartupInfoW(&siw);
2245         return siw.wShowWindow;
2246     case GPD_STARTF_SIZE:
2247         GetStartupInfoW(&siw);
2248         x = siw.dwXSize;
2249         if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2250         y = siw.dwYSize;
2251         if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2252         return MAKELONG( x, y );
2253     case GPD_STARTF_POSITION:
2254         GetStartupInfoW(&siw);
2255         x = siw.dwX;
2256         if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2257         y = siw.dwY;
2258         if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2259         return MAKELONG( x, y );
2260     case GPD_STARTF_FLAGS:
2261         GetStartupInfoW(&siw);
2262         return siw.dwFlags;
2263     case GPD_PARENT:
2264         return 0;
2265     case GPD_FLAGS:
2266         return GetProcessFlags(0);
2267     case GPD_USERDATA:
2268         return process_dword;
2269     default:
2270         ERR("Unknown offset %d\n", offset );
2271         return 0;
2272     }
2273 }
2274
2275 /***********************************************************************
2276  *           SetProcessDword    (KERNEL.484)
2277  * 'Of course you cannot directly access Windows internal structures'
2278  */
2279 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2280 {
2281     TRACE("(%ld, %d)\n", dwProcessID, offset );
2282
2283     if (dwProcessID && dwProcessID != GetCurrentProcessId())
2284     {
2285         ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2286         return;
2287     }
2288
2289     switch ( offset )
2290     {
2291     case GPD_APP_COMPAT_FLAGS:
2292     case GPD_LOAD_DONE_EVENT:
2293     case GPD_HINSTANCE16:
2294     case GPD_WINDOWS_VERSION:
2295     case GPD_THDB:
2296     case GPD_PDB:
2297     case GPD_STARTF_SHELLDATA:
2298     case GPD_STARTF_HOTKEY:
2299     case GPD_STARTF_SHOWWINDOW:
2300     case GPD_STARTF_SIZE:
2301     case GPD_STARTF_POSITION:
2302     case GPD_STARTF_FLAGS:
2303     case GPD_PARENT:
2304     case GPD_FLAGS:
2305         ERR("Not allowed to modify offset %d\n", offset );
2306         break;
2307     case GPD_USERDATA:
2308         process_dword = value;
2309         break;
2310     default:
2311         ERR("Unknown offset %d\n", offset );
2312         break;
2313     }
2314 }
2315
2316
2317 /***********************************************************************
2318  *           ExitProcess   (KERNEL.466)
2319  */
2320 void WINAPI ExitProcess16( WORD status )
2321 {
2322     DWORD count;
2323     ReleaseThunkLock( &count );
2324     ExitProcess( status );
2325 }
2326
2327
2328 /*********************************************************************
2329  *           OpenProcess   (KERNEL32.@)
2330  */
2331 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2332 {
2333     HANDLE ret = 0;
2334     SERVER_START_REQ( open_process )
2335     {
2336         req->pid     = id;
2337         req->access  = access;
2338         req->inherit = inherit;
2339         if (!wine_server_call_err( req )) ret = reply->handle;
2340     }
2341     SERVER_END_REQ;
2342     return ret;
2343 }
2344
2345
2346 /*********************************************************************
2347  *           MapProcessHandle   (KERNEL.483)
2348  */
2349 DWORD WINAPI MapProcessHandle( HANDLE handle )
2350 {
2351     DWORD ret = 0;
2352     SERVER_START_REQ( get_process_info )
2353     {
2354         req->handle = handle;
2355         if (!wine_server_call_err( req )) ret = reply->pid;
2356     }
2357     SERVER_END_REQ;
2358     return ret;
2359 }
2360
2361
2362 /*********************************************************************
2363  *           CloseW32Handle (KERNEL.474)
2364  *           CloseHandle    (KERNEL32.@)
2365  */
2366 BOOL WINAPI CloseHandle( HANDLE handle )
2367 {
2368     NTSTATUS status;
2369
2370     /* stdio handles need special treatment */
2371     if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2372         (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2373         (handle == (HANDLE)STD_ERROR_HANDLE))
2374         handle = GetStdHandle( (DWORD)handle );
2375
2376     if (is_console_handle(handle))
2377         return CloseConsoleHandle(handle);
2378
2379     status = NtClose( handle );
2380     if (status) SetLastError( RtlNtStatusToDosError(status) );
2381     return !status;
2382 }
2383
2384
2385 /*********************************************************************
2386  *           GetHandleInformation   (KERNEL32.@)
2387  */
2388 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2389 {
2390     BOOL ret;
2391     SERVER_START_REQ( set_handle_info )
2392     {
2393         req->handle = handle;
2394         req->flags  = 0;
2395         req->mask   = 0;
2396         req->fd     = -1;
2397         ret = !wine_server_call_err( req );
2398         if (ret && flags) *flags = reply->old_flags;
2399     }
2400     SERVER_END_REQ;
2401     return ret;
2402 }
2403
2404
2405 /*********************************************************************
2406  *           SetHandleInformation   (KERNEL32.@)
2407  */
2408 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2409 {
2410     BOOL ret;
2411     SERVER_START_REQ( set_handle_info )
2412     {
2413         req->handle = handle;
2414         req->flags  = flags;
2415         req->mask   = mask;
2416         req->fd     = -1;
2417         ret = !wine_server_call_err( req );
2418     }
2419     SERVER_END_REQ;
2420     return ret;
2421 }
2422
2423
2424 /*********************************************************************
2425  *           DuplicateHandle   (KERNEL32.@)
2426  */
2427 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2428                              HANDLE dest_process, HANDLE *dest,
2429                              DWORD access, BOOL inherit, DWORD options )
2430 {
2431     NTSTATUS status;
2432
2433     if (is_console_handle(source))
2434     {
2435         /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2436         if (source_process != dest_process ||
2437             source_process != GetCurrentProcess())
2438         {
2439             SetLastError(ERROR_INVALID_PARAMETER);
2440             return FALSE;
2441         }
2442         *dest = DuplicateConsoleHandle( source, access, inherit, options );
2443         return (*dest != INVALID_HANDLE_VALUE);
2444     }
2445     status = NtDuplicateObject( source_process, source, dest_process, dest,
2446                                 access, inherit ? OBJ_INHERIT : 0, options );
2447     if (status) SetLastError( RtlNtStatusToDosError(status) );
2448     return !status;
2449 }
2450
2451
2452 /***********************************************************************
2453  *           ConvertToGlobalHandle   (KERNEL.476)
2454  *           ConvertToGlobalHandle  (KERNEL32.@)
2455  */
2456 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2457 {
2458     HANDLE ret = INVALID_HANDLE_VALUE;
2459     DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2460                      DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2461     return ret;
2462 }
2463
2464
2465 /***********************************************************************
2466  *           SetHandleContext   (KERNEL32.@)
2467  */
2468 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2469 {
2470     FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2471           "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2472     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2473     return FALSE;
2474 }
2475
2476
2477 /***********************************************************************
2478  *           GetHandleContext   (KERNEL32.@)
2479  */
2480 DWORD WINAPI GetHandleContext(HANDLE hnd)
2481 {
2482     FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2483           "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2484     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2485     return 0;
2486 }
2487
2488
2489 /***********************************************************************
2490  *           CreateSocketHandle   (KERNEL32.@)
2491  */
2492 HANDLE WINAPI CreateSocketHandle(void)
2493 {
2494     FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2495           "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2496     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2497     return INVALID_HANDLE_VALUE;
2498 }
2499
2500
2501 /***********************************************************************
2502  *           SetPriorityClass   (KERNEL32.@)
2503  */
2504 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2505 {
2506     BOOL ret;
2507     SERVER_START_REQ( set_process_info )
2508     {
2509         req->handle   = hprocess;
2510         req->priority = priorityclass;
2511         req->mask     = SET_PROCESS_INFO_PRIORITY;
2512         ret = !wine_server_call_err( req );
2513     }
2514     SERVER_END_REQ;
2515     return ret;
2516 }
2517
2518
2519 /***********************************************************************
2520  *           GetPriorityClass   (KERNEL32.@)
2521  */
2522 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
2523 {
2524     DWORD ret = 0;
2525     SERVER_START_REQ( get_process_info )
2526     {
2527         req->handle = hprocess;
2528         if (!wine_server_call_err( req )) ret = reply->priority;
2529     }
2530     SERVER_END_REQ;
2531     return ret;
2532 }
2533
2534
2535 /***********************************************************************
2536  *          SetProcessAffinityMask   (KERNEL32.@)
2537  */
2538 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
2539 {
2540     BOOL ret;
2541     SERVER_START_REQ( set_process_info )
2542     {
2543         req->handle   = hProcess;
2544         req->affinity = affmask;
2545         req->mask     = SET_PROCESS_INFO_AFFINITY;
2546         ret = !wine_server_call_err( req );
2547     }
2548     SERVER_END_REQ;
2549     return ret;
2550 }
2551
2552
2553 /**********************************************************************
2554  *          GetProcessAffinityMask    (KERNEL32.@)
2555  */
2556 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2557                                       LPDWORD lpProcessAffinityMask,
2558                                       LPDWORD lpSystemAffinityMask )
2559 {
2560     BOOL ret = FALSE;
2561     SERVER_START_REQ( get_process_info )
2562     {
2563         req->handle = hProcess;
2564         if (!wine_server_call_err( req ))
2565         {
2566             if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2567             if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2568             ret = TRUE;
2569         }
2570     }
2571     SERVER_END_REQ;
2572     return ret;
2573 }
2574
2575
2576 /***********************************************************************
2577  *           GetProcessVersion    (KERNEL32.@)
2578  */
2579 DWORD WINAPI GetProcessVersion( DWORD processid )
2580 {
2581     IMAGE_NT_HEADERS *nt;
2582
2583     if (processid && processid != GetCurrentProcessId())
2584     {
2585         FIXME("should use ReadProcessMemory\n");
2586         return 0;
2587     }
2588     if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2589         return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2590                 nt->OptionalHeader.MinorSubsystemVersion);
2591     return 0;
2592 }
2593
2594
2595 /***********************************************************************
2596  *              SetProcessWorkingSetSize        [KERNEL32.@]
2597  * Sets the min/max working set sizes for a specified process.
2598  *
2599  * PARAMS
2600  *    hProcess [I] Handle to the process of interest
2601  *    minset   [I] Specifies minimum working set size
2602  *    maxset   [I] Specifies maximum working set size
2603  *
2604  * RETURNS  STD
2605  */
2606 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2607                                      SIZE_T maxset)
2608 {
2609     FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2610     if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2611         /* Trim the working set to zero */
2612         /* Swap the process out of physical RAM */
2613     }
2614     return TRUE;
2615 }
2616
2617 /***********************************************************************
2618  *           GetProcessWorkingSetSize    (KERNEL32.@)
2619  */
2620 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2621                                      PSIZE_T maxset)
2622 {
2623     FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2624     /* 32 MB working set size */
2625     if (minset) *minset = 32*1024*1024;
2626     if (maxset) *maxset = 32*1024*1024;
2627     return TRUE;
2628 }
2629
2630
2631 /***********************************************************************
2632  *           SetProcessShutdownParameters    (KERNEL32.@)
2633  */
2634 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2635 {
2636     FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2637     shutdown_flags = flags;
2638     shutdown_priority = level;
2639     return TRUE;
2640 }
2641
2642
2643 /***********************************************************************
2644  * GetProcessShutdownParameters                 (KERNEL32.@)
2645  *
2646  */
2647 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2648 {
2649     *lpdwLevel = shutdown_priority;
2650     *lpdwFlags = shutdown_flags;
2651     return TRUE;
2652 }
2653
2654
2655 /***********************************************************************
2656  *           GetProcessPriorityBoost    (KERNEL32.@)
2657  */
2658 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2659 {
2660     FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2661     
2662     /* Report that no boost is present.. */
2663     *pDisablePriorityBoost = FALSE;
2664     
2665     return TRUE;
2666 }
2667
2668 /***********************************************************************
2669  *           SetProcessPriorityBoost    (KERNEL32.@)
2670  */
2671 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2672 {
2673     FIXME("(%p,%d): stub\n",hprocess,disableboost);
2674     /* Say we can do it. I doubt the program will notice that we don't. */
2675     return TRUE;
2676 }
2677
2678
2679 /***********************************************************************
2680  *              ReadProcessMemory (KERNEL32.@)
2681  */
2682 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2683                                SIZE_T *bytes_read )
2684 {
2685     NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2686     if (status) SetLastError( RtlNtStatusToDosError(status) );
2687     return !status;
2688 }
2689
2690
2691 /***********************************************************************
2692  *           WriteProcessMemory                 (KERNEL32.@)
2693  */
2694 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2695                                 SIZE_T *bytes_written )
2696 {
2697     NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2698     if (status) SetLastError( RtlNtStatusToDosError(status) );
2699     return !status;
2700 }
2701
2702
2703 /****************************************************************************
2704  *              FlushInstructionCache (KERNEL32.@)
2705  */
2706 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2707 {
2708     if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2709     FIXME("(%p,%p,0x%08lx): stub\n",hProcess, lpBaseAddress, dwSize);
2710     return TRUE;
2711 }
2712
2713
2714 /******************************************************************
2715  *              GetProcessIoCounters (KERNEL32.@)
2716  */
2717 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2718 {
2719     NTSTATUS    status;
2720
2721     status = NtQueryInformationProcess(hProcess, ProcessIoCounters, 
2722                                        ioc, sizeof(*ioc), NULL);
2723     if (status) SetLastError( RtlNtStatusToDosError(status) );
2724     return !status;
2725 }
2726
2727 /***********************************************************************
2728  * ProcessIdToSessionId   (KERNEL32.@)
2729  * This function is available on Terminal Server 4SP4 and Windows 2000
2730  */
2731 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2732 {
2733     /* According to MSDN, if the calling process is not in a terminal
2734      * services environment, then the sessionid returned is zero.
2735      */
2736     *sessionid_ptr = 0;
2737     return TRUE;
2738 }
2739
2740
2741 /***********************************************************************
2742  *              RegisterServiceProcess (KERNEL.491)
2743  *              RegisterServiceProcess (KERNEL32.@)
2744  *
2745  * A service process calls this function to ensure that it continues to run
2746  * even after a user logged off.
2747  */
2748 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2749 {
2750     /* I don't think that Wine needs to do anything in that function */
2751     return 1; /* success */
2752 }
2753
2754
2755 /***********************************************************************
2756  *           GetSystemMSecCount (SYSTEM.6)
2757  *           GetTickCount       (KERNEL32.@)
2758  *
2759  * Returns the number of milliseconds, modulo 2^32, since the start
2760  * of the wineserver.
2761  */
2762 DWORD WINAPI GetTickCount(void)
2763 {
2764     struct timeval t;
2765     gettimeofday( &t, NULL );
2766     return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
2767 }
2768
2769
2770 /***********************************************************************
2771  *           GetCurrentProcess   (KERNEL32.@)
2772  */
2773 #undef GetCurrentProcess
2774 HANDLE WINAPI GetCurrentProcess(void)
2775 {
2776     return (HANDLE)0xffffffff;
2777 }