Added sample config file in the new format.
[wine/multimedia.git] / scheduler / process.c
blob1a6217625fe37ccc35158d6414e31558cc3822f6
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 "file.h"
23 #include "global.h"
24 #include "heap.h"
25 #include "task.h"
26 #include "ldt.h"
27 #include "thread.h"
28 #include "winerror.h"
29 #include "server.h"
30 #include "options.h"
31 #include "callback.h"
32 #include "debugtools.h"
34 DEFAULT_DEBUG_CHANNEL(process);
35 DECLARE_DEBUG_CHANNEL(relay);
36 DECLARE_DEBUG_CHANNEL(win32);
38 PDB current_process;
40 static char **main_exe_argv;
41 static char main_exe_name[MAX_PATH];
42 static HANDLE main_exe_file = INVALID_HANDLE_VALUE;
43 static HMODULE main_module;
45 unsigned int server_startticks;
47 /***********************************************************************
48 * PROCESS_CallUserSignalProc
50 * FIXME: Some of the signals aren't sent correctly!
52 * The exact meaning of the USER signals is undocumented, but this
53 * should cover the basic idea:
55 * USIG_DLL_UNLOAD_WIN16
56 * This is sent when a 16-bit module is unloaded.
58 * USIG_DLL_UNLOAD_WIN32
59 * This is sent when a 32-bit module is unloaded.
61 * USIG_DLL_UNLOAD_ORPHANS
62 * This is sent after the last Win3.1 module is unloaded,
63 * to allow removal of orphaned menus.
65 * USIG_FAULT_DIALOG_PUSH
66 * USIG_FAULT_DIALOG_POP
67 * These are called to allow USER to prepare for displaying a
68 * fault dialog, even though the fault might have happened while
69 * inside a USER critical section.
71 * USIG_THREAD_INIT
72 * This is called from the context of a new thread, as soon as it
73 * has started to run.
75 * USIG_THREAD_EXIT
76 * This is called, still in its context, just before a thread is
77 * about to terminate.
79 * USIG_PROCESS_CREATE
80 * This is called, in the parent process context, after a new process
81 * has been created.
83 * USIG_PROCESS_INIT
84 * This is called in the new process context, just after the main thread
85 * has started execution (after the main thread's USIG_THREAD_INIT has
86 * been sent).
88 * USIG_PROCESS_LOADED
89 * This is called after the executable file has been loaded into the
90 * new process context.
92 * USIG_PROCESS_RUNNING
93 * This is called immediately before the main entry point is called.
95 * USIG_PROCESS_EXIT
96 * This is called in the context of a process that is about to
97 * terminate (but before the last thread's USIG_THREAD_EXIT has
98 * been sent).
100 * USIG_PROCESS_DESTROY
101 * This is called after a process has terminated.
104 * The meaning of the dwFlags bits is as follows:
106 * USIG_FLAGS_WIN32
107 * Current process is 32-bit.
109 * USIG_FLAGS_GUI
110 * Current process is a (Win32) GUI process.
112 * USIG_FLAGS_FEEDBACK
113 * Current process needs 'feedback' (determined from the STARTUPINFO
114 * flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
116 * USIG_FLAGS_FAULT
117 * The signal is being sent due to a fault.
119 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE hModule )
121 DWORD flags = current_process.flags;
122 DWORD startup_flags = current_startupinfo.dwFlags;
123 DWORD dwFlags = 0;
125 /* Determine dwFlags */
127 if ( !(flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
129 if ( !(flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
131 if ( dwFlags & USIG_FLAGS_GUI )
133 /* Feedback defaults to ON */
134 if ( !(startup_flags & STARTF_FORCEOFFFEEDBACK) )
135 dwFlags |= USIG_FLAGS_FEEDBACK;
137 else
139 /* Feedback defaults to OFF */
140 if (startup_flags & STARTF_FORCEONFEEDBACK)
141 dwFlags |= USIG_FLAGS_FEEDBACK;
144 /* Convert module handle to 16-bit */
146 if ( HIWORD( hModule ) )
147 hModule = MapHModuleLS( hModule );
149 /* Call USER signal proc */
151 if ( Callout.UserSignalProc )
153 if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
154 Callout.UserSignalProc( uCode, GetCurrentThreadId(), dwFlags, hModule );
155 else
156 Callout.UserSignalProc( uCode, GetCurrentProcessId(), dwFlags, hModule );
161 /***********************************************************************
162 * process_init
164 * Main process initialisation code
166 static BOOL process_init( char *argv[] )
168 BOOL ret;
170 /* store the program name */
171 argv0 = argv[0];
172 main_exe_argv = argv;
174 /* Fill the initial process structure */
175 current_process.exit_code = STILL_ACTIVE;
176 current_process.threads = 1;
177 current_process.running_threads = 1;
178 current_process.ring0_threads = 1;
179 current_process.group = &current_process;
180 current_process.priority = 8; /* Normal */
181 current_process.env_db = &current_envdb;
183 /* Setup the server connection */
184 NtCurrentTeb()->socket = CLIENT_InitServer();
185 if (CLIENT_InitThread()) return FALSE;
187 /* Retrieve startup info from the server */
188 SERVER_START_REQ
190 struct init_process_request *req = server_alloc_req( sizeof(*req),
191 sizeof(main_exe_name)-1 );
193 req->ldt_copy = &wine_ldt_copy;
194 req->ppid = getppid();
195 if ((ret = !server_call( REQ_INIT_PROCESS )))
197 size_t len = server_data_size( req );
198 memcpy( main_exe_name, server_data_ptr(req), len );
199 main_exe_name[len] = 0;
200 main_exe_file = req->exe_file;
201 current_startupinfo.dwFlags = req->start_flags;
202 server_startticks = req->server_start;
203 current_startupinfo.wShowWindow = req->cmd_show;
204 current_envdb.hStdin = current_startupinfo.hStdInput = req->hstdin;
205 current_envdb.hStdout = current_startupinfo.hStdOutput = req->hstdout;
206 current_envdb.hStderr = current_startupinfo.hStdError = req->hstderr;
209 SERVER_END_REQ;
210 if (!ret) return FALSE;
212 /* Create the system and process heaps */
213 if (!HEAP_CreateSystemHeap()) return FALSE;
214 current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
216 /* Copy the parent environment */
217 if (!ENV_BuildEnvironment()) return FALSE;
219 /* Initialize the critical sections */
220 InitializeCriticalSection( &current_process.crit_section );
222 /* Parse command line arguments */
223 OPTIONS_ParseOptions( argv );
225 return MAIN_MainInit();
229 /***********************************************************************
230 * build_command_line
232 * Build the command line of a process from the argv array.
234 * Note that it does NOT necessarily include the file name.
235 * Sometimes we don't even have any command line options at all.
237 static inline char *build_command_line( char **argv )
239 int len, quote = 0;
240 char *cmdline, *p, **arg;
242 for (arg = argv, len = 0; *arg; arg++) len += strlen(*arg) + 1;
243 if ((argv[0]) && (quote = (strchr( argv[0], ' ' ) != NULL))) len += 2;
244 if (!(p = cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
245 arg = argv;
246 if (quote)
248 *p++ = '\"';
249 strcpy( p, *arg );
250 p += strlen(p);
251 *p++ = '\"';
252 *p++ = ' ';
253 arg++;
255 while (*arg)
257 strcpy( p, *arg );
258 p += strlen(p);
259 *p++ = ' ';
260 arg++;
262 if (p > cmdline) p--; /* remove last space */
263 *p = 0;
264 return cmdline;
268 /***********************************************************************
269 * start_process
271 * Startup routine of a new process. Runs on the new process stack.
273 static void start_process(void)
275 int debugged, console_app;
276 LPTHREAD_START_ROUTINE entry;
277 WINE_MODREF *wm;
279 /* build command line */
280 if (!(current_envdb.cmd_line = build_command_line( main_exe_argv ))) goto error;
282 /* create 32-bit module for main exe */
283 if (!(main_module = BUILTIN32_LoadExeModule( main_module ))) goto error;
285 /* use original argv[0] as name for the main module */
286 if (!main_exe_name[0])
288 if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
289 lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
292 /* Retrieve entry point address */
293 entry = (LPTHREAD_START_ROUTINE)((char*)main_module +
294 PE_HEADER(main_module)->OptionalHeader.AddressOfEntryPoint);
295 console_app = (PE_HEADER(main_module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
296 if (console_app) current_process.flags |= PDB32_CONSOLE_PROC;
298 /* Signal the parent process to continue */
299 SERVER_START_REQ
301 struct init_process_done_request *req = server_alloc_req( sizeof(*req), 0 );
302 req->module = (void *)main_module;
303 req->entry = entry;
304 req->name = main_exe_name;
305 req->gui = !console_app;
306 server_call( REQ_INIT_PROCESS_DONE );
307 debugged = req->debugged;
309 SERVER_END_REQ;
311 /* Install signal handlers; this cannot be done before, since we cannot
312 * send exceptions to the debugger before the create process event that
313 * is sent by REQ_INIT_PROCESS_DONE */
314 if (!SIGNAL_Init()) goto error;
316 /* create the main modref and load dependencies */
317 if (!(wm = PE_CreateModule( main_module, main_exe_name, 0, main_exe_file, FALSE )))
318 goto error;
319 wm->refCount++;
321 EnterCriticalSection( &current_process.crit_section );
322 PE_InitTls();
323 MODULE_DllProcessAttach( current_process.exe_modref, (LPVOID)1 );
324 LeaveCriticalSection( &current_process.crit_section );
326 /* Get pointers to USER routines called by KERNEL */
327 THUNK_InitCallout();
329 /* Call FinalUserInit routine */
330 if (Callout.FinalUserInit16) Callout.FinalUserInit16();
332 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
333 * context of the parent process. Actually, the USER signal proc
334 * doesn't really care about that, but it *does* require that the
335 * startup parameters are correctly set up, so that GetProcessDword
336 * works. Furthermore, before calling the USER signal proc the
337 * 16-bit stack must be set up, which it is only after TASK_Create
338 * in the case of a 16-bit process. Thus, we send the signal here.
340 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
341 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
342 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
343 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
344 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
345 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
347 TRACE_(relay)( "Starting Win32 process %s (entryproc=%p)\n", current_process.exe_modref->filename, entry );
348 if (debugged) DbgBreakPoint();
349 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
350 * Dunno about other OSs */
351 SetLastError(0); /* clear error code */
352 ExitThread( entry(NULL) );
354 error:
355 ExitProcess( GetLastError() );
359 /***********************************************************************
360 * open_winelib_app
362 * Try to open the Winelib app .so file based on argv[0] or WINEPRELOAD.
364 void *open_winelib_app( char *argv[] )
366 void *ret = NULL;
367 char *tmp;
368 const char *name;
370 if ((name = getenv( "WINEPRELOAD" )))
372 if (!(ret = wine_dll_load_main_exe( name, 0 )))
374 MESSAGE( "%s: could not load '%s' as specified in the WINEPRELOAD environment variable\n",
375 argv[0], name );
376 ExitProcess(1);
379 else
381 /* if argv[0] is "wine", don't try to load anything */
382 if (!(name = strrchr( argv[0], '/' ))) name = argv[0];
383 else name++;
384 if (!strcmp( name, "wine" )) return NULL;
386 /* now try argv[0] with ".so" appended */
387 if ((tmp = HeapAlloc( GetProcessHeap(), 0, strlen(argv[0]) + 4 )))
389 strcpy( tmp, argv[0] );
390 strcat( tmp, ".so" );
391 /* search in PATH only if there was no '/' in argv[0] */
392 ret = wine_dll_load_main_exe( tmp, (name == argv[0]) );
393 if (!ret && !argv[1])
395 /* if no argv[1], this will be better than displaying usage */
396 MESSAGE( "%s: could not load library '%s' as Winelib application\n",
397 argv[0], tmp );
398 ExitProcess(1);
400 HeapFree( GetProcessHeap(), 0, tmp );
403 return ret;
406 /***********************************************************************
407 * PROCESS_InitWine
409 * Wine initialisation: load and start the main exe file.
411 void PROCESS_InitWine( int argc, char *argv[] )
413 DWORD stack_size = 0;
415 /* Initialize everything */
416 if (!process_init( argv )) exit(1);
418 if (open_winelib_app( argv )) goto found; /* try to open argv[0] as a winelib app */
420 main_exe_argv = ++argv; /* remove argv[0] (wine itself) */
422 if (!main_exe_name[0])
424 if (!argv[0]) OPTIONS_Usage();
426 /* open the exe file */
427 if (!SearchPathA( NULL, argv[0], ".exe", sizeof(main_exe_name), main_exe_name, NULL ) &&
428 !SearchPathA( NULL, argv[0], NULL, sizeof(main_exe_name), main_exe_name, NULL ))
430 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
431 goto error;
435 if (main_exe_file == INVALID_HANDLE_VALUE)
437 if ((main_exe_file = CreateFileA( main_exe_name, GENERIC_READ, FILE_SHARE_READ,
438 NULL, OPEN_EXISTING, 0, -1 )) == INVALID_HANDLE_VALUE)
440 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
441 goto error;
445 /* first try Win32 format; this will fail if the file is not a PE binary */
446 if ((main_module = PE_LoadImage( main_exe_file, main_exe_name, 0 )))
448 if (PE_HEADER(main_module)->FileHeader.Characteristics & IMAGE_FILE_DLL)
449 ExitProcess( ERROR_BAD_EXE_FORMAT );
450 stack_size = PE_HEADER(main_module)->OptionalHeader.SizeOfStackReserve;
451 goto found;
454 /* it must be 16-bit or DOS format */
455 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
456 current_process.flags |= PDB32_WIN16_PROC;
457 main_exe_name[0] = 0;
458 CloseHandle( main_exe_file );
459 main_exe_file = INVALID_HANDLE_VALUE;
460 _EnterWin16Lock();
462 found:
463 /* allocate main thread stack */
464 if (!THREAD_InitStack( NtCurrentTeb(), stack_size, TRUE )) goto error;
466 /* switch to the new stack */
467 SYSDEPS_SwitchToThreadStack( start_process );
469 error:
470 ExitProcess( GetLastError() );
474 /***********************************************************************
475 * PROCESS_InitWinelib
477 * Initialisation of a new Winelib process.
479 void PROCESS_InitWinelib( int argc, char *argv[] )
481 if (!process_init( argv )) exit(1);
483 /* allocate main thread stack */
484 if (!THREAD_InitStack( NtCurrentTeb(), 0, TRUE )) ExitProcess( GetLastError() );
486 /* switch to the new stack */
487 SYSDEPS_SwitchToThreadStack( start_process );
491 /***********************************************************************
492 * build_argv
494 * Build an argv array from a command-line.
495 * The command-line is modified to insert nulls.
496 * 'reserved' is the number of args to reserve before the first one.
498 static char **build_argv( char *cmdline, int reserved )
500 char **argv;
501 int count = reserved + 1;
502 char *p = cmdline;
504 /* if first word is quoted store it as a single arg */
505 if (*cmdline == '\"')
507 if ((p = strchr( cmdline + 1, '\"' )))
509 p++;
510 count++;
512 else p = cmdline;
514 while (*p)
516 while (*p && isspace(*p)) p++;
517 if (!*p) break;
518 count++;
519 while (*p && !isspace(*p)) p++;
522 if ((argv = malloc( count * sizeof(*argv) )))
524 char **argvptr = argv + reserved;
525 p = cmdline;
526 if (*cmdline == '\"')
528 if ((p = strchr( cmdline + 1, '\"' )))
530 *argvptr++ = cmdline + 1;
531 *p++ = 0;
533 else p = cmdline;
535 while (*p)
537 while (*p && isspace(*p)) *p++ = 0;
538 if (!*p) break;
539 *argvptr++ = p;
540 while (*p && !isspace(*p)) p++;
542 *argvptr = 0;
544 return argv;
548 /***********************************************************************
549 * build_envp
551 * Build the environment of a new child process.
553 static char **build_envp( const char *env, const char *extra_env )
555 const char *p;
556 char **envp;
557 int count = 0;
559 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
560 for (p = env; *p; count++) p += strlen(p) + 1;
561 count += 3;
563 if ((envp = malloc( count * sizeof(*envp) )))
565 extern char **environ;
566 char **envptr = envp;
567 char **unixptr = environ;
568 /* first the extra strings */
569 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
570 /* then put PATH, HOME and WINEPREFIX from the unix env */
571 for (unixptr = environ; unixptr && *unixptr; unixptr++)
572 if (!memcmp( *unixptr, "PATH=", 5 ) ||
573 !memcmp( *unixptr, "HOME=", 5 ) ||
574 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
575 /* now put the Windows environment strings */
576 for (p = env; *p; p += strlen(p) + 1)
578 if (memcmp( p, "PATH=", 5 ) &&
579 memcmp( p, "HOME=", 5 ) &&
580 memcmp( p, "WINEPRELOAD=", 12 ) &&
581 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
583 *envptr = 0;
585 return envp;
589 /***********************************************************************
590 * exec_wine_binary
592 * Locate the Wine binary to exec for a new Win32 process.
594 static void exec_wine_binary( char **argv, char **envp )
596 const char *path, *pos, *ptr;
598 /* first, try for a WINELOADER environment variable */
599 argv[0] = getenv("WINELOADER");
600 if (argv[0])
601 execve( argv[0], argv, envp );
603 /* next, try bin directory */
604 argv[0] = BINDIR "/wine";
605 execve( argv[0], argv, envp );
607 /* now try the path of argv0 of the current binary */
608 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
609 if ((ptr = strrchr( full_argv0, '/' )))
611 memcpy( argv[0], full_argv0, ptr - full_argv0 );
612 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
613 execve( argv[0], argv, envp );
615 free( argv[0] );
617 /* now search in the Unix path */
618 if ((path = getenv( "PATH" )))
620 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
621 pos = path;
622 for (;;)
624 while (*pos == ':') pos++;
625 if (!*pos) break;
626 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
627 memcpy( argv[0], pos, ptr - pos );
628 strcpy( argv[0] + (ptr - pos), "/wine" );
629 execve( argv[0], argv, envp );
630 pos = ptr;
633 free( argv[0] );
635 /* finally try the current directory */
636 argv[0] = "./wine";
637 execve( argv[0], argv, envp );
641 /***********************************************************************
642 * fork_and_exec
644 * Fork and exec a new Unix process, checking for errors.
646 static int fork_and_exec( const char *filename, char *cmdline,
647 const char *env, const char *newdir )
649 int fd[2];
650 int pid, err;
651 char *extra_env = NULL;
653 if (!env)
655 env = GetEnvironmentStringsA();
656 extra_env = DRIVE_BuildEnv();
659 if (pipe(fd) == -1)
661 FILE_SetDosError();
662 return -1;
664 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
665 if (!(pid = fork())) /* child */
667 char **argv = build_argv( cmdline, filename ? 0 : 2 );
668 char **envp = build_envp( env, extra_env );
669 close( fd[0] );
671 if (newdir) chdir(newdir);
673 if (argv && envp)
675 if (!filename)
677 argv[1] = "--";
678 exec_wine_binary( argv, envp );
680 else execve( filename, argv, envp );
682 err = errno;
683 write( fd[1], &err, sizeof(err) );
684 _exit(1);
686 close( fd[1] );
687 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
689 errno = err;
690 pid = -1;
692 if (pid == -1) FILE_SetDosError();
693 close( fd[0] );
694 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
695 return pid;
699 /***********************************************************************
700 * PROCESS_Create
702 * Create a new process. If hFile is a valid handle we have an exe
703 * file, and we exec a new copy of wine to load it; otherwise we
704 * simply exec the specified filename as a Unix process.
706 BOOL PROCESS_Create( HFILE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
707 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
708 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
709 LPPROCESS_INFORMATION info, LPCSTR lpCurrentDirectory )
711 BOOL ret;
712 int pid;
713 const char *unixfilename = NULL;
714 const char *unixdir = NULL;
715 DOS_FULL_NAME full_name;
716 HANDLE load_done_evt = (HANDLE)-1;
718 info->hThread = info->hProcess = INVALID_HANDLE_VALUE;
720 if (lpCurrentDirectory)
722 if (DOSFS_GetFullName( lpCurrentDirectory, TRUE, &full_name ))
723 unixdir = full_name.long_name;
725 else
727 char buf[MAX_PATH];
728 if (GetCurrentDirectoryA(sizeof(buf),buf))
730 if (DOSFS_GetFullName( buf, TRUE, &full_name ))
731 unixdir = full_name.long_name;
735 /* create the process on the server side */
737 SERVER_START_REQ
739 size_t len = (hFile == -1) ? 0 : MAX_PATH;
740 struct new_process_request *req = server_alloc_req( sizeof(*req), len );
741 req->inherit_all = inherit;
742 req->create_flags = flags;
743 req->start_flags = startup->dwFlags;
744 req->exe_file = hFile;
745 if (startup->dwFlags & STARTF_USESTDHANDLES)
747 req->hstdin = startup->hStdInput;
748 req->hstdout = startup->hStdOutput;
749 req->hstderr = startup->hStdError;
751 else
753 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
754 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
755 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
757 req->cmd_show = startup->wShowWindow;
758 req->alloc_fd = 0;
760 if (hFile == -1) /* unix process */
762 unixfilename = filename;
763 if (DOSFS_GetFullName( filename, TRUE, &full_name ))
764 unixfilename = full_name.long_name;
766 else /* new wine process */
768 if (!GetLongPathNameA( filename, server_data_ptr(req), MAX_PATH ))
769 lstrcpynA( server_data_ptr(req), filename, MAX_PATH );
771 ret = !server_call( REQ_NEW_PROCESS );
773 SERVER_END_REQ;
774 if (!ret) return FALSE;
776 /* fork and execute */
778 pid = fork_and_exec( unixfilename, cmd_line, env, unixdir );
780 SERVER_START_REQ
782 struct wait_process_request *req = server_alloc_req( sizeof(*req), 0 );
783 req->cancel = (pid == -1);
784 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
785 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
786 req->timeout = 2000;
787 if ((ret = !server_call( REQ_WAIT_PROCESS )) && (pid != -1))
789 info->dwProcessId = (DWORD)req->pid;
790 info->dwThreadId = (DWORD)req->tid;
791 info->hProcess = req->phandle;
792 info->hThread = req->thandle;
793 load_done_evt = req->event;
796 SERVER_END_REQ;
797 if (!ret || (pid == -1)) goto error;
799 /* Wait until process is initialized (or initialization failed) */
800 if (load_done_evt != (HANDLE)-1)
802 DWORD res;
803 HANDLE handles[2];
805 handles[0] = info->hProcess;
806 handles[1] = load_done_evt;
807 res = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
808 CloseHandle( load_done_evt );
809 if (res == STATUS_WAIT_0) /* the process died */
811 DWORD exitcode;
812 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
813 CloseHandle( info->hThread );
814 CloseHandle( info->hProcess );
815 return FALSE;
818 return TRUE;
820 error:
821 if (load_done_evt != (HANDLE)-1) CloseHandle( load_done_evt );
822 if (info->hThread != INVALID_HANDLE_VALUE) CloseHandle( info->hThread );
823 if (info->hProcess != INVALID_HANDLE_VALUE) CloseHandle( info->hProcess );
824 return FALSE;
828 /***********************************************************************
829 * ExitProcess (KERNEL32.100)
831 void WINAPI ExitProcess( DWORD status )
833 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
834 SERVER_START_REQ
836 struct terminate_process_request *req = server_alloc_req( sizeof(*req), 0 );
837 /* send the exit code to the server */
838 req->handle = GetCurrentProcess();
839 req->exit_code = status;
840 server_call( REQ_TERMINATE_PROCESS );
842 SERVER_END_REQ;
843 exit( status );
846 /***********************************************************************
847 * ExitProcess16 (KERNEL.466)
849 void WINAPI ExitProcess16( WORD status )
851 DWORD count;
852 ReleaseThunkLock( &count );
853 ExitProcess( status );
856 /******************************************************************************
857 * TerminateProcess (KERNEL32.684)
859 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
861 NTSTATUS status = NtTerminateProcess( handle, exit_code );
862 if (status) SetLastError( RtlNtStatusToDosError(status) );
863 return !status;
867 /***********************************************************************
868 * GetProcessDword (KERNEL32.18) (KERNEL.485)
869 * 'Of course you cannot directly access Windows internal structures'
871 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
873 TDB *pTask;
874 DWORD x, y;
876 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
878 if (dwProcessID && dwProcessID != GetCurrentProcessId())
880 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
881 return 0;
884 switch ( offset )
886 case GPD_APP_COMPAT_FLAGS:
887 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
888 return pTask? pTask->compat_flags : 0;
890 case GPD_LOAD_DONE_EVENT:
891 return current_process.load_done_evt;
893 case GPD_HINSTANCE16:
894 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
895 return pTask? pTask->hInstance : 0;
897 case GPD_WINDOWS_VERSION:
898 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
899 return pTask? pTask->version : 0;
901 case GPD_THDB:
902 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
904 case GPD_PDB:
905 return (DWORD)&current_process;
907 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
908 return current_startupinfo.hStdOutput;
910 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
911 return current_startupinfo.hStdInput;
913 case GPD_STARTF_SHOWWINDOW:
914 return current_startupinfo.wShowWindow;
916 case GPD_STARTF_SIZE:
917 x = current_startupinfo.dwXSize;
918 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
919 y = current_startupinfo.dwYSize;
920 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
921 return MAKELONG( x, y );
923 case GPD_STARTF_POSITION:
924 x = current_startupinfo.dwX;
925 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
926 y = current_startupinfo.dwY;
927 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
928 return MAKELONG( x, y );
930 case GPD_STARTF_FLAGS:
931 return current_startupinfo.dwFlags;
933 case GPD_PARENT:
934 return 0;
936 case GPD_FLAGS:
937 return current_process.flags;
939 case GPD_USERDATA:
940 return current_process.process_dword;
942 default:
943 ERR_(win32)("Unknown offset %d\n", offset );
944 return 0;
948 /***********************************************************************
949 * SetProcessDword (KERNEL.484)
950 * 'Of course you cannot directly access Windows internal structures'
952 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
954 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
956 if (dwProcessID && dwProcessID != GetCurrentProcessId())
958 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
959 return;
962 switch ( offset )
964 case GPD_APP_COMPAT_FLAGS:
965 case GPD_LOAD_DONE_EVENT:
966 case GPD_HINSTANCE16:
967 case GPD_WINDOWS_VERSION:
968 case GPD_THDB:
969 case GPD_PDB:
970 case GPD_STARTF_SHELLDATA:
971 case GPD_STARTF_HOTKEY:
972 case GPD_STARTF_SHOWWINDOW:
973 case GPD_STARTF_SIZE:
974 case GPD_STARTF_POSITION:
975 case GPD_STARTF_FLAGS:
976 case GPD_PARENT:
977 case GPD_FLAGS:
978 ERR_(win32)("Not allowed to modify offset %d\n", offset );
979 break;
981 case GPD_USERDATA:
982 current_process.process_dword = value;
983 break;
985 default:
986 ERR_(win32)("Unknown offset %d\n", offset );
987 break;
992 /*********************************************************************
993 * OpenProcess (KERNEL32.543)
995 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
997 HANDLE ret = 0;
998 SERVER_START_REQ
1000 struct open_process_request *req = server_alloc_req( sizeof(*req), 0 );
1002 req->pid = (void *)id;
1003 req->access = access;
1004 req->inherit = inherit;
1005 if (!server_call( REQ_OPEN_PROCESS )) ret = req->handle;
1007 SERVER_END_REQ;
1008 return ret;
1011 /*********************************************************************
1012 * MapProcessHandle (KERNEL.483)
1014 DWORD WINAPI MapProcessHandle( HANDLE handle )
1016 DWORD ret = 0;
1017 SERVER_START_REQ
1019 struct get_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1020 req->handle = handle;
1021 if (!server_call( REQ_GET_PROCESS_INFO )) ret = (DWORD)req->pid;
1023 SERVER_END_REQ;
1024 return ret;
1027 /***********************************************************************
1028 * SetPriorityClass (KERNEL32.503)
1030 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1032 BOOL ret;
1033 SERVER_START_REQ
1035 struct set_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1036 req->handle = hprocess;
1037 req->priority = priorityclass;
1038 req->mask = SET_PROCESS_INFO_PRIORITY;
1039 ret = !server_call( REQ_SET_PROCESS_INFO );
1041 SERVER_END_REQ;
1042 return ret;
1046 /***********************************************************************
1047 * GetPriorityClass (KERNEL32.250)
1049 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1051 DWORD ret = 0;
1052 SERVER_START_REQ
1054 struct get_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1055 req->handle = hprocess;
1056 if (!server_call( REQ_GET_PROCESS_INFO )) ret = req->priority;
1058 SERVER_END_REQ;
1059 return ret;
1063 /***********************************************************************
1064 * SetProcessAffinityMask (KERNEL32.662)
1066 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1068 BOOL ret;
1069 SERVER_START_REQ
1071 struct set_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1072 req->handle = hProcess;
1073 req->affinity = affmask;
1074 req->mask = SET_PROCESS_INFO_AFFINITY;
1075 ret = !server_call( REQ_SET_PROCESS_INFO );
1077 SERVER_END_REQ;
1078 return ret;
1081 /**********************************************************************
1082 * GetProcessAffinityMask (KERNEL32.373)
1084 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1085 LPDWORD lpProcessAffinityMask,
1086 LPDWORD lpSystemAffinityMask )
1088 BOOL ret = FALSE;
1089 SERVER_START_REQ
1091 struct get_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1092 req->handle = hProcess;
1093 if (!server_call( REQ_GET_PROCESS_INFO ))
1095 if (lpProcessAffinityMask) *lpProcessAffinityMask = req->process_affinity;
1096 if (lpSystemAffinityMask) *lpSystemAffinityMask = req->system_affinity;
1097 ret = TRUE;
1100 SERVER_END_REQ;
1101 return ret;
1105 /***********************************************************************
1106 * GetProcessVersion (KERNEL32)
1108 DWORD WINAPI GetProcessVersion( DWORD processid )
1110 IMAGE_NT_HEADERS *nt;
1112 if (processid && processid != GetCurrentProcessId())
1113 return 0; /* FIXME: should use ReadProcessMemory */
1114 if ((nt = RtlImageNtHeader( current_process.module )))
1115 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1116 nt->OptionalHeader.MinorSubsystemVersion);
1117 return 0;
1120 /***********************************************************************
1121 * GetProcessFlags (KERNEL32)
1123 DWORD WINAPI GetProcessFlags( DWORD processid )
1125 if (processid && processid != GetCurrentProcessId()) return 0;
1126 return current_process.flags;
1130 /***********************************************************************
1131 * SetProcessWorkingSetSize [KERNEL32.662]
1132 * Sets the min/max working set sizes for a specified process.
1134 * PARAMS
1135 * hProcess [I] Handle to the process of interest
1136 * minset [I] Specifies minimum working set size
1137 * maxset [I] Specifies maximum working set size
1139 * RETURNS STD
1141 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1142 DWORD maxset)
1144 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1145 if(( minset == (DWORD)-1) && (maxset == (DWORD)-1)) {
1146 /* Trim the working set to zero */
1147 /* Swap the process out of physical RAM */
1149 return TRUE;
1152 /***********************************************************************
1153 * GetProcessWorkingSetSize (KERNEL32)
1155 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1156 LPDWORD maxset)
1158 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1159 /* 32 MB working set size */
1160 if (minset) *minset = 32*1024*1024;
1161 if (maxset) *maxset = 32*1024*1024;
1162 return TRUE;
1165 /***********************************************************************
1166 * SetProcessShutdownParameters (KERNEL32)
1168 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1169 * Now tracks changes made (but does not act on these changes)
1171 static DWORD shutdown_flags = 0;
1172 static DWORD shutdown_priority = 0x280;
1174 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1176 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1177 shutdown_flags = flags;
1178 shutdown_priority = level;
1179 return TRUE;
1183 /***********************************************************************
1184 * GetProcessShutdownParameters (KERNEL32)
1187 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1189 *lpdwLevel = shutdown_priority;
1190 *lpdwFlags = shutdown_flags;
1191 return TRUE;
1195 /***********************************************************************
1196 * SetProcessPriorityBoost (KERNEL32)
1198 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1200 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1201 /* Say we can do it. I doubt the program will notice that we don't. */
1202 return TRUE;
1206 /***********************************************************************
1207 * ReadProcessMemory (KERNEL32)
1209 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1210 LPDWORD bytes_read )
1212 unsigned int offset = (unsigned int)addr % sizeof(int);
1213 unsigned int pos = 0, len, max;
1214 int res;
1216 if (bytes_read) *bytes_read = size;
1218 /* first time, read total length to check for permissions */
1219 len = (size + offset + sizeof(int) - 1) / sizeof(int);
1220 max = min( REQUEST_MAX_VAR_SIZE, len * sizeof(int) );
1222 for (;;)
1224 SERVER_START_REQ
1226 struct read_process_memory_request *req = server_alloc_req( sizeof(*req), max );
1227 req->handle = process;
1228 req->addr = (char *)addr + pos - offset;
1229 req->len = len;
1230 if (!(res = server_call( REQ_READ_PROCESS_MEMORY )))
1232 size_t result = server_data_size( req );
1233 if (result > size + offset) result = size + offset;
1234 memcpy( (char *)buffer + pos, server_data_ptr(req) + offset, result - offset );
1235 size -= result - offset;
1236 pos += result - offset;
1239 SERVER_END_REQ;
1240 if (res)
1242 if (bytes_read) *bytes_read = 0;
1243 return FALSE;
1245 if (!size) return TRUE;
1246 max = min( REQUEST_MAX_VAR_SIZE, size );
1247 len = (max + sizeof(int) - 1) / sizeof(int);
1248 offset = 0;
1253 /***********************************************************************
1254 * WriteProcessMemory (KERNEL32)
1256 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPVOID buffer, DWORD size,
1257 LPDWORD bytes_written )
1259 unsigned int first_offset, last_offset;
1260 unsigned int pos = 0, len, max, first_mask, last_mask;
1261 int res;
1263 if (!size)
1265 SetLastError( ERROR_INVALID_PARAMETER );
1266 return FALSE;
1268 if (bytes_written) *bytes_written = size;
1270 /* compute the mask for the first int */
1271 first_mask = ~0;
1272 first_offset = (unsigned int)addr % sizeof(int);
1273 memset( &first_mask, 0, first_offset );
1275 /* compute the mask for the last int */
1276 last_offset = (size + first_offset) % sizeof(int);
1277 last_mask = 0;
1278 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1280 /* for the first request, use the total length */
1281 len = (size + first_offset + sizeof(int) - 1) / sizeof(int);
1282 max = min( REQUEST_MAX_VAR_SIZE, len * sizeof(int) );
1284 for (;;)
1286 SERVER_START_REQ
1288 struct write_process_memory_request *req = server_alloc_req( sizeof(*req), max );
1289 req->handle = process;
1290 req->addr = (char *)addr - first_offset + pos;
1291 req->len = len;
1292 req->first_mask = (!pos) ? first_mask : ~0;
1293 if (size + first_offset <= max) /* last round */
1295 req->last_mask = last_mask;
1296 max = size + first_offset;
1298 else req->last_mask = ~0;
1300 memcpy( (char *)server_data_ptr(req) + first_offset, (char *)buffer + pos,
1301 max - first_offset );
1302 if (!(res = server_call( REQ_WRITE_PROCESS_MEMORY )))
1304 pos += max - first_offset;
1305 size -= max - first_offset;
1308 SERVER_END_REQ;
1309 if (res)
1311 if (bytes_written) *bytes_written = 0;
1312 return FALSE;
1314 if (!size) return TRUE;
1315 first_offset = 0;
1316 len = min( size + sizeof(int) - 1, REQUEST_MAX_VAR_SIZE ) / sizeof(int);
1317 max = len * sizeof(int);
1322 /***********************************************************************
1323 * RegisterServiceProcess (KERNEL, KERNEL32)
1325 * A service process calls this function to ensure that it continues to run
1326 * even after a user logged off.
1328 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1330 /* I don't think that Wine needs to do anything in that function */
1331 return 1; /* success */
1334 /***********************************************************************
1335 * GetExitCodeProcess [KERNEL32.325]
1337 * Gets termination status of specified process
1339 * RETURNS
1340 * Success: TRUE
1341 * Failure: FALSE
1343 BOOL WINAPI GetExitCodeProcess(
1344 HANDLE hProcess, /* [in] handle to the process */
1345 LPDWORD lpExitCode) /* [out] address to receive termination status */
1347 BOOL ret;
1348 SERVER_START_REQ
1350 struct get_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1351 req->handle = hProcess;
1352 ret = !server_call( REQ_GET_PROCESS_INFO );
1353 if (ret && lpExitCode) *lpExitCode = req->exit_code;
1355 SERVER_END_REQ;
1356 return ret;
1360 /***********************************************************************
1361 * SetErrorMode (KERNEL32.486)
1363 UINT WINAPI SetErrorMode( UINT mode )
1365 UINT old = current_process.error_mode;
1366 current_process.error_mode = mode;
1367 return old;
1370 /***********************************************************************
1371 * GetCurrentProcess (KERNEL32.198)
1373 #undef GetCurrentProcess
1374 HANDLE WINAPI GetCurrentProcess(void)
1376 return 0xffffffff;