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