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