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:
1 parent
bc3070991a
commit
2849477415
107 files changed
+42526
-868
No files matched your search
@@ -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}");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user