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