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