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