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