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