From 754619f30e880a4b9b6212aaca1c26415f4925b1 Mon Sep 17 00:00:00 2001 From: Marvis Date: Mon, 23 Nov 2026 14:42:21 +0100 Subject: [PATCH] Run Minecraft: runtime HLE, D3D12.X device on the host GPU, shader IR Loader: map title-shipped DLLs, patch static TLS loads to slot 0, crash reporter, title paths for GetModuleFileName*. HLE: task queue and async, XUser (one offline user), system ids, title id, features, invites, game events, persistent local storage, GameInput with no devices, xmem, console audio hardware queues, life cycle (close suspends, then terminates), and a file layer with virtual drives rewritten in path-taking imports. GPU: D3D12.X device, DXGI chain, heaps, resources, fences, queues and command lists translated onto a host D3D12 device; clears, barriers, copies, resolves and PresentX into the title's window. Shaders: SGD5 reader and `victory translate`; SSA IR with node splitting for irreducible flow; structurisation removing EXEC. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 114 ++ Cargo.toml | 1 + apps/victory/src/census.rs | 1 + apps/victory/src/main.rs | 5 + apps/victory/src/run.rs | 77 +- apps/victory/src/shader.rs | 51 +- apps/victory/src/translate.rs | 198 +++ crates/victory-core/src/config.rs | 34 +- crates/victory-game/Cargo.toml | 4 + crates/victory-game/src/lib.rs | 2 + crates/victory-game/src/sgd5.rs | 136 ++ crates/victory-gpu/Cargo.toml | 17 + crates/victory-gpu/src/descriptor.rs | 201 +++ crates/victory-gpu/src/device.rs | 300 +++++ crates/victory-gpu/src/dxgi.rs | 267 ++++ crates/victory-gpu/src/fence.rs | 154 +++ crates/victory-gpu/src/frame.rs | 139 ++ crates/victory-gpu/src/host.rs | 603 +++++++++ crates/victory-gpu/src/lib.rs | 37 +- crates/victory-gpu/src/list.rs | 678 ++++++++++ crates/victory-gpu/src/object.rs | 346 +++++ crates/victory-gpu/src/pipeline.rs | 161 +++ crates/victory-gpu/src/query.rs | 72 + crates/victory-gpu/src/queue.rs | 220 +++ crates/victory-gpu/src/resource.rs | 1165 ++++++++++++++++ crates/victory-gpu/src/root.rs | 196 +++ crates/victory-gpu/src/signature.rs | 83 ++ crates/victory-hle/Cargo.toml | 8 + crates/victory-hle/src/host.rs | 18 + crates/victory-hle/src/lib.rs | 5 +- crates/victory-hle/src/modules/audio.rs | 551 ++++++++ crates/victory-hle/src/modules/d3d12x.rs | 51 + crates/victory-hle/src/modules/files.rs | 587 ++++++++ crates/victory-hle/src/modules/gameinput.rs | 275 ++++ crates/victory-hle/src/modules/kernel.rs | 396 +++++- crates/victory-hle/src/modules/lifecycle.rs | 242 ++++ crates/victory-hle/src/modules/mod.rs | 34 +- crates/victory-hle/src/modules/storage.rs | 200 +++ crates/victory-hle/src/modules/xasync.rs | 959 ++++++++++++++ crates/victory-hle/src/modules/xgame.rs | 172 +++ .../victory-hle/src/modules/xgameruntime.rs | 273 +++- crates/victory-hle/src/modules/xmem.rs | 357 +++++ crates/victory-hle/src/modules/xsystem.rs | 154 +++ crates/victory-hle/src/modules/xuser.rs | 298 +++++ crates/victory-hle/src/registry.rs | 3 +- crates/victory-hle/src/runtime.rs | 87 ++ crates/victory-loader/Cargo.toml | 1 + crates/victory-loader/src/crash.rs | 101 ++ crates/victory-loader/src/lib.rs | 21 +- crates/victory-loader/src/resolve.rs | 2 + crates/victory-loader/src/tls.rs | 218 +++ crates/victory-loader/src/windows.rs | 125 +- crates/victory-loader/tests/load_probe.rs | 32 +- crates/victory-shader/src/gfx10/mod.rs | 38 +- crates/victory-shader/src/ir.rs | 1180 +++++++++++++++++ crates/victory-shader/src/lib.rs | 5 + crates/victory-shader/src/native.rs | 16 +- crates/victory-shader/src/structure.rs | 1136 ++++++++++++++++ docs/architecture.md | 35 +- tests/fixtures/hle-probe/src/lib.rs | 17 + victory.example.toml | 4 + 61 files changed, 12775 insertions(+), 88 deletions(-) create mode 100644 apps/victory/src/translate.rs create mode 100644 crates/victory-game/src/sgd5.rs create mode 100644 crates/victory-gpu/src/descriptor.rs create mode 100644 crates/victory-gpu/src/device.rs create mode 100644 crates/victory-gpu/src/dxgi.rs create mode 100644 crates/victory-gpu/src/fence.rs create mode 100644 crates/victory-gpu/src/frame.rs create mode 100644 crates/victory-gpu/src/host.rs create mode 100644 crates/victory-gpu/src/list.rs create mode 100644 crates/victory-gpu/src/object.rs create mode 100644 crates/victory-gpu/src/pipeline.rs create mode 100644 crates/victory-gpu/src/query.rs create mode 100644 crates/victory-gpu/src/queue.rs create mode 100644 crates/victory-gpu/src/resource.rs create mode 100644 crates/victory-gpu/src/root.rs create mode 100644 crates/victory-gpu/src/signature.rs create mode 100644 crates/victory-hle/src/modules/audio.rs create mode 100644 crates/victory-hle/src/modules/d3d12x.rs create mode 100644 crates/victory-hle/src/modules/files.rs create mode 100644 crates/victory-hle/src/modules/gameinput.rs create mode 100644 crates/victory-hle/src/modules/lifecycle.rs create mode 100644 crates/victory-hle/src/modules/storage.rs create mode 100644 crates/victory-hle/src/modules/xasync.rs create mode 100644 crates/victory-hle/src/modules/xgame.rs create mode 100644 crates/victory-hle/src/modules/xmem.rs create mode 100644 crates/victory-hle/src/modules/xsystem.rs create mode 100644 crates/victory-hle/src/modules/xuser.rs create mode 100644 crates/victory-loader/src/crash.rs create mode 100644 crates/victory-loader/src/tls.rs create mode 100644 crates/victory-shader/src/ir.rs create mode 100644 crates/victory-shader/src/structure.rs diff --git a/Cargo.lock b/Cargo.lock index e005915..73a2242 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -673,10 +673,19 @@ version = "0.1.0" [[package]] name = "victory-game" version = "0.1.0" +dependencies = [ + "memchr", + "miniz_oxide", +] [[package]] name = "victory-gpu" version = "0.1.0" +dependencies = [ + "tracing", + "windows", + "windows-sys", +] [[package]] name = "victory-hle" @@ -684,6 +693,7 @@ version = "0.1.0" dependencies = [ "tempfile", "tracing", + "victory-gpu", "victory-loader", "victory-pe", "windows-sys", @@ -749,12 +759,107 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -764,6 +869,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + [[package]] name = "winnow" version = "1.0.5" diff --git a/Cargo.toml b/Cargo.toml index a47c64f..900d7e7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,6 +33,7 @@ serde = { version = "1.0.229", features = ["derive"] } toml = "1.2.2" object = { version = "0.41.0", default-features = false, features = ["read_core", "pe", "coff", "archive", "std"] } windows-sys = "0.61.2" +windows = "0.62.2" blake3 = "1.8.7" memchr = "2.8.3" miniz_oxide = "0.9.1" diff --git a/apps/victory/src/census.rs b/apps/victory/src/census.rs index 469b8c5..9398719 100644 --- a/apps/victory/src/census.rs +++ b/apps/victory/src/census.rs @@ -68,6 +68,7 @@ pub fn run(paths: Vec, strict: bool, list_missing: bool) -> Result<()> match class { Some(Provenance::Hle) => stats.hle += 1, Some(Provenance::Host) => stats.host += 1, + Some(Provenance::Title) => unreachable!("census maps no title DLLs"), None => stats.missing += 1, } } diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index 37c7a70..86d9287 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -7,6 +7,7 @@ mod census; mod inspect; mod run; mod shader; +mod translate; use std::path::PathBuf; @@ -66,6 +67,9 @@ enum Command { #[arg(long)] disasm: bool, }, + /// Run every shader found (containers, SGD5 files) through the + /// translator and report what it cannot handle yet. + Translate { paths: Vec }, /// Prepare, map and bind a title executable; with --execute, run it. Run { exe: PathBuf, @@ -109,6 +113,7 @@ fn main() -> Result<()> { verbose, disasm, } => shader::run(paths, verbose || disasm, disasm), + Command::Translate { paths } => translate::run(paths), Command::Run { exe, unimplemented, diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index e90faf5..54f14e5 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -8,7 +8,7 @@ use crate::Unimplemented; pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool) -> Result<()> { use std::sync::Arc; use victory_hle::{HleResolver, HostPolicy}; - use victory_loader::UnimplementedPolicy; + use victory_loader::{BindReport, UnimplementedPolicy, WithTitleDlls}; let cfg = victory_core::Config::load()?; let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?; @@ -19,41 +19,78 @@ pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool None => println!("build unknown ({hash})"), } - let image = victory_loader::load(&prepared, &cfg.cache_subdir("images")?)?; + let images = cfg.cache_subdir("images")?; + let image = victory_loader::load(&prepared, &images)?; victory_hle::runtime::set_main_image(image.base()); - let resolver = HleResolver::new(if strict { - HostPolicy::none() - } else { - HostPolicy::default() - }); - let policy = match unimplemented { - Unimplemented::Trap => UnimplementedPolicy::Trap, - Unimplemented::Zero => UnimplementedPolicy::ReturnZero, - }; - let report = image.bind_imports(&resolver, policy)?; + victory_hle::runtime::set_image_path(image.base(), exe); println!( "mapped at {:#x} (preferred {:#x})", image.base(), image.info().image_base ); + let resolver = HleResolver::new(if strict { + HostPolicy::none() + } else { + HostPolicy::default() + }); + // DLLs the host or our runtime provide are never taken from the title. + let wanted = |dll: &str| { + !resolver.host.allows(dll) && !victory_hle::registry().iter().any(|m| m.serves(dll)) + }; + let title_dir = exe.parent().unwrap_or(Path::new(".")); + // A missing manifest leaves id 0 and no storage quota. + let manifest = + std::fs::read_to_string(title_dir.join("MicrosoftGame.config")).unwrap_or_default(); + let title = victory_hle::runtime::Title::from_manifest(&manifest); + let storage = cfg.data_subdir(&format!("{:08X}/storage", title.id))?; println!( - "bound {} hle, {} host, {} missing", - report.hle, - report.host, - report.missing.len() + "title {:08X}, storage {} ({} MB)", + title.id, + storage.display(), + title.storage_bytes >> 20 ); - for m in &report.missing { - println!(" missing {}!{}", m.dll, m.symbol); + victory_hle::runtime::set_title(victory_hle::runtime::Title { storage, ..title }); + 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()); + victory_hle::runtime::set_image_path(dll.base(), &title_dir.join(name)); } + + let policy = match unimplemented { + Unimplemented::Trap => UnimplementedPolicy::Trap, + Unimplemented::Zero => UnimplementedPolicy::ReturnZero, + }; + let with_dlls = WithTitleDlls { + inner: &resolver, + dlls: &dlls, + }; + let show = |name: &str, report: BindReport| { + println!( + "bound {name}: {} hle, {} host, {} title, {} missing", + report.hle, + report.host, + report.title, + report.missing.len() + ); + for m in &report.missing { + println!(" missing {}!{}", m.dll, m.symbol); + } + }; + for (name, dll) in &dlls { + show(name, dll.bind_imports(&with_dlls, policy)?); + } + let exe_name = exe.file_name().unwrap_or_default().to_string_lossy(); + show(&exe_name, image.bind_imports(&with_dlls, policy)?); if !execute { println!("not executing (pass --execute to start the title)"); return Ok(()); } + victory_loader::report_crashes(); // SAFETY: imports are bound; from here on we run title code. - let main = unsafe { Arc::new(image).spawn_main()? }; + let main = unsafe { Arc::new(image).spawn_main(dlls)? }; let code = main .join() - .map_err(|_| anyhow::anyhow!("title main thread panicked"))?; + .map_err(|_| anyhow::anyhow!("title main thread panicked"))??; println!("title exited with {code}"); Ok(()) } diff --git a/apps/victory/src/shader.rs b/apps/victory/src/shader.rs index 5944fcf..b02b056 100644 --- a/apps/victory/src/shader.rs +++ b/apps/victory/src/shader.rs @@ -1,14 +1,53 @@ //! Survey shader containers: bitcode, console additions and native code. +use std::borrow::Cow; use std::collections::BTreeMap; use std::path::PathBuf; use anyhow::Result; +use victory_game::sgd5; use victory_shader::gfx10::{self, Instruction}; use victory_shader::{Container, DxilProgram, FourCC, HwStage, ShaderError, native_programs}; /// Files above this size are skipped (read whole into memory for now). -const MAX_FILE: u64 = 2 << 30; +pub(crate) const MAX_FILE: u64 = 2 << 30; + +/// A shader container in a file: as is, or packed in an SGD5 record. +pub(crate) enum Source<'a> { + Raw { offset: usize, data: &'a [u8] }, + Packed(sgd5::Record<'a>), +} + +impl Source<'_> { + /// The container bytes; `None` if a packed record is corrupt. + pub(crate) fn bytes(&self) -> Option> { + match self { + Source::Raw { data, .. } => Some(Cow::Borrowed(data)), + Source::Packed(r) => r.unpack().map(Cow::Owned), + } + } + + pub(crate) fn label(&self) -> String { + match self { + Source::Raw { offset, .. } => format!("@{offset:#x}"), + Source::Packed(r) => format!("@{:#x} {}", r.offset, r.name.unwrap_or("?")), + } + } +} + +/// The records of an SGD5 file, or else every container found by its magic. +pub(crate) fn sources(data: &[u8]) -> Vec> { + if sgd5::is_sgd5(data) { + return sgd5::records(data).map(Source::Packed).collect(); + } + memchr::memmem::find_iter(data, b"DXBC") + .filter(|&offset| Container::parse(&data[offset..]).is_ok()) + .map(|offset| Source::Raw { + offset, + data: &data[offset..], + }) + .collect() +} #[derive(Default)] struct Totals { @@ -49,8 +88,12 @@ pub fn run(paths: Vec, verbose: bool, disasm: bool) -> Result<()> { continue; }; let mut found_here = 0; - for offset in memchr::memmem::find_iter(&data, b"DXBC") { - let Ok(container) = Container::parse(&data[offset..]) else { + for source in sources(&data) { + let Some(bytes) = source.bytes() else { + eprintln!("corrupt record {}{}", path.display(), source.label()); + continue; + }; + let Ok(container) = Container::parse(&bytes) else { continue; }; found_here += 1; @@ -120,7 +163,7 @@ pub fn run(paths: Vec, verbose: bool, disasm: bool) -> Result<()> { None => "no parsable DXIL program".to_owned(), } + &native; if verbose { - println!("{}@{offset:#x}: {line}", path.display()); + println!("{}{}: {line}", path.display(), source.label()); for l in &listing { println!("{l}"); } diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs new file mode 100644 index 0000000..f56e8fd --- /dev/null +++ b/apps/victory/src/translate.rs @@ -0,0 +1,198 @@ +//! The offline batch: every shader found goes through the translator, and +//! what it cannot handle yet is tallied (decision 0003). + +use std::collections::{BTreeMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use anyhow::Result; +use victory_shader::structure::{self, Atom, LaneExit}; +use victory_shader::{Container, FourCC, ShaderError, ir, native_programs}; + +use crate::shader::{MAX_FILE, Source, sources}; + +#[derive(Default)] +struct Tally { + containers: usize, + duplicates: usize, + programs: usize, + translated: usize, + instructions: usize, + structured: usize, + vector: usize, + guarded: usize, + /// Guards that read a mask the pass cannot see into. + opaque: usize, + lane_branches: usize, + uniform_branches: usize, + /// Reason → programs stopped by it, and the first one. + failed: BTreeMap, +} + +impl Tally { + fn fail(&mut self, reason: String, example: impl FnOnce() -> String) { + self.failed + .entry(reason) + .or_insert_with(|| (0, example())) + .0 += 1; + } + + fn merge(&mut self, other: Tally) { + self.containers += other.containers; + self.duplicates += other.duplicates; + self.programs += other.programs; + self.translated += other.translated; + self.instructions += other.instructions; + self.structured += other.structured; + self.vector += other.vector; + self.guarded += other.guarded; + self.opaque += other.opaque; + self.lane_branches += other.lane_branches; + self.uniform_branches += other.uniform_branches; + for (reason, (n, example)) in other.failed { + self.failed.entry(reason).or_insert((0, example)).0 += n; + } + } +} + +pub fn run(paths: Vec) -> Result<()> { + let paths = crate::default_paths(paths)?; + let threads = 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 { + for entry in walkdir::WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + { + if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE { + continue; + } + let Ok(data) = std::fs::read(entry.path()) else { + continue; + }; + let jobs = sources(&data); + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads.min(jobs.len()) { + s.spawn(|| { + let mut t = Tally::default(); + while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + translate(job, entry.path(), &seen, &mut t); + } + lock(&total).merge(t); + }); + } + }); + } + } + let t = total.into_inner().unwrap_or_else(|e| e.into_inner()); + println!( + "containers {} ({} duplicates skipped)", + t.containers, t.duplicates + ); + println!( + "programs {} translated of {} ({} IR instructions)", + t.translated, t.programs, t.instructions + ); + println!( + "structured {} of {} ({} vector instructions, {} guarded, {} on opaque masks; \ + branches {} per lane, {} uniform)", + t.structured, + t.translated, + t.vector, + t.guarded, + t.opaque, + t.lane_branches, + t.uniform_branches + ); + let mut failed: Vec<_> = t.failed.into_iter().collect(); + failed.sort_by_key(|(_, (n, _))| std::cmp::Reverse(*n)); + for (reason, (n, example)) in failed { + println!(" {n:>7} {reason} (e.g. {example})"); + } + Ok(()) +} + +fn translate(source: &Source, path: &Path, seen: &Mutex>, t: &mut Tally) { + 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 { + return t.fail("no DXIL part (SM5 or older)".into(), example); + }; + if !lock(seen).insert(blake3::hash(dxil)) { + t.duplicates += 1; + return; + } + let programs = match native_programs(dxil) { + Ok(p) => p, + Err(e) => return t.fail(e.to_string(), example), + }; + for p in programs { + t.programs += 1; + match ir::build(&p.code, p.wave64, p.vgprs) { + Ok(program) => { + t.translated += 1; + t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::(); + match structure::structure(&program) { + Ok(s) => tally_structured(&program, &s, t), + Err(e) => { + let reason = match e { + ShaderError::Unsupported { what, .. } => format!("structure: {what}"), + ShaderError::Isa { reason, .. } => format!("structure: {reason}"), + e => e.to_string(), + }; + t.fail(reason, || format!("{} {:?}", example(), p.stage)); + } + } + } + Err(e) => { + let reason = match e { + ShaderError::Unsupported { what, .. } => format!("unsupported: {what}"), + e => e.to_string(), + }; + t.fail(reason, || format!("{} {:?}", example(), p.stage)); + } + } + } +} + +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) { + t.vector += block + .insts + .iter() + .filter(|i| i.read(ir::Reg::S(ir::EXEC)).is_some()) + .count(); + for &g in guards.iter().flatten() { + t.guarded += 1; + let support = s.bools.support(g); + t.opaque += usize::from(support.iter().any(|a| matches!(a, Atom::Opaque(_)))); + } + } + for exit in &s.exits { + if let LaneExit::Branch { when, .. } = *exit { + if s.bools + .support(when) + .iter() + .all(|a| matches!(a, Atom::Uniform(_))) + { + t.uniform_branches += 1; + } else { + t.lane_branches += 1; + } + } + } +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} diff --git a/crates/victory-core/src/config.rs b/crates/victory-core/src/config.rs index c412f9b..596aa43 100644 --- a/crates/victory-core/src/config.rs +++ b/crates/victory-core/src/config.rs @@ -17,6 +17,9 @@ pub struct Config { pub game_dir: Option, /// Root for all derived data. Always outside the repository. pub cache_dir: PathBuf, + /// What titles write and must keep (persistent local storage). Never + /// inside the cache, which may be deleted at any time. + pub data_dir: PathBuf, /// Other titles used to exercise platform-level code. pub test_titles: Vec, /// The config file that was read, if any. @@ -35,6 +38,7 @@ struct FileConfig { struct FilePaths { game_dir: Option, cache_dir: Option, + data_dir: Option, #[serde(default)] test_titles: Vec, } @@ -83,10 +87,14 @@ impl Config { }; let cache_dir = env_path("VICTORY_CACHE_DIR") .or(file.cache_dir) - .map_or_else(default_cache_dir, Ok)?; + .map_or_else(|| default_dir("cache"), Ok)?; + let data_dir = env_path("VICTORY_DATA_DIR") + .or(file.data_dir) + .map_or_else(|| default_dir("data"), Ok)?; Ok(Config { game_dir: env_path("VICTORY_GAME_DIR").or(file.game_dir), cache_dir, + data_dir, test_titles, source, }) @@ -102,20 +110,30 @@ impl Config { /// Returns `/`, creating it, after checking the asset policy. pub fn cache_subdir(&self, sub: &str) -> Result { - let dir = self.cache_dir.join(sub); - ensure_outside_repo(&dir)?; - std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?; - Ok(dir) + subdir(&self.cache_dir, sub) + } + + /// Returns `/`, creating it, after checking the asset policy. + pub fn data_subdir(&self, sub: &str) -> Result { + subdir(&self.data_dir, sub) } } -fn default_cache_dir() -> Result { +fn subdir(root: &Path, sub: &str) -> Result { + let dir = root.join(sub); + ensure_outside_repo(&dir)?; + std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?; + Ok(dir) +} + +/// `%LOCALAPPDATA%/victory/` (elsewhere the XDG or home cache). +fn default_dir(name: &str) -> Result { let base = std::env::var_os("LOCALAPPDATA") .or_else(|| std::env::var_os("XDG_CACHE_HOME")) .map(PathBuf::from) .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache"))) - .context("cannot determine a cache directory; set VICTORY_CACHE_DIR")?; - Ok(base.join("victory").join("cache")) + .context("cannot determine a user directory; set VICTORY_CACHE_DIR and VICTORY_DATA_DIR")?; + Ok(base.join("victory").join(name)) } #[cfg(test)] diff --git a/crates/victory-game/Cargo.toml b/crates/victory-game/Cargo.toml index 8fc1fae..b6239d6 100644 --- a/crates/victory-game/Cargo.toml +++ b/crates/victory-game/Cargo.toml @@ -7,5 +7,9 @@ rust-version.workspace = true license.workspace = true publish.workspace = true +[dependencies] +memchr.workspace = true +miniz_oxide.workspace = true + [lints] workspace = true diff --git a/crates/victory-game/src/lib.rs b/crates/victory-game/src/lib.rs index 646c6f7..008bbc8 100644 --- a/crates/victory-game/src/lib.rs +++ b/crates/victory-game/src/lib.rs @@ -3,6 +3,8 @@ //! offsets or byte-pattern signatures). What may and may not be stored here //! is defined in docs/asset-policy.md. +pub mod sgd5; + /// A specific build of the Grand Theft Auto VI executable we know how to run. #[derive(Debug, Clone, Copy)] pub struct KnownBuild { diff --git a/crates/victory-game/src/sgd5.rs b/crates/victory-game/src/sgd5.rs new file mode 100644 index 0000000..9a2539f --- /dev/null +++ b/crates/victory-game/src/sgd5.rs @@ -0,0 +1,136 @@ +//! `SGD5`: the engine's shader file. Each record holds one shader container, +//! deflate-packed. The header tables are not decoded yet, so records are +//! found by their marker and cross-checked by their sizes: +//! +//! ```text +//! u8 name length (with NUL), name, NUL, u8 kind, +//! u32 n, u32 0x000DDCE7, u32 n, u32 unpacked size, raw deflate (n - 12 bytes) +//! ``` + +pub const MAGIC: &[u8; 4] = b"SGD5"; +const MARKER: [u8; 4] = 0x000D_DCE7_u32.to_le_bytes(); +/// Containers are at most a few MiB; refuse to allocate for absurd sizes. +const MAX_UNPACKED: usize = 64 << 20; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Record<'a> { + /// Offset of the marker in the file. + pub offset: usize, + /// Like `PS___Wrapped`; `None` if the bytes before the + /// record do not read as one. + pub name: Option<&'a str>, + /// Record type, meaning unknown (0x32 most shaders, 0x41 mesh shaders + /// and some material families, 0x3c compute, 0x40, 0x42). + pub kind: u8, + packed: &'a [u8], + unpacked_size: usize, +} + +impl Record<'_> { + /// The container, or `None` if the stream is corrupt. + pub fn unpack(&self) -> Option> { + miniz_oxide::inflate::decompress_to_vec_with_limit(self.packed, self.unpacked_size) + .ok() + .filter(|out| out.len() == self.unpacked_size) + } +} + +/// An SGD5 file, or a file holding one (an archive: records are found by +/// their marker, so no index is needed). +pub fn is_sgd5(file: &[u8]) -> bool { + memchr::memmem::find(file, MAGIC).is_some() +} + +/// Every record in an SGD5 file, in file order. +pub fn records(file: &[u8]) -> impl Iterator> { + memchr::memmem::find_iter(file, &MARKER).filter_map(|at| record(file, at)) +} + +fn record(file: &[u8], at: usize) -> Option> { + let u32_at = |o: usize| { + file.get(o..o + 4) + .map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")) as usize) + }; + let n = u32_at(at.checked_sub(4)?)?; + let unpacked_size = u32_at(at + 8)?; + if u32_at(at + 4)? != n || n < 12 || unpacked_size > MAX_UNPACKED { + return None; + } + let nul = at.checked_sub(6)?; + Some(Record { + offset: at, + name: (file[nul] == 0).then(|| name_before(file, nul)).flatten(), + kind: file[at - 5], + packed: file.get(at + 12..at + n)?, + unpacked_size, + }) +} + +/// The printable name that ends at `nul` and follows its length byte. +fn name_before(file: &[u8], nul: usize) -> Option<&str> { + let run = file[..nul] + .iter() + .rposition(|b| !b.is_ascii_graphic()) + .map_or(0, |p| p + 1); + // From 32 characters on, the length byte is printable too. + (run.saturating_sub(1)..nul) + .find(|&l| usize::from(file[l]) == nul - l) + .and_then(|l| std::str::from_utf8(&file[l + 1..nul]).ok()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn record_bytes(name: &str, kind: u8, payload: &[u8]) -> Vec { + let packed = miniz_oxide::deflate::compress_to_vec(payload, 6); + let n = (packed.len() + 12) as u32; + let mut out = vec![0xF4, 0x01, 0, 0, name.len() as u8 + 1]; + out.extend_from_slice(name.as_bytes()); + out.extend_from_slice(&[0, kind]); + for v in [n, 0x000D_DCE7, n, payload.len() as u32] { + out.extend_from_slice(&v.to_le_bytes()); + } + out.extend_from_slice(&packed); + out + } + + #[test] + fn reads_records() { + let long = format!("PS_{}_Wrapped", "x".repeat(40)); + let mut file = MAGIC.to_vec(); + file.extend_from_slice(&[1, 2, 3, 4]); + file.extend(record_bytes( + "VS_Blit_0011aabb_Wrapped", + 0x32, + b"first container", + )); + // A marker whose sizes disagree is not a record. + file.extend_from_slice(&[9, 0, 0, 0, 0xE7, 0xDC, 0x0D, 0, 8, 0, 0, 0]); + file.extend(record_bytes(&long, 0x41, &[7; 300])); + + assert!(is_sgd5(&file)); + let found: Vec<_> = records(&file).collect(); + assert_eq!(found.len(), 2); + assert_eq!(found[0].name, Some("VS_Blit_0011aabb_Wrapped")); + assert_eq!(found[0].kind, 0x32); + assert_eq!(found[0].unpack().as_deref(), Some(&b"first container"[..])); + assert_eq!(found[1].name, Some(long.as_str())); + assert_eq!(found[1].unpack(), Some(vec![7; 300])); + + // The same file inside an archive. + let mut archive = vec![0x5A; 0x1000]; + archive.extend_from_slice(&file); + assert!(is_sgd5(&archive)); + assert_eq!(records(&archive).count(), 2); + assert!(!is_sgd5(&archive[..0x1000])); + } + + #[test] + fn corrupt_stream_does_not_unpack() { + let mut file = record_bytes("CS_x", 0x3c, &[1; 64]); + file[27] = 0xFF; // first packed byte: reserved block type + let r = records(&file).next().unwrap(); + assert_eq!(r.unpack(), None); + } +} diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index d45e5bd..475e7b2 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -7,5 +7,22 @@ rust-version.workspace = true license.workspace = true publish.workspace = true +[dependencies] +tracing.workspace = true + [lints] workspace = true + +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_LibraryLoader", "Win32_System_Threading"] } +windows = { workspace = true, features = [ + "Win32_Graphics_Direct3D", + "Win32_Graphics_Direct3D12", + "Win32_Graphics_Dxgi", + "Win32_Graphics_Dxgi_Common", + "Win32_Graphics_Gdi", + "Win32_Security", + "Win32_System_LibraryLoader", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", +] } diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs new file mode 100644 index 0000000..f31a097 --- /dev/null +++ b/crates/victory-gpu/src/descriptor.rs @@ -0,0 +1,201 @@ +//! Descriptor heaps: zeroed memory, with handles that are plain addresses +//! (CPU and GPU alike, as on the console). +//! +//! Descriptor sizes: views 32 bytes and samplers 16, the size of RDNA 2's +//! image and sampler descriptors, so a title that copies descriptors itself +//! moves whole ones. Render target and depth views are ours alone; 128 bytes +//! leaves room for whatever stride a title assumes. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use crate::object::{self, DESCRIPTOR_HEAP, E_INVALIDARG, HRESULT, Iid, Object, Table, This, guid}; +use crate::resource::{Memory, PAGEABLE_IIDS}; + +const HEAP_IIDS: [Iid; 4] = [ + guid( + 0x8efb471d, + 0x616c, + 0x4f49, + [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct HeapDesc { + kind: u32, + count: u32, + flags: u32, + nodes: u32, +} + +#[repr(C)] +struct Heap { + object: Object, + desc: HeapDesc, + memory: Memory, +} + +fn heap<'a>(this: This) -> &'a Heap { + // SAFETY: called from descriptor heap methods only. + unsafe { &*this.cast::() } +} + +/// Bytes per descriptor, by heap type (views, samplers, render targets, +/// depth). +fn increment(kind: u32) -> Option { + [32, 16, 128, 128].get(kind as usize).copied() +} + +/// Device method. +pub(crate) extern "system" fn increment_size(_: This, kind: u32) -> u32 { + increment(kind).unwrap_or(0) +} + +/// What our render target views hold: the resource and the view +/// description, turned into a host view when a command uses them. +#[repr(C)] +#[derive(Clone, Copy)] +pub(crate) struct RtvRecord { + tag: u32, + described: u32, + pub(crate) resource: This, + desc: [u32; 6], +} +const RTV_TAG: u32 = u32::from_le_bytes(*b"vRTV"); +const _: () = assert!(size_of::() <= 112); + +impl RtvRecord { + /// The view description in the host's type (the same layout). + #[cfg(windows)] + pub(crate) fn desc( + &self, + ) -> Option { + // SAFETY: 24 bytes in the host's layout. + (self.described != 0).then(|| unsafe { + (&raw const self.desc) + .cast::() + .read_unaligned() + }) + } +} + +/// Device method: records the view at `handle` (descriptor memory). +pub(crate) extern "system" fn create_rtv( + _: This, + resource: This, + desc: *const [u32; 6], + handle: u64, +) { + if handle == 0 { + return; + } + // SAFETY: the title passes a description or null. + let described = unsafe { desc.as_ref() }; + let record = RtvRecord { + tag: RTV_TAG, + described: u32::from(described.is_some()), + resource, + desc: described.copied().unwrap_or_default(), + }; + // SAFETY: the handle is a descriptor slot, at least 112 bytes. + unsafe { (handle as *mut RtvRecord).write_unaligned(record) }; +} + +/// The view recorded at `handle`, if one is. +pub(crate) fn rtv_record(handle: u64) -> Option { + if handle == 0 { + return None; + } + // SAFETY: the handle is a descriptor slot the title passes back. + let record = unsafe { (handle as *const RtvRecord).read_unaligned() }; + (record.tag == RTV_TAG).then_some(record) +} + +/// Device method. +pub(crate) extern "system" fn create_heap( + _: This, + desc: *const HeapDesc, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + let Some(size) = increment(desc.kind).map(|i| u64::from(i) * u64::from(desc.count.max(1))) + else { + return E_INVALIDARG; + }; + tracing::debug!(?desc, "descriptor heap"); + let memory = match Memory::zeroed(size, 64) { + Ok(memory) => memory, + Err(hr) => return hr, + }; + let heap = Box::new(Heap { + object: Object::new(&FUNCTIONS), + desc, + memory, + }); + object::hand_out(DESCRIPTOR_HEAP, heap, iid, &HEAP_IIDS, out) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = object::is(iid, &HEAP_IIDS).then_some(this); + object::answer(DESCRIPTOR_HEAP, iid, found, out) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::(this) +} +extern "system" fn desc(this: This, out: *mut HeapDesc) { + if !out.is_null() { + // SAFETY: checked non-null; the title passes room for a description. + unsafe { out.write(heap(this).desc) }; + } +} +/// The same address for the CPU and the GPU start. +extern "system" fn start(this: This) -> u64 { + heap(this).memory.address() +} + +/// IUnknown 3, object 4, device child 1, heap 3. +static FUNCTIONS: Table<11> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + f[8] = desc as *const (); // 0x40 + f[9] = start as *const (); // 0x48 CPU + f[10] = start as *const (); // 0x50 GPU + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::{S_OK, slot}; + + #[test] + fn heaps_hold_count_descriptors_from_their_start() { + let null = std::ptr::null(); + let desc = HeapDesc { + kind: 0, + count: 1000, + flags: 1, + nodes: 0, + }; + let mut h = null; + assert_eq!(create_heap(null, &desc, &HEAP_IIDS[0], &mut h), S_OK); + let cpu = slot:: u64>(h, 0x48)(h); + assert_eq!(cpu % 64, 0); + assert_eq!(slot:: u64>(h, 0x50)(h), cpu); + assert_eq!(increment_size(null, 0), 32); + // SAFETY: the heap holds 1000 descriptors of 32 bytes. + unsafe { (cpu as *mut u8).add(999 * 32 + 31).write(1) }; + assert_eq!(increment_size(null, 9), 0); + let bad = HeapDesc { kind: 9, ..desc }; + assert_eq!(create_heap(null, &bad, &HEAP_IIDS[0], &mut h), E_INVALIDARG); + } +} diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs new file mode 100644 index 0000000..9e52a80 --- /dev/null +++ b/crates/victory-gpu/src/device.rs @@ -0,0 +1,300 @@ +//! The device titles get from device creation, laid out as their inlined +//! code expects: the object header, then device fields. Its table starts +//! like the PC device interface (IUnknown, the object methods, then the +//! device methods in PC order); console additions follow. Methods we have +//! not written log their table offset and fail, so a run shows what to +//! write next. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::c_void; + +use crate::object::{ + self, E_INVALIDARG, E_NOINTERFACE, E_NOTIMPL, HRESULT, Iid, Object, S_FALSE, S_OK, Table, This, + guid, guid_text, +}; +use crate::{ + descriptor, dxgi, fence, frame, list, pipeline, query, queue, resource, root, signature, +}; + +/// What D3D returns when none of the requested feature levels is supported. +const UNSUPPORTED: HRESULT = 0x887A_0004_u32 as i32; + +/// The device interface id (the same as on PC). Titles also import it as +/// data. +pub static IID: Iid = guid( + 0x189819f1, + 0x1db6, + 0x4b57, + [0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7], +); + +/// The interface version these layouts were checked against (2.4, what +/// Minecraft passes). Newer titles may lay objects out differently. +pub const CHECKED_VERSION: u32 = 0x0002_0004; + +/// Feature level 12_2, what the console hardware supports. +const HIGHEST_FEATURE_LEVEL: u32 = 0xc200; + +#[repr(C)] +pub struct Device { + object: Object, + /// GPU address of a null constant buffer; none yet. + null_constant_buffer: u64, + /// Byte 0 non-zero: calls the title would otherwise inline come to the + /// table. The rest is reserved. + out_of_line: [u32; 16], +} +const _: () = assert!(size_of::() == 0x58); + +/// One device per process, as on the console. +pub(crate) static DEVICE: Device = Device { + object: Object::new(&FUNCTIONS), + null_constant_buffer: 0, + out_of_line: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], +}; + +pub(crate) fn device() -> This { + (&raw const DEVICE).cast() +} + +/// Device creation: `(adapter, parameters, iid, out)`. The parameters start +/// with the interface version; the rest (ring and scratch sizes, features +/// to leave out) does not matter to us yet. +pub extern "system" fn create( + _adapter: *const c_void, + parameters: *const u32, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + if parameters.is_null() || iid.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null; the title passes its parameters and an id. + let (version, iid) = unsafe { (parameters.read(), &*iid) }; + tracing::info!(version = format_args!("{version:#x}"), "D3D12.X device"); + if version != CHECKED_VERSION { + tracing::warn!( + version = format_args!("{version:#x}"), + "device layouts were checked against {CHECKED_VERSION:#x} only" + ); + } + if *iid != IID { + tracing::warn!(iid = %guid_text(iid), "device created as an unknown interface"); + return E_NOINTERFACE; + } + if out.is_null() { + return S_FALSE; + } + object::answer(object::DEVICE, iid, Some(device()), out) +} + +/// The device, or its DXGI side. +extern "system" fn query_interface(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = if object::is(iid, &[IID]) { + Some(this) + } else if object::is(iid, &dxgi::DEVICE_IIDS) { + Some(dxgi::device()) + } else { + None + }; + object::answer(object::DEVICE, iid, found, out) +} + +extern "system" fn node_count(_: This) -> u32 { + 1 +} + +/// Feature query 2: the highest of the requested feature levels we support. +#[repr(C)] +struct FeatureLevels { + count: u32, + requested: *const u32, + highest: u32, +} + +/// Feature query 0, what an RDNA 2 GPU reports. The console's layout has +/// one field more than PC's (index 11). +const OPTIONS: [u32; 16] = [ + 1, // double-precision shader operations + 1, // output-merger logic operations + 2, // minimum precision: 16-bit + 3, // tiled resources tier + 3, // resource binding tier + 1, // stencil reference from pixel shaders + 1, // typed UAV loads of more formats + 1, // rasterizer-ordered views + 3, // conservative rasterization tier + 40, // GPU address bits per resource + 0, // 64 KiB standard swizzle + 0, // console-only field + 0, // cross-node sharing tier + 0, // cross-adapter row-major textures + 1, // viewport and render target index from any stage + 2, // resource heap tier +]; + +extern "system" fn check_feature_support( + _: This, + feature: u32, + data: *mut c_void, + size: u32, +) -> HRESULT { + const OPTIONS_QUERY: u32 = 0; + const ARCHITECTURE: u32 = 1; + const FEATURE_LEVELS: u32 = 2; + const FORMAT_SUPPORT: u32 = 3; + const MULTISAMPLE: u32 = 4; + let expected = match feature { + OPTIONS_QUERY => size_of_val(&OPTIONS), + ARCHITECTURE => 16, + FEATURE_LEVELS => size_of::(), + FORMAT_SUPPORT => 12, + MULTISAMPLE => 16, + _ => { + tracing::warn!(feature, size, "device feature query not implemented"); + return E_NOTIMPL; + } + }; + if data.is_null() || size as usize != expected { + return E_INVALIDARG; + } + match feature { + OPTIONS_QUERY => { + // SAFETY: checked size and non-null. + unsafe { data.cast::<[u32; 16]>().write_unaligned(OPTIONS) }; + S_OK + } + ARCHITECTURE => { + // SAFETY: checked size and non-null. + let a = unsafe { &mut *data.cast::<[u32; 4]>() }; + if a[0] != 0 { + return E_INVALIDARG; // one node only + } + // Not tile-based; unified, cache-coherent memory. + a[1..].copy_from_slice(&[0, 1, 1]); + S_OK + } + FORMAT_SUPPORT => { + // SAFETY: checked size and non-null. + let q = unsafe { &mut *data.cast::<[u32; 3]>() }; + // shortcut: every use of every format; answer from the host + // device once there is one. + q[1] = 0x7fff_ffff; + q[2] = 0xffff; + S_OK + } + MULTISAMPLE => { + // SAFETY: checked size and non-null. + let q = unsafe { &mut *data.cast::<[u32; 4]>() }; + // Format, sample count, flags in; one quality level out for the + // counts the hardware has. + q[3] = u32::from(matches!(q[1], 1 | 2 | 4 | 8)); + S_OK + } + _ => feature_levels(data), + } +} + +fn feature_levels(data: *mut c_void) -> HRESULT { + // SAFETY: the caller checked size and non-null. + let query = unsafe { &mut *data.cast::() }; + if query.requested.is_null() { + return E_INVALIDARG; + } + // SAFETY: the title passes `count` levels. + let requested = unsafe { std::slice::from_raw_parts(query.requested, query.count as usize) }; + match requested + .iter() + .copied() + .filter(|&l| l <= HIGHEST_FEATURE_LEVEL) + .max() + { + Some(level) => { + query.highest = level; + S_OK + } + None => UNSUPPORTED, + } +} + +/// IUnknown 3, object methods 4, device methods 76. +static FUNCTIONS: Table<83> = { + let mut f = object::d3d12_object(object::missing_table::<{ object::DEVICE }, 83>()); + f[0] = query_interface as *const (); // 0x00 + f[7] = node_count as *const (); // 0x38 + f[8] = queue::create as *const (); // 0x40 + f[9] = list::create_allocator as *const (); // 0x48 + f[12] = list::create_list as *const (); // 0x60 + f[10] = pipeline::create_graphics as *const (); // 0x50 + f[11] = pipeline::create_compute as *const (); // 0x58 + f[13] = check_feature_support as *const (); // 0x68 + f[14] = descriptor::create_heap as *const (); // 0x70 + f[15] = descriptor::increment_size as *const (); // 0x78 + f[16] = root::create as *const (); // 0x80 + f[20] = descriptor::create_rtv as *const (); // 0xa0 + f[25] = resource::allocation_info as *const (); // 0xc8 + f[27] = resource::create_committed as *const (); // 0xd8 + f[28] = resource::create_heap as *const (); // 0xe0 + f[29] = resource::create_placed as *const (); // 0xe8 + f[36] = fence::create as *const (); // 0x120 + f[38] = resource::copyable_footprints as *const (); // 0x130 + f[39] = query::create as *const (); // 0x138 + f[41] = signature::create as *const (); // 0x148 + f[69] = object::ignore as *const (); // 0x228 debug error filter + f[73] = list::create_list_x as *const (); // 0x248 + f[78] = frame::set_interval as *const (); // 0x270 + f[79] = frame::schedule as *const (); // 0x278 + f[80] = frame::wait as *const (); // 0x280 + f[81] = frame::statistics as *const (); // 0x288 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::slot; + + fn create_as(iid: &Iid) -> (HRESULT, This) { + let version = CHECKED_VERSION; + let mut device = std::ptr::null(); + let hr = create(std::ptr::null(), &version, iid, &mut device); + (hr, device) + } + + #[test] + fn creation_hands_out_the_device() { + let (hr, device) = create_as(&IID); + assert_eq!(hr, S_OK); + assert_eq!(device, super::device()); + // The title tests byte 0x18 before inlining a device call. + // SAFETY: the device is 0x58 bytes. + assert_ne!(unsafe { device.cast::().add(0x18).read() }, 0); + assert_eq!(create_as(&[0; 16]).0, E_NOINTERFACE); + assert_eq!( + slot:: u32>(device, 0x38)(device), + 1 + ); + let missing = slot:: HRESULT>(device, 0x88); + assert_eq!(missing(), E_NOTIMPL); + } + + #[test] + fn feature_levels_pick_the_highest_supported() { + type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT; + let device = device(); + let check = slot::(device, 0x68); + let query = |levels: &[u32], size| { + let mut query = FeatureLevels { + count: levels.len() as u32, + requested: levels.as_ptr(), + highest: 0, + }; + let hr = check(device, 2, (&raw mut query).cast(), size); + (hr, query.highest) + }; + let levels = [0xb000, 0xb100, 0xc000, 0xc100, 0xd000]; + assert_eq!(query(&levels, 0x18), (S_OK, 0xc100)); + assert_eq!(query(&levels, 0x10).0, E_INVALIDARG); + assert_eq!(query(&levels[4..], 0x18).0, UNSUPPORTED); + } +} diff --git a/crates/victory-gpu/src/dxgi.rs b/crates/victory-gpu/src/dxgi.rs new file mode 100644 index 0000000..61ad2a5 --- /dev/null +++ b/crates/victory-gpu/src/dxgi.rs @@ -0,0 +1,267 @@ +//! The DXGI side of the device: one adapter with one output, reached from +//! the device by interface query. Tables follow the PC interfaces' order +//! (IUnknown, the object methods, then each interface's methods). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use crate::object::{ + self, ADAPTER, DXGI_DEVICE, E_INVALIDARG, FACTORY, HRESULT, Iid, NOT_FOUND, OUTPUT, Object, + S_OK, Table, This, guid, +}; + +/// The DXGI device interfaces, base first (as on PC). +pub(crate) const DEVICE_IIDS: [Iid; 3] = [ + guid( + 0x54ec77fa, + 0x1377, + 0x44e6, + [0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c], + ), + guid( + 0x77db970f, + 0x6276, + 0x48ba, + [0xba, 0x28, 0x07, 0x01, 0x43, 0xb4, 0x39, 0x2c], + ), + guid( + 0x05008617, + 0xfbfd, + 0x4051, + [0xa7, 0x90, 0x14, 0x48, 0x84, 0xb4, 0xf6, 0xa9], + ), +]; +const ADAPTER_IIDS: [Iid; 3] = [ + guid( + 0x2411e7e1, + 0x12ac, + 0x4ccf, + [0xbd, 0x14, 0x97, 0x98, 0xe8, 0x53, 0x4d, 0xc0], + ), + guid( + 0x29038f61, + 0x3839, + 0x4626, + [0x91, 0xfd, 0x08, 0x68, 0x79, 0x01, 0x1a, 0x05], + ), + guid( + 0x0aa1ae0a, + 0xfa0e, + 0x4b84, + [0x86, 0x44, 0xe0, 0x5f, 0xf8, 0xe5, 0xac, 0xb5], + ), +]; +const FACTORY_IIDS: [Iid; 3] = [ + guid( + 0x7b7166ec, + 0x21c7, + 0x44ae, + [0xb2, 0x1a, 0xc9, 0xae, 0x32, 0x1a, 0xe3, 0x69], + ), + guid( + 0x770aae78, + 0xf26f, + 0x4dba, + [0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87], + ), + guid( + 0x50c83a1c, + 0xe072, + 0x4c48, + [0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, 0xd0], + ), +]; +const OUTPUT_IIDS: [Iid; 1] = [guid( + 0xae02eedb, + 0xc735, + 0x4690, + [0x8d, 0x52, 0x5a, 0x8d, 0xc2, 0x02, 0x13, 0xaa], +)]; + +static DEVICE: Object = Object::new(&DEVICE_FUNCTIONS); +static ADAPTER_OBJECT: Object = Object::new(&ADAPTER_FUNCTIONS); +static FACTORY_OBJECT: Object = Object::new(&FACTORY_FUNCTIONS); +static OUTPUT_OBJECT: Object = Object::new(&OUTPUT_FUNCTIONS); + +pub(crate) fn device() -> This { + &DEVICE +} + +/// `found` if `iid` is one of `known`. +fn query(kind: usize, iid: *const Iid, known: &[Iid], found: This, out: *mut This) -> HRESULT { + object::answer(kind, iid, object::is(iid, known).then_some(found), out) +} + +/// The DXGI device also answers for the D3D12 device. +extern "system" fn device_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + if object::is(iid, &[crate::device::IID]) { + return object::answer(DXGI_DEVICE, iid, Some(crate::device::device()), out); + } + query(DXGI_DEVICE, iid, &DEVICE_IIDS, this, out) +} +extern "system" fn device_parent(_: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(DXGI_DEVICE, iid, &ADAPTER_IIDS, &ADAPTER_OBJECT, out) +} +extern "system" fn device_adapter(_: This, out: *mut This) -> HRESULT { + object::answer(DXGI_DEVICE, &ADAPTER_IIDS[0], Some(&ADAPTER_OBJECT), out) +} + +extern "system" fn adapter_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(ADAPTER, iid, &ADAPTER_IIDS, this, out) +} +extern "system" fn adapter_parent(_: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(ADAPTER, iid, &FACTORY_IIDS, &FACTORY_OBJECT, out) +} +extern "system" fn adapter_outputs(_: This, index: u32, out: *mut This) -> HRESULT { + if index != 0 { + return NOT_FOUND; + } + object::answer(ADAPTER, &OUTPUT_IIDS[0], Some(&OUTPUT_OBJECT), out) +} + +#[repr(C)] +struct AdapterDescription { + name: [u16; 128], + vendor: u32, + device: u32, + subsystem: u32, + revision: u32, + dedicated_video_memory: usize, + dedicated_system_memory: usize, + shared_system_memory: usize, + luid: [u32; 2], +} +const _: () = assert!(size_of::() == 0x130); + +const AMD: u32 = 0x1002; +const GIB: usize = 1 << 30; + +extern "system" fn adapter_description(_: This, out: *mut AdapterDescription) -> HRESULT { + if out.is_null() { + return E_INVALIDARG; + } + let mut name = [0; 128]; + for (slot, unit) in name.iter_mut().zip("VIctory console GPU".encode_utf16()) { + *slot = unit; + } + // shortcut: memory sizes are the Series X game split (10 GiB fast, + // 3.5 GiB standard), not measured; revisit once memory is emulated. + let description = AdapterDescription { + name, + vendor: AMD, + device: 0, + subsystem: 0, + revision: 0, + dedicated_video_memory: 10 * GIB, + dedicated_system_memory: 0, + shared_system_memory: 7 * GIB / 2, + luid: [1, 0], + }; + // SAFETY: checked non-null; the title passes room for the description. + unsafe { out.write(description) }; + S_OK +} + +extern "system" fn factory_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(FACTORY, iid, &FACTORY_IIDS, this, out) +} +extern "system" fn factory_adapters(_: This, index: u32, out: *mut This) -> HRESULT { + if index != 0 { + return NOT_FOUND; + } + object::answer(FACTORY, &ADAPTER_IIDS[0], Some(&ADAPTER_OBJECT), out) +} + +extern "system" fn output_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(OUTPUT, iid, &OUTPUT_IIDS, this, out) +} +extern "system" fn output_parent(_: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(OUTPUT, iid, &ADAPTER_IIDS, &ADAPTER_OBJECT, out) +} + +/// IUnknown 3, object 4, device 5 + 2 + 3. +static DEVICE_FUNCTIONS: Table<17> = { + let mut f = object::missing_table::(); + f[0] = device_query as *const (); + f[6] = device_parent as *const (); // 0x30 + f[7] = device_adapter as *const (); // 0x38 + Table(f) +}; + +/// IUnknown 3, object 4, adapter 3 + 1 + 1. +static ADAPTER_FUNCTIONS: Table<12> = { + let mut f = object::missing_table::(); + f[0] = adapter_query as *const (); + f[6] = adapter_parent as *const (); // 0x30 + f[7] = adapter_outputs as *const (); // 0x38 + f[8] = adapter_description as *const (); // 0x40 + Table(f) +}; + +/// IUnknown 3, object 4, factory 5 + 2 + 11. +static FACTORY_FUNCTIONS: Table<25> = { + let mut f = object::missing_table::(); + f[0] = factory_query as *const (); + f[7] = factory_adapters as *const (); // 0x38 + f[12] = factory_adapters as *const (); // 0x60, the same for version 1 + Table(f) +}; + +/// IUnknown 3, object 4, output 15 (12 as on PC, then 3 console ones). +static OUTPUT_FUNCTIONS: Table<22> = { + let mut f = object::missing_table::(); + f[0] = output_query as *const (); + f[6] = output_parent as *const (); // 0x30 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::{E_NOINTERFACE, slot}; + + type Query = extern "system" fn(This, *const Iid, *mut This) -> HRESULT; + type Get = extern "system" fn(This, *mut This) -> HRESULT; + type Indexed = extern "system" fn(This, u32, *mut This) -> HRESULT; + type Describe = extern "system" fn(This, *mut AdapterDescription) -> HRESULT; + + /// Minecraft's startup: device → DXGI device (newest first) → adapter → + /// description, factory, first output. + #[test] + fn startup_walks_from_device_to_output() { + let d3d = crate::device::device(); + let newest_pc = guid( + 0x6007896c, + 0x3244, + 0x4afd, + [0xbf, 0x18, 0xa6, 0xd3, 0xbe, 0xda, 0x50, 0x23], + ); + let mut dxgi = std::ptr::null(); + let qi = slot::(d3d, 0); + assert_eq!(qi(d3d, &newest_pc, &mut dxgi), E_NOINTERFACE); + assert!(dxgi.is_null()); + assert_eq!(qi(d3d, &DEVICE_IIDS[2], &mut dxgi), S_OK); + assert_eq!(dxgi, device()); + + let mut adapter = std::ptr::null(); + assert_eq!(slot::(dxgi, 0x38)(dxgi, &mut adapter), S_OK); + let mut description = std::mem::MaybeUninit::::uninit(); + assert_eq!( + slot::(adapter, 0x40)(adapter, description.as_mut_ptr()), + S_OK + ); + // SAFETY: written above. + assert_eq!(unsafe { description.assume_init() }.vendor, AMD); + + let mut factory = std::ptr::null(); + let parent = slot::(adapter, 0x30); + assert_eq!(parent(adapter, &FACTORY_IIDS[2], &mut factory), S_OK); + let mut again = std::ptr::null(); + assert_eq!(slot::(factory, 0x38)(factory, 0, &mut again), S_OK); + assert_eq!(again, adapter); + + let mut output = std::ptr::null(); + let outputs = slot::(adapter, 0x38); + assert_eq!(outputs(adapter, 0, &mut output), S_OK); + assert!(!output.is_null()); + assert_eq!(outputs(adapter, 1, &mut output), NOT_FOUND); + } +} diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs new file mode 100644 index 0000000..11c692b --- /dev/null +++ b/crates/victory-gpu/src/fence.rs @@ -0,0 +1,154 @@ +//! Fences: a 64-bit value and the events waiting for it. Nothing runs on a +//! GPU yet, so only signals (the title's, later our queues') move one. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::c_void; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +use crate::object::{self, E_NOTIMPL, FENCE, HRESULT, Iid, Object, S_OK, Table, This, guid}; +use crate::resource::PAGEABLE_IIDS; + +pub(crate) const FENCE_IIDS: [Iid; 4] = [ + guid( + 0x0a753dcf, + 0xc4d8, + 0x4b91, + [0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +struct Fence { + object: Object, + value: AtomicU64, + /// Events to set once the value reaches theirs (handles as integers). + waiters: Mutex>, +} + +fn fence<'a>(this: This) -> &'a Fence { + // SAFETY: called from fence methods only. + unsafe { &*this.cast::() } +} + +pub(crate) extern "system" fn create( + _: This, + initial: u64, + flags: u32, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + tracing::debug!(initial, flags, "fence"); + let fence = Box::new(Fence { + object: Object::new(&FUNCTIONS), + value: AtomicU64::new(initial), + waiters: Mutex::new(Vec::new()), + }); + object::hand_out(FENCE, fence, iid, &FENCE_IIDS, out) +} + +fn set_event(event: usize) { + #[cfg(windows)] + // SAFETY: the title passed an event handle. + unsafe { + windows_sys::Win32::System::Threading::SetEvent(event as *mut c_void) + }; + #[cfg(not(windows))] + let _ = event; +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer( + FENCE, + iid, + object::is(iid, &FENCE_IIDS).then_some(this), + out, + ) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::(this) +} +extern "system" fn completed(this: This) -> u64 { + fence(this).value.load(Ordering::Acquire) +} +extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c_void) -> HRESULT { + let fence = fence(this); + let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); + if fence.value.load(Ordering::Acquire) >= value { + if !event.is_null() { + set_event(event as usize); + } + return S_OK; + } + if event.is_null() { + // shortcut: a null event means "block until reached"; nothing can + // reach it while no GPU work runs, so fail instead of hanging. + tracing::warn!(value, "blocking fence wait not implemented"); + return E_NOTIMPL; + } + waiters.push((value, event as usize)); + S_OK +} +pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { + let fence = fence(this); + let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); + fence.value.store(value, Ordering::Release); + waiters.retain(|&(wanted, event)| { + let reached = wanted <= value; + if reached { + set_event(event); + } + !reached + }); + S_OK +} + +/// IUnknown 3, object 4, device child 1, fence 3. +static FUNCTIONS: Table<11> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + f[8] = completed as *const (); // 0x40 + f[9] = set_event_on_completion as *const (); // 0x48 + f[10] = signal as *const (); // 0x50 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::slot; + + #[cfg(windows)] + #[test] + fn signals_set_waiting_events() { + use windows_sys::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; + use windows_sys::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + + let mut f = std::ptr::null(); + assert_eq!(create(std::ptr::null(), 1, 0, &FENCE_IIDS[0], &mut f), S_OK); + assert_eq!(slot:: u64>(f, 0x40)(f), 1); + // SAFETY: plain auto-reset event. + let event = unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) }; + assert!(!event.is_null()); + let wait = slot:: HRESULT>(f, 0x48); + let signal = slot:: HRESULT>(f, 0x50); + assert_eq!(wait(f, 5, event), S_OK); + // SAFETY: a valid event. + assert_ne!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0); + assert_eq!(signal(f, 5), S_OK); + // SAFETY: as above. + assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0); + assert_eq!(wait(f, 5, event), S_OK, "already reached"); + // SAFETY: as above. + assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0); + assert_eq!(wait(f, 9, std::ptr::null_mut()), E_NOTIMPL); + // SAFETY: ours. + unsafe { CloseHandle(event) }; + assert_eq!(slot:: u32>(f, 0x10)(f), 0); + } +} diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs new file mode 100644 index 0000000..842b894 --- /dev/null +++ b/crates/victory-gpu/src/frame.rs @@ -0,0 +1,139 @@ +//! Frame pacing: the title sets a frame interval and waits for each frame +//! to begin. Ours is a clock started by the first interval set, ticking +//! once per interval; the token is the frame number. +//! +//! shortcut: event offsets and display events are not told apart (all +//! waits end on the next tick); tie the clock to presentation once frames +//! reach the screen. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use crate::object::{HRESULT, S_OK, This}; + +/// `HRESULT_FROM_WIN32(WAIT_TIMEOUT)`. +const TIMEOUT: HRESULT = 0x8007_0102_u32 as i32; +const SIXTIETH: Duration = Duration::from_micros(16_667); + +struct Clock { + start: Instant, + interval: Duration, +} + +static CLOCK: Mutex> = Mutex::new(None); +static FRAME: AtomicU64 = AtomicU64::new(0); + +fn clock() -> std::sync::MutexGuard<'static, Option> { + CLOCK.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Device method: `periods` intervals of `length` microseconds per frame. +pub(crate) extern "system" fn set_interval( + _: This, + _output: This, + length: u32, + periods: u32, + _flags: u32, +) -> HRESULT { + let interval = match u64::from(length) * u64::from(periods.max(1)) { + 0 => SIXTIETH, + us => Duration::from_micros(us), + }; + tracing::info!(?interval, "frame interval"); + let mut clock = clock(); + match clock.as_mut() { + Some(c) => c.interval = interval, + None => { + *clock = Some(Clock { + start: Instant::now(), + interval, + }) + } + } + S_OK +} + +/// Device method: events are scheduled at every tick. +pub(crate) extern "system" fn schedule( + _: This, + _kind: u32, + _offset: u32, + _list: *const u8, + _flags: u32, +) -> HRESULT { + S_OK +} + +/// How long until the next tick. +fn until_next_tick() -> Duration { + let mut clock = clock(); + let c = clock.get_or_insert_with(|| Clock { + start: Instant::now(), + interval: SIXTIETH, + }); + let elapsed = c.start.elapsed().as_nanos(); + let interval = c.interval.as_nanos().max(1); + let next = (elapsed / interval + 1) * interval; + Duration::from_nanos((next - elapsed) as u64) +} + +/// Device method: blocks until the next tick, then hands out the frame's +/// token. +pub(crate) extern "system" fn wait( + _: This, + _kind: u32, + timeout_ms: u32, + _list: *const u8, + _flags: u32, + token: *mut u64, +) -> HRESULT { + let wait = until_next_tick(); + let limit = Duration::from_millis(u64::from(timeout_ms)); + if wait > limit { + std::thread::sleep(limit); + return TIMEOUT; + } + std::thread::sleep(wait); + let frame = FRAME.fetch_add(1, Ordering::Relaxed) + 1; + if !token.is_null() { + // SAFETY: checked non-null; the title passes its token. + unsafe { token.write(frame) }; + } + S_OK +} + +/// Device method: no statistics are kept, so none are returned. +pub(crate) extern "system" fn statistics( + _: This, + _token: u64, + _kinds: u32, + count: *mut u32, + _out: *mut u8, +) -> HRESULT { + if !count.is_null() { + // SAFETY: checked non-null. + unsafe { count.write(0) }; + } + S_OK +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn waits_end_on_ticks_and_count_frames() { + let null = std::ptr::null(); + assert_eq!(set_interval(null, null, 2_000, 1, 0), S_OK); + let mut first = 0; + assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut first), S_OK); + let before = Instant::now(); + let mut second = 0; + assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut second), S_OK); + assert!(second > first); + assert!(before.elapsed() <= Duration::from_millis(50)); + assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT); + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs new file mode 100644 index 0000000..a130169 --- /dev/null +++ b/crates/victory-gpu/src/host.rs @@ -0,0 +1,603 @@ +//! The host GPU: one D3D12 device and direct queue (decision 0007), and a +//! window to present on. +//! +//! shortcut: every submission is waited for, so CPU and GPU never overlap; +//! overlap them with per-submission fences once more than clears run. + +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM}; +use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::Win32::Graphics::Dxgi::*; +use windows::Win32::System::LibraryLoader::GetModuleHandleW; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::Win32::UI::WindowsAndMessaging::*; +use windows::core::{Interface, PCWSTR, w}; + +/// Resource states without the console's own bits (compression hints from +/// bit 25 up), which the host rejects. +pub(crate) fn pc_state(state: u32) -> u32 { + state & 0x01ff_ffff +} + +/// A console state as a host texture state: PC bits only, and none of the +/// buffer-only ones the console allows on textures (vertex, constant and +/// index buffer, stream out, indirect arguments, as in "generic read"). +pub(crate) fn texture_state(state: u32) -> u32 { + const BUFFER_ONLY: u32 = 0x1 | 0x2 | 0x100 | 0x200; + pc_state(state) & !BUFFER_ONLY +} + +/// Render target views live only until their command is recorded, so a +/// ring of host descriptors is enough. +const RTV_RING: u32 = 1024; + +pub(crate) struct Host { + pub(crate) device: ID3D12Device, + queue: ID3D12CommandQueue, + fence: ID3D12Fence, + /// The last value signalled on `fence`, behind the submission lock. + submitted: Mutex, + event: HANDLE, + rtvs: ID3D12DescriptorHeap, + rtv_size: u32, + /// With `VICTORY_D3D12_DEBUG` set: the debug layer's messages. + messages: Option, + next_rtv: AtomicU32, + presenter: Mutex>, +} + +// SAFETY: D3D12 devices, queues, fences and descriptor heaps are +// free-threaded; the event handle is only waited on under `submitted`. +unsafe impl Send for Host {} +// SAFETY: as above. +unsafe impl Sync for Host {} + +/// The host GPU, created on first use; `None` without one (a run then +/// behaves as before: nothing executes). +pub(crate) fn host() -> Option<&'static Host> { + static HOST: OnceLock> = OnceLock::new(); + HOST.get_or_init(|| match create() { + Ok(host) => Some(host), + Err(e) => { + tracing::warn!(error = %e, "no host D3D12 device; command lists will not run"); + None + } + }) + .as_ref() +} + +fn create() -> windows::core::Result { + // SAFETY: plain D3D12 object creation with valid descriptions. + unsafe { + let debug = std::env::var_os("VICTORY_D3D12_DEBUG").is_some(); + if debug { + let mut layer: Option = None; + match D3D12GetDebugInterface(&mut layer) { + Ok(()) => layer.into_iter().for_each(|l| l.EnableDebugLayer()), + Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"), + } + } + let mut device: Option = None; + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; + let device = device.ok_or_else(windows::core::Error::empty)?; + let messages = debug + .then(|| device.cast::().ok()) + .flatten(); + let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + })?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = CreateEventW(None, false, false, None)?; + let rtvs: ID3D12DescriptorHeap = + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: RTV_RING, + ..Default::default() + })?; + let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + tracing::info!("host D3D12 device ready"); + Ok(Host { + device, + queue, + fence, + submitted: Mutex::new(0), + event, + rtvs, + rtv_size, + messages, + next_rtv: AtomicU32::new(0), + presenter: Mutex::new(None), + }) + } +} + +/// A host command list and its allocator, always used together. +pub(crate) struct HostList { + allocator: ID3D12CommandAllocator, + pub(crate) list: ID3D12GraphicsCommandList, + /// Work for submission time, in recorded order. + deferred: Mutex, + /// Set when closing failed: the list must not run until reset. + broken: std::sync::atomic::AtomicBool, +} + +/// What a list does on the CPU when it is submitted: copies between host +/// memory regions (title buffers and upload buffers), and the upload +/// buffers its GPU copies read, kept until the list is reset. +#[derive(Default)] +struct Deferred { + /// Destination, source, bytes. + copies: Vec<(usize, usize, usize)>, + uploads: Vec, +} + +impl Host { + /// A new list, open for recording. + pub(crate) fn new_list(&self) -> windows::core::Result { + // SAFETY: plain object creation. + unsafe { + let allocator: ID3D12CommandAllocator = self + .device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = self.device.CreateCommandList( + 0, + D3D12_COMMAND_LIST_TYPE_DIRECT, + &allocator, + None, + )?; + Ok(HostList { + allocator, + list, + deferred: Mutex::default(), + broken: Default::default(), + }) + } + } + + /// Runs closed lists and waits for them. + pub(crate) fn execute(&self, lists: &[&HostList]) { + // A list that failed to close would remove the device. + let lists: Vec<&HostList> = lists + .iter() + .copied() + .filter(|l| !l.broken.load(Ordering::Relaxed)) + .collect(); + for list in &lists { + list.run_deferred(); + } + let lists: Vec> = + lists.iter().map(|l| l.list.cast().ok()).collect(); + let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); + *submitted += 1; + // SAFETY: closed lists; the fence and event are ours. + unsafe { + self.queue.ExecuteCommandLists(&lists); + let waited = self + .queue + .Signal(&self.fence, *submitted) + .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event)); + match waited { + Ok(()) => { + WaitForSingleObject(self.event, INFINITE); + } + Err(e) => tracing::warn!(error = %e, "host submission not waited for"), + } + } + self.log_messages(); + } + + /// Moves the debug layer's messages into our log. + pub(crate) fn log_messages(&self) { + let Some(queue) = &self.messages else { + return; + }; + // SAFETY: each message is read into a buffer of the size the queue + // reports, then the queue is emptied. + unsafe { + for i in 0..queue.GetNumStoredMessages() { + let mut size = 0; + if queue.GetMessage(i, None, &mut size).is_err() || size == 0 { + continue; + } + let mut buffer = vec![0u64; size.div_ceil(8)]; + let message = buffer.as_mut_ptr().cast::(); + if queue.GetMessage(i, Some(message), &mut size).is_ok() { + let m = &*message; + let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); + let text = String::from_utf8_lossy(text); + tracing::warn!( + id = m.ID.0, + severity = m.Severity.0, + "D3D12: {}", + text.trim_end_matches('\0') + ); + } + } + queue.ClearStoredMessages(); + } + } + + /// A host render target view of `resource`, valid until it is recorded. + pub(crate) fn rtv( + &self, + resource: &ID3D12Resource, + desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>, + ) -> D3D12_CPU_DESCRIPTOR_HANDLE { + let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING; + // SAFETY: a slot of our heap and a live resource. + unsafe { + let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart(); + handle.ptr += (slot * self.rtv_size) as usize; + self.device + .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle); + handle + } + } +} + +impl HostList { + pub(crate) fn close(&self) { + // SAFETY: our list. + if let Err(e) = unsafe { self.list.Close() } { + self.broken.store(true, Ordering::Relaxed); + tracing::warn!(error = %e, "host command list did not close"); + if let Some(host) = host() { + host.log_messages(); + } + } + } + + /// Only after the list's last submission finished (every one is waited + /// for). + pub(crate) fn reset(&self) { + *self.deferred() = Deferred::default(); + self.broken.store(false, Ordering::Relaxed); + // SAFETY: the list is not executing. + let reset = unsafe { + self.allocator + .Reset() + .and_then(|()| self.list.Reset(&self.allocator, None)) + }; + if let Err(e) = reset { + tracing::warn!(error = %e, "host command list did not reset"); + } + } + + fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> { + self.deferred.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Copies `len` bytes from `src` to `dst` when the list is submitted. + pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) { + self.deferred() + .copies + .push((dst as usize, src as usize, len)); + } + + /// A mapped upload buffer of `size` bytes, alive until the list is + /// reset. + /// + /// shortcut: one buffer per copy; pool them once uploads are frequent. + pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + let (buffer, data) = host.upload_buffer(size)?; + self.deferred().uploads.push(buffer.clone()); + Some((buffer, data)) + } + + fn run_deferred(&self) { + for &(dst, src, len) in &self.deferred().copies { + // SAFETY: both ranges were checked against their resources when + // recorded; titles keep resources alive until their work ends. + unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len) }; + } + } +} + +impl Host { + /// A buffer in the upload heap, mapped for writing. + fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_UPLOAD, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buffer: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping of an upload buffer. + let made = unsafe { + self.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut buffer, + ) + .and_then(|()| { + let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; + b.Map(0, None, Some(&mut data)) + }) + }; + match made { + Ok(()) => Some((buffer?, data.cast())), + Err(e) => { + tracing::warn!(error = %e, size, "no upload buffer"); + None + } + } + } +} + +/// The swap chain formats a presented texture can be copied into: its own +/// family's. +fn swap_format(format: DXGI_FORMAT) -> Option { + Some(match format.0 { + 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM, + 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM, + 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM, + 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT, + _ => return None, + }) +} + +const BUFFERS: u32 = 2; + +struct Presenter { + swap_chain: IDXGISwapChain3, + width: u32, + height: u32, + format: DXGI_FORMAT, + copy: HostList, +} + +impl Host { + /// Shows `texture`, which is in `state` (a host state) and stays in it. + pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32) { + // SAFETY: a live resource. + let desc = unsafe { texture.GetDesc() }; + let Some(format) = swap_format(desc.Format) else { + tracing::warn!(format = desc.Format.0, "cannot present this format"); + return; + }; + let (width, height) = (desc.Width as u32, desc.Height); + let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner()); + if presenter.is_none() { + *presenter = match self.presenter(width, height, format) { + Ok(p) => Some(p), + Err(e) => { + tracing::warn!(error = %e, "no swap chain"); + return; + } + }; + } + let Some(p) = presenter.as_mut() else { + return; + }; + if (p.width, p.height, p.format) != (width, height, format) { + // SAFETY: no back buffer is held; every submission was waited for. + let resized = unsafe { + p.swap_chain + .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0)) + }; + match resized { + Ok(()) => (p.width, p.height, p.format) = (width, height, format), + Err(e) => { + tracing::warn!(error = %e, width, height, "swap chain not resized"); + return; + } + } + } + let state = D3D12_RESOURCE_STATES(state as i32); + // SAFETY: our swap chain, list and a live source texture. + unsafe { + let index = p.swap_chain.GetCurrentBackBufferIndex(); + let Ok(back) = p.swap_chain.GetBuffer::(index) else { + return; + }; + p.copy.reset(); + let list = &p.copy.list; + list.ResourceBarrier(&[ + transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition( + &back, + D3D12_RESOURCE_STATE_PRESENT, + D3D12_RESOURCE_STATE_COPY_DEST, + ), + ]); + list.CopyResource(&back, texture); + list.ResourceBarrier(&[ + transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state), + transition( + &back, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_PRESENT, + ), + ]); + p.copy.close(); + self.execute(&[&p.copy]); + let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); + } + } + + fn presenter( + &self, + width: u32, + height: u32, + format: DXGI_FORMAT, + ) -> windows::core::Result { + let hwnd = match title_window() { + Some(hwnd) => hwnd, + None => window(width, height)?, + }; + // SAFETY: plain object creation for our window. + unsafe { + let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; + let desc = DXGI_SWAP_CHAIN_DESC1 { + Width: width, + Height: height, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, + BufferCount: BUFFERS, + SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, + ..Default::default() + }; + let swap_chain = factory + .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)? + .cast::()?; + let copy = self.new_list()?; + copy.close(); + tracing::info!(width, height, format = format.0, "presenting to a window"); + Ok(Presenter { + swap_chain, + width, + height, + format, + copy, + }) + } + } +} + +/// A visible top-level window of this process: the one the title made, if +/// it made one. +fn title_window() -> Option { + extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL { + let mut process = 0; + // SAFETY: a window handle from the enumeration; `found` is ours. + unsafe { + GetWindowThreadProcessId(hwnd, Some(&mut process)); + if process == windows::Win32::System::Threading::GetCurrentProcessId() + && IsWindowVisible(hwnd).as_bool() + { + *(found.0 as *mut Option) = Some(hwnd); + return false.into(); + } + } + true.into() + } + let mut found: Option = None; + // SAFETY: the callback only writes `found`, which outlives the call. + let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) }; + found +} + +pub(crate) fn transition( + resource: &ID3D12Resource, + before: D3D12_RESOURCE_STATES, + after: D3D12_RESOURCE_STATES, +) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + // SAFETY: a borrowed pointer; the barrier never releases it. + pResource: unsafe { std::mem::transmute_copy(resource) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + } +} + +/// A window of the given client size, owned by its own message thread. +fn window(width: u32, height: u32) -> windows::core::Result { + let (sender, receiver) = std::sync::mpsc::channel(); + std::thread::Builder::new() + .name("victory-window".into()) + .spawn(move || { + let made = make_window(width, height); + let ok = made.is_ok(); + let _ = sender.send(made.map(|h| h.0 as usize)); + if ok { + pump(); + } + }) + .map_err(|_| windows::core::Error::empty())?; + let hwnd = receiver + .recv() + .map_err(|_| windows::core::Error::empty())??; + Ok(HWND(hwnd as *mut _)) +} + +extern "system" fn window_proc( + hwnd: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, +) -> LRESULT { + // SAFETY: the default handling for our window. + unsafe { DefWindowProcW(hwnd, message, wparam, lparam) } +} + +fn make_window(width: u32, height: u32) -> windows::core::Result { + const CLASS: PCWSTR = w!("VIctory"); + // SAFETY: registers our class once and creates a window of it. + unsafe { + let instance = GetModuleHandleW(None)?; + let class = WNDCLASSEXW { + cbSize: size_of::() as u32, + lpfnWndProc: Some(window_proc), + hInstance: instance.into(), + lpszClassName: CLASS, + hCursor: LoadCursorW(None, IDC_ARROW)?, + ..Default::default() + }; + RegisterClassExW(&class); + let mut rect = RECT { + left: 0, + top: 0, + right: width as i32, + bottom: height as i32, + }; + AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?; + CreateWindowExW( + WINDOW_EX_STYLE(0), + CLASS, + w!("VIctory"), + WS_OVERLAPPEDWINDOW | WS_VISIBLE, + CW_USEDEFAULT, + CW_USEDEFAULT, + rect.right - rect.left, + rect.bottom - rect.top, + None, + None, + Some(instance.into()), + None, + ) + } +} + +fn pump() { + let mut message = MSG::default(); + // SAFETY: the standard message loop of this thread's window. + unsafe { + while GetMessageW(&mut message, None, 0, 0).as_bool() { + let _ = TranslateMessage(&message); + DispatchMessageW(&message); + } + } +} diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index bbe28a7..ad6a787 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -1,12 +1,31 @@ //! D3D12.X on host D3D12. //! -//! D3D12.X records many commands by writing command-processor packets into -//! command lists from code inlined into the title itself, so no import-level -//! hook sees them. This crate decodes those packet streams at -//! `ExecuteCommandLists` time and replays them on host D3D12, and maps the -//! title's GPU virtual addresses (console memory is unified) to host -//! resources. +//! D3D12.X records commands from code inlined into the title, which writes +//! packets into the command list while its put pointer is below a limit and +//! calls the list's method otherwise. Our lists keep the limits at zero, so +//! every command arrives here as a call, to be run on host D3D12. The +//! title's GPU addresses are CPU addresses (console memory is unified). //! -//! Planned modules: `packets` (stream decoder), `memory` (title GPU -//! addresses to host heaps), `pipeline` (PSOs from `victory-shader` output), -//! `present` (swap chain, frame pacing). +//! [`device`] is the device object titles create, [`dxgi`] its adapter side, +//! [`resource`] heaps and resources, [`fence`] fences, [`queue`] command +//! queues, [`list`] command allocators and lists, [`descriptor`] +//! descriptor heaps, [`root`] root signatures, [`query`] query heaps, +//! [`signature`] command signatures, [`pipeline`] pipeline states, +//! [`frame`] frame pacing, [`object`] what all console graphics objects +//! share. Planned: `present` (swap chain). + +pub mod descriptor; +pub mod device; +pub mod dxgi; +pub mod fence; +pub mod frame; +#[cfg(windows)] +mod host; +pub mod list; +pub mod object; +pub mod pipeline; +pub mod query; +pub mod queue; +pub mod resource; +pub mod root; +pub mod signature; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs new file mode 100644 index 0000000..7328609 --- /dev/null +++ b/crates/victory-gpu/src/list.rs @@ -0,0 +1,678 @@ +//! Command allocators and command lists. +//! +//! The title's inlined code writes packets into a list only while its put +//! pointer is below a limit, and calls the list's method otherwise. Our +//! lists keep the pointer and every limit at zero, so every command reaches +//! the table as a call. +//! +//! shortcut: the methods record nothing yet; unwritten ones log once, so a +//! run lists what to translate. Translate them onto host command lists +//! (TODO.md, GPU). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::mem::offset_of; + +use crate::object::{ + self, ALLOCATOR, E_INVALIDARG, HRESULT, Iid, LIST, Object, S_OK, Table, This, guid, +}; +use crate::resource::PAGEABLE_IIDS; + +const ALLOCATOR_IIDS: [Iid; 4] = [ + guid( + 0x6102dee4, + 0xaf59, + 0x4b09, + [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +/// The list interfaces whose ids are the same as on PC, then the device +/// child's. +const LIST_IIDS: [Iid; 8] = [ + guid( + 0x7116d91c, + 0xe7e4, + 0x47ce, + [0xb8, 0xc6, 0xec, 0x81, 0x68, 0xf4, 0x37, 0xe5], + ), + guid( + 0x5b160d0f, + 0xac1b, + 0x4185, + [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55], + ), + guid( + 0x553103fb, + 0x1fe7, + 0x4557, + [0xbb, 0x38, 0x94, 0x6d, 0x7d, 0x0e, 0x7c, 0xa7], + ), + guid( + 0x38c3e585, + 0xff17, + 0x412c, + [0x91, 0x50, 0x4f, 0xc6, 0xf9, 0xd7, 0x2a, 0x28], + ), + guid( + 0x6fda83a7, + 0xb84c, + 0x4e38, + [0x9a, 0xc8, 0xc7, 0xbd, 0x22, 0x01, 0x6b, 0x3d], + ), + guid( + 0x8754318e, + 0xd3a9, + 0x4541, + [0x98, 0xcf, 0x64, 0x5b, 0x50, 0xdc, 0x48, 0x74], + ), + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +struct Allocator { + object: Object, + kind: u32, +} + +/// The layout the title's inlined code reads. +#[repr(C)] +struct List { + object: Object, + kind: u32, + /// The put pointer, then the plain, draw, API and unbiased API limits: + /// all zero, so every inline check fails. + put: [u64; 5], + reserved: [u32; 64], + /// State the inline code keeps for building packets; unused by us. + graphics_root_headers: [u32; 128], + compute_root_headers: [u32; 128], + pipeline_shadow: [u32; 8], + /// Ours, after the console layout: the host list the calls record + /// into (decision 0007). + #[cfg(windows)] + host: Option, +} +const _: () = assert!(offset_of!(List, put) == 0x18); +const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560); + +/// The host list behind a title list, if there is a host GPU. +#[cfg(windows)] +pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> { + if this.is_null() { + return None; + } + // SAFETY: the title passes one of our lists. + unsafe { (*this.cast::()).host.as_ref() } +} + +pub(crate) extern "system" fn create_allocator( + _: This, + kind: u32, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + let allocator = Box::new(Allocator { + object: Object::new(&ALLOCATOR_FUNCTIONS), + kind, + }); + object::hand_out(ALLOCATOR, allocator, iid, &ALLOCATOR_IIDS, out) +} + +/// Lists start open, as in D3D12. +pub(crate) extern "system" fn create_list( + _: This, + _nodes: u32, + kind: u32, + allocator: This, + _pipeline: This, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + new_list(kind, allocator, iid, out) +} + +/// The console's list creation: type, flags, node mask and barrier batch +/// size in a description. +#[repr(C)] +#[derive(Debug)] +pub(crate) struct ListDesc { + kind: u32, + flags: u32, + nodes: u32, + barrier_batch: u32, +} + +pub(crate) extern "system" fn create_list_x( + _: This, + desc: *const ListDesc, + allocator: This, + _pipeline: This, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + tracing::debug!(?desc, "console command list"); + new_list(desc.kind, allocator, iid, out) +} + +fn new_list(kind: u32, allocator: This, iid: *const Iid, out: *mut This) -> HRESULT { + if allocator.is_null() { + return E_INVALIDARG; + } + tracing::debug!(kind, "command list"); + let list = Box::new(List { + object: Object::new(&LIST_FUNCTIONS), + kind, + put: [0; 5], + reserved: [0; 64], + graphics_root_headers: [0; 128], + compute_root_headers: [0; 128], + pipeline_shadow: [0; 8], + #[cfg(windows)] + host: crate::host::host().and_then(|h| match h.new_list() { + Ok(list) => Some(list), + Err(e) => { + tracing::warn!(error = %e, "no host command list"); + None + } + }), + }); + object::hand_out(LIST, list, iid, &LIST_IIDS, out) +} + +extern "system" fn allocator_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = object::is(iid, &ALLOCATOR_IIDS).then_some(this); + object::answer(ALLOCATOR, iid, found, out) +} +extern "system" fn allocator_release(this: This) -> u32 { + object::release_boxed::(this) +} +/// Nothing is recorded, so there is nothing to free. +extern "system" fn allocator_reset(_: This) -> HRESULT { + S_OK +} + +extern "system" fn list_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer(LIST, iid, object::is(iid, &LIST_IIDS).then_some(this), out) +} +extern "system" fn list_release(this: This) -> u32 { + object::release_boxed::(this) +} +extern "system" fn list_type(this: This) -> u32 { + // SAFETY: `this` is one of our lists. + unsafe { (*this.cast::()).kind } +} +extern "system" fn close(this: This) -> HRESULT { + #[cfg(windows)] + if let Some(host) = host_list(this) { + host.close(); + } + S_OK +} +extern "system" fn reset(this: This, allocator: This, _pipeline: This) -> HRESULT { + if allocator.is_null() { + return E_INVALIDARG; + } + #[cfg(windows)] + if let Some(host) = host_list(this) { + host.reset(); + } + S_OK +} + +/// A resource barrier as titles pass it: type, flags, then a resource and +/// either a subresource and two states (transition) or a second resource +/// (aliasing). The same layout as the host's. +#[repr(C)] +#[derive(Clone, Copy)] +pub(crate) struct Barrier { + kind: u32, + flags: u32, + first: This, + second: u64, + last: u64, +} + +/// The barrier on host resources, or `None` if it names a resource the host +/// GPU does not have (buffers so far). +#[cfg(windows)] +fn host_barrier(b: &Barrier) -> Option { + use windows::core::Interface; + let host = |r: This| crate::resource::host_resource(r).map(|h| h.as_raw().cast_const().cast()); + match b.kind { + 0 => { + // A split barrier's first half: its second half transitions. + const BEGIN_ONLY: u32 = 1; + if b.flags & BEGIN_ONLY != 0 { + return None; + } + // shortcut: whole resources, from the state we tracked (see + // `host_transition`); subresources are not told apart. + let wanted = crate::host::texture_state(b.last as u32); + let (resource, before) = crate::resource::host_transition(b.first, wanted)?; + Some(Barrier { + kind: 0, + flags: 0, + first: resource.cast_const().cast(), + second: 0xffff_ffff | (u64::from(before) << 32), + last: u64::from(wanted), + }) + } + 1 => Some(Barrier { + first: if b.first.is_null() { + b.first + } else { + host(b.first)? + }, + second: if b.second == 0 { + 0 + } else { + host(b.second as This)? as u64 + }, + ..*b + }), + 2 => Some(Barrier { + first: if b.first.is_null() { + b.first + } else { + host(b.first)? + }, + ..*b + }), + _ => None, + } +} + +/// Returns the console's barrier "actions" (none). +extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 { + #[cfg(windows)] + if let Some(list) = host_list(this) + && !barriers.is_null() + { + // SAFETY: the title passes `count` barriers. + let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) }; + let host: Vec = barriers.iter().filter_map(host_barrier).collect(); + if !host.is_empty() { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; + const _: () = assert!(size_of::() == size_of::()); + // SAFETY: the same layout; borrowed resource pointers, never + // released through this slice. + let host = unsafe { + std::slice::from_raw_parts( + host.as_ptr().cast::(), + host.len(), + ) + }; + // SAFETY: an open list and live resources. + unsafe { list.list.ResourceBarrier(host) }; + } + } + 0 +} + +/// Moves a title texture's host copy to `state` in the list, if needed. +#[cfg(windows)] +fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State; + if let Some(texture) = crate::resource::host_resource(resource) + && let Some((_, before)) = crate::resource::host_transition(resource, state) + { + let barrier = crate::host::transition(texture, State(before as i32), State(state as i32)); + // SAFETY: an open list and a live texture. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + } +} + +#[cfg(windows)] +const COPY_DEST: u32 = 0x400; +#[cfg(windows)] +const COPY_SOURCE: u32 = 0x800; + +/// `len` bytes at `offset` of a title buffer, if they are inside it. +#[cfg(windows)] +fn buffer_range(buffer: This, offset: u64, len: u64) -> Option<*mut u8> { + let (data, size) = crate::resource::buffer_bytes(buffer)?; + let end = offset.checked_add(len)?; + if end > size { + tracing::warn!(offset, len, size, "copy outside its buffer"); + return None; + } + // SAFETY: inside the buffer, checked above. + Some(unsafe { data.add(offset as usize) }) +} + +/// Buffer to buffer: both are host memory, copied at submission. +extern "system" fn copy_buffer_region( + this: This, + dst: This, + dst_offset: u64, + src: This, + src_offset: u64, + len: u64, +) { + #[cfg(windows)] + if let Some(list) = host_list(this) + && let Some(to) = buffer_range(dst, dst_offset, len) + && let Some(from) = buffer_range(src, src_offset, len) + { + list.defer_copy(to, from, len as usize); + } + #[cfg(not(windows))] + let _ = (this, dst, dst_offset, src, src_offset, len); +} + +extern "system" fn copy_resource(this: This, dst: This, src: This) { + #[cfg(windows)] + { + let Some(list) = host_list(this) else { + return; + }; + if let (Some(to), Some(from)) = ( + crate::resource::host_resource(dst), + crate::resource::host_resource(src), + ) { + ensure_state(list, dst, COPY_DEST); + ensure_state(list, src, COPY_SOURCE); + // SAFETY: an open list and live textures. + unsafe { list.list.CopyResource(to, from) }; + } else if let (Some((to, a)), Some((from, b))) = ( + crate::resource::buffer_bytes(dst), + crate::resource::buffer_bytes(src), + ) { + list.defer_copy(to, from, a.min(b) as usize); + } + } + #[cfg(not(windows))] + let _ = (this, dst, src); +} + +extern "system" fn copy_resource_x(this: This, dst: This, src: This, _flags: u32) { + copy_resource(this, dst, src); +} + +/// A copy location as titles pass it, laid out as the host's: a resource, +/// then a subresource index (type 0) or a placed footprint (type 1). +#[repr(C)] +#[derive(Clone, Copy)] +pub(crate) struct CopyLocation { + resource: This, + kind: u32, + footprint: crate::resource::PlacedFootprint, +} + +/// Texture to texture on the GPU; buffer to texture through an upload +/// buffer filled at submission. Texture to buffer (read back) is not done +/// yet. +extern "system" fn copy_texture_region( + this: This, + dst: *const CopyLocation, + x: u32, + y: u32, + z: u32, + src: *const CopyLocation, + source_box: *const [u32; 6], +) { + #[cfg(windows)] + { + use windows::Win32::Graphics::Direct3D12::{D3D12_BOX, D3D12_TEXTURE_COPY_LOCATION}; + use windows::core::Interface; + const FOOTPRINT: u32 = 1; + // SAFETY: the title passes both locations (null is tolerated). + let (Some(list), Some(&dst), Some(&src)) = + (host_list(this), unsafe { dst.as_ref() }, unsafe { + src.as_ref() + }) + else { + return; + }; + let Some(to) = crate::resource::host_resource(dst.resource) else { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!("texture to buffer copies not implemented")); + return; + }; + let mut from = src; + let _upload; // keeps the source alive while this call records it + if src.kind == FOOTPRINT { + let (Some(host), Some(bytes)) = (crate::host::host(), src.footprint.bytes()) else { + return; + }; + let Some(data) = buffer_range(src.resource, src.footprint.offset, bytes) else { + return; + }; + let Some((buffer, staging)) = list.upload(host, bytes) else { + return; + }; + list.defer_copy(staging, data, bytes as usize); + from.resource = buffer.as_raw().cast_const().cast(); + from.footprint.offset = 0; + _upload = buffer; + } else { + let Some(texture) = crate::resource::host_resource(src.resource) else { + return; + }; + ensure_state(list, src.resource, COPY_SOURCE); + from.resource = texture.as_raw().cast_const().cast(); + } + ensure_state(list, dst.resource, COPY_DEST); + let mut to_location = dst; + to_location.resource = to.as_raw().cast_const().cast(); + let host_box = (!source_box.is_null()).then(|| source_box.cast::()); + const _: () = + assert!(size_of::() == size_of::()); + // SAFETY: an open list; both locations in the host's layout, naming + // live resources; the box is the title's (same layout). + unsafe { + list.list.CopyTextureRegion( + (&raw const to_location).cast(), + x, + y, + z, + (&raw const from).cast(), + host_box, + ) + }; + } + #[cfg(not(windows))] + let _ = (this, dst, x, y, z, src, source_box); +} + +#[allow(clippy::too_many_arguments)] // the method's own arguments +extern "system" fn copy_texture_region_x( + this: This, + dst: *const CopyLocation, + x: u32, + y: u32, + z: u32, + src: *const CopyLocation, + source_box: *const [u32; 6], + _flags: u32, +) { + copy_texture_region(this, dst, x, y, z, src, source_box); +} + +extern "system" fn resolve( + this: This, + dst: This, + dst_sub: u32, + src: This, + src_sub: u32, + format: u32, +) { + #[cfg(windows)] + if let Some(list) = host_list(this) + && let (Some(to), Some(from)) = ( + crate::resource::host_resource(dst), + crate::resource::host_resource(src), + ) + { + use windows::Win32::Foundation::RECT; + use windows::Win32::Graphics::Direct3D12::{ + D3D12_RESOLVE_MODE_AVERAGE, ID3D12GraphicsCommandList1, + }; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; + use windows::core::Interface; + const RESOLVE_DEST: u32 = 0x1000; + const RESOLVE_SOURCE: u32 = 0x2000; + ensure_state(list, dst, RESOLVE_DEST); + ensure_state(list, src, RESOLVE_SOURCE); + // SAFETY: an open list and live textures; the region is inside both. + unsafe { + let (a, b) = (to.GetDesc(), from.GetDesc()); + let format = DXGI_FORMAT(format as i32); + if (a.Width, a.Height) == (b.Width, b.Height) { + list.list + .ResolveSubresource(to, dst_sub, from, src_sub, format); + } else if let Ok(list1) = list.list.cast::() { + // The console clips a larger source to the destination. + let rect = RECT { + left: 0, + top: 0, + right: a.Width.min(b.Width) as i32, + bottom: a.Height.min(b.Height) as i32, + }; + list1.ResolveSubresourceRegion( + to, + dst_sub, + 0, + 0, + from, + src_sub, + Some(&rect), + format, + D3D12_RESOLVE_MODE_AVERAGE, + ); + } + } + } + #[cfg(not(windows))] + let _ = (this, dst, dst_sub, src, src_sub, format); +} + +#[repr(C)] +pub(crate) struct Rect { + left: i32, + top: i32, + right: i32, + bottom: i32, +} + +extern "system" fn clear_rtv( + this: This, + handle: u64, + color: *const [f32; 4], + count: u32, + rects: *const Rect, +) { + #[cfg(windows)] + { + let (Some(list), Some(record)) = (host_list(this), crate::descriptor::rtv_record(handle)) + else { + return; + }; + let (Some(texture), Some(host)) = ( + crate::resource::host_resource(record.resource), + crate::host::host(), + ) else { + return; + }; + // SAFETY: the title passes four floats (null is tolerated). + let Some(color) = (unsafe { color.as_ref() }) else { + return; + }; + let rects = (count > 0 && !rects.is_null()).then(|| { + // SAFETY: the title passes `count` rectangles, laid out as the host's. + unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) } + }); + const RENDER_TARGET: u32 = 0x4; + let rtv = host.rtv(texture, record.desc().as_ref()); + // SAFETY: an open list, a fresh view of a live texture. + unsafe { + if let Some((_, before)) = + crate::resource::host_transition(record.resource, RENDER_TARGET) + { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State; + list.list.ResourceBarrier(&[crate::host::transition( + texture, + State(before as i32), + State(RENDER_TARGET as i32), + )]); + } + list.list.ClearRenderTargetView(rtv, color, rects); + } + } + #[cfg(not(windows))] + let _ = (this, handle, color, count, rects); +} + +/// IUnknown 3, object 4, device child 1, allocator 2. +static ALLOCATOR_FUNCTIONS: Table<10> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = allocator_query as *const (); + f[2] = allocator_release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + f[8] = allocator_reset as *const (); // 0x40 + f[9] = object::ignore as *const (); // 0x48 allocation callback + Table(f) +}; + +/// IUnknown 3, object 4, device child 1, list 1, graphics list 96 (59 as +/// on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3 + 13). +static LIST_FUNCTIONS: Table<140> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = list_query as *const (); + f[2] = list_release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + f[8] = list_type as *const (); // 0x40 + f[9] = close as *const (); // 0x48 + f[10] = reset as *const (); // 0x50 + f[15] = copy_buffer_region as *const (); // 0x78 + f[16] = copy_texture_region as *const (); // 0x80 + f[17] = copy_resource as *const (); // 0x88 + f[19] = resolve as *const (); // 0x98 + f[26] = barrier as *const (); // 0xd0 + f[83] = copy_texture_region_x as *const (); // 0x298 + f[84] = copy_resource_x as *const (); // 0x2a0 + f[52] = clear_rtv as *const (); // 0x1a0 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::slot; + + #[test] + fn every_inline_command_falls_back_to_the_table() { + let null = std::ptr::null(); + let mut allocator = null; + assert_eq!( + create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), + S_OK + ); + let mut list = null; + let hr = create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list); + assert_eq!(hr, S_OK); + // What the title's inline draw checks: put < draw limit. + // SAFETY: the list is 0x560 bytes. + let (put, draw_limit, api_limit) = unsafe { + let at = |o: usize| list.cast::().add(o).cast::().read(); + (at(0x18), at(0x28), at(0x30)) + }; + assert!(put >= draw_limit && put >= api_limit); + assert_eq!(slot:: u32>(list, 0x40)(list), 0); + assert_eq!( + slot:: HRESULT>(list, 0x48)(list), + S_OK + ); + let release = |o: This| slot:: u32>(o, 0x10)(o); + assert_eq!(release(list), 0); + assert_eq!(release(allocator), 0); + } +} diff --git a/crates/victory-gpu/src/object.rs b/crates/victory-gpu/src/object.rs new file mode 100644 index 0000000..669e874 --- /dev/null +++ b/crates/victory-gpu/src/object.rs @@ -0,0 +1,346 @@ +//! What every console graphics object starts with: a function table +//! pointer, bookkeeping bits and a reference count. Tables begin with +//! IUnknown's three slots. Our objects are static and never destroyed. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::collections::BTreeMap; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + +pub type HRESULT = i32; +pub const S_OK: HRESULT = 0; +pub(crate) const S_FALSE: HRESULT = 1; +pub(crate) const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32; +pub(crate) const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32; +pub(crate) const E_POINTER: HRESULT = 0x8000_4003_u32 as i32; +pub(crate) const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32; +pub(crate) const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; +/// What D3D and DXGI return for a missing item (adapter, output, private +/// data). +pub(crate) const NOT_FOUND: HRESULT = 0x887A_0002_u32 as i32; +const MORE_DATA: HRESULT = 0x887A_0003_u32 as i32; + +pub type Iid = [u8; 16]; + +/// An interface id from its text form's fields, in memory order. +pub const fn guid(a: u32, b: u16, c: u16, d: [u8; 8]) -> Iid { + let (a, b, c) = (a.to_le_bytes(), b.to_le_bytes(), c.to_le_bytes()); + [ + a[0], a[1], a[2], a[3], b[0], b[1], c[0], c[1], d[0], d[1], d[2], d[3], d[4], d[5], d[6], + d[7], + ] +} + +pub fn guid_text(g: &Iid) -> String { + let a = u32::from_le_bytes([g[0], g[1], g[2], g[3]]); + let b = u16::from_le_bytes([g[4], g[5]]); + let c = u16::from_le_bytes([g[6], g[7]]); + let d: String = g[8..].iter().map(|x| format!("{x:02x}")).collect(); + format!("{a:08x}-{b:04x}-{c:04x}-{}-{}", &d[..4], &d[4..]) +} + +#[repr(C)] +pub struct Object { + functions: *const *const (), + /// Device index (bits 0-2) and bookkeeping bits; all zero. + bits: u32, + refs: AtomicU32, +} +// SAFETY: the table is static and immutable; the count is atomic. +unsafe impl Sync for Object {} + +impl Object { + pub(crate) const fn new(table: &'static Table) -> Self { + Object { + functions: table.0.as_ptr(), + bits: 0, + refs: AtomicU32::new(0), + } + } +} + +pub(crate) type This = *const Object; + +#[repr(transparent)] +pub(crate) struct Table(pub [*const (); N]); +// SAFETY: function addresses only. +unsafe impl Sync for Table {} + +pub(crate) extern "system" fn add_ref(this: This) -> u32 { + // SAFETY: `this` is one of our objects. + unsafe { &*this }.refs.fetch_add(1, Ordering::Relaxed) + 1 +} + +pub(crate) extern "system" fn release(this: This) -> u32 { + // SAFETY: `this` is one of our objects. + let refs = &unsafe { &*this }.refs; + let _ = refs.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_sub(1)); + refs.load(Ordering::Relaxed) +} + +/// Answers an interface query (or any call handing out an object): a new +/// reference to `found`, or null and `E_NOINTERFACE`. +pub(crate) fn answer(kind: usize, iid: *const Iid, found: Option, out: *mut This) -> HRESULT { + if out.is_null() { + return E_POINTER; + } + let hr = match found { + Some(object) => { + add_ref(object); + // SAFETY: checked non-null; the title passes room for a pointer. + unsafe { out.write(object) }; + return S_OK; + } + None => E_NOINTERFACE, + }; + // SAFETY: the title passes an interface id (null is tolerated). + let iid = unsafe { iid.as_ref() }.map(guid_text).unwrap_or_default(); + tracing::warn!(object = KINDS[kind], %iid, "unknown interface"); + // SAFETY: checked non-null. + unsafe { out.write(std::ptr::null()) }; + hr +} + +/// Whether `iid` is one of `known`. +pub(crate) fn is(iid: *const Iid, known: &[Iid]) -> bool { + // SAFETY: the title passes an interface id (null is tolerated). + unsafe { iid.as_ref() }.is_some_and(|i| known.contains(i)) +} + +/// Hands a new object to the title as one of `known`, or drops it. `T` +/// starts with its `Object`; its table's release slot is +/// [`release_boxed::`]. +pub(crate) fn hand_out( + kind: usize, + object: Box, + iid: *const Iid, + known: &[Iid], + out: *mut This, +) -> HRESULT { + if !is(iid, known) { + return answer(kind, iid, None, out); + } + if out.is_null() { + // Asked only whether creation would succeed. + return S_FALSE; + } + answer(kind, iid, Some(Box::into_raw(object).cast()), out) +} + +/// Release for objects made by [`hand_out`]: the last reference frees it. +pub(crate) fn release_boxed(this: This) -> u32 { + // SAFETY: `this` is the header of a boxed `T`. + let refs = &unsafe { &*this }.refs; + match refs.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_sub(1)) { + Ok(1) => { + private_data().retain(|&(object, _), _| object != this as usize); + // SAFETY: that was the last reference to a `Box`. + drop(unsafe { Box::from_raw(this.cast_mut().cast::()) }); + 0 + } + Ok(n) => n - 1, + Err(_) => 0, + } +} + +/// Private data of every object, by object address and id. +static PRIVATE: Mutex>> = Mutex::new(BTreeMap::new()); + +fn private_data() -> std::sync::MutexGuard<'static, BTreeMap<(usize, Iid), Vec>> { + PRIVATE.lock().unwrap_or_else(|e| e.into_inner()) +} + +extern "system" fn get_private_data( + this: This, + id: *const Iid, + size: *mut u32, + data: *mut u8, +) -> HRESULT { + // SAFETY: the title passes an id and its buffer size (null is tolerated). + let (Some(id), Some(size)) = (unsafe { (id.as_ref(), size.as_mut()) }) else { + return E_INVALIDARG; + }; + let map = private_data(); + let Some(value) = map.get(&(this as usize, *id)) else { + *size = 0; + return NOT_FOUND; + }; + let len = value.len() as u32; + let room = std::mem::replace(size, len); + if data.is_null() { + return S_OK; + } + if room < len { + return MORE_DATA; + } + // SAFETY: the buffer holds `room` >= `len` bytes. + unsafe { data.copy_from_nonoverlapping(value.as_ptr(), value.len()) }; + S_OK +} + +/// Null data removes the entry. +extern "system" fn set_private_data( + this: This, + id: *const Iid, + size: u32, + data: *const u8, +) -> HRESULT { + // SAFETY: the title passes an id (null is tolerated). + let Some(&id) = (unsafe { id.as_ref() }) else { + return E_INVALIDARG; + }; + let mut map = private_data(); + if data.is_null() { + map.remove(&(this as usize, id)); + } else { + // SAFETY: the title passes `size` bytes. + let value = unsafe { std::slice::from_raw_parts(data, size as usize) }; + map.insert((this as usize, id), value.to_vec()); + } + S_OK +} + +/// Fills a D3D12 table's object methods: private data and name (setting +/// an interface as private data stays unwritten). +pub(crate) const fn d3d12_object(mut f: [*const (); N]) -> [*const (); N] { + f[3] = get_private_data as *const (); // 0x18 + f[4] = set_private_data as *const (); // 0x20 + f[6] = set_name as *const (); // 0x30 + f +} + +/// The object methods' name setter: names only reach our log. +pub(crate) extern "system" fn set_name(this: This, name: *const u16) -> HRESULT { + let name = if name.is_null() { + String::new() + } else { + // SAFETY: a non-null name is NUL-terminated UTF-16. + let len = (0..).take_while(|&i| unsafe { *name.add(i) } != 0).count(); + // SAFETY: `len` units were just read. + String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(name, len) }) + }; + tracing::debug!(object = ?this, %name, "named"); + S_OK +} + +/// The device-child method: the device that made the object. +pub(crate) extern "system" fn parent_device(_: This, iid: *const Iid, out: *mut This) -> HRESULT { + let device = crate::device::device(); + answer( + DEVICE, + iid, + is(iid, &[crate::device::IID]).then_some(device), + out, + ) +} + +pub(crate) const DEVICE: usize = 0; +pub(crate) const DXGI_DEVICE: usize = 1; +pub(crate) const ADAPTER: usize = 2; +pub(crate) const FACTORY: usize = 3; +pub(crate) const OUTPUT: usize = 4; +pub(crate) const HEAP: usize = 5; +pub(crate) const RESOURCE: usize = 6; +pub(crate) const FENCE: usize = 7; +pub(crate) const QUEUE: usize = 8; +pub(crate) const ALLOCATOR: usize = 9; +pub(crate) const LIST: usize = 10; +pub(crate) const DESCRIPTOR_HEAP: usize = 11; +pub(crate) const ROOT_SIGNATURE: usize = 12; +pub(crate) const QUERY_HEAP: usize = 13; +pub(crate) const COMMAND_SIGNATURE: usize = 14; +pub(crate) const PIPELINE: usize = 15; +const KINDS: [&str; 16] = [ + "device", + "DXGI device", + "adapter", + "factory", + "output", + "heap", + "resource", + "fence", + "command queue", + "command allocator", + "command list", + "descriptor heap", + "root signature", + "query heap", + "command signature", + "pipeline state", +]; + +const MAX_SLOTS: usize = 160; + +/// Which unwritten slots have been reported; each is logged once. +static REPORTED: [[AtomicBool; MAX_SLOTS]; KINDS.len()] = + [const { [const { AtomicBool::new(false) }; MAX_SLOTS] }; KINDS.len()]; + +/// Logged once per slot. Wrong for a slot that returns a value instead of +/// an `HRESULT`. +extern "system" fn missing() -> HRESULT { + if !REPORTED[KIND][SLOT].swap(true, Ordering::Relaxed) { + tracing::warn!( + object = KINDS[KIND], + slot = format_args!("{:#x}", SLOT * 8), + "method not implemented" + ); + } + E_NOTIMPL +} + +/// Accepts and ignores (debug-only settings). +pub(crate) extern "system" fn ignore() -> HRESULT { + S_OK +} + +macro_rules! missing { + ($kind:ident; $($slot:literal)*) => { [$(missing::<$kind, $slot> as *const ()),*] }; +} + +/// A table of `N` slots that log and fail; callers fill in what they have. +pub(crate) const fn missing_table() -> [*const (); N] { + let all = missing!(KIND; + 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 + 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 + 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 + 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 + 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 + 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 + 158 159 + ); + assert!(N <= all.len()); + let mut table = [std::ptr::null(); N]; + let mut i = 0; + while i < N { + table[i] = all[i]; + i += 1; + } + table[1] = add_ref as *const (); + table[2] = release as *const (); + table +} + +#[cfg(test)] +pub(crate) fn slot(object: This, offset: usize) -> F { + // SAFETY: `object` is ours and its table has the slot. + let f = unsafe { *(*object).functions.add(offset / 8) }; + // SAFETY: the caller names the slot's signature. + unsafe { std::mem::transmute_copy(&f) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn guids_round_trip_through_text() { + let g = guid( + 0x189819f1, + 0x1db6, + 0x4b57, + [0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7], + ); + assert_eq!(g[..4], [0xf1, 0x19, 0x98, 0x18]); + assert_eq!(guid_text(&g), "189819f1-1db6-4b57-be54-1821339b85f7"); + } +} diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs new file mode 100644 index 0000000..341b0f8 --- /dev/null +++ b/crates/victory-gpu/src/pipeline.rs @@ -0,0 +1,161 @@ +//! Pipeline states. Both descriptions start as on PC: the root signature, +//! then the shader stages (five for graphics, one for compute); only those +//! are read so far. +//! +//! shortcut: the console shader containers are kept, not translated, and +//! the rest of the description is ignored. Translate through the cache +//! here (TODO.md, GPU: pipeline creation, decision 0003). The 32-byte +//! packet after the header stays zero: titles only copy it inline, which +//! our null command-list limits keep from running. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::mem::offset_of; + +use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, PIPELINE, Table, This, guid}; +use crate::resource::PAGEABLE_IIDS; + +const PIPELINE_IIDS: [Iid; 4] = [ + guid( + 0x765a30f3, + 0xf624, + 0x4c6f, + [0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +pub(crate) struct Bytecode { + code: *const u8, + size: usize, +} + +#[repr(C)] +pub(crate) struct GraphicsHead { + root: This, + /// Vertex, pixel, domain, hull, geometry. + stages: [Bytecode; 5], +} + +#[repr(C)] +pub(crate) struct ComputeHead { + root: This, + stage: Bytecode, +} + +#[repr(C)] +struct Pipeline { + object: Object, + packet: [u32; 8], + /// Each stage's container, empty when the stage is unused. + shaders: Vec>, +} +const _: () = assert!(offset_of!(Pipeline, packet) == 0x10); + +fn copy(stage: &Bytecode) -> Vec { + if stage.code.is_null() || stage.size == 0 { + return Vec::new(); + } + // SAFETY: the title passes `size` bytes of shader code. + unsafe { std::slice::from_raw_parts(stage.code, stage.size) }.to_vec() +} + +fn hand_out(shaders: Vec>, iid: *const Iid, out: *mut This) -> HRESULT { + let sizes: Vec = shaders.iter().map(Vec::len).collect(); + tracing::debug!(?sizes, "pipeline state"); + let pipeline = Box::new(Pipeline { + object: Object::new(&FUNCTIONS), + packet: [0; 8], + shaders, + }); + object::hand_out(PIPELINE, pipeline, iid, &PIPELINE_IIDS, out) +} + +/// Device method. +pub(crate) extern "system" fn create_graphics( + _: This, + desc: *const GraphicsHead, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + hand_out(desc.stages.iter().map(copy).collect(), iid, out) +} + +/// Device method. +pub(crate) extern "system" fn create_compute( + _: This, + desc: *const ComputeHead, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + hand_out(vec![copy(&desc.stage)], iid, out) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = object::is(iid, &PIPELINE_IIDS).then_some(this); + object::answer(PIPELINE, iid, found, out) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::(this) +} + +/// IUnknown 3, object 4, device child 1, pipeline 3. +static FUNCTIONS: Table<11> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::{S_OK, slot}; + + #[test] + fn pipelines_keep_their_shaders() { + let (vs, ps) = ([1u8, 2, 3], [4u8; 5]); + let none = || Bytecode { + code: std::ptr::null(), + size: 0, + }; + let desc = GraphicsHead { + root: std::ptr::null(), + stages: [ + Bytecode { + code: vs.as_ptr(), + size: vs.len(), + }, + Bytecode { + code: ps.as_ptr(), + size: ps.len(), + }, + none(), + none(), + none(), + ], + }; + let mut p = std::ptr::null(); + assert_eq!( + create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p), + S_OK + ); + // SAFETY: one of our pipelines. + let shaders = unsafe { &(*p.cast::()).shaders }; + assert_eq!(shaders[0], vs); + assert_eq!(shaders[1], ps); + assert!(shaders[2].is_empty()); + assert_eq!(slot:: u32>(p, 0x10)(p), 0); + } +} diff --git a/crates/victory-gpu/src/query.rs b/crates/victory-gpu/src/query.rs new file mode 100644 index 0000000..b5c109e --- /dev/null +++ b/crates/victory-gpu/src/query.rs @@ -0,0 +1,72 @@ +//! Query heaps. Nothing runs on a GPU yet, so no query ever produces a +//! result; the heap only remembers its description. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, QUERY_HEAP, Table, This, guid}; +use crate::resource::PAGEABLE_IIDS; + +const HEAP_IIDS: [Iid; 4] = [ + guid( + 0x0d9658ae, + 0xed45, + 0x469e, + [0xa6, 0x1d, 0x97, 0x0e, 0xc5, 0x83, 0xca, 0xb4], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct Desc { + kind: u32, + count: u32, + nodes: u32, +} + +#[repr(C)] +struct Heap { + object: Object, + desc: Desc, +} + +/// Device method. +pub(crate) extern "system" fn create( + _: This, + desc: *const Desc, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + tracing::debug!(?desc, "query heap"); + let heap = Box::new(Heap { + object: Object::new(&FUNCTIONS), + desc, + }); + object::hand_out(QUERY_HEAP, heap, iid, &HEAP_IIDS, out) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer( + QUERY_HEAP, + iid, + object::is(iid, &HEAP_IIDS).then_some(this), + out, + ) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::(this) +} + +/// IUnknown 3, object 4, device child 1. +static FUNCTIONS: Table<8> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + Table(f) +}; diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs new file mode 100644 index 0000000..c537a3f --- /dev/null +++ b/crates/victory-gpu/src/queue.rs @@ -0,0 +1,220 @@ +//! Command queues. Nothing is executed yet: submitted lists are dropped and +//! fence signals complete at once, as if the GPU were infinitely fast. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, QUEUE, S_OK, Table, This, guid}; +use crate::resource::PAGEABLE_IIDS; + +const QUEUE_IIDS: [Iid; 4] = [ + guid( + 0x0ec870a6, + 0x5d7e, + 0x4c22, + [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct QueueDesc { + kind: u32, + priority: i32, + flags: u32, + nodes: u32, +} + +/// The title reads the list type right after the header. +#[repr(C)] +struct Queue { + object: Object, + kind: u32, + desc: QueueDesc, +} +const _: () = assert!(std::mem::offset_of!(Queue, kind) == 0x10); + +fn queue<'a>(this: This) -> &'a Queue { + // SAFETY: called from queue methods only. + unsafe { &*this.cast::() } +} + +pub(crate) extern "system" fn create( + _: This, + desc: *const QueueDesc, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + tracing::debug!(?desc, "command queue"); + let queue = Box::new(Queue { + object: Object::new(&FUNCTIONS), + kind: desc.kind, + desc, + }); + object::hand_out(QUEUE, queue, iid, &QUEUE_IIDS, out) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer( + QUEUE, + iid, + object::is(iid, &QUEUE_IIDS).then_some(this), + out, + ) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::(this) +} + +/// Runs the lists' host lists and waits for them (decision 0007). +extern "system" fn execute(_: This, count: u32, lists: *const This) { + if lists.is_null() { + return; + } + #[cfg(windows)] + if let Some(host) = crate::host::host() { + // SAFETY: the title passes `count` lists. + let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) }; + let host_lists: Vec<_> = lists + .iter() + .filter_map(|&l| crate::list::host_list(l)) + .collect(); + host.execute(&host_lists); + return; + } + static ONCE: AtomicBool = AtomicBool::new(false); + if !ONCE.swap(true, Ordering::Relaxed) { + tracing::warn!(count, "command lists submitted; no host GPU runs them"); + } +} + +/// The start of a present plane: frame token, then the plane's resources. +#[repr(C)] +pub(crate) struct Plane { + token: u64, + count: u32, + resources: *const This, +} +/// Markers and events only matter to profilers. +extern "system" fn marker(_: This) {} +extern "system" fn signal(_: This, fence: This, value: u64) -> HRESULT { + if fence.is_null() { + return E_INVALIDARG; + } + crate::fence::signal(fence, value) +} +/// Nothing runs on the queue, so waiting for a fence never blocks it. +extern "system" fn wait(_: This, fence: This, _value: u64) -> HRESULT { + if fence.is_null() { E_INVALIDARG } else { S_OK } +} +/// Ticks per second of GPU timestamps; none are written yet. +extern "system" fn timestamp_frequency(_: This, out: *mut u64) -> HRESULT { + if out.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null. + unsafe { out.write(100_000_000) }; + S_OK +} +/// Shows the first plane's first resource in our window. +/// +/// shortcut: one plane, no scaling or placement, the source expected in +/// the common state. +extern "system" fn present( + _: This, + planes: u32, + plane_parameters: *const Plane, + _parameters: *const u8, +) -> HRESULT { + static FRAMES: AtomicU64 = AtomicU64::new(0); + let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; + if frame.is_power_of_two() { + tracing::info!(frame, "frame presented"); + } + #[cfg(windows)] + if planes > 0 + // SAFETY: the title passes `planes` plane descriptions. + && let Some(plane) = unsafe { plane_parameters.as_ref() } + && plane.count > 0 + && !plane.resources.is_null() + // SAFETY: the plane lists `count` resources. + && let resource = unsafe { *plane.resources } + && let Some(texture) = crate::resource::host_resource(resource) + && let Some(host) = crate::host::host() + { + const COPY_SOURCE: u32 = 0x800; + let state = crate::resource::host_transition(resource, COPY_SOURCE) + .map_or(COPY_SOURCE, |(_, before)| before); + host.present(texture, state); + crate::resource::host_transition(resource, state); + } + #[cfg(not(windows))] + let _ = (planes, plane_parameters); + S_OK +} +extern "system" fn desc(this: This, out: *mut QueueDesc) { + if !out.is_null() { + // SAFETY: checked non-null; the title passes room for a description. + unsafe { out.write(queue(this).desc) }; + } +} + +/// IUnknown 3, object 4, device child 1, queue 26 (12 as on PC, then +/// console ones). +static FUNCTIONS: Table<34> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + f[10] = execute as *const (); // 0x50 + f[11] = marker as *const (); // 0x58 set marker + f[12] = marker as *const (); // 0x60 begin event + f[13] = marker as *const (); // 0x68 end event + f[14] = signal as *const (); // 0x70 + f[15] = wait as *const (); // 0x78 + f[16] = timestamp_frequency as *const (); // 0x80 + f[26] = desc as *const (); // 0xd0 + f[30] = present as *const (); // 0xf0 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::slot; + + #[test] + fn queue_signals_complete_at_once() { + let null = std::ptr::null(); + let desc = QueueDesc { + kind: 0, + priority: 0, + flags: 0, + nodes: 0, + }; + let mut q = null; + assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK); + // SAFETY: the title reads the type at +0x10. + assert_eq!(unsafe { q.cast::().add(0x10).cast::().read() }, 0); + let mut fence = null; + let fence_iid = &crate::fence::FENCE_IIDS[0]; + assert_eq!( + crate::fence::create(null, 0, 0, fence_iid, &mut fence), + S_OK + ); + let signal = slot:: HRESULT>(q, 0x70); + assert_eq!(signal(q, fence, 7), S_OK); + assert_eq!( + slot:: u64>(fence, 0x40)(fence), + 7 + ); + assert_eq!(slot:: u32>(q, 0x10)(q), 0); + } +} diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs new file mode 100644 index 0000000..28ed947 --- /dev/null +++ b/crates/victory-gpu/src/resource.rs @@ -0,0 +1,1165 @@ +//! Heaps, committed and placed resources, and resource sizes. +//! +//! shortcut: heaps and resources are plain host memory and a resource's +//! GPU address is its CPU address, as on the console. Rewrite them on host +//! D3D12 heaps and resources once the command-stream decoder needs the host +//! GPU to see them (TODO.md, GPU). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::alloc::{Layout, alloc_zeroed, dealloc}; +use std::ffi::c_void; +use std::ptr::NonNull; + +use crate::object::{ + self, E_INVALIDARG, E_OUTOFMEMORY, HEAP, HRESULT, Iid, Object, RESOURCE, S_OK, Table, This, + guid, +}; + +/// The interfaces every device child also answers for. +pub(crate) const PAGEABLE_IIDS: [Iid; 3] = [ + guid( + 0x63ee58fb, + 0x1268, + 0x4835, + [0x86, 0xda, 0xf0, 0x08, 0xce, 0x62, 0xf0, 0xd6], + ), + guid( + 0x905db94b, + 0xa00c, + 0x4140, + [0x9d, 0xf5, 0x2b, 0x64, 0xca, 0x9e, 0xa3, 0x57], + ), + guid( + 0xc4fec28f, + 0x7966, + 0x4e95, + [0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8], + ), +]; +const HEAP_IIDS: [Iid; 4] = [ + guid( + 0x6b3b2502, + 0x6e51, + 0x45b3, + [0x90, 0xee, 0x98, 0x84, 0x26, 0x5e, 0x8d, 0xf3], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; +const RESOURCE_IIDS: [Iid; 4] = [ + guid( + 0x696442be, + 0xa72e, + 0x4059, + [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +const KIB_64: u64 = 64 << 10; +const MIB_4: u64 = 4 << 20; + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct HeapProperties { + kind: u32, + cpu_pages: u32, + pool: u32, + creation_nodes: u32, + visible_nodes: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct HeapDesc { + size: u64, + properties: HeapProperties, + alignment: u64, + flags: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct ResourceDesc { + dimension: u32, + alignment: u64, + width: u64, + height: u32, + depth_or_array_size: u16, + mip_levels: u16, + format: u32, + sample_count: u32, + sample_quality: u32, + layout: u32, + flags: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct AllocationInfo { + size: u64, + alignment: u64, +} + +const _: () = assert!(size_of::() == 20); +const _: () = assert!(size_of::() == 48); +const _: () = assert!(size_of::() == 56); + +const BUFFER: u32 = 1; +const TEXTURE_3D: u32 = 4; + +/// Bytes per element and the element's width in texels (4 for block +/// compression), by DXGI format number. `None` for 1-bit, video and +/// console-only formats. +fn element(format: u32) -> Option<(u64, u64)> { + Some(match format { + 1..=4 => (16, 1), + 5..=8 => (12, 1), + 9..=22 => (8, 1), + 23..=47 | 67 | 87..=93 => (4, 1), + 48..=59 | 68 | 69 | 85 | 86 | 115 => (2, 1), + 60..=65 => (1, 1), + 70..=72 | 79..=81 => (8, 4), + 73..=78 | 82..=84 | 94..=99 => (16, 4), + _ => return None, + }) +} + +/// Bytes and alignment a resource takes in our layout: every mip of every +/// array slice and sample, packed, rounded up to 64 KiB. +/// +/// shortcut: an unpadded bound, not the console's tiled layout. Titles that +/// write console-tiled data straight into memory may need more; revisit with +/// the texture layouts (TODO.md, formats). +fn footprint(desc: &ResourceDesc) -> Option { + let bytes = if desc.dimension == BUFFER { + desc.width + } else { + let (element, block) = element(desc.format)?; + let (depth, slices) = if desc.dimension == TEXTURE_3D { + (u64::from(desc.depth_or_array_size), 1) + } else { + (1, u64::from(desc.depth_or_array_size)) + }; + let height = u64::from(desc.height); + let mips = mip_count(desc); + let mut chain = 0u64; + for mip in 0..mips.min(64) { + let w = (desc.width >> mip).max(1).div_ceil(block); + let h = (height >> mip).max(1).div_ceil(block); + let d = (depth >> mip).max(1); + chain = chain.checked_add(w.checked_mul(h)?.checked_mul(d)?.checked_mul(element)?)?; + } + chain + .checked_mul(slices)? + .checked_mul(u64::from(desc.sample_count.max(1)))? + }; + if bytes == 0 { + return None; + } + let minimum = if desc.sample_count > 1 { MIB_4 } else { KIB_64 }; + let alignment = desc.alignment.max(minimum); + if !alignment.is_power_of_two() { + return None; + } + Some(AllocationInfo { + size: bytes.checked_next_multiple_of(KIB_64)?, + alignment, + }) +} + +/// Mip levels, the full chain for 0. +fn mip_count(desc: &ResourceDesc) -> u32 { + let depth = if desc.dimension == TEXTURE_3D { + u64::from(desc.depth_or_array_size) + } else { + 1 + }; + match desc.mip_levels { + 0 => { + 64 - desc + .width + .max(u64::from(desc.height)) + .max(depth) + .max(1) + .leading_zeros() + } + n => u32::from(n), + } +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct PlacedFootprint { + pub(crate) offset: u64, + format: u32, + width: u32, + height: u32, + depth: u32, + row_pitch: u32, +} + +impl PlacedFootprint { + /// The bytes it spans in a buffer: every row pitched but the last. + pub(crate) fn bytes(&self) -> Option { + let (element, block) = element(self.format)?; + let lines = u64::from(self.height).div_ceil(block) * u64::from(self.depth); + let last = u64::from(self.width).div_ceil(block) * element; + Some(u64::from(self.row_pitch) * lines.saturating_sub(1) + last) + } +} +const _: () = assert!(size_of::() == 32); + +const NO_FOOTPRINT: PlacedFootprint = PlacedFootprint { + offset: u64::MAX, + format: 0, + width: 0, + height: 0, + depth: 0, + row_pitch: 0, +}; + +/// One subresource's size in an upload buffer: footprint (offset 0), rows +/// and bytes per row. Planes of depth-stencil formats are not told apart. +fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, u64)> { + const PITCH: u64 = 256; + if desc.dimension == BUFFER { + let footprint = PlacedFootprint { + offset: 0, + format: 0, + width: u32::try_from(desc.width).ok()?, + height: 1, + depth: 1, + row_pitch: u32::try_from(desc.width.next_multiple_of(PITCH)).ok()?, + }; + return (index == 0).then_some((footprint, 1, desc.width)); + } + let mips = mip_count(desc); + let slices = if desc.dimension == TEXTURE_3D { + 1 + } else { + u32::from(desc.depth_or_array_size).max(1) + }; + let (mip, slice) = (index % mips, index / mips); + if slice >= slices { + return None; + } + let (element, block) = element(desc.format)?; + let width = (desc.width >> mip).max(1).next_multiple_of(block); + let height = (u64::from(desc.height) >> mip) + .max(1) + .next_multiple_of(block); + let depth = if desc.dimension == TEXTURE_3D { + (u32::from(desc.depth_or_array_size) >> mip).max(1) + } else { + 1 + }; + let row_size = width / block * element; + let footprint = PlacedFootprint { + offset: 0, + format: desc.format, + width: u32::try_from(width).ok()?, + height: u32::try_from(height).ok()?, + depth, + row_pitch: u32::try_from(row_size.next_multiple_of(PITCH)).ok()?, + }; + Some((footprint, u32::try_from(height / block).ok()?, row_size)) +} + +/// Device method: where each subresource goes in an upload buffer, rows +/// 256-byte and subresources 512-byte aligned, as on PC. Unknown sizes give +/// the documented all-ones values. +pub(crate) extern "system" fn copyable_footprints( + _: This, + desc: *const ResourceDesc, + first: u32, + count: u32, + base: u64, + layouts: *mut PlacedFootprint, + rows: *mut u32, + row_sizes: *mut u64, + total: *mut u64, +) { + const PLACEMENT: u64 = 512; + // SAFETY: the title passes a description (null is tolerated). + let desc = unsafe { desc.as_ref() }; + let mut end = base; + let mut known = desc.is_some(); + for i in 0..count { + let one = desc.and_then(|d| subresource(d, first + i)); + let (layout, row_count, row_size) = match one { + Some((mut footprint, row_count, row_size)) => { + footprint.offset = end.next_multiple_of(PLACEMENT); + let pitch = u64::from(footprint.row_pitch); + let lines = u64::from(row_count) * u64::from(footprint.depth); + end = footprint.offset + pitch * lines.saturating_sub(1) + row_size; + (footprint, row_count, row_size) + } + None => { + known = false; + (NO_FOOTPRINT, u32::MAX, u64::MAX) + } + }; + let i = i as usize; + // SAFETY: each output is null or holds `count` entries. + unsafe { + if !layouts.is_null() { + layouts.add(i).write(layout); + } + if !rows.is_null() { + rows.add(i).write(row_count); + } + if !row_sizes.is_null() { + row_sizes.add(i).write(row_size); + } + } + } + if !known { + tracing::warn!(?desc, "no footprint for this resource"); + } + if !total.is_null() { + // SAFETY: checked non-null. + unsafe { total.write(if known { end - base } else { u64::MAX }) }; + } +} + +/// Device method: the footprint of resources placed one after another. +/// Returns a 16-byte value, through a hidden first argument. Invalid input +/// gives the documented size `u64::MAX`. +pub(crate) extern "system" fn allocation_info( + out: *mut AllocationInfo, + _: This, + _visible: u32, + count: u32, + descs: *const ResourceDesc, +) -> *mut AllocationInfo { + let descs = if descs.is_null() { + &[][..] + } else { + // SAFETY: the title passes `count` descriptions. + unsafe { std::slice::from_raw_parts(descs, count as usize) } + }; + let mut total = AllocationInfo { + size: 0, + alignment: KIB_64, + }; + for desc in descs { + let Some(one) = footprint(desc) else { + tracing::warn!(?desc, "no size for this resource"); + total = AllocationInfo { + size: u64::MAX, + alignment: 0, + }; + break; + }; + total.size = total.size.next_multiple_of(one.alignment) + one.size; + total.alignment = total.alignment.max(one.alignment); + } + // SAFETY: the caller passes room for the value. + unsafe { out.write(total) }; + out +} + +/// Zeroed host memory standing in for GPU memory. +pub(crate) struct Memory { + ptr: NonNull, + layout: Layout, +} + +impl Memory { + /// `size` zeroed bytes aligned to `alignment` (a power of two). + pub(crate) fn zeroed(size: u64, alignment: u64) -> Result { + Memory::new(AllocationInfo { size, alignment }) + } + + pub(crate) fn address(&self) -> u64 { + self.ptr.as_ptr() as u64 + } + + fn new(info: AllocationInfo) -> Result { + let layout = usize::try_from(info.size) + .ok() + .zip(usize::try_from(info.alignment).ok()) + .filter(|&(size, _)| size > 0) + .and_then(|(size, align)| Layout::from_size_align(size, align).ok()) + .ok_or(E_INVALIDARG)?; + // SAFETY: the size is non-zero. + let ptr = NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(E_OUTOFMEMORY)?; + Ok(Memory { ptr, layout }) + } +} + +impl Drop for Memory { + fn drop(&mut self) { + // SAFETY: allocated in `new` with this layout. + unsafe { dealloc(self.ptr.as_ptr(), self.layout) }; + } +} + +#[repr(C)] +struct Heap { + object: Object, + desc: HeapDesc, + memory: Memory, +} + +pub(crate) extern "system" fn create_heap( + _: This, + desc: *const HeapDesc, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + tracing::debug!( + size = desc.size, + kind = desc.properties.kind, + flags = format_args!("{:#x}", desc.flags), + "heap" + ); + if desc.alignment != 0 && !desc.alignment.is_power_of_two() { + return E_INVALIDARG; + } + let info = AllocationInfo { + size: desc.size, + alignment: desc.alignment.max(KIB_64), + }; + let memory = match Memory::new(info) { + Ok(memory) => memory, + Err(hr) => return hr, + }; + let heap = Box::new(Heap { + object: Object::new(&HEAP_FUNCTIONS), + desc, + memory, + }); + object::hand_out(HEAP, heap, iid, &HEAP_IIDS, out) +} + +extern "system" fn heap_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer(HEAP, iid, object::is(iid, &HEAP_IIDS).then_some(this), out) +} +extern "system" fn heap_release(this: This) -> u32 { + object::release_boxed::(this) +} +extern "system" fn heap_desc(this: This, out: *mut HeapDesc) { + if !out.is_null() { + // SAFETY: `this` is a heap; the title passes room for a description. + unsafe { out.write((*this.cast::()).desc) }; + } +} + +/// A resource's memory: its own, or a range of a heap it holds a reference +/// to. +enum Backing { + Committed(Memory), + Placed { heap: This, offset: u64 }, +} + +impl Drop for Backing { + fn drop(&mut self) { + if let Backing::Placed { heap, .. } = *self { + heap_release(heap); + } + } +} + +#[repr(C)] +struct Resource { + object: Object, + desc: ResourceDesc, + heap: HeapProperties, + heap_flags: u32, + backing: Backing, + /// Textures also live on the host GPU (decision 0007); buffers do not + /// yet. + #[cfg(windows)] + host: Option, + /// The state the host texture is in. The title's barriers name console + /// states (looser than the host's), so we transition from this one. + #[cfg(windows)] + host_state: std::sync::atomic::AtomicU32, +} + +/// Moves the host texture to `wanted` (a host texture state); the host +/// resource and the state it leaves, if that is a change. +#[cfg(windows)] +pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u32)> { + use windows::core::Interface; + let r = resource(this); + let host = r.host.as_ref()?; + let before = r + .host_state + .swap(wanted, std::sync::atomic::Ordering::Relaxed); + (before != wanted).then(|| (host.as_raw(), before)) +} + +/// The host GPU's copy of a title resource, if it has one. +#[cfg(windows)] +pub(crate) fn host_resource<'a>( + this: This, +) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + if this.is_null() { + return None; + } + resource(this).host.as_ref() +} + +/// A host texture like the title's: same description, in GPU memory, +/// without the console's layout and flags. +#[cfg(windows)] +fn host_texture( + desc: &ResourceDesc, + state: u32, + clear: *const c_void, +) -> Option { + use windows::Win32::Graphics::Direct3D12::*; + const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access + if desc.dimension == BUFFER { + return None; + } + let host = crate::host::host()?; + let mut d = *desc; + d.layout = 0; + d.alignment = 0; + d.flags &= PC_FLAGS; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let mut texture: Option = None; + // SAFETY: the description has the host layout (checked size, same + // fields); the out pointer is ours. + let made = unsafe { + host.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + (&raw const d).cast(), + D3D12_RESOURCE_STATES(crate::host::texture_state(state) as i32), + // The same layout: format, then color or depth and stencil. + (!clear.is_null()).then_some(clear.cast()), + &mut texture, + ) + }; + if let Err(e) = made { + tracing::warn!(error = %e, desc = ?d, "no host texture"); + } + texture +} + +/// A buffer's host memory and size; `None` for textures. +pub(crate) fn buffer_bytes(this: This) -> Option<(*mut u8, u64)> { + if this.is_null() { + return None; + } + let r = resource(this); + (r.desc.dimension == BUFFER).then(|| (r.data(), r.desc.width)) +} + +impl Resource { + fn data(&self) -> *mut u8 { + match self.backing { + Backing::Committed(ref memory) => memory.ptr.as_ptr(), + // SAFETY: placement checked the range lies inside the heap. + Backing::Placed { heap, offset } => unsafe { + (*heap.cast::()) + .memory + .ptr + .as_ptr() + .add(offset as usize) + }, + } + } +} + +fn resource<'a>(this: This) -> &'a Resource { + // SAFETY: called from resource methods only. + unsafe { &*this.cast::() } +} + +// The creation methods' own arguments, passed on. +#[allow(clippy::too_many_arguments)] +fn hand_out_resource( + desc: ResourceDesc, + heap: HeapProperties, + heap_flags: u32, + backing: Backing, + state: u32, + clear: *const c_void, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + #[cfg(not(windows))] + let _ = (state, clear); + let resource = Box::new(Resource { + object: Object::new(&RESOURCE_FUNCTIONS), + desc, + heap, + heap_flags, + backing, + #[cfg(windows)] + host: host_texture(&desc, state, clear), + #[cfg(windows)] + host_state: crate::host::texture_state(state).into(), + }); + object::hand_out(RESOURCE, resource, iid, &RESOURCE_IIDS, out) +} + +pub(crate) extern "system" fn create_committed( + _: This, + heap: *const HeapProperties, + heap_flags: u32, + desc: *const ResourceDesc, + state: u32, + clear: *const c_void, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes both descriptions (null is tolerated). + let (Some(&heap), Some(&desc)) = (unsafe { (heap.as_ref(), desc.as_ref()) }) else { + return E_INVALIDARG; + }; + let Some(info) = footprint(&desc) else { + tracing::warn!(?desc, "no size for this resource"); + return E_INVALIDARG; + }; + tracing::debug!( + dimension = desc.dimension, + size = info.size, + heap = heap.kind, + "committed resource" + ); + let memory = match Memory::new(info) { + Ok(memory) => memory, + Err(hr) => return hr, + }; + hand_out_resource( + desc, + heap, + heap_flags, + Backing::Committed(memory), + state, + clear, + iid, + out, + ) +} + +pub(crate) extern "system" fn create_placed( + _: This, + heap: This, + offset: u64, + desc: *const ResourceDesc, + state: u32, + clear: *const c_void, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + if heap.is_null() { + return E_INVALIDARG; + } + // SAFETY: the title passes one of our heaps. + let h = unsafe { &*heap.cast::() }; + let fits = footprint(&desc).is_some_and(|info| { + offset.is_multiple_of(info.alignment) + && offset + .checked_add(info.size) + .is_some_and(|end| end <= h.desc.size) + }); + if !fits { + tracing::warn!( + ?desc, + offset, + heap = h.desc.size, + "placed resource does not fit" + ); + return E_INVALIDARG; + } + object::add_ref(heap); + let backing = Backing::Placed { heap, offset }; + hand_out_resource( + desc, + h.desc.properties, + h.desc.flags, + backing, + state, + clear, + iid, + out, + ) +} + +extern "system" fn resource_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer( + RESOURCE, + iid, + object::is(iid, &RESOURCE_IIDS).then_some(this), + out, + ) +} +extern "system" fn resource_release(this: This) -> u32 { + object::release_boxed::(this) +} +/// Memory is always mapped (subresources are not told apart yet); a null +/// `out` only asks for residency. +extern "system" fn map(this: This, _sub: u32, _read: *const c_void, out: *mut *mut u8) -> HRESULT { + if !out.is_null() { + // SAFETY: checked non-null; the title passes room for a pointer. + unsafe { out.write(resource(this).data()) }; + } + S_OK +} +extern "system" fn unmap(_: This, _sub: u32, _written: *const c_void) {} +extern "system" fn resource_desc(this: This, out: *mut ResourceDesc) { + if !out.is_null() { + // SAFETY: checked non-null; the title passes room for a description. + unsafe { out.write(resource(this).desc) }; + } +} +extern "system" fn gpu_address(this: This) -> u64 { + resource(this).data() as u64 +} +extern "system" fn heap_properties( + this: This, + properties: *mut HeapProperties, + flags: *mut u32, +) -> HRESULT { + let r = resource(this); + // SAFETY: either pointer may be null; otherwise the title passes room. + unsafe { + if let Some(p) = properties.as_mut() { + *p = r.heap; + } + if let Some(f) = flags.as_mut() { + *f = r.heap_flags; + } + } + S_OK +} + +/// IUnknown 3, object 4, device child 1, heap 1. +static HEAP_FUNCTIONS: Table<9> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = heap_query as *const (); + f[2] = heap_release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + f[8] = heap_desc as *const (); // 0x40 + Table(f) +}; + +/// IUnknown 3, object 4, device child 1, resource 10 (7 as on PC, then 3 +/// console ones). +static RESOURCE_FUNCTIONS: Table<18> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = resource_query as *const (); + f[2] = resource_release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + f[8] = map as *const (); // 0x40 + f[9] = unmap as *const (); // 0x48 + f[10] = resource_desc as *const (); // 0x50 + f[11] = gpu_address as *const (); // 0x58 + f[14] = heap_properties as *const (); // 0x70 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::slot; + + type Release = extern "system" fn(This) -> u32; + type Map = extern "system" fn(This, u32, *const c_void, *mut *mut u8) -> HRESULT; + type Address = extern "system" fn(This) -> u64; + + const PROPERTIES: HeapProperties = HeapProperties { + kind: 1, + cpu_pages: 0, + pool: 0, + creation_nodes: 0, + visible_nodes: 0, + }; + + fn buffer(width: u64) -> ResourceDesc { + ResourceDesc { + dimension: BUFFER, + alignment: 0, + width, + height: 1, + depth_or_array_size: 1, + mip_levels: 1, + format: 0, + sample_count: 1, + sample_quality: 0, + layout: 1, + flags: 0, + } + } + + fn texture(width: u64, height: u32, format: u32, mips: u16) -> ResourceDesc { + ResourceDesc { + dimension: 3, + width, + height, + format, + mip_levels: mips, + layout: 0, + ..buffer(0) + } + } + + fn heap(size: u64) -> This { + let desc = HeapDesc { + size, + properties: PROPERTIES, + alignment: 0, + flags: 0, + }; + let mut heap = std::ptr::null(); + assert_eq!( + create_heap(std::ptr::null(), &desc, &HEAP_IIDS[0], &mut heap), + S_OK + ); + heap + } + + #[test] + fn heaps_are_zeroed_aligned_memory() { + let heap = heap(1 << 20); + // SAFETY: a heap we just made. + let memory = unsafe { &(*heap.cast::()).memory }; + assert_eq!(memory.ptr.as_ptr() as u64 % KIB_64, 0); + let mut back = std::mem::MaybeUninit::::uninit(); + slot::(heap, 0x40)(heap, back.as_mut_ptr()); + // SAFETY: written above. + assert_eq!(unsafe { back.assume_init() }.size, 1 << 20); + assert_eq!(slot::(heap, 0x10)(heap), 0); + + let bad = HeapDesc { + size: 1 << 20, + properties: PROPERTIES, + alignment: 3, + flags: 0, + }; + let mut out = std::ptr::null(); + assert_eq!( + create_heap(std::ptr::null(), &bad, &HEAP_IIDS[0], &mut out), + E_INVALIDARG + ); + } + + #[test] + fn sizes_cover_every_mip() { + let size = |d: &ResourceDesc| footprint(d).map(|i| i.size); + assert_eq!(size(&buffer(256)), Some(KIB_64)); + // 256x256 RGBA8, full chain: 4/3 of 256 KiB, rounded up. + assert_eq!(size(&texture(256, 256, 28, 0)), Some(384 << 10)); + // BC1 is 8 bytes per 4x4 block: 1024x1024, one mip = 512 KiB. + assert_eq!(size(&texture(1024, 1024, 71, 1)), Some(512 << 10)); + assert_eq!(size(&texture(16, 16, 66, 1)), None, "1-bit format"); + + let mut info = AllocationInfo { + size: 0, + alignment: 0, + }; + let descs = [buffer(100), texture(256, 256, 28, 0)]; + allocation_info(&mut info, std::ptr::null(), 0, 2, descs.as_ptr()); + assert_eq!( + info, + AllocationInfo { + size: (64 + 384) << 10, + alignment: KIB_64 + } + ); + allocation_info(&mut info, std::ptr::null(), 0, 1, &texture(1, 1, 999, 1)); + assert_eq!(info.size, u64::MAX); + } + + #[test] + fn upload_footprints_follow_the_pc_rules() { + let null = std::ptr::null(); + let mut layouts = [NO_FOOTPRINT; 2]; + let (mut rows, mut sizes, mut total) = ([0; 2], [0; 2], 0); + let mut footprints = |desc: &ResourceDesc, first, count| { + let (l, r, s) = (layouts.as_mut_ptr(), rows.as_mut_ptr(), sizes.as_mut_ptr()); + copyable_footprints(null, desc, first, count, 0, l, r, s, &mut total); + (layouts, rows, sizes, total) + }; + // 100x60 RGBA8, 2 mips: 400-byte rows pitched to 512. + let (l, r, s, t) = footprints(&texture(100, 60, 28, 2), 0, 2); + assert_eq!((l[0].row_pitch, r[0], s[0]), (512, 60, 400)); + // Mip 1 (50x30, 200-byte rows) starts after 59 pitched rows and one + // packed row, rounded up to 512. + assert_eq!(l[1].offset, (512 * 59 + 400u64).next_multiple_of(512)); + assert_eq!((l[1].width, l[1].height, r[1]), (50, 30, 30)); + assert_eq!(t, l[1].offset + 256 * 29 + 200); + // BC1: rows of 4x4 blocks, 8 bytes each. + let (_, r, s, _) = footprints(&texture(64, 64, 71, 1), 0, 1); + assert_eq!((r[0], s[0]), (16, 128)); + let (_, _, _, t) = footprints(&texture(64, 64, 71, 1), 1, 1); + assert_eq!(t, u64::MAX, "no second subresource"); + } + + /// A 4x4 texture filled from a title buffer through our list and queue, + /// then read back from the host GPU. + #[cfg(windows)] + #[test] + fn buffer_data_reaches_the_host_texture() { + use windows::Win32::Graphics::Direct3D12::*; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let null = std::ptr::null(); + let iid = &RESOURCE_IIDS[0]; + const COPY_DEST: u32 = 0x400; + let (mut image, mut source) = (null, null); + let rgba = texture(4, 4, 28, 1); + assert_eq!( + create_committed( + null, + &PROPERTIES, + 0, + &rgba, + COPY_DEST, + null.cast(), + iid, + &mut image + ), + S_OK + ); + assert_eq!( + create_committed( + null, + &PROPERTIES, + 0, + &buffer(1024), + 0, + null.cast(), + iid, + &mut source + ), + S_OK + ); + let (data, _) = buffer_bytes(source).unwrap(); + // SAFETY: the buffer holds 1024 bytes. + let bytes = unsafe { std::slice::from_raw_parts_mut(data, 1024) }; + for (i, b) in bytes.iter_mut().enumerate() { + *b = (i % 251) as u8; + } + + let queue_iid = guid( + 0x0ec870a6, + 0x5d7e, + 0x4c22, + [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed], + ); + let allocator_iid = guid( + 0x6102dee4, + 0xaf59, + 0x4b09, + [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24], + ); + let list_iid = guid( + 0x5b160d0f, + 0xac1b, + 0x4185, + [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55], + ); + let (mut queue, mut allocator, mut list) = (null, null, null); + let queue_desc = [0u32; 4]; + assert_eq!( + crate::queue::create(null, queue_desc.as_ptr().cast(), &queue_iid, &mut queue), + S_OK + ); + assert_eq!( + crate::list::create_allocator(null, 0, &allocator_iid, &mut allocator), + S_OK + ); + assert_eq!( + crate::list::create_list(null, 0, 0, allocator, null, &list_iid, &mut list), + S_OK + ); + + #[repr(C)] + struct Location { + resource: This, + kind: u32, + footprint: PlacedFootprint, + } + let rows = PlacedFootprint { + offset: 0, + format: 28, + width: 4, + height: 4, + depth: 1, + row_pitch: 256, + }; + let to = Location { + resource: image, + kind: 0, + footprint: PlacedFootprint { offset: 0, ..rows }, + }; + let from = Location { + resource: source, + kind: 1, + footprint: rows, + }; + type Copy = + extern "system" fn(This, *const Location, u32, u32, u32, *const Location, *const u8); + slot::(list, 0x80)(list, &to, 0, 0, 0, &from, null.cast()); + slot:: HRESULT>(list, 0x48)(list); + slot::(queue, 0x50)(queue, 1, &list); + + // Read the host texture back into a readback buffer. + let readback_heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let readback_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut readback: Option = None; + // SAFETY: plain creation of a readback buffer. + unsafe { + host.device + .CreateCommittedResource( + &readback_heap, + D3D12_HEAP_FLAG_NONE, + &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ) + .unwrap(); + } + let readback = readback.unwrap(); + let host_image = host_resource(image).unwrap(); + let back = host.new_list().unwrap(); + let (_, before) = host_transition(image, 0x800).unwrap(); + use windows::core::Interface; + let out_to = Location { + resource: readback.as_raw().cast_const().cast(), + kind: 1, + footprint: rows, + }; + let out_from = Location { + resource: host_image.as_raw().cast_const().cast(), + kind: 0, + footprint: to.footprint, + }; + // SAFETY: an open list, live resources, locations in the host layout. + unsafe { + back.list.ResourceBarrier(&[crate::host::transition( + host_image, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + back.list.CopyTextureRegion( + (&raw const out_to).cast(), + 0, + 0, + 0, + (&raw const out_from).cast(), + None, + ); + } + back.close(); + host.execute(&[&back]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: the copy finished (execute waits); the buffer is 1024 bytes. + let read = unsafe { + readback + .Map( + 0, + Some(&D3D12_RANGE { + Begin: 0, + End: 1024, + }), + Some(&mut mapped), + ) + .unwrap(); + std::slice::from_raw_parts(mapped.cast::(), 1024) + }; + for row in 0..4 { + let at = row * 256; + assert_eq!(read[at..at + 16], bytes[at..at + 16], "row {row}"); + } + } + + #[test] + fn committed_and_placed_resources_map_at_their_gpu_address() { + let null = std::ptr::null(); + let mut committed = null; + let hr = create_committed( + null, + &PROPERTIES, + 0, + &buffer(256), + 0, + null.cast(), + &RESOURCE_IIDS[0], + &mut committed, + ); + assert_eq!(hr, S_OK); + let mut data = std::ptr::null_mut(); + assert_eq!( + slot::(committed, 0x40)(committed, 0, null.cast(), &mut data), + S_OK + ); + assert_eq!(slot::
(committed, 0x58)(committed), data as u64); + // SAFETY: the buffer is at least 256 zeroed bytes. + assert_eq!(unsafe { *data.add(255) }, 0); + assert_eq!(slot::(committed, 0x10)(committed), 0); + + let heap = heap(4 * KIB_64); + let place = |offset, desc: &ResourceDesc, out: &mut This| { + create_placed( + null, + heap, + offset, + desc, + 0, + null.cast(), + &RESOURCE_IIDS[0], + out, + ) + }; + let mut placed = null; + assert_eq!(place(KIB_64, &buffer(KIB_64), &mut placed), S_OK); + // SAFETY: a heap we made. + let base = unsafe { (*heap.cast::()).memory.ptr.as_ptr() } as u64; + assert_eq!(slot::
(placed, 0x58)(placed), base + KIB_64); + let mut other = null; + assert_eq!( + place(4 * KIB_64, &buffer(1), &mut other), + E_INVALIDARG, + "past the end" + ); + assert_eq!( + place(100, &buffer(1), &mut other), + E_INVALIDARG, + "misaligned" + ); + // The resource keeps the heap alive. + assert_eq!(slot::(heap, 0x10)(heap), 1); + assert_eq!(slot::(placed, 0x10)(placed), 0); + } +} diff --git a/crates/victory-gpu/src/root.rs b/crates/victory-gpu/src/root.rs new file mode 100644 index 0000000..ce25137 --- /dev/null +++ b/crates/victory-gpu/src/root.rs @@ -0,0 +1,196 @@ +//! Root signatures. +//! +//! Serializing goes to the host's `D3D12SerializeRootSignature`: the +//! description is laid out as on PC, and the blob it returns works as the +//! console's, whose two methods sit in the same slots. The console's own +//! flags (bit 24 and up) are dropped first. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::c_void; +use std::sync::OnceLock; + +use crate::object::{ + self, E_INVALIDARG, E_NOTIMPL, HRESULT, Iid, Object, ROOT_SIGNATURE, Table, This, guid, +}; +use crate::resource::PAGEABLE_IIDS; + +const ROOT_SIGNATURE_IIDS: [Iid; 3] = [ + guid( + 0xc54a6b66, + 0x72df, + 0x4ee8, + [0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14], + ), + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +const CONSOLE_FLAGS: u32 = 0xff00_0000; + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct Desc { + parameter_count: u32, + parameters: *const c_void, + sampler_count: u32, + samplers: *const c_void, + flags: u32, +} + +type Serialize = + unsafe extern "system" fn(*const Desc, u32, *mut *mut c_void, *mut *mut c_void) -> HRESULT; + +/// The host's serializer, from `d3d12.dll` in System32. +fn host_serializer() -> Option { + static FUNCTION: OnceLock> = OnceLock::new(); + let address = *FUNCTION.get_or_init(|| { + #[cfg(windows)] + { + use windows_sys::Win32::System::LibraryLoader::{ + GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW, + }; + let name: Vec = "d3d12.dll".encode_utf16().chain([0]).collect(); + // SAFETY: a NUL-terminated name; System32 only. + let module = unsafe { + LoadLibraryExW( + name.as_ptr(), + std::ptr::null_mut(), + LOAD_LIBRARY_SEARCH_SYSTEM32, + ) + }; + if module.is_null() { + return None; + } + // SAFETY: a loaded module and a NUL-terminated name. + unsafe { GetProcAddress(module, c"D3D12SerializeRootSignature".as_ptr().cast()) } + .map(|f| f as usize) + } + #[cfg(not(windows))] + None + }); + // SAFETY: the export has this signature. + address.map(|a| unsafe { std::mem::transmute::(a) }) +} + +/// `d3d12_xs!D3D12SerializeRootSignature`. +pub extern "system" fn serialize( + desc: *const Desc, + version: u32, + blob: *mut *mut c_void, + error: *mut *mut c_void, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + if desc.flags & CONSOLE_FLAGS != 0 { + tracing::debug!( + flags = format_args!("{:#x}", desc.flags), + "console root signature flags dropped" + ); + } + let desc = Desc { + flags: desc.flags & !CONSOLE_FLAGS, + ..desc + }; + let Some(serialize) = host_serializer() else { + tracing::warn!("no host d3d12.dll to serialize root signatures"); + return E_NOTIMPL; + }; + // SAFETY: the host function takes the same arguments the title passed. + unsafe { serialize(&desc, version, blob, error) } +} + +#[repr(C)] +struct RootSignature { + object: Object, + /// The serialized form, kept for translating pipelines later. + blob: Vec, +} + +/// Device method. +pub(crate) extern "system" fn create( + _: This, + _nodes: u32, + blob: *const u8, + size: usize, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + if blob.is_null() || size == 0 { + return E_INVALIDARG; + } + // SAFETY: the title passes `size` bytes. + let blob = unsafe { std::slice::from_raw_parts(blob, size) }.to_vec(); + tracing::debug!(size, "root signature"); + let root = Box::new(RootSignature { + object: Object::new(&FUNCTIONS), + blob, + }); + object::hand_out(ROOT_SIGNATURE, root, iid, &ROOT_SIGNATURE_IIDS, out) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = object::is(iid, &ROOT_SIGNATURE_IIDS).then_some(this); + object::answer(ROOT_SIGNATURE, iid, found, out) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::(this) +} + +/// IUnknown 3, object 4, device child 1. +static FUNCTIONS: Table<8> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::{S_OK, slot}; + + /// One 32-bit constant at b0, serialized by the host, then created. + #[cfg(windows)] + #[test] + fn host_serialized_blobs_create_root_signatures() { + #[repr(C)] + struct Constants { + kind: u32, + register: u32, + space: u32, + count: u32, + visibility: u32, + } + let parameter = Constants { + kind: 1, + register: 0, + space: 0, + count: 1, + visibility: 0, + }; + let desc = Desc { + parameter_count: 1, + parameters: (&raw const parameter).cast(), + sampler_count: 0, + samplers: std::ptr::null(), + flags: 0x0100_0001, + }; + let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut()); + assert_eq!(serialize(&desc, 1, &mut blob, &mut error), S_OK); + let blob = blob.cast_const().cast::(); + let data = slot:: *const u8>(blob, 0x18)(blob); + let size = slot:: usize>(blob, 0x20)(blob); + assert!(size > 0); + let null = std::ptr::null(); + let mut root = null; + assert_eq!( + create(null, 0, data, size, &ROOT_SIGNATURE_IIDS[0], &mut root), + S_OK + ); + assert_eq!(slot:: u32>(root, 0x10)(root), 0); + slot:: u32>(blob, 0x10)(blob); + } +} diff --git a/crates/victory-gpu/src/signature.rs b/crates/victory-gpu/src/signature.rs new file mode 100644 index 0000000..adeacdb --- /dev/null +++ b/crates/victory-gpu/src/signature.rs @@ -0,0 +1,83 @@ +//! Command signatures: the record layout of indirect execution. Kept for +//! translating it later. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use crate::object::{ + self, COMMAND_SIGNATURE, E_INVALIDARG, HRESULT, Iid, Object, Table, This, guid, +}; +use crate::resource::PAGEABLE_IIDS; + +const SIGNATURE_IIDS: [Iid; 4] = [ + guid( + 0xc36a797c, + 0xec80, + 0x4f0a, + [0x89, 0x85, 0xa7, 0xb2, 0x47, 0x50, 0x82, 0xd1], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +pub(crate) struct Desc { + stride: u32, + count: u32, + /// Each a type and up to three 32-bit fields. + arguments: *const [u32; 4], + nodes: u32, +} + +#[repr(C)] +struct Signature { + object: Object, + stride: u32, + arguments: Vec<[u32; 4]>, +} + +/// Device method. +pub(crate) extern "system" fn create( + _: This, + desc: *const Desc, + _root: This, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + if desc.arguments.is_null() && desc.count > 0 { + return E_INVALIDARG; + } + let arguments = if desc.count == 0 { + Vec::new() + } else { + // SAFETY: the title passes `count` argument descriptions. + unsafe { std::slice::from_raw_parts(desc.arguments, desc.count as usize) }.to_vec() + }; + tracing::debug!(stride = desc.stride, ?arguments, "command signature"); + let signature = Box::new(Signature { + object: Object::new(&FUNCTIONS), + stride: desc.stride, + arguments, + }); + object::hand_out(COMMAND_SIGNATURE, signature, iid, &SIGNATURE_IIDS, out) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = object::is(iid, &SIGNATURE_IIDS).then_some(this); + object::answer(COMMAND_SIGNATURE, iid, found, out) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::(this) +} + +/// IUnknown 3, object 4, device child 1. +static FUNCTIONS: Table<8> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + Table(f) +}; diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index fd0d2a5..8a9581f 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -8,6 +8,7 @@ license.workspace = true publish.workspace = true [dependencies] +victory-gpu.workspace = true victory-loader.workspace = true victory-pe.workspace = true tracing.workspace = true @@ -15,7 +16,14 @@ tracing.workspace = true [target.'cfg(windows)'.dependencies] windows-sys = { workspace = true, features = [ "Win32_Foundation", + "Win32_Globalization", + "Win32_Storage_FileSystem", + "Win32_System_Diagnostics_Debug", "Win32_System_LibraryLoader", + "Win32_System_Memory", + "Win32_System_ProcessStatus", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", ] } [dev-dependencies] diff --git a/crates/victory-hle/src/host.rs b/crates/victory-hle/src/host.rs index 904d5e0..244fc3d 100644 --- a/crates/victory-hle/src/host.rs +++ b/crates/victory-hle/src/host.rs @@ -36,6 +36,14 @@ impl Default for HostPolicy { "sspicli.dll", "cabinet.dll", "avrt.dll", + // Window, message and shell APIs: the host's desktop window + // stands in for the console's single core window. + "ext-ms-win-rtcore-ntuser-*", + "api-ms-win-shcore-*", + "msvcp_win.dll", + "ole32.dll", + "advapi32.dll", + "iphlpapi.dll", ]; HostPolicy { allow: allow.iter().map(|s| s.to_string()).collect(), @@ -67,6 +75,16 @@ impl HostPolicy { } } +/// The host's own `name` from the System32 DLL `dll`: what a title import +/// of it is bound to when we do not override it. +pub(crate) fn function(dll: &str, name: &str) -> Option { + let name = ImportSymbol::Name { + hint: 0, + name: name.into(), + }; + imp::resolve(dll, &name) +} + #[cfg(windows)] mod imp { use std::collections::HashMap; diff --git a/crates/victory-hle/src/lib.rs b/crates/victory-hle/src/lib.rs index a231331..ae83541 100644 --- a/crates/victory-hle/src/lib.rs +++ b/crates/victory-hle/src/lib.rs @@ -44,9 +44,8 @@ impl HleResolver { impl ImportResolver for HleResolver { fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution { - if let ImportSymbol::Name { name, .. } = symbol - && let Some(address) = registry::lookup(dll, name) - { + // Ordinal imports look up `#n`. + if let Some(address) = registry::lookup(dll, &symbol.to_string()) { return Resolution::Found { address, provenance: Provenance::Hle, diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs new file mode 100644 index 0000000..ced4194 --- /dev/null +++ b/crates/victory-hle/src/modules/audio.rs @@ -0,0 +1,551 @@ +//! The console's audio hardware (`AcpHal.dll`, `xapu.dll`), enough for +//! middleware to start and then mix in software: +//! +//! * the APU heap: host memory with 32-bit device addresses; +//! * SHAPE context arrays allocated from it; +//! * the audio coprocessor's command and message queues, where every +//! command completes at once and is acknowledged as the hardware would; +//! * the APU decoder's connections, which accept no work. +//! +//! What the hardware computes (XMA decoding, hardware rate conversion, EQ, +//! mixing, Opus decoding) is not emulated, so voices that need it stay +//! silent. Software-decoded audio plays through the host's WASAPI, which +//! middleware reaches through COM like on PC. fmod's console build sets +//! all of this up inside `System_Create` and waits there for its first +//! command to be acknowledged. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::alloc::Layout; +use std::collections::{BTreeMap, VecDeque}; +use std::ffi::c_void; +use std::sync::{Mutex, MutexGuard}; +use std::time::Instant; + +use super::xasync::E_INVALIDARG; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleModule, hle_export}; + +const E_FAIL: HRESULT = 0x8000_4005_u32 as i32; +const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; +/// The decoder's "no result yet", which fmod checks for. +const PENDING_RESULTS: HRESULT = 0x8AC8_1001_u32 as i32; + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +// The APU heap. + +struct Block { + size: usize, + apu: u32, + layout: Layout, +} + +struct Heap { + /// By host address. + blocks: BTreeMap, + next_apu: u32, +} + +static HEAP: Mutex = Mutex::new(Heap { + blocks: BTreeMap::new(), + next_apu: 0x0001_0000, +}); + +/// Zeroed host memory and its device address. +// shortcut: device addresses are handed out once and never reused, so the +// 32-bit space runs out after 4 GiB of allocations in total; reuse freed +// ranges if a title streams that much through the heap. +fn heap_alloc(size: usize, align: usize) -> Option<(*mut u8, u32)> { + let layout = Layout::from_size_align(size.max(1), align.max(16)).ok()?; + let mut heap = lock(&HEAP); + let apu = heap.next_apu.checked_next_multiple_of(align as u32)?; + let next = apu.checked_add(u32::try_from(layout.size()).ok()?)?; + // SAFETY: non-zero size. + let ptr = unsafe { std::alloc::alloc_zeroed(layout) }; + if ptr.is_null() { + return None; + } + heap.next_apu = next; + heap.blocks + .insert(ptr as usize, Block { size, apu, layout }); + Some((ptr, apu)) +} + +fn heap_free(ptr: *mut u8) { + let block = lock(&HEAP).blocks.remove(&(ptr as usize)); + if let Some(block) = block { + // SAFETY: allocated by `heap_alloc` with this layout. + unsafe { std::alloc::dealloc(ptr, block.layout) }; + } +} + +/// The device address of any byte of a heap block, 0 elsewhere. +fn heap_map(ptr: usize) -> u32 { + let heap = lock(&HEAP); + match heap.blocks.range(..=ptr).next_back() { + Some((&start, block)) if ptr < start + block.size.max(1) => { + block.apu + (ptr - start) as u32 + } + _ => 0, + } +} + +/// The host address of a device address, if a heap block holds it. +fn heap_unmap(apu: u32) -> Option<*mut u8> { + let heap = lock(&HEAP); + heap.blocks + .iter() + .find(|(_, b)| (b.apu..b.apu.saturating_add(b.size as u32)).contains(&apu)) + .map(|(&start, b)| (start + (apu - b.apu) as usize) as *mut u8) +} + +pub extern "system" fn ApuAlloc( + out: *mut *mut c_void, + apu: *mut u32, + size: u32, + align: u32, + _flags: u32, +) -> HRESULT { + if out.is_null() || size == 0 || align < 4 || !align.is_power_of_two() { + return E_INVALIDARG; + } + let Some((ptr, address)) = heap_alloc(size as usize, align as usize) else { + return E_OUTOFMEMORY; + }; + // SAFETY: checked non-null; optional out parameter checked below. + unsafe { + out.write(ptr.cast()); + if !apu.is_null() { + apu.write(address); + } + } + S_OK +} + +pub extern "system" fn ApuFree(ptr: *mut c_void) { + heap_free(ptr.cast()); +} + +pub extern "system" fn ApuMapVirtualAddress(ptr: *const c_void) -> u32 { + heap_map(ptr as usize) +} + +pub extern "system" fn ApuIsVirtualAddressValid(ptr: *const c_void, align: u32) -> bool { + let apu = heap_map(ptr as usize); + apu != 0 && (align == 0 || apu.is_multiple_of(align)) +} + +// SHAPE context arrays. + +/// Six counts (rate conversion, EQ/compression, filter/volume, DMA, XMA, +/// PCM), then the six arrays and their device addresses. +#[repr(C, packed)] +pub struct ShapeContexts { + counts: [u32; 6], + arrays: [*mut c_void; 6], + apu: [u32; 6], +} + +/// Bytes per context: rate conversion, DMA and XMA as fmod clears them; +/// the others (not seen yet) get a generous upper bound. +const CONTEXT_BYTES: [usize; 6] = [32, 256, 256, 16, 64, 256]; + +static CONTEXTS: Mutex> = Mutex::new(None); + +pub extern "system" fn AcpHalAllocateShapeContexts(contexts: *mut ShapeContexts) -> HRESULT { + if contexts.is_null() { + return E_INVALIDARG; + } + let mut allocated = lock(&CONTEXTS); + if allocated.is_some() { + return E_FAIL; + } + // SAFETY: the title passes its request; packed fields are copied out. + let counts = unsafe { std::ptr::addr_of!((*contexts).counts).read_unaligned() }; + let mut arrays: [*mut c_void; 6] = [std::ptr::null_mut(); 6]; + let mut addresses = [0u32; 6]; + for i in 0..6 { + if counts[i] == 0 { + continue; + } + let Some((ptr, apu)) = heap_alloc(counts[i] as usize * CONTEXT_BYTES[i], 256) else { + arrays.iter().for_each(|&p| heap_free(p.cast())); + return E_OUTOFMEMORY; + }; + (arrays[i], addresses[i]) = (ptr.cast(), apu); + } + // SAFETY: as above. + unsafe { + std::ptr::addr_of_mut!((*contexts).arrays).write_unaligned(arrays); + std::ptr::addr_of_mut!((*contexts).apu).write_unaligned(addresses); + } + *allocated = Some(arrays.map(|p| p as usize)); + S_OK +} + +pub extern "system" fn AcpHalReleaseShapeContexts() -> HRESULT { + match lock(&CONTEXTS).take() { + Some(arrays) => { + arrays.iter().for_each(|&p| heap_free(p as *mut u8)); + S_OK + } + None => E_FAIL, + } +} + +// The audio coprocessor. + +const LOAD_FLOWGRAPH: u32 = 1; +const REGISTER_MESSAGES: u32 = 2; +const UNREGISTER_MESSAGES: u32 = 3; + +const FLOWGRAPH_COMPLETED: u32 = 0x02; +const COMMAND_COMPLETED: u32 = 0x10; +const DISCONNECTED: u32 = 0x80; + +/// Audio frames of 128 samples at 48 kHz. +const FRAMES_PER_SECOND: u64 = 375; + +#[repr(C, packed)] +#[derive(Clone, Copy)] +struct Message { + kind: u32, + dropped: u32, + usec: u32, + data: [u8; 16], +} + +struct State { + connected: bool, + /// Message kinds the title registered for. + mask: u32, + messages: VecDeque, + since: Instant, +} + +impl State { + fn usec(&self) -> u64 { + self.since.elapsed().as_micros() as u64 + } + + fn frame(&self) -> u32 { + (self.usec() * FRAMES_PER_SECOND / 1_000_000) as u32 + } + + // shortcut: the queue is unbounded and never reports dropped messages; + // bound it at the size given to `connect` if a title relies on drops. + fn post(&mut self, kind: u32, data: &[u8]) { + if self.mask & kind == 0 { + return; + } + let mut message = Message { + kind, + dropped: 0, + usec: self.usec() as u32, + data: [0; 16], + }; + message.data[..data.len()].copy_from_slice(data); + self.messages.push_back(message); + } +} + +/// The interface object: its method table, then our state. +#[repr(C)] +pub struct Acp { + vtable: &'static AcpMethods, + state: Mutex, +} + +#[repr(C)] +struct AcpMethods { + connect: extern "system" fn(*mut Acp, u32, u32) -> HRESULT, + disconnect: extern "system" fn(*mut Acp) -> HRESULT, + submit: extern "system" fn(*mut Acp, u32, u64, u32, *const c_void, u32) -> HRESULT, + pop_message: extern "system" fn(*mut Acp, *mut Message) -> bool, + message_count: extern "system" fn(*mut Acp) -> u32, + release: extern "system" fn(*mut Acp), +} + +static ACP_METHODS: AcpMethods = AcpMethods { + connect, + disconnect, + submit, + pop_message, + message_count, + release, +}; + +fn state(this: *mut Acp) -> MutexGuard<'static, State> { + // SAFETY: title code calls methods on the object `AcpHalCreate` made, + // which lives until `release`. + lock(unsafe { &(*this).state }) +} + +extern "system" fn connect(this: *mut Acp, commands: u32, _messages: u32) -> HRESULT { + if commands == 0 { + return E_INVALIDARG; + } + state(this).connected = true; + S_OK +} + +extern "system" fn disconnect(this: *mut Acp) -> HRESULT { + let mut state = state(this); + if !state.connected { + return E_FAIL; + } + state.post(DISCONNECTED, &[]); + state.connected = false; + S_OK +} + +/// Done at once: message registrations take effect, a flowgraph completes +/// unprocessed, a command with an id is acknowledged, and its notification +/// word is set. +extern "system" fn submit( + this: *mut Acp, + command: u32, + id: u64, + _frame: u32, + data: *const c_void, + notification: u32, +) -> HRESULT { + static SEEN: Mutex = Mutex::new(0); + if command < 64 && *lock(&SEEN) & 1 << command == 0 { + *lock(&SEEN) |= 1 << command; + tracing::info!(command, "first coprocessor command of this kind"); + } + let mut state = state(this); + let word = |at: usize| -> Option { + // SAFETY: the command's data starts with these u32 fields. + (!data.is_null()).then(|| unsafe { data.cast::().add(at).read_unaligned() }) + }; + match command { + REGISTER_MESSAGES => state.mask |= word(0).unwrap_or(0), + UNREGISTER_MESSAGES => state.mask &= !word(0).unwrap_or(0), + LOAD_FLOWGRAPH => { + let flowgraph = word(1).unwrap_or(0); + state.post(FLOWGRAPH_COMPLETED, &flowgraph.to_le_bytes()); + } + _ => {} + } + if id != 0 { + let mut done = [0u8; 16]; + done[..4].copy_from_slice(&command.to_le_bytes()); + done[4..12].copy_from_slice(&id.to_le_bytes()); + done[12..].copy_from_slice(&state.frame().to_le_bytes()); + state.post(COMMAND_COMPLETED, &done); + } + if notification != 0 + && let Some(word) = heap_unmap(notification) + { + // SAFETY: a u32 in a heap block, which the title reads as volatile. + unsafe { word.cast::().write_volatile(1) }; + } + S_OK +} + +extern "system" fn pop_message(this: *mut Acp, out: *mut Message) -> bool { + let Some(message) = state(this).messages.pop_front() else { + return false; + }; + if !out.is_null() { + // SAFETY: the title passes room for one message. + unsafe { out.write_unaligned(message) }; + } + true +} + +extern "system" fn message_count(this: *mut Acp) -> u32 { + state(this).messages.len() as u32 +} + +extern "system" fn release(this: *mut Acp) { + // SAFETY: made by `AcpHalCreate` with `Box::into_raw`; released once. + drop(unsafe { Box::from_raw(this) }); +} + +pub extern "system" fn AcpHalCreate(out: *mut *mut Acp) -> HRESULT { + if out.is_null() { + return E_INVALIDARG; + } + let acp = Box::new(Acp { + vtable: &ACP_METHODS, + state: Mutex::new(State { + connected: false, + mask: 0, + messages: VecDeque::new(), + since: Instant::now(), + }), + }); + // SAFETY: checked non-null. + unsafe { out.write(Box::into_raw(acp)) }; + S_OK +} + +// The APU decoder: connections get their memory, commands are refused. + +#[repr(C)] +pub struct ConnectInput { + process: u32, + streams: u32, + commands_per_stream: u32, + memory: u32, + frames_per_output: u32, + options: u32, +} + +#[repr(C)] +pub struct ConnectOutput { + memory: *mut c_void, + result_event: *mut c_void, +} + +/// The memory a connection hands out. +pub struct Connection(*mut u8, Layout); + +pub extern "system" fn XApuConnect( + input: *const ConnectInput, + output: *mut ConnectOutput, + handle: *mut *mut Connection, +) -> HRESULT { + const RESULT_READY_EVENT: u32 = 8; + if input.is_null() || output.is_null() || handle.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null. + let input = unsafe { &*input }; + if input.options & RESULT_READY_EVENT != 0 { + // shortcut: no event to signal, since no result ever comes; create + // one if a title asks for it. + return E_FAIL; + } + let Ok(layout) = Layout::from_size_align(input.memory.max(16) as usize, 16) else { + return E_INVALIDARG; + }; + // SAFETY: non-zero size. + let memory = unsafe { std::alloc::alloc_zeroed(layout) }; + if memory.is_null() { + return E_OUTOFMEMORY; + } + // SAFETY: checked non-null. + unsafe { + output.write(ConnectOutput { + memory: memory.cast(), + result_event: std::ptr::null_mut(), + }); + handle.write(Box::into_raw(Box::new(Connection(memory, layout)))); + } + S_OK +} + +/// Nothing is decoded: the stream fails instead of waiting forever. +pub extern "system" fn XApuEnqueueCommand() -> HRESULT { + E_FAIL +} + +pub extern "system" fn XApuDequeueResult() -> HRESULT { + PENDING_RESULTS +} + +pub extern "system" fn XApuDisconnect(handle: *mut Connection) -> HRESULT { + if handle.is_null() { + return E_INVALIDARG; + } + // SAFETY: made by `XApuConnect`; disconnected once. + let Connection(memory, layout) = *unsafe { Box::from_raw(handle) }; + // SAFETY: allocated in `XApuConnect` with this layout. + unsafe { std::alloc::dealloc(memory, layout) }; + S_OK +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "audio", + dlls: &["acphal.dll", "xapu.dll"], + exports: vec![ + hle_export!(AcpHalAllocateShapeContexts), + hle_export!(AcpHalReleaseShapeContexts), + hle_export!(AcpHalCreate), + hle_export!(ApuAlloc), + hle_export!(ApuFree), + hle_export!(ApuIsVirtualAddressValid), + hle_export!(ApuMapVirtualAddress), + hle_export!(XApuConnect), + hle_export!(XApuEnqueueCommand), + hle_export!(XApuDequeueResult), + hle_export!(XApuDisconnect), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn heap_maps_every_byte_of_a_block() { + let (mut ptr, mut apu) = (std::ptr::null_mut(), 0); + assert_eq!(ApuAlloc(&mut ptr, &mut apu, 0x100, 128, 1), S_OK); + assert!(apu != 0 && apu.is_multiple_of(128)); + let inner = ptr.cast::().wrapping_add(0x40).cast_const().cast(); + assert_eq!(ApuMapVirtualAddress(inner), apu + 0x40); + assert!(ApuIsVirtualAddressValid(ptr, 128)); + assert_eq!(heap_unmap(apu + 4), Some(ptr.cast::().wrapping_add(4))); + ApuFree(ptr); + assert_eq!(ApuMapVirtualAddress(ptr), 0); + assert_eq!(ApuAlloc(&mut ptr, &mut apu, 0x100, 6, 1), E_INVALIDARG); + } + + #[test] + fn startup_as_fmod_does_it() { + // Context arrays: rate conversion, DMA and XMA. + let mut request = ShapeContexts { + counts: [0x200, 0, 0, 0x400, 0x200, 0], + arrays: [std::ptr::null_mut(); 6], + apu: [0; 6], + }; + assert_eq!(size_of::(), 0x60); + assert_eq!(AcpHalAllocateShapeContexts(&mut request), S_OK); + let arrays = request.arrays; + assert!(!arrays[0].is_null() && !arrays[3].is_null() && !arrays[4].is_null()); + assert!(arrays[1].is_null()); + // SAFETY: 0x200 rate-conversion contexts of 32 bytes were allocated. + unsafe { arrays[0].cast::().write_bytes(0, 0x200 << 5) }; + + // Connect, register every message but frame starts, then wait for + // the registration to be acknowledged. + let mut acp = std::ptr::null_mut(); + assert_eq!(AcpHalCreate(&mut acp), S_OK); + // SAFETY: just created. + let m = unsafe { (*acp).vtable }; + assert_eq!((m.connect)(acp, 0x804, 0x804), S_OK); + let mask = 0xfe_u32; + let data = (&raw const mask).cast(); + assert_eq!( + (m.submit)(acp, REGISTER_MESSAGES, 1, u32::MAX, data, 0), + S_OK + ); + let mut message = Message { + kind: 0, + dropped: 0, + usec: 0, + data: [0; 16], + }; + assert!((m.pop_message)(acp, &mut message)); + let (kind, dropped) = (message.kind, message.dropped); + assert_eq!((kind, dropped), (COMMAND_COMPLETED, 0)); + assert_eq!( + u64::from_le_bytes(message.data[4..12].try_into().unwrap()), + 1 + ); + assert!(!(m.pop_message)(acp, &mut message)); + assert_eq!((m.disconnect)(acp), S_OK); + assert_eq!((m.message_count)(acp), 1, "disconnected"); + (m.release)(acp); + assert_eq!(AcpHalReleaseShapeContexts(), S_OK); + } +} diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs new file mode 100644 index 0000000..9c38f44 --- /dev/null +++ b/crates/victory-hle/src/modules/d3d12x.rs @@ -0,0 +1,51 @@ +//! `d3d12_xs.dll`: device creation. The device and everything it creates +//! live in `victory-gpu`. + +use victory_gpu::device; + +use crate::{HleExport, HleModule}; + +pub(crate) fn module() -> HleModule { + HleModule { + name: "d3d12x", + dlls: &["d3d12_xs.dll"], + exports: vec![ + HleExport { + name: "D3D12XboxCreateDevice", + address: device::create as *const () as usize, + }, + HleExport { + name: "D3D12SerializeRootSignature", + address: victory_gpu::root::serialize as *const () as usize, + }, + // A data import: the title reads the id at this address. + HleExport { + name: "IID_ID3D12Device", + address: (&raw const device::IID) as usize, + }, + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{HleResolver, HostPolicy}; + use victory_loader::ImportResolver; + use victory_loader::Resolution; + use victory_pe::ImportSymbol; + + #[test] + fn the_interface_id_import_is_bound_to_data() { + let symbol = ImportSymbol::Name { + hint: 0, + name: "IID_ID3D12Device".into(), + }; + let r = HleResolver::new(HostPolicy::none()); + let Resolution::Found { address, .. } = r.resolve("d3d12_xs.dll", &symbol) else { + panic!("not bound"); + }; + // SAFETY: the address is our static id. + assert_eq!(unsafe { *(address as *const [u8; 16]) }, device::IID); + } +} diff --git a/crates/victory-hle/src/modules/files.rs b/crates/victory-hle/src/modules/files.rs new file mode 100644 index 0000000..a0c9eeb --- /dev/null +++ b/crates/victory-hle/src/modules/files.rs @@ -0,0 +1,587 @@ +//! Virtual drives over host folders: on the console, title storage is a +//! drive of its own, and titles build paths on that assumption. +//! +//! Every title import that takes a path is bound here. A path on a virtual +//! drive (`X:\..`, `X:/..`, `X:`, `\\?\X:\..`) is rewritten to the host +//! folder behind it and handed to the host's own function; any other path +//! goes to the host unchanged. A rewritten narrow path goes to the wide +//! twin, so host folders outside the ANSI code page work. Letters are +//! chosen among those the host does not use, so no host drive is hidden. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] +#![allow(clippy::too_many_arguments)] + +use std::ffi::{CStr, c_char, c_void}; +use std::os::windows::ffi::OsStrExt; +use std::path::Path; +use std::sync::{Mutex, MutexGuard}; + +use windows_sys::Win32::Globalization::{CP_ACP, MultiByteToWideChar}; +use windows_sys::Win32::Storage::FileSystem::GetLogicalDrives; + +use crate::{HleExport, HleModule, hle_export}; + +/// The host's own function: what the import would have been bound to. +macro_rules! host { + ($dll:literal, $name:literal: $ty:ty) => {{ + static ADDRESS: std::sync::OnceLock = std::sync::OnceLock::new(); + let address = *ADDRESS.get_or_init(|| { + crate::host::function($dll, $name) + .unwrap_or_else(|| panic!("the host lacks {}!{}", $dll, $name)) + }); + // SAFETY: the host exports this function with this signature. + unsafe { std::mem::transmute::(address) } + }}; +} + +/// Mounted drives: upper-case letter and host root (UTF-16, no trailing +/// separator, no NUL). +static DRIVES: Mutex)>> = Mutex::new(Vec::new()); + +fn drives() -> MutexGuard<'static, Vec<(u16, Vec)>> { + DRIVES.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Gives the host folder `root` a drive letter (the same one if it already +/// has one): the highest letter neither the host nor another mount uses. +pub fn mount(root: &Path) -> Option { + let mut wide: Vec = root.as_os_str().encode_wide().collect(); + while wide.len() > 3 && wide.last().is_some_and(|c| SEPARATORS.contains(c)) { + wide.pop(); + } + let mut drives = drives(); + if let Some(&(letter, _)) = drives.iter().find(|(_, r)| *r == wide) { + return char::from_u32(letter.into()); + } + // SAFETY: no arguments. + let host = unsafe { GetLogicalDrives() }; + let letter = (b'D'..=b'Z').rev().find(|&l| { + host >> (l - b'A') & 1 == 0 && !drives.iter().any(|(m, _)| *m == u16::from(l)) + })?; + tracing::info!(drive = %char::from(letter), root = %root.display(), "virtual drive"); + drives.push((letter.into(), wide)); + Some(letter.into()) +} + +const SEPARATORS: [u16; 2] = [b'\\' as u16, b'/' as u16]; +const VERBATIM: [u16; 4] = [b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16]; + +/// The host path, NUL-terminated, for `path` (without its NUL) if it is on +/// a virtual drive. +// shortcut: host roots are not made verbatim, so a long host root can push a +// title path past MAX_PATH; switch to `\\?\` paths (normalising `..` and `/` +// ourselves) if a title's paths get that long. +fn translate(path: &[u16]) -> Option> { + let (prefix, rest) = match path.strip_prefix(&VERBATIM[..]) { + Some(rest) => (&VERBATIM[..], rest), + None => (&[][..], path), + }; + let &[letter, colon, ..] = rest else { + return None; + }; + if colon != u16::from(b':') { + return None; + } + let letter = u8::try_from(letter).ok().filter(u8::is_ascii_alphabetic)?; + let letter = u16::from(letter.to_ascii_uppercase()); + let drives = drives(); + let (_, root) = drives.iter().find(|(l, _)| *l == letter)?; + let tail = &rest[2..]; + let mut out = prefix.to_vec(); + out.extend_from_slice(root); + // `X:` and `X:name` are relative to the root. + if !tail.first().is_some_and(|c| SEPARATORS.contains(c)) { + out.push(b'\\'.into()); + } + let verbatim = !prefix.is_empty(); + out.extend(tail.iter().map(|&c| { + if verbatim && c == u16::from(b'/') { + b'\\'.into() + } else { + c + } + })); + out.push(0); + Some(out) +} + +/// A title's wide path: the host path when it is on a virtual drive, else +/// the title's own pointer. +struct Wide(*const u16, Option>); + +impl Wide { + fn ptr(&self) -> *const u16 { + self.1.as_ref().map_or(self.0, |p| p.as_ptr()) + } +} + +fn wide(path: *const u16) -> Wide { + if path.is_null() { + return Wide(path, None); + } + // SAFETY: the title passes a NUL-terminated path. + let path_slice = unsafe { + let len = (0..).take_while(|&i| *path.add(i) != 0).count(); + std::slice::from_raw_parts(path, len) + }; + Wide(path, translate(path_slice)) +} + +/// A narrow path (ANSI code page, as the host decodes it) on a virtual +/// drive, as a wide host path. +fn narrow(path: *const c_char) -> Option> { + if path.is_null() { + return None; + } + // SAFETY: the title passes a NUL-terminated path. + let bytes = unsafe { CStr::from_ptr(path) }.to_bytes(); + // The drive part is ASCII in every code page; decode only candidates. + match bytes.strip_prefix(br"\\?\").unwrap_or(bytes) { + [letter, b':', ..] if letter.is_ascii_alphabetic() => {} + _ => return None, + } + let len = i32::try_from(bytes.len()).ok()?; + // SAFETY: sizing call, then a call with room for `n` units. + let wide = unsafe { + let n = MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, std::ptr::null_mut(), 0); + let mut wide = vec![0u16; usize::try_from(n).ok()?]; + MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, wide.as_mut_ptr(), n); + wide + }; + translate(&wide) +} + +/// An ASCII mode string (`"rb"`, `"w, ccs=UTF-8"`) for a wide CRT call. +fn widen(mode: *const c_char) -> Vec { + if mode.is_null() { + return vec![0]; + } + // SAFETY: a NUL-terminated mode string. + let bytes = unsafe { CStr::from_ptr(mode) }.to_bytes(); + bytes.iter().map(|&b| u16::from(b)).chain([0]).collect() +} + +type Handle = *mut c_void; +type File = *mut c_void; + +// kernel32 and its file API sets. + +pub extern "system" fn CreateFileW( + path: *const u16, + access: u32, + share: u32, + security: *const c_void, + disposition: u32, + flags: u32, + template: Handle, +) -> Handle { + let p = wide(path); + host!("kernel32.dll", "CreateFileW": extern "system" fn(*const u16, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( + p.ptr(), + access, + share, + security, + disposition, + flags, + template, + ) +} + +pub extern "system" fn CreateFileA( + path: *const c_char, + access: u32, + share: u32, + security: *const c_void, + disposition: u32, + flags: u32, + template: Handle, +) -> Handle { + match narrow(path) { + Some(p) => CreateFileW( + p.as_ptr(), + access, + share, + security, + disposition, + flags, + template, + ), + None => { + host!("kernel32.dll", "CreateFileA": extern "system" fn(*const c_char, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( + path, + access, + share, + security, + disposition, + flags, + template, + ) + } + } +} + +pub extern "system" fn DeleteFileA(path: *const c_char) -> i32 { + match narrow(path) { + Some(p) => { + host!("kernel32.dll", "DeleteFileW": extern "system" fn(*const u16) -> i32)(p.as_ptr()) + } + None => { + host!("kernel32.dll", "DeleteFileA": extern "system" fn(*const c_char) -> i32)(path) + } + } +} + +pub extern "system" fn CreateDirectoryW(path: *const u16, security: *const c_void) -> i32 { + let p = wide(path); + host!("kernel32.dll", "CreateDirectoryW": extern "system" fn(*const u16, *const c_void) -> i32)( + p.ptr(), + security, + ) +} + +pub extern "system" fn GetFileAttributesExW( + path: *const u16, + level: i32, + info: *mut c_void, +) -> i32 { + let p = wide(path); + host!("kernel32.dll", "GetFileAttributesExW": extern "system" fn(*const u16, i32, *mut c_void) -> i32)( + p.ptr(), + level, + info, + ) +} + +pub extern "system" fn GetDiskFreeSpaceExW( + path: *const u16, + available: *mut u64, + total: *mut u64, + free: *mut u64, +) -> i32 { + let p = wide(path); + host!("kernel32.dll", "GetDiskFreeSpaceExW": extern "system" fn(*const u16, *mut u64, *mut u64, *mut u64) -> i32)( + p.ptr(), + available, + total, + free, + ) +} + +/// Wants a volume root: a virtual drive answers for the host volume its +/// folder is on. +pub extern "system" fn GetDiskFreeSpaceW( + root: *const u16, + sectors_per_cluster: *mut u32, + bytes_per_sector: *mut u32, + free_clusters: *mut u32, + clusters: *mut u32, +) -> i32 { + let mut p = wide(root); + if let Some(host) = &mut p.1 + && let [letter, colon, sep, ..] = host[..] + && colon == u16::from(b':') + && SEPARATORS.contains(&sep) + { + *host = vec![letter, colon, sep, 0]; + } + host!("kernel32.dll", "GetDiskFreeSpaceW": extern "system" fn(*const u16, *mut u32, *mut u32, *mut u32, *mut u32) -> i32)( + p.ptr(), + sectors_per_cluster, + bytes_per_sector, + free_clusters, + clusters, + ) +} + +pub extern "system" fn FindFirstFileW(path: *const u16, data: *mut c_void) -> Handle { + let p = wide(path); + host!("kernel32.dll", "FindFirstFileW": extern "system" fn(*const u16, *mut c_void) -> Handle)( + p.ptr(), + data, + ) +} + +pub extern "system" fn FindFirstFileExW( + path: *const u16, + level: i32, + data: *mut c_void, + search: i32, + filter: *mut c_void, + flags: u32, +) -> Handle { + let p = wide(path); + host!("kernel32.dll", "FindFirstFileExW": extern "system" fn(*const u16, i32, *mut c_void, i32, *mut c_void, u32) -> Handle)( + p.ptr(), + level, + data, + search, + filter, + flags, + ) +} + +pub extern "system" fn MoveFileExW(from: *const u16, to: *const u16, flags: u32) -> i32 { + let (from, to) = (wide(from), wide(to)); + host!("kernel32.dll", "MoveFileExW": extern "system" fn(*const u16, *const u16, u32) -> i32)( + from.ptr(), + to.ptr(), + flags, + ) +} + +pub extern "system" fn SetCurrentDirectoryA(path: *const c_char) -> i32 { + match narrow(path) { + Some(p) => { + host!("kernel32.dll", "SetCurrentDirectoryW": extern "system" fn(*const u16) -> i32)( + p.as_ptr(), + ) + } + None => { + host!("kernel32.dll", "SetCurrentDirectoryA": extern "system" fn(*const c_char) -> i32)( + path, + ) + } + } +} + +// The C runtime (ucrtbase, which the title's CRT imports bind to). + +pub extern "C" fn _wfopen(path: *const u16, mode: *const u16) -> File { + let p = wide(path); + host!("ucrtbase.dll", "_wfopen": extern "C" fn(*const u16, *const u16) -> File)(p.ptr(), mode) +} + +pub extern "C" fn _wfopen_s(out: *mut File, path: *const u16, mode: *const u16) -> i32 { + let p = wide(path); + host!("ucrtbase.dll", "_wfopen_s": extern "C" fn(*mut File, *const u16, *const u16) -> i32)( + out, + p.ptr(), + mode, + ) +} + +pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> File { + let p = wide(path); + host!("ucrtbase.dll", "_wfsopen": extern "C" fn(*const u16, *const u16, i32) -> File)( + p.ptr(), + mode, + share, + ) +} + +pub extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> File { + match narrow(path) { + Some(p) => _wfopen(p.as_ptr(), widen(mode).as_ptr()), + None => { + host!("ucrtbase.dll", "fopen": extern "C" fn(*const c_char, *const c_char) -> File)( + path, mode, + ) + } + } +} + +pub extern "C" fn fopen_s(out: *mut File, path: *const c_char, mode: *const c_char) -> i32 { + match narrow(path) { + Some(p) => _wfopen_s(out, p.as_ptr(), widen(mode).as_ptr()), + None => { + host!("ucrtbase.dll", "fopen_s": extern "C" fn(*mut File, *const c_char, *const c_char) -> i32)( + out, path, mode, + ) + } + } +} + +pub extern "C" fn _wstat64(path: *const u16, stat: *mut c_void) -> i32 { + let p = wide(path); + host!("ucrtbase.dll", "_wstat64": extern "C" fn(*const u16, *mut c_void) -> i32)(p.ptr(), stat) +} + +pub extern "C" fn _stat64i32(path: *const c_char, stat: *mut c_void) -> i32 { + match narrow(path) { + Some(p) => { + host!("ucrtbase.dll", "_wstat64i32": extern "C" fn(*const u16, *mut c_void) -> i32)( + p.as_ptr(), + stat, + ) + } + None => { + host!("ucrtbase.dll", "_stat64i32": extern "C" fn(*const c_char, *mut c_void) -> i32)( + path, stat, + ) + } + } +} + +pub extern "C" fn remove(path: *const c_char) -> i32 { + match narrow(path) { + Some(p) => host!("ucrtbase.dll", "_wremove": extern "C" fn(*const u16) -> i32)(p.as_ptr()), + None => host!("ucrtbase.dll", "remove": extern "C" fn(*const c_char) -> i32)(path), + } +} + +pub extern "C" fn _wchmod(path: *const u16, mode: i32) -> i32 { + let p = wide(path); + host!("ucrtbase.dll", "_wchmod": extern "C" fn(*const u16, i32) -> i32)(p.ptr(), mode) +} + +pub extern "C" fn _wutime64(path: *const u16, times: *mut c_void) -> i32 { + let p = wide(path); + host!("ucrtbase.dll", "_wutime64": extern "C" fn(*const u16, *mut c_void) -> i32)( + p.ptr(), + times, + ) +} + +// The C++ library: `std::basic_filebuf::open` goes through `_Fiopen`. + +const FIOPEN: &str = "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z"; + +/// `_Fiopen(const char* path, ios_base::openmode, int protection)`. +extern "C" fn fiopen(path: *const c_char, mode: i32, protection: i32) -> File { + match narrow(path) { + Some(p) => { + host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z": extern "C" fn(*const u16, i32, i32) -> File)( + p.as_ptr(), + mode, + protection, + ) + } + None => { + host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z": extern "C" fn(*const c_char, i32, i32) -> File)( + path, mode, protection, + ) + } + } +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "files", + dlls: &[ + "kernel32.dll", + "kernelbase.dll", + "api-ms-win-core-file-*", + "api-ms-win-core-processenvironment-*", + "ucrtbase.dll", + "api-ms-win-crt-stdio-*", + "api-ms-win-crt-filesystem-*", + "api-ms-win-crt-time-*", + "msvcp140.dll", + ], + exports: vec![ + hle_export!(CreateFileW), + hle_export!(CreateFileA), + hle_export!(DeleteFileA), + hle_export!(CreateDirectoryW), + hle_export!(GetFileAttributesExW), + hle_export!(GetDiskFreeSpaceExW), + hle_export!(GetDiskFreeSpaceW), + hle_export!(FindFirstFileW), + hle_export!(FindFirstFileExW), + hle_export!(MoveFileExW), + hle_export!(SetCurrentDirectoryA), + hle_export!(_wfopen), + hle_export!(_wfopen_s), + hle_export!(_wfsopen), + hle_export!(fopen), + hle_export!(fopen_s), + hle_export!(_wstat64), + hle_export!(_stat64i32), + hle_export!(remove), + hle_export!(_wchmod), + hle_export!(_wutime64), + HleExport { + name: FIOPEN, + address: fiopen as *const () as usize, + }, + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn w(s: &str) -> Vec { + s.encode_utf16().chain([0]).collect() + } + + fn text(v: &[u16]) -> String { + String::from_utf16_lossy(&v[..v.len() - 1]) + } + + #[test] + fn rewrites_only_paths_on_mounted_drives() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().to_string_lossy().into_owned(); + let letter = mount(dir.path()).unwrap(); + assert_eq!( + mount(dir.path()), + Some(letter), + "mounting twice reuses the letter" + ); + let tr = |s: String| translate(&w(&s)[..s.encode_utf16().count()]).map(|v| text(&v)); + assert_eq!( + tr(format!("{letter}:/a/b.txt")), + Some(format!("{root}/a/b.txt")) + ); + let lower = letter.to_ascii_lowercase(); + assert_eq!(tr(format!("{lower}:\\a")), Some(format!("{root}\\a"))); + assert_eq!(tr(format!("{letter}:")), Some(format!("{root}\\"))); + assert_eq!( + tr(format!(r"\\?\{letter}:/a/b")), + Some(format!(r"\\?\{root}\a\b")) + ); + assert_eq!(tr(r"C:\Windows".into()), None); + assert_eq!(tr("relative/path".into()), None); + assert_eq!(tr(String::new()), None); + } + + #[test] + fn title_file_calls_land_in_the_host_folder() { + let dir = tempfile::tempdir().unwrap(); + let letter = mount(dir.path()).unwrap(); + const GENERIC_WRITE: u32 = 0x4000_0000; + const CREATE_ALWAYS: u32 = 2; + let close = host!("kernel32.dll", "CloseHandle": extern "system" fn(Handle) -> i32); + let fclose = host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32); + + let path = w(&format!(r"{letter}:\created.bin")); + let null = std::ptr::null_mut(); + let h = CreateFileW( + path.as_ptr(), + GENERIC_WRITE, + 0, + null, + CREATE_ALWAYS, + 0, + null, + ); + assert_ne!(h as isize, -1); + close(h); + assert!(dir.path().join("created.bin").is_file()); + + let path = format!("{letter}:/opened.txt\0"); + let f = fopen(path.as_ptr().cast(), c"wb".as_ptr()); + assert!(!f.is_null()); + fclose(f); + assert!(dir.path().join("opened.txt").is_file()); + + let path = format!("{letter}:/stream.txt\0"); + const OUT: i32 = 2; + let f = fiopen(path.as_ptr().cast(), OUT, 0x40); + assert!(!f.is_null()); + fclose(f); + assert!(dir.path().join("stream.txt").is_file()); + + assert_eq!(remove(path.as_ptr().cast()), 0); + assert!(!dir.path().join("stream.txt").exists()); + + // Other paths pass through untouched. + let host_path = format!("{}\0", dir.path().join("plain.txt").display()); + let f = fopen(host_path.as_ptr().cast(), c"wb".as_ptr()); + assert!(!f.is_null()); + fclose(f); + assert!(dir.path().join("plain.txt").is_file()); + } +} diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs new file mode 100644 index 0000000..f84e714 --- /dev/null +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -0,0 +1,275 @@ +//! `gameinput.dll`: input devices. For now nothing is ever connected: +//! readings and device lookups fail as they do with no device plugged in, +//! callbacks are accepted and never called. +#![allow(non_snake_case)] +// Title code calls these through the object, passing pointers the real API +// would trust. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::c_void; +use std::sync::LazyLock; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Instant; + +use super::xasync::{E_INVALIDARG, E_NOTIMPL}; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleExport, HleModule}; + +/// The documented "no such reading" and "no such device" errors. +pub const READING_NOT_FOUND: HRESULT = 0x838A_0003_u32 as i32; +pub const DEVICE_NOT_FOUND: HRESULT = 0x838A_0002_u32 as i32; +const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32; + +#[repr(C)] +pub struct Object { + vtable: &'static Vtable, +} + +#[repr(C)] +struct Vtable([*const (); 22]); +// SAFETY: function addresses only. +unsafe impl Sync for Vtable {} + +static OBJECT: Object = Object { vtable: &VTABLE }; + +type This = *const Object; +type Out = *mut *const c_void; + +/// The DLL's only export (ordinal 1): the input object, static and shared. +pub extern "system" fn GameInputCreate(out: *mut This) -> HRESULT { + tracing::info!("GameInputCreate: no input devices"); + if out.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null; the title passes room for a pointer. + unsafe { out.write(&OBJECT) }; + S_OK +} + +/// Clears a COM out pointer and returns `hr`. +fn fail(out: Out, hr: HRESULT) -> HRESULT { + if !out.is_null() { + // SAFETY: checked non-null; the title passes room for a pointer. + unsafe { out.write(std::ptr::null()) }; + } + hr +} + +extern "system" fn query_interface(_: This, _iid: *const c_void, out: Out) -> HRESULT { + tracing::warn!("input QueryInterface not implemented"); + fail(out, E_NOINTERFACE) +} +extern "system" fn add_ref(_: This) -> u32 { + 1 +} + +static START: LazyLock = LazyLock::new(Instant::now); + +/// Microseconds; only ever compared with readings, and there are none. +extern "system" fn timestamp(_: This) -> u64 { + START.elapsed().as_micros() as u64 +} + +extern "system" fn current_reading( + _: This, + _kind: u32, + _device: *const c_void, + out: Out, +) -> HRESULT { + fail(out, READING_NOT_FOUND) +} +extern "system" fn relative_reading( + _: This, + _reference: *const c_void, + _kind: u32, + _device: *const c_void, + out: Out, +) -> HRESULT { + fail(out, READING_NOT_FOUND) +} +extern "system" fn temporal_reading( + _: This, + _time: u64, + _device: *const c_void, + out: Out, +) -> HRESULT { + fail(out, READING_NOT_FOUND) +} + +static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1); + +fn token(out: *mut u64) -> HRESULT { + if !out.is_null() { + // SAFETY: checked non-null. + unsafe { out.write(NEXT_TOKEN.fetch_add(1, Ordering::Relaxed)) }; + } + S_OK +} + +extern "system" fn register_reading( + _: This, + _device: *const c_void, + _kind: u32, + _threshold: f32, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + token(out) +} +/// Enumerating existing devices finds none, so the callback never runs. +extern "system" fn register_device( + _: This, + _device: *const c_void, + kind: u32, + _status: u32, + _enumeration: u32, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + tracing::info!( + kind = format_args!("{kind:#x}"), + "input device callback: no devices" + ); + token(out) +} +/// Guide button and keyboard layout callbacks. +extern "system" fn register_other( + _: This, + _device: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + token(out) +} +extern "system" fn stop_callback(_: This, _token: u64) {} +extern "system" fn unregister_callback(_: This, _token: u64, _timeout: u64) -> bool { + true +} + +/// Dispatcher and aggregate device: not needed while nothing is connected. +extern "system" fn create_dispatcher(_: This, out: Out) -> HRESULT { + tracing::warn!("input dispatcher not implemented"); + fail(out, E_NOTIMPL) +} +extern "system" fn create_aggregate(_: This, _kind: u32, out: Out) -> HRESULT { + tracing::warn!("aggregate input device not implemented"); + fail(out, E_NOTIMPL) +} +/// Lookup by id, object, platform handle or platform string. +extern "system" fn find_device(_: This, _value: *const c_void, out: Out) -> HRESULT { + fail(out, DEVICE_NOT_FOUND) +} +extern "system" fn enable_oem_device( + _: This, + _vendor: u16, + _product: u16, + _interface: u8, + _collection: u8, +) -> HRESULT { + S_OK +} +extern "system" fn set_focus_policy(_: This, _policy: u32) {} + +static VTABLE: Vtable = Vtable([ + query_interface as *const (), // 0x00 + add_ref as *const (), // 0x08 AddRef + add_ref as *const (), // 0x10 Release: the object is static + timestamp as *const (), // 0x18 + current_reading as *const (), // 0x20 + relative_reading as *const (), // 0x28 next + relative_reading as *const (), // 0x30 previous + temporal_reading as *const (), // 0x38 + register_reading as *const (), // 0x40 + register_device as *const (), // 0x48 + register_other as *const (), // 0x50 guide button + register_other as *const (), // 0x58 keyboard layout + stop_callback as *const (), // 0x60 + unregister_callback as *const (), // 0x68 + create_dispatcher as *const (), // 0x70 + create_aggregate as *const (), // 0x78 + find_device as *const (), // 0x80 by id + find_device as *const (), // 0x88 by object + find_device as *const (), // 0x90 by platform handle + find_device as *const (), // 0x98 by platform string + enable_oem_device as *const (), // 0xa0 + set_focus_policy as *const (), // 0xa8 +]); + +pub(crate) fn module() -> HleModule { + HleModule { + name: "gameinput", + dlls: &["gameinput.dll"], + // Titles import it by ordinal only. + exports: vec![HleExport { + name: "#1", + address: GameInputCreate as *const () as usize, + }], + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::HleResolver; + use crate::HostPolicy; + use victory_loader::Provenance; + use victory_pe::ImportSymbol; + + fn slot(object: This, offset: usize) -> F { + // SAFETY: `object` is ours. + let f = unsafe { (*object).vtable.0[offset / 8] }; + // SAFETY: the caller names the slot's signature. + unsafe { std::mem::transmute_copy(&f) } + } + + #[test] + fn ordinal_one_resolves_to_create() { + let r = HleResolver::new(HostPolicy::none()); + assert_eq!( + r.classify("GameInput.dll", &ImportSymbol::Ordinal(1)), + Some(Provenance::Hle) + ); + assert_eq!(r.classify("GameInput.dll", &ImportSymbol::Ordinal(2)), None); + } + + #[test] + fn startup_sees_no_devices() { + type Register = extern "system" fn( + This, + *const c_void, + u32, + u32, + u32, + *mut c_void, + *const c_void, + *mut u64, + ) -> HRESULT; + type Reading = extern "system" fn(This, u32, *const c_void, Out) -> HRESULT; + type Find = extern "system" fn(This, *const c_void, Out) -> HRESULT; + + let mut input = std::ptr::null(); + assert_eq!(GameInputCreate(&mut input), S_OK); + assert!(!input.is_null()); + + let mut token = 0; + let register = slot::(input, 0x48); + let null = std::ptr::null_mut(); + assert_eq!( + register(input, null, 0x40130, 1, 1, null, null, &mut token), + S_OK + ); + assert_ne!(token, 0); + + let mut out = 0x1234 as *const c_void; + let reading = slot::(input, 0x20); + assert_eq!(reading(input, 4, null, &mut out), READING_NOT_FOUND); + assert!(out.is_null()); + out = 0x1234 as *const c_void; + let find = slot::(input, 0x80); + assert_eq!(find(input, null, &mut out), DEVICE_NOT_FOUND); + assert!(out.is_null()); + } +} diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index c3faa3e..9062464 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -3,10 +3,13 @@ //! Only the differences live here; everything else passes through to the //! host (see `HostPolicy`). #![allow(non_snake_case)] +// Title code calls these through its import table, passing pointers the real +// API would trust. +#![allow(clippy::not_unsafe_ptr_arg_deref)] -use std::ffi::c_void; +use std::ffi::{CStr, c_void}; -use crate::{HleModule, hle_export, runtime}; +use crate::{HleModule, HostPolicy, hle_export, registry, runtime}; /// `GetModuleHandleW(NULL)` must return the title's image, not our exe. pub extern "system" fn GetModuleHandleW(name: *const u16) -> *mut c_void { @@ -24,6 +27,207 @@ pub extern "system" fn GetModuleHandleA(name: *const u8) -> *mut c_void { host::get_module_handle_a(name) } +/// A title image's path is its original file, not our cache copy; +/// `NULL` means the title's exe. +pub extern "system" fn GetModuleFileNameW(module: *mut c_void, out: *mut u16, size: u32) -> u32 { + let Some(path) = title_path(module) else { + return host::get_module_file_name_w(module, out, size); + }; + let wide: Vec = path.encode_utf16().collect(); + // SAFETY: the title passes a buffer of `size` characters. + copy_truncated(&wide, unsafe { + std::slice::from_raw_parts_mut(out, size as usize) + }) +} + +/// See [`GetModuleFileNameW`]. +pub extern "system" fn GetModuleFileNameA(module: *mut c_void, out: *mut u8, size: u32) -> u32 { + let Some(path) = title_path(module) else { + return host::get_module_file_name_a(module, out, size); + }; + // SAFETY: the title passes a buffer of `size` bytes. + copy_truncated(path.as_bytes(), unsafe { + std::slice::from_raw_parts_mut(out, size as usize) + }) +} + +fn title_path(module: *mut c_void) -> Option { + let base = if module.is_null() { + runtime::main_image()? + } else { + module as usize + }; + Some(runtime::image_path(base)?.to_string_lossy().into_owned()) +} + +/// `GetModuleFileName`'s contract: copy with a NUL; if it does not fit, +/// truncate to the buffer, report `ERROR_INSUFFICIENT_BUFFER` and return +/// the buffer size. +fn copy_truncated(text: &[T], out: &mut [T]) -> u32 { + let Some(room) = out.len().checked_sub(1) else { + host::set_last_error(ERROR_INSUFFICIENT_BUFFER); + return 0; + }; + let n = text.len().min(room); + out[..n].copy_from_slice(&text[..n]); + out[n] = T::default(); + if n < text.len() { + host::set_last_error(ERROR_INSUFFICIENT_BUFFER); + return out.len() as u32; + } + n as u32 +} + +const ERROR_INSUFFICIENT_BUFFER: u32 = 122; + +/// Console-only DLLs we implement load as a pseudo handle (titles load +/// `xgameruntime.dll` this way); anything else loads on the host. +pub extern "system" fn LoadLibraryExA( + name: *const u8, + file: *mut c_void, + flags: u32, +) -> *mut c_void { + if !name.is_null() { + // SAFETY: the title passes a NUL-terminated file name. + let text = unsafe { CStr::from_ptr(name.cast()) }.to_string_lossy(); + if let Some(handle) = console_module(&text) { + return handle; + } + } + host::load_library_ex_a(name, file, flags) +} + +/// See [`LoadLibraryExA`]. +pub extern "system" fn LoadLibraryExW( + name: *const u16, + file: *mut c_void, + flags: u32, +) -> *mut c_void { + if !name.is_null() { + // SAFETY: the title passes a NUL-terminated file name. + let text = unsafe { + let len = (0..).take_while(|&i| *name.add(i) != 0).count(); + String::from_utf16_lossy(std::slice::from_raw_parts(name, len)) + }; + if let Some(handle) = console_module(&text) { + return handle; + } + } + host::load_library_ex_w(name, file, flags) +} + +pub extern "system" fn LoadLibraryA(name: *const u8) -> *mut c_void { + LoadLibraryExA(name, std::ptr::null_mut(), 0) +} + +pub extern "system" fn LoadLibraryW(name: *const u16) -> *mut c_void { + LoadLibraryExW(name, std::ptr::null_mut(), 0) +} + +/// Looks up our implementations behind a pseudo handle; real modules go to +/// the host. +pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void { + let Some(m) = registry().iter().find(|m| handle(m) == module) else { + return host::get_proc_address(module, name); + }; + // Values below 0x10000 are ordinals; we export by name only. + if (name as usize) < 0x1_0000 { + tracing::warn!( + module = m.name, + ordinal = name as usize, + "GetProcAddress by ordinal" + ); + return std::ptr::null_mut(); + } + // SAFETY: not an ordinal, so the title passes a NUL-terminated name. + let name = unsafe { CStr::from_ptr(name.cast()) }.to_string_lossy(); + match m.exports.iter().find(|e| e.name == name) { + Some(e) => e.address as *mut c_void, + None => { + tracing::warn!(module = m.name, %name, "GetProcAddress: not implemented"); + std::ptr::null_mut() + } + } +} + +pub extern "system" fn FreeLibrary(module: *mut c_void) -> i32 { + if registry().iter().any(|m| handle(m) == module) { + return 1; + } + host::free_library(module) +} + +/// Title debug output goes to our log (no debugger needs to be attached). +pub extern "system" fn OutputDebugStringA(text: *const u8) { + if !text.is_null() { + // SAFETY: the title passes a NUL-terminated string. + let text = unsafe { CStr::from_ptr(text.cast()) }.to_string_lossy(); + tracing::info!(target: "title", "{}", text.trim_end()); + } +} + +/// See [`OutputDebugStringA`]. +pub extern "system" fn OutputDebugStringW(text: *const u16) { + if !text.is_null() { + // SAFETY: the title passes a NUL-terminated string. + let text = unsafe { + let len = (0..).take_while(|&i| *text.add(i) != 0).count(); + String::from_utf16_lossy(std::slice::from_raw_parts(text, len)) + }; + tracing::info!(target: "title", "{}", text.trim_end()); + } +} + +/// The CRT's `exit`, through which the title's entry point returns: logs +/// the code and the caller, then exits on the host. +pub extern "C" fn exit(code: i32) -> ! { + tracing::warn!(code, from = %host::callers(), "title exits"); + host::exit(code) +} + +/// The CRT's `abort` (also reached from `terminate`): logged like [`exit`]. +pub extern "C" fn abort() -> ! { + tracing::error!(from = %host::callers(), "title aborts"); + host::abort() +} + +/// The CRT's `terminate` and the STL's invalid-argument exit: logged, then +/// the host's `abort`. +pub extern "C" fn terminate() -> ! { + tracing::error!(from = %host::callers(), "title calls terminate"); + host::abort() +} + +/// See [`terminate`]. +pub extern "C" fn _invalid_parameter_noinfo_noreturn() -> ! { + tracing::error!(from = %host::callers(), "title passed an invalid parameter"); + host::abort() +} + +/// See [`exit`]; only the current process is logged. +pub extern "system" fn TerminateProcess(process: *mut c_void, code: u32) -> i32 { + if process as isize == -1 { + tracing::warn!(code, from = %host::callers(), "title terminates the process"); + } + host::terminate_process(process, code) +} + +/// The pseudo handle of one of our modules: its address, never a real image. +fn handle(m: &HleModule) -> *mut c_void { + m as *const HleModule as *mut c_void +} + +fn console_module(path: &str) -> Option<*mut c_void> { + let file = path.rsplit(['\\', '/']).next().unwrap_or(path); + // DLLs the host has too are real host modules, whatever `--strict` says. + if HostPolicy::default().allows(file) { + return None; + } + let m = registry().iter().find(|m| m.serves(file))?; + tracing::info!(dll = file, "loaded as a pseudo module"); + Some(handle(m)) +} + pub(crate) fn module() -> HleModule { HleModule { name: "kernel", @@ -31,8 +235,29 @@ pub(crate) fn module() -> HleModule { "kernel32.dll", "kernelbase.dll", "api-ms-win-core-libraryloader-*", + "api-ms-win-core-processthreads-*", + "api-ms-win-core-debug-*", + "api-ms-win-crt-runtime-*", + ], + exports: vec![ + hle_export!(GetModuleHandleW), + hle_export!(GetModuleHandleA), + hle_export!(GetModuleFileNameW), + hle_export!(GetModuleFileNameA), + hle_export!(LoadLibraryExA), + hle_export!(LoadLibraryExW), + hle_export!(LoadLibraryA), + hle_export!(LoadLibraryW), + hle_export!(GetProcAddress), + hle_export!(FreeLibrary), + hle_export!(OutputDebugStringA), + hle_export!(OutputDebugStringW), + hle_export!(exit), + hle_export!(abort), + hle_export!(terminate), + hle_export!(_invalid_parameter_noinfo_noreturn), + hle_export!(TerminateProcess), ], - exports: vec![hle_export!(GetModuleHandleW), hle_export!(GetModuleHandleA)], } } @@ -40,14 +265,105 @@ pub(crate) fn module() -> HleModule { mod host { use std::ffi::c_void; + use windows_sys::Win32::Foundation::{FreeLibrary, SetLastError}; + use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; + use windows_sys::Win32::System::LibraryLoader::{ + GetModuleFileNameA, GetModuleFileNameW, GetModuleHandleA, GetModuleHandleW, GetProcAddress, + LoadLibraryExA, LoadLibraryExW, + }; + use windows_sys::Win32::System::Threading::TerminateProcess; + + unsafe extern "C" { + #[link_name = "exit"] + fn crt_exit(code: i32) -> !; + #[link_name = "abort"] + fn crt_abort() -> !; + } + + // SAFETY (every function): forwarding the title's own arguments to the + // host API of the same name. + pub(super) fn get_module_handle_w(name: *const u16) -> *mut c_void { - // SAFETY: forwarding the title's own argument to the host API. - unsafe { windows_sys::Win32::System::LibraryLoader::GetModuleHandleW(name) } + // SAFETY: see above. + unsafe { GetModuleHandleW(name) } } pub(super) fn get_module_handle_a(name: *const u8) -> *mut c_void { - // SAFETY: forwarding the title's own argument to the host API. - unsafe { windows_sys::Win32::System::LibraryLoader::GetModuleHandleA(name) } + // SAFETY: see above. + unsafe { GetModuleHandleA(name) } + } + + pub(super) fn get_module_file_name_w(module: *mut c_void, out: *mut u16, size: u32) -> u32 { + // SAFETY: see above. + unsafe { GetModuleFileNameW(module, out, size) } + } + + pub(super) fn get_module_file_name_a(module: *mut c_void, out: *mut u8, size: u32) -> u32 { + // SAFETY: see above. + unsafe { GetModuleFileNameA(module, out, size) } + } + + pub(super) fn set_last_error(code: u32) { + // SAFETY: see above. + unsafe { SetLastError(code) } + } + + pub(super) fn load_library_ex_a(name: *const u8, file: *mut c_void, flags: u32) -> *mut c_void { + // SAFETY: see above. + unsafe { LoadLibraryExA(name, file, flags) } + } + + pub(super) fn load_library_ex_w( + name: *const u16, + file: *mut c_void, + flags: u32, + ) -> *mut c_void { + // SAFETY: see above. + unsafe { LoadLibraryExW(name, file, flags) } + } + + pub(super) fn get_proc_address(module: *mut c_void, name: *const u8) -> *mut c_void { + // SAFETY: see above. + unsafe { GetProcAddress(module, name) }.map_or(std::ptr::null_mut(), |f| f as *mut c_void) + } + + pub(super) fn free_library(module: *mut c_void) -> i32 { + // SAFETY: see above. + unsafe { FreeLibrary(module) } + } + + pub(super) fn exit(code: i32) -> ! { + // SAFETY: see above. + unsafe { crt_exit(code) } + } + + pub(super) fn abort() -> ! { + // SAFETY: see above. + unsafe { crt_abort() } + } + + pub(super) fn terminate_process(process: *mut c_void, code: u32) -> i32 { + // SAFETY: see above. + unsafe { TerminateProcess(process, code) } + } + + /// Our caller's callers, as `module+rva`. + pub(super) fn callers() -> String { + let mut frames = [std::ptr::null_mut(); 12]; + // SAFETY: fills at most `frames.len()` return addresses. + let n = unsafe { + RtlCaptureStackBackTrace( + 2, + frames.len() as u32, + frames.as_mut_ptr(), + std::ptr::null_mut(), + ) + }; + let names: Vec<_> = frames[..usize::from(n)] + .iter() + .map(|&f| victory_loader::locate(f as usize)) + .collect(); + names.join(" < ") } } @@ -62,4 +378,70 @@ mod host { pub(super) fn get_module_handle_a(_: *const u8) -> *mut c_void { std::ptr::null_mut() } + + pub(super) fn load_library_ex_a(_: *const u8, _: *mut c_void, _: u32) -> *mut c_void { + std::ptr::null_mut() + } + + pub(super) fn get_module_file_name_w(_: *mut c_void, _: *mut u16, _: u32) -> u32 { + 0 + } + + pub(super) fn get_module_file_name_a(_: *mut c_void, _: *mut u8, _: u32) -> u32 { + 0 + } + + pub(super) fn set_last_error(_: u32) {} + + pub(super) fn load_library_ex_w(_: *const u16, _: *mut c_void, _: u32) -> *mut c_void { + std::ptr::null_mut() + } + + pub(super) fn get_proc_address(_: *mut c_void, _: *const u8) -> *mut c_void { + std::ptr::null_mut() + } + + pub(super) fn free_library(_: *mut c_void) -> i32 { + 0 + } + + pub(super) fn exit(code: i32) -> ! { + std::process::exit(code) + } + + pub(super) fn abort() -> ! { + std::process::abort() + } + + pub(super) fn terminate_process(_: *mut c_void, code: u32) -> i32 { + std::process::exit(code as i32) + } + + pub(super) fn callers() -> String { + String::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn title_images_report_their_original_path() { + let base = 0x7000_0000_0000; + runtime::set_image_path(base, std::path::Path::new(r"C:\title\game.exe")); + let module = base as *mut c_void; + let mut buf = [0xFFFFu16; 32]; + let n = GetModuleFileNameW(module, buf.as_mut_ptr(), buf.len() as u32); + assert_eq!( + String::from_utf16_lossy(&buf[..n as usize]), + r"C:\title\game.exe" + ); + assert_eq!(buf[n as usize], 0); + + // Too small: truncated, NUL-terminated, the buffer size returned. + let mut small = [0u8; 4]; + assert_eq!(GetModuleFileNameA(module, small.as_mut_ptr(), 4), 4); + assert_eq!(&small, &[b'C', b':', b'\\', 0]); + } } diff --git a/crates/victory-hle/src/modules/lifecycle.rs b/crates/victory-hle/src/modules/lifecycle.rs new file mode 100644 index 0000000..309103f --- /dev/null +++ b/crates/victory-hle/src/modules/lifecycle.rs @@ -0,0 +1,242 @@ +//! The title's life cycle. A console title is never told it is closing: +//! quitting it first suspends it (its suspend routines run, and it has a +//! second to save) and then ends the process. Closing the title's window +//! does the same here. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] +#![allow(clippy::too_many_arguments)] + +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Mutex, MutexGuard}; +use std::time::Duration; + +use windows_sys::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, WPARAM}; +use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess}; +use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, HMENU}; +use windows_sys::core::{PCSTR, PCWSTR, w}; + +use crate::{HleModule, hle_export}; + +type Routine = extern "system" fn(quiesced: u8, context: *mut c_void); + +/// Registration id, routine and context of each suspend routine. +static ROUTINES: Mutex> = Mutex::new(Vec::new()); + +fn routines() -> MutexGuard<'static, Vec<(usize, Routine, usize)>> { + ROUTINES.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// How long the console lets suspend routines run before it ends the title. +const SUSPEND_DEADLINE: Duration = Duration::from_secs(1); + +const ERROR_INVALID_PARAMETER: u32 = 87; + +pub extern "system" fn RegisterAppStateChangeNotification( + routine: Option, + context: *mut c_void, + registration: *mut usize, +) -> u32 { + let Some(routine) = routine else { + return ERROR_INVALID_PARAMETER; + }; + if registration.is_null() { + return ERROR_INVALID_PARAMETER; + } + static NEXT: AtomicUsize = AtomicUsize::new(1); + let id = NEXT.fetch_add(1, Ordering::Relaxed); + routines().push((id, routine, context as usize)); + // SAFETY: checked non-null; the title passes room for its registration. + unsafe { registration.write(id) }; + 0 +} + +pub extern "system" fn UnregisterAppStateChangeNotification(registration: usize) { + routines().retain(|&(id, ..)| id != registration); +} + +/// The window procedure a title window had before ours. +const TITLE_PROC: PCWSTR = w!("victory.wndproc"); + +pub extern "system" fn CreateWindowExW( + ex_style: u32, + class: PCWSTR, + name: PCWSTR, + style: u32, + x: i32, + y: i32, + width: i32, + height: i32, + parent: HWND, + menu: HMENU, + instance: HINSTANCE, + param: *const c_void, +) -> HWND { + // SAFETY: the title's own arguments, forwarded. + let hwnd = unsafe { + wm::CreateWindowExW( + ex_style, class, name, style, x, y, width, height, parent, menu, instance, param, + ) + }; + hook(hwnd); + hwnd +} + +/// See [`CreateWindowExW`]. +pub extern "system" fn CreateWindowExA( + ex_style: u32, + class: PCSTR, + name: PCSTR, + style: u32, + x: i32, + y: i32, + width: i32, + height: i32, + parent: HWND, + menu: HMENU, + instance: HINSTANCE, + param: *const c_void, +) -> HWND { + // SAFETY: the title's own arguments, forwarded. + let hwnd = unsafe { + wm::CreateWindowExA( + ex_style, class, name, style, x, y, width, height, parent, menu, instance, param, + ) + }; + hook(hwnd); + hwnd +} + +/// Puts our procedure in front of the title's. +fn hook(hwnd: HWND) { + if hwnd.is_null() { + return; + } + // SAFETY: a window this thread just created. The title's procedure is + // stored before ours can run. + unsafe { + let title = wm::GetWindowLongPtrW(hwnd, wm::GWLP_WNDPROC); + wm::SetPropW(hwnd, TITLE_PROC, title as *mut c_void); + wm::SetWindowLongPtrW(hwnd, wm::GWLP_WNDPROC, window_proc as *const () as isize); + } +} + +extern "system" fn window_proc( + hwnd: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, +) -> LRESULT { + // A user close (close button, Alt+F4, window or taskbar menu); a + // console title never sees one, nor a WM_CLOSE from it. + if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_CLOSE as usize { + quit(); + return 0; + } + // SAFETY: the procedure `hook` stored, called the way the system would. + unsafe { + let title = wm::GetPropW(hwnd, TITLE_PROC); + if message == wm::WM_NCDESTROY { + wm::RemovePropW(hwnd, TITLE_PROC); + } + let title = std::mem::transmute::<*mut c_void, wm::WNDPROC>(title); + wm::CallWindowProcW(title, hwnd, message, wparam, lparam) + } +} + +/// Suspends the title as the console would on quit, then ends the process. +fn quit() { + static QUITTING: AtomicBool = AtomicBool::new(false); + if QUITTING.swap(true, Ordering::Relaxed) { + return; + } + let suspend = routines().clone(); + tracing::info!(routines = suspend.len(), "window closed: suspending the title"); + // Not on the window thread: titles hand the suspend to that thread and + // wait for it inside the routine. + std::thread::spawn(move || { + for (_, routine, context) in suspend { + routine(1, context as *mut c_void); + } + tracing::info!("title suspended; ending it"); + end(); + }); + std::thread::spawn(|| { + std::thread::sleep(SUSPEND_DEADLINE); + tracing::warn!("title did not finish suspending in time; ending it"); + end(); + }); +} + +fn end() { + // SAFETY: ends this process, as the console ends a suspended title. + unsafe { TerminateProcess(GetCurrentProcess(), 0) }; +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "lifecycle", + dlls: &[ + "api-ms-win-core-psm-appnotify-*", + "ext-ms-win-rtcore-ntuser-window-*", + ], + exports: vec![ + hle_export!(RegisterAppStateChangeNotification), + hle_export!(UnregisterAppStateChangeNotification), + hle_export!(CreateWindowExW), + hle_export!(CreateWindowExA), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + extern "system" fn noop(_: u8, _: *mut c_void) {} + + #[test] + fn registrations_come_and_go() { + let (mut a, mut b) = (0, 0); + assert_eq!( + RegisterAppStateChangeNotification(Some(noop), std::ptr::null_mut(), &mut a), + 0 + ); + assert_eq!( + RegisterAppStateChangeNotification(Some(noop), std::ptr::null_mut(), &mut b), + 0 + ); + UnregisterAppStateChangeNotification(a); + let left: Vec<_> = routines().iter().map(|r| r.0).collect(); + assert_eq!(left, [b]); + } + + #[test] + fn hooked_windows_still_reach_the_title_procedure() { + let null = std::ptr::null_mut(); + let hwnd = CreateWindowExW( + 0, + w!("STATIC"), + w!("before"), + 0, + 0, + 0, + 10, + 10, + null, + null, + null, + std::ptr::null(), + ); + assert!(!hwnd.is_null()); + let mut text = [0u16; 16]; + // SAFETY: our window; the buffer holds 16 characters. + unsafe { + wm::SetWindowTextW(hwnd, w!("after")); + let n = wm::GetWindowTextW(hwnd, text.as_mut_ptr(), 16); + assert_eq!(String::from_utf16_lossy(&text[..n as usize]), "after"); + assert!(!wm::GetPropW(hwnd, TITLE_PROC).is_null()); + wm::DestroyWindow(hwnd); + } + } +} diff --git a/crates/victory-hle/src/modules/mod.rs b/crates/victory-hle/src/modules/mod.rs index 0d0f47b..39bd303 100644 --- a/crates/victory-hle/src/modules/mod.rs +++ b/crates/victory-hle/src/modules/mod.rs @@ -5,15 +5,41 @@ //! Run `victory census` over your titles to see what is still missing. //! //! Planned areas (driven by census results, not by completeness): -//! `xmem` (console memory types, GPU-visible allocations), `file` (package -//! paths), `thread` (TLS callbacks for title threads), `d3d12x` (bridge to -//! `victory-gpu`), `xaudio2`, `gameinput`, `xuser`/`xstore` stubs. +//! `file` (package paths), `thread` (TLS callbacks for title threads), +//! `xaudio2`, `xstore` stubs. +pub mod audio; +pub mod d3d12x; +#[cfg(windows)] +pub mod files; +pub mod gameinput; pub mod kernel; +#[cfg(windows)] +pub mod lifecycle; +pub mod storage; +pub mod xasync; +pub mod xgame; pub mod xgameruntime; +#[cfg(windows)] +pub mod xmem; +pub mod xsystem; +pub mod xuser; use crate::HleModule; pub(crate) fn all() -> Vec { - vec![kernel::module(), xgameruntime::module()] + let mut all = vec![ + kernel::module(), + xgameruntime::module(), + gameinput::module(), + d3d12x::module(), + audio::module(), + ]; + #[cfg(windows)] + all.push(files::module()); + #[cfg(windows)] + all.push(lifecycle::module()); + #[cfg(windows)] + all.push(xmem::module()); + all } diff --git a/crates/victory-hle/src/modules/storage.rs b/crates/victory-hle/src/modules/storage.rs new file mode 100644 index 0000000..d30d099 --- /dev/null +++ b/crates/victory-hle/src/modules/storage.rs @@ -0,0 +1,200 @@ +//! Persistent local storage: a host folder of the title's own +//! (`runtime::Title::storage`, under the data directory, never the cache) +//! with the quota its manifest declares, seen by the title as a drive +//! (`files`). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::path::Path; + +use super::xasync::{self, AsyncBlock, E_ABORT}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, S_OK, add_ref, missing, put, + put_string, +}; +use crate::runtime; + +pub const PROVIDER: Guid = Guid::new( + 0xf4fa_f4d4, + 0x2d04, + 0x4fce, + [0xb3, 0xe0, 0x47, 0x4a, 0x71, 0x3a, 0x3e, 0x84], +); +pub const IID: Guid = Guid::new( + 0xd294_11df, + 0x0794, + 0x4553, + [0x8b, 0x27, 0x95, 0xfc, 0x02, 0xd0, 0xf7, 0x5d], +); + +pub static OBJECT: Object = Object::new("persistent local storage", &VTABLE); +pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT)]; + +type This = *const Object; + +/// The path titles get: the root of a virtual drive over the folder. On the +/// console storage is a drive of its own, and titles rely on it: Minecraft +/// keeps only what precedes the path's last `:\` and mounts that as a +/// drive, so a host folder such as `C:\Users\..` would make it write to the +/// root of `C:`. None (the path calls fail) before the title is set. +fn folder() -> Option { + let storage = runtime::title().storage; + if storage.as_os_str().is_empty() { + return None; + } + #[cfg(windows)] + return super::files::mount(&storage).map(|letter| format!("{letter}:\\")); + #[cfg(not(windows))] + None +} + +extern "system" fn path_size(_: This, out: *mut usize) -> HRESULT { + match folder() { + Some(path) => put(out, path.len() + 1), + None => NOT_SUPPORTED, + } +} + +extern "system" fn path(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { + match folder() { + Some(path) => put_string(&path, size, buffer, used), + None => NOT_SUPPORTED, + } +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SpaceInfo { + /// Writable now. + pub available_free: u64, + /// Left in the quota. + pub total_free: u64, + pub used: u64, + /// The quota. + pub total: u64, +} + +fn used_bytes(dir: &Path) -> u64 { + let Ok(entries) = std::fs::read_dir(dir) else { + return 0; + }; + entries + .flatten() + .map(|e| match e.metadata() { + Ok(m) if m.is_dir() => used_bytes(&e.path()), + Ok(m) => m.len(), + Err(_) => 0, + }) + .sum() +} + +fn space() -> SpaceInfo { + let title = runtime::title(); + let used = used_bytes(&title.storage); + let free = title.storage_bytes.saturating_sub(used); + // shortcut: the host disk's free space is not checked; do so if a title + // fills its quota on a nearly full disk. + SpaceInfo { + available_free: free, + total_free: free, + used, + total: title.storage_bytes, + } +} + +extern "system" fn space_info(_: This, out: *mut SpaceInfo) -> HRESULT { + put(out, space()) +} + +/// Tells our prompts apart from other calls on the same block. +static PROMPT: u8 = 0; + +/// There is nobody to ask: granted when the quota has room, else declined. +extern "system" fn prompt_for_space(_: This, bytes: u64, block: *mut AsyncBlock) -> HRESULT { + let hr = if bytes <= space().total_free { + S_OK + } else { + E_ABORT + }; + xasync::finished(block, (&raw const PROMPT).cast(), hr) +} + +extern "system" fn prompt_result(_: This, block: *mut AsyncBlock) -> HRESULT { + let none = std::ptr::null_mut(); + xasync::XAsyncGetResult(block, (&raw const PROMPT).cast(), 0, none, none.cast()) +} + +static VTABLE: Methods<8> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + path_size as *const (), // 0x18 + path as *const (), // 0x20 + space_info as *const (), // 0x28 + prompt_for_space as *const (), // 0x30 + prompt_result as *const (), // 0x38 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + #[test] + fn serves_a_drive_over_the_title_folder_and_its_quota() { + type Size = extern "system" fn(This, *mut usize) -> HRESULT; + type Get = extern "system" fn(This, usize, *mut u8, *mut usize) -> HRESULT; + type Space = extern "system" fn(This, *mut SpaceInfo) -> HRESULT; + type Prompt = extern "system" fn(This, u64, *mut AsyncBlock) -> HRESULT; + type Result = extern "system" fn(This, *mut AsyncBlock) -> HRESULT; + let this: This = &OBJECT; + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("save.dat"), [0u8; 100]).unwrap(); + runtime::set_title(runtime::Title { + id: 1, + storage: dir.path().to_owned(), + storage_bytes: 1000, + }); + + // The path is a drive root, never the host folder. + let mut size = 0; + assert_eq!(method::(&OBJECT, 0x18)(this, &mut size), S_OK); + assert_eq!(size, 4, "X:\\ and its NUL"); + let (mut buffer, mut used) = ([0u8; 4], 0); + let get = method::(&OBJECT, 0x20); + assert_eq!(get(this, 4, buffer.as_mut_ptr(), &mut used), S_OK); + let drive = std::str::from_utf8(&buffer[..3]).unwrap(); + assert!(drive.ends_with(":\\"), "{drive}"); + // Title file calls on it reach the folder. + let path = format!("{drive}save.dat\0"); + let mut attributes = [0u8; 36]; + let get_attributes = super::super::files::GetFileAttributesExW; + let wide: Vec = path.encode_utf16().collect(); + assert_ne!( + get_attributes(wide.as_ptr(), 0, attributes.as_mut_ptr().cast()), + 0 + ); + + let mut info = SpaceInfo { + available_free: 0, + total_free: 0, + used: 0, + total: 0, + }; + assert_eq!(method::(&OBJECT, 0x28)(this, &mut info), S_OK); + assert_eq!((info.used, info.total_free, info.total), (100, 900, 1000)); + + let prompt = method::(&OBJECT, 0x30); + let result = method::(&OBJECT, 0x38); + for (bytes, expect) in [(900, S_OK), (901, E_ABORT)] { + let mut block = AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + assert_eq!(prompt(this, bytes, &mut block), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut block, true), expect); + assert_eq!(result(this, &mut block), expect, "{bytes} bytes"); + } + } +} diff --git a/crates/victory-hle/src/modules/xasync.rs b/crates/victory-hle/src/modules/xasync.rs new file mode 100644 index 0000000..f73d828 --- /dev/null +++ b/crates/victory-hle/src/modules/xasync.rs @@ -0,0 +1,959 @@ +//! XTaskQueue and XAsync: the runtime's callback queues and async-call +//! blocks, served as the task-queue provider's object from `QueryApiImpl`. +//! +//! As documented for the public API: a queue has a work port and a +//! completion port, each dispatched manually (the title calls dispatch), +//! on a thread pool, serialised on one thread, or immediately on the +//! submitting thread. A null queue handle means the process queue. An +//! async block's system area holds its status and result size, so both +//! stay readable after our state for the call is gone. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::collections::{HashMap, VecDeque}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard}; +use std::time::Duration; + +use super::xgameruntime::{Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing}; + +/// The task-queue provider; it is also the interface id titles ask for. +pub const PROVIDER: Guid = Guid { + data1: 0x073b_7dcb, + data2: 0x1fcf, + data3: 0x4030, + data4: [0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28], +}; + +pub const E_PENDING: HRESULT = 0x8000_000A_u32 as i32; +pub const E_ABORT: HRESULT = 0x8000_4004_u32 as i32; +pub const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32; +pub const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32; +pub const E_NOT_SUFFICIENT_BUFFER: HRESULT = 0x8007_007A_u32 as i32; +pub const E_ILLEGAL_METHOD_CALL: HRESULT = 0x8000_000E_u32 as i32; + +const WORK: u32 = 0; +const COMPLETION: u32 = 1; +const INFINITE: u32 = u32::MAX; + +type Callback = extern "system" fn(*mut c_void, bool); +type MonitorCallback = extern "system" fn(*mut c_void, *const Queue, u32); +type TerminatedCallback = extern "system" fn(*mut c_void); +type CompletionRoutine = extern "system" fn(*mut AsyncBlock); +type Provider = extern "system" fn(u32, *const ProviderData) -> HRESULT; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Mode { + Manual, + ThreadPool, + Serialized, + Immediate, +} + +impl Mode { + fn from_raw(mode: u32) -> Option { + [ + Mode::Manual, + Mode::ThreadPool, + Mode::Serialized, + Mode::Immediate, + ] + .get(mode as usize) + .copied() + } +} + +/// A title callback and its context (addresses, so tasks can cross threads). +#[derive(Clone, Copy)] +struct Task { + context: usize, + callback: usize, +} + +impl Task { + fn new(context: *mut c_void, callback: Callback) -> Task { + Task { + context: context as usize, + callback: callback as usize, + } + } + + fn run(self, canceled: bool) { + // SAFETY: built from a `Callback` in `new`. + let callback: Callback = unsafe { std::mem::transmute(self.callback) }; + callback(self.context as *mut c_void, canceled); + } +} + +struct Port { + mode: Mode, + tasks: Mutex>, + ready: Condvar, +} + +impl Port { + fn new(mode: Mode) -> Arc { + let port = Arc::new(Port { + mode, + tasks: Mutex::default(), + ready: Condvar::new(), + }); + if mode == Mode::Serialized { + // shortcut: the worker lives as long as the process, even after + // the queue closes; join it on close if titles churn queues. + let worker = port.clone(); + std::thread::spawn(move || { + loop { + if let Some(task) = worker.take(INFINITE) { + task.run(false); + } + } + }); + } + port + } + + fn submit(&self, task: Task) { + match self.mode { + Mode::Immediate => task.run(false), + // shortcut: a thread per callback, not a pool; fine at startup + // rates, pool them if a title submits thousands per frame. + Mode::ThreadPool => drop(std::thread::spawn(move || task.run(false))), + Mode::Manual | Mode::Serialized => { + lock(&self.tasks).push_back(task); + self.ready.notify_one(); + } + } + } + + /// The next queued task, waiting up to `timeout_ms`. + fn take(&self, timeout_ms: u32) -> Option { + let tasks = lock(&self.tasks); + let mut tasks = if timeout_ms == INFINITE { + self.ready + .wait_while(tasks, |t| t.is_empty()) + .unwrap_or_else(|e| e.into_inner()) + } else { + let timeout = Duration::from_millis(timeout_ms.into()); + self.ready + .wait_timeout_while(tasks, timeout, |t| t.is_empty()) + .unwrap_or_else(|e| e.into_inner()) + .0 + }; + tasks.pop_front() + } +} + +/// A queue handle is `Arc::into_raw` of this; duplicating and closing a +/// handle add and drop a reference. +pub struct Queue { + ports: [Arc; 2], + monitors: Mutex>, + terminated: AtomicBool, +} + +impl Queue { + fn new(ports: [Arc; 2]) -> Arc { + Arc::new(Queue { + ports, + monitors: Mutex::default(), + terminated: AtomicBool::new(false), + }) + } + + fn submit(self: &Arc, port: u32, delay_ms: u32, task: Task) -> HRESULT { + if port > COMPLETION { + return E_INVALIDARG; + } + if self.terminated.load(Ordering::Acquire) { + return E_ABORT; + } + if delay_ms == 0 { + self.deliver(port, task); + } else { + let queue = self.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(delay_ms.into())); + queue.deliver(port, task); + }); + } + S_OK + } + + fn deliver(self: &Arc, port: u32, task: Task) { + self.ports[port as usize].submit(task); + // Copied out: a monitor may unregister itself. + let monitors = lock(&self.monitors).clone(); + for (_, context, callback) in monitors { + // SAFETY: stored from a `MonitorCallback` in `register_monitor`. + let callback: MonitorCallback = unsafe { std::mem::transmute(callback) }; + callback(context as *mut c_void, Arc::as_ptr(self), port); + } + } +} + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The process queue: `None` until first used (then a thread-pool queue), +/// `Some(None)` once the title clears it. +static PROCESS_QUEUE: Mutex>>> = Mutex::new(None); + +fn process_queue() -> Option> { + lock(&PROCESS_QUEUE) + .get_or_insert_with(|| { + Some(Queue::new([ + Port::new(Mode::ThreadPool), + Port::new(Mode::ThreadPool), + ])) + }) + .clone() +} + +/// A new reference to the queue behind `handle` (null: the process queue). +fn queue(handle: *const Queue) -> Option> { + if handle.is_null() { + return process_queue(); + } + // SAFETY: a handle we returned, which the title has not closed. + unsafe { + Arc::increment_strong_count(handle); + Some(Arc::from_raw(handle)) + } +} + +pub fn XTaskQueueCreate(work: u32, completion: u32, out: *mut *const Queue) -> HRESULT { + let (Some(work), Some(completion)) = (Mode::from_raw(work), Mode::from_raw(completion)) else { + return E_INVALIDARG; + }; + if out.is_null() { + return E_INVALIDARG; + } + let queue = Queue::new([Port::new(work), Port::new(completion)]); + // SAFETY: checked non-null; the title passes room for a handle. + unsafe { out.write(Arc::into_raw(queue)) }; + S_OK +} + +/// A port handle points at the port, which its queue keeps alive. +pub fn XTaskQueueGetPort(handle: *const Queue, port: u32, out: *mut *const c_void) -> HRESULT { + let Some(queue) = queue(handle) else { + return E_INVALIDARG; + }; + if port > COMPLETION || out.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null. + unsafe { out.write(Arc::as_ptr(&queue.ports[port as usize]).cast()) }; + S_OK +} + +pub fn XTaskQueueCreateComposite( + work: *const c_void, + completion: *const c_void, + out: *mut *const Queue, +) -> HRESULT { + if work.is_null() || completion.is_null() || out.is_null() { + return E_INVALIDARG; + } + let port = |p: *const c_void| { + // SAFETY: a port handle from `XTaskQueueGetPort`, whose queue is open. + unsafe { + Arc::increment_strong_count(p.cast::()); + Arc::from_raw(p.cast::()) + } + }; + let queue = Queue::new([port(work), port(completion)]); + // SAFETY: checked non-null. + unsafe { out.write(Arc::into_raw(queue)) }; + S_OK +} + +pub fn XTaskQueueDuplicateHandle(handle: *const Queue, out: *mut *const Queue) -> HRESULT { + match queue(handle) { + Some(queue) if !out.is_null() => { + // SAFETY: checked non-null. + unsafe { out.write(Arc::into_raw(queue)) }; + S_OK + } + _ => E_INVALIDARG, + } +} + +pub fn XTaskQueueCloseHandle(handle: *const Queue) { + if !handle.is_null() { + // SAFETY: a handle we returned; this drops its reference. + unsafe { Arc::decrement_strong_count(handle) }; + } +} + +/// Runs one queued callback of a manual port; false if none came in time. +pub fn XTaskQueueDispatch(handle: *const Queue, port: u32, timeout_ms: u32) -> bool { + let Some(queue) = queue(handle) else { + return false; + }; + let Some(port) = queue.ports.get(port as usize) else { + return false; + }; + if port.mode != Mode::Manual { + return false; + } + match port.take(timeout_ms) { + Some(task) => { + task.run(false); + true + } + None => false, + } +} + +pub fn XTaskQueueSubmitDelayedCallback( + handle: *const Queue, + port: u32, + delay_ms: u32, + context: *mut c_void, + callback: Option, +) -> HRESULT { + match (queue(handle), callback) { + (Some(queue), Some(callback)) => queue.submit(port, delay_ms, Task::new(context, callback)), + _ => E_INVALIDARG, + } +} + +/// Cancels what is still queued (callbacks see `canceled`), refuses new +/// work, then calls `callback`. +pub fn XTaskQueueTerminate( + handle: *const Queue, + _wait: bool, + context: *mut c_void, + callback: Option, +) -> HRESULT { + let Some(queue) = queue(handle) else { + return E_INVALIDARG; + }; + queue.terminated.store(true, Ordering::Release); + for port in &queue.ports { + let pending: Vec = lock(&port.tasks).drain(..).collect(); + for task in pending { + task.run(true); + } + } + if let Some(callback) = callback { + callback(context); + } + S_OK +} + +static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1); + +pub fn XTaskQueueRegisterMonitor( + handle: *const Queue, + context: *mut c_void, + callback: Option, + token: *mut u64, +) -> HRESULT { + let (Some(queue), Some(callback)) = (queue(handle), callback) else { + return E_INVALIDARG; + }; + if token.is_null() { + return E_INVALIDARG; + } + let id = NEXT_TOKEN.fetch_add(1, Ordering::Relaxed); + lock(&queue.monitors).push((id, context as usize, callback as usize)); + // SAFETY: checked non-null. + unsafe { token.write(id) }; + S_OK +} + +pub fn XTaskQueueUnregisterMonitor(handle: *const Queue, token: u64) { + if let Some(queue) = queue(handle) { + lock(&queue.monitors).retain(|m| m.0 != token); + } +} + +/// A new handle to the process queue, if there is one. +pub fn XTaskQueueGetCurrentProcessTaskQueue(out: *mut *const Queue) -> bool { + let found = process_queue(); + if !out.is_null() { + // SAFETY: checked non-null. + unsafe { out.write(found.clone().map_or(std::ptr::null(), Arc::into_raw)) }; + } + found.is_some() +} + +pub fn XTaskQueueSetCurrentProcessTaskQueue(handle: *const Queue) { + let new = if handle.is_null() { + None + } else { + queue(handle) + }; + *lock(&PROCESS_QUEUE) = Some(new); +} + +/// An async block: what the title fills in, then the system area. +#[repr(C)] +pub struct AsyncBlock { + pub queue: *const Queue, + pub context: *mut c_void, + pub callback: Option, + /// Ours: [unused, status, result size, unused]. + pub internal: [usize; 4], +} + +#[repr(C)] +pub struct ProviderData { + pub block: *mut AsyncBlock, + pub buffer_size: usize, + pub buffer: *mut c_void, + pub context: *mut c_void, +} + +const OP_BEGIN: u32 = 0; +const OP_DO_WORK: u32 = 1; +const OP_GET_RESULT: u32 = 2; +const OP_CANCEL: u32 = 3; +const OP_CLEANUP: u32 = 4; + +/// One call in flight, until its result is taken or it fails. +struct Call { + provider: Provider, + context: usize, + identity: usize, + done: Mutex, + finished: Condvar, +} + +impl Call { + fn provider( + &self, + op: u32, + block: *mut AsyncBlock, + size: usize, + buffer: *mut c_void, + ) -> HRESULT { + let data = ProviderData { + block, + buffer_size: size, + buffer, + context: self.context as *mut c_void, + }; + (self.provider)(op, &data) + } +} + +/// Calls by block address. +static CALLS: LazyLock>>> = LazyLock::new(Default::default); + +fn call(block: *mut AsyncBlock) -> Option> { + lock(&CALLS).get(&(block as usize)).cloned() +} + +/// The block's status and result-size words. +fn words(block: *mut AsyncBlock) -> (&'static AtomicUsize, &'static AtomicUsize) { + // SAFETY: the title's block outlives the call; its system area is ours. + unsafe { + let internal = std::ptr::addr_of_mut!((*block).internal).cast::(); + (&*internal.add(1), &*internal.add(2)) + } +} + +fn status(block: *mut AsyncBlock) -> HRESULT { + words(block).0.load(Ordering::Acquire) as u32 as i32 +} + +fn release(block: *mut AsyncBlock) { + // Unlocked before the provider runs: it may call back into us. + let removed = lock(&CALLS).remove(&(block as usize)); + if let Some(call) = removed { + call.provider(OP_CLEANUP, block, 0, std::ptr::null_mut()); + } +} + +pub fn XAsyncBegin( + block: *mut AsyncBlock, + context: *mut c_void, + identity: *const c_void, + _identity_name: *const u8, + provider: Option, +) -> HRESULT { + let Some(provider) = provider else { + return E_INVALIDARG; + }; + if block.is_null() || call(block).is_some() { + return E_INVALIDARG; + } + let (status, size) = words(block); + status.store(E_PENDING as u32 as usize, Ordering::Release); + size.store(0, Ordering::Release); + let call = Arc::new(Call { + provider, + context: context as usize, + identity: identity as usize, + done: Mutex::new(false), + finished: Condvar::new(), + }); + lock(&CALLS).insert(block as usize, call.clone()); + // A failed begin fails the call, so the completion routine still runs. + let hr = call.provider(OP_BEGIN, block, 0, std::ptr::null_mut()); + if hr < 0 { + XAsyncComplete(block, hr, 0); + } + S_OK +} + +/// Queues the provider's `DoWork` on the block's work port. +pub fn XAsyncSchedule(block: *mut AsyncBlock, delay_ms: u32) -> HRESULT { + extern "system" fn work(block: *mut c_void, canceled: bool) { + let block = block.cast::(); + let Some(call) = call(block) else { return }; + let hr = if canceled { + E_ABORT + } else { + call.provider(OP_DO_WORK, block, 0, std::ptr::null_mut()) + }; + if hr != E_PENDING { + XAsyncComplete(block, hr, 0); + } + } + if block.is_null() || call(block).is_none() { + return E_INVALIDARG; + } + // SAFETY: a block in flight is valid. + let handle = unsafe { (*block).queue }; + match queue(handle) { + Some(queue) => queue.submit(WORK, delay_ms, Task::new(block.cast(), work)), + None => E_INVALIDARG, + } +} + +/// Records the result (the first one wins), wakes waiters and queues the +/// completion routine on the block's completion port. +pub fn XAsyncComplete(block: *mut AsyncBlock, result: HRESULT, required_size: usize) { + extern "system" fn complete(block: *mut c_void, _canceled: bool) { + let block = block.cast::(); + // SAFETY: read before the status was published; see below. + if let Some(routine) = unsafe { (*block).callback } { + routine(block); + } + } + let Some(call) = call(block) else { return }; + if result == E_PENDING { + return; + } + let mut done = lock(&call.done); + if *done { + return; + } + // Read before publishing: once the status is set, the title may free + // the block. + // SAFETY: a block in flight is valid. + let (handle, routine) = unsafe { ((*block).queue, (*block).callback) }; + let (status, size) = words(block); + if result < 0 || required_size == 0 { + release(block); + } + size.store(required_size, Ordering::Release); + status.store(result as u32 as usize, Ordering::Release); + *done = true; + call.finished.notify_all(); + drop(done); + if routine.is_some() { + let task = Task::new(block.cast(), complete); + match queue(handle) { + Some(queue) if queue.submit(COMPLETION, 0, task) == S_OK => {} + _ => task.run(true), + } + } +} + +pub fn XAsyncGetStatus(block: *mut AsyncBlock, wait: bool) -> HRESULT { + if block.is_null() { + return E_INVALIDARG; + } + if wait && let Some(call) = call(block) { + let done = lock(&call.done); + drop(call.finished.wait_while(done, |d| !*d)); + } + status(block) +} + +pub fn XAsyncGetResultSize(block: *mut AsyncBlock, out: *mut usize) -> HRESULT { + if block.is_null() || out.is_null() { + return E_INVALIDARG; + } + let hr = status(block); + if hr == S_OK { + // SAFETY: checked non-null. + unsafe { out.write(words(block).1.load(Ordering::Acquire)) }; + } + hr +} + +/// Asks the provider to cancel; the call fails with `E_ABORT` unless the +/// provider completed it first. +pub fn XAsyncCancel(block: *mut AsyncBlock) { + if let Some(call) = call(block) { + call.provider(OP_CANCEL, block, 0, std::ptr::null_mut()); + XAsyncComplete(block, E_ABORT, 0); + } +} + +/// Has the provider write the result into `buffer`, then ends the call. +pub fn XAsyncGetResult( + block: *mut AsyncBlock, + identity: *const c_void, + buffer_size: usize, + buffer: *mut c_void, + used: *mut usize, +) -> HRESULT { + if block.is_null() { + return E_INVALIDARG; + } + let hr = status(block); + let size = words(block).1.load(Ordering::Acquire); + if hr != S_OK || size == 0 { + if hr == S_OK && !used.is_null() { + // SAFETY: checked non-null. + unsafe { used.write(0) }; + } + return hr; + } + let Some(call) = call(block) else { + return E_ILLEGAL_METHOD_CALL; + }; + if call.identity != identity as usize { + return E_INVALIDARG; + } + if buffer_size < size || buffer.is_null() { + return E_NOT_SUFFICIENT_BUFFER; + } + let hr = call.provider(OP_GET_RESULT, block, buffer_size, buffer); + if !used.is_null() { + // SAFETY: checked non-null. + unsafe { used.write(size) }; + } + release(block); + hr +} + +/// Starts a call on `block` that is already over: it completes with `hr` +/// and no result data, through the block's completion port as usual. +pub fn finished(block: *mut AsyncBlock, identity: *const c_void, hr: HRESULT) -> HRESULT { + extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data. + let data = unsafe { &*data }; + if op == OP_BEGIN { + XAsyncComplete(data.block, data.context as usize as u32 as i32, 0); + } + S_OK + } + let context = hr as u32 as usize as *mut c_void; + XAsyncBegin(block, context, identity, std::ptr::null(), Some(provider)) +} + +// The object `QueryApiImpl` returns. Each method takes the object first, +// then the API's arguments; slot offsets as titles call them. + +pub static OBJECT: Object = Object::new("task queue", &VTABLE); + +/// Its interface id is the provider's. +pub const INTERFACES: &[Interface] = &[(PROVIDER, PROVIDER, &OBJECT)]; + +type This = *const Object; +extern "system" fn m_get_status(_: This, b: *mut AsyncBlock, wait: u8) -> HRESULT { + XAsyncGetStatus(b, wait != 0) +} +extern "system" fn m_get_result_size(_: This, b: *mut AsyncBlock, out: *mut usize) -> HRESULT { + XAsyncGetResultSize(b, out) +} +extern "system" fn m_cancel(_: This, b: *mut AsyncBlock) { + XAsyncCancel(b) +} +extern "system" fn m_begin( + _: This, + b: *mut AsyncBlock, + context: *mut c_void, + identity: *const c_void, + name: *const u8, + provider: Option, +) -> HRESULT { + XAsyncBegin(b, context, identity, name, provider) +} +extern "system" fn m_schedule(_: This, b: *mut AsyncBlock, delay: u32) -> HRESULT { + XAsyncSchedule(b, delay) +} +extern "system" fn m_complete(_: This, b: *mut AsyncBlock, hr: HRESULT, size: usize) { + XAsyncComplete(b, hr, size) +} +extern "system" fn m_get_result( + _: This, + b: *mut AsyncBlock, + identity: *const c_void, + size: usize, + buffer: *mut c_void, + used: *mut usize, +) -> HRESULT { + XAsyncGetResult(b, identity, size, buffer, used) +} +extern "system" fn m_create( + _: This, + work: u32, + completion: u32, + out: *mut *const Queue, +) -> HRESULT { + XTaskQueueCreate(work, completion, out) +} +extern "system" fn m_create_composite( + _: This, + work: *const c_void, + completion: *const c_void, + out: *mut *const Queue, +) -> HRESULT { + XTaskQueueCreateComposite(work, completion, out) +} +extern "system" fn m_get_port( + _: This, + q: *const Queue, + port: u32, + out: *mut *const c_void, +) -> HRESULT { + XTaskQueueGetPort(q, port, out) +} +extern "system" fn m_duplicate(_: This, q: *const Queue, out: *mut *const Queue) -> HRESULT { + XTaskQueueDuplicateHandle(q, out) +} +extern "system" fn m_dispatch(_: This, q: *const Queue, port: u32, timeout: u32) -> bool { + XTaskQueueDispatch(q, port, timeout) +} +extern "system" fn m_close(_: This, q: *const Queue) { + XTaskQueueCloseHandle(q) +} +extern "system" fn m_submit( + _: This, + q: *const Queue, + port: u32, + context: *mut c_void, + callback: Option, +) -> HRESULT { + XTaskQueueSubmitDelayedCallback(q, port, 0, context, callback) +} +extern "system" fn m_submit_delayed( + _: This, + q: *const Queue, + port: u32, + delay: u32, + context: *mut c_void, + callback: Option, +) -> HRESULT { + XTaskQueueSubmitDelayedCallback(q, port, delay, context, callback) +} +extern "system" fn m_terminate( + _: This, + q: *const Queue, + wait: u8, + context: *mut c_void, + callback: Option, +) -> HRESULT { + XTaskQueueTerminate(q, wait != 0, context, callback) +} +extern "system" fn m_register_monitor( + _: This, + q: *const Queue, + context: *mut c_void, + callback: Option, + token: *mut u64, +) -> HRESULT { + XTaskQueueRegisterMonitor(q, context, callback, token) +} +extern "system" fn m_unregister_monitor(_: This, q: *const Queue, token: u64) { + XTaskQueueUnregisterMonitor(q, token) +} +extern "system" fn m_get_process_queue(_: This, out: *mut *const Queue) -> bool { + XTaskQueueGetCurrentProcessTaskQueue(out) +} +extern "system" fn m_set_process_queue(_: This, q: *const Queue) { + XTaskQueueSetCurrentProcessTaskQueue(q) +} +/// The runtime's debug check that the caller is not a time-critical thread, +/// which every runtime call in a title makes first. +extern "system" fn m_check_thread(_: This) {} + +static VTABLE: Methods<31> = Methods([ + missing::<0> as *const (), // 0x00 QueryInterface + add_ref as *const (), // 0x08 AddRef + add_ref as *const (), // 0x10 Release: the object is static + m_get_status as *const (), // 0x18 + m_get_result_size as *const (), // 0x20 + m_cancel as *const (), // 0x28 + missing::<6> as *const (), // 0x30 run a work callback as a call + m_begin as *const (), // 0x38 + missing::<8> as *const (), // 0x40 + m_schedule as *const (), // 0x48 + m_complete as *const (), // 0x50 + m_get_result as *const (), // 0x58 + m_create as *const (), // 0x60 + m_create_composite as *const (), // 0x68 + m_get_port as *const (), // 0x70 + m_duplicate as *const (), // 0x78 + m_dispatch as *const (), // 0x80 + m_close as *const (), // 0x88 + m_submit as *const (), // 0x90 + m_submit_delayed as *const (), // 0x98 + missing::<20> as *const (), // 0xa0 register a wait handle + missing::<21> as *const (), // 0xa8 unregister it + m_terminate as *const (), // 0xb0 + m_register_monitor as *const (), // 0xb8 + m_unregister_monitor as *const (), // 0xc0 + m_get_process_queue as *const (), // 0xc8 + m_set_process_queue as *const (), // 0xd0 + missing::<27> as *const (), // 0xd8 thread time-sensitivity + missing::<28> as *const (), // 0xe0 + m_check_thread as *const (), // 0xe8 + missing::<30> as *const (), // 0xf0 +]); + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::AtomicU32; + + fn slot(offset: usize) -> F { + crate::modules::xgameruntime::method(&OBJECT, offset) + } + + static RAN: AtomicU32 = AtomicU32::new(0); + extern "system" fn count(context: *mut c_void, canceled: bool) { + RAN.fetch_add( + if canceled { 100 } else { context as u32 }, + Ordering::SeqCst, + ); + } + + #[test] + fn manual_ports_run_callbacks_when_dispatched() { + type Create = extern "system" fn(This, u32, u32, *mut *const Queue) -> HRESULT; + type Submit = extern "system" fn(This, *const Queue, u32, *mut c_void, Callback) -> HRESULT; + type Dispatch = extern "system" fn(This, *const Queue, u32, u32) -> bool; + type Close = extern "system" fn(This, *const Queue); + let this: This = &OBJECT; + let mut q = std::ptr::null(); + assert_eq!(slot::(0x60)(this, 0, 0, &mut q), S_OK); + assert_eq!( + slot::(0x90)(this, q, COMPLETION, 5 as *mut c_void, count), + S_OK + ); + assert_eq!(RAN.load(Ordering::SeqCst), 0, "manual: nothing runs yet"); + assert!( + !slot::(0x80)(this, q, WORK, 0), + "work port is empty" + ); + assert!(slot::(0x80)(this, q, COMPLETION, 0)); + assert_eq!(RAN.load(Ordering::SeqCst), 5); + assert!(!slot::(0x80)(this, q, COMPLETION, 0)); + slot::(0x88)(this, q); + } + + /// A provider that schedules its work and returns a u64 result. + extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data. + let data = unsafe { &*data }; + match op { + OP_BEGIN => XAsyncSchedule(data.block, 0), + OP_DO_WORK => { + XAsyncComplete(data.block, S_OK, 8); + S_OK + } + OP_GET_RESULT => { + // SAFETY: at least 8 bytes, checked by the runtime. + unsafe { data.buffer.cast::().write(data.context as u64) }; + S_OK + } + _ => S_OK, + } + } + + static COMPLETED: AtomicU32 = AtomicU32::new(0); + extern "system" fn completed(_: *mut AsyncBlock) { + COMPLETED.fetch_add(1, Ordering::SeqCst); + } + + #[test] + fn async_calls_complete_and_return_results() { + let mut q = std::ptr::null(); + // Work on a thread pool, completion dispatched by hand. + assert_eq!(XTaskQueueCreate(1, 0, &mut q), S_OK); + let mut block = AsyncBlock { + queue: q, + context: std::ptr::null_mut(), + callback: Some(completed), + internal: [0; 4], + }; + let identity = 0x1d as *const c_void; + assert_eq!( + XAsyncBegin( + &mut block, + 42 as *mut c_void, + identity, + std::ptr::null(), + Some(provider) + ), + S_OK + ); + assert_eq!(XAsyncGetStatus(&mut block, true), S_OK); + let mut size = 0; + assert_eq!(XAsyncGetResultSize(&mut block, &mut size), S_OK); + assert_eq!(size, 8); + assert_eq!(COMPLETED.load(Ordering::SeqCst), 0, "completion is manual"); + assert!(XTaskQueueDispatch(q, COMPLETION, INFINITE)); + assert_eq!(COMPLETED.load(Ordering::SeqCst), 1); + + let mut value = 0u64; + let mut small = 0u32; + let out = (&mut small as *mut u32).cast(); + assert_eq!( + XAsyncGetResult(&mut block, identity, 4, out, std::ptr::null_mut()), + E_NOT_SUFFICIENT_BUFFER + ); + let out = (&mut value as *mut u64).cast(); + let mut used = 0; + assert_eq!( + XAsyncGetResult(&mut block, identity, 8, out, &mut used), + S_OK + ); + assert_eq!((value, used), (42, 8)); + assert!(call(&mut block).is_none(), "the call ends with its result"); + XTaskQueueCloseHandle(q); + } + + #[test] + fn terminate_cancels_what_is_queued() { + static TERMINATED: AtomicBool = AtomicBool::new(false); + extern "system" fn terminated(_: *mut c_void) { + TERMINATED.store(true, Ordering::SeqCst); + } + extern "system" fn note(context: *mut c_void, canceled: bool) { + // SAFETY: the test passes a pointer to its flag. + unsafe { *context.cast::() = canceled }; + } + let mut q = std::ptr::null(); + assert_eq!(XTaskQueueCreate(0, 0, &mut q), S_OK); + let mut canceled = false; + let flag = (&mut canceled as *mut bool).cast(); + assert_eq!( + XTaskQueueSubmitDelayedCallback(q, WORK, 0, flag, Some(note)), + S_OK + ); + assert_eq!( + XTaskQueueTerminate(q, true, std::ptr::null_mut(), Some(terminated)), + S_OK + ); + assert!(canceled && TERMINATED.load(Ordering::SeqCst)); + assert_eq!( + XTaskQueueSubmitDelayedCallback(q, WORK, 0, flag, Some(note)), + E_ABORT + ); + XTaskQueueCloseHandle(q); + } +} diff --git a/crates/victory-hle/src/modules/xgame.rs b/crates/victory-hle/src/modules/xgame.rs new file mode 100644 index 0000000..ff242c0 --- /dev/null +++ b/crates/victory-hle/src/modules/xgame.rs @@ -0,0 +1,172 @@ +//! The title's own id (from its manifest), which runtime areas exist, and +//! game invites and events. Offline no invite arrives and events go +//! nowhere. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{CStr, c_char, c_void}; + +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, token, +}; +use crate::runtime; + +/// Title id and launching another title. +pub const TITLE_PROVIDER: Guid = Guid::new( + 0x973a_344e, + 0x24bf, + 0x4d0f, + [0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29], +); +/// As Minecraft (2022) asks for it. +pub const TITLE_IID: Guid = Guid::new( + 0x2549_f142, + 0x6419, + 0x4a06, + [0x97, 0xb5, 0x93, 0x1a, 0xab, 0x7c, 0x2f, 0x34], +); +/// Feature checks; the interface id is the provider's, as for the next two. +pub const FEATURES: Guid = Guid::new( + 0x8836_fe87, + 0xedb9, + 0x4fe3, + [0x8d, 0xad, 0x05, 0xf0, 0xd2, 0xcd, 0x5b, 0x40], +); +pub const INVITES: Guid = Guid::new( + 0x0651_aae2, + 0x4012, + 0x4077, + [0xbf, 0x84, 0x8b, 0x90, 0x97, 0x09, 0x0e, 0x2c], +); +pub const EVENTS: Guid = Guid::new( + 0xbbfb_dcc7, + 0xbfe7, + 0x409b, + [0xa5, 0xca, 0xed, 0xf0, 0x54, 0x96, 0x0b, 0x4d], +); + +pub static TITLE_OBJECT: Object = Object::new("title", &TITLE_VTABLE); +pub static FEATURES_OBJECT: Object = Object::new("features", &FEATURES_VTABLE); +pub static INVITES_OBJECT: Object = Object::new("invites", &INVITES_VTABLE); +pub static EVENTS_OBJECT: Object = Object::new("events", &EVENTS_VTABLE); + +pub const INTERFACES: &[Interface] = &[ + (TITLE_PROVIDER, TITLE_IID, &TITLE_OBJECT), + (FEATURES, FEATURES, &FEATURES_OBJECT), + (INVITES, INVITES, &INVITES_OBJECT), + (EVENTS, EVENTS, &EVENTS_OBJECT), +]; + +type This = *const Object; + +extern "system" fn title_id(_: This, out: *mut u32) -> HRESULT { + put(out, runtime::title().id) +} + +/// Runtime areas by number, in the public feature list's order, that we +/// serve: async calls and providers (2, 3), game (5), invites (6), +/// persistent local storage (12), system (15), task queues (16), users +/// (18), error reports (19), game events (20). Not the others: store, game +/// saves, UI, networking, packages, streaming, threads... +const AVAILABLE: [u32; 10] = [2, 3, 5, 6, 12, 15, 16, 18, 19, 20]; + +extern "system" fn is_feature_available(_: This, feature: u32) -> bool { + AVAILABLE.contains(&feature) +} + +/// Nothing raises these events offline, so the callback never runs. +extern "system" fn register( + _: This, + _queue: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + put(out, token()) +} +extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool { + true +} + +/// Accepted and dropped; the name goes to the debug log. +extern "system" fn write_event( + _: This, + _user: *const c_void, + _service_config: *const c_char, + _session: *const c_char, + name: *const c_char, + _dimensions: *const c_char, + _measurements: *const c_char, +) -> HRESULT { + if !name.is_null() { + // SAFETY: a non-null name is a NUL-terminated string. + let name = unsafe { CStr::from_ptr(name) }.to_string_lossy(); + tracing::debug!(%name, "game event dropped"); + } + S_OK +} + +static TITLE_VTABLE: Methods<5> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + title_id as *const (), // 0x18 + missing::<4> as *const (), // 0x20 launch another title (returns nothing) +]); + +static FEATURES_VTABLE: Methods<4> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + is_feature_available as *const (), // 0x18 +]); + +static INVITES_VTABLE: Methods<5> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + register as *const (), // 0x18 + unregister as *const (), // 0x20 +]); + +static EVENTS_VTABLE: Methods<4> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + write_event as *const (), // 0x18 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + #[test] + fn served_areas_are_available_others_not() { + type Check = extern "system" fn(This, u32) -> bool; + let check = method::(&FEATURES_OBJECT, 0x18); + assert!(check(&FEATURES_OBJECT, 18), "users"); + assert!(!check(&FEATURES_OBJECT, 14), "store"); + + type Register = extern "system" fn( + This, + *const c_void, + *mut c_void, + *const c_void, + *mut u64, + ) -> HRESULT; + type Unregister = extern "system" fn(This, u64, bool) -> bool; + let null = std::ptr::null(); + let mut token = 0; + let register = method::(&INVITES_OBJECT, 0x18); + assert_eq!( + register(&INVITES_OBJECT, null, null as _, null, &mut token), + S_OK + ); + assert_ne!(token, 0); + assert!(method::(&INVITES_OBJECT, 0x20)( + &INVITES_OBJECT, + token, + true + )); + } +} diff --git a/crates/victory-hle/src/modules/xgameruntime.rs b/crates/victory-hle/src/modules/xgameruntime.rs index 01ed816..66bbee1 100644 --- a/crates/victory-hle/src/modules/xgameruntime.rs +++ b/crates/victory-hle/src/modules/xgameruntime.rs @@ -1,13 +1,165 @@ //! `xgameruntime.dll`: the console game runtime (XGame*, XUser*, XTaskQueue*...). //! -//! The DLL names titles actually import these from are confirmed by running -//! `victory census` on real titles; extend `dlls` accordingly. +//! Titles rarely import it. A stub linked into the title loads the DLL with +//! `LoadLibraryExA` (answered with a pseudo handle, see `kernel`), looks up +//! the `*ApiImpl` functions and `XErrorReport` with `GetProcAddress`, and +//! initialises. Each runtime API call then asks `QueryApiImpl` for a COM-style +//! object of its area (provider and interface GUIDs), calls one method and +//! releases it. Until an area is implemented its query fails, and the call +//! returns that error without touching the object. An area's interface id +//! changes when its method table does, so each object answers only the ids +//! whose slots we know. Implemented: task queues and async blocks +//! (`xasync`), one offline user (`xuser`), system information (`xsystem`), +//! title id, feature checks, invites and events (`xgame`), persistent local +//! storage (`storage`). #![allow(non_snake_case)] +// Title code calls these through its import table, passing pointers the real +// API would trust. +#![allow(clippy::not_unsafe_ptr_arg_deref)] +use std::ffi::{CStr, c_char, c_void}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::{storage, xasync, xgame, xsystem, xuser}; use crate::{HleModule, hle_export}; pub type HRESULT = i32; pub const S_OK: HRESULT = 0; +/// `HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)`. +pub const NOT_SUPPORTED: HRESULT = 0x8007_0032_u32 as i32; + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Guid { + pub data1: u32, + pub data2: u16, + pub data3: u16, + pub data4: [u8; 8], +} + +impl Guid { + pub const fn new(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> Guid { + Guid { + data1, + data2, + data3, + data4, + } + } +} + +impl std::fmt::Display for Guid { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let d = self.data4; + write!( + f, + "{:08x}-{:04x}-{:04x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", + self.data1, self.data2, self.data3, d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7] + ) + } +} + +/// A runtime object as title code calls it: its first word points at the +/// method table. Ours are static, so reference counting is a no-op. +#[repr(C)] +pub struct Object { + vtable: *const *const (), + /// Named in the log when a title calls a method we lack. + area: &'static str, +} + +// SAFETY: the table is a static array of function addresses. +unsafe impl Sync for Object {} + +impl Object { + pub const fn new(area: &'static str, methods: &'static Methods) -> Object { + Object { + vtable: methods.0.as_ptr(), + area, + } + } +} + +/// An object's method table, by slot (`QueryInterface`, `AddRef`, +/// `Release`, then the area's methods from offset 0x18). +pub struct Methods(pub [*const (); N]); + +// SAFETY: function addresses only. +unsafe impl Sync for Methods {} + +/// A (provider, interface id) pair a title may ask for, and our object. +pub type Interface = (Guid, Guid, &'static Object); + +const AREAS: [&[Interface]; 5] = [ + xasync::INTERFACES, + xuser::INTERFACES, + xsystem::INTERFACES, + xgame::INTERFACES, + storage::INTERFACES, +]; + +/// `AddRef` and `Release`. +pub extern "system" fn add_ref(_: *const Object) -> u32 { + 1 +} + +/// A slot nobody has needed yet; logged with its area. Wrong for a slot +/// that returns `bool` or a value. +pub extern "system" fn missing(this: *const Object) -> HRESULT { + // SAFETY: title code calls methods on objects we handed out. + let area = unsafe { (*this).area }; + tracing::warn!( + area, + slot = format_args!("{:#x}", SLOT * 8), + "runtime method not implemented" + ); + xasync::E_NOTIMPL +} + +/// Writes `value` through `out` if it is non-null. +pub fn put(out: *mut T, value: T) -> HRESULT { + if out.is_null() { + return xasync::E_INVALIDARG; + } + // SAFETY: checked non-null; the title passes room for a `T`. + unsafe { out.write(value) }; + S_OK +} + +/// Copies `text` and a NUL into the title's `size`-byte buffer and reports +/// the bytes used, as the runtime's string getters do. +pub fn put_string(text: &str, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { + let len = text.len() + 1; + if buffer.is_null() || size < len { + return xasync::E_NOT_SUFFICIENT_BUFFER; + } + // SAFETY: the buffer holds `size` bytes, checked above. + unsafe { + buffer.copy_from_nonoverlapping(text.as_ptr(), text.len()); + buffer.add(text.len()).write(0); + } + if !used.is_null() { + // SAFETY: checked non-null. + unsafe { used.write(len) }; + } + S_OK +} + +/// A new registration token for callbacks we never call (events nobody +/// raises offline). +pub fn token() -> u64 { + static NEXT: AtomicU64 = AtomicU64::new(1); + NEXT.fetch_add(1, Ordering::Relaxed) +} + +/// Calls method `slot` (byte offset) of `object` as title code would. +#[cfg(test)] +pub(crate) fn method(object: &Object, slot: usize) -> F { + // SAFETY: the caller names the slot's signature; tables cover the slots + // tests use. + unsafe { std::mem::transmute_copy(&*object.vtable.add(slot / 8)) } +} pub extern "system" fn XGameRuntimeInitialize() -> HRESULT { tracing::info!("XGameRuntimeInitialize"); @@ -18,6 +170,63 @@ pub extern "system" fn XGameRuntimeUninitialize() { tracing::info!("XGameRuntimeUninitialize"); } +/// The arguments identify the title's build of the stub; not checked. +pub extern "system" fn InitializeApiImpl(version: u64, build: u64) -> HRESULT { + tracing::info!(version, build, "InitializeApiImpl"); + S_OK +} + +pub extern "system" fn InitializeApiImplEx(version: u64, build: u64, flags: u64) -> HRESULT { + tracing::info!(version, build, flags, "InitializeApiImplEx"); + S_OK +} + +pub extern "system" fn UninitializeApiImpl() { + tracing::info!("UninitializeApiImpl"); +} + +/// The object for an implemented (provider, interface id); others fail, +/// each pair logged once. +pub extern "system" fn QueryApiImpl( + provider: *const Guid, + iid: *const Guid, + out: *mut *mut c_void, +) -> HRESULT { + static QUERIED: Mutex> = Mutex::new(Vec::new()); + // SAFETY: the title passes pointers to GUIDs (null is tolerated). + let (Some(&provider), Some(&iid)) = (unsafe { provider.as_ref() }, unsafe { iid.as_ref() }) + else { + return NOT_SUPPORTED; + }; + let found = AREAS + .iter() + .flat_map(|area| area.iter()) + .find(|(p, i, _)| (*p, *i) == (provider, iid)); + if let Some(&(_, _, object)) = found + && !out.is_null() + { + // SAFETY: checked non-null; the title passes room for a pointer. + unsafe { out.write((object as *const Object).cast_mut().cast()) }; + return S_OK; + } + let mut queried = QUERIED.lock().unwrap_or_else(|e| e.into_inner()); + if !queried.contains(&(provider, iid)) { + queried.push((provider, iid)); + tracing::warn!(%provider, %iid, "runtime API area not implemented"); + } + NOT_SUPPORTED +} + +pub extern "system" fn XErrorReport(hr: HRESULT, message: *const c_char) { + let message = if message.is_null() { + "".into() + } else { + // SAFETY: a non-null message is a NUL-terminated string. + unsafe { CStr::from_ptr(message) }.to_string_lossy() + }; + tracing::warn!(hr = format_args!("{:#010x}", hr as u32), %message, "XErrorReport"); +} + pub(crate) fn module() -> HleModule { HleModule { name: "xgameruntime", @@ -25,6 +234,66 @@ pub(crate) fn module() -> HleModule { exports: vec![ hle_export!(XGameRuntimeInitialize), hle_export!(XGameRuntimeUninitialize), + hle_export!(InitializeApiImpl), + hle_export!(InitializeApiImplEx), + hle_export!(UninitializeApiImpl), + hle_export!(QueryApiImpl), + hle_export!(XErrorReport), ], } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::kernel::{FreeLibrary, GetProcAddress, LoadLibraryExA}; + + #[test] + fn title_stub_loads_the_runtime_dynamically() { + let load = |name: &CStr| LoadLibraryExA(name.as_ptr().cast(), std::ptr::null_mut(), 0x800); + let runtime = load(c"xgameruntime.dll"); + assert!(!runtime.is_null()); + let proc = |name: &CStr| GetProcAddress(runtime, name.as_ptr().cast()); + for name in [ + c"InitializeApiImpl", + c"InitializeApiImplEx", + c"QueryApiImpl", + c"UninitializeApiImpl", + c"XErrorReport", + ] { + assert!(!proc(name).is_null(), "{name:?}"); + } + assert!(proc(c"NotAnExport").is_null()); + let ordinal = std::ptr::without_provenance::(1); + assert!(GetProcAddress(runtime, ordinal).is_null()); + + type Init = extern "system" fn(u64, u64, u64) -> HRESULT; + type Query = extern "system" fn(*const Guid, *const Guid, *mut *mut c_void) -> HRESULT; + // SAFETY: the addresses are our functions with these signatures. + let (init, query) = unsafe { + ( + std::mem::transmute::<*mut c_void, Init>(proc(c"InitializeApiImplEx")), + std::mem::transmute::<*mut c_void, Query>(proc(c"QueryApiImpl")), + ) + }; + assert_eq!(init(1, 2, 2), S_OK); + let guid = Guid { + data1: 1, + data2: 2, + data3: 3, + data4: [4; 8], + }; + let untouched = 0x1234 as *mut c_void; + let mut out = untouched; + assert!(query(&guid, &guid, &mut out) < 0); + assert_eq!(out, untouched); + assert_eq!(FreeLibrary(runtime), 1); + + #[cfg(windows)] + { + let kernel32 = load(c"kernel32.dll"); + assert!(!kernel32.is_null(), "host DLLs still load from the host"); + assert!(!GetProcAddress(kernel32, c"GetTickCount".as_ptr().cast()).is_null()); + } + } +} diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs new file mode 100644 index 0000000..55ef50c --- /dev/null +++ b/crates/victory-hle/src/modules/xmem.rs @@ -0,0 +1,357 @@ +//! `xmem.dll`: console memory, served from host memory. The GPU side works +//! from CPU addresses (unified memory), so memory types and bandwidth +//! classes change nothing here; what constrains addresses (alignment, +//! 2 MiB pages, address-bit limits) is honoured. +#![allow(non_snake_case)] +// Title code calls these through its import table, passing pointers the real +// API would trust. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::alloc::{Layout, alloc, dealloc}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use windows_sys::Win32::Foundation::HANDLE; +use windows_sys::Win32::System::Memory::{ + MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, MEM_RELEASE, MEM_RESERVE, + MEMORY_BASIC_INFORMATION, MemExtendedParameterAddressRequirements, PAGE_NOACCESS, + PAGE_READWRITE, VirtualAlloc2, VirtualFree, VirtualQueryEx, +}; +use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; +use windows_sys::core::BOOL; + +use crate::{HleModule, hle_export}; + +const MIB: usize = 1 << 20; +const GIB: usize = 1 << 30; +/// Title memory of an Xbox Series X in the advanced mode: 10 GiB of +/// GPU-optimal and 3.5 GiB of standard memory. +const GPU_OPTIMAL_LIMIT: usize = 10 * GIB; +const STANDARD_LIMIT: usize = 7 * GIB / 2; + +/// Standard memory the title has handed to the system. +static TRANSFERRED: AtomicUsize = AtomicUsize::new(0); + +// Console additions to the host's flags. +/// 2 MiB pages; the host reads this bit as large pages, which need a +/// privilege. +const PAGES_2M: u32 = 0x2000_0000; +/// With `PAGES_2M`: 64 KiB pages; the host reads it as AWE memory. +const PAGES_64K_BIT: u32 = 0x40_0000; +/// The host's protection constants and `PAGE_GUARD`. Above them the console +/// adds GPU access bits (0x800-0x40000). Write-combining and uncached are +/// dropped too: our GPU side reads this memory through the CPU. +const HOST_PROTECTION: u32 = 0x1ff; +/// XMem flags of memory both processors reach: all of ours. +const GRAPHICS: u64 = 3; +/// XMem flag bit of 32-bit graphics memory. +const ADDRESS_32BIT: u64 = 4; + +/// The highest address XMem `flags` allow, 0 for no limit: 32 bits, or +/// 46 down to 40 bits from the field at bit 12. +fn highest_address(flags: u64) -> usize { + let bits = match (flags & ADDRESS_32BIT, flags >> 12 & 7) { + (0, 0) => return 0, + (0, field) => 47 - field, + _ => 32, + }; + (1 << bits) - 1 +} + +pub extern "system" fn XMemVirtualAlloc( + base: *mut c_void, + size: usize, + kind: u32, + flags: u64, + protect: u32, +) -> *mut c_void { + let mut requirements = MEM_ADDRESS_REQUIREMENTS { + HighestEndingAddress: highest_address(flags) as *mut c_void, + Alignment: if kind & (PAGES_2M | PAGES_64K_BIT) == PAGES_2M { + 2 * MIB + } else { + 0 + }, + ..Default::default() + }; + let mut kind = kind & !(PAGES_2M | PAGES_64K_BIT); + let protect = match protect & HOST_PROTECTION { + 0 => PAGE_NOACCESS, + p => p, + }; + let mut parameter = MEM_EXTENDED_PARAMETER::default(); + parameter.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as u64; + parameter.Anonymous2.Pointer = (&raw mut requirements).cast(); + // Address requirements apply to reservations at an address of our choice. + let constrained = base.is_null() + && (!requirements.HighestEndingAddress.is_null() || requirements.Alignment != 0); + if constrained { + kind |= MEM_RESERVE; + } + // SAFETY: the title's own arguments, cleaned of console bits; the + // parameter points at `requirements`, which outlives the call. + unsafe { + VirtualAlloc2( + GetCurrentProcess(), + base, + size, + kind, + protect, + if constrained { &mut parameter } else { std::ptr::null_mut() }, + constrained.into(), + ) + } +} + +/// `MEMORY_BASIC_INFORMATION` (the console's first 0x30 bytes are the +/// same), then the XMem flags and tag. +#[repr(C)] +pub struct BasicInformation { + host: MEMORY_BASIC_INFORMATION, + flags: u64, + tag_code: u32, + tag: [u8; 4], +} + +// shortcut: every committed page reports graphics memory and no tag, since +// all of it is GPU-reachable here; remember the flags of `XMemVirtualAlloc` +// regions if a title tells CPU-only memory apart. +pub extern "system" fn XMemVirtualQuery( + process: HANDLE, + address: *const c_void, + out: *mut BasicInformation, +) -> BOOL { + let size = size_of::(); + // SAFETY: the title passes room for the whole structure; the host + // fails on a null one. + unsafe { + if VirtualQueryEx(process, address, out.cast(), size) == 0 { + return 0; + } + let info = &mut *out; + info.flags = if info.host.State == MEM_COMMIT { GRAPHICS } else { 0 }; + info.tag_code = 0; + info.tag = [0; 4]; + } + 1 +} + +// `XMemAlloc` attributes: alignment as log2 (5 bits at 24, 4 bytes and up +// from 2), then the memory type, then bit 33: a 32-bit address. +const ALIGNMENT_SHIFT: u64 = 24; +const ALLOC_32BIT: u64 = 1 << 33; +/// Our block header: the block's size and alignment, just below the +/// pointer handed out. +const HEADER: usize = 2 * size_of::(); + +fn layout(size: usize, attributes: u64) -> Option { + // An alignment of at least 16 leaves room for the header. + let align = 1usize << (attributes >> ALIGNMENT_SHIFT & 0x1f).max(4); + Layout::from_size_align(size.checked_add(align)?, align).ok() +} + +/// The title's general allocator, for middleware too. +// shortcut: allocation hooks (`XMemSetAllocationHooks`, or hooks the title +// exports) are not called; no title we have sets them. +pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void { + if attributes & ALLOC_32BIT != 0 { + return XMemVirtualAlloc( + std::ptr::null_mut(), + size, + MEM_RESERVE | MEM_COMMIT, + GRAPHICS | ADDRESS_32BIT, + PAGE_READWRITE, + ); + } + let Some(layout) = layout(size, attributes) else { + return std::ptr::null_mut(); + }; + // SAFETY: the layout has a non-zero size. + let block = unsafe { alloc(layout) }; + if block.is_null() { + return block.cast(); + } + // SAFETY: the block holds the alignment (at least the header) and then + // `size` bytes. + unsafe { + let user = block.add(layout.align()); + user.sub(HEADER) + .cast::<[usize; 2]>() + .write([layout.size(), layout.align()]); + user.cast() + } +} + +/// Frees what [`XMemAlloc`] returned, given the same attributes. +pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) { + if address.is_null() { + return; + } + // SAFETY: the address came from `XMemAlloc` with these attributes: a + // whole reservation, or a header-prefixed block. + unsafe { + if attributes & ALLOC_32BIT != 0 { + VirtualFree(address, 0, MEM_RELEASE); + return; + } + let user = address.cast::(); + let [size, align] = user.sub(HEADER).cast::<[usize; 2]>().read(); + dealloc( + user.sub(align), + Layout::from_size_align_unchecked(size, align), + ); + } +} + +/// The oldest layout we know; newer titles pass other flag values (Minecraft +/// 0x20000001) and read the same leading fields. +#[repr(C)] +#[derive(Debug, Default)] +pub struct WorkingSet { + pub title_limit: usize, + pub title_used: usize, + pub tools_limit: usize, + pub tools_used: usize, + pub stack_used: u32, + pub physical_pages: u32, + pub gpu_optimal_limit: usize, + pub gpu_optimal_used: usize, + pub tools_gpu_optimal_limit: usize, + pub tools_gpu_optimal_used: usize, + pub kernel_pool_used: u32, + pub kernel_pool_limit: u32, +} + +/// The title's budget and our process's commit as what it uses. No tools +/// memory: a retail console. +// shortcut: all fields are filled whatever the flags ask for, and use is +// not split by bandwidth class (GPU-optimal use reads 0); track +// allocations per class if a title budgets from that field. +pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut WorkingSet) -> BOOL { + if out.is_null() { + return 0; + } + let mut counters = PROCESS_MEMORY_COUNTERS { + cb: size_of::() as u32, + ..Default::default() + }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) }; + let stats = WorkingSet { + title_limit: GPU_OPTIMAL_LIMIT + STANDARD_LIMIT - TRANSFERRED.load(Ordering::Relaxed), + title_used: counters.PagefileUsage, + gpu_optimal_limit: GPU_OPTIMAL_LIMIT, + ..Default::default() + }; + // SAFETY: checked non-null; the title passes room for the structure. + unsafe { out.write(stats) }; + 1 +} + +/// Hands title memory (standard, in 2 MiB pages) to the system. The other +/// transfers involve tools memory, which a retail console has none of. +pub extern "system" fn XMemTransferMemory(kind: u32, size: usize) -> BOOL { + const TITLE_TO_SYSTEM: u32 = 0; + tracing::info!(kind, size, "XMemTransferMemory"); + if size == 0 { + return 1; + } + let Some(size) = size.checked_next_multiple_of(2 * MIB) else { + return 0; + }; + let moved = kind == TITLE_TO_SYSTEM + && TRANSFERRED + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |t| { + t.checked_add(size).filter(|&t| t <= STANDARD_LIMIT) + }) + .is_ok(); + moved.into() +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "xmem", + dlls: &["xmem.dll"], + exports: vec![ + hle_export!(XMemAlloc), + hle_export!(XMemFree), + hle_export!(XMemVirtualAlloc), + hle_export!(XMemVirtualQuery), + hle_export!(XMemGetWorkingSetStatistics), + hle_export!(XMemTransferMemory), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn query(address: *const c_void) -> BasicInformation { + // SAFETY: plain data; zero is a valid value. + let mut info: BasicInformation = unsafe { std::mem::zeroed() }; + // SAFETY: a pseudo handle needs no closing. + let process = unsafe { GetCurrentProcess() }; + assert_eq!(XMemVirtualQuery(process, address, &mut info), 1); + info + } + + #[test] + fn alloc_honours_alignment_and_frees() { + for (field, align) in [(0, 16), (4, 16), (0xc, 4096), (0x10, 64 * 1024)] { + let attributes = field << ALIGNMENT_SHIFT | 1 << 29; // a graphics type + let p = XMemAlloc(100, attributes); + assert!(!p.is_null()); + assert_eq!(p as usize % align, 0, "field {field:#x}"); + // SAFETY: 100 bytes were allocated. + unsafe { p.cast::().write_bytes(0xab, 100) }; + XMemFree(p, attributes); + } + let p = XMemAlloc(4096, ALLOC_32BIT); + assert!(!p.is_null() && (p as usize) < 1 << 32); + XMemFree(p, ALLOC_32BIT); + } + + #[test] + fn virtual_alloc_meets_console_constraints() { + const GPU_READ_WRITE: u32 = 0x2000; + let p = XMemVirtualAlloc( + std::ptr::null_mut(), + 4 * MIB, + PAGES_2M | MEM_RESERVE | MEM_COMMIT, + GRAPHICS | 7 << 12, // 40-bit addresses + PAGE_READWRITE | GPU_READ_WRITE, + ); + assert!(!p.is_null()); + assert_eq!(p as usize % (2 * MIB), 0); + assert!((p as usize) < 1 << 40); + let info = query(p); + assert_eq!(info.host.State, MEM_COMMIT); + assert_eq!(info.host.Protect, PAGE_READWRITE); + assert_eq!(info.flags & GRAPHICS, GRAPHICS); + // SAFETY: our own reservation. + assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0); + assert_eq!(query(p).flags, 0); + } + + #[test] + fn transfers_shrink_the_title_budget() { + let mut before = WorkingSet::default(); + assert_eq!(XMemGetWorkingSetStatistics(0x2000_0001, &mut before), 1); + assert!(before.title_used > 0); + assert_eq!(XMemTransferMemory(0, 128 * MIB - 1), 1); + assert_eq!(XMemTransferMemory(2, MIB), 0, "no tools memory"); + assert_eq!(XMemTransferMemory(0, STANDARD_LIMIT), 0, "over budget"); + let mut after = WorkingSet::default(); + XMemGetWorkingSetStatistics(0x2000_0001, &mut after); + assert_eq!(before.title_limit - after.title_limit, 128 * MIB); + } + + #[test] + fn statistics_have_the_console_layout() { + assert_eq!(size_of::(), 0x50); + assert_eq!(size_of::(), 0x40); + assert_eq!(std::mem::offset_of!(WorkingSet, gpu_optimal_limit), 0x28); + } +} diff --git a/crates/victory-hle/src/modules/xsystem.rs b/crates/victory-hle/src/modules/xsystem.rs new file mode 100644 index 0000000..e6bc740 --- /dev/null +++ b/crates/victory-hle/src/modules/xsystem.rs @@ -0,0 +1,154 @@ +//! XSystem: the console's identity and sandbox, and how analytics describe +//! the device. Fixed values: one offline retail Xbox Series X. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, add_ref, missing, put_string, +}; + +pub const PROVIDER: Guid = Guid::new( + 0xe349_bd1a, + 0xfc20, + 0x4e40, + [0xb9, 0x9c, 0x41, 0x78, 0xcc, 0x6b, 0x40, 0x9f], +); + +/// The interface as Minecraft (2022) asks for it; an older table +/// ended before the device id. +pub const IID: Guid = Guid::new( + 0x6fd7_1f09, + 0x7513, + 0x49f0, + [0x89, 0xbc, 0xbf, 0xaf, 0x5d, 0xf6, 0xf8, 0x52], +); + +/// Analytics information; its interface id is the provider's. +pub const ANALYTICS: Guid = Guid::new( + 0xb884_675d, + 0xb738, + 0x4a9c, + [0x81, 0x5d, 0x9a, 0x9a, 0x1e, 0x0c, 0x6c, 0x9b], +); + +/// 38 characters (39 bytes with the NUL). +const CONSOLE_ID: &str = "00000000000000000000000000000000000001"; +/// The retail sandbox. +const SANDBOX: &str = "RETAIL"; +/// Base64 of 32 bytes: 44 characters (45 bytes with the NUL). +const DEVICE_ID: &str = "VkljdG9yeSBvZmZsaW5lIGRldmljZSBpZGVudGl0eSE="; + +pub static OBJECT: Object = Object::new("system", &VTABLE); +pub static ANALYTICS_OBJECT: Object = Object::new("analytics", &ANALYTICS_VTABLE); + +pub const INTERFACES: &[Interface] = &[ + (PROVIDER, IID, &OBJECT), + (ANALYTICS, ANALYTICS, &ANALYTICS_OBJECT), +]; + +type This = *const Object; + +extern "system" fn console_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { + put_string(CONSOLE_ID, size, buffer, used) +} +extern "system" fn sandbox_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { + put_string(SANDBOX, size, buffer, used) +} +/// The device id this title sees (titles see different ones). +extern "system" fn device_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { + put_string(DEVICE_ID, size, buffer, used) +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Version { + pub major: u16, + pub minor: u16, + pub build: u16, + pub revision: u16, +} + +#[repr(C)] +pub struct AnalyticsInfo { + pub os: Version, + pub hosting_os: Version, + /// NUL-terminated. + pub family: [u8; 64], + pub form: [u8; 64], +} + +const OS: Version = Version { + major: 10, + minor: 0, + build: 22000, + revision: 0, +}; + +fn text(s: &str) -> [u8; 64] { + let mut out = [0; 64]; + out[..s.len()].copy_from_slice(s.as_bytes()); + out +} + +/// A struct this large comes back through the caller's buffer, whose +/// address is also the return value. +extern "system" fn analytics_info(_: This, out: *mut AnalyticsInfo) -> *mut AnalyticsInfo { + let info = AnalyticsInfo { + os: OS, + hosting_os: OS, + family: text("Xbox"), + form: text("Xbox Series X"), + }; + // SAFETY: the caller passes room for the struct. + unsafe { out.write(info) }; + out +} + +static VTABLE: Methods<6> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + console_id as *const (), // 0x18, by the older table; titles seen do not call it + sandbox_id as *const (), // 0x20 + device_id as *const (), // 0x28 +]); + +static ANALYTICS_VTABLE: Methods<4> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + analytics_info as *const (), // 0x18 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::{S_OK, method}; + + #[test] + fn identity_strings_fit_the_documented_sizes() { + type Get = extern "system" fn(This, usize, *mut u8, *mut usize) -> HRESULT; + let this: This = &OBJECT; + let mut buffer = [0u8; 64]; + let mut used = 0; + for (slot, size) in [(0x18, 39), (0x20, 16), (0x28, 45)] { + let get = method::(&OBJECT, slot); + assert_eq!(get(this, size, buffer.as_mut_ptr(), &mut used), S_OK); + assert!(used <= size && buffer[used - 1] == 0, "slot {slot:#x}"); + } + assert_eq!(&buffer[..7], b"VkljdG9"); + } + + #[test] + fn analytics_info_comes_back_through_the_buffer() { + type Get = extern "system" fn(This, *mut AnalyticsInfo) -> *mut AnalyticsInfo; + let mut info = std::mem::MaybeUninit::::uninit(); + let get = method::(&ANALYTICS_OBJECT, 0x18); + let back = get(&ANALYTICS_OBJECT, info.as_mut_ptr()); + assert_eq!(back, info.as_mut_ptr()); + // SAFETY: written by the call. + let info = unsafe { info.assume_init() }; + assert_eq!(size_of::(), 0x90); + assert_eq!(info.os.build, 22000); + assert_eq!(&info.form[..14], b"Xbox Series X\0"); + } +} diff --git a/crates/victory-hle/src/modules/xuser.rs b/crates/victory-hle/src/modules/xuser.rs new file mode 100644 index 0000000..18bfc35 --- /dev/null +++ b/crates/victory-hle/src/modules/xuser.rs @@ -0,0 +1,298 @@ +//! XUser: one offline local user, signed in, never a guest, with every +//! privilege. Served as the user provider's objects from `QueryApiImpl`; +//! adding a user completes through `xasync` like any other async call. No +//! input device is associated with the user (there are none, `gameinput`). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::c_void; + +use super::xasync::{self, AsyncBlock, ProviderData}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, token, +}; + +/// The user provider. +pub const PROVIDER: Guid = Guid { + data1: 0x01ac_d177, + data2: 0x91f9, + data3: 0x4763, + data4: [0xa3, 0x8e, 0xcc, 0xbb, 0x55, 0xce, 0x32, 0xe0], +}; + +/// Its main interface. +pub const IID: Guid = Guid { + data1: 0xeb9b_f948, + data2: 0x18dc, + data3: 0x4d82, + data4: [0xbb, 0xcc, 0x40, 0xe0, 0xa8, 0x09, 0xc4, 0xc0], +}; + +/// The interface titles ask for to read a gamertag. +pub const GAMERTAG_IID: Guid = Guid { + data1: 0xcef4_fac0, + data2: 0x7676, + data3: 0x4a94, + data4: [0xa1, 0x19, 0x4c, 0x43, 0xf9, 0xeb, 0x5b, 0x74], +}; + +/// The user's devices and audio endpoints. +pub const DEVICE_PROVIDER: Guid = Guid::new( + 0x7d82_4997, + 0x10dc, + 0x45ab, + [0x86, 0xb7, 0x27, 0x37, 0x76, 0x7c, 0x0b, 0xf1], +); + +/// The device interface as Minecraft (2022) asks for it. +pub const DEVICE_IID: Guid = Guid::new( + 0x0cc6_a956, + 0xe7e1, + 0x4fdf, + [0x93, 0x41, 0x9d, 0x5d, 0xa6, 0x49, 0xeb, 0xc8], +); + +/// The documented "no such user" error. +pub const USER_NOT_FOUND: HRESULT = 0x8924_5104_u32 as i32; + +pub const XUID: u64 = 0x0009_0000_0000_0001; +pub const LOCAL_ID: u64 = 1; +const GAMERTAG: &str = "Player"; + +/// The only user; a handle is its address, duplicating and closing are free. +pub struct User; +static USER: User = User; +type Handle = *const User; + +fn user() -> Handle { + &USER +} + +fn found(found: bool, out: *mut Handle) -> HRESULT { + if found { + put(out, user()) + } else { + USER_NOT_FOUND + } +} + +pub static OBJECT: Object = Object::new("user", &VTABLE); +pub static GAMERTAG_OBJECT: Object = Object::new("user gamertag", &GAMERTAG_VTABLE); +pub static DEVICE_OBJECT: Object = Object::new("user devices", &DEVICE_VTABLE); + +pub const INTERFACES: &[Interface] = &[ + (PROVIDER, IID, &OBJECT), + (PROVIDER, GAMERTAG_IID, &GAMERTAG_OBJECT), + (DEVICE_PROVIDER, DEVICE_IID, &DEVICE_OBJECT), +]; + +type This = *const Object; +extern "system" fn duplicate(_: This, _: Handle, out: *mut Handle) -> HRESULT { + put(out, user()) +} +extern "system" fn close(_: This, _: Handle) {} +extern "system" fn compare(_: This, a: Handle, b: Handle) -> i32 { + i32::from(a != b) +} + +/// The async provider for adding a user: done at once, the result is a +/// handle. +extern "system" fn add_provider(op: u32, data: *const ProviderData) -> HRESULT { + const BEGIN: u32 = 0; + const GET_RESULT: u32 = 2; + // SAFETY: the async runtime passes valid provider data. + let data = unsafe { &*data }; + match op { + BEGIN => xasync::XAsyncComplete(data.block, S_OK, size_of::()), + GET_RESULT => return put(data.buffer.cast::(), user()), + _ => {} + } + S_OK +} + +/// Tells our add calls apart from other async calls on the same block. +static ADD: u8 = 0; + +/// Any options add the one user, silently. +extern "system" fn add_async(_: This, options: u32, block: *mut AsyncBlock) -> HRESULT { + tracing::info!(options, "XUserAddAsync: the offline local user"); + xasync::XAsyncBegin( + block, + std::ptr::null_mut(), + (&raw const ADD).cast(), + std::ptr::null(), + Some(add_provider), + ) +} +extern "system" fn add_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT { + xasync::XAsyncGetResult( + block, + (&raw const ADD).cast(), + size_of::(), + out.cast(), + std::ptr::null_mut(), + ) +} +extern "system" fn get_local_id(_: This, _: Handle, out: *mut u64) -> HRESULT { + put(out, LOCAL_ID) +} +extern "system" fn find_by_local_id(_: This, id: u64, out: *mut Handle) -> HRESULT { + found(id == LOCAL_ID, out) +} +extern "system" fn get_id(_: This, _: Handle, out: *mut u64) -> HRESULT { + put(out, XUID) +} +extern "system" fn find_by_id(_: This, id: u64, out: *mut Handle) -> HRESULT { + found(id == XUID, out) +} +extern "system" fn get_is_guest(_: This, _: Handle, out: *mut bool) -> HRESULT { + put(out, false) +} +/// 0: signed in. +extern "system" fn get_state(_: This, _: Handle, out: *mut u32) -> HRESULT { + put(out, 0) +} +/// The same name for every component (classic, modern, suffix, unique). +extern "system" fn get_gamertag( + _: This, + _: Handle, + _component: u32, + size: usize, + buffer: *mut u8, + used: *mut usize, +) -> HRESULT { + put_string(GAMERTAG, size, buffer, used) +} +/// Granted; deny reason 0 (none). +extern "system" fn check_privilege( + _: This, + _: Handle, + _options: u32, + _privilege: u32, + has: *mut bool, + reason: *mut u32, +) -> HRESULT { + if !reason.is_null() { + // SAFETY: checked non-null. + unsafe { reason.write(0) }; + } + put(has, true) +} + +/// The user never changes and no device is ever associated, so these +/// callbacks are never called. +extern "system" fn register( + _: This, + _queue: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + put(out, token()) +} +extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool { + true +} + +/// No input device belongs to a user. +extern "system" fn find_for_device(_: This, _device: *const c_void, _: *mut Handle) -> HRESULT { + USER_NOT_FOUND +} + +// Unset slots: gamer pictures, token and signature, issue resolution. +static VTABLE: Methods<35> = Methods([ + missing::<0> as *const (), // 0x00 QueryInterface + add_ref as *const (), // 0x08 AddRef + add_ref as *const (), // 0x10 Release: the object is static + duplicate as *const (), // 0x18 + close as *const (), // 0x20 + compare as *const (), // 0x28 + missing::<6> as *const (), // 0x30 maximum users + add_async as *const (), // 0x38 + add_result as *const (), // 0x40 + get_local_id as *const (), // 0x48 + find_by_local_id as *const (), // 0x50 + get_id as *const (), // 0x58 + find_by_id as *const (), // 0x60 + get_is_guest as *const (), // 0x68 + get_state as *const (), // 0x70 + get_gamertag as *const (), // 0x78 older gamertag slot + missing::<16> as *const (), // 0x80 gamer picture: begin + missing::<17> as *const (), // 0x88 result size + missing::<18> as *const (), // 0x90 result + missing::<19> as *const (), // 0x98 age group + check_privilege as *const (), // 0xa0 + missing::<21> as *const (), // 0xa8 resolve privilege with UI: begin + missing::<22> as *const (), // 0xb0 result + missing::<23> as *const (), // 0xb8 token and signature: begin + missing::<24> as *const (), // 0xc0 result size + missing::<25> as *const (), // 0xc8 result + missing::<26> as *const (), // 0xd0 the same, UTF-16: begin + missing::<27> as *const (), // 0xd8 result size + missing::<28> as *const (), // 0xe0 result + missing::<29> as *const (), // 0xe8 resolve issue with UI: begin + missing::<30> as *const (), // 0xf0 result + missing::<31> as *const (), // 0xf8 the same, UTF-16: begin + missing::<32> as *const (), // 0x100 result + register as *const (), // 0x108 change event + unregister as *const (), // 0x110 +]); + +static GAMERTAG_VTABLE: Methods<4> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + get_gamertag as *const (), // 0x18 +]); + +static DEVICE_VTABLE: Methods<6> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + find_for_device as *const (), // 0x18 + register as *const (), // 0x20 device association changed + unregister as *const (), // 0x28 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xasync::E_NOT_SUFFICIENT_BUFFER; + use crate::modules::xgameruntime::method as slot; + + #[test] + fn startup_adds_the_user_and_reads_its_id() { + type Add = extern "system" fn(This, u32, *mut AsyncBlock) -> HRESULT; + type AddResult = extern "system" fn(This, *mut AsyncBlock, *mut Handle) -> HRESULT; + type GetId = extern "system" fn(This, Handle, *mut u64) -> HRESULT; + type Gamertag = + extern "system" fn(This, Handle, u32, usize, *mut u8, *mut usize) -> HRESULT; + let this: This = &OBJECT; + let mut block = AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + assert_eq!(slot::(&OBJECT, 0x38)(this, 1, &mut block), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut block, true), S_OK); + let mut handle = std::ptr::null(); + assert_eq!( + slot::(&OBJECT, 0x40)(this, &mut block, &mut handle), + S_OK + ); + assert!(!handle.is_null()); + let mut xuid = 0; + assert_eq!(slot::(&OBJECT, 0x58)(this, handle, &mut xuid), S_OK); + assert_eq!(xuid, XUID); + + let mut name = [0u8; 16]; + let mut used = 0; + let get = slot::(&GAMERTAG_OBJECT, 0x18); + assert_eq!(get(this, handle, 0, 16, name.as_mut_ptr(), &mut used), S_OK); + assert_eq!(&name[..used], b"Player\0"); + assert_eq!( + get(this, handle, 0, 2, name.as_mut_ptr(), &mut used), + E_NOT_SUFFICIENT_BUFFER + ); + } +} diff --git a/crates/victory-hle/src/registry.rs b/crates/victory-hle/src/registry.rs index 563e7b0..e8744b4 100644 --- a/crates/victory-hle/src/registry.rs +++ b/crates/victory-hle/src/registry.rs @@ -4,7 +4,8 @@ use std::sync::LazyLock; use crate::modules; -/// One function we implement, under the name the title imports. +/// One function we implement, under the name the title imports (`#n` for an +/// ordinal). #[derive(Debug, Clone, Copy)] pub struct HleExport { pub name: &'static str, diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index 2c5ef87..3bb5ad7 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -1,5 +1,7 @@ //! Process-wide state the implementations need. +use std::path::{Path, PathBuf}; +use std::sync::Mutex; use std::sync::atomic::{AtomicUsize, Ordering}; static MAIN_IMAGE_BASE: AtomicUsize = AtomicUsize::new(0); @@ -16,3 +18,88 @@ pub fn main_image() -> Option { base => Some(base), } } + +/// Original file of each title image we mapped, by base address. +static IMAGE_PATHS: Mutex> = Mutex::new(Vec::new()); + +/// Records the file a title image was mapped from: the title asks for its +/// own path (`GetModuleFileName`) to find its data, and must not get our +/// cache copy. +pub fn set_image_path(base: usize, path: &Path) { + let path = std::path::absolute(path).unwrap_or_else(|_| path.to_owned()); + let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); + paths.retain(|(b, _)| *b != base); + paths.push((base, path)); +} + +pub fn image_path(base: usize) -> Option { + let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); + paths + .iter() + .find(|(b, _)| *b == base) + .map(|(_, p)| p.clone()) +} + +/// What the title's manifest (`MicrosoftGame.config` beside its executable) +/// says about it, and where its persistent local storage lives. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Title { + pub id: u32, + /// Persistent local storage: our folder for it and the title's quota. + pub storage: PathBuf, + pub storage_bytes: u64, +} + +impl Title { + /// Title id and storage quota from the manifest's text (zero where it + /// has none); the storage folder is left for the caller to choose. + // shortcut: finds the two elements by text, not as XML; parse properly + // once more of the manifest is needed. + pub fn from_manifest(text: &str) -> Title { + fn element<'a>(text: &'a str, tag: &str) -> Option<&'a str> { + let start = text.find(&format!("<{tag}>"))? + tag.len() + 2; + let len = text[start..].find('<')?; + Some(text[start..start + len].trim()) + } + let id = element(text, "TitleId").and_then(|v| u32::from_str_radix(v, 16).ok()); + let storage_mb = text + .find("") + .and_then(|at| element(&text[at..], "SizeMB")) + .and_then(|v| v.parse::().ok()); + Title { + id: id.unwrap_or(0), + storage: PathBuf::new(), + storage_bytes: storage_mb.unwrap_or(0) << 20, + } + } +} + +static TITLE: Mutex> = Mutex::new(None); + +pub fn set_title(title: Title) { + *TITLE.lock().unwrap_or_else(|e| e.into_inner()) = Some(title); +} + +/// The running title; the default (id 0, no storage) until set. +pub fn title() -> Title { + TITLE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_title_id_and_storage_quota() { + let text = "\n 639AA8DD\n\ + \n 1024 \n\ + "; + let t = Title::from_manifest(text); + assert_eq!((t.id, t.storage_bytes), (0x639A_A8DD, 1024 << 20)); + assert_eq!(Title::from_manifest("").storage_bytes, 0); + } +} diff --git a/crates/victory-loader/Cargo.toml b/crates/victory-loader/Cargo.toml index e5d0a11..cb40a16 100644 --- a/crates/victory-loader/Cargo.toml +++ b/crates/victory-loader/Cargo.toml @@ -19,6 +19,7 @@ blake3.workspace = true windows-sys = { workspace = true, features = [ "Win32_Foundation", "Win32_System_Diagnostics_Debug", + "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Threading", diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs new file mode 100644 index 0000000..03755b2 --- /dev/null +++ b/crates/victory-loader/src/crash.rs @@ -0,0 +1,101 @@ +//! 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. + +use windows_sys::Win32::Foundation::{ + EXCEPTION_ACCESS_VIOLATION, 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, +}; +use windows_sys::Win32::System::LibraryLoader::{ + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + GetModuleFileNameW, GetModuleHandleExW, +}; + +const EXCEPTION_CONTINUE_SEARCH: i32 = 0; +/// Stack slots scanned for return addresses into a module. +const STACK_SCAN: usize = 64; + +/// 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)) }; +} + +unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + // 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] { + 0 => "read", + 1 => "write", + _ => "execute", + }; + format!(" ({kind} {:#x})", record.ExceptionInformation[1]) + } else { + String::new() + }; + eprintln!( + "VIctory: exception {:#010x} at {}{access}", + 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); + } + } + EXCEPTION_CONTINUE_SEARCH +} + +/// `module+rva`, or the bare address. +pub fn locate(address: usize) -> String { + module_of(address).unwrap_or_else(|| format!("{address:#x}")) +} + +fn module_of(address: usize) -> Option { + let mut module: HMODULE = std::ptr::null_mut(); + // SAFETY: looks up the module containing `address`; no reference taken. + let found = unsafe { + GetModuleHandleExW( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + address as *const u16, + &mut module, + ) + }; + if found == 0 { + return None; + } + let mut path = [0u16; 260]; + // SAFETY: `module` is a loaded module; the buffer length is passed. + let len = unsafe { GetModuleFileNameW(module, path.as_mut_ptr(), path.len() as u32) }; + let path = String::from_utf16_lossy(&path[..len as usize]); + let name = path.rsplit('\\').next().unwrap_or(&path); + Some(format!("{name}+{:#x}", address - module as usize)) +} diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index d32a4ab..8124319 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -11,25 +11,34 @@ //! none of its code and resolves none of its imports; //! 2. load that copy as a real module (debuggers, profilers, crash dumps //! and stack walks all see it); this step is Windows-only; -//! 3. bind every import ourselves through an [`ImportResolver`], our -//! runtime (`victory-hle`) or the host, and route anything unresolved -//! to a generated stub that reports exactly what was called; -//! 4. run TLS callbacks and the entry point on a thread with the stack size -//! the image asks for. +//! 3. map the DLLs the title ships beside it the same way +//! (`load_title_dlls`); +//! 4. bind every import ourselves through an [`ImportResolver`], our +//! runtime (`victory-hle`), the host or the title's DLLs, and route +//! anything unresolved to a generated stub that reports exactly what +//! was called; +//! 5. initialise the title's DLLs, then run TLS callbacks and the entry +//! point on a thread with the stack size the image asks for. +#[cfg(windows)] +mod crash; pub mod prepare; pub mod resolve; #[cfg(windows)] mod thunks; #[cfg(windows)] +mod tls; +#[cfg(windows)] mod windows; +#[cfg(windows)] +pub use crash::{locate, report_crashes}; pub use prepare::{PrepareError, PreparedImage, prepare}; pub use resolve::{ImportResolver, Provenance, Resolution}; #[cfg(windows)] pub use thunks::{UnimplementedPolicy, unimplemented_call_count}; #[cfg(windows)] -pub use windows::{BindReport, LoadedImage, MissingImport, load}; +pub use windows::{BindReport, LoadedImage, MissingImport, WithTitleDlls, load, load_title_dlls}; /// `DLL_PROCESS_ATTACH`, for TLS callbacks. pub const DLL_PROCESS_ATTACH: u32 = 1; diff --git a/crates/victory-loader/src/resolve.rs b/crates/victory-loader/src/resolve.rs index c6399d8..2da1291 100644 --- a/crates/victory-loader/src/resolve.rs +++ b/crates/victory-loader/src/resolve.rs @@ -10,6 +10,8 @@ pub enum Provenance { /// The host's own implementation (e.g. Windows API sets that behave the /// same on console and PC). Host, + /// A DLL the title ships, mapped like the executable. + Title, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/victory-loader/src/tls.rs b/crates/victory-loader/src/tls.rs new file mode 100644 index 0000000..588a871 --- /dev/null +++ b/crates/victory-loader/src/tls.rs @@ -0,0 +1,218 @@ +//! Static TLS of an executable mapped as a DLL. +//! +//! An exe always gets TLS index 0, so title code reaches its thread-local +//! block as `mov r64, gs:[0x58]` (the thread's TLS array) followed by +//! `[r64]`, without reading `_tls_index`. Mapped as a DLL, the image gets +//! another index. Every such load is turned into a call to a thunk that +//! yields `&array[index]` instead, and the image's `_tls_index` (which CRT +//! code does read, and adds to the array pointer) is set to 0. + +use std::ffi::c_void; + +use anyhow::{Result, bail}; +use victory_pe::ImageInfo; +use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; +use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_READWRITE, + VirtualAlloc, VirtualProtect, +}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +const SCN_MEM_EXECUTE: u32 = 0x2000_0000; +const TLS64_ADDRESS_OF_INDEX: usize = 16; +/// `mov r64, gs:[0x58]` is `65 REX 8B ModRM 25 58 00 00 00`. +const LOAD_LEN: usize = 9; +const THUNK_SIZE: usize = 32; + +/// Redirects the image's TLS-array loads if the OS gave it an index other +/// than 0. Returns the number of loads patched. +/// +/// # Safety +/// `base` is the image `info` describes, mapped and not yet running. +pub(crate) unsafe fn redirect(base: usize, info: &ImageInfo) -> Result { + let Some(tls) = &info.tls else { return Ok(0) }; + // SAFETY: the TLS directory and the index it points to are in the image; + // the OS relocated the pointer and wrote the index. + let index_at = unsafe { + ((base + tls.directory_rva as usize + TLS64_ADDRESS_OF_INDEX) as *const usize).read() + } as *mut u32; + // SAFETY: as above. + let index = unsafe { index_at.read() }; + if index == 0 { + return Ok(0); + } + let thunks = thunks(near(base, info.size_of_image as usize)?, index)?; + let mut patched = 0; + for section in info + .sections + .iter() + .filter(|s| s.characteristics & SCN_MEM_EXECUTE != 0) + { + let start = base + section.rva as usize; + let len = section.virtual_size as usize; + let mut old = 0; + // SAFETY: the section is part of the mapped image. + if unsafe { VirtualProtect(start as _, len, PAGE_EXECUTE_READWRITE, &mut old) } == 0 { + bail!( + "VirtualProtect(code) failed: {}", + std::io::Error::last_os_error() + ); + } + // SAFETY: writable now, and no title code runs yet. + let code = unsafe { std::slice::from_raw_parts_mut(start as *mut u8, len) }; + patched += patch(code, start, thunks); + // SAFETY: restoring the protection we changed; flushing our own code. + unsafe { + VirtualProtect(start as _, len, old, &mut old); + FlushInstructionCache(GetCurrentProcess(), start as _, len); + } + } + // SAFETY: see `index_at`; `.data` is writable. + unsafe { index_at.write(0) }; + tracing::info!(index, patched, "static TLS redirected"); + Ok(patched) +} + +/// Rewrites each `mov r64, gs:[0x58]` in `code` (at address `at`) as +/// `call thunks[r]; nop4`. `thunks` must be within 2 GiB of `code`. +fn patch(code: &mut [u8], at: usize, thunks: usize) -> usize { + let mut count = 0; + let mut i = 0; + while i + LOAD_LEN <= code.len() { + 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. + if c[0] == 0x65 + && (rex == 0x48 || rex == 0x4C) + && c[2] == 0x8B + && c[3] & 0xC7 == 0x04 + && c[4..] == [0x25, 0x58, 0, 0, 0] + && reg != 4 + { + let rel = (thunks + reg * THUNK_SIZE) as i64 - (at + i + 5) as i64; + code[i] = 0xE8; + code[i + 1..i + 5].copy_from_slice(&(rel as i32).to_le_bytes()); + code[i + 5..i + 9].copy_from_slice(&[0x0F, 0x1F, 0x40, 0x00]); + count += 1; + i += LOAD_LEN; + } else { + i += 1; + } + } + count +} + +/// Fills `block` with one thunk per register: `mov r, gs:[0x58]; +/// lea r, [r + index * 8]; ret` (flags untouched, like the load it replaces). +fn thunks(block: *mut u8, index: u32) -> Result { + let disp = (index * 8).to_le_bytes(); + for reg in 0..16u8 { + let (r, low) = (reg >> 3, reg & 7); + let mut code = vec![0x65, 0x48 | r << 2, 0x8B, low << 3 | 4, 0x25, 0x58, 0, 0, 0]; + code.extend([0x48 | r << 2 | r, 0x8D, 0x80 | low << 3 | low]); + if low == 4 { + code.push(0x24); // SIB: [r12 + disp32] + } + code.extend(disp); + code.push(0xC3); + // SAFETY: `block` holds 16 thunks and is still writable. + unsafe { + std::ptr::copy_nonoverlapping( + code.as_ptr(), + block.add(usize::from(reg) * THUNK_SIZE), + code.len(), + ) + }; + } + let mut old = 0; + // SAFETY: `block` is our allocation of one page. + if unsafe { VirtualProtect(block as _, 4096, PAGE_EXECUTE_READ, &mut old) } == 0 { + bail!( + "VirtualProtect(TLS thunks) failed: {}", + std::io::Error::last_os_error() + ); + } + Ok(block as usize) +} + +/// One writable page within `rel32` reach of `[base, base + size)`. Leaked: +/// title code calls into it for the life of the process. +fn near(base: usize, size: usize) -> Result<*mut u8> { + const GRANULE: usize = 0x1_0000; + // The search spans 1 GiB each side, so every call site stays in reach. + if size >= 1 << 30 { + bail!("image too large for TLS thunks within rel32 reach"); + } + let above = (base + size).next_multiple_of(GRANULE); + for k in 0..(1usize << 14) { + for hint in [ + base.checked_sub((k + 1) * GRANULE), + Some(above + k * GRANULE), + ] { + let Some(hint) = hint else { continue }; + // SAFETY: a fresh allocation at a free address, or null. + let p = unsafe { + VirtualAlloc( + hint as *const c_void, + 4096, + MEM_COMMIT | MEM_RESERVE, + PAGE_READWRITE, + ) + }; + if !p.is_null() { + return Ok(p.cast()); + } + } + } + bail!("no free page near the image for TLS thunks") +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Reads the thread's TLS array pointer the way title code does. + fn tls_array() -> usize { + let array: usize; + // SAFETY: reads TEB.ThreadLocalStoragePointer. + unsafe { std::arch::asm!("mov {}, gs:[0x58]", out(reg) array) }; + array + } + + #[test] + fn loads_become_calls_that_yield_the_title_slot() { + let page = near(tls_array as *const () as usize, 0).unwrap(); + let thunks = thunks(near(page as usize, 4096).unwrap(), 3).unwrap(); + // (before the load, REX, ModRM, after the load): each case returns + // the loaded register in rax; r12 is saved, being callee-saved. + let cases: [(&[u8], u8, u8, &[u8]); 3] = [ + (&[], 0x48, 0x04, &[0xC3]), // rax + (&[], 0x4C, 0x04, &[0x4C, 0x89, 0xC0, 0xC3]), // r8 + ( + &[0x41, 0x54], + 0x4C, + 0x24, + &[0x4C, 0x89, 0xE0, 0x41, 0x5C, 0xC3], + ), // r12 + ]; + for (before, rex, modrm, after) in cases { + let mut code = before.to_vec(); + code.extend([0x65, rex, 0x8B, modrm, 0x25, 0x58, 0, 0, 0]); + code.extend(after); + // SAFETY: the page is ours and writable. + let bytes = unsafe { std::slice::from_raw_parts_mut(page, code.len()) }; + bytes.copy_from_slice(&code); + assert_eq!(patch(bytes, page as usize, thunks), 1); + let mut old = 0; + // SAFETY: our page, made executable to run the patched code. + unsafe { VirtualProtect(page as _, 4096, PAGE_EXECUTE_READ, &mut old) }; + // SAFETY: the page holds the patched load and a return. + let f: extern "system" fn() -> usize = unsafe { std::mem::transmute(page) }; + assert_eq!(f(), tls_array() + 3 * 8, "REX {rex:#x} ModRM {modrm:#x}"); + // SAFETY: our page again. + unsafe { VirtualProtect(page as _, 4096, PAGE_READWRITE, &mut old) }; + } + } +} diff --git a/crates/victory-loader/src/windows.rs b/crates/victory-loader/src/windows.rs index 389a03b..61568d5 100644 --- a/crates/victory-loader/src/windows.rs +++ b/crates/victory-loader/src/windows.rs @@ -1,8 +1,10 @@ //! Loading a prepared image as a real Windows module and binding it. +use std::collections::HashSet; use std::ffi::{CString, c_void}; use std::os::windows::ffi::OsStrExt; use std::path::{Path, PathBuf}; +use std::sync::Arc; use std::sync::atomic::AtomicU64; use anyhow::{Context, Result, bail}; @@ -12,7 +14,7 @@ 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}; +use crate::{DLL_PROCESS_ATTACH, ImportResolver, PreparedImage, Provenance, Resolution, prepare}; /// A title image mapped into this process. #[derive(Debug)] @@ -39,6 +41,7 @@ pub struct MissingImport { pub struct BindReport { pub hle: usize, pub host: usize, + pub title: usize, pub missing: Vec, } @@ -72,6 +75,11 @@ pub fn load(prepared: &PreparedImage, dir: &Path) -> Result { path, info: prepared.info.clone(), }; + // A DLL indexes its TLS properly; only an exe assumes index 0. + if !loaded.info.is_dll() { + // SAFETY: just mapped, and no title code has run. + unsafe { crate::tls::redirect(loaded.base(), &loaded.info) }?; + } tracing::info!( base = format_args!("{:#x}", loaded.base()), preferred = format_args!("{:#x}", loaded.info.image_base), @@ -81,6 +89,67 @@ pub fn load(prepared: &PreparedImage, dir: &Path) -> Result { Ok(loaded) } +/// Maps the DLLs the title ships in `title_dir` that `main` imports, +/// directly or through each other, in initialisation order (dependencies +/// first). Only DLL names `wanted` accepts are considered, so DLLs the host +/// or our runtime provide stay with them. Imports are not bound. +pub fn load_title_dlls( + main: &ImageInfo, + title_dir: &Path, + cache_dir: &Path, + wanted: &dyn Fn(&str) -> bool, +) -> Result> { + fn visit( + info: &ImageInfo, + dirs: (&Path, &Path), + wanted: &dyn Fn(&str) -> bool, + seen: &mut HashSet, + loaded: &mut Vec<(String, LoadedImage)>, + ) -> Result<()> { + for module in info.imports.iter().chain(&info.delay_imports) { + let name = module.dll.to_ascii_lowercase(); + let path = dirs.0.join(&name); + if !seen.insert(name.clone()) || !wanted(&name) || !path.is_file() { + continue; + } + let original = + std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?; + let image = load(&prepare(&original)?, dirs.1) + .with_context(|| format!("loading {}", path.display()))?; + visit(&image.info, dirs, wanted, seen, loaded)?; + loaded.push((name, image)); + } + Ok(()) + } + let mut loaded = Vec::new(); + let dirs = (title_dir, cache_dir); + visit(main, dirs, wanted, &mut HashSet::new(), &mut loaded)?; + Ok(loaded) +} + +/// Resolves through `inner`, then through the exports of the title's DLLs. +pub struct WithTitleDlls<'a> { + pub inner: &'a dyn ImportResolver, + pub dlls: &'a [(String, LoadedImage)], +} + +impl ImportResolver for WithTitleDlls<'_> { + fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution { + let found = self.inner.resolve(dll, symbol); + if found != Resolution::Missing { + return found; + } + self.dlls + .iter() + .find(|(name, _)| name.eq_ignore_ascii_case(dll)) + .and_then(|(_, image)| image.export_symbol(symbol)) + .map_or(Resolution::Missing, |address| Resolution::Found { + address, + provenance: Provenance::Title, + }) + } +} + fn write_if_changed(path: &Path, bytes: &[u8]) -> Result<()> { if std::fs::read(path).is_ok_and(|existing| existing == bytes) { return Ok(()); @@ -109,6 +178,16 @@ impl LoadedImage { .map(|f| f as *const () as usize) } + /// Address of an export, by name or ordinal. + pub fn export_symbol(&self, symbol: &ImportSymbol) -> Option { + match symbol { + ImportSymbol::Name { name, .. } => self.export(name), + // SAFETY: MAKEINTRESOURCE-style ordinal lookup on a valid module. + ImportSymbol::Ordinal(o) => unsafe { GetProcAddress(self.module, *o as usize as _) } + .map(|f| f as *const () as usize), + } + } + /// Fills every IAT slot of the image. /// /// Each import goes to `resolver`; whatever it cannot resolve gets an @@ -134,6 +213,7 @@ impl LoadedImage { match provenance { Provenance::Hle => report.hle += 1, Provenance::Host => report.host += 1, + Provenance::Title => report.title += 1, } slots.push((entry.iat_slot_rva, address)); } @@ -209,13 +289,40 @@ impl LoadedImage { } } - /// Starts the title: on a new thread with the stack size from the image - /// header, runs the TLS callbacks (`DLL_PROCESS_ATTACH`), then the - /// original entry point. Returns the thread so the caller can join it. + /// Initialises a DLL as the Windows loader would: its TLS callbacks, + /// then `DllMain(DLL_PROCESS_ATTACH)`. /// /// # Safety - /// Runs title code. Imports must be bound first. - pub unsafe fn spawn_main(self: std::sync::Arc) -> Result> { + /// Runs title code. Imports must be bound first, and the DLLs this one + /// depends on attached. + pub unsafe fn attach(&self) -> Result<()> { + // SAFETY: forwarded from the caller. + unsafe { self.run_tls_callbacks(DLL_PROCESS_ATTACH) }; + if self.info.entry_rva == 0 { + return Ok(()); + } + type DllMain = unsafe extern "system" fn(*mut c_void, u32, *mut c_void) -> i32; + // SAFETY: the entry RVA came from the original image header. + let main: DllMain = + unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) }; + // SAFETY: forwarded from the caller. + if unsafe { main(self.module, DLL_PROCESS_ATTACH, std::ptr::null_mut()) } == 0 { + bail!("DllMain returned FALSE"); + } + Ok(()) + } + + /// Starts the title: on a new thread with the stack size from the image + /// header, attaches `dlls` in order (see [`Self::attach`]), runs the + /// image's TLS callbacks (`DLL_PROCESS_ATTACH`), then its original entry + /// point. Returns the thread so the caller can join it. + /// + /// # Safety + /// Runs title code. Imports of the image and of `dlls` must be bound. + pub unsafe fn spawn_main( + self: Arc, + dlls: Vec<(String, LoadedImage)>, + ) -> Result>> { if self.info.entry_rva == 0 { bail!("image has no entry point"); } @@ -226,6 +333,10 @@ impl LoadedImage { .name("title-main".into()) .stack_size(stack) .spawn(move || { + for (name, dll) in &dlls { + // SAFETY: forwarded from the caller of `spawn_main`. + unsafe { dll.attach() }.with_context(|| format!("attaching {name}"))?; + } // SAFETY: forwarded from the caller of `spawn_main`. unsafe { self.run_tls_callbacks(DLL_PROCESS_ATTACH) }; type Entry = unsafe extern "system" fn(*mut c_void) -> u32; @@ -233,7 +344,7 @@ impl LoadedImage { let entry: Entry = unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) }; // SAFETY: forwarded from the caller of `spawn_main`. - unsafe { entry(std::ptr::null_mut()) } + Ok(unsafe { entry(std::ptr::null_mut()) }) }) .context("spawning title main thread") } diff --git a/crates/victory-loader/tests/load_probe.rs b/crates/victory-loader/tests/load_probe.rs index 859ecdd..d6e8f16 100644 --- a/crates/victory-loader/tests/load_probe.rs +++ b/crates/victory-loader/tests/load_probe.rs @@ -7,7 +7,8 @@ use std::path::{Path, PathBuf}; use std::process::Command; use victory_loader::{ - ImportResolver, Provenance, Resolution, UnimplementedPolicy, prepare, unimplemented_call_count, + ImportResolver, Provenance, Resolution, UnimplementedPolicy, WithTitleDlls, prepare, + unimplemented_call_count, }; use victory_pe::ImportSymbol; use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA}; @@ -120,9 +121,33 @@ fn loads_binds_and_calls_probe() { let dir = tempfile::tempdir().unwrap(); let image = victory_loader::load(&prepared, dir.path()).unwrap(); + + // The "title" ships victory-probe-title.dll: any real DLL will do. + let title_dir = tempfile::tempdir().unwrap(); + std::fs::copy( + r"C:\Windows\System32\version.dll", + title_dir.path().join("victory-probe-title.dll"), + ) + .unwrap(); + let dlls = + victory_loader::load_title_dlls(image.info(), title_dir.path(), dir.path(), &|_| true) + .unwrap(); + let names: Vec<_> = dlls.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, ["victory-probe-title.dll"]); + let resolver = WithTitleDlls { + inner: &TestResolver, + dlls: &dlls, + }; + for (_, dll) in &dlls { + dll.bind_imports(&resolver, UnimplementedPolicy::ReturnZero) + .unwrap(); + // SAFETY: its imports are bound, and it depends on no other title DLL. + unsafe { dll.attach() }.unwrap(); + } let report = image - .bind_imports(&TestResolver, UnimplementedPolicy::ReturnZero) + .bind_imports(&resolver, UnimplementedPolicy::ReturnZero) .unwrap(); + assert_eq!(report.title, 1); assert_eq!(report.hle, 3); assert!(report.host > 0); @@ -142,6 +167,9 @@ fn loads_binds_and_calls_probe() { let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_pid")); assert_eq!(f(), std::process::id(), "host API must pass through"); + let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_title")); + assert_ne!(f(), 0, "title DLL export must be bound"); + let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_delayed")); assert_eq!(f(), 4242, "delay-loaded API must be bound"); diff --git a/crates/victory-shader/src/gfx10/mod.rs b/crates/victory-shader/src/gfx10/mod.rs index 7236dd6..5d6cf6a 100644 --- a/crates/victory-shader/src/gfx10/mod.rs +++ b/crates/victory-shader/src/gfx10/mod.rs @@ -18,7 +18,7 @@ mod fields; mod opcodes; mod sp3; -pub use fields::{Cache, Dpp, Fields, Operand, Sdwa, Valu}; +pub use fields::{Cache, Dpp, Fields, NULL, Operand, Sdwa, Valu}; use std::collections::BTreeMap; @@ -76,12 +76,9 @@ pub fn decode(code: &[u8]) -> Result, ShaderError> { while !found.contains_key(&offset) { let inst = instruction(code, offset)?; let next = offset + 4 * inst.words.len(); - let flow = match flow(&inst, next, code.len())? { - Flow::Stop if inst.name() == Some("s_setpc_b64") => { - far_jump(&found, &inst, code.len())?.map_or(Flow::Stop, Flow::Jump) - } - flow => flow, - }; + let flow = control(&inst, code.len(), |at| { + found.range(..at).next_back().map(|(_, i)| i) + })?; found.insert(offset, inst); match flow { Flow::Next => offset = next, @@ -104,13 +101,32 @@ pub fn decode(code: &[u8]) -> Result, ShaderError> { Ok(list) } -enum Flow { +/// Where execution goes after an instruction. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Flow { Next, + /// End of the program, or an indirect jump that is not a far jump. Stop, Jump(usize), + /// Conditional: to the target or the next instruction. Branch(usize), } +/// Control flow after `inst`, resolving far jumps. `before(at)` returns the +/// decoded instruction with the highest offset below `at`, if any. +pub(crate) fn control<'a>( + inst: &Instruction, + len: usize, + before: impl Fn(usize) -> Option<&'a Instruction>, +) -> Result { + Ok(match flow(inst, inst.offset + 4 * inst.words.len(), len)? { + Flow::Stop if inst.name() == Some("s_setpc_b64") => { + far_jump(before, inst, len)?.map_or(Flow::Stop, Flow::Jump) + } + flow => flow, + }) +} + fn flow(inst: &Instruction, next: usize, len: usize) -> Result { let target = || { let delta = 4 * i64::from(inst.words[0] as u16 as i16); @@ -138,8 +154,8 @@ fn flow(inst: &Instruction, next: usize, len: usize) -> Result, +fn far_jump<'a>( + before: impl Fn(usize) -> Option<&'a Instruction>, setpc: &Instruction, len: usize, ) -> Result, ShaderError> { @@ -147,7 +163,7 @@ fn far_jump( let mut delta = None; let mut at = setpc.offset; for _ in 0..4 { - let Some((_, prev)) = found.range(..at).next_back() else { + let Some(prev) = before(at) else { break; }; if prev.offset + 4 * prev.words.len() != at { diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs new file mode 100644 index 0000000..ac4be42 --- /dev/null +++ b/crates/victory-shader/src/ir.rs @@ -0,0 +1,1180 @@ +//! One-to-one SSA form of a native program (decision 0003, step 1). +//! +//! Every machine instruction becomes one [`Inst`], except scheduling-only +//! ones (`s_nop`, `s_waitcnt*`, `s_inst_prefetch`...), which are dropped. +//! Each register dword is a variable: a read names the [`Value`] it sees, a +//! write defines a new one, and [`Phi`]s merge values where control flow +//! joins. Nothing is raised: an instruction keeps its opcode and decoded +//! fields, so its exact semantics stay with it. +//! +//! Implicit operands are explicit: SCC, M0, and EXEC, which every vector +//! instruction reads. A write to a VGPR also reads the register's old value, +//! because lanes disabled in EXEC keep it. +//! +//! M0-relative VGPR access (`v_movrels/d/sd_b32`, `v_swaprel_b32`) names its +//! operand's whole possible range: from the encoded register up to the +//! program's VGPR count, all read (and all written, for a destination). + +use crate::ShaderError; +use crate::gfx10::{self, Fields, Flow, Instruction, Operand}; + +/// One register dword. Scalar codes as in [`Operand::Scalar`]: 0-105 SGPRs, +/// 106/107 VCC, 108-123 trap temporaries, 124 M0, 126/127 EXEC. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Reg { + S(u8), + Scc, + V(u8), +} + +pub const VCC: u8 = 106; +pub const M0: u8 = 124; +pub const EXEC: u8 = 126; + +/// An SSA value: the content of one register dword (SCC: one bit). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Value(pub u32); + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Program { + pub wave64: bool, + /// VGPRs v0 up to this exist; bounds M0-relative access. + pub vgprs: u16, + /// In code order, then copies made to give every loop one entry; block 0 + /// is the entry. + pub blocks: Vec, + /// Registers read before any write, with their value on entry: what the + /// hardware or a called fetch routine set up (user SGPRs, system values, + /// vertex inputs). + pub inputs: Vec<(Reg, Value)>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Block { + /// Byte offset of the block's first machine instruction (shared by a + /// block and its copies). + pub offset: usize, + pub preds: Vec, + pub phis: Vec, + pub insts: Vec, + pub exit: Exit, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Exit { + Jump(usize), + /// `s_cbranch_*`, the block's last instruction. + Branch { + taken: usize, + not_taken: usize, + }, + /// `s_endpgm` and its variants. + End, + /// `s_setpc_b64` to an address held in registers, e.g. the handover to + /// the next half of a merged hardware stage. + Indirect, +} + +impl Exit { + pub fn successors(&self) -> Vec { + match *self { + Exit::Jump(b) => vec![b], + Exit::Branch { taken, not_taken } => vec![taken, not_taken], + Exit::End | Exit::Indirect => vec![], + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Phi { + pub reg: Reg, + pub value: Value, + /// One per predecessor, in [`Block::preds`] order. + pub args: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Inst { + pub machine: Instruction, + pub fields: Fields, + /// Every register dword read, with the value it holds. + pub reads: Vec<(Reg, Value)>, + /// Every register dword written, with the value it receives. + pub writes: Vec<(Reg, Value)>, +} + +impl Inst { + pub fn name(&self) -> &'static str { + self.machine.name().unwrap_or("") + } + + /// The value `reg` holds when this instruction reads it. + pub fn read(&self, reg: Reg) -> Option { + self.reads.iter().find(|r| r.0 == reg).map(|r| r.1) + } + + /// The value this instruction writes to `reg`. + pub fn write(&self, reg: Reg) -> Option { + self.writes.iter().find(|w| w.0 == reg).map(|w| w.1) + } +} + +/// Decodes `code` and builds its SSA form; `vgprs` is the program's VGPR +/// count. Fails on instructions the IR cannot express yet +/// ([`ShaderError::Unsupported`]). +pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result { + let list = gfx10::decode(code)?; + let lanes = 1 + u8::from(wave64); + let isa = |offset, reason| ShaderError::Isa { offset, reason }; + + let mut flows = Vec::with_capacity(list.len()); + let mut leaders = vec![0]; + for (i, inst) in list.iter().enumerate() { + let flow = gfx10::control(inst, code.len(), |at| { + list[..list.partition_point(|i| i.offset < at)].last() + })?; + if let Flow::Jump(t) | Flow::Branch(t) = flow { + leaders.push(t); + } + if flow != Flow::Next + && let Some(next) = list.get(i + 1) + { + leaders.push(next.offset); + } + flows.push(flow); + } + leaders.sort_unstable(); + leaders.dedup(); + let block_at = |offset: usize| { + leaders + .binary_search(&offset) + .map_err(|_| isa(offset, "jump into a block")) + }; + + let mut blocks: Vec = leaders + .iter() + .map(|&offset| Block { + offset, + preds: Vec::new(), + phis: Vec::new(), + insts: Vec::new(), + exit: Exit::End, + }) + .collect(); + let next_offsets: Vec> = (0..list.len()) + .map(|i| list.get(i + 1).map(|n| n.offset)) + .collect(); + for ((machine, flow), next) in list.into_iter().zip(flows).zip(next_offsets) { + let b = leaders.partition_point(|&l| l <= machine.offset) - 1; + let name = machine.name().ok_or(ShaderError::Unsupported { + offset: machine.offset, + what: "unknown opcode", + })?; + let fields = machine.fields(wave64); + let fallthrough = || block_at(next.ok_or(isa(machine.offset, "falls off the code"))?); + let ends = flow != Flow::Next || next.is_none_or(|n| leaders.binary_search(&n).is_ok()); + if ends { + blocks[b].exit = match flow { + Flow::Next => Exit::Jump(fallthrough()?), + Flow::Jump(t) => Exit::Jump(block_at(t)?), + Flow::Branch(t) => Exit::Branch { + taken: block_at(t)?, + not_taken: fallthrough()?, + }, + Flow::Stop if name == "s_setpc_b64" => Exit::Indirect, + Flow::Stop => Exit::End, + }; + } + if let Some((reads, writes)) = effects(&machine, &fields, name, lanes, vgprs)? { + let unset = |regs: Vec| regs.into_iter().map(|r| (r, NONE)).collect(); + blocks[b].insts.push(Inst { + machine, + fields, + reads: unset(reads), + writes: unset(writes), + }); + } + } + link(&mut blocks); + if !blocks[0].preds.is_empty() { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a branch to the program entry", + }); + } + split_irreducible(&mut blocks)?; + + let order = reverse_postorder(&blocks); + let (live_in, live_out) = liveness(&blocks, &order); + let mut values = 0u32; + let mut new_value = || { + values += 1; + Value(values - 1) + }; + let mut inputs = Vec::new(); + let mut outs: Vec> = vec![Vec::new(); blocks.len()]; + let mut current = [NONE; REGS]; + for &b in &order { + current.fill(NONE); + let block = &mut blocks[b]; + for reg in members(&live_in[b]) { + current[index(reg)] = match block.preds[..] { + [] => { + let v = new_value(); + inputs.push((reg, v)); + v + } + // A single predecessor comes earlier in reverse postorder. + [p] => lookup(&outs[p], reg), + _ => { + let value = new_value(); + block.phis.push(Phi { + reg, + value, + args: Vec::new(), + }); + value + } + }; + } + for inst in &mut block.insts { + for (reg, v) in &mut inst.reads { + *v = current[index(*reg)]; + debug_assert_ne!(*v, NONE, "{reg:?} read at {:#x}", inst.machine.offset); + } + for (reg, v) in &mut inst.writes { + *v = new_value(); + current[index(*reg)] = *v; + } + } + outs[b] = members(&live_out[b]) + .map(|reg| (reg, current[index(reg)])) + .collect(); + } + for block in &mut blocks { + for phi in &mut block.phis { + phi.args = block + .preds + .iter() + .map(|&p| lookup(&outs[p], phi.reg)) + .collect(); + debug_assert!(!phi.args.contains(&NONE), "{phi:?}"); + } + } + remove_trivial_phis(&mut blocks, values); + Ok(Program { + wave64, + vgprs, + blocks, + inputs, + }) +} + +/// Placeholder before renaming. +const NONE: Value = Value(u32::MAX); +/// SGPR codes 0-127, SCC, VGPRs 0-255. +const REGS: usize = 128 + 1 + 256; +type RegSet = [u64; REGS.div_ceil(64)]; + +fn index(reg: Reg) -> usize { + match reg { + Reg::S(c) => usize::from(c), + Reg::Scc => 128, + Reg::V(r) => 129 + usize::from(r), + } +} + +fn reg_at(i: usize) -> Reg { + match i { + 0..128 => Reg::S(i as u8), + 128 => Reg::Scc, + _ => Reg::V((i - 129) as u8), + } +} + +fn insert(set: &mut RegSet, reg: Reg) { + let i = index(reg); + set[i / 64] |= 1 << (i % 64); +} + +fn contains(set: &RegSet, reg: Reg) -> bool { + let i = index(reg); + set[i / 64] >> (i % 64) & 1 != 0 +} + +/// In [`Reg`] order, which is also index order. +fn members(set: &RegSet) -> impl Iterator + '_ { + (0..REGS) + .filter(|&i| set[i / 64] >> (i % 64) & 1 != 0) + .map(reg_at) +} + +/// `outs` is sorted by register, and holds every register live out. +fn lookup(outs: &[(Reg, Value)], reg: Reg) -> Value { + outs.binary_search_by_key(®, |&(r, _)| r) + .map_or(NONE, |i| outs[i].1) +} + +pub(crate) fn reverse_postorder(blocks: &[Block]) -> Vec { + let mut seen = vec![false; blocks.len()]; + let mut post = Vec::with_capacity(blocks.len()); + let mut stack = vec![(0, 0)]; + seen[0] = true; + while let Some(top) = stack.last_mut() { + let (b, i) = *top; + top.1 += 1; + match blocks[b].exit.successors().get(i) { + Some(&s) if !seen[s] => { + seen[s] = true; + stack.push((s, 0)); + } + Some(_) => {} + None => { + post.push(b); + stack.pop(); + } + } + } + post.reverse(); + post +} + +/// Recomputes every block's predecessors from the exits. +fn link(blocks: &mut [Block]) { + for block in blocks.iter_mut() { + block.preds.clear(); + } + for b in 0..blocks.len() { + for s in blocks[b].exit.successors() { + blocks[s].preds.push(b); + } + } +} + +/// An edge to an earlier block in reverse postorder whose target does not +/// dominate its source, if any: there the control flow is irreducible. +/// `index` is each block's position in `order`. +pub(crate) fn irreducible_edge( + blocks: &[Block], + order: &[usize], + index: &[usize], +) -> Option<(usize, usize)> { + let &entry = order.first()?; + let mut idom = vec![usize::MAX; blocks.len()]; + idom[entry] = entry; + let intersect = |idom: &[usize], mut a: usize, mut b: usize| { + while a != b { + while index[a] > index[b] { + a = idom[a]; + } + while index[b] > index[a] { + b = idom[b]; + } + } + a + }; + let mut changed = true; + while changed { + changed = false; + for &b in &order[1..] { + let mut new = usize::MAX; + for &q in blocks[b].preds.iter().filter(|&&q| idom[q] != usize::MAX) { + new = if new == usize::MAX { + q + } else { + intersect(&idom, q, new) + }; + } + if idom[b] != new { + idom[b] = new; + changed = true; + } + } + } + for &b in order { + for s in blocks[b].exit.successors() { + if index[s] > index[b] { + continue; + } + let mut d = b; + while d != s && d != entry { + d = idom[d]; + } + if d != s { + return Some((b, s)); + } + } + } + None +} + +/// Node splitting, before SSA. While a loop is entered at several blocks +/// (a compiler-rotated loop whose peeled first test jumps into its body), +/// the entry first in reverse postorder stays the header, and another +/// entry's outside predecessors move to a copy of everything that entry +/// reaches in the loop before the header. The copies run the same +/// instructions, so behaviour is unchanged. +fn split_irreducible(blocks: &mut Vec) -> Result<(), ShaderError> { + let limit = 4 * blocks.len() + 64; + loop { + let order = reverse_postorder(blocks); + let mut index = vec![usize::MAX; blocks.len()]; + for (i, &b) in order.iter().enumerate() { + index[b] = i; + } + let Some((from, _)) = irreducible_edge(blocks, &order, &index) else { + return Ok(()); + }; + let found = multi_entry_loop(blocks, &vec![true; blocks.len()]); + let Some((region, mut entries)) = found.filter(|_| blocks.len() < limit) else { + return Err(ShaderError::Unsupported { + offset: blocks[from].offset, + what: "irreducible control flow", + }); + }; + entries.sort_by_key(|&e| index[e]); + let (header, entry) = (entries[0], entries[1]); + + // What `entry` reaches in the loop before the header, and its copies. + let mut copy = vec![usize::MAX; blocks.len()]; + let mut copied = Vec::new(); + let mut stack = vec![entry]; + while let Some(b) = stack.pop() { + if copy[b] != usize::MAX { + continue; + } + copy[b] = blocks.len() + copied.len(); + copied.push(b); + for s in blocks[b].exit.successors() { + if region[s] && s != header { + stack.push(s); + } + } + } + let retarget = |exit: &mut Exit, to: &dyn Fn(usize) -> usize| match exit { + Exit::Jump(s) => *s = to(*s), + Exit::Branch { taken, not_taken } => { + *taken = to(*taken); + *not_taken = to(*not_taken); + } + Exit::End | Exit::Indirect => {} + }; + for &b in &copied { + let mut block = blocks[b].clone(); + retarget(&mut block.exit, &|s| { + if copy[s] == usize::MAX { s } else { copy[s] } + }); + blocks.push(block); + } + let outside: Vec = blocks[entry] + .preds + .iter() + .copied() + .filter(|&p| !region[p]) + .collect(); + for p in outside { + retarget(&mut blocks[p].exit, &|s| { + if s == entry { copy[entry] } else { s } + }); + } + link(blocks); + } +} + +/// A loop among the `inside` blocks entered at more than one block, with +/// its entries. Loops nested in a single-entry loop are searched with its +/// header removed, so one is found whenever the control flow is irreducible. +fn multi_entry_loop(blocks: &[Block], inside: &[bool]) -> Option<(Vec, Vec)> { + let reach = |from: usize, forward: bool| { + let mut seen = vec![false; blocks.len()]; + let mut stack = vec![from]; + while let Some(b) = stack.pop() { + let next = if forward { + blocks[b].exit.successors() + } else { + blocks[b].preds.clone() + }; + for n in next { + if inside[n] && !seen[n] { + seen[n] = true; + stack.push(n); + } + } + } + seen + }; + let mut done = vec![false; blocks.len()]; + for v in (0..blocks.len()).filter(|&v| inside[v]) { + if done[v] { + continue; + } + // Blocks on a cycle through `v`; `v` itself only if there is one. + let (ahead, behind) = (reach(v, true), reach(v, false)); + let region: Vec = ahead.iter().zip(&behind).map(|(a, b)| a & b).collect(); + if !region[v] { + continue; + } + let members = (0..blocks.len()).filter(|&b| region[b]); + for b in members.clone() { + done[b] = true; + } + let entries: Vec = members + .filter(|&b| blocks[b].preds.iter().any(|&p| !region[p])) + .collect(); + match entries[..] { + [] => {} + [header] => { + let mut nested = region; + nested[header] = false; + if let Some(found) = multi_entry_loop(blocks, &nested) { + return Some(found); + } + } + _ => return Some((region, entries)), + } + } + None +} + +/// Registers live into and out of each block. +fn liveness(blocks: &[Block], order: &[usize]) -> (Vec, Vec) { + let empty = [0; REGS.div_ceil(64)]; + let mut uses = vec![empty; blocks.len()]; + let mut defs = vec![empty; blocks.len()]; + for (b, block) in blocks.iter().enumerate() { + for inst in &block.insts { + for &(reg, _) in &inst.reads { + if !contains(&defs[b], reg) { + insert(&mut uses[b], reg); + } + } + for &(reg, _) in &inst.writes { + insert(&mut defs[b], reg); + } + } + } + let mut live_in = vec![empty; blocks.len()]; + let mut live_out = vec![empty; blocks.len()]; + let mut changed = true; + while changed { + changed = false; + for &b in order.iter().rev() { + let mut out = empty; + for s in blocks[b].exit.successors() { + for (o, i) in out.iter_mut().zip(&live_in[s]) { + *o |= i; + } + } + let mut inn = empty; + for w in 0..inn.len() { + inn[w] = uses[b][w] | out[w] & !defs[b][w]; + } + if inn != live_in[b] || out != live_out[b] { + (live_in[b], live_out[b]) = (inn, out); + changed = true; + } + } + } + (live_in, live_out) +} + +/// Phis are placed for every live register at every join; those whose +/// arguments are all one value (or the phi itself) are replaced by it. +fn remove_trivial_phis(blocks: &mut [Block], values: u32) { + let mut replaced: Vec = (0..values).map(Value).collect(); + let find = |replaced: &[Value], mut v: Value| { + while replaced[v.0 as usize] != v { + v = replaced[v.0 as usize]; + } + v + }; + let mut changed = true; + while changed { + changed = false; + for block in blocks.iter_mut() { + block.phis.retain(|phi| { + let mut only = None; + for &a in &phi.args { + let a = find(&replaced, a); + if a == phi.value || Some(a) == only { + continue; + } + if only.is_some() { + return true; + } + only = Some(a); + } + let Some(v) = only else { return true }; + replaced[phi.value.0 as usize] = v; + changed = true; + false + }); + } + } + for block in blocks { + for phi in &mut block.phis { + for a in &mut phi.args { + *a = find(&replaced, *a); + } + } + for inst in &mut block.insts { + for (_, v) in &mut inst.reads { + *v = find(&replaced, *v); + } + } + } +} + +/// Scheduling hints, performance counters and tracing: no effect on results. +const DROPPED: &[&str] = &[ + "s_nop", + "s_waitcnt", + "s_waitcnt_vscnt", + "s_waitcnt_vmcnt", + "s_waitcnt_expcnt", + "s_waitcnt_lgkmcnt", + "s_waitcnt_depctr", + "s_wait_idle", + "s_inst_prefetch", + "s_clause", + "s_setprio", + "s_sleep", + "s_ttracedata", + "s_ttracedata_imm", + "s_incperflevel", + "s_decperflevel", + "v_nop", + "v_pipeflush", + "v_clrexcp", +]; + +/// Registers read, registers written. +type Effects = (Vec, Vec); + +/// Registers an instruction reads and writes, one per dword, or `None` if +/// the IR drops it. +fn effects( + inst: &Instruction, + fields: &Fields, + name: &'static str, + lanes: u8, + vgprs: u16, +) -> Result, ShaderError> { + if DROPPED.contains(&name) { + return Ok(None); + } + let unsupported = || ShaderError::Unsupported { + offset: inst.offset, + what: name, + }; + let mask = |code: u8| (0..lanes).map(move |i| Reg::S(code + i)); + let (mut r, mut w) = (Vec::new(), Vec::new()); + let regs = |op: &Operand, out: &mut Vec| { + add_regs(op, lanes, out).map_err(|_| ShaderError::Isa { + offset: inst.offset, + reason: "register range out of bounds", + }) + }; + let vector = !matches!( + fields, + Fields::Sop { .. } | Fields::Sopp { .. } | Fields::Smem { .. } + ); + match fields { + Fields::Sop { dst, src, .. } => { + if name.starts_with("s_movrel") + || name.starts_with("s_subvector_loop") + || matches!(name, "s_call_b64" | "s_rfe_b64") + { + return Err(unsupported()); + } + for s in src { + regs(s, &mut r)?; + } + if let Some(d) = dst { + regs(d, &mut w)?; + } + if matches!(name, "s_addc_u32" | "s_subb_u32" | "s_cmovk_i32") + || name.starts_with("s_cselect_") + || name.starts_with("s_cmov_") + { + r.push(Reg::Scc); + } + if name.contains("saveexec") || name.contains("wrexec") { + r.extend(mask(EXEC)); + w.extend(mask(EXEC)); + } + if writes_scc(inst.encoding, name) { + w.push(Reg::Scc); + } + } + Fields::Sopp { .. } => match name { + "s_cbranch_scc0" | "s_cbranch_scc1" => r.push(Reg::Scc), + "s_cbranch_vccz" | "s_cbranch_vccnz" => r.extend(mask(VCC)), + "s_cbranch_execz" | "s_cbranch_execnz" => r.extend(mask(EXEC)), + "s_sendmsg" | "s_sendmsghalt" => r.push(Reg::S(M0)), + "s_endpgm" + | "s_endpgm_saved" + | "s_endpgm_ordered_ps_done" + | "s_code_end" + | "s_branch" + | "s_barrier" + | "s_icache_inv" + | "s_wakeup" + | "s_round_mode" + | "s_denorm_mode" => {} + _ => return Err(unsupported()), + }, + Fields::Smem { + data, + base, + soffset, + .. + } => match name { + "s_memtime" | "s_memrealtime" | "s_get_waveid_in_workgroup" => { + regs(data.as_ref().ok_or_else(unsupported)?, &mut w)?; + } + "s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => {} + _ if name.contains("_load_") || name.contains("_store_") => { + regs(base, &mut r)?; + regs(soffset, &mut r)?; + let data = data.as_ref().ok_or_else(unsupported)?; + regs( + data, + if name.contains("_load_") { + &mut w + } else { + &mut r + }, + )?; + } + _ => return Err(unsupported()), + }, + Fields::Valu(v) => { + let (src_indexed, dst_indexed) = match name { + "v_movrels_b32" => (true, false), + "v_movreld_b32" => (false, true), + "v_movrelsd_b32" | "v_movrelsd_2_b32" | "v_swaprel_b32" => (true, true), + _ => (false, false), + }; + // v[reg + M0] for any M0 that stays inside the program's VGPRs. + let indexed = |op: &Operand, out: &mut Vec| match *op { + Operand::Vector { reg, .. } if u16::from(reg) < vgprs => { + out.extend((u16::from(reg)..vgprs).map(|r| Reg::V(r as u8))); + Ok(()) + } + _ => Err(ShaderError::Isa { + offset: inst.offset, + reason: "relative VGPR base outside the program's VGPRs", + }), + }; + for (i, s) in v.src.iter().enumerate() { + if i == 0 && src_indexed { + indexed(s, &mut r)?; + } else { + regs(s, &mut r)?; + } + } + // GFX10 compares into EXEC write nothing else. + if name.starts_with("v_cmpx") { + w.extend(mask(EXEC)); + } else if let Some(d) = &v.dst { + if dst_indexed { + indexed(d, &mut w)?; + } else { + regs(d, &mut w)?; + } + } + if let Some(c) = &v.carry { + regs(c, &mut w)?; + } + match name { + "v_swap_b32" => regs(&v.src[0], &mut w)?, + "v_swaprel_b32" => indexed(&v.src[0], &mut w)?, + _ => {} + } + if name.starts_with("v_interp_") || src_indexed || dst_indexed { + r.push(Reg::S(M0)); + } + } + Fields::Vintrp { dst, src, .. } => { + regs(src, &mut r)?; + r.push(Reg::S(M0)); + regs(dst, &mut w)?; + } + Fields::Ds { + dst, + addr, + data, + gds, + .. + } => { + for o in addr.iter().chain(data) { + regs(o, &mut r)?; + } + if let Some(d) = dst { + regs(d, &mut w)?; + } + if *gds + || name.starts_with("ds_gws") + || name.contains("addtid") + || matches!(name, "ds_ordered_count" | "ds_append" | "ds_consume") + { + r.push(Reg::S(M0)); + } + } + Fields::Buffer { + data, + addr, + rsrc, + soffset, + offen, + idxen, + lds, + cache, + .. + } => { + if *offen || *idxen { + regs(addr, &mut r)?; + } + regs(rsrc, &mut r)?; + regs(soffset, &mut r)?; + if *lds { + r.push(Reg::S(M0)); + } + if let Some(d) = data { + if name.contains("_load_") { + if !lds { + regs(d, &mut w)?; + } + } else if name.contains("_store_") { + regs(d, &mut r)?; + } else if name.contains("_atomic_") { + regs(d, &mut r)?; + if cache.glc { + regs(&atomic_result(d, name), &mut w)?; + } + } else { + return Err(unsupported()); + } + } + } + Fields::Image { + data, + addr, + rsrc, + sampler, + cache, + .. + } => { + for a in addr.iter().chain([rsrc]).chain(sampler) { + regs(a, &mut r)?; + } + if name.contains("_store") { + regs(data, &mut r)?; + } else if name.contains("_atomic_") { + regs(data, &mut r)?; + if cache.glc { + regs(&atomic_result(data, name), &mut w)?; + } + } else { + regs(data, &mut w)?; + } + } + Fields::Flat { + dst, + addr, + data, + saddr, + .. + } => { + for o in [addr, data, saddr].into_iter().flatten() { + regs(o, &mut r)?; + } + if let Some(d) = dst { + regs(d, &mut w)?; + } + } + Fields::Exp { src, .. } => { + for s in src.iter().flatten() { + regs(s, &mut r)?; + } + } + } + if vector { + r.extend(mask(EXEC)); + // Lanes disabled in EXEC keep the old value. + r.extend(w.iter().filter(|w| matches!(w, Reg::V(_)))); + } + let mut seen = Vec::with_capacity(r.len()); + r.retain(|reg| { + let new = !seen.contains(reg); + seen.push(*reg); + new + }); + Ok(Some((r, w))) +} + +/// Scalar ALU opcodes that set SCC (carry, overflow, comparison, or "result +/// is not zero"). +fn writes_scc(encoding: gfx10::Encoding, name: &str) -> bool { + use gfx10::Encoding::*; + match encoding { + Sopc => true, + Sopk => name.starts_with("s_cmpk_") || name == "s_addk_i32", + _ => { + let stem = name.split('_').nth(1).unwrap_or(""); + name.contains("saveexec") + || name.contains("wrexec") + || matches!( + stem, + "add" + | "sub" + | "addc" + | "subb" + | "min" + | "max" + | "and" + | "or" + | "xor" + | "andn2" + | "orn2" + | "nand" + | "nor" + | "xnor" + | "lshl" + | "lshr" + | "ashr" + | "bfe" + | "absdiff" + | "lshl1" + | "lshl2" + | "lshl3" + | "lshl4" + | "not" + | "wqm" + | "bcnt0" + | "bcnt1" + | "quadmask" + | "abs" + ) + } + } +} + +/// What an atomic with `glc` returns: the old value (for compare-and-swap, +/// half the data operand). +fn atomic_result(data: &Operand, name: &str) -> Operand { + match *data { + Operand::Vector { reg, dwords } if name.contains("cmpswap") => Operand::Vector { + reg, + dwords: dwords / 2, + }, + op => op, + } +} + +/// Appends the register dwords an operand names; reading `vccz`, `execz`, +/// `scc` or `lds_direct` reads the register behind it. +fn add_regs(op: &Operand, lanes: u8, out: &mut Vec) -> Result<(), ()> { + match *op { + Operand::Scalar { code, .. } if code == gfx10::NULL => {} + Operand::Scalar { code, dwords } => { + let end = u16::from(code) + u16::from(dwords); + if end > 128 { + return Err(()); + } + out.extend((code..end as u8).map(Reg::S)); + } + Operand::Vector { reg, dwords } => { + if u16::from(reg) + u16::from(dwords) > 256 { + return Err(()); + } + out.extend((0..dwords).map(|i| Reg::V(reg + i))); + } + Operand::Const(251) => out.extend((0..lanes).map(|i| Reg::S(VCC + i))), + Operand::Const(252) => out.extend((0..lanes).map(|i| Reg::S(EXEC + i))), + Operand::Const(253) => out.push(Reg::Scc), + Operand::Const(254) => out.push(Reg::S(M0)), + Operand::Const(_) | Operand::Literal(_) | Operand::Attr { .. } => {} + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const S_ENDPGM: u32 = 0xBF81_0000; + + fn build_words(words: &[u32], wave64: bool) -> Program { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + build(&code, wave64, 256).unwrap() + } + + fn input(p: &Program, reg: Reg) -> Value { + p.inputs.iter().find(|i| i.0 == reg).expect("input").1 + } + + #[test] + fn joins_get_phis_only_where_values_differ() { + let code = [ + 0xBF06_0100, // s_cmp_eq_u32 s0, s1 + 0xBF85_0001, // s_cbranch_scc1 -> 12 + 0xBE82_0380, // s_mov_b32 s2, 0 + 0x7E00_0202, // 12: v_mov_b32 v0, s2 + 0x7E02_0200, // v_mov_b32 v1, s0 + S_ENDPGM, + ]; + for wave64 in [false, true] { + let p = build_words(&code, wave64); + let [b0, b1, b2] = &p.blocks[..] else { + panic!("{:?}", p.blocks) + }; + assert_eq!( + b0.exit, + Exit::Branch { + taken: 2, + not_taken: 1 + } + ); + assert_eq!(b1.exit, Exit::Jump(2)); + assert_eq!(b2.preds, [0, 1]); + assert_eq!(b0.insts[1].read(Reg::Scc), b0.insts[0].write(Reg::Scc)); + + // s2 differs per path; s0, EXEC, v0 and v1 do not. + let [phi] = &b2.phis[..] else { + panic!("{:?}", b2.phis) + }; + assert_eq!(phi.reg, Reg::S(2)); + assert_eq!( + phi.args, + [input(&p, Reg::S(2)), b1.insts[0].write(Reg::S(2)).unwrap()] + ); + let [mov0, mov1, end] = &b2.insts[..] else { + panic!() + }; + assert_eq!(mov0.read(Reg::S(2)), Some(phi.value)); + assert_eq!(mov1.read(Reg::S(0)), Some(input(&p, Reg::S(0)))); + // The old v1 is read: lanes outside EXEC keep it. + assert_eq!(mov1.read(Reg::V(1)), Some(input(&p, Reg::V(1)))); + assert_eq!(mov1.read(Reg::S(EXEC)), Some(input(&p, Reg::S(EXEC)))); + assert_eq!(mov1.read(Reg::S(EXEC + 1)).is_some(), wave64); + assert_eq!((end.name(), b2.exit), ("s_endpgm", Exit::End)); + } + } + + #[test] + fn loops_carry_values_through_phis() { + let p = build_words( + &[ + 0xBE80_0380, // s_mov_b32 s0, 0 + 0x8000_8100, // 4: s_add_u32 s0, s0, 1 + 0xBF07_8400, // s_cmp_lg_u32 s0, 4 + 0xBF85_FFFD, // s_cbranch_scc1 -> 4 + S_ENDPGM, + ], + true, + ); + assert!(p.inputs.is_empty(), "{:?}", p.inputs); + let [b0, b1, b2] = &p.blocks[..] else { + panic!() + }; + assert_eq!(b1.preds, [0, 1]); + assert_eq!( + b1.exit, + Exit::Branch { + taken: 1, + not_taken: 2 + } + ); + let [phi] = &b1.phis[..] else { + panic!("{:?}", b1.phis) + }; + let add = &b1.insts[0]; + assert_eq!(phi.reg, Reg::S(0)); + assert_eq!( + phi.args, + [ + b0.insts[0].write(Reg::S(0)).unwrap(), + add.write(Reg::S(0)).unwrap() + ] + ); + assert_eq!(add.read(Reg::S(0)), Some(phi.value)); + assert_eq!(b1.insts[1].read(Reg::S(0)), add.write(Reg::S(0))); + assert_eq!(b2.insts[0].name(), "s_endpgm"); + } + + #[test] + fn drops_scheduling_and_follows_far_jumps() { + let p = build_words( + &[ + 0xBF80_0000, // s_nop 0 + 0xBE88_1F00, // s_getpc_b64 s[8:9] + 0x8008_FF08, + 20, // s_add_u32 s8, s8, 20 -> 8 + 20 = 28 + 0x8209_8009, // s_addc_u32 s9, s9, 0 + 0xBE80_2008, // s_setpc_b64 s[8:9] + 0xFFFF_FFFF, // not code + S_ENDPGM, + ], + false, + ); + let names: Vec<_> = p.blocks[0].insts.iter().map(Inst::name).collect(); + assert_eq!( + names, + ["s_getpc_b64", "s_add_u32", "s_addc_u32", "s_setpc_b64"] + ); + assert_eq!(p.blocks[0].exit, Exit::Jump(1)); + assert_eq!(p.blocks[1].offset, 28); + // s_addc_u32 reads the carry s_add_u32 left in SCC. + let i = &p.blocks[0].insts; + assert_eq!(i[2].read(Reg::Scc), i[1].write(Reg::Scc)); + } + + #[test] + fn reports_what_it_cannot_express() { + let code: Vec = [0xBE80_2E01_u32, S_ENDPGM] // s_movrels_b32 s0, s1 + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + assert_eq!( + build(&code, false, 256), + Err(ShaderError::Unsupported { + offset: 0, + what: "s_movrels_b32" + }) + ); + } + + #[test] + fn relative_vgpr_access_spans_up_to_the_vgpr_count() { + let code: Vec = [ + 0x7E04_8501_u32, // v_movreld_b32 v2, v1: v[2 + m0] = v1 + 0x7E00_8704, // v_movrels_b32 v0, v4: v0 = v[4 + m0] + S_ENDPGM, + ] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let p = build(&code, false, 6).unwrap(); + let [movreld, movrels, _] = &p.blocks[0].insts[..] else { + panic!() + }; + let vgprs = |regs: &[(Reg, Value)]| -> Vec { + regs.iter() + .filter_map(|r| match r.0 { + Reg::V(v) => Some(v), + _ => None, + }) + .collect() + }; + assert_eq!(vgprs(&movreld.writes), [2, 3, 4, 5]); + // v1 is the source; v2-v5 are read for the lanes and indices not written. + assert_eq!(vgprs(&movreld.reads), [1, 2, 3, 4, 5]); + assert!(movreld.read(Reg::S(M0)).is_some()); + assert_eq!(vgprs(&movrels.writes), [0]); + assert_eq!(vgprs(&movrels.reads), [4, 5, 0]); + assert_eq!(movrels.read(Reg::V(4)), movreld.write(Reg::V(4))); + assert!(build(&code, false, 4).is_err(), "v4 is past 4 VGPRs"); + } +} diff --git a/crates/victory-shader/src/lib.rs b/crates/victory-shader/src/lib.rs index 214667f..4cb8928 100644 --- a/crates/victory-shader/src/lib.rs +++ b/crates/victory-shader/src/lib.rs @@ -9,7 +9,9 @@ pub mod dxbc; pub mod dxil; pub mod gfx10; +pub mod ir; pub mod native; +pub mod structure; pub use dxbc::{Container, FourCC, Part}; pub use dxil::{DxilProgram, ShaderKind, XboxExtras}; @@ -23,4 +25,7 @@ pub enum ShaderError { Malformed(&'static str), #[error("GFX10 code at {offset:#x}: {reason}")] Isa { offset: usize, reason: &'static str }, + /// Valid code the translator cannot handle yet: an opcode name or a construct. + #[error("GFX10 code at {offset:#x}: {what} is not supported")] + Unsupported { offset: usize, what: &'static str }, } diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs index 84f381a..ab43d3f 100644 --- a/crates/victory-shader/src/native.rs +++ b/crates/victory-shader/src/native.rs @@ -17,6 +17,7 @@ //! mesh 0x48, compute 0x60; unused ones are 0xDEADBEEF_DEADBEEF //! record +0x00 u64 code offset, +0x08 u64 code size (payload-relative), //! +0x14 u32 flags: bit 5 wave32 (else wave64) +//! +0x50 u32 bits 0-9 VGPRs used, bits 20-27 SGPRs used //! ``` //! //! Other kinds seen: 0x07 program header + bitcode (or a stub when stripped), @@ -47,9 +48,10 @@ const SLOTS: [(HwStage, usize); 8] = [ (HwStage::Cs, 0x60), ]; const ABSENT: u64 = 0xDEAD_BEEF_DEAD_BEEF; -const RECORD_SIZE: u64 = 0x18; +const RECORD_SIZE: u64 = 0x54; const RECORD_FLAGS: usize = 0x14; const FLAG_WAVE32: u32 = 1 << 5; +const RECORD_REGS: usize = 0x50; /// Unpacked blobs are a few KiB; refuse to allocate for absurd sizes. const MAX_UNPACKED: u64 = 16 << 20; @@ -72,6 +74,8 @@ pub struct NativeProgram { pub stage: HwStage, /// Runs as 64 lanes per wave (else 32); sizes lane masks. pub wave64: bool, + /// VGPRs the program uses (v0 up to this), the bound of indexed access. + pub vgprs: u16, /// GFX10 machine code. pub code: Vec, } @@ -145,9 +149,14 @@ fn programs(fssm: &[u8]) -> Result, ShaderError> { bytes(payload, record, RECORD_SIZE).ok_or(Malformed("FSSM record out of bounds"))?; let code = bytes(payload, u64_at(record, 0)?, u64_at(record, 8)?) .ok_or(Malformed("native code out of bounds"))?; + let vgprs = (u32_at(record, RECORD_REGS)? & 0x3FF) as u16; + if vgprs > 256 { + return Err(Malformed("implausible VGPR count")); + } out.push(NativeProgram { stage, wave64: u32_at(record, RECORD_FLAGS)? & FLAG_WAVE32 == 0, + vgprs, code: code.to_vec(), }); } @@ -166,6 +175,7 @@ mod tests { const VS_CODE: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8]; const PS_CODE: [u8; 4] = [9, 10, 11, 12]; + const VGPRS: u32 = 28; fn slot(stage: HwStage) -> usize { SLOTS.iter().find(|s| s.0 == stage).unwrap().1 @@ -187,6 +197,8 @@ mod tests { let flags = if stage == HwStage::Ps { FLAG_WAVE32 } else { 0 }; payload.extend_from_slice(&[0; 4]); payload.extend_from_slice(&flags.to_le_bytes()); + payload.resize(record as usize + RECORD_REGS, 0); + payload.extend_from_slice(&(VGPRS | 31 << 20).to_le_bytes()); payload.extend_from_slice(code); } let mut out = b"FSSM".to_vec(); @@ -236,11 +248,13 @@ mod tests { NativeProgram { stage: HwStage::Vs, wave64: true, + vgprs: 28, code: VS_CODE.to_vec() }, NativeProgram { stage: HwStage::Ps, wave64: false, + vgprs: 28, code: PS_CODE.to_vec() }, ] diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs new file mode 100644 index 0000000..bcabd96 --- /dev/null +++ b/crates/victory-shader/src/structure.rs @@ -0,0 +1,1136 @@ +//! Control-flow structurisation (decision 0003): the program as one lane +//! runs it, without EXEC. +//! +//! Lane masks (EXEC, compare and carry results, the SGPRs they are saved +//! in) become per-lane booleans ([`Bools`]). A branch on a wave-wide test of +//! a mask (`s_cbranch_execz`, `vccz`, SCC of a mask operation) becomes a +//! branch on the lane's own bit: compiled code only skips work that lanes +//! outside the mask would not change, or tests a value that is the same in +//! every lane, so either way each lane can decide alone. A path-sensitive +//! pass then proves, for each vector instruction, that EXEC holds in every +//! lane that reaches it; what it cannot prove stays as the instruction's +//! guard, a per-lane `if` around it. +//! +//! The control-flow graph keeps its shape and must be reducible (DXIL's +//! only requirement). Helper lanes of a pixel shader count as live: on PC +//! their side effects are dropped too, and what they compute is only read +//! through derivatives. + +use std::collections::{HashMap, HashSet}; +use std::hash::{BuildHasherDefault, Hasher}; + +use crate::ShaderError; +use crate::gfx10::{Fields, NULL, Operand}; +use crate::ir::{EXEC, Exit, Inst, Program, Reg, VCC, Value}; + +/// A per-lane boolean: a node of [`Bools`]. Equal functions are equal nodes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Bool(u32); + +impl Bool { + pub const FALSE: Bool = Bool(0); + pub const TRUE: Bool = Bool(1); +} + +/// What a variable of [`Bools`] stands for. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Atom { + /// The lane's bit of the compare or carry result in this VALU-written + /// value, before EXEC masking. + Lane(Value), + /// An SCC value, the same in every lane. + Uniform(Value), + /// A lane mask joined at a block entry, by its low dword's phi. + Phi(Value), + /// `s_wqm` result: some lane of the quad is in the source mask. + Quad(Value), + /// A mask the pass cannot see into (loaded, built from scalars, an + /// EXEC write it does not follow): the lane's bit of the register pair + /// this value is a dword of. + Opaque(Value), + /// A constant mask other than all lanes or none. + Constant(u64), +} + +/// Reduced ordered binary decision diagrams over [`Atom`]s. +#[derive(Debug, Clone)] +pub struct Bools { + /// (variable, low, high); nodes 0 and 1 are the constants. + nodes: Vec<(u32, Bool, Bool)>, + unique: Map<(u32, Bool, Bool), Bool>, + memo: Map<(Bool, Bool, Bool), Bool>, + atoms: Vec, + /// Reverse-postorder index of the block that defines each atom. + born: Vec, + ids: Map, + overflow: bool, +} + +/// The tables below have small integer keys; SipHash dominated run time. +type Map = HashMap>; + +/// FxHash's multiply-rotate step. +#[derive(Default)] +struct Fx(u64); + +impl Hasher for Fx { + fn finish(&self) -> u64 { + self.0 + } + + fn write(&mut self, bytes: &[u8]) { + for &b in bytes { + self.write_u64(u64::from(b)); + } + } + + fn write_u32(&mut self, n: u32) { + self.write_u64(u64::from(n)); + } + + fn write_u64(&mut self, n: u64) { + self.0 = (self.0.rotate_left(5) ^ n).wrapping_mul(0x517c_c1b7_2722_0a95); + } + + fn write_usize(&mut self, n: usize) { + self.write_u64(n as u64); + } +} + +const TERMINAL: u32 = u32::MAX; +const MAX_NODES: usize = 1 << 21; + +impl Bools { + fn new() -> Self { + Bools { + nodes: vec![ + (TERMINAL, Bool::FALSE, Bool::FALSE), + (TERMINAL, Bool::TRUE, Bool::TRUE), + ], + unique: Map::default(), + memo: Map::default(), + atoms: Vec::new(), + born: Vec::new(), + ids: Map::default(), + overflow: false, + } + } + + /// The atom tested at the top of `b` and the results when it is false + /// and true; `None` for the constants. + pub fn node(&self, b: Bool) -> Option<(Atom, Bool, Bool)> { + let (v, lo, hi) = self.nodes[b.0 as usize]; + (v != TERMINAL).then(|| (self.atoms[v as usize], lo, hi)) + } + + /// The atoms `b` depends on, in variable order. + pub fn support(&self, b: Bool) -> Vec { + let mut vars = self.vars(b); + vars.sort_unstable(); + vars.into_iter().map(|v| self.atoms[v as usize]).collect() + } + + fn vars(&self, b: Bool) -> Vec { + let (mut seen, mut vars, mut stack) = (Vec::new(), Vec::new(), vec![b]); + while let Some(b) = stack.pop() { + let (v, lo, hi) = self.nodes[b.0 as usize]; + if v == TERMINAL || seen.contains(&b) { + continue; + } + seen.push(b); + if !vars.contains(&v) { + vars.push(v); + } + stack.extend([lo, hi]); + } + vars + } + + fn atom(&mut self, atom: Atom, born: usize) -> Bool { + let v = *self.ids.entry(atom).or_insert_with(|| { + self.atoms.push(atom); + self.born.push(born); + (self.atoms.len() - 1) as u32 + }); + self.mk(v, Bool::FALSE, Bool::TRUE) + } + + fn mk(&mut self, v: u32, lo: Bool, hi: Bool) -> Bool { + if lo == hi { + return lo; + } + if let Some(&b) = self.unique.get(&(v, lo, hi)) { + return b; + } + if self.nodes.len() >= MAX_NODES { + // The caller fails once it sees `overflow`. + self.overflow = true; + return Bool::FALSE; + } + let b = Bool(self.nodes.len() as u32); + self.nodes.push((v, lo, hi)); + self.unique.insert((v, lo, hi), b); + b + } + + /// Cofactors of `b` for `v`, which is `b`'s top variable or above it. + fn split(&self, b: Bool, v: u32) -> (Bool, Bool) { + match self.nodes[b.0 as usize] { + (bv, lo, hi) if bv == v => (lo, hi), + _ => (b, b), + } + } + + fn ite(&mut self, f: Bool, g: Bool, h: Bool) -> Bool { + if f == Bool::TRUE || g == h { + return g; + } + if f == Bool::FALSE { + return h; + } + if (g, h) == (Bool::TRUE, Bool::FALSE) { + return f; + } + if let Some(&r) = self.memo.get(&(f, g, h)) { + return r; + } + let top = |b: Bool| self.nodes[b.0 as usize].0; + let v = top(f).min(top(g)).min(top(h)); + let ((f0, f1), (g0, g1), (h0, h1)) = (self.split(f, v), self.split(g, v), self.split(h, v)); + let lo = self.ite(f0, g0, h0); + let hi = self.ite(f1, g1, h1); + let r = self.mk(v, lo, hi); + self.memo.insert((f, g, h), r); + r + } + + fn and(&mut self, a: Bool, b: Bool) -> Bool { + self.ite(a, b, Bool::FALSE) + } + + fn or(&mut self, a: Bool, b: Bool) -> Bool { + self.ite(a, Bool::TRUE, b) + } + + fn not(&mut self, a: Bool) -> Bool { + self.ite(a, Bool::FALSE, Bool::TRUE) + } + + fn xor(&mut self, a: Bool, b: Bool) -> Bool { + let nb = self.not(b); + self.ite(a, nb, b) + } + + fn implies(&mut self, a: Bool, b: Bool) -> bool { + let nb = self.not(b); + self.and(a, nb) == Bool::FALSE + } + + /// `b` with every atom born at reverse-postorder index `from` or later + /// existentially quantified: what still holds once those are redefined. + fn forget(&mut self, b: Bool, from: usize, memo: &mut Map) -> Bool { + let (v, lo, hi) = self.nodes[b.0 as usize]; + if v == TERMINAL { + return b; + } + if let Some(&r) = memo.get(&b) { + return r; + } + let lo = self.forget(lo, from, memo); + let hi = self.forget(hi, from, memo); + let r = if self.born[v as usize] >= from { + self.or(lo, hi) + } else { + self.mk(v, lo, hi) + }; + memo.insert(b, r); + r + } + + fn restrict(&mut self, b: Bool, v: u32, value: bool, memo: &mut Map) -> Bool { + let (bv, lo, hi) = self.nodes[b.0 as usize]; + if bv == TERMINAL || bv > v { + return b; + } + if bv == v { + return if value { hi } else { lo }; + } + if let Some(&r) = memo.get(&b) { + return r; + } + let l = self.restrict(lo, v, value, memo); + let h = self.restrict(hi, v, value, memo); + let r = self.mk(bv, l, h); + memo.insert(b, r); + r + } + + /// `b` with each atom that `known` decides replaced by its value. + fn given(&mut self, mut b: Bool, known: Bool) -> Bool { + for v in self.vars(b) { + let x = self.mk(v, Bool::FALSE, Bool::TRUE); + let nx = self.not(x); + if self.implies(known, x) { + b = self.restrict(b, v, true, &mut Map::default()); + } else if self.implies(known, nx) { + b = self.restrict(b, v, false, &mut Map::default()); + } + } + b + } +} + +/// How a lane leaves a block. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LaneExit { + Jump(usize), + /// To `taken` in lanes where `when` holds. A condition over + /// [`Atom::Uniform`]s only is a uniform branch. + Branch { + when: Bool, + taken: usize, + not_taken: usize, + }, + End, + Indirect, +} + +/// A [`Program`] as one lane runs it: same blocks, per-lane branches. +#[derive(Debug, Clone)] +pub struct Structured { + pub bools: Bools, + /// Per block. + pub exits: Vec, + /// Per block and instruction: the condition, beyond reaching it, under + /// which a lane runs a vector instruction; `None` when reaching it is + /// enough (lanes outside EXEC then never get there, so a VGPR write + /// needs no old value). Always `None` for scalar instructions. + pub guards: Vec>>, + /// The lane's bit of each lane-mask value, by its low dword's value. + pub masks: HashMap, +} + +/// Builds the per-lane form of `program`. +pub fn structure(program: &Program) -> Result { + let mut l = Lanes::new(program)?; + loop { + let execs = l.masks_in_order(); + let cond = l.paths()?; + let wrong = l.wrong_joins(&cond); + if wrong.is_empty() { + return l.finish(&execs, &cond); + } + l.unresolved.extend(wrong); + l.reset(); + } +} + +/// A lane mask by the values of its low and high dword (both the low one in +/// wave32). +type Key = (Value, Value); + +struct Lanes<'a> { + p: &'a Program, + order: Vec, + /// Reverse-postorder index per block. + index: Vec, + /// Per block, in predecessor order: (block, over its taken edge). + incoming: Vec>, + /// Block and instruction index writing each value. + defs: Map, + /// Block and index of each phi value. + phis: Map, + /// Mask joins found wrong when resolved to a constant: atoms instead. + unresolved: HashSet, + b: Bools, + /// Masks derived from EXEC and VALU results. + masks: Map, + /// Other values read as masks: constants, uniform selects, opaque ones. + other: Map, + /// For branches: SCC of a mask operation ("some lane is set") as the + /// lane's own bit. + scc_lane: Map, + /// Joins resolved to a constant, to check once all edges are known. + joins: Vec, + /// Per block: what a lane knows on entry, over forward edges only. + first: Vec, + /// Per block ending in a branch: when a lane takes it. + when: Vec>, +} + +/// A mask join taken as `value` in every lane that reaches `block`: each +/// incoming mask held (or failed) on its edge. +struct Join { + block: usize, + /// The phi value naming the join. + id: Value, + value: bool, + args: Vec, +} + +struct SopMasks { + dst: Option<(Key, Bool)>, + exec: Option<(Key, Bool)>, + /// Some operand derives from EXEC or a VALU result. + derived: bool, + /// For branches: SCC ("result is not zero") per lane. + scc: Option, +} + +const MAX_ROUNDS: usize = 256; + +impl<'a> Lanes<'a> { + fn new(p: &'a Program) -> Result { + let blocks = &p.blocks; + let order = crate::ir::reverse_postorder(blocks); + let mut index = vec![usize::MAX; blocks.len()]; + for (i, &b) in order.iter().enumerate() { + index[b] = i; + } + check_reducible(p, &order, &index)?; + let mut incoming = vec![Vec::new(); blocks.len()]; + let (mut defs, mut phis) = (Map::default(), Map::default()); + for (b, block) in blocks.iter().enumerate() { + for (k, s) in block.exit.successors().into_iter().enumerate() { + incoming[s].push((b, k == 0)); + } + for (i, phi) in block.phis.iter().enumerate() { + phis.insert(phi.value, (b, i)); + } + for (i, inst) in block.insts.iter().enumerate() { + for &(_, v) in &inst.writes { + defs.insert(v, (b, i)); + } + } + } + Ok(Lanes { + p, + order, + index, + incoming, + defs, + phis, + unresolved: HashSet::new(), + b: Bools::new(), + masks: Map::default(), + other: Map::default(), + scc_lane: Map::default(), + joins: Vec::new(), + first: vec![Bool::FALSE; blocks.len()], + when: vec![None; blocks.len()], + }) + } + + fn reset(&mut self) { + self.b = Bools::new(); + self.masks.clear(); + self.other.clear(); + self.scc_lane.clear(); + self.joins.clear(); + self.first.fill(Bool::FALSE); + self.when.fill(None); + } + + /// Lane masks, branch conditions and forward-edge knowledge, block by + /// block in reverse postorder; returns EXEC at each instruction reading it. + fn masks_in_order(&mut self) -> Vec>> { + let p = self.p; + let input = |reg| p.inputs.iter().find(|i| i.0 == reg).map(|i| i.1); + if let Some(lo) = input(Reg::S(EXEC)) { + let hi = if p.wave64 { + input(Reg::S(EXEC + 1)).unwrap_or(lo) + } else { + lo + }; + self.masks.insert((lo, hi), Bool::TRUE); + } + let mut execs: Vec>> = + p.blocks.iter().map(|b| vec![None; b.insts.len()]).collect(); + for n in 0..self.order.len() { + let b = self.order[n]; + let mut c = if n == 0 { Bool::TRUE } else { Bool::FALSE }; + for k in 0..self.incoming[b].len() { + let (q, taken) = self.incoming[b][k]; + if self.index[q] < n { + let e = self.edge(self.first[q], q, taken); + c = self.b.or(c, e); + } + } + self.first[b] = c; + for (i, inst) in p.blocks[b].insts.iter().enumerate() { + if inst.read(Reg::S(EXEC)).is_some() { + execs[b][i] = Some(self.exec(inst)); + } + self.step(inst); + } + if let Exit::Branch { .. } = p.blocks[b].exit + && let Some(last) = p.blocks[b].insts.last() + { + self.when[b] = Some(self.branch(last)); + } + } + execs + } + + /// `c` narrowed by the branch at the end of `q` towards one successor. + fn edge(&mut self, c: Bool, q: usize, taken: bool) -> Bool { + match self.when[q] { + Some(w) if taken => self.b.and(c, w), + Some(w) => { + let nw = self.b.not(w); + self.b.and(c, nw) + } + None => c, + } + } + + /// Joins whose constant fails on some edge, given what lanes know. + fn wrong_joins(&mut self, cond: &[Bool]) -> Vec { + let mut wrong = Vec::new(); + let mut j = 0; + // Checking an argument can resolve another join; it is checked too. + while j < self.joins.len() { + let (block, id, value) = (self.joins[j].block, self.joins[j].id, self.joins[j].value); + for (n, a) in self.joins[j].args.clone().into_iter().enumerate() { + let (q, taken) = self.incoming[block][n]; + let e = self.edge(cond[q], q, taken); + let mut m = self.mask(a).0; + if !value { + m = self.b.not(m); + } + if !self.b.implies(e, m) { + wrong.push(id); + break; + } + } + j += 1; + } + wrong + } + + fn finish( + mut self, + execs: &[Vec>], + cond: &[Bool], + ) -> Result { + let blocks = &self.p.blocks; + let b = &mut self.b; + let guards = blocks + .iter() + .enumerate() + .map(|(n, block)| { + block + .insts + .iter() + .zip(&execs[n]) + .map(|(inst, exec)| match (exec, &inst.fields) { + (None, _) + | (_, Fields::Sop { .. } | Fields::Sopp { .. } | Fields::Smem { .. }) => { + None + } + (&Some(e), _) if b.implies(cond[n], e) => None, + (&Some(e), _) => Some(b.given(e, cond[n])), + }) + .collect() + }) + .collect(); + let exits = blocks + .iter() + .enumerate() + .map(|(n, block)| match block.exit { + Exit::Jump(t) => LaneExit::Jump(t), + Exit::End => LaneExit::End, + Exit::Indirect => LaneExit::Indirect, + Exit::Branch { taken, not_taken } => LaneExit::Branch { + when: b.given(self.when[n].unwrap_or(Bool::FALSE), cond[n]), + taken, + not_taken, + }, + }) + .collect(); + if self.b.overflow { + return Err(TOO_LARGE); + } + Ok(Structured { + masks: self.masks.iter().map(|(&(lo, _), &m)| (lo, m)).collect(), + bools: self.b, + exits, + guards, + }) + } + + fn key(&self, value: impl Fn(Reg) -> Option, code: u8) -> Option { + let lo = value(Reg::S(code))?; + let hi = if self.p.wave64 { + value(Reg::S(code + 1))? + } else { + lo + }; + Some((lo, hi)) + } + + fn born(&self, v: Value) -> usize { + match (self.defs.get(&v), self.phis.get(&v)) { + (Some(&(b, _)), _) | (_, Some(&(b, _))) => self.index[b], + _ => 0, + } + } + + fn exec(&mut self, inst: &Inst) -> Bool { + match self.key(|r| inst.read(r), EXEC) { + Some(k) => self.mask(k).0, + None => Bool::TRUE, + } + } + + /// The mask a value pair holds, and whether it derives from EXEC or a + /// VALU result. + fn mask(&mut self, k: Key) -> (Bool, bool) { + if let Some(&m) = self.masks.get(&k) { + return (m, true); + } + if let Some(&m) = self.other.get(&k) { + return (m, false); + } + let p = self.p; + let (m, derived) = match self.join(k) { + Some(join) => join, + None => { + let (lo, hi) = (self.defs.get(&k.0).copied(), self.defs.get(&k.1).copied()); + let def = |d: Option<(usize, usize)>| d.map(|(b, i)| &p.blocks[b].insts[i]); + let m = match (lo, hi) { + (Some(at), Some(hi)) if at == hi => def(lo) + .and_then(|i| self.sop(i)) + .and_then(|r| r.dst) + .map(|d| d.1), + _ => None, + }; + // What an EXEC write the pass does not follow leaves there. + let exec_write = |d: Option<(usize, usize)>, v: Value| { + def(d).is_some_and(|i| { + i.write(Reg::S(EXEC)) == Some(v) || i.write(Reg::S(EXEC + 1)) == Some(v) + }) + }; + let derived = exec_write(lo, k.0) || exec_write(hi, k.1); + let m = m.unwrap_or_else(|| { + let born = self.born(k.0); + self.b.atom(Atom::Opaque(k.0), born) + }); + (m, derived) + } + }; + let cache = if derived { + &mut self.masks + } else { + &mut self.other + }; + cache.insert(k, m); + (m, derived) + } + + /// A mask joined by phis at a block entry, and whether a mask coming in + /// on a forward edge derives from EXEC or a VALU result. Where every + /// lane arriving so far has the incoming mask set (or clear), the join + /// is that constant, for a lane can only read it after arriving. + fn join(&mut self, k: Key) -> Option<(Bool, bool)> { + let p = self.p; + let (lo, hi) = (self.phis.get(&k.0).copied(), self.phis.get(&k.1).copied()); + let block = match (lo, hi) { + (Some((a, _)), Some((b, _))) if a != b => return None, + (Some((b, _)), _) | (_, Some((b, _))) => b, + _ => return None, + }; + let target = &p.blocks[block]; + let arg = |phi: Option<(usize, usize)>, own: Value, n: usize| { + phi.map_or(own, |(_, i)| target.phis[i].args[n]) + }; + let args: Vec = (0..target.preds.len()) + .map(|n| (arg(lo, k.0, n), arg(hi, k.1, n))) + .collect(); + let id = lo.map_or(k.1, |_| k.0); + let mut derived = false; + // (edge condition, mask) per forward edge; back edges come later. + let mut forward = Vec::new(); + for (n, &a) in args.iter().enumerate() { + let (q, taken) = self.incoming[block][n]; + if self.index[q] < self.index[block] { + let (m, d) = self.mask(a); + derived |= d; + let e = self.edge(self.first[q], q, taken); + forward.push((e, m)); + } + } + if forward.len() == args.len() + && let Some(&(_, m)) = forward.first() + && forward.iter().all(|f| f.1 == m) + { + return Some((m, derived)); + } + if !self.unresolved.contains(&id) { + for value in [true, false] { + let b = &mut self.b; + let holds = forward.iter().all(|&(e, m)| { + let m = if value { m } else { b.not(m) }; + b.implies(e, m) + }); + if holds { + self.joins.push(Join { + block, + id, + value, + args, + }); + let m = if value { Bool::TRUE } else { Bool::FALSE }; + return Some((m, derived)); + } + } + } + let born = self.index[block]; + Some((self.b.atom(Atom::Phi(id), born), derived)) + } + + fn operand(&mut self, inst: &Inst, op: &Operand) -> Option<(Bool, bool)> { + let wave64 = self.p.wave64; + let constant = |b: &mut Bools, v: u64| { + let v = if wave64 { v } else { v & 0xFFFF_FFFF }; + match v { + 0 => Bool::FALSE, + _ if v == u64::MAX >> (32 * u8::from(!wave64)) => Bool::TRUE, + _ => b.atom(Atom::Constant(v), 0), + } + }; + Some(match *op { + Operand::Scalar { code, .. } if code != NULL => { + let k = self.key(|r| inst.read(r), code)?; + self.mask(k) + } + Operand::Const(c @ 128..=208) => { + let v = if c <= 192 { + i64::from(c) - 128 + } else { + 192 - i64::from(c) + }; + (constant(&mut self.b, v as u64), false) + } + Operand::Literal(x) => (constant(&mut self.b, u64::from(x)), false), + _ => return None, + }) + } + + /// Lane-mask meaning of a lane-width scalar operation. + fn sop(&mut self, inst: &Inst) -> Option { + let Fields::Sop { dst, src, .. } = &inst.fields else { + return None; + }; + let width = if self.p.wave64 { "_b64" } else { "_b32" }; + let op = inst.name().strip_prefix("s_")?.strip_suffix(width)?; + let dst = match dst { + Some(Operand::Scalar { code, .. }) if *code != NULL => { + self.key(|r| inst.write(r), *code) + } + _ => None, + }; + let exec_out = self.key(|r| inst.write(r), EXEC); + let (save, f) = match (op.strip_suffix("_saveexec"), op.strip_suffix("_wrexec")) { + (Some(f), _) => (Some(true), f), + (_, Some(f)) => (Some(false), f), + _ => (None, op), + }; + let mut derived = exec_out.is_some() || save.is_some(); + let mut arg = |n: usize, l: &mut Self| { + let (m, d) = l.operand(inst, src.get(n)?)?; + derived |= d; + Some(m) + }; + if let Some(saveexec) = save { + let s = arg(0, self)?; + let exec = self.exec(inst); + let new = self.combine(f, s, exec)?; + let saved = if saveexec { exec } else { new }; + return Some(SopMasks { + dst: dst.map(|d| (d, saved)), + exec: exec_out.map(|e| (e, new)), + derived, + scc: Some(new), + }); + } + let (result, scc) = match op { + "mov" => (arg(0, self)?, None), + "not" => { + let a = arg(0, self)?; + let r = self.b.not(a); + (r, Some(r)) + } + "wqm" => { + let a = arg(0, self)?; + let lo = dst.or(exec_out)?.0; + let born = self.born(lo); + let q = self.b.atom(Atom::Quad(lo), born); + let r = self.b.or(a, q); + (r, Some(r)) + } + "cselect" => { + let (a, c) = (arg(0, self)?, arg(1, self)?); + let scc = inst.read(Reg::Scc)?; + let born = self.born(scc); + let u = self.b.atom(Atom::Uniform(scc), born); + (self.b.ite(u, a, c), None) + } + _ => { + let (a, c) = (arg(0, self)?, arg(1, self)?); + let r = self.combine(op, a, c)?; + (r, Some(r)) + } + }; + Some(SopMasks { + dst: dst.map(|d| (d, result)), + exec: exec_out.map(|e| (e, result)), + derived, + scc, + }) + } + + fn combine(&mut self, f: &str, a: Bool, c: Bool) -> Option { + let b = &mut self.b; + Some(match f { + "and" => b.and(a, c), + "or" => b.or(a, c), + "xor" => b.xor(a, c), + "andn2" => { + let nc = b.not(c); + b.and(a, nc) + } + "orn2" => { + let nc = b.not(c); + b.or(a, nc) + } + "andn1" => { + let na = b.not(a); + b.and(na, c) + } + "orn1" => { + let na = b.not(a); + b.or(na, c) + } + "nand" => { + let r = b.and(a, c); + b.not(r) + } + "nor" => { + let r = b.or(a, c); + b.not(r) + } + "xnor" => { + let r = b.xor(a, c); + b.not(r) + } + _ => return None, + }) + } + + /// Records the masks `inst` defines. + fn step(&mut self, inst: &Inst) { + let name = inst.name(); + match &inst.fields { + Fields::Sop { src, .. } => { + let mut takes_mask = false; + for s in src { + if let Operand::Scalar { code, .. } = *s + && code != NULL + && let Some(k) = self.key(|r| inst.read(r), code) + { + let phi = self.phis.contains_key(&k.0) || self.phis.contains_key(&k.1); + takes_mask |= self.masks.contains_key(&k) || phi && self.mask(k).1; + } + } + let touches_exec = + inst.write(Reg::S(EXEC)).is_some() || inst.read(Reg::S(EXEC)).is_some(); + if (takes_mask || touches_exec) + && let Some(r) = self.sop(inst).filter(|r| r.derived) + { + for (k, m) in r.dst.into_iter().chain(r.exec) { + self.masks.insert(k, m); + } + if let (Some(scc), Some(m)) = (inst.write(Reg::Scc), r.scc) { + self.scc_lane.insert(scc, m); + } + } + // `s_cmp_eq/lg` of a mask: "no lane differs" per lane. + let width = if self.p.wave64 { "64" } else { "32" }; + if takes_mask + && let (Some(rest), Some(scc)) = + (name.strip_prefix("s_cmp_"), inst.write(Reg::Scc)) + && rest + .strip_suffix(width) + .is_some_and(|r| r == "eq_u" || r == "lg_u") + && let [a, c] = &src[..] + && let (Some((a, _)), Some((c, _))) = + (self.operand(inst, a), self.operand(inst, c)) + { + let ne = self.b.xor(a, c); + let m = if rest.starts_with("eq") { + self.b.not(ne) + } else { + ne + }; + self.scc_lane.insert(scc, m); + } + } + Fields::Valu(v) => { + let exec = self.exec(inst); + let lane = |l: &mut Self, k: Key| { + let born = l.born(k.0); + let a = l.b.atom(Atom::Lane(k.0), born); + let m = l.b.and(exec, a); + l.masks.insert(k, m); + }; + if name.starts_with("v_cmpx") { + if let Some(k) = self.key(|r| inst.write(r), EXEC) { + lane(self, k); + } + } else { + let compare = v.dst.filter(|_| name.starts_with("v_cmp")); + for op in compare.iter().chain(&v.carry) { + if let Operand::Scalar { code, .. } = *op + && let Some(k) = self.key(|r| inst.write(r), code) + { + lane(self, k); + } + } + } + } + _ => {} + } + } + + /// The per-lane condition under which a block's closing branch is taken. + fn branch(&mut self, inst: &Inst) -> Bool { + let exec = self.exec(inst); + match inst.name() { + "s_cbranch_execz" => self.b.not(exec), + "s_cbranch_execnz" => exec, + n @ ("s_cbranch_vccz" | "s_cbranch_vccnz") => { + let vcc = match self.key(|r| inst.read(r), VCC) { + Some(k) => self.mask(k).0, + None => Bool::FALSE, + }; + let any = self.b.and(vcc, exec); + if n.ends_with("nz") { + any + } else { + self.b.not(any) + } + } + n => { + let Some(scc) = inst.read(Reg::Scc) else { + return Bool::FALSE; + }; + let set = match self.scc_lane.get(&scc) { + Some(&m) => m, + None => { + let born = self.born(scc); + self.b.atom(Atom::Uniform(scc), born) + } + }; + if n == "s_cbranch_scc1" { + set + } else { + self.b.not(set) + } + } + } + } + + /// What a lane knows on entering each block, to a fixpoint. A loop + /// header forgets what the back edge says about atoms the loop redefines. + fn paths(&mut self) -> Result, ShaderError> { + let n = self.p.blocks.len(); + let mut cond = vec![Bool::FALSE; n]; + if let Some(&entry) = self.order.first() { + cond[entry] = Bool::TRUE; + } + for _ in 0..MAX_ROUNDS { + let mut changed = false; + for i in 1..self.order.len() { + let s = self.order[i]; + let mut c = Bool::FALSE; + for k in 0..self.incoming[s].len() { + let (q, taken) = self.incoming[s][k]; + let mut e = self.edge(cond[q], q, taken); + if i <= self.index[q] { + e = self.b.forget(e, i, &mut Map::default()); + } + c = self.b.or(c, e); + } + if c != cond[s] { + cond[s] = c; + changed = true; + } + } + if self.b.overflow { + return Err(TOO_LARGE); + } + if !changed { + return Ok(cond); + } + } + Err(ShaderError::Isa { + offset: 0, + reason: "lane conditions do not settle", + }) + } +} + +const TOO_LARGE: ShaderError = ShaderError::Isa { + offset: 0, + reason: "lane conditions too large", +}; + +/// `ir::build` splits irreducible loops; checked again because everything +/// here assumes a reducible graph. +fn check_reducible(p: &Program, order: &[usize], index: &[usize]) -> Result<(), ShaderError> { + match crate::ir::irreducible_edge(&p.blocks, order, index) { + Some((from, _)) => Err(ShaderError::Unsupported { + offset: p.blocks[from].offset, + what: "irreducible control flow", + }), + None => Ok(()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ir; + + const S_ENDPGM: u32 = 0xBF81_0000; + + fn build(words: &[u32], wave64: bool) -> Program { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + ir::build(&code, wave64, 256).unwrap() + } + + fn guarded(s: &Structured) -> usize { + s.guards.iter().flatten().filter(|g| g.is_some()).count() + } + + #[test] + fn divergent_if_becomes_a_lane_branch() { + let p = build( + &[ + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0xBE80_3C6A, // s_and_saveexec_b32 s0, vcc_lo + 0xBF88_0001, // s_cbranch_execz -> 16 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0x887E_007E, // 16: s_or_b32 exec_lo, exec_lo, s0 + 0x7E04_0280, // v_mov_b32 v2, 0 + S_ENDPGM, + ], + false, + ); + let s = structure(&p).unwrap(); + let LaneExit::Branch { + when, + taken: 2, + not_taken: 1, + } = s.exits[0] + else { + panic!("{:?}", s.exits) + }; + // Skipped exactly where the compare fails. + let cmp = p.blocks[0].insts[0].write(Reg::S(VCC)).unwrap(); + assert_eq!( + s.bools.node(when), + Some((Atom::Lane(cmp), Bool::TRUE, Bool::FALSE)) + ); + assert_eq!(guarded(&s), 0, "{:?}", s.guards); + } + + #[test] + fn exec_narrowed_without_a_branch_leaves_a_guard() { + let p = build( + &[ + 0x7DA4_0080, // v_cmpx_eq_u32 exec, 0, v0 + 0x7E02_0280, // v_mov_b32 v1, 0 + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + assert_eq!(s.guards[0][0], None, "the compare runs in every lane"); + let g = s.guards[0][1].expect("guard"); + assert!(matches!(s.bools.support(g)[..], [Atom::Lane(_)])); + } + + #[test] + fn divergent_loop_exits_per_lane() { + let p = build( + &[ + 0xBE82_0480, // s_mov_b64 s[2:3], 0 + 0x4A00_0081, // 4: v_add_nc_u32 v0, 1, v0 + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0x8882_026A, // s_or_b64 s[2:3], vcc, s[2:3] + 0x8AFE_027E, // s_andn2_b64 exec, exec, s[2:3] + 0xBF89_FFFB, // s_cbranch_execnz -> 4 + 0x88FE_027E, // s_or_b64 exec, exec, s[2:3] + 0x7E02_0280, // v_mov_b32 v1, 0 + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + assert_eq!(guarded(&s), 0, "{:?}", s.guards); + let LaneExit::Branch { + when, + taken: 1, + not_taken: 2, + } = s.exits[1] + else { + panic!("{:?}", s.exits) + }; + // Back while the lane's compare fails. + assert!(matches!( + s.bools.node(when), + Some((Atom::Lane(_), Bool::TRUE, Bool::FALSE)) + )); + } + + #[test] + fn scalar_branches_stay_uniform() { + let p = build( + &[ + 0xBF06_0100, // s_cmp_eq_u32 s0, s1 + 0xBF85_0001, // s_cbranch_scc1 -> 12 + 0x7E02_0280, // v_mov_b32 v1, 0 + S_ENDPGM, // 12 + ], + true, + ); + let s = structure(&p).unwrap(); + let LaneExit::Branch { when, .. } = s.exits[0] else { + panic!() + }; + assert!(matches!(s.bools.support(when)[..], [Atom::Uniform(_)])); + assert_eq!(guarded(&s), 0); + } + + #[test] + fn irreducible_loops_are_split() { + let p = build( + &[ + 0xBF06_0100, // s_cmp_eq_u32 s0, s1 + 0xBF85_0001, // s_cbranch_scc1 -> 12, into the loop's middle + 0x8002_8102, // 8: s_add_u32 s2, s2, 1 + 0xBF84_FFFE, // 12: s_cbranch_scc0 -> 8 + S_ENDPGM, + ], + false, + ); + // The loop keeps 12 as its header; the entry into 8 gets a copy of it. + let copy = &p.blocks[4]; + assert_eq!((copy.offset, copy.exit), (8, ir::Exit::Jump(2))); + assert_eq!(p.blocks[0].exit.successors(), [2, 4]); + assert_eq!(p.blocks[1].preds, [2]); + assert!(structure(&p).is_ok()); + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 2cca2eb..468d294 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -33,7 +33,7 @@ Converting them ahead of time from files is only a warm-up. | `victory-pe` | read-only PE32+ and import-library analysis | | `victory-loader` | prepare, map, bind and start the title image | | `victory-hle` | console API implementations, host pass-through policy | -| `victory-gpu` | D3D12.X packet streams and GPU memory → host D3D12 (skeleton) | +| `victory-gpu` | D3D12.X objects, command lists and GPU memory → host D3D12 | | `victory-shader` | Xbox shader containers → host shaders | | `victory-formats` | texture layouts, BCPack, audio codecs (skeleton) | | `victory-pipeline` | converter trait, content-addressed cache | @@ -51,7 +51,36 @@ For every `dll!function` the title imports, in order: 1. our implementation in `victory-hle::modules` (always wins); 2. the host's own function, if `HostPolicy` allows that DLL; -3. a generated stub that names the import when called (`--unimplemented +3. an export of a DLL the title ships beside its executable, mapped like + the executable (only DLLs neither of the above serves); +4. a generated stub that names the import when called (`--unimplemented trap` breaks into the debugger and aborts; `zero` logs once and returns 0). -`victory census` shows this classification without running anything. +`LoadLibrary*` of a console-only DLL we implement (e.g. `xgameruntime.dll`) +returns a pseudo handle; `GetProcAddress` on it finds our functions. +`QueryApiImpl` hands out our runtime objects by provider (task queues and +async blocks so far, `victory-hle::modules::xasync`). + +Title storage is a drive on the console, and titles build paths on that. +`victory-hle::modules::files` binds every path-taking title import +(kernel32 and the C/C++ runtime) and rewrites paths on a virtual drive to +the host folder behind it; persistent local storage is one such drive over +a folder under `VICTORY_DATA_DIR`. Other paths reach the host unchanged. + +An exe's code reaches its static TLS as slot 0; mapped as a DLL it gets +another slot, so the loader redirects those loads (`victory-loader::tls`). +`victory run --execute` installs a crash reporter that names faults as +`module+rva` (`victory-loader::crash`). + +`victory census` shows this classification without running anything (it +does not map title DLLs; `victory run` without `--execute` does). + +## Shaders + +`victory_shader::ir::build` turns a native program into SSA, one +instruction per machine instruction. `victory_shader::structure` then +removes EXEC: lane masks become per-lane booleans, wave-wide mask tests +become per-lane branches, and vector instructions keep a guard only where +a lane can reach them with its EXEC bit clear. `victory translate` runs +every shader it finds (containers, SGD5 files) through both and lists what +they cannot handle yet. diff --git a/tests/fixtures/hle-probe/src/lib.rs b/tests/fixtures/hle-probe/src/lib.rs index 8ee844e..264dd6a 100644 --- a/tests/fixtures/hle-probe/src/lib.rs +++ b/tests/fixtures/hle-probe/src/lib.rs @@ -12,6 +12,12 @@ unsafe extern "system" { fn VIctoryProbeNotImplemented(x: u64) -> u64; } +// A DLL the "title" ships; the test supplies a renamed copy of version.dll. +#[link(name = "victory-probe-title", kind = "raw-dylib")] +unsafe extern "system" { + fn GetFileVersionInfoSizeW(path: *const u16, handle: *mut u32) -> u32; +} + // Delay-loaded (see build.rs): bound through the delay-load table. #[link(name = "victory-probe-delayed", kind = "raw-dylib")] unsafe extern "system" { @@ -42,6 +48,17 @@ pub extern "system" fn probe_pid() -> u32 { unsafe { GetCurrentProcessId() } } +/// An export of a title-shipped DLL: the version-info size of kernel32.dll. +#[unsafe(no_mangle)] +pub extern "system" fn probe_title() -> u32 { + let path: Vec = r"C:\Windows\System32\kernel32.dll" + .encode_utf16() + .chain(Some(0)) + .collect(); + let mut handle = 0; + unsafe { GetFileVersionInfoSizeW(path.as_ptr(), &mut handle) } +} + /// A delay-loaded console API. #[unsafe(no_mangle)] pub extern "system" fn probe_delayed() -> u32 { diff --git a/victory.example.toml b/victory.example.toml index ee48e75..0b37ff2 100644 --- a/victory.example.toml +++ b/victory.example.toml @@ -10,6 +10,10 @@ game_dir = 'D:\victory-data\game' # Derived data. Default: %LOCALAPPDATA%\victory\cache. env: VICTORY_CACHE_DIR # cache_dir = 'D:\victory-data\cache' +# What titles save (persistent local storage), kept apart from the cache. +# Default: %LOCALAPPDATA%\victory\data. env: VICTORY_DATA_DIR +# data_dir = 'D:\victory-data\data' + # Other Xbox Series titles used to test platform-level code. # env: VICTORY_TEST_TITLES (separated by ';') test_titles = []