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