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