Moved stack switch handling (large stack) to sysdeps.c
[wine.git] / scheduler / process.c
blob861c0440e0256fac105a164e5ed761e853667d2a
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 /* Initialize signal handling */
211 if (!SIGNAL_Init()) return FALSE;
213 /* Remember TEB selector of initial process for emergency use */
214 SYSLEVEL_EmergencyTeb = NtCurrentTeb()->teb_sel;
216 /* Create the system and process heaps */
217 if (!HEAP_CreateSystemHeap()) return FALSE;
218 pdb->heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
220 /* Copy the parent environment */
221 if (!ENV_BuildEnvironment()) return FALSE;
223 /* Create the SEGPTR heap */
224 if (!(SegptrHeap = HeapCreate( HEAP_WINE_SEGPTR, 0, 0 ))) return FALSE;
226 /* Initialize the critical sections */
227 InitializeCriticalSection( &pdb->crit_section );
228 InitializeCriticalSection( &initial_envdb.section );
230 /* Initialize syslevel handling */
231 SYSLEVEL_Init();
233 return TRUE;
237 /***********************************************************************
238 * load_system_dlls
240 * Load system DLLs into the initial process (and initialize them)
242 static int load_system_dlls(void)
244 char driver[MAX_PATH];
246 PROFILE_GetWineIniString( "Wine", "GraphicsDriver", "x11drv", driver, sizeof(driver) );
247 if (!LoadLibraryA( driver ))
249 MESSAGE( "Could not load graphics driver '%s'\n", driver );
250 return 0;
253 if (!LoadLibraryA("USER32.DLL")) return 0;
255 /* Get pointers to USER routines called by KERNEL */
256 THUNK_InitCallout();
258 /* Call FinalUserInit routine */
259 Callout.FinalUserInit16();
261 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
262 * context of the parent process. Actually, the USER signal proc
263 * doesn't really care about that, but it *does* require that the
264 * startup parameters are correctly set up, so that GetProcessDword
265 * works. Furthermore, before calling the USER signal proc the
266 * 16-bit stack must be set up, which it is only after TASK_Create
267 * in the case of a 16-bit process. Thus, we send the signal here.
269 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
270 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
271 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
272 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
274 return 1;
278 /***********************************************************************
279 * build_command_line
281 * Build the command-line of a process from the argv array.
283 static inline char *build_command_line( char **argv )
285 int len, quote;
286 char *cmdline, *p, **arg;
288 for (arg = argv, len = 0; *arg; arg++) len += strlen(*arg) + 1;
289 if ((quote = (strchr( argv[0], ' ' ) != NULL))) len += 2;
290 if (!(p = cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
291 arg = argv;
292 if (quote)
294 *p++ = '\"';
295 strcpy( p, *arg );
296 p += strlen(p);
297 *p++ = '\"';
298 *p++ = ' ';
299 arg++;
301 while (*arg)
303 strcpy( p, *arg );
304 p += strlen(p);
305 *p++ = ' ';
306 arg++;
308 if (p > cmdline) p--; /* remove last space */
309 *p = 0;
310 return cmdline;
314 /***********************************************************************
315 * start_process
317 * Startup routine of a new process. Runs on the new process stack.
319 static void start_process(void)
321 __TRY
323 struct init_process_done_request *req = get_req_buffer();
324 int debugged, console_app;
325 HMODULE16 hModule16;
326 UINT cmdShow = SW_SHOWNORMAL;
327 LPTHREAD_START_ROUTINE entry;
328 PDB *pdb = PROCESS_Current();
329 HMODULE module = pdb->exe_modref->module;
331 /* Increment EXE refcount */
332 pdb->exe_modref->refCount++;
334 /* build command line */
335 if (!(pdb->env_db->cmd_line = build_command_line( main_exe_argv ))) goto error;
337 /* Retrieve entry point address */
338 entry = (LPTHREAD_START_ROUTINE)RVA_PTR( module, OptionalHeader.AddressOfEntryPoint );
339 console_app = (PE_HEADER(module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
341 if (console_app) pdb->flags |= PDB32_CONSOLE_PROC;
343 /* Signal the parent process to continue */
344 req->module = (void *)module;
345 req->entry = entry;
346 req->gui = !console_app;
347 server_call( REQ_INIT_PROCESS_DONE );
348 debugged = req->debugged;
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() );
384 __EXCEPT(UnhandledExceptionFilter)
386 TerminateThread( GetCurrentThread(), GetExceptionCode() );
388 __ENDTRY
392 /***********************************************************************
393 * PROCESS_Start
395 * Startup routine of a new Win32 process once the main module has been loaded.
397 static void PROCESS_Start( HMODULE main_module, LPCSTR filename ) WINE_NORETURN;
398 static void PROCESS_Start( HMODULE main_module, LPCSTR filename )
400 /* load main module */
401 if (PE_HEADER(main_module)->FileHeader.Characteristics & IMAGE_FILE_DLL)
402 ExitProcess( ERROR_BAD_EXE_FORMAT );
404 /* Create 32-bit MODREF */
405 if (!PE_CreateModule( main_module, filename, 0, FALSE ))
406 ExitProcess( GetLastError() );
408 /* allocate main thread stack */
409 if (!THREAD_InitStack( NtCurrentTeb(),
410 PE_HEADER(main_module)->OptionalHeader.SizeOfStackReserve, TRUE ))
411 ExitProcess( GetLastError() );
413 SIGNAL_Init(); /* reinitialize signal stack */
415 /* switch to the new stack */
416 SYSDEPS_SwitchToThreadStack( start_process );
420 /***********************************************************************
421 * PROCESS_InitWine
423 * Wine initialisation: load and start the main exe file.
425 void PROCESS_InitWine( int argc, char *argv[] )
427 DWORD type;
429 /* Initialize everything */
430 if (!MAIN_MainInit( argv )) exit(1);
432 main_exe_argv = ++argv; /* remove argv[0] (wine itself) */
434 if (!main_exe_name)
436 char buffer[MAX_PATH];
437 if (!argv[0]) OPTIONS_Usage();
439 /* open the exe file */
440 if (!SearchPathA( NULL, argv[0], ".exe", sizeof(buffer), buffer, NULL ) &&
441 !SearchPathA( NULL, argv[0], NULL, sizeof(buffer), buffer, NULL ))
443 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
444 goto error;
446 if (!(main_exe_name = strdup(buffer)))
448 MESSAGE( "%s: out of memory\n", argv0 );
449 ExitProcess(1);
453 if (main_exe_file == INVALID_HANDLE_VALUE)
455 if ((main_exe_file = CreateFileA( main_exe_name, GENERIC_READ, FILE_SHARE_READ,
456 NULL, OPEN_EXISTING, 0, -1 )) == INVALID_HANDLE_VALUE)
458 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
459 goto error;
463 if (!MODULE_GetBinaryType( main_exe_file, main_exe_name, &type ))
465 MESSAGE( "%s: unrecognized executable '%s'\n", argv0, main_exe_name );
466 goto error;
469 switch (type)
471 case SCS_32BIT_BINARY:
473 HMODULE main_module = PE_LoadImage( main_exe_file, main_exe_name );
474 if (main_module) PROCESS_Start( main_module, main_exe_name );
476 break;
478 case SCS_WOW_BINARY:
480 HMODULE main_module;
481 LPCSTR filename;
482 /* create 32-bit module for main exe */
483 if (!(main_module = BUILTIN32_LoadExeModule( &filename ))) goto error;
484 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
485 PROCESS_Current()->flags |= PDB32_WIN16_PROC;
486 SYSLEVEL_EnterWin16Lock();
487 PROCESS_Start( main_module, filename );
489 break;
491 case SCS_DOS_BINARY:
492 FIXME( "DOS binaries support is broken at the moment; feel free to fix it...\n" );
493 SetLastError( ERROR_BAD_FORMAT );
494 break;
496 case SCS_PIF_BINARY:
497 case SCS_POSIX_BINARY:
498 case SCS_OS216_BINARY:
499 default:
500 MESSAGE( "%s: unrecognized executable '%s'\n", argv0, main_exe_name );
501 SetLastError( ERROR_BAD_FORMAT );
502 break;
504 error:
505 ExitProcess( GetLastError() );
509 /***********************************************************************
510 * PROCESS_InitWinelib
512 * Initialisation of a new Winelib process.
514 void PROCESS_InitWinelib( int argc, char *argv[] )
516 HMODULE main_module;
517 LPCSTR filename;
519 if (!MAIN_MainInit( argv )) exit(1);
521 main_exe_argv = argv;
523 /* create 32-bit module for main exe */
524 if (!(main_module = BUILTIN32_LoadExeModule( &filename ))) ExitProcess( GetLastError() );
526 PROCESS_Start( main_module, filename );
530 /***********************************************************************
531 * build_argv
533 * Build an argv array from a command-line.
534 * The command-line is modified to insert nulls.
535 * 'reserved' is the number of args to reserve before the first one.
537 static char **build_argv( char *cmdline, int reserved )
539 char **argv;
540 int count = reserved + 1;
541 char *p = cmdline;
543 /* if first word is quoted store it as a single arg */
544 if (*cmdline == '\"')
546 if ((p = strchr( cmdline + 1, '\"' )))
548 p++;
549 count++;
551 else p = cmdline;
553 while (*p)
555 while (*p && isspace(*p)) p++;
556 if (!*p) break;
557 count++;
558 while (*p && !isspace(*p)) p++;
561 if ((argv = malloc( count * sizeof(*argv) )))
563 char **argvptr = argv + reserved;
564 p = cmdline;
565 if (*cmdline == '\"')
567 if ((p = strchr( cmdline + 1, '\"' )))
569 *argvptr++ = cmdline + 1;
570 *p++ = 0;
572 else p = cmdline;
574 while (*p)
576 while (*p && isspace(*p)) *p++ = 0;
577 if (!*p) break;
578 *argvptr++ = p;
579 while (*p && !isspace(*p)) p++;
581 *argvptr = 0;
583 return argv;
587 /***********************************************************************
588 * build_envp
590 * Build the environment of a new child process.
592 static char **build_envp( const char *env )
594 const char *p;
595 char **envp;
596 int count;
598 for (p = env, count = 0; *p; count++) p += strlen(p) + 1;
599 count += 3;
600 if ((envp = malloc( count * sizeof(*envp) )))
602 extern char **environ;
603 char **envptr = envp;
604 char **unixptr = environ;
605 /* first put PATH, HOME and WINEPREFIX from the unix env */
606 for (unixptr = environ; unixptr && *unixptr; unixptr++)
607 if (!memcmp( *unixptr, "PATH=", 5 ) ||
608 !memcmp( *unixptr, "HOME=", 5 ) ||
609 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
610 /* now put the Windows environment strings */
611 for (p = env; *p; p += strlen(p) + 1)
613 if (memcmp( p, "PATH=", 5 ) &&
614 memcmp( p, "HOME=", 5 ) &&
615 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
617 *envptr = 0;
619 return envp;
623 /***********************************************************************
624 * find_wine_binary
626 * Locate the Wine binary to exec for a new Win32 process.
628 static void exec_wine_binary( char **argv, char **envp )
630 const char *path, *pos, *ptr;
632 /* first try bin directory */
633 argv[0] = BINDIR "/wine";
634 execve( argv[0], argv, envp );
636 /* now try the path of argv0 of the current binary */
637 if (!(argv[0] = malloc( strlen(argv0) + 6 ))) return;
638 if ((ptr = strrchr( argv0, '/' )))
640 memcpy( argv[0], argv0, ptr - argv0 );
641 strcpy( argv[0] + (ptr - argv0), "/wine" );
642 execve( argv[0], argv, envp );
644 free( argv[0] );
646 /* now search in the Unix path */
647 if ((path = getenv( "PATH" )))
649 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
650 pos = path;
651 for (;;)
653 while (*pos == ':') pos++;
654 if (!*pos) break;
655 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
656 memcpy( argv[0], pos, ptr - pos );
657 strcpy( argv[0] + (ptr - pos), "/wine" );
658 execve( argv[0], argv, envp );
659 pos = ptr;
662 free( argv[0] );
664 /* finally try the current directory */
665 argv[0] = "./wine";
666 execve( argv[0], argv, envp );
670 /***********************************************************************
671 * fork_and_exec
673 * Fork and exec a new Unix process, checking for errors.
675 static int fork_and_exec( const char *filename, const char *cmdline, const char *env )
677 int fd[2];
678 int pid, err;
680 if (pipe(fd) == -1)
682 FILE_SetDosError();
683 return -1;
685 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
686 if (!(pid = fork())) /* child */
688 char **argv = build_argv( (char *)cmdline, filename ? 0 : 2 );
689 char **envp = build_envp( env );
690 close( fd[0] );
691 if (argv && envp)
693 if (!filename)
695 argv[1] = "--";
696 exec_wine_binary( argv, envp );
698 else execve( filename, argv, envp );
700 err = errno;
701 write( fd[1], &err, sizeof(err) );
702 _exit(1);
704 close( fd[1] );
705 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
707 errno = err;
708 pid = -1;
710 if (pid == -1) FILE_SetDosError();
711 close( fd[0] );
712 return pid;
716 /***********************************************************************
717 * PROCESS_Create
719 * Create a new process. If hFile is a valid handle we have an exe
720 * file, and we exec a new copy of wine to load it; otherwise we
721 * simply exec the specified filename as a Unix process.
723 BOOL PROCESS_Create( HFILE hFile, LPCSTR filename, LPCSTR cmd_line, LPCSTR env,
724 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
725 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
726 LPPROCESS_INFORMATION info )
728 int pid;
729 const char *unixfilename = NULL;
730 DOS_FULL_NAME full_name;
731 HANDLE load_done_evt = -1;
732 struct new_process_request *req = get_req_buffer();
733 struct wait_process_request *wait_req = get_req_buffer();
735 info->hThread = info->hProcess = INVALID_HANDLE_VALUE;
737 /* create the process on the server side */
739 req->inherit_all = inherit;
740 req->create_flags = flags;
741 req->start_flags = startup->dwFlags;
742 req->exe_file = hFile;
743 if (startup->dwFlags & STARTF_USESTDHANDLES)
745 req->hstdin = startup->hStdInput;
746 req->hstdout = startup->hStdOutput;
747 req->hstderr = startup->hStdError;
749 else
751 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
752 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
753 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
755 req->cmd_show = startup->wShowWindow;
756 req->alloc_fd = 0;
758 if (hFile == -1) /* unix process */
760 unixfilename = filename;
761 if (DOSFS_GetFullName( filename, TRUE, &full_name )) unixfilename = full_name.long_name;
762 req->filename[0] = 0;
764 else /* new wine process */
766 if (!GetFullPathNameA( filename, server_remaining(req->filename), req->filename, NULL ))
767 lstrcpynA( req->filename, filename, server_remaining(req->filename) );
769 if (server_call( REQ_NEW_PROCESS )) return FALSE;
771 /* fork and execute */
773 pid = fork_and_exec( unixfilename, cmd_line, env ? env : GetEnvironmentStringsA() );
775 wait_req->cancel = (pid == -1);
776 wait_req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
777 wait_req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
778 wait_req->timeout = 2000;
779 if (server_call( REQ_WAIT_PROCESS ) || (pid == -1)) goto error;
780 info->dwProcessId = (DWORD)wait_req->pid;
781 info->dwThreadId = (DWORD)wait_req->tid;
782 info->hProcess = wait_req->phandle;
783 info->hThread = wait_req->thandle;
784 load_done_evt = wait_req->event;
786 /* Wait until process is initialized (or initialization failed) */
787 if (load_done_evt != -1)
789 DWORD res;
790 HANDLE handles[2];
792 handles[0] = info->hProcess;
793 handles[1] = load_done_evt;
794 res = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
795 CloseHandle( load_done_evt );
796 if (res == STATUS_WAIT_0) /* the process died */
798 DWORD exitcode;
799 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
800 CloseHandle( info->hThread );
801 CloseHandle( info->hProcess );
802 return FALSE;
805 return TRUE;
807 error:
808 if (load_done_evt != -1) CloseHandle( load_done_evt );
809 if (info->hThread != INVALID_HANDLE_VALUE) CloseHandle( info->hThread );
810 if (info->hProcess != INVALID_HANDLE_VALUE) CloseHandle( info->hProcess );
811 return FALSE;
815 /***********************************************************************
816 * ExitProcess (KERNEL32.100)
818 void WINAPI ExitProcess( DWORD status )
820 struct terminate_process_request *req = get_req_buffer();
822 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
823 /* send the exit code to the server */
824 req->handle = GetCurrentProcess();
825 req->exit_code = status;
826 server_call( REQ_TERMINATE_PROCESS );
827 exit( status );
830 /***********************************************************************
831 * ExitProcess16 (KERNEL.466)
833 void WINAPI ExitProcess16( WORD status )
835 SYSLEVEL_ReleaseWin16Lock();
836 ExitProcess( status );
839 /******************************************************************************
840 * TerminateProcess (KERNEL32.684)
842 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
844 BOOL ret;
845 struct terminate_process_request *req = get_req_buffer();
846 req->handle = handle;
847 req->exit_code = exit_code;
848 if ((ret = !server_call( REQ_TERMINATE_PROCESS )) && req->self) exit( exit_code );
849 return ret;
853 /***********************************************************************
854 * GetProcessDword (KERNEL32.18) (KERNEL.485)
855 * 'Of course you cannot directly access Windows internal structures'
857 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
859 PDB *process = PROCESS_IdToPDB( dwProcessID );
860 TDB *pTask;
861 DWORD x, y;
863 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
864 if ( !process )
866 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
867 return 0;
870 switch ( offset )
872 case GPD_APP_COMPAT_FLAGS:
873 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
874 return pTask? pTask->compat_flags : 0;
876 case GPD_LOAD_DONE_EVENT:
877 return process->load_done_evt;
879 case GPD_HINSTANCE16:
880 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
881 return pTask? pTask->hInstance : 0;
883 case GPD_WINDOWS_VERSION:
884 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
885 return pTask? pTask->version : 0;
887 case GPD_THDB:
888 if ( process != PROCESS_Current() ) return 0;
889 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
891 case GPD_PDB:
892 return (DWORD)process;
894 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
895 return process->env_db->startup_info->hStdOutput;
897 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
898 return process->env_db->startup_info->hStdInput;
900 case GPD_STARTF_SHOWWINDOW:
901 return process->env_db->startup_info->wShowWindow;
903 case GPD_STARTF_SIZE:
904 x = process->env_db->startup_info->dwXSize;
905 if ( x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
906 y = process->env_db->startup_info->dwYSize;
907 if ( y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
908 return MAKELONG( x, y );
910 case GPD_STARTF_POSITION:
911 x = process->env_db->startup_info->dwX;
912 if ( x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
913 y = process->env_db->startup_info->dwY;
914 if ( y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
915 return MAKELONG( x, y );
917 case GPD_STARTF_FLAGS:
918 return process->env_db->startup_info->dwFlags;
920 case GPD_PARENT:
921 return 0;
923 case GPD_FLAGS:
924 return process->flags;
926 case GPD_USERDATA:
927 return process->process_dword;
929 default:
930 ERR_(win32)("Unknown offset %d\n", offset );
931 return 0;
935 /***********************************************************************
936 * SetProcessDword (KERNEL.484)
937 * 'Of course you cannot directly access Windows internal structures'
939 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
941 PDB *process = PROCESS_IdToPDB( dwProcessID );
943 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
944 if ( !process )
946 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
947 return;
950 switch ( offset )
952 case GPD_APP_COMPAT_FLAGS:
953 case GPD_LOAD_DONE_EVENT:
954 case GPD_HINSTANCE16:
955 case GPD_WINDOWS_VERSION:
956 case GPD_THDB:
957 case GPD_PDB:
958 case GPD_STARTF_SHELLDATA:
959 case GPD_STARTF_HOTKEY:
960 case GPD_STARTF_SHOWWINDOW:
961 case GPD_STARTF_SIZE:
962 case GPD_STARTF_POSITION:
963 case GPD_STARTF_FLAGS:
964 case GPD_PARENT:
965 case GPD_FLAGS:
966 ERR_(win32)("Not allowed to modify offset %d\n", offset );
967 break;
969 case GPD_USERDATA:
970 process->process_dword = value;
971 break;
973 default:
974 ERR_(win32)("Unknown offset %d\n", offset );
975 break;
980 /*********************************************************************
981 * OpenProcess (KERNEL32.543)
983 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
985 HANDLE ret = 0;
986 struct open_process_request *req = get_req_buffer();
988 req->pid = (void *)id;
989 req->access = access;
990 req->inherit = inherit;
991 if (!server_call( REQ_OPEN_PROCESS )) ret = req->handle;
992 return ret;
995 /*********************************************************************
996 * MapProcessHandle (KERNEL.483)
998 DWORD WINAPI MapProcessHandle( HANDLE handle )
1000 DWORD ret = 0;
1001 struct get_process_info_request *req = get_req_buffer();
1002 req->handle = handle;
1003 if (!server_call( REQ_GET_PROCESS_INFO )) ret = (DWORD)req->pid;
1004 return ret;
1007 /***********************************************************************
1008 * GetThreadLocale (KERNEL32.295)
1010 LCID WINAPI GetThreadLocale(void)
1012 return PROCESS_Current()->locale;
1016 /***********************************************************************
1017 * SetPriorityClass (KERNEL32.503)
1019 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1021 struct set_process_info_request *req = get_req_buffer();
1022 req->handle = hprocess;
1023 req->priority = priorityclass;
1024 req->mask = SET_PROCESS_INFO_PRIORITY;
1025 return !server_call( REQ_SET_PROCESS_INFO );
1029 /***********************************************************************
1030 * GetPriorityClass (KERNEL32.250)
1032 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1034 DWORD ret = 0;
1035 struct get_process_info_request *req = get_req_buffer();
1036 req->handle = hprocess;
1037 if (!server_call( REQ_GET_PROCESS_INFO )) ret = req->priority;
1038 return ret;
1042 /***********************************************************************
1043 * SetProcessAffinityMask (KERNEL32.662)
1045 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1047 struct set_process_info_request *req = get_req_buffer();
1048 req->handle = hProcess;
1049 req->affinity = affmask;
1050 req->mask = SET_PROCESS_INFO_AFFINITY;
1051 return !server_call( REQ_SET_PROCESS_INFO );
1054 /**********************************************************************
1055 * GetProcessAffinityMask (KERNEL32.373)
1057 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1058 LPDWORD lpProcessAffinityMask,
1059 LPDWORD lpSystemAffinityMask )
1061 BOOL ret = FALSE;
1062 struct get_process_info_request *req = get_req_buffer();
1063 req->handle = hProcess;
1064 if (!server_call( REQ_GET_PROCESS_INFO ))
1066 if (lpProcessAffinityMask) *lpProcessAffinityMask = req->process_affinity;
1067 if (lpSystemAffinityMask) *lpSystemAffinityMask = req->system_affinity;
1068 ret = TRUE;
1070 return ret;
1074 /***********************************************************************
1075 * GetStdHandle (KERNEL32.276)
1077 HANDLE WINAPI GetStdHandle( DWORD std_handle )
1079 PDB *pdb = PROCESS_Current();
1081 switch(std_handle)
1083 case STD_INPUT_HANDLE: return pdb->env_db->hStdin;
1084 case STD_OUTPUT_HANDLE: return pdb->env_db->hStdout;
1085 case STD_ERROR_HANDLE: return pdb->env_db->hStderr;
1087 SetLastError( ERROR_INVALID_PARAMETER );
1088 return INVALID_HANDLE_VALUE;
1092 /***********************************************************************
1093 * SetStdHandle (KERNEL32.506)
1095 BOOL WINAPI SetStdHandle( DWORD std_handle, HANDLE handle )
1097 PDB *pdb = PROCESS_Current();
1098 /* FIXME: should we close the previous handle? */
1099 switch(std_handle)
1101 case STD_INPUT_HANDLE:
1102 pdb->env_db->hStdin = handle;
1103 return TRUE;
1104 case STD_OUTPUT_HANDLE:
1105 pdb->env_db->hStdout = handle;
1106 return TRUE;
1107 case STD_ERROR_HANDLE:
1108 pdb->env_db->hStderr = handle;
1109 return TRUE;
1111 SetLastError( ERROR_INVALID_PARAMETER );
1112 return FALSE;
1115 /***********************************************************************
1116 * GetProcessVersion (KERNEL32)
1118 DWORD WINAPI GetProcessVersion( DWORD processid )
1120 TDB *pTask;
1121 PDB *pdb = PROCESS_IdToPDB( processid );
1123 if (!pdb) return 0;
1124 if (!(pTask = (TDB *)GlobalLock16( pdb->task ))) return 0;
1125 return (pTask->version&0xff) | (((pTask->version >>8) & 0xff)<<16);
1128 /***********************************************************************
1129 * GetProcessFlags (KERNEL32)
1131 DWORD WINAPI GetProcessFlags( DWORD processid )
1133 PDB *pdb = PROCESS_IdToPDB( processid );
1134 if (!pdb) return 0;
1135 return pdb->flags;
1138 /***********************************************************************
1139 * SetProcessWorkingSetSize [KERNEL32.662]
1140 * Sets the min/max working set sizes for a specified process.
1142 * PARAMS
1143 * hProcess [I] Handle to the process of interest
1144 * minset [I] Specifies minimum working set size
1145 * maxset [I] Specifies maximum working set size
1147 * RETURNS STD
1149 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1150 DWORD maxset)
1152 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1153 if(( minset == -1) && (maxset == -1)) {
1154 /* Trim the working set to zero */
1155 /* Swap the process out of physical RAM */
1157 return TRUE;
1160 /***********************************************************************
1161 * GetProcessWorkingSetSize (KERNEL32)
1163 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1164 LPDWORD maxset)
1166 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1167 /* 32 MB working set size */
1168 if (minset) *minset = 32*1024*1024;
1169 if (maxset) *maxset = 32*1024*1024;
1170 return TRUE;
1173 /***********************************************************************
1174 * SetProcessShutdownParameters (KERNEL32)
1176 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1177 * Now tracks changes made (but does not act on these changes)
1178 * NOTE: the definition for SHUTDOWN_NORETRY was done on guesswork.
1179 * It really shouldn't be here, but I'll move it when it's been checked!
1181 #define SHUTDOWN_NORETRY 1
1182 static unsigned int shutdown_noretry = 0;
1183 static unsigned int shutdown_priority = 0x280L;
1184 BOOL WINAPI SetProcessShutdownParameters(DWORD level,DWORD flags)
1186 if (flags & SHUTDOWN_NORETRY)
1187 shutdown_noretry = 1;
1188 else
1189 shutdown_noretry = 0;
1190 if (level > 0x100L && level < 0x3FFL)
1191 shutdown_priority = level;
1192 else
1194 ERR("invalid priority level 0x%08lx\n", level);
1195 return FALSE;
1197 return TRUE;
1201 /***********************************************************************
1202 * GetProcessShutdownParameters (KERNEL32)
1205 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel,
1206 LPDWORD lpdwFlags )
1208 (*lpdwLevel) = shutdown_priority;
1209 (*lpdwFlags) = (shutdown_noretry * SHUTDOWN_NORETRY);
1210 return TRUE;
1212 /***********************************************************************
1213 * SetProcessPriorityBoost (KERNEL32)
1215 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1217 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1218 /* Say we can do it. I doubt the program will notice that we don't. */
1219 return TRUE;
1223 /***********************************************************************
1224 * ReadProcessMemory (KERNEL32)
1226 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1227 LPDWORD bytes_read )
1229 struct read_process_memory_request *req = get_req_buffer();
1230 unsigned int offset = (unsigned int)addr % sizeof(int);
1231 unsigned int max = server_remaining( req->data ); /* max length in one request */
1232 unsigned int pos;
1234 if (bytes_read) *bytes_read = size;
1236 /* first time, read total length to check for permissions */
1237 req->handle = process;
1238 req->addr = (char *)addr - offset;
1239 req->len = (size + offset + sizeof(int) - 1) / sizeof(int);
1240 if (server_call( REQ_READ_PROCESS_MEMORY )) goto error;
1242 if (size <= max - offset)
1244 memcpy( buffer, (char *)req->data + offset, size );
1245 return TRUE;
1248 /* now take care of the remaining data */
1249 memcpy( buffer, (char *)req->data + offset, max - offset );
1250 pos = max - offset;
1251 size -= pos;
1252 while (size)
1254 if (max > size) max = size;
1255 req->handle = process;
1256 req->addr = (char *)addr + pos;
1257 req->len = (max + sizeof(int) - 1) / sizeof(int);
1258 if (server_call( REQ_READ_PROCESS_MEMORY )) goto error;
1259 memcpy( (char *)buffer + pos, (char *)req->data, max );
1260 size -= max;
1261 pos += max;
1263 return TRUE;
1265 error:
1266 if (bytes_read) *bytes_read = 0;
1267 return FALSE;
1271 /***********************************************************************
1272 * WriteProcessMemory (KERNEL32)
1274 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPVOID buffer, DWORD size,
1275 LPDWORD bytes_written )
1277 unsigned int first_offset, last_offset;
1278 struct write_process_memory_request *req = get_req_buffer();
1279 unsigned int max = server_remaining( req->data ); /* max length in one request */
1280 unsigned int pos, last_mask;
1282 if (!size)
1284 SetLastError( ERROR_INVALID_PARAMETER );
1285 return FALSE;
1287 if (bytes_written) *bytes_written = size;
1289 /* compute the mask for the first int */
1290 req->first_mask = ~0;
1291 first_offset = (unsigned int)addr % sizeof(int);
1292 memset( &req->first_mask, 0, first_offset );
1294 /* compute the mask for the last int */
1295 last_offset = (size + first_offset) % sizeof(int);
1296 last_mask = 0;
1297 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1299 req->handle = process;
1300 req->addr = (char *)addr - first_offset;
1301 /* for the first request, use the total length */
1302 req->len = (size + first_offset + sizeof(int) - 1) / sizeof(int);
1304 if (size + first_offset < max) /* we can do it in one round */
1306 memcpy( (char *)req->data + first_offset, buffer, size );
1307 req->last_mask = last_mask;
1308 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1309 return TRUE;
1312 /* needs multiple server calls */
1314 memcpy( (char *)req->data + first_offset, buffer, max - first_offset );
1315 req->last_mask = ~0;
1316 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1317 pos = max - first_offset;
1318 size -= pos;
1319 while (size)
1321 if (size <= max) /* last one */
1323 req->last_mask = last_mask;
1324 max = size;
1326 req->handle = process;
1327 req->addr = (char *)addr + pos;
1328 req->len = (max + sizeof(int) - 1) / sizeof(int);
1329 req->first_mask = ~0;
1330 memcpy( req->data, (char *) buffer + pos, max );
1331 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1332 pos += max;
1333 size -= max;
1335 return TRUE;
1337 error:
1338 if (bytes_written) *bytes_written = 0;
1339 return FALSE;
1344 /***********************************************************************
1345 * RegisterServiceProcess (KERNEL, KERNEL32)
1347 * A service process calls this function to ensure that it continues to run
1348 * even after a user logged off.
1350 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1352 /* I don't think that Wine needs to do anything in that function */
1353 return 1; /* success */
1356 /***********************************************************************
1357 * GetExitCodeProcess [KERNEL32.325]
1359 * Gets termination status of specified process
1361 * RETURNS
1362 * Success: TRUE
1363 * Failure: FALSE
1365 BOOL WINAPI GetExitCodeProcess(
1366 HANDLE hProcess, /* [I] handle to the process */
1367 LPDWORD lpExitCode) /* [O] address to receive termination status */
1369 BOOL ret = FALSE;
1370 struct get_process_info_request *req = get_req_buffer();
1371 req->handle = hProcess;
1372 if (!server_call( REQ_GET_PROCESS_INFO ))
1374 if (lpExitCode) *lpExitCode = req->exit_code;
1375 ret = TRUE;
1377 return ret;
1381 /***********************************************************************
1382 * SetErrorMode (KERNEL32.486)
1384 UINT WINAPI SetErrorMode( UINT mode )
1386 UINT old = PROCESS_Current()->error_mode;
1387 PROCESS_Current()->error_mode = mode;
1388 return old;
1391 /***********************************************************************
1392 * GetCurrentProcess (KERNEL32.198)
1394 #undef GetCurrentProcess
1395 HANDLE WINAPI GetCurrentProcess(void)
1397 return 0xffffffff;