Removed some unnecessary inclusions of wingdi.h and winuser.h
[wine/hacks.git] / scheduler / process.c
blob656e81d88b11f948ff06c4545f82a119e8ad684e
1 /*
2 * Win32 processes
4 * Copyright 1996, 1998 Alexandre Julliard
5 */
7 #include <assert.h>
8 #include <ctype.h>
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include "wine/winbase16.h"
16 #include "wine/exception.h"
17 #include "process.h"
18 #include "main.h"
19 #include "module.h"
20 #include "neexe.h"
21 #include "file.h"
22 #include "global.h"
23 #include "heap.h"
24 #include "task.h"
25 #include "ldt.h"
26 #include "syslevel.h"
27 #include "thread.h"
28 #include "winerror.h"
29 #include "pe_image.h"
30 #include "server.h"
31 #include "options.h"
32 #include "callback.h"
33 #include "debugtools.h"
35 DEFAULT_DEBUG_CHANNEL(process);
36 DECLARE_DEBUG_CHANNEL(relay);
37 DECLARE_DEBUG_CHANNEL(win32);
40 static ENVDB initial_envdb;
41 static STARTUPINFOA initial_startup;
42 static char **main_exe_argv;
43 static char *main_exe_name;
44 static HFILE main_exe_file = -1;
47 /***********************************************************************
48 * PROCESS_IdToPDB
50 * Convert a process id to a PDB, making sure it is valid.
52 PDB *PROCESS_IdToPDB( DWORD pid )
54 if (!pid || pid == GetCurrentProcessId()) return PROCESS_Current();
55 return NULL;
59 /***********************************************************************
60 * PROCESS_CallUserSignalProc
62 * FIXME: Some of the signals aren't sent correctly!
64 * The exact meaning of the USER signals is undocumented, but this
65 * should cover the basic idea:
67 * USIG_DLL_UNLOAD_WIN16
68 * This is sent when a 16-bit module is unloaded.
70 * USIG_DLL_UNLOAD_WIN32
71 * This is sent when a 32-bit module is unloaded.
73 * USIG_DLL_UNLOAD_ORPHANS
74 * This is sent after the last Win3.1 module is unloaded,
75 * to allow removal of orphaned menus.
77 * USIG_FAULT_DIALOG_PUSH
78 * USIG_FAULT_DIALOG_POP
79 * These are called to allow USER to prepare for displaying a
80 * fault dialog, even though the fault might have happened while
81 * inside a USER critical section.
83 * USIG_THREAD_INIT
84 * This is called from the context of a new thread, as soon as it
85 * has started to run.
87 * USIG_THREAD_EXIT
88 * This is called, still in its context, just before a thread is
89 * about to terminate.
91 * USIG_PROCESS_CREATE
92 * This is called, in the parent process context, after a new process
93 * has been created.
95 * USIG_PROCESS_INIT
96 * This is called in the new process context, just after the main thread
97 * has started execution (after the main thread's USIG_THREAD_INIT has
98 * been sent).
100 * USIG_PROCESS_LOADED
101 * This is called after the executable file has been loaded into the
102 * new process context.
104 * USIG_PROCESS_RUNNING
105 * This is called immediately before the main entry point is called.
107 * USIG_PROCESS_EXIT
108 * This is called in the context of a process that is about to
109 * terminate (but before the last thread's USIG_THREAD_EXIT has
110 * been sent).
112 * USIG_PROCESS_DESTROY
113 * This is called after a process has terminated.
116 * The meaning of the dwFlags bits is as follows:
118 * USIG_FLAGS_WIN32
119 * Current process is 32-bit.
121 * USIG_FLAGS_GUI
122 * Current process is a (Win32) GUI process.
124 * USIG_FLAGS_FEEDBACK
125 * Current process needs 'feedback' (determined from the STARTUPINFO
126 * flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
128 * USIG_FLAGS_FAULT
129 * The signal is being sent due to a fault.
131 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE hModule )
133 DWORD flags = PROCESS_Current()->flags;
134 DWORD startup_flags = PROCESS_Current()->env_db->startup_info->dwFlags;
135 DWORD dwFlags = 0;
137 /* Determine dwFlags */
139 if ( !(flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
141 if ( !(flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
143 if ( dwFlags & USIG_FLAGS_GUI )
145 /* Feedback defaults to ON */
146 if ( !(startup_flags & STARTF_FORCEOFFFEEDBACK) )
147 dwFlags |= USIG_FLAGS_FEEDBACK;
149 else
151 /* Feedback defaults to OFF */
152 if (startup_flags & STARTF_FORCEONFEEDBACK)
153 dwFlags |= USIG_FLAGS_FEEDBACK;
156 /* Convert module handle to 16-bit */
158 if ( HIWORD( hModule ) )
159 hModule = MapHModuleLS( hModule );
161 /* Call USER signal proc */
163 if ( Callout.UserSignalProc )
165 if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
166 Callout.UserSignalProc( uCode, GetCurrentThreadId(), dwFlags, hModule );
167 else
168 Callout.UserSignalProc( uCode, GetCurrentProcessId(), dwFlags, hModule );
173 /***********************************************************************
174 * process_init
176 * Main process initialisation code
178 static BOOL process_init( char *argv[] )
180 struct init_process_request *req;
181 PDB *pdb = PROCESS_Current();
183 /* store the program name */
184 argv0 = argv[0];
186 /* Fill the initial process structure */
187 pdb->exit_code = STILL_ACTIVE;
188 pdb->threads = 1;
189 pdb->running_threads = 1;
190 pdb->ring0_threads = 1;
191 pdb->env_db = &initial_envdb;
192 pdb->group = pdb;
193 pdb->priority = 8; /* Normal */
194 pdb->winver = 0xffff; /* to be determined */
195 initial_envdb.startup_info = &initial_startup;
197 /* Setup the server connection */
198 NtCurrentTeb()->socket = CLIENT_InitServer();
199 if (CLIENT_InitThread()) return FALSE;
201 /* Retrieve startup info from the server */
202 req = get_req_buffer();
203 req->ldt_copy = ldt_copy;
204 req->ldt_flags = ldt_flags_copy;
205 req->ppid = getppid();
206 if (server_call( REQ_INIT_PROCESS )) return FALSE;
207 main_exe_file = req->exe_file;
208 if (req->filename[0]) main_exe_name = strdup( req->filename );
209 initial_startup.dwFlags = req->start_flags;
210 initial_startup.wShowWindow = req->cmd_show;
211 initial_envdb.hStdin = initial_startup.hStdInput = req->hstdin;
212 initial_envdb.hStdout = initial_startup.hStdOutput = req->hstdout;
213 initial_envdb.hStderr = initial_startup.hStdError = req->hstderr;
215 /* Remember TEB selector of initial process for emergency use */
216 SYSLEVEL_EmergencyTeb = NtCurrentTeb()->teb_sel;
218 /* Create the system and process heaps */
219 if (!HEAP_CreateSystemHeap()) return FALSE;
220 pdb->heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
222 /* Copy the parent environment */
223 if (!ENV_BuildEnvironment()) return FALSE;
225 /* Create the SEGPTR heap */
226 if (!(SegptrHeap = HeapCreate( HEAP_WINE_SEGPTR, 0, 0 ))) return FALSE;
228 /* Initialize the critical sections */
229 InitializeCriticalSection( &pdb->crit_section );
230 InitializeCriticalSection( &initial_envdb.section );
232 /* Initialize syslevel handling */
233 SYSLEVEL_Init();
235 /* Parse command line arguments */
236 OPTIONS_ParseOptions( argv );
238 return MAIN_MainInit();
242 /***********************************************************************
243 * load_system_dlls
245 * Load system DLLs into the initial process (and initialize them)
247 static int load_system_dlls(void)
249 char driver[MAX_PATH];
251 PROFILE_GetWineIniString( "Wine", "GraphicsDriver", "x11drv", driver, sizeof(driver) );
252 if (!LoadLibraryA( driver ))
254 MESSAGE( "Could not load graphics driver '%s'\n", driver );
255 return 0;
258 if (!LoadLibraryA("USER32.DLL")) return 0;
260 /* Get pointers to USER routines called by KERNEL */
261 THUNK_InitCallout();
263 /* Call FinalUserInit routine */
264 Callout.FinalUserInit16();
266 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
267 * context of the parent process. Actually, the USER signal proc
268 * doesn't really care about that, but it *does* require that the
269 * startup parameters are correctly set up, so that GetProcessDword
270 * works. Furthermore, before calling the USER signal proc the
271 * 16-bit stack must be set up, which it is only after TASK_Create
272 * in the case of a 16-bit process. Thus, we send the signal here.
274 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
275 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
276 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
277 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
279 return 1;
283 /***********************************************************************
284 * build_command_line
286 * Build the command-line of a process from the argv array.
288 static inline char *build_command_line( char **argv )
290 int len, quote;
291 char *cmdline, *p, **arg;
293 for (arg = argv, len = 0; *arg; arg++) len += strlen(*arg) + 1;
294 if ((quote = (strchr( argv[0], ' ' ) != NULL))) len += 2;
295 if (!(p = cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
296 arg = argv;
297 if (quote)
299 *p++ = '\"';
300 strcpy( p, *arg );
301 p += strlen(p);
302 *p++ = '\"';
303 *p++ = ' ';
304 arg++;
306 while (*arg)
308 strcpy( p, *arg );
309 p += strlen(p);
310 *p++ = ' ';
311 arg++;
313 if (p > cmdline) p--; /* remove last space */
314 *p = 0;
315 return cmdline;
319 /***********************************************************************
320 * start_process
322 * Startup routine of a new process. Runs on the new process stack.
324 static void start_process(void)
326 struct init_process_done_request *req = get_req_buffer();
327 int debugged, console_app;
328 HMODULE16 hModule16;
329 UINT cmdShow = SW_SHOWNORMAL;
330 LPTHREAD_START_ROUTINE entry;
331 PDB *pdb = PROCESS_Current();
332 HMODULE module = pdb->exe_modref->module;
334 /* Increment EXE refcount */
335 pdb->exe_modref->refCount++;
337 /* build command line */
338 if (!(pdb->env_db->cmd_line = build_command_line( main_exe_argv ))) goto error;
340 /* Retrieve entry point address */
341 entry = (LPTHREAD_START_ROUTINE)RVA_PTR( module, OptionalHeader.AddressOfEntryPoint );
342 console_app = (PE_HEADER(module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
344 if (console_app) pdb->flags |= PDB32_CONSOLE_PROC;
346 /* Signal the parent process to continue */
347 req->module = (void *)module;
348 req->entry = entry;
349 req->name = &pdb->exe_modref->filename;
350 req->gui = !console_app;
351 server_call( REQ_INIT_PROCESS_DONE );
352 debugged = req->debugged;
354 /* Install signal handlers; this cannot be done before, since we cannot
355 * send exceptions to the debugger before the create process event that
356 * is sent by REQ_INIT_PROCESS_DONE */
357 if (!SIGNAL_Init()) goto error;
359 /* Load KERNEL (necessary for TASK_Create) */
360 if (!LoadLibraryA( "KERNEL32" )) goto error;
362 /* Create 16-bit dummy module */
363 if ((hModule16 = MODULE_CreateDummyModule( pdb->exe_modref->filename, module )) < 32)
364 ExitProcess( hModule16 );
366 if (pdb->env_db->startup_info->dwFlags & STARTF_USESHOWWINDOW)
367 cmdShow = pdb->env_db->startup_info->wShowWindow;
368 if (!TASK_Create( (NE_MODULE *)GlobalLock16( hModule16 ), cmdShow,
369 NtCurrentTeb(), NULL, 0 ))
370 goto error;
372 /* Load the system dlls */
373 if (!load_system_dlls()) goto error;
375 EnterCriticalSection( &pdb->crit_section );
376 PE_InitTls();
377 MODULE_DllProcessAttach( pdb->exe_modref, (LPVOID)1 );
378 LeaveCriticalSection( &pdb->crit_section );
380 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
381 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
383 TRACE_(relay)( "Starting Win32 process (entryproc=%p)\n", entry );
384 if (debugged) DbgBreakPoint();
385 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
386 * Dunno about other OSs */
387 ExitThread( entry(NULL) );
389 error:
390 ExitProcess( GetLastError() );
394 /***********************************************************************
395 * PROCESS_Start
397 * Startup routine of a new Win32 process once the main module has been loaded.
398 * The filename is free'd by this routine.
400 static void PROCESS_Start( HMODULE main_module, LPSTR filename ) WINE_NORETURN;
401 static void PROCESS_Start( HMODULE main_module, LPSTR filename )
403 if (!filename)
405 /* if no explicit filename, use argv[0] */
406 if (!(filename = malloc( MAX_PATH ))) ExitProcess(1);
407 if (!GetLongPathNameA( full_argv0, filename, MAX_PATH ))
408 lstrcpynA( filename, full_argv0, MAX_PATH );
411 /* load main module */
412 if (PE_HEADER(main_module)->FileHeader.Characteristics & IMAGE_FILE_DLL)
413 ExitProcess( ERROR_BAD_EXE_FORMAT );
415 /* Create 32-bit MODREF */
416 if (!PE_CreateModule( main_module, filename, 0, FALSE ))
417 goto error;
418 free( filename );
420 /* allocate main thread stack */
421 if (!THREAD_InitStack( NtCurrentTeb(),
422 PE_HEADER(main_module)->OptionalHeader.SizeOfStackReserve, TRUE ))
423 goto error;
425 /* switch to the new stack */
426 SYSDEPS_SwitchToThreadStack( start_process );
428 error:
429 ExitProcess( GetLastError() );
433 /***********************************************************************
434 * PROCESS_InitWine
436 * Wine initialisation: load and start the main exe file.
438 void PROCESS_InitWine( int argc, char *argv[] )
440 DWORD type;
442 /* Initialize everything */
443 if (!process_init( argv )) exit(1);
445 main_exe_argv = ++argv; /* remove argv[0] (wine itself) */
447 if (!main_exe_name)
449 char buffer[MAX_PATH];
450 if (!argv[0]) OPTIONS_Usage();
452 /* open the exe file */
453 if (!SearchPathA( NULL, argv[0], ".exe", sizeof(buffer), buffer, NULL ) &&
454 !SearchPathA( NULL, argv[0], NULL, sizeof(buffer), buffer, NULL ))
456 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
457 goto error;
459 if (!(main_exe_name = strdup(buffer)))
461 MESSAGE( "%s: out of memory\n", argv0 );
462 ExitProcess(1);
466 if (main_exe_file == INVALID_HANDLE_VALUE)
468 if ((main_exe_file = CreateFileA( main_exe_name, GENERIC_READ, FILE_SHARE_READ,
469 NULL, OPEN_EXISTING, 0, -1 )) == INVALID_HANDLE_VALUE)
471 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
472 goto error;
476 if (!MODULE_GetBinaryType( main_exe_file, main_exe_name, &type ))
478 MESSAGE( "%s: unrecognized executable '%s'\n", argv0, main_exe_name );
479 goto error;
482 switch (type)
484 case SCS_32BIT_BINARY:
486 HMODULE main_module = PE_LoadImage( main_exe_file, main_exe_name );
487 if (main_module) PROCESS_Start( main_module, main_exe_name );
489 break;
491 case SCS_WOW_BINARY:
493 HMODULE main_module;
494 /* create 32-bit module for main exe */
495 if (!(main_module = BUILTIN32_LoadExeModule())) goto error;
496 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
497 PROCESS_Current()->flags |= PDB32_WIN16_PROC;
498 SYSLEVEL_EnterWin16Lock();
499 PROCESS_Start( main_module, NULL );
501 break;
503 case SCS_DOS_BINARY:
504 FIXME( "DOS binaries support is broken at the moment; feel free to fix it...\n" );
505 SetLastError( ERROR_BAD_FORMAT );
506 break;
508 case SCS_PIF_BINARY:
509 case SCS_POSIX_BINARY:
510 case SCS_OS216_BINARY:
511 default:
512 MESSAGE( "%s: unrecognized executable '%s'\n", argv0, main_exe_name );
513 SetLastError( ERROR_BAD_FORMAT );
514 break;
516 error:
517 ExitProcess( GetLastError() );
521 /***********************************************************************
522 * PROCESS_InitWinelib
524 * Initialisation of a new Winelib process.
526 void PROCESS_InitWinelib( int argc, char *argv[] )
528 HMODULE main_module;
530 if (!process_init( argv )) exit(1);
532 /* create 32-bit module for main exe */
533 if (!(main_module = BUILTIN32_LoadExeModule())) ExitProcess( GetLastError() );
535 main_exe_argv = argv;
536 PROCESS_Start( main_module, NULL );
540 /***********************************************************************
541 * build_argv
543 * Build an argv array from a command-line.
544 * The command-line is modified to insert nulls.
545 * 'reserved' is the number of args to reserve before the first one.
547 static char **build_argv( char *cmdline, int reserved )
549 char **argv;
550 int count = reserved + 1;
551 char *p = cmdline;
553 /* if first word is quoted store it as a single arg */
554 if (*cmdline == '\"')
556 if ((p = strchr( cmdline + 1, '\"' )))
558 p++;
559 count++;
561 else p = cmdline;
563 while (*p)
565 while (*p && isspace(*p)) p++;
566 if (!*p) break;
567 count++;
568 while (*p && !isspace(*p)) p++;
571 if ((argv = malloc( count * sizeof(*argv) )))
573 char **argvptr = argv + reserved;
574 p = cmdline;
575 if (*cmdline == '\"')
577 if ((p = strchr( cmdline + 1, '\"' )))
579 *argvptr++ = cmdline + 1;
580 *p++ = 0;
582 else p = cmdline;
584 while (*p)
586 while (*p && isspace(*p)) *p++ = 0;
587 if (!*p) break;
588 *argvptr++ = p;
589 while (*p && !isspace(*p)) p++;
591 *argvptr = 0;
593 return argv;
597 /***********************************************************************
598 * build_envp
600 * Build the environment of a new child process.
602 static char **build_envp( const char *env )
604 const char *p;
605 char **envp;
606 int count;
608 for (p = env, count = 0; *p; count++) p += strlen(p) + 1;
609 count += 3;
610 if ((envp = malloc( count * sizeof(*envp) )))
612 extern char **environ;
613 char **envptr = envp;
614 char **unixptr = environ;
615 /* first put PATH, HOME and WINEPREFIX from the unix env */
616 for (unixptr = environ; unixptr && *unixptr; unixptr++)
617 if (!memcmp( *unixptr, "PATH=", 5 ) ||
618 !memcmp( *unixptr, "HOME=", 5 ) ||
619 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
620 /* now put the Windows environment strings */
621 for (p = env; *p; p += strlen(p) + 1)
623 if (memcmp( p, "PATH=", 5 ) &&
624 memcmp( p, "HOME=", 5 ) &&
625 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
627 *envptr = 0;
629 return envp;
633 /***********************************************************************
634 * find_wine_binary
636 * Locate the Wine binary to exec for a new Win32 process.
638 static void exec_wine_binary( char **argv, char **envp )
640 const char *path, *pos, *ptr;
642 /* first try bin directory */
643 argv[0] = BINDIR "/wine";
644 execve( argv[0], argv, envp );
646 /* now try the path of argv0 of the current binary */
647 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
648 if ((ptr = strrchr( full_argv0, '/' )))
650 memcpy( argv[0], full_argv0, ptr - full_argv0 );
651 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
652 execve( argv[0], argv, envp );
654 free( argv[0] );
656 /* now search in the Unix path */
657 if ((path = getenv( "PATH" )))
659 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
660 pos = path;
661 for (;;)
663 while (*pos == ':') pos++;
664 if (!*pos) break;
665 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
666 memcpy( argv[0], pos, ptr - pos );
667 strcpy( argv[0] + (ptr - pos), "/wine" );
668 execve( argv[0], argv, envp );
669 pos = ptr;
672 free( argv[0] );
674 /* finally try the current directory */
675 argv[0] = "./wine";
676 execve( argv[0], argv, envp );
680 /***********************************************************************
681 * fork_and_exec
683 * Fork and exec a new Unix process, checking for errors.
685 static int fork_and_exec( const char *filename, char *cmdline,
686 const char *env, const char *newdir )
688 int fd[2];
689 int pid, err;
691 if (pipe(fd) == -1)
693 FILE_SetDosError();
694 return -1;
696 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
697 if (!(pid = fork())) /* child */
699 char **argv = build_argv( cmdline, filename ? 0 : 2 );
700 char **envp = build_envp( env );
701 close( fd[0] );
703 if (newdir) chdir(newdir);
705 if (argv && envp)
707 if (!filename)
709 argv[1] = "--";
710 exec_wine_binary( argv, envp );
712 else execve( filename, argv, envp );
714 err = errno;
715 write( fd[1], &err, sizeof(err) );
716 _exit(1);
718 close( fd[1] );
719 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
721 errno = err;
722 pid = -1;
724 if (pid == -1) FILE_SetDosError();
725 close( fd[0] );
726 return pid;
730 /***********************************************************************
731 * PROCESS_Create
733 * Create a new process. If hFile is a valid handle we have an exe
734 * file, and we exec a new copy of wine to load it; otherwise we
735 * simply exec the specified filename as a Unix process.
737 BOOL PROCESS_Create( HFILE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
738 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
739 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
740 LPPROCESS_INFORMATION info, LPCSTR lpCurrentDirectory )
742 int pid;
743 const char *unixfilename = NULL;
744 const char *unixdir = NULL;
745 DOS_FULL_NAME full_name;
746 HANDLE load_done_evt = -1;
747 struct new_process_request *req = get_req_buffer();
748 struct wait_process_request *wait_req = get_req_buffer();
750 info->hThread = info->hProcess = INVALID_HANDLE_VALUE;
752 /* create the process on the server side */
754 req->inherit_all = inherit;
755 req->create_flags = flags;
756 req->start_flags = startup->dwFlags;
757 req->exe_file = hFile;
758 if (startup->dwFlags & STARTF_USESTDHANDLES)
760 req->hstdin = startup->hStdInput;
761 req->hstdout = startup->hStdOutput;
762 req->hstderr = startup->hStdError;
764 else
766 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
767 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
768 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
770 req->cmd_show = startup->wShowWindow;
771 req->alloc_fd = 0;
773 if (lpCurrentDirectory) {
774 if (DOSFS_GetFullName( lpCurrentDirectory, TRUE, &full_name ))
775 unixdir = full_name.long_name;
776 } else {
777 CHAR buf[260];
778 if (GetCurrentDirectoryA(sizeof(buf),buf)) {
779 if (DOSFS_GetFullName( buf, TRUE, &full_name ))
780 unixdir = full_name.long_name;
784 if (hFile == -1) /* unix process */
786 unixfilename = filename;
787 if (DOSFS_GetFullName( filename, TRUE, &full_name )) unixfilename = full_name.long_name;
788 req->filename[0] = 0;
790 else /* new wine process */
792 if (!GetLongPathNameA( filename, req->filename, server_remaining(req->filename) ))
793 lstrcpynA( req->filename, filename, server_remaining(req->filename) );
795 if (server_call( REQ_NEW_PROCESS )) return FALSE;
797 /* fork and execute */
799 pid = fork_and_exec( unixfilename, cmd_line, env ? env : GetEnvironmentStringsA(), unixdir );
801 wait_req->cancel = (pid == -1);
802 wait_req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
803 wait_req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
804 wait_req->timeout = 2000;
805 if (server_call( REQ_WAIT_PROCESS ) || (pid == -1)) goto error;
806 info->dwProcessId = (DWORD)wait_req->pid;
807 info->dwThreadId = (DWORD)wait_req->tid;
808 info->hProcess = wait_req->phandle;
809 info->hThread = wait_req->thandle;
810 load_done_evt = wait_req->event;
812 /* Wait until process is initialized (or initialization failed) */
813 if (load_done_evt != -1)
815 DWORD res;
816 HANDLE handles[2];
818 handles[0] = info->hProcess;
819 handles[1] = load_done_evt;
820 res = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
821 CloseHandle( load_done_evt );
822 if (res == STATUS_WAIT_0) /* the process died */
824 DWORD exitcode;
825 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
826 CloseHandle( info->hThread );
827 CloseHandle( info->hProcess );
828 return FALSE;
831 return TRUE;
833 error:
834 if (load_done_evt != -1) CloseHandle( load_done_evt );
835 if (info->hThread != INVALID_HANDLE_VALUE) CloseHandle( info->hThread );
836 if (info->hProcess != INVALID_HANDLE_VALUE) CloseHandle( info->hProcess );
837 return FALSE;
841 /***********************************************************************
842 * ExitProcess (KERNEL32.100)
844 void WINAPI ExitProcess( DWORD status )
846 struct terminate_process_request *req = get_req_buffer();
848 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
849 /* send the exit code to the server */
850 req->handle = GetCurrentProcess();
851 req->exit_code = status;
852 server_call( REQ_TERMINATE_PROCESS );
853 exit( status );
856 /***********************************************************************
857 * ExitProcess16 (KERNEL.466)
859 void WINAPI ExitProcess16( WORD status )
861 SYSLEVEL_ReleaseWin16Lock();
862 ExitProcess( status );
865 /******************************************************************************
866 * TerminateProcess (KERNEL32.684)
868 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
870 BOOL ret;
871 struct terminate_process_request *req = get_req_buffer();
872 req->handle = handle;
873 req->exit_code = exit_code;
874 if ((ret = !server_call( REQ_TERMINATE_PROCESS )) && req->self) exit( exit_code );
875 return ret;
879 /***********************************************************************
880 * GetProcessDword (KERNEL32.18) (KERNEL.485)
881 * 'Of course you cannot directly access Windows internal structures'
883 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
885 PDB *process = PROCESS_IdToPDB( dwProcessID );
886 TDB *pTask;
887 DWORD x, y;
889 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
890 if ( !process )
892 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
893 return 0;
896 switch ( offset )
898 case GPD_APP_COMPAT_FLAGS:
899 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
900 return pTask? pTask->compat_flags : 0;
902 case GPD_LOAD_DONE_EVENT:
903 return process->load_done_evt;
905 case GPD_HINSTANCE16:
906 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
907 return pTask? pTask->hInstance : 0;
909 case GPD_WINDOWS_VERSION:
910 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
911 return pTask? pTask->version : 0;
913 case GPD_THDB:
914 if ( process != PROCESS_Current() ) return 0;
915 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
917 case GPD_PDB:
918 return (DWORD)process;
920 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
921 return process->env_db->startup_info->hStdOutput;
923 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
924 return process->env_db->startup_info->hStdInput;
926 case GPD_STARTF_SHOWWINDOW:
927 return process->env_db->startup_info->wShowWindow;
929 case GPD_STARTF_SIZE:
930 x = process->env_db->startup_info->dwXSize;
931 if ( x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
932 y = process->env_db->startup_info->dwYSize;
933 if ( y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
934 return MAKELONG( x, y );
936 case GPD_STARTF_POSITION:
937 x = process->env_db->startup_info->dwX;
938 if ( x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
939 y = process->env_db->startup_info->dwY;
940 if ( y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
941 return MAKELONG( x, y );
943 case GPD_STARTF_FLAGS:
944 return process->env_db->startup_info->dwFlags;
946 case GPD_PARENT:
947 return 0;
949 case GPD_FLAGS:
950 return process->flags;
952 case GPD_USERDATA:
953 return process->process_dword;
955 default:
956 ERR_(win32)("Unknown offset %d\n", offset );
957 return 0;
961 /***********************************************************************
962 * SetProcessDword (KERNEL.484)
963 * 'Of course you cannot directly access Windows internal structures'
965 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
967 PDB *process = PROCESS_IdToPDB( dwProcessID );
969 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
970 if ( !process )
972 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
973 return;
976 switch ( offset )
978 case GPD_APP_COMPAT_FLAGS:
979 case GPD_LOAD_DONE_EVENT:
980 case GPD_HINSTANCE16:
981 case GPD_WINDOWS_VERSION:
982 case GPD_THDB:
983 case GPD_PDB:
984 case GPD_STARTF_SHELLDATA:
985 case GPD_STARTF_HOTKEY:
986 case GPD_STARTF_SHOWWINDOW:
987 case GPD_STARTF_SIZE:
988 case GPD_STARTF_POSITION:
989 case GPD_STARTF_FLAGS:
990 case GPD_PARENT:
991 case GPD_FLAGS:
992 ERR_(win32)("Not allowed to modify offset %d\n", offset );
993 break;
995 case GPD_USERDATA:
996 process->process_dword = value;
997 break;
999 default:
1000 ERR_(win32)("Unknown offset %d\n", offset );
1001 break;
1006 /*********************************************************************
1007 * OpenProcess (KERNEL32.543)
1009 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1011 HANDLE ret = 0;
1012 struct open_process_request *req = get_req_buffer();
1014 req->pid = (void *)id;
1015 req->access = access;
1016 req->inherit = inherit;
1017 if (!server_call( REQ_OPEN_PROCESS )) ret = req->handle;
1018 return ret;
1021 /*********************************************************************
1022 * MapProcessHandle (KERNEL.483)
1024 DWORD WINAPI MapProcessHandle( HANDLE handle )
1026 DWORD ret = 0;
1027 struct get_process_info_request *req = get_req_buffer();
1028 req->handle = handle;
1029 if (!server_call( REQ_GET_PROCESS_INFO )) ret = (DWORD)req->pid;
1030 return ret;
1033 /***********************************************************************
1034 * SetPriorityClass (KERNEL32.503)
1036 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1038 struct set_process_info_request *req = get_req_buffer();
1039 req->handle = hprocess;
1040 req->priority = priorityclass;
1041 req->mask = SET_PROCESS_INFO_PRIORITY;
1042 return !server_call( REQ_SET_PROCESS_INFO );
1046 /***********************************************************************
1047 * GetPriorityClass (KERNEL32.250)
1049 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1051 DWORD ret = 0;
1052 struct get_process_info_request *req = get_req_buffer();
1053 req->handle = hprocess;
1054 if (!server_call( REQ_GET_PROCESS_INFO )) ret = req->priority;
1055 return ret;
1059 /***********************************************************************
1060 * SetProcessAffinityMask (KERNEL32.662)
1062 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1064 struct set_process_info_request *req = get_req_buffer();
1065 req->handle = hProcess;
1066 req->affinity = affmask;
1067 req->mask = SET_PROCESS_INFO_AFFINITY;
1068 return !server_call( REQ_SET_PROCESS_INFO );
1071 /**********************************************************************
1072 * GetProcessAffinityMask (KERNEL32.373)
1074 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1075 LPDWORD lpProcessAffinityMask,
1076 LPDWORD lpSystemAffinityMask )
1078 BOOL ret = FALSE;
1079 struct get_process_info_request *req = get_req_buffer();
1080 req->handle = hProcess;
1081 if (!server_call( REQ_GET_PROCESS_INFO ))
1083 if (lpProcessAffinityMask) *lpProcessAffinityMask = req->process_affinity;
1084 if (lpSystemAffinityMask) *lpSystemAffinityMask = req->system_affinity;
1085 ret = TRUE;
1087 return ret;
1091 /***********************************************************************
1092 * GetStdHandle (KERNEL32.276)
1094 HANDLE WINAPI GetStdHandle( DWORD std_handle )
1096 PDB *pdb = PROCESS_Current();
1098 switch(std_handle)
1100 case STD_INPUT_HANDLE: return pdb->env_db->hStdin;
1101 case STD_OUTPUT_HANDLE: return pdb->env_db->hStdout;
1102 case STD_ERROR_HANDLE: return pdb->env_db->hStderr;
1104 SetLastError( ERROR_INVALID_PARAMETER );
1105 return INVALID_HANDLE_VALUE;
1109 /***********************************************************************
1110 * SetStdHandle (KERNEL32.506)
1112 BOOL WINAPI SetStdHandle( DWORD std_handle, HANDLE handle )
1114 PDB *pdb = PROCESS_Current();
1115 /* FIXME: should we close the previous handle? */
1116 switch(std_handle)
1118 case STD_INPUT_HANDLE:
1119 pdb->env_db->hStdin = handle;
1120 return TRUE;
1121 case STD_OUTPUT_HANDLE:
1122 pdb->env_db->hStdout = handle;
1123 return TRUE;
1124 case STD_ERROR_HANDLE:
1125 pdb->env_db->hStderr = handle;
1126 return TRUE;
1128 SetLastError( ERROR_INVALID_PARAMETER );
1129 return FALSE;
1132 /***********************************************************************
1133 * GetProcessVersion (KERNEL32)
1135 DWORD WINAPI GetProcessVersion( DWORD processid )
1137 TDB *pTask;
1138 PDB *pdb = PROCESS_IdToPDB( processid );
1140 if (!pdb) return 0;
1141 if (!(pTask = (TDB *)GlobalLock16( pdb->task ))) return 0;
1142 return (pTask->version&0xff) | (((pTask->version >>8) & 0xff)<<16);
1145 /***********************************************************************
1146 * GetProcessFlags (KERNEL32)
1148 DWORD WINAPI GetProcessFlags( DWORD processid )
1150 PDB *pdb = PROCESS_IdToPDB( processid );
1151 if (!pdb) return 0;
1152 return pdb->flags;
1155 /***********************************************************************
1156 * SetProcessWorkingSetSize [KERNEL32.662]
1157 * Sets the min/max working set sizes for a specified process.
1159 * PARAMS
1160 * hProcess [I] Handle to the process of interest
1161 * minset [I] Specifies minimum working set size
1162 * maxset [I] Specifies maximum working set size
1164 * RETURNS STD
1166 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1167 DWORD maxset)
1169 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1170 if(( minset == -1) && (maxset == -1)) {
1171 /* Trim the working set to zero */
1172 /* Swap the process out of physical RAM */
1174 return TRUE;
1177 /***********************************************************************
1178 * GetProcessWorkingSetSize (KERNEL32)
1180 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1181 LPDWORD maxset)
1183 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1184 /* 32 MB working set size */
1185 if (minset) *minset = 32*1024*1024;
1186 if (maxset) *maxset = 32*1024*1024;
1187 return TRUE;
1190 /***********************************************************************
1191 * SetProcessShutdownParameters (KERNEL32)
1193 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1194 * Now tracks changes made (but does not act on these changes)
1195 * NOTE: the definition for SHUTDOWN_NORETRY was done on guesswork.
1196 * It really shouldn't be here, but I'll move it when it's been checked!
1198 #define SHUTDOWN_NORETRY 1
1199 static unsigned int shutdown_noretry = 0;
1200 static unsigned int shutdown_priority = 0x280L;
1201 BOOL WINAPI SetProcessShutdownParameters(DWORD level,DWORD flags)
1203 if (flags & SHUTDOWN_NORETRY)
1204 shutdown_noretry = 1;
1205 else
1206 shutdown_noretry = 0;
1207 if (level > 0x100L && level < 0x3FFL)
1208 shutdown_priority = level;
1209 else
1211 ERR("invalid priority level 0x%08lx\n", level);
1212 return FALSE;
1214 return TRUE;
1218 /***********************************************************************
1219 * GetProcessShutdownParameters (KERNEL32)
1222 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel,
1223 LPDWORD lpdwFlags )
1225 (*lpdwLevel) = shutdown_priority;
1226 (*lpdwFlags) = (shutdown_noretry * SHUTDOWN_NORETRY);
1227 return TRUE;
1229 /***********************************************************************
1230 * SetProcessPriorityBoost (KERNEL32)
1232 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1234 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1235 /* Say we can do it. I doubt the program will notice that we don't. */
1236 return TRUE;
1240 /***********************************************************************
1241 * ReadProcessMemory (KERNEL32)
1243 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1244 LPDWORD bytes_read )
1246 struct read_process_memory_request *req = get_req_buffer();
1247 unsigned int offset = (unsigned int)addr % sizeof(int);
1248 unsigned int max = server_remaining( req->data ); /* max length in one request */
1249 unsigned int pos;
1251 if (bytes_read) *bytes_read = size;
1253 /* first time, read total length to check for permissions */
1254 req->handle = process;
1255 req->addr = (char *)addr - offset;
1256 req->len = (size + offset + sizeof(int) - 1) / sizeof(int);
1257 if (server_call( REQ_READ_PROCESS_MEMORY )) goto error;
1259 if (size <= max - offset)
1261 memcpy( buffer, (char *)req->data + offset, size );
1262 return TRUE;
1265 /* now take care of the remaining data */
1266 memcpy( buffer, (char *)req->data + offset, max - offset );
1267 pos = max - offset;
1268 size -= pos;
1269 while (size)
1271 if (max > size) max = size;
1272 req->handle = process;
1273 req->addr = (char *)addr + pos;
1274 req->len = (max + sizeof(int) - 1) / sizeof(int);
1275 if (server_call( REQ_READ_PROCESS_MEMORY )) goto error;
1276 memcpy( (char *)buffer + pos, (char *)req->data, max );
1277 size -= max;
1278 pos += max;
1280 return TRUE;
1282 error:
1283 if (bytes_read) *bytes_read = 0;
1284 return FALSE;
1288 /***********************************************************************
1289 * WriteProcessMemory (KERNEL32)
1291 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPVOID buffer, DWORD size,
1292 LPDWORD bytes_written )
1294 unsigned int first_offset, last_offset;
1295 struct write_process_memory_request *req = get_req_buffer();
1296 unsigned int max = server_remaining( req->data ); /* max length in one request */
1297 unsigned int pos, last_mask;
1299 if (!size)
1301 SetLastError( ERROR_INVALID_PARAMETER );
1302 return FALSE;
1304 if (bytes_written) *bytes_written = size;
1306 /* compute the mask for the first int */
1307 req->first_mask = ~0;
1308 first_offset = (unsigned int)addr % sizeof(int);
1309 memset( &req->first_mask, 0, first_offset );
1311 /* compute the mask for the last int */
1312 last_offset = (size + first_offset) % sizeof(int);
1313 last_mask = 0;
1314 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1316 req->handle = process;
1317 req->addr = (char *)addr - first_offset;
1318 /* for the first request, use the total length */
1319 req->len = (size + first_offset + sizeof(int) - 1) / sizeof(int);
1321 if (size + first_offset < max) /* we can do it in one round */
1323 memcpy( (char *)req->data + first_offset, buffer, size );
1324 req->last_mask = last_mask;
1325 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1326 return TRUE;
1329 /* needs multiple server calls */
1331 memcpy( (char *)req->data + first_offset, buffer, max - first_offset );
1332 req->last_mask = ~0;
1333 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1334 pos = max - first_offset;
1335 size -= pos;
1336 while (size)
1338 if (size <= max) /* last one */
1340 req->last_mask = last_mask;
1341 max = size;
1343 req->handle = process;
1344 req->addr = (char *)addr + pos;
1345 req->len = (max + sizeof(int) - 1) / sizeof(int);
1346 req->first_mask = ~0;
1347 memcpy( req->data, (char *) buffer + pos, max );
1348 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1349 pos += max;
1350 size -= max;
1352 return TRUE;
1354 error:
1355 if (bytes_written) *bytes_written = 0;
1356 return FALSE;
1361 /***********************************************************************
1362 * RegisterServiceProcess (KERNEL, KERNEL32)
1364 * A service process calls this function to ensure that it continues to run
1365 * even after a user logged off.
1367 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1369 /* I don't think that Wine needs to do anything in that function */
1370 return 1; /* success */
1373 /***********************************************************************
1374 * GetExitCodeProcess [KERNEL32.325]
1376 * Gets termination status of specified process
1378 * RETURNS
1379 * Success: TRUE
1380 * Failure: FALSE
1382 BOOL WINAPI GetExitCodeProcess(
1383 HANDLE hProcess, /* [I] handle to the process */
1384 LPDWORD lpExitCode) /* [O] address to receive termination status */
1386 BOOL ret = FALSE;
1387 struct get_process_info_request *req = get_req_buffer();
1388 req->handle = hProcess;
1389 if (!server_call( REQ_GET_PROCESS_INFO ))
1391 if (lpExitCode) *lpExitCode = req->exit_code;
1392 ret = TRUE;
1394 return ret;
1398 /***********************************************************************
1399 * SetErrorMode (KERNEL32.486)
1401 UINT WINAPI SetErrorMode( UINT mode )
1403 UINT old = PROCESS_Current()->error_mode;
1404 PROCESS_Current()->error_mode = mode;
1405 return old;
1408 /***********************************************************************
1409 * GetCurrentProcess (KERNEL32.198)
1411 #undef GetCurrentProcess
1412 HANDLE WINAPI GetCurrentProcess(void)
1414 return 0xffffffff;