Skip to content
Draft
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
12 changes: 11 additions & 1 deletion crates/xcl/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,17 @@ fn main() {
// xcl.exe without high-entropy ASLR: the title's memory then lies under 2^40, which a
// retail title's BVH builder requires of its GPU addresses (#585, PR #631)
match std::env::var("CARGO_CFG_TARGET_ENV").as_deref() {
Ok("msvc") => println!("cargo:rustc-link-arg-bin=xcl=/HIGHENTROPYVA:NO"),
Ok("msvc") => {
println!("cargo:rustc-link-arg-bin=xcl=/HIGHENTROPYVA:NO");
// the segment heap as the process heap (`xcl.manifest`): NVIDIA's compiler and DXC
// allocate from it on many threads at once during the shader preparation, and the NT
// heap's lock serialises them (#156)
let dir = std::env::var_os("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR");
let manifest = Path::new(&dir).join("xcl.manifest");
println!("cargo:rerun-if-changed=xcl.manifest");
println!("cargo:rustc-link-arg-bin=xcl=/MANIFEST:EMBED");
println!("cargo:rustc-link-arg-bin=xcl=/MANIFESTINPUT:{}", manifest.display());
}
Ok("gnu") => println!("cargo:rustc-link-arg-bin=xcl=-Wl,--disable-high-entropy-va"),
_ => {}
}
Expand Down
42 changes: 33 additions & 9 deletions crates/xcl/src/eh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,25 +127,49 @@ static ENDING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::ne
/// trace: the buffered log lines went with the process.
unsafe extern "system" fn hk_nt_terminate_process(h: isize, status: i32) -> i32 {
if (h == 0 || h == -1) && !ENDING.swap(true, Ordering::AcqRel) {
let probe = 0usize;
let (tid, stack) = (windows_sys::Win32::System::Threading::GetCurrentThreadId(), stack_callers_n(&probe as *const usize as usize, 16));
if status != 0 {
crate::xlog_error!("process ends with status {status:#x} (thread {tid}); on the stack: {stack}");
dump_threads();
} else {
crate::xlog_info!("process ends (thread {tid}); on the stack: {stack}");
}
crate::log::flush();
log_process_end(status);
}
let orig: unsafe extern "system" fn(isize, i32) -> i32 = std::mem::transmute(ORIG_NT_TERMINATE.load(Ordering::Acquire));
orig(h, status)
}

static ORIG_EXIT_USER_PROCESS: AtomicUsize = AtomicUsize::new(0);

/// ntdll!RtlExitUserProcess (ExitProcess, exit(), abort()'s _exit(3)): the end logged here,
/// before it takes the loader lock and the process heap's lock and ends the other threads. Its
/// `NtTerminateProcess(0, …)` then logs nothing: logging there allocates under the heap lock that
/// ntdll holds, which the NT heap lets the same thread take again but the segment heap does not
/// (the process hangs at its exit, #156).
unsafe extern "system" fn hk_rtl_exit_user_process(status: i32) {
if !ENDING.swap(true, Ordering::AcqRel) {
log_process_end(status);
}
let orig: unsafe extern "system" fn(i32) = std::mem::transmute(ORIG_EXIT_USER_PROCESS.load(Ordering::Acquire));
orig(status)
}

/// The end of the process, once: status, the calls that led there and, when the status is not 0,
/// every other thread – and the log written out.
unsafe fn log_process_end(status: i32) {
let probe = 0usize;
let (tid, stack) = (windows_sys::Win32::System::Threading::GetCurrentThreadId(), stack_callers_n(&probe as *const usize as usize, 16));
if status != 0 {
crate::xlog_error!("process ends with status {status:#x} (thread {tid}); on the stack: {stack}");
dump_threads();
} else {
crate::xlog_info!("process ends (thread {tid}); on the stack: {stack}");
}
crate::log::flush();
}

pub fn install_crash_handler() {
unsafe {
if let Err(e) = hooks::hook("ntdll.dll", "NtTerminateProcess", hk_nt_terminate_process as usize, &ORIG_NT_TERMINATE) {
crate::xlog_warn!("{e}");
}
if let Err(e) = hooks::hook("ntdll.dll", "RtlExitUserProcess", hk_rtl_exit_user_process as usize, &ORIG_EXIT_USER_PROCESS) {
crate::xlog_warn!("{e}");
}
SetUnhandledExceptionFilter(Some(unhandled_filter));
install_invalid_parameter_handler();
windows_sys::Win32::System::Diagnostics::Debug::AddVectoredExceptionHandler(0, Some(cpp_exception_logger));
Expand Down
3 changes: 3 additions & 0 deletions crates/xcl/tests/e2e.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,9 @@ fn test_title_runs_and_game_folder_is_untouched() {
assert!(backend_init < dll_init, "D3D12 backend initialized after title DLL code ran");
let window = |tag| log.lines().find_map(|line| line.split_once(tag).map(|(_, hwnd)| hwnd)).unwrap();
assert_eq!(window("Shader preparation window "), window("present: swap chain window "));
// the title's ExitProcess is logged (`eh::hk_rtl_exit_user_process`), before ntdll's exit
// takes the heap lock: under the segment heap, logging later hangs the exit (#156)
assert!(log.contains("process ends (thread "), "the end of the process is not in the log");

// (2) the game folder is untouched
assert_eq!(snapshot(&game), before, "GAME FOLDER WAS MODIFIED");
Expand Down
17 changes: 17 additions & 0 deletions crates/xcl/tests/segment_heap.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//! `xcl.exe` carries the manifest that makes the segment heap its process heap (`xcl.manifest`,
//! embedded by `build.rs` on MSVC).

#[cfg(target_env = "msvc")]
#[test]
fn xcl_exe_asks_for_the_segment_heap() {
use windows_sys::Win32::System::LibraryLoader::{FindResourceW, LoadLibraryExW, LOAD_LIBRARY_AS_DATAFILE};
let exe: Vec<u16> = env!("CARGO_BIN_EXE_xcl").encode_utf16().chain([0]).collect();
let module = unsafe { LoadLibraryExW(exe.as_ptr(), std::ptr::null_mut(), LOAD_LIBRARY_AS_DATAFILE) };
assert!(!module.is_null(), "xcl.exe cannot be loaded as a data file");
// RT_MANIFEST (24), CREATEPROCESS_MANIFEST_RESOURCE_ID (1): the manifest Windows reads at start
let found = unsafe { FindResourceW(module, 1 as _, 24 as _) };
assert!(!found.is_null(), "xcl.exe has no process manifest");
let bytes = std::fs::read(env!("CARGO_BIN_EXE_xcl")).expect("read xcl.exe");
let text = String::from_utf8_lossy(&bytes);
assert!(text.contains("<heapType") && text.contains(">SegmentHeap</heapType>"), "the manifest does not ask for the segment heap");
}
8 changes: 8 additions & 0 deletions crates/xcl/xcl.manifest
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<heapType xmlns="http://schemas.microsoft.com/SMI/2020/WindowsSettings">SegmentHeap</heapType>
</windowsSettings>
</application>
</assembly>
Loading