Make PDB, ENVDB and STARTUPINFO global variables.
[wine.git] / scheduler / process.c
blob78256eefee07716576debba282e210d84f720c0e
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 /* Get pointers to USER routines called by KERNEL */
233 THUNK_InitCallout();
235 /* Call FinalUserInit routine */
236 Callout.FinalUserInit16();
238 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
239 * context of the parent process. Actually, the USER signal proc
240 * doesn't really care about that, but it *does* require that the
241 * startup parameters are correctly set up, so that GetProcessDword
242 * works. Furthermore, before calling the USER signal proc the
243 * 16-bit stack must be set up, which it is only after TASK_Create
244 * in the case of a 16-bit process. Thus, we send the signal here.
246 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
247 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
248 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
249 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
251 return 1;
255 /***********************************************************************
256 * build_command_line
258 * Build the command-line of a process from the argv array.
260 static inline char *build_command_line( char **argv )
262 int len, quote;
263 char *cmdline, *p, **arg;
265 for (arg = argv, len = 0; *arg; arg++) len += strlen(*arg) + 1;
266 if ((quote = (strchr( argv[0], ' ' ) != NULL))) len += 2;
267 if (!(p = cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
268 arg = argv;
269 if (quote)
271 *p++ = '\"';
272 strcpy( p, *arg );
273 p += strlen(p);
274 *p++ = '\"';
275 *p++ = ' ';
276 arg++;
278 while (*arg)
280 strcpy( p, *arg );
281 p += strlen(p);
282 *p++ = ' ';
283 arg++;
285 if (p > cmdline) p--; /* remove last space */
286 *p = 0;
287 return cmdline;
291 /***********************************************************************
292 * start_process
294 * Startup routine of a new process. Runs on the new process stack.
296 static void start_process(void)
298 struct init_process_done_request *req = get_req_buffer();
299 int debugged, console_app;
300 UINT cmdShow = SW_SHOWNORMAL;
301 LPTHREAD_START_ROUTINE entry;
302 HMODULE module = current_process.exe_modref->module;
304 /* Increment EXE refcount */
305 current_process.exe_modref->refCount++;
307 /* build command line */
308 if (!(current_envdb.cmd_line = build_command_line( main_exe_argv ))) goto error;
310 /* Retrieve entry point address */
311 entry = (LPTHREAD_START_ROUTINE)((char*)module + PE_HEADER(module)->OptionalHeader.AddressOfEntryPoint);
312 console_app = (PE_HEADER(module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
314 if (console_app) current_process.flags |= PDB32_CONSOLE_PROC;
316 /* Signal the parent process to continue */
317 req->module = (void *)module;
318 req->entry = entry;
319 req->name = &current_process.exe_modref->filename;
320 req->gui = !console_app;
321 server_call( REQ_INIT_PROCESS_DONE );
322 debugged = req->debugged;
324 /* Install signal handlers; this cannot be done before, since we cannot
325 * send exceptions to the debugger before the create process event that
326 * is sent by REQ_INIT_PROCESS_DONE */
327 if (!SIGNAL_Init()) goto error;
329 /* Load KERNEL (necessary for TASK_Create) */
330 if (!LoadLibraryA( "KERNEL32" )) goto error;
332 /* Create 16-bit task */
333 if (current_startupinfo.dwFlags & STARTF_USESHOWWINDOW)
334 cmdShow = current_startupinfo.wShowWindow;
335 if (!TASK_Create( (NE_MODULE *)GlobalLock16( MapHModuleLS(module) ), cmdShow,
336 NtCurrentTeb(), NULL, 0 ))
337 goto error;
339 /* Load the system dlls */
340 if (!load_system_dlls()) goto error;
342 EnterCriticalSection( &current_process.crit_section );
343 PE_InitTls();
344 MODULE_DllProcessAttach( current_process.exe_modref, (LPVOID)1 );
345 LeaveCriticalSection( &current_process.crit_section );
347 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
348 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
350 TRACE_(relay)( "Starting Win32 process (entryproc=%p)\n", entry );
351 if (debugged) DbgBreakPoint();
352 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
353 * Dunno about other OSs */
354 ExitThread( entry(NULL) );
356 error:
357 ExitProcess( GetLastError() );
361 /***********************************************************************
362 * PROCESS_Start
364 * Startup routine of a new Win32 process once the main module has been loaded.
365 * The filename is free'd by this routine.
367 static void PROCESS_Start( HMODULE main_module, HFILE hFile, LPSTR filename ) WINE_NORETURN;
368 static void PROCESS_Start( HMODULE main_module, HFILE hFile, LPSTR filename )
370 if (!filename)
372 /* if no explicit filename, use argv[0] */
373 if (!(filename = malloc( MAX_PATH ))) ExitProcess(1);
374 if (!GetLongPathNameA( full_argv0, filename, MAX_PATH ))
375 lstrcpynA( filename, full_argv0, MAX_PATH );
378 /* load main module */
379 if (PE_HEADER(main_module)->FileHeader.Characteristics & IMAGE_FILE_DLL)
380 ExitProcess( ERROR_BAD_EXE_FORMAT );
382 /* Create 32-bit MODREF */
383 if (!PE_CreateModule( main_module, filename, 0, hFile, FALSE ))
384 goto error;
385 free( filename );
387 /* allocate main thread stack */
388 if (!THREAD_InitStack( NtCurrentTeb(),
389 PE_HEADER(main_module)->OptionalHeader.SizeOfStackReserve, TRUE ))
390 goto error;
392 /* switch to the new stack */
393 SYSDEPS_SwitchToThreadStack( start_process );
395 error:
396 ExitProcess( GetLastError() );
400 /***********************************************************************
401 * PROCESS_InitWine
403 * Wine initialisation: load and start the main exe file.
405 void PROCESS_InitWine( int argc, char *argv[] )
407 DWORD type;
409 /* Initialize everything */
410 if (!process_init( argv )) exit(1);
412 main_exe_argv = ++argv; /* remove argv[0] (wine itself) */
414 if (!main_exe_name)
416 char buffer[MAX_PATH];
417 if (!argv[0]) OPTIONS_Usage();
419 /* open the exe file */
420 if (!SearchPathA( NULL, argv[0], ".exe", sizeof(buffer), buffer, NULL ) &&
421 !SearchPathA( NULL, argv[0], NULL, sizeof(buffer), buffer, NULL ))
423 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
424 goto error;
426 if (!(main_exe_name = strdup(buffer)))
428 MESSAGE( "%s: out of memory\n", argv0 );
429 ExitProcess(1);
433 if (main_exe_file == INVALID_HANDLE_VALUE)
435 if ((main_exe_file = CreateFileA( main_exe_name, GENERIC_READ, FILE_SHARE_READ,
436 NULL, OPEN_EXISTING, 0, -1 )) == INVALID_HANDLE_VALUE)
438 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
439 goto error;
443 if (!MODULE_GetBinaryType( main_exe_file, main_exe_name, &type ))
445 MESSAGE( "%s: unrecognized executable '%s'\n", argv0, main_exe_name );
446 goto error;
449 switch (type)
451 case SCS_32BIT_BINARY:
453 HMODULE main_module = PE_LoadImage( main_exe_file, main_exe_name, 0 );
454 if (main_module) PROCESS_Start( main_module, main_exe_file, main_exe_name );
456 break;
458 case SCS_WOW_BINARY:
460 HMODULE main_module;
461 /* create 32-bit module for main exe */
462 if (!(main_module = BUILTIN32_LoadExeModule())) goto error;
463 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
464 current_process.flags |= PDB32_WIN16_PROC;
465 SYSLEVEL_EnterWin16Lock();
466 PROCESS_Start( main_module, -1, NULL );
468 break;
470 case SCS_DOS_BINARY:
472 HMODULE main_module;
473 /* create 32-bit module for main exe */
474 if (!(main_module = BUILTIN32_LoadExeModule())) goto error;
475 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
476 if (!MZ_LoadImage( main_module, main_exe_file, main_exe_name )) goto error;
477 PROCESS_Start( main_module, main_exe_file, NULL );
479 break;
481 case SCS_PIF_BINARY:
482 case SCS_POSIX_BINARY:
483 case SCS_OS216_BINARY:
484 default:
485 MESSAGE( "%s: unrecognized executable '%s'\n", argv0, main_exe_name );
486 SetLastError( ERROR_BAD_FORMAT );
487 break;
489 error:
490 ExitProcess( GetLastError() );
494 /***********************************************************************
495 * PROCESS_InitWinelib
497 * Initialisation of a new Winelib process.
499 void PROCESS_InitWinelib( int argc, char *argv[] )
501 HMODULE main_module;
503 if (!process_init( argv )) exit(1);
505 /* create 32-bit module for main exe */
506 if (!(main_module = BUILTIN32_LoadExeModule())) ExitProcess( GetLastError() );
508 main_exe_argv = argv;
509 PROCESS_Start( main_module, -1, NULL );
513 /***********************************************************************
514 * build_argv
516 * Build an argv array from a command-line.
517 * The command-line is modified to insert nulls.
518 * 'reserved' is the number of args to reserve before the first one.
520 static char **build_argv( char *cmdline, int reserved )
522 char **argv;
523 int count = reserved + 1;
524 char *p = cmdline;
526 /* if first word is quoted store it as a single arg */
527 if (*cmdline == '\"')
529 if ((p = strchr( cmdline + 1, '\"' )))
531 p++;
532 count++;
534 else p = cmdline;
536 while (*p)
538 while (*p && isspace(*p)) p++;
539 if (!*p) break;
540 count++;
541 while (*p && !isspace(*p)) p++;
544 if ((argv = malloc( count * sizeof(*argv) )))
546 char **argvptr = argv + reserved;
547 p = cmdline;
548 if (*cmdline == '\"')
550 if ((p = strchr( cmdline + 1, '\"' )))
552 *argvptr++ = cmdline + 1;
553 *p++ = 0;
555 else p = cmdline;
557 while (*p)
559 while (*p && isspace(*p)) *p++ = 0;
560 if (!*p) break;
561 *argvptr++ = p;
562 while (*p && !isspace(*p)) p++;
564 *argvptr = 0;
566 return argv;
570 /***********************************************************************
571 * build_envp
573 * Build the environment of a new child process.
575 static char **build_envp( const char *env )
577 const char *p;
578 char **envp;
579 int count;
581 for (p = env, count = 0; *p; count++) p += strlen(p) + 1;
582 count += 3;
583 if ((envp = malloc( count * sizeof(*envp) )))
585 extern char **environ;
586 char **envptr = envp;
587 char **unixptr = environ;
588 /* first put PATH, HOME and WINEPREFIX from the unix env */
589 for (unixptr = environ; unixptr && *unixptr; unixptr++)
590 if (!memcmp( *unixptr, "PATH=", 5 ) ||
591 !memcmp( *unixptr, "HOME=", 5 ) ||
592 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
593 /* now put the Windows environment strings */
594 for (p = env; *p; p += strlen(p) + 1)
596 if (memcmp( p, "PATH=", 5 ) &&
597 memcmp( p, "HOME=", 5 ) &&
598 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
600 *envptr = 0;
602 return envp;
606 /***********************************************************************
607 * find_wine_binary
609 * Locate the Wine binary to exec for a new Win32 process.
611 static void exec_wine_binary( char **argv, char **envp )
613 const char *path, *pos, *ptr;
615 /* first try bin directory */
616 argv[0] = BINDIR "/wine";
617 execve( argv[0], argv, envp );
619 /* now try the path of argv0 of the current binary */
620 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
621 if ((ptr = strrchr( full_argv0, '/' )))
623 memcpy( argv[0], full_argv0, ptr - full_argv0 );
624 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
625 execve( argv[0], argv, envp );
627 free( argv[0] );
629 /* now search in the Unix path */
630 if ((path = getenv( "PATH" )))
632 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
633 pos = path;
634 for (;;)
636 while (*pos == ':') pos++;
637 if (!*pos) break;
638 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
639 memcpy( argv[0], pos, ptr - pos );
640 strcpy( argv[0] + (ptr - pos), "/wine" );
641 execve( argv[0], argv, envp );
642 pos = ptr;
645 free( argv[0] );
647 /* finally try the current directory */
648 argv[0] = "./wine";
649 execve( argv[0], argv, envp );
653 /***********************************************************************
654 * fork_and_exec
656 * Fork and exec a new Unix process, checking for errors.
658 static int fork_and_exec( const char *filename, char *cmdline,
659 const char *env, const char *newdir )
661 int fd[2];
662 int pid, err;
664 if (pipe(fd) == -1)
666 FILE_SetDosError();
667 return -1;
669 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
670 if (!(pid = fork())) /* child */
672 char **argv = build_argv( cmdline, filename ? 0 : 2 );
673 char **envp = build_envp( env );
674 close( fd[0] );
676 if (newdir) chdir(newdir);
678 if (argv && envp)
680 if (!filename)
682 argv[1] = "--";
683 exec_wine_binary( argv, envp );
685 else execve( filename, argv, envp );
687 err = errno;
688 write( fd[1], &err, sizeof(err) );
689 _exit(1);
691 close( fd[1] );
692 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
694 errno = err;
695 pid = -1;
697 if (pid == -1) FILE_SetDosError();
698 close( fd[0] );
699 return pid;
703 /***********************************************************************
704 * PROCESS_Create
706 * Create a new process. If hFile is a valid handle we have an exe
707 * file, and we exec a new copy of wine to load it; otherwise we
708 * simply exec the specified filename as a Unix process.
710 BOOL PROCESS_Create( HFILE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
711 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
712 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
713 LPPROCESS_INFORMATION info, LPCSTR lpCurrentDirectory )
715 int pid;
716 const char *unixfilename = NULL;
717 const char *unixdir = NULL;
718 DOS_FULL_NAME full_name;
719 HANDLE load_done_evt = -1;
720 struct new_process_request *req = get_req_buffer();
721 struct wait_process_request *wait_req = get_req_buffer();
723 info->hThread = info->hProcess = INVALID_HANDLE_VALUE;
725 /* create the process on the server side */
727 req->inherit_all = inherit;
728 req->create_flags = flags;
729 req->start_flags = startup->dwFlags;
730 req->exe_file = hFile;
731 if (startup->dwFlags & STARTF_USESTDHANDLES)
733 req->hstdin = startup->hStdInput;
734 req->hstdout = startup->hStdOutput;
735 req->hstderr = startup->hStdError;
737 else
739 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
740 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
741 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
743 req->cmd_show = startup->wShowWindow;
744 req->alloc_fd = 0;
746 if (lpCurrentDirectory) {
747 if (DOSFS_GetFullName( lpCurrentDirectory, TRUE, &full_name ))
748 unixdir = full_name.long_name;
749 } else {
750 CHAR buf[260];
751 if (GetCurrentDirectoryA(sizeof(buf),buf)) {
752 if (DOSFS_GetFullName( buf, TRUE, &full_name ))
753 unixdir = full_name.long_name;
757 if (hFile == -1) /* unix process */
759 unixfilename = filename;
760 if (DOSFS_GetFullName( filename, TRUE, &full_name )) unixfilename = full_name.long_name;
761 req->filename[0] = 0;
763 else /* new wine process */
765 if (!GetLongPathNameA( filename, req->filename, server_remaining(req->filename) ))
766 lstrcpynA( req->filename, filename, server_remaining(req->filename) );
768 if (server_call( REQ_NEW_PROCESS )) return FALSE;
770 /* fork and execute */
772 pid = fork_and_exec( unixfilename, cmd_line, env ? env : GetEnvironmentStringsA(), unixdir );
774 wait_req->cancel = (pid == -1);
775 wait_req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
776 wait_req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
777 wait_req->timeout = 2000;
778 if (server_call( REQ_WAIT_PROCESS ) || (pid == -1)) goto error;
779 info->dwProcessId = (DWORD)wait_req->pid;
780 info->dwThreadId = (DWORD)wait_req->tid;
781 info->hProcess = wait_req->phandle;
782 info->hThread = wait_req->thandle;
783 load_done_evt = wait_req->event;
785 /* Wait until process is initialized (or initialization failed) */
786 if (load_done_evt != -1)
788 DWORD res;
789 HANDLE handles[2];
791 handles[0] = info->hProcess;
792 handles[1] = load_done_evt;
793 res = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
794 CloseHandle( load_done_evt );
795 if (res == STATUS_WAIT_0) /* the process died */
797 DWORD exitcode;
798 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
799 CloseHandle( info->hThread );
800 CloseHandle( info->hProcess );
801 return FALSE;
804 return TRUE;
806 error:
807 if (load_done_evt != -1) CloseHandle( load_done_evt );
808 if (info->hThread != INVALID_HANDLE_VALUE) CloseHandle( info->hThread );
809 if (info->hProcess != INVALID_HANDLE_VALUE) CloseHandle( info->hProcess );
810 return FALSE;
814 /***********************************************************************
815 * ExitProcess (KERNEL32.100)
817 void WINAPI ExitProcess( DWORD status )
819 struct terminate_process_request *req = get_req_buffer();
821 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
822 /* send the exit code to the server */
823 req->handle = GetCurrentProcess();
824 req->exit_code = status;
825 server_call( REQ_TERMINATE_PROCESS );
826 exit( status );
829 /***********************************************************************
830 * ExitProcess16 (KERNEL.466)
832 void WINAPI ExitProcess16( WORD status )
834 SYSLEVEL_ReleaseWin16Lock();
835 ExitProcess( status );
838 /******************************************************************************
839 * TerminateProcess (KERNEL32.684)
841 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
843 BOOL ret;
844 struct terminate_process_request *req = get_req_buffer();
845 req->handle = handle;
846 req->exit_code = exit_code;
847 if ((ret = !server_call( REQ_TERMINATE_PROCESS )) && req->self) exit( exit_code );
848 return ret;
852 /***********************************************************************
853 * GetProcessDword (KERNEL32.18) (KERNEL.485)
854 * 'Of course you cannot directly access Windows internal structures'
856 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
858 TDB *pTask;
859 DWORD x, y;
861 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
863 if (dwProcessID && dwProcessID != GetCurrentProcessId())
865 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
866 return 0;
869 switch ( offset )
871 case GPD_APP_COMPAT_FLAGS:
872 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
873 return pTask? pTask->compat_flags : 0;
875 case GPD_LOAD_DONE_EVENT:
876 return current_process.load_done_evt;
878 case GPD_HINSTANCE16:
879 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
880 return pTask? pTask->hInstance : 0;
882 case GPD_WINDOWS_VERSION:
883 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
884 return pTask? pTask->version : 0;
886 case GPD_THDB:
887 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
889 case GPD_PDB:
890 return (DWORD)&current_process;
892 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
893 return current_startupinfo.hStdOutput;
895 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
896 return current_startupinfo.hStdInput;
898 case GPD_STARTF_SHOWWINDOW:
899 return current_startupinfo.wShowWindow;
901 case GPD_STARTF_SIZE:
902 x = current_startupinfo.dwXSize;
903 if ( x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
904 y = current_startupinfo.dwYSize;
905 if ( y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
906 return MAKELONG( x, y );
908 case GPD_STARTF_POSITION:
909 x = current_startupinfo.dwX;
910 if ( x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
911 y = current_startupinfo.dwY;
912 if ( y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
913 return MAKELONG( x, y );
915 case GPD_STARTF_FLAGS:
916 return current_startupinfo.dwFlags;
918 case GPD_PARENT:
919 return 0;
921 case GPD_FLAGS:
922 return current_process.flags;
924 case GPD_USERDATA:
925 return current_process.process_dword;
927 default:
928 ERR_(win32)("Unknown offset %d\n", offset );
929 return 0;
933 /***********************************************************************
934 * SetProcessDword (KERNEL.484)
935 * 'Of course you cannot directly access Windows internal structures'
937 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
939 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
941 if (dwProcessID && dwProcessID != GetCurrentProcessId())
943 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
944 return;
947 switch ( offset )
949 case GPD_APP_COMPAT_FLAGS:
950 case GPD_LOAD_DONE_EVENT:
951 case GPD_HINSTANCE16:
952 case GPD_WINDOWS_VERSION:
953 case GPD_THDB:
954 case GPD_PDB:
955 case GPD_STARTF_SHELLDATA:
956 case GPD_STARTF_HOTKEY:
957 case GPD_STARTF_SHOWWINDOW:
958 case GPD_STARTF_SIZE:
959 case GPD_STARTF_POSITION:
960 case GPD_STARTF_FLAGS:
961 case GPD_PARENT:
962 case GPD_FLAGS:
963 ERR_(win32)("Not allowed to modify offset %d\n", offset );
964 break;
966 case GPD_USERDATA:
967 current_process.process_dword = value;
968 break;
970 default:
971 ERR_(win32)("Unknown offset %d\n", offset );
972 break;
977 /*********************************************************************
978 * OpenProcess (KERNEL32.543)
980 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
982 HANDLE ret = 0;
983 struct open_process_request *req = get_req_buffer();
985 req->pid = (void *)id;
986 req->access = access;
987 req->inherit = inherit;
988 if (!server_call( REQ_OPEN_PROCESS )) ret = req->handle;
989 return ret;
992 /*********************************************************************
993 * MapProcessHandle (KERNEL.483)
995 DWORD WINAPI MapProcessHandle( HANDLE handle )
997 DWORD ret = 0;
998 struct get_process_info_request *req = get_req_buffer();
999 req->handle = handle;
1000 if (!server_call( REQ_GET_PROCESS_INFO )) ret = (DWORD)req->pid;
1001 return ret;
1004 /***********************************************************************
1005 * SetPriorityClass (KERNEL32.503)
1007 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1009 struct set_process_info_request *req = get_req_buffer();
1010 req->handle = hprocess;
1011 req->priority = priorityclass;
1012 req->mask = SET_PROCESS_INFO_PRIORITY;
1013 return !server_call( REQ_SET_PROCESS_INFO );
1017 /***********************************************************************
1018 * GetPriorityClass (KERNEL32.250)
1020 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1022 DWORD ret = 0;
1023 struct get_process_info_request *req = get_req_buffer();
1024 req->handle = hprocess;
1025 if (!server_call( REQ_GET_PROCESS_INFO )) ret = req->priority;
1026 return ret;
1030 /***********************************************************************
1031 * SetProcessAffinityMask (KERNEL32.662)
1033 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1035 struct set_process_info_request *req = get_req_buffer();
1036 req->handle = hProcess;
1037 req->affinity = affmask;
1038 req->mask = SET_PROCESS_INFO_AFFINITY;
1039 return !server_call( REQ_SET_PROCESS_INFO );
1042 /**********************************************************************
1043 * GetProcessAffinityMask (KERNEL32.373)
1045 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1046 LPDWORD lpProcessAffinityMask,
1047 LPDWORD lpSystemAffinityMask )
1049 BOOL ret = FALSE;
1050 struct get_process_info_request *req = get_req_buffer();
1051 req->handle = hProcess;
1052 if (!server_call( REQ_GET_PROCESS_INFO ))
1054 if (lpProcessAffinityMask) *lpProcessAffinityMask = req->process_affinity;
1055 if (lpSystemAffinityMask) *lpSystemAffinityMask = req->system_affinity;
1056 ret = TRUE;
1058 return ret;
1062 /***********************************************************************
1063 * GetProcessVersion (KERNEL32)
1065 DWORD WINAPI GetProcessVersion( DWORD processid )
1067 IMAGE_NT_HEADERS *nt;
1069 if (processid && processid != GetCurrentProcessId())
1070 return 0; /* FIXME: should use ReadProcessMemory */
1071 if ((nt = RtlImageNtHeader( current_process.module )))
1072 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1073 nt->OptionalHeader.MinorSubsystemVersion);
1074 return 0;
1077 /***********************************************************************
1078 * GetProcessFlags (KERNEL32)
1080 DWORD WINAPI GetProcessFlags( DWORD processid )
1082 if (processid && processid != GetCurrentProcessId()) return 0;
1083 return current_process.flags;
1087 /***********************************************************************
1088 * SetProcessWorkingSetSize [KERNEL32.662]
1089 * Sets the min/max working set sizes for a specified process.
1091 * PARAMS
1092 * hProcess [I] Handle to the process of interest
1093 * minset [I] Specifies minimum working set size
1094 * maxset [I] Specifies maximum working set size
1096 * RETURNS STD
1098 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1099 DWORD maxset)
1101 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1102 if(( minset == -1) && (maxset == -1)) {
1103 /* Trim the working set to zero */
1104 /* Swap the process out of physical RAM */
1106 return TRUE;
1109 /***********************************************************************
1110 * GetProcessWorkingSetSize (KERNEL32)
1112 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1113 LPDWORD maxset)
1115 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1116 /* 32 MB working set size */
1117 if (minset) *minset = 32*1024*1024;
1118 if (maxset) *maxset = 32*1024*1024;
1119 return TRUE;
1122 /***********************************************************************
1123 * SetProcessShutdownParameters (KERNEL32)
1125 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1126 * Now tracks changes made (but does not act on these changes)
1127 * NOTE: the definition for SHUTDOWN_NORETRY was done on guesswork.
1128 * It really shouldn't be here, but I'll move it when it's been checked!
1130 #define SHUTDOWN_NORETRY 1
1131 static unsigned int shutdown_noretry = 0;
1132 static unsigned int shutdown_priority = 0x280L;
1133 BOOL WINAPI SetProcessShutdownParameters(DWORD level,DWORD flags)
1135 if (flags & SHUTDOWN_NORETRY)
1136 shutdown_noretry = 1;
1137 else
1138 shutdown_noretry = 0;
1139 if (level > 0x100L && level < 0x3FFL)
1140 shutdown_priority = level;
1141 else
1143 ERR("invalid priority level 0x%08lx\n", level);
1144 return FALSE;
1146 return TRUE;
1150 /***********************************************************************
1151 * GetProcessShutdownParameters (KERNEL32)
1154 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel,
1155 LPDWORD lpdwFlags )
1157 (*lpdwLevel) = shutdown_priority;
1158 (*lpdwFlags) = (shutdown_noretry * SHUTDOWN_NORETRY);
1159 return TRUE;
1161 /***********************************************************************
1162 * SetProcessPriorityBoost (KERNEL32)
1164 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1166 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1167 /* Say we can do it. I doubt the program will notice that we don't. */
1168 return TRUE;
1172 /***********************************************************************
1173 * ReadProcessMemory (KERNEL32)
1175 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1176 LPDWORD bytes_read )
1178 struct read_process_memory_request *req = get_req_buffer();
1179 unsigned int offset = (unsigned int)addr % sizeof(int);
1180 unsigned int max = server_remaining( req->data ); /* max length in one request */
1181 unsigned int pos;
1183 if (bytes_read) *bytes_read = size;
1185 /* first time, read total length to check for permissions */
1186 req->handle = process;
1187 req->addr = (char *)addr - offset;
1188 req->len = (size + offset + sizeof(int) - 1) / sizeof(int);
1189 if (server_call( REQ_READ_PROCESS_MEMORY )) goto error;
1191 if (size <= max - offset)
1193 memcpy( buffer, (char *)req->data + offset, size );
1194 return TRUE;
1197 /* now take care of the remaining data */
1198 memcpy( buffer, (char *)req->data + offset, max - offset );
1199 pos = max - offset;
1200 size -= pos;
1201 while (size)
1203 if (max > size) max = size;
1204 req->handle = process;
1205 req->addr = (char *)addr + pos;
1206 req->len = (max + sizeof(int) - 1) / sizeof(int);
1207 if (server_call( REQ_READ_PROCESS_MEMORY )) goto error;
1208 memcpy( (char *)buffer + pos, (char *)req->data, max );
1209 size -= max;
1210 pos += max;
1212 return TRUE;
1214 error:
1215 if (bytes_read) *bytes_read = 0;
1216 return FALSE;
1220 /***********************************************************************
1221 * WriteProcessMemory (KERNEL32)
1223 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPVOID buffer, DWORD size,
1224 LPDWORD bytes_written )
1226 unsigned int first_offset, last_offset;
1227 struct write_process_memory_request *req = get_req_buffer();
1228 unsigned int max = server_remaining( req->data ); /* max length in one request */
1229 unsigned int pos, last_mask;
1231 if (!size)
1233 SetLastError( ERROR_INVALID_PARAMETER );
1234 return FALSE;
1236 if (bytes_written) *bytes_written = size;
1238 /* compute the mask for the first int */
1239 req->first_mask = ~0;
1240 first_offset = (unsigned int)addr % sizeof(int);
1241 memset( &req->first_mask, 0, first_offset );
1243 /* compute the mask for the last int */
1244 last_offset = (size + first_offset) % sizeof(int);
1245 last_mask = 0;
1246 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1248 req->handle = process;
1249 req->addr = (char *)addr - first_offset;
1250 /* for the first request, use the total length */
1251 req->len = (size + first_offset + sizeof(int) - 1) / sizeof(int);
1253 if (size + first_offset < max) /* we can do it in one round */
1255 memcpy( (char *)req->data + first_offset, buffer, size );
1256 req->last_mask = last_mask;
1257 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1258 return TRUE;
1261 /* needs multiple server calls */
1263 memcpy( (char *)req->data + first_offset, buffer, max - first_offset );
1264 req->last_mask = ~0;
1265 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1266 pos = max - first_offset;
1267 size -= pos;
1268 while (size)
1270 if (size <= max) /* last one */
1272 req->last_mask = last_mask;
1273 max = size;
1275 req->handle = process;
1276 req->addr = (char *)addr + pos;
1277 req->len = (max + sizeof(int) - 1) / sizeof(int);
1278 req->first_mask = ~0;
1279 memcpy( req->data, (char *) buffer + pos, max );
1280 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1281 pos += max;
1282 size -= max;
1284 return TRUE;
1286 error:
1287 if (bytes_written) *bytes_written = 0;
1288 return FALSE;
1293 /***********************************************************************
1294 * RegisterServiceProcess (KERNEL, KERNEL32)
1296 * A service process calls this function to ensure that it continues to run
1297 * even after a user logged off.
1299 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1301 /* I don't think that Wine needs to do anything in that function */
1302 return 1; /* success */
1305 /***********************************************************************
1306 * GetExitCodeProcess [KERNEL32.325]
1308 * Gets termination status of specified process
1310 * RETURNS
1311 * Success: TRUE
1312 * Failure: FALSE
1314 BOOL WINAPI GetExitCodeProcess(
1315 HANDLE hProcess, /* [I] handle to the process */
1316 LPDWORD lpExitCode) /* [O] address to receive termination status */
1318 BOOL ret = FALSE;
1319 struct get_process_info_request *req = get_req_buffer();
1320 req->handle = hProcess;
1321 if (!server_call( REQ_GET_PROCESS_INFO ))
1323 if (lpExitCode) *lpExitCode = req->exit_code;
1324 ret = TRUE;
1326 return ret;
1330 /***********************************************************************
1331 * SetErrorMode (KERNEL32.486)
1333 UINT WINAPI SetErrorMode( UINT mode )
1335 UINT old = current_process.error_mode;
1336 current_process.error_mode = mode;
1337 return old;
1340 /***********************************************************************
1341 * GetCurrentProcess (KERNEL32.198)
1343 #undef GetCurrentProcess
1344 HANDLE WINAPI GetCurrentProcess(void)
1346 return 0xffffffff;