Added a wine rpm uninstall section to wineinstall.
[wine/gsoc_dplay.git] / scheduler / process.c
blob594d85a0544f9a38a35c428a0ed9257dc6818e8b
1 /*
2 * Win32 processes
4 * Copyright 1996, 1998 Alexandre Julliard
5 */
7 #include <assert.h>
8 #include <ctype.h>
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include "wine/winbase16.h"
16 #include "wine/exception.h"
17 #include "process.h"
18 #include "main.h"
19 #include "module.h"
20 #include "neexe.h"
21 #include "dosexe.h"
22 #include "file.h"
23 #include "global.h"
24 #include "heap.h"
25 #include "task.h"
26 #include "ldt.h"
27 #include "syslevel.h"
28 #include "thread.h"
29 #include "winerror.h"
30 #include "server.h"
31 #include "options.h"
32 #include "callback.h"
33 #include "debugtools.h"
35 DEFAULT_DEBUG_CHANNEL(process);
36 DECLARE_DEBUG_CHANNEL(relay);
37 DECLARE_DEBUG_CHANNEL(win32);
39 PDB current_process;
41 static char **main_exe_argv;
42 static char *main_exe_name;
43 static HFILE main_exe_file = -1;
46 /***********************************************************************
47 * PROCESS_CallUserSignalProc
49 * FIXME: Some of the signals aren't sent correctly!
51 * The exact meaning of the USER signals is undocumented, but this
52 * should cover the basic idea:
54 * USIG_DLL_UNLOAD_WIN16
55 * This is sent when a 16-bit module is unloaded.
57 * USIG_DLL_UNLOAD_WIN32
58 * This is sent when a 32-bit module is unloaded.
60 * USIG_DLL_UNLOAD_ORPHANS
61 * This is sent after the last Win3.1 module is unloaded,
62 * to allow removal of orphaned menus.
64 * USIG_FAULT_DIALOG_PUSH
65 * USIG_FAULT_DIALOG_POP
66 * These are called to allow USER to prepare for displaying a
67 * fault dialog, even though the fault might have happened while
68 * inside a USER critical section.
70 * USIG_THREAD_INIT
71 * This is called from the context of a new thread, as soon as it
72 * has started to run.
74 * USIG_THREAD_EXIT
75 * This is called, still in its context, just before a thread is
76 * about to terminate.
78 * USIG_PROCESS_CREATE
79 * This is called, in the parent process context, after a new process
80 * has been created.
82 * USIG_PROCESS_INIT
83 * This is called in the new process context, just after the main thread
84 * has started execution (after the main thread's USIG_THREAD_INIT has
85 * been sent).
87 * USIG_PROCESS_LOADED
88 * This is called after the executable file has been loaded into the
89 * new process context.
91 * USIG_PROCESS_RUNNING
92 * This is called immediately before the main entry point is called.
94 * USIG_PROCESS_EXIT
95 * This is called in the context of a process that is about to
96 * terminate (but before the last thread's USIG_THREAD_EXIT has
97 * been sent).
99 * USIG_PROCESS_DESTROY
100 * This is called after a process has terminated.
103 * The meaning of the dwFlags bits is as follows:
105 * USIG_FLAGS_WIN32
106 * Current process is 32-bit.
108 * USIG_FLAGS_GUI
109 * Current process is a (Win32) GUI process.
111 * USIG_FLAGS_FEEDBACK
112 * Current process needs 'feedback' (determined from the STARTUPINFO
113 * flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
115 * USIG_FLAGS_FAULT
116 * The signal is being sent due to a fault.
118 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE hModule )
120 DWORD flags = current_process.flags;
121 DWORD startup_flags = current_startupinfo.dwFlags;
122 DWORD dwFlags = 0;
124 /* Determine dwFlags */
126 if ( !(flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
128 if ( !(flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
130 if ( dwFlags & USIG_FLAGS_GUI )
132 /* Feedback defaults to ON */
133 if ( !(startup_flags & STARTF_FORCEOFFFEEDBACK) )
134 dwFlags |= USIG_FLAGS_FEEDBACK;
136 else
138 /* Feedback defaults to OFF */
139 if (startup_flags & STARTF_FORCEONFEEDBACK)
140 dwFlags |= USIG_FLAGS_FEEDBACK;
143 /* Convert module handle to 16-bit */
145 if ( HIWORD( hModule ) )
146 hModule = MapHModuleLS( hModule );
148 /* Call USER signal proc */
150 if ( Callout.UserSignalProc )
152 if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
153 Callout.UserSignalProc( uCode, GetCurrentThreadId(), dwFlags, hModule );
154 else
155 Callout.UserSignalProc( uCode, GetCurrentProcessId(), dwFlags, hModule );
160 /***********************************************************************
161 * process_init
163 * Main process initialisation code
165 static BOOL process_init( char *argv[] )
167 struct init_process_request *req;
169 /* store the program name */
170 argv0 = argv[0];
172 /* Fill the initial process structure */
173 current_process.exit_code = STILL_ACTIVE;
174 current_process.threads = 1;
175 current_process.running_threads = 1;
176 current_process.ring0_threads = 1;
177 current_process.group = &current_process;
178 current_process.priority = 8; /* Normal */
179 current_process.env_db = &current_envdb;
181 /* Setup the server connection */
182 NtCurrentTeb()->socket = CLIENT_InitServer();
183 if (CLIENT_InitThread()) return FALSE;
185 /* Retrieve startup info from the server */
186 req = get_req_buffer();
187 req->ldt_copy = ldt_copy;
188 req->ldt_flags = ldt_flags_copy;
189 req->ppid = getppid();
190 if (server_call( REQ_INIT_PROCESS )) return FALSE;
191 main_exe_file = req->exe_file;
192 if (req->filename[0]) main_exe_name = strdup( req->filename );
193 current_startupinfo.dwFlags = req->start_flags;
194 current_startupinfo.wShowWindow = req->cmd_show;
195 current_envdb.hStdin = current_startupinfo.hStdInput = req->hstdin;
196 current_envdb.hStdout = current_startupinfo.hStdOutput = req->hstdout;
197 current_envdb.hStderr = current_startupinfo.hStdError = req->hstderr;
199 /* Remember TEB selector of initial process for emergency use */
200 SYSLEVEL_EmergencyTeb = NtCurrentTeb()->teb_sel;
202 /* Create the system and process heaps */
203 if (!HEAP_CreateSystemHeap()) return FALSE;
204 current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
206 /* Copy the parent environment */
207 if (!ENV_BuildEnvironment()) return FALSE;
209 /* Create the SEGPTR heap */
210 if (!(SegptrHeap = HeapCreate( HEAP_WINE_SEGPTR, 0, 0 ))) return FALSE;
212 /* Initialize the critical sections */
213 InitializeCriticalSection( &current_process.crit_section );
215 /* Initialize syslevel handling */
216 SYSLEVEL_Init();
218 /* Parse command line arguments */
219 OPTIONS_ParseOptions( argv );
221 return MAIN_MainInit();
225 /***********************************************************************
226 * load_system_dlls
228 * Load system DLLs into the initial process (and initialize them)
230 static int load_system_dlls(void)
232 /* Load KERNEL */
233 if (!LoadLibraryA( "KERNEL32" )) return 0;
235 /* Get pointers to USER routines called by KERNEL */
236 THUNK_InitCallout();
238 /* Call FinalUserInit routine */
239 Callout.FinalUserInit16();
241 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
242 * context of the parent process. Actually, the USER signal proc
243 * doesn't really care about that, but it *does* require that the
244 * startup parameters are correctly set up, so that GetProcessDword
245 * works. Furthermore, before calling the USER signal proc the
246 * 16-bit stack must be set up, which it is only after TASK_Create
247 * in the case of a 16-bit process. Thus, we send the signal here.
249 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
250 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
251 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
252 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
254 return 1;
258 /***********************************************************************
259 * build_command_line
261 * Build the command-line of a process from the argv array.
263 static inline char *build_command_line( char **argv )
265 int len, quote;
266 char *cmdline, *p, **arg;
268 for (arg = argv, len = 0; *arg; arg++) len += strlen(*arg) + 1;
269 if ((quote = (strchr( argv[0], ' ' ) != NULL))) len += 2;
270 if (!(p = cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
271 arg = argv;
272 if (quote)
274 *p++ = '\"';
275 strcpy( p, *arg );
276 p += strlen(p);
277 *p++ = '\"';
278 *p++ = ' ';
279 arg++;
281 while (*arg)
283 strcpy( p, *arg );
284 p += strlen(p);
285 *p++ = ' ';
286 arg++;
288 if (p > cmdline) p--; /* remove last space */
289 *p = 0;
290 return cmdline;
294 /***********************************************************************
295 * start_process
297 * Startup routine of a new process. Runs on the new process stack.
299 static void start_process(void)
301 struct init_process_done_request *req = get_req_buffer();
302 int debugged, console_app;
303 LPTHREAD_START_ROUTINE entry;
304 HMODULE module = current_process.exe_modref->module;
306 /* Increment EXE refcount */
307 current_process.exe_modref->refCount++;
309 /* build command line */
310 if (!(current_envdb.cmd_line = build_command_line( main_exe_argv ))) goto error;
312 /* Retrieve entry point address */
313 entry = (LPTHREAD_START_ROUTINE)((char*)module + PE_HEADER(module)->OptionalHeader.AddressOfEntryPoint);
314 console_app = (PE_HEADER(module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
316 if (console_app) current_process.flags |= PDB32_CONSOLE_PROC;
318 /* Signal the parent process to continue */
319 req->module = (void *)module;
320 req->entry = entry;
321 req->name = &current_process.exe_modref->filename;
322 req->gui = !console_app;
323 server_call( REQ_INIT_PROCESS_DONE );
324 debugged = req->debugged;
326 /* Install signal handlers; this cannot be done before, since we cannot
327 * send exceptions to the debugger before the create process event that
328 * is sent by REQ_INIT_PROCESS_DONE */
329 if (!SIGNAL_Init()) goto error;
331 /* Load the system dlls */
332 if (!load_system_dlls()) goto error;
334 EnterCriticalSection( &current_process.crit_section );
335 PE_InitTls();
336 MODULE_DllProcessAttach( current_process.exe_modref, (LPVOID)1 );
337 LeaveCriticalSection( &current_process.crit_section );
339 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
340 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
342 TRACE_(relay)( "Starting Win32 process (entryproc=%p)\n", entry );
343 if (debugged) DbgBreakPoint();
344 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
345 * Dunno about other OSs */
346 SetLastError(0); /* clear error code */
347 ExitThread( entry(NULL) );
349 error:
350 ExitProcess( GetLastError() );
354 /***********************************************************************
355 * PROCESS_Start
357 * Startup routine of a new Win32 process once the main module has been loaded.
358 * The filename is free'd by this routine.
360 static void PROCESS_Start( HMODULE main_module, HFILE hFile, LPSTR filename ) WINE_NORETURN;
361 static void PROCESS_Start( HMODULE main_module, HFILE hFile, LPSTR filename )
363 if (!filename)
365 /* if no explicit filename, use argv[0] */
366 if (!(filename = malloc( MAX_PATH ))) ExitProcess(1);
367 if (!GetLongPathNameA( full_argv0, filename, MAX_PATH ))
368 lstrcpynA( filename, full_argv0, MAX_PATH );
371 /* load main module */
372 if (PE_HEADER(main_module)->FileHeader.Characteristics & IMAGE_FILE_DLL)
373 ExitProcess( ERROR_BAD_EXE_FORMAT );
375 /* Create 32-bit MODREF */
376 if (!PE_CreateModule( main_module, filename, 0, hFile, FALSE ))
377 goto error;
378 free( filename );
380 /* allocate main thread stack */
381 if (!THREAD_InitStack( NtCurrentTeb(),
382 PE_HEADER(main_module)->OptionalHeader.SizeOfStackReserve, TRUE ))
383 goto error;
385 /* switch to the new stack */
386 SYSDEPS_SwitchToThreadStack( start_process );
388 error:
389 ExitProcess( GetLastError() );
393 /***********************************************************************
394 * PROCESS_InitWine
396 * Wine initialisation: load and start the main exe file.
398 void PROCESS_InitWine( int argc, char *argv[] )
400 DWORD type;
402 /* Initialize everything */
403 if (!process_init( argv )) exit(1);
405 main_exe_argv = ++argv; /* remove argv[0] (wine itself) */
407 if (!main_exe_name)
409 char buffer[MAX_PATH];
410 if (!argv[0]) OPTIONS_Usage();
412 /* open the exe file */
413 if (!SearchPathA( NULL, argv[0], ".exe", sizeof(buffer), buffer, NULL ) &&
414 !SearchPathA( NULL, argv[0], NULL, sizeof(buffer), buffer, NULL ))
416 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
417 goto error;
419 if (!(main_exe_name = strdup(buffer)))
421 MESSAGE( "%s: out of memory\n", argv0 );
422 ExitProcess(1);
426 if (main_exe_file == INVALID_HANDLE_VALUE)
428 if ((main_exe_file = CreateFileA( main_exe_name, GENERIC_READ, FILE_SHARE_READ,
429 NULL, OPEN_EXISTING, 0, -1 )) == INVALID_HANDLE_VALUE)
431 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
432 goto error;
436 if (!MODULE_GetBinaryType( main_exe_file, main_exe_name, &type ))
438 MESSAGE( "%s: unrecognized executable '%s'\n", argv0, main_exe_name );
439 goto error;
442 switch (type)
444 case SCS_32BIT_BINARY:
446 HMODULE main_module = PE_LoadImage( main_exe_file, main_exe_name, 0 );
447 if (main_module) PROCESS_Start( main_module, main_exe_file, main_exe_name );
449 break;
451 case SCS_WOW_BINARY:
453 HMODULE main_module;
454 /* create 32-bit module for main exe */
455 if (!(main_module = BUILTIN32_LoadExeModule())) goto error;
456 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
457 current_process.flags |= PDB32_WIN16_PROC;
458 SYSLEVEL_EnterWin16Lock();
459 PROCESS_Start( main_module, -1, NULL );
461 break;
463 case SCS_DOS_BINARY:
465 HMODULE main_module;
466 /* create 32-bit module for main exe */
467 if (!(main_module = BUILTIN32_LoadExeModule())) goto error;
468 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
469 if (!MZ_LoadImage( main_module, main_exe_file, main_exe_name )) goto error;
470 PROCESS_Start( main_module, main_exe_file, NULL );
472 break;
474 case SCS_PIF_BINARY:
475 case SCS_POSIX_BINARY:
476 case SCS_OS216_BINARY:
477 default:
478 MESSAGE( "%s: unrecognized executable '%s'\n", argv0, main_exe_name );
479 SetLastError( ERROR_BAD_FORMAT );
480 break;
482 error:
483 ExitProcess( GetLastError() );
487 /***********************************************************************
488 * PROCESS_InitWinelib
490 * Initialisation of a new Winelib process.
492 void PROCESS_InitWinelib( int argc, char *argv[] )
494 HMODULE main_module;
496 if (!process_init( argv )) exit(1);
498 /* create 32-bit module for main exe */
499 if (!(main_module = BUILTIN32_LoadExeModule())) ExitProcess( GetLastError() );
501 main_exe_argv = argv;
502 PROCESS_Start( main_module, -1, NULL );
506 /***********************************************************************
507 * build_argv
509 * Build an argv array from a command-line.
510 * The command-line is modified to insert nulls.
511 * 'reserved' is the number of args to reserve before the first one.
513 static char **build_argv( char *cmdline, int reserved )
515 char **argv;
516 int count = reserved + 1;
517 char *p = cmdline;
519 /* if first word is quoted store it as a single arg */
520 if (*cmdline == '\"')
522 if ((p = strchr( cmdline + 1, '\"' )))
524 p++;
525 count++;
527 else p = cmdline;
529 while (*p)
531 while (*p && isspace(*p)) p++;
532 if (!*p) break;
533 count++;
534 while (*p && !isspace(*p)) p++;
537 if ((argv = malloc( count * sizeof(*argv) )))
539 char **argvptr = argv + reserved;
540 p = cmdline;
541 if (*cmdline == '\"')
543 if ((p = strchr( cmdline + 1, '\"' )))
545 *argvptr++ = cmdline + 1;
546 *p++ = 0;
548 else p = cmdline;
550 while (*p)
552 while (*p && isspace(*p)) *p++ = 0;
553 if (!*p) break;
554 *argvptr++ = p;
555 while (*p && !isspace(*p)) p++;
557 *argvptr = 0;
559 return argv;
563 /***********************************************************************
564 * build_envp
566 * Build the environment of a new child process.
568 static char **build_envp( const char *env )
570 const char *p;
571 char **envp;
572 int count;
574 for (p = env, count = 0; *p; count++) p += strlen(p) + 1;
575 count += 3;
576 if ((envp = malloc( count * sizeof(*envp) )))
578 extern char **environ;
579 char **envptr = envp;
580 char **unixptr = environ;
581 /* first put PATH, HOME and WINEPREFIX from the unix env */
582 for (unixptr = environ; unixptr && *unixptr; unixptr++)
583 if (!memcmp( *unixptr, "PATH=", 5 ) ||
584 !memcmp( *unixptr, "HOME=", 5 ) ||
585 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
586 /* now put the Windows environment strings */
587 for (p = env; *p; p += strlen(p) + 1)
589 if (memcmp( p, "PATH=", 5 ) &&
590 memcmp( p, "HOME=", 5 ) &&
591 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
593 *envptr = 0;
595 return envp;
599 /***********************************************************************
600 * find_wine_binary
602 * Locate the Wine binary to exec for a new Win32 process.
604 static void exec_wine_binary( char **argv, char **envp )
606 const char *path, *pos, *ptr;
608 /* first try bin directory */
609 argv[0] = BINDIR "/wine";
610 execve( argv[0], argv, envp );
612 /* now try the path of argv0 of the current binary */
613 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
614 if ((ptr = strrchr( full_argv0, '/' )))
616 memcpy( argv[0], full_argv0, ptr - full_argv0 );
617 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
618 execve( argv[0], argv, envp );
620 free( argv[0] );
622 /* now search in the Unix path */
623 if ((path = getenv( "PATH" )))
625 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
626 pos = path;
627 for (;;)
629 while (*pos == ':') pos++;
630 if (!*pos) break;
631 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
632 memcpy( argv[0], pos, ptr - pos );
633 strcpy( argv[0] + (ptr - pos), "/wine" );
634 execve( argv[0], argv, envp );
635 pos = ptr;
638 free( argv[0] );
640 /* finally try the current directory */
641 argv[0] = "./wine";
642 execve( argv[0], argv, envp );
646 /***********************************************************************
647 * fork_and_exec
649 * Fork and exec a new Unix process, checking for errors.
651 static int fork_and_exec( const char *filename, char *cmdline,
652 const char *env, const char *newdir )
654 int fd[2];
655 int pid, err;
657 if (pipe(fd) == -1)
659 FILE_SetDosError();
660 return -1;
662 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
663 if (!(pid = fork())) /* child */
665 char **argv = build_argv( cmdline, filename ? 0 : 2 );
666 char **envp = build_envp( env );
667 close( fd[0] );
669 if (newdir) chdir(newdir);
671 if (argv && envp)
673 if (!filename)
675 argv[1] = "--";
676 exec_wine_binary( argv, envp );
678 else execve( filename, argv, envp );
680 err = errno;
681 write( fd[1], &err, sizeof(err) );
682 _exit(1);
684 close( fd[1] );
685 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
687 errno = err;
688 pid = -1;
690 if (pid == -1) FILE_SetDosError();
691 close( fd[0] );
692 return pid;
696 /***********************************************************************
697 * PROCESS_Create
699 * Create a new process. If hFile is a valid handle we have an exe
700 * file, and we exec a new copy of wine to load it; otherwise we
701 * simply exec the specified filename as a Unix process.
703 BOOL PROCESS_Create( HFILE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
704 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
705 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
706 LPPROCESS_INFORMATION info, LPCSTR lpCurrentDirectory )
708 int pid;
709 const char *unixfilename = NULL;
710 const char *unixdir = NULL;
711 DOS_FULL_NAME full_name;
712 HANDLE load_done_evt = -1;
713 struct new_process_request *req = get_req_buffer();
714 struct wait_process_request *wait_req = get_req_buffer();
716 info->hThread = info->hProcess = INVALID_HANDLE_VALUE;
718 /* create the process on the server side */
720 req->inherit_all = inherit;
721 req->create_flags = flags;
722 req->start_flags = startup->dwFlags;
723 req->exe_file = hFile;
724 if (startup->dwFlags & STARTF_USESTDHANDLES)
726 req->hstdin = startup->hStdInput;
727 req->hstdout = startup->hStdOutput;
728 req->hstderr = startup->hStdError;
730 else
732 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
733 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
734 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
736 req->cmd_show = startup->wShowWindow;
737 req->alloc_fd = 0;
739 if (lpCurrentDirectory) {
740 if (DOSFS_GetFullName( lpCurrentDirectory, TRUE, &full_name ))
741 unixdir = full_name.long_name;
742 } else {
743 CHAR buf[260];
744 if (GetCurrentDirectoryA(sizeof(buf),buf)) {
745 if (DOSFS_GetFullName( buf, TRUE, &full_name ))
746 unixdir = full_name.long_name;
750 if (hFile == -1) /* unix process */
752 unixfilename = filename;
753 if (DOSFS_GetFullName( filename, TRUE, &full_name )) unixfilename = full_name.long_name;
754 req->filename[0] = 0;
756 else /* new wine process */
758 if (!GetLongPathNameA( filename, req->filename, server_remaining(req->filename) ))
759 lstrcpynA( req->filename, filename, server_remaining(req->filename) );
761 if (server_call( REQ_NEW_PROCESS )) return FALSE;
763 /* fork and execute */
765 pid = fork_and_exec( unixfilename, cmd_line, env ? env : GetEnvironmentStringsA(), unixdir );
767 wait_req->cancel = (pid == -1);
768 wait_req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
769 wait_req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
770 wait_req->timeout = 2000;
771 if (server_call( REQ_WAIT_PROCESS ) || (pid == -1)) goto error;
772 info->dwProcessId = (DWORD)wait_req->pid;
773 info->dwThreadId = (DWORD)wait_req->tid;
774 info->hProcess = wait_req->phandle;
775 info->hThread = wait_req->thandle;
776 load_done_evt = wait_req->event;
778 /* Wait until process is initialized (or initialization failed) */
779 if (load_done_evt != -1)
781 DWORD res;
782 HANDLE handles[2];
784 handles[0] = info->hProcess;
785 handles[1] = load_done_evt;
786 res = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
787 CloseHandle( load_done_evt );
788 if (res == STATUS_WAIT_0) /* the process died */
790 DWORD exitcode;
791 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
792 CloseHandle( info->hThread );
793 CloseHandle( info->hProcess );
794 return FALSE;
797 return TRUE;
799 error:
800 if (load_done_evt != -1) CloseHandle( load_done_evt );
801 if (info->hThread != INVALID_HANDLE_VALUE) CloseHandle( info->hThread );
802 if (info->hProcess != INVALID_HANDLE_VALUE) CloseHandle( info->hProcess );
803 return FALSE;
807 /***********************************************************************
808 * ExitProcess (KERNEL32.100)
810 void WINAPI ExitProcess( DWORD status )
812 struct terminate_process_request *req = get_req_buffer();
814 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
815 /* send the exit code to the server */
816 req->handle = GetCurrentProcess();
817 req->exit_code = status;
818 server_call( REQ_TERMINATE_PROCESS );
819 exit( status );
822 /***********************************************************************
823 * ExitProcess16 (KERNEL.466)
825 void WINAPI ExitProcess16( WORD status )
827 SYSLEVEL_ReleaseWin16Lock();
828 ExitProcess( status );
831 /******************************************************************************
832 * TerminateProcess (KERNEL32.684)
834 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
836 BOOL ret;
837 struct terminate_process_request *req = get_req_buffer();
838 req->handle = handle;
839 req->exit_code = exit_code;
840 if ((ret = !server_call( REQ_TERMINATE_PROCESS )) && req->self) exit( exit_code );
841 return ret;
845 /***********************************************************************
846 * GetProcessDword (KERNEL32.18) (KERNEL.485)
847 * 'Of course you cannot directly access Windows internal structures'
849 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
851 TDB *pTask;
852 DWORD x, y;
854 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
856 if (dwProcessID && dwProcessID != GetCurrentProcessId())
858 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
859 return 0;
862 switch ( offset )
864 case GPD_APP_COMPAT_FLAGS:
865 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
866 return pTask? pTask->compat_flags : 0;
868 case GPD_LOAD_DONE_EVENT:
869 return current_process.load_done_evt;
871 case GPD_HINSTANCE16:
872 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
873 return pTask? pTask->hInstance : 0;
875 case GPD_WINDOWS_VERSION:
876 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
877 return pTask? pTask->version : 0;
879 case GPD_THDB:
880 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
882 case GPD_PDB:
883 return (DWORD)&current_process;
885 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
886 return current_startupinfo.hStdOutput;
888 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
889 return current_startupinfo.hStdInput;
891 case GPD_STARTF_SHOWWINDOW:
892 return current_startupinfo.wShowWindow;
894 case GPD_STARTF_SIZE:
895 x = current_startupinfo.dwXSize;
896 if ( x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
897 y = current_startupinfo.dwYSize;
898 if ( y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
899 return MAKELONG( x, y );
901 case GPD_STARTF_POSITION:
902 x = current_startupinfo.dwX;
903 if ( x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
904 y = current_startupinfo.dwY;
905 if ( y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
906 return MAKELONG( x, y );
908 case GPD_STARTF_FLAGS:
909 return current_startupinfo.dwFlags;
911 case GPD_PARENT:
912 return 0;
914 case GPD_FLAGS:
915 return current_process.flags;
917 case GPD_USERDATA:
918 return current_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 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
934 if (dwProcessID && dwProcessID != GetCurrentProcessId())
936 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
937 return;
940 switch ( offset )
942 case GPD_APP_COMPAT_FLAGS:
943 case GPD_LOAD_DONE_EVENT:
944 case GPD_HINSTANCE16:
945 case GPD_WINDOWS_VERSION:
946 case GPD_THDB:
947 case GPD_PDB:
948 case GPD_STARTF_SHELLDATA:
949 case GPD_STARTF_HOTKEY:
950 case GPD_STARTF_SHOWWINDOW:
951 case GPD_STARTF_SIZE:
952 case GPD_STARTF_POSITION:
953 case GPD_STARTF_FLAGS:
954 case GPD_PARENT:
955 case GPD_FLAGS:
956 ERR_(win32)("Not allowed to modify offset %d\n", offset );
957 break;
959 case GPD_USERDATA:
960 current_process.process_dword = value;
961 break;
963 default:
964 ERR_(win32)("Unknown offset %d\n", offset );
965 break;
970 /*********************************************************************
971 * OpenProcess (KERNEL32.543)
973 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
975 HANDLE ret = 0;
976 struct open_process_request *req = get_req_buffer();
978 req->pid = (void *)id;
979 req->access = access;
980 req->inherit = inherit;
981 if (!server_call( REQ_OPEN_PROCESS )) ret = req->handle;
982 return ret;
985 /*********************************************************************
986 * MapProcessHandle (KERNEL.483)
988 DWORD WINAPI MapProcessHandle( HANDLE handle )
990 DWORD ret = 0;
991 struct get_process_info_request *req = get_req_buffer();
992 req->handle = handle;
993 if (!server_call( REQ_GET_PROCESS_INFO )) ret = (DWORD)req->pid;
994 return ret;
997 /***********************************************************************
998 * SetPriorityClass (KERNEL32.503)
1000 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1002 struct set_process_info_request *req = get_req_buffer();
1003 req->handle = hprocess;
1004 req->priority = priorityclass;
1005 req->mask = SET_PROCESS_INFO_PRIORITY;
1006 return !server_call( REQ_SET_PROCESS_INFO );
1010 /***********************************************************************
1011 * GetPriorityClass (KERNEL32.250)
1013 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1015 DWORD ret = 0;
1016 struct get_process_info_request *req = get_req_buffer();
1017 req->handle = hprocess;
1018 if (!server_call( REQ_GET_PROCESS_INFO )) ret = req->priority;
1019 return ret;
1023 /***********************************************************************
1024 * SetProcessAffinityMask (KERNEL32.662)
1026 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1028 struct set_process_info_request *req = get_req_buffer();
1029 req->handle = hProcess;
1030 req->affinity = affmask;
1031 req->mask = SET_PROCESS_INFO_AFFINITY;
1032 return !server_call( REQ_SET_PROCESS_INFO );
1035 /**********************************************************************
1036 * GetProcessAffinityMask (KERNEL32.373)
1038 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1039 LPDWORD lpProcessAffinityMask,
1040 LPDWORD lpSystemAffinityMask )
1042 BOOL ret = FALSE;
1043 struct get_process_info_request *req = get_req_buffer();
1044 req->handle = hProcess;
1045 if (!server_call( REQ_GET_PROCESS_INFO ))
1047 if (lpProcessAffinityMask) *lpProcessAffinityMask = req->process_affinity;
1048 if (lpSystemAffinityMask) *lpSystemAffinityMask = req->system_affinity;
1049 ret = TRUE;
1051 return ret;
1055 /***********************************************************************
1056 * GetProcessVersion (KERNEL32)
1058 DWORD WINAPI GetProcessVersion( DWORD processid )
1060 IMAGE_NT_HEADERS *nt;
1062 if (processid && processid != GetCurrentProcessId())
1063 return 0; /* FIXME: should use ReadProcessMemory */
1064 if ((nt = RtlImageNtHeader( current_process.module )))
1065 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1066 nt->OptionalHeader.MinorSubsystemVersion);
1067 return 0;
1070 /***********************************************************************
1071 * GetProcessFlags (KERNEL32)
1073 DWORD WINAPI GetProcessFlags( DWORD processid )
1075 if (processid && processid != GetCurrentProcessId()) return 0;
1076 return current_process.flags;
1080 /***********************************************************************
1081 * SetProcessWorkingSetSize [KERNEL32.662]
1082 * Sets the min/max working set sizes for a specified process.
1084 * PARAMS
1085 * hProcess [I] Handle to the process of interest
1086 * minset [I] Specifies minimum working set size
1087 * maxset [I] Specifies maximum working set size
1089 * RETURNS STD
1091 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1092 DWORD maxset)
1094 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1095 if(( minset == -1) && (maxset == -1)) {
1096 /* Trim the working set to zero */
1097 /* Swap the process out of physical RAM */
1099 return TRUE;
1102 /***********************************************************************
1103 * GetProcessWorkingSetSize (KERNEL32)
1105 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1106 LPDWORD maxset)
1108 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1109 /* 32 MB working set size */
1110 if (minset) *minset = 32*1024*1024;
1111 if (maxset) *maxset = 32*1024*1024;
1112 return TRUE;
1115 /***********************************************************************
1116 * SetProcessShutdownParameters (KERNEL32)
1118 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1119 * Now tracks changes made (but does not act on these changes)
1121 static DWORD shutdown_flags = 0;
1122 static DWORD shutdown_priority = 0x280;
1124 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1126 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1127 shutdown_flags = flags;
1128 shutdown_priority = level;
1129 return TRUE;
1133 /***********************************************************************
1134 * GetProcessShutdownParameters (KERNEL32)
1137 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1139 *lpdwLevel = shutdown_priority;
1140 *lpdwFlags = shutdown_flags;
1141 return TRUE;
1145 /***********************************************************************
1146 * SetProcessPriorityBoost (KERNEL32)
1148 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1150 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1151 /* Say we can do it. I doubt the program will notice that we don't. */
1152 return TRUE;
1156 /***********************************************************************
1157 * ReadProcessMemory (KERNEL32)
1159 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1160 LPDWORD bytes_read )
1162 struct read_process_memory_request *req = get_req_buffer();
1163 unsigned int offset = (unsigned int)addr % sizeof(int);
1164 unsigned int max = server_remaining( req->data ); /* max length in one request */
1165 unsigned int pos;
1167 if (bytes_read) *bytes_read = size;
1169 /* first time, read total length to check for permissions */
1170 req->handle = process;
1171 req->addr = (char *)addr - offset;
1172 req->len = (size + offset + sizeof(int) - 1) / sizeof(int);
1173 if (server_call( REQ_READ_PROCESS_MEMORY )) goto error;
1175 if (size <= max - offset)
1177 memcpy( buffer, (char *)req->data + offset, size );
1178 return TRUE;
1181 /* now take care of the remaining data */
1182 memcpy( buffer, (char *)req->data + offset, max - offset );
1183 pos = max - offset;
1184 size -= pos;
1185 while (size)
1187 if (max > size) max = size;
1188 req->handle = process;
1189 req->addr = (char *)addr + pos;
1190 req->len = (max + sizeof(int) - 1) / sizeof(int);
1191 if (server_call( REQ_READ_PROCESS_MEMORY )) goto error;
1192 memcpy( (char *)buffer + pos, (char *)req->data, max );
1193 size -= max;
1194 pos += max;
1196 return TRUE;
1198 error:
1199 if (bytes_read) *bytes_read = 0;
1200 return FALSE;
1204 /***********************************************************************
1205 * WriteProcessMemory (KERNEL32)
1207 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPVOID buffer, DWORD size,
1208 LPDWORD bytes_written )
1210 unsigned int first_offset, last_offset;
1211 struct write_process_memory_request *req = get_req_buffer();
1212 unsigned int max = server_remaining( req->data ); /* max length in one request */
1213 unsigned int pos, last_mask;
1215 if (!size)
1217 SetLastError( ERROR_INVALID_PARAMETER );
1218 return FALSE;
1220 if (bytes_written) *bytes_written = size;
1222 /* compute the mask for the first int */
1223 req->first_mask = ~0;
1224 first_offset = (unsigned int)addr % sizeof(int);
1225 memset( &req->first_mask, 0, first_offset );
1227 /* compute the mask for the last int */
1228 last_offset = (size + first_offset) % sizeof(int);
1229 last_mask = 0;
1230 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1232 req->handle = process;
1233 req->addr = (char *)addr - first_offset;
1234 /* for the first request, use the total length */
1235 req->len = (size + first_offset + sizeof(int) - 1) / sizeof(int);
1237 if (size + first_offset < max) /* we can do it in one round */
1239 memcpy( (char *)req->data + first_offset, buffer, size );
1240 req->last_mask = last_mask;
1241 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1242 return TRUE;
1245 /* needs multiple server calls */
1247 memcpy( (char *)req->data + first_offset, buffer, max - first_offset );
1248 req->last_mask = ~0;
1249 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1250 pos = max - first_offset;
1251 size -= pos;
1252 while (size)
1254 if (size <= max) /* last one */
1256 req->last_mask = last_mask;
1257 max = size;
1259 req->handle = process;
1260 req->addr = (char *)addr + pos;
1261 req->len = (max + sizeof(int) - 1) / sizeof(int);
1262 req->first_mask = ~0;
1263 memcpy( req->data, (char *) buffer + pos, max );
1264 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1265 pos += max;
1266 size -= max;
1268 return TRUE;
1270 error:
1271 if (bytes_written) *bytes_written = 0;
1272 return FALSE;
1277 /***********************************************************************
1278 * RegisterServiceProcess (KERNEL, KERNEL32)
1280 * A service process calls this function to ensure that it continues to run
1281 * even after a user logged off.
1283 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1285 /* I don't think that Wine needs to do anything in that function */
1286 return 1; /* success */
1289 /***********************************************************************
1290 * GetExitCodeProcess [KERNEL32.325]
1292 * Gets termination status of specified process
1294 * RETURNS
1295 * Success: TRUE
1296 * Failure: FALSE
1298 BOOL WINAPI GetExitCodeProcess(
1299 HANDLE hProcess, /* [I] handle to the process */
1300 LPDWORD lpExitCode) /* [O] address to receive termination status */
1302 BOOL ret = FALSE;
1303 struct get_process_info_request *req = get_req_buffer();
1304 req->handle = hProcess;
1305 if (!server_call( REQ_GET_PROCESS_INFO ))
1307 if (lpExitCode) *lpExitCode = req->exit_code;
1308 ret = TRUE;
1310 return ret;
1314 /***********************************************************************
1315 * SetErrorMode (KERNEL32.486)
1317 UINT WINAPI SetErrorMode( UINT mode )
1319 UINT old = current_process.error_mode;
1320 current_process.error_mode = mode;
1321 return old;
1324 /***********************************************************************
1325 * GetCurrentProcess (KERNEL32.198)
1327 #undef GetCurrentProcess
1328 HANDLE WINAPI GetCurrentProcess(void)
1330 return 0xffffffff;