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