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