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