Setup signal handling and exceptions only after REQ_INIT_PROCESS_DONE
[wine.git] / scheduler / process.c
blob1c8205a78fb0fa2fdfc918729513e3ff8a07a39d
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 "file.h"
22 #include "global.h"
23 #include "heap.h"
24 #include "task.h"
25 #include "ldt.h"
26 #include "syslevel.h"
27 #include "thread.h"
28 #include "winerror.h"
29 #include "pe_image.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);
40 static ENVDB initial_envdb;
41 static STARTUPINFOA initial_startup;
42 static char **main_exe_argv;
43 static char *main_exe_name;
44 static HFILE main_exe_file = -1;
47 /***********************************************************************
48 * PROCESS_IdToPDB
50 * Convert a process id to a PDB, making sure it is valid.
52 PDB *PROCESS_IdToPDB( DWORD pid )
54 if (!pid || pid == GetCurrentProcessId()) return PROCESS_Current();
55 return NULL;
59 /***********************************************************************
60 * PROCESS_CallUserSignalProc
62 * FIXME: Some of the signals aren't sent correctly!
64 * The exact meaning of the USER signals is undocumented, but this
65 * should cover the basic idea:
67 * USIG_DLL_UNLOAD_WIN16
68 * This is sent when a 16-bit module is unloaded.
70 * USIG_DLL_UNLOAD_WIN32
71 * This is sent when a 32-bit module is unloaded.
73 * USIG_DLL_UNLOAD_ORPHANS
74 * This is sent after the last Win3.1 module is unloaded,
75 * to allow removal of orphaned menus.
77 * USIG_FAULT_DIALOG_PUSH
78 * USIG_FAULT_DIALOG_POP
79 * These are called to allow USER to prepare for displaying a
80 * fault dialog, even though the fault might have happened while
81 * inside a USER critical section.
83 * USIG_THREAD_INIT
84 * This is called from the context of a new thread, as soon as it
85 * has started to run.
87 * USIG_THREAD_EXIT
88 * This is called, still in its context, just before a thread is
89 * about to terminate.
91 * USIG_PROCESS_CREATE
92 * This is called, in the parent process context, after a new process
93 * has been created.
95 * USIG_PROCESS_INIT
96 * This is called in the new process context, just after the main thread
97 * has started execution (after the main thread's USIG_THREAD_INIT has
98 * been sent).
100 * USIG_PROCESS_LOADED
101 * This is called after the executable file has been loaded into the
102 * new process context.
104 * USIG_PROCESS_RUNNING
105 * This is called immediately before the main entry point is called.
107 * USIG_PROCESS_EXIT
108 * This is called in the context of a process that is about to
109 * terminate (but before the last thread's USIG_THREAD_EXIT has
110 * been sent).
112 * USIG_PROCESS_DESTROY
113 * This is called after a process has terminated.
116 * The meaning of the dwFlags bits is as follows:
118 * USIG_FLAGS_WIN32
119 * Current process is 32-bit.
121 * USIG_FLAGS_GUI
122 * Current process is a (Win32) GUI process.
124 * USIG_FLAGS_FEEDBACK
125 * Current process needs 'feedback' (determined from the STARTUPINFO
126 * flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
128 * USIG_FLAGS_FAULT
129 * The signal is being sent due to a fault.
131 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE hModule )
133 DWORD flags = PROCESS_Current()->flags;
134 DWORD startup_flags = PROCESS_Current()->env_db->startup_info->dwFlags;
135 DWORD dwFlags = 0;
137 /* Determine dwFlags */
139 if ( !(flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
141 if ( !(flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
143 if ( dwFlags & USIG_FLAGS_GUI )
145 /* Feedback defaults to ON */
146 if ( !(startup_flags & STARTF_FORCEOFFFEEDBACK) )
147 dwFlags |= USIG_FLAGS_FEEDBACK;
149 else
151 /* Feedback defaults to OFF */
152 if (startup_flags & STARTF_FORCEONFEEDBACK)
153 dwFlags |= USIG_FLAGS_FEEDBACK;
156 /* Convert module handle to 16-bit */
158 if ( HIWORD( hModule ) )
159 hModule = MapHModuleLS( hModule );
161 /* Call USER signal proc */
163 if ( Callout.UserSignalProc )
165 if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
166 Callout.UserSignalProc( uCode, GetCurrentThreadId(), dwFlags, hModule );
167 else
168 Callout.UserSignalProc( uCode, GetCurrentProcessId(), dwFlags, hModule );
173 /***********************************************************************
174 * PROCESS_Init
176 BOOL PROCESS_Init(void)
178 struct init_process_request *req;
179 PDB *pdb = PROCESS_Current();
181 /* Fill the initial process structure */
182 pdb->exit_code = STILL_ACTIVE;
183 pdb->threads = 1;
184 pdb->running_threads = 1;
185 pdb->ring0_threads = 1;
186 pdb->env_db = &initial_envdb;
187 pdb->group = pdb;
188 pdb->priority = 8; /* Normal */
189 pdb->winver = 0xffff; /* to be determined */
190 initial_envdb.startup_info = &initial_startup;
192 /* Setup the server connection */
193 NtCurrentTeb()->socket = CLIENT_InitServer();
194 if (CLIENT_InitThread()) return FALSE;
196 /* Retrieve startup info from the server */
197 req = get_req_buffer();
198 req->ldt_copy = ldt_copy;
199 req->ldt_flags = ldt_flags_copy;
200 req->ppid = getppid();
201 if (server_call( REQ_INIT_PROCESS )) return FALSE;
202 main_exe_file = req->exe_file;
203 if (req->filename[0]) main_exe_name = strdup( req->filename );
204 initial_startup.dwFlags = req->start_flags;
205 initial_startup.wShowWindow = req->cmd_show;
206 initial_envdb.hStdin = initial_startup.hStdInput = req->hstdin;
207 initial_envdb.hStdout = initial_startup.hStdOutput = req->hstdout;
208 initial_envdb.hStderr = initial_startup.hStdError = req->hstderr;
210 /* Remember TEB selector of initial process for emergency use */
211 SYSLEVEL_EmergencyTeb = NtCurrentTeb()->teb_sel;
213 /* Create the system and process heaps */
214 if (!HEAP_CreateSystemHeap()) return FALSE;
215 pdb->heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
217 /* Copy the parent environment */
218 if (!ENV_BuildEnvironment()) return FALSE;
220 /* Create the SEGPTR heap */
221 if (!(SegptrHeap = HeapCreate( HEAP_WINE_SEGPTR, 0, 0 ))) return FALSE;
223 /* Initialize the critical sections */
224 InitializeCriticalSection( &pdb->crit_section );
225 InitializeCriticalSection( &initial_envdb.section );
227 /* Initialize syslevel handling */
228 SYSLEVEL_Init();
230 return TRUE;
234 /***********************************************************************
235 * load_system_dlls
237 * Load system DLLs into the initial process (and initialize them)
239 static int load_system_dlls(void)
241 char driver[MAX_PATH];
243 PROFILE_GetWineIniString( "Wine", "GraphicsDriver", "x11drv", driver, sizeof(driver) );
244 if (!LoadLibraryA( driver ))
246 MESSAGE( "Could not load graphics driver '%s'\n", driver );
247 return 0;
250 if (!LoadLibraryA("USER32.DLL")) return 0;
252 /* Get pointers to USER routines called by KERNEL */
253 THUNK_InitCallout();
255 /* Call FinalUserInit routine */
256 Callout.FinalUserInit16();
258 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
259 * context of the parent process. Actually, the USER signal proc
260 * doesn't really care about that, but it *does* require that the
261 * startup parameters are correctly set up, so that GetProcessDword
262 * works. Furthermore, before calling the USER signal proc the
263 * 16-bit stack must be set up, which it is only after TASK_Create
264 * in the case of a 16-bit process. Thus, we send the signal here.
266 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
267 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
268 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
269 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
271 return 1;
275 /***********************************************************************
276 * build_command_line
278 * Build the command-line of a process from the argv array.
280 static inline char *build_command_line( char **argv )
282 int len, quote;
283 char *cmdline, *p, **arg;
285 for (arg = argv, len = 0; *arg; arg++) len += strlen(*arg) + 1;
286 if ((quote = (strchr( argv[0], ' ' ) != NULL))) len += 2;
287 if (!(p = cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
288 arg = argv;
289 if (quote)
291 *p++ = '\"';
292 strcpy( p, *arg );
293 p += strlen(p);
294 *p++ = '\"';
295 *p++ = ' ';
296 arg++;
298 while (*arg)
300 strcpy( p, *arg );
301 p += strlen(p);
302 *p++ = ' ';
303 arg++;
305 if (p > cmdline) p--; /* remove last space */
306 *p = 0;
307 return cmdline;
311 /***********************************************************************
312 * start_process
314 * Startup routine of a new process. Runs on the new process stack.
316 static void start_process(void)
318 struct init_process_done_request *req = get_req_buffer();
319 int debugged, console_app;
320 HMODULE16 hModule16;
321 UINT cmdShow = SW_SHOWNORMAL;
322 LPTHREAD_START_ROUTINE entry;
323 PDB *pdb = PROCESS_Current();
324 HMODULE module = pdb->exe_modref->module;
326 /* Increment EXE refcount */
327 pdb->exe_modref->refCount++;
329 /* build command line */
330 if (!(pdb->env_db->cmd_line = build_command_line( main_exe_argv ))) goto error;
332 /* Retrieve entry point address */
333 entry = (LPTHREAD_START_ROUTINE)RVA_PTR( module, OptionalHeader.AddressOfEntryPoint );
334 console_app = (PE_HEADER(module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
336 if (console_app) pdb->flags |= PDB32_CONSOLE_PROC;
338 /* Signal the parent process to continue */
339 req->module = (void *)module;
340 req->entry = entry;
341 req->gui = !console_app;
342 server_call( REQ_INIT_PROCESS_DONE );
343 debugged = req->debugged;
345 /* Install signal handlers; this cannot be done before, since we cannot
346 * send exceptions to the debugger before the create process event that
347 * is sent by REQ_INIT_PROCESS_DONE */
348 if (!SIGNAL_Init()) goto error;
350 /* Load KERNEL (necessary for TASK_Create) */
351 if (!LoadLibraryA( "KERNEL32" )) goto error;
353 /* Create 16-bit dummy module */
354 if ((hModule16 = MODULE_CreateDummyModule( pdb->exe_modref->filename, module )) < 32)
355 ExitProcess( hModule16 );
357 if (pdb->env_db->startup_info->dwFlags & STARTF_USESHOWWINDOW)
358 cmdShow = pdb->env_db->startup_info->wShowWindow;
359 if (!TASK_Create( (NE_MODULE *)GlobalLock16( hModule16 ), cmdShow,
360 NtCurrentTeb(), NULL, 0 ))
361 goto error;
363 /* Load the system dlls */
364 if (!load_system_dlls()) goto error;
366 EnterCriticalSection( &pdb->crit_section );
367 PE_InitTls();
368 MODULE_DllProcessAttach( pdb->exe_modref, (LPVOID)1 );
369 LeaveCriticalSection( &pdb->crit_section );
371 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
372 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
374 TRACE_(relay)( "Starting Win32 process (entryproc=%p)\n", entry );
375 if (debugged) DbgBreakPoint();
376 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
377 * Dunno about other OSs */
378 ExitThread( entry(NULL) );
380 error:
381 ExitProcess( GetLastError() );
385 /***********************************************************************
386 * PROCESS_Start
388 * Startup routine of a new Win32 process once the main module has been loaded.
390 static void PROCESS_Start( HMODULE main_module, LPCSTR filename ) WINE_NORETURN;
391 static void PROCESS_Start( HMODULE main_module, LPCSTR filename )
393 /* load main module */
394 if (PE_HEADER(main_module)->FileHeader.Characteristics & IMAGE_FILE_DLL)
395 ExitProcess( ERROR_BAD_EXE_FORMAT );
397 /* Create 32-bit MODREF */
398 if (!PE_CreateModule( main_module, filename, 0, FALSE ))
399 ExitProcess( GetLastError() );
401 /* allocate main thread stack */
402 if (!THREAD_InitStack( NtCurrentTeb(),
403 PE_HEADER(main_module)->OptionalHeader.SizeOfStackReserve, TRUE ))
404 ExitProcess( GetLastError() );
406 /* switch to the new stack */
407 SYSDEPS_SwitchToThreadStack( start_process );
411 /***********************************************************************
412 * PROCESS_InitWine
414 * Wine initialisation: load and start the main exe file.
416 void PROCESS_InitWine( int argc, char *argv[] )
418 DWORD type;
420 /* Initialize everything */
421 if (!MAIN_MainInit( argv )) exit(1);
423 main_exe_argv = ++argv; /* remove argv[0] (wine itself) */
425 if (!main_exe_name)
427 char buffer[MAX_PATH];
428 if (!argv[0]) OPTIONS_Usage();
430 /* open the exe file */
431 if (!SearchPathA( NULL, argv[0], ".exe", sizeof(buffer), buffer, NULL ) &&
432 !SearchPathA( NULL, argv[0], NULL, sizeof(buffer), buffer, NULL ))
434 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
435 goto error;
437 if (!(main_exe_name = strdup(buffer)))
439 MESSAGE( "%s: out of memory\n", argv0 );
440 ExitProcess(1);
444 if (main_exe_file == INVALID_HANDLE_VALUE)
446 if ((main_exe_file = CreateFileA( main_exe_name, GENERIC_READ, FILE_SHARE_READ,
447 NULL, OPEN_EXISTING, 0, -1 )) == INVALID_HANDLE_VALUE)
449 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
450 goto error;
454 if (!MODULE_GetBinaryType( main_exe_file, main_exe_name, &type ))
456 MESSAGE( "%s: unrecognized executable '%s'\n", argv0, main_exe_name );
457 goto error;
460 switch (type)
462 case SCS_32BIT_BINARY:
464 HMODULE main_module = PE_LoadImage( main_exe_file, main_exe_name );
465 if (main_module) PROCESS_Start( main_module, main_exe_name );
467 break;
469 case SCS_WOW_BINARY:
471 HMODULE main_module;
472 LPCSTR filename;
473 /* create 32-bit module for main exe */
474 if (!(main_module = BUILTIN32_LoadExeModule( &filename ))) goto error;
475 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
476 PROCESS_Current()->flags |= PDB32_WIN16_PROC;
477 SYSLEVEL_EnterWin16Lock();
478 PROCESS_Start( main_module, filename );
480 break;
482 case SCS_DOS_BINARY:
483 FIXME( "DOS binaries support is broken at the moment; feel free to fix it...\n" );
484 SetLastError( ERROR_BAD_FORMAT );
485 break;
487 case SCS_PIF_BINARY:
488 case SCS_POSIX_BINARY:
489 case SCS_OS216_BINARY:
490 default:
491 MESSAGE( "%s: unrecognized executable '%s'\n", argv0, main_exe_name );
492 SetLastError( ERROR_BAD_FORMAT );
493 break;
495 error:
496 ExitProcess( GetLastError() );
500 /***********************************************************************
501 * PROCESS_InitWinelib
503 * Initialisation of a new Winelib process.
505 void PROCESS_InitWinelib( int argc, char *argv[] )
507 HMODULE main_module;
508 LPCSTR filename;
510 if (!MAIN_MainInit( argv )) exit(1);
512 main_exe_argv = argv;
514 /* create 32-bit module for main exe */
515 if (!(main_module = BUILTIN32_LoadExeModule( &filename ))) ExitProcess( GetLastError() );
517 PROCESS_Start( main_module, filename );
521 /***********************************************************************
522 * build_argv
524 * Build an argv array from a command-line.
525 * The command-line is modified to insert nulls.
526 * 'reserved' is the number of args to reserve before the first one.
528 static char **build_argv( char *cmdline, int reserved )
530 char **argv;
531 int count = reserved + 1;
532 char *p = cmdline;
534 /* if first word is quoted store it as a single arg */
535 if (*cmdline == '\"')
537 if ((p = strchr( cmdline + 1, '\"' )))
539 p++;
540 count++;
542 else p = cmdline;
544 while (*p)
546 while (*p && isspace(*p)) p++;
547 if (!*p) break;
548 count++;
549 while (*p && !isspace(*p)) p++;
552 if ((argv = malloc( count * sizeof(*argv) )))
554 char **argvptr = argv + reserved;
555 p = cmdline;
556 if (*cmdline == '\"')
558 if ((p = strchr( cmdline + 1, '\"' )))
560 *argvptr++ = cmdline + 1;
561 *p++ = 0;
563 else p = cmdline;
565 while (*p)
567 while (*p && isspace(*p)) *p++ = 0;
568 if (!*p) break;
569 *argvptr++ = p;
570 while (*p && !isspace(*p)) p++;
572 *argvptr = 0;
574 return argv;
578 /***********************************************************************
579 * build_envp
581 * Build the environment of a new child process.
583 static char **build_envp( const char *env )
585 const char *p;
586 char **envp;
587 int count;
589 for (p = env, count = 0; *p; count++) p += strlen(p) + 1;
590 count += 3;
591 if ((envp = malloc( count * sizeof(*envp) )))
593 extern char **environ;
594 char **envptr = envp;
595 char **unixptr = environ;
596 /* first put PATH, HOME and WINEPREFIX from the unix env */
597 for (unixptr = environ; unixptr && *unixptr; unixptr++)
598 if (!memcmp( *unixptr, "PATH=", 5 ) ||
599 !memcmp( *unixptr, "HOME=", 5 ) ||
600 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
601 /* now put the Windows environment strings */
602 for (p = env; *p; p += strlen(p) + 1)
604 if (memcmp( p, "PATH=", 5 ) &&
605 memcmp( p, "HOME=", 5 ) &&
606 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
608 *envptr = 0;
610 return envp;
614 /***********************************************************************
615 * find_wine_binary
617 * Locate the Wine binary to exec for a new Win32 process.
619 static void exec_wine_binary( char **argv, char **envp )
621 const char *path, *pos, *ptr;
623 /* first try bin directory */
624 argv[0] = BINDIR "/wine";
625 execve( argv[0], argv, envp );
627 /* now try the path of argv0 of the current binary */
628 if (!(argv[0] = malloc( strlen(argv0) + 6 ))) return;
629 if ((ptr = strrchr( argv0, '/' )))
631 memcpy( argv[0], argv0, ptr - argv0 );
632 strcpy( argv[0] + (ptr - argv0), "/wine" );
633 execve( argv[0], argv, envp );
635 free( argv[0] );
637 /* now search in the Unix path */
638 if ((path = getenv( "PATH" )))
640 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
641 pos = path;
642 for (;;)
644 while (*pos == ':') pos++;
645 if (!*pos) break;
646 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
647 memcpy( argv[0], pos, ptr - pos );
648 strcpy( argv[0] + (ptr - pos), "/wine" );
649 execve( argv[0], argv, envp );
650 pos = ptr;
653 free( argv[0] );
655 /* finally try the current directory */
656 argv[0] = "./wine";
657 execve( argv[0], argv, envp );
661 /***********************************************************************
662 * fork_and_exec
664 * Fork and exec a new Unix process, checking for errors.
666 static int fork_and_exec( const char *filename, const char *cmdline, const char *env )
668 int fd[2];
669 int pid, err;
671 if (pipe(fd) == -1)
673 FILE_SetDosError();
674 return -1;
676 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
677 if (!(pid = fork())) /* child */
679 char **argv = build_argv( (char *)cmdline, filename ? 0 : 2 );
680 char **envp = build_envp( env );
681 close( fd[0] );
682 if (argv && envp)
684 if (!filename)
686 argv[1] = "--";
687 exec_wine_binary( argv, envp );
689 else execve( filename, argv, envp );
691 err = errno;
692 write( fd[1], &err, sizeof(err) );
693 _exit(1);
695 close( fd[1] );
696 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
698 errno = err;
699 pid = -1;
701 if (pid == -1) FILE_SetDosError();
702 close( fd[0] );
703 return pid;
707 /***********************************************************************
708 * PROCESS_Create
710 * Create a new process. If hFile is a valid handle we have an exe
711 * file, and we exec a new copy of wine to load it; otherwise we
712 * simply exec the specified filename as a Unix process.
714 BOOL PROCESS_Create( HFILE hFile, LPCSTR filename, LPCSTR cmd_line, LPCSTR env,
715 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
716 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
717 LPPROCESS_INFORMATION info )
719 int pid;
720 const char *unixfilename = NULL;
721 DOS_FULL_NAME full_name;
722 HANDLE load_done_evt = -1;
723 struct new_process_request *req = get_req_buffer();
724 struct wait_process_request *wait_req = get_req_buffer();
726 info->hThread = info->hProcess = INVALID_HANDLE_VALUE;
728 /* create the process on the server side */
730 req->inherit_all = inherit;
731 req->create_flags = flags;
732 req->start_flags = startup->dwFlags;
733 req->exe_file = hFile;
734 if (startup->dwFlags & STARTF_USESTDHANDLES)
736 req->hstdin = startup->hStdInput;
737 req->hstdout = startup->hStdOutput;
738 req->hstderr = startup->hStdError;
740 else
742 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
743 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
744 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
746 req->cmd_show = startup->wShowWindow;
747 req->alloc_fd = 0;
749 if (hFile == -1) /* unix process */
751 unixfilename = filename;
752 if (DOSFS_GetFullName( filename, TRUE, &full_name )) unixfilename = full_name.long_name;
753 req->filename[0] = 0;
755 else /* new wine process */
757 if (!GetFullPathNameA( filename, server_remaining(req->filename), req->filename, NULL ))
758 lstrcpynA( req->filename, filename, server_remaining(req->filename) );
760 if (server_call( REQ_NEW_PROCESS )) return FALSE;
762 /* fork and execute */
764 pid = fork_and_exec( unixfilename, cmd_line, env ? env : GetEnvironmentStringsA() );
766 wait_req->cancel = (pid == -1);
767 wait_req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
768 wait_req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
769 wait_req->timeout = 2000;
770 if (server_call( REQ_WAIT_PROCESS ) || (pid == -1)) goto error;
771 info->dwProcessId = (DWORD)wait_req->pid;
772 info->dwThreadId = (DWORD)wait_req->tid;
773 info->hProcess = wait_req->phandle;
774 info->hThread = wait_req->thandle;
775 load_done_evt = wait_req->event;
777 /* Wait until process is initialized (or initialization failed) */
778 if (load_done_evt != -1)
780 DWORD res;
781 HANDLE handles[2];
783 handles[0] = info->hProcess;
784 handles[1] = load_done_evt;
785 res = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
786 CloseHandle( load_done_evt );
787 if (res == STATUS_WAIT_0) /* the process died */
789 DWORD exitcode;
790 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
791 CloseHandle( info->hThread );
792 CloseHandle( info->hProcess );
793 return FALSE;
796 return TRUE;
798 error:
799 if (load_done_evt != -1) CloseHandle( load_done_evt );
800 if (info->hThread != INVALID_HANDLE_VALUE) CloseHandle( info->hThread );
801 if (info->hProcess != INVALID_HANDLE_VALUE) CloseHandle( info->hProcess );
802 return FALSE;
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 /* send the exit code to the server */
815 req->handle = GetCurrentProcess();
816 req->exit_code = status;
817 server_call( REQ_TERMINATE_PROCESS );
818 exit( status );
821 /***********************************************************************
822 * ExitProcess16 (KERNEL.466)
824 void WINAPI ExitProcess16( WORD status )
826 SYSLEVEL_ReleaseWin16Lock();
827 ExitProcess( status );
830 /******************************************************************************
831 * TerminateProcess (KERNEL32.684)
833 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
835 BOOL ret;
836 struct terminate_process_request *req = get_req_buffer();
837 req->handle = handle;
838 req->exit_code = exit_code;
839 if ((ret = !server_call( REQ_TERMINATE_PROCESS )) && req->self) exit( exit_code );
840 return ret;
844 /***********************************************************************
845 * GetProcessDword (KERNEL32.18) (KERNEL.485)
846 * 'Of course you cannot directly access Windows internal structures'
848 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
850 PDB *process = PROCESS_IdToPDB( dwProcessID );
851 TDB *pTask;
852 DWORD x, y;
854 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
855 if ( !process )
857 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
858 return 0;
861 switch ( offset )
863 case GPD_APP_COMPAT_FLAGS:
864 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
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( GetCurrentTask() );
872 return pTask? pTask->hInstance : 0;
874 case GPD_WINDOWS_VERSION:
875 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
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 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 )
937 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
938 return;
941 switch ( offset )
943 case GPD_APP_COMPAT_FLAGS:
944 case GPD_LOAD_DONE_EVENT:
945 case GPD_HINSTANCE16:
946 case GPD_WINDOWS_VERSION:
947 case GPD_THDB:
948 case GPD_PDB:
949 case GPD_STARTF_SHELLDATA:
950 case GPD_STARTF_HOTKEY:
951 case GPD_STARTF_SHOWWINDOW:
952 case GPD_STARTF_SIZE:
953 case GPD_STARTF_POSITION:
954 case GPD_STARTF_FLAGS:
955 case GPD_PARENT:
956 case GPD_FLAGS:
957 ERR_(win32)("Not allowed to modify offset %d\n", offset );
958 break;
960 case GPD_USERDATA:
961 process->process_dword = value;
962 break;
964 default:
965 ERR_(win32)("Unknown offset %d\n", offset );
966 break;
971 /*********************************************************************
972 * OpenProcess (KERNEL32.543)
974 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
976 HANDLE ret = 0;
977 struct open_process_request *req = get_req_buffer();
979 req->pid = (void *)id;
980 req->access = access;
981 req->inherit = inherit;
982 if (!server_call( REQ_OPEN_PROCESS )) ret = req->handle;
983 return ret;
986 /*********************************************************************
987 * MapProcessHandle (KERNEL.483)
989 DWORD WINAPI MapProcessHandle( HANDLE handle )
991 DWORD ret = 0;
992 struct get_process_info_request *req = get_req_buffer();
993 req->handle = handle;
994 if (!server_call( REQ_GET_PROCESS_INFO )) ret = (DWORD)req->pid;
995 return ret;
998 /***********************************************************************
999 * GetThreadLocale (KERNEL32.295)
1001 LCID WINAPI GetThreadLocale(void)
1003 return PROCESS_Current()->locale;
1007 /***********************************************************************
1008 * SetPriorityClass (KERNEL32.503)
1010 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1012 struct set_process_info_request *req = get_req_buffer();
1013 req->handle = hprocess;
1014 req->priority = priorityclass;
1015 req->mask = SET_PROCESS_INFO_PRIORITY;
1016 return !server_call( REQ_SET_PROCESS_INFO );
1020 /***********************************************************************
1021 * GetPriorityClass (KERNEL32.250)
1023 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1025 DWORD ret = 0;
1026 struct get_process_info_request *req = get_req_buffer();
1027 req->handle = hprocess;
1028 if (!server_call( REQ_GET_PROCESS_INFO )) ret = req->priority;
1029 return ret;
1033 /***********************************************************************
1034 * SetProcessAffinityMask (KERNEL32.662)
1036 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1038 struct set_process_info_request *req = get_req_buffer();
1039 req->handle = hProcess;
1040 req->affinity = affmask;
1041 req->mask = SET_PROCESS_INFO_AFFINITY;
1042 return !server_call( REQ_SET_PROCESS_INFO );
1045 /**********************************************************************
1046 * GetProcessAffinityMask (KERNEL32.373)
1048 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1049 LPDWORD lpProcessAffinityMask,
1050 LPDWORD lpSystemAffinityMask )
1052 BOOL ret = FALSE;
1053 struct get_process_info_request *req = get_req_buffer();
1054 req->handle = hProcess;
1055 if (!server_call( REQ_GET_PROCESS_INFO ))
1057 if (lpProcessAffinityMask) *lpProcessAffinityMask = req->process_affinity;
1058 if (lpSystemAffinityMask) *lpSystemAffinityMask = req->system_affinity;
1059 ret = TRUE;
1061 return ret;
1065 /***********************************************************************
1066 * GetStdHandle (KERNEL32.276)
1068 HANDLE WINAPI GetStdHandle( DWORD std_handle )
1070 PDB *pdb = PROCESS_Current();
1072 switch(std_handle)
1074 case STD_INPUT_HANDLE: return pdb->env_db->hStdin;
1075 case STD_OUTPUT_HANDLE: return pdb->env_db->hStdout;
1076 case STD_ERROR_HANDLE: return pdb->env_db->hStderr;
1078 SetLastError( ERROR_INVALID_PARAMETER );
1079 return INVALID_HANDLE_VALUE;
1083 /***********************************************************************
1084 * SetStdHandle (KERNEL32.506)
1086 BOOL WINAPI SetStdHandle( DWORD std_handle, HANDLE handle )
1088 PDB *pdb = PROCESS_Current();
1089 /* FIXME: should we close the previous handle? */
1090 switch(std_handle)
1092 case STD_INPUT_HANDLE:
1093 pdb->env_db->hStdin = handle;
1094 return TRUE;
1095 case STD_OUTPUT_HANDLE:
1096 pdb->env_db->hStdout = handle;
1097 return TRUE;
1098 case STD_ERROR_HANDLE:
1099 pdb->env_db->hStderr = handle;
1100 return TRUE;
1102 SetLastError( ERROR_INVALID_PARAMETER );
1103 return FALSE;
1106 /***********************************************************************
1107 * GetProcessVersion (KERNEL32)
1109 DWORD WINAPI GetProcessVersion( DWORD processid )
1111 TDB *pTask;
1112 PDB *pdb = PROCESS_IdToPDB( processid );
1114 if (!pdb) return 0;
1115 if (!(pTask = (TDB *)GlobalLock16( pdb->task ))) return 0;
1116 return (pTask->version&0xff) | (((pTask->version >>8) & 0xff)<<16);
1119 /***********************************************************************
1120 * GetProcessFlags (KERNEL32)
1122 DWORD WINAPI GetProcessFlags( DWORD processid )
1124 PDB *pdb = PROCESS_IdToPDB( processid );
1125 if (!pdb) return 0;
1126 return pdb->flags;
1129 /***********************************************************************
1130 * SetProcessWorkingSetSize [KERNEL32.662]
1131 * Sets the min/max working set sizes for a specified process.
1133 * PARAMS
1134 * hProcess [I] Handle to the process of interest
1135 * minset [I] Specifies minimum working set size
1136 * maxset [I] Specifies maximum working set size
1138 * RETURNS STD
1140 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1141 DWORD maxset)
1143 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1144 if(( minset == -1) && (maxset == -1)) {
1145 /* Trim the working set to zero */
1146 /* Swap the process out of physical RAM */
1148 return TRUE;
1151 /***********************************************************************
1152 * GetProcessWorkingSetSize (KERNEL32)
1154 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1155 LPDWORD maxset)
1157 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1158 /* 32 MB working set size */
1159 if (minset) *minset = 32*1024*1024;
1160 if (maxset) *maxset = 32*1024*1024;
1161 return TRUE;
1164 /***********************************************************************
1165 * SetProcessShutdownParameters (KERNEL32)
1167 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1168 * Now tracks changes made (but does not act on these changes)
1169 * NOTE: the definition for SHUTDOWN_NORETRY was done on guesswork.
1170 * It really shouldn't be here, but I'll move it when it's been checked!
1172 #define SHUTDOWN_NORETRY 1
1173 static unsigned int shutdown_noretry = 0;
1174 static unsigned int shutdown_priority = 0x280L;
1175 BOOL WINAPI SetProcessShutdownParameters(DWORD level,DWORD flags)
1177 if (flags & SHUTDOWN_NORETRY)
1178 shutdown_noretry = 1;
1179 else
1180 shutdown_noretry = 0;
1181 if (level > 0x100L && level < 0x3FFL)
1182 shutdown_priority = level;
1183 else
1185 ERR("invalid priority level 0x%08lx\n", level);
1186 return FALSE;
1188 return TRUE;
1192 /***********************************************************************
1193 * GetProcessShutdownParameters (KERNEL32)
1196 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel,
1197 LPDWORD lpdwFlags )
1199 (*lpdwLevel) = shutdown_priority;
1200 (*lpdwFlags) = (shutdown_noretry * SHUTDOWN_NORETRY);
1201 return TRUE;
1203 /***********************************************************************
1204 * SetProcessPriorityBoost (KERNEL32)
1206 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1208 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1209 /* Say we can do it. I doubt the program will notice that we don't. */
1210 return TRUE;
1214 /***********************************************************************
1215 * ReadProcessMemory (KERNEL32)
1217 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1218 LPDWORD bytes_read )
1220 struct read_process_memory_request *req = get_req_buffer();
1221 unsigned int offset = (unsigned int)addr % sizeof(int);
1222 unsigned int max = server_remaining( req->data ); /* max length in one request */
1223 unsigned int pos;
1225 if (bytes_read) *bytes_read = size;
1227 /* first time, read total length to check for permissions */
1228 req->handle = process;
1229 req->addr = (char *)addr - offset;
1230 req->len = (size + offset + sizeof(int) - 1) / sizeof(int);
1231 if (server_call( REQ_READ_PROCESS_MEMORY )) goto error;
1233 if (size <= max - offset)
1235 memcpy( buffer, (char *)req->data + offset, size );
1236 return TRUE;
1239 /* now take care of the remaining data */
1240 memcpy( buffer, (char *)req->data + offset, max - offset );
1241 pos = max - offset;
1242 size -= pos;
1243 while (size)
1245 if (max > size) max = size;
1246 req->handle = process;
1247 req->addr = (char *)addr + pos;
1248 req->len = (max + sizeof(int) - 1) / sizeof(int);
1249 if (server_call( REQ_READ_PROCESS_MEMORY )) goto error;
1250 memcpy( (char *)buffer + pos, (char *)req->data, max );
1251 size -= max;
1252 pos += max;
1254 return TRUE;
1256 error:
1257 if (bytes_read) *bytes_read = 0;
1258 return FALSE;
1262 /***********************************************************************
1263 * WriteProcessMemory (KERNEL32)
1265 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPVOID buffer, DWORD size,
1266 LPDWORD bytes_written )
1268 unsigned int first_offset, last_offset;
1269 struct write_process_memory_request *req = get_req_buffer();
1270 unsigned int max = server_remaining( req->data ); /* max length in one request */
1271 unsigned int pos, last_mask;
1273 if (!size)
1275 SetLastError( ERROR_INVALID_PARAMETER );
1276 return FALSE;
1278 if (bytes_written) *bytes_written = size;
1280 /* compute the mask for the first int */
1281 req->first_mask = ~0;
1282 first_offset = (unsigned int)addr % sizeof(int);
1283 memset( &req->first_mask, 0, first_offset );
1285 /* compute the mask for the last int */
1286 last_offset = (size + first_offset) % sizeof(int);
1287 last_mask = 0;
1288 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1290 req->handle = process;
1291 req->addr = (char *)addr - first_offset;
1292 /* for the first request, use the total length */
1293 req->len = (size + first_offset + sizeof(int) - 1) / sizeof(int);
1295 if (size + first_offset < max) /* we can do it in one round */
1297 memcpy( (char *)req->data + first_offset, buffer, size );
1298 req->last_mask = last_mask;
1299 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1300 return TRUE;
1303 /* needs multiple server calls */
1305 memcpy( (char *)req->data + first_offset, buffer, max - first_offset );
1306 req->last_mask = ~0;
1307 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1308 pos = max - first_offset;
1309 size -= pos;
1310 while (size)
1312 if (size <= max) /* last one */
1314 req->last_mask = last_mask;
1315 max = size;
1317 req->handle = process;
1318 req->addr = (char *)addr + pos;
1319 req->len = (max + sizeof(int) - 1) / sizeof(int);
1320 req->first_mask = ~0;
1321 memcpy( req->data, (char *) buffer + pos, max );
1322 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1323 pos += max;
1324 size -= max;
1326 return TRUE;
1328 error:
1329 if (bytes_written) *bytes_written = 0;
1330 return FALSE;
1335 /***********************************************************************
1336 * RegisterServiceProcess (KERNEL, KERNEL32)
1338 * A service process calls this function to ensure that it continues to run
1339 * even after a user logged off.
1341 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1343 /* I don't think that Wine needs to do anything in that function */
1344 return 1; /* success */
1347 /***********************************************************************
1348 * GetExitCodeProcess [KERNEL32.325]
1350 * Gets termination status of specified process
1352 * RETURNS
1353 * Success: TRUE
1354 * Failure: FALSE
1356 BOOL WINAPI GetExitCodeProcess(
1357 HANDLE hProcess, /* [I] handle to the process */
1358 LPDWORD lpExitCode) /* [O] address to receive termination status */
1360 BOOL ret = FALSE;
1361 struct get_process_info_request *req = get_req_buffer();
1362 req->handle = hProcess;
1363 if (!server_call( REQ_GET_PROCESS_INFO ))
1365 if (lpExitCode) *lpExitCode = req->exit_code;
1366 ret = TRUE;
1368 return ret;
1372 /***********************************************************************
1373 * SetErrorMode (KERNEL32.486)
1375 UINT WINAPI SetErrorMode( UINT mode )
1377 UINT old = PROCESS_Current()->error_mode;
1378 PROCESS_Current()->error_mode = mode;
1379 return old;
1382 /***********************************************************************
1383 * GetCurrentProcess (KERNEL32.198)
1385 #undef GetCurrentProcess
1386 HANDLE WINAPI GetCurrentProcess(void)
1388 return 0xffffffff;