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