Removed calls to internal (non-exported) wine functions.
[wine.git] / scheduler / process.c
blob7c65993582957fb9b7a5a5e484bb6adbab7f665d
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 "wine/library.h"
18 #include "process.h"
19 #include "drive.h"
20 #include "main.h"
21 #include "module.h"
22 #include "neexe.h"
23 #include "file.h"
24 #include "global.h"
25 #include "heap.h"
26 #include "task.h"
27 #include "ldt.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[MAX_PATH];
43 static HANDLE main_exe_file = INVALID_HANDLE_VALUE;
44 static HMODULE main_module;
46 unsigned int server_startticks;
48 /***********************************************************************
49 * PROCESS_CallUserSignalProc
51 * FIXME: Some of the signals aren't sent correctly!
53 * The exact meaning of the USER signals is undocumented, but this
54 * should cover the basic idea:
56 * USIG_DLL_UNLOAD_WIN16
57 * This is sent when a 16-bit module is unloaded.
59 * USIG_DLL_UNLOAD_WIN32
60 * This is sent when a 32-bit module is unloaded.
62 * USIG_DLL_UNLOAD_ORPHANS
63 * This is sent after the last Win3.1 module is unloaded,
64 * to allow removal of orphaned menus.
66 * USIG_FAULT_DIALOG_PUSH
67 * USIG_FAULT_DIALOG_POP
68 * These are called to allow USER to prepare for displaying a
69 * fault dialog, even though the fault might have happened while
70 * inside a USER critical section.
72 * USIG_THREAD_INIT
73 * This is called from the context of a new thread, as soon as it
74 * has started to run.
76 * USIG_THREAD_EXIT
77 * This is called, still in its context, just before a thread is
78 * about to terminate.
80 * USIG_PROCESS_CREATE
81 * This is called, in the parent process context, after a new process
82 * has been created.
84 * USIG_PROCESS_INIT
85 * This is called in the new process context, just after the main thread
86 * has started execution (after the main thread's USIG_THREAD_INIT has
87 * been sent).
89 * USIG_PROCESS_LOADED
90 * This is called after the executable file has been loaded into the
91 * new process context.
93 * USIG_PROCESS_RUNNING
94 * This is called immediately before the main entry point is called.
96 * USIG_PROCESS_EXIT
97 * This is called in the context of a process that is about to
98 * terminate (but before the last thread's USIG_THREAD_EXIT has
99 * been sent).
101 * USIG_PROCESS_DESTROY
102 * This is called after a process has terminated.
105 * The meaning of the dwFlags bits is as follows:
107 * USIG_FLAGS_WIN32
108 * Current process is 32-bit.
110 * USIG_FLAGS_GUI
111 * Current process is a (Win32) GUI process.
113 * USIG_FLAGS_FEEDBACK
114 * Current process needs 'feedback' (determined from the STARTUPINFO
115 * flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
117 * USIG_FLAGS_FAULT
118 * The signal is being sent due to a fault.
120 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE hModule )
122 DWORD flags = current_process.flags;
123 DWORD startup_flags = current_startupinfo.dwFlags;
124 DWORD dwFlags = 0;
126 /* Determine dwFlags */
128 if ( !(flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
130 if ( !(flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
132 if ( dwFlags & USIG_FLAGS_GUI )
134 /* Feedback defaults to ON */
135 if ( !(startup_flags & STARTF_FORCEOFFFEEDBACK) )
136 dwFlags |= USIG_FLAGS_FEEDBACK;
138 else
140 /* Feedback defaults to OFF */
141 if (startup_flags & STARTF_FORCEONFEEDBACK)
142 dwFlags |= USIG_FLAGS_FEEDBACK;
145 /* Convert module handle to 16-bit */
147 if ( HIWORD( hModule ) )
148 hModule = MapHModuleLS( hModule );
150 /* Call USER signal proc */
152 if ( Callout.UserSignalProc )
154 if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
155 Callout.UserSignalProc( uCode, GetCurrentThreadId(), dwFlags, hModule );
156 else
157 Callout.UserSignalProc( uCode, GetCurrentProcessId(), dwFlags, hModule );
162 /***********************************************************************
163 * process_init
165 * Main process initialisation code
167 static BOOL process_init( char *argv[] )
169 BOOL ret;
171 /* store the program name */
172 argv0 = argv[0];
173 main_exe_argv = argv;
175 /* Fill the initial process structure */
176 current_process.exit_code = STILL_ACTIVE;
177 current_process.threads = 1;
178 current_process.running_threads = 1;
179 current_process.ring0_threads = 1;
180 current_process.group = &current_process;
181 current_process.priority = 8; /* Normal */
182 current_process.env_db = &current_envdb;
184 /* Setup the server connection */
185 NtCurrentTeb()->socket = CLIENT_InitServer();
186 if (CLIENT_InitThread()) return FALSE;
188 /* Retrieve startup info from the server */
189 SERVER_START_REQ
191 struct init_process_request *req = server_alloc_req( sizeof(*req),
192 sizeof(main_exe_name)-1 );
194 req->ldt_copy = &wine_ldt_copy;
195 req->ppid = getppid();
196 if ((ret = !server_call( REQ_INIT_PROCESS )))
198 size_t len = server_data_size( req );
199 memcpy( main_exe_name, server_data_ptr(req), len );
200 main_exe_name[len] = 0;
201 main_exe_file = req->exe_file;
202 current_startupinfo.dwFlags = req->start_flags;
203 server_startticks = req->server_start;
204 current_startupinfo.wShowWindow = req->cmd_show;
205 current_envdb.hStdin = current_startupinfo.hStdInput = req->hstdin;
206 current_envdb.hStdout = current_startupinfo.hStdOutput = req->hstdout;
207 current_envdb.hStderr = current_startupinfo.hStdError = req->hstderr;
210 SERVER_END_REQ;
211 if (!ret) return FALSE;
213 /* Create the system and process heaps */
214 if (!HEAP_CreateSystemHeap()) return FALSE;
215 current_process.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( &current_process.crit_section );
226 /* Parse command line arguments */
227 OPTIONS_ParseOptions( argv );
229 return MAIN_MainInit();
233 /***********************************************************************
234 * build_command_line
236 * Build the command line of a process from the argv array.
238 * Note that it does NOT necessarily include the file name.
239 * Sometimes we don't even have any command line options at all.
241 static inline char *build_command_line( char **argv )
243 int len, quote = 0;
244 char *cmdline, *p, **arg;
246 for (arg = argv, len = 0; *arg; arg++) len += strlen(*arg) + 1;
247 if ((argv[0]) && (quote = (strchr( argv[0], ' ' ) != NULL))) len += 2;
248 if (!(p = cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
249 arg = argv;
250 if (quote)
252 *p++ = '\"';
253 strcpy( p, *arg );
254 p += strlen(p);
255 *p++ = '\"';
256 *p++ = ' ';
257 arg++;
259 while (*arg)
261 strcpy( p, *arg );
262 p += strlen(p);
263 *p++ = ' ';
264 arg++;
266 if (p > cmdline) p--; /* remove last space */
267 *p = 0;
268 return cmdline;
272 /***********************************************************************
273 * start_process
275 * Startup routine of a new process. Runs on the new process stack.
277 static void start_process(void)
279 int debugged, console_app;
280 LPTHREAD_START_ROUTINE entry;
281 WINE_MODREF *wm;
283 /* build command line */
284 if (!(current_envdb.cmd_line = build_command_line( main_exe_argv ))) goto error;
286 /* create 32-bit module for main exe */
287 if (!(main_module = BUILTIN32_LoadExeModule( main_module ))) goto error;
289 /* use original argv[0] as name for the main module */
290 if (!main_exe_name[0])
292 if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
293 lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
296 /* Retrieve entry point address */
297 entry = (LPTHREAD_START_ROUTINE)((char*)main_module +
298 PE_HEADER(main_module)->OptionalHeader.AddressOfEntryPoint);
299 console_app = (PE_HEADER(main_module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
300 if (console_app) current_process.flags |= PDB32_CONSOLE_PROC;
302 /* Signal the parent process to continue */
303 SERVER_START_REQ
305 struct init_process_done_request *req = server_alloc_req( sizeof(*req), 0 );
306 req->module = (void *)main_module;
307 req->entry = entry;
308 req->name = main_exe_name;
309 req->gui = !console_app;
310 server_call( REQ_INIT_PROCESS_DONE );
311 debugged = req->debugged;
313 SERVER_END_REQ;
315 /* Install signal handlers; this cannot be done before, since we cannot
316 * send exceptions to the debugger before the create process event that
317 * is sent by REQ_INIT_PROCESS_DONE */
318 if (!SIGNAL_Init()) goto error;
320 /* create the main modref and load dependencies */
321 if (!(wm = PE_CreateModule( main_module, main_exe_name, 0, main_exe_file, FALSE )))
322 goto error;
323 wm->refCount++;
325 EnterCriticalSection( &current_process.crit_section );
326 PE_InitTls();
327 MODULE_DllProcessAttach( current_process.exe_modref, (LPVOID)1 );
328 LeaveCriticalSection( &current_process.crit_section );
330 /* Get pointers to USER routines called by KERNEL */
331 THUNK_InitCallout();
333 /* Call FinalUserInit routine */
334 if (Callout.FinalUserInit16) Callout.FinalUserInit16();
336 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
337 * context of the parent process. Actually, the USER signal proc
338 * doesn't really care about that, but it *does* require that the
339 * startup parameters are correctly set up, so that GetProcessDword
340 * works. Furthermore, before calling the USER signal proc the
341 * 16-bit stack must be set up, which it is only after TASK_Create
342 * in the case of a 16-bit process. Thus, we send the signal here.
344 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
345 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
346 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
347 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
348 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
349 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
351 TRACE_(relay)( "Starting Win32 process (entryproc=%p)\n", entry );
352 if (debugged) DbgBreakPoint();
353 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
354 * Dunno about other OSs */
355 SetLastError(0); /* clear error code */
356 ExitThread( entry(NULL) );
358 error:
359 ExitProcess( GetLastError() );
363 /***********************************************************************
364 * open_winelib_app
366 * Try to open the Winelib app .so file based on argv[0] or WINEPRELOAD.
368 void *open_winelib_app( const char *argv0 )
370 void *ret = NULL;
371 char *tmp;
372 const char *name;
374 if ((name = getenv( "WINEPRELOAD" )))
376 ret = wine_dll_load_main_exe( name, 0 );
378 else
380 /* if argv[0] is "wine", don't try to load anything */
381 if (!(name = strrchr( argv0, '/' ))) name = argv0;
382 else name++;
383 if (!strcmp( name, "wine" )) return NULL;
385 /* now try argv[0] with ".so" appended */
386 if ((tmp = HeapAlloc( GetProcessHeap(), 0, strlen(argv0) + 4 )))
388 strcpy( tmp, argv0 );
389 strcat( tmp, ".so" );
390 /* search in PATH only if there was no '/' in argv[0] */
391 ret = wine_dll_load_main_exe( tmp, (name == argv0) );
392 HeapFree( GetProcessHeap(), 0, tmp );
395 return ret;
398 /***********************************************************************
399 * PROCESS_InitWine
401 * Wine initialisation: load and start the main exe file.
403 void PROCESS_InitWine( int argc, char *argv[] )
405 DWORD stack_size = 0;
407 /* Initialize everything */
408 if (!process_init( argv )) exit(1);
410 if (open_winelib_app( argv[0] )) goto found; /* try to open argv[0] as a winelib app */
412 main_exe_argv = ++argv; /* remove argv[0] (wine itself) */
414 if (!main_exe_name[0])
416 if (!argv[0]) OPTIONS_Usage();
418 /* open the exe file */
419 if (!SearchPathA( NULL, argv[0], ".exe", sizeof(main_exe_name), main_exe_name, NULL ) &&
420 !SearchPathA( NULL, argv[0], NULL, sizeof(main_exe_name), main_exe_name, NULL ))
422 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
423 goto error;
427 if (main_exe_file == INVALID_HANDLE_VALUE)
429 if ((main_exe_file = CreateFileA( main_exe_name, GENERIC_READ, FILE_SHARE_READ,
430 NULL, OPEN_EXISTING, 0, -1 )) == INVALID_HANDLE_VALUE)
432 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
433 goto error;
437 /* first try Win32 format; this will fail if the file is not a PE binary */
438 if ((main_module = PE_LoadImage( main_exe_file, main_exe_name, 0 )))
440 if (PE_HEADER(main_module)->FileHeader.Characteristics & IMAGE_FILE_DLL)
441 ExitProcess( ERROR_BAD_EXE_FORMAT );
442 stack_size = PE_HEADER(main_module)->OptionalHeader.SizeOfStackReserve;
443 goto found;
446 /* it must be 16-bit or DOS format */
447 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
448 current_process.flags |= PDB32_WIN16_PROC;
449 main_exe_name[0] = 0;
450 CloseHandle( main_exe_file );
451 main_exe_file = INVALID_HANDLE_VALUE;
452 _EnterWin16Lock();
454 found:
455 /* allocate main thread stack */
456 if (!THREAD_InitStack( NtCurrentTeb(), stack_size, TRUE )) goto error;
458 /* switch to the new stack */
459 SYSDEPS_SwitchToThreadStack( start_process );
461 error:
462 ExitProcess( GetLastError() );
466 /***********************************************************************
467 * PROCESS_InitWinelib
469 * Initialisation of a new Winelib process.
471 void PROCESS_InitWinelib( int argc, char *argv[] )
473 if (!process_init( argv )) exit(1);
475 /* allocate main thread stack */
476 if (!THREAD_InitStack( NtCurrentTeb(), 0, TRUE )) ExitProcess( GetLastError() );
478 /* switch to the new stack */
479 SYSDEPS_SwitchToThreadStack( start_process );
483 /***********************************************************************
484 * build_argv
486 * Build an argv array from a command-line.
487 * The command-line is modified to insert nulls.
488 * 'reserved' is the number of args to reserve before the first one.
490 static char **build_argv( char *cmdline, int reserved )
492 char **argv;
493 int count = reserved + 1;
494 char *p = cmdline;
496 /* if first word is quoted store it as a single arg */
497 if (*cmdline == '\"')
499 if ((p = strchr( cmdline + 1, '\"' )))
501 p++;
502 count++;
504 else p = cmdline;
506 while (*p)
508 while (*p && isspace(*p)) p++;
509 if (!*p) break;
510 count++;
511 while (*p && !isspace(*p)) p++;
514 if ((argv = malloc( count * sizeof(*argv) )))
516 char **argvptr = argv + reserved;
517 p = cmdline;
518 if (*cmdline == '\"')
520 if ((p = strchr( cmdline + 1, '\"' )))
522 *argvptr++ = cmdline + 1;
523 *p++ = 0;
525 else p = cmdline;
527 while (*p)
529 while (*p && isspace(*p)) *p++ = 0;
530 if (!*p) break;
531 *argvptr++ = p;
532 while (*p && !isspace(*p)) p++;
534 *argvptr = 0;
536 return argv;
540 /***********************************************************************
541 * build_envp
543 * Build the environment of a new child process.
545 static char **build_envp( const char *env, const char *extra_env )
547 const char *p;
548 char **envp;
549 int count = 0;
551 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
552 for (p = env; *p; count++) p += strlen(p) + 1;
553 count += 3;
555 if ((envp = malloc( count * sizeof(*envp) )))
557 extern char **environ;
558 char **envptr = envp;
559 char **unixptr = environ;
560 /* first the extra strings */
561 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
562 /* then put PATH, HOME and WINEPREFIX from the unix env */
563 for (unixptr = environ; unixptr && *unixptr; unixptr++)
564 if (!memcmp( *unixptr, "PATH=", 5 ) ||
565 !memcmp( *unixptr, "HOME=", 5 ) ||
566 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
567 /* now put the Windows environment strings */
568 for (p = env; *p; p += strlen(p) + 1)
570 if (memcmp( p, "PATH=", 5 ) &&
571 memcmp( p, "HOME=", 5 ) &&
572 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
574 *envptr = 0;
576 return envp;
580 /***********************************************************************
581 * exec_wine_binary
583 * Locate the Wine binary to exec for a new Win32 process.
585 static void exec_wine_binary( char **argv, char **envp )
587 const char *path, *pos, *ptr;
589 /* first, try for a WINELOADER environment variable */
590 argv[0] = getenv("WINELOADER");
591 if (argv[0])
592 execve( argv[0], argv, envp );
594 /* next, try bin directory */
595 argv[0] = BINDIR "/wine";
596 execve( argv[0], argv, envp );
598 /* now try the path of argv0 of the current binary */
599 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
600 if ((ptr = strrchr( full_argv0, '/' )))
602 memcpy( argv[0], full_argv0, ptr - full_argv0 );
603 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
604 execve( argv[0], argv, envp );
606 free( argv[0] );
608 /* now search in the Unix path */
609 if ((path = getenv( "PATH" )))
611 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
612 pos = path;
613 for (;;)
615 while (*pos == ':') pos++;
616 if (!*pos) break;
617 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
618 memcpy( argv[0], pos, ptr - pos );
619 strcpy( argv[0] + (ptr - pos), "/wine" );
620 execve( argv[0], argv, envp );
621 pos = ptr;
624 free( argv[0] );
626 /* finally try the current directory */
627 argv[0] = "./wine";
628 execve( argv[0], argv, envp );
632 /***********************************************************************
633 * fork_and_exec
635 * Fork and exec a new Unix process, checking for errors.
637 static int fork_and_exec( const char *filename, char *cmdline,
638 const char *env, const char *newdir )
640 int fd[2];
641 int pid, err;
642 char *extra_env = NULL;
644 if (!env)
646 env = GetEnvironmentStringsA();
647 extra_env = DRIVE_BuildEnv();
650 if (pipe(fd) == -1)
652 FILE_SetDosError();
653 return -1;
655 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
656 if (!(pid = fork())) /* child */
658 char **argv = build_argv( cmdline, filename ? 0 : 2 );
659 char **envp = build_envp( env, extra_env );
660 close( fd[0] );
662 if (newdir) chdir(newdir);
664 if (argv && envp)
666 if (!filename)
668 argv[1] = "--";
669 exec_wine_binary( argv, envp );
671 else execve( filename, argv, envp );
673 err = errno;
674 write( fd[1], &err, sizeof(err) );
675 _exit(1);
677 close( fd[1] );
678 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
680 errno = err;
681 pid = -1;
683 if (pid == -1) FILE_SetDosError();
684 close( fd[0] );
685 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
686 return pid;
690 /***********************************************************************
691 * PROCESS_Create
693 * Create a new process. If hFile is a valid handle we have an exe
694 * file, and we exec a new copy of wine to load it; otherwise we
695 * simply exec the specified filename as a Unix process.
697 BOOL PROCESS_Create( HFILE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
698 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
699 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
700 LPPROCESS_INFORMATION info, LPCSTR lpCurrentDirectory )
702 BOOL ret;
703 int pid;
704 const char *unixfilename = NULL;
705 const char *unixdir = NULL;
706 DOS_FULL_NAME full_name;
707 HANDLE load_done_evt = (HANDLE)-1;
709 info->hThread = info->hProcess = INVALID_HANDLE_VALUE;
711 if (lpCurrentDirectory)
713 if (DOSFS_GetFullName( lpCurrentDirectory, TRUE, &full_name ))
714 unixdir = full_name.long_name;
716 else
718 char buf[MAX_PATH];
719 if (GetCurrentDirectoryA(sizeof(buf),buf))
721 if (DOSFS_GetFullName( buf, TRUE, &full_name ))
722 unixdir = full_name.long_name;
726 /* create the process on the server side */
728 SERVER_START_REQ
730 size_t len = (hFile == -1) ? 0 : MAX_PATH;
731 struct new_process_request *req = server_alloc_req( sizeof(*req), len );
732 req->inherit_all = inherit;
733 req->create_flags = flags;
734 req->start_flags = startup->dwFlags;
735 req->exe_file = hFile;
736 if (startup->dwFlags & STARTF_USESTDHANDLES)
738 req->hstdin = startup->hStdInput;
739 req->hstdout = startup->hStdOutput;
740 req->hstderr = startup->hStdError;
742 else
744 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
745 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
746 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
748 req->cmd_show = startup->wShowWindow;
749 req->alloc_fd = 0;
751 if (hFile == -1) /* unix process */
753 unixfilename = filename;
754 if (DOSFS_GetFullName( filename, TRUE, &full_name ))
755 unixfilename = full_name.long_name;
757 else /* new wine process */
759 if (!GetLongPathNameA( filename, server_data_ptr(req), MAX_PATH ))
760 lstrcpynA( server_data_ptr(req), filename, MAX_PATH );
762 ret = !server_call( REQ_NEW_PROCESS );
764 SERVER_END_REQ;
765 if (!ret) return FALSE;
767 /* fork and execute */
769 pid = fork_and_exec( unixfilename, cmd_line, env, unixdir );
771 SERVER_START_REQ
773 struct wait_process_request *req = server_alloc_req( sizeof(*req), 0 );
774 req->cancel = (pid == -1);
775 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
776 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
777 req->timeout = 2000;
778 if ((ret = !server_call( REQ_WAIT_PROCESS )) && (pid != -1))
780 info->dwProcessId = (DWORD)req->pid;
781 info->dwThreadId = (DWORD)req->tid;
782 info->hProcess = req->phandle;
783 info->hThread = req->thandle;
784 load_done_evt = req->event;
787 SERVER_END_REQ;
788 if (!ret || (pid == -1)) goto error;
790 /* Wait until process is initialized (or initialization failed) */
791 if (load_done_evt != (HANDLE)-1)
793 DWORD res;
794 HANDLE handles[2];
796 handles[0] = info->hProcess;
797 handles[1] = load_done_evt;
798 res = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
799 CloseHandle( load_done_evt );
800 if (res == STATUS_WAIT_0) /* the process died */
802 DWORD exitcode;
803 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
804 CloseHandle( info->hThread );
805 CloseHandle( info->hProcess );
806 return FALSE;
809 return TRUE;
811 error:
812 if (load_done_evt != (HANDLE)-1) CloseHandle( load_done_evt );
813 if (info->hThread != INVALID_HANDLE_VALUE) CloseHandle( info->hThread );
814 if (info->hProcess != INVALID_HANDLE_VALUE) CloseHandle( info->hProcess );
815 return FALSE;
819 /***********************************************************************
820 * ExitProcess (KERNEL32.100)
822 void WINAPI ExitProcess( DWORD status )
824 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
825 SERVER_START_REQ
827 struct terminate_process_request *req = server_alloc_req( sizeof(*req), 0 );
828 /* send the exit code to the server */
829 req->handle = GetCurrentProcess();
830 req->exit_code = status;
831 server_call( REQ_TERMINATE_PROCESS );
833 SERVER_END_REQ;
834 exit( status );
837 /***********************************************************************
838 * ExitProcess16 (KERNEL.466)
840 void WINAPI ExitProcess16( WORD status )
842 DWORD count;
843 ReleaseThunkLock( &count );
844 ExitProcess( status );
847 /******************************************************************************
848 * TerminateProcess (KERNEL32.684)
850 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
852 NTSTATUS status = NtTerminateProcess( handle, exit_code );
853 if (status) SetLastError( RtlNtStatusToDosError(status) );
854 return !status;
858 /***********************************************************************
859 * GetProcessDword (KERNEL32.18) (KERNEL.485)
860 * 'Of course you cannot directly access Windows internal structures'
862 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
864 TDB *pTask;
865 DWORD x, y;
867 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
869 if (dwProcessID && dwProcessID != GetCurrentProcessId())
871 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
872 return 0;
875 switch ( offset )
877 case GPD_APP_COMPAT_FLAGS:
878 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
879 return pTask? pTask->compat_flags : 0;
881 case GPD_LOAD_DONE_EVENT:
882 return current_process.load_done_evt;
884 case GPD_HINSTANCE16:
885 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
886 return pTask? pTask->hInstance : 0;
888 case GPD_WINDOWS_VERSION:
889 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
890 return pTask? pTask->version : 0;
892 case GPD_THDB:
893 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
895 case GPD_PDB:
896 return (DWORD)&current_process;
898 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
899 return current_startupinfo.hStdOutput;
901 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
902 return current_startupinfo.hStdInput;
904 case GPD_STARTF_SHOWWINDOW:
905 return current_startupinfo.wShowWindow;
907 case GPD_STARTF_SIZE:
908 x = current_startupinfo.dwXSize;
909 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
910 y = current_startupinfo.dwYSize;
911 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
912 return MAKELONG( x, y );
914 case GPD_STARTF_POSITION:
915 x = current_startupinfo.dwX;
916 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
917 y = current_startupinfo.dwY;
918 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
919 return MAKELONG( x, y );
921 case GPD_STARTF_FLAGS:
922 return current_startupinfo.dwFlags;
924 case GPD_PARENT:
925 return 0;
927 case GPD_FLAGS:
928 return current_process.flags;
930 case GPD_USERDATA:
931 return current_process.process_dword;
933 default:
934 ERR_(win32)("Unknown offset %d\n", offset );
935 return 0;
939 /***********************************************************************
940 * SetProcessDword (KERNEL.484)
941 * 'Of course you cannot directly access Windows internal structures'
943 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
945 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
947 if (dwProcessID && dwProcessID != GetCurrentProcessId())
949 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
950 return;
953 switch ( offset )
955 case GPD_APP_COMPAT_FLAGS:
956 case GPD_LOAD_DONE_EVENT:
957 case GPD_HINSTANCE16:
958 case GPD_WINDOWS_VERSION:
959 case GPD_THDB:
960 case GPD_PDB:
961 case GPD_STARTF_SHELLDATA:
962 case GPD_STARTF_HOTKEY:
963 case GPD_STARTF_SHOWWINDOW:
964 case GPD_STARTF_SIZE:
965 case GPD_STARTF_POSITION:
966 case GPD_STARTF_FLAGS:
967 case GPD_PARENT:
968 case GPD_FLAGS:
969 ERR_(win32)("Not allowed to modify offset %d\n", offset );
970 break;
972 case GPD_USERDATA:
973 current_process.process_dword = value;
974 break;
976 default:
977 ERR_(win32)("Unknown offset %d\n", offset );
978 break;
983 /*********************************************************************
984 * OpenProcess (KERNEL32.543)
986 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
988 HANDLE ret = 0;
989 SERVER_START_REQ
991 struct open_process_request *req = server_alloc_req( sizeof(*req), 0 );
993 req->pid = (void *)id;
994 req->access = access;
995 req->inherit = inherit;
996 if (!server_call( REQ_OPEN_PROCESS )) ret = req->handle;
998 SERVER_END_REQ;
999 return ret;
1002 /*********************************************************************
1003 * MapProcessHandle (KERNEL.483)
1005 DWORD WINAPI MapProcessHandle( HANDLE handle )
1007 DWORD ret = 0;
1008 SERVER_START_REQ
1010 struct get_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1011 req->handle = handle;
1012 if (!server_call( REQ_GET_PROCESS_INFO )) ret = (DWORD)req->pid;
1014 SERVER_END_REQ;
1015 return ret;
1018 /***********************************************************************
1019 * SetPriorityClass (KERNEL32.503)
1021 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1023 BOOL ret;
1024 SERVER_START_REQ
1026 struct set_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1027 req->handle = hprocess;
1028 req->priority = priorityclass;
1029 req->mask = SET_PROCESS_INFO_PRIORITY;
1030 ret = !server_call( REQ_SET_PROCESS_INFO );
1032 SERVER_END_REQ;
1033 return ret;
1037 /***********************************************************************
1038 * GetPriorityClass (KERNEL32.250)
1040 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1042 DWORD ret = 0;
1043 SERVER_START_REQ
1045 struct get_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1046 req->handle = hprocess;
1047 if (!server_call( REQ_GET_PROCESS_INFO )) ret = req->priority;
1049 SERVER_END_REQ;
1050 return ret;
1054 /***********************************************************************
1055 * SetProcessAffinityMask (KERNEL32.662)
1057 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1059 BOOL ret;
1060 SERVER_START_REQ
1062 struct set_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1063 req->handle = hProcess;
1064 req->affinity = affmask;
1065 req->mask = SET_PROCESS_INFO_AFFINITY;
1066 ret = !server_call( REQ_SET_PROCESS_INFO );
1068 SERVER_END_REQ;
1069 return ret;
1072 /**********************************************************************
1073 * GetProcessAffinityMask (KERNEL32.373)
1075 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1076 LPDWORD lpProcessAffinityMask,
1077 LPDWORD lpSystemAffinityMask )
1079 BOOL ret = FALSE;
1080 SERVER_START_REQ
1082 struct get_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1083 req->handle = hProcess;
1084 if (!server_call( REQ_GET_PROCESS_INFO ))
1086 if (lpProcessAffinityMask) *lpProcessAffinityMask = req->process_affinity;
1087 if (lpSystemAffinityMask) *lpSystemAffinityMask = req->system_affinity;
1088 ret = TRUE;
1091 SERVER_END_REQ;
1092 return ret;
1096 /***********************************************************************
1097 * GetProcessVersion (KERNEL32)
1099 DWORD WINAPI GetProcessVersion( DWORD processid )
1101 IMAGE_NT_HEADERS *nt;
1103 if (processid && processid != GetCurrentProcessId())
1104 return 0; /* FIXME: should use ReadProcessMemory */
1105 if ((nt = RtlImageNtHeader( current_process.module )))
1106 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1107 nt->OptionalHeader.MinorSubsystemVersion);
1108 return 0;
1111 /***********************************************************************
1112 * GetProcessFlags (KERNEL32)
1114 DWORD WINAPI GetProcessFlags( DWORD processid )
1116 if (processid && processid != GetCurrentProcessId()) return 0;
1117 return current_process.flags;
1121 /***********************************************************************
1122 * SetProcessWorkingSetSize [KERNEL32.662]
1123 * Sets the min/max working set sizes for a specified process.
1125 * PARAMS
1126 * hProcess [I] Handle to the process of interest
1127 * minset [I] Specifies minimum working set size
1128 * maxset [I] Specifies maximum working set size
1130 * RETURNS STD
1132 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1133 DWORD maxset)
1135 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1136 if(( minset == (DWORD)-1) && (maxset == (DWORD)-1)) {
1137 /* Trim the working set to zero */
1138 /* Swap the process out of physical RAM */
1140 return TRUE;
1143 /***********************************************************************
1144 * GetProcessWorkingSetSize (KERNEL32)
1146 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1147 LPDWORD maxset)
1149 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1150 /* 32 MB working set size */
1151 if (minset) *minset = 32*1024*1024;
1152 if (maxset) *maxset = 32*1024*1024;
1153 return TRUE;
1156 /***********************************************************************
1157 * SetProcessShutdownParameters (KERNEL32)
1159 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1160 * Now tracks changes made (but does not act on these changes)
1162 static DWORD shutdown_flags = 0;
1163 static DWORD shutdown_priority = 0x280;
1165 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1167 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1168 shutdown_flags = flags;
1169 shutdown_priority = level;
1170 return TRUE;
1174 /***********************************************************************
1175 * GetProcessShutdownParameters (KERNEL32)
1178 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1180 *lpdwLevel = shutdown_priority;
1181 *lpdwFlags = shutdown_flags;
1182 return TRUE;
1186 /***********************************************************************
1187 * SetProcessPriorityBoost (KERNEL32)
1189 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1191 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1192 /* Say we can do it. I doubt the program will notice that we don't. */
1193 return TRUE;
1197 /***********************************************************************
1198 * ReadProcessMemory (KERNEL32)
1200 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1201 LPDWORD bytes_read )
1203 unsigned int offset = (unsigned int)addr % sizeof(int);
1204 unsigned int pos = 0, len, max;
1205 int res;
1207 if (bytes_read) *bytes_read = size;
1209 /* first time, read total length to check for permissions */
1210 len = (size + offset + sizeof(int) - 1) / sizeof(int);
1211 max = min( REQUEST_MAX_VAR_SIZE, len * sizeof(int) );
1213 for (;;)
1215 SERVER_START_REQ
1217 struct read_process_memory_request *req = server_alloc_req( sizeof(*req), max );
1218 req->handle = process;
1219 req->addr = (char *)addr + pos - offset;
1220 req->len = len;
1221 if (!(res = server_call( REQ_READ_PROCESS_MEMORY )))
1223 size_t result = server_data_size( req );
1224 if (result > size + offset) result = size + offset;
1225 memcpy( (char *)buffer + pos, server_data_ptr(req) + offset, result - offset );
1226 size -= result - offset;
1227 pos += result - offset;
1230 SERVER_END_REQ;
1231 if (res)
1233 if (bytes_read) *bytes_read = 0;
1234 return FALSE;
1236 if (!size) return TRUE;
1237 max = min( REQUEST_MAX_VAR_SIZE, size );
1238 len = (max + sizeof(int) - 1) / sizeof(int);
1239 offset = 0;
1244 /***********************************************************************
1245 * WriteProcessMemory (KERNEL32)
1247 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPVOID buffer, DWORD size,
1248 LPDWORD bytes_written )
1250 unsigned int first_offset, last_offset;
1251 unsigned int pos = 0, len, max, first_mask, last_mask;
1252 int res;
1254 if (!size)
1256 SetLastError( ERROR_INVALID_PARAMETER );
1257 return FALSE;
1259 if (bytes_written) *bytes_written = size;
1261 /* compute the mask for the first int */
1262 first_mask = ~0;
1263 first_offset = (unsigned int)addr % sizeof(int);
1264 memset( &first_mask, 0, first_offset );
1266 /* compute the mask for the last int */
1267 last_offset = (size + first_offset) % sizeof(int);
1268 last_mask = 0;
1269 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1271 /* for the first request, use the total length */
1272 len = (size + first_offset + sizeof(int) - 1) / sizeof(int);
1273 max = min( REQUEST_MAX_VAR_SIZE, len * sizeof(int) );
1275 for (;;)
1277 SERVER_START_REQ
1279 struct write_process_memory_request *req = server_alloc_req( sizeof(*req), max );
1280 req->handle = process;
1281 req->addr = (char *)addr - first_offset + pos;
1282 req->len = len;
1283 req->first_mask = (!pos) ? first_mask : ~0;
1284 if (size + first_offset <= max) /* last round */
1286 req->last_mask = last_mask;
1287 max = size + first_offset;
1289 else req->last_mask = ~0;
1291 memcpy( (char *)server_data_ptr(req) + first_offset, (char *)buffer + pos,
1292 max - first_offset );
1293 if (!(res = server_call( REQ_WRITE_PROCESS_MEMORY )))
1295 pos += max - first_offset;
1296 size -= max - first_offset;
1299 SERVER_END_REQ;
1300 if (res)
1302 if (bytes_written) *bytes_written = 0;
1303 return FALSE;
1305 if (!size) return TRUE;
1306 first_offset = 0;
1307 len = min( size + sizeof(int) - 1, REQUEST_MAX_VAR_SIZE ) / sizeof(int);
1308 max = len * sizeof(int);
1313 /***********************************************************************
1314 * RegisterServiceProcess (KERNEL, KERNEL32)
1316 * A service process calls this function to ensure that it continues to run
1317 * even after a user logged off.
1319 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1321 /* I don't think that Wine needs to do anything in that function */
1322 return 1; /* success */
1325 /***********************************************************************
1326 * GetExitCodeProcess [KERNEL32.325]
1328 * Gets termination status of specified process
1330 * RETURNS
1331 * Success: TRUE
1332 * Failure: FALSE
1334 BOOL WINAPI GetExitCodeProcess(
1335 HANDLE hProcess, /* [I] handle to the process */
1336 LPDWORD lpExitCode) /* [O] address to receive termination status */
1338 BOOL ret;
1339 SERVER_START_REQ
1341 struct get_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1342 req->handle = hProcess;
1343 ret = !server_call( REQ_GET_PROCESS_INFO );
1344 if (ret && lpExitCode) *lpExitCode = req->exit_code;
1346 SERVER_END_REQ;
1347 return ret;
1351 /***********************************************************************
1352 * SetErrorMode (KERNEL32.486)
1354 UINT WINAPI SetErrorMode( UINT mode )
1356 UINT old = current_process.error_mode;
1357 current_process.error_mode = mode;
1358 return old;
1361 /***********************************************************************
1362 * GetCurrentProcess (KERNEL32.198)
1364 #undef GetCurrentProcess
1365 HANDLE WINAPI GetCurrentProcess(void)
1367 return 0xffffffff;