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