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