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

+11 -1
View File
@@ -12,7 +12,7 @@ victory-core.workspace = true
victory-pe.workspace = true
victory-loader.workspace = true
victory-hle.workspace = true
victory-shader.workspace = true
victory-shader = { workspace = true, features = ["host"] }
victory-game.workspace = true
anyhow.workspace = true
blake3.workspace = true
@@ -20,5 +20,15 @@ memchr.workspace = true
clap.workspace = true
walkdir.workspace = true
[features]
# Debug-level logs and the debugging switches (frame capture, stack dumps,
# the host debug layer, scripted keys). Off in a plain release build.
diagnostics = [
"victory-core/diagnostics",
"victory-hle/diagnostics",
"victory-loader/diagnostics",
"victory-shader/diagnostics",
]
[lints]
workspace = true
+44 -3
View File
@@ -69,7 +69,22 @@ enum Command {
},
/// Run every shader found (containers, SGD5 files) through the
/// translator and report what it cannot handle yet.
Translate { paths: Vec<PathBuf> },
Translate {
paths: Vec<PathBuf>,
/// Check emitted DXIL with dxil.dll's validator (`VICTORY_DXIL`,
/// else the newest Windows SDK's).
#[arg(long)]
validate: bool,
/// Also create a host D3D12 pipeline for each emitted shader.
#[arg(long)]
pipelines: bool,
/// Print one line per program and outcome.
#[arg(long)]
list: bool,
/// Worker threads (default: every logical core).
#[arg(long)]
jobs: Option<usize>,
},
/// Prepare, map and bind a title executable; with --execute, run it.
Run {
exe: PathBuf,
@@ -82,6 +97,13 @@ enum Command {
/// Actually start the title. Without it, stop after binding.
#[arg(long)]
execute: bool,
/// The console model the title sees (device type, memory).
#[arg(long, value_enum, default_value_t = Console::SeriesX)]
console: Console,
/// Arguments for the title, after `--` (it reads the whole command
/// line; a title that relaunches itself passes some).
#[arg(last = true)]
title_args: Vec<String>,
},
/// Show the resolved configuration and check it.
Config,
@@ -93,8 +115,19 @@ enum Unimplemented {
Zero,
}
#[derive(Clone, Copy, ValueEnum)]
enum Console {
SeriesX,
SeriesS,
}
fn main() -> Result<()> {
victory_core::logging::init("info");
// The audio recorder `run` starts for `VICTORY_AUDIO_CAPTURE`.
#[cfg(all(windows, feature = "diagnostics"))]
if victory_hle::modules::audio::capture::child() {
return Ok(());
}
let cli = Cli::parse();
match cli.command {
Command::Inspect {
@@ -113,13 +146,21 @@ fn main() -> Result<()> {
verbose,
disasm,
} => shader::run(paths, verbose || disasm, disasm),
Command::Translate { paths } => translate::run(paths),
Command::Translate {
paths,
validate,
pipelines,
list,
jobs,
} => translate::run(paths, validate, pipelines, list, jobs),
Command::Run {
exe,
unimplemented,
strict,
execute,
} => run::run(&exe, unimplemented, strict, execute),
console,
title_args: _,
} => run::run(&exe, unimplemented, strict, execute, console),
Command::Config => show_config(),
}
}
+203 -33
View File
@@ -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")
}
+11 -5
View File
@@ -35,18 +35,21 @@ impl Source<'_> {
}
}
/// The records of an SGD5 file, or else every container found by its magic.
/// The packed records of SGD5 data, and every container stored as is (the
/// executable keeps some records uncompressed), found by its magic.
pub(crate) fn sources(data: &[u8]) -> Vec<Source<'_>> {
let mut out: Vec<Source<'_>> = Vec::new();
if sgd5::is_sgd5(data) {
return sgd5::records(data).map(Source::Packed).collect();
out.extend(sgd5::records(data).map(Source::Packed));
}
memchr::memmem::find_iter(data, b"DXBC")
let raw = memchr::memmem::find_iter(data, b"DXBC")
.filter(|&offset| Container::parse(&data[offset..]).is_ok())
.map(|offset| Source::Raw {
offset,
data: &data[offset..],
})
.collect()
});
out.extend(raw);
out
}
#[derive(Default)]
@@ -119,6 +122,9 @@ pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> {
*t.unnamed.entry(key).or_default() += 1;
}
if disasm {
listing
.extend(n.layout.iter().map(|p| format!(" {p:?}")));
listing.extend(n.used.iter().map(|u| format!(" {u:?}")));
listing.extend(
insts.iter().map(|i| format_instruction(i, n.wave64)),
);
+477 -13
View File
@@ -7,8 +7,13 @@ use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use anyhow::Result;
use victory_shader::emit::host::{self, Host};
use victory_shader::emit::{self, validator::Validator};
use victory_shader::structure::{self, Atom, LaneExit};
use victory_shader::{Container, FourCC, ShaderError, ir, native_programs};
use victory_shader::{
Container, FourCC, HwStage, NativeProgram, RootType, ShaderError, ir, native_programs,
};
use victory_shader::{io, resource};
use crate::shader::{MAX_FILE, Source, sources};
@@ -26,12 +31,59 @@ struct Tally {
opaque: usize,
lane_branches: usize,
uniform_branches: usize,
tracked: usize,
loaded: usize,
built: usize,
constant: usize,
/// Descriptors and scalar accesses with a computed address term.
dynamic: usize,
scalar: usize,
used: usize,
/// Used-resource entries whose root parameter no descriptor traces
/// to, by resource and root type.
untraced_used: BTreeMap<String, usize>,
/// Root parameters descriptors trace to that no used entry names.
unlisted: usize,
/// Vertex and pixel programs, and those whose I/O was raised.
io_programs: usize,
io_raised: usize,
interpolated: usize,
vertex_values: usize,
/// Exports by target kind.
exports: BTreeMap<&'static str, usize>,
/// Exports still packed as f16 pairs after the export patch.
compressed: usize,
/// Vertex and pixel programs every earlier stage handled, and how far
/// emission got with them.
emit_programs: usize,
emitted: usize,
validated: usize,
pipelines: usize,
/// The same for compute programs.
cs_programs: usize,
cs_emitted: usize,
cs_validated: usize,
cs_pipelines: usize,
/// The same for mesh programs.
ms_programs: usize,
ms_emitted: usize,
ms_validated: usize,
ms_pipelines: usize,
/// Reason → programs stopped by it, and the first one.
failed: BTreeMap<String, (usize, String)>,
/// With `--list`: one line per program and outcome.
list: bool,
lines: Vec<String>,
}
impl Tally {
fn fail(&mut self, reason: String, example: impl FnOnce() -> String) {
if self.list {
let e = example();
self.lines.push(format!("{e} {reason}"));
self.failed.entry(reason).or_insert((0, e)).0 += 1;
return;
}
self.failed
.entry(reason)
.or_insert_with(|| (0, example()))
@@ -50,15 +102,85 @@ impl Tally {
self.opaque += other.opaque;
self.lane_branches += other.lane_branches;
self.uniform_branches += other.uniform_branches;
self.tracked += other.tracked;
self.loaded += other.loaded;
self.built += other.built;
self.constant += other.constant;
self.dynamic += other.dynamic;
self.scalar += other.scalar;
self.used += other.used;
for (k, n) in other.untraced_used {
*self.untraced_used.entry(k).or_default() += n;
}
self.unlisted += other.unlisted;
self.io_programs += other.io_programs;
self.io_raised += other.io_raised;
self.interpolated += other.interpolated;
self.vertex_values += other.vertex_values;
self.compressed += other.compressed;
self.emit_programs += other.emit_programs;
self.emitted += other.emitted;
self.validated += other.validated;
self.pipelines += other.pipelines;
self.cs_programs += other.cs_programs;
self.cs_emitted += other.cs_emitted;
self.cs_validated += other.cs_validated;
self.cs_pipelines += other.cs_pipelines;
self.ms_programs += other.ms_programs;
self.ms_emitted += other.ms_emitted;
self.ms_validated += other.ms_validated;
self.ms_pipelines += other.ms_pipelines;
for (k, n) in other.exports {
*self.exports.entry(k).or_default() += n;
}
self.lines.extend(other.lines);
for (reason, (n, example)) in other.failed {
self.failed.entry(reason).or_insert((0, example)).0 += n;
}
}
}
pub fn run(paths: Vec<PathBuf>) -> Result<()> {
/// Emitted shaders by label, shared between threads.
type Kept = std::sync::Arc<Mutex<Vec<(String, emit::HostShader)>>>;
/// The optional checks after emission, one set per thread.
struct Checks {
/// Shaders named in `VICTORY_PAIRS` (`vs+ps,...`, label substrings),
/// kept to build those pipelines after the walk.
keep: Option<Kept>,
validator: Option<Validator>,
host: Option<(Host, emit::HostShader)>,
}
pub fn run(
paths: Vec<PathBuf>,
validate: bool,
pipelines: bool,
list: bool,
jobs: Option<usize>,
) -> Result<()> {
let paths = crate::default_paths(paths)?;
let threads = std::thread::available_parallelism().map_or(4, |n| n.get());
let dll = validate.then(Validator::default_path).flatten();
if validate {
Validator::load(dll.as_deref()).map_err(anyhow::Error::msg)?;
println!(
"validator {}",
dll.as_ref()
.map_or("dxil.dll".into(), |p| p.display().to_string())
);
}
if pipelines {
Host::new(false).map_err(anyhow::Error::msg)?;
}
let pairs: Vec<(String, String)> = std::env::var("VICTORY_PAIRS")
.unwrap_or_default()
.split(',')
.filter_map(|p| p.split_once('+'))
.map(|(v, p)| (v.trim().to_owned(), p.trim().to_owned()))
.collect();
let kept = std::sync::Arc::new(Mutex::new(Vec::new()));
let threads =
jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get()));
let seen = Mutex::new(HashSet::new());
let total = Mutex::new(Tally::default());
for root in &paths {
@@ -77,9 +199,21 @@ pub fn run(paths: Vec<PathBuf>) -> Result<()> {
std::thread::scope(|s| {
for _ in 0..threads.min(jobs.len()) {
s.spawn(|| {
let mut t = Tally::default();
let mut t = Tally {
list,
..Tally::default()
};
let mut checks = Checks {
keep: (!pairs.is_empty()).then(|| kept.clone()),
validator: validate
.then(|| Validator::load(dll.as_deref()).ok())
.flatten(),
host: pipelines
.then(|| Host::new(false).ok().map(|h| (h, host::stub_ps())))
.flatten(),
};
while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) {
translate(job, entry.path(), &seen, &mut t);
translate(job, entry.path(), &seen, &mut t, &mut checks);
}
lock(&total).merge(t);
});
@@ -107,6 +241,58 @@ pub fn run(paths: Vec<PathBuf>) -> Result<()> {
t.lane_branches,
t.uniform_branches
);
println!(
"resources {} of {} tracked (descriptors {} loaded, {} built, {} constant; \
{} scalar accesses; {} with a computed term)",
t.tracked, t.translated, t.loaded, t.built, t.constant, t.scalar, t.dynamic
);
println!(
" used-resource entries {}: {} not traced {:?}; {} traced parameters not listed",
t.used,
t.untraced_used.values().sum::<usize>(),
t.untraced_used,
t.unlisted
);
println!(
"I/O {} of {} vertex and pixel programs raised ({} interpolations, \
{} vertex values; exports {:?}, {} still f16 pairs)",
t.io_raised, t.io_programs, t.interpolated, t.vertex_values, t.exports, t.compressed
);
println!(
"DXIL {} emitted of {} vertex and pixel programs; {} validated, {} pipelines",
t.emitted, t.emit_programs, t.validated, t.pipelines
);
println!(
" {} emitted of {} compute programs; {} validated, {} pipelines",
t.cs_emitted, t.cs_programs, t.cs_validated, t.cs_pipelines
);
println!(
" {} emitted of {} mesh programs; {} validated, {} pipelines",
t.ms_emitted, t.ms_programs, t.ms_validated, t.ms_pipelines
);
if !pairs.is_empty() {
let host = Host::new(false).map_err(anyhow::Error::msg)?;
let kept = lock(&kept);
let find = |name: &str| kept.iter().find(|(l, _)| l.contains(name));
for (v, p) in &pairs {
let made = match (find(v), find(p)) {
(Some((_, vs)), Some((_, ps))) => if vs.stage == HwStage::Ms {
host.mesh_pipeline(vs, ps)
} else {
host.pipeline(vs, ps)
}
.map(|_| "pipeline created".to_owned())
.unwrap_or_else(|e| e),
_ => "not emitted".to_owned(),
};
println!("pair {v} + {p}: {made}");
}
}
let mut lines = t.lines;
lines.sort();
for l in lines {
println!("{l}");
}
let mut failed: Vec<_> = t.failed.into_iter().collect();
failed.sort_by_key(|(_, (n, _))| std::cmp::Reverse(*n));
for (reason, (n, example)) in failed {
@@ -115,16 +301,22 @@ pub fn run(paths: Vec<PathBuf>) -> Result<()> {
Ok(())
}
fn translate(source: &Source, path: &Path, seen: &Mutex<HashSet<blake3::Hash>>, t: &mut Tally) {
fn translate(
source: &Source,
path: &Path,
seen: &Mutex<HashSet<blake3::Hash>>,
t: &mut Tally,
checks: &mut Checks,
) {
let example = || format!("{}{}", path.display(), source.label());
let Some(bytes) = source.bytes() else {
return t.fail("corrupt record".into(), example);
};
t.containers += 1;
let Some(dxil) = Container::parse(&bytes)
.ok()
.and_then(|c| c.part(FourCC::DXIL).map(|p| p.data))
else {
let Ok(container) = Container::parse(&bytes) else {
return t.fail("no DXIL part (SM5 or older)".into(), example);
};
let Some(dxil) = container.part(FourCC::DXIL).map(|p| p.data) else {
return t.fail("no DXIL part (SM5 or older)".into(), example);
};
if !lock(seen).insert(blake3::hash(dxil)) {
@@ -137,12 +329,50 @@ fn translate(source: &Source, path: &Path, seen: &Mutex<HashSet<blake3::Hash>>,
};
for p in programs {
t.programs += 1;
match ir::build(&p.code, p.wave64, p.vgprs) {
match ir::build(&p.patched_code(), p.wave64, p.vgprs) {
Ok(program) => {
t.translated += 1;
t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::<usize>();
match structure::structure(&program) {
Ok(s) => tally_structured(&program, &s, t),
let res = match resource::track(&program, &p.layout, p.stage) {
Ok(r) => {
tally_resources(&p, &r, t);
Some(r)
}
Err(ShaderError::Unsupported { offset, what }) => {
t.fail(format!("resources: {what}"), || {
format!("{} {:?} at {offset:#x}", example(), p.stage)
});
None
}
Err(e) => {
t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage));
None
}
};
let graphics = matches!(p.stage, HwStage::Vs | HwStage::Ps);
let compute = p.stage == HwStage::Cs;
let mut raised = None;
if graphics || compute || p.stage == HwStage::Ms {
t.io_programs += usize::from(graphics);
match io::raise(&program, &p) {
Ok(r) => {
if graphics {
tally_io(&r, t);
}
raised = Some(r);
}
Err(ShaderError::Unsupported { offset, what }) => t
.fail(format!("I/O: {what}"), || {
format!("{} {:?} at {offset:#x}", example(), p.stage)
}),
Err(e) => t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage)),
}
}
let structured = match structure::structure(&program) {
Ok(s) => {
tally_structured(&program, &s, t);
Some(s)
}
Err(e) => {
let reason = match e {
ShaderError::Unsupported { what, .. } => format!("structure: {what}"),
@@ -150,6 +380,22 @@ fn translate(source: &Source, path: &Path, seen: &Mutex<HashSet<blake3::Hash>>,
e => e.to_string(),
};
t.fail(reason, || format!("{} {:?}", example(), p.stage));
None
}
};
if let (Some(r), Some(i), Some(s)) = (res, raised, structured) {
let label = || format!("{} {:?}", example(), p.stage);
*counter(t, p.stage, 0) += 1;
match emit::emit(&container, &p, &program, &s, &i, &r) {
Ok(shader) => {
*counter(t, p.stage, 1) += 1;
check(shader, t, checks, label);
}
Err(ShaderError::Unsupported { offset, what }) => t
.fail(format!("emit: {what}"), || {
format!("{} at {offset:#x}", label())
}),
Err(e) => t.fail(format!("emit: {e}"), label),
}
}
}
@@ -164,6 +410,224 @@ fn translate(source: &Source, path: &Path, seen: &Mutex<HashSet<blake3::Hash>>,
}
}
/// Validates an emitted shader if asked to.
fn check(
mut shader: emit::HostShader,
t: &mut Tally,
checks: &mut Checks,
label: impl Fn() -> String,
) {
if let Some(keep) = &checks.keep {
lock(keep).push((label(), shader.clone()));
}
// `VICTORY_EMIT_DUMP` with `--list`: every emitted shader as a file.
if t.list
&& let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP")
{
let name: String = label()
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
.collect();
let _ = std::fs::write(
format!("{dir}/{}.dxil", &name[name.len().saturating_sub(100)..]),
&shader.dxil,
);
}
if let Some((h, stub_ps)) = &checks.host {
let made = match shader.stage {
HwStage::Vs => h.pipeline(&shader, stub_ps).map(drop),
HwStage::Cs => h.compute_pipeline(&shader).map(drop),
HwStage::Ms => h.mesh_pipeline(&shader, stub_ps).map(drop),
_ => host::stub_vs(&shader).and_then(|vs| h.pipeline(&vs, &shader).map(drop)),
};
match made {
Ok(()) => {
*counter(t, shader.stage, 3) += 1;
if t.list {
t.lines.push(format!("{} pipeline created", label()));
}
}
Err(e) => t.fail(format!("pipeline: {e}"), &label),
}
}
let Some(v) = checks.validator.as_mut() else {
return;
};
match v.validate(&mut shader.dxil) {
Ok(()) => {
*counter(t, shader.stage, 2) += 1;
if t.list {
t.lines.push(format!("{} validated", label()));
}
}
Err(text) => {
let first = text
.lines()
.find(|l| l.contains("error"))
.unwrap_or(text.lines().next().unwrap_or(""))
.to_owned();
if let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP") {
let n = t
.failed
.get(&format!("validator: {first}"))
.map_or(0, |f| f.0);
if n < 3 {
let name = format!(
"{dir}/{}_{n}",
first
.chars()
.filter(char::is_ascii_alphanumeric)
.take(40)
.collect::<String>()
);
let _ = std::fs::write(format!("{name}.dxil"), &shader.dxil);
let _ = std::fs::write(format!("{name}.txt"), format!("{}\n{text}", label()));
}
}
t.fail(format!("validator: {first}"), label);
}
}
}
/// Emission counts of `stage`'s kind: 0 programs, 1 emitted, 2 validated,
/// 3 pipelines.
fn counter(t: &mut Tally, stage: HwStage, k: usize) -> &mut usize {
let [a, b, c, d] = match stage {
HwStage::Cs => [
&mut t.cs_programs,
&mut t.cs_emitted,
&mut t.cs_validated,
&mut t.cs_pipelines,
],
HwStage::Ms => [
&mut t.ms_programs,
&mut t.ms_emitted,
&mut t.ms_validated,
&mut t.ms_pipelines,
],
_ => [
&mut t.emit_programs,
&mut t.emitted,
&mut t.validated,
&mut t.pipelines,
],
};
[a, b, c, d].into_iter().nth(k).expect("0 to 3")
}
fn tally_io(r: &io::Io, t: &mut Tally) {
t.io_raised += 1;
for (_, i) in &r.interps {
match i {
io::Interp::Interpolated { .. } => t.interpolated += 1,
io::Interp::Vertex { .. } => t.vertex_values += 1,
}
}
for e in &r.exports {
let kind = match e.target {
io::Target::Color(_) => "color",
io::Target::Depth => "depth",
io::Target::Null => "null",
io::Target::Position(_) => "position",
io::Target::Param { .. } => "param",
io::Target::Unread => "unread param",
io::Target::Primitive => "primitive",
io::Target::PrimitiveParam { .. } => "primitive param",
};
*t.exports.entry(kind).or_default() += 1;
t.compressed += usize::from(e.compressed);
}
}
fn tally_resources(p: &NativeProgram, r: &resource::Resources, t: &mut Tally) {
t.tracked += 1;
t.scalar += r.scalar.len();
t.dynamic += r.scalar.iter().filter(|s| s.1.dynamic.is_some()).count();
let address = |load| r.scalar.iter().find(|s| s.0 == load).map(|s| s.1);
let mut traced = HashSet::new();
for leaf in r.descriptors.iter().flat_map(|d| d.source.leaves()) {
let a = match *leaf {
resource::Source::Loaded { load, .. } => {
t.loaded += 1;
address(load)
}
resource::Source::Built { address, .. } => {
t.built += 1;
t.dynamic += usize::from(address.dynamic.is_some());
Some(address)
}
resource::Source::Constant(_) => {
t.constant += 1;
None
}
resource::Source::Phi { .. } => unreachable!("leaves are no phis"),
};
// Heaps hold dynamic resources, which no used entry lists; code
// tables are no root parameter.
if let Some(a) = a
&& a.param != resource::CODE
&& !matches!(
p.layout[a.param].root,
RootType::ResourceHeap | RootType::SamplerHeap
)
{
traced.insert(p.layout[a.param].user_data);
}
}
// Root constants are listed as a CBV, read straight from the SGPRs.
traced.extend(
r.params
.iter()
.map(|&(_, param, _)| &p.layout[param])
.filter(|l| l.root == RootType::Constants)
.map(|l| l.user_data),
);
let listed: HashSet<u8> = p.used.iter().map(|u| u.user_data).collect();
t.used += p.used.len();
// Immediate samplers are literals in the code: the distinct sampler
// values (decoded) are matched against the listed entries, which do not
// say which value is whose.
let mut values: Vec<emit::StaticSampler> = Vec::new();
for d in r
.descriptors
.iter()
.filter(|d| d.role == resource::Role::Sampler)
{
for leaf in d.source.leaves() {
if let resource::Source::Constant(words) = leaf
&& let Ok(w) = <[u32; 4]>::try_from(&words[..words.len().min(4)])
{
let s = emit::StaticSampler::from_words(w);
if !values.contains(&s) {
values.push(s);
}
}
}
}
// Engines often declare equal samplers at several registers, so equal
// values may stand for several entries, but never more values than
// entries.
let immediate = p
.used
.iter()
.filter(|u| u.root == RootType::ImmediateSampler)
.count();
let samplers_match = !values.is_empty() && values.len() <= immediate;
let matched = |u: &&victory_shader::UsedResource| {
if u.root == RootType::ImmediateSampler {
samplers_match
} else {
traced.contains(&u.user_data)
}
};
for u in p.used.iter().filter(|u| !matched(u)) {
*t.untraced_used
.entry(format!("{:?} via {:?}", u.kind, u.root))
.or_default() += 1;
}
t.unlisted += traced.difference(&listed).count();
}
fn tally_structured(program: &ir::Program, s: &structure::Structured, t: &mut Tally) {
t.structured += 1;
for (block, guards) in program.blocks.iter().zip(&s.guards) {