Run Grand Theft Auto VI from first boot into the world

The title now boots through every first-boot and menu screen at its own
30 fps, drawing with translated shaders, with input, sound, saves and
loading served; it reaches the world, where the host GPU path still
fails (see "Not working yet").

Loader and runtime
- Crash reports unwind properly, name C++ throws and host GPU failures,
  carry the title's last debug lines and are appended to crashes.log.
- Thread notices on our own threads, reentrant late DLL loading, exit in
  the console's order, relaunch on a launch-new-game request.
- Offline guard: the title cannot reach the network (sockets, name
  lookups, WinHTTP, the media source resolver); by-name lookups and
  loads follow the import rules.
- Every runtime area the title calls is served (networking hint,
  packages, store, saves, display, UI, speech stubs, user, async pool).
  Saves persist; an update is one rename and survives a kill at any step.
- DirectStorage reads for real: shared worker pool, priorities, zlib and
  BCPack. BCPack is our own decoder; the format's constant tables ship in
  crates/victory-formats/src/bcpack-tables.bin (the asset policy's one
  exception, see docs/asset-policy.md).
- GameInput from XInput pads and the keyboard, with a keyboard stand-in
  pad; console timers (1 ms) for the whole process.
- Audio: XMA2 decoding on the emulated contexts, Opus on the decoder
  queues, the DSP interface as a stub; title memory placed below 2^40.
- Console texture layouts (sizes, tiling, detiling) and the layout
  library's imports.

GPU
- Draws, mesh dispatches and compute dispatches run on the host with
  shaders translated at first use and cached on disk; descriptor heaps,
  views, root signatures, barriers and host texture states; rectangle
  lists; comparison samplers.
- Title memory reaches the host through persistent mirrors that copy
  only pages written since the last copy; shader-written buffers are
  copied back.
- Presentation with frame pacing per event kind; framerate in the window
  caption.

Shaders
- DXIL emission for vertex, pixel, compute and mesh programs from the
  console's native code, with a differential test suite against the PC
  compile. World set: mesh 8,191 of 8,506, vertex/pixel 10,617 of
  12,346, compute 1,643 of 2,539; utility set complete.

Build
- Debugging aids (debug logs, frame capture, stack dumps, scripted keys,
  the host debug layer, the software adapter) exist only with the
  `diagnostics` feature; `[profile.diag]` keeps that build apart.

Not working yet
- In the world the host device is removed within seconds (descriptor
  handling fixes are in, unproven by a surviving run) and frames present
  black.
- 64-bit image atomics, merged geometry stages and the BVH builder's own
  shaders do not translate; reverb is silent.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
MarvisandClaude Fable 5.2 committed 2026-11-23 23:10:01 +01:00
1 parent bc3070991a
commit 2849477415
107 files changed
+42526 -868

No files matched your search

+5
View File
@@ -20,6 +20,7 @@ windows-sys = { workspace = true, features = [
"Wdk_System_Threading",
"Win32_Foundation",
"Win32_System_Diagnostics_Debug",
"Win32_System_Diagnostics_ToolHelp",
"Win32_System_Kernel",
"Win32_System_LibraryLoader",
"Win32_System_Memory",
@@ -29,5 +30,9 @@ windows-sys = { workspace = true, features = [
[dev-dependencies]
tempfile.workspace = true
[features]
# Debugging switches (scheduled stack dumps and the like).
diagnostics = []
[lints]
workspace = true
+324 -42
View File
@@ -1,77 +1,330 @@
//! Names the faulting code when title code crashes.
//!
//! A vectored handler sees every exception first, so it only logs the kinds
//! that end a process (access violations and the like) and leaves handling
//! to the title's own handlers.
//! A vectored handler sees every exception first, so it only prints the
//! kinds that end a process (access violations and the like, and
//! breakpoints: titles assert with `int3`, fatal without a debugger) as
//! first-chance, since a handler may still take them (ntdll's loader does
//! with its own probes). What nobody handles, of any kind (an uncaught C++
//! exception too), is reported from the unhandled-exception filter
//! (`report_unhandled`, which the runtime calls ahead of the title's own)
//! and appended to the crash log, with the title's last debug output, which
//! often states the reason. Panics of ours go to the crash log too.
use std::ptr::null_mut;
use windows_sys::Win32::Foundation::{
EXCEPTION_ACCESS_VIOLATION, EXCEPTION_ILLEGAL_INSTRUCTION, EXCEPTION_INT_DIVIDE_BY_ZERO,
EXCEPTION_PRIV_INSTRUCTION, EXCEPTION_STACK_OVERFLOW, HMODULE,
EXCEPTION_ACCESS_VIOLATION, EXCEPTION_BREAKPOINT, EXCEPTION_ILLEGAL_INSTRUCTION,
EXCEPTION_INT_DIVIDE_BY_ZERO, EXCEPTION_PRIV_INSTRUCTION, EXCEPTION_STACK_OVERFLOW, HMODULE,
};
use windows_sys::Win32::System::Diagnostics::Debug::{
AddVectoredExceptionHandler, EXCEPTION_POINTERS,
AddVectoredExceptionHandler, CONTEXT, EXCEPTION_POINTERS, RtlLookupFunctionEntry,
RtlVirtualUnwind, SetUnhandledExceptionFilter, UNW_FLAG_NHANDLER,
};
use windows_sys::Win32::System::LibraryLoader::{
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
GetModuleFileNameW, GetModuleHandleExW,
};
use windows_sys::Win32::System::Threading::GetCurrentThreadStackLimits;
const EXCEPTION_CONTINUE_SEARCH: i32 = 0;
/// Stack slots scanned for return addresses into a module.
const STACK_SCAN: usize = 64;
/// Frames listed per report.
pub(crate) const MAX_FRAMES: usize = 40;
/// Installs the handler; call once before running title code.
pub fn report_crashes() {
// SAFETY: registers a handler that only reads the exception it is given.
unsafe { AddVectoredExceptionHandler(0, Some(handler)) };
/// Memory saved to files when a crash is reported: (address, length, file).
#[cfg(feature = "diagnostics")]
static SAVE: std::sync::OnceLock<Vec<(usize, usize, std::path::PathBuf)>> =
std::sync::OnceLock::new();
/// Debugging aid: on a reported crash, also write each `[address, address
/// + len)` (readable title memory, e.g. an engine table) to its file.
#[cfg(feature = "diagnostics")]
pub fn save_on_crash(ranges: Vec<(usize, usize, std::path::PathBuf)>) {
let _ = SAVE.set(ranges);
}
/// The file crash reports are appended to, besides being printed.
static LOG: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new();
/// 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) {
if LOG.set(file).is_ok() {
let print = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
print(info);
append_to_log(&format!(
"VIctory: panic on thread {:?}: {info}\n{}",
std::thread::current().name().unwrap_or("?"),
title_output()
));
}));
}
}
/// Appends a failure that is not an exception (the host GPU's) to the crash
/// log, with the title's last debug output, and prints it.
pub fn log_crash(text: &str) {
let text = format!("{text}
{}", title_output());
eprint!("{text}");
append_to_log(&text);
}
fn append_to_log(text: &str) {
use std::io::Write;
let Some(file) = LOG.get() else { return };
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let opened = std::fs::OpenOptions::new().create(true).append(true).open(file);
if let Ok(mut f) = opened {
let _ = write!(f, "unix time {now}, process {}\n{text}\n", std::process::id());
}
}
/// The title's last lines of debug output, kept for crash reports.
static SAID: std::sync::Mutex<std::collections::VecDeque<String>> =
std::sync::Mutex::new(std::collections::VecDeque::new());
const SAID_LINES: usize = 8;
/// Keeps a line of the title's debug output for the next crash report.
pub fn note_title_output(line: &str) {
if line.is_empty() {
return;
}
let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
if said.len() == SAID_LINES {
said.pop_front();
}
said.push_back(line.to_owned());
}
/// The kept lines, one per report line; nothing if another thread holds
/// them (it may be the one that faulted).
fn title_output() -> String {
let Ok(said) = SAID.try_lock() else {
return String::new();
};
said.iter().map(|l| format!(" title said: {l}\n")).collect()
}
/// Installs the handlers; call once before running title code.
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) };
EXCEPTION_CONTINUE_SEARCH
}
// SAFETY: registers handlers that only read the exception they are
// given; the title's own filter, once it sets one, takes the place of
// ours and calls `report_unhandled` first.
unsafe {
AddVectoredExceptionHandler(0, Some(handler));
SetUnhandledExceptionFilter(Some(filter));
}
}
/// What the vectored handler reports as it happens.
const FATAL: [i32; 6] = [
EXCEPTION_ACCESS_VIOLATION,
EXCEPTION_ILLEGAL_INSTRUCTION,
EXCEPTION_PRIV_INSTRUCTION,
EXCEPTION_INT_DIVIDE_BY_ZERO,
EXCEPTION_STACK_OVERFLOW,
EXCEPTION_BREAKPOINT,
];
unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 {
// SAFETY: the system passes valid exception pointers.
if FATAL.contains(&unsafe { (*(*info).ExceptionRecord).ExceptionCode }) {
// SAFETY: as above.
unsafe { report("first-chance exception", info, false) };
}
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.
///
/// # 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) };
}
/// MSVC's code for a C++ `throw`, and its magic first parameter.
const CPP_EXCEPTION: i32 = 0xE06D_7363_u32 as i32;
const CPP_MAGIC: usize = 0x1993_0520;
/// What a C++ throw threw: the decorated name of its type, then its value
/// where that names the cause (an integer, e.g. an HRESULT; a standard
/// exception's message).
///
/// # Safety
/// `p` are the parameters of a live MSVC throw (`p[0]` the magic).
unsafe fn thrown(p: &[usize]) -> String {
// SAFETY: the throw's ThrowInfo, its RVAs relative to `p[3]`: catchable
// type array at +12 (count, then type RVAs), each type's descriptor at
// +4, whose decorated name starts at +16; the object is at `p[1]`.
unsafe {
let rva = |at: usize| (at as *const u32).read_unaligned() as usize;
let types = p[3] + rva(p[2] + 12);
let name = |i: usize| {
let descriptor = p[3] + rva(p[3] + rva(types + 4 + 4 * i) + 4);
std::ffi::CStr::from_ptr((descriptor + 16) as *const std::ffi::c_char)
.to_string_lossy()
};
let first = name(0);
let value = match &*first {
// int, unsigned, long (HRESULT), unsigned long
".H" | ".I" | ".J" | ".K" if p[1] != 0 => {
format!(" = {:#010x}", (p[1] as *const u32).read_unaligned())
}
// std::exception keeps its message after the table pointer.
_ if (0..rva(types)).any(|i| name(i) == ".?AVexception@std@@") => {
let message = (p[1] as *const *const std::ffi::c_char).add(1).read();
if message.is_null() {
String::new()
} else {
format!(": {}", std::ffi::CStr::from_ptr(message).to_string_lossy())
}
}
_ => String::new(),
};
format!("{first}{value}")
}
}
/// # Safety
/// See [`report_unhandled`].
unsafe fn report(what: &str, info: *const EXCEPTION_POINTERS, to_file: bool) {
// SAFETY: the system passes valid exception pointers.
let (record, context) = unsafe { (&*(*info).ExceptionRecord, &*(*info).ContextRecord) };
let code = record.ExceptionCode;
if ![
EXCEPTION_ACCESS_VIOLATION,
EXCEPTION_ILLEGAL_INSTRUCTION,
EXCEPTION_PRIV_INSTRUCTION,
EXCEPTION_INT_DIVIDE_BY_ZERO,
EXCEPTION_STACK_OVERFLOW,
]
.contains(&code)
{
return EXCEPTION_CONTINUE_SEARCH;
}
let at = record.ExceptionAddress as usize;
let access = if code == EXCEPTION_ACCESS_VIOLATION {
let kind = match record.ExceptionInformation[0] {
let p = record.ExceptionInformation;
let detail = if code == EXCEPTION_ACCESS_VIOLATION {
let kind = match p[0] {
0 => "read",
1 => "write",
_ => "execute",
};
format!(" ({kind} {:#x})", record.ExceptionInformation[1])
format!(" ({kind} {:#x})", p[1])
} else if code == CPP_EXCEPTION && record.NumberParameters >= 4 && p[0] == CPP_MAGIC {
// SAFETY: a live MSVC throw.
format!(" (C++ {} thrown)", unsafe { thrown(&p) })
} else {
String::new()
};
eprintln!(
"VIctory: exception {:#010x} at {}{access}",
// Printed line by line (a fault while unwinding must not lose the
// lines before it), and kept for the file.
let mut text = String::new();
let mut line = |l: String| {
eprintln!("{l}");
text.push_str(&l);
text.push('\n');
};
line(format!(
"VIctory: {what} {:#010x} at {}{detail}",
code as u32,
locate(at)
);
eprintln!(
" rax {:#x} rbx {:#x} rcx {:#x} rdx {:#x} rsi {:#x} rdi {:#x} rsp {:#x}",
context.Rax, context.Rbx, context.Rcx, context.Rdx, context.Rsi, context.Rdi, context.Rsp
);
// shortcut: a stack scan, not an unwind; it lists stale return
// addresses too. Use RtlVirtualUnwind if this misleads.
let stack = context.Rsp as *const usize;
for i in 0..STACK_SCAN {
// SAFETY: slots just above the faulting RSP are committed stack.
let value = unsafe { stack.add(i).read_unaligned() };
if let Some(name) = module_of(value) {
eprintln!(" [rsp+{:#x}] {name}", i * 8);
));
line(format!(
" rax {:#x} rbx {:#x} rcx {:#x} rdx {:#x} rsi {:#x} rdi {:#x} rsp {:#x} rbp {:#x}",
context.Rax,
context.Rbx,
context.Rcx,
context.Rdx,
context.Rsi,
context.Rdi,
context.Rsp,
context.Rbp
));
line(format!(
" r8 {:#x} r9 {:#x} r10 {:#x} r11 {:#x} r12 {:#x} r13 {:#x} r14 {:#x} r15 {:#x}",
context.R8,
context.R9,
context.R10,
context.R11,
context.R12,
context.R13,
context.R14,
context.R15
));
for (i, pc) in unwind(*context).into_iter().enumerate() {
line(format!(" #{i:<2} {}", locate(pc as usize)));
}
if to_file {
let said = title_output();
eprint!("{said}");
text.push_str(&said);
append_to_log(&text);
}
#[cfg(feature = "diagnostics")]
for (address, len, file) in SAVE.get().into_iter().flatten() {
// SAFETY: the caller of `save_on_crash` named readable memory.
let bytes = unsafe { std::slice::from_raw_parts(*address as *const u8, *len) };
let saved = std::fs::write(file, bytes);
eprintln!(
" saved {address:#x}+{len:#x} to {} ({saved:?})",
file.display()
);
}
}
/// Return addresses of the faulting thread's frames, from the faulting
/// instruction up, by the unwind data of each image (the Windows loader
/// registered it for title images too). Code without unwind data (our
/// thunks, leaf functions) is taken to have its return address at `rsp`.
fn unwind(context: CONTEXT) -> Vec<u64> {
let (mut low, mut high) = (0, 0);
// SAFETY: writes the current thread's stack bounds.
unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) };
let mut frames = Vec::with_capacity(MAX_FRAMES);
unwind_into(context, low, high, &mut frames);
frames
}
/// [`unwind`] for any thread of the process, its stack being `low..high`;
/// pushes no more than `MAX_FRAMES`, so it does not allocate when `frames`
/// has that capacity (another thread may be suspended holding the heap).
pub(crate) fn unwind_into(mut context: CONTEXT, low: usize, high: usize, frames: &mut Vec<u64>) {
frames.push(context.Rip);
while frames.len() < MAX_FRAMES {
// Stop where reading the stack would fault inside this handler.
let rsp = context.Rsp as usize;
if rsp < low || rsp + 8 > high {
break;
}
let mut image = 0;
// SAFETY: looks up the function table entry covering `Rip`, if any.
let entry = unsafe { RtlLookupFunctionEntry(context.Rip, &mut image, null_mut()) };
if entry.is_null() {
// SAFETY: `rsp` is inside this thread's stack.
context.Rip = unsafe { (rsp as *const u64).read() };
context.Rsp += 8;
} else {
let (mut data, mut frame) = (null_mut(), 0);
// SAFETY: `entry` belongs to `image`; the context is our copy.
unsafe {
RtlVirtualUnwind(
UNW_FLAG_NHANDLER,
image,
context.Rip,
entry,
&mut context,
&mut data,
&mut frame,
null_mut(),
)
};
}
if context.Rip == 0 {
break;
}
frames.push(context.Rip);
}
EXCEPTION_CONTINUE_SEARCH
}
/// `module+rva`, or the bare address.
@@ -99,3 +352,32 @@ fn module_of(address: usize) -> Option<String> {
let name = path.rsplit('\\').next().unwrap_or(&path);
Some(format!("{name}+{:#x}", address - module as usize))
}
#[cfg(test)]
mod tests {
use super::*;
use windows_sys::Win32::System::Diagnostics::Debug::{
RtlCaptureContext, RtlCaptureStackBackTrace,
};
#[test]
#[inline(never)]
fn unwinds_like_the_system_walk() {
// SAFETY: zeroed CONTEXT is valid; both calls write our buffers.
let (frames, walked) = unsafe {
let mut context: CONTEXT = std::mem::zeroed();
RtlCaptureContext(&mut context);
let mut walked = [null_mut(); 8];
let n = RtlCaptureStackBackTrace(0, 8, walked.as_mut_ptr(), null_mut());
(unwind(context), walked[..usize::from(n)].to_vec())
};
// Frame 0 differs (two call sites in this function); callers agree.
assert!(walked.len() >= 4, "{walked:?}");
let ours: Vec<_> = frames[1..walked.len()]
.iter()
.map(|&f| f as usize)
.collect();
let system: Vec<_> = walked[1..].iter().map(|&f| f as usize).collect();
assert_eq!(ours, system);
}
}
+11 -1
View File
@@ -25,6 +25,8 @@
mod crash;
pub mod prepare;
pub mod resolve;
#[cfg(all(windows, feature = "diagnostics"))]
mod stacks;
#[cfg(windows)]
mod threads;
#[cfg(windows)]
@@ -35,9 +37,15 @@ mod tls;
mod windows;
#[cfg(windows)]
pub use crash::{locate, report_crashes};
pub use crash::{
locate, log_crash, log_crashes_to, note_title_output, report_crashes, report_unhandled,
};
#[cfg(all(windows, feature = "diagnostics"))]
pub use crash::save_on_crash;
pub use prepare::{PrepareError, PreparedImage, prepare};
pub use resolve::{ImportResolver, Provenance, Resolution};
#[cfg(all(windows, feature = "diagnostics"))]
pub use stacks::{dump_stacks, dump_stacks_on_schedule};
#[cfg(windows)]
pub use threads::disable_thread_calls;
#[cfg(windows)]
@@ -49,3 +57,5 @@ pub use windows::{
/// `DLL_PROCESS_ATTACH`, for TLS callbacks.
pub const DLL_PROCESS_ATTACH: u32 = 1;
/// `DLL_PROCESS_DETACH`.
pub const DLL_PROCESS_DETACH: u32 = 0;
+224
View File
@@ -0,0 +1,224 @@
//! Where every thread is: `VICTORY_STACKS=<seconds>[,<seconds>...]` prints
//! each thread's unwound stack as `module+rva` that many seconds after
//! [`dump_stacks_on_schedule`], to find what a title waits on.
use std::ffi::c_void;
use windows_sys::Wdk::System::Threading::{
NtQueryInformationThread, ThreadBasicInformation, ThreadQuerySetWin32StartAddress,
};
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE, LocalFree};
use windows_sys::Win32::System::Diagnostics::Debug::{
CONTEXT, CONTEXT_FULL_AMD64, GetThreadContext,
};
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
};
use windows_sys::Win32::System::Threading::{
GetCurrentProcessId, GetCurrentThreadId, GetThreadDescription, OpenThread, ResumeThread,
SuspendThread, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION, THREAD_SUSPEND_RESUME,
};
use crate::crash::{MAX_FRAMES, locate, unwind_into};
/// Reads `VICTORY_STACKS` and, if set, starts a thread that prints every
/// thread's stack at each listed time (seconds from now).
pub fn dump_stacks_on_schedule() {
let Ok(list) = std::env::var("VICTORY_STACKS") else {
return;
};
let mut times: Vec<f64> = list
.split(',')
.filter_map(|t| t.trim().parse().ok())
.collect();
times.sort_by(f64::total_cmp);
let start = std::time::Instant::now();
std::thread::spawn(move || {
for t in times {
let at = std::time::Duration::from_secs_f64(t.max(0.0));
std::thread::sleep(at.saturating_sub(start.elapsed()));
dump_stacks();
}
});
}
/// `THREAD_BASIC_INFORMATION` (ntddk).
#[repr(C)]
struct BasicInfo {
exit_status: i32,
teb: *const usize,
client_id: [usize; 2],
affinity: usize,
priority: i32,
base_priority: i32,
}
/// `GetThreadContext` wants a 16-byte aligned context.
#[repr(C, align(16))]
struct Aligned(CONTEXT);
/// Prints every other thread's stack to stderr. Each thread is suspended
/// only while its context is read and unwound into a buffer allocated
/// beforehand (it may hold the heap lock).
pub fn dump_stacks() {
// SAFETY: plain queries and a snapshot of this process's threads.
let (me, process, snapshot) = unsafe {
(
GetCurrentThreadId(),
GetCurrentProcessId(),
CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0),
)
};
if snapshot == INVALID_HANDLE_VALUE {
return;
}
let mut ids = Vec::new();
// SAFETY: zeroed is a valid THREADENTRY32; its size is set before use.
let mut entry: THREADENTRY32 = unsafe { std::mem::zeroed() };
entry.dwSize = size_of::<THREADENTRY32>() as u32;
// SAFETY: `snapshot` is open; `entry` is sized.
let mut more = unsafe { Thread32First(snapshot, &mut entry) } != 0;
while more {
if entry.th32OwnerProcessID == process && entry.th32ThreadID != me {
ids.push(entry.th32ThreadID);
}
// SAFETY: as above.
more = unsafe { Thread32Next(snapshot, &mut entry) } != 0;
}
// SAFETY: we opened it.
unsafe { CloseHandle(snapshot) };
eprintln!("VIctory: stacks of {} threads", ids.len());
for id in ids {
// SAFETY: opens a thread of our own process.
let thread = unsafe {
OpenThread(
THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION,
0,
id,
)
};
if thread.is_null() {
continue;
}
let (frames, (priority, base)) = frames_of(thread);
eprintln!(
" thread {id} \"{}\" start {} priority {priority} (base {base})",
name_of(thread),
locate(start_of(thread))
);
for (i, pc) in frames.into_iter().enumerate() {
eprintln!(" #{i:<2} {}", locate(pc as usize));
}
// SAFETY: we opened it.
unsafe { CloseHandle(thread) };
}
}
/// The thread's frames and its current and base scheduling priority (0-31).
fn frames_of(thread: HANDLE) -> (Vec<u64>, (i32, i32)) {
let mut frames = Vec::with_capacity(MAX_FRAMES);
let mut info: BasicInfo = BasicInfo {
exit_status: 0,
teb: std::ptr::null(),
client_id: [0; 2],
affinity: 0,
priority: 0,
base_priority: 0,
};
// SAFETY: writes `info`, whose layout and size are the system's.
let status = unsafe {
NtQueryInformationThread(
thread,
ThreadBasicInformation,
(&raw mut info).cast(),
size_of::<BasicInfo>() as u32,
std::ptr::null_mut(),
)
};
if status != 0 || info.teb.is_null() {
return (frames, (0, 0));
}
// SAFETY: the TEB of a live thread of this process: its NT_TIB holds
// the stack base at +8 and the stack limit at +0x10.
let (high, low) = unsafe { (info.teb.add(1).read(), info.teb.add(2).read()) };
// SAFETY: zeroed is a valid CONTEXT.
let mut context = Aligned(unsafe { std::mem::zeroed() });
context.0.ContextFlags = CONTEXT_FULL_AMD64;
// SAFETY: suspends, reads and resumes a thread that is not this one;
// nothing between suspend and resume allocates or takes a lock the
// thread could hold besides the unwinder's own.
unsafe {
if SuspendThread(thread) == u32::MAX {
return (frames, (info.priority, info.base_priority));
}
if GetThreadContext(thread, &mut context.0) != 0 {
unwind_into(context.0, low, high, &mut frames);
}
ResumeThread(thread);
}
(frames, (info.priority, info.base_priority))
}
fn start_of(thread: HANDLE) -> usize {
let mut start = 0usize;
// SAFETY: writes one pointer-sized start address.
unsafe {
NtQueryInformationThread(
thread,
ThreadQuerySetWin32StartAddress,
(&raw mut start).cast(),
size_of::<usize>() as u32,
std::ptr::null_mut(),
)
};
start
}
fn name_of(thread: HANDLE) -> String {
let mut name = std::ptr::null_mut();
// SAFETY: the system allocates the string; we free it with LocalFree.
unsafe {
if GetThreadDescription(thread, &mut name) < 0 || name.is_null() {
return String::new();
}
let len = (0..).take_while(|&i| *name.add(i) != 0).count();
let text = String::from_utf16_lossy(std::slice::from_raw_parts(name, len));
LocalFree(name.cast::<c_void>());
text
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn another_threads_stack_unwinds_to_its_start() {
let (tx, rx) = std::sync::mpsc::channel();
let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>();
let parked = std::thread::spawn(move || {
// SAFETY: plain query.
tx.send(unsafe { GetCurrentThreadId() }).unwrap();
stop_rx.recv().ok();
});
let id = rx.recv().unwrap();
// SAFETY: a thread of this process.
let thread = unsafe {
OpenThread(
THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION,
0,
id,
)
};
assert!(!thread.is_null());
let (frames, _) = frames_of(thread);
// Waiting in the kernel, several frames down from the thread start.
assert!(frames.len() >= 3, "{frames:?}");
assert!(start_of(thread) != 0);
// SAFETY: opened above.
unsafe { CloseHandle(thread) };
dump_stacks();
stop_tx.send(()).unwrap();
parked.join().unwrap();
}
}
+262 -17
View File
@@ -6,9 +6,11 @@
//! callbacks, then a DLL's `DllMain`.
use std::ffi::c_void;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use crate::LoadedImage;
use crate::{DLL_PROCESS_DETACH, LoadedImage};
const DLL_THREAD_ATTACH: u32 = 2;
const DLL_THREAD_DETACH: u32 = 3;
@@ -41,9 +43,143 @@ pub(crate) fn mapped(image: &LoadedImage) {
});
}
/// Its `DLL_PROCESS_ATTACH` is done. The list keeps attach order, which is
/// the Windows loader's initialisation order.
pub(crate) fn attached(base: usize) {
if let Some(m) = images().iter_mut().find(|m| m.image.base() == base) {
let mut images = images();
if let Some(i) = images.iter().position(|m| m.image.base() == base) {
let mut m = images.remove(i);
m.attached = true;
images.push(m);
}
static AT_EXIT: std::sync::Once = std::sync::Once::new();
// Registered before the title's own exit functions, so it runs after
// them, as `ExitProcess` follows `exit`'s functions on Windows.
// SAFETY: registers a function with the host CRT's exit table.
AT_EXIT.call_once(|| unsafe {
atexit(detach_all);
});
}
pub(crate) fn detached(base: usize) {
if let Some(m) = images().iter_mut().find(|m| m.image.base() == base) {
m.attached = false;
}
}
unsafe extern "C" {
fn atexit(f: extern "C" fn()) -> i32;
}
/// Set once the process is ending: no more thread notices.
static EXITING: AtomicBool = AtomicBool::new(false);
/// How long title images may take to detach before the process ends anyway
/// (a thread ended while holding a lock their detach code wants).
const DETACH_DEADLINE: Duration = Duration::from_secs(5);
/// Process exit (the CRT's `exit`, which titles call), in `ExitProcess`'s
/// order: the title's exit functions have run; every other thread ends
/// (title threads and ours); every attached image gets
/// `DLL_PROCESS_DETACH`, DLLs in reverse initialisation order, then the
/// exe's TLS callbacks; then the CRT ends the process.
extern "C" fn detach_all() {
let attached: Vec<_> = images()
.iter_mut()
.filter(|m| m.attached)
.map(|m| {
m.attached = false;
m.image.clone()
})
.collect();
let (dlls, exes): (Vec<_>, Vec<_>) =
attached.into_iter().rev().partition(|i| i.info().is_dll());
tracing::info!(
images = dlls.len() + exes.len(),
"process exit: ending other threads, detaching title images"
);
EXITING.store(true, Ordering::SeqCst);
end_other_threads();
// As on Windows, a lock a thread held when it ended stays taken; detach
// code that waits for one would hang the exit.
std::thread::spawn(|| {
std::thread::sleep(DETACH_DEADLINE);
tracing::warn!("process exit: title images did not detach in time; ending");
// SAFETY: ends this process, which is exiting anyway.
unsafe {
windows_sys::Win32::System::Threading::TerminateProcess(
windows_sys::Win32::System::Threading::GetCurrentProcess(),
1,
)
};
});
for image in dlls.iter().chain(&exes) {
// SAFETY: attached images are bound. A non-null third argument
// tells the entry points the process is ending.
unsafe {
image.notify(
DLL_PROCESS_DETACH,
true,
std::ptr::without_provenance_mut(1),
)
};
}
}
/// Ends every thread of the process but this one (and the ones started
/// while doing so), as `ExitProcess` does first; except the system's
/// thread-pool workers, which `TerminateThread` refuses (the process fails
/// fast) and which run no title code (no title image uses that pool).
fn end_other_threads() {
use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
};
use windows_sys::Win32::System::Threading::{
GetCurrentProcessId, GetCurrentThreadId, OpenThread, THREAD_TERMINATE, TerminateThread,
THREAD_QUERY_INFORMATION,
};
// SAFETY: plain queries of the calling process and thread.
let (process, me) = unsafe { (GetCurrentProcessId(), GetCurrentThreadId()) };
let mut ended = std::collections::HashSet::new();
loop {
// SAFETY: a snapshot of every thread, walked with a sized entry.
let others: Vec<u32> = unsafe {
let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if snapshot == INVALID_HANDLE_VALUE {
break;
}
let mut entry = THREADENTRY32 {
dwSize: size_of::<THREADENTRY32>() as u32,
..std::mem::zeroed()
};
let mut ids = Vec::new();
let mut more = Thread32First(snapshot, &mut entry) != 0;
while more {
if entry.th32OwnerProcessID == process && entry.th32ThreadID != me {
ids.push(entry.th32ThreadID);
}
more = Thread32Next(snapshot, &mut entry) != 0;
}
CloseHandle(snapshot);
ids
};
let new: Vec<u32> = others.into_iter().filter(|id| ended.insert(*id)).collect();
if new.is_empty() {
break;
}
for id in new {
// SAFETY: a thread of this process, which is exiting.
unsafe {
let thread = OpenThread(THREAD_TERMINATE | THREAD_QUERY_INFORMATION, 0, id);
if !thread.is_null() {
if !starts_in(thread, c"ntdll.dll") {
TerminateThread(thread, 0);
}
CloseHandle(thread);
}
}
}
}
}
@@ -71,65 +207,174 @@ pub fn disable_thread_calls(base: usize) -> Option<bool> {
static ON_THREAD: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = on_thread;
unsafe extern "system" fn on_thread(_: *mut c_void, reason: u32, _: *mut c_void) {
if reason != DLL_THREAD_ATTACH && reason != DLL_THREAD_DETACH || started_by_rust() {
if reason != DLL_THREAD_ATTACH && reason != DLL_THREAD_DETACH {
return;
}
if EXITING.load(Ordering::SeqCst) {
return; // our exit watchdog, or threads ending with the process
}
// A snapshot: title code may map and attach another DLL from here.
let notify: Vec<_> = images()
.iter()
.filter(|m| m.attached)
.map(|m| (m.image.clone(), !m.quiet))
.collect();
if notify.is_empty() {
return;
}
// Rust's std sets its threads up after this callback and aborts the
// process if their per-thread state was touched first (the current
// thread's id, which our logging asks for when title code calls us).
// That state is put back as the thread started.
let saved = (reason == DLL_THREAD_ATTACH && started_by_rust()).then(OwnTls::save);
// Starts in load order, ends in reverse, as the Windows loader does.
let notify_one = |(image, dll_main): &(Arc<LoadedImage>, bool)| {
// SAFETY: attached images have their imports bound.
unsafe { image.notify(reason, *dll_main) };
unsafe { image.notify(reason, *dll_main, std::ptr::null_mut()) };
};
if reason == DLL_THREAD_ATTACH {
notify.iter().for_each(notify_one);
} else {
notify.iter().rev().for_each(notify_one);
}
if let Some(saved) = saved {
saved.restore();
}
}
/// Our own image's static TLS block on this thread (Rust's std keeps its
/// per-thread state there), as copied before title code ran.
struct OwnTls {
block: *mut u8,
saved: Vec<u8>,
}
/// The TLS directory the linker emits for our image (the CRT's symbol).
#[repr(C)]
struct TlsDirectory {
start: usize,
end: usize,
index: *const u32,
callbacks: usize,
zero_fill: u32,
characteristics: u32,
}
unsafe extern "C" {
static _tls_used: TlsDirectory;
}
impl OwnTls {
fn save() -> OwnTls {
let array: *const *mut u8;
// SAFETY: reads TEB.ThreadLocalStoragePointer; the directory is our
// image's, and Windows set up its block on this thread before
// calling TLS callbacks.
let (block, len) = unsafe {
std::arch::asm!("mov {}, gs:[0x58]", out(reg) array, options(nostack, readonly));
let dir = &raw const _tls_used;
let block = *array.add((*dir).index.read() as usize);
(block, (*dir).end - (*dir).start + (*dir).zero_fill as usize)
};
// SAFETY: the block is `len` bytes, live for the thread's life.
let saved = unsafe { std::slice::from_raw_parts(block, len) }.to_vec();
OwnTls { block, saved }
}
fn restore(self) {
// SAFETY: the same block on the same thread, no reference to it held.
unsafe { std::ptr::copy_nonoverlapping(self.saved.as_ptr(), self.block, self.saved.len()) };
}
}
/// Whether Rust's std started this thread (its start routine is in our
/// exe): the title's main thread and our runtime's workers. They get no
/// notices: std aborts the process if anything on such a thread asks for
/// the current thread (as stdout and stderr locks do) before its start
/// routine has run, and title code may call our runtime, which logs.
// shortcut: title code on our workers (xasync callbacks) runs without
// thread notices; send them from the worker's start if a title needs them.
/// exe): the title's main thread and our runtime's workers, which run
/// title callbacks.
fn started_by_rust() -> bool {
// SAFETY: the calling thread's pseudo handle.
starts_in(unsafe { windows_sys::Win32::System::Threading::GetCurrentThread() }, c"")
}
/// Whether `thread`'s start routine lies in the module named `module`
/// (empty: our exe).
fn starts_in(thread: windows_sys::Win32::Foundation::HANDLE, module: &std::ffi::CStr) -> bool {
use windows_sys::Wdk::System::Threading::{
NtQueryInformationThread, ThreadQuerySetWin32StartAddress,
};
use windows_sys::Win32::System::LibraryLoader::{
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
GetModuleHandleExW, GetModuleHandleW,
GetModuleHandleA, GetModuleHandleExW,
};
use windows_sys::Win32::System::Threading::GetCurrentThread;
let mut start = 0usize;
// SAFETY: writes one pointer-sized start address.
let status = unsafe {
NtQueryInformationThread(
GetCurrentThread(),
thread,
ThreadQuerySetWin32StartAddress,
(&raw mut start).cast(),
size_of::<usize>() as u32,
std::ptr::null_mut(),
)
};
let mut module = std::ptr::null_mut();
let mut found = std::ptr::null_mut();
let name = if module.is_empty() {
std::ptr::null()
} else {
module.as_ptr().cast()
};
// SAFETY: looks up the module containing an address, taking no reference.
status == 0
&& unsafe {
GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
start as *const u16,
&mut module,
&mut found,
)
} != 0
// SAFETY: our own exe's handle.
&& module == unsafe { GetModuleHandleW(std::ptr::null()) }
// SAFETY: a module handle by name (or our exe's); no reference taken.
&& found == unsafe { GetModuleHandleA(name) }
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
/// In a child process of the next test: ends the other threads and
/// checks that a busy one stopped.
#[test]
fn exit_child() {
if std::env::var_os("VICTORY_EXIT_CHILD").is_none() {
return;
}
static TICKS: AtomicU64 = AtomicU64::new(0);
std::thread::spawn(|| {
loop {
TICKS.fetch_add(1, Ordering::SeqCst);
std::thread::yield_now();
}
});
while TICKS.load(Ordering::SeqCst) == 0 {
std::thread::yield_now();
}
super::end_other_threads();
let at = TICKS.load(Ordering::SeqCst);
std::thread::sleep(Duration::from_millis(50));
let ended = TICKS.load(Ordering::SeqCst) == at;
// The test harness's threads are gone too: leave at once.
println!("{}", if ended { "ENDED" } else { "STILL RUNNING" });
std::process::exit(0);
}
#[test]
fn exit_ends_the_other_threads_first() {
let out = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "threads::tests::exit_child", "--nocapture"])
.env("VICTORY_EXIT_CHILD", "1")
.output()
.unwrap();
let text = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success() && text.contains("ENDED"), "{text}");
}
}
+3 -2
View File
@@ -82,8 +82,9 @@ fn patch(code: &mut [u8], at: usize, thunks: usize) -> usize {
let c = &code[i..i + LOAD_LEN];
let rex = c[1];
let reg = usize::from((c[3] >> 3) & 7) | if rex & 4 != 0 { 8 } else { 0 };
// shortcut: a byte match, not a decode; a false hit inside other
// bytes is unlikely at 9 specific bytes. Decode .text if one shows.
// shortcut: a byte match, not a decode. In Grand Theft Auto VI all
// 53,246 hits are instruction starts and none is missed (checked
// against a full disassembly); decode .text if a title shows one.
if c[0] == 0x65
&& (rex == 0x48 || rex == 0x4C)
&& c[2] == 0x8B
+34 -7
View File
@@ -14,7 +14,10 @@ use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryExW};
use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect};
use crate::thunks::{ImportSite, ThunkBlock, UnimplementedPolicy};
use crate::{DLL_PROCESS_ATTACH, ImportResolver, PreparedImage, Provenance, Resolution, prepare};
use crate::{
DLL_PROCESS_ATTACH, DLL_PROCESS_DETACH, ImportResolver, PreparedImage, Provenance, Resolution,
prepare,
};
/// A title image mapped into this process. A clone names the same mapping
/// (no reference of its own): unload one copy only.
@@ -308,13 +311,20 @@ impl LoadedImage {
/// # Safety
/// Runs title code. Imports must be bound first.
pub unsafe fn run_tls_callbacks(&self, reason: u32) {
// SAFETY: forwarded from the caller.
unsafe { self.tls_callbacks(reason, std::ptr::null_mut()) }
}
/// # Safety
/// See [`Self::run_tls_callbacks`].
unsafe fn tls_callbacks(&self, reason: u32, reserved: *mut c_void) {
let Some(tls) = &self.info.tls else { return };
for &rva in &tls.callback_rvas {
type TlsCallback = unsafe extern "system" fn(*mut c_void, u32, *mut c_void);
// SAFETY: the RVA came from the image's own TLS directory.
let callback: TlsCallback = unsafe { std::mem::transmute(self.base() + rva as usize) };
// SAFETY: the caller guarantees imports are bound.
unsafe { callback(self.module, reason, std::ptr::null_mut()) };
unsafe { callback(self.module, reason, reserved) };
}
}
@@ -327,22 +337,39 @@ impl LoadedImage {
/// depends on attached.
pub unsafe fn attach(&self) -> Result<()> {
// SAFETY: forwarded from the caller.
if unsafe { self.notify(DLL_PROCESS_ATTACH, true) } == Some(0) {
if unsafe { self.notify(DLL_PROCESS_ATTACH, true, std::ptr::null_mut()) } == Some(0) {
bail!("DllMain returned FALSE");
}
crate::threads::attached(self.base());
Ok(())
}
/// `DLL_PROCESS_DETACH` as `FreeLibrary` sends it (TLS callbacks, then
/// `DllMain`); the image hears of no more threads.
///
/// # Safety
/// Runs title code. The image must have been attached (or its attach
/// failed), and no other thread may be using it.
pub unsafe fn detach(&self) {
crate::threads::detached(self.base());
// SAFETY: forwarded from the caller.
unsafe { self.notify(DLL_PROCESS_DETACH, true, std::ptr::null_mut()) };
}
/// Runs the image's TLS callbacks with `reason`, then, if `dll_main` and
/// the image is a DLL with an entry point, its `DllMain`, whose result
/// is returned.
/// is returned. `reserved` is the entry points' third argument.
///
/// # Safety
/// Runs title code. Imports must be bound first.
pub(crate) unsafe fn notify(&self, reason: u32, dll_main: bool) -> Option<i32> {
pub(crate) unsafe fn notify(
&self,
reason: u32,
dll_main: bool,
reserved: *mut c_void,
) -> Option<i32> {
// SAFETY: forwarded from the caller.
unsafe { self.run_tls_callbacks(reason) };
unsafe { self.tls_callbacks(reason, reserved) };
if !dll_main || !self.info.is_dll() || self.info.entry_rva == 0 {
return None;
}
@@ -351,7 +378,7 @@ impl LoadedImage {
let main: DllMain =
unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) };
// SAFETY: forwarded from the caller.
Some(unsafe { main(self.module, reason, std::ptr::null_mut()) })
Some(unsafe { main(self.module, reason, reserved) })
}
/// Starts the title: on a new thread with the stack size from the image
+20 -2
View File
@@ -39,7 +39,10 @@ fn build_probe() -> PathBuf {
extern "system" fn fake_xgameruntime_initialize() -> i32 {
0x1234
}
/// Asks for the current thread, as our logging does: on a thread std is
/// still starting, that must not abort the process.
extern "system" fn fake_get_tick_count() -> u32 {
let _ = std::thread::current().id();
777
}
extern "system" fn fake_delayed() -> u32 {
@@ -192,8 +195,18 @@ fn loads_binds_and_calls_probe() {
image.attach().unwrap();
let f: extern "system" fn() -> u64 = std::mem::transmute(call("probe_thread_starts"));
let before = f();
// Starting in title code, as a title's threads do (ours start in
// our exe and are left out); the extra argument is ignored.
// A thread std starts, as our runtime's workers are: notified
// before std sets it up, which must still find its state pristine.
let worker = std::thread::Builder::new()
.name("probe-worker".into())
.spawn(|| std::thread::current().name().map(str::to_owned))
.unwrap();
assert_eq!(worker.join().unwrap().as_deref(), Some("probe-worker"));
let mid = f();
assert!(mid >> 32 > before >> 32 && mid as u32 > before as u32);
let before = mid;
// Starting in title code, as a title's threads do; the extra
// argument is ignored.
let start: unsafe extern "system" fn(*mut std::ffi::c_void) -> u32 =
std::mem::transmute(call("probe_pid"));
let thread = CreateThread(
@@ -223,6 +236,11 @@ fn loads_binds_and_calls_probe() {
);
assert_eq!(victory_loader::disable_thread_calls(1), None);
// `FreeLibrary`'s notice, as a failed late load sends it.
let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_detaches"));
assert_eq!(f(), 0);
image.detach();
assert_eq!(f(), 1);
image.unload();
}
}