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