4 * Copyright 1996, 1998 Alexandre Julliard
15 #include "wine/winbase16.h"
16 #include "wine/exception.h"
34 #include "debugtools.h"
36 DEFAULT_DEBUG_CHANNEL(process);
37 DECLARE_DEBUG_CHANNEL(relay);
38 DECLARE_DEBUG_CHANNEL(win32);
41 static ENVDB initial_envdb;
42 static STARTUPINFOA initial_startup;
43 static char **main_exe_argv;
44 static char *main_exe_name;
45 static HFILE main_exe_file = -1;
48 /***********************************************************************
51 * Convert a process id to a PDB, making sure it is valid.
53 PDB *PROCESS_IdToPDB( DWORD pid )
55 if (!pid || pid == GetCurrentProcessId()) return PROCESS_Current();
60 /***********************************************************************
61 * PROCESS_CallUserSignalProc
63 * FIXME: Some of the signals aren't sent correctly!
65 * The exact meaning of the USER signals is undocumented, but this
66 * should cover the basic idea:
68 * USIG_DLL_UNLOAD_WIN16
69 * This is sent when a 16-bit module is unloaded.
71 * USIG_DLL_UNLOAD_WIN32
72 * This is sent when a 32-bit module is unloaded.
74 * USIG_DLL_UNLOAD_ORPHANS
75 * This is sent after the last Win3.1 module is unloaded,
76 * to allow removal of orphaned menus.
78 * USIG_FAULT_DIALOG_PUSH
79 * USIG_FAULT_DIALOG_POP
80 * These are called to allow USER to prepare for displaying a
81 * fault dialog, even though the fault might have happened while
82 * inside a USER critical section.
85 * This is called from the context of a new thread, as soon as it
89 * This is called, still in its context, just before a thread is
93 * This is called, in the parent process context, after a new process
97 * This is called in the new process context, just after the main thread
98 * has started execution (after the main thread's USIG_THREAD_INIT has
101 * USIG_PROCESS_LOADED
102 * This is called after the executable file has been loaded into the
103 * new process context.
105 * USIG_PROCESS_RUNNING
106 * This is called immediately before the main entry point is called.
109 * This is called in the context of a process that is about to
110 * terminate (but before the last thread's USIG_THREAD_EXIT has
113 * USIG_PROCESS_DESTROY
114 * This is called after a process has terminated.
117 * The meaning of the dwFlags bits is as follows:
120 * Current process is 32-bit.
123 * Current process is a (Win32) GUI process.
125 * USIG_FLAGS_FEEDBACK
126 * Current process needs 'feedback' (determined from the STARTUPINFO
127 * flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
130 * The signal is being sent due to a fault.
132 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE hModule )
134 DWORD flags = PROCESS_Current()->flags;
135 DWORD startup_flags = PROCESS_Current()->env_db->startup_info->dwFlags;
138 /* Determine dwFlags */
140 if ( !(flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
142 if ( !(flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
144 if ( dwFlags & USIG_FLAGS_GUI )
146 /* Feedback defaults to ON */
147 if ( !(startup_flags & STARTF_FORCEOFFFEEDBACK) )
148 dwFlags |= USIG_FLAGS_FEEDBACK;
152 /* Feedback defaults to OFF */
153 if (startup_flags & STARTF_FORCEONFEEDBACK)
154 dwFlags |= USIG_FLAGS_FEEDBACK;
157 /* Convert module handle to 16-bit */
159 if ( HIWORD( hModule ) )
160 hModule = MapHModuleLS( hModule );
162 /* Call USER signal proc */
164 if ( Callout.UserSignalProc )
166 if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
167 Callout.UserSignalProc( uCode, GetCurrentThreadId(), dwFlags, hModule );
169 Callout.UserSignalProc( uCode, GetCurrentProcessId(), dwFlags, hModule );
174 /***********************************************************************
177 * Main process initialisation code
179 static BOOL process_init( char *argv[] )
181 struct init_process_request *req;
182 PDB *pdb = PROCESS_Current();
184 /* store the program name */
187 /* Fill the initial process structure */
188 pdb->exit_code = STILL_ACTIVE;
190 pdb->running_threads = 1;
191 pdb->ring0_threads = 1;
192 pdb->env_db = &initial_envdb;
194 pdb->priority = 8; /* Normal */
195 pdb->winver = 0xffff; /* to be determined */
196 initial_envdb.startup_info = &initial_startup;
198 /* Setup the server connection */
199 NtCurrentTeb()->socket = CLIENT_InitServer();
200 if (CLIENT_InitThread()) return FALSE;
202 /* Retrieve startup info from the server */
203 req = get_req_buffer();
204 req->ldt_copy = ldt_copy;
205 req->ldt_flags = ldt_flags_copy;
206 req->ppid = getppid();
207 if (server_call( REQ_INIT_PROCESS )) return FALSE;
208 main_exe_file = req->exe_file;
209 if (req->filename[0]) main_exe_name = strdup( req->filename );
210 initial_startup.dwFlags = req->start_flags;
211 initial_startup.wShowWindow = req->cmd_show;
212 initial_envdb.hStdin = initial_startup.hStdInput = req->hstdin;
213 initial_envdb.hStdout = initial_startup.hStdOutput = req->hstdout;
214 initial_envdb.hStderr = initial_startup.hStdError = req->hstderr;
216 /* Remember TEB selector of initial process for emergency use */
217 SYSLEVEL_EmergencyTeb = NtCurrentTeb()->teb_sel;
219 /* Create the system and process heaps */
220 if (!HEAP_CreateSystemHeap()) return FALSE;
221 pdb->heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
223 /* Copy the parent environment */
224 if (!ENV_BuildEnvironment()) return FALSE;
226 /* Create the SEGPTR heap */
227 if (!(SegptrHeap = HeapCreate( HEAP_WINE_SEGPTR, 0, 0 ))) return FALSE;
229 /* Initialize the critical sections */
230 InitializeCriticalSection( &pdb->crit_section );
231 InitializeCriticalSection( &initial_envdb.section );
233 /* Initialize syslevel handling */
236 /* Parse command line arguments */
237 OPTIONS_ParseOptions( argv );
239 return MAIN_MainInit();
243 /***********************************************************************
246 * Load system DLLs into the initial process (and initialize them)
248 static int load_system_dlls(void)
250 char driver[MAX_PATH];
252 PROFILE_GetWineIniString( "Wine", "GraphicsDriver", "x11drv", driver, sizeof(driver) );
253 if (!LoadLibraryA( driver ))
255 MESSAGE( "Could not load graphics driver '%s'\n", driver );
259 if (!LoadLibraryA("USER32.DLL")) return 0;
261 /* Get pointers to USER routines called by KERNEL */
264 /* Call FinalUserInit routine */
265 Callout.FinalUserInit16();
267 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
268 * context of the parent process. Actually, the USER signal proc
269 * doesn't really care about that, but it *does* require that the
270 * startup parameters are correctly set up, so that GetProcessDword
271 * works. Furthermore, before calling the USER signal proc the
272 * 16-bit stack must be set up, which it is only after TASK_Create
273 * in the case of a 16-bit process. Thus, we send the signal here.
275 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
276 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
277 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
278 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
284 /***********************************************************************
287 * Build the command-line of a process from the argv array.
289 static inline char *build_command_line( char **argv )
292 char *cmdline, *p, **arg;
294 for (arg = argv, len = 0; *arg; arg++) len += strlen(*arg) + 1;
295 if ((quote = (strchr( argv[0], ' ' ) != NULL))) len += 2;
296 if (!(p = cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
314 if (p > cmdline) p--; /* remove last space */
320 /***********************************************************************
323 * Startup routine of a new process. Runs on the new process stack.
325 static void start_process(void)
327 struct init_process_done_request *req = get_req_buffer();
328 int debugged, console_app;
330 UINT cmdShow = SW_SHOWNORMAL;
331 LPTHREAD_START_ROUTINE entry;
332 PDB *pdb = PROCESS_Current();
333 HMODULE module = pdb->exe_modref->module;
335 /* Increment EXE refcount */
336 pdb->exe_modref->refCount++;
338 /* build command line */
339 if (!(pdb->env_db->cmd_line = build_command_line( main_exe_argv ))) goto error;
341 /* Retrieve entry point address */
342 entry = (LPTHREAD_START_ROUTINE)RVA_PTR( module, OptionalHeader.AddressOfEntryPoint );
343 console_app = (PE_HEADER(module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
345 if (console_app) pdb->flags |= PDB32_CONSOLE_PROC;
347 /* Signal the parent process to continue */
348 req->module = (void *)module;
350 req->name = &pdb->exe_modref->filename;
351 req->gui = !console_app;
352 server_call( REQ_INIT_PROCESS_DONE );
353 debugged = req->debugged;
355 /* Install signal handlers; this cannot be done before, since we cannot
356 * send exceptions to the debugger before the create process event that
357 * is sent by REQ_INIT_PROCESS_DONE */
358 if (!SIGNAL_Init()) goto error;
360 /* Load KERNEL (necessary for TASK_Create) */
361 if (!LoadLibraryA( "KERNEL32" )) goto error;
363 /* Create 16-bit dummy module */
364 if ((hModule16 = MODULE_CreateDummyModule( pdb->exe_modref->filename, module )) < 32)
365 ExitProcess( hModule16 );
367 if (pdb->env_db->startup_info->dwFlags & STARTF_USESHOWWINDOW)
368 cmdShow = pdb->env_db->startup_info->wShowWindow;
369 if (!TASK_Create( (NE_MODULE *)GlobalLock16( hModule16 ), cmdShow,
370 NtCurrentTeb(), NULL, 0 ))
373 /* Load the system dlls */
374 if (!load_system_dlls()) goto error;
376 EnterCriticalSection( &pdb->crit_section );
378 MODULE_DllProcessAttach( pdb->exe_modref, (LPVOID)1 );
379 LeaveCriticalSection( &pdb->crit_section );
381 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
382 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
384 TRACE_(relay)( "Starting Win32 process (entryproc=%p)\n", entry );
385 if (debugged) DbgBreakPoint();
386 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
387 * Dunno about other OSs */
388 ExitThread( entry(NULL) );
391 ExitProcess( GetLastError() );
395 /***********************************************************************
398 * Startup routine of a new Win32 process once the main module has been loaded.
399 * The filename is free'd by this routine.
401 static void PROCESS_Start( HMODULE main_module, LPSTR filename ) WINE_NORETURN;
402 static void PROCESS_Start( HMODULE main_module, LPSTR filename )
406 /* if no explicit filename, use argv[0] */
407 if (!(filename = malloc( MAX_PATH ))) ExitProcess(1);
408 if (!GetLongPathNameA( full_argv0, filename, MAX_PATH ))
409 lstrcpynA( filename, full_argv0, MAX_PATH );
412 /* load main module */
413 if (PE_HEADER(main_module)->FileHeader.Characteristics & IMAGE_FILE_DLL)
414 ExitProcess( ERROR_BAD_EXE_FORMAT );
416 /* Create 32-bit MODREF */
417 if (!PE_CreateModule( main_module, filename, 0, FALSE ))
421 /* allocate main thread stack */
422 if (!THREAD_InitStack( NtCurrentTeb(),
423 PE_HEADER(main_module)->OptionalHeader.SizeOfStackReserve, TRUE ))
426 /* switch to the new stack */
427 SYSDEPS_SwitchToThreadStack( start_process );
430 ExitProcess( GetLastError() );
434 /***********************************************************************
437 * Wine initialisation: load and start the main exe file.
439 void PROCESS_InitWine( int argc, char *argv[] )
443 /* Initialize everything */
444 if (!process_init( argv )) exit(1);
446 main_exe_argv = ++argv; /* remove argv[0] (wine itself) */
450 char buffer[MAX_PATH];
451 if (!argv[0]) OPTIONS_Usage();
453 /* open the exe file */
454 if (!SearchPathA( NULL, argv[0], ".exe", sizeof(buffer), buffer, NULL ) &&
455 !SearchPathA( NULL, argv[0], NULL, sizeof(buffer), buffer, NULL ))
457 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
460 if (!(main_exe_name = strdup(buffer)))
462 MESSAGE( "%s: out of memory\n", argv0 );
467 if (main_exe_file == INVALID_HANDLE_VALUE)
469 if ((main_exe_file = CreateFileA( main_exe_name, GENERIC_READ, FILE_SHARE_READ,
470 NULL, OPEN_EXISTING, 0, -1 )) == INVALID_HANDLE_VALUE)
472 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
477 if (!MODULE_GetBinaryType( main_exe_file, main_exe_name, &type ))
479 MESSAGE( "%s: unrecognized executable '%s'\n", argv0, main_exe_name );
485 case SCS_32BIT_BINARY:
487 HMODULE main_module = PE_LoadImage( main_exe_file, main_exe_name );
488 if (main_module) PROCESS_Start( main_module, main_exe_name );
495 /* create 32-bit module for main exe */
496 if (!(main_module = BUILTIN32_LoadExeModule())) goto error;
497 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
498 PROCESS_Current()->flags |= PDB32_WIN16_PROC;
499 SYSLEVEL_EnterWin16Lock();
500 PROCESS_Start( main_module, NULL );
507 /* create 32-bit module for main exe */
508 if (!(main_module = BUILTIN32_LoadExeModule())) goto error;
509 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
510 if (!MZ_LoadImage( main_module, main_exe_file, main_exe_name )) goto error;
511 PROCESS_Start( main_module, NULL );
516 case SCS_POSIX_BINARY:
517 case SCS_OS216_BINARY:
519 MESSAGE( "%s: unrecognized executable '%s'\n", argv0, main_exe_name );
520 SetLastError( ERROR_BAD_FORMAT );
524 ExitProcess( GetLastError() );
528 /***********************************************************************
529 * PROCESS_InitWinelib
531 * Initialisation of a new Winelib process.
533 void PROCESS_InitWinelib( int argc, char *argv[] )
537 if (!process_init( argv )) exit(1);
539 /* create 32-bit module for main exe */
540 if (!(main_module = BUILTIN32_LoadExeModule())) ExitProcess( GetLastError() );
542 main_exe_argv = argv;
543 PROCESS_Start( main_module, NULL );
547 /***********************************************************************
550 * Build an argv array from a command-line.
551 * The command-line is modified to insert nulls.
552 * 'reserved' is the number of args to reserve before the first one.
554 static char **build_argv( char *cmdline, int reserved )
557 int count = reserved + 1;
560 /* if first word is quoted store it as a single arg */
561 if (*cmdline == '\"')
563 if ((p = strchr( cmdline + 1, '\"' )))
572 while (*p && isspace(*p)) p++;
575 while (*p && !isspace(*p)) p++;
578 if ((argv = malloc( count * sizeof(*argv) )))
580 char **argvptr = argv + reserved;
582 if (*cmdline == '\"')
584 if ((p = strchr( cmdline + 1, '\"' )))
586 *argvptr++ = cmdline + 1;
593 while (*p && isspace(*p)) *p++ = 0;
596 while (*p && !isspace(*p)) p++;
604 /***********************************************************************
607 * Build the environment of a new child process.
609 static char **build_envp( const char *env )
615 for (p = env, count = 0; *p; count++) p += strlen(p) + 1;
617 if ((envp = malloc( count * sizeof(*envp) )))
619 extern char **environ;
620 char **envptr = envp;
621 char **unixptr = environ;
622 /* first put PATH, HOME and WINEPREFIX from the unix env */
623 for (unixptr = environ; unixptr && *unixptr; unixptr++)
624 if (!memcmp( *unixptr, "PATH=", 5 ) ||
625 !memcmp( *unixptr, "HOME=", 5 ) ||
626 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
627 /* now put the Windows environment strings */
628 for (p = env; *p; p += strlen(p) + 1)
630 if (memcmp( p, "PATH=", 5 ) &&
631 memcmp( p, "HOME=", 5 ) &&
632 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
640 /***********************************************************************
643 * Locate the Wine binary to exec for a new Win32 process.
645 static void exec_wine_binary( char **argv, char **envp )
647 const char *path, *pos, *ptr;
649 /* first try bin directory */
650 argv[0] = BINDIR "/wine";
651 execve( argv[0], argv, envp );
653 /* now try the path of argv0 of the current binary */
654 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
655 if ((ptr = strrchr( full_argv0, '/' )))
657 memcpy( argv[0], full_argv0, ptr - full_argv0 );
658 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
659 execve( argv[0], argv, envp );
663 /* now search in the Unix path */
664 if ((path = getenv( "PATH" )))
666 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
670 while (*pos == ':') pos++;
672 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
673 memcpy( argv[0], pos, ptr - pos );
674 strcpy( argv[0] + (ptr - pos), "/wine" );
675 execve( argv[0], argv, envp );
681 /* finally try the current directory */
683 execve( argv[0], argv, envp );
687 /***********************************************************************
690 * Fork and exec a new Unix process, checking for errors.
692 static int fork_and_exec( const char *filename, char *cmdline,
693 const char *env, const char *newdir )
703 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
704 if (!(pid = fork())) /* child */
706 char **argv = build_argv( cmdline, filename ? 0 : 2 );
707 char **envp = build_envp( env );
710 if (newdir) chdir(newdir);
717 exec_wine_binary( argv, envp );
719 else execve( filename, argv, envp );
722 write( fd[1], &err, sizeof(err) );
726 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
731 if (pid == -1) FILE_SetDosError();
737 /***********************************************************************
740 * Create a new process. If hFile is a valid handle we have an exe
741 * file, and we exec a new copy of wine to load it; otherwise we
742 * simply exec the specified filename as a Unix process.
744 BOOL PROCESS_Create( HFILE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
745 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
746 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
747 LPPROCESS_INFORMATION info, LPCSTR lpCurrentDirectory )
750 const char *unixfilename = NULL;
751 const char *unixdir = NULL;
752 DOS_FULL_NAME full_name;
753 HANDLE load_done_evt = -1;
754 struct new_process_request *req = get_req_buffer();
755 struct wait_process_request *wait_req = get_req_buffer();
757 info->hThread = info->hProcess = INVALID_HANDLE_VALUE;
759 /* create the process on the server side */
761 req->inherit_all = inherit;
762 req->create_flags = flags;
763 req->start_flags = startup->dwFlags;
764 req->exe_file = hFile;
765 if (startup->dwFlags & STARTF_USESTDHANDLES)
767 req->hstdin = startup->hStdInput;
768 req->hstdout = startup->hStdOutput;
769 req->hstderr = startup->hStdError;
773 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
774 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
775 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
777 req->cmd_show = startup->wShowWindow;
780 if (lpCurrentDirectory) {
781 if (DOSFS_GetFullName( lpCurrentDirectory, TRUE, &full_name ))
782 unixdir = full_name.long_name;
785 if (GetCurrentDirectoryA(sizeof(buf),buf)) {
786 if (DOSFS_GetFullName( buf, TRUE, &full_name ))
787 unixdir = full_name.long_name;
791 if (hFile == -1) /* unix process */
793 unixfilename = filename;
794 if (DOSFS_GetFullName( filename, TRUE, &full_name )) unixfilename = full_name.long_name;
795 req->filename[0] = 0;
797 else /* new wine process */
799 if (!GetLongPathNameA( filename, req->filename, server_remaining(req->filename) ))
800 lstrcpynA( req->filename, filename, server_remaining(req->filename) );
802 if (server_call( REQ_NEW_PROCESS )) return FALSE;
804 /* fork and execute */
806 pid = fork_and_exec( unixfilename, cmd_line, env ? env : GetEnvironmentStringsA(), unixdir );
808 wait_req->cancel = (pid == -1);
809 wait_req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
810 wait_req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
811 wait_req->timeout = 2000;
812 if (server_call( REQ_WAIT_PROCESS ) || (pid == -1)) goto error;
813 info->dwProcessId = (DWORD)wait_req->pid;
814 info->dwThreadId = (DWORD)wait_req->tid;
815 info->hProcess = wait_req->phandle;
816 info->hThread = wait_req->thandle;
817 load_done_evt = wait_req->event;
819 /* Wait until process is initialized (or initialization failed) */
820 if (load_done_evt != -1)
825 handles[0] = info->hProcess;
826 handles[1] = load_done_evt;
827 res = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
828 CloseHandle( load_done_evt );
829 if (res == STATUS_WAIT_0) /* the process died */
832 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
833 CloseHandle( info->hThread );
834 CloseHandle( info->hProcess );
841 if (load_done_evt != -1) CloseHandle( load_done_evt );
842 if (info->hThread != INVALID_HANDLE_VALUE) CloseHandle( info->hThread );
843 if (info->hProcess != INVALID_HANDLE_VALUE) CloseHandle( info->hProcess );
848 /***********************************************************************
849 * ExitProcess (KERNEL32.100)
851 void WINAPI ExitProcess( DWORD status )
853 struct terminate_process_request *req = get_req_buffer();
855 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
856 /* send the exit code to the server */
857 req->handle = GetCurrentProcess();
858 req->exit_code = status;
859 server_call( REQ_TERMINATE_PROCESS );
863 /***********************************************************************
864 * ExitProcess16 (KERNEL.466)
866 void WINAPI ExitProcess16( WORD status )
868 SYSLEVEL_ReleaseWin16Lock();
869 ExitProcess( status );
872 /******************************************************************************
873 * TerminateProcess (KERNEL32.684)
875 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
878 struct terminate_process_request *req = get_req_buffer();
879 req->handle = handle;
880 req->exit_code = exit_code;
881 if ((ret = !server_call( REQ_TERMINATE_PROCESS )) && req->self) exit( exit_code );
886 /***********************************************************************
887 * GetProcessDword (KERNEL32.18) (KERNEL.485)
888 * 'Of course you cannot directly access Windows internal structures'
890 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
892 PDB *process = PROCESS_IdToPDB( dwProcessID );
896 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
899 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
905 case GPD_APP_COMPAT_FLAGS:
906 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
907 return pTask? pTask->compat_flags : 0;
909 case GPD_LOAD_DONE_EVENT:
910 return process->load_done_evt;
912 case GPD_HINSTANCE16:
913 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
914 return pTask? pTask->hInstance : 0;
916 case GPD_WINDOWS_VERSION:
917 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
918 return pTask? pTask->version : 0;
921 if ( process != PROCESS_Current() ) return 0;
922 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
925 return (DWORD)process;
927 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
928 return process->env_db->startup_info->hStdOutput;
930 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
931 return process->env_db->startup_info->hStdInput;
933 case GPD_STARTF_SHOWWINDOW:
934 return process->env_db->startup_info->wShowWindow;
936 case GPD_STARTF_SIZE:
937 x = process->env_db->startup_info->dwXSize;
938 if ( x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
939 y = process->env_db->startup_info->dwYSize;
940 if ( y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
941 return MAKELONG( x, y );
943 case GPD_STARTF_POSITION:
944 x = process->env_db->startup_info->dwX;
945 if ( x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
946 y = process->env_db->startup_info->dwY;
947 if ( y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
948 return MAKELONG( x, y );
950 case GPD_STARTF_FLAGS:
951 return process->env_db->startup_info->dwFlags;
957 return process->flags;
960 return process->process_dword;
963 ERR_(win32)("Unknown offset %d\n", offset );
968 /***********************************************************************
969 * SetProcessDword (KERNEL.484)
970 * 'Of course you cannot directly access Windows internal structures'
972 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
974 PDB *process = PROCESS_IdToPDB( dwProcessID );
976 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
979 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
985 case GPD_APP_COMPAT_FLAGS:
986 case GPD_LOAD_DONE_EVENT:
987 case GPD_HINSTANCE16:
988 case GPD_WINDOWS_VERSION:
991 case GPD_STARTF_SHELLDATA:
992 case GPD_STARTF_HOTKEY:
993 case GPD_STARTF_SHOWWINDOW:
994 case GPD_STARTF_SIZE:
995 case GPD_STARTF_POSITION:
996 case GPD_STARTF_FLAGS:
999 ERR_(win32)("Not allowed to modify offset %d\n", offset );
1003 process->process_dword = value;
1007 ERR_(win32)("Unknown offset %d\n", offset );
1013 /*********************************************************************
1014 * OpenProcess (KERNEL32.543)
1016 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1019 struct open_process_request *req = get_req_buffer();
1021 req->pid = (void *)id;
1022 req->access = access;
1023 req->inherit = inherit;
1024 if (!server_call( REQ_OPEN_PROCESS )) ret = req->handle;
1028 /*********************************************************************
1029 * MapProcessHandle (KERNEL.483)
1031 DWORD WINAPI MapProcessHandle( HANDLE handle )
1034 struct get_process_info_request *req = get_req_buffer();
1035 req->handle = handle;
1036 if (!server_call( REQ_GET_PROCESS_INFO )) ret = (DWORD)req->pid;
1040 /***********************************************************************
1041 * SetPriorityClass (KERNEL32.503)
1043 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1045 struct set_process_info_request *req = get_req_buffer();
1046 req->handle = hprocess;
1047 req->priority = priorityclass;
1048 req->mask = SET_PROCESS_INFO_PRIORITY;
1049 return !server_call( REQ_SET_PROCESS_INFO );
1053 /***********************************************************************
1054 * GetPriorityClass (KERNEL32.250)
1056 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1059 struct get_process_info_request *req = get_req_buffer();
1060 req->handle = hprocess;
1061 if (!server_call( REQ_GET_PROCESS_INFO )) ret = req->priority;
1066 /***********************************************************************
1067 * SetProcessAffinityMask (KERNEL32.662)
1069 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1071 struct set_process_info_request *req = get_req_buffer();
1072 req->handle = hProcess;
1073 req->affinity = affmask;
1074 req->mask = SET_PROCESS_INFO_AFFINITY;
1075 return !server_call( REQ_SET_PROCESS_INFO );
1078 /**********************************************************************
1079 * GetProcessAffinityMask (KERNEL32.373)
1081 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1082 LPDWORD lpProcessAffinityMask,
1083 LPDWORD lpSystemAffinityMask )
1086 struct get_process_info_request *req = get_req_buffer();
1087 req->handle = hProcess;
1088 if (!server_call( REQ_GET_PROCESS_INFO ))
1090 if (lpProcessAffinityMask) *lpProcessAffinityMask = req->process_affinity;
1091 if (lpSystemAffinityMask) *lpSystemAffinityMask = req->system_affinity;
1098 /***********************************************************************
1099 * GetStdHandle (KERNEL32.276)
1101 HANDLE WINAPI GetStdHandle( DWORD std_handle )
1103 PDB *pdb = PROCESS_Current();
1107 case STD_INPUT_HANDLE: return pdb->env_db->hStdin;
1108 case STD_OUTPUT_HANDLE: return pdb->env_db->hStdout;
1109 case STD_ERROR_HANDLE: return pdb->env_db->hStderr;
1111 SetLastError( ERROR_INVALID_PARAMETER );
1112 return INVALID_HANDLE_VALUE;
1116 /***********************************************************************
1117 * SetStdHandle (KERNEL32.506)
1119 BOOL WINAPI SetStdHandle( DWORD std_handle, HANDLE handle )
1121 PDB *pdb = PROCESS_Current();
1122 /* FIXME: should we close the previous handle? */
1125 case STD_INPUT_HANDLE:
1126 pdb->env_db->hStdin = handle;
1128 case STD_OUTPUT_HANDLE:
1129 pdb->env_db->hStdout = handle;
1131 case STD_ERROR_HANDLE:
1132 pdb->env_db->hStderr = handle;
1135 SetLastError( ERROR_INVALID_PARAMETER );
1139 /***********************************************************************
1140 * GetProcessVersion (KERNEL32)
1142 DWORD WINAPI GetProcessVersion( DWORD processid )
1145 PDB *pdb = PROCESS_IdToPDB( processid );
1148 if (!(pTask = (TDB *)GlobalLock16( pdb->task ))) return 0;
1149 return (pTask->version&0xff) | (((pTask->version >>8) & 0xff)<<16);
1152 /***********************************************************************
1153 * GetProcessFlags (KERNEL32)
1155 DWORD WINAPI GetProcessFlags( DWORD processid )
1157 PDB *pdb = PROCESS_IdToPDB( processid );
1162 /***********************************************************************
1163 * SetProcessWorkingSetSize [KERNEL32.662]
1164 * Sets the min/max working set sizes for a specified process.
1167 * hProcess [I] Handle to the process of interest
1168 * minset [I] Specifies minimum working set size
1169 * maxset [I] Specifies maximum working set size
1173 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1176 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1177 if(( minset == -1) && (maxset == -1)) {
1178 /* Trim the working set to zero */
1179 /* Swap the process out of physical RAM */
1184 /***********************************************************************
1185 * GetProcessWorkingSetSize (KERNEL32)
1187 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1190 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1191 /* 32 MB working set size */
1192 if (minset) *minset = 32*1024*1024;
1193 if (maxset) *maxset = 32*1024*1024;
1197 /***********************************************************************
1198 * SetProcessShutdownParameters (KERNEL32)
1200 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1201 * Now tracks changes made (but does not act on these changes)
1202 * NOTE: the definition for SHUTDOWN_NORETRY was done on guesswork.
1203 * It really shouldn't be here, but I'll move it when it's been checked!
1205 #define SHUTDOWN_NORETRY 1
1206 static unsigned int shutdown_noretry = 0;
1207 static unsigned int shutdown_priority = 0x280L;
1208 BOOL WINAPI SetProcessShutdownParameters(DWORD level,DWORD flags)
1210 if (flags & SHUTDOWN_NORETRY)
1211 shutdown_noretry = 1;
1213 shutdown_noretry = 0;
1214 if (level > 0x100L && level < 0x3FFL)
1215 shutdown_priority = level;
1218 ERR("invalid priority level 0x%08lx\n", level);
1225 /***********************************************************************
1226 * GetProcessShutdownParameters (KERNEL32)
1229 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel,
1232 (*lpdwLevel) = shutdown_priority;
1233 (*lpdwFlags) = (shutdown_noretry * SHUTDOWN_NORETRY);
1236 /***********************************************************************
1237 * SetProcessPriorityBoost (KERNEL32)
1239 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1241 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1242 /* Say we can do it. I doubt the program will notice that we don't. */
1247 /***********************************************************************
1248 * ReadProcessMemory (KERNEL32)
1250 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1251 LPDWORD bytes_read )
1253 struct read_process_memory_request *req = get_req_buffer();
1254 unsigned int offset = (unsigned int)addr % sizeof(int);
1255 unsigned int max = server_remaining( req->data ); /* max length in one request */
1258 if (bytes_read) *bytes_read = size;
1260 /* first time, read total length to check for permissions */
1261 req->handle = process;
1262 req->addr = (char *)addr - offset;
1263 req->len = (size + offset + sizeof(int) - 1) / sizeof(int);
1264 if (server_call( REQ_READ_PROCESS_MEMORY )) goto error;
1266 if (size <= max - offset)
1268 memcpy( buffer, (char *)req->data + offset, size );
1272 /* now take care of the remaining data */
1273 memcpy( buffer, (char *)req->data + offset, max - offset );
1278 if (max > size) max = size;
1279 req->handle = process;
1280 req->addr = (char *)addr + pos;
1281 req->len = (max + sizeof(int) - 1) / sizeof(int);
1282 if (server_call( REQ_READ_PROCESS_MEMORY )) goto error;
1283 memcpy( (char *)buffer + pos, (char *)req->data, max );
1290 if (bytes_read) *bytes_read = 0;
1295 /***********************************************************************
1296 * WriteProcessMemory (KERNEL32)
1298 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPVOID buffer, DWORD size,
1299 LPDWORD bytes_written )
1301 unsigned int first_offset, last_offset;
1302 struct write_process_memory_request *req = get_req_buffer();
1303 unsigned int max = server_remaining( req->data ); /* max length in one request */
1304 unsigned int pos, last_mask;
1308 SetLastError( ERROR_INVALID_PARAMETER );
1311 if (bytes_written) *bytes_written = size;
1313 /* compute the mask for the first int */
1314 req->first_mask = ~0;
1315 first_offset = (unsigned int)addr % sizeof(int);
1316 memset( &req->first_mask, 0, first_offset );
1318 /* compute the mask for the last int */
1319 last_offset = (size + first_offset) % sizeof(int);
1321 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1323 req->handle = process;
1324 req->addr = (char *)addr - first_offset;
1325 /* for the first request, use the total length */
1326 req->len = (size + first_offset + sizeof(int) - 1) / sizeof(int);
1328 if (size + first_offset < max) /* we can do it in one round */
1330 memcpy( (char *)req->data + first_offset, buffer, size );
1331 req->last_mask = last_mask;
1332 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1336 /* needs multiple server calls */
1338 memcpy( (char *)req->data + first_offset, buffer, max - first_offset );
1339 req->last_mask = ~0;
1340 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1341 pos = max - first_offset;
1345 if (size <= max) /* last one */
1347 req->last_mask = last_mask;
1350 req->handle = process;
1351 req->addr = (char *)addr + pos;
1352 req->len = (max + sizeof(int) - 1) / sizeof(int);
1353 req->first_mask = ~0;
1354 memcpy( req->data, (char *) buffer + pos, max );
1355 if (server_call( REQ_WRITE_PROCESS_MEMORY )) goto error;
1362 if (bytes_written) *bytes_written = 0;
1368 /***********************************************************************
1369 * RegisterServiceProcess (KERNEL, KERNEL32)
1371 * A service process calls this function to ensure that it continues to run
1372 * even after a user logged off.
1374 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1376 /* I don't think that Wine needs to do anything in that function */
1377 return 1; /* success */
1380 /***********************************************************************
1381 * GetExitCodeProcess [KERNEL32.325]
1383 * Gets termination status of specified process
1389 BOOL WINAPI GetExitCodeProcess(
1390 HANDLE hProcess, /* [I] handle to the process */
1391 LPDWORD lpExitCode) /* [O] address to receive termination status */
1394 struct get_process_info_request *req = get_req_buffer();
1395 req->handle = hProcess;
1396 if (!server_call( REQ_GET_PROCESS_INFO ))
1398 if (lpExitCode) *lpExitCode = req->exit_code;
1405 /***********************************************************************
1406 * SetErrorMode (KERNEL32.486)
1408 UINT WINAPI SetErrorMode( UINT mode )
1410 UINT old = PROCESS_Current()->error_mode;
1411 PROCESS_Current()->error_mode = mode;
1415 /***********************************************************************
1416 * GetCurrentProcess (KERNEL32.198)
1418 #undef GetCurrentProcess
1419 HANDLE WINAPI GetCurrentProcess(void)