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