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