Converted the load order code to use Unicode throughout.
[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
31 #include "wine/winbase16.h"
32 #include "wine/winuser16.h"
33 #include "ntstatus.h"
34 #include "thread.h"
35 #include "drive.h"
36 #include "file.h"
37 #include "heap.h"
38 #include "module.h"
39 #include "options.h"
40 #include "kernel_private.h"
41 #include "wine/server.h"
42 #include "wine/debug.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(process);
45 WINE_DECLARE_DEBUG_CHANNEL(server);
46 WINE_DECLARE_DEBUG_CHANNEL(relay);
47 WINE_DECLARE_DEBUG_CHANNEL(snoop);
48
49 /* Win32 process database */
50 typedef struct _PDB
51 {
52     LONG             header[2];        /* 00 Kernel object header */
53     HMODULE          module;           /* 08 Main exe module (NT) */
54     PPEB_LDR_DATA    LdrData;          /* 0c Pointer to loader information */
55     RTL_USER_PROCESS_PARAMETERS *ProcessParameters;  /*  10 Process parameters */
56     DWORD            unknown2;         /* 14 Unknown */
57     HANDLE           heap;             /* 18 Default process heap */
58     HANDLE           mem_context;      /* 1c Process memory context */
59     DWORD            flags;            /* 20 Flags */
60     void            *pdb16;            /* 24 DOS PSP */
61     WORD             PSP_sel;          /* 28 Selector to DOS PSP */
62     WORD             imte;             /* 2a IMTE for the process module */
63     WORD             threads;          /* 2c Number of threads */
64     WORD             running_threads;  /* 2e Number of running threads */
65     WORD             free_lib_count;   /* 30 Recursion depth of FreeLibrary calls */
66     WORD             ring0_threads;    /* 32 Number of ring 0 threads */
67     HANDLE           system_heap;      /* 34 System heap to allocate handles */
68     HTASK            task;             /* 38 Win16 task */
69     void            *mem_map_files;    /* 3c Pointer to mem-mapped files */
70     struct _ENVDB   *env_db;           /* 40 Environment database */
71     void            *handle_table;     /* 44 Handle table */
72     struct _PDB     *parent;           /* 48 Parent process */
73     void            *modref_list;      /* 4c MODREF list */
74     void            *thread_list;      /* 50 List of threads */
75     void            *debuggee_CB;      /* 54 Debuggee context block */
76     void            *local_heap_free;  /* 58 Head of local heap free list */
77     DWORD            unknown4;         /* 5c Unknown */
78     CRITICAL_SECTION crit_section;     /* 60 Critical section */
79     DWORD            unknown5[3];      /* 78 Unknown */
80     void            *console;          /* 84 Console */
81     DWORD            tls_bits[2];      /* 88 TLS in-use bits */
82     DWORD            process_dword;    /* 90 Unknown */
83     struct _PDB     *group;            /* 94 Process group */
84     void            *exe_modref;       /* 98 MODREF for the process EXE */
85     void            *top_filter;       /* 9c Top exception filter */
86     DWORD            priority;         /* a0 Priority level */
87     HANDLE           heap_list;        /* a4 Head of process heap list */
88     void            *heap_handles;     /* a8 Head of heap handles list */
89     DWORD            unknown6;         /* ac Unknown */
90     void            *console_provider; /* b0 Console provider (??) */
91     WORD             env_selector;     /* b4 Selector to process environment */
92     WORD             error_mode;       /* b6 Error mode */
93     HANDLE           load_done_evt;    /* b8 Event for process loading done */
94     void            *UTState;          /* bc Head of Univeral Thunk list */
95     DWORD            unknown8;         /* c0 Unknown (NT) */
96     LCID             locale;           /* c4 Locale to be queried by GetThreadLocale (NT) */
97 } PDB;
98
99 PDB current_process;
100
101 static RTL_USER_PROCESS_PARAMETERS      process_pmts;
102 static PEB_LDR_DATA                     process_ldr;
103
104 static char main_exe_name[MAX_PATH];
105 static char *main_exe_name_ptr = main_exe_name;
106 static HANDLE main_exe_file;
107 static DWORD shutdown_flags = 0;
108 static DWORD shutdown_priority = 0x280;
109 static DWORD process_dword;
110 static BOOL oem_file_apis;
111
112 extern unsigned int server_startticks;
113 int main_create_flags = 0;
114
115 /* Process flags */
116 #define PDB32_DEBUGGED      0x0001  /* Process is being debugged */
117 #define PDB32_WIN16_PROC    0x0008  /* Win16 process */
118 #define PDB32_DOS_PROC      0x0010  /* Dos process */
119 #define PDB32_CONSOLE_PROC  0x0020  /* Console process */
120 #define PDB32_FILE_APIS_OEM 0x0040  /* File APIs are OEM */
121 #define PDB32_WIN32S_PROC   0x8000  /* Win32s process */
122
123 /* dlls/ntdll/env.c */
124 extern BOOL init_user_process_pmts( size_t, char*, size_t );
125 extern BOOL build_command_line( char **argv );
126
127 extern WINE_MODREF *MODULE_AllocModRef( HMODULE hModule, LPCSTR filename );  /* FIXME */
128
129 extern void RELAY_InitDebugLists(void);
130 extern void SHELL_LoadRegistry(void);
131 extern void VERSION_Init( const char *appname );
132
133 /***********************************************************************
134  *           get_basename
135  */
136 inline static const char *get_basename( const char *name )
137 {
138     char *p;
139
140     if ((p = strrchr( name, '/' ))) name = p + 1;
141     if ((p = strrchr( name, '\\' ))) name = p + 1;
142     return name;
143 }
144
145
146 /***********************************************************************
147  *           open_builtin_exe_file
148  *
149  * Open an exe file for a builtin exe.
150  */
151 static void *open_builtin_exe_file( const char *name, char *error, int error_size,
152                                     int test_only, int *file_exists )
153 {
154     char exename[MAX_PATH], *p;
155     const char *basename = get_basename(name);
156
157     if (strlen(basename) >= sizeof(exename)) return NULL;
158     strcpy( exename, basename );
159     for (p = exename; *p; p++) *p = FILE_tolower(*p);
160     return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
161 }
162
163
164 /***********************************************************************
165  *           open_exe_file
166  *
167  * Open a specific exe file, taking load order into account.
168  * Returns the file handle or 0 for a builtin exe.
169  */
170 static HANDLE open_exe_file( const char *name )
171 {
172     enum loadorder_type loadorder[LOADORDER_NTYPES];
173     char buffer[MAX_PATH];
174     HANDLE handle;
175     int i, file_exists;
176
177     TRACE("looking for %s\n", debugstr_a(name) );
178
179     if ((handle = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
180                                NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
181     {
182         /* file doesn't exist, check for builtin */
183         if (!FILE_contains_path( name )) goto error;
184         if (!MODULE_GetBuiltinPath( name, "", buffer, sizeof(buffer) )) goto error;
185         name = buffer;
186     }
187
188     MODULE_GetLoadOrderA( loadorder, NULL, name, TRUE );
189
190     for(i = 0; i < LOADORDER_NTYPES; i++)
191     {
192         if (loadorder[i] == LOADORDER_INVALID) break;
193         switch(loadorder[i])
194         {
195         case LOADORDER_DLL:
196             TRACE( "Trying native exe %s\n", debugstr_a(name) );
197             if (handle != INVALID_HANDLE_VALUE) return handle;
198             break;
199         case LOADORDER_BI:
200             TRACE( "Trying built-in exe %s\n", debugstr_a(name) );
201             open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
202             if (file_exists)
203             {
204                 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
205                 return 0;
206             }
207         default:
208             break;
209         }
210     }
211     if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
212
213  error:
214     SetLastError( ERROR_FILE_NOT_FOUND );
215     return INVALID_HANDLE_VALUE;
216 }
217
218
219 /***********************************************************************
220  *           find_exe_file
221  *
222  * Open an exe file, and return the full name and file handle.
223  * Returns FALSE if file could not be found.
224  * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
225  * If file is a builtin exe, returns TRUE and sets handle to 0.
226  */
227 static BOOL find_exe_file( const char *name, char *buffer, int buflen, HANDLE *handle )
228 {
229     enum loadorder_type loadorder[LOADORDER_NTYPES];
230     int i, file_exists;
231
232     TRACE("looking for %s\n", debugstr_a(name) );
233
234     if (!SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) &&
235         !MODULE_GetBuiltinPath( name, ".exe", buffer, buflen ))
236     {
237         /* no builtin found, try native without extension in case it is a Unix app */
238
239         if (SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
240         {
241             TRACE( "Trying native/Unix binary %s\n", debugstr_a(buffer) );
242             if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
243                                         NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
244                 return TRUE;
245         }
246         return FALSE;
247     }
248
249     MODULE_GetLoadOrderA( loadorder, NULL, buffer, TRUE );
250
251     for(i = 0; i < LOADORDER_NTYPES; i++)
252     {
253         if (loadorder[i] == LOADORDER_INVALID) break;
254         switch(loadorder[i])
255         {
256         case LOADORDER_DLL:
257             TRACE( "Trying native exe %s\n", debugstr_a(buffer) );
258             if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
259                                         NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
260                 return TRUE;
261             if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
262             break;
263         case LOADORDER_BI:
264             TRACE( "Trying built-in exe %s\n", debugstr_a(buffer) );
265             open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
266             if (file_exists)
267             {
268                 *handle = 0;
269                 return TRUE;
270             }
271             break;
272         default:
273             break;
274         }
275     }
276     SetLastError( ERROR_FILE_NOT_FOUND );
277     return FALSE;
278 }
279
280
281 /**********************************************************************
282  *           load_pe_exe
283  *
284  * Load a PE format EXE file.
285  */
286 static HMODULE load_pe_exe( HANDLE file )
287 {
288     IMAGE_NT_HEADERS *nt;
289     HANDLE mapping;
290     void *module;
291     OBJECT_ATTRIBUTES attr;
292     LARGE_INTEGER size;
293     DWORD len = 0;
294
295     attr.Length                   = sizeof(attr);
296     attr.RootDirectory            = 0;
297     attr.ObjectName               = NULL;
298     attr.Attributes               = 0;
299     attr.SecurityDescriptor       = NULL;
300     attr.SecurityQualityOfService = NULL;
301     size.QuadPart = 0;
302
303     if (NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
304                          &attr, &size, 0, SEC_IMAGE, file ) != STATUS_SUCCESS)
305         return NULL;
306
307     module = NULL;
308     if (NtMapViewOfSection( mapping, GetCurrentProcess(), &module, 0, 0, &size, &len,
309                             ViewShare, 0, PAGE_READONLY ) != STATUS_SUCCESS)
310         return NULL;
311
312     NtClose( mapping );
313
314     /* virus check */
315     nt = RtlImageNtHeader( module );
316     if (nt->OptionalHeader.AddressOfEntryPoint)
317     {
318         if (!RtlImageRvaToSection( nt, module, nt->OptionalHeader.AddressOfEntryPoint ))
319             MESSAGE("VIRUS WARNING: PE module has an invalid entrypoint (0x%08lx) "
320                     "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
321                     nt->OptionalHeader.AddressOfEntryPoint );
322     }
323     return module;
324 }
325
326 /***********************************************************************
327  *           process_init
328  *
329  * Main process initialisation code
330  */
331 static BOOL process_init( char *argv[] )
332 {
333     BOOL ret;
334     size_t info_size = 0;
335
336     setbuf(stdout,NULL);
337     setbuf(stderr,NULL);
338     setlocale(LC_CTYPE,"");
339
340     /* store the program name */
341     argv0 = argv[0];
342
343     /* Fill the initial process structure */
344     current_process.threads           = 1;
345     current_process.running_threads   = 1;
346     current_process.ring0_threads     = 1;
347     current_process.group             = &current_process;
348     current_process.priority          = 8;  /* Normal */
349     current_process.ProcessParameters = &process_pmts;
350     current_process.LdrData           = &process_ldr;
351     InitializeListHead(&process_ldr.InLoadOrderModuleList);
352     InitializeListHead(&process_ldr.InMemoryOrderModuleList);
353     InitializeListHead(&process_ldr.InInitializationOrderModuleList);
354
355     /* Setup the server connection */
356     wine_server_init_thread();
357
358     /* Retrieve startup info from the server */
359     SERVER_START_REQ( init_process )
360     {
361         req->ldt_copy  = &wine_ldt_copy;
362         if ((ret = !wine_server_call_err( req )))
363         {
364             main_exe_file     = reply->exe_file;
365             main_create_flags = reply->create_flags;
366             info_size         = reply->info_size;
367             server_startticks = reply->server_start;
368             process_pmts.hStdInput   = reply->hstdin;
369             process_pmts.hStdOutput  = reply->hstdout;
370             process_pmts.hStdError   = reply->hstderr;
371         }
372     }
373     SERVER_END_REQ;
374     if (!ret) return FALSE;
375
376     /* Create the process heap */
377     current_process.heap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL );
378
379     if (info_size == 0)
380     {
381         /* This is wine specific: we have no parent (we're started from unix)
382          * so, create a simple console with bare handles to unix stdio 
383          * input & output streams (aka simple console)
384          */
385         wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE,  TRUE, &process_pmts.hStdInput );
386         wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &process_pmts.hStdOutput );
387         wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, &process_pmts.hStdError );
388     }
389     else
390     {
391         /* convert value from server:
392          * + 0 => INVALID_HANDLE_VALUE
393          * + console handle need to be mapped
394          */
395         if (!process_pmts.hStdInput)
396             process_pmts.hStdInput = INVALID_HANDLE_VALUE;
397         else if (VerifyConsoleIoHandle(console_handle_map(process_pmts.hStdInput)))
398             process_pmts.hStdInput = console_handle_map(process_pmts.hStdInput);
399         if (!process_pmts.hStdOutput)
400             process_pmts.hStdOutput = INVALID_HANDLE_VALUE;
401         else if (VerifyConsoleIoHandle(console_handle_map(process_pmts.hStdOutput)))
402             process_pmts.hStdOutput = console_handle_map(process_pmts.hStdOutput);
403         if (!process_pmts.hStdError)
404             process_pmts.hStdError = INVALID_HANDLE_VALUE;
405         else if (VerifyConsoleIoHandle(console_handle_map(process_pmts.hStdError)))
406             process_pmts.hStdError = console_handle_map(process_pmts.hStdError);
407     }
408
409     /* Copy the parent environment */
410     if (!init_user_process_pmts( info_size, main_exe_name, sizeof(main_exe_name) ))
411         return FALSE;
412
413     /* Parse command line arguments */
414     OPTIONS_ParseOptions( !info_size ? argv : NULL );
415
416     /* <hack: to be changed later on> */
417     process_pmts.CurrentDirectoryName.Length = 3 * sizeof(WCHAR);
418     process_pmts.CurrentDirectoryName.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
419     process_pmts.CurrentDirectoryName.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, process_pmts.CurrentDirectoryName.MaximumLength);
420     process_pmts.CurrentDirectoryName.Buffer[0] = 'C';
421     process_pmts.CurrentDirectoryName.Buffer[1] = ':';
422     process_pmts.CurrentDirectoryName.Buffer[2] = '\\';
423     process_pmts.CurrentDirectoryName.Buffer[3] = '\0';
424     /* </hack: to be changed later on> */
425
426     /* initialise DOS drives */
427     if (!DRIVE_Init()) return FALSE;
428
429     /* initialise DOS directories */
430     if (!DIR_Init()) return FALSE;
431
432     /* registry initialisation */
433     SHELL_LoadRegistry();
434
435     /* global boot finished, the rest is process-local */
436     SERVER_START_REQ( boot_done )
437     {
438         req->debug_level = TRACE_ON(server);
439         wine_server_call( req );
440     }
441     SERVER_END_REQ;
442
443     if (TRACE_ON(relay) || TRACE_ON(snoop)) RELAY_InitDebugLists();
444
445     return TRUE;
446 }
447
448
449 /***********************************************************************
450  *           start_process
451  *
452  * Startup routine of a new process. Runs on the new process stack.
453  */
454 static void start_process( void *arg )
455 {
456     __TRY
457     {
458         LPTHREAD_START_ROUTINE entry;
459         HANDLE main_file = main_exe_file;
460         IMAGE_NT_HEADERS *nt;
461         WINE_MODREF *wm;
462         PEB *peb = NtCurrentTeb()->Peb;
463
464         if (main_file)
465         {
466             UINT drive_type = GetDriveTypeA( main_exe_name );
467             /* don't keep the file handle open on removable media */
468             if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
469         }
470
471         /* Retrieve entry point address */
472         nt = RtlImageNtHeader( peb->ImageBaseAddress );
473         entry = (LPTHREAD_START_ROUTINE)((char*)peb->ImageBaseAddress +
474                                          nt->OptionalHeader.AddressOfEntryPoint);
475
476         /* Install signal handlers; this cannot be done before, since we cannot
477          * send exceptions to the debugger before the create process event that
478          * is sent by REQ_INIT_PROCESS_DONE.
479          * We do need the handlers in place by the time the request is over, so
480          * we set them up here. If we segfault between here and the server call
481          * something is very wrong... */
482         if (!SIGNAL_Init()) goto error;
483
484         /* Signal the parent process to continue */
485         SERVER_START_REQ( init_process_done )
486         {
487             req->module      = peb->ImageBaseAddress;
488             req->module_size = nt->OptionalHeader.SizeOfImage;
489             req->entry       = entry;
490             /* API requires a double indirection */
491             req->name        = &main_exe_name_ptr;
492             req->exe_file    = main_file;
493             req->gui         = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
494             wine_server_add_data( req, main_exe_name, strlen(main_exe_name) );
495             wine_server_call( req );
496             peb->BeingDebugged = reply->debugged;
497         }
498         SERVER_END_REQ;
499
500         /* create the main modref and load dependencies */
501         if (!(wm = MODULE_AllocModRef( peb->ImageBaseAddress, main_exe_name ))) goto error;
502         if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
503         if (MODULE_DllProcessAttach( NULL, (LPVOID)1 ) != STATUS_SUCCESS)
504         {
505             ERR( "Main exe initialization failed\n" );
506             goto error;
507         }
508
509         if (TRACE_ON(relay))
510             DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n",
511                      GetCurrentThreadId(), main_exe_name, entry );
512         if (peb->BeingDebugged) DbgBreakPoint();
513         SetLastError(0);  /* clear error code */
514         ExitThread( entry( NtCurrentTeb()->Peb ) );
515
516     error:
517         ExitProcess( GetLastError() );
518     }
519     __EXCEPT(UnhandledExceptionFilter)
520     {
521         TerminateThread( GetCurrentThread(), GetExceptionCode() );
522     }
523     __ENDTRY
524 }
525
526
527 /***********************************************************************
528  *           __wine_process_init
529  *
530  * Wine initialisation: load and start the main exe file.
531  */
532 void __wine_process_init( int argc, char *argv[] )
533 {
534     char error[1024], *p;
535     DWORD stack_size = 0;
536     int file_exists;
537
538     /* Initialize everything */
539     if (!process_init( argv )) exit(1);
540
541     argv++;  /* remove argv[0] (wine itself) */
542
543     TRACE( "starting process name=%s file=%p argv[0]=%s\n",
544            debugstr_a(main_exe_name), main_exe_file, debugstr_a(argv[0]) );
545
546     if (!main_exe_name[0])
547     {
548         if (!argv[0]) OPTIONS_Usage();
549
550         if (!find_exe_file( argv[0], main_exe_name, sizeof(main_exe_name), &main_exe_file ))
551         {
552             MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
553             ExitProcess(1);
554         }
555         if (main_exe_file == INVALID_HANDLE_VALUE)
556         {
557             MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
558             ExitProcess(1);
559         }
560     }
561
562     if (!main_exe_file)  /* no file handle -> Winelib app */
563     {
564         TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
565         if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
566             goto found;
567         MESSAGE( "%s: cannot open builtin library for '%s': %s\n", argv0, main_exe_name, error );
568         ExitProcess(1);
569     }
570     VERSION_Init( main_exe_name );
571
572     switch( MODULE_GetBinaryType( main_exe_file ))
573     {
574     case BINARY_PE_EXE:
575         TRACE( "starting Win32 binary %s\n", debugstr_a(main_exe_name) );
576         if ((current_process.module = load_pe_exe( main_exe_file ))) goto found;
577         MESSAGE( "%s: could not load '%s' as Win32 binary\n", argv0, main_exe_name );
578         ExitProcess(1);
579     case BINARY_PE_DLL:
580         MESSAGE( "%s: '%s' is a DLL, not an executable\n", argv0, main_exe_name );
581         ExitProcess(1);
582     case BINARY_UNKNOWN:
583         /* check for .com extension */
584         if (!(p = strrchr( main_exe_name, '.' )) || FILE_strcasecmp( p, ".com" ))
585         {
586             MESSAGE( "%s: cannot determine executable type for '%s'\n", argv0, main_exe_name );
587             ExitProcess(1);
588         }
589         /* fall through */
590     case BINARY_WIN16:
591     case BINARY_DOS:
592         TRACE( "starting Win16/DOS binary %s\n", debugstr_a(main_exe_name) );
593         CloseHandle( main_exe_file );
594         main_exe_file = 0;
595         argv--;
596         argv[0] = "winevdm.exe";
597         if (open_builtin_exe_file( "winevdm.exe", error, sizeof(error), 0, &file_exists ))
598             goto found;
599         MESSAGE( "%s: trying to run '%s', cannot open builtin library for 'winevdm.exe': %s\n",
600                  argv0, main_exe_name, error );
601         ExitProcess(1);
602     case BINARY_OS216:
603         MESSAGE( "%s: '%s' is an OS/2 binary, not supported\n", argv0, main_exe_name );
604         ExitProcess(1);
605     case BINARY_UNIX_EXE:
606         MESSAGE( "%s: '%s' is a Unix binary, not supported\n", argv0, main_exe_name );
607         ExitProcess(1);
608     case BINARY_UNIX_LIB:
609         {
610             DOS_FULL_NAME full_name;
611             const char *name = main_exe_name;
612             UNICODE_STRING nameW;
613
614             TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
615             RtlCreateUnicodeStringFromAsciiz(&nameW, name);
616             if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) name = full_name.long_name;
617             RtlFreeUnicodeString(&nameW);
618             CloseHandle( main_exe_file );
619             main_exe_file = 0;
620             if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) ))
621             {
622                 if ((p = strrchr( main_exe_name, '.' )) && !strcmp( p, ".so" )) *p = 0;
623                 goto found;
624             }
625             MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
626             ExitProcess(1);
627         }
628     }
629
630  found:
631     /* build command line */
632     if (!build_command_line( argv )) goto error;
633
634     /* create 32-bit module for main exe */
635     if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
636     stack_size = RtlImageNtHeader(current_process.module)->OptionalHeader.SizeOfStackReserve;
637
638     /* allocate main thread stack */
639     if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
640
641     /* switch to the new stack */
642     wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
643
644  error:
645     ExitProcess( GetLastError() );
646 }
647
648
649 /***********************************************************************
650  *           build_argv
651  *
652  * Build an argv array from a command-line.
653  * The command-line is modified to insert nulls.
654  * 'reserved' is the number of args to reserve before the first one.
655  */
656 static char **build_argv( char *cmdline, int reserved )
657 {
658     int argc;
659     char** argv;
660     char *arg,*s,*d;
661     int in_quotes,bcount;
662
663     argc=reserved+1;
664     bcount=0;
665     in_quotes=0;
666     s=cmdline;
667     while (1) {
668         if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
669             /* space */
670             argc++;
671             /* skip the remaining spaces */
672             while (*s==' ' || *s=='\t') {
673                 s++;
674             }
675             if (*s=='\0')
676                 break;
677             bcount=0;
678             continue;
679         } else if (*s=='\\') {
680             /* '\', count them */
681             bcount++;
682         } else if ((*s=='"') && ((bcount & 1)==0)) {
683             /* unescaped '"' */
684             in_quotes=!in_quotes;
685             bcount=0;
686         } else {
687             /* a regular character */
688             bcount=0;
689         }
690         s++;
691     }
692     argv=malloc(argc*sizeof(*argv));
693     if (!argv)
694         return NULL;
695
696     arg=d=s=cmdline;
697     bcount=0;
698     in_quotes=0;
699     argc=reserved;
700     while (*s) {
701         if ((*s==' ' || *s=='\t') && !in_quotes) {
702             /* Close the argument and copy it */
703             *d=0;
704             argv[argc++]=arg;
705
706             /* skip the remaining spaces */
707             do {
708                 s++;
709             } while (*s==' ' || *s=='\t');
710
711             /* Start with a new argument */
712             arg=d=s;
713             bcount=0;
714         } else if (*s=='\\') {
715             /* '\\' */
716             *d++=*s++;
717             bcount++;
718         } else if (*s=='"') {
719             /* '"' */
720             if ((bcount & 1)==0) {
721                 /* Preceeded by an even number of '\', this is half that
722                  * number of '\', plus a '"' which we discard.
723                  */
724                 d-=bcount/2;
725                 s++;
726                 in_quotes=!in_quotes;
727             } else {
728                 /* Preceeded by an odd number of '\', this is half that
729                  * number of '\' followed by a '"'
730                  */
731                 d=d-bcount/2-1;
732                 *d++='"';
733                 s++;
734             }
735             bcount=0;
736         } else {
737             /* a regular character */
738             *d++=*s++;
739             bcount=0;
740         }
741     }
742     if (*arg) {
743         *d='\0';
744         argv[argc++]=arg;
745     }
746     argv[argc]=NULL;
747
748     return argv;
749 }
750
751
752 /***********************************************************************
753  *           build_envp
754  *
755  * Build the environment of a new child process.
756  */
757 static char **build_envp( const char *env, const char *extra_env )
758 {
759     const char *p;
760     char **envp;
761     int count = 0;
762
763     if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
764     for (p = env; *p; count++) p += strlen(p) + 1;
765     count += 3;
766
767     if ((envp = malloc( count * sizeof(*envp) )))
768     {
769         extern char **environ;
770         char **envptr = envp;
771         char **unixptr = environ;
772         /* first the extra strings */
773         if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
774         /* then put PATH, HOME and WINEPREFIX from the unix env */
775         for (unixptr = environ; unixptr && *unixptr; unixptr++)
776             if (!memcmp( *unixptr, "PATH=", 5 ) ||
777                 !memcmp( *unixptr, "HOME=", 5 ) ||
778                 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
779         /* now put the Windows environment strings */
780         for (p = env; *p; p += strlen(p) + 1)
781         {
782             if (!memcmp( p, "PATH=", 5 ))  /* store PATH as WINEPATH */
783             {
784                 char *winepath = malloc( strlen(p) + 5 );
785                 strcpy( winepath, "WINE" );
786                 strcpy( winepath + 4, p );
787                 *envptr++ = winepath;
788             }
789             else if (memcmp( p, "HOME=", 5 ) &&
790                      memcmp( p, "WINEPATH=", 9 ) &&
791                      memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
792         }
793         *envptr = 0;
794     }
795     return envp;
796 }
797
798
799 /***********************************************************************
800  *           exec_wine_binary
801  *
802  * Locate the Wine binary to exec for a new Win32 process.
803  */
804 static void exec_wine_binary( char **argv, char **envp )
805 {
806     const char *path, *pos, *ptr;
807
808     /* first, try for a WINELOADER environment variable */
809     argv[0] = getenv("WINELOADER");
810     if (argv[0])
811         execve( argv[0], argv, envp );
812
813     /* next, try bin directory */
814     argv[0] = BINDIR "/wine";
815     execve( argv[0], argv, envp );
816
817     /* now try the path of argv0 of the current binary */
818     if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
819     if ((ptr = strrchr( full_argv0, '/' )))
820     {
821         memcpy( argv[0], full_argv0, ptr - full_argv0 );
822         strcpy( argv[0] + (ptr - full_argv0), "/wine" );
823         execve( argv[0], argv, envp );
824     }
825     free( argv[0] );
826
827     /* now search in the Unix path */
828     if ((path = getenv( "PATH" )))
829     {
830         if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
831         pos = path;
832         for (;;)
833         {
834             while (*pos == ':') pos++;
835             if (!*pos) break;
836             if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
837             memcpy( argv[0], pos, ptr - pos );
838             strcpy( argv[0] + (ptr - pos), "/wine" );
839             execve( argv[0], argv, envp );
840             pos = ptr;
841         }
842     }
843     free( argv[0] );
844 }
845
846
847 /***********************************************************************
848  *           fork_and_exec
849  *
850  * Fork and exec a new Unix binary, checking for errors.
851  */
852 static int fork_and_exec( const char *filename, char *cmdline,
853                           const char *env, const char *newdir )
854 {
855     int fd[2];
856     int pid, err;
857
858     if (!env) env = GetEnvironmentStringsA();
859
860     if (pipe(fd) == -1)
861     {
862         FILE_SetDosError();
863         return -1;
864     }
865     fcntl( fd[1], F_SETFD, 1 );  /* set close on exec */
866     if (!(pid = fork()))  /* child */
867     {
868         char **argv = build_argv( cmdline, 0 );
869         char **envp = build_envp( env, NULL );
870         close( fd[0] );
871
872         /* Reset signals that we previously set to SIG_IGN */
873         signal( SIGPIPE, SIG_DFL );
874         signal( SIGCHLD, SIG_DFL );
875
876         if (newdir) chdir(newdir);
877
878         if (argv && envp) execve( filename, argv, envp );
879         err = errno;
880         write( fd[1], &err, sizeof(err) );
881         _exit(1);
882     }
883     close( fd[1] );
884     if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0))  /* exec failed */
885     {
886         errno = err;
887         pid = -1;
888     }
889     if (pid == -1) FILE_SetDosError();
890     close( fd[0] );
891     return pid;
892 }
893
894
895 /***********************************************************************
896  *           create_process
897  *
898  * Create a new process. If hFile is a valid handle we have an exe
899  * file, otherwise it is a Winelib app.
900  */
901 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
902                             LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
903                             BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
904                             LPPROCESS_INFORMATION info, LPCSTR unixdir )
905 {
906     BOOL ret, success = FALSE;
907     HANDLE process_info;
908     startup_info_t startup_info;
909     char *extra_env = NULL;
910     int startfd[2];
911     int execfd[2];
912     pid_t pid;
913     int err;
914     char dummy = 0;
915
916     if (!env)
917     {
918         env = GetEnvironmentStringsA();
919         extra_env = DRIVE_BuildEnv();
920     }
921
922     /* create the synchronization pipes */
923
924     if (pipe( startfd ) == -1)
925     {
926         FILE_SetDosError();
927         return FALSE;
928     }
929     if (pipe( execfd ) == -1)
930     {
931         close( startfd[0] );
932         close( startfd[1] );
933         FILE_SetDosError();
934         return FALSE;
935     }
936     fcntl( execfd[1], F_SETFD, 1 );  /* set close on exec */
937
938     /* create the child process */
939
940     if (!(pid = fork()))  /* child */
941     {
942         char **argv = build_argv( cmd_line, 1 );
943         char **envp = build_envp( env, extra_env );
944
945         close( startfd[1] );
946         close( execfd[0] );
947
948         /* wait for parent to tell us to start */
949         if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
950
951         close( startfd[0] );
952         /* Reset signals that we previously set to SIG_IGN */
953         signal( SIGPIPE, SIG_DFL );
954         signal( SIGCHLD, SIG_DFL );
955
956         if (unixdir) chdir(unixdir);
957
958         if (argv && envp) exec_wine_binary( argv, envp );
959
960         err = errno;
961         write( execfd[1], &err, sizeof(err) );
962         _exit(1);
963     }
964
965     /* this is the parent */
966
967     close( startfd[0] );
968     close( execfd[1] );
969     if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
970     if (pid == -1)
971     {
972         close( startfd[1] );
973         close( execfd[0] );
974         FILE_SetDosError();
975         return FALSE;
976     }
977
978     /* fill the startup info structure */
979
980     startup_info.size        = sizeof(startup_info);
981     /* startup_info.filename_len is set below */
982     startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
983     startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
984     startup_info.title_len   = startup->lpTitle ? strlen(startup->lpTitle) : 0;
985     startup_info.x           = startup->dwX;
986     startup_info.y           = startup->dwY;
987     startup_info.cx          = startup->dwXSize;
988     startup_info.cy          = startup->dwYSize;
989     startup_info.x_chars     = startup->dwXCountChars;
990     startup_info.y_chars     = startup->dwYCountChars;
991     startup_info.attribute   = startup->dwFillAttribute;
992     startup_info.cmd_show    = startup->wShowWindow;
993     startup_info.flags       = startup->dwFlags;
994
995     /* create the process on the server side */
996
997     SERVER_START_REQ( new_process )
998     {
999         char buf[MAX_PATH];
1000         LPCSTR nameptr;
1001
1002         req->inherit_all  = inherit;
1003         req->create_flags = flags;
1004         req->unix_pid     = pid;
1005         req->exe_file     = hFile;
1006         if (startup->dwFlags & STARTF_USESTDHANDLES)
1007         {
1008             req->hstdin  = startup->hStdInput;
1009             req->hstdout = startup->hStdOutput;
1010             req->hstderr = startup->hStdError;
1011         }
1012         else
1013         {
1014             req->hstdin  = GetStdHandle( STD_INPUT_HANDLE );
1015             req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1016             req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1017         }
1018
1019         if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1020         {
1021             /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1022             if (is_console_handle(req->hstdin))  req->hstdin  = INVALID_HANDLE_VALUE;
1023             if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1024             if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1025         }
1026         else
1027         {
1028             if (is_console_handle(req->hstdin))  req->hstdin  = console_handle_unmap(req->hstdin);
1029             if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1030             if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1031         }
1032
1033         if (GetLongPathNameA( filename, buf, MAX_PATH ))
1034             nameptr = buf;
1035         else
1036             nameptr = filename;
1037
1038         startup_info.filename_len = strlen(nameptr);
1039         wine_server_add_data( req, &startup_info, sizeof(startup_info) );
1040         wine_server_add_data( req, nameptr, startup_info.filename_len );
1041         wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
1042         wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
1043         wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
1044
1045         ret = !wine_server_call_err( req );
1046         process_info = reply->info;
1047     }
1048     SERVER_END_REQ;
1049
1050     if (!ret)
1051     {
1052         close( startfd[1] );
1053         close( execfd[0] );
1054         return FALSE;
1055     }
1056
1057     /* tell child to start and wait for it to exec */
1058
1059     write( startfd[1], &dummy, 1 );
1060     close( startfd[1] );
1061
1062     if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1063     {
1064         errno = err;
1065         FILE_SetDosError();
1066         close( execfd[0] );
1067         CloseHandle( process_info );
1068         return FALSE;
1069     }
1070
1071     /* wait for the new process info to be ready */
1072
1073     WaitForSingleObject( process_info, INFINITE );
1074     SERVER_START_REQ( get_new_process_info )
1075     {
1076         req->info     = process_info;
1077         req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1078         req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1079         if ((ret = !wine_server_call_err( req )))
1080         {
1081             info->dwProcessId = (DWORD)reply->pid;
1082             info->dwThreadId  = (DWORD)reply->tid;
1083             info->hProcess    = reply->phandle;
1084             info->hThread     = reply->thandle;
1085             success           = reply->success;
1086         }
1087     }
1088     SERVER_END_REQ;
1089
1090     if (ret && !success)  /* new process failed to start */
1091     {
1092         DWORD exitcode;
1093         if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1094         CloseHandle( info->hThread );
1095         CloseHandle( info->hProcess );
1096         ret = FALSE;
1097     }
1098     CloseHandle( process_info );
1099     return ret;
1100 }
1101
1102
1103 /***********************************************************************
1104  *           create_vdm_process
1105  *
1106  * Create a new VDM process for a 16-bit or DOS application.
1107  */
1108 static BOOL create_vdm_process( LPCSTR filename, LPSTR cmd_line, LPCSTR env,
1109                                 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1110                                 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
1111                                 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1112 {
1113     BOOL ret;
1114     LPSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + strlen(cmd_line) + 30 );
1115
1116     if (!new_cmd_line)
1117     {
1118         SetLastError( ERROR_OUTOFMEMORY );
1119         return FALSE;
1120     }
1121     sprintf( new_cmd_line, "winevdm.exe --app-name \"%s\" %s", filename, cmd_line );
1122     ret = create_process( 0, "winevdm.exe", new_cmd_line, env, psa, tsa, inherit,
1123                           flags, startup, info, unixdir );
1124     HeapFree( GetProcessHeap(), 0, new_cmd_line );
1125     return ret;
1126 }
1127
1128
1129 /*************************************************************************
1130  *               get_file_name
1131  *
1132  * Helper for CreateProcess: retrieve the file name to load from the
1133  * app name and command line. Store the file name in buffer, and
1134  * return a possibly modified command line.
1135  * Also returns a handle to the opened file if it's a Windows binary.
1136  */
1137 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1138                             int buflen, HANDLE *handle )
1139 {
1140     char *name, *pos, *ret = NULL;
1141     const char *p;
1142
1143     /* if we have an app name, everything is easy */
1144
1145     if (appname)
1146     {
1147         /* use the unmodified app name as file name */
1148         lstrcpynA( buffer, appname, buflen );
1149         *handle = open_exe_file( buffer );
1150         if (!(ret = cmdline) || !cmdline[0])
1151         {
1152             /* no command-line, create one */
1153             if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1154                 sprintf( ret, "\"%s\"", appname );
1155         }
1156         return ret;
1157     }
1158
1159     if (!cmdline)
1160     {
1161         SetLastError( ERROR_INVALID_PARAMETER );
1162         return NULL;
1163     }
1164
1165     /* first check for a quoted file name */
1166
1167     if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1168     {
1169         int len = p - cmdline - 1;
1170         /* extract the quoted portion as file name */
1171         if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1172         memcpy( name, cmdline + 1, len );
1173         name[len] = 0;
1174
1175         if (find_exe_file( name, buffer, buflen, handle ))
1176             ret = cmdline;  /* no change necessary */
1177         goto done;
1178     }
1179
1180     /* now try the command-line word by word */
1181
1182     if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1183     pos = name;
1184     p = cmdline;
1185
1186     while (*p)
1187     {
1188         do *pos++ = *p++; while (*p && *p != ' ');
1189         *pos = 0;
1190         if (find_exe_file( name, buffer, buflen, handle ))
1191         {
1192             ret = cmdline;
1193             break;
1194         }
1195     }
1196
1197     if (!ret || !strchr( name, ' ' )) goto done;  /* no change necessary */
1198
1199     /* now build a new command-line with quotes */
1200
1201     if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1202     sprintf( ret, "\"%s\"%s", name, p );
1203
1204  done:
1205     HeapFree( GetProcessHeap(), 0, name );
1206     return ret;
1207 }
1208
1209
1210 /**********************************************************************
1211  *       CreateProcessA          (KERNEL32.@)
1212  */
1213 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1214                             LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1215                             DWORD flags, LPVOID env, LPCSTR cur_dir,
1216                             LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1217 {
1218     BOOL retv = FALSE;
1219     HANDLE hFile = 0;
1220     const char *unixdir = NULL;
1221     DOS_FULL_NAME full_dir;
1222     char name[MAX_PATH];
1223     LPSTR tidy_cmdline;
1224     char *p;
1225
1226     /* Process the AppName and/or CmdLine to get module name and path */
1227
1228     TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1229
1230     if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1231         return FALSE;
1232     if (hFile == INVALID_HANDLE_VALUE) goto done;
1233
1234     /* Warn if unsupported features are used */
1235
1236     if (flags & NORMAL_PRIORITY_CLASS)
1237         FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1238     if (flags & IDLE_PRIORITY_CLASS)
1239         FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1240     if (flags & HIGH_PRIORITY_CLASS)
1241         FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1242     if (flags & REALTIME_PRIORITY_CLASS)
1243         FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1244     if (flags & CREATE_NEW_PROCESS_GROUP)
1245         FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1246     if (flags & CREATE_UNICODE_ENVIRONMENT)
1247         FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1248     if (flags & CREATE_SEPARATE_WOW_VDM)
1249         FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1250     if (flags & CREATE_SHARED_WOW_VDM)
1251         FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1252     if (flags & CREATE_DEFAULT_ERROR_MODE)
1253         FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1254     if (flags & CREATE_NO_WINDOW)
1255         FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1256     if (flags & PROFILE_USER)
1257         FIXME("(%s,...): PROFILE_USER ignored\n", name);
1258     if (flags & PROFILE_KERNEL)
1259         FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1260     if (flags & PROFILE_SERVER)
1261         FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1262     if (startup_info->lpDesktop)
1263         FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1264               name, debugstr_a(startup_info->lpDesktop));
1265     if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1266         FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1267     if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1268         FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1269     if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1270         FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1271     if (startup_info->dwFlags & STARTF_USEHOTKEY)
1272         FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1273
1274     if (cur_dir)
1275     {
1276         UNICODE_STRING cur_dirW;
1277         RtlCreateUnicodeStringFromAsciiz(&cur_dirW, cur_dir);
1278         if (DOSFS_GetFullName( cur_dirW.Buffer, TRUE, &full_dir ))
1279             unixdir = full_dir.long_name;
1280         RtlFreeUnicodeString(&cur_dirW);
1281     }
1282     else
1283     {
1284         WCHAR buf[MAX_PATH];
1285         if (GetCurrentDirectoryW(MAX_PATH, buf))
1286         {
1287             if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1288         }
1289     }
1290
1291     info->hThread = info->hProcess = 0;
1292     info->dwProcessId = info->dwThreadId = 0;
1293
1294     /* Determine executable type */
1295
1296     if (!hFile)  /* builtin exe */
1297     {
1298         TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1299         retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1300                                inherit, flags, startup_info, info, unixdir );
1301         goto done;
1302     }
1303
1304     switch( MODULE_GetBinaryType( hFile ))
1305     {
1306     case BINARY_PE_EXE:
1307         TRACE( "starting %s as Win32 binary\n", debugstr_a(name) );
1308         retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1309                                inherit, flags, startup_info, info, unixdir );
1310         break;
1311     case BINARY_WIN16:
1312     case BINARY_DOS:
1313         TRACE( "starting %s as Win16/DOS binary\n", debugstr_a(name) );
1314         retv = create_vdm_process( name, tidy_cmdline, env, process_attr, thread_attr,
1315                                    inherit, flags, startup_info, info, unixdir );
1316         break;
1317     case BINARY_OS216:
1318         FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1319         SetLastError( ERROR_BAD_EXE_FORMAT );
1320         break;
1321     case BINARY_PE_DLL:
1322         TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1323         SetLastError( ERROR_BAD_EXE_FORMAT );
1324         break;
1325     case BINARY_UNIX_LIB:
1326         TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_a(name) );
1327         retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1328                                inherit, flags, startup_info, info, unixdir );
1329         break;
1330     case BINARY_UNKNOWN:
1331         /* check for .com or .bat extension */
1332         if ((p = strrchr( name, '.' )))
1333         {
1334             if (!FILE_strcasecmp( p, ".com" ))
1335             {
1336                 TRACE( "starting %s as DOS binary\n", debugstr_a(name) );
1337                 retv = create_vdm_process( name, tidy_cmdline, env, process_attr, thread_attr,
1338                                            inherit, flags, startup_info, info, unixdir );
1339                 break;
1340             }
1341             if (!FILE_strcasecmp( p, ".bat" ))
1342             {
1343                 char comspec[MAX_PATH];
1344                 if (GetEnvironmentVariableA("COMSPEC", comspec, sizeof(comspec)))
1345                 {
1346                     char *newcmdline;
1347                     if ((newcmdline = HeapAlloc( GetProcessHeap(), 0,
1348                                                  strlen(comspec) + 4 + strlen(tidy_cmdline) + 1)))
1349                     {
1350                         sprintf( newcmdline, "%s /c %s", comspec,  tidy_cmdline);
1351                         TRACE( "starting %s as batch binary: %s\n",
1352                                debugstr_a(name), debugstr_a(newcmdline) );
1353                         retv = CreateProcessA( comspec, newcmdline, process_attr, thread_attr,
1354                                                inherit, flags, env, cur_dir, startup_info, info );
1355                         HeapFree( GetProcessHeap(), 0, newcmdline );
1356                         break;
1357                     }
1358                 }
1359             }
1360         }
1361         /* fall through */
1362     case BINARY_UNIX_EXE:
1363         {
1364             /* unknown file, try as unix executable */
1365             UNICODE_STRING nameW;
1366             DOS_FULL_NAME full_name;
1367             const char *unixfilename = name;
1368
1369             TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1370
1371             RtlCreateUnicodeStringFromAsciiz(&nameW, name);
1372             if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) unixfilename = full_name.long_name;
1373             RtlFreeUnicodeString(&nameW);
1374             retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1375         }
1376         break;
1377     }
1378     CloseHandle( hFile );
1379
1380  done:
1381     if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1382     return retv;
1383 }
1384
1385
1386 /**********************************************************************
1387  *       CreateProcessW          (KERNEL32.@)
1388  * NOTES
1389  *  lpReserved is not converted
1390  */
1391 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1392                             LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1393                             LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1394                             LPPROCESS_INFORMATION info )
1395 {
1396     BOOL ret;
1397     STARTUPINFOA StartupInfoA;
1398
1399     LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1400     LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1401     LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1402
1403     memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1404     StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1405     StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1406
1407     TRACE("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1408
1409     if (startup_info->lpReserved)
1410       FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1411             debugstr_w(startup_info->lpReserved));
1412
1413     ret = CreateProcessA( app_nameA,  cmd_lineA, process_attr, thread_attr,
1414                           inherit, flags, env, cur_dirA, &StartupInfoA, info );
1415
1416     HeapFree( GetProcessHeap(), 0, cur_dirA );
1417     HeapFree( GetProcessHeap(), 0, cmd_lineA );
1418     HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1419     HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1420
1421     return ret;
1422 }
1423
1424
1425 /***********************************************************************
1426  *           wait_input_idle
1427  *
1428  * Wrapper to call WaitForInputIdle USER function
1429  */
1430 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1431
1432 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1433 {
1434     HMODULE mod = GetModuleHandleA( "user32.dll" );
1435     if (mod)
1436     {
1437         WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1438         if (ptr) return ptr( process, timeout );
1439     }
1440     return 0;
1441 }
1442
1443
1444 /***********************************************************************
1445  *           WinExec   (KERNEL32.@)
1446  */
1447 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1448 {
1449     PROCESS_INFORMATION info;
1450     STARTUPINFOA startup;
1451     char *cmdline;
1452     UINT ret;
1453
1454     memset( &startup, 0, sizeof(startup) );
1455     startup.cb = sizeof(startup);
1456     startup.dwFlags = STARTF_USESHOWWINDOW;
1457     startup.wShowWindow = nCmdShow;
1458
1459     /* cmdline needs to be writeable for CreateProcess */
1460     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1461     strcpy( cmdline, lpCmdLine );
1462
1463     if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1464                         0, NULL, NULL, &startup, &info ))
1465     {
1466         /* Give 30 seconds to the app to come up */
1467         if (wait_input_idle( info.hProcess, 30000 ) == 0xFFFFFFFF)
1468             WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1469         ret = 33;
1470         /* Close off the handles */
1471         CloseHandle( info.hThread );
1472         CloseHandle( info.hProcess );
1473     }
1474     else if ((ret = GetLastError()) >= 32)
1475     {
1476         FIXME("Strange error set by CreateProcess: %d\n", ret );
1477         ret = 11;
1478     }
1479     HeapFree( GetProcessHeap(), 0, cmdline );
1480     return ret;
1481 }
1482
1483
1484 /**********************************************************************
1485  *          LoadModule    (KERNEL32.@)
1486  */
1487 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1488 {
1489     LOADPARAMS *params = (LOADPARAMS *)paramBlock;
1490     PROCESS_INFORMATION info;
1491     STARTUPINFOA startup;
1492     HINSTANCE hInstance;
1493     LPSTR cmdline, p;
1494     char filename[MAX_PATH];
1495     BYTE len;
1496
1497     if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1498
1499     if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1500         !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1501         return (HINSTANCE)GetLastError();
1502
1503     len = (BYTE)params->lpCmdLine[0];
1504     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
1505         return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
1506
1507     strcpy( cmdline, filename );
1508     p = cmdline + strlen(cmdline);
1509     *p++ = ' ';
1510     memcpy( p, params->lpCmdLine + 1, len );
1511     p[len] = 0;
1512
1513     memset( &startup, 0, sizeof(startup) );
1514     startup.cb = sizeof(startup);
1515     if (params->lpCmdShow)
1516     {
1517         startup.dwFlags = STARTF_USESHOWWINDOW;
1518         startup.wShowWindow = params->lpCmdShow[1];
1519     }
1520
1521     if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
1522                         params->lpEnvAddress, NULL, &startup, &info ))
1523     {
1524         /* Give 30 seconds to the app to come up */
1525         if (wait_input_idle( info.hProcess, 30000 ) ==  0xFFFFFFFF )
1526             WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1527         hInstance = (HINSTANCE)33;
1528         /* Close off the handles */
1529         CloseHandle( info.hThread );
1530         CloseHandle( info.hProcess );
1531     }
1532     else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
1533     {
1534         FIXME("Strange error set by CreateProcess: %p\n", hInstance );
1535         hInstance = (HINSTANCE)11;
1536     }
1537
1538     HeapFree( GetProcessHeap(), 0, cmdline );
1539     return hInstance;
1540 }
1541
1542
1543 /******************************************************************************
1544  *           TerminateProcess   (KERNEL32.@)
1545  */
1546 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1547 {
1548     NTSTATUS status = NtTerminateProcess( handle, exit_code );
1549     if (status) SetLastError( RtlNtStatusToDosError(status) );
1550     return !status;
1551 }
1552
1553
1554 /***********************************************************************
1555  * GetExitCodeProcess [KERNEL32.@]
1556  *
1557  * Gets termination status of specified process
1558  *
1559  * RETURNS
1560  *   Success: TRUE
1561  *   Failure: FALSE
1562  */
1563 BOOL WINAPI GetExitCodeProcess(
1564     HANDLE hProcess,    /* [in] handle to the process */
1565     LPDWORD lpExitCode) /* [out] address to receive termination status */
1566 {
1567     BOOL ret;
1568     SERVER_START_REQ( get_process_info )
1569     {
1570         req->handle = hProcess;
1571         ret = !wine_server_call_err( req );
1572         if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1573     }
1574     SERVER_END_REQ;
1575     return ret;
1576 }
1577
1578
1579 /***********************************************************************
1580  *           SetErrorMode   (KERNEL32.@)
1581  */
1582 UINT WINAPI SetErrorMode( UINT mode )
1583 {
1584     UINT old = current_process.error_mode;
1585     current_process.error_mode = mode;
1586     return old;
1587 }
1588
1589
1590 /**********************************************************************
1591  * TlsAlloc [KERNEL32.@]  Allocates a TLS index.
1592  *
1593  * Allocates a thread local storage index
1594  *
1595  * RETURNS
1596  *    Success: TLS Index
1597  *    Failure: 0xFFFFFFFF
1598  */
1599 DWORD WINAPI TlsAlloc( void )
1600 {
1601     DWORD i, mask, ret = 0;
1602     DWORD *bits = current_process.tls_bits;
1603     RtlAcquirePebLock();
1604     if (*bits == 0xffffffff)
1605     {
1606         bits++;
1607         ret = 32;
1608         if (*bits == 0xffffffff)
1609         {
1610             RtlReleasePebLock();
1611             SetLastError( ERROR_NO_MORE_ITEMS );
1612             return 0xffffffff;
1613         }
1614     }
1615     for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1616     *bits |= mask;
1617     RtlReleasePebLock();
1618     NtCurrentTeb()->TlsSlots[ret+i] = 0; /* clear the value */
1619     return ret + i;
1620 }
1621
1622
1623 /**********************************************************************
1624  * TlsFree [KERNEL32.@]  Releases a TLS index.
1625  *
1626  * Releases a thread local storage index, making it available for reuse
1627  *
1628  * RETURNS
1629  *    Success: TRUE
1630  *    Failure: FALSE
1631  */
1632 BOOL WINAPI TlsFree(
1633     DWORD index) /* [in] TLS Index to free */
1634 {
1635     DWORD mask = (1 << (index & 31));
1636     DWORD *bits = current_process.tls_bits;
1637     if (index >= 64)
1638     {
1639         SetLastError( ERROR_INVALID_PARAMETER );
1640         return FALSE;
1641     }
1642     if (index >= 32) bits++;
1643     RtlAcquirePebLock();
1644     if (!(*bits & mask))  /* already free? */
1645     {
1646         RtlReleasePebLock();
1647         SetLastError( ERROR_INVALID_PARAMETER );
1648         return FALSE;
1649     }
1650     *bits &= ~mask;
1651     NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
1652     RtlReleasePebLock();
1653     return TRUE;
1654 }
1655
1656
1657 /**********************************************************************
1658  * TlsGetValue [KERNEL32.@]  Gets value in a thread's TLS slot
1659  *
1660  * RETURNS
1661  *    Success: Value stored in calling thread's TLS slot for index
1662  *    Failure: 0 and GetLastError returns NO_ERROR
1663  */
1664 LPVOID WINAPI TlsGetValue(
1665     DWORD index) /* [in] TLS index to retrieve value for */
1666 {
1667     if (index >= 64)
1668     {
1669         SetLastError( ERROR_INVALID_PARAMETER );
1670         return NULL;
1671     }
1672     SetLastError( ERROR_SUCCESS );
1673     return NtCurrentTeb()->TlsSlots[index];
1674 }
1675
1676
1677 /**********************************************************************
1678  * TlsSetValue [KERNEL32.@]  Stores a value in the thread's TLS slot.
1679  *
1680  * RETURNS
1681  *    Success: TRUE
1682  *    Failure: FALSE
1683  */
1684 BOOL WINAPI TlsSetValue(
1685     DWORD index,  /* [in] TLS index to set value for */
1686     LPVOID value) /* [in] Value to be stored */
1687 {
1688     if (index >= 64)
1689     {
1690         SetLastError( ERROR_INVALID_PARAMETER );
1691         return FALSE;
1692     }
1693     NtCurrentTeb()->TlsSlots[index] = value;
1694     return TRUE;
1695 }
1696
1697
1698 /***********************************************************************
1699  *           GetProcessFlags    (KERNEL32.@)
1700  */
1701 DWORD WINAPI GetProcessFlags( DWORD processid )
1702 {
1703     IMAGE_NT_HEADERS *nt;
1704     DWORD flags = 0;
1705
1706     if (processid && processid != GetCurrentProcessId()) return 0;
1707
1708     if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
1709     {
1710         if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
1711             flags |= PDB32_CONSOLE_PROC;
1712     }
1713     if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
1714     if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
1715     return flags;
1716 }
1717
1718
1719 /***********************************************************************
1720  *           GetProcessDword    (KERNEL.485)
1721  *           GetProcessDword    (KERNEL32.18)
1722  * 'Of course you cannot directly access Windows internal structures'
1723  */
1724 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1725 {
1726     DWORD               x, y;
1727     STARTUPINFOW        siw;
1728
1729     TRACE("(%ld, %d)\n", dwProcessID, offset );
1730
1731     if (dwProcessID && dwProcessID != GetCurrentProcessId())
1732     {
1733         ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1734         return 0;
1735     }
1736
1737     switch ( offset )
1738     {
1739     case GPD_APP_COMPAT_FLAGS:
1740         return GetAppCompatFlags16(0);
1741     case GPD_LOAD_DONE_EVENT:
1742         return 0;
1743     case GPD_HINSTANCE16:
1744         return GetTaskDS16();
1745     case GPD_WINDOWS_VERSION:
1746         return GetExeVersion16();
1747     case GPD_THDB:
1748         return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1749     case GPD_PDB:
1750         return (DWORD)NtCurrentTeb()->Peb;
1751     case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1752         GetStartupInfoW(&siw);
1753         return (DWORD)siw.hStdOutput;
1754     case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1755         GetStartupInfoW(&siw);
1756         return (DWORD)siw.hStdInput;
1757     case GPD_STARTF_SHOWWINDOW:
1758         GetStartupInfoW(&siw);
1759         return siw.wShowWindow;
1760     case GPD_STARTF_SIZE:
1761         GetStartupInfoW(&siw);
1762         x = siw.dwXSize;
1763         if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1764         y = siw.dwYSize;
1765         if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1766         return MAKELONG( x, y );
1767     case GPD_STARTF_POSITION:
1768         GetStartupInfoW(&siw);
1769         x = siw.dwX;
1770         if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1771         y = siw.dwY;
1772         if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1773         return MAKELONG( x, y );
1774     case GPD_STARTF_FLAGS:
1775         GetStartupInfoW(&siw);
1776         return siw.dwFlags;
1777     case GPD_PARENT:
1778         return 0;
1779     case GPD_FLAGS:
1780         return GetProcessFlags(0);
1781     case GPD_USERDATA:
1782         return process_dword;
1783     default:
1784         ERR("Unknown offset %d\n", offset );
1785         return 0;
1786     }
1787 }
1788
1789 /***********************************************************************
1790  *           SetProcessDword    (KERNEL.484)
1791  * 'Of course you cannot directly access Windows internal structures'
1792  */
1793 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1794 {
1795     TRACE("(%ld, %d)\n", dwProcessID, offset );
1796
1797     if (dwProcessID && dwProcessID != GetCurrentProcessId())
1798     {
1799         ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1800         return;
1801     }
1802
1803     switch ( offset )
1804     {
1805     case GPD_APP_COMPAT_FLAGS:
1806     case GPD_LOAD_DONE_EVENT:
1807     case GPD_HINSTANCE16:
1808     case GPD_WINDOWS_VERSION:
1809     case GPD_THDB:
1810     case GPD_PDB:
1811     case GPD_STARTF_SHELLDATA:
1812     case GPD_STARTF_HOTKEY:
1813     case GPD_STARTF_SHOWWINDOW:
1814     case GPD_STARTF_SIZE:
1815     case GPD_STARTF_POSITION:
1816     case GPD_STARTF_FLAGS:
1817     case GPD_PARENT:
1818     case GPD_FLAGS:
1819         ERR("Not allowed to modify offset %d\n", offset );
1820         break;
1821     case GPD_USERDATA:
1822         process_dword = value;
1823         break;
1824     default:
1825         ERR("Unknown offset %d\n", offset );
1826         break;
1827     }
1828 }
1829
1830
1831 /***********************************************************************
1832  *           ExitProcess   (KERNEL.466)
1833  */
1834 void WINAPI ExitProcess16( WORD status )
1835 {
1836     DWORD count;
1837     ReleaseThunkLock( &count );
1838     ExitProcess( status );
1839 }
1840
1841
1842 /*********************************************************************
1843  *           OpenProcess   (KERNEL32.@)
1844  */
1845 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1846 {
1847     HANDLE ret = 0;
1848     SERVER_START_REQ( open_process )
1849     {
1850         req->pid     = id;
1851         req->access  = access;
1852         req->inherit = inherit;
1853         if (!wine_server_call_err( req )) ret = reply->handle;
1854     }
1855     SERVER_END_REQ;
1856     return ret;
1857 }
1858
1859
1860 /*********************************************************************
1861  *           MapProcessHandle   (KERNEL.483)
1862  */
1863 DWORD WINAPI MapProcessHandle( HANDLE handle )
1864 {
1865     DWORD ret = 0;
1866     SERVER_START_REQ( get_process_info )
1867     {
1868         req->handle = handle;
1869         if (!wine_server_call_err( req )) ret = reply->pid;
1870     }
1871     SERVER_END_REQ;
1872     return ret;
1873 }
1874
1875
1876 /***********************************************************************
1877  *           SetPriorityClass   (KERNEL32.@)
1878  */
1879 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1880 {
1881     BOOL ret;
1882     SERVER_START_REQ( set_process_info )
1883     {
1884         req->handle   = hprocess;
1885         req->priority = priorityclass;
1886         req->mask     = SET_PROCESS_INFO_PRIORITY;
1887         ret = !wine_server_call_err( req );
1888     }
1889     SERVER_END_REQ;
1890     return ret;
1891 }
1892
1893
1894 /***********************************************************************
1895  *           GetPriorityClass   (KERNEL32.@)
1896  */
1897 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1898 {
1899     DWORD ret = 0;
1900     SERVER_START_REQ( get_process_info )
1901     {
1902         req->handle = hprocess;
1903         if (!wine_server_call_err( req )) ret = reply->priority;
1904     }
1905     SERVER_END_REQ;
1906     return ret;
1907 }
1908
1909
1910 /***********************************************************************
1911  *          SetProcessAffinityMask   (KERNEL32.@)
1912  */
1913 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1914 {
1915     BOOL ret;
1916     SERVER_START_REQ( set_process_info )
1917     {
1918         req->handle   = hProcess;
1919         req->affinity = affmask;
1920         req->mask     = SET_PROCESS_INFO_AFFINITY;
1921         ret = !wine_server_call_err( req );
1922     }
1923     SERVER_END_REQ;
1924     return ret;
1925 }
1926
1927
1928 /**********************************************************************
1929  *          GetProcessAffinityMask    (KERNEL32.@)
1930  */
1931 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1932                                       LPDWORD lpProcessAffinityMask,
1933                                       LPDWORD lpSystemAffinityMask )
1934 {
1935     BOOL ret = FALSE;
1936     SERVER_START_REQ( get_process_info )
1937     {
1938         req->handle = hProcess;
1939         if (!wine_server_call_err( req ))
1940         {
1941             if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
1942             if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
1943             ret = TRUE;
1944         }
1945     }
1946     SERVER_END_REQ;
1947     return ret;
1948 }
1949
1950
1951 /***********************************************************************
1952  *           GetProcessVersion    (KERNEL32.@)
1953  */
1954 DWORD WINAPI GetProcessVersion( DWORD processid )
1955 {
1956     IMAGE_NT_HEADERS *nt;
1957
1958     if (processid && processid != GetCurrentProcessId())
1959     {
1960         FIXME("should use ReadProcessMemory\n");
1961         return 0;
1962     }
1963     if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
1964         return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1965                 nt->OptionalHeader.MinorSubsystemVersion);
1966     return 0;
1967 }
1968
1969
1970 /***********************************************************************
1971  *              SetProcessWorkingSetSize        [KERNEL32.@]
1972  * Sets the min/max working set sizes for a specified process.
1973  *
1974  * PARAMS
1975  *    hProcess [I] Handle to the process of interest
1976  *    minset   [I] Specifies minimum working set size
1977  *    maxset   [I] Specifies maximum working set size
1978  *
1979  * RETURNS  STD
1980  */
1981 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
1982                                      SIZE_T maxset)
1983 {
1984     FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1985     if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
1986         /* Trim the working set to zero */
1987         /* Swap the process out of physical RAM */
1988     }
1989     return TRUE;
1990 }
1991
1992 /***********************************************************************
1993  *           GetProcessWorkingSetSize    (KERNEL32.@)
1994  */
1995 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
1996                                      PSIZE_T maxset)
1997 {
1998     FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
1999     /* 32 MB working set size */
2000     if (minset) *minset = 32*1024*1024;
2001     if (maxset) *maxset = 32*1024*1024;
2002     return TRUE;
2003 }
2004
2005
2006 /***********************************************************************
2007  *           SetProcessShutdownParameters    (KERNEL32.@)
2008  */
2009 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2010 {
2011     FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2012     shutdown_flags = flags;
2013     shutdown_priority = level;
2014     return TRUE;
2015 }
2016
2017
2018 /***********************************************************************
2019  * GetProcessShutdownParameters                 (KERNEL32.@)
2020  *
2021  */
2022 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2023 {
2024     *lpdwLevel = shutdown_priority;
2025     *lpdwFlags = shutdown_flags;
2026     return TRUE;
2027 }
2028
2029
2030 /***********************************************************************
2031  *           GetProcessPriorityBoost    (KERNEL32.@)
2032  */
2033 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2034 {
2035     FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2036     
2037     /* Report that no boost is present.. */
2038     *pDisablePriorityBoost = FALSE;
2039     
2040     return TRUE;
2041 }
2042
2043 /***********************************************************************
2044  *           SetProcessPriorityBoost    (KERNEL32.@)
2045  */
2046 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2047 {
2048     FIXME("(%p,%d): stub\n",hprocess,disableboost);
2049     /* Say we can do it. I doubt the program will notice that we don't. */
2050     return TRUE;
2051 }
2052
2053
2054 /***********************************************************************
2055  *              ReadProcessMemory (KERNEL32.@)
2056  */
2057 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2058                                SIZE_T *bytes_read )
2059 {
2060     NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2061     if (status) SetLastError( RtlNtStatusToDosError(status) );
2062     return !status;
2063 }
2064
2065
2066 /***********************************************************************
2067  *           WriteProcessMemory                 (KERNEL32.@)
2068  */
2069 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2070                                 SIZE_T *bytes_written )
2071 {
2072     NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2073     if (status) SetLastError( RtlNtStatusToDosError(status) );
2074     return !status;
2075 }
2076
2077
2078 /****************************************************************************
2079  *              FlushInstructionCache (KERNEL32.@)
2080  */
2081 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2082 {
2083     if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2084     FIXME("(%p,%p,0x%08lx): stub\n",hProcess, lpBaseAddress, dwSize);
2085     return TRUE;
2086 }
2087
2088
2089 /******************************************************************
2090  *              GetProcessIoCounters (KERNEL32.@)
2091  */
2092 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2093 {
2094     NTSTATUS    status;
2095
2096     status = NtQueryInformationProcess(hProcess, ProcessIoCounters, 
2097                                        ioc, sizeof(*ioc), NULL);
2098     if (status) SetLastError( RtlNtStatusToDosError(status) );
2099     return !status;
2100 }
2101
2102 /***********************************************************************
2103  * ProcessIdToSessionId   (KERNEL32.@)
2104  * This function is available on Terminal Server 4SP4 and Windows 2000
2105  */
2106 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2107 {
2108     /* According to MSDN, if the calling process is not in a terminal
2109      * services environment, then the sessionid returned is zero.
2110      */
2111     *sessionid_ptr = 0;
2112     return TRUE;
2113 }
2114
2115
2116 /***********************************************************************
2117  *              RegisterServiceProcess (KERNEL.491)
2118  *              RegisterServiceProcess (KERNEL32.@)
2119  *
2120  * A service process calls this function to ensure that it continues to run
2121  * even after a user logged off.
2122  */
2123 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2124 {
2125     /* I don't think that Wine needs to do anything in that function */
2126     return 1; /* success */
2127 }
2128
2129
2130 /**************************************************************************
2131  *              SetFileApisToOEM   (KERNEL32.@)
2132  */
2133 VOID WINAPI SetFileApisToOEM(void)
2134 {
2135     oem_file_apis = TRUE;
2136 }
2137
2138
2139 /**************************************************************************
2140  *              SetFileApisToANSI   (KERNEL32.@)
2141  */
2142 VOID WINAPI SetFileApisToANSI(void)
2143 {
2144     oem_file_apis = FALSE;
2145 }
2146
2147
2148 /******************************************************************************
2149  * AreFileApisANSI [KERNEL32.@]  Determines if file functions are using ANSI
2150  *
2151  * RETURNS
2152  *    TRUE:  Set of file functions is using ANSI code page
2153  *    FALSE: Set of file functions is using OEM code page
2154  */
2155 BOOL WINAPI AreFileApisANSI(void)
2156 {
2157     return !oem_file_apis;
2158 }
2159
2160
2161 /***********************************************************************
2162  *           GetCurrentProcess   (KERNEL32.@)
2163  */
2164 #undef GetCurrentProcess
2165 HANDLE WINAPI GetCurrentProcess(void)
2166 {
2167     return (HANDLE)0xffffffff;
2168 }