Generate CREATE_PROCESS/THREAD debug events internally in the server.
[wine] / scheduler / process.c
1 /*
2  * Win32 processes
3  *
4  * Copyright 1996, 1998 Alexandre Julliard
5  */
6
7 #include <assert.h>
8 #include <fcntl.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <unistd.h>
12 #include "wine/winbase16.h"
13 #include "wine/exception.h"
14 #include "process.h"
15 #include "module.h"
16 #include "neexe.h"
17 #include "file.h"
18 #include "global.h"
19 #include "heap.h"
20 #include "task.h"
21 #include "ldt.h"
22 #include "syslevel.h"
23 #include "thread.h"
24 #include "winerror.h"
25 #include "pe_image.h"
26 #include "server.h"
27 #include "options.h"
28 #include "callback.h"
29 #include "debugtools.h"
30
31 DEFAULT_DEBUG_CHANNEL(process)
32 DECLARE_DEBUG_CHANNEL(relay)
33 DECLARE_DEBUG_CHANNEL(win32)
34
35
36 /* The initial process PDB */
37 static PDB initial_pdb;
38
39 static PDB *PROCESS_First = &initial_pdb;
40
41
42 /***********************************************************************
43  *           PROCESS_WalkProcess
44  */
45 void PROCESS_WalkProcess(void)
46 {
47     PDB  *pdb;
48     char *name;
49
50     pdb = PROCESS_First;
51     MESSAGE( " pid        PDB         #th  modref     module \n" );
52     while(pdb)
53     {
54         if (pdb == &initial_pdb)
55             name = "initial PDB";
56         else
57             name = (pdb->exe_modref) ? pdb->exe_modref->filename : "";
58
59         MESSAGE( " %8p %8p %5d  %8p %s\n", pdb->server_pid, pdb,
60                pdb->threads, pdb->exe_modref, name);
61         pdb = pdb->next;
62     }
63     return;
64 }
65
66 /***********************************************************************
67  *           PROCESS_IsCurrent
68  *
69  * Check if a handle is to the current process
70  */
71 BOOL PROCESS_IsCurrent( HANDLE handle )
72 {
73     struct get_process_info_request *req = get_req_buffer();
74     req->handle = handle;
75     return (!server_call( REQ_GET_PROCESS_INFO ) &&
76             (req->pid == PROCESS_Current()->server_pid));
77 }
78
79
80 /***********************************************************************
81  *           PROCESS_IdToPDB
82  *
83  * Convert a process id to a PDB, making sure it is valid.
84  */
85 PDB *PROCESS_IdToPDB( DWORD pid )
86 {
87     PDB *pdb;
88
89     if (!pid) return PROCESS_Current();
90     pdb = PROCESS_First;
91     while (pdb)
92     {
93         if ((DWORD)pdb->server_pid == pid) return pdb;
94         pdb = pdb->next;
95     }
96     SetLastError( ERROR_INVALID_PARAMETER );
97     return NULL;
98 }
99
100
101 /***********************************************************************
102  *           PROCESS_CallUserSignalProc
103  *
104  * FIXME:  Some of the signals aren't sent correctly!
105  *
106  * The exact meaning of the USER signals is undocumented, but this 
107  * should cover the basic idea:
108  *
109  * USIG_DLL_UNLOAD_WIN16
110  *     This is sent when a 16-bit module is unloaded.
111  *
112  * USIG_DLL_UNLOAD_WIN32
113  *     This is sent when a 32-bit module is unloaded.
114  *
115  * USIG_DLL_UNLOAD_ORPHANS
116  *     This is sent after the last Win3.1 module is unloaded,
117  *     to allow removal of orphaned menus.
118  *
119  * USIG_FAULT_DIALOG_PUSH
120  * USIG_FAULT_DIALOG_POP
121  *     These are called to allow USER to prepare for displaying a
122  *     fault dialog, even though the fault might have happened while
123  *     inside a USER critical section.
124  *
125  * USIG_THREAD_INIT
126  *     This is called from the context of a new thread, as soon as it
127  *     has started to run.
128  *
129  * USIG_THREAD_EXIT
130  *     This is called, still in its context, just before a thread is
131  *     about to terminate.
132  *
133  * USIG_PROCESS_CREATE
134  *     This is called, in the parent process context, after a new process
135  *     has been created.
136  *
137  * USIG_PROCESS_INIT
138  *     This is called in the new process context, just after the main thread
139  *     has started execution (after the main thread's USIG_THREAD_INIT has
140  *     been sent).
141  *
142  * USIG_PROCESS_LOADED
143  *     This is called after the executable file has been loaded into the
144  *     new process context.
145  *
146  * USIG_PROCESS_RUNNING
147  *     This is called immediately before the main entry point is called.
148  *
149  * USIG_PROCESS_EXIT
150  *     This is called in the context of a process that is about to
151  *     terminate (but before the last thread's USIG_THREAD_EXIT has
152  *     been sent).
153  *
154  * USIG_PROCESS_DESTROY
155  *     This is called after a process has terminated.
156  *
157  *
158  * The meaning of the dwFlags bits is as follows:
159  *
160  * USIG_FLAGS_WIN32
161  *     Current process is 32-bit.
162  *
163  * USIG_FLAGS_GUI
164  *     Current process is a (Win32) GUI process.
165  *
166  * USIG_FLAGS_FEEDBACK 
167  *     Current process needs 'feedback' (determined from the STARTUPINFO
168  *     flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
169  *
170  * USIG_FLAGS_FAULT
171  *     The signal is being sent due to a fault.
172  */
173 void PROCESS_CallUserSignalProc( UINT uCode, DWORD dwThreadId, HMODULE hModule )
174 {
175     DWORD flags = PROCESS_Current()->flags;
176     DWORD startup_flags = PROCESS_Current()->env_db->startup_info->dwFlags;
177     DWORD dwFlags = 0;
178
179     /* Determine dwFlags */
180
181     if ( !(flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
182
183     if ( !(flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
184
185     if ( dwFlags & USIG_FLAGS_GUI )
186     {
187         /* Feedback defaults to ON */
188         if ( !(startup_flags & STARTF_FORCEOFFFEEDBACK) )
189             dwFlags |= USIG_FLAGS_FEEDBACK;
190     }
191     else
192     {
193         /* Feedback defaults to OFF */
194         if (startup_flags & STARTF_FORCEONFEEDBACK)
195             dwFlags |= USIG_FLAGS_FEEDBACK;
196     }
197
198     /* Convert module handle to 16-bit */
199
200     if ( HIWORD( hModule ) )
201         hModule = MapHModuleLS( hModule );
202
203     /* Call USER signal proc */
204
205     if ( Callout.UserSignalProc )
206     {
207         if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
208             Callout.UserSignalProc( uCode, dwThreadId, dwFlags, hModule );
209         else
210             Callout.UserSignalProc( uCode, GetCurrentProcessId(), dwFlags, hModule );
211     }
212 }
213
214 /***********************************************************************
215  *           PROCESS_CreateEnvDB
216  *
217  * Create the env DB for a newly started process.
218  */
219 static BOOL PROCESS_CreateEnvDB(void)
220 {
221     struct init_process_request *req = get_req_buffer();
222     STARTUPINFOA *startup;
223     ENVDB *env_db;
224     char cmd_line[4096];
225     PDB *pdb = PROCESS_Current();
226
227     /* Allocate the env DB */
228
229     if (!(env_db = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(ENVDB) )))
230         return FALSE;
231     pdb->env_db = env_db;
232     InitializeCriticalSection( &env_db->section );
233
234     /* Allocate and fill the startup info */
235     if (!(startup = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(STARTUPINFOA) )))
236         return FALSE;
237     env_db->startup_info = startup;
238
239     /* Retrieve startup info from the server */
240
241     req->ldt_copy  = ldt_copy;
242     req->ldt_flags = ldt_flags_copy;
243     if (server_call( REQ_INIT_PROCESS )) return FALSE;
244     pdb->exe_file        = req->exe_file;
245     startup->dwFlags     = req->start_flags;
246     startup->wShowWindow = req->cmd_show;
247     env_db->hStdin  = startup->hStdInput  = req->hstdin;
248     env_db->hStdout = startup->hStdOutput = req->hstdout;
249     env_db->hStderr = startup->hStdError  = req->hstderr;
250     lstrcpynA( cmd_line, req->cmdline, sizeof(cmd_line) );
251
252     /* Copy the parent environment */
253
254     if (!ENV_InheritEnvironment( req->env_ptr )) return FALSE;
255
256     /* Copy the command line */
257
258     if (!(pdb->env_db->cmd_line = HEAP_strdupA( GetProcessHeap(), 0, cmd_line )))
259         return FALSE;
260
261     return TRUE;
262 }
263
264
265 /***********************************************************************
266  *           PROCESS_FreePDB
267  *
268  * Free a PDB and all associated storage.
269  */
270 void PROCESS_FreePDB( PDB *pdb )
271 {
272     PDB **pptr = &PROCESS_First;
273
274     ENV_FreeEnvironment( pdb );
275     while (*pptr && (*pptr != pdb)) pptr = &(*pptr)->next;
276     if (*pptr) *pptr = pdb->next;
277     HeapFree( SystemHeap, 0, pdb );
278 }
279
280
281 /***********************************************************************
282  *           PROCESS_CreatePDB
283  *
284  * Allocate and fill a PDB structure.
285  * Runs in the context of the parent process.
286  */
287 static PDB *PROCESS_CreatePDB( PDB *parent, BOOL inherit )
288 {
289     PDB *pdb = HeapAlloc( SystemHeap, HEAP_ZERO_MEMORY, sizeof(PDB) );
290
291     if (!pdb) return NULL;
292     pdb->exit_code       = STILL_ACTIVE;
293     pdb->threads         = 1;
294     pdb->running_threads = 1;
295     pdb->ring0_threads   = 1;
296     pdb->parent          = parent;
297     pdb->group           = pdb;
298     pdb->priority        = 8;  /* Normal */
299     pdb->next            = PROCESS_First;
300     pdb->winver          = 0xffff; /* to be determined */
301     pdb->main_queue      = INVALID_HANDLE_VALUE16;
302     PROCESS_First = pdb;
303     return pdb;
304 }
305
306
307 /***********************************************************************
308  *           PROCESS_Init
309  */
310 BOOL PROCESS_Init( BOOL win32 )
311 {
312     TEB *teb;
313     int server_fd;
314
315     /* Start the server */
316     server_fd = CLIENT_InitServer();
317
318     /* Fill the initial process structure */
319     initial_pdb.exit_code       = STILL_ACTIVE;
320     initial_pdb.threads         = 1;
321     initial_pdb.running_threads = 1;
322     initial_pdb.ring0_threads   = 1;
323     initial_pdb.group           = &initial_pdb;
324     initial_pdb.priority        = 8;  /* Normal */
325     initial_pdb.flags           = win32? 0 : PDB32_WIN16_PROC;
326     initial_pdb.winver          = 0xffff; /* to be determined */
327     initial_pdb.main_queue      = INVALID_HANDLE_VALUE16;
328
329     /* Initialize virtual memory management */
330     if (!VIRTUAL_Init()) return FALSE;
331
332     /* Create the initial thread structure and socket pair */
333     if (!(teb = THREAD_CreateInitialThread( &initial_pdb, server_fd ))) return FALSE;
334
335     /* Remember TEB selector of initial process for emergency use */
336     SYSLEVEL_EmergencyTeb = teb->teb_sel;
337
338     /* Create the system and process heaps */
339     if (!HEAP_CreateSystemHeap()) return FALSE;
340     initial_pdb.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
341
342     /* Create the idle event for the initial process
343        FIXME 1: Shouldn't we call UserSignalProc for the initial process too?
344        FIXME 2: It seems to me that the initial pdb becomes never freed, so I don't now
345                 where to release the idle event for the initial process.
346     */
347     initial_pdb.idle_event = CreateEventA ( NULL, TRUE, FALSE, NULL );
348     initial_pdb.idle_event = ConvertToGlobalHandle ( initial_pdb.idle_event );
349
350     /* Initialize signal handling */
351     if (!SIGNAL_Init()) return FALSE;
352
353     /* Create the environment DB of the first process */
354     if (!PROCESS_CreateEnvDB()) return FALSE;
355
356     /* Create the SEGPTR heap */
357     if (!(SegptrHeap = HeapCreate( HEAP_WINE_SEGPTR, 0, 0 ))) return FALSE;
358
359     /* Initialize the first process critical section */
360     InitializeCriticalSection( &initial_pdb.crit_section );
361
362     return TRUE;
363 }
364
365
366 /***********************************************************************
367  *           PROCESS_Start
368  *
369  * Startup routine of a new process. Called in the context of the new process.
370  */
371 void PROCESS_Start(void)
372 {
373     struct init_process_done_request *req = get_req_buffer();
374     UINT cmdShow = SW_SHOWNORMAL;
375     LPTHREAD_START_ROUTINE entry = NULL;
376     PDB *pdb = PROCESS_Current();
377     NE_MODULE *pModule = NE_GetPtr( pdb->module );
378     LPCSTR filename = ((OFSTRUCT *)((char*)(pModule) + (pModule)->fileinfo))->szPathName;
379     IMAGE_OPTIONAL_HEADER *header = !pModule->module32? NULL :
380                                     &PE_HEADER(pModule->module32)->OptionalHeader;
381
382     /* Get process type */
383     enum { PROC_DOS, PROC_WIN16, PROC_WIN32 } type;
384     if ( pdb->flags & PDB32_DOS_PROC )
385         type = PROC_DOS;
386     else if ( pdb->flags & PDB32_WIN16_PROC )
387         type = PROC_WIN16;
388     else
389         type = PROC_WIN32;
390
391     /* Initialize the critical section */
392     InitializeCriticalSection( &pdb->crit_section );
393
394     /* Create the heap */
395     if (!(pdb->heap = GetProcessHeap()))
396     {
397         if (!(pdb->heap = HeapCreate( HEAP_GROWABLE, 
398                                       header? header->SizeOfHeapReserve : 0x10000,
399                                       header? header->SizeOfHeapCommit  : 0 ))) 
400             goto error;
401     }
402
403     /* Create the environment db */
404     if (!PROCESS_CreateEnvDB()) goto error;
405
406     /* Create a task for this process */
407     if (pdb->env_db->startup_info->dwFlags & STARTF_USESHOWWINDOW)
408         cmdShow = pdb->env_db->startup_info->wShowWindow;
409     if (!TASK_Create( pModule, cmdShow ))
410         goto error;
411
412     /* Load all process modules */
413     switch ( type )
414     {
415     case PROC_WIN16:
416         if ( !NE_InitProcess( pModule ) )
417             goto error;
418         break;
419
420     case PROC_WIN32:
421         /* Create 32-bit MODREF */
422         if ( !PE_CreateModule( pModule->module32, filename, 0, FALSE ) ) 
423             goto error;
424
425         /* Increment EXE refcount */
426         assert( pdb->exe_modref );
427         pdb->exe_modref->refCount++;
428
429         /* Retrieve entry point address */
430         entry = (LPTHREAD_START_ROUTINE)RVA_PTR(pModule->module32,
431                                                 OptionalHeader.AddressOfEntryPoint);
432         break;
433
434     case PROC_DOS:
435         /* FIXME: move DOS startup code here */
436         break;
437     }
438
439
440     /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
441      *       context of the parent process.  Actually, the USER signal proc
442      *       doesn't really care about that, but it *does* require that the
443      *       startup parameters are correctly set up, so that GetProcessDword
444      *       works.  Furthermore, before calling the USER signal proc the 
445      *       16-bit stack must be set up, which it is only after TASK_Create
446      *       in the case of a 16-bit process. Thus, we send the signal here.
447      */
448
449     PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0, 0 );
450     PROCESS_CallUserSignalProc( USIG_THREAD_INIT, GetCurrentThreadId(), 0 );
451     PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0, 0 );
452     PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0, 0 );
453
454     /* Signal the parent process to continue */
455     req->module = (void *)pModule->module32;
456     req->entry  = entry;
457     server_call( REQ_INIT_PROCESS_DONE );
458
459     /* Send all required start-up debugger events */
460     if ( type == PROC_WIN32 && (pdb->flags & PDB32_DEBUGGED) )
461     {
462         EnterCriticalSection( &pdb->crit_section );
463         MODULE_SendLoadDLLEvents();
464         LeaveCriticalSection( &pdb->crit_section );
465     }
466
467     if ( (pdb->flags & PDB32_CONSOLE_PROC) || (pdb->flags & PDB32_DOS_PROC) )
468         AllocConsole();
469
470     /* Perform Win32 specific process initialization */
471     if ( type == PROC_WIN32 )
472     {
473         EnterCriticalSection( &pdb->crit_section );
474
475         PE_InitTls();
476         MODULE_DllProcessAttach( pdb->exe_modref, (LPVOID)1 );
477
478         LeaveCriticalSection( &pdb->crit_section );
479     }
480
481     /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
482     if ( type != PROC_WIN16 && (pdb->flags & PDB32_CONSOLE_PROC))
483         PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0, 0 );
484
485     switch ( type )
486     {
487     case PROC_DOS:
488         TRACE_(relay)( "Starting DOS process\n" );
489         DOSVM_Enter( NULL );
490         ERR_(relay)( "DOSVM_Enter returned; should not happen!\n" );
491         ExitProcess( 0 );
492
493     case PROC_WIN16:
494         TRACE_(relay)( "Starting Win16 process\n" );
495         TASK_CallToStart();
496         ERR_(relay)( "TASK_CallToStart returned; should not happen!\n" );
497         ExitProcess( 0 );
498
499     case PROC_WIN32:
500         TRACE_(relay)( "Starting Win32 process (entryproc=%p)\n", entry );
501         if (pdb->flags & PDB32_DEBUGGED) DebugBreak();
502         /* FIXME: should use _PEB as parameter for NT 3.5 programs !
503          * Dunno about other OSs */
504         ExitProcess( entry(NULL) );
505     }
506
507  error:
508     ExitProcess( GetLastError() );
509 }
510
511
512 /***********************************************************************
513  *           PROCESS_Create
514  *
515  * Create a new process database and associated info.
516  */
517 PDB *PROCESS_Create( NE_MODULE *pModule, HFILE hFile, LPCSTR cmd_line, LPCSTR env,
518                      LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
519                      BOOL inherit, DWORD flags, STARTUPINFOA *startup,
520                      PROCESS_INFORMATION *info )
521 {
522     HANDLE handles[2], load_done_evt = 0;
523     DWORD exitcode, size;
524     BOOL alloc_stack16;
525     int server_thandle, fd = -1;
526     struct new_process_request *req = get_req_buffer();
527     TEB *teb = NULL;
528     PDB *parent = PROCESS_Current();
529     PDB *pdb = PROCESS_CreatePDB( parent, inherit );
530
531     if (!pdb) return NULL;
532     info->hThread = info->hProcess = INVALID_HANDLE_VALUE;
533     if (!(load_done_evt = CreateEventA( NULL, TRUE, FALSE, NULL ))) goto error;
534     
535     /* Create the process on the server side */
536
537     req->inherit      = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
538     req->inherit_all  = inherit;
539     req->create_flags = flags;
540     req->start_flags  = startup->dwFlags;
541     req->exe_file     = hFile;
542     req->event        = load_done_evt;
543     if (startup->dwFlags & STARTF_USESTDHANDLES)
544     {
545         req->hstdin  = startup->hStdInput;
546         req->hstdout = startup->hStdOutput;
547         req->hstderr = startup->hStdError;
548     }
549     else
550     {
551         req->hstdin  = GetStdHandle( STD_INPUT_HANDLE );
552         req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
553         req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
554     }
555     req->cmd_show = startup->wShowWindow;
556     req->env_ptr = (void*)env;  /* FIXME: hack */
557     lstrcpynA( req->cmdline, cmd_line, server_remaining(req->cmdline) );
558     if (server_call_fd( REQ_NEW_PROCESS, -1, &fd )) goto error;
559     fcntl( fd, F_SETFD, 1 ); /* set close on exec flag */
560     pdb->server_pid   = req->pid;
561     info->hProcess    = req->phandle;
562     info->dwProcessId = (DWORD)req->pid;
563     info->hThread     = req->thandle;
564     info->dwThreadId  = (DWORD)req->tid;
565
566     if ((flags & (DEBUG_PROCESS|DEBUG_ONLY_THIS_PROCESS)) ||
567         ((parent->flags & PDB32_DEBUGGED) && !(flags & DEBUG_ONLY_THIS_PROCESS)))
568         pdb->flags |= PDB32_DEBUGGED;
569
570     if (pModule->module32)   /* Win32 process */
571     {
572         IMAGE_OPTIONAL_HEADER *header = &PE_HEADER(pModule->module32)->OptionalHeader;
573         size = header->SizeOfStackReserve;
574         if (header->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI) 
575             pdb->flags |= PDB32_CONSOLE_PROC;
576         alloc_stack16 = TRUE;
577     }
578     else if (!pModule->dos_image) /* Win16 process */
579     {
580         alloc_stack16 = FALSE;
581         size = 0;
582         pdb->flags |= PDB32_WIN16_PROC;
583     }
584     else  /* DOS process */
585     {
586         alloc_stack16 = FALSE;
587         size = 0;
588         pdb->flags |= PDB32_DOS_PROC;
589     }
590
591     /* Create the main thread */
592
593     if (!(teb = THREAD_Create( pdb, fd, flags & CREATE_SUSPENDED, size,
594                                alloc_stack16, tsa, &server_thandle ))) goto error;
595     teb->tid = (void *)info->dwThreadId;
596     teb->startup = PROCESS_Start;
597     fd = -1;  /* don't close it */
598
599     /* Pass module to new process (FIXME: hack) */
600     pdb->module = pModule->self;
601     SYSDEPS_SpawnThread( teb );
602
603     /* Wait until process is initialized (or initialization failed) */
604     handles[0] = info->hProcess;
605     handles[1] = load_done_evt;
606
607     switch ( WaitForMultipleObjects( 2, handles, FALSE, INFINITE ) )
608     {
609     default: 
610         ERR( "WaitForMultipleObjects failed\n" );
611         break;
612
613     case 0:
614         /* Child initialization code returns error condition as exitcode */
615         if ( GetExitCodeProcess( info->hProcess, &exitcode ) )
616             SetLastError( exitcode );
617         goto error;
618
619     case 1:
620         /* Get 16-bit task up and running */
621         if ( pdb->flags & PDB32_WIN16_PROC )
622         {
623             /* Post event to start the task */
624             PostEvent16( pdb->task );
625
626             /* If we ourselves are a 16-bit task, we Yield() directly. */
627             if ( parent->flags & PDB32_WIN16_PROC )
628                 OldYield16();
629         }
630         break;
631     } 
632
633     CloseHandle( load_done_evt );
634     load_done_evt = 0;
635
636     return pdb;
637
638 error:
639     if (load_done_evt) CloseHandle( load_done_evt );
640     if (info->hThread != INVALID_HANDLE_VALUE) CloseHandle( info->hThread );
641     if (info->hProcess != INVALID_HANDLE_VALUE) CloseHandle( info->hProcess );
642     PROCESS_FreePDB( pdb );
643     if (fd != -1) close( fd );
644     return NULL;
645 }
646
647
648 /***********************************************************************
649  *           ExitProcess   (KERNEL32.100)
650  */
651 void WINAPI ExitProcess( DWORD status )
652 {
653     EnterCriticalSection( &PROCESS_Current()->crit_section );
654     MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
655     LeaveCriticalSection( &PROCESS_Current()->crit_section );
656
657     TASK_KillTask( 0 );
658     TerminateProcess( GetCurrentProcess(), status );
659 }
660
661 /***********************************************************************
662  *           ExitProcess16   (KERNEL.466)
663  */
664 void WINAPI ExitProcess16( WORD status )
665 {
666     SYSLEVEL_ReleaseWin16Lock();
667     ExitProcess( status );
668 }
669
670 /******************************************************************************
671  *           TerminateProcess   (KERNEL32.684)
672  */
673 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
674 {
675     struct terminate_process_request *req = get_req_buffer();
676     req->handle    = handle;
677     req->exit_code = exit_code;
678     return !server_call( REQ_TERMINATE_PROCESS );
679 }
680
681
682 /***********************************************************************
683  *           GetProcessDword    (KERNEL32.18) (KERNEL.485)
684  * 'Of course you cannot directly access Windows internal structures'
685  */
686 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
687 {
688     PDB *process = PROCESS_IdToPDB( dwProcessID );
689     TDB *pTask;
690     DWORD x, y;
691
692     TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
693     if ( !process ) return 0;
694
695     switch ( offset ) 
696     {
697     case GPD_APP_COMPAT_FLAGS:
698         pTask = (TDB *)GlobalLock16( process->task );
699         return pTask? pTask->compat_flags : 0;
700
701     case GPD_LOAD_DONE_EVENT:
702         return process->load_done_evt;
703
704     case GPD_HINSTANCE16:
705         pTask = (TDB *)GlobalLock16( process->task );
706         return pTask? pTask->hInstance : 0;
707
708     case GPD_WINDOWS_VERSION:
709         pTask = (TDB *)GlobalLock16( process->task );
710         return pTask? pTask->version : 0;
711
712     case GPD_THDB:
713         if ( process != PROCESS_Current() ) return 0;
714         return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
715
716     case GPD_PDB:
717         return (DWORD)process;
718
719     case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
720         return process->env_db->startup_info->hStdOutput;
721
722     case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
723         return process->env_db->startup_info->hStdInput;
724
725     case GPD_STARTF_SHOWWINDOW:
726         return process->env_db->startup_info->wShowWindow;
727
728     case GPD_STARTF_SIZE:
729         x = process->env_db->startup_info->dwXSize;
730         if ( x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
731         y = process->env_db->startup_info->dwYSize;
732         if ( y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
733         return MAKELONG( x, y );
734
735     case GPD_STARTF_POSITION:
736         x = process->env_db->startup_info->dwX;
737         if ( x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
738         y = process->env_db->startup_info->dwY;
739         if ( y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
740         return MAKELONG( x, y );
741
742     case GPD_STARTF_FLAGS:
743         return process->env_db->startup_info->dwFlags;
744
745     case GPD_PARENT:
746         return process->parent? (DWORD)process->parent->server_pid : 0;
747
748     case GPD_FLAGS:
749         return process->flags;
750
751     case GPD_USERDATA:
752         return process->process_dword;
753
754     default:
755         ERR_(win32)("Unknown offset %d\n", offset );
756         return 0;
757     }
758 }
759
760 /***********************************************************************
761  *           SetProcessDword    (KERNEL.484)
762  * 'Of course you cannot directly access Windows internal structures'
763  */
764 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
765 {
766     PDB *process = PROCESS_IdToPDB( dwProcessID );
767
768     TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
769     if ( !process ) return;
770
771     switch ( offset ) 
772     {
773     case GPD_APP_COMPAT_FLAGS:
774     case GPD_LOAD_DONE_EVENT:
775     case GPD_HINSTANCE16:
776     case GPD_WINDOWS_VERSION:
777     case GPD_THDB:
778     case GPD_PDB:
779     case GPD_STARTF_SHELLDATA:
780     case GPD_STARTF_HOTKEY:
781     case GPD_STARTF_SHOWWINDOW:
782     case GPD_STARTF_SIZE:
783     case GPD_STARTF_POSITION:
784     case GPD_STARTF_FLAGS:
785     case GPD_PARENT:
786     case GPD_FLAGS:
787         ERR_(win32)("Not allowed to modify offset %d\n", offset );
788         break;
789
790     case GPD_USERDATA:
791         process->process_dword = value; 
792         break;
793
794     default:
795         ERR_(win32)("Unknown offset %d\n", offset );
796         break;
797     }
798 }
799
800
801 /***********************************************************************
802  *           GetCurrentProcess   (KERNEL32.198)
803  */
804 HANDLE WINAPI GetCurrentProcess(void)
805 {
806     return CURRENT_PROCESS_PSEUDOHANDLE;
807 }
808
809
810 /*********************************************************************
811  *           OpenProcess   (KERNEL32.543)
812  */
813 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
814 {
815     HANDLE ret = 0;
816     struct open_process_request *req = get_req_buffer();
817
818     req->pid     = (void *)id;
819     req->access  = access;
820     req->inherit = inherit;
821     if (!server_call( REQ_OPEN_PROCESS )) ret = req->handle;
822     return ret;
823 }                             
824
825 /*********************************************************************
826  *           MapProcessHandle   (KERNEL.483)
827  */
828 DWORD WINAPI MapProcessHandle( HANDLE handle )
829 {
830     DWORD ret = 0;
831     struct get_process_info_request *req = get_req_buffer();
832     req->handle = handle;
833     if (!server_call( REQ_GET_PROCESS_INFO )) ret = (DWORD)req->pid;
834     return ret;
835 }
836
837 /***********************************************************************
838  *           GetCurrentProcessId   (KERNEL32.199)
839  */
840 DWORD WINAPI GetCurrentProcessId(void)
841 {
842     return (DWORD)PROCESS_Current()->server_pid;
843 }
844
845
846 /***********************************************************************
847  *           GetThreadLocale    (KERNEL32.295)
848  */
849 LCID WINAPI GetThreadLocale(void)
850 {
851     return PROCESS_Current()->locale;
852 }
853
854
855 /***********************************************************************
856  *           SetPriorityClass   (KERNEL32.503)
857  */
858 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
859 {
860     struct set_process_info_request *req = get_req_buffer();
861     req->handle   = hprocess;
862     req->priority = priorityclass;
863     req->mask     = SET_PROCESS_INFO_PRIORITY;
864     return !server_call( REQ_SET_PROCESS_INFO );
865 }
866
867
868 /***********************************************************************
869  *           GetPriorityClass   (KERNEL32.250)
870  */
871 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
872 {
873     DWORD ret = 0;
874     struct get_process_info_request *req = get_req_buffer();
875     req->handle = hprocess;
876     if (!server_call( REQ_GET_PROCESS_INFO )) ret = req->priority;
877     return ret;
878 }
879
880
881 /***********************************************************************
882  *          SetProcessAffinityMask   (KERNEL32.662)
883  */
884 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
885 {
886     struct set_process_info_request *req = get_req_buffer();
887     req->handle   = hProcess;
888     req->affinity = affmask;
889     req->mask     = SET_PROCESS_INFO_AFFINITY;
890     return !server_call( REQ_SET_PROCESS_INFO );
891 }
892
893 /**********************************************************************
894  *          GetProcessAffinityMask    (KERNEL32.373)
895  */
896 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
897                                       LPDWORD lpProcessAffinityMask,
898                                       LPDWORD lpSystemAffinityMask )
899 {
900     BOOL ret = FALSE;
901     struct get_process_info_request *req = get_req_buffer();
902     req->handle = hProcess;
903     if (!server_call( REQ_GET_PROCESS_INFO ))
904     {
905         if (lpProcessAffinityMask) *lpProcessAffinityMask = req->process_affinity;
906         if (lpSystemAffinityMask) *lpSystemAffinityMask = req->system_affinity;
907         ret = TRUE;
908     }
909     return ret;
910 }
911
912
913 /***********************************************************************
914  *           GetStdHandle    (KERNEL32.276)
915  */
916 HANDLE WINAPI GetStdHandle( DWORD std_handle )
917 {
918     PDB *pdb = PROCESS_Current();
919
920     switch(std_handle)
921     {
922     case STD_INPUT_HANDLE:  return pdb->env_db->hStdin;
923     case STD_OUTPUT_HANDLE: return pdb->env_db->hStdout;
924     case STD_ERROR_HANDLE:  return pdb->env_db->hStderr;
925     }
926     SetLastError( ERROR_INVALID_PARAMETER );
927     return INVALID_HANDLE_VALUE;
928 }
929
930
931 /***********************************************************************
932  *           SetStdHandle    (KERNEL32.506)
933  */
934 BOOL WINAPI SetStdHandle( DWORD std_handle, HANDLE handle )
935 {
936     PDB *pdb = PROCESS_Current();
937     /* FIXME: should we close the previous handle? */
938     switch(std_handle)
939     {
940     case STD_INPUT_HANDLE:
941         pdb->env_db->hStdin = handle;
942         return TRUE;
943     case STD_OUTPUT_HANDLE:
944         pdb->env_db->hStdout = handle;
945         return TRUE;
946     case STD_ERROR_HANDLE:
947         pdb->env_db->hStderr = handle;
948         return TRUE;
949     }
950     SetLastError( ERROR_INVALID_PARAMETER );
951     return FALSE;
952 }
953
954 /***********************************************************************
955  *           GetProcessVersion    (KERNEL32)
956  */
957 DWORD WINAPI GetProcessVersion( DWORD processid )
958 {
959     TDB *pTask;
960     PDB *pdb = PROCESS_IdToPDB( processid );
961
962     if (!pdb) return 0;
963     if (!(pTask = (TDB *)GlobalLock16( pdb->task ))) return 0;
964     return (pTask->version&0xff) | (((pTask->version >>8) & 0xff)<<16);
965 }
966
967 /***********************************************************************
968  *           GetProcessFlags    (KERNEL32)
969  */
970 DWORD WINAPI GetProcessFlags( DWORD processid )
971 {
972     PDB *pdb = PROCESS_IdToPDB( processid );
973     if (!pdb) return 0;
974     return pdb->flags;
975 }
976
977 /***********************************************************************
978  *              SetProcessWorkingSetSize        [KERNEL32.662]
979  * Sets the min/max working set sizes for a specified process.
980  *
981  * PARAMS
982  *    hProcess [I] Handle to the process of interest
983  *    minset   [I] Specifies minimum working set size
984  *    maxset   [I] Specifies maximum working set size
985  *
986  * RETURNS  STD
987  */
988 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
989                                        DWORD maxset)
990 {
991     FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
992     if(( minset == -1) && (maxset == -1)) {
993         /* Trim the working set to zero */
994         /* Swap the process out of physical RAM */
995     }
996     return TRUE;
997 }
998
999 /***********************************************************************
1000  *           GetProcessWorkingSetSize    (KERNEL32)
1001  */
1002 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1003                                        LPDWORD maxset)
1004 {
1005         FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1006         /* 32 MB working set size */
1007         if (minset) *minset = 32*1024*1024;
1008         if (maxset) *maxset = 32*1024*1024;
1009         return TRUE;
1010 }
1011
1012 /***********************************************************************
1013  *           SetProcessShutdownParameters    (KERNEL32)
1014  *
1015  * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1016  * Now tracks changes made (but does not act on these changes)
1017  * NOTE: the definition for SHUTDOWN_NORETRY was done on guesswork.
1018  * It really shouldn't be here, but I'll move it when it's been checked!
1019  */
1020 #define SHUTDOWN_NORETRY 1
1021 static unsigned int shutdown_noretry = 0;
1022 static unsigned int shutdown_priority = 0x280L;
1023 BOOL WINAPI SetProcessShutdownParameters(DWORD level,DWORD flags)
1024 {
1025     if (flags & SHUTDOWN_NORETRY)
1026       shutdown_noretry = 1;
1027     else
1028       shutdown_noretry = 0;
1029     if (level > 0x100L && level < 0x3FFL)
1030       shutdown_priority = level;
1031     else
1032       {
1033         ERR("invalid priority level 0x%08lx\n", level);
1034         return FALSE;
1035       }
1036     return TRUE;
1037 }
1038
1039
1040 /***********************************************************************
1041  * GetProcessShutdownParameters                 (KERNEL32)
1042  *
1043  */
1044 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel,
1045                                             LPDWORD lpdwFlags )
1046 {
1047   (*lpdwLevel) = shutdown_priority;
1048   (*lpdwFlags) = (shutdown_noretry * SHUTDOWN_NORETRY);
1049   return TRUE;
1050 }
1051 /***********************************************************************
1052  *           SetProcessPriorityBoost    (KERNEL32)
1053  */
1054 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1055 {
1056     FIXME("(%d,%d): stub\n",hprocess,disableboost);
1057     /* Say we can do it. I doubt the program will notice that we don't. */
1058     return TRUE;
1059 }
1060
1061
1062 /***********************************************************************
1063  *           ReadProcessMemory                  (KERNEL32)
1064  */
1065 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1066                                LPDWORD bytes_read )
1067 {
1068     struct read_process_memory_request *req = get_req_buffer();
1069     unsigned int offset = (unsigned int)addr % sizeof(int);
1070     unsigned int max = server_remaining( req->data );  /* max length in one request */
1071     unsigned int pos;
1072
1073     if (bytes_read) *bytes_read = size;
1074
1075     /* first time, read total length to check for permissions */
1076     req->handle = process;
1077     req->addr   = (char *)addr - offset;
1078     req->len    = (size + offset + sizeof(int) - 1) / sizeof(int);
1079     if (server_call( REQ_READ_PROCESS_MEMORY )) goto error;
1080
1081     if (size <= max - offset)
1082     {
1083         memcpy( buffer, (char *)req->data + offset, size );
1084         return TRUE;
1085     }
1086
1087     /* now take care of the remaining data */
1088     memcpy( buffer, (char *)req->data + offset, max - offset );
1089     pos = max - offset;
1090     size -= pos;
1091     while (size)
1092     {
1093         if (max > size) max = size;
1094         req->handle = process;
1095         req->addr   = (char *)addr + pos;
1096         req->len    = (max + sizeof(int) - 1) / sizeof(int);
1097         if (server_call( REQ_READ_PROCESS_MEMORY )) goto error;
1098         memcpy( (char *)buffer + pos, (char *)req->data, max );
1099         size -= max;
1100         pos += max;
1101     }
1102     return TRUE;
1103
1104  error:
1105     if (bytes_read) *bytes_read = 0;
1106     return FALSE;
1107 }
1108
1109
1110 /***********************************************************************
1111  *           WriteProcessMemory                 (KERNEL32)
1112  */
1113 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPVOID buffer, DWORD size,
1114                                 LPDWORD bytes_written )
1115 {
1116     unsigned int first_offset, last_offset;
1117     struct write_process_memory_request *req = get_req_buffer();
1118     unsigned int max = server_remaining( req->data );  /* max length in one request */
1119     unsigned int pos, last_mask;
1120
1121     if (!size)
1122     {
1123         SetLastError( ERROR_INVALID_PARAMETER );
1124         return FALSE;
1125     }
1126     if (bytes_written) *bytes_written = size;
1127
1128     /* compute the mask for the first int */
1129     req->first_mask = ~0;
1130     first_offset = (unsigned int)addr % sizeof(int);
1131     memset( &req->first_mask, 0, first_offset );
1132
1133     /* compute the mask for the last int */
1134     last_offset = (size + first_offset) % sizeof(int);
1135     last_mask = 0;
1136     memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1137
1138     req->handle = process;
1139     req->addr = (char *)addr - first_offset;
1140     /* for the first request, use the total length */
1141     req->len = (size + first_offset + sizeof(int) - 1) / sizeof(int);
1142
1143     if (size + first_offset < max)  /* we can do it in one round */
1144     {
1145         memcpy( (char *)req->data + first_offset, buffer, size );
1146         req->last_mask = last_mask;
1147         if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1148         return TRUE;
1149     }
1150
1151     /* needs multiple server calls */
1152
1153     memcpy( (char *)req->data + first_offset, buffer, max - first_offset );
1154     req->last_mask = ~0;
1155     if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1156     pos = max - first_offset;
1157     size -= pos;
1158     while (size)
1159     {
1160         if (size <= max)  /* last one */
1161         {
1162             req->last_mask = last_mask;
1163             max = size;
1164         }
1165         req->handle = process;
1166         req->addr = (char *)addr + pos;
1167         req->len = (max + sizeof(int) - 1) / sizeof(int);
1168         req->first_mask = ~0;
1169         memcpy( req->data, (char *) buffer + pos, max );
1170         if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1171         pos += max;
1172         size -= max;
1173     }
1174     return TRUE;
1175
1176  error:
1177     if (bytes_written) *bytes_written = 0;
1178     return FALSE;
1179
1180 }
1181
1182
1183 /***********************************************************************
1184  *           RegisterServiceProcess             (KERNEL, KERNEL32)
1185  *
1186  * A service process calls this function to ensure that it continues to run
1187  * even after a user logged off.
1188  */
1189 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1190 {
1191         /* I don't think that Wine needs to do anything in that function */
1192         return 1; /* success */
1193 }
1194
1195 /***********************************************************************
1196  * GetExitCodeProcess [KERNEL32.325]
1197  *
1198  * Gets termination status of specified process
1199  * 
1200  * RETURNS
1201  *   Success: TRUE
1202  *   Failure: FALSE
1203  */
1204 BOOL WINAPI GetExitCodeProcess(
1205     HANDLE hProcess,  /* [I] handle to the process */
1206     LPDWORD lpExitCode) /* [O] address to receive termination status */
1207 {
1208     BOOL ret = FALSE;
1209     struct get_process_info_request *req = get_req_buffer();
1210     req->handle = hProcess;
1211     if (!server_call( REQ_GET_PROCESS_INFO ))
1212     {
1213         if (lpExitCode) *lpExitCode = req->exit_code;
1214         ret = TRUE;
1215     }
1216     return ret;
1217 }
1218
1219
1220 /***********************************************************************
1221  *           SetErrorMode   (KERNEL32.486)
1222  */
1223 UINT WINAPI SetErrorMode( UINT mode )
1224 {
1225     UINT old = PROCESS_Current()->error_mode;
1226     PROCESS_Current()->error_mode = mode;
1227     return old;
1228 }