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