diff --git a/apps/xtp/src/run.rs b/apps/xtp/src/run.rs index f0c2f8f5..c028f0e8 100644 --- a/apps/xtp/src/run.rs +++ b/apps/xtp/src/run.rs @@ -251,6 +251,7 @@ pub fn run( return Ok(()); } xtp_loader::report_crashes(); + xtp_hle::modules::lifecycle::install_crash_restart(autopilot.is_some()); xtp_loader::log_crashes_to(temp.with_file_name("crashes.log")); xtp_hle::runtime::use_console_timers(); #[cfg(feature = "diagnostics")] diff --git a/crates/xtp-hle/Cargo.toml b/crates/xtp-hle/Cargo.toml index f4e0b980..56c82ff6 100644 --- a/crates/xtp-hle/Cargo.toml +++ b/crates/xtp-hle/Cargo.toml @@ -52,6 +52,9 @@ xtp-core.workspace = true tempfile.workspace = true xtp-testkit.workspace = true +[target.'cfg(windows)'.dev-dependencies] +windows-sys = { workspace = true, features = ["Win32_System_JobObjects"] } + [features] # Debugging switches (scripted keys and the like). diagnostics = [ diff --git a/crates/xtp-hle/src/modules/kernel.rs b/crates/xtp-hle/src/modules/kernel.rs index fef9058c..d13b17c4 100644 --- a/crates/xtp-hle/src/modules/kernel.rs +++ b/crates/xtp-hle/src/modules/kernel.rs @@ -266,7 +266,7 @@ pub extern "system" fn SetUnhandledExceptionFilter(filter: usize) -> usize { extern "system" fn report_unhandled(info: *const c_void) -> i32 { host::report_unhandled(info); - match TITLE_FILTER.load(std::sync::atomic::Ordering::Acquire) { + let disposition = match TITLE_FILTER.load(std::sync::atomic::Ordering::Acquire) { 0 => 0, // EXCEPTION_CONTINUE_SEARCH filter => { type Filter = extern "system" fn(*const c_void) -> i32; @@ -274,7 +274,12 @@ extern "system" fn report_unhandled(info: *const c_void) -> i32 { let filter: Filter = unsafe { std::mem::transmute(filter) }; filter(info) } + }; + #[cfg(windows)] + if disposition != windows_sys::Win32::System::Diagnostics::Debug::EXCEPTION_CONTINUE_EXECUTION { + xtp_loader::run_on_crash(); } + disposition } /// See [`exit`]; only the current process is logged. diff --git a/crates/xtp-hle/src/modules/lifecycle.rs b/crates/xtp-hle/src/modules/lifecycle.rs index aec06246..3e1f5e35 100644 --- a/crates/xtp-hle/src/modules/lifecycle.rs +++ b/crates/xtp-hle/src/modules/lifecycle.rs @@ -31,6 +31,12 @@ fn routines() -> MutexGuard<'static, Vec<(usize, Routine, usize)>> { /// How long the console lets suspend routines run before it ends the title. const SUSPEND_DEADLINE: Duration = Duration::from_secs(1); +static ENDING: AtomicBool = AtomicBool::new(false); + +fn claim_ending() -> bool { + !ENDING.swap(true, Ordering::SeqCst) +} + const ERROR_INVALID_PARAMETER: u32 = 87; pub extern "system" fn RegisterAppStateChangeNotification( @@ -203,10 +209,13 @@ extern "system" fn window_proc( /// Suspends the title as the console does when it ends it, runs `then` /// (once), then ends the process. Returns at once; later calls do nothing. pub(crate) fn end_title(why: &'static str, then: Box) { - static ENDING: AtomicBool = AtomicBool::new(false); - if ENDING.swap(true, Ordering::SeqCst) { + if !claim_ending() { return; } + RESTART_ON_CRASH + .lock() + .unwrap_or_else(|e| e.into_inner()) + .take(); let suspend = routines().clone(); tracing::info!(routines = suspend.len(), "{why}: suspending the title"); // Whoever comes first (the routines or the deadline) runs `then`; the @@ -239,9 +248,83 @@ pub(crate) fn end_title(why: &'static str, then: Box) { /// of the process it replaces. const RELAUNCHED_FROM: &str = "XTP_RELAUNCHED_FROM"; +/// Set in the environment of a process restarted after a crash so a second +/// crash does not loop indefinitely. Cleared from the environment at startup +/// (into [`ALREADY_CRASH_RESTARTED`]) so a later `XLaunchNewGame` relaunch +/// does not inherit it. +const CRASH_RESTARTED: &str = "XTP_CRASH_RESTARTED"; + +/// Remembered in-process after [`wait_for_previous`] removes [`CRASH_RESTARTED`] +/// from the environment. +static ALREADY_CRASH_RESTARTED: AtomicBool = AtomicBool::new(false); + +/// Command-line arguments recorded by `XLaunchRestartOnCrash`. +static RESTART_ON_CRASH: Mutex>> = Mutex::new(None); + +/// Records the arguments to relaunch with if the process hits an unhandled +/// crash (`XLaunchRestartOnCrash`). +pub(crate) fn set_restart_on_crash(args: Vec) { + let mut restart = RESTART_ON_CRASH.lock().unwrap_or_else(|e| e.into_inner()); + if !ENDING.load(Ordering::SeqCst) { + *restart = Some(args); + } +} + +/// Installs the hook for fatal unhandled exceptions. Autopilot logs a skip +/// if the title armed a restart, so its harness can observe the original exit. +pub fn install_crash_restart(autopilot: bool) { + xtp_loader::on_crash(if autopilot { + || relaunch_on_crash(true) + } else { + || relaunch_on_crash(false) + }); +} + +fn relaunch_on_crash(autopilot: bool) { + let Some(args) = RESTART_ON_CRASH + .try_lock() + .ok() + .and_then(|mut args| args.take()) + else { + return; + }; + if !claim_crash_restart(autopilot) { + return; + } + if relaunch_with_env(args, Some((CRASH_RESTARTED, "1"))) { + // Terminate directly from the crash filter without running normal + // shutdown hooks (saving the pipeline cache or releasing input could + // deadlock if the faulting thread holds an internal lock). + // SAFETY: terminating our own crashing process after spawning the + // replacement; exit code 1 distinguishes a crash-restart exit. + unsafe { + TerminateProcess(GetCurrentProcess(), 1); + } + } +} + +fn claim_crash_restart(autopilot: bool) -> bool { + if autopilot { + tracing::info!("skipping crash restart: autopilot is enabled"); + return false; + } + if ALREADY_CRASH_RESTARTED.load(Ordering::Relaxed) + || std::env::var_os(CRASH_RESTARTED).is_some() + { + tracing::info!("skipping crash restart: already restarted once"); + return false; + } + // Both paths must claim the shutdown before either can spawn a replacement. + claim_ending() +} + /// Starts `xtp` again with `args` (after the title has suspended); the /// new process waits until this one has ended. pub(crate) fn relaunch(args: Vec) { + let _ = relaunch_with_env(args, None); +} + +fn relaunch_with_env(args: Vec, extra_env: Option<(&str, &str)>) -> bool { use windows_sys::Win32::Foundation::{DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE}; let mut me: HANDLE = std::ptr::null_mut(); // SAFETY: an inheritable duplicate of our own process handle. @@ -262,19 +345,34 @@ pub(crate) fn relaunch(args: Vec) { if duplicated { command.env(RELAUNCHED_FROM, (me as usize).to_string()); } + if let Some((k, v)) = extra_env { + command.env(k, v); + } command.spawn() }); match spawned { - Ok(child) => tracing::info!(pid = child.id(), ?args, "relaunched"), - Err(e) => tracing::warn!(%e, "relaunch failed; the title just ends"), + Ok(child) => { + tracing::info!(pid = child.id(), ?args, "relaunched"); + true + } + Err(e) => { + tracing::warn!(%e, "relaunch failed; the title just ends"); + false + } } } -/// In a relaunched `xtp`: waits (30 s at most) for the process it -/// replaces to be gone, so the two never share the title's files. +/// In a relaunched `xtp`: consumes `XTP_CRASH_RESTARTED` (so a later +/// `XLaunchNewGame` does not inherit it) and waits (30 s at most) for the +/// process it replaces to be gone, so the two never share the title's files. pub fn wait_for_previous() { use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; use windows_sys::Win32::System::Threading::WaitForSingleObject; + if std::env::var_os(CRASH_RESTARTED).is_some() { + ALREADY_CRASH_RESTARTED.store(true, Ordering::Relaxed); + // SAFETY: removing our own variable at startup before title threads run. + unsafe { std::env::remove_var(CRASH_RESTARTED) }; + } let Some(handle) = std::env::var(RELAUNCHED_FROM) .ok() .and_then(|h| h.parse::().ok()) @@ -321,6 +419,46 @@ pub(crate) fn module() -> HleModule { mod tests { use super::*; + #[test] + fn crash_restart_and_intentional_end_have_only_one_winner() { + const CHILD: &str = "XTP_TEST_CRASH_RESTART_CLAIM"; + // These flags are process-global, so no other library tests may run here. + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "modules::lifecycle::tests::crash_restart_and_intentional_end_have_only_one_winner", + "--exact", + "--nocapture", + ]) + .env(CHILD, "1") + .env_remove(CRASH_RESTARTED) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed; 0 failed;")); + return; + } + + assert!(!claim_crash_restart(true)); + assert!(!ENDING.load(Ordering::SeqCst)); + ALREADY_CRASH_RESTARTED.store(true, Ordering::Relaxed); + assert!(!claim_crash_restart(false)); + assert!(!ENDING.load(Ordering::SeqCst)); + ALREADY_CRASH_RESTARTED.store(false, Ordering::Relaxed); + + for crash_first in [true, false] { + let (crash_won, intentional_won) = if crash_first { + let crash_won = claim_crash_restart(false); + (crash_won, claim_ending()) + } else { + let intentional_won = claim_ending(); + (claim_crash_restart(false), intentional_won) + }; + assert_eq!((crash_won, intentional_won), (crash_first, !crash_first)); + ENDING.store(false, Ordering::SeqCst); + } + } + extern "system" fn noop(_: u8, _: *mut c_void) {} #[test] diff --git a/crates/xtp-hle/src/modules/xgame.rs b/crates/xtp-hle/src/modules/xgame.rs index db0290e7..395838b2 100644 --- a/crates/xtp-hle/src/modules/xgame.rs +++ b/crates/xtp-hle/src/modules/xgame.rs @@ -93,6 +93,20 @@ extern "system" fn launch_new_game( } } +/// Records `args` so the crash reporter relaunches the title once if an +/// unhandled crash occurs (`XLaunchRestartOnCrash` in `XGame.h`). +extern "system" fn launch_restart_on_crash(_: This, args: *const c_char, reserved: u32) -> HRESULT { + if reserved != 0 { + return super::xasync::E_INVALIDARG; + } + let args = text(args).unwrap_or_default(); + tracing::info!(args, "XLaunchRestartOnCrash"); + let ours: Vec<_> = std::env::args_os().skip(1).collect(); + let command = relaunch_args(ours, std::ffi::OsStr::new(""), "", &args); + super::lifecycle::set_restart_on_crash(command); + S_OK +} + /// Our own arguments for the relaunch: the title's executable replaced by /// `exe`, earlier title arguments dropped, `args` after `--`. fn relaunch_args( @@ -161,12 +175,17 @@ extern "system" fn write_event( S_OK } -static TITLE_VTABLE: Methods<5> = Methods([ +/// `TITLE_IID` vtable: `XGameGetXboxTitleId` (0x18) and `XLaunchNewGame` (0x20) +/// are confirmed; `XLaunchRestartOnCrash` at slot 0x28 is inferred from +/// `XGame.h` declaration order after `IUnknown`, not confirmed against a live +/// call site. +static TITLE_VTABLE: Methods<6> = Methods([ missing::<0> as *const (), add_ref as *const (), add_ref as *const (), - title_id as *const (), // 0x18 - launch_new_game as *const (), // 0x20 + title_id as *const (), // 0x18 + launch_new_game as *const (), // 0x20 + launch_restart_on_crash as *const (), // 0x28 ]); static FEATURES_VTABLE: Methods<4> = Methods([ @@ -229,6 +248,27 @@ mod tests { assert_eq!(other[1], "G:/other.exe"); } + #[test] + fn a_restart_without_title_args_keeps_the_executable_and_drops_old_args() { + let ours = ["run", "G:/game.exe", "--", "-old"].map(std::ffi::OsString::from); + let current = std::ffi::OsStr::new("G:/game.exe"); + for args in [std::ptr::null(), c"".as_ptr(), c" \t".as_ptr()] { + let args = text(args).unwrap_or_default(); + assert_eq!(relaunch_args(ours.to_vec(), current, "", &args), ours[..2]); + } + } + + #[test] + fn a_restart_uses_the_shared_whitespace_split_for_quoted_args() { + let ours = ["run", "G:/game.exe", "--", "-old"].map(std::ffi::OsString::from); + let current = std::ffi::OsStr::new("G:/game.exe"); + let command = relaunch_args(ours.to_vec(), current, "", "-save \"slot 1\""); + assert_eq!( + command, + ["run", "G:/game.exe", "--", "-save", "\"slot", "1\""].map(std::ffi::OsString::from) + ); + } + #[test] fn served_areas_are_available_others_not() { type Check = extern "system" fn(This, u32) -> bool; diff --git a/crates/xtp-hle/tests/restart_on_crash.rs b/crates/xtp-hle/tests/restart_on_crash.rs new file mode 100644 index 00000000..f18286ee --- /dev/null +++ b/crates/xtp-hle/tests/restart_on_crash.rs @@ -0,0 +1,382 @@ +//! Isolated child-process probes for crash restart, the title's unhandled +//! exception filter, and unattended runs. +#![cfg(windows)] + +use std::ffi::{c_char, c_void}; +use std::fs::OpenOptions; +use std::io::Write; +use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::OnceLock; + +use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, WAIT_OBJECT_0}; +use windows_sys::Win32::System::Diagnostics::Debug::{ + EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH, EXCEPTION_POINTERS, RaiseException, + SEM_NOGPFAULTERRORBOX, SetErrorMode, +}; +use windows_sys::Win32::System::JobObjects::{ + AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, + JOBOBJECT_BASIC_ACCOUNTING_INFORMATION, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, + JobObjectBasicAccountingInformation, JobObjectExtendedLimitInformation, + QueryInformationJobObject, SetInformationJobObject, +}; +use windows_sys::Win32::System::Threading::{ + CreateEventW, EVENT_MODIFY_STATE, GetExitCodeProcess, OpenEventW, OpenProcess, + PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, SYNCHRONIZATION_SYNCHRONIZE, SetEvent, + WaitForSingleObject, +}; +use xtp_hle::modules::{kernel, lifecycle, xasync, xgame, xgameruntime}; + +const PROBE_DIR_ENV: &str = "XTP_RESTART_PROBE_DIR"; +const RECOVERABLE_EXCEPTION: u32 = 0xE042_4700; +const STATUS_ACCESS_VIOLATION: u32 = EXCEPTION_ACCESS_VIOLATION as u32; +const TIMEOUT_MS: u32 = 10_000; +static LOG: OnceLock = OnceLock::new(); + +#[derive(Clone, Copy)] +enum Scenario { + Default, + NullArgs, + TitleFilter, + Autopilot, + Shutdown, +} + +#[test] +fn the_replacement_exits_without_another_restart() { + isolated( + "the_replacement_exits_without_another_restart", + Scenario::Default, + ); +} + +#[test] +fn null_args_restart_without_title_arguments() { + isolated( + "null_args_restart_without_title_arguments", + Scenario::NullArgs, + ); +} + +#[test] +fn the_title_filter_runs_before_restart() { + isolated( + "the_title_filter_runs_before_restart", + Scenario::TitleFilter, + ); +} + +#[test] +fn autopilot_keeps_the_original_crash_exit() { + isolated( + "autopilot_keeps_the_original_crash_exit", + Scenario::Autopilot, + ); +} + +#[test] +fn a_fault_in_a_suspend_routine_does_not_restart() { + isolated( + "a_fault_in_a_suspend_routine_does_not_restart", + Scenario::Shutdown, + ); +} + +fn isolated(name: &str, scenario: Scenario) { + if let Some(dir) = std::env::var_os(PROBE_DIR_ENV) { + run_child(Path::new(&dir), scenario); + } + + let dir = tempfile::tempdir().expect("probe directory"); + let dir = dir.path(); + let ready = event(dir, "ready", true); + let proceed = event(dir, "proceed", true); + let job = probe_job(); + let mut child = Command::new(std::env::current_exe().expect("test binary path")) + .args(["--exact", name, "--nocapture"]) + .env(PROBE_DIR_ENV, dir) + .env_remove("XTP_CRASH_RESTARTED") + .env_remove("XTP_RELAUNCHED_FROM") + .spawn() + .expect("spawn initial probe"); + // SAFETY: both handles are live. The child waits for `proceed` before + // running anything that could spawn a replacement. + if unsafe { AssignProcessToJobObject(job.as_raw_handle(), child.as_raw_handle()) } == 0 { + let error = std::io::Error::last_os_error(); + child.kill().expect("stop the unassigned probe"); + child.wait().expect("reap the unassigned probe"); + panic!("assign initial probe to the job: {error}"); + } + signal(&proceed); + + let status = wait_for_exit(child.as_raw_handle(), "initial probe"); + let restarted = !matches!(scenario, Scenario::Autopilot | Scenario::Shutdown); + if !restarted { + assert_eq!(status, STATUS_ACCESS_VIOLATION, "original exception exit"); + } else { + assert_eq!(status, 1, "crash-restart exit for {name}"); + // The replacement publishes its PID and waits before it can fault. + // Hold its process handle before allowing it to proceed. + wait_for_event(&ready, "replacement PID"); + let pid = std::fs::read_to_string(dir.join("replacement.pid")) + .expect("read replacement PID") + .parse() + .expect("parse replacement PID"); + // SAFETY: the waiting replacement published this PID. + let process = unsafe { + OpenProcess( + PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, + 0, + pid, + ) + }; + let process = own_handle(process, "open replacement process"); + signal(&proceed); + assert_eq!( + wait_for_exit(process.as_raw_handle(), "replacement probe"), + STATUS_ACCESS_VIOLATION, + "the replacement must exit with the exception code instead of spawning again" + ); + } + + assert_eq!(process_count(&job), if restarted { 2 } else { 1 }); + let log = std::fs::read_to_string(dir.join("runs.log")).expect("read probe log"); + let expected: &[&str] = match scenario { + Scenario::Default => &["initial", "replacement", "--", "-recover", "-slot=3"], + Scenario::NullArgs => &["initial", "replacement"], + Scenario::TitleFilter => &[ + "initial", + "filter resumed", + "execution resumed", + "filter searched", + "replacement", + "--", + "-recover", + "-slot=3", + ], + Scenario::Autopilot => &["initial"], + Scenario::Shutdown => &["initial", "suspend routine"], + }; + assert_eq!(log.lines().collect::>(), expected); +} + +/// All probe descendants inherit job membership. Closing the parent's sole +/// job handle kills any that are still running, including on a failed check. +fn probe_job() -> OwnedHandle { + // SAFETY: null attributes and name create an unnamed, non-inheritable job handle. + let job = own_handle( + unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) }, + "create probe job", + ); + let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); + limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + // SAFETY: the live job handle and the buffer match the information class. + let ok = unsafe { + SetInformationJobObject( + job.as_raw_handle(), + JobObjectExtendedLimitInformation, + (&raw const limits).cast(), + size_of_val(&limits) as u32, + ) + }; + assert_ne!( + ok, + 0, + "set probe job limits: {}", + std::io::Error::last_os_error() + ); + job +} + +/// Counts every process assigned to the job, including those that already exited. +fn process_count(job: &OwnedHandle) -> u32 { + let mut info = JOBOBJECT_BASIC_ACCOUNTING_INFORMATION::default(); + // SAFETY: the live job handle and the writable buffer match the information class. + let ok = unsafe { + QueryInformationJobObject( + job.as_raw_handle(), + JobObjectBasicAccountingInformation, + (&raw mut info).cast(), + size_of_val(&info) as u32, + std::ptr::null_mut(), + ) + }; + assert_ne!( + ok, + 0, + "query probe job accounting: {}", + std::io::Error::last_os_error() + ); + info.TotalProcesses +} + +fn own_handle(handle: RawHandle, operation: &str) -> OwnedHandle { + assert!( + !handle.is_null(), + "{operation}: {}", + std::io::Error::last_os_error() + ); + // SAFETY: the successful Win32 call returned a new handle to close. + unsafe { OwnedHandle::from_raw_handle(handle) } +} + +fn event(dir: &Path, name: &str, create: bool) -> OwnedHandle { + let name = format!( + "Local\\xtp-restart-{}-{name}", + dir.file_name().unwrap().to_string_lossy() + ); + let name: Vec = name.encode_utf16().chain([0]).collect(); + // SAFETY: the event name is NUL-terminated. Only the parent creates the + // events, and each signal wakes one waiter. + let handle = unsafe { + if create { + CreateEventW(std::ptr::null(), 0, 0, name.as_ptr()) + } else { + OpenEventW( + EVENT_MODIFY_STATE | SYNCHRONIZATION_SYNCHRONIZE, + 0, + name.as_ptr(), + ) + } + }; + own_handle(handle, "open probe event") +} + +fn signal(event: &OwnedHandle) { + // SAFETY: the event handle is live and allows signalling. + assert_ne!(unsafe { SetEvent(event.as_raw_handle()) }, 0); +} + +fn wait_for_event(event: &OwnedHandle, what: &str) { + // SAFETY: the event handle is live and allows waiting. + let wait = unsafe { WaitForSingleObject(event.as_raw_handle(), TIMEOUT_MS) }; + assert_eq!(wait, WAIT_OBJECT_0, "waiting for {what}"); +} + +fn wait_for_exit(process: RawHandle, what: &str) -> u32 { + // SAFETY: callers hold a live process handle with wait and query rights. + unsafe { + let wait = WaitForSingleObject(process, TIMEOUT_MS); + assert_eq!(wait, WAIT_OBJECT_0, "waiting for {what} to exit"); + let mut code = 0; + assert_ne!( + GetExitCodeProcess(process, &mut code), + 0, + "query {what} exit code: {}", + std::io::Error::last_os_error() + ); + code + } +} + +fn log(line: &str) { + let mut log = OpenOptions::new() + .create(true) + .append(true) + .open(LOG.get().expect("probe log path")) + .expect("open probe log"); + writeln!(log, "{line}").expect("write probe log"); +} + +extern "system" fn title_filter(info: *const c_void) -> i32 { + // SAFETY: Windows supplies the active exception pointers to the filter. + let code = unsafe { (*(*info.cast::()).ExceptionRecord).ExceptionCode }; + if code as u32 == RECOVERABLE_EXCEPTION { + log("filter resumed"); + EXCEPTION_CONTINUE_EXECUTION + } else { + log("filter searched"); + EXCEPTION_CONTINUE_SEARCH + } +} + +fn run_child(dir: &Path, scenario: Scenario) -> ! { + // SAFETY: this probe process can suppress dialogs for its own fault. + unsafe { SetErrorMode(SEM_NOGPFAULTERRORBOX) }; + let replacement = std::env::var_os("XTP_CRASH_RESTARTED").is_some(); + let proceed = event(dir, "proceed", false); + if !replacement { + wait_for_event(&proceed, "parent to assign the probe to the job"); + } + lifecycle::wait_for_previous(); + LOG.set(dir.join("runs.log")).expect("set probe log path"); + + if replacement { + log("replacement"); + for arg in std::env::args().skip_while(|arg| arg != "--") { + log(&arg); + } + let ready = event(dir, "ready", false); + std::fs::write(dir.join("replacement.pid"), std::process::id().to_string()) + .expect("publish replacement PID"); + signal(&ready); + wait_for_event(&proceed, "parent to open the replacement process"); + } else { + log("initial"); + } + + xtp_loader::report_crashes(); + lifecycle::install_crash_restart(matches!(scenario, Scenario::Autopilot)); + + let obj = &xgame::TITLE_OBJECT; + type RestartOnCrash = extern "system" fn( + *const xgameruntime::Object, + *const c_char, + u32, + ) -> xgameruntime::HRESULT; + // SAFETY: `TITLE_OBJECT` starts with its vtable; slot 5 implements + // `XLaunchRestartOnCrash` with this signature. + let vtable = unsafe { *std::ptr::from_ref(obj).cast::<*const *const ()>() }; + // SAFETY: slot 5 in this vtable is a `RestartOnCrash` function pointer. + let restart: RestartOnCrash = unsafe { std::mem::transmute(*vtable.add(5)) }; + assert_eq!(restart(obj, std::ptr::null(), 1), xasync::E_INVALIDARG); + let args = match scenario { + Scenario::NullArgs => std::ptr::null(), + _ => c"-recover -slot=3".as_ptr(), + }; + assert_eq!(restart(obj, args, 0), xgameruntime::S_OK); + + if !replacement && matches!(scenario, Scenario::TitleFilter) { + kernel::SetUnhandledExceptionFilter(title_filter as *const () as usize); + // SAFETY: a continuable test exception with no arguments. The title + // filter resumes it without editing the processor context. + unsafe { RaiseException(RECOVERABLE_EXCEPTION, 0, 0, std::ptr::null()) }; + log("execution resumed"); + } + if matches!(scenario, Scenario::Shutdown) { + let mut registration = 0; + assert_eq!( + lifecycle::RegisterAppStateChangeNotification( + Some(fault_on_suspend), + std::ptr::null_mut(), + &mut registration + ), + 0 + ); + type LaunchNewGame = extern "system" fn( + *const xgameruntime::Object, + *const c_char, + *const c_char, + *const c_void, + ); + // SAFETY: slot 4 in this vtable implements `XLaunchNewGame` with this signature. + let launch: LaunchNewGame = unsafe { std::mem::transmute(*vtable.add(4)) }; + launch(obj, std::ptr::null(), std::ptr::null(), std::ptr::null()); + panic!("XLaunchNewGame returned"); + } + + fault() +} + +extern "system" fn fault_on_suspend(_: u8, _: *mut c_void) { + log("suspend routine"); + fault() +} + +fn fault() -> ! { + // SAFETY: a synthetic access violation in this isolated probe. Its two + // arguments describe a write to address zero. + unsafe { RaiseException(STATUS_ACCESS_VIOLATION, 0, 2, [1, 0].as_ptr()) }; + panic!("the access violation returned"); +} diff --git a/crates/xtp-loader/src/crash.rs b/crates/xtp-loader/src/crash.rs index 40caae29..bedfef53 100644 --- a/crates/xtp-loader/src/crash.rs +++ b/crates/xtp-loader/src/crash.rs @@ -55,6 +55,32 @@ pub fn save_on_crash(ranges: Vec<(usize, usize, std::path::PathBuf)>) { /// The file crash reports are appended to, besides being printed. static LOG: std::sync::OnceLock = std::sync::OnceLock::new(); +/// Optional callback for a fatal unhandled exception. The atomic pointer +/// lets the exception filter take the callback without locking. +static ON_CRASH: std::sync::atomic::AtomicPtr<()> = + std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()); + +/// Registers a callback to run once, after reporting a fatal unhandled +/// exception and giving the title's filter a chance to resume execution. +pub fn on_crash(hook: fn()) { + ON_CRASH.store(hook as *mut (), Ordering::Release); +} + +/// Runs the callback from a top-level exception filter after reporting the +/// exception, when no title filter resumes execution. +pub fn run_on_crash() { + static FIRED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if FIRED.swap(true, Ordering::SeqCst) { + return; + } + let ptr = ON_CRASH.load(Ordering::Acquire); + if !ptr.is_null() { + // SAFETY: `on_crash` only stores valid `fn()` pointers. + let hook: fn() = unsafe { std::mem::transmute(ptr) }; + hook(); + } +} + /// Also appends every unhandled-exception report and panic to `file`, so a /// crash can be read after the console is gone. pub fn log_crashes_to(file: std::path::PathBuf) { @@ -137,6 +163,7 @@ pub fn report_crashes() { unsafe extern "system" fn filter(info: *const EXCEPTION_POINTERS) -> i32 { // SAFETY: the system passes the exception being dispatched. unsafe { report_unhandled(info) }; + run_on_crash(); EXCEPTION_CONTINUE_SEARCH } static INSTALL: std::sync::Once = std::sync::Once::new(); @@ -588,8 +615,8 @@ unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { EXCEPTION_CONTINUE_SEARCH } -/// For an unhandled-exception filter: reports the exception that is about -/// to end the process, and appends it to the crash log. +/// Reports an exception from a top-level filter and appends it to the crash +/// log. The title's filter may still resume execution. /// /// # Safety /// `info` comes from the system, for an exception being dispatched. diff --git a/crates/xtp-loader/src/lib.rs b/crates/xtp-loader/src/lib.rs index 3f13cb85..69ea0538 100644 --- a/crates/xtp-loader/src/lib.rs +++ b/crates/xtp-loader/src/lib.rs @@ -55,8 +55,8 @@ pub use census::Census; pub use crash::save_on_crash; #[cfg(windows)] pub use crash::{ - locate, log_crash, log_crashes_to, note_title_output, read_memory as read_title_memory, - report_crashes, report_unhandled, + locate, log_crash, log_crashes_to, note_title_output, on_crash, + read_memory as read_title_memory, report_crashes, report_unhandled, run_on_crash, }; pub use prepare::{PrepareError, PreparedImage, prepare}; pub use resolve::{ImportResolver, Provenance, Resolution}; diff --git a/docs/analysis/hle.md b/docs/analysis/hle.md index fb983d42..1739318f 100644 --- a/docs/analysis/hle.md +++ b/docs/analysis/hle.md @@ -177,7 +177,7 @@ Legend: ✔ implemented and tested, ◐ partial, ✘ missing, — not needed. | Speech synthesis | ✔ Windows voices, text and SSML to 48 kHz PCM | → PC runtime | 4 / — | Done (R6) | | Closed captions, high contrast | ✔ Windows settings and title override | ✔ `accessibility.rs` | 5 / 3 | Done (R7) | | XError callback and options | ✘ class absent | ✔ | — / — | After xcl, if the title asks (R9) | -| Relaunch (`XLaunchNewGame`), restart on crash | ◐ relaunch untested live | ✔ both | 4 (lifecycle) / — | Verify (R10) | +| Relaunch (`XLaunchNewGame`), restart on crash | ◐ `XLaunchRestartOnCrash` tested; `XLaunchNewGame` untested live | ✔ both | 9 (lifecycle + `restart_on_crash`) / — | Partial (R10) | | HDR, URIs, deferrals, screenshots | ✔ | ◐ | 1 / — | Keep XTP | ### 4.3 Audio @@ -372,17 +372,24 @@ shows the title calls them. completes as cancelled. - **Depends on:** R1, optional. -### R10. Relaunch and restart on crash, live — S +### R10. Relaunch and restart on crash, live — S (restart-on-crash done; live relaunch untested) - **Goal:** confirm `XLaunchNewGame` (wait for the old process, start again - with the arguments) on the real title, and add `XLaunchRestartOnCrash` - (record the arguments; the crash reporter relaunches once). -- **Files:** `crates/xtp-hle/src/modules/xgame.rs`, `modules/lifecycle.rs`, - `apps/xtp/src/run.rs` (relaunch path). + with the arguments) on the real title. `XLaunchRestartOnCrash` (record the + arguments; relaunch once on a fatal unhandled SEH exception) is done. + The title's filter can resume execution. Under `--autopilot`, an armed + restart is logged and skipped. After a successful spawn, the crashing + process exits with code 1 and the replacement waits for it to exit. + Starting a title shutdown clears the pending restart before suspend + routines run. +- **Files:** `crates/xtp-hle/src/modules/{xgame,lifecycle,kernel}.rs`, + `crates/xtp-loader/src/crash.rs`, `apps/xtp/src/run.rs`. - **xcl ref:** `hle/xgameruntime/api.rs` `XLaunchNewGame`, `XLaunchRestartOnCrash`. - **Acceptance:** a child-process test (pattern of the save crash test): a probe calling restart-on-crash then faulting is started a second time - with the recorded arguments, and only once. + with the recorded arguments, and only once. The probe also covers a title + filter resuming execution, an unattended run keeping its original exit, + and a fault in a suspend routine during shutdown. - **Depends on:** — ### R7. Closed captions and high contrast — S (done) @@ -510,7 +517,7 @@ shows the title calls them. | 8 | A1 Opus check | S | — | | 9 | I2 mouse as right stick | M | I1 | | 10 | R5 message/error dialogs (done) | M | (R1) | -| 11 | R10 relaunch, restart on crash | S | — | +| 11 | R10 relaunch and restart on crash (restart tested, live relaunch pending) | S | — | | 12 | R7 closed captions, high contrast (done) | S | — | | 13 | R6 speech synthesis (done) | M | — | | 14 | I3 trigger rumble | M | — |