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