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