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]>
225 lines
7.6 KiB
Rust
225 lines
7.6 KiB
Rust
//! 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();
|
|
}
|
|
}
|