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