From 0ac269f1135fb9b17858c7588bb4f8d2d0ce2244 Mon Sep 17 00:00:00 2001 From: PrivacyOnion Date: Wed, 25 Nov 2026 06:58:32 +0100 Subject: [PATCH 1/5] hle, loader, app: implement XLaunchRestartOnCrash --- apps/xtp/src/run.rs | 1 + crates/xtp-hle/Cargo.toml | 4 + crates/xtp-hle/src/modules/lifecycle.rs | 37 +++++++ crates/xtp-hle/src/modules/xgame.rs | 26 ++++- crates/xtp-hle/tests/restart_on_crash.rs | 122 +++++++++++++++++++++++ crates/xtp-loader/src/crash.rs | 26 +++++ crates/xtp-loader/src/lib.rs | 4 +- 7 files changed, 215 insertions(+), 5 deletions(-) create mode 100644 crates/xtp-hle/tests/restart_on_crash.rs diff --git a/apps/xtp/src/run.rs b/apps/xtp/src/run.rs index f0c2f8f5..69a4b40f 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_loader::on_crash(xtp_hle::modules::lifecycle::relaunch_on_crash); 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..4e5f23c4 100644 --- a/crates/xtp-hle/Cargo.toml +++ b/crates/xtp-hle/Cargo.toml @@ -69,3 +69,7 @@ diagnostics = [ [lints] workspace = true + +[[test]] +name = "restart_on_crash" +harness = false diff --git a/crates/xtp-hle/src/modules/lifecycle.rs b/crates/xtp-hle/src/modules/lifecycle.rs index aec06246..4d132d01 100644 --- a/crates/xtp-hle/src/modules/lifecycle.rs +++ b/crates/xtp-hle/src/modules/lifecycle.rs @@ -239,9 +239,43 @@ 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. +const CRASH_RESTARTED: &str = "XTP_CRASH_RESTARTED"; + +/// 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) { + *RESTART_ON_CRASH.lock().unwrap_or_else(|e| e.into_inner()) = Some(args); +} + +/// Crash-reporter hook (`xtp_loader::on_crash`): if `XLaunchRestartOnCrash` +/// recorded arguments and this process was not already restarted from a crash, +/// spawns a replacement process once with [`CRASH_RESTARTED`] set. +pub fn relaunch_on_crash() { + if std::env::var_os(CRASH_RESTARTED).is_some() { + tracing::info!("skipping crash restart: already restarted once"); + return; + } + let Ok(mut guard) = RESTART_ON_CRASH.try_lock() else { + return; + }; + let Some(args) = guard.take() else { + return; + }; + relaunch_with_env(args, Some((CRASH_RESTARTED, "1"))); +} + /// 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) { + relaunch_with_env(args, None); +} + +fn relaunch_with_env(args: Vec, extra_env: Option<(&str, &str)>) { 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,6 +296,9 @@ 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 { diff --git a/crates/xtp-hle/src/modules/xgame.rs b/crates/xtp-hle/src/modules/xgame.rs index db0290e7..7004100e 100644 --- a/crates/xtp-hle/src/modules/xgame.rs +++ b/crates/xtp-hle/src/modules/xgame.rs @@ -93,6 +93,25 @@ extern "system" fn launch_new_game( } } +const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32; + +/// 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 E_INVALIDARG; + } + let args = text(args).unwrap_or_default(); + tracing::info!(args, "XLaunchRestartOnCrash"); + let current = runtime::main_image() + .and_then(runtime::image_path) + .unwrap_or_default(); + let ours: Vec<_> = std::env::args_os().skip(1).collect(); + let command = relaunch_args(ours, current.as_os_str(), "", &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 +180,13 @@ extern "system" fn write_event( S_OK } -static TITLE_VTABLE: Methods<5> = Methods([ +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([ 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..f5fc6f7e --- /dev/null +++ b/crates/xtp-hle/tests/restart_on_crash.rs @@ -0,0 +1,122 @@ +//! Child-process test for `XLaunchRestartOnCrash` (issue #11 / R10): +//! a probe registers restart-on-crash arguments, triggers an unhandled fault, +//! is automatically relaunched with the recorded arguments after waiting for +//! the crashing process to exit, and does not relaunch a third time when it +//! faults again. +#![cfg(windows)] + +use std::ffi::{CString, c_char}; +use std::fs::OpenOptions; +use std::io::Write; +use std::path::PathBuf; +use std::process::Command; +use std::time::{Duration, Instant}; + +use xtp_hle::modules::{lifecycle, xgame, xgameruntime}; + +const PROBE_LOG_ENV: &str = "XTP_RESTART_PROBE_LOG"; + +fn main() { + if let Some(log_path) = std::env::var_os(PROBE_LOG_ENV) { + run_child(PathBuf::from(log_path)); + } else { + run_parent(); + } +} + +fn run_parent() { + let dir = tempfile::tempdir().expect("temp dir"); + let log_path = dir.path().join("runs.log"); + + let exe = std::env::current_exe().expect("test binary path"); + let status = Command::new(&exe) + .arg("--probe-mode") + .env(PROBE_LOG_ENV, &log_path) + .env_remove("XTP_CRASH_RESTARTED") + .env_remove("XTP_RELAUNCHED_FROM") + .status() + .expect("spawn initial child"); + assert!( + !status.success(), + "initial child should terminate with a fault" + ); + + // Wait for the restarted grandchild to start, record its line, and fault. + let deadline = Instant::now() + Duration::from_secs(10); + while Instant::now() < deadline { + if let Ok(text) = std::fs::read_to_string(&log_path) + && text.lines().count() >= 2 + { + break; + } + std::thread::sleep(Duration::from_millis(50)); + } + + // Give a brief settle window to verify a second crash does NOT trigger a + // third launch. + std::thread::sleep(Duration::from_millis(400)); + let final_text = std::fs::read_to_string(&log_path).expect("read probe log"); + let final_lines: Vec<&str> = final_text.lines().collect(); + + assert_eq!( + final_lines.len(), + 2, + "expected exactly 2 runs (initial + 1 restart), got {final_lines:?}" + ); + assert!( + final_lines[0].contains("--probe-mode") && !final_lines[0].contains("-recover"), + "unexpected run 1 args: {}", + final_lines[0] + ); + assert!( + final_lines[1].contains("--probe-mode") && final_lines[1].contains("-- -recover -slot=3"), + "run 2 did not receive recorded restart arguments: {}", + final_lines[1] + ); + println!("test restart_on_crash ... ok"); +} + +fn run_child(log_path: PathBuf) { + lifecycle::wait_for_previous(); + let args: Vec = std::env::args().skip(1).collect(); + { + let mut f = OpenOptions::new() + .create(true) + .append(true) + .open(&log_path) + .expect("open probe log"); + writeln!(f, "pid={} args={}", std::process::id(), args.join(" ")).expect("write probe log"); + let _ = f.flush(); + } + + xtp_loader::report_crashes(); + xtp_loader::on_crash(lifecycle::relaunch_on_crash); + + // Call XLaunchRestartOnCrash through TITLE_OBJECT vtable slot 0x28. + let obj = &xgame::TITLE_OBJECT; + type RestartOnCrash = extern "system" fn( + *const xgameruntime::Object, + *const c_char, + u32, + ) -> xgameruntime::HRESULT; + // SAFETY: `TITLE_OBJECT`'s first word is its vtable; slot 5 (offset 0x28) + // is `launch_restart_on_crash`. + let restart: RestartOnCrash = unsafe { + let vtable = *(obj as *const xgameruntime::Object as *const *const *const ()); + std::mem::transmute(*vtable.add(5)) + }; + + let bad_hr = restart(obj, std::ptr::null(), 1); + assert!(bad_hr < 0, "non-zero reserved must fail"); + + let recorded = CString::new("-recover -slot=3").unwrap(); + let hr = restart(obj, recorded.as_ptr(), 0); + assert_eq!(hr, xgameruntime::S_OK); + + // Deliberately trigger an unhandled access violation so `report_unhandled` + // invokes the registered crash-restart hook. + // SAFETY: intentional null write in an isolated child probe process. + unsafe { + std::ptr::write_volatile(std::ptr::null_mut::(), 0xdead_beef); + } +} diff --git a/crates/xtp-loader/src/crash.rs b/crates/xtp-loader/src/crash.rs index 40caae29..81210873 100644 --- a/crates/xtp-loader/src/crash.rs +++ b/crates/xtp-loader/src/crash.rs @@ -55,6 +55,31 @@ 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 invoked once after an unhandled crash is reported +/// (used by `XLaunchRestartOnCrash`). Stored in an atomic pointer so crash +/// handling never blocks on a mutex. +static ON_CRASH: std::sync::atomic::AtomicPtr<()> = + std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()); + +/// Registers a callback to run once after an unhandled crash has been +/// reported (before the process terminates). +pub fn on_crash(hook: fn()) { + ON_CRASH.store(hook as *mut (), Ordering::Release); +} + +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) { @@ -596,6 +621,7 @@ unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { pub unsafe fn report_unhandled(info: *const EXCEPTION_POINTERS) { // SAFETY: forwarded from the caller. unsafe { report("unhandled exception", info, true) }; + run_on_crash(); } /// The bytes at `at` as hex, as many as the longest x86 instruction (15), diff --git a/crates/xtp-loader/src/lib.rs b/crates/xtp-loader/src/lib.rs index 3f13cb85..29ed8579 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, }; pub use prepare::{PrepareError, PreparedImage, prepare}; pub use resolve::{ImportResolver, Provenance, Resolution}; From 339144041ec50fad47b06b72df5376e1892a9187 Mon Sep 17 00:00:00 2001 From: PrivacyOnion Date: Wed, 25 Nov 2026 07:19:54 +0100 Subject: [PATCH 2/5] hle, docs: end crashing process on restart and clear env var --- crates/xtp-hle/src/modules/lifecycle.rs | 49 ++++++++++++++++++------ crates/xtp-hle/src/modules/xgame.rs | 12 +++--- crates/xtp-hle/tests/restart_on_crash.rs | 37 ++++++++++++++---- docs/analysis/hle.md | 4 +- 4 files changed, 74 insertions(+), 28 deletions(-) diff --git a/crates/xtp-hle/src/modules/lifecycle.rs b/crates/xtp-hle/src/modules/lifecycle.rs index 4d132d01..a989974d 100644 --- a/crates/xtp-hle/src/modules/lifecycle.rs +++ b/crates/xtp-hle/src/modules/lifecycle.rs @@ -240,9 +240,15 @@ pub(crate) fn end_title(why: &'static str, then: Box) { 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. +/// 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); @@ -254,9 +260,12 @@ pub(crate) fn set_restart_on_crash(args: Vec) { /// Crash-reporter hook (`xtp_loader::on_crash`): if `XLaunchRestartOnCrash` /// recorded arguments and this process was not already restarted from a crash, -/// spawns a replacement process once with [`CRASH_RESTARTED`] set. +/// spawns a replacement process once with [`CRASH_RESTARTED`] set and ends +/// this process immediately so the two instances never overlap. pub fn relaunch_on_crash() { - if std::env::var_os(CRASH_RESTARTED).is_some() { + if ALREADY_CRASH_RESTARTED.load(Ordering::Relaxed) + || std::env::var_os(CRASH_RESTARTED).is_some() + { tracing::info!("skipping crash restart: already restarted once"); return; } @@ -266,16 +275,18 @@ pub fn relaunch_on_crash() { let Some(args) = guard.take() else { return; }; - relaunch_with_env(args, Some((CRASH_RESTARTED, "1"))); + if relaunch_with_env(args, Some((CRASH_RESTARTED, "1"))) { + end_with(1); + } } /// 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) { - relaunch_with_env(args, None); + let _ = relaunch_with_env(args, None); } -fn relaunch_with_env(args: Vec, extra_env: Option<(&str, &str)>) { +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. @@ -302,16 +313,28 @@ fn relaunch_with_env(args: Vec, extra_env: Option<(&str, &st 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()) @@ -329,13 +352,17 @@ pub fn wait_for_previous() { } fn end() { + end_with(0); +} + +fn end_with(code: u32) { // A held cursor would outlive us. super::gameinput::release_mouse(); // Compiled host pipelines kept for the next run. #[cfg(windows)] xtp_gpu::pipeline::save_pipeline_cache(); // SAFETY: ends this process, as the console ends a suspended title. - unsafe { TerminateProcess(GetCurrentProcess(), 0) }; + unsafe { TerminateProcess(GetCurrentProcess(), code) }; } pub(crate) fn module() -> HleModule { diff --git a/crates/xtp-hle/src/modules/xgame.rs b/crates/xtp-hle/src/modules/xgame.rs index 7004100e..fa0acdc5 100644 --- a/crates/xtp-hle/src/modules/xgame.rs +++ b/crates/xtp-hle/src/modules/xgame.rs @@ -93,21 +93,16 @@ extern "system" fn launch_new_game( } } -const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32; - /// 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 E_INVALIDARG; + return super::xasync::E_INVALIDARG; } let args = text(args).unwrap_or_default(); tracing::info!(args, "XLaunchRestartOnCrash"); - let current = runtime::main_image() - .and_then(runtime::image_path) - .unwrap_or_default(); let ours: Vec<_> = std::env::args_os().skip(1).collect(); - let command = relaunch_args(ours, current.as_os_str(), "", &args); + let command = relaunch_args(ours, std::ffi::OsStr::new(""), "", &args); super::lifecycle::set_restart_on_crash(command); S_OK } @@ -180,6 +175,9 @@ extern "system" fn write_event( S_OK } +/// `TITLE_IID` exposes the three `XGame.h` functions in declaration order after +/// `IUnknown`: `XGameGetXboxTitleId` (0x18), `XLaunchNewGame` (0x20), and +/// `XLaunchRestartOnCrash` (0x28). static TITLE_VTABLE: Methods<6> = Methods([ missing::<0> as *const (), add_ref as *const (), diff --git a/crates/xtp-hle/tests/restart_on_crash.rs b/crates/xtp-hle/tests/restart_on_crash.rs index f5fc6f7e..3fba48cc 100644 --- a/crates/xtp-hle/tests/restart_on_crash.rs +++ b/crates/xtp-hle/tests/restart_on_crash.rs @@ -41,20 +41,41 @@ fn run_parent() { "initial child should terminate with a fault" ); - // Wait for the restarted grandchild to start, record its line, and fault. + // Wait for the restarted grandchild to start and log its PID. let deadline = Instant::now() + Duration::from_secs(10); + let mut grandchild_pid = None; while Instant::now() < deadline { - if let Ok(text) = std::fs::read_to_string(&log_path) - && text.lines().count() >= 2 - { - break; + if let Ok(text) = std::fs::read_to_string(&log_path) { + let lines: Vec<&str> = text.lines().collect(); + if lines.len() >= 2 { + grandchild_pid = lines[1] + .strip_prefix("pid=") + .and_then(|rest| rest.split_whitespace().next()) + .and_then(|s| s.parse::().ok()); + break; + } } std::thread::sleep(Duration::from_millis(50)); } - // Give a brief settle window to verify a second crash does NOT trigger a - // third launch. - std::thread::sleep(Duration::from_millis(400)); + // Deterministically wait for the restarted grandchild to fault and exit so + // it is never left running and we know no third launch occurred. + if let Some(pid) = grandchild_pid { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Threading::{ + OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject, + }; + // SAFETY: opening the grandchild PID for SYNCHRONIZE only. + let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) }; + if !handle.is_null() { + // SAFETY: valid process handle returned by `OpenProcess`. + unsafe { + WaitForSingleObject(handle, 10_000); + CloseHandle(handle); + } + } + } + let final_text = std::fs::read_to_string(&log_path).expect("read probe log"); let final_lines: Vec<&str> = final_text.lines().collect(); diff --git a/docs/analysis/hle.md b/docs/analysis/hle.md index fb983d42..b5624bdc 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 | 5 (lifecycle + `restart_on_crash`) / — | Partial (R10) | | HDR, URIs, deferrals, screenshots | ✔ | ◐ | 1 / — | Keep XTP | ### 4.3 Audio @@ -372,7 +372,7 @@ 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). From 709ae5d9c59773e6118934e93077937bd11649e3 Mon Sep 17 00:00:00 2001 From: PrivacyOnion Date: Wed, 25 Nov 2026 07:48:25 +0100 Subject: [PATCH 3/5] hle, docs: terminate directly on crash restart and check exit codes --- crates/xtp-hle/src/modules/lifecycle.rs | 15 ++++--- crates/xtp-hle/src/modules/xgame.rs | 7 +-- crates/xtp-hle/tests/restart_on_crash.rs | 55 ++++++++++++++++++------ docs/analysis/hle.md | 6 +-- 4 files changed, 58 insertions(+), 25 deletions(-) diff --git a/crates/xtp-hle/src/modules/lifecycle.rs b/crates/xtp-hle/src/modules/lifecycle.rs index a989974d..106d6a2a 100644 --- a/crates/xtp-hle/src/modules/lifecycle.rs +++ b/crates/xtp-hle/src/modules/lifecycle.rs @@ -276,7 +276,14 @@ pub fn relaunch_on_crash() { return; }; if relaunch_with_env(args, Some((CRASH_RESTARTED, "1"))) { - end_with(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); + } } } @@ -352,17 +359,13 @@ pub fn wait_for_previous() { } fn end() { - end_with(0); -} - -fn end_with(code: u32) { // A held cursor would outlive us. super::gameinput::release_mouse(); // Compiled host pipelines kept for the next run. #[cfg(windows)] xtp_gpu::pipeline::save_pipeline_cache(); // SAFETY: ends this process, as the console ends a suspended title. - unsafe { TerminateProcess(GetCurrentProcess(), code) }; + unsafe { TerminateProcess(GetCurrentProcess(), 0) }; } pub(crate) fn module() -> HleModule { diff --git a/crates/xtp-hle/src/modules/xgame.rs b/crates/xtp-hle/src/modules/xgame.rs index fa0acdc5..7914815a 100644 --- a/crates/xtp-hle/src/modules/xgame.rs +++ b/crates/xtp-hle/src/modules/xgame.rs @@ -175,9 +175,10 @@ extern "system" fn write_event( S_OK } -/// `TITLE_IID` exposes the three `XGame.h` functions in declaration order after -/// `IUnknown`: `XGameGetXboxTitleId` (0x18), `XLaunchNewGame` (0x20), and -/// `XLaunchRestartOnCrash` (0x28). +/// `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 (), diff --git a/crates/xtp-hle/tests/restart_on_crash.rs b/crates/xtp-hle/tests/restart_on_crash.rs index 3fba48cc..17fb0c92 100644 --- a/crates/xtp-hle/tests/restart_on_crash.rs +++ b/crates/xtp-hle/tests/restart_on_crash.rs @@ -36,9 +36,10 @@ fn run_parent() { .env_remove("XTP_RELAUNCHED_FROM") .status() .expect("spawn initial child"); - assert!( - !status.success(), - "initial child should terminate with a fault" + assert_eq!( + status.code(), + Some(1), + "initial child should terminate with exit code 1 after spawning its replacement" ); // Wait for the restarted grandchild to start and log its PID. @@ -58,21 +59,49 @@ fn run_parent() { std::thread::sleep(Duration::from_millis(50)); } - // Deterministically wait for the restarted grandchild to fault and exit so - // it is never left running and we know no third launch occurred. - if let Some(pid) = grandchild_pid { - use windows_sys::Win32::Foundation::CloseHandle; + // Deterministically wait for the restarted grandchild to fault and exit, + // killing it if the wait times out. Asserting its exit code is + // STATUS_ACCESS_VIOLATION (0xC0000005) proves it did not take the + // crash-restart path (which exits with 1) and therefore spawned no third + // process. + let pid = grandchild_pid.expect("restarted grandchild never logged its PID"); + { + use windows_sys::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; use windows_sys::Win32::System::Threading::{ - OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject, + GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, + PROCESS_SYNCHRONIZE, PROCESS_TERMINATE, TerminateProcess, WaitForSingleObject, + }; + const STATUS_ACCESS_VIOLATION: u32 = 0xC000_0005; + // SAFETY: opening the grandchild PID to wait, query exit code, or kill + // on timeout. + let handle = unsafe { + OpenProcess( + PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_TERMINATE, + 0, + pid, + ) }; - // SAFETY: opening the grandchild PID for SYNCHRONIZE only. - let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) }; if !handle.is_null() { // SAFETY: valid process handle returned by `OpenProcess`. - unsafe { - WaitForSingleObject(handle, 10_000); - CloseHandle(handle); + let wait = unsafe { WaitForSingleObject(handle, 10_000) }; + if wait != WAIT_OBJECT_0 { + // SAFETY: terminating a timed-out test grandchild. + unsafe { + TerminateProcess(handle, 1); + CloseHandle(handle); + } + panic!("restarted grandchild (pid={pid}) did not exit within 10 s"); } + let mut exit_code = 0u32; + // SAFETY: querying exit code of the exited grandchild handle. + let got = unsafe { GetExitCodeProcess(handle, &mut exit_code) }; + // SAFETY: closing the handle from `OpenProcess`. + unsafe { CloseHandle(handle) }; + assert_ne!(got, 0, "GetExitCodeProcess failed"); + assert_eq!( + exit_code, STATUS_ACCESS_VIOLATION, + "grandchild should exit with STATUS_ACCESS_VIOLATION (not relaunch again), got {exit_code:#x}" + ); } } diff --git a/docs/analysis/hle.md b/docs/analysis/hle.md index b5624bdc..ab2e4f92 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 | ✔ `XLaunchRestartOnCrash` tested; `XLaunchNewGame` untested live | ✔ both | 5 (lifecycle + `restart_on_crash`) / — | Partial (R10) | +| Relaunch (`XLaunchNewGame`), restart on crash | ◐ `XLaunchRestartOnCrash` tested; `XLaunchNewGame` untested live | ✔ both | 5 (lifecycle + `restart_on_crash`) / — | Partial (R10) | | HDR, URIs, deferrals, screenshots | ✔ | ◐ | 1 / — | Keep XTP | ### 4.3 Audio @@ -374,8 +374,8 @@ shows the title calls them. ### 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). + with the arguments) on the real title. `XLaunchRestartOnCrash` (record the + arguments; the crash reporter relaunches once) is done. - **Files:** `crates/xtp-hle/src/modules/xgame.rs`, `modules/lifecycle.rs`, `apps/xtp/src/run.rs` (relaunch path). - **xcl ref:** `hle/xgameruntime/api.rs` `XLaunchNewGame`, From b04fb41677fcb379fa170b9e454b03edf1f636f4 Mon Sep 17 00:00:00 2001 From: PrivacyOnion Date: Wed, 25 Nov 2026 12:49:42 +0100 Subject: [PATCH 4/5] hle, loader, app, docs: honor title filters and autopilot on restart --- apps/xtp/src/run.rs | 2 +- crates/xtp-hle/src/modules/kernel.rs | 7 +- crates/xtp-hle/src/modules/lifecycle.rs | 33 ++- crates/xtp-hle/tests/restart_on_crash.rs | 310 +++++++++++++---------- crates/xtp-loader/src/crash.rs | 19 +- crates/xtp-loader/src/lib.rs | 2 +- docs/analysis/hle.md | 14 +- 7 files changed, 232 insertions(+), 155 deletions(-) diff --git a/apps/xtp/src/run.rs b/apps/xtp/src/run.rs index 69a4b40f..c028f0e8 100644 --- a/apps/xtp/src/run.rs +++ b/apps/xtp/src/run.rs @@ -251,7 +251,7 @@ pub fn run( return Ok(()); } xtp_loader::report_crashes(); - xtp_loader::on_crash(xtp_hle::modules::lifecycle::relaunch_on_crash); + 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/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 106d6a2a..52b5e186 100644 --- a/crates/xtp-hle/src/modules/lifecycle.rs +++ b/crates/xtp-hle/src/modules/lifecycle.rs @@ -258,23 +258,34 @@ pub(crate) fn set_restart_on_crash(args: Vec) { *RESTART_ON_CRASH.lock().unwrap_or_else(|e| e.into_inner()) = Some(args); } -/// Crash-reporter hook (`xtp_loader::on_crash`): if `XLaunchRestartOnCrash` -/// recorded arguments and this process was not already restarted from a crash, -/// spawns a replacement process once with [`CRASH_RESTARTED`] set and ends -/// this process immediately so the two instances never overlap. -pub fn relaunch_on_crash() { +/// 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 autopilot { + tracing::info!("skipping crash restart: autopilot is enabled"); + return; + } if ALREADY_CRASH_RESTARTED.load(Ordering::Relaxed) || std::env::var_os(CRASH_RESTARTED).is_some() { tracing::info!("skipping crash restart: already restarted once"); return; } - let Ok(mut guard) = RESTART_ON_CRASH.try_lock() else { - return; - }; - let Some(args) = guard.take() else { - 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 diff --git a/crates/xtp-hle/tests/restart_on_crash.rs b/crates/xtp-hle/tests/restart_on_crash.rs index 17fb0c92..4ac7fcd1 100644 --- a/crates/xtp-hle/tests/restart_on_crash.rs +++ b/crates/xtp-hle/tests/restart_on_crash.rs @@ -1,172 +1,228 @@ -//! Child-process test for `XLaunchRestartOnCrash` (issue #11 / R10): -//! a probe registers restart-on-crash arguments, triggers an unhandled fault, -//! is automatically relaunched with the recorded arguments after waiting for -//! the crashing process to exit, and does not relaunch a third time when it -//! faults again. +//! Isolated child-process probes for crash restart, the title's unhandled +//! exception filter, and unattended runs. #![cfg(windows)] -use std::ffi::{CString, c_char}; +use std::ffi::{c_char, c_void}; use std::fs::OpenOptions; use std::io::Write; -use std::path::PathBuf; +use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle}; +use std::path::{Path, PathBuf}; use std::process::Command; -use std::time::{Duration, Instant}; - -use xtp_hle::modules::{lifecycle, xgame, xgameruntime}; - -const PROBE_LOG_ENV: &str = "XTP_RESTART_PROBE_LOG"; +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::Threading::{ + CreateEventW, EVENT_MODIFY_STATE, GetExitCodeProcess, OpenEventW, OpenProcess, + PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE, + SYNCHRONIZATION_SYNCHRONIZE, SetEvent, TerminateProcess, WaitForSingleObject, +}; +use xtp_hle::modules::{kernel, lifecycle, 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(); fn main() { - if let Some(log_path) = std::env::var_os(PROBE_LOG_ENV) { - run_child(PathBuf::from(log_path)); + if let Some(dir) = std::env::var_os(PROBE_DIR_ENV) { + run_child(Path::new(&dir)); } else { - run_parent(); + run_parent("default", &[]); + run_parent( + "title-filter", + &["filter resumed", "execution resumed", "filter searched"], + ); + run_parent("autopilot", &[]); } } -fn run_parent() { - let dir = tempfile::tempdir().expect("temp dir"); - let log_path = dir.path().join("runs.log"); - - let exe = std::env::current_exe().expect("test binary path"); - let status = Command::new(&exe) - .arg("--probe-mode") - .env(PROBE_LOG_ENV, &log_path) +fn run_parent(mode: &str, filter_log: &[&str]) { + let dir = tempfile::tempdir().expect("probe directory"); + let dir = dir.path(); + let ready = event(dir, "ready", true); + let proceed = event(dir, "proceed", true); + let child = Command::new(std::env::current_exe().expect("test binary path")) + .arg(mode) + .env(PROBE_DIR_ENV, dir) .env_remove("XTP_CRASH_RESTARTED") .env_remove("XTP_RELAUNCHED_FROM") - .status() - .expect("spawn initial child"); - assert_eq!( - status.code(), - Some(1), - "initial child should terminate with exit code 1 after spawning its replacement" - ); + .spawn() + .expect("spawn initial probe"); - // Wait for the restarted grandchild to start and log its PID. - let deadline = Instant::now() + Duration::from_secs(10); - let mut grandchild_pid = None; - while Instant::now() < deadline { - if let Ok(text) = std::fs::read_to_string(&log_path) { - let lines: Vec<&str> = text.lines().collect(); - if lines.len() >= 2 { - grandchild_pid = lines[1] - .strip_prefix("pid=") - .and_then(|rest| rest.split_whitespace().next()) - .and_then(|s| s.parse::().ok()); - break; - } - } - std::thread::sleep(Duration::from_millis(50)); - } - - // Deterministically wait for the restarted grandchild to fault and exit, - // killing it if the wait times out. Asserting its exit code is - // STATUS_ACCESS_VIOLATION (0xC0000005) proves it did not take the - // crash-restart path (which exits with 1) and therefore spawned no third - // process. - let pid = grandchild_pid.expect("restarted grandchild never logged its PID"); - { - use windows_sys::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; - use windows_sys::Win32::System::Threading::{ - GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, - PROCESS_SYNCHRONIZE, PROCESS_TERMINATE, TerminateProcess, WaitForSingleObject, - }; - const STATUS_ACCESS_VIOLATION: u32 = 0xC000_0005; - // SAFETY: opening the grandchild PID to wait, query exit code, or kill - // on timeout. - let handle = unsafe { + let status = wait_for_exit(child.as_raw_handle(), "initial probe"); + if mode == "autopilot" { + assert_eq!(status, STATUS_ACCESS_VIOLATION, "autopilot's original exit"); + assert!(!dir.join("replacement.pid").exists()); + } else { + assert_eq!(status, 1, "crash-restart exit for {mode}"); + // 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 | PROCESS_TERMINATE, 0, pid, ) }; - if !handle.is_null() { - // SAFETY: valid process handle returned by `OpenProcess`. - let wait = unsafe { WaitForSingleObject(handle, 10_000) }; - if wait != WAIT_OBJECT_0 { - // SAFETY: terminating a timed-out test grandchild. - unsafe { - TerminateProcess(handle, 1); - CloseHandle(handle); - } - panic!("restarted grandchild (pid={pid}) did not exit within 10 s"); - } - let mut exit_code = 0u32; - // SAFETY: querying exit code of the exited grandchild handle. - let got = unsafe { GetExitCodeProcess(handle, &mut exit_code) }; - // SAFETY: closing the handle from `OpenProcess`. - unsafe { CloseHandle(handle) }; - assert_ne!(got, 0, "GetExitCodeProcess failed"); - assert_eq!( - exit_code, STATUS_ACCESS_VIOLATION, - "grandchild should exit with STATUS_ACCESS_VIOLATION (not relaunch again), got {exit_code:#x}" - ); - } + 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" + ); } - let final_text = std::fs::read_to_string(&log_path).expect("read probe log"); - let final_lines: Vec<&str> = final_text.lines().collect(); + let log = std::fs::read_to_string(dir.join("runs.log")).expect("read probe log"); + let mut expected = vec![mode]; + expected.extend_from_slice(filter_log); + let replacement_args = format!("{mode} -- -recover -slot=3"); + if mode != "autopilot" { + expected.push(&replacement_args); + } + assert_eq!(log.lines().collect::>(), expected); +} - assert_eq!( - final_lines.len(), - 2, - "expected exactly 2 runs (initial + 1 restart), got {final_lines:?}" - ); +fn own_handle(handle: RawHandle, operation: &str) -> OwnedHandle { assert!( - final_lines[0].contains("--probe-mode") && !final_lines[0].contains("-recover"), - "unexpected run 1 args: {}", - final_lines[0] + !handle.is_null(), + "{operation}: {}", + std::io::Error::last_os_error() ); - assert!( - final_lines[1].contains("--probe-mode") && final_lines[1].contains("-- -recover -slot=3"), - "run 2 did not receive recorded restart arguments: {}", - final_lines[1] + // 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() ); - println!("test restart_on_crash ... ok"); + 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 run_child(log_path: PathBuf) { +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, query and + // terminate rights throughout this call. + unsafe { + let wait = WaitForSingleObject(process, TIMEOUT_MS); + if wait != WAIT_OBJECT_0 { + TerminateProcess(process, 1); + WaitForSingleObject(process, TIMEOUT_MS); + panic!("waiting for {what} to exit: {wait:#x}"); + } + let mut code = 0; + assert_ne!(GetExitCodeProcess(process, &mut code), 0); + 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) { lifecycle::wait_for_previous(); - let args: Vec = std::env::args().skip(1).collect(); - { - let mut f = OpenOptions::new() - .create(true) - .append(true) - .open(&log_path) - .expect("open probe log"); - writeln!(f, "pid={} args={}", std::process::id(), args.join(" ")).expect("write probe log"); - let _ = f.flush(); + // SAFETY: this probe process can suppress dialogs for its own fault. + unsafe { SetErrorMode(SEM_NOGPFAULTERRORBOX) }; + let args: Vec<_> = std::env::args().skip(1).collect(); + LOG.set(dir.join("runs.log")).expect("set probe log path"); + log(&args.join(" ")); + + let replacement = args.iter().any(|arg| arg == "--"); + if replacement { + let ready = event(dir, "ready", false); + let proceed = event(dir, "proceed", 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"); } xtp_loader::report_crashes(); - xtp_loader::on_crash(lifecycle::relaunch_on_crash); + lifecycle::install_crash_restart(args[0] == "autopilot"); - // Call XLaunchRestartOnCrash through TITLE_OBJECT vtable slot 0x28. let obj = &xgame::TITLE_OBJECT; type RestartOnCrash = extern "system" fn( *const xgameruntime::Object, *const c_char, u32, ) -> xgameruntime::HRESULT; - // SAFETY: `TITLE_OBJECT`'s first word is its vtable; slot 5 (offset 0x28) - // is `launch_restart_on_crash`. + // SAFETY: `TITLE_OBJECT` starts with its vtable; slot 5 implements + // `XLaunchRestartOnCrash` with this signature. let restart: RestartOnCrash = unsafe { - let vtable = *(obj as *const xgameruntime::Object as *const *const *const ()); + let vtable = *std::ptr::from_ref(obj).cast::<*const *const ()>(); std::mem::transmute(*vtable.add(5)) }; + assert!(restart(obj, std::ptr::null(), 1) < 0); + assert_eq!( + restart(obj, c"-recover -slot=3".as_ptr(), 0), + xgameruntime::S_OK + ); - let bad_hr = restart(obj, std::ptr::null(), 1); - assert!(bad_hr < 0, "non-zero reserved must fail"); - - let recorded = CString::new("-recover -slot=3").unwrap(); - let hr = restart(obj, recorded.as_ptr(), 0); - assert_eq!(hr, xgameruntime::S_OK); - - // Deliberately trigger an unhandled access violation so `report_unhandled` - // invokes the registered crash-restart hook. - // SAFETY: intentional null write in an isolated child probe process. - unsafe { - std::ptr::write_volatile(std::ptr::null_mut::(), 0xdead_beef); + if !replacement && args[0] == "title-filter" { + 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"); } + + // 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 81210873..bedfef53 100644 --- a/crates/xtp-loader/src/crash.rs +++ b/crates/xtp-loader/src/crash.rs @@ -55,19 +55,20 @@ 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 invoked once after an unhandled crash is reported -/// (used by `XLaunchRestartOnCrash`). Stored in an atomic pointer so crash -/// handling never blocks on a mutex. +/// 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 an unhandled crash has been -/// reported (before the process terminates). +/// 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); } -fn run_on_crash() { +/// 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; @@ -162,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(); @@ -613,15 +615,14 @@ 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. pub unsafe fn report_unhandled(info: *const EXCEPTION_POINTERS) { // SAFETY: forwarded from the caller. unsafe { report("unhandled exception", info, true) }; - run_on_crash(); } /// The bytes at `at` as hex, as many as the longest x86 instruction (15), diff --git a/crates/xtp-loader/src/lib.rs b/crates/xtp-loader/src/lib.rs index 29ed8579..69ea0538 100644 --- a/crates/xtp-loader/src/lib.rs +++ b/crates/xtp-loader/src/lib.rs @@ -56,7 +56,7 @@ pub use crash::save_on_crash; #[cfg(windows)] pub use crash::{ locate, log_crash, log_crashes_to, note_title_output, on_crash, - read_memory as read_title_memory, report_crashes, report_unhandled, + 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 ab2e4f92..68b9a578 100644 --- a/docs/analysis/hle.md +++ b/docs/analysis/hle.md @@ -375,14 +375,18 @@ shows the title calls them. ### 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. `XLaunchRestartOnCrash` (record the - arguments; the crash reporter relaunches once) is done. -- **Files:** `crates/xtp-hle/src/modules/xgame.rs`, `modules/lifecycle.rs`, - `apps/xtp/src/run.rs` (relaunch path). + 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. +- **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 and an unattended run keeping its original exit. - **Depends on:** — ### R7. Closed captions and high contrast — S (done) @@ -510,7 +514,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, restart on crash | S | Restart tested; live relaunch pending | | 12 | R7 closed captions, high contrast (done) | S | — | | 13 | R6 speech synthesis (done) | M | — | | 14 | I3 trigger rumble | M | — | From d50e45d24869f91f614efe0e7d4daa00bc93514d Mon Sep 17 00:00:00 2001 From: PrivacyOnion Date: Wed, 25 Nov 2026 14:50:22 +0100 Subject: [PATCH 5/5] hle, docs: disarm crash restart on shutdown and harden probes --- crates/xtp-hle/Cargo.toml | 7 +- crates/xtp-hle/src/modules/lifecycle.rs | 15 +- crates/xtp-hle/src/modules/xgame.rs | 21 ++ crates/xtp-hle/tests/restart_on_crash.rs | 256 ++++++++++++++++++----- docs/analysis/hle.md | 9 +- 5 files changed, 248 insertions(+), 60 deletions(-) diff --git a/crates/xtp-hle/Cargo.toml b/crates/xtp-hle/Cargo.toml index 4e5f23c4..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 = [ @@ -69,7 +72,3 @@ diagnostics = [ [lints] workspace = true - -[[test]] -name = "restart_on_crash" -harness = false diff --git a/crates/xtp-hle/src/modules/lifecycle.rs b/crates/xtp-hle/src/modules/lifecycle.rs index 52b5e186..e01815ef 100644 --- a/crates/xtp-hle/src/modules/lifecycle.rs +++ b/crates/xtp-hle/src/modules/lifecycle.rs @@ -31,6 +31,8 @@ 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); + const ERROR_INVALID_PARAMETER: u32 = 87; pub extern "system" fn RegisterAppStateChangeNotification( @@ -203,10 +205,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) { 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 @@ -255,7 +260,10 @@ static RESTART_ON_CRASH: Mutex>> = Mutex::new(Non /// Records the arguments to relaunch with if the process hits an unhandled /// crash (`XLaunchRestartOnCrash`). pub(crate) fn set_restart_on_crash(args: Vec) { - *RESTART_ON_CRASH.lock().unwrap_or_else(|e| e.into_inner()) = Some(args); + 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 @@ -276,6 +284,9 @@ fn relaunch_on_crash(autopilot: bool) { else { return; }; + if ENDING.load(Ordering::SeqCst) { + return; + } if autopilot { tracing::info!("skipping crash restart: autopilot is enabled"); return; diff --git a/crates/xtp-hle/src/modules/xgame.rs b/crates/xtp-hle/src/modules/xgame.rs index 7914815a..395838b2 100644 --- a/crates/xtp-hle/src/modules/xgame.rs +++ b/crates/xtp-hle/src/modules/xgame.rs @@ -248,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 index 4ac7fcd1..f18286ee 100644 --- a/crates/xtp-hle/tests/restart_on_crash.rs +++ b/crates/xtp-hle/tests/restart_on_crash.rs @@ -15,12 +15,18 @@ 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, PROCESS_TERMINATE, - SYNCHRONIZATION_SYNCHRONIZE, SetEvent, TerminateProcess, WaitForSingleObject, + PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, SYNCHRONIZATION_SYNCHRONIZE, SetEvent, + WaitForSingleObject, }; -use xtp_hle::modules::{kernel, lifecycle, xgame, xgameruntime}; +use xtp_hle::modules::{kernel, lifecycle, xasync, xgame, xgameruntime}; const PROBE_DIR_ENV: &str = "XTP_RESTART_PROBE_DIR"; const RECOVERABLE_EXCEPTION: u32 = 0xE042_4700; @@ -28,38 +34,88 @@ const STATUS_ACCESS_VIOLATION: u32 = EXCEPTION_ACCESS_VIOLATION as u32; const TIMEOUT_MS: u32 = 10_000; static LOG: OnceLock = OnceLock::new(); -fn main() { +#[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)); - } else { - run_parent("default", &[]); - run_parent( - "title-filter", - &["filter resumed", "execution resumed", "filter searched"], - ); - run_parent("autopilot", &[]); + run_child(Path::new(&dir), scenario); } -} -fn run_parent(mode: &str, filter_log: &[&str]) { let dir = tempfile::tempdir().expect("probe directory"); let dir = dir.path(); let ready = event(dir, "ready", true); let proceed = event(dir, "proceed", true); - let child = Command::new(std::env::current_exe().expect("test binary path")) - .arg(mode) + 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"); - if mode == "autopilot" { - assert_eq!(status, STATUS_ACCESS_VIOLATION, "autopilot's original exit"); - assert!(!dir.join("replacement.pid").exists()); + 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 {mode}"); + 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"); @@ -70,7 +126,7 @@ fn run_parent(mode: &str, filter_log: &[&str]) { // SAFETY: the waiting replacement published this PID. let process = unsafe { OpenProcess( - PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_TERMINATE, + PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, 0, pid, ) @@ -84,16 +140,77 @@ fn run_parent(mode: &str, filter_log: &[&str]) { ); } + 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 mut expected = vec![mode]; - expected.extend_from_slice(filter_log); - let replacement_args = format!("{mode} -- -recover -slot=3"); - if mode != "autopilot" { - expected.push(&replacement_args); - } + 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(), @@ -138,17 +255,17 @@ fn wait_for_event(event: &OwnedHandle, what: &str) { } fn wait_for_exit(process: RawHandle, what: &str) -> u32 { - // SAFETY: callers hold a live process handle with wait, query and - // terminate rights throughout this call. + // SAFETY: callers hold a live process handle with wait and query rights. unsafe { let wait = WaitForSingleObject(process, TIMEOUT_MS); - if wait != WAIT_OBJECT_0 { - TerminateProcess(process, 1); - WaitForSingleObject(process, TIMEOUT_MS); - panic!("waiting for {what} to exit: {wait:#x}"); - } + assert_eq!(wait, WAIT_OBJECT_0, "waiting for {what} to exit"); let mut code = 0; - assert_ne!(GetExitCodeProcess(process, &mut code), 0); + assert_ne!( + GetExitCodeProcess(process, &mut code), + 0, + "query {what} exit code: {}", + std::io::Error::last_os_error() + ); code } } @@ -174,26 +291,33 @@ extern "system" fn title_filter(info: *const c_void) -> i32 { } } -fn run_child(dir: &Path) { - lifecycle::wait_for_previous(); +fn run_child(dir: &Path, scenario: Scenario) -> ! { // SAFETY: this probe process can suppress dialogs for its own fault. unsafe { SetErrorMode(SEM_NOGPFAULTERRORBOX) }; - let args: Vec<_> = std::env::args().skip(1).collect(); + 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"); - log(&args.join(" ")); - let replacement = args.iter().any(|arg| arg == "--"); if replacement { + log("replacement"); + for arg in std::env::args().skip_while(|arg| arg != "--") { + log(&arg); + } let ready = event(dir, "ready", false); - let proceed = event(dir, "proceed", 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(args[0] == "autopilot"); + lifecycle::install_crash_restart(matches!(scenario, Scenario::Autopilot)); let obj = &xgame::TITLE_OBJECT; type RestartOnCrash = extern "system" fn( @@ -203,24 +327,54 @@ fn run_child(dir: &Path) { ) -> xgameruntime::HRESULT; // SAFETY: `TITLE_OBJECT` starts with its vtable; slot 5 implements // `XLaunchRestartOnCrash` with this signature. - let restart: RestartOnCrash = unsafe { - let vtable = *std::ptr::from_ref(obj).cast::<*const *const ()>(); - std::mem::transmute(*vtable.add(5)) + 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!(restart(obj, std::ptr::null(), 1) < 0); - assert_eq!( - restart(obj, c"-recover -slot=3".as_ptr(), 0), - xgameruntime::S_OK - ); + assert_eq!(restart(obj, args, 0), xgameruntime::S_OK); - if !replacement && args[0] == "title-filter" { + 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()) }; diff --git a/docs/analysis/hle.md b/docs/analysis/hle.md index 68b9a578..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 | ◐ `XLaunchRestartOnCrash` tested; `XLaunchNewGame` untested live | ✔ both | 5 (lifecycle + `restart_on_crash`) / — | Partial (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 @@ -379,6 +379,8 @@ shows the title calls them. 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`, @@ -386,7 +388,8 @@ shows the title calls them. - **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. The probe also covers a title - filter resuming execution and an unattended run keeping its original exit. + 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) @@ -514,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 | Restart tested; live relaunch pending | +| 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 | — |