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