Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/xtp/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down
3 changes: 3 additions & 0 deletions crates/xtp-hle/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down
7 changes: 6 additions & 1 deletion crates/xtp-hle/src/modules/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,15 +266,20 @@ 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;
// SAFETY: the title registered this filter.
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.
Expand Down
150 changes: 144 additions & 6 deletions crates/xtp-hle/src/modules/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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<dyn FnOnce() + Send>) {
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
Expand Down Expand Up @@ -239,9 +248,83 @@ pub(crate) fn end_title(why: &'static str, then: Box<dyn FnOnce() + Send>) {
/// 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<Option<Vec<std::ffi::OsString>>> = 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<std::ffi::OsString>) {
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<std::ffi::OsString>) {
let _ = relaunch_with_env(args, None);
}

fn relaunch_with_env(args: Vec<std::ffi::OsString>, 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.
Expand All @@ -262,19 +345,34 @@ pub(crate) fn relaunch(args: Vec<std::ffi::OsString>) {
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::<usize>().ok())
Expand Down Expand Up @@ -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]
Expand Down
46 changes: 43 additions & 3 deletions crates/xtp-hle/src/modules/xgame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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([
Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading