Stubs for IQueryAssociations.
[wine.git] / scheduler / process.c
blobb7cd744828cc1a37c394c5285b7b547b7aa57d3b
1 /*
2 * Win32 processes
4 * Copyright 1996, 1998 Alexandre Julliard
5 */
7 #include <assert.h>
8 #include <fcntl.h>
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <unistd.h>
13 #include "wine/winbase16.h"
14 #include "wine/exception.h"
15 #include "process.h"
16 #include "main.h"
17 #include "module.h"
18 #include "neexe.h"
19 #include "file.h"
20 #include "global.h"
21 #include "heap.h"
22 #include "task.h"
23 #include "ldt.h"
24 #include "syslevel.h"
25 #include "thread.h"
26 #include "winerror.h"
27 #include "pe_image.h"
28 #include "server.h"
29 #include "options.h"
30 #include "callback.h"
31 #include "debugtools.h"
33 DEFAULT_DEBUG_CHANNEL(process);
34 DECLARE_DEBUG_CHANNEL(relay);
35 DECLARE_DEBUG_CHANNEL(win32);
38 /* The initial process PDB */
39 static PDB initial_pdb;
40 static ENVDB initial_envdb;
41 static STARTUPINFOA initial_startup;
43 static PDB *PROCESS_First = &initial_pdb;
46 /***********************************************************************
47 * PROCESS_WalkProcess
49 void PROCESS_WalkProcess(void)
51 PDB *pdb;
52 char *name;
54 pdb = PROCESS_First;
55 MESSAGE( " pid PDB #th modref module \n" );
56 while(pdb)
58 if (pdb == &initial_pdb)
59 name = "initial PDB";
60 else
61 name = (pdb->exe_modref) ? pdb->exe_modref->filename : "";
63 MESSAGE( " %8p %8p %5d %8p %s\n", pdb->server_pid, pdb,
64 pdb->threads, pdb->exe_modref, name);
65 pdb = pdb->next;
67 return;
71 /***********************************************************************
72 * PROCESS_IdToPDB
74 * Convert a process id to a PDB, making sure it is valid.
76 PDB *PROCESS_IdToPDB( DWORD pid )
78 PDB *pdb;
80 if (!pid) return PROCESS_Current();
81 pdb = PROCESS_First;
82 while (pdb)
84 if ((DWORD)pdb->server_pid == pid) return pdb;
85 pdb = pdb->next;
87 SetLastError( ERROR_INVALID_PARAMETER );
88 return NULL;
92 /***********************************************************************
93 * PROCESS_CallUserSignalProc
95 * FIXME: Some of the signals aren't sent correctly!
97 * The exact meaning of the USER signals is undocumented, but this
98 * should cover the basic idea:
100 * USIG_DLL_UNLOAD_WIN16
101 * This is sent when a 16-bit module is unloaded.
103 * USIG_DLL_UNLOAD_WIN32
104 * This is sent when a 32-bit module is unloaded.
106 * USIG_DLL_UNLOAD_ORPHANS
107 * This is sent after the last Win3.1 module is unloaded,
108 * to allow removal of orphaned menus.
110 * USIG_FAULT_DIALOG_PUSH
111 * USIG_FAULT_DIALOG_POP
112 * These are called to allow USER to prepare for displaying a
113 * fault dialog, even though the fault might have happened while
114 * inside a USER critical section.
116 * USIG_THREAD_INIT
117 * This is called from the context of a new thread, as soon as it
118 * has started to run.
120 * USIG_THREAD_EXIT
121 * This is called, still in its context, just before a thread is
122 * about to terminate.
124 * USIG_PROCESS_CREATE
125 * This is called, in the parent process context, after a new process
126 * has been created.
128 * USIG_PROCESS_INIT
129 * This is called in the new process context, just after the main thread
130 * has started execution (after the main thread's USIG_THREAD_INIT has
131 * been sent).
133 * USIG_PROCESS_LOADED
134 * This is called after the executable file has been loaded into the
135 * new process context.
137 * USIG_PROCESS_RUNNING
138 * This is called immediately before the main entry point is called.
140 * USIG_PROCESS_EXIT
141 * This is called in the context of a process that is about to
142 * terminate (but before the last thread's USIG_THREAD_EXIT has
143 * been sent).
145 * USIG_PROCESS_DESTROY
146 * This is called after a process has terminated.
149 * The meaning of the dwFlags bits is as follows:
151 * USIG_FLAGS_WIN32
152 * Current process is 32-bit.
154 * USIG_FLAGS_GUI
155 * Current process is a (Win32) GUI process.
157 * USIG_FLAGS_FEEDBACK
158 * Current process needs 'feedback' (determined from the STARTUPINFO
159 * flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
161 * USIG_FLAGS_FAULT
162 * The signal is being sent due to a fault.
164 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE hModule )
166 DWORD flags = PROCESS_Current()->flags;
167 DWORD startup_flags = PROCESS_Current()->env_db->startup_info->dwFlags;
168 DWORD dwFlags = 0;
170 /* Determine dwFlags */
172 if ( !(flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
174 if ( !(flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
176 if ( dwFlags & USIG_FLAGS_GUI )
178 /* Feedback defaults to ON */
179 if ( !(startup_flags & STARTF_FORCEOFFFEEDBACK) )
180 dwFlags |= USIG_FLAGS_FEEDBACK;
182 else
184 /* Feedback defaults to OFF */
185 if (startup_flags & STARTF_FORCEONFEEDBACK)
186 dwFlags |= USIG_FLAGS_FEEDBACK;
189 /* Convert module handle to 16-bit */
191 if ( HIWORD( hModule ) )
192 hModule = MapHModuleLS( hModule );
194 /* Call USER signal proc */
196 if ( Callout.UserSignalProc )
198 if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
199 Callout.UserSignalProc( uCode, GetCurrentThreadId(), dwFlags, hModule );
200 else
201 Callout.UserSignalProc( uCode, GetCurrentProcessId(), dwFlags, hModule );
205 /***********************************************************************
206 * PROCESS_CreateEnvDB
208 * Create the env DB for a newly started process.
210 static BOOL PROCESS_CreateEnvDB(void)
212 struct init_process_request *req = get_req_buffer();
213 STARTUPINFOA *startup;
214 ENVDB *env_db;
215 char cmd_line[4096];
216 PDB *pdb = PROCESS_Current();
218 /* Allocate the env DB */
220 if (!(env_db = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(ENVDB) )))
221 return FALSE;
222 pdb->env_db = env_db;
223 InitializeCriticalSection( &env_db->section );
225 /* Allocate and fill the startup info */
226 if (!(startup = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(STARTUPINFOA) )))
227 return FALSE;
228 env_db->startup_info = startup;
230 /* Retrieve startup info from the server */
232 req->ldt_copy = ldt_copy;
233 req->ldt_flags = ldt_flags_copy;
234 if (server_call( REQ_INIT_PROCESS )) return FALSE;
235 pdb->exe_file = req->exe_file;
236 startup->dwFlags = req->start_flags;
237 startup->wShowWindow = req->cmd_show;
238 env_db->hStdin = startup->hStdInput = req->hstdin;
239 env_db->hStdout = startup->hStdOutput = req->hstdout;
240 env_db->hStderr = startup->hStdError = req->hstderr;
241 lstrcpynA( cmd_line, req->cmdline, sizeof(cmd_line) );
243 /* Copy the parent environment */
245 if (!ENV_InheritEnvironment( req->env_ptr )) return FALSE;
247 /* Copy the command line */
249 if (!(pdb->env_db->cmd_line = HEAP_strdupA( GetProcessHeap(), 0, cmd_line )))
250 return FALSE;
252 return TRUE;
256 /***********************************************************************
257 * PROCESS_FreePDB
259 * Free a PDB and all associated storage.
261 void PROCESS_FreePDB( PDB *pdb )
263 PDB **pptr = &PROCESS_First;
265 ENV_FreeEnvironment( pdb );
266 while (*pptr && (*pptr != pdb)) pptr = &(*pptr)->next;
267 if (*pptr) *pptr = pdb->next;
268 HeapFree( GetProcessHeap(), 0, pdb );
272 /***********************************************************************
273 * PROCESS_CreatePDB
275 * Allocate and fill a PDB structure.
276 * Runs in the context of the parent process.
278 static PDB *PROCESS_CreatePDB( PDB *parent, BOOL inherit )
280 PDB *pdb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(PDB) );
282 if (!pdb) return NULL;
283 pdb->exit_code = STILL_ACTIVE;
284 pdb->heap = GetProcessHeap();
285 pdb->threads = 1;
286 pdb->running_threads = 1;
287 pdb->ring0_threads = 1;
288 pdb->parent = parent;
289 pdb->group = pdb;
290 pdb->priority = 8; /* Normal */
291 pdb->next = PROCESS_First;
292 pdb->winver = 0xffff; /* to be determined */
293 pdb->main_queue = INVALID_HANDLE_VALUE16;
294 PROCESS_First = pdb;
295 return pdb;
299 /***********************************************************************
300 * PROCESS_Init
302 BOOL PROCESS_Init( BOOL win32 )
304 struct init_process_request *req;
305 TEB *teb;
306 int server_fd;
308 /* Start the server */
309 server_fd = CLIENT_InitServer();
311 /* Fill the initial process structure */
312 initial_pdb.exit_code = STILL_ACTIVE;
313 initial_pdb.threads = 1;
314 initial_pdb.running_threads = 1;
315 initial_pdb.ring0_threads = 1;
316 initial_pdb.env_db = &initial_envdb;
317 initial_pdb.group = &initial_pdb;
318 initial_pdb.priority = 8; /* Normal */
319 initial_pdb.flags = win32? 0 : PDB32_WIN16_PROC;
320 initial_pdb.winver = 0xffff; /* to be determined */
321 initial_pdb.main_queue = INVALID_HANDLE_VALUE16;
322 initial_envdb.startup_info = &initial_startup;
324 /* Initialize virtual memory management */
325 if (!VIRTUAL_Init()) return FALSE;
327 /* Create the initial thread structure and socket pair */
328 if (!(teb = THREAD_CreateInitialThread( &initial_pdb, server_fd ))) return FALSE;
330 /* Remember TEB selector of initial process for emergency use */
331 SYSLEVEL_EmergencyTeb = teb->teb_sel;
333 /* Create the system and process heaps */
334 if (!HEAP_CreateSystemHeap()) return FALSE;
335 initial_pdb.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
337 /* Create the idle event for the initial process
338 FIXME 1: Shouldn't we call UserSignalProc for the initial process too?
339 FIXME 2: It seems to me that the initial pdb becomes never freed, so I don't now
340 where to release the idle event for the initial process.
342 initial_pdb.idle_event = CreateEventA ( NULL, TRUE, FALSE, NULL );
343 initial_pdb.idle_event = ConvertToGlobalHandle ( initial_pdb.idle_event );
345 /* Initialize signal handling */
346 if (!SIGNAL_Init()) return FALSE;
348 /* Retrieve startup info from the server */
349 req = get_req_buffer();
350 req->ldt_copy = ldt_copy;
351 req->ldt_flags = ldt_flags_copy;
352 if (server_call( REQ_INIT_PROCESS )) return FALSE;
353 initial_pdb.exe_file = req->exe_file;
354 initial_startup.dwFlags = req->start_flags;
355 initial_startup.wShowWindow = req->cmd_show;
356 initial_envdb.hStdin = initial_startup.hStdInput = req->hstdin;
357 initial_envdb.hStdout = initial_startup.hStdOutput = req->hstdout;
358 initial_envdb.hStderr = initial_startup.hStdError = req->hstderr;
359 initial_envdb.cmd_line = "";
361 /* Copy the parent environment */
362 if (!ENV_InheritEnvironment( NULL )) return FALSE;
364 /* Create the SEGPTR heap */
365 if (!(SegptrHeap = HeapCreate( HEAP_WINE_SEGPTR, 0, 0 ))) return FALSE;
367 /* Initialize the critical sections */
368 InitializeCriticalSection( &initial_pdb.crit_section );
369 InitializeCriticalSection( &initial_envdb.section );
371 return TRUE;
375 /***********************************************************************
376 * start_process
378 * Startup routine of a new Win32 process. Runs on the new process stack.
380 static void start_process(void)
382 struct init_process_done_request *req = get_req_buffer();
383 int debugged;
384 HMODULE16 hModule16;
385 UINT cmdShow = SW_SHOWNORMAL;
386 LPTHREAD_START_ROUTINE entry;
387 PDB *pdb = PROCESS_Current();
388 HMODULE main_module = pdb->exe_modref->module;
390 /* Increment EXE refcount */
391 pdb->exe_modref->refCount++;
393 /* Retrieve entry point address */
394 entry = (LPTHREAD_START_ROUTINE)RVA_PTR( main_module, OptionalHeader.AddressOfEntryPoint );
396 /* Create 16-bit dummy module */
397 if ((hModule16 = MODULE_CreateDummyModule( pdb->exe_modref->filename, main_module )) < 32)
398 ExitProcess( hModule16 );
400 if (pdb->env_db->startup_info->dwFlags & STARTF_USESHOWWINDOW)
401 cmdShow = pdb->env_db->startup_info->wShowWindow;
402 if (!TASK_Create( (NE_MODULE *)GlobalLock16( hModule16 ), cmdShow )) goto error;
404 /* Signal the parent process to continue */
405 req->module = (void *)main_module;
406 req->entry = entry;
407 server_call( REQ_INIT_PROCESS_DONE );
408 debugged = req->debugged;
410 if (pdb->flags & PDB32_CONSOLE_PROC) AllocConsole();
412 /* Load system DLLs into the initial process (and initialize them) */
413 if (!LoadLibraryA( "KERNEL32" )) goto error;
414 if (!LoadLibraryA( "x11drv" )) goto error;
416 if ( !LoadLibrary16("GDI.EXE" ) || !LoadLibraryA("GDI32.DLL" )
417 || !LoadLibrary16("USER.EXE") || !LoadLibraryA("USER32.DLL"))
418 goto error;
420 /* Get pointers to USER routines called by KERNEL */
421 THUNK_InitCallout();
423 /* Call FinalUserInit routine */
424 Callout.FinalUserInit16();
426 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
427 * context of the parent process. Actually, the USER signal proc
428 * doesn't really care about that, but it *does* require that the
429 * startup parameters are correctly set up, so that GetProcessDword
430 * works. Furthermore, before calling the USER signal proc the
431 * 16-bit stack must be set up, which it is only after TASK_Create
432 * in the case of a 16-bit process. Thus, we send the signal here.
435 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
436 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
437 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
438 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
440 EnterCriticalSection( &pdb->crit_section );
441 PE_InitTls();
442 MODULE_DllProcessAttach( pdb->exe_modref, (LPVOID)1 );
443 LeaveCriticalSection( &pdb->crit_section );
445 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
446 if (pdb->flags & PDB32_CONSOLE_PROC)
447 PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
449 TRACE_(relay)( "Starting Win32 process (entryproc=%p)\n", entry );
450 if (debugged) DbgBreakPoint();
451 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
452 * Dunno about other OSs */
453 ExitProcess( entry(NULL) );
455 error:
456 ExitProcess( GetLastError() );
460 /***********************************************************************
461 * PROCESS_Init32
463 * Initialisation of a new Win32 process.
465 void PROCESS_Init32( HFILE hFile, LPCSTR filename, LPCSTR cmd_line )
467 WORD version;
468 HMODULE main_module;
469 PDB *pdb = PROCESS_Current();
471 pdb->env_db->cmd_line = HEAP_strdupA( GetProcessHeap(), 0, cmd_line );
473 /* load main module */
474 if ((main_module = PE_LoadImage( hFile, filename, &version )) < 32)
475 ExitProcess( main_module );
476 #if 0
477 if (PE_HEADER(main_module)->FileHeader.Characteristics & IMAGE_FILE_DLL)
479 SetLastError( 20 ); /* FIXME: not the right error code */
480 goto error;
482 #endif
484 /* Create 32-bit MODREF */
485 if (!PE_CreateModule( main_module, filename, 0, FALSE )) goto error;
487 /* allocate main thread stack */
488 if (!THREAD_InitStack( NtCurrentTeb(), pdb,
489 PE_HEADER(main_module)->OptionalHeader.SizeOfStackReserve, TRUE ))
490 goto error;
492 SIGNAL_Init(); /* reinitialize signal stack */
494 /* switch to the new stack */
495 CALL32_Init( &IF1632_CallLargeStack, start_process, NtCurrentTeb()->stack_top );
496 error:
497 ExitProcess( GetLastError() );
501 /***********************************************************************
502 * PROCESS_InitWinelib
504 * Initialisation of a new Winelib process.
506 void PROCESS_InitWinelib( int argc, char *argv[] )
508 PDB *pdb;
509 HMODULE main_module;
510 LPCSTR filename;
511 LPSTR cmdline, p;
512 int i, len = 0;
514 if (!MAIN_MainInit( argc, argv, TRUE )) exit(1);
515 pdb = PROCESS_Current();
517 /* build command-line */
518 for (i = 0; Options.argv[i]; i++) len += strlen(Options.argv[i]) + 1;
519 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) goto error;
520 for (p = cmdline, i = 0; Options.argv[i]; i++)
522 strcpy( p, Options.argv[i] );
523 p += strlen(p);
524 *p++ = ' ';
526 if (p > cmdline) p--;
527 *p = 0;
528 pdb->env_db->cmd_line = cmdline;
530 /* create 32-bit module for main exe */
531 if ((main_module = BUILTIN32_LoadExeModule( &filename )) < 32 ) goto error;
533 /* Create 32-bit MODREF */
534 if (!PE_CreateModule( main_module, filename, 0, FALSE )) goto error;
536 /* allocate main thread stack */
537 if (!THREAD_InitStack( NtCurrentTeb(), pdb,
538 PE_HEADER(main_module)->OptionalHeader.SizeOfStackReserve, TRUE ))
539 goto error;
541 SIGNAL_Init(); /* reinitialize signal stack */
543 /* switch to the new stack */
544 CALL32_Init( &IF1632_CallLargeStack, start_process, NtCurrentTeb()->stack_top );
545 error:
546 ExitProcess( GetLastError() );
550 /***********************************************************************
551 * PROCESS_Start
553 * Startup routine of a new process. Called in the context of the new process.
555 void PROCESS_Start(void)
557 struct init_process_done_request *req = get_req_buffer();
558 int debugged;
559 UINT cmdShow = SW_SHOWNORMAL;
560 LPTHREAD_START_ROUTINE entry = NULL;
561 PDB *pdb = PROCESS_Current();
562 NE_MODULE *pModule = NE_GetPtr( pdb->module );
563 LPCSTR filename = ((OFSTRUCT *)((char*)(pModule) + (pModule)->fileinfo))->szPathName;
565 /* Get process type */
566 enum { PROC_DOS, PROC_WIN16, PROC_WIN32 } type;
567 if ( pdb->flags & PDB32_DOS_PROC )
568 type = PROC_DOS;
569 else if ( pdb->flags & PDB32_WIN16_PROC )
570 type = PROC_WIN16;
571 else
572 type = PROC_WIN32;
574 /* Initialize the critical section */
575 InitializeCriticalSection( &pdb->crit_section );
577 /* Create the environment db */
578 if (!PROCESS_CreateEnvDB()) goto error;
580 /* Create a task for this process */
581 if (pdb->env_db->startup_info->dwFlags & STARTF_USESHOWWINDOW)
582 cmdShow = pdb->env_db->startup_info->wShowWindow;
583 if (!TASK_Create( pModule, cmdShow ))
584 goto error;
586 /* Load all process modules */
587 switch ( type )
589 case PROC_WIN16:
590 if ( !NE_InitProcess( pModule ) )
591 goto error;
592 break;
594 case PROC_WIN32:
595 /* Create 32-bit MODREF */
596 if ( !PE_CreateModule( pModule->module32, filename, 0, FALSE ) )
597 goto error;
599 /* Increment EXE refcount */
600 assert( pdb->exe_modref );
601 pdb->exe_modref->refCount++;
603 /* Retrieve entry point address */
604 entry = (LPTHREAD_START_ROUTINE)RVA_PTR(pModule->module32,
605 OptionalHeader.AddressOfEntryPoint);
606 break;
608 case PROC_DOS:
609 /* FIXME: move DOS startup code here */
610 break;
614 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
615 * context of the parent process. Actually, the USER signal proc
616 * doesn't really care about that, but it *does* require that the
617 * startup parameters are correctly set up, so that GetProcessDword
618 * works. Furthermore, before calling the USER signal proc the
619 * 16-bit stack must be set up, which it is only after TASK_Create
620 * in the case of a 16-bit process. Thus, we send the signal here.
623 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
624 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
625 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
626 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
628 /* Signal the parent process to continue */
629 req->module = (void *)pModule->module32;
630 req->entry = entry;
631 server_call( REQ_INIT_PROCESS_DONE );
632 debugged = req->debugged;
634 if ( (pdb->flags & PDB32_CONSOLE_PROC) || (pdb->flags & PDB32_DOS_PROC) )
635 AllocConsole();
637 /* Perform Win32 specific process initialization */
638 if ( type == PROC_WIN32 )
640 EnterCriticalSection( &pdb->crit_section );
642 PE_InitTls();
643 MODULE_DllProcessAttach( pdb->exe_modref, (LPVOID)1 );
645 LeaveCriticalSection( &pdb->crit_section );
648 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
649 if ( type != PROC_WIN16 && (pdb->flags & PDB32_CONSOLE_PROC))
650 PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
652 switch ( type )
654 case PROC_DOS:
655 TRACE_(relay)( "Starting DOS process\n" );
656 DOSVM_Enter( NULL );
657 ERR_(relay)( "DOSVM_Enter returned; should not happen!\n" );
658 ExitProcess( 0 );
660 case PROC_WIN16:
661 TRACE_(relay)( "Starting Win16 process\n" );
662 TASK_CallToStart();
663 ERR_(relay)( "TASK_CallToStart returned; should not happen!\n" );
664 ExitProcess( 0 );
666 case PROC_WIN32:
667 TRACE_(relay)( "Starting Win32 process (entryproc=%p)\n", entry );
668 if (debugged) DbgBreakPoint();
669 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
670 * Dunno about other OSs */
671 ExitProcess( entry(NULL) );
674 error:
675 ExitProcess( GetLastError() );
679 /***********************************************************************
680 * PROCESS_Create
682 * Create a new process database and associated info.
684 PDB *PROCESS_Create( NE_MODULE *pModule, HFILE hFile, LPCSTR cmd_line, LPCSTR env,
685 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
686 BOOL inherit, DWORD flags, STARTUPINFOA *startup,
687 PROCESS_INFORMATION *info )
689 HANDLE handles[2], load_done_evt = -1;
690 DWORD exitcode, size;
691 BOOL alloc_stack16;
692 int fd = -1;
693 struct new_process_request *req = get_req_buffer();
694 TEB *teb = NULL;
695 PDB *parent = PROCESS_Current();
696 PDB *pdb = PROCESS_CreatePDB( parent, inherit );
698 if (!pdb) return NULL;
699 info->hThread = info->hProcess = INVALID_HANDLE_VALUE;
701 /* Create the process on the server side */
703 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
704 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
705 req->inherit_all = 2 /*inherit*/; /* HACK! */
706 req->create_flags = flags;
707 req->start_flags = startup->dwFlags;
708 req->exe_file = hFile;
709 if (startup->dwFlags & STARTF_USESTDHANDLES)
711 req->hstdin = startup->hStdInput;
712 req->hstdout = startup->hStdOutput;
713 req->hstderr = startup->hStdError;
715 else
717 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
718 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
719 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
721 req->cmd_show = startup->wShowWindow;
722 req->env_ptr = (void*)env; /* FIXME: hack */
723 lstrcpynA( req->cmdline, cmd_line, server_remaining(req->cmdline) );
724 if (server_call_fd( REQ_NEW_PROCESS, -1, &fd )) goto error;
725 pdb->server_pid = req->pid;
726 info->hProcess = req->phandle;
727 info->dwProcessId = (DWORD)req->pid;
728 info->hThread = req->thandle;
729 info->dwThreadId = (DWORD)req->tid;
730 load_done_evt = req->event;
732 if (pModule->module32) /* Win32 process */
734 IMAGE_OPTIONAL_HEADER *header = &PE_HEADER(pModule->module32)->OptionalHeader;
735 size = header->SizeOfStackReserve;
736 if (header->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
737 pdb->flags |= PDB32_CONSOLE_PROC;
738 alloc_stack16 = TRUE;
740 else if (!pModule->dos_image) /* Win16 process */
742 alloc_stack16 = FALSE;
743 size = 0;
744 pdb->flags |= PDB32_WIN16_PROC;
746 else /* DOS process */
748 alloc_stack16 = FALSE;
749 size = 0;
750 pdb->flags |= PDB32_DOS_PROC;
753 /* Create the main thread */
755 if (!(teb = THREAD_Create( pdb, req->pid, req->tid, fd, size, alloc_stack16 ))) goto error;
756 teb->startup = PROCESS_Start;
757 fd = -1; /* don't close it */
759 /* Pass module to new process (FIXME: hack) */
760 pdb->module = pModule->self;
761 SYSDEPS_SpawnThread( teb );
763 /* Wait until process is initialized (or initialization failed) */
764 handles[0] = info->hProcess;
765 handles[1] = load_done_evt;
767 switch ( WaitForMultipleObjects( 2, handles, FALSE, INFINITE ) )
769 default:
770 ERR( "WaitForMultipleObjects failed\n" );
771 break;
773 case 0:
774 /* Child initialization code returns error condition as exitcode */
775 if ( GetExitCodeProcess( info->hProcess, &exitcode ) )
776 SetLastError( exitcode );
777 goto error;
779 case 1:
780 /* Get 16-bit task up and running */
781 if ( pdb->flags & PDB32_WIN16_PROC )
783 /* Post event to start the task */
784 PostEvent16( pdb->task );
786 /* If we ourselves are a 16-bit task, we Yield() directly. */
787 if ( parent->flags & PDB32_WIN16_PROC )
788 OldYield16();
790 break;
793 CloseHandle( load_done_evt );
794 return pdb;
796 error:
797 if (load_done_evt != -1) CloseHandle( load_done_evt );
798 if (info->hThread != INVALID_HANDLE_VALUE) CloseHandle( info->hThread );
799 if (info->hProcess != INVALID_HANDLE_VALUE) CloseHandle( info->hProcess );
800 PROCESS_FreePDB( pdb );
801 if (fd != -1) close( fd );
802 return NULL;
806 /***********************************************************************
807 * ExitProcess (KERNEL32.100)
809 void WINAPI ExitProcess( DWORD status )
811 struct terminate_process_request *req = get_req_buffer();
813 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
814 TASK_KillTask( 0 );
816 /* send the exit code to the server */
817 req->handle = GetCurrentProcess();
818 req->exit_code = status;
819 server_call( REQ_TERMINATE_PROCESS );
820 /* FIXME: need separate address spaces for that */
821 /* exit( status ); */
822 SYSDEPS_ExitThread( status );
825 /***********************************************************************
826 * ExitProcess16 (KERNEL.466)
828 void WINAPI ExitProcess16( WORD status )
830 SYSLEVEL_ReleaseWin16Lock();
831 ExitProcess( status );
834 /******************************************************************************
835 * TerminateProcess (KERNEL32.684)
837 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
839 BOOL ret;
840 struct terminate_process_request *req = get_req_buffer();
841 req->handle = handle;
842 req->exit_code = exit_code;
843 if ((ret = !server_call( REQ_TERMINATE_PROCESS )) && req->self) exit( exit_code );
844 return ret;
848 /***********************************************************************
849 * GetProcessDword (KERNEL32.18) (KERNEL.485)
850 * 'Of course you cannot directly access Windows internal structures'
852 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
854 PDB *process = PROCESS_IdToPDB( dwProcessID );
855 TDB *pTask;
856 DWORD x, y;
858 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
859 if ( !process ) return 0;
861 switch ( offset )
863 case GPD_APP_COMPAT_FLAGS:
864 pTask = (TDB *)GlobalLock16( process->task );
865 return pTask? pTask->compat_flags : 0;
867 case GPD_LOAD_DONE_EVENT:
868 return process->load_done_evt;
870 case GPD_HINSTANCE16:
871 pTask = (TDB *)GlobalLock16( process->task );
872 return pTask? pTask->hInstance : 0;
874 case GPD_WINDOWS_VERSION:
875 pTask = (TDB *)GlobalLock16( process->task );
876 return pTask? pTask->version : 0;
878 case GPD_THDB:
879 if ( process != PROCESS_Current() ) return 0;
880 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
882 case GPD_PDB:
883 return (DWORD)process;
885 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
886 return process->env_db->startup_info->hStdOutput;
888 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
889 return process->env_db->startup_info->hStdInput;
891 case GPD_STARTF_SHOWWINDOW:
892 return process->env_db->startup_info->wShowWindow;
894 case GPD_STARTF_SIZE:
895 x = process->env_db->startup_info->dwXSize;
896 if ( x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
897 y = process->env_db->startup_info->dwYSize;
898 if ( y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
899 return MAKELONG( x, y );
901 case GPD_STARTF_POSITION:
902 x = process->env_db->startup_info->dwX;
903 if ( x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
904 y = process->env_db->startup_info->dwY;
905 if ( y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
906 return MAKELONG( x, y );
908 case GPD_STARTF_FLAGS:
909 return process->env_db->startup_info->dwFlags;
911 case GPD_PARENT:
912 return process->parent? (DWORD)process->parent->server_pid : 0;
914 case GPD_FLAGS:
915 return process->flags;
917 case GPD_USERDATA:
918 return process->process_dword;
920 default:
921 ERR_(win32)("Unknown offset %d\n", offset );
922 return 0;
926 /***********************************************************************
927 * SetProcessDword (KERNEL.484)
928 * 'Of course you cannot directly access Windows internal structures'
930 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
932 PDB *process = PROCESS_IdToPDB( dwProcessID );
934 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
935 if ( !process ) return;
937 switch ( offset )
939 case GPD_APP_COMPAT_FLAGS:
940 case GPD_LOAD_DONE_EVENT:
941 case GPD_HINSTANCE16:
942 case GPD_WINDOWS_VERSION:
943 case GPD_THDB:
944 case GPD_PDB:
945 case GPD_STARTF_SHELLDATA:
946 case GPD_STARTF_HOTKEY:
947 case GPD_STARTF_SHOWWINDOW:
948 case GPD_STARTF_SIZE:
949 case GPD_STARTF_POSITION:
950 case GPD_STARTF_FLAGS:
951 case GPD_PARENT:
952 case GPD_FLAGS:
953 ERR_(win32)("Not allowed to modify offset %d\n", offset );
954 break;
956 case GPD_USERDATA:
957 process->process_dword = value;
958 break;
960 default:
961 ERR_(win32)("Unknown offset %d\n", offset );
962 break;
967 /*********************************************************************
968 * OpenProcess (KERNEL32.543)
970 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
972 HANDLE ret = 0;
973 struct open_process_request *req = get_req_buffer();
975 req->pid = (void *)id;
976 req->access = access;
977 req->inherit = inherit;
978 if (!server_call( REQ_OPEN_PROCESS )) ret = req->handle;
979 return ret;
982 /*********************************************************************
983 * MapProcessHandle (KERNEL.483)
985 DWORD WINAPI MapProcessHandle( HANDLE handle )
987 DWORD ret = 0;
988 struct get_process_info_request *req = get_req_buffer();
989 req->handle = handle;
990 if (!server_call( REQ_GET_PROCESS_INFO )) ret = (DWORD)req->pid;
991 return ret;
994 /***********************************************************************
995 * GetThreadLocale (KERNEL32.295)
997 LCID WINAPI GetThreadLocale(void)
999 return PROCESS_Current()->locale;
1003 /***********************************************************************
1004 * SetPriorityClass (KERNEL32.503)
1006 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1008 struct set_process_info_request *req = get_req_buffer();
1009 req->handle = hprocess;
1010 req->priority = priorityclass;
1011 req->mask = SET_PROCESS_INFO_PRIORITY;
1012 return !server_call( REQ_SET_PROCESS_INFO );
1016 /***********************************************************************
1017 * GetPriorityClass (KERNEL32.250)
1019 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1021 DWORD ret = 0;
1022 struct get_process_info_request *req = get_req_buffer();
1023 req->handle = hprocess;
1024 if (!server_call( REQ_GET_PROCESS_INFO )) ret = req->priority;
1025 return ret;
1029 /***********************************************************************
1030 * SetProcessAffinityMask (KERNEL32.662)
1032 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1034 struct set_process_info_request *req = get_req_buffer();
1035 req->handle = hProcess;
1036 req->affinity = affmask;
1037 req->mask = SET_PROCESS_INFO_AFFINITY;
1038 return !server_call( REQ_SET_PROCESS_INFO );
1041 /**********************************************************************
1042 * GetProcessAffinityMask (KERNEL32.373)
1044 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1045 LPDWORD lpProcessAffinityMask,
1046 LPDWORD lpSystemAffinityMask )
1048 BOOL ret = FALSE;
1049 struct get_process_info_request *req = get_req_buffer();
1050 req->handle = hProcess;
1051 if (!server_call( REQ_GET_PROCESS_INFO ))
1053 if (lpProcessAffinityMask) *lpProcessAffinityMask = req->process_affinity;
1054 if (lpSystemAffinityMask) *lpSystemAffinityMask = req->system_affinity;
1055 ret = TRUE;
1057 return ret;
1061 /***********************************************************************
1062 * GetStdHandle (KERNEL32.276)
1064 HANDLE WINAPI GetStdHandle( DWORD std_handle )
1066 PDB *pdb = PROCESS_Current();
1068 switch(std_handle)
1070 case STD_INPUT_HANDLE: return pdb->env_db->hStdin;
1071 case STD_OUTPUT_HANDLE: return pdb->env_db->hStdout;
1072 case STD_ERROR_HANDLE: return pdb->env_db->hStderr;
1074 SetLastError( ERROR_INVALID_PARAMETER );
1075 return INVALID_HANDLE_VALUE;
1079 /***********************************************************************
1080 * SetStdHandle (KERNEL32.506)
1082 BOOL WINAPI SetStdHandle( DWORD std_handle, HANDLE handle )
1084 PDB *pdb = PROCESS_Current();
1085 /* FIXME: should we close the previous handle? */
1086 switch(std_handle)
1088 case STD_INPUT_HANDLE:
1089 pdb->env_db->hStdin = handle;
1090 return TRUE;
1091 case STD_OUTPUT_HANDLE:
1092 pdb->env_db->hStdout = handle;
1093 return TRUE;
1094 case STD_ERROR_HANDLE:
1095 pdb->env_db->hStderr = handle;
1096 return TRUE;
1098 SetLastError( ERROR_INVALID_PARAMETER );
1099 return FALSE;
1102 /***********************************************************************
1103 * GetProcessVersion (KERNEL32)
1105 DWORD WINAPI GetProcessVersion( DWORD processid )
1107 TDB *pTask;
1108 PDB *pdb = PROCESS_IdToPDB( processid );
1110 if (!pdb) return 0;
1111 if (!(pTask = (TDB *)GlobalLock16( pdb->task ))) return 0;
1112 return (pTask->version&0xff) | (((pTask->version >>8) & 0xff)<<16);
1115 /***********************************************************************
1116 * GetProcessFlags (KERNEL32)
1118 DWORD WINAPI GetProcessFlags( DWORD processid )
1120 PDB *pdb = PROCESS_IdToPDB( processid );
1121 if (!pdb) return 0;
1122 return pdb->flags;
1125 /***********************************************************************
1126 * SetProcessWorkingSetSize [KERNEL32.662]
1127 * Sets the min/max working set sizes for a specified process.
1129 * PARAMS
1130 * hProcess [I] Handle to the process of interest
1131 * minset [I] Specifies minimum working set size
1132 * maxset [I] Specifies maximum working set size
1134 * RETURNS STD
1136 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1137 DWORD maxset)
1139 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1140 if(( minset == -1) && (maxset == -1)) {
1141 /* Trim the working set to zero */
1142 /* Swap the process out of physical RAM */
1144 return TRUE;
1147 /***********************************************************************
1148 * GetProcessWorkingSetSize (KERNEL32)
1150 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1151 LPDWORD maxset)
1153 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1154 /* 32 MB working set size */
1155 if (minset) *minset = 32*1024*1024;
1156 if (maxset) *maxset = 32*1024*1024;
1157 return TRUE;
1160 /***********************************************************************
1161 * SetProcessShutdownParameters (KERNEL32)
1163 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1164 * Now tracks changes made (but does not act on these changes)
1165 * NOTE: the definition for SHUTDOWN_NORETRY was done on guesswork.
1166 * It really shouldn't be here, but I'll move it when it's been checked!
1168 #define SHUTDOWN_NORETRY 1
1169 static unsigned int shutdown_noretry = 0;
1170 static unsigned int shutdown_priority = 0x280L;
1171 BOOL WINAPI SetProcessShutdownParameters(DWORD level,DWORD flags)
1173 if (flags & SHUTDOWN_NORETRY)
1174 shutdown_noretry = 1;
1175 else
1176 shutdown_noretry = 0;
1177 if (level > 0x100L && level < 0x3FFL)
1178 shutdown_priority = level;
1179 else
1181 ERR("invalid priority level 0x%08lx\n", level);
1182 return FALSE;
1184 return TRUE;
1188 /***********************************************************************
1189 * GetProcessShutdownParameters (KERNEL32)
1192 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel,
1193 LPDWORD lpdwFlags )
1195 (*lpdwLevel) = shutdown_priority;
1196 (*lpdwFlags) = (shutdown_noretry * SHUTDOWN_NORETRY);
1197 return TRUE;
1199 /***********************************************************************
1200 * SetProcessPriorityBoost (KERNEL32)
1202 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1204 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1205 /* Say we can do it. I doubt the program will notice that we don't. */
1206 return TRUE;
1210 /***********************************************************************
1211 * ReadProcessMemory (KERNEL32)
1213 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1214 LPDWORD bytes_read )
1216 struct read_process_memory_request *req = get_req_buffer();
1217 unsigned int offset = (unsigned int)addr % sizeof(int);
1218 unsigned int max = server_remaining( req->data ); /* max length in one request */
1219 unsigned int pos;
1221 if (bytes_read) *bytes_read = size;
1223 /* first time, read total length to check for permissions */
1224 req->handle = process;
1225 req->addr = (char *)addr - offset;
1226 req->len = (size + offset + sizeof(int) - 1) / sizeof(int);
1227 if (server_call( REQ_READ_PROCESS_MEMORY )) goto error;
1229 if (size <= max - offset)
1231 memcpy( buffer, (char *)req->data + offset, size );
1232 return TRUE;
1235 /* now take care of the remaining data */
1236 memcpy( buffer, (char *)req->data + offset, max - offset );
1237 pos = max - offset;
1238 size -= pos;
1239 while (size)
1241 if (max > size) max = size;
1242 req->handle = process;
1243 req->addr = (char *)addr + pos;
1244 req->len = (max + sizeof(int) - 1) / sizeof(int);
1245 if (server_call( REQ_READ_PROCESS_MEMORY )) goto error;
1246 memcpy( (char *)buffer + pos, (char *)req->data, max );
1247 size -= max;
1248 pos += max;
1250 return TRUE;
1252 error:
1253 if (bytes_read) *bytes_read = 0;
1254 return FALSE;
1258 /***********************************************************************
1259 * WriteProcessMemory (KERNEL32)
1261 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPVOID buffer, DWORD size,
1262 LPDWORD bytes_written )
1264 unsigned int first_offset, last_offset;
1265 struct write_process_memory_request *req = get_req_buffer();
1266 unsigned int max = server_remaining( req->data ); /* max length in one request */
1267 unsigned int pos, last_mask;
1269 if (!size)
1271 SetLastError( ERROR_INVALID_PARAMETER );
1272 return FALSE;
1274 if (bytes_written) *bytes_written = size;
1276 /* compute the mask for the first int */
1277 req->first_mask = ~0;
1278 first_offset = (unsigned int)addr % sizeof(int);
1279 memset( &req->first_mask, 0, first_offset );
1281 /* compute the mask for the last int */
1282 last_offset = (size + first_offset) % sizeof(int);
1283 last_mask = 0;
1284 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1286 req->handle = process;
1287 req->addr = (char *)addr - first_offset;
1288 /* for the first request, use the total length */
1289 req->len = (size + first_offset + sizeof(int) - 1) / sizeof(int);
1291 if (size + first_offset < max) /* we can do it in one round */
1293 memcpy( (char *)req->data + first_offset, buffer, size );
1294 req->last_mask = last_mask;
1295 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1296 return TRUE;
1299 /* needs multiple server calls */
1301 memcpy( (char *)req->data + first_offset, buffer, max - first_offset );
1302 req->last_mask = ~0;
1303 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1304 pos = max - first_offset;
1305 size -= pos;
1306 while (size)
1308 if (size <= max) /* last one */
1310 req->last_mask = last_mask;
1311 max = size;
1313 req->handle = process;
1314 req->addr = (char *)addr + pos;
1315 req->len = (max + sizeof(int) - 1) / sizeof(int);
1316 req->first_mask = ~0;
1317 memcpy( req->data, (char *) buffer + pos, max );
1318 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1319 pos += max;
1320 size -= max;
1322 return TRUE;
1324 error:
1325 if (bytes_written) *bytes_written = 0;
1326 return FALSE;
1331 /***********************************************************************
1332 * RegisterServiceProcess (KERNEL, KERNEL32)
1334 * A service process calls this function to ensure that it continues to run
1335 * even after a user logged off.
1337 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1339 /* I don't think that Wine needs to do anything in that function */
1340 return 1; /* success */
1343 /***********************************************************************
1344 * GetExitCodeProcess [KERNEL32.325]
1346 * Gets termination status of specified process
1348 * RETURNS
1349 * Success: TRUE
1350 * Failure: FALSE
1352 BOOL WINAPI GetExitCodeProcess(
1353 HANDLE hProcess, /* [I] handle to the process */
1354 LPDWORD lpExitCode) /* [O] address to receive termination status */
1356 BOOL ret = FALSE;
1357 struct get_process_info_request *req = get_req_buffer();
1358 req->handle = hProcess;
1359 if (!server_call( REQ_GET_PROCESS_INFO ))
1361 if (lpExitCode) *lpExitCode = req->exit_code;
1362 ret = TRUE;
1364 return ret;
1368 /***********************************************************************
1369 * SetErrorMode (KERNEL32.486)
1371 UINT WINAPI SetErrorMode( UINT mode )
1373 UINT old = PROCESS_Current()->error_mode;
1374 PROCESS_Current()->error_mode = mode;
1375 return old;
1378 /***********************************************************************
1379 * GetCurrentProcess (KERNEL32.198)
1381 #undef GetCurrentProcess
1382 HANDLE WINAPI GetCurrentProcess(void)
1384 return 0xffffffff;