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
+203
-33
@@ -2,14 +2,22 @@ use std::path::Path;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
use crate::Unimplemented;
|
||||
use crate::{Console, Unimplemented};
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool) -> Result<()> {
|
||||
pub fn run(
|
||||
exe: &Path,
|
||||
unimplemented: Unimplemented,
|
||||
strict: bool,
|
||||
execute: bool,
|
||||
console: Console,
|
||||
) -> Result<()> {
|
||||
use std::sync::Arc;
|
||||
use victory_hle::{HleResolver, HostPolicy};
|
||||
use victory_loader::{BindReport, UnimplementedPolicy, WithTitleDlls};
|
||||
|
||||
// A title that relaunched itself: the old process must be gone first.
|
||||
victory_hle::modules::lifecycle::wait_for_previous();
|
||||
let cfg = victory_core::Config::load()?;
|
||||
let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?;
|
||||
let prepared = victory_loader::prepare(&original)?;
|
||||
@@ -20,6 +28,7 @@ pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool
|
||||
}
|
||||
|
||||
let images = cfg.cache_subdir("images")?;
|
||||
victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?);
|
||||
let image = victory_loader::load(&prepared, &images)?;
|
||||
victory_hle::runtime::set_main_image(image.base());
|
||||
victory_hle::runtime::set_image_path(image.base(), exe);
|
||||
@@ -46,7 +55,16 @@ pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool
|
||||
storage.display(),
|
||||
title.storage_bytes >> 20
|
||||
);
|
||||
// The console's fixed drives: the package as `G:`, temporary files `T:`.
|
||||
victory_hle::modules::files::mount_at('G', title_dir);
|
||||
let temp = cfg.data_subdir(&format!("{:08X}/temp", title.id))?;
|
||||
victory_hle::modules::files::mount_at('T', &temp);
|
||||
victory_hle::runtime::set_title(victory_hle::runtime::Title { storage, ..title });
|
||||
victory_hle::console::set(match console {
|
||||
Console::SeriesX => victory_hle::console::Console::SeriesX,
|
||||
Console::SeriesS => victory_hle::console::Console::SeriesS,
|
||||
});
|
||||
println!("console {}", victory_hle::console::current().name());
|
||||
let dlls = victory_loader::load_title_dlls(image.info(), title_dir, &images, &wanted)?;
|
||||
for (name, dll) in &dlls {
|
||||
println!("title dll {name} at {:#x}", dll.base());
|
||||
@@ -83,12 +101,17 @@ pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool
|
||||
return Ok(());
|
||||
}
|
||||
victory_loader::report_crashes();
|
||||
victory_loader::log_crashes_to(temp.with_file_name("crashes.log"));
|
||||
victory_hle::runtime::use_console_timers();
|
||||
#[cfg(feature = "diagnostics")]
|
||||
diagnostics(&image, &cfg);
|
||||
let late = LateDlls {
|
||||
host: resolver.host.clone(),
|
||||
title_dir: title_dir.to_owned(),
|
||||
cache_dir: images,
|
||||
policy,
|
||||
mapped: std::sync::Mutex::new(dlls.clone()),
|
||||
lock: LoaderLock::default(),
|
||||
};
|
||||
victory_hle::runtime::set_title_dll_loader(Box::new(move |file| {
|
||||
late.load(file, show).map_err(|e| format!("{e:#}"))
|
||||
@@ -102,6 +125,60 @@ pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The debugging aids (README): scheduled stack dumps, watched values and
|
||||
/// memory saved on a crash.
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
fn diagnostics(image: &victory_loader::LoadedImage, cfg: &victory_core::Config) {
|
||||
victory_loader::dump_stacks_on_schedule();
|
||||
victory_hle::modules::audio::capture::start();
|
||||
watch(image.base(), image.info().size_of_image as usize);
|
||||
// Debugging aid: `VICTORY_CRASH_SAVE=<rva>:<len>,...` (hex) writes those
|
||||
// title ranges to `crash-<rva>.bin` in the cache dir on a crash.
|
||||
let size = image.info().size_of_image as usize;
|
||||
let ranges = std::env::var("VICTORY_CRASH_SAVE").unwrap_or_default();
|
||||
let hex = |s: &str| usize::from_str_radix(s.trim().trim_start_matches("0x"), 16).ok();
|
||||
victory_loader::save_on_crash(
|
||||
ranges
|
||||
.split(',')
|
||||
.filter_map(|r| r.split_once(':'))
|
||||
.filter_map(|(rva, len)| Some((hex(rva)?, hex(len)?)))
|
||||
.filter(|&(rva, len)| rva.checked_add(len).is_some_and(|end| end <= size))
|
||||
.map(|(rva, len)| {
|
||||
let file = cfg.cache_dir.join(format!("crash-{rva:x}.bin"));
|
||||
(image.base() + rva, len, file)
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Debugging aid: `VICTORY_WATCH=<rva>,...` (hex) logs the u32 at each
|
||||
/// title+rva whenever it changes, polled every 5 ms (an engine's state, say).
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
fn watch(base: usize, size: usize) {
|
||||
let Ok(list) = std::env::var("VICTORY_WATCH") else {
|
||||
return;
|
||||
};
|
||||
let rvas: Vec<usize> = list
|
||||
.split(',')
|
||||
.filter_map(|r| usize::from_str_radix(r.trim().trim_start_matches("0x"), 16).ok())
|
||||
.filter(|&rva| rva + 4 <= size)
|
||||
.collect();
|
||||
std::thread::spawn(move || {
|
||||
let mut seen = vec![None; rvas.len()];
|
||||
loop {
|
||||
for (&rva, seen) in rvas.iter().zip(&mut seen) {
|
||||
// SAFETY: four bytes inside the mapped image, checked above.
|
||||
let value = unsafe { ((base + rva) as *const u32).read_volatile() };
|
||||
if *seen != Some(value) {
|
||||
eprintln!("VIctory: title+{rva:#x} = {value:#x}");
|
||||
*seen = Some(value);
|
||||
}
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// DLLs the host or our runtime provide are never taken from the title.
|
||||
#[cfg(windows)]
|
||||
fn title_dll(host: &victory_hle::HostPolicy, dll: &str) -> bool {
|
||||
@@ -118,51 +195,144 @@ struct LateDlls {
|
||||
policy: victory_loader::UnimplementedPolicy,
|
||||
/// Every title DLL mapped so far, to bind new ones against.
|
||||
mapped: std::sync::Mutex<Vec<(String, victory_loader::LoadedImage)>>,
|
||||
lock: LoaderLock,
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl LateDlls {
|
||||
/// Maps `file` and the title DLLs it needs, binds them and runs their
|
||||
/// `DllMain` on the calling thread, as the Windows loader would.
|
||||
/// Every `LoadLibrary` of the title comes here first. Returns a title
|
||||
/// image called `file`, mapping it and the title DLLs it needs first,
|
||||
/// binding them and running their `DllMain` on the calling thread, as
|
||||
/// the Windows loader would; `None` if `file` is no title image.
|
||||
fn load(
|
||||
&self,
|
||||
file: &str,
|
||||
show: impl Fn(&str, victory_loader::BindReport),
|
||||
) -> Result<Option<usize>> {
|
||||
use victory_hle::runtime::{image_named, set_image_path};
|
||||
// shortcut: not reentrant, so a DllMain that loads another new title
|
||||
// DLL deadlocks; use a reentrant lock if a title does that.
|
||||
let mut mapped = self.mapped.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let wanted = |dll: &str| title_dll(&self.host, dll) && image_named(dll).is_none();
|
||||
let new = victory_loader::load_title_dll(file, &self.title_dir, &self.cache_dir, &wanted)?;
|
||||
let hle = victory_hle::HleResolver::new(self.host.clone());
|
||||
let old = victory_loader::WithTitleDlls {
|
||||
inner: &hle,
|
||||
dlls: &mapped,
|
||||
};
|
||||
let resolver = victory_loader::WithTitleDlls {
|
||||
inner: &old,
|
||||
dlls: &new,
|
||||
};
|
||||
for (name, dll) in &new {
|
||||
println!(
|
||||
"title dll {name} at {:#x} (loaded by the title)",
|
||||
dll.base()
|
||||
);
|
||||
show(name, dll.bind_imports(&resolver, self.policy)?);
|
||||
set_image_path(dll.base(), &self.title_dir.join(name));
|
||||
use victory_hle::runtime::{forget_image, image_named, set_image_path};
|
||||
// Waits while another thread initialises a DLL; a `DllMain` that
|
||||
// loads another DLL re-enters.
|
||||
self.lock.hold(|| {
|
||||
if let Some(base) = image_named(file) {
|
||||
return Ok(Some(base));
|
||||
}
|
||||
let new = {
|
||||
let mut mapped = self.mapped.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let wanted = |dll: &str| title_dll(&self.host, dll) && image_named(dll).is_none();
|
||||
let new = victory_loader::load_title_dll(
|
||||
file,
|
||||
&self.title_dir,
|
||||
&self.cache_dir,
|
||||
&wanted,
|
||||
)?;
|
||||
let hle = victory_hle::HleResolver::new(self.host.clone());
|
||||
let old = victory_loader::WithTitleDlls {
|
||||
inner: &hle,
|
||||
dlls: &mapped,
|
||||
};
|
||||
let resolver = victory_loader::WithTitleDlls {
|
||||
inner: &old,
|
||||
dlls: &new,
|
||||
};
|
||||
for (name, dll) in &new {
|
||||
println!(
|
||||
"title dll {name} at {:#x} (loaded by the title)",
|
||||
dll.base()
|
||||
);
|
||||
show(name, dll.bind_imports(&resolver, self.policy)?);
|
||||
set_image_path(dll.base(), &self.title_dir.join(name));
|
||||
}
|
||||
// Visible before their `DllMain`s run, which may load more.
|
||||
mapped.extend(new.iter().cloned());
|
||||
new
|
||||
};
|
||||
let failed = new.iter().enumerate().find_map(|(i, (name, dll))| {
|
||||
// SAFETY: bound above, dependencies attached first.
|
||||
let attached = unsafe { dll.attach() };
|
||||
attached
|
||||
.err()
|
||||
.map(|e| (i, e.context(format!("attaching {name}"))))
|
||||
});
|
||||
let Some((i, error)) = failed else {
|
||||
return Ok(new.last().map(|(_, dll)| dll.base()));
|
||||
};
|
||||
// As `LoadLibrary` does when a `DllMain` fails: detach what this
|
||||
// load attached (the failed one too) and unmap all of it.
|
||||
let bases: Vec<_> = new.iter().map(|(_, d)| d.base()).collect();
|
||||
self.mapped
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.retain(|(_, d)| !bases.contains(&d.base()));
|
||||
for (_, done) in new[..=i].iter().rev() {
|
||||
// SAFETY: attached (or failing to) on this thread just now.
|
||||
unsafe { done.detach() };
|
||||
}
|
||||
for (_, dll) in new {
|
||||
forget_image(dll.base());
|
||||
// SAFETY: detached, and no title code holds it yet.
|
||||
unsafe { dll.unload() };
|
||||
}
|
||||
Err(error)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The Windows loader lock's shape: one thread at a time, re-entered by
|
||||
/// the thread that holds it.
|
||||
#[cfg(windows)]
|
||||
#[derive(Default)]
|
||||
struct LoaderLock {
|
||||
owner: std::sync::Mutex<(Option<std::thread::ThreadId>, usize)>,
|
||||
free: std::sync::Condvar,
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl LoaderLock {
|
||||
fn hold<T>(&self, f: impl FnOnce() -> T) -> T {
|
||||
let me = std::thread::current().id();
|
||||
let lock = || self.owner.lock().unwrap_or_else(|e| e.into_inner());
|
||||
{
|
||||
let mut owner = lock();
|
||||
while owner.0.is_some_and(|o| o != me) {
|
||||
owner = self.free.wait(owner).unwrap_or_else(|e| e.into_inner());
|
||||
}
|
||||
*owner = (Some(me), owner.1 + 1);
|
||||
}
|
||||
for (name, dll) in &new {
|
||||
// SAFETY: bound above, dependencies attached first.
|
||||
unsafe { dll.attach() }.with_context(|| format!("attaching {name}"))?;
|
||||
let result = f();
|
||||
let mut owner = lock();
|
||||
owner.1 -= 1;
|
||||
if owner.1 == 0 {
|
||||
owner.0 = None;
|
||||
self.free.notify_one();
|
||||
}
|
||||
let base = new.last().map(|(_, dll)| dll.base());
|
||||
mapped.extend(new);
|
||||
Ok(base)
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, windows))]
|
||||
mod tests {
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[test]
|
||||
fn loader_lock_is_reentrant_and_exclusive() {
|
||||
let lock = Arc::new(super::LoaderLock::default());
|
||||
assert_eq!(lock.hold(|| lock.hold(|| 7)), 7);
|
||||
let order = Arc::new(Mutex::new(Vec::new()));
|
||||
let other = lock.hold(|| {
|
||||
let (theirs, their_order) = (lock.clone(), order.clone());
|
||||
let other = std::thread::spawn(move || {
|
||||
theirs.hold(|| their_order.lock().unwrap().push(2));
|
||||
});
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
order.lock().unwrap().push(1);
|
||||
other
|
||||
});
|
||||
other.join().unwrap();
|
||||
assert_eq!(*order.lock().unwrap(), [1, 2]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool) -> Result<()> {
|
||||
pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool, _: Console) -> Result<()> {
|
||||
anyhow::bail!("running titles requires Windows")
|
||||
}
|
||||
Reference in new issue
Block a user