Documentation fixes.
[wine] / scheduler / process.c
1 /*
2  * Win32 processes
3  *
4  * Copyright 1996, 1998 Alexandre Julliard
5  */
6
7 #include <assert.h>
8 #include <ctype.h>
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include "wine/winbase16.h"
16 #include "wine/exception.h"
17 #include "wine/library.h"
18 #include "drive.h"
19 #include "module.h"
20 #include "file.h"
21 #include "thread.h"
22 #include "winerror.h"
23 #include "server.h"
24 #include "options.h"
25 #include "callback.h"
26 #include "debugtools.h"
27
28 DEFAULT_DEBUG_CHANNEL(process);
29 DECLARE_DEBUG_CHANNEL(relay);
30 DECLARE_DEBUG_CHANNEL(win32);
31
32 struct _ENVDB;
33
34 /* Win32 process database */
35 typedef struct _PDB
36 {
37     LONG             header[2];        /* 00 Kernel object header */
38     HMODULE          module;           /* 08 Main exe module (NT) */
39     void            *event;            /* 0c Pointer to an event object (unused) */
40     DWORD            exit_code;        /* 10 Process exit code */
41     DWORD            unknown2;         /* 14 Unknown */
42     HANDLE           heap;             /* 18 Default process heap */
43     HANDLE           mem_context;      /* 1c Process memory context */
44     DWORD            flags;            /* 20 Flags */
45     void            *pdb16;            /* 24 DOS PSP */
46     WORD             PSP_sel;          /* 28 Selector to DOS PSP */
47     WORD             imte;             /* 2a IMTE for the process module */
48     WORD             threads;          /* 2c Number of threads */
49     WORD             running_threads;  /* 2e Number of running threads */
50     WORD             free_lib_count;   /* 30 Recursion depth of FreeLibrary calls */
51     WORD             ring0_threads;    /* 32 Number of ring 0 threads */
52     HANDLE           system_heap;      /* 34 System heap to allocate handles */
53     HTASK            task;             /* 38 Win16 task */
54     void            *mem_map_files;    /* 3c Pointer to mem-mapped files */
55     struct _ENVDB   *env_db;           /* 40 Environment database */
56     void            *handle_table;     /* 44 Handle table */
57     struct _PDB     *parent;           /* 48 Parent process */
58     void            *modref_list;      /* 4c MODREF list */
59     void            *thread_list;      /* 50 List of threads */
60     void            *debuggee_CB;      /* 54 Debuggee context block */
61     void            *local_heap_free;  /* 58 Head of local heap free list */
62     DWORD            unknown4;         /* 5c Unknown */
63     CRITICAL_SECTION crit_section;     /* 60 Critical section */
64     DWORD            unknown5[3];      /* 78 Unknown */
65     void            *console;          /* 84 Console */
66     DWORD            tls_bits[2];      /* 88 TLS in-use bits */
67     DWORD            process_dword;    /* 90 Unknown */
68     struct _PDB     *group;            /* 94 Process group */
69     void            *exe_modref;       /* 98 MODREF for the process EXE */
70     void            *top_filter;       /* 9c Top exception filter */
71     DWORD            priority;         /* a0 Priority level */
72     HANDLE           heap_list;        /* a4 Head of process heap list */
73     void            *heap_handles;     /* a8 Head of heap handles list */
74     DWORD            unknown6;         /* ac Unknown */
75     void            *console_provider; /* b0 Console provider (??) */
76     WORD             env_selector;     /* b4 Selector to process environment */
77     WORD             error_mode;       /* b6 Error mode */
78     HANDLE           load_done_evt;    /* b8 Event for process loading done */
79     void            *UTState;          /* bc Head of Univeral Thunk list */
80     DWORD            unknown8;         /* c0 Unknown (NT) */
81     LCID             locale;           /* c4 Locale to be queried by GetThreadLocale (NT) */
82 } PDB;
83
84 PDB current_process;
85
86 /* Process flags */
87 #define PDB32_DEBUGGED      0x0001  /* Process is being debugged */
88 #define PDB32_WIN16_PROC    0x0008  /* Win16 process */
89 #define PDB32_DOS_PROC      0x0010  /* Dos process */
90 #define PDB32_CONSOLE_PROC  0x0020  /* Console process */
91 #define PDB32_FILE_APIS_OEM 0x0040  /* File APIs are OEM */
92 #define PDB32_WIN32S_PROC   0x8000  /* Win32s process */
93
94 static char **main_exe_argv;
95 static char main_exe_name[MAX_PATH];
96 static HANDLE main_exe_file;
97
98 unsigned int server_startticks;
99
100 /* memory/environ.c */
101 extern struct _ENVDB *ENV_BuildEnvironment(void);
102 extern BOOL ENV_BuildCommandLine( char **argv );
103 extern STARTUPINFOA current_startupinfo;
104
105 /* scheduler/pthread.c */
106 extern void PTHREAD_init_done(void);
107
108 extern BOOL MAIN_MainInit(void);
109
110
111 /***********************************************************************
112  *           PROCESS_CallUserSignalProc
113  *
114  * FIXME:  Some of the signals aren't sent correctly!
115  *
116  * The exact meaning of the USER signals is undocumented, but this 
117  * should cover the basic idea:
118  *
119  * USIG_DLL_UNLOAD_WIN16
120  *     This is sent when a 16-bit module is unloaded.
121  *
122  * USIG_DLL_UNLOAD_WIN32
123  *     This is sent when a 32-bit module is unloaded.
124  *
125  * USIG_DLL_UNLOAD_ORPHANS
126  *     This is sent after the last Win3.1 module is unloaded,
127  *     to allow removal of orphaned menus.
128  *
129  * USIG_FAULT_DIALOG_PUSH
130  * USIG_FAULT_DIALOG_POP
131  *     These are called to allow USER to prepare for displaying a
132  *     fault dialog, even though the fault might have happened while
133  *     inside a USER critical section.
134  *
135  * USIG_THREAD_INIT
136  *     This is called from the context of a new thread, as soon as it
137  *     has started to run.
138  *
139  * USIG_THREAD_EXIT
140  *     This is called, still in its context, just before a thread is
141  *     about to terminate.
142  *
143  * USIG_PROCESS_CREATE
144  *     This is called, in the parent process context, after a new process
145  *     has been created.
146  *
147  * USIG_PROCESS_INIT
148  *     This is called in the new process context, just after the main thread
149  *     has started execution (after the main thread's USIG_THREAD_INIT has
150  *     been sent).
151  *
152  * USIG_PROCESS_LOADED
153  *     This is called after the executable file has been loaded into the
154  *     new process context.
155  *
156  * USIG_PROCESS_RUNNING
157  *     This is called immediately before the main entry point is called.
158  *
159  * USIG_PROCESS_EXIT
160  *     This is called in the context of a process that is about to
161  *     terminate (but before the last thread's USIG_THREAD_EXIT has
162  *     been sent).
163  *
164  * USIG_PROCESS_DESTROY
165  *     This is called after a process has terminated.
166  *
167  *
168  * The meaning of the dwFlags bits is as follows:
169  *
170  * USIG_FLAGS_WIN32
171  *     Current process is 32-bit.
172  *
173  * USIG_FLAGS_GUI
174  *     Current process is a (Win32) GUI process.
175  *
176  * USIG_FLAGS_FEEDBACK 
177  *     Current process needs 'feedback' (determined from the STARTUPINFO
178  *     flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
179  *
180  * USIG_FLAGS_FAULT
181  *     The signal is being sent due to a fault.
182  */
183 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE16 hModule )
184 {
185     DWORD flags = current_process.flags;
186     DWORD startup_flags = current_startupinfo.dwFlags;
187     DWORD dwFlags = 0;
188
189     if (!Callout.UserSignalProc) return;
190
191     /* Determine dwFlags */
192
193     if ( !(flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
194
195     if ( !(flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
196
197     if ( dwFlags & USIG_FLAGS_GUI )
198     {
199         /* Feedback defaults to ON */
200         if ( !(startup_flags & STARTF_FORCEOFFFEEDBACK) )
201             dwFlags |= USIG_FLAGS_FEEDBACK;
202     }
203     else
204     {
205         /* Feedback defaults to OFF */
206         if (startup_flags & STARTF_FORCEONFEEDBACK)
207             dwFlags |= USIG_FLAGS_FEEDBACK;
208     }
209
210     /* Call USER signal proc */
211
212     if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
213         Callout.UserSignalProc( uCode, GetCurrentThreadId(), dwFlags, hModule );
214     else
215         Callout.UserSignalProc( uCode, GetCurrentProcessId(), dwFlags, hModule );
216 }
217
218
219 /***********************************************************************
220  *           set_console_handles
221  *
222  * Set the console handles to use stdin/stdout.
223  */
224 static void set_console_handles( HANDLE console )
225 {
226     wine_server_send_fd( 0 );
227     wine_server_send_fd( 1 );
228
229     SERVER_START_REQ( set_console_fd )
230     {
231         req->handle = console;
232         req->fd_in  = 0;
233         req->fd_out = 1;
234         req->pid    = 0;
235         SERVER_CALL();
236     }
237     SERVER_END_REQ;
238 }
239
240
241 /***********************************************************************
242  *           process_init
243  *
244  * Main process initialisation code
245  */
246 static BOOL process_init( char *argv[] )
247 {
248     BOOL ret;
249     int create_flags = 0;
250
251     /* store the program name */
252     argv0 = argv[0];
253     main_exe_argv = argv;
254
255     /* Fill the initial process structure */
256     current_process.exit_code       = STILL_ACTIVE;
257     current_process.threads         = 1;
258     current_process.running_threads = 1;
259     current_process.ring0_threads   = 1;
260     current_process.group           = &current_process;
261     current_process.priority        = 8;  /* Normal */
262
263     /* Setup the server connection */
264     CLIENT_InitServer();
265
266     /* Retrieve startup info from the server */
267     SERVER_START_VAR_REQ( init_process, sizeof(main_exe_name)-1 )
268     {
269         req->ldt_copy  = &wine_ldt_copy;
270         req->ppid      = getppid();
271         if ((ret = !SERVER_CALL_ERR()))
272         {
273             size_t len = server_data_size( req );
274             memcpy( main_exe_name, server_data_ptr(req), len );
275             main_exe_name[len] = 0;
276             main_exe_file = req->exe_file;
277             create_flags  = req->create_flags;
278             current_startupinfo.dwFlags     = req->start_flags;
279             server_startticks               = req->server_start;
280             current_startupinfo.wShowWindow = req->cmd_show;
281             current_startupinfo.hStdInput   = req->hstdin;
282             current_startupinfo.hStdOutput  = req->hstdout;
283             current_startupinfo.hStdError   = req->hstderr;
284         }
285     }
286     SERVER_END_VAR_REQ;
287     if (!ret) return FALSE;
288
289     SetStdHandle( STD_INPUT_HANDLE,  current_startupinfo.hStdInput );
290     SetStdHandle( STD_OUTPUT_HANDLE, current_startupinfo.hStdOutput );
291     SetStdHandle( STD_ERROR_HANDLE,  current_startupinfo.hStdError );
292     if (create_flags & CREATE_NEW_CONSOLE)
293         set_console_handles( current_startupinfo.hStdOutput );
294
295     /* Create the process heap */
296     current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
297
298     /* Now we can use the pthreads routines */
299     PTHREAD_init_done();
300
301     /* Copy the parent environment */
302     if (!(current_process.env_db = ENV_BuildEnvironment())) return FALSE;
303
304     /* Parse command line arguments */
305     OPTIONS_ParseOptions( argv );
306
307     return MAIN_MainInit();
308 }
309
310
311 /***********************************************************************
312  *           start_process
313  *
314  * Startup routine of a new process. Runs on the new process stack.
315  */
316 static void start_process(void)
317 {
318     int debugged, console_app;
319     LPTHREAD_START_ROUTINE entry;
320     WINE_MODREF *wm;
321
322     /* use original argv[0] as name for the main module */
323     if (!main_exe_name[0])
324     {
325         if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
326             lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
327     }
328
329     /* Retrieve entry point address */
330     entry = (LPTHREAD_START_ROUTINE)((char*)current_process.module +
331                          PE_HEADER(current_process.module)->OptionalHeader.AddressOfEntryPoint);
332     console_app = (PE_HEADER(current_process.module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
333     if (console_app) current_process.flags |= PDB32_CONSOLE_PROC;
334
335     /* Signal the parent process to continue */
336     SERVER_START_REQ( init_process_done )
337     {
338         req->module   = (void *)current_process.module;
339         req->entry    = entry;
340         req->name     = main_exe_name;
341         req->exe_file = main_exe_file;
342         req->gui      = !console_app;
343         SERVER_CALL();
344         debugged = req->debugged;
345     }
346     SERVER_END_REQ;
347
348     /* Install signal handlers; this cannot be done before, since we cannot
349      * send exceptions to the debugger before the create process event that
350      * is sent by REQ_INIT_PROCESS_DONE */
351     if (!SIGNAL_Init()) goto error;
352
353     /* create the main modref and load dependencies */
354     if (!(wm = PE_CreateModule( current_process.module, main_exe_name, 0, 0, FALSE )))
355         goto error;
356     wm->refCount++;
357
358     RtlAcquirePebLock();
359     PE_InitTls();
360     MODULE_DllProcessAttach( NULL, (LPVOID)1 );
361     RtlReleasePebLock();
362
363     /* Get pointers to USER routines called by KERNEL */
364     THUNK_InitCallout();
365
366     /* Call FinalUserInit routine */
367     if (Callout.FinalUserInit16) Callout.FinalUserInit16();
368
369     /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
370      *       context of the parent process.  Actually, the USER signal proc
371      *       doesn't really care about that, but it *does* require that the
372      *       startup parameters are correctly set up, so that GetProcessDword
373      *       works.  Furthermore, before calling the USER signal proc the 
374      *       16-bit stack must be set up, which it is only after TASK_Create
375      *       in the case of a 16-bit process. Thus, we send the signal here.
376      */
377     PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
378     PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
379     PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
380     PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
381     /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
382     if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
383
384     if (TRACE_ON(relay))
385         DPRINTF( "%08lx:Starting process %s (entryproc=%p)\n",
386                  GetCurrentThreadId(), main_exe_name, entry );
387     if (debugged) DbgBreakPoint();
388     /* FIXME: should use _PEB as parameter for NT 3.5 programs !
389      * Dunno about other OSs */
390     SetLastError(0);  /* clear error code */
391     ExitThread( entry(NULL) );
392
393  error:
394     ExitProcess( GetLastError() );
395 }
396
397
398 /***********************************************************************
399  *           open_winelib_app
400  *
401  * Try to open the Winelib app .so file based on argv[0] or WINEPRELOAD.
402  */
403 void *open_winelib_app( char *argv[] )
404 {
405     void *ret = NULL;
406     char *tmp;
407     const char *name;
408     char errStr[100];
409
410     if ((name = getenv( "WINEPRELOAD" )))
411     {
412         if (!(ret = wine_dll_load_main_exe( name, 0, errStr, sizeof(errStr) )))
413         {
414             MESSAGE( "%s: could not load '%s' as specified in the WINEPRELOAD environment variable: %s\n",
415                      argv[0], name, errStr );
416             ExitProcess(1);
417         }
418     }
419     else
420     {
421         const char *argv0 = main_exe_name;
422         if (!*argv0)
423         {
424             /* if argv[0] is "wine", don't try to load anything */
425             argv0 = argv[0];
426             if (!(name = strrchr( argv0, '/' ))) name = argv0;
427             else name++;
428             if (!strcmp( name, "wine" )) return NULL;
429         }
430
431         /* now try argv[0] with ".so" appended */
432         if ((tmp = HeapAlloc( GetProcessHeap(), 0, strlen(argv0) + 4 )))
433         {
434             strcpy( tmp, argv0 );
435             strcat( tmp, ".so" );
436             /* search in PATH only if there was no '/' in argv[0] */
437             ret = wine_dll_load_main_exe( tmp, (name == argv0), errStr, sizeof(errStr) );
438             if (!ret && !argv[1])
439             {
440                 /* if no argv[1], this will be better than displaying usage */
441                 MESSAGE( "%s: could not load library '%s' as Winelib application: %s\n",
442                          argv[0], tmp, errStr );
443                 ExitProcess(1);
444             }
445             HeapFree( GetProcessHeap(), 0, tmp );
446         }
447     }
448     return ret;
449 }
450
451 /***********************************************************************
452  *           PROCESS_InitWine
453  *
454  * Wine initialisation: load and start the main exe file.
455  */
456 void PROCESS_InitWine( int argc, char *argv[], LPSTR win16_exe_name, HANDLE *win16_exe_file )
457 {
458     DWORD stack_size = 0;
459
460     /* Initialize everything */
461     if (!process_init( argv )) exit(1);
462
463     if (open_winelib_app( argv )) goto found; /* try to open argv[0] as a winelib app */
464
465     main_exe_argv = ++argv;  /* remove argv[0] (wine itself) */
466
467     if (!main_exe_name[0])
468     {
469         if (!argv[0]) OPTIONS_Usage();
470
471         /* open the exe file */
472         if (!SearchPathA( NULL, argv[0], ".exe", sizeof(main_exe_name), main_exe_name, NULL ) &&
473             !SearchPathA( NULL, argv[0], NULL, sizeof(main_exe_name), main_exe_name, NULL ))
474         {
475             MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
476             goto error;
477         }
478     }
479
480     if (!main_exe_file)
481     {
482         if ((main_exe_file = CreateFileA( main_exe_name, GENERIC_READ, FILE_SHARE_READ,
483                                           NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
484         {
485             MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
486             goto error;
487         }
488     }
489
490     /* first try Win32 format; this will fail if the file is not a PE binary */
491     if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 )))
492     {
493         if (PE_HEADER(current_process.module)->FileHeader.Characteristics & IMAGE_FILE_DLL)
494             ExitProcess( ERROR_BAD_EXE_FORMAT );
495         goto found;
496     }
497
498     /* it must be 16-bit or DOS format */
499     NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
500     current_process.flags |= PDB32_WIN16_PROC;
501     strcpy( win16_exe_name, main_exe_name );
502     main_exe_name[0] = 0;
503     *win16_exe_file = main_exe_file;
504     main_exe_file = 0;
505     _EnterWin16Lock();
506
507  found:
508     /* build command line */
509     if (!ENV_BuildCommandLine( main_exe_argv )) goto error;
510
511     /* create 32-bit module for main exe */
512     if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
513     stack_size = PE_HEADER(current_process.module)->OptionalHeader.SizeOfStackReserve;
514
515     /* allocate main thread stack */
516     if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
517
518     /* switch to the new stack */
519     SYSDEPS_SwitchToThreadStack( start_process );
520
521  error:
522     ExitProcess( GetLastError() );
523 }
524
525
526 /***********************************************************************
527  *           build_argv
528  *
529  * Build an argv array from a command-line.
530  * The command-line is modified to insert nulls.
531  * 'reserved' is the number of args to reserve before the first one.
532  */
533 static char **build_argv( char *cmdline, int reserved )
534 {
535     char **argv;
536     int count = reserved + 1;
537     char *p = cmdline;
538
539     /* if first word is quoted store it as a single arg */
540     if (*cmdline == '\"')
541     {
542         if ((p = strchr( cmdline + 1, '\"' )))
543         {
544             p++;
545             count++;
546         }
547         else p = cmdline;
548     }
549     while (*p)
550     {
551         while (*p && isspace(*p)) p++;
552         if (!*p) break;
553         count++;
554         while (*p && !isspace(*p)) p++;
555     }
556
557     if ((argv = malloc( count * sizeof(*argv) )))
558     {
559         char **argvptr = argv + reserved;
560         p = cmdline;
561         if (*cmdline == '\"')
562         {
563             if ((p = strchr( cmdline + 1, '\"' )))
564             {
565                 *argvptr++ = cmdline + 1;
566                 *p++ = 0;
567             }
568             else p = cmdline;
569         }
570         while (*p)
571         {
572             while (*p && isspace(*p)) *p++ = 0;
573             if (!*p) break;
574             *argvptr++ = p;
575             while (*p && !isspace(*p)) p++;
576         }
577         *argvptr = 0;
578     }
579     return argv;
580 }
581
582
583 /***********************************************************************
584  *           build_envp
585  *
586  * Build the environment of a new child process.
587  */
588 static char **build_envp( const char *env, const char *extra_env )
589 {
590     const char *p;
591     char **envp;
592     int count = 0;
593
594     if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
595     for (p = env; *p; count++) p += strlen(p) + 1;
596     count += 3;
597
598     if ((envp = malloc( count * sizeof(*envp) )))
599     {
600         extern char **environ;
601         char **envptr = envp;
602         char **unixptr = environ;
603         /* first the extra strings */
604         if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
605         /* then put PATH, HOME and WINEPREFIX from the unix env */
606         for (unixptr = environ; unixptr && *unixptr; unixptr++)
607             if (!memcmp( *unixptr, "PATH=", 5 ) ||
608                 !memcmp( *unixptr, "HOME=", 5 ) ||
609                 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
610         /* now put the Windows environment strings */
611         for (p = env; *p; p += strlen(p) + 1)
612         {
613             if (memcmp( p, "PATH=", 5 ) &&
614                 memcmp( p, "HOME=", 5 ) &&
615                 memcmp( p, "WINEPRELOAD=", 12 ) &&
616                 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
617         }
618         *envptr = 0;
619     }
620     return envp;
621 }
622
623
624 /***********************************************************************
625  *           exec_wine_binary
626  *
627  * Locate the Wine binary to exec for a new Win32 process.
628  */
629 static void exec_wine_binary( char **argv, char **envp )
630 {
631     const char *path, *pos, *ptr;
632
633     /* first, try for a WINELOADER environment variable */
634     argv[0] = getenv("WINELOADER");
635     if (argv[0])
636         execve( argv[0], argv, envp );
637
638     /* next, try bin directory */
639     argv[0] = BINDIR "/wine";
640     execve( argv[0], argv, envp );
641
642     /* now try the path of argv0 of the current binary */
643     if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
644     if ((ptr = strrchr( full_argv0, '/' )))
645     {
646         memcpy( argv[0], full_argv0, ptr - full_argv0 );
647         strcpy( argv[0] + (ptr - full_argv0), "/wine" );
648         execve( argv[0], argv, envp );
649     }
650     free( argv[0] );
651
652     /* now search in the Unix path */
653     if ((path = getenv( "PATH" )))
654     {
655         if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
656         pos = path;
657         for (;;)
658         {
659             while (*pos == ':') pos++;
660             if (!*pos) break;
661             if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
662             memcpy( argv[0], pos, ptr - pos );
663             strcpy( argv[0] + (ptr - pos), "/wine" );
664             execve( argv[0], argv, envp );
665             pos = ptr;
666         }
667     }
668     free( argv[0] );
669
670     /* finally try the current directory */
671     argv[0] = "./wine";
672     execve( argv[0], argv, envp );
673 }
674
675
676 /***********************************************************************
677  *           fork_and_exec
678  *
679  * Fork and exec a new Unix process, checking for errors.
680  */
681 static int fork_and_exec( const char *filename, char *cmdline,
682                           const char *env, const char *newdir )
683 {
684     int fd[2];
685     int pid, err;
686     char *extra_env = NULL;
687
688     if (!env)
689     {
690         env = GetEnvironmentStringsA();
691         extra_env = DRIVE_BuildEnv();
692     }
693
694     if (pipe(fd) == -1)
695     {
696         FILE_SetDosError();
697         return -1;
698     }
699     fcntl( fd[1], F_SETFD, 1 );  /* set close on exec */
700     if (!(pid = fork()))  /* child */
701     {
702         char **argv = build_argv( cmdline, filename ? 0 : 2 );
703         char **envp = build_envp( env, extra_env );
704         close( fd[0] );
705
706         if (newdir) chdir(newdir);
707
708         if (argv && envp)
709         {
710             if (!filename)
711             {
712                 argv[1] = "--";
713                 exec_wine_binary( argv, envp );
714             }
715             else execve( filename, argv, envp );
716         }
717         err = errno;
718         write( fd[1], &err, sizeof(err) );
719         _exit(1);
720     }
721     close( fd[1] );
722     if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0))  /* exec failed */
723     {
724         errno = err;
725         pid = -1;
726     }
727     if (pid == -1) FILE_SetDosError();
728     close( fd[0] );
729     if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
730     return pid;
731 }
732
733
734 /***********************************************************************
735  *           PROCESS_Create
736  *
737  * Create a new process. If hFile is a valid handle we have an exe
738  * file, and we exec a new copy of wine to load it; otherwise we
739  * simply exec the specified filename as a Unix process.
740  */
741 BOOL PROCESS_Create( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
742                      LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
743                      BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
744                      LPPROCESS_INFORMATION info, LPCSTR lpCurrentDirectory )
745 {
746     BOOL ret;
747     int pid;
748     const char *unixfilename = NULL;
749     const char *unixdir = NULL;
750     DOS_FULL_NAME full_dir, full_name;
751     HANDLE load_done_evt = 0;
752     HANDLE process_info;
753
754     info->hThread = info->hProcess = 0;
755
756     if (lpCurrentDirectory)
757     {
758         if (DOSFS_GetFullName( lpCurrentDirectory, TRUE, &full_dir ))
759             unixdir = full_dir.long_name;
760     }
761     else
762     {
763         char buf[MAX_PATH];
764         if (GetCurrentDirectoryA(sizeof(buf),buf))
765         {
766             if (DOSFS_GetFullName( buf, TRUE, &full_dir ))
767                 unixdir = full_dir.long_name;
768         }
769     }
770
771     /* create the process on the server side */
772
773     SERVER_START_VAR_REQ( new_process, MAX_PATH )
774     {
775         req->inherit_all  = inherit;
776         req->create_flags = flags;
777         req->start_flags  = startup->dwFlags;
778         req->exe_file     = hFile;
779         if (startup->dwFlags & STARTF_USESTDHANDLES)
780         {
781             req->hstdin  = startup->hStdInput;
782             req->hstdout = startup->hStdOutput;
783             req->hstderr = startup->hStdError;
784         }
785         else
786         {
787             req->hstdin  = GetStdHandle( STD_INPUT_HANDLE );
788             req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
789             req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
790         }
791         req->cmd_show = startup->wShowWindow;
792
793         if (!hFile)  /* unix process */
794         {
795             unixfilename = filename;
796             if (DOSFS_GetFullName( filename, TRUE, &full_name ))
797                 unixfilename = full_name.long_name;
798             lstrcpynA( server_data_ptr(req), unixfilename, MAX_PATH );
799         }
800         else  /* new wine process */
801         {
802             if (!GetLongPathNameA( filename, server_data_ptr(req), MAX_PATH ))
803                 lstrcpynA( server_data_ptr(req), filename, MAX_PATH );
804         }
805         ret = !SERVER_CALL_ERR();
806         process_info = req->info;
807     }
808     SERVER_END_VAR_REQ;
809     if (!ret) return FALSE;
810
811     /* fork and execute */
812
813     pid = fork_and_exec( unixfilename, cmd_line, env, unixdir );
814
815     /* wait for the new process info to be ready */
816
817     ret = FALSE;
818     if ((pid != -1) && (WaitForSingleObject( process_info, 2000 ) == STATUS_WAIT_0))
819     {
820         SERVER_START_REQ( get_new_process_info )
821         {
822             req->info     = process_info;
823             req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
824             req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
825             if ((ret = !SERVER_CALL_ERR()))
826             {
827                 info->dwProcessId = (DWORD)req->pid;
828                 info->dwThreadId  = (DWORD)req->tid;
829                 info->hProcess    = req->phandle;
830                 info->hThread     = req->thandle;
831                 load_done_evt     = req->event;
832             }
833         }
834         SERVER_END_REQ;
835     }
836     CloseHandle( process_info );
837     if (!ret) goto error;
838
839     /* Wait until process is initialized (or initialization failed) */
840     if (load_done_evt)
841     {
842         DWORD res;
843         HANDLE handles[2];
844
845         handles[0] = info->hProcess;
846         handles[1] = load_done_evt;
847         res = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
848         CloseHandle( load_done_evt );
849         if (res == STATUS_WAIT_0)  /* the process died */
850         {
851             DWORD exitcode;
852             if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
853             CloseHandle( info->hThread );
854             CloseHandle( info->hProcess );
855             return FALSE;
856         }
857     }
858     return TRUE;
859
860 error:
861     if (load_done_evt) CloseHandle( load_done_evt );
862     if (info->hThread) CloseHandle( info->hThread );
863     if (info->hProcess) CloseHandle( info->hProcess );
864     return FALSE;
865 }
866
867
868 /***********************************************************************
869  *           ExitProcess   (KERNEL32.@)
870  */
871 void WINAPI ExitProcess( DWORD status )
872 {
873     MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
874     SERVER_START_REQ( terminate_process )
875     {
876         /* send the exit code to the server */
877         req->handle    = GetCurrentProcess();
878         req->exit_code = status;
879         SERVER_CALL();
880     }
881     SERVER_END_REQ;
882     exit( status );
883 }
884
885 /***********************************************************************
886  *           ExitProcess   (KERNEL.466)
887  */
888 void WINAPI ExitProcess16( WORD status )
889 {
890     DWORD count;
891     ReleaseThunkLock( &count );
892     ExitProcess( status );
893 }
894
895 /******************************************************************************
896  *           TerminateProcess   (KERNEL32.@)
897  */
898 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
899 {
900     NTSTATUS status = NtTerminateProcess( handle, exit_code );
901     if (status) SetLastError( RtlNtStatusToDosError(status) );
902     return !status;
903 }
904
905
906 /***********************************************************************
907  *           GetProcessDword    (KERNEL.485)
908  *           GetProcessDword    (KERNEL32.18)
909  * 'Of course you cannot directly access Windows internal structures'
910  */
911 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
912 {
913     DWORD x, y;
914
915     TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
916
917     if (dwProcessID && dwProcessID != GetCurrentProcessId())
918     {
919         ERR("%d: process %lx not accessible\n", offset, dwProcessID);
920         return 0;
921     }
922
923     switch ( offset ) 
924     {
925     case GPD_APP_COMPAT_FLAGS:
926         return GetAppCompatFlags16(0);
927
928     case GPD_LOAD_DONE_EVENT:
929         return current_process.load_done_evt;
930
931     case GPD_HINSTANCE16:
932         return GetTaskDS16();
933
934     case GPD_WINDOWS_VERSION:
935         return GetExeVersion16();
936
937     case GPD_THDB:
938         return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
939
940     case GPD_PDB:
941         return (DWORD)&current_process;
942
943     case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
944         return current_startupinfo.hStdOutput;
945
946     case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
947         return current_startupinfo.hStdInput;
948
949     case GPD_STARTF_SHOWWINDOW:
950         return current_startupinfo.wShowWindow;
951
952     case GPD_STARTF_SIZE:
953         x = current_startupinfo.dwXSize;
954         if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
955         y = current_startupinfo.dwYSize;
956         if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
957         return MAKELONG( x, y );
958
959     case GPD_STARTF_POSITION:
960         x = current_startupinfo.dwX;
961         if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
962         y = current_startupinfo.dwY;
963         if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
964         return MAKELONG( x, y );
965
966     case GPD_STARTF_FLAGS:
967         return current_startupinfo.dwFlags;
968
969     case GPD_PARENT:
970         return 0;
971
972     case GPD_FLAGS:
973         return current_process.flags;
974
975     case GPD_USERDATA:
976         return current_process.process_dword;
977
978     default:
979         ERR_(win32)("Unknown offset %d\n", offset );
980         return 0;
981     }
982 }
983
984 /***********************************************************************
985  *           SetProcessDword    (KERNEL.484)
986  * 'Of course you cannot directly access Windows internal structures'
987  */
988 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
989 {
990     TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
991
992     if (dwProcessID && dwProcessID != GetCurrentProcessId())
993     {
994         ERR("%d: process %lx not accessible\n", offset, dwProcessID);
995         return;
996     }
997
998     switch ( offset ) 
999     {
1000     case GPD_APP_COMPAT_FLAGS:
1001     case GPD_LOAD_DONE_EVENT:
1002     case GPD_HINSTANCE16:
1003     case GPD_WINDOWS_VERSION:
1004     case GPD_THDB:
1005     case GPD_PDB:
1006     case GPD_STARTF_SHELLDATA:
1007     case GPD_STARTF_HOTKEY:
1008     case GPD_STARTF_SHOWWINDOW:
1009     case GPD_STARTF_SIZE:
1010     case GPD_STARTF_POSITION:
1011     case GPD_STARTF_FLAGS:
1012     case GPD_PARENT:
1013     case GPD_FLAGS:
1014         ERR_(win32)("Not allowed to modify offset %d\n", offset );
1015         break;
1016
1017     case GPD_USERDATA:
1018         current_process.process_dword = value; 
1019         break;
1020
1021     default:
1022         ERR_(win32)("Unknown offset %d\n", offset );
1023         break;
1024     }
1025 }
1026
1027
1028 /*********************************************************************
1029  *           OpenProcess   (KERNEL32.@)
1030  */
1031 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1032 {
1033     HANDLE ret = 0;
1034     SERVER_START_REQ( open_process )
1035     {
1036         req->pid     = (void *)id;
1037         req->access  = access;
1038         req->inherit = inherit;
1039         if (!SERVER_CALL_ERR()) ret = req->handle;
1040     }
1041     SERVER_END_REQ;
1042     return ret;
1043 }
1044
1045 /*********************************************************************
1046  *           MapProcessHandle   (KERNEL.483)
1047  */
1048 DWORD WINAPI MapProcessHandle( HANDLE handle )
1049 {
1050     DWORD ret = 0;
1051     SERVER_START_REQ( get_process_info )
1052     {
1053         req->handle = handle;
1054         if (!SERVER_CALL_ERR()) ret = (DWORD)req->pid;
1055     }
1056     SERVER_END_REQ;
1057     return ret;
1058 }
1059
1060 /***********************************************************************
1061  *           SetPriorityClass   (KERNEL32.@)
1062  */
1063 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1064 {
1065     BOOL ret;
1066     SERVER_START_REQ( set_process_info )
1067     {
1068         req->handle   = hprocess;
1069         req->priority = priorityclass;
1070         req->mask     = SET_PROCESS_INFO_PRIORITY;
1071         ret = !SERVER_CALL_ERR();
1072     }
1073     SERVER_END_REQ;
1074     return ret;
1075 }
1076
1077
1078 /***********************************************************************
1079  *           GetPriorityClass   (KERNEL32.@)
1080  */
1081 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1082 {
1083     DWORD ret = 0;
1084     SERVER_START_REQ( get_process_info )
1085     {
1086         req->handle = hprocess;
1087         if (!SERVER_CALL_ERR()) ret = req->priority;
1088     }
1089     SERVER_END_REQ;
1090     return ret;
1091 }
1092
1093
1094 /***********************************************************************
1095  *          SetProcessAffinityMask   (KERNEL32.@)
1096  */
1097 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1098 {
1099     BOOL ret;
1100     SERVER_START_REQ( set_process_info )
1101     {
1102         req->handle   = hProcess;
1103         req->affinity = affmask;
1104         req->mask     = SET_PROCESS_INFO_AFFINITY;
1105         ret = !SERVER_CALL_ERR();
1106     }
1107     SERVER_END_REQ;
1108     return ret;
1109 }
1110
1111 /**********************************************************************
1112  *          GetProcessAffinityMask    (KERNEL32.@)
1113  */
1114 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1115                                       LPDWORD lpProcessAffinityMask,
1116                                       LPDWORD lpSystemAffinityMask )
1117 {
1118     BOOL ret = FALSE;
1119     SERVER_START_REQ( get_process_info )
1120     {
1121         req->handle = hProcess;
1122         if (!SERVER_CALL_ERR())
1123         {
1124             if (lpProcessAffinityMask) *lpProcessAffinityMask = req->process_affinity;
1125             if (lpSystemAffinityMask) *lpSystemAffinityMask = req->system_affinity;
1126             ret = TRUE;
1127         }
1128     }
1129     SERVER_END_REQ;
1130     return ret;
1131 }
1132
1133
1134 /***********************************************************************
1135  *           GetProcessVersion    (KERNEL32.@)
1136  */
1137 DWORD WINAPI GetProcessVersion( DWORD processid )
1138 {
1139     IMAGE_NT_HEADERS *nt;
1140
1141     if (processid && processid != GetCurrentProcessId())
1142     {
1143         FIXME("should use ReadProcessMemory\n");
1144         return 0;
1145     }
1146     if ((nt = RtlImageNtHeader( current_process.module )))
1147         return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1148                 nt->OptionalHeader.MinorSubsystemVersion);
1149     return 0;
1150 }
1151
1152 /***********************************************************************
1153  *           GetProcessFlags    (KERNEL32.@)
1154  */
1155 DWORD WINAPI GetProcessFlags( DWORD processid )
1156 {
1157     if (processid && processid != GetCurrentProcessId()) return 0;
1158     return current_process.flags;
1159 }
1160
1161
1162 /***********************************************************************
1163  *              SetProcessWorkingSetSize        [KERNEL32.@]
1164  * Sets the min/max working set sizes for a specified process.
1165  *
1166  * PARAMS
1167  *    hProcess [I] Handle to the process of interest
1168  *    minset   [I] Specifies minimum working set size
1169  *    maxset   [I] Specifies maximum working set size
1170  *
1171  * RETURNS  STD
1172  */
1173 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1174                                        DWORD maxset)
1175 {
1176     FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1177     if(( minset == (DWORD)-1) && (maxset == (DWORD)-1)) {
1178         /* Trim the working set to zero */
1179         /* Swap the process out of physical RAM */
1180     }
1181     return TRUE;
1182 }
1183
1184 /***********************************************************************
1185  *           GetProcessWorkingSetSize    (KERNEL32.@)
1186  */
1187 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1188                                        LPDWORD maxset)
1189 {
1190         FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1191         /* 32 MB working set size */
1192         if (minset) *minset = 32*1024*1024;
1193         if (maxset) *maxset = 32*1024*1024;
1194         return TRUE;
1195 }
1196
1197 /***********************************************************************
1198  *           SetProcessShutdownParameters    (KERNEL32.@)
1199  *
1200  * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1201  * Now tracks changes made (but does not act on these changes)
1202  */
1203 static DWORD shutdown_flags = 0;
1204 static DWORD shutdown_priority = 0x280;
1205
1206 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1207 {
1208     FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1209     shutdown_flags = flags;
1210     shutdown_priority = level;
1211     return TRUE;
1212 }
1213
1214
1215 /***********************************************************************
1216  * GetProcessShutdownParameters                 (KERNEL32.@)
1217  *
1218  */
1219 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1220 {
1221     *lpdwLevel = shutdown_priority;
1222     *lpdwFlags = shutdown_flags;
1223     return TRUE;
1224 }
1225
1226
1227 /***********************************************************************
1228  *           SetProcessPriorityBoost    (KERNEL32.@)
1229  */
1230 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1231 {
1232     FIXME("(%d,%d): stub\n",hprocess,disableboost);
1233     /* Say we can do it. I doubt the program will notice that we don't. */
1234     return TRUE;
1235 }
1236
1237
1238 /***********************************************************************
1239  *              ReadProcessMemory (KERNEL32.@)
1240  */
1241 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1242                                LPDWORD bytes_read )
1243 {
1244     unsigned int offset = (unsigned int)addr % sizeof(int);
1245     unsigned int pos = 0, len, max;
1246     int res;
1247
1248     if (bytes_read) *bytes_read = size;
1249
1250     /* first time, read total length to check for permissions */
1251     len = (size + offset + sizeof(int) - 1) / sizeof(int);
1252     max = min( REQUEST_MAX_VAR_SIZE, len * sizeof(int) );
1253
1254     for (;;)
1255     {
1256         SERVER_START_VAR_REQ( read_process_memory, max )
1257         {
1258             req->handle = process;
1259             req->addr   = (char *)addr + pos - offset;
1260             req->len    = len;
1261             if (!(res = SERVER_CALL_ERR()))
1262             {
1263                 size_t result = server_data_size( req );
1264                 if (result > size + offset) result = size + offset;
1265                 memcpy( (char *)buffer + pos, server_data_ptr(req) + offset, result - offset );
1266                 size -= result - offset;
1267                 pos += result - offset;
1268             }
1269         }
1270         SERVER_END_VAR_REQ;
1271         if (res)
1272         {
1273             if (bytes_read) *bytes_read = 0;
1274             return FALSE;
1275         }
1276         if (!size) return TRUE;
1277         max = min( REQUEST_MAX_VAR_SIZE, size );
1278         len = (max + sizeof(int) - 1) / sizeof(int);
1279         offset = 0;
1280     }
1281 }
1282
1283
1284 /***********************************************************************
1285  *           WriteProcessMemory                 (KERNEL32.@)
1286  */
1287 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPVOID buffer, DWORD size,
1288                                 LPDWORD bytes_written )
1289 {
1290     unsigned int first_offset, last_offset;
1291     unsigned int pos = 0, len, max, first_mask, last_mask;
1292     int res;
1293
1294     if (!size)
1295     {
1296         SetLastError( ERROR_INVALID_PARAMETER );
1297         return FALSE;
1298     }
1299     if (bytes_written) *bytes_written = size;
1300
1301     /* compute the mask for the first int */
1302     first_mask = ~0;
1303     first_offset = (unsigned int)addr % sizeof(int);
1304     memset( &first_mask, 0, first_offset );
1305
1306     /* compute the mask for the last int */
1307     last_offset = (size + first_offset) % sizeof(int);
1308     last_mask = 0;
1309     memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1310
1311     /* for the first request, use the total length */
1312     len = (size + first_offset + sizeof(int) - 1) / sizeof(int);
1313     max = min( REQUEST_MAX_VAR_SIZE, len * sizeof(int) );
1314
1315     for (;;)
1316     {
1317         SERVER_START_VAR_REQ( write_process_memory, max )
1318         {
1319             req->handle = process;
1320             req->addr = (char *)addr - first_offset + pos;
1321             req->len = len;
1322             req->first_mask = (!pos) ? first_mask : ~0;
1323             if (size + first_offset <= max)  /* last round */
1324             {
1325                 req->last_mask = last_mask;
1326                 max = size + first_offset;
1327             }
1328             else req->last_mask = ~0;
1329
1330             memcpy( (char *)server_data_ptr(req) + first_offset, (char *)buffer + pos,
1331                     max - first_offset );
1332             if (!(res = SERVER_CALL_ERR()))
1333             {
1334                 pos += max - first_offset;
1335                 size -= max - first_offset;
1336             }
1337         }
1338         SERVER_END_VAR_REQ;
1339         if (res)
1340         {
1341             if (bytes_written) *bytes_written = 0;
1342             return FALSE;
1343         }
1344         if (!size) return TRUE;
1345         first_offset = 0;
1346         len = min( size + sizeof(int) - 1, REQUEST_MAX_VAR_SIZE ) / sizeof(int);
1347         max = len * sizeof(int);
1348     }
1349 }
1350
1351
1352 /***********************************************************************
1353  *              RegisterServiceProcess (KERNEL.491)
1354  *              RegisterServiceProcess (KERNEL32.@)
1355  *
1356  * A service process calls this function to ensure that it continues to run
1357  * even after a user logged off.
1358  */
1359 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1360 {
1361         /* I don't think that Wine needs to do anything in that function */
1362         return 1; /* success */
1363 }
1364
1365 /***********************************************************************
1366  * GetExitCodeProcess [KERNEL32.@]
1367  *
1368  * Gets termination status of specified process
1369  * 
1370  * RETURNS
1371  *   Success: TRUE
1372  *   Failure: FALSE
1373  */
1374 BOOL WINAPI GetExitCodeProcess(
1375     HANDLE hProcess,    /* [in] handle to the process */
1376     LPDWORD lpExitCode) /* [out] address to receive termination status */
1377 {
1378     BOOL ret;
1379     SERVER_START_REQ( get_process_info )
1380     {
1381         req->handle = hProcess;
1382         ret = !SERVER_CALL_ERR();
1383         if (ret && lpExitCode) *lpExitCode = req->exit_code;
1384     }
1385     SERVER_END_REQ;
1386     return ret;
1387 }
1388
1389
1390 /***********************************************************************
1391  *           SetErrorMode   (KERNEL32.@)
1392  */
1393 UINT WINAPI SetErrorMode( UINT mode )
1394 {
1395     UINT old = current_process.error_mode;
1396     current_process.error_mode = mode;
1397     return old;
1398 }
1399
1400
1401 /**************************************************************************
1402  *              SetFileApisToOEM   (KERNEL32.@)
1403  */
1404 VOID WINAPI SetFileApisToOEM(void)
1405 {
1406     current_process.flags |= PDB32_FILE_APIS_OEM;
1407 }
1408
1409
1410 /**************************************************************************
1411  *              SetFileApisToANSI   (KERNEL32.@)
1412  */
1413 VOID WINAPI SetFileApisToANSI(void)
1414 {
1415     current_process.flags &= ~PDB32_FILE_APIS_OEM;
1416 }
1417
1418
1419 /******************************************************************************
1420  * AreFileApisANSI [KERNEL32.@]  Determines if file functions are using ANSI
1421  *
1422  * RETURNS
1423  *    TRUE:  Set of file functions is using ANSI code page
1424  *    FALSE: Set of file functions is using OEM code page
1425  */
1426 BOOL WINAPI AreFileApisANSI(void)
1427 {
1428     return !(current_process.flags & PDB32_FILE_APIS_OEM);
1429 }
1430
1431
1432 /**********************************************************************
1433  * TlsAlloc [KERNEL32.@]  Allocates a TLS index.
1434  *
1435  * Allocates a thread local storage index
1436  *
1437  * RETURNS
1438  *    Success: TLS Index
1439  *    Failure: 0xFFFFFFFF
1440  */
1441 DWORD WINAPI TlsAlloc( void )
1442 {
1443     DWORD i, mask, ret = 0;
1444     DWORD *bits = current_process.tls_bits;
1445     RtlAcquirePebLock();
1446     if (*bits == 0xffffffff)
1447     {
1448         bits++;
1449         ret = 32;
1450         if (*bits == 0xffffffff)
1451         {
1452             RtlReleasePebLock();
1453             SetLastError( ERROR_NO_MORE_ITEMS );
1454             return 0xffffffff;
1455         }
1456     }
1457     for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1458     *bits |= mask;
1459     RtlReleasePebLock();
1460     return ret + i;
1461 }
1462
1463
1464 /**********************************************************************
1465  * TlsFree [KERNEL32.@]  Releases a TLS index.
1466  *
1467  * Releases a thread local storage index, making it available for reuse
1468  * 
1469  * RETURNS
1470  *    Success: TRUE
1471  *    Failure: FALSE
1472  */
1473 BOOL WINAPI TlsFree(
1474     DWORD index) /* [in] TLS Index to free */
1475 {
1476     DWORD mask = (1 << (index & 31));
1477     DWORD *bits = current_process.tls_bits;
1478     if (index >= 64)
1479     {
1480         SetLastError( ERROR_INVALID_PARAMETER );
1481         return FALSE;
1482     }
1483     if (index >= 32) bits++;
1484     RtlAcquirePebLock();
1485     if (!(*bits & mask))  /* already free? */
1486     {
1487         RtlReleasePebLock();
1488         SetLastError( ERROR_INVALID_PARAMETER );
1489         return FALSE;
1490     }
1491     *bits &= ~mask;
1492     NtCurrentTeb()->tls_array[index] = 0;
1493     /* FIXME: should zero all other thread values */
1494     RtlReleasePebLock();
1495     return TRUE;
1496 }
1497
1498
1499 /**********************************************************************
1500  * TlsGetValue [KERNEL32.@]  Gets value in a thread's TLS slot
1501  *
1502  * RETURNS
1503  *    Success: Value stored in calling thread's TLS slot for index
1504  *    Failure: 0 and GetLastError returns NO_ERROR
1505  */
1506 LPVOID WINAPI TlsGetValue(
1507     DWORD index) /* [in] TLS index to retrieve value for */
1508 {
1509     if (index >= 64)
1510     {
1511         SetLastError( ERROR_INVALID_PARAMETER );
1512         return NULL;
1513     }
1514     SetLastError( ERROR_SUCCESS );
1515     return NtCurrentTeb()->tls_array[index];
1516 }
1517
1518
1519 /**********************************************************************
1520  * TlsSetValue [KERNEL32.@]  Stores a value in the thread's TLS slot.
1521  *
1522  * RETURNS
1523  *    Success: TRUE
1524  *    Failure: FALSE
1525  */
1526 BOOL WINAPI TlsSetValue(
1527     DWORD index,  /* [in] TLS index to set value for */
1528     LPVOID value) /* [in] Value to be stored */
1529 {
1530     if (index >= 64)
1531     {
1532         SetLastError( ERROR_INVALID_PARAMETER );
1533         return FALSE;
1534     }
1535     NtCurrentTeb()->tls_array[index] = value;
1536     return TRUE;
1537 }
1538
1539
1540 /***********************************************************************
1541  *           GetCurrentProcess   (KERNEL32.@)
1542  */
1543 #undef GetCurrentProcess
1544 HANDLE WINAPI GetCurrentProcess(void)
1545 {
1546     return 0xffffffff;
1547 }