Run Grand Theft Auto VI from first boot into the world

The title now boots through every first-boot and menu screen at its own
30 fps, drawing with translated shaders, with input, sound, saves and
loading served; it reaches the world, where the host GPU path still
fails (see "Not working yet").

Loader and runtime
- Crash reports unwind properly, name C++ throws and host GPU failures,
  carry the title's last debug lines and are appended to crashes.log.
- Thread notices on our own threads, reentrant late DLL loading, exit in
  the console's order, relaunch on a launch-new-game request.
- Offline guard: the title cannot reach the network (sockets, name
  lookups, WinHTTP, the media source resolver); by-name lookups and
  loads follow the import rules.
- Every runtime area the title calls is served (networking hint,
  packages, store, saves, display, UI, speech stubs, user, async pool).
  Saves persist; an update is one rename and survives a kill at any step.
- DirectStorage reads for real: shared worker pool, priorities, zlib and
  BCPack. BCPack is our own decoder; the format's constant tables ship in
  crates/victory-formats/src/bcpack-tables.bin (the asset policy's one
  exception, see docs/asset-policy.md).
- GameInput from XInput pads and the keyboard, with a keyboard stand-in
  pad; console timers (1 ms) for the whole process.
- Audio: XMA2 decoding on the emulated contexts, Opus on the decoder
  queues, the DSP interface as a stub; title memory placed below 2^40.
- Console texture layouts (sizes, tiling, detiling) and the layout
  library's imports.

GPU
- Draws, mesh dispatches and compute dispatches run on the host with
  shaders translated at first use and cached on disk; descriptor heaps,
  views, root signatures, barriers and host texture states; rectangle
  lists; comparison samplers.
- Title memory reaches the host through persistent mirrors that copy
  only pages written since the last copy; shader-written buffers are
  copied back.
- Presentation with frame pacing per event kind; framerate in the window
  caption.

Shaders
- DXIL emission for vertex, pixel, compute and mesh programs from the
  console's native code, with a differential test suite against the PC
  compile. World set: mesh 8,191 of 8,506, vertex/pixel 10,617 of
  12,346, compute 1,643 of 2,539; utility set complete.

Build
- Debugging aids (debug logs, frame capture, stack dumps, scripted keys,
  the host debug layer, the software adapter) exist only with the
  `diagnostics` feature; `[profile.diag]` keeps that build apart.

Not working yet
- In the world the host device is removed within seconds (descriptor
  handling fixes are in, unproven by a surviving run) and frames present
  black.
- 64-bit image atomics, merged geometry stages and the BVH builder's own
  shaders do not translate; reverb is silent.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
MarvisandClaude Fable 5.2 committed 2026-11-23 23:10:01 +01:00
1 parent bc3070991a
commit 2849477415
107 files changed
+42455 -797

No files matched your search

+2
View File
@@ -45,6 +45,8 @@
# Typical game data (non-exhaustive on purpose; the policy check is an allowlist)
*.bin
# The one exception (docs/asset-policy.md): the BCPack format's constant tables.
!/crates/victory-formats/src/bcpack-tables.bin
*.dat
*.pak
*.rpf
Generated
+20
View File
@@ -320,6 +320,12 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "opus-pure"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccd077a3f06e5fc42b04bb59f70d5fe0cdb2c119eef0e240af7e287180ee23ba"
[[package]]
name = "pin-project-lite"
version = "0.2.18"
@@ -682,7 +688,14 @@ dependencies = [
name = "victory-gpu"
version = "0.1.0"
dependencies = [
"anyhow",
"blake3",
"miniz_oxide",
"tempfile",
"tracing",
"victory-formats",
"victory-pipeline",
"victory-shader",
"windows",
"windows-sys",
]
@@ -691,11 +704,16 @@ dependencies = [
name = "victory-hle"
version = "0.1.0"
dependencies = [
"miniz_oxide",
"opus-pure",
"tempfile",
"tracing",
"victory-formats",
"victory-gpu",
"victory-loader",
"victory-pe",
"windows",
"windows-core",
"windows-sys",
]
@@ -738,6 +756,8 @@ version = "0.1.0"
dependencies = [
"miniz_oxide",
"thiserror",
"windows",
"windows-sys",
]
[[package]]
+9
View File
@@ -34,11 +34,14 @@ 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"
windows-core = "0.62.2"
blake3 = "1.8.7"
memchr = "2.8.3"
miniz_oxide = "0.9.1"
walkdir = "2.5.1"
tempfile = "3.27.0"
# Opus decoding for the console's audio decoder (BSD-3-Clause, pure Rust).
opus-pure = "0.2.4"
[workspace.lints.rust]
unsafe_op_in_unsafe_fn = "deny"
@@ -55,3 +58,9 @@ opt-level = 2
[profile.release]
debug = "line-tables-only"
# The development build: release code generation plus the `diagnostics`
# feature (`cargo build --profile diag -p victory --features diagnostics`),
# kept in its own folder so it does not evict the plain release build.
[profile.diag]
inherits = "release"
+15
View File
@@ -33,11 +33,26 @@ victory census [paths...] [--missing] [--strict]
victory lib-exports <import.lib> [--list]
victory shader-info [paths...] [--verbose] [--disasm]
victory run <exe> [--execute] [--unimplemented trap|zero] [--strict]
[--console series-x|series-s] [-- <title arguments>]
victory config
```
Logging: `VICTORY_LOG=victory_loader=trace,info`.
Debugging `run --execute` (builds with `--features diagnostics` only): `VICTORY_STACKS=20,60` prints every thread's stack at those seconds;
`VICTORY_WATCH=<rva>,...` logs a title u32 when it changes; `VICTORY_KEYS=30:Enter,35:X` presses keys
(focus or not); `VICTORY_CRASH_SAVE=<rva>:<len>,...` saves title memory to the cache dir on a crash;
`VICTORY_AUDIO_CAPTURE=<file.wav>` records what the title plays (our process only, from a child process);
`VICTORY_XMA_DUMP=<dir>` saves the first 32 XMA voices' context and input (`VICTORY_XMA_STREAMS=<dir>` runs the ignored `xma` test on them);
`VICTORY_D3D12_DEBUG=1` runs the host debug layer, `VICTORY_D3D12_DRED=1` adds device-removed data to a GPU failure
(the allocation a page fault hit, the commands in flight with their pipelines, user data and root views);
`VICTORY_D3D12_WARP=1` puts the host device on the software adapter (a shader's wild access cannot reset the driver);
`VICTORY_DUMP_TARGETS=1` with `VICTORY_CAPTURE` saves every render target and written texture of the frames in `VICTORY_CAPTURE_FRAMES`.
Every build appends crashes and host GPU failures to `crashes.log` in the title's data folder.
Input: XInput pads. With none connected the keyboard is a pad while the title's window has focus: WASD/IJKL sticks,
arrows D-pad, Enter A, Backspace B, X X, Y Y, Q/E shoulders, Z/C triggers, F/H stick clicks, Esc Menu, Tab View.
## License
GPL-3.0-or-later. See [LICENSE](LICENSE).
+11 -1
View File
@@ -12,7 +12,7 @@ victory-core.workspace = true
victory-pe.workspace = true
victory-loader.workspace = true
victory-hle.workspace = true
victory-shader.workspace = true
victory-shader = { workspace = true, features = ["host"] }
victory-game.workspace = true
anyhow.workspace = true
blake3.workspace = true
@@ -20,5 +20,15 @@ memchr.workspace = true
clap.workspace = true
walkdir.workspace = true
[features]
# Debug-level logs and the debugging switches (frame capture, stack dumps,
# the host debug layer, scripted keys). Off in a plain release build.
diagnostics = [
"victory-core/diagnostics",
"victory-hle/diagnostics",
"victory-loader/diagnostics",
"victory-shader/diagnostics",
]
[lints]
workspace = true
+44 -3
View File
@@ -69,7 +69,22 @@ enum Command {
},
/// Run every shader found (containers, SGD5 files) through the
/// translator and report what it cannot handle yet.
Translate { paths: Vec<PathBuf> },
Translate {
paths: Vec<PathBuf>,
/// Check emitted DXIL with dxil.dll's validator (`VICTORY_DXIL`,
/// else the newest Windows SDK's).
#[arg(long)]
validate: bool,
/// Also create a host D3D12 pipeline for each emitted shader.
#[arg(long)]
pipelines: bool,
/// Print one line per program and outcome.
#[arg(long)]
list: bool,
/// Worker threads (default: every logical core).
#[arg(long)]
jobs: Option<usize>,
},
/// Prepare, map and bind a title executable; with --execute, run it.
Run {
exe: PathBuf,
@@ -82,6 +97,13 @@ enum Command {
/// Actually start the title. Without it, stop after binding.
#[arg(long)]
execute: bool,
/// The console model the title sees (device type, memory).
#[arg(long, value_enum, default_value_t = Console::SeriesX)]
console: Console,
/// Arguments for the title, after `--` (it reads the whole command
/// line; a title that relaunches itself passes some).
#[arg(last = true)]
title_args: Vec<String>,
},
/// Show the resolved configuration and check it.
Config,
@@ -93,8 +115,19 @@ enum Unimplemented {
Zero,
}
#[derive(Clone, Copy, ValueEnum)]
enum Console {
SeriesX,
SeriesS,
}
fn main() -> Result<()> {
victory_core::logging::init("info");
// The audio recorder `run` starts for `VICTORY_AUDIO_CAPTURE`.
#[cfg(all(windows, feature = "diagnostics"))]
if victory_hle::modules::audio::capture::child() {
return Ok(());
}
let cli = Cli::parse();
match cli.command {
Command::Inspect {
@@ -113,13 +146,21 @@ fn main() -> Result<()> {
verbose,
disasm,
} => shader::run(paths, verbose || disasm, disasm),
Command::Translate { paths } => translate::run(paths),
Command::Translate {
paths,
validate,
pipelines,
list,
jobs,
} => translate::run(paths, validate, pipelines, list, jobs),
Command::Run {
exe,
unimplemented,
strict,
execute,
} => run::run(&exe, unimplemented, strict, execute),
console,
title_args: _,
} => run::run(&exe, unimplemented, strict, execute, console),
Command::Config => show_config(),
}
}
+184 -14
View File
@@ -2,14 +2,22 @@ use std::path::Path;
use anyhow::{Context, Result};
use crate::Unimplemented;
use crate::{Console, Unimplemented};
#[cfg(windows)]
pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool) -> Result<()> {
pub fn run(
exe: &Path,
unimplemented: Unimplemented,
strict: bool,
execute: bool,
console: Console,
) -> Result<()> {
use std::sync::Arc;
use victory_hle::{HleResolver, HostPolicy};
use victory_loader::{BindReport, UnimplementedPolicy, WithTitleDlls};
// A title that relaunched itself: the old process must be gone first.
victory_hle::modules::lifecycle::wait_for_previous();
let cfg = victory_core::Config::load()?;
let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?;
let prepared = victory_loader::prepare(&original)?;
@@ -20,6 +28,7 @@ pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool
}
let images = cfg.cache_subdir("images")?;
victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?);
let image = victory_loader::load(&prepared, &images)?;
victory_hle::runtime::set_main_image(image.base());
victory_hle::runtime::set_image_path(image.base(), exe);
@@ -46,7 +55,16 @@ pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool
storage.display(),
title.storage_bytes >> 20
);
// The console's fixed drives: the package as `G:`, temporary files `T:`.
victory_hle::modules::files::mount_at('G', title_dir);
let temp = cfg.data_subdir(&format!("{:08X}/temp", title.id))?;
victory_hle::modules::files::mount_at('T', &temp);
victory_hle::runtime::set_title(victory_hle::runtime::Title { storage, ..title });
victory_hle::console::set(match console {
Console::SeriesX => victory_hle::console::Console::SeriesX,
Console::SeriesS => victory_hle::console::Console::SeriesS,
});
println!("console {}", victory_hle::console::current().name());
let dlls = victory_loader::load_title_dlls(image.info(), title_dir, &images, &wanted)?;
for (name, dll) in &dlls {
println!("title dll {name} at {:#x}", dll.base());
@@ -83,12 +101,17 @@ pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool
return Ok(());
}
victory_loader::report_crashes();
victory_loader::log_crashes_to(temp.with_file_name("crashes.log"));
victory_hle::runtime::use_console_timers();
#[cfg(feature = "diagnostics")]
diagnostics(&image, &cfg);
let late = LateDlls {
host: resolver.host.clone(),
title_dir: title_dir.to_owned(),
cache_dir: images,
policy,
mapped: std::sync::Mutex::new(dlls.clone()),
lock: LoaderLock::default(),
};
victory_hle::runtime::set_title_dll_loader(Box::new(move |file| {
late.load(file, show).map_err(|e| format!("{e:#}"))
@@ -102,6 +125,60 @@ pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool
Ok(())
}
/// The debugging aids (README): scheduled stack dumps, watched values and
/// memory saved on a crash.
#[cfg(all(windows, feature = "diagnostics"))]
fn diagnostics(image: &victory_loader::LoadedImage, cfg: &victory_core::Config) {
victory_loader::dump_stacks_on_schedule();
victory_hle::modules::audio::capture::start();
watch(image.base(), image.info().size_of_image as usize);
// Debugging aid: `VICTORY_CRASH_SAVE=<rva>:<len>,...` (hex) writes those
// title ranges to `crash-<rva>.bin` in the cache dir on a crash.
let size = image.info().size_of_image as usize;
let ranges = std::env::var("VICTORY_CRASH_SAVE").unwrap_or_default();
let hex = |s: &str| usize::from_str_radix(s.trim().trim_start_matches("0x"), 16).ok();
victory_loader::save_on_crash(
ranges
.split(',')
.filter_map(|r| r.split_once(':'))
.filter_map(|(rva, len)| Some((hex(rva)?, hex(len)?)))
.filter(|&(rva, len)| rva.checked_add(len).is_some_and(|end| end <= size))
.map(|(rva, len)| {
let file = cfg.cache_dir.join(format!("crash-{rva:x}.bin"));
(image.base() + rva, len, file)
})
.collect(),
);
}
/// Debugging aid: `VICTORY_WATCH=<rva>,...` (hex) logs the u32 at each
/// title+rva whenever it changes, polled every 5 ms (an engine's state, say).
#[cfg(all(windows, feature = "diagnostics"))]
fn watch(base: usize, size: usize) {
let Ok(list) = std::env::var("VICTORY_WATCH") else {
return;
};
let rvas: Vec<usize> = list
.split(',')
.filter_map(|r| usize::from_str_radix(r.trim().trim_start_matches("0x"), 16).ok())
.filter(|&rva| rva + 4 <= size)
.collect();
std::thread::spawn(move || {
let mut seen = vec![None; rvas.len()];
loop {
for (&rva, seen) in rvas.iter().zip(&mut seen) {
// SAFETY: four bytes inside the mapped image, checked above.
let value = unsafe { ((base + rva) as *const u32).read_volatile() };
if *seen != Some(value) {
eprintln!("VIctory: title+{rva:#x} = {value:#x}");
*seen = Some(value);
}
}
std::thread::sleep(std::time::Duration::from_millis(5));
}
});
}
/// DLLs the host or our runtime provide are never taken from the title.
#[cfg(windows)]
fn title_dll(host: &victory_hle::HostPolicy, dll: &str) -> bool {
@@ -118,23 +195,36 @@ struct LateDlls {
policy: victory_loader::UnimplementedPolicy,
/// Every title DLL mapped so far, to bind new ones against.
mapped: std::sync::Mutex<Vec<(String, victory_loader::LoadedImage)>>,
lock: LoaderLock,
}
#[cfg(windows)]
impl LateDlls {
/// Maps `file` and the title DLLs it needs, binds them and runs their
/// `DllMain` on the calling thread, as the Windows loader would.
/// Every `LoadLibrary` of the title comes here first. Returns a title
/// image called `file`, mapping it and the title DLLs it needs first,
/// binding them and running their `DllMain` on the calling thread, as
/// the Windows loader would; `None` if `file` is no title image.
fn load(
&self,
file: &str,
show: impl Fn(&str, victory_loader::BindReport),
) -> Result<Option<usize>> {
use victory_hle::runtime::{image_named, set_image_path};
// shortcut: not reentrant, so a DllMain that loads another new title
// DLL deadlocks; use a reentrant lock if a title does that.
use victory_hle::runtime::{forget_image, image_named, set_image_path};
// Waits while another thread initialises a DLL; a `DllMain` that
// loads another DLL re-enters.
self.lock.hold(|| {
if let Some(base) = image_named(file) {
return Ok(Some(base));
}
let new = {
let mut mapped = self.mapped.lock().unwrap_or_else(|e| e.into_inner());
let wanted = |dll: &str| title_dll(&self.host, dll) && image_named(dll).is_none();
let new = victory_loader::load_title_dll(file, &self.title_dir, &self.cache_dir, &wanted)?;
let new = victory_loader::load_title_dll(
file,
&self.title_dir,
&self.cache_dir,
&wanted,
)?;
let hle = victory_hle::HleResolver::new(self.host.clone());
let old = victory_loader::WithTitleDlls {
inner: &hle,
@@ -152,17 +242,97 @@ impl LateDlls {
show(name, dll.bind_imports(&resolver, self.policy)?);
set_image_path(dll.base(), &self.title_dir.join(name));
}
for (name, dll) in &new {
// Visible before their `DllMain`s run, which may load more.
mapped.extend(new.iter().cloned());
new
};
let failed = new.iter().enumerate().find_map(|(i, (name, dll))| {
// SAFETY: bound above, dependencies attached first.
unsafe { dll.attach() }.with_context(|| format!("attaching {name}"))?;
let attached = unsafe { dll.attach() };
attached
.err()
.map(|e| (i, e.context(format!("attaching {name}"))))
});
let Some((i, error)) = failed else {
return Ok(new.last().map(|(_, dll)| dll.base()));
};
// As `LoadLibrary` does when a `DllMain` fails: detach what this
// load attached (the failed one too) and unmap all of it.
let bases: Vec<_> = new.iter().map(|(_, d)| d.base()).collect();
self.mapped
.lock()
.unwrap_or_else(|e| e.into_inner())
.retain(|(_, d)| !bases.contains(&d.base()));
for (_, done) in new[..=i].iter().rev() {
// SAFETY: attached (or failing to) on this thread just now.
unsafe { done.detach() };
}
let base = new.last().map(|(_, dll)| dll.base());
mapped.extend(new);
Ok(base)
for (_, dll) in new {
forget_image(dll.base());
// SAFETY: detached, and no title code holds it yet.
unsafe { dll.unload() };
}
Err(error)
})
}
}
/// The Windows loader lock's shape: one thread at a time, re-entered by
/// the thread that holds it.
#[cfg(windows)]
#[derive(Default)]
struct LoaderLock {
owner: std::sync::Mutex<(Option<std::thread::ThreadId>, usize)>,
free: std::sync::Condvar,
}
#[cfg(windows)]
impl LoaderLock {
fn hold<T>(&self, f: impl FnOnce() -> T) -> T {
let me = std::thread::current().id();
let lock = || self.owner.lock().unwrap_or_else(|e| e.into_inner());
{
let mut owner = lock();
while owner.0.is_some_and(|o| o != me) {
owner = self.free.wait(owner).unwrap_or_else(|e| e.into_inner());
}
*owner = (Some(me), owner.1 + 1);
}
let result = f();
let mut owner = lock();
owner.1 -= 1;
if owner.1 == 0 {
owner.0 = None;
self.free.notify_one();
}
result
}
}
#[cfg(all(test, windows))]
mod tests {
use std::sync::{Arc, Mutex};
#[test]
fn loader_lock_is_reentrant_and_exclusive() {
let lock = Arc::new(super::LoaderLock::default());
assert_eq!(lock.hold(|| lock.hold(|| 7)), 7);
let order = Arc::new(Mutex::new(Vec::new()));
let other = lock.hold(|| {
let (theirs, their_order) = (lock.clone(), order.clone());
let other = std::thread::spawn(move || {
theirs.hold(|| their_order.lock().unwrap().push(2));
});
std::thread::sleep(std::time::Duration::from_millis(50));
order.lock().unwrap().push(1);
other
});
other.join().unwrap();
assert_eq!(*order.lock().unwrap(), [1, 2]);
}
}
#[cfg(not(windows))]
pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool) -> Result<()> {
pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool, _: Console) -> Result<()> {
anyhow::bail!("running titles requires Windows")
}
+11 -5
View File
@@ -35,18 +35,21 @@ impl Source<'_> {
}
}
/// The records of an SGD5 file, or else every container found by its magic.
/// The packed records of SGD5 data, and every container stored as is (the
/// executable keeps some records uncompressed), found by its magic.
pub(crate) fn sources(data: &[u8]) -> Vec<Source<'_>> {
let mut out: Vec<Source<'_>> = Vec::new();
if sgd5::is_sgd5(data) {
return sgd5::records(data).map(Source::Packed).collect();
out.extend(sgd5::records(data).map(Source::Packed));
}
memchr::memmem::find_iter(data, b"DXBC")
let raw = memchr::memmem::find_iter(data, b"DXBC")
.filter(|&offset| Container::parse(&data[offset..]).is_ok())
.map(|offset| Source::Raw {
offset,
data: &data[offset..],
})
.collect()
});
out.extend(raw);
out
}
#[derive(Default)]
@@ -119,6 +122,9 @@ pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> {
*t.unnamed.entry(key).or_default() += 1;
}
if disasm {
listing
.extend(n.layout.iter().map(|p| format!(" {p:?}")));
listing.extend(n.used.iter().map(|u| format!(" {u:?}")));
listing.extend(
insts.iter().map(|i| format_instruction(i, n.wave64)),
);
+477 -13
View File
@@ -7,8 +7,13 @@ use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use anyhow::Result;
use victory_shader::emit::host::{self, Host};
use victory_shader::emit::{self, validator::Validator};
use victory_shader::structure::{self, Atom, LaneExit};
use victory_shader::{Container, FourCC, ShaderError, ir, native_programs};
use victory_shader::{
Container, FourCC, HwStage, NativeProgram, RootType, ShaderError, ir, native_programs,
};
use victory_shader::{io, resource};
use crate::shader::{MAX_FILE, Source, sources};
@@ -26,12 +31,59 @@ struct Tally {
opaque: usize,
lane_branches: usize,
uniform_branches: usize,
tracked: usize,
loaded: usize,
built: usize,
constant: usize,
/// Descriptors and scalar accesses with a computed address term.
dynamic: usize,
scalar: usize,
used: usize,
/// Used-resource entries whose root parameter no descriptor traces
/// to, by resource and root type.
untraced_used: BTreeMap<String, usize>,
/// Root parameters descriptors trace to that no used entry names.
unlisted: usize,
/// Vertex and pixel programs, and those whose I/O was raised.
io_programs: usize,
io_raised: usize,
interpolated: usize,
vertex_values: usize,
/// Exports by target kind.
exports: BTreeMap<&'static str, usize>,
/// Exports still packed as f16 pairs after the export patch.
compressed: usize,
/// Vertex and pixel programs every earlier stage handled, and how far
/// emission got with them.
emit_programs: usize,
emitted: usize,
validated: usize,
pipelines: usize,
/// The same for compute programs.
cs_programs: usize,
cs_emitted: usize,
cs_validated: usize,
cs_pipelines: usize,
/// The same for mesh programs.
ms_programs: usize,
ms_emitted: usize,
ms_validated: usize,
ms_pipelines: usize,
/// Reason → programs stopped by it, and the first one.
failed: BTreeMap<String, (usize, String)>,
/// With `--list`: one line per program and outcome.
list: bool,
lines: Vec<String>,
}
impl Tally {
fn fail(&mut self, reason: String, example: impl FnOnce() -> String) {
if self.list {
let e = example();
self.lines.push(format!("{e} {reason}"));
self.failed.entry(reason).or_insert((0, e)).0 += 1;
return;
}
self.failed
.entry(reason)
.or_insert_with(|| (0, example()))
@@ -50,15 +102,85 @@ impl Tally {
self.opaque += other.opaque;
self.lane_branches += other.lane_branches;
self.uniform_branches += other.uniform_branches;
self.tracked += other.tracked;
self.loaded += other.loaded;
self.built += other.built;
self.constant += other.constant;
self.dynamic += other.dynamic;
self.scalar += other.scalar;
self.used += other.used;
for (k, n) in other.untraced_used {
*self.untraced_used.entry(k).or_default() += n;
}
self.unlisted += other.unlisted;
self.io_programs += other.io_programs;
self.io_raised += other.io_raised;
self.interpolated += other.interpolated;
self.vertex_values += other.vertex_values;
self.compressed += other.compressed;
self.emit_programs += other.emit_programs;
self.emitted += other.emitted;
self.validated += other.validated;
self.pipelines += other.pipelines;
self.cs_programs += other.cs_programs;
self.cs_emitted += other.cs_emitted;
self.cs_validated += other.cs_validated;
self.cs_pipelines += other.cs_pipelines;
self.ms_programs += other.ms_programs;
self.ms_emitted += other.ms_emitted;
self.ms_validated += other.ms_validated;
self.ms_pipelines += other.ms_pipelines;
for (k, n) in other.exports {
*self.exports.entry(k).or_default() += n;
}
self.lines.extend(other.lines);
for (reason, (n, example)) in other.failed {
self.failed.entry(reason).or_insert((0, example)).0 += n;
}
}
}
pub fn run(paths: Vec<PathBuf>) -> Result<()> {
/// Emitted shaders by label, shared between threads.
type Kept = std::sync::Arc<Mutex<Vec<(String, emit::HostShader)>>>;
/// The optional checks after emission, one set per thread.
struct Checks {
/// Shaders named in `VICTORY_PAIRS` (`vs+ps,...`, label substrings),
/// kept to build those pipelines after the walk.
keep: Option<Kept>,
validator: Option<Validator>,
host: Option<(Host, emit::HostShader)>,
}
pub fn run(
paths: Vec<PathBuf>,
validate: bool,
pipelines: bool,
list: bool,
jobs: Option<usize>,
) -> Result<()> {
let paths = crate::default_paths(paths)?;
let threads = std::thread::available_parallelism().map_or(4, |n| n.get());
let dll = validate.then(Validator::default_path).flatten();
if validate {
Validator::load(dll.as_deref()).map_err(anyhow::Error::msg)?;
println!(
"validator {}",
dll.as_ref()
.map_or("dxil.dll".into(), |p| p.display().to_string())
);
}
if pipelines {
Host::new(false).map_err(anyhow::Error::msg)?;
}
let pairs: Vec<(String, String)> = std::env::var("VICTORY_PAIRS")
.unwrap_or_default()
.split(',')
.filter_map(|p| p.split_once('+'))
.map(|(v, p)| (v.trim().to_owned(), p.trim().to_owned()))
.collect();
let kept = std::sync::Arc::new(Mutex::new(Vec::new()));
let threads =
jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get()));
let seen = Mutex::new(HashSet::new());
let total = Mutex::new(Tally::default());
for root in &paths {
@@ -77,9 +199,21 @@ pub fn run(paths: Vec<PathBuf>) -> Result<()> {
std::thread::scope(|s| {
for _ in 0..threads.min(jobs.len()) {
s.spawn(|| {
let mut t = Tally::default();
let mut t = Tally {
list,
..Tally::default()
};
let mut checks = Checks {
keep: (!pairs.is_empty()).then(|| kept.clone()),
validator: validate
.then(|| Validator::load(dll.as_deref()).ok())
.flatten(),
host: pipelines
.then(|| Host::new(false).ok().map(|h| (h, host::stub_ps())))
.flatten(),
};
while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) {
translate(job, entry.path(), &seen, &mut t);
translate(job, entry.path(), &seen, &mut t, &mut checks);
}
lock(&total).merge(t);
});
@@ -107,6 +241,58 @@ pub fn run(paths: Vec<PathBuf>) -> Result<()> {
t.lane_branches,
t.uniform_branches
);
println!(
"resources {} of {} tracked (descriptors {} loaded, {} built, {} constant; \
{} scalar accesses; {} with a computed term)",
t.tracked, t.translated, t.loaded, t.built, t.constant, t.scalar, t.dynamic
);
println!(
" used-resource entries {}: {} not traced {:?}; {} traced parameters not listed",
t.used,
t.untraced_used.values().sum::<usize>(),
t.untraced_used,
t.unlisted
);
println!(
"I/O {} of {} vertex and pixel programs raised ({} interpolations, \
{} vertex values; exports {:?}, {} still f16 pairs)",
t.io_raised, t.io_programs, t.interpolated, t.vertex_values, t.exports, t.compressed
);
println!(
"DXIL {} emitted of {} vertex and pixel programs; {} validated, {} pipelines",
t.emitted, t.emit_programs, t.validated, t.pipelines
);
println!(
" {} emitted of {} compute programs; {} validated, {} pipelines",
t.cs_emitted, t.cs_programs, t.cs_validated, t.cs_pipelines
);
println!(
" {} emitted of {} mesh programs; {} validated, {} pipelines",
t.ms_emitted, t.ms_programs, t.ms_validated, t.ms_pipelines
);
if !pairs.is_empty() {
let host = Host::new(false).map_err(anyhow::Error::msg)?;
let kept = lock(&kept);
let find = |name: &str| kept.iter().find(|(l, _)| l.contains(name));
for (v, p) in &pairs {
let made = match (find(v), find(p)) {
(Some((_, vs)), Some((_, ps))) => if vs.stage == HwStage::Ms {
host.mesh_pipeline(vs, ps)
} else {
host.pipeline(vs, ps)
}
.map(|_| "pipeline created".to_owned())
.unwrap_or_else(|e| e),
_ => "not emitted".to_owned(),
};
println!("pair {v} + {p}: {made}");
}
}
let mut lines = t.lines;
lines.sort();
for l in lines {
println!("{l}");
}
let mut failed: Vec<_> = t.failed.into_iter().collect();
failed.sort_by_key(|(_, (n, _))| std::cmp::Reverse(*n));
for (reason, (n, example)) in failed {
@@ -115,16 +301,22 @@ pub fn run(paths: Vec<PathBuf>) -> Result<()> {
Ok(())
}
fn translate(source: &Source, path: &Path, seen: &Mutex<HashSet<blake3::Hash>>, t: &mut Tally) {
fn translate(
source: &Source,
path: &Path,
seen: &Mutex<HashSet<blake3::Hash>>,
t: &mut Tally,
checks: &mut Checks,
) {
let example = || format!("{}{}", path.display(), source.label());
let Some(bytes) = source.bytes() else {
return t.fail("corrupt record".into(), example);
};
t.containers += 1;
let Some(dxil) = Container::parse(&bytes)
.ok()
.and_then(|c| c.part(FourCC::DXIL).map(|p| p.data))
else {
let Ok(container) = Container::parse(&bytes) else {
return t.fail("no DXIL part (SM5 or older)".into(), example);
};
let Some(dxil) = container.part(FourCC::DXIL).map(|p| p.data) else {
return t.fail("no DXIL part (SM5 or older)".into(), example);
};
if !lock(seen).insert(blake3::hash(dxil)) {
@@ -137,12 +329,50 @@ fn translate(source: &Source, path: &Path, seen: &Mutex<HashSet<blake3::Hash>>,
};
for p in programs {
t.programs += 1;
match ir::build(&p.code, p.wave64, p.vgprs) {
match ir::build(&p.patched_code(), p.wave64, p.vgprs) {
Ok(program) => {
t.translated += 1;
t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::<usize>();
match structure::structure(&program) {
Ok(s) => tally_structured(&program, &s, t),
let res = match resource::track(&program, &p.layout, p.stage) {
Ok(r) => {
tally_resources(&p, &r, t);
Some(r)
}
Err(ShaderError::Unsupported { offset, what }) => {
t.fail(format!("resources: {what}"), || {
format!("{} {:?} at {offset:#x}", example(), p.stage)
});
None
}
Err(e) => {
t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage));
None
}
};
let graphics = matches!(p.stage, HwStage::Vs | HwStage::Ps);
let compute = p.stage == HwStage::Cs;
let mut raised = None;
if graphics || compute || p.stage == HwStage::Ms {
t.io_programs += usize::from(graphics);
match io::raise(&program, &p) {
Ok(r) => {
if graphics {
tally_io(&r, t);
}
raised = Some(r);
}
Err(ShaderError::Unsupported { offset, what }) => t
.fail(format!("I/O: {what}"), || {
format!("{} {:?} at {offset:#x}", example(), p.stage)
}),
Err(e) => t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage)),
}
}
let structured = match structure::structure(&program) {
Ok(s) => {
tally_structured(&program, &s, t);
Some(s)
}
Err(e) => {
let reason = match e {
ShaderError::Unsupported { what, .. } => format!("structure: {what}"),
@@ -150,6 +380,22 @@ fn translate(source: &Source, path: &Path, seen: &Mutex<HashSet<blake3::Hash>>,
e => e.to_string(),
};
t.fail(reason, || format!("{} {:?}", example(), p.stage));
None
}
};
if let (Some(r), Some(i), Some(s)) = (res, raised, structured) {
let label = || format!("{} {:?}", example(), p.stage);
*counter(t, p.stage, 0) += 1;
match emit::emit(&container, &p, &program, &s, &i, &r) {
Ok(shader) => {
*counter(t, p.stage, 1) += 1;
check(shader, t, checks, label);
}
Err(ShaderError::Unsupported { offset, what }) => t
.fail(format!("emit: {what}"), || {
format!("{} at {offset:#x}", label())
}),
Err(e) => t.fail(format!("emit: {e}"), label),
}
}
}
@@ -164,6 +410,224 @@ fn translate(source: &Source, path: &Path, seen: &Mutex<HashSet<blake3::Hash>>,
}
}
/// Validates an emitted shader if asked to.
fn check(
mut shader: emit::HostShader,
t: &mut Tally,
checks: &mut Checks,
label: impl Fn() -> String,
) {
if let Some(keep) = &checks.keep {
lock(keep).push((label(), shader.clone()));
}
// `VICTORY_EMIT_DUMP` with `--list`: every emitted shader as a file.
if t.list
&& let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP")
{
let name: String = label()
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
.collect();
let _ = std::fs::write(
format!("{dir}/{}.dxil", &name[name.len().saturating_sub(100)..]),
&shader.dxil,
);
}
if let Some((h, stub_ps)) = &checks.host {
let made = match shader.stage {
HwStage::Vs => h.pipeline(&shader, stub_ps).map(drop),
HwStage::Cs => h.compute_pipeline(&shader).map(drop),
HwStage::Ms => h.mesh_pipeline(&shader, stub_ps).map(drop),
_ => host::stub_vs(&shader).and_then(|vs| h.pipeline(&vs, &shader).map(drop)),
};
match made {
Ok(()) => {
*counter(t, shader.stage, 3) += 1;
if t.list {
t.lines.push(format!("{} pipeline created", label()));
}
}
Err(e) => t.fail(format!("pipeline: {e}"), &label),
}
}
let Some(v) = checks.validator.as_mut() else {
return;
};
match v.validate(&mut shader.dxil) {
Ok(()) => {
*counter(t, shader.stage, 2) += 1;
if t.list {
t.lines.push(format!("{} validated", label()));
}
}
Err(text) => {
let first = text
.lines()
.find(|l| l.contains("error"))
.unwrap_or(text.lines().next().unwrap_or(""))
.to_owned();
if let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP") {
let n = t
.failed
.get(&format!("validator: {first}"))
.map_or(0, |f| f.0);
if n < 3 {
let name = format!(
"{dir}/{}_{n}",
first
.chars()
.filter(char::is_ascii_alphanumeric)
.take(40)
.collect::<String>()
);
let _ = std::fs::write(format!("{name}.dxil"), &shader.dxil);
let _ = std::fs::write(format!("{name}.txt"), format!("{}\n{text}", label()));
}
}
t.fail(format!("validator: {first}"), label);
}
}
}
/// Emission counts of `stage`'s kind: 0 programs, 1 emitted, 2 validated,
/// 3 pipelines.
fn counter(t: &mut Tally, stage: HwStage, k: usize) -> &mut usize {
let [a, b, c, d] = match stage {
HwStage::Cs => [
&mut t.cs_programs,
&mut t.cs_emitted,
&mut t.cs_validated,
&mut t.cs_pipelines,
],
HwStage::Ms => [
&mut t.ms_programs,
&mut t.ms_emitted,
&mut t.ms_validated,
&mut t.ms_pipelines,
],
_ => [
&mut t.emit_programs,
&mut t.emitted,
&mut t.validated,
&mut t.pipelines,
],
};
[a, b, c, d].into_iter().nth(k).expect("0 to 3")
}
fn tally_io(r: &io::Io, t: &mut Tally) {
t.io_raised += 1;
for (_, i) in &r.interps {
match i {
io::Interp::Interpolated { .. } => t.interpolated += 1,
io::Interp::Vertex { .. } => t.vertex_values += 1,
}
}
for e in &r.exports {
let kind = match e.target {
io::Target::Color(_) => "color",
io::Target::Depth => "depth",
io::Target::Null => "null",
io::Target::Position(_) => "position",
io::Target::Param { .. } => "param",
io::Target::Unread => "unread param",
io::Target::Primitive => "primitive",
io::Target::PrimitiveParam { .. } => "primitive param",
};
*t.exports.entry(kind).or_default() += 1;
t.compressed += usize::from(e.compressed);
}
}
fn tally_resources(p: &NativeProgram, r: &resource::Resources, t: &mut Tally) {
t.tracked += 1;
t.scalar += r.scalar.len();
t.dynamic += r.scalar.iter().filter(|s| s.1.dynamic.is_some()).count();
let address = |load| r.scalar.iter().find(|s| s.0 == load).map(|s| s.1);
let mut traced = HashSet::new();
for leaf in r.descriptors.iter().flat_map(|d| d.source.leaves()) {
let a = match *leaf {
resource::Source::Loaded { load, .. } => {
t.loaded += 1;
address(load)
}
resource::Source::Built { address, .. } => {
t.built += 1;
t.dynamic += usize::from(address.dynamic.is_some());
Some(address)
}
resource::Source::Constant(_) => {
t.constant += 1;
None
}
resource::Source::Phi { .. } => unreachable!("leaves are no phis"),
};
// Heaps hold dynamic resources, which no used entry lists; code
// tables are no root parameter.
if let Some(a) = a
&& a.param != resource::CODE
&& !matches!(
p.layout[a.param].root,
RootType::ResourceHeap | RootType::SamplerHeap
)
{
traced.insert(p.layout[a.param].user_data);
}
}
// Root constants are listed as a CBV, read straight from the SGPRs.
traced.extend(
r.params
.iter()
.map(|&(_, param, _)| &p.layout[param])
.filter(|l| l.root == RootType::Constants)
.map(|l| l.user_data),
);
let listed: HashSet<u8> = p.used.iter().map(|u| u.user_data).collect();
t.used += p.used.len();
// Immediate samplers are literals in the code: the distinct sampler
// values (decoded) are matched against the listed entries, which do not
// say which value is whose.
let mut values: Vec<emit::StaticSampler> = Vec::new();
for d in r
.descriptors
.iter()
.filter(|d| d.role == resource::Role::Sampler)
{
for leaf in d.source.leaves() {
if let resource::Source::Constant(words) = leaf
&& let Ok(w) = <[u32; 4]>::try_from(&words[..words.len().min(4)])
{
let s = emit::StaticSampler::from_words(w);
if !values.contains(&s) {
values.push(s);
}
}
}
}
// Engines often declare equal samplers at several registers, so equal
// values may stand for several entries, but never more values than
// entries.
let immediate = p
.used
.iter()
.filter(|u| u.root == RootType::ImmediateSampler)
.count();
let samplers_match = !values.is_empty() && values.len() <= immediate;
let matched = |u: &&victory_shader::UsedResource| {
if u.root == RootType::ImmediateSampler {
samplers_match
} else {
traced.contains(&u.user_data)
}
};
for u in p.used.iter().filter(|u| !matched(u)) {
*t.untraced_used
.entry(format!("{:?} via {:?}", u.kind, u.root))
.or_default() += 1;
}
t.unlisted += traced.difference(&listed).count();
}
fn tally_structured(program: &ir::Program, s: &structure::Structured, t: &mut Tally) {
t.structured += 1;
for (block, guards) in program.blocks.iter().zip(&s.guards) {
+4
View File
@@ -17,5 +17,9 @@ tracing-subscriber.workspace = true
[dev-dependencies]
tempfile.workspace = true
[features]
# Lets `VICTORY_LOG` enable debug and trace output.
diagnostics = []
[lints]
workspace = true
+20 -4
View File
@@ -1,9 +1,21 @@
//! One tracing setup for every binary.
//!
//! Filter with `VICTORY_LOG` (falls back to `RUST_LOG`), e.g.
//! `VICTORY_LOG=victory_loader=trace,info`.
//! `VICTORY_LOG=victory_loader=trace,info`. Debug and trace output exist
//! only in builds with the `diagnostics` feature; a plain release build
//! logs info and above whatever the filter asks for.
use tracing_subscriber::EnvFilter;
use tracing_subscriber::filter::LevelFilter;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
/// The most verbose level this build can log.
const CAP: LevelFilter = if cfg!(feature = "diagnostics") {
LevelFilter::TRACE
} else {
LevelFilter::INFO
};
pub fn init(default_level: &str) {
let filter = std::env::var("VICTORY_LOG")
@@ -11,9 +23,13 @@ pub fn init(default_level: &str) {
.ok()
.and_then(|v| EnvFilter::try_new(v).ok())
.unwrap_or_else(|| EnvFilter::new(default_level));
let _ = tracing_subscriber::fmt()
.with_env_filter(filter)
let _ = tracing_subscriber::registry()
.with(CAP)
.with(filter)
.with(
tracing_subscriber::fmt::layer()
.with_target(true)
.with_writer(std::io::stderr)
.with_writer(std::io::stderr),
)
.try_init();
}
Binary file not shown.
File diff suppressed because it is too large. Load diff
+8 -4
View File
@@ -1,6 +1,10 @@
//! Platform-level data formats, shared by every Xbox Series title.
//!
//! Planned modules, each pure (bytes in, bytes out, no I/O): texture
//! layouts (RDNA2 swizzle modes to linear), BCPack textures, audio codecs
//! (XMA2, Opus), and the zlib streams used by hardware decompression.
//! Which come first depends on what Grand Theft Auto VI's assets contain.
//! Each module is pure (bytes in, bytes out, no I/O): [`texture`] (the
//! GPU's tiled texture layouts and copies to and from linear rows). Planned:
//! BCPack textures, audio codecs (XMA2, Opus), and the zlib streams used by
//! hardware decompression.
pub mod bcpack;
pub mod texture;
pub mod xma;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+410
View File
@@ -0,0 +1,410 @@
//! Huffman and level tables of the WMA Pro bitstream that XMA2 frames use,
//! converted from FFmpeg's `libavcodec/wmaprodata.h` (LGPL-2.1-or-later,
//! used here under GPL-3.0-or-later as that licence allows). Pairs are
//! (symbol, code length) in canonical code order.
pub(super) const CRITICAL_FREQ: [u16; 28] = [
100, 200, 300, 400, 510, 630, 770, 920,
1080, 1270, 1480, 1720, 2000, 2320, 2700, 3150,
3700, 4400, 5300, 6400, 7700, 9500, 12000, 15500,
20675, 28575, 41375, 63875,
];
pub(super) const SCALE: [(u16, u8); 121] = [
(58, 5), (64, 6), (66, 7), (65, 7), (62, 5), (63, 6), (68, 9), (69, 10),
(54, 15), (19, 19), (20, 19), (21, 19), (22, 19), (23, 19), (24, 19), (25, 19),
(26, 19), (27, 19), (28, 19), (29, 19), (30, 19), (31, 19), (32, 19), (33, 19),
(34, 19), (17, 19), (36, 19), (37, 19), (38, 19), (39, 19), (40, 19), (41, 19),
(42, 19), (43, 19), (44, 19), (45, 19), (46, 19), (47, 19), (48, 19), (49, 19),
(50, 19), (51, 19), (52, 19), (15, 19), (16, 19), (14, 19), (13, 19), (12, 19),
(11, 19), (10, 19), (0, 19), (9, 19), (8, 19), (7, 19), (6, 19), (5, 19),
(4, 19), (55, 13), (70, 13), (3, 19), (2, 19), (1, 19), (35, 19), (71, 19),
(72, 19), (73, 19), (74, 19), (75, 19), (76, 19), (77, 19), (78, 19), (79, 19),
(80, 19), (81, 19), (82, 19), (83, 19), (84, 19), (85, 19), (86, 19), (87, 19),
(88, 19), (89, 19), (90, 19), (91, 19), (92, 19), (93, 19), (94, 19), (95, 19),
(96, 19), (97, 19), (98, 19), (99, 19), (100, 19), (101, 19), (102, 19), (103, 19),
(104, 19), (105, 19), (106, 19), (107, 19), (108, 19), (109, 19), (110, 19), (111, 19),
(112, 19), (113, 19), (114, 19), (115, 19), (116, 19), (117, 19), (118, 19), (119, 19),
(120, 19), (18, 18), (53, 16), (56, 11), (57, 8), (67, 7), (61, 3), (59, 2),
(60, 1),
];
pub(super) const SCALE_RL: [(u16, u8); 120] = [
(103, 7), (80, 11), (60, 11), (18, 10), (56, 10), (21, 12), (90, 12), (58, 11),
(27, 11), (69, 12), (84, 15), (48, 15), (86, 14), (47, 13), (19, 10), (32, 9),
(78, 6), (5, 5), (28, 4), (53, 5), (9, 7), (31, 8), (38, 8), (10, 7),
(88, 11), (25, 12), (105, 12), (118, 11), (23, 12), (82, 14), (98, 16), (110, 16),
(108, 15), (93, 13), (68, 10), (72, 12), (97, 12), (81, 12), (42, 12), (64, 8),
(4, 4), (1, 2), (7, 6), (14, 7), (0, 9), (55, 9), (61, 9), (117, 10),
(24, 12), (44, 12), (67, 12), (70, 16), (99, 18), (96, 21), (95, 21), (2, 21),
(77, 21), (52, 21), (111, 21), (102, 20), (101, 17), (46, 15), (73, 15), (109, 15),
(51, 14), (92, 14), (30, 7), (11, 7), (66, 7), (15, 8), (16, 8), (116, 9),
(65, 9), (57, 10), (59, 10), (115, 9), (12, 7), (35, 9), (17, 9), (41, 9),
(20, 11), (91, 11), (26, 12), (75, 15), (45, 15), (107, 14), (83, 14), (100, 15),
(89, 15), (43, 11), (62, 9), (37, 9), (104, 8), (6, 5), (39, 8), (40, 9),
(34, 9), (79, 7), (8, 6), (63, 6), (87, 12), (94, 14), (49, 14), (50, 13),
(22, 11), (119, 10), (33, 9), (36, 9), (113, 11), (106, 12), (112, 13), (71, 15),
(85, 15), (74, 14), (76, 10), (114, 7), (29, 5), (54, 6), (13, 6), (3, 2),
];
pub(super) const SCALE_RL_RUN: [u8; 120] = [
0, 0, 0, 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, 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, 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, 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, 0,
1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 0, 1, 0, 1, 0, 1,
];
pub(super) const SCALE_RL_LEVEL: [u8; 120] = [
0, 0, 1, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 6,
6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 7, 7, 8, 8, 9, 9,
];
pub(super) const COEF0_LENS: [u8; 272] = [
2, 9, 14, 14, 13, 12, 13, 14,
15, 15, 12, 10, 10, 10, 13, 14,
15, 15, 12, 11, 13, 14, 14, 13,
15, 15, 14, 12, 12, 8, 10, 10,
15, 15, 14, 13, 14, 14, 13, 15,
20, 20, 19, 21, 21, 20, 19, 17,
17, 18, 18, 15, 15, 13, 12, 14,
15, 15, 14, 15, 15, 12, 11, 6,
7, 8, 9, 13, 13, 13, 14, 14,
11, 10, 7, 8, 14, 14, 14, 14,
12, 13, 13, 12, 12, 12, 11, 9,
13, 14, 14, 12, 11, 11, 11, 9,
8, 7, 14, 15, 15, 14, 14, 12,
13, 15, 16, 17, 17, 14, 12, 12,
12, 15, 15, 14, 14, 14, 13, 13,
9, 9, 11, 11, 10, 7, 6, 13,
15, 15, 14, 14, 14, 13, 14, 15,
15, 13, 14, 14, 14, 14, 10, 9,
10, 10, 11, 11, 10, 8, 9, 13,
14, 14, 12, 11, 14, 15, 15, 13,
12, 14, 14, 14, 14, 13, 14, 14,
3, 5, 8, 10, 10, 15, 15, 14,
14, 16, 16, 15, 12, 11, 11, 11,
7, 8, 8, 9, 12, 13, 13, 12,
14, 15, 15, 13, 10, 11, 11, 13,
14, 14, 13, 14, 14, 11, 10, 13,
15, 15, 14, 12, 11, 4, 6, 6,
8, 12, 12, 12, 13, 13, 12, 13,
13, 14, 14, 13, 13, 13, 9, 7,
9, 11, 14, 14, 13, 14, 14, 13,
10, 8, 7, 5, 9, 12, 13, 14,
15, 15, 12, 12, 10, 14, 14, 13,
12, 13, 14, 14, 12, 13, 13, 12,
12, 12, 9, 7, 6, 3, 4, 4,
];
pub(super) const COEF0_SYMS: [u16; 272] = [
2, 25, 111, 94, 69, 58, 87, 93,
136, 135, 59, 37, 34, 36, 82, 182,
120, 138, 195, 45, 168, 216, 178, 86,
140, 219, 186, 162, 239, 18, 156, 35,
127, 236, 109, 85, 180, 253, 88, 147,
268, 264, 256, 266, 270, 262, 260, 248,
246, 252, 258, 137, 189, 230, 64, 179,
146, 208, 101, 118, 238, 163, 46, 9,
153, 0, 26, 247, 169, 76, 202, 131,
194, 38, 13, 19, 132, 106, 191, 97,
65, 198, 77, 62, 66, 164, 48, 27,
81, 183, 102, 60, 47, 49, 159, 227,
20, 14, 112, 263, 144, 217, 104, 63,
79, 209, 269, 250, 254, 203, 241, 196,
61, 220, 148, 124, 185, 100, 80, 78,
193, 28, 50, 235, 41, 1, 10, 171,
226, 150, 103, 114, 115, 170, 105, 211,
149, 249, 108, 188, 107, 255, 231, 155,
42, 40, 55, 160, 39, 21, 29, 215,
234, 184, 228, 51, 116, 142, 145, 172,
165, 181, 130, 113, 117, 89, 128, 204,
3, 7, 154, 157, 43, 141, 265, 133,
225, 271, 244, 221, 74, 54, 56, 52,
15, 222, 22, 30, 83, 199, 173, 73,
123, 210, 143, 175, 44, 53, 237, 174,
139, 134, 110, 218, 129, 161, 213, 177,
267, 151, 125, 67, 223, 5, 11, 192,
23, 214, 243, 166, 200, 176, 68, 224,
187, 257, 261, 232, 96, 251, 31, 16,
32, 57, 207, 121, 91, 126, 119, 99,
158, 24, 212, 8, 33, 70, 92, 205,
240, 242, 75, 197, 233, 259, 190, 98,
71, 201, 122, 206, 72, 90, 95, 84,
167, 245, 229, 17, 12, 4, 152, 6,
];
pub(super) const COEF1: [(u16, u8); 244] = [
(2, 2), (3, 3), (102, 3), (4, 4), (148, 6), (134, 9), (171, 10), (18, 10),
(11, 8), (159, 8), (14, 9), (156, 14), (235, 15), (61, 15), (38, 13), (153, 13),
(48, 14), (49, 14), (23, 11), (203, 13), (208, 19), (204, 19), (129, 18), (94, 17),
(87, 16), (62, 15), (174, 15), (147, 15), (29, 12), (191, 12), (64, 15), (65, 15),
(146, 14), (164, 13), (142, 5), (132, 4), (103, 5), (154, 7), (165, 9), (181, 11),
(109, 12), (30, 12), (86, 16), (92, 16), (239, 15), (138, 14), (39, 13), (50, 14),
(115, 15), (238, 21), (228, 21), (236, 21), (222, 21), (216, 20), (226, 20), (196, 18),
(192, 17), (120, 16), (221, 14), (51, 14), (24, 11), (143, 8), (7, 6), (9, 7),
(152, 10), (136, 12), (160, 12), (241, 15), (66, 15), (168, 14), (219, 14), (113, 14),
(193, 12), (19, 10), (173, 10), (105, 8), (149, 9), (15, 9), (205, 13), (207, 13),
(125, 17), (190, 17), (182, 16), (68, 15), (70, 15), (67, 15), (137, 13), (31, 12),
(223, 14), (116, 15), (210, 19), (220, 19), (198, 18), (126, 17), (88, 16), (41, 13),
(25, 11), (40, 13), (73, 15), (243, 15), (53, 14), (195, 12), (183, 11), (225, 14),
(52, 14), (71, 15), (121, 16), (89, 16), (170, 14), (55, 14), (69, 15), (83, 15),
(209, 13), (108, 11), (32, 12), (54, 14), (122, 16), (184, 16), (176, 15), (42, 13),
(12, 8), (161, 8), (6, 5), (167, 9), (106, 9), (20, 10), (145, 12), (111, 13),
(43, 13), (26, 11), (175, 10), (107, 10), (34, 12), (33, 12), (197, 12), (74, 15),
(128, 17), (232, 20), (212, 20), (224, 19), (202, 18), (90, 16), (57, 14), (227, 14),
(97, 16), (93, 16), (140, 15), (185, 11), (27, 11), (16, 9), (158, 11), (211, 13),
(56, 14), (117, 15), (72, 15), (166, 13), (91, 16), (95, 16), (80, 15), (101, 16),
(194, 17), (127, 17), (82, 15), (21, 10), (144, 10), (177, 10), (151, 6), (10, 7),
(157, 7), (8, 6), (5, 4), (13, 8), (0, 9), (213, 13), (46, 13), (199, 12),
(35, 12), (162, 12), (135, 10), (169, 9), (45, 13), (59, 14), (114, 14), (44, 13),
(188, 16), (186, 16), (75, 15), (79, 15), (118, 15), (187, 11), (112, 13), (139, 14),
(178, 15), (81, 15), (110, 12), (28, 11), (163, 8), (133, 6), (104, 6), (17, 9),
(22, 10), (229, 14), (172, 14), (217, 13), (201, 12), (36, 12), (218, 20), (242, 22),
(240, 22), (234, 21), (230, 19), (206, 18), (200, 18), (214, 18), (130, 17), (131, 17),
(141, 15), (84, 15), (76, 15), (215, 13), (58, 14), (231, 14), (233, 14), (180, 15),
(77, 15), (37, 12), (189, 11), (179, 10), (155, 10), (47, 13), (96, 16), (99, 16),
(119, 15), (63, 14), (237, 14), (78, 15), (85, 15), (60, 14), (98, 16), (100, 16),
(124, 16), (123, 16), (150, 11), (1, 7),
];
pub(super) const COEF0_RUN: [u16; 272] = [
0, 0, 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,
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,
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 0, 1, 2, 3,
4, 5, 6, 7, 8, 9, 0, 1,
2, 3, 4, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0,
];
pub(super) const COEF0_LEVEL: [f32; 272] = [
0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0,
2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0,
2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0,
2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0,
2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0,
3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0,
3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0,
3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0,
4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 5.0,
5.0, 5.0, 5.0, 6.0, 6.0, 7.0, 7.0, 8.0,
8.0, 9.0, 9.0, 10.0, 10.0, 11.0, 11.0, 12.0,
12.0, 13.0, 13.0, 14.0, 14.0, 15.0, 15.0, 16.0,
16.0, 17.0, 17.0, 18.0, 18.0, 19.0, 19.0, 20.0,
20.0, 21.0, 21.0, 22.0, 22.0, 23.0, 23.0, 24.0,
24.0, 25.0, 25.0, 26.0, 26.0, 27.0, 27.0, 28.0,
];
pub(super) const COEF1_RUN: [u16; 244] = [
0, 0, 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, 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, 0, 1, 2, 3,
4, 5, 6, 7, 8, 9, 0, 1,
2, 3, 4, 5, 0, 1, 2, 0,
1, 2, 0, 1, 2, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 0, 0,
];
pub(super) const COEF1_LEVEL: [f32; 244] = [
0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0,
2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0,
2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0,
2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0,
2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0,
3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0,
4.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 6.0,
6.0, 6.0, 7.0, 7.0, 7.0, 8.0, 8.0, 9.0,
9.0, 10.0, 10.0, 11.0, 11.0, 12.0, 12.0, 13.0,
13.0, 14.0, 14.0, 15.0, 15.0, 16.0, 16.0, 17.0,
17.0, 18.0, 18.0, 19.0, 19.0, 20.0, 20.0, 21.0,
21.0, 22.0, 22.0, 23.0, 23.0, 24.0, 24.0, 25.0,
25.0, 26.0, 26.0, 27.0, 27.0, 28.0, 28.0, 29.0,
29.0, 30.0, 30.0, 31.0, 31.0, 32.0, 32.0, 33.0,
33.0, 34.0, 34.0, 35.0, 35.0, 36.0, 36.0, 37.0,
37.0, 38.0, 38.0, 39.0, 39.0, 40.0, 40.0, 41.0,
41.0, 42.0, 42.0, 43.0, 43.0, 44.0, 44.0, 45.0,
45.0, 46.0, 46.0, 47.0, 47.0, 48.0, 48.0, 49.0,
49.0, 50.0, 51.0, 52.0,
];
pub(super) const VEC4_LENS: [u8; 127] = [
1, 6, 8, 10, 10, 10, 10, 8,
8, 10, 10, 9, 8, 8, 9, 12,
12, 11, 12, 12, 11, 9, 9, 8,
8, 9, 9, 8, 8, 9, 9, 12,
12, 12, 14, 14, 13, 11, 11, 9,
8, 9, 9, 11, 11, 10, 9, 8,
6, 6, 6, 6, 6, 6, 11, 11,
10, 11, 11, 10, 10, 11, 11, 9,
7, 6, 7, 7, 6, 6, 6, 5,
7, 11, 11, 10, 9, 8, 6, 9,
9, 10, 10, 9, 8, 8, 6, 6,
6, 8, 8, 9, 12, 12, 11, 10,
8, 8, 8, 10, 10, 10, 10, 9,
9, 8, 10, 11, 11, 9, 8, 8,
8, 9, 9, 10, 11, 12, 12, 9,
9, 9, 8, 8, 7, 7, 7,
];
pub(super) const VEC4_SYMS: [u16; 127] = [
0, 4370, 275, 8195, 4146, 12545, 8225, 290,
4625, 515, 20, 8706, 8210, 4355, 4131, 16385,
5121, 8961, 321, 1041, 51, 4641, 546, 4610,
530, 513, 8451, 4385, 4130, 33, 8211, 5,
66, 4161, 1281, 81, 6, 801, 8196, 8481,
8449, 4611, 531, 561, 769, 12290, 8226, 19,
4097, 2, 4369, 274, 4354, 4114, 12291, 16641,
12305, 49, 12321, 260, 4100, 516, 21, 12546,
8466, 4353, 4371, 4626, 257, 18, 17, 1,
4386, 8241, 771, 4865, 8705, 8194, 4098, 12561,
276, 50, 785, 4116, 8209, 4099, 273, 4113,
258, 259, 4609, 35, 1026, 1025, 16401, 305,
34, 529, 289, 770, 12289, 4, 4145, 4356,
12306, 8193, 12801, 261, 16386, 4881, 3, 514,
4129, 545, 306, 36, 4101, 65, 20481, 786,
4401, 4866, 8721, 291, 8450, 8465, 4115,
];
pub(super) const VEC2: [(u16, u8); 137] = [
(19, 5), (165, 10), (211, 11), (46, 11), (75, 10), (177, 11), (12, 11), (86, 8),
(83, 7), (38, 7), (133, 9), (178, 10), (28, 10), (104, 9), (73, 9), (35, 5),
(52, 6), (113, 9), (8, 9), (101, 8), (69, 7), (0, 3), (71, 8), (119, 9),
(91, 10), (179, 10), (114, 8), (166, 10), (10, 10), (44, 10), (145, 10), (66, 6),
(21, 6), (24, 8), (146, 9), (26, 9), (65, 7), (5, 7), (226, 11), (225, 12),
(15, 12), (180, 10), (147, 9), (115, 8), (40, 8), (89, 9), (134, 9), (84, 7),
(54, 7), (42, 9), (60, 10), (31, 11), (193, 11), (181, 10), (76, 10), (148, 9),
(37, 6), (67, 6), (33, 6), (3, 6), (17, 6), (2, 6), (102, 8), (87, 8),
(116, 8), (56, 8), (50, 5), (20, 5), (120, 9), (58, 9), (29, 10), (194, 10),
(135, 9), (97, 8), (7, 8), (105, 9), (13, 11), (241, 12), (16, 12), (45, 10),
(149, 9), (74, 9), (98, 7), (23, 7), (85, 7), (70, 7), (195, 10), (161, 10),
(129, 9), (72, 8), (51, 5), (36, 5), (117, 8), (61, 10), (11, 10), (162, 9),
(1, 7), (4, 6), (49, 6), (68, 6), (9, 9), (27, 9), (130, 8), (39, 7),
(53, 6), (99, 7), (25, 8), (150, 9), (90, 9), (103, 8), (163, 9), (196, 10),
(210, 10), (136, 9), (121, 9), (41, 8), (131, 8), (43, 9), (164, 9), (118, 8),
(88, 8), (81, 7), (6, 7), (55, 7), (59, 9), (30, 10), (209, 11), (14, 11),
(151, 9), (106, 9), (82, 6), (22, 6), (100, 7), (132, 8), (57, 8), (18, 4),
(34, 4),
];
pub(super) const VEC1: [(u16, u8); 101] = [
(7, 5), (32, 8), (59, 10), (60, 10), (83, 11), (82, 11), (62, 10), (33, 8),
(45, 9), (61, 10), (84, 11), (85, 11), (1, 6), (13, 5), (19, 6), (25, 7),
(34, 8), (46, 9), (47, 9), (14, 5), (6, 5), (64, 10), (87, 11), (86, 11),
(63, 10), (88, 11), (90, 11), (35, 8), (26, 7), (0, 7), (48, 9), (65, 10),
(66, 10), (36, 8), (15, 5), (20, 6), (91, 11), (89, 11), (67, 10), (49, 9),
(50, 9), (69, 10), (92, 11), (93, 11), (27, 7), (5, 5), (37, 8), (68, 10),
(71, 10), (51, 9), (52, 9), (70, 10), (94, 11), (96, 11), (38, 8), (21, 6),
(16, 5), (4, 5), (28, 7), (53, 9), (95, 11), (97, 11), (73, 10), (39, 8),
(29, 7), (72, 10), (98, 11), (99, 11), (54, 9), (40, 8), (22, 6), (30, 7),
(55, 9), (74, 10), (76, 10), (56, 9), (75, 10), (77, 10), (17, 5), (3, 5),
(23, 6), (41, 8), (57, 9), (78, 10), (79, 10), (31, 7), (10, 4), (9, 4),
(100, 5), (2, 5), (11, 4), (8, 4), (18, 5), (42, 8), (58, 9), (80, 10),
(81, 10), (43, 8), (44, 8), (24, 6), (12, 4),
];
+14 -1
View File
@@ -8,13 +8,26 @@ license.workspace = true
publish.workspace = true
[dependencies]
blake3.workspace = true
miniz_oxide.workspace = true
tracing.workspace = true
anyhow.workspace = true
victory-formats.workspace = true
victory-pipeline.workspace = true
victory-shader.workspace = true
[dev-dependencies]
tempfile.workspace = true
[features]
# Debugging switches (frame capture, the host debug layer, per-draw data).
diagnostics = []
[lints]
workspace = true
[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_LibraryLoader", "Win32_System_Threading"] }
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] }
windows = { workspace = true, features = [
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D12",
+525
View File
@@ -0,0 +1,525 @@
//! Presented frames written to PNG files, to see what reaches the screen:
//! with `VICTORY_CAPTURE=<folder>`, every frame whose number is a power of
//! two (the frames the log reports) is saved as `frame-<n>.png`, at half
//! size. Only in builds with diagnostics.
use std::path::PathBuf;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
/// The folder frames go to, if capturing.
pub(crate) fn folder() -> Option<&'static PathBuf> {
static FOLDER: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();
FOLDER
.get_or_init(|| std::env::var_os("VICTORY_CAPTURE").map(PathBuf::from))
.as_ref()
}
/// Frames listed in `VICTORY_CAPTURE_FRAMES` (comma-separated): saved
/// too, and their draws traced at debug level.
pub(crate) fn listed(n: u64) -> bool {
static LIST: std::sync::OnceLock<Vec<u64>> = std::sync::OnceLock::new();
LIST.get_or_init(|| {
let list = std::env::var("VICTORY_CAPTURE_FRAMES").unwrap_or_default();
list.split(',')
.filter_map(|f| f.trim().parse().ok())
.collect()
})
.contains(&n)
}
/// Whether frame `n` is saved.
pub(crate) fn wanted(n: u64) -> bool {
folder().is_some() && (n.is_power_of_two() || listed(n))
}
/// Saves 8-bit RGBA or BGRA rows (`pitch` bytes apart) as frame `n`.
pub(crate) fn save(n: u64, width: u32, height: u32, pitch: usize, bgra: bool, rows: &[u8]) {
save_as(&format!("frame-{n}"), width, height, pitch, bgra, rows);
}
/// Saves 8-bit RGBA or BGRA rows as `<name>.png`, at half size.
fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows: &[u8]) {
let Some(folder) = folder() else { return };
let (w, h) = ((width / 2).max(1), (height / 2).max(1));
// Filter byte 0 per row, then RGB of every other pixel of every other row.
let mut raw = Vec::with_capacity((w as usize * 3 + 1) * h as usize);
for y in 0..h as usize {
raw.push(0);
let row = &rows[(2 * y).min(height as usize - 1) * pitch..];
for x in 0..w as usize {
let p = &row[(2 * x).min(width as usize - 1) * 4..][..3];
if bgra {
raw.extend([p[2], p[1], p[0]]);
} else {
raw.extend_from_slice(p);
}
}
}
let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
let mut header = Vec::new();
header.extend(w.to_be_bytes());
header.extend(h.to_be_bytes());
header.extend([8, 2, 0, 0, 0]); // 8-bit RGB
chunk(&mut png, b"IHDR", &header);
chunk(
&mut png,
b"IDAT",
&miniz_oxide::deflate::compress_to_vec_zlib(&raw, 3),
);
chunk(&mut png, b"IEND", &[]);
let path = folder.join(format!("{name}.png"));
match std::fs::write(&path, png) {
Ok(()) => tracing::info!(path = %path.display(), "frame saved"),
Err(e) => tracing::warn!(error = %e, path = %path.display(), "frame not saved"),
}
}
fn chunk(png: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
png.extend((data.len() as u32).to_be_bytes());
let start = png.len();
png.extend(kind);
png.extend(data);
let crc = crc32(&png[start..]);
png.extend(crc.to_be_bytes());
}
fn crc32(bytes: &[u8]) -> u32 {
let mut crc = !0u32;
for &b in bytes {
crc ^= u32::from(b);
for _ in 0..8 {
crc = (crc >> 1) ^ (0xedb8_8320 & (crc & 1).wrapping_neg());
}
}
!crc
}
/// Records a copy of `texture` (in the copy-source state) into a
/// readback buffer.
pub(crate) fn read_back(
device: &ID3D12Device,
list: &ID3D12GraphicsCommandList,
texture: &ID3D12Resource,
) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> {
let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
let mut total = 0;
// SAFETY: a live texture; outputs for one subresource.
unsafe {
let desc = texture.GetDesc();
device.GetCopyableFootprints(
&desc,
0,
1,
0,
Some(&mut footprint),
None,
None,
Some(&mut total),
);
}
let heap = D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_READBACK,
..Default::default()
};
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: total,
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<ID3D12Resource> = None;
// SAFETY: plain creation; an open list; locations naming live resources.
unsafe {
device
.CreateCommittedResource(
&heap,
D3D12_HEAP_FLAG_NONE,
&desc,
D3D12_RESOURCE_STATE_COPY_DEST,
None,
&mut buffer,
)
.ok()?;
let buffer = buffer?;
let to = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(&buffer),
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: footprint,
},
};
let from = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(texture),
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
SubresourceIndex: 0,
},
};
list.CopyTextureRegion(&to, 0, 0, 0, &from, None);
Some((buffer, footprint))
}
}
/// Saves a frame read back by [`read_back`] (8-bit color only).
pub(crate) fn save_read_back(
frame: u64,
buffer: &ID3D12Resource,
footprint: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
) {
let f = footprint.Footprint;
let bgra = match f.Format {
DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => false,
DXGI_FORMAT_B8G8R8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM_SRGB => true,
other => {
tracing::warn!(format = other.0, "frame not saved: not 8-bit color");
return;
}
};
let mut data = std::ptr::null_mut();
// SAFETY: the copy finished (every submission is waited for); the
// mapping spans the footprint's rows.
unsafe {
if buffer.Map(0, None, Some(&mut data)).is_err() {
return;
}
let len = f.RowPitch as usize * f.Height as usize;
let rows = std::slice::from_raw_parts(data.cast::<u8>(), len);
save(frame, f.Width, f.Height, f.RowPitch as usize, bgra, rows);
buffer.Unmap(0, None);
}
}
/// With `VICTORY_DUMP_TARGETS` set: title textures the frames listed in
/// `VICTORY_CAPTURE_FRAMES` render to or write, in first-use order, saved
/// at that frame's present as `frame-<n>-<i>-<resource>-<w>x<h>-f<format>.png`
/// (what each holds at the end of the frame; formats normalized to show
/// structure: floats scaled by their largest value, depth by its range).
static TARGETS: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
fn dump_on() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| folder().is_some() && std::env::var_os("VICTORY_DUMP_TARGETS").is_some())
}
/// Notes a title texture the frame being built renders to or writes.
pub(crate) fn note_target(resource: crate::object::This) {
if resource.is_null() || !dump_on() || !listed(crate::queue::presented() + 1) {
return;
}
let mut targets = TARGETS.lock().unwrap_or_else(|e| e.into_inner());
if !targets.contains(&(resource as usize)) {
targets.push(resource as usize);
}
}
/// At the present of frame `frame`: saves the noted targets.
pub(crate) fn dump_targets(frame: u64) {
let targets = std::mem::take(&mut *TARGETS.lock().unwrap_or_else(|e| e.into_inner()));
let Some(host) = crate::host::host() else { return };
for (i, &resource) in targets.iter().enumerate() {
let resource = resource as crate::object::This;
let Some(texture) = crate::resource::host_resource(resource) else {
continue;
};
// SAFETY: a live resource.
let d = unsafe { texture.GetDesc() };
if d.SampleDesc.Count > 1 || d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D {
continue;
}
const COPY_SOURCE: u32 = 0x800;
let Some(before) = crate::resource::host_transition(resource, COPY_SOURCE).map(|(_, b)| b)
else {
dump_one(host, texture, COPY_SOURCE, frame, i, resource, &d);
continue;
};
dump_one(host, texture, before, frame, i, resource, &d);
crate::resource::host_transition(resource, before);
}
}
fn dump_one(
host: &crate::host::Host,
texture: &ID3D12Resource,
state: u32,
frame: u64,
i: usize,
resource: crate::object::This,
d: &D3D12_RESOURCE_DESC,
) {
let Ok(list) = host.new_list() else { return };
let state = D3D12_RESOURCE_STATES(crate::host::legal_state(texture, state) as i32);
let copy = D3D12_RESOURCE_STATE_COPY_SOURCE;
// SAFETY: an open list of ours and a live texture.
let read = unsafe {
if state != copy {
list.list
.ResourceBarrier(&[crate::host::transition(texture, state, copy)]);
}
let read = read_back(&host.device, &list.list, texture);
if state != copy {
list.list
.ResourceBarrier(&[crate::host::transition(texture, copy, state)]);
}
read
};
list.close();
host.execute(&[&list]);
let Some((buffer, footprint)) = read else { return };
let f = footprint.Footprint;
let mut data = std::ptr::null_mut();
// SAFETY: the copy finished; the mapping spans the footprint's rows.
unsafe {
if buffer.Map(0, None, Some(&mut data)).is_err() {
return;
}
let pitch = f.RowPitch as usize;
let rows = std::slice::from_raw_parts(data.cast::<u8>(), pitch * f.Height as usize);
if let Some(rgba) = to_rgba(f.Format.0 as u32, f.Width as usize, f.Height as usize, pitch, rows) {
let name = format!(
"frame-{frame}-{i:02}-{resource:?}-{}x{}-f{}",
d.Width, d.Height, d.Format.0
);
save_as(&name, f.Width, f.Height, f.Width as usize * 4, false, &rgba);
} else {
tracing::info!(format = f.Format.0, ?resource, "target not dumped: format");
}
buffer.Unmap(0, None);
}
}
fn half(h: u16) -> f32 {
let (sign, exp, man) = ((h >> 15) as u32, ((h >> 10) & 0x1f) as i32, (h & 0x3ff) as f32);
let v = match exp {
0 => man * 2f32.powi(-24),
31 => f32::INFINITY,
e => (1.0 + man / 1024.0) * 2f32.powi(e - 15),
};
if sign == 1 { -v } else { v }
}
/// A float packed in `bits` with a 5-bit exponent and `man` mantissa bits
/// (the 11- and 10-bit floats of R11G11B10).
fn small_float(bits: u32, man: u32) -> f32 {
let (exp, m) = ((bits >> man) & 0x1f, (bits & ((1 << man) - 1)) as f32);
match exp {
0 => m / (1 << man) as f32 * 2f32.powi(-14),
31 => f32::INFINITY,
e => (1.0 + m / (1 << man) as f32) * 2f32.powi(e as i32 - 15),
}
}
/// Rows of a host format as 8-bit RGBA: 8-bit color as is, everything else
/// as channel values scaled so the largest finite one is white (single
/// channels: lowest black, highest white, as grey). `None` for formats not
/// handled.
fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(w * h * 4);
let px = |x: usize, y: usize, n: usize| &rows[y * pitch + x * n..][..n];
let u16_at = |b: &[u8], i: usize| u16::from_le_bytes([b[2 * i], b[2 * i + 1]]);
let u32_at = |b: &[u8], i: usize| u32::from_le_bytes(b[4 * i..4 * i + 4].try_into().unwrap_or([0; 4]));
// Channel values as floats, then scaled.
type Decode = Box<dyn Fn(&[u8]) -> [f32; 3]>;
let (n, decode): (usize, Decode) = match format {
27..=32 => {
for y in 0..h {
for x in 0..w {
let p = px(x, y, 4);
out.extend([p[0], p[1], p[2], 255]);
}
}
return Some(out);
}
87..=93 => {
for y in 0..h {
for x in 0..w {
let p = px(x, y, 4);
out.extend([p[2], p[1], p[0], 255]);
}
}
return Some(out);
}
23..=25 => (4, Box::new(move |b| {
let v = u32_at(b, 0);
[(v & 0x3ff) as f32, (v >> 10 & 0x3ff) as f32, (v >> 20 & 0x3ff) as f32]
})),
26 => (4, Box::new(move |b| {
let v = u32_at(b, 0);
[small_float(v & 0x7ff, 6), small_float(v >> 11 & 0x7ff, 6), small_float(v >> 22, 5)]
})),
9..=11 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])),
33..=34 => (4, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0])),
1..=2 => (16, Box::new(move |b| {
[0, 1, 2].map(|i| f32::from_bits(u32_at(b, i)))
})),
15..=16 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)), f32::from_bits(u32_at(b, 1)), 0.0])),
35..=38 => (4, Box::new(move |b| [f32::from(u16_at(b, 0)), f32::from(u16_at(b, 1)), 0.0])),
48..=52 => (2, Box::new(move |b| [f32::from(b[0]), f32::from(b[1]), 0.0])),
// Single channels: shown as grey.
39..=43 => (4, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])),
53..=54 => (2, Box::new(move |b| [half(u16_at(b, 0)); 3])),
55..=59 => (2, Box::new(move |b| [f32::from(u16_at(b, 0)); 3])),
60..=65 => (1, Box::new(move |b| [f32::from(b[0]); 3])),
_ => return None,
};
let values: Vec<[f32; 3]> = (0..h)
.flat_map(|y| (0..w).map(move |x| (x, y)))
.map(|(x, y)| decode(px(x, y, n)))
.collect();
let grey = matches!(format, 39..=43 | 53..=65);
let finite = values.iter().flatten().copied().filter(|v| v.is_finite());
let (low, high) = if grey {
finite.fold((f32::MAX, f32::MIN), |(l, h), v| (l.min(v), h.max(v)))
} else {
(0.0, finite.fold(0.0f32, f32::max))
};
let range = (high - low).max(1e-20);
tracing::info!(format, low, high, "target values");
for v in values {
let c = v.map(|c| (((c - low) / range).clamp(0.0, 1.0) * 255.0) as u8);
out.extend([c[0], c[1], c[2], 255]);
}
Some(out)
}
/// Pixels per side of the grid [`probe`] reads.
const GRID: u32 = 4;
/// Bytes between the grid's pixels in the readback buffer (placement
/// alignment).
const SLOT: u64 = 512;
/// Records copies of a grid of pixels of `texture` (8-bit color, in the
/// copy-source state) into a readback buffer, to tell black frames.
pub(crate) fn probe(
device: &ID3D12Device,
list: &ID3D12GraphicsCommandList,
texture: &ID3D12Resource,
) -> Option<ID3D12Resource> {
// SAFETY: a live resource.
let d = unsafe { texture.GetDesc() };
if !matches!(d.Format.0, 27..=29 | 87 | 90 | 91) {
return None;
}
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: SLOT * u64::from(GRID * GRID),
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
..Default::default()
};
let heap = D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_READBACK,
..Default::default()
};
let mut buffer: Option<ID3D12Resource> = None;
// SAFETY: plain creation; an open list; locations naming live resources.
unsafe {
device
.CreateCommittedResource(
&heap,
D3D12_HEAP_FLAG_NONE,
&desc,
D3D12_RESOURCE_STATE_COPY_DEST,
None,
&mut buffer,
)
.ok()?;
let buffer = buffer?;
for i in 0..GRID * GRID {
let (x, y) = (
(2 * (i % GRID) + 1) * d.Width as u32 / (2 * GRID),
(2 * (i / GRID) + 1) * d.Height / (2 * GRID),
);
let to = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(&buffer),
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
Offset: SLOT * u64::from(i),
Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
Format: d.Format,
Width: 1,
Height: 1,
Depth: 1,
RowPitch: 256,
},
},
},
};
let from = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(texture),
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
SubresourceIndex: 0,
},
};
let pixel = D3D12_BOX {
left: x,
top: y,
front: 0,
right: x + 1,
bottom: y + 1,
back: 1,
};
list.CopyTextureRegion(&to, 0, 0, 0, &from, Some(&pixel));
}
Some(buffer)
}
}
/// Whether every pixel [`probe`] read is (near) black.
pub(crate) fn black(buffer: &ID3D12Resource) -> bool {
let mut data = std::ptr::null_mut();
// SAFETY: the copies finished (every submission is waited for).
unsafe {
if buffer.Map(0, None, Some(&mut data)).is_err() {
return false;
}
let bytes =
std::slice::from_raw_parts(data.cast::<u8>(), (SLOT * u64::from(GRID * GRID)) as usize);
let level = bytes
.chunks(SLOT as usize)
.flat_map(|pixel| pixel[..3].iter().copied())
.max()
.unwrap_or(0);
buffer.Unmap(0, None);
let mut levels = LEVELS.lock().unwrap_or_else(|e| e.into_inner());
if levels.len() == 12 {
levels.pop_front();
}
levels.push_back(level);
level < 8
}
}
/// The brightest probed channel of the last frames, oldest first: a fade
/// darkens over several, a glitch drops at once.
static LEVELS: std::sync::Mutex<std::collections::VecDeque<u8>> =
std::sync::Mutex::new(std::collections::VecDeque::new());
pub(crate) fn recent_levels() -> Vec<u8> {
let levels = LEVELS.lock().unwrap_or_else(|e| e.into_inner());
levels.iter().copied().collect()
}
#[cfg(test)]
mod tests {
#[test]
fn crc_matches_the_png_check_value() {
assert_eq!(super::crc32(b"IEND"), 0xae42_6082);
}
}
+50
View File
@@ -0,0 +1,50 @@
//! Which console the title runs on. Titles pick settings (resolution,
//! memory budgets) by it, so the user chooses; Series X unless told.
use std::sync::atomic::{AtomicBool, Ordering};
const GIB: usize = 1 << 30;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Console {
#[default]
SeriesX,
SeriesS,
}
impl Console {
/// Title memory in bytes: (GPU-optimal, standard). Series X in the
/// advanced configuration; Series S has one range, counted as standard
/// (7,776 MiB, the published console-mode figure).
// shortcut: later system updates gave Series S titles more (amount not
// published here); Grand Theft Auto VI sizes nothing from this figure
// (it goes by the device type), so update it if a title does.
pub const fn title_memory(self) -> (usize, usize) {
match self {
Console::SeriesX => (10 * GIB, 7 * GIB / 2),
Console::SeriesS => (0, 7_776 << 20),
}
}
pub const fn name(self) -> &'static str {
match self {
Console::SeriesX => "Xbox Series X",
Console::SeriesS => "Xbox Series S",
}
}
}
static SERIES_S: AtomicBool = AtomicBool::new(false);
/// Set before the title starts.
pub fn set(console: Console) {
SERIES_S.store(console == Console::SeriesS, Ordering::Relaxed);
}
pub fn current() -> Console {
if SERIES_S.load(Ordering::Relaxed) {
Console::SeriesS
} else {
Console::SeriesX
}
}
+147
View File
@@ -0,0 +1,147 @@
//! Diagnostics: where the submission copies of title memory go (which
//! ranges, how often, of what memory) and what limits their rate, logged
//! with the frame-rate line. `VICTORY_COPY_MODE=plain` copies without the
//! mapped-page guard, `none` skips the copies (both for timing only).
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
/// Counters since the last line.
pub(crate) enum C {
Submissions,
Copies,
CopyBytes,
Refreshes,
RefreshBytes,
Skipped,
SkippedBytes,
Runs,
RunUs,
Queries,
QueryUs,
MoveUs,
Unmapped,
/// Write-watch askings and their time.
Watches,
WatchUs,
/// Bytes of watched ranges checked, and of those found unchanged.
Checked,
Unchanged,
/// Copies that met an unmapped page.
Fallbacks,
/// Writes taken by the guard on view memory.
GuardFaults,
/// Texture bytes detiled after a watched write; hashed; detiled after a
/// hash change.
TexWatched,
TexHashed,
TexChanged,
}
const COUNTERS: usize = 22;
static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS];
pub(crate) fn add(c: C, n: u64) {
COUNT[c as usize].fetch_add(n, Relaxed);
}
/// How copies run: 0 guarded (as always), 1 plain, 2 not at all.
pub(crate) fn mode() -> u8 {
static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
*MODE.get_or_init(|| match std::env::var("VICTORY_COPY_MODE").as_deref() {
Ok("plain") => 1,
Ok("none") => 2,
_ => 0,
})
}
/// Per source range (start, length): copies, bytes, microseconds, memory type.
type Ranges = HashMap<(usize, usize), (u64, u64, u64, u32)>;
static RANGES: Mutex<Option<Ranges>> = Mutex::new(None);
/// A copy of `len` bytes from `src` (memory type `kind`) took `us`.
pub(crate) fn range(src: usize, len: usize, us: u64, kind: u32) {
let mut map = RANGES.lock().unwrap_or_else(|e| e.into_inner());
let e = map
.get_or_insert_with(HashMap::new)
.entry((src, len))
.or_insert((0, 0, 0, kind));
e.0 += 1;
e.1 += len as u64;
e.2 += us;
}
fn page_faults() -> u64 {
use windows_sys::Win32::System::ProcessStatus::{
K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS,
};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
let mut c = PROCESS_MEMORY_COUNTERS {
cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
..Default::default()
};
// SAFETY: our own process and a sized structure.
unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
u64::from(c.PageFaultCount)
}
/// Logs the counters per frame over `frames` frames, and the ranges that
/// took most bytes.
pub(crate) fn log(frames: f64) {
static FAULTS: AtomicU64 = AtomicU64::new(0);
let faults = page_faults();
let faults = faults - FAULTS.swap(faults, Relaxed).min(faults);
let c: Vec<f64> = COUNT
.iter()
.map(|a| a.swap(0, Relaxed) as f64 / frames)
.collect();
let mb = |v: f64| v / 1e6;
let ms = |v: f64| v / 1e3;
tracing::info!(
"copies per frame: {:.1} submissions; {:.0} title copies {:.1} MB; {:.0} refreshes {:.1} MB, \
{:.0} skipped {:.1} MB; {:.0} runs {:.1} ms; {:.0} queries {:.2} ms, moves {:.2} ms, \
{:.2} MB unmapped; {:.0} page faults; {:.0} watches {:.2} ms, {:.1} MB checked, {:.1} MB \
unchanged; {:.1} fallbacks; {:.0} guard faults; textures {:.1} MB watched and \
changed, {:.1} MB hashed, {:.1} MB of them changed",
c[C::Submissions as usize],
c[C::Copies as usize],
mb(c[C::CopyBytes as usize]),
c[C::Refreshes as usize],
mb(c[C::RefreshBytes as usize]),
c[C::Skipped as usize],
mb(c[C::SkippedBytes as usize]),
c[C::Runs as usize],
ms(c[C::RunUs as usize]),
c[C::Queries as usize],
ms(c[C::QueryUs as usize]),
ms(c[C::MoveUs as usize]),
mb(c[C::Unmapped as usize]),
faults as f64 / frames,
c[C::Watches as usize],
ms(c[C::WatchUs as usize]),
mb(c[C::Checked as usize]),
mb(c[C::Unchanged as usize]),
c[C::Fallbacks as usize],
c[C::GuardFaults as usize],
mb(c[C::TexWatched as usize]),
mb(c[C::TexHashed as usize]),
mb(c[C::TexChanged as usize]),
);
let ranges = RANGES.lock().unwrap_or_else(|e| e.into_inner()).take();
let mut ranges: Vec<_> = ranges.into_iter().flatten().collect();
ranges.sort_by_key(|&(_, (_, bytes, _, _))| std::cmp::Reverse(bytes));
for ((src, len), (n, bytes, us, _)) in ranges.into_iter().take(10) {
use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery};
// SAFETY: plain data filled in by the query.
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: a valid out pointer of the right size.
unsafe { VirtualQuery(src as *const _, &mut info, size_of_val(&info)) };
let kind = info.Type;
tracing::info!(
" copied from {src:#x}+{len:#x} (memory {kind:#x}): {:.1}x/frame, {:.2} MB/frame, {:.2} ms/frame",
n as f64 / frames,
bytes as f64 / 1e6 / frames,
us as f64 / 1e3 / frames
);
}
}
+611 -22
View File
@@ -10,6 +10,9 @@
use crate::object::{self, DESCRIPTOR_HEAP, E_INVALIDARG, HRESULT, Iid, Object, Table, This, guid};
use crate::resource::{Memory, PAGEABLE_IIDS};
#[cfg(windows)]
pub(crate) mod host;
const HEAP_IIDS: [Iid; 4] = [
guid(
0x8efb471d,
@@ -31,18 +34,139 @@ pub(crate) struct HeapDesc {
nodes: u32,
}
/// Newer titles (Grand Theft Auto VI) pass the description followed by
/// memory of their own for the descriptors: an address and its size in
/// bytes, or a null address to have the heap allocate (inferred from the
/// title's call sites; older titles pass the plain description).
#[repr(C)]
struct Heap {
object: Object,
desc: HeapDesc,
memory: Memory,
#[derive(Debug, Clone, Copy)]
struct Placement {
address: u64,
size: u64,
}
fn heap<'a>(this: This) -> &'a Heap {
#[repr(C)]
pub(crate) struct Heap {
object: Object,
desc: HeapDesc,
/// The first descriptor: in `memory`, or in the title's own memory.
pub(crate) start: u64,
memory: Option<Memory>,
/// Shader-visible view and sampler heaps get a host heap with the same
/// descriptor order when a draw first uses them (decision 0007, step
/// 3); slots written before wait in `pending`.
#[cfg(windows)]
host: std::sync::OnceLock<Option<host::HostHeap>>,
#[cfg(windows)]
pending: std::sync::Mutex<Vec<u32>>,
}
pub(crate) fn heap<'a>(this: This) -> &'a Heap {
// SAFETY: called from descriptor heap methods only.
unsafe { &*this.cast::<Heap>() }
}
impl Heap {
/// Whether this is a sampler heap.
pub(crate) fn samplers(&self) -> bool {
self.desc.kind == SAMPLERS
}
/// The host heap, made on first use from what the title wrote so far.
/// Made late because a host view heap the size of Grand Theft Auto VI's
/// costs over 100 MB of commit, which its boot needs for its page pool.
#[cfg(windows)]
pub(crate) fn host(&self) -> Option<&host::HostHeap> {
if let Some(h) = self.host.get() {
return h.as_ref();
}
if self.desc.flags & SHADER_VISIBLE == 0 || !matches!(self.desc.kind, VIEWS_KIND | SAMPLERS)
{
return None;
}
let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
let h = self
.host
.get_or_init(|| host::HostHeap::new(self.samplers(), self.desc.count))
.as_ref()?;
let step = u64::from(increment(self.desc.kind)?);
for i in pending.drain(..) {
h.mirror(i, self.start + u64::from(i) * step, false);
}
Some(h)
}
/// The descriptor index of `handle` in this heap, if it lies in it.
pub(crate) fn index(&self, handle: u64) -> Option<u32> {
let step = u64::from(increment(self.desc.kind)?);
let at = handle.checked_sub(self.start)?;
let index = at / step;
(index < u64::from(self.desc.count)).then_some(index as u32)
}
}
const VIEWS_KIND: u32 = 0;
const SAMPLERS: u32 = 1;
const SHADER_VISIBLE: u32 = 1;
/// Shader-visible heaps by address range, for mirroring descriptor writes:
/// start, end, heap.
#[cfg(windows)]
static SHADER_HEAPS: std::sync::Mutex<Vec<(u64, u64, usize)>> = std::sync::Mutex::new(Vec::new());
/// The shader-visible heap holding `handle`, and the descriptor's index.
#[cfg(windows)]
fn shader_slot<'a>(handle: u64) -> Option<(&'a Heap, u32)> {
let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
let &(_, _, at) = heaps
.iter()
.find(|&&(start, end, _)| (start..end).contains(&handle))?;
// SAFETY: registered heaps are live (removed when dropped).
let heap = unsafe { &*(at as *const Heap) };
Some((heap, heap.index(handle)?))
}
/// Makes the host descriptor for what the title wrote at `handle`, if it
/// is in a shader-visible heap.
#[cfg(windows)]
fn mirror(handle: u64) {
let Some((heap, index)) = shader_slot(handle) else {
return;
};
let mut pending = heap.pending.lock().unwrap_or_else(|e| e.into_inner());
match heap.host.get() {
None => pending.push(index),
Some(host) => {
drop(pending);
if let Some(host) = host {
host.mirror(index, handle, false);
}
}
}
}
/// Gives back dynamic slots of the host heap behind the title heap at
/// `heap`, if that heap still exists.
#[cfg(windows)]
pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) {
let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
if heaps.iter().any(|&(_, _, h)| h == heap)
// SAFETY: registered heaps are live (removed when dropped).
&& let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get()
{
host.release(first, n);
}
}
#[cfg(windows)]
impl Drop for Heap {
fn drop(&mut self) {
let at = std::ptr::from_ref::<Heap>(self) as usize;
let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
heaps.retain(|&(_, _, h)| h != at);
}
}
/// Bytes per descriptor, by heap type (views, samplers, render targets,
/// depth).
fn increment(kind: u32) -> Option<u32> {
@@ -73,12 +197,40 @@ impl RtvRecord {
pub(crate) fn desc(
&self,
) -> Option<windows::Win32::Graphics::Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC> {
// SAFETY: 24 bytes in the host's layout.
(self.described != 0).then(|| unsafe {
(&raw const self.desc)
.cast::<windows::Win32::Graphics::Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC>()
.read_unaligned()
})
const TEXTURE_2D: u32 = 4;
self.host_desc(TEXTURE_2D)
}
/// The depth view description in the host's type (the same layout).
#[cfg(windows)]
pub(crate) fn depth_desc(
&self,
) -> Option<windows::Win32::Graphics::Direct3D12::D3D12_DEPTH_STENCIL_VIEW_DESC> {
const TEXTURE_2D: u32 = 3;
self.host_desc(TEXTURE_2D)
}
/// The description words as a host type, the format as the host has it.
/// Without one, a typeless host copy gets a 2D view (`dimension`) in
/// the title's format, which the host needs spelled out.
#[cfg(windows)]
fn host_desc<T>(&self, dimension: u32) -> Option<T> {
assert!(size_of::<T>() <= size_of::<[u32; 6]>());
let mut words = if self.described != 0 {
self.desc
} else {
[
crate::resource::view_format(self.resource)?,
dimension,
0,
0,
0,
0,
]
};
words[0] = crate::resource::pc_format(words[0]);
// SAFETY: both host view descriptions are 24 bytes in this layout.
Some(unsafe { (&raw const words).cast::<T>().read_unaligned() })
}
}
@@ -104,41 +256,380 @@ pub(crate) extern "system" fn create_rtv(
unsafe { (handle as *mut RtvRecord).write_unaligned(record) };
}
/// Device method: a depth view, recorded as render target views are.
pub(crate) extern "system" fn create_dsv(
this: This,
resource: This,
desc: *const [u32; 6],
handle: u64,
) {
create_rtv(this, resource, desc, handle);
if handle != 0 {
// SAFETY: just written by `create_rtv`.
unsafe { (handle as *mut u32).write_unaligned(DSV_TAG) };
}
}
const DSV_TAG: u32 = u32::from_le_bytes(*b"vDSV");
/// A shader view or sampler as the title described it (descriptions in the
/// host's layout, kept as words), for the host to build its own from.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum View {
/// Constant buffer: GPU address and size.
Constant(u64, u32),
/// Shader resource: resource, description (none: the resource's own).
Shader(usize, Option<[u32; 10]>),
/// Unordered access: resource, counter resource, description.
Unordered(usize, usize, Option<[u32; 10]>),
Sampler([u32; 13]),
/// The console's own sampler description: flags, filters per axis,
/// addressing, LOD and anisotropy settings, border color, then
/// console-only tuning words.
ConsoleSampler([u32; 27]),
/// A view of memory without a resource object: whether it is unordered
/// access, the resource description, then the view's (the plain one
/// followed by the memory address and console fields).
Placed(bool, [u32; 14], [u32; 16]),
}
impl View {
/// Whether the view reads buffer memory (constant buffers, buffer views
/// of resources or of memory) or memory the title placed a texture in:
/// such views get host slots only for draws.
#[cfg(windows)]
fn is_buffer(&self) -> bool {
match self {
View::Constant(..) | View::Placed(..) => true,
View::Shader(r, _) | View::Unordered(r, _, _) => {
crate::resource::buffer_bytes(*r as This).is_some()
}
View::Sampler(_) | View::ConsoleSampler(_) => false,
}
}
}
/// Every distinct view in use; a descriptor holds a tag, an index into it
/// and the entry's generation, which survive titles copying descriptors as
/// bytes. A view of a resource lives as long as the resource: when the
/// title releases it, its entries are freed for reuse under a new
/// generation, so descriptors (and host slots made from them) naming the
/// old one go stale instead of naming whatever is made at the same address
/// next.
/// shortcut: views without a resource object (constant buffers, memory
/// views, samplers) are kept for the run; they are bounded by the title's
/// memory and sampler states.
struct Views {
/// Each entry's view and generation.
list: Vec<(View, u32)>,
index: std::collections::BTreeMap<View, u32>,
/// Entries naming each resource.
by_resource: std::collections::BTreeMap<usize, Vec<u32>>,
free: Vec<u32>,
}
static VIEWS: std::sync::Mutex<Views> = std::sync::Mutex::new(Views {
list: Vec::new(),
index: std::collections::BTreeMap::new(),
by_resource: std::collections::BTreeMap::new(),
free: Vec::new(),
});
const VIEW_TAG: u32 = u32::from_le_bytes(*b"vVIE");
impl View {
/// The resource objects the view names.
fn resources(&self) -> [usize; 2] {
match *self {
View::Shader(r, _) => [r, 0],
View::Unordered(r, counter, _) => [r, counter],
_ => [0, 0],
}
}
}
fn record(handle: u64, view: View) {
if handle == 0 {
return;
}
let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let i = match views.index.get(&view) {
Some(&i) => i,
None => {
let i = match views.free.pop() {
Some(i) => {
views.list[i as usize].0 = view.clone();
i
}
None => {
views.list.push((view.clone(), 1));
views.list.len() as u32 - 1
}
};
for r in view.resources().into_iter().filter(|&r| r != 0) {
views.by_resource.entry(r).or_default().push(i);
}
views.index.insert(view, i);
i
}
};
let generation = views.list[i as usize].1;
// SAFETY: the handle is a descriptor slot, at least 16 bytes.
unsafe { (handle as *mut [u32; 3]).write_unaligned([VIEW_TAG, i, generation]) };
drop(views);
#[cfg(windows)]
mirror(handle);
}
/// The title released `resource`: the views naming it go stale.
pub(crate) fn forget(resource: usize) {
let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let Some(entries) = views.by_resource.remove(&resource) else {
return;
};
for i in entries {
let (view, generation) = views.list[i as usize].clone();
// Entries freed through a view's other resource may hold another
// view by now.
if views.index.get(&view) != Some(&i) || !view.resources().contains(&resource) {
continue;
}
views.index.remove(&view);
views.list[i as usize].1 = generation.wrapping_add(1).max(1);
// The view's other resource (a counter) keeps a stale entry, which
// `forget` of that resource skips.
views.free.push(i);
}
}
/// The view of entry `i` if `generation` is still its own.
#[cfg(windows)]
fn view_at(i: u32, generation: u32) -> Option<View> {
let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let (view, current) = views.list.get(i as usize)?;
(*current == generation).then(|| view.clone())
}
/// The view recorded at `handle`, if one is (and its resource is alive).
pub(crate) fn view(handle: u64) -> Option<View> {
if handle == 0 {
return None;
}
// SAFETY: the handle is a descriptor slot the title passes back.
let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let (view, current) = views.list.get(i as usize)?;
(tag == VIEW_TAG && *current == generation).then(|| view.clone())
}
/// A description of `N` words, if the title passes one.
fn words<const N: usize>(desc: *const [u32; N]) -> Option<[u32; N]> {
// SAFETY: the title passes a description or null.
(!desc.is_null()).then(|| unsafe { desc.read_unaligned() })
}
/// Device method.
pub(crate) extern "system" fn create_cbv(_: This, desc: *const [u32; 4], handle: u64) {
if let Some([lo, hi, size, _]) = words(desc) {
let address = u64::from(lo) | u64::from(hi) << 32;
record(handle, View::Constant(address, size));
}
}
/// Device method.
pub(crate) extern "system" fn create_srv(
_: This,
resource: This,
desc: *const [u32; 10],
handle: u64,
) {
record(handle, View::Shader(resource as usize, words(desc)));
}
/// Device method.
pub(crate) extern "system" fn create_uav(
_: This,
resource: This,
counter: This,
desc: *const [u32; 10],
handle: u64,
) {
let view = View::Unordered(resource as usize, counter as usize, words(desc));
record(handle, view);
}
/// Device methods 0x230 and 0x238: shader resource and unordered access
/// views of memory the title placed itself, `(resource desc, view desc,
/// handle)`.
pub(crate) extern "system" fn create_placed_srv(
_: This,
resource: *const [u32; 14],
desc: *const [u32; 16],
handle: u64,
) {
if let (Some(resource), Some(desc)) = (words(resource), words(desc)) {
record(handle, View::Placed(false, resource, desc));
}
}
pub(crate) extern "system" fn create_placed_uav(
_: This,
resource: *const [u32; 14],
desc: *const [u32; 16],
handle: u64,
) {
if let (Some(resource), Some(desc)) = (words(resource), words(desc)) {
record(handle, View::Placed(true, resource, desc));
}
}
/// Device method.
pub(crate) extern "system" fn create_sampler(_: This, desc: *const [u32; 13], handle: u64) {
if let Some(desc) = words(desc) {
record(handle, View::Sampler(desc));
}
}
/// Device method 0x1e8.
pub(crate) extern "system" fn create_sampler_x(_: This, desc: *const [u32; 27], handle: u64) {
if let Some(desc) = words(desc) {
record(handle, View::ConsoleSampler(desc));
}
}
/// Device method: `count` descriptors of `kind` from `src` to `dst`.
pub(crate) extern "system" fn copy_simple(_: This, count: u32, dst: u64, src: u64, kind: u32) {
let step = u64::from(increment(kind).unwrap_or(0));
let len = u64::from(count) * step;
if dst != 0 && src != 0 {
// SAFETY: both ranges are descriptor slots the title owns.
unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len as usize) };
#[cfg(windows)]
for i in 0..u64::from(count) {
mirror(dst + i * step);
}
}
}
/// Device method: ranges of descriptors (start and count each) gathered
/// from the sources and scattered to the destinations, in order.
#[allow(clippy::too_many_arguments)] // the method's own arguments
pub(crate) extern "system" fn copy(
_: This,
dst_ranges: u32,
dst_starts: *const u64,
dst_sizes: *const u32,
src_ranges: u32,
src_starts: *const u64,
src_sizes: *const u32,
kind: u32,
) {
let Some(step) = increment(kind) else {
return;
};
// Each range as (start, count); a null size array means one descriptor
// per range.
let ranges = |n: u32, starts: *const u64, sizes: *const u32| -> Vec<(u64, u32)> {
(0..n as usize)
.map(|i| {
// SAFETY: the title passes `n` starts and sizes (or null sizes).
unsafe {
(
*starts.add(i),
if sizes.is_null() { 1 } else { *sizes.add(i) },
)
}
})
.collect()
};
if dst_starts.is_null() || src_starts.is_null() {
return;
}
let src = ranges(src_ranges, src_starts, src_sizes);
let mut dst = ranges(dst_ranges, dst_starts, dst_sizes).into_iter();
let (mut to, mut room) = dst.next().unwrap_or((0, 0));
for (mut from, mut left) in src {
while left > 0 {
while room == 0 {
let Some(next) = dst.next() else { return };
(to, room) = next;
}
let n = left.min(room);
copy_simple(std::ptr::null(), n, to, from, kind);
let bytes = u64::from(n) * u64::from(step);
(to, from, room, left) = (to + bytes, from + bytes, room - n, left - n);
}
}
}
/// The view recorded at `handle`, if one is.
pub(crate) fn rtv_record(handle: u64) -> Option<RtvRecord> {
tagged_record(handle, RTV_TAG)
}
/// The depth view recorded at `handle`, if one is.
pub(crate) fn dsv_record(handle: u64) -> Option<RtvRecord> {
tagged_record(handle, DSV_TAG)
}
fn tagged_record(handle: u64, tag: u32) -> Option<RtvRecord> {
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)
(record.tag == tag).then_some(record)
}
/// Device method.
pub(crate) extern "system" fn create_heap(
_: This,
desc: *const HeapDesc,
desc_ptr: *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 {
let Some(&desc) = (unsafe { desc_ptr.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,
// SAFETY: read only as a hint: a title that passes the plain
// description has its own stack or data after it.
let placement = unsafe { desc_ptr.add(1).cast::<Placement>().read_unaligned() };
// shortcut: a placement is recognised by its size matching the count,
// since the plain and extended descriptions share the slot and the
// interface version; find the flag that tells them apart if a title
// trips over this.
let placed = placement.address != 0 && placement.size == size;
tracing::debug!(?desc, placed, "descriptor heap");
let (start, memory) = if placed {
(placement.address, None)
} else {
match Memory::zeroed(size, 64) {
Ok(memory) => (memory.address(), Some(memory)),
Err(hr) => return hr,
}
};
let visible = desc.flags & SHADER_VISIBLE != 0 && matches!(desc.kind, VIEWS_KIND | SAMPLERS);
let heap = Box::new(Heap {
object: Object::new(&FUNCTIONS),
desc,
start,
memory,
#[cfg(windows)]
host: std::sync::OnceLock::new(),
#[cfg(windows)]
pending: Default::default(),
});
#[cfg(windows)]
if visible {
let at = std::ptr::from_ref::<Heap>(&heap) as usize;
let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
heaps.push((start, start + size, at));
}
#[cfg(not(windows))]
let _ = visible;
object::hand_out(DESCRIPTOR_HEAP, heap, iid, &HEAP_IIDS, out)
}
@@ -157,12 +648,12 @@ extern "system" fn desc(this: This, out: *mut HeapDesc) {
}
/// The same address for the CPU and the GPU start.
extern "system" fn start(this: This) -> u64 {
heap(this).memory.address()
heap(this).start
}
/// IUnknown 3, object 4, device child 1, heap 3.
static FUNCTIONS: Table<11> = {
let mut f = object::d3d12_object(object::missing_table::<DESCRIPTOR_HEAP, 11>());
static FUNCTIONS: Table<24> = {
let mut f = object::d3d12_object(object::missing_table::<DESCRIPTOR_HEAP, 24>());
f[0] = query as *const ();
f[2] = release as *const ();
f[7] = object::parent_device as *const (); // 0x38
@@ -177,6 +668,16 @@ mod tests {
use super::*;
use crate::object::{S_OK, slot};
/// What newer titles pass; tests use it throughout, so that reading the
/// placement stays inside the value.
#[repr(C)]
struct Extended(HeapDesc, Placement);
fn create(desc: HeapDesc, placement: Placement, out: &mut This) -> HRESULT {
let extended = Extended(desc, placement);
create_heap(std::ptr::null(), &extended.0, &HEAP_IIDS[0], out)
}
#[test]
fn heaps_hold_count_descriptors_from_their_start() {
let null = std::ptr::null();
@@ -186,8 +687,12 @@ mod tests {
flags: 1,
nodes: 0,
};
let none = Placement {
address: 0,
size: 0,
};
let mut h = null;
assert_eq!(create_heap(null, &desc, &HEAP_IIDS[0], &mut h), S_OK);
assert_eq!(create(desc, none, &mut h), S_OK);
let cpu = slot::<extern "system" fn(This) -> u64>(h, 0x48)(h);
assert_eq!(cpu % 64, 0);
assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x50)(h), cpu);
@@ -196,6 +701,90 @@ mod tests {
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);
assert_eq!(create(bad, none, &mut h), E_INVALIDARG);
}
#[test]
fn views_survive_copies() {
let null = std::ptr::null();
let mut heap = vec![0u64; 4 * 8]; // four 32-byte slots
let at = |i: usize| heap.as_ptr() as u64 + 32 * i as u64;
let (s0, s1, s2, s3) = (at(0), at(1), at(2), at(3));
create_cbv(null, &[0x1000, 1, 256, 0], s0);
assert_eq!(view(s0), Some(View::Constant(0x1_0000_1000, 256)));
create_srv(null, null, std::ptr::null(), s1);
assert_eq!(view(s1), Some(View::Shader(0, None)));
// The same view twice is one entry.
create_srv(null, null, std::ptr::null(), s2);
// SAFETY: both slots are in `heap`.
assert_eq!(unsafe { *(s1 as *const [u32; 3]) }, unsafe {
*(s2 as *const [u32; 3])
});
// Two ranges of one into one range of two.
let (dst, dst_n, src, src_n) = ([s2], [2u32], [s0, s1], [1u32, 1]);
copy(
null,
1,
dst.as_ptr(),
dst_n.as_ptr(),
2,
src.as_ptr(),
src_n.as_ptr(),
0,
);
assert_eq!(view(s2), view(s0));
assert_eq!(view(s3), view(s1));
assert_eq!(view(at(0) + 8), None);
heap[0] = 0;
}
/// A released resource's views go stale; the same view of a new
/// resource at the same address is a new record.
#[test]
fn views_die_with_their_resource() {
let null = std::ptr::null();
let slots = [0u64; 2 * 4];
let (a, b) = (slots.as_ptr() as u64, slots.as_ptr() as u64 + 32);
let resource = 0x7777_0000usize as This;
create_srv(null, resource, std::ptr::null(), a);
assert_eq!(view(a), Some(View::Shader(0x7777_0000, None)));
forget(0x7777_0000);
assert_eq!(view(a), None, "stale after release");
create_srv(null, resource, std::ptr::null(), b);
assert_eq!(view(b), Some(View::Shader(0x7777_0000, None)));
// SAFETY: both slots are in `slots`.
let (old, new) = unsafe { (*(a as *const [u32; 3]), *(b as *const [u32; 3])) };
assert_ne!(old, new, "a new generation");
}
/// Grand Theft Auto VI places its shader-visible heap in its own memory
/// and checks that the heap starts there.
#[test]
fn placed_heaps_start_at_the_title_memory() {
let mut memory = vec![0u8; 64 * 32];
let address = memory.as_mut_ptr() as u64;
let desc = HeapDesc {
kind: 0,
count: 64,
flags: 1,
nodes: 1,
};
let mut h = std::ptr::null();
assert_eq!(
create(
desc,
Placement {
address,
size: 64 * 32
},
&mut h
),
S_OK
);
assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x48)(h), address);
assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x50)(h), address);
// A size that does not match the count is not a placement.
assert_eq!(create(desc, Placement { address, size: 7 }, &mut h), S_OK);
assert_ne!(slot::<extern "system" fn(This) -> u64>(h, 0x48)(h), address);
}
}
+731
View File
@@ -0,0 +1,731 @@
//! Host descriptor heaps behind the title's shader-visible heaps (decision
//! 0007, step 3). Translated shaders index the heaps directly at the
//! title's descriptor positions, so each host heap keeps the title heap's
//! order: slot `i` is made from what the title wrote at slot `i`, when it
//! writes it (view creation and descriptor copies) and again when a draw
//! reads it through a table and finds the slot changed.
use std::sync::Mutex;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use super::{VIEW_TAG, View, view_at};
use crate::host::host;
pub(crate) struct HostHeap {
pub(crate) heap: ID3D12DescriptorHeap,
cpu: usize,
step: u32,
/// Slots mirroring the title's; view heaps have [`DYNAMIC`] more.
count: u32,
sampler: bool,
/// The record (view index and generation) each slot was last made from.
made: Mutex<Vec<u64>>,
/// Where the search for free dynamic slots starts, and which are taken
/// (by lists not yet reset).
next: Mutex<(u32, Vec<bool>)>,
}
/// The host's limit for shader-visible view heaps on resource binding
/// tiers 1 and 2; tier 3 hardware may take more.
const PORTABLE_VIEWS: u32 = 1_000_000;
/// Slots past the title's in a view heap, for tables a draw needs made
/// afresh (constant buffers copied per draw). A list holds the slots it
/// took until it is reset (its submissions have run) or released.
const DYNAMIC: u32 = 1 << 16;
impl HostHeap {
pub(crate) fn new(sampler: bool, count: u32) -> Option<Self> {
let host = host()?;
let kind = if sampler {
D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER
} else {
D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV
};
let make = |count: u32| -> windows::core::Result<ID3D12DescriptorHeap> {
// SAFETY: plain heap creation.
unsafe {
host.device
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: kind,
NumDescriptors: count,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})
}
};
let extra = if sampler { 0 } else { DYNAMIC };
let (heap, count) = match make(count + extra) {
Ok(heap) => (heap, count),
Err(e) if !sampler && count + extra > PORTABLE_VIEWS => {
// shortcut: descriptors past the host's limit are left out;
// a title that reaches them needs remapping.
tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}");
(make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - extra)
}
Err(e) => {
tracing::warn!(error = %e, count, sampler, "no host descriptor heap");
return None;
}
};
// SAFETY: a live heap.
let (cpu, step) = unsafe {
(
heap.GetCPUDescriptorHandleForHeapStart().ptr,
host.device.GetDescriptorHandleIncrementSize(kind),
)
};
tracing::debug!(count, sampler, "host descriptor heap");
let h = HostHeap {
heap,
cpu,
step,
count,
sampler,
made: Mutex::new(vec![0; count as usize]),
next: Mutex::new((0, vec![false; DYNAMIC as usize])),
};
// A slot never written is undefined: shaders reading one (a slot
// the title wrote in a way we do not know, or a table entry no
// used-resource entry names) read a wild address. Every slot starts
// null instead.
let started = std::time::Instant::now();
if let Err(e) = h.fill_null(kind, count + extra) {
tracing::warn!(error = %e, "host descriptor heap not made null");
}
tracing::debug!(ms = started.elapsed().as_millis(), "host descriptor heap made null");
Some(h)
}
/// Makes the first `total` slots null: one null slot in a CPU-side heap,
/// doubled by copies to a block, the block copied over the heap.
fn fill_null(&self, kind: D3D12_DESCRIPTOR_HEAP_TYPE, total: u32) -> windows::core::Result<()> {
const BLOCK: u32 = 1 << 16;
let Some(host) = host() else { return Ok(()) };
// SAFETY: plain heap creation and copies inside live heaps.
unsafe {
let block: ID3D12DescriptorHeap =
host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: kind,
NumDescriptors: BLOCK,
..Default::default()
})?;
let start = block.GetCPUDescriptorHandleForHeapStart();
let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE {
ptr: start.ptr + (i * self.step) as usize,
};
if self.sampler {
null_sampler(start);
} else {
null_view(start);
}
let mut filled = 1;
while filled < BLOCK {
let n = filled.min(BLOCK - filled);
host.device.CopyDescriptorsSimple(n, at(filled), start, kind);
filled += n;
}
let mut done = 0;
while done < total {
let n = BLOCK.min(total - done);
host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind);
done += n;
}
}
Ok(())
}
/// A plain point sampler at slot `index`, for sampler slots without a
/// view.
fn null_sampler(&self, index: u32) {
null_sampler(self.cpu(index));
}
}
/// A plain point sampler at `at`.
fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
let Some(host) = host() else { return };
let desc = D3D12_SAMPLER_DESC {
Filter: D3D12_FILTER_MIN_MAG_MIP_POINT,
AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
MaxAnisotropy: 1,
ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER,
..Default::default()
};
// SAFETY: a slot of a sampler heap of ours.
unsafe { host.device.CreateSampler(&desc, at) };
}
impl HostHeap {
/// `n` consecutive free dynamic slots (view heaps only), taken until
/// [`HostHeap::release`]: the first's index.
pub(crate) fn dynamic(&self, n: u32) -> Option<u32> {
if self.sampler || n == 0 || n > DYNAMIC {
return None;
}
let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
let (next, taken) = &mut *guard;
let n = n as usize;
// Search from `next` on, then from the start.
let starts = (*next as usize..DYNAMIC as usize).chain(0..*next as usize);
let mut run = 0;
let mut found = None;
let mut last = usize::MAX;
for at in starts {
// A run cannot wrap past the end.
if at != last.wrapping_add(1) {
run = 0;
}
last = at;
run = if taken[at] { 0 } else { run + 1 };
if run == n {
found = Some(at + 1 - n);
break;
}
}
let Some(first) = found else {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made"));
return None;
};
taken[first..first + n].fill(true);
*next = ((first + n) % DYNAMIC as usize) as u32;
Some(self.count + first as u32)
}
/// Gives back `n` dynamic slots from `first` (an index [`dynamic`]
/// returned).
///
/// [`dynamic`]: HostHeap::dynamic
pub(crate) fn release(&self, first: u32, n: u32) {
let Some(at) = first.checked_sub(self.count) else {
return;
};
let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
let end = (at + n).min(DYNAMIC) as usize;
if let Some(slots) = guard.1.get_mut(at as usize..end) {
slots.fill(false);
}
}
/// Makes slot `index` (a dynamic one) from `view`; a null view if the
/// host cannot.
pub(crate) fn make_at(&self, index: u32, view: &View) {
if !make(view, self.cpu(index)) {
null_for(view, self.cpu(index));
}
}
/// Makes slot `index` read nothing: a null view, or a plain sampler.
pub(crate) fn make_null(&self, index: u32) {
if self.sampler {
self.null_sampler(index);
} else {
null_view(self.cpu(index));
}
}
/// Makes slot `index` (a dynamic one) a constant buffer view of host
/// memory.
pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) {
let Some(host) = host() else { return };
let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC {
BufferLocation: gpu,
SizeInBytes: size.next_multiple_of(256),
};
// SAFETY: a slot of our heap; the memory is the caller's.
unsafe {
host.device
.CreateConstantBufferView(Some(&desc), self.cpu(index))
};
}
fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE {
D3D12_CPU_DESCRIPTOR_HANDLE {
ptr: self.cpu + index as usize * self.step as usize,
}
}
/// Makes host slot `index` from the record the title has at `handle`
/// if it changed since, and returns the view recorded there. Buffer
/// views are made only for draws (`for_draw`), which also copy their
/// data: a host copy of a buffer is made on first use.
pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option<View> {
if index >= self.count {
return None;
}
// SAFETY: the handle is a descriptor slot in title memory.
let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
// Generations start at 1, so a made slot's key is never 0.
let key = u64::from(generation) << 32 | u64::from(i);
let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten();
let Some(view) = view else {
// Not a view of ours (never written, or of a resource the
// title released): nothing to read.
if made[index as usize] != 0 {
made[index as usize] = 0;
self.make_null(index);
}
return None;
};
if made[index as usize] != key {
let later = !for_draw && view.is_buffer();
made[index as usize] = if later { 0 } else { key };
if (later || !make(&view, self.cpu(index))) && !self.sampler {
null_for(&view, self.cpu(index));
}
}
Some(view)
}
/// The view host slot `index` was made from, in a few words, with the
/// title and host addresses of a buffer view (diagnostics). "null" for
/// a slot never made or left null.
#[cfg(feature = "diagnostics")]
pub(crate) fn describe_slot(&self, index: u32) -> Option<String> {
let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?;
if key == 0 {
return Some("null".into());
}
let view = view_at(key as u32, (key >> 32) as u32)?;
let mut text: String = format!("{view:?}").chars().take(120).collect();
if let Some((address, len)) = buffer_range(&view) {
let host = crate::shadow::find(address, len.max(1)).map(|s| s.gpu(address));
text.push_str(&format!(" title {address:#x}+{len:#x} host {host:#x?}"));
}
Some(text)
}
}
/// Logs `what` the first time it happens.
macro_rules! once {
($($arg:tt)*) => {{
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| tracing::warn!($($arg)*));
}};
}
/// A view description from its words, with the format as the host has it.
fn srv_desc(words: &[u32; 10]) -> D3D12_SHADER_RESOURCE_VIEW_DESC {
let mut words = *words;
words[0] = crate::resource::pc_format(words[0]);
// SAFETY: 40 bytes in the host's layout.
unsafe {
std::ptr::from_ref(&words)
.cast::<D3D12_SHADER_RESOURCE_VIEW_DESC>()
.read_unaligned()
}
}
fn uav_desc(words: &[u32; 10]) -> D3D12_UNORDERED_ACCESS_VIEW_DESC {
let mut words = *words;
words[0] = crate::resource::pc_format(words[0]);
// SAFETY: 40 bytes in the host's layout.
unsafe {
std::ptr::from_ref(&words)
.cast::<D3D12_UNORDERED_ACCESS_VIEW_DESC>()
.read_unaligned()
}
}
/// A buffer view of title memory at `address` on its host copy: the first
/// element moves by the copy's offset.
/// Bytes per element of a buffer view.
fn element_size(desc: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> u64 {
// SAFETY: a buffer view's union member.
let buffer = unsafe { desc.Anonymous.Buffer };
if buffer.StructureByteStride > 0 {
u64::from(buffer.StructureByteStride)
} else if buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0 {
4
} else {
crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
}
}
/// The title memory a buffer shader or unordered access view reads: its
/// address and length.
pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> {
let (base, words): (u64, &[u32; 10]) = match view {
View::Shader(r, Some(desc)) => (
crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64,
desc,
),
View::Placed(false, resource, desc) if resource[0] == 1 => (
u64::from(desc[10]) | u64::from(desc[11]) << 32,
desc[..10].try_into().ok()?,
),
View::Unordered(r, _, Some(desc)) => {
let base = crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64;
return unordered_range(base, desc);
}
View::Placed(true, resource, desc) if resource[0] == 1 => {
let base = u64::from(desc[10]) | u64::from(desc[11]) << 32;
return unordered_range(base, desc[..10].try_into().ok()?);
}
_ => return None,
};
let desc = srv_desc(words);
let element = element_size(&desc);
// SAFETY: a buffer view's union member.
let buffer = unsafe { desc.Anonymous.Buffer };
Some((
base + buffer.FirstElement * element,
u64::from(buffer.NumElements) * element,
))
}
/// [`buffer_range`] of an unordered access view of memory at `base`.
fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> {
let desc = uav_desc(words);
// SAFETY: a buffer view's union member.
let buffer = unsafe { desc.Anonymous.Buffer };
let element = if buffer.StructureByteStride > 0 {
u64::from(buffer.StructureByteStride)
} else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 {
4
} else {
crate::resource::element(desc.Format.0 as u32)?.0
};
Some((
base + buffer.FirstElement * element,
u64::from(buffer.NumElements) * element,
))
}
fn buffer_srv(
address: u64,
len: u64,
mut desc: D3D12_SHADER_RESOURCE_VIEW_DESC,
at: D3D12_CPU_DESCRIPTOR_HANDLE,
) -> bool {
let Some(shadow) = crate::shadow::find(address, len) else {
return false;
};
let element = element_size(&desc);
// SAFETY: a buffer view's union member.
let buffer = unsafe { &mut desc.Anonymous.Buffer };
let offset = shadow.offset(address);
if element == 0 || offset % element != 0 {
once!(
offset,
element,
"buffer view not on an element of its host copy"
);
return false;
}
buffer.FirstElement += offset / element;
let Some(host) = host() else { return false };
// SAFETY: a live buffer and a slot of our heap.
unsafe {
host.device
.CreateShaderResourceView(&shadow.buffer, Some(&desc), at)
};
true
}
/// An unordered access view of title buffer memory at `address` (`len`
/// bytes) on its host copy, as [`buffer_srv`]; false if the copy cannot be
/// written by shaders (upload memory).
/// shortcut: what shaders write stays in the host copy; title memory (and
/// so the CPU, and copies run on the CPU) does not see it.
fn buffer_uav(
address: u64,
len: u64,
mut desc: D3D12_UNORDERED_ACCESS_VIEW_DESC,
at: D3D12_CPU_DESCRIPTOR_HANDLE,
) -> bool {
let Some(shadow) = crate::shadow::find(address, len) else {
return false;
};
// SAFETY: a live buffer.
let flags = unsafe { shadow.buffer.GetDesc() }.Flags;
if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 {
once!("unordered access to a buffer whose host copy shaders cannot write");
return false;
}
// SAFETY: a buffer view's union member.
let buffer = unsafe { &mut desc.Anonymous.Buffer };
let element = if buffer.StructureByteStride > 0 {
u64::from(buffer.StructureByteStride)
} else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 {
4
} else {
crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
};
let offset = shadow.offset(address);
if element == 0 || offset % element != 0 {
once!(offset, element, "unordered buffer view not on an element of its host copy");
return false;
}
buffer.FirstElement += offset / element;
buffer.CounterOffsetInBytes = 0;
let Some(host) = host() else { return false };
// SAFETY: a live buffer and a slot of our heap.
unsafe {
host.device
.CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at)
};
true
}
/// Whether the host can make a shader (or unordered access) view of
/// `texture` in `format` (none: the texture's own). The console allows any
/// view; the host refuses (and removes the device for) views without the
/// resource's permission, of typed depth, and in another format than a
/// typed resource's. A view of a typed texture in another format of its
/// family takes the texture's format.
/// shortcut: such a view (sRGB of UNORM, say) reads without its
/// conversion; cast with castable formats if colors come out wrong.
fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordered: bool) -> bool {
use crate::resource::{DEPTH_FORMATS, family};
// SAFETY: a live resource.
let d = unsafe { texture.GetDesc() };
let allowed = if unordered {
d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0
} else {
d.Flags.0 & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0 == 0
};
let own = d.Format.0 as u32;
if !allowed || DEPTH_FORMATS.iter().any(|&(typed, _)| typed == own) {
once!(
unordered,
format = own,
flags = d.Flags.0,
"view the host does not allow"
);
return false;
}
// Every family has more than one format, its typeless one first.
let typeless = family(own) == own && family(own + 1) == own;
if let Some(format) = format.as_deref_mut()
&& unordered
&& let Some(&(_, linear)) = crate::resource::SRGB
.iter()
.find(|&&(s, _)| s == format.0 as u32)
{
format.0 = linear as i32;
}
let view = format.as_ref().map_or(0, |f| f.0 as u32);
if view == 0 {
return !typeless;
}
if family(view) != family(own) {
once!(view, own, "view format of another family");
return false;
}
if let Some(format) = format
&& !typeless
{
*format = d.Format;
}
true
}
/// Makes the host descriptor for `view` at `at`; false if it cannot.
fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> bool {
let Some(host) = host() else { return false };
let device = &host.device;
match view {
&View::Constant(address, size) => {
let Some(shadow) = crate::shadow::find(address, u64::from(size)) else {
return false;
};
let gpu = shadow.gpu(address);
if gpu % 256 != 0 {
once!(
address = format_args!("{address:#x}"),
"constant buffer not 256-byte aligned on the host"
);
return false;
}
let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC {
BufferLocation: gpu,
SizeInBytes: size.next_multiple_of(256),
};
// SAFETY: a slot of our heap; the range lies in the host copy.
unsafe { device.CreateConstantBufferView(Some(&desc), at) };
true
}
View::Shader(resource, desc) => {
let resource = *resource as crate::object::This;
if let Some(texture) = crate::resource::host_resource(resource) {
let mut desc = desc.as_ref().map(srv_desc);
if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) {
return false;
}
// SAFETY: a live texture and a slot of our heap.
unsafe {
device.CreateShaderResourceView(
texture,
desc.as_ref().map(std::ptr::from_ref),
at,
)
};
true
} else if let (Some((data, len)), Some(desc)) =
(crate::resource::buffer_bytes(resource), desc)
{
buffer_srv(data as u64, len, srv_desc(desc), at)
} else {
false
}
}
View::Unordered(resource, _counter, desc) => {
let resource = *resource as crate::object::This;
let Some(texture) = crate::resource::host_resource(resource) else {
return match (crate::resource::buffer_bytes(resource), desc) {
(Some((data, len)), Some(desc)) => {
buffer_uav(data as u64, len, uav_desc(desc), at)
}
_ => false,
};
};
let mut desc = desc.as_ref().map(uav_desc);
if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) {
return false;
}
// SAFETY: a live texture and a slot of our heap.
unsafe {
device.CreateUnorderedAccessView(
texture,
None::<&ID3D12Resource>,
desc.as_ref().map(std::ptr::from_ref),
at,
)
};
true
}
View::Sampler(words) => {
// SAFETY: 13 words in the host's layout.
let desc = unsafe {
std::ptr::from_ref(words)
.cast::<D3D12_SAMPLER_DESC>()
.read_unaligned()
};
// SAFETY: a slot of our sampler heap.
unsafe { device.CreateSampler(&desc, at) };
true
}
View::ConsoleSampler(words) => {
let desc = crate::sampler::console(words);
// SAFETY: a slot of our sampler heap.
unsafe { device.CreateSampler(&desc, at) };
true
}
View::Placed(unordered, resource, desc) => {
if let Some(view) = placed_texture(view) {
return make(&view, at);
}
const BUFFER: u32 = 1;
if resource[0] != BUFFER {
// shortcut: unordered access to a texture the title placed
// itself is not mirrored; give it a resource as shader
// views of such textures get when a dispatch writes one.
once!(dimension = resource[0], "placed unordered texture view not mirrored");
return false;
}
// The resource description's width, after the alignment.
let len = u64::from(resource[4]) | u64::from(resource[5]) << 32;
let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
let words: &[u32; 10] = desc[..10].try_into().unwrap_or(&[0; 10]);
if *unordered {
buffer_uav(address, len, uav_desc(words), at)
} else {
buffer_srv(address, len, srv_desc(words), at)
}
}
}
}
/// A shader view of a texture the title placed in memory itself, as a view
/// of the resource made for that memory (on first use).
pub(crate) fn placed_texture(view: &View) -> Option<View> {
const BUFFER: u32 = 1;
let View::Placed(false, resource, desc) = view else {
return None;
};
if resource[0] == BUFFER {
return None;
}
let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
let texture = crate::resource::texture_at(address, resource)?;
Some(View::Shader(texture as usize, desc[..10].try_into().ok()))
}
/// A null view of the kind `view` is, for a slot whose view the host
/// cannot make: unordered access (to a buffer or a 2D texture) or a shader
/// view. Writes to it are dropped, reads give zeros.
fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) {
let buffer = match view {
View::Unordered(r, _, _) => crate::resource::buffer_bytes(*r as crate::object::This).is_some(),
View::Placed(true, resource, _) => resource[0] == 1,
_ => return null_view(at),
};
let Some(host) = host() else { return };
let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: DXGI_FORMAT_R32_UINT,
ViewDimension: if buffer {
D3D12_UAV_DIMENSION_BUFFER
} else {
D3D12_UAV_DIMENSION_TEXTURE2D
},
..Default::default()
};
// SAFETY: a slot of our heap; a null resource is allowed with a desc.
unsafe {
host.device.CreateUnorderedAccessView(
None::<&ID3D12Resource>,
None::<&ID3D12Resource>,
Some(&desc),
at,
)
};
}
/// A view that reads zeros, for slots whose view the host cannot make.
fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
let Some(host) = host() else { return };
let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: DXGI_FORMAT_R8G8B8A8_UNORM,
ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
Texture2D: D3D12_TEX2D_SRV {
MipLevels: 1,
..Default::default()
},
},
};
// SAFETY: a slot of our heap; a null resource is allowed with a desc.
unsafe {
host.device
.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at)
};
}
#[cfg(test)]
mod tests {
use super::*;
/// Dynamic slots stay taken until given back, and runs do not wrap.
#[test]
fn dynamic_slots_are_held_until_released() {
let Some(heap) = HostHeap::new(false, 4) else {
return; // no host GPU
};
let a = heap.dynamic(DYNAMIC - 100).unwrap();
let b = heap.dynamic(60).unwrap();
assert_eq!((a, b), (4, 4 + DYNAMIC - 100));
// 40 left at the end: 50 do not fit until something is given back.
assert_eq!(heap.dynamic(50), None);
heap.release(a, 50);
assert_eq!(heap.dynamic(50), Some(4));
assert_eq!(heap.dynamic(40), Some(4 + DYNAMIC - 40));
}
}
+191 -8
View File
@@ -28,8 +28,72 @@ pub static IID: Iid = guid(
[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.
/// The levels the device answers to, as on PC: `ID3D12Device1` to
/// `ID3D12Device8`, and `ID3D12Device11`, which Grand Theft Auto VI creates
/// its device as. Each level's table is the one before plus its methods.
const LEVEL_IIDS: [Iid; 9] = [
guid(
0x77acce80,
0x638e,
0x4e65,
[0x88, 0x95, 0xc1, 0xf2, 0x33, 0x86, 0x86, 0x3e],
),
guid(
0x30baa41e,
0xb15b,
0x475c,
[0xa0, 0xbb, 0x1a, 0xf5, 0xc5, 0xb6, 0x43, 0x28],
),
guid(
0x81dadc15,
0x2bad,
0x4392,
[0x93, 0xc5, 0x10, 0x13, 0x45, 0xc4, 0xaa, 0x98],
),
guid(
0xe865df17,
0xa9ee,
0x46f9,
[0xa4, 0x63, 0x30, 0x98, 0x31, 0x5a, 0xa2, 0xe5],
),
guid(
0x8b4f173b,
0x2fea,
0x4b80,
[0x8f, 0x58, 0x43, 0x07, 0x19, 0x1a, 0xb9, 0x5d],
),
guid(
0xc70b221b,
0x40e4,
0x4a17,
[0x89, 0xaf, 0x02, 0x5a, 0x07, 0x27, 0xa6, 0xdc],
),
guid(
0x5c014b53,
0x68a1,
0x4b9b,
[0x8b, 0xd1, 0xdd, 0x60, 0x46, 0xb9, 0x35, 0x8b],
),
guid(
0x728f1fa2,
0xea11,
0x4a9f,
[0x9b, 0x52, 0x9b, 0x42, 0xa4, 0x84, 0xd5, 0xc9],
),
guid(
0x5405c344,
0xd457,
0x444e,
[0xb4, 0xdd, 0x23, 0x66, 0xe4, 0x5a, 0xee, 0x39],
),
];
fn is_device(iid: *const Iid) -> bool {
object::is(iid, &[IID]) || object::is(iid, &LEVEL_IIDS)
}
/// The interface version these layouts were checked against (2.4). Both
/// Minecraft (March 2022) and Grand Theft Auto VI (April 2026) pass it.
pub const CHECKED_VERSION: u32 = 0x0002_0004;
/// Feature level 12_2, what the console hardware supports.
@@ -78,19 +142,34 @@ pub extern "system" fn create(
"device layouts were checked against {CHECKED_VERSION:#x} only"
);
}
if *iid != IID {
if !is_device(iid) {
tracing::warn!(iid = %guid_text(iid), "device created as an unknown interface");
return E_NOINTERFACE;
}
if out.is_null() {
return S_FALSE;
}
if *iid == LEVEL_IIDS[8] {
NEWER.store(true, std::sync::atomic::Ordering::Relaxed);
}
object::answer(object::DEVICE, iid, Some(device()), out)
}
/// Set when the title creates the device as `ID3D12Device11`. Its lists and
/// queues then have the newer layouts (two more methods each; see
/// `list` and `queue`), although the interface version stays 2.4.
/// shortcut: the creation interface is the only sign of the newer layouts
/// we have (Grand Theft Auto VI, April 2026, versus Minecraft, March 2022);
/// look for a better one if a title breaks the rule.
static NEWER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub(crate) fn newer() -> bool {
NEWER.load(std::sync::atomic::Ordering::Relaxed)
}
/// 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]) {
let found = if is_device(iid) {
Some(this)
} else if object::is(iid, &dxgi::DEVICE_IIDS) {
Some(dxgi::device())
@@ -100,6 +179,55 @@ extern "system" fn query_interface(this: This, iid: *const Iid, out: *mut This)
object::answer(object::DEVICE, iid, found, out)
}
/// What `D3D12ConfigureVirtualMemoryX` takes and fills in.
#[repr(C)]
pub struct VirtualMemory {
flags: u32,
/// GPU page table size in 4 MiB pages.
page_table_pages: u32,
/// Memory kept across title processes for the frame buffer.
preserved_bytes: u32,
/// Out: the range graphics addresses fall in.
lowest: u64,
highest: u64,
}
const _: () = assert!(size_of::<VirtualMemory>() == 0x20);
/// `d3d12_xs!D3D12ConfigureVirtualMemoryX`, called before any graphics
/// allocation. The inputs size console structures we do not have; the
/// range out is all of user space, since GPU addresses are CPU addresses.
pub extern "system" fn configure_virtual_memory(config: *mut VirtualMemory) -> HRESULT {
// SAFETY: the title passes its configuration (null is tolerated).
let Some(config) = (unsafe { config.as_mut() }) else {
return E_INVALIDARG;
};
tracing::info!(
flags = config.flags,
page_table_pages = config.page_table_pages,
preserved_bytes = config.preserved_bytes,
"graphics virtual memory"
);
(config.lowest, config.highest) = user_space();
S_OK
}
fn user_space() -> (u64, u64) {
#[cfg(windows)]
{
use windows_sys::Win32::System::SystemInformation::{GetSystemInfo, SYSTEM_INFO};
// SAFETY: plain data, filled in by the call.
let mut info: SYSTEM_INFO = unsafe { std::mem::zeroed() };
// SAFETY: a valid out pointer.
unsafe { GetSystemInfo(&mut info) };
(
info.lpMinimumApplicationAddress as u64,
info.lpMaximumApplicationAddress as u64,
)
}
#[cfg(not(windows))]
(0x1_0000, 0x7fff_fffe_ffff)
}
extern "system" fn node_count(_: This) -> u32 {
1
}
@@ -217,9 +345,13 @@ fn feature_levels(data: *mut c_void) -> HRESULT {
}
}
/// IUnknown 3, object methods 4, device methods 76.
static FUNCTIONS: Table<83> = {
let mut f = object::d3d12_object(object::missing_table::<{ object::DEVICE }, 83>());
/// IUnknown 3, object methods 4, device methods 76 (0x18-0x290), then the
/// methods `ID3D12Device1` to `ID3D12Device8` add, in order: 3, 1, 3, 6, 9,
/// 1, 2, 9 (0x298-0x3a0, the console's own among them), then those of
/// `ID3D12Device9` to `ID3D12Device11`, whose console layout is unknown.
/// Every slot exists so that a call to one we have not written logs it.
static FUNCTIONS: Table<160> = {
let mut f = object::d3d12_object(object::missing_table::<{ object::DEVICE }, 160>());
f[0] = query_interface as *const (); // 0x00
f[7] = node_count as *const (); // 0x38
f[8] = queue::create as *const (); // 0x40
@@ -231,8 +363,16 @@ static FUNCTIONS: Table<83> = {
f[14] = descriptor::create_heap as *const (); // 0x70
f[15] = descriptor::increment_size as *const (); // 0x78
f[16] = root::create as *const (); // 0x80
f[17] = descriptor::create_cbv as *const (); // 0x88
f[18] = descriptor::create_srv as *const (); // 0x90
f[19] = descriptor::create_uav as *const (); // 0x98
f[20] = descriptor::create_rtv as *const (); // 0xa0
f[21] = descriptor::create_dsv as *const (); // 0xa8
f[22] = descriptor::create_sampler as *const (); // 0xb0
f[23] = descriptor::copy as *const (); // 0xb8
f[24] = descriptor::copy_simple as *const (); // 0xc0
f[25] = resource::allocation_info as *const (); // 0xc8
f[26] = resource::custom_heap_properties as *const (); // 0xd0
f[27] = resource::create_committed as *const (); // 0xd8
f[28] = resource::create_heap as *const (); // 0xe0
f[29] = resource::create_placed as *const (); // 0xe8
@@ -240,12 +380,26 @@ static FUNCTIONS: Table<83> = {
f[38] = resource::copyable_footprints as *const (); // 0x130
f[39] = query::create as *const (); // 0x138
f[41] = signature::create as *const (); // 0x148
f[48] = queue::create_x as *const (); // 0x180
f[61] = descriptor::create_sampler_x as *const (); // 0x1e8
f[62] = pipeline::create_compute_x as *const (); // 0x1f0
f[69] = object::ignore as *const (); // 0x228 debug error filter
f[70] = descriptor::create_placed_srv as *const (); // 0x230
f[71] = descriptor::create_placed_uav as *const (); // 0x238
f[73] = list::create_list_x as *const (); // 0x248
f[74] = resource::register_page_pool as *const (); // 0x250
f[75] = resource::unregister_page_pool as *const (); // 0x258
// CreateCommittedResourceX: its description is PC's plus DCC options,
// which we have no use for (the AMD upscaler's, on Series S).
f[76] = resource::create_committed as *const (); // 0x260
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
f[86] = pipeline::create_stream as *const (); // 0x2b0
f[108] = resource::allocation_info2 as *const (); // 0x360
f[127] = resource::create_committed3 as *const (); // 0x3f8
f[133] = resource::create_at_address as *const (); // 0x428
Table(f)
};
@@ -274,10 +428,39 @@ mod tests {
slot::<extern "system" fn(This) -> u32>(device, 0x38)(device),
1
);
let missing = slot::<extern "system" fn() -> HRESULT>(device, 0x88);
let missing = slot::<extern "system" fn() -> HRESULT>(device, 0xf0);
assert_eq!(missing(), E_NOTIMPL);
}
#[test]
fn newer_device_levels_are_the_same_device() {
// ID3D12Device11, as Grand Theft Auto VI asks for it.
let (hr, device) = create_as(&LEVEL_IIDS[8]);
assert_eq!((hr, device), (S_OK, super::device()));
let mut same = std::ptr::null();
assert_eq!(query_interface(device, &LEVEL_IIDS[4], &mut same), S_OK);
assert_eq!(same, device);
// A Device8 method we have not written fails without crashing.
let missing = slot::<extern "system" fn() -> HRESULT>(device, 0x3a0);
assert_eq!(missing(), E_NOTIMPL);
}
#[test]
fn virtual_memory_configuration_reports_user_space() {
let mut config = VirtualMemory {
flags: 0,
page_table_pages: 7,
preserved_bytes: 0,
lowest: 0,
highest: 0,
};
assert_eq!(configure_virtual_memory(&mut config), S_OK);
assert!(0 < config.lowest && config.lowest < config.highest);
let heap = Box::new(0u8);
assert!((config.lowest..=config.highest).contains(&(&raw const *heap as u64)));
assert_eq!(configure_virtual_memory(std::ptr::null_mut()), E_INVALIDARG);
}
#[test]
fn feature_levels_pick_the_highest_supported() {
type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT;
+987
View File
@@ -0,0 +1,987 @@
//! Draws on the host GPU (decision 0007, step 3). A list keeps the state
//! the title sets for its draws (pipeline, descriptor heaps, root
//! arguments, vertex and index buffers, targets); each draw then brings the
//! host list up to date: the host pipeline and our root signature, the
//! user data the translated shaders read, the host copies of the buffers
//! and descriptors they read, and the states of the textures involved.
//! State the host keeps across draws (viewports, scissors, blend factor,
//! stencil reference, topology, targets) is set on the host list as the
//! title sets it.
use std::sync::atomic::{AtomicU64, Ordering};
use victory_shader::{ResourceType, RootType, UsedResource};
use crate::descriptor::View;
use windows::Win32::Foundation::RECT;
use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
use windows::core::Interface;
use crate::host::HostList;
use crate::object::This;
use crate::pipeline::host::HostPipeline;
/// A root argument as the title set it.
#[derive(Debug, Clone, Default)]
enum Root {
#[default]
None,
/// A descriptor table's first descriptor (an address in a heap).
Table(u64),
Constants(Vec<u32>),
/// A root view's GPU address.
View(u64),
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct VertexView {
address: u64,
size: u32,
stride: u32,
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct IndexView {
address: u64,
size: u32,
format: u32,
}
/// What one title list has set, and what its host list was last given.
#[derive(Default)]
pub(crate) struct State {
pipeline: usize,
/// View heap, sampler heap.
heaps: [usize; 2],
graphics: Vec<Root>,
compute: Vec<Root>,
vertex: [VertexView; 32],
index: IndexView,
/// Bound render target and depth resources, for their host states.
targets: Vec<usize>,
depth: usize,
/// The title's primitive topology (the host's may differ).
topology: u32,
/// What the host list has: pipeline, root signature, heaps.
host_pipeline: usize,
/// Graphics, compute.
host_roots: [usize; 2],
host_heaps: [usize; 2],
/// Tables made afresh in this list: (table, what it holds) → first
/// dynamic slot.
fresh_tables: std::collections::HashMap<(u64, u64), u32>,
/// The dynamic slots the list holds: title heap, first, count; given
/// back when the list is reset or released.
dynamic: Vec<(usize, u32, u32)>,
}
impl Drop for State {
fn drop(&mut self) {
for &(heap, first, n) in &self.dynamic {
crate::descriptor::release_dynamic(heap, first, n);
}
}
}
/// Draws recorded on the host GPU since the last frame line.
static DRAWN: AtomicU64 = AtomicU64::new(0);
/// Draws run on the host so far.
pub(crate) fn drawn() -> u64 {
DRAWN.load(Ordering::Relaxed)
}
/// The draws traced since the last present (diagnostics builds, with
/// debug logging for this module): logged when the frame comes out black.
#[cfg(feature = "diagnostics")]
static FRAME: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
/// The draws traced since the last call.
#[cfg(feature = "diagnostics")]
pub(crate) fn take_frame() -> Vec<String> {
std::mem::take(&mut *FRAME.lock().unwrap_or_else(|e| e.into_inner()))
}
/// Marks the last traced draw as not run on the host.
#[cfg(feature = "diagnostics")]
fn dropped() {
if let Some(last) = FRAME.lock().unwrap_or_else(|e| e.into_inner()).last_mut() {
last.push_str(" DROPPED");
}
}
/// Dispatches run on the host so far.
static DISPATCHED: AtomicU64 = AtomicU64::new(0);
pub(crate) fn dispatched() -> u64 {
DISPATCHED.load(Ordering::Relaxed)
}
/// The host address of a root view: its buffer's host copy, or for a
/// constant buffer not 256-byte aligned there (the console needs 16) a
/// copy in upload memory.
/// shortcut: a root view has no size; constant buffers are taken as 64 KiB,
/// other views as 1 MiB (both cut at their buffer's end).
fn root_view(list: &HostList, address: u64, srv: bool) -> Option<u64> {
let shadow = crate::shadow::find(address, 1)?;
let len = shadow
.left(address)
.min(if srv { 1 << 20 } else { 1 << 16 });
let gpu = shadow.gpu(address);
if srv || gpu % 256 == 0 {
shadow.refresh(list, address, len);
return Some(gpu);
}
let (gpu, to) = list.scratch(len)?;
list.defer_fill(to, address as *const u8, len as usize);
Some(gpu)
}
macro_rules! once {
($($arg:tt)*) => {{
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| tracing::warn!($($arg)*));
}};
}
fn set(roots: &mut Vec<Root>, slot: u32, root: Root) {
let slot = slot as usize;
if roots.len() <= slot {
roots.resize(slot + 1, Root::None);
}
roots[slot] = root;
}
impl State {
pub(crate) fn reset(&mut self, pipeline: This) {
*self = State::default();
self.pipeline = pipeline as usize;
}
/// The title's topology; console-only ones become host lists (see
/// [`crate::primitive`]).
pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) {
self.topology = topology;
let host = match topology {
RECTANGLES => 4,
TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => {
once!(topology, "console topology drawn as a triangle list");
4
}
t => t,
};
// SAFETY: an open list.
unsafe {
list.list
.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(host as i32))
};
}
pub(crate) fn set_pipeline(&mut self, pipeline: This) {
self.pipeline = pipeline as usize;
}
pub(crate) fn set_heaps(&mut self, heaps: &[This]) {
self.heaps = [0; 2];
for &h in heaps {
if !h.is_null() {
let samplers = crate::descriptor::heap(h).samplers();
self.heaps[usize::from(samplers)] = h as usize;
}
}
}
fn roots(&mut self, compute: bool) -> &mut Vec<Root> {
if compute {
&mut self.compute
} else {
&mut self.graphics
}
}
pub(crate) fn set_table(&mut self, compute: bool, slot: u32, handle: u64) {
set(self.roots(compute), slot, Root::Table(handle));
}
pub(crate) fn set_view(&mut self, compute: bool, slot: u32, address: u64) {
set(self.roots(compute), slot, Root::View(address));
}
pub(crate) fn set_constants(&mut self, compute: bool, slot: u32, values: &[u32], offset: u32) {
let roots = self.roots(compute);
let s = slot as usize;
if !matches!(roots.get(s), Some(Root::Constants(_))) {
set(roots, slot, Root::Constants(Vec::new()));
}
if let Root::Constants(c) = &mut roots[s] {
let end = offset as usize + values.len();
if c.len() < end {
c.resize(end, 0);
}
c[offset as usize..end].copy_from_slice(values);
}
}
pub(crate) fn set_vertex_buffers(&mut self, start: u32, views: &[VertexView]) {
for (i, v) in views.iter().enumerate() {
if let Some(slot) = self.vertex.get_mut(start as usize + i) {
*slot = *v;
}
}
}
pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) {
self.index = view.copied().unwrap_or_default();
}
/// Render targets and depth, set on the host list at once.
pub(crate) fn set_targets(&mut self, list: &HostList, handles: &[u64], depth: u64) {
let Some(host) = crate::host::host() else {
return;
};
self.targets.clear();
let mut rtvs = Vec::new();
for &h in handles {
let Some(record) = crate::descriptor::rtv_record(h) else {
once!(
handle = format_args!("{h:#x}"),
"render target without a recorded view"
);
continue;
};
let Some(texture) = crate::resource::host_resource(record.resource) else {
continue;
};
self.targets.push(record.resource as usize);
#[cfg(feature = "diagnostics")]
crate::capture::note_target(record.resource);
rtvs.push(host.rtv(texture, record.desc().as_ref()));
}
self.depth = 0;
let dsv = crate::descriptor::dsv_record(depth).and_then(|record| {
let texture = crate::resource::host_resource(record.resource)?;
self.depth = record.resource as usize;
#[cfg(feature = "diagnostics")]
crate::capture::note_target(record.resource);
Some(host.dsv(texture, record.depth_desc().as_ref()))
});
// SAFETY: an open list; the views were just made.
unsafe {
list.list.OMSetRenderTargets(
rtvs.len() as u32,
(!rtvs.is_empty()).then_some(rtvs.as_ptr()),
false,
dsv.as_ref().map(std::ptr::from_ref),
)
};
}
/// The user-data value of a root argument, as translated shaders read
/// it: a table's byte offset in its heap, a constant's value.
fn user_value(&self, compute: bool, slot: u8, root: RootType, dword: u32) -> u32 {
match (self.roots_ref(compute).get(usize::from(slot)), root) {
(Some(Root::Table(handle)), RootType::Table) => match self.heap_of(*handle) {
Some(heap) => (handle - heap.start) as u32,
None => {
once!(
handle = format_args!("{handle:#x}"),
"descriptor table outside the bound heaps"
);
0
}
},
(Some(Root::Constants(c)), RootType::Constants) => {
c.get(dword as usize).copied().unwrap_or(0)
}
_ => {
once!(
slot,
?root,
"a shader reads a root argument the title did not set"
);
0
}
}
}
/// The bound heap holding `handle`.
fn heap_of(&self, handle: u64) -> Option<&'static crate::descriptor::Heap> {
self.heaps
.iter()
.filter(|&&h| h != 0)
.map(|&h| crate::descriptor::heap(h as This))
.find(|h| h.index(handle).is_some())
}
/// Brings the host list up to date for a draw; false if the draw cannot
/// run on the host.
fn prepare(&mut self, list: &HostList, indexed: bool) -> bool {
self.prepare_for(list, indexed, false)
}
/// As [`State::prepare`], for draws (`mesh` false) or mesh dispatches.
fn prepare_for(&mut self, list: &HostList, indexed: bool, mesh: bool) -> bool {
let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
return false;
};
if p.compute || p.mesh != mesh {
once!(mesh, "a draw or mesh dispatch with another kind of pipeline");
return false;
}
self.bind(list, p, false);
let l = &list.list;
// Vertex buffers the input layout reads.
let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32];
let mut count = 0;
for (slot, (view, &v)) in views.iter_mut().zip(&self.vertex).enumerate() {
if p.slots & 1 << slot == 0 {
continue;
}
count = slot + 1;
if v.address == 0 || v.size == 0 {
continue;
}
let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else {
continue;
};
shadow.refresh(list, v.address, u64::from(v.size));
*view = D3D12_VERTEX_BUFFER_VIEW {
BufferLocation: shadow.gpu(v.address),
SizeInBytes: v.size,
StrideInBytes: v.stride,
};
}
// SAFETY: an open list; the views name live host buffers.
unsafe {
if count > 0 {
l.IASetVertexBuffers(0, Some(&views[..count]));
}
}
if indexed {
let v = self.index;
let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else {
return false;
};
shadow.refresh(list, v.address, u64::from(v.size));
let view = D3D12_INDEX_BUFFER_VIEW {
BufferLocation: shadow.gpu(v.address),
SizeInBytes: v.size,
Format: DXGI_FORMAT(v.format as i32),
};
// SAFETY: an open list; the view names a live host buffer.
unsafe { l.IASetIndexBuffer(Some(&view)) };
}
const RENDER_TARGET: u32 = 0x4;
const DEPTH_WRITE: u32 = 0x10;
for &t in &self.targets {
crate::list::ensure_state(list, t as This, RENDER_TARGET);
}
if self.depth != 0 {
crate::list::ensure_state(list, self.depth as This, DEPTH_WRITE);
}
true
}
/// A descriptor a shader reads through a table: its host slot made if
/// it changed, constant data copied, textures made readable.
/// What draws and dispatches share: heaps, our root signature, the
/// pipeline, and per stage the user data, root views and the
/// descriptors its tables hold.
fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) {
let l = &list.list;
// Heaps first: a root signature with directly indexed heaps must be
// set after them.
if self.host_heaps != self.heaps {
let heaps: Vec<Option<ID3D12DescriptorHeap>> = self
.heaps
.iter()
.filter(|&&h| h != 0)
.filter_map(|&h| crate::descriptor::heap(h as This).host())
.map(|h| Some(h.heap.clone()))
.collect();
// SAFETY: an open list and shader-visible heaps.
unsafe { l.SetDescriptorHeaps(&heaps) };
self.host_heaps = self.heaps;
self.host_roots = [0; 2];
}
let root = p.root.as_raw() as usize;
if self.host_roots[usize::from(compute)] != root {
// SAFETY: an open list and a live root signature.
unsafe {
if compute {
l.SetComputeRootSignature(&p.root);
} else {
l.SetGraphicsRootSignature(&p.root);
}
}
self.host_roots[usize::from(compute)] = root;
}
if self.host_pipeline != self.pipeline {
// SAFETY: an open list and a live pipeline.
unsafe { l.SetPipelineState(&p.pso) };
self.host_pipeline = self.pipeline;
list.used_pipeline(&p.name);
}
for stage in &p.stages {
let t = stage.translated();
let made = self.tables(list, &t.used, compute);
if let Some((param, dwords)) = stage.user_data {
let mut values = vec![0u32; dwords as usize];
for u in &t.host.user_data {
let fresh = made
.iter()
.find(|m| m.0 == u.slot && u.root == RootType::Table);
values[u.index as usize] = match fresh {
Some(&(_, offset)) => offset,
None => self.user_value(compute, u.slot, u.root, u.dword),
};
}
// SAFETY: an open list; `values` covers the parameter.
unsafe {
if compute {
l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
} else {
l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
}
}
}
for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] {
for &(slot, param) in views {
let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot))
else {
once!(slot, "a shader reads a root view the title did not set");
continue;
};
let Some(gpu) = root_view(list, *address, srv) else {
continue;
};
// SAFETY: an open list; the address is in live memory.
unsafe {
match (compute, srv) {
(false, false) => l.SetGraphicsRootConstantBufferView(param, gpu),
(false, true) => l.SetGraphicsRootShaderResourceView(param, gpu),
(true, false) => l.SetComputeRootConstantBufferView(param, gpu),
(true, true) => l.SetComputeRootShaderResourceView(param, gpu),
}
}
}
}
}
}
/// Runs a dispatch on the host.
pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) {
let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
once!(
pipeline = format_args!("{:#x}", self.pipeline),
"a dispatch without a host pipeline dropped"
);
return;
};
if !p.compute {
once!("a dispatch with a graphics pipeline");
return;
}
self.bind(list, p, true);
#[cfg(feature = "diagnostics")]
list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
// SAFETY: an open list with everything set.
unsafe { list.list.Dispatch(x, y, z) };
DISPATCHED.fetch_add(1, Ordering::Relaxed);
}
/// What a draw or dispatch runs, for the device-removed report
/// (diagnostics): the pipeline, then per stage the user data it gets
/// (with the view at that heap index, if one is), the host addresses
/// of its root views and the views its tables name.
#[cfg(feature = "diagnostics")]
fn op_text(&self, kind: String, compute: bool) -> String {
use std::fmt::Write;
let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
return kind;
};
let mut text = format!("{kind} {}", p.name);
let views = (self.heaps[0] != 0)
.then(|| crate::descriptor::heap(self.heaps[0] as This).host())
.flatten();
for stage in &p.stages {
let t = stage.translated();
let _ = write!(text, " | {}:", stage.shader.hash);
for u in &t.host.user_data {
let v = self.user_value(compute, u.slot, u.root, u.dword);
let _ = write!(text, " u{}={v:#x}", u.index);
let index = if u.root == RootType::Table { v / 32 } else { v };
if let Some(slot) = views.and_then(|h| h.describe_slot(index)) {
let _ = write!(text, " [heap {index}: {slot}]");
}
}
for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs) {
if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) {
let host = crate::shadow::find(*address, 1)
.map(|s| (s.gpu(*address), s.left(*address)));
let _ = write!(text, " root{slot}={address:#x} host {host:#x?}");
}
}
}
let _ = write!(text, " tables {:?}", self.reads(compute));
text
}
/// Runs a mesh dispatch of `x` groups on the host (the title's mesh
/// programs are one-dimensional).
pub(crate) fn dispatch_mesh(&mut self, list: &HostList, x: u32) {
#[cfg(feature = "diagnostics")]
self.trace("mesh", x, 0);
let ran = self.prepare_for(list, false, true)
&& match list.list.cast::<ID3D12GraphicsCommandList6>() {
Ok(l6) => {
#[cfg(feature = "diagnostics")]
list.note_op(|| self.op_text(format!("mesh {x}"), false));
// SAFETY: an open list with everything set.
unsafe { l6.DispatchMesh(x, 1, 1) };
DRAWN.fetch_add(1, Ordering::Relaxed);
true
}
Err(_) => false,
};
#[cfg(feature = "diagnostics")]
if !ran {
dropped();
}
#[cfg(not(feature = "diagnostics"))]
let _ = ran;
}
fn roots_ref(&self, compute: bool) -> &Vec<Root> {
if compute {
&self.compute
} else {
&self.graphics
}
}
fn table_entry(&self, list: &HostList, u: &UsedResource, compute: bool) {
let Some(Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else {
return;
};
let handle = table + u64::from(u.table_offset_dwords) * 4;
let Some(heap) = self.heap_of(handle) else {
return;
};
let (Some(host), Some(index)) = (heap.host(), heap.index(handle)) else {
return;
};
if let Some(view) = host.mirror(index, handle, true) {
readable(list, u, &view);
}
}
/// The descriptors a shader reads through tables. Tables holding a
/// constant buffer are made afresh for the draw in dynamic slots, with
/// the constant data copied to upload memory when the list is
/// submitted: the host wants constant buffers 256-byte aligned, the
/// console only 16. Returns those tables' new byte offsets by root
/// parameter; the other tables' slots are made from the title's.
///
/// Within a list, the same table holding the same descriptors is made
/// once: its constant data is copied at submission either way, and the
/// big tables the world binds would otherwise take hundreds of slots per
/// draw, wrapping the dynamic slots onto lists not yet submitted.
fn tables(&mut self, list: &HostList, used: &[UsedResource], compute: bool) -> Vec<(u8, u32)> {
let tables = |u: &&UsedResource| u.root == RootType::Table;
let mut fresh: Vec<u8> = used
.iter()
.filter(tables)
.filter(|u| u.kind == ResourceType::Cbv)
.map(|u| u.slot)
.collect();
fresh.sort_unstable();
fresh.dedup();
for u in used.iter().filter(tables) {
if !fresh.contains(&u.slot) {
self.table_entry(list, u, compute);
}
}
let mut made = Vec::new();
for slot in fresh {
let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else {
continue;
};
let entries: Vec<&UsedResource> = used
.iter()
.filter(tables)
.filter(|u| u.slot == slot)
.collect();
let Some(heap) = self.heap_of(table) else {
continue;
};
let Some(host) = heap.host() else {
continue;
};
let n = entries
.iter()
.map(|u| u.table_offset_dwords / 8 + 1)
.max()
.unwrap_or(1);
// The table and what its entries hold (record words).
let key = {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
for k in 0..n {
let at = table + u64::from(k) * 32;
// SAFETY: a descriptor slot in title memory.
unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h);
}
(table, h.finish())
};
if let Some(&first) = self.fresh_tables.get(&key) {
for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) {
let handle = table + u64::from(u.table_offset_dwords) * 4;
if let Some(view) = crate::descriptor::view(handle) {
readable(list, u, &view);
}
}
made.push((slot, first * 32));
continue;
}
let Some(first) = host.dynamic(n) else {
continue;
};
self.fresh_tables.insert(key, first);
self.dynamic
.push((std::ptr::from_ref(heap) as usize, first, n));
// The whole range: a shader may index past the entries its
// used-resource list names (descriptor arrays).
for k in 0..n {
let index = first + k;
let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k);
match crate::descriptor::view(table + u64::from(k) * 32) {
Some(View::Constant(address, size)) => {
let Some((gpu, to)) = list.scratch(u64::from(size)) else {
host.make_null(index);
continue;
};
list.defer_fill(to, address as *const u8, size as usize);
host.constant_at(index, gpu, size);
}
Some(view) => {
host.make_at(index, &view);
if let Some(u) = used {
readable(list, u, &view);
}
}
None => {
host.make_null(index);
if used.is_some() {
once!(slot, "a table entry without a view");
}
}
}
}
made.push((slot, first * 32));
}
made
}
/// The first draws, at debug level: what they bind and read
/// (diagnostics builds).
#[cfg(feature = "diagnostics")]
fn trace(&self, kind: &str, count: u32, first: u32) {
static TRACED: AtomicU64 = AtomicU64::new(0);
if !tracing::enabled!(tracing::Level::DEBUG) {
return;
}
let listed = crate::capture::listed(crate::queue::presented() + 1);
let logged = listed || TRACED.fetch_add(1, Ordering::Relaxed) < 64;
let targets: Vec<String> = self
.targets
.iter()
.filter_map(|&t| crate::resource::host_resource(t as This))
.map(|t| {
// SAFETY: a live resource.
let d = unsafe { t.GetDesc() };
format!("{}x{} f{}", d.Width, d.Height, d.Format.0)
})
.collect();
let v = self.vertex[0];
let line = format!(
"{kind} {count} from {first} topology {} pipeline {:#x} targets {targets:?} vb {:#x}+{} stride {} reads {:?}",
self.topology,
self.pipeline,
v.address,
v.size,
v.stride,
self.reads(false)
);
if logged {
tracing::debug!("draw {line}");
}
let mut frame = FRAME.lock().unwrap_or_else(|e| e.into_inner());
if frame.len() < 256 {
frame.push(line);
}
}
/// What a draw's shaders read, one line per used resource (diagnostics
/// builds).
#[cfg(feature = "diagnostics")]
fn reads(&self, compute: bool) -> Vec<String> {
let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
return vec!["no host pipeline".into()];
};
let mut out = Vec::new();
for stage in &p.stages {
let t = stage.translated();
for u in &t.used {
let what = match (u.root, self.roots_ref(compute).get(usize::from(u.slot))) {
(RootType::Table, Some(Root::Table(table))) => {
let handle = table + u64::from(u.table_offset_dwords) * 4;
describe(crate::descriptor::view(handle).as_ref())
}
(root, _) => format!("{root:?}"),
};
out.push(format!(
"{} {:?} s{}+{}: {what}",
stage.shader.hash, u.kind, u.slot, u.table_offset_dwords
));
}
}
out
}
pub(crate) fn draw(
&mut self,
list: &HostList,
vertices: u32,
instances: u32,
first: u32,
first_instance: u32,
) {
#[cfg(feature = "diagnostics")]
self.trace("draw", vertices, first);
let rects = self.topology == RECTANGLES;
let ran = self.prepare(list, false) && (!rects || self.rectangles(list, vertices, first));
if ran {
// Rectangles were expanded into their own vertex buffers.
let (count, from) = if rects {
(vertices / 3 * 6, 0)
} else {
(vertices, first)
};
#[cfg(feature = "diagnostics")]
list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false));
// SAFETY: an open list with everything set.
unsafe {
list.list
.DrawInstanced(count, instances, from, first_instance)
};
DRAWN.fetch_add(1, Ordering::Relaxed);
}
#[cfg(feature = "diagnostics")]
if !ran {
dropped();
}
}
/// Binds vertex buffers holding the rectangles of vertices `first..first
/// + count` as triangles, made when the list is submitted.
fn rectangles(&self, list: &HostList, count: u32, first: u32) -> bool {
let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
return false;
};
let rects = u64::from(count / 3);
for slot in 0..32 {
let elements: Vec<(u32, u32)> = p
.inputs
.iter()
.filter(|e| e.slot == slot && !e.per_instance)
.map(|e| (e.offset, e.format))
.collect();
if elements.is_empty() {
continue;
}
let v = self.vertex[slot as usize];
let stride = u64::from(v.stride);
let from = v.address + u64::from(first) * stride;
if v.address == 0
|| stride == 0
|| u64::from(first + count) * stride > u64::from(v.size)
|| crate::shadow::find(from, rects * 3 * stride).is_none()
{
once!(slot, "rectangle vertices outside their buffer");
return false;
}
let Some((gpu, to)) = list.scratch(rects * 6 * stride) else {
return false;
};
let (from, to, stride) = (from as usize, to as usize, stride as usize);
let n = rects as usize;
list.defer_host(move || {
// SAFETY: the vertices lie in a title buffer (checked when
// recorded) and the scratch memory is the list's.
let (src, dst) = unsafe {
(
std::slice::from_raw_parts(from as *const u8, n * 3 * stride),
std::slice::from_raw_parts_mut(to as *mut u8, n * 6 * stride),
)
};
crate::primitive::expand_rects(src, dst, stride, &elements);
});
let view = D3D12_VERTEX_BUFFER_VIEW {
BufferLocation: gpu,
SizeInBytes: (rects * 6 * stride as u64) as u32,
StrideInBytes: v.stride,
};
// SAFETY: an open list; the view names live scratch memory.
unsafe { list.list.IASetVertexBuffers(slot, Some(&[view])) };
}
true
}
pub(crate) fn draw_indexed(
&mut self,
list: &HostList,
indices: u32,
instances: u32,
first: u32,
base: i32,
first_instance: u32,
) {
#[cfg(feature = "diagnostics")]
self.trace("indexed", indices, first);
if self.topology == RECTANGLES {
once!("indexed rectangles not drawn");
}
let ran = self.topology != RECTANGLES && self.prepare(list, true);
if ran {
#[cfg(feature = "diagnostics")]
list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false));
// SAFETY: an open list with everything set.
unsafe {
list.list
.DrawIndexedInstanced(indices, instances, first, base, first_instance)
};
DRAWN.fetch_add(1, Ordering::Relaxed);
}
#[cfg(feature = "diagnostics")]
if !ran {
dropped();
}
}
}
/// Gets what a shader reads or writes through a view ready: buffer data
/// copied, textures moved to the state they need.
fn readable(list: &HostList, u: &UsedResource, view: &View) {
const SHADER_RESOURCE: u32 = 0x40 | 0x80;
const UNORDERED_ACCESS: u32 = 0x8;
let placed = crate::descriptor::host::placed_texture(view);
let view = placed.as_ref().unwrap_or(view);
// Buffer views read title memory: their range is copied at submission;
// what shaders write through unordered access goes back to it after.
if let Some((address, len)) = crate::descriptor::host::buffer_range(view)
&& len > 0
&& let Some(shadow) = crate::shadow::find(address, len)
{
shadow.refresh(list, address, len);
if u.kind == ResourceType::Uav {
shadow.gpu_writes(list, address, len);
}
}
match (view, u.kind) {
(View::Shader(resource, _), ResourceType::Srv) => {
if let Some(t) = crate::resource::host_resource(*resource as This)
&& crate::texture::title_written(t)
{
crate::texture::upload(list, *resource as This, t);
}
crate::list::ensure_state(list, *resource as This, SHADER_RESOURCE);
#[cfg(feature = "diagnostics")]
if let Some(t) = crate::resource::host_resource(*resource as This) {
// SAFETY: a live resource.
let d = unsafe { t.GetDesc() };
if d.Flags.0 & 7 == 0 {
tracing::debug!(
resource = format_args!("{resource:#x}"),
?d,
"a shader reads a texture the title fills"
);
}
}
}
(View::Unordered(resource, _, _), ResourceType::Uav) => {
#[cfg(feature = "diagnostics")]
crate::capture::note_target(*resource as This);
crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS);
}
_ => {}
}
}
/// A view in a few words (diagnostics builds).
#[cfg(feature = "diagnostics")]
fn describe(view: Option<&View>) -> String {
let texture = |r: This| {
crate::resource::host_resource(r).map(|t| {
// SAFETY: a live resource.
let d = unsafe { t.GetDesc() };
format!("{}x{} f{} flags {:#x}", d.Width, d.Height, d.Format.0, d.Flags.0)
})
};
match view {
None => "no view".into(),
Some(v @ View::Shader(r, _)) => texture(*r as This)
.unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))),
Some(View::Unordered(r, ..)) => format!("uav {:?}", texture(*r as This)),
Some(View::Placed(u, r, d)) => format!(
"placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}",
r[0],
u64::from(r[4]) | u64::from(r[5]) << 32,
r[6],
r[8],
r[11],
u64::from(d[10]) | u64::from(d[11]) << 32
),
// The first four values, as a colour rectangle's constants are.
Some(View::Constant(address, size))
if *size >= 16 && crate::texture::committed(*address as *const u8, 16) =>
{
// SAFETY: 16 committed bytes of title memory.
let v = unsafe { (*address as *const [f32; 4]).read_unaligned() };
format!("Constant({address:#x}, {size}) {v:?}")
}
Some(v) => format!("{v:?}").chars().take(60).collect(),
}
}
/// The console's own primitive topologies.
const TRIANGLE_FAN: u32 = 6;
const RECTANGLES: u32 = 17;
const LINE_LOOP: u32 = 18;
const QUADS: u32 = 19;
const QUAD_STRIP: u32 = 20;
/// Fixed-function state, straight onto the host list.
pub(crate) fn viewports(list: &HostList, viewports: &[D3D12_VIEWPORT]) {
// SAFETY: an open list.
unsafe { list.list.RSSetViewports(viewports) };
}
pub(crate) fn scissors(list: &HostList, rects: &[RECT]) {
// SAFETY: an open list.
unsafe { list.list.RSSetScissorRects(rects) };
}
pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) {
// SAFETY: an open list.
unsafe { list.list.OMSetBlendFactor(factor) };
}
pub(crate) fn stencil_ref(list: &HostList, reference: u32) {
// SAFETY: an open list.
unsafe { list.list.OMSetStencilRef(reference) };
}
+67 -15
View File
@@ -4,8 +4,8 @@
#![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,
self, ADAPTER, DXGI_DEVICE, E_INVALIDARG, FACTORY, HRESULT, Iid, MORE_DATA, NOT_FOUND, OUTPUT,
Object, S_OK, Table, This, guid,
};
/// The DXGI device interfaces, base first (as on PC).
@@ -132,7 +132,6 @@ struct AdapterDescription {
const _: () = assert!(size_of::<AdapterDescription>() == 0x130);
const AMD: u32 = 0x1002;
const GIB: usize = 1 << 30;
extern "system" fn adapter_description(_: This, out: *mut AdapterDescription) -> HRESULT {
if out.is_null() {
@@ -142,17 +141,18 @@ extern "system" fn adapter_description(_: This, out: *mut AdapterDescription) ->
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.
// shortcut: memory sizes are the title's split (GPU-optimal, standard),
// not measured; revisit once memory is emulated.
let (gpu_optimal, standard) = crate::console::current().title_memory();
let description = AdapterDescription {
name,
vendor: AMD,
device: 0,
subsystem: 0,
revision: 0,
dedicated_video_memory: 10 * GIB,
dedicated_video_memory: gpu_optimal,
dedicated_system_memory: 0,
shared_system_memory: 7 * GIB / 2,
shared_system_memory: standard,
luid: [1, 0],
};
// SAFETY: checked non-null; the title passes room for the description.
@@ -178,8 +178,8 @@ extern "system" fn output_parent(_: This, iid: *const Iid, out: *mut This) -> HR
}
/// IUnknown 3, object 4, device 5 + 2 + 3.
static DEVICE_FUNCTIONS: Table<17> = {
let mut f = object::missing_table::<DXGI_DEVICE, 17>();
static DEVICE_FUNCTIONS: Table<32> = {
let mut f = object::missing_table::<DXGI_DEVICE, 32>();
f[0] = device_query as *const ();
f[6] = device_parent as *const (); // 0x30
f[7] = device_adapter as *const (); // 0x38
@@ -187,8 +187,8 @@ static DEVICE_FUNCTIONS: Table<17> = {
};
/// IUnknown 3, object 4, adapter 3 + 1 + 1.
static ADAPTER_FUNCTIONS: Table<12> = {
let mut f = object::missing_table::<ADAPTER, 12>();
static ADAPTER_FUNCTIONS: Table<24> = {
let mut f = object::missing_table::<ADAPTER, 24>();
f[0] = adapter_query as *const ();
f[6] = adapter_parent as *const (); // 0x30
f[7] = adapter_outputs as *const (); // 0x38
@@ -197,19 +197,71 @@ static ADAPTER_FUNCTIONS: Table<12> = {
};
/// IUnknown 3, object 4, factory 5 + 2 + 11.
static FACTORY_FUNCTIONS: Table<25> = {
let mut f = object::missing_table::<FACTORY, 25>();
static FACTORY_FUNCTIONS: Table<32> = {
let mut f = object::missing_table::<FACTORY, 32>();
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)
};
/// A display mode as the console lists it: size, refresh rate (numerator,
/// denominator), format, scanline order, scaling, flags.
#[repr(C)]
struct Mode {
width: u32,
height: u32,
refresh: [u32; 2],
format: u32,
scanlines: u32,
scaling: u32,
flags: u32,
}
const _: () = assert!(size_of::<Mode>() == 32);
/// The console's mode list: one 4K mode at 60 Hz (Grand Theft Auto VI looks
/// for a 120 Hz one to allow 120 Hz frame intervals).
/// shortcut: fixed mode, not the host display's; report the host's rates if
/// a title paces by them.
extern "system" fn modes(
_: This,
_format: u32,
_flags: u32,
count: *mut u32,
out: *mut Mode,
) -> HRESULT {
// SAFETY: the title passes its count (null is tolerated).
let Some(count) = (unsafe { count.as_mut() }) else {
return E_INVALIDARG;
};
if out.is_null() {
*count = 1;
return S_OK;
}
if *count < 1 {
return MORE_DATA;
}
*count = 1;
let mode = Mode {
width: 3840,
height: 2160,
refresh: [60, 1],
format: 0,
scanlines: 1, // progressive
scaling: 0,
flags: 0,
};
// SAFETY: checked non-null; room for `count` >= 1 modes.
unsafe { out.write(mode) };
S_OK
}
/// 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::<OUTPUT, 22>();
static OUTPUT_FUNCTIONS: Table<32> = {
let mut f = object::missing_table::<OUTPUT, 32>();
f[0] = output_query as *const ();
f[6] = output_parent as *const (); // 0x30
f[21] = modes as *const (); // 0xa8
Table(f)
};
+22 -3
View File
@@ -24,7 +24,10 @@ pub(crate) const FENCE_IIDS: [Iid; 4] = [
#[repr(C)]
struct Fence {
object: Object,
/// Titles also read it straight from memory, at the fence's GPU
/// address.
value: AtomicU64,
flags: u32,
/// Events to set once the value reaches theirs (handles as integers).
waiters: Mutex<Vec<(u64, usize)>>,
}
@@ -45,6 +48,7 @@ pub(crate) extern "system" fn create(
let fence = Box::new(Fence {
object: Object::new(&FUNCTIONS),
value: AtomicU64::new(initial),
flags,
waiters: Mutex::new(Vec::new()),
});
object::hand_out(FENCE, fence, iid, &FENCE_IIDS, out)
@@ -106,15 +110,26 @@ pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
S_OK
}
/// IUnknown 3, object 4, device child 1, fence 3.
static FUNCTIONS: Table<11> = {
let mut f = object::d3d12_object(object::missing_table::<FENCE, 11>());
extern "system" fn creation_flags(this: This) -> u32 {
fence(this).flags
}
/// Where the value lives (GPU addresses are CPU addresses).
extern "system" fn gpu_address(this: This) -> u64 {
(&raw const fence(this).value) as u64
}
/// IUnknown 3, object 4, device child 1, fence 3, fence 1 (2, a console
/// one among them).
static FUNCTIONS: Table<24> = {
let mut f = object::d3d12_object(object::missing_table::<FENCE, 24>());
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
f[11] = creation_flags as *const (); // 0x58
f[12] = gpu_address as *const (); // 0x60
Table(f)
};
@@ -147,6 +162,10 @@ mod tests {
// SAFETY: as above.
assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0);
assert_eq!(wait(f, 9, std::ptr::null_mut()), E_NOTIMPL);
// Grand Theft Auto VI reads the value at the fence's address.
let at = slot::<extern "system" fn(This) -> u64>(f, 0x60)(f);
// SAFETY: the fence's value.
assert_eq!(unsafe { *(at as *const u64) }, 5);
// SAFETY: ours.
unsafe { CloseHandle(event) };
assert_eq!(slot::<extern "system" fn(This) -> u32>(f, 0x10)(f), 0);
+119 -32
View File
@@ -1,25 +1,35 @@
//! 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.
//! once per interval; the token is the frame number. Each event kind
//! (origin, vblank, flip) happens once per tick, so two waits for the same
//! kind never end on the same tick: Grand Theft Auto VI polls the origin
//! with "token on time-out" (starting its next frame at once) and is paced
//! by a blocking wait for the flip before each present.
//!
//! 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.
//! shortcut: event offsets are ignored (every event is at the tick); tie
//! the clock to presentation if a title paces by them.
#![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};
use crate::object::{HRESULT, S_FALSE, S_OK, This};
/// `HRESULT_FROM_WIN32(WAIT_TIMEOUT)`.
const TIMEOUT: HRESULT = 0x8007_0102_u32 as i32;
/// What a wait returns when its time is up first.
const TIMEOUT: HRESULT = S_FALSE;
/// The frame-origin event: the one that starts frames and makes tokens.
const ORIGIN: u32 = 0;
/// Make the frame's token even if the wait times out (the title starts the
/// frame early).
const TOKEN_ON_TIMEOUT: u32 = 2;
const SIXTIETH: Duration = Duration::from_micros(16_667);
struct Clock {
start: Instant,
interval: Duration,
/// The tick number at `start` (ticks go on across interval changes).
first: u64,
}
static CLOCK: Mutex<Option<Clock>> = Mutex::new(None);
@@ -29,29 +39,32 @@ fn clock() -> std::sync::MutexGuard<'static, Option<Clock>> {
CLOCK.lock().unwrap_or_else(|e| e.into_inner())
}
/// Device method: `periods` intervals of `length` microseconds per frame.
/// Device method: a frame every `length` microseconds. The period is how
/// many intervals a frame may take to reach the display (pipeline depth),
/// not part of the rate.
pub(crate) extern "system" fn set_interval(
_: This,
_output: This,
length: u32,
periods: u32,
_period: u32,
_flags: u32,
) -> HRESULT {
let interval = match u64::from(length) * u64::from(periods.max(1)) {
let interval = match length {
0 => SIXTIETH,
us => Duration::from_micros(us),
us => Duration::from_micros(u64::from(us)),
};
tracing::info!(?interval, "frame interval");
let mut clock = clock();
match clock.as_mut() {
Some(c) => c.interval = interval,
None => {
*clock = Some(Clock {
// A new interval starts from now, after the last tick handed out.
let first = LAST
.iter()
.map(|t| t.load(Ordering::Relaxed))
.max()
.unwrap_or(0);
*clock() = Some(Clock {
start: Instant::now(),
interval,
})
}
}
first,
});
S_OK
}
@@ -66,42 +79,84 @@ pub(crate) extern "system" fn schedule(
S_OK
}
/// How long until the next tick.
fn until_next_tick() -> Duration {
/// Frames begun so far (frame waits that ended).
pub(crate) fn current() -> u64 {
FRAME.load(Ordering::Relaxed)
}
/// Per event kind (origin, vblank, flip and later kinds): the last tick a
/// wait for it ended on.
static LAST: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
fn last(kind: u32) -> &'static AtomicU64 {
&LAST[(kind as usize).min(LAST.len() - 1)]
}
/// The next tick after now and after the last one a wait for `kind` ended
/// on (an event happens once per tick: a wait woken a little early must not
/// let the next one end on the same tick), and how long until it.
fn next_tick(kind: u32) -> (u64, Duration) {
let mut clock = clock();
let c = clock.get_or_insert_with(|| Clock {
start: Instant::now(),
interval: SIXTIETH,
first: 0,
});
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)
let tick =
(c.first + (elapsed / interval + 1) as u64).max(last(kind).load(Ordering::Relaxed) + 1);
let at = u128::from(tick - c.first) * interval;
(
tick,
Duration::from_nanos(at.saturating_sub(elapsed) as u64),
)
}
/// Device method: blocks until the next tick, then hands out the frame's
/// token.
/// Device method: blocks until the next tick (or the time-out); an origin
/// wait then hands out the new frame's token. Other events keep the token
/// the title passes. Ticks are absolute (start plus whole intervals), so
/// lateness never accumulates.
pub(crate) extern "system" fn wait(
_: This,
_kind: u32,
kind: u32,
timeout_ms: u32,
_list: *const u8,
_flags: u32,
flags: u32,
token: *mut u64,
) -> HRESULT {
let wait = until_next_tick();
let origin = kind == ORIGIN;
let (tick, wait) = next_tick(kind);
let limit = Duration::from_millis(u64::from(timeout_ms));
if wait > limit {
let hr = if wait > limit {
std::thread::sleep(limit);
return TIMEOUT;
}
TIMEOUT
} else {
std::thread::sleep(wait);
last(kind).fetch_max(tick, Ordering::Relaxed);
S_OK
};
// A frame begun on a time-out takes no tick: its flip still does.
if origin && (hr == S_OK || flags & TOKEN_ON_TIMEOUT != 0) {
// Tokens count frames (consecutive), not ticks.
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
}
#[cfg(feature = "diagnostics")]
tracing::debug!(
kind,
timeout_ms,
flags,
hr,
tick,
wait_us = wait.as_micros() as u64,
frame = current(),
"frame wait"
);
hr
}
/// Device method: no statistics are kept, so none are returned.
@@ -135,5 +190,37 @@ mod tests {
assert!(second > first);
assert!(before.elapsed() <= Duration::from_millis(50));
assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT);
// Tokens count frames, a frame started early on a time-out too.
let mut early = 0;
let flags = TOKEN_ON_TIMEOUT;
assert_eq!(
wait(null, 0, 0, std::ptr::null(), flags, &mut early),
TIMEOUT
);
let mut next = 0;
assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut next), S_OK);
assert!(early == second + 1 && next == early + 1);
assert!(LAST[0].load(Ordering::Relaxed) >= 2);
// The title's loop (the clock is global, so in the same test): an
// origin poll that times out (and starts the frame), then a
// blocking flip wait. Each flip takes its own tick.
const FLIP: u32 = 2;
assert_eq!(set_interval(null, null, 5_000, 3, 0), S_OK);
let mut token = 0;
let flips: Vec<u64> = (0..4)
.map(|_| {
let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token);
assert_eq!(
wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token),
S_OK
);
LAST[2].load(Ordering::Relaxed)
})
.collect();
assert!(flips.windows(2).all(|w| w[1] == w[0] + 1), "{flips:?}");
// Even when a flip wait begins on the tick another just ended on.
let (tick, _) = next_tick(FLIP);
assert!(tick > flips[3]);
}
}
File diff suppressed because it is too large. Load diff
+26 -1
View File
@@ -12,10 +12,18 @@
//! 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).
//! share, [`console`] which console model the title sees. Planned:
//! `present` (swap chain).
#[cfg(all(windows, feature = "diagnostics"))]
mod capture;
pub mod console;
#[cfg(all(windows, feature = "diagnostics"))]
mod copystat;
pub mod descriptor;
pub mod device;
#[cfg(windows)]
mod draw;
pub mod dxgi;
pub mod fence;
pub mod frame;
@@ -24,8 +32,25 @@ mod host;
pub mod list;
pub mod object;
pub mod pipeline;
#[cfg(windows)]
mod primitive;
pub mod query;
pub mod queue;
pub mod resource;
pub mod root;
#[cfg(windows)]
mod sampler;
#[cfg(windows)]
pub mod shader_cache;
#[cfg(windows)]
mod shadow;
pub mod signature;
#[cfg(windows)]
mod texture;
#[cfg(windows)]
mod watch;
#[cfg(windows)]
pub use host::on_failure;
#[cfg(windows)]
pub use watch::{title_memory_remapped, writing as kernel_will_write};
+725 -48
View File
@@ -5,9 +5,9 @@
//! 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).
//! Each list records onto a host command list as its methods are called
//! (decision 0007); draw state lives in [`crate::draw`]. Methods not
//! written yet log once with their caller, so a run lists what to do next.
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::mem::offset_of;
@@ -15,6 +15,7 @@ use std::mem::offset_of;
use crate::object::{
self, ALLOCATOR, E_INVALIDARG, HRESULT, Iid, LIST, Object, S_OK, Table, This, guid,
};
use crate::queue::Written;
use crate::resource::PAGEABLE_IIDS;
const ALLOCATOR_IIDS: [Iid; 4] = [
@@ -29,9 +30,11 @@ const ALLOCATOR_IIDS: [Iid; 4] = [
PAGEABLE_IIDS[2],
];
/// The list interfaces whose ids are the same as on PC, then the device
/// child's.
const LIST_IIDS: [Iid; 8] = [
/// The list interfaces up to `ID3D12GraphicsCommandList6` (the table has
/// all their slots): those whose ids are the same as on PC, the console's
/// own List5 and List6 (Grand Theft Auto VI asks for List6), then the
/// device child's.
const LIST_IIDS: [Iid; 10] = [
guid(
0x7116d91c,
0xe7e4,
@@ -68,6 +71,18 @@ const LIST_IIDS: [Iid; 8] = [
0x4541,
[0x98, 0xcf, 0x64, 0x5b, 0x50, 0xdc, 0x48, 0x74],
),
guid(
0x55050859,
0x4024,
0x474c,
[0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74],
),
guid(
0xc3827890,
0x4024,
0x474c,
[0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74],
),
PAGEABLE_IIDS[1],
PAGEABLE_IIDS[2],
];
@@ -91,14 +106,33 @@ struct List {
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).
/// Newer titles' lists are larger: Grand Theft Auto VI's state flush
/// (title+0x32786) copies a pipeline's 32 bytes to +0x544..+0x564 and
/// tests +0x548, so its layout runs past 0x560. Its size is unknown;
/// this keeps our fields clear of whatever the title writes there.
newer: [u32; 256],
/// Ours, after the console layout: memory handed out by
/// [`allocate_upload`], kept until the list is reset; the host list the
/// calls record into (decision 0007), and the draw state the title set.
uploads: std::sync::Mutex<Vec<Vec<u8>>>,
#[cfg(windows)]
host: Option<crate::host::HostList>,
#[cfg(windows)]
state: std::sync::Mutex<crate::draw::State>,
}
const _: () = assert!(offset_of!(List, put) == 0x18);
const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560);
/// Runs `f` with the host list and draw state of a title list, if there
/// is a host GPU.
#[cfg(windows)]
fn with_state(this: This, f: impl FnOnce(&crate::host::HostList, &mut crate::draw::State)) {
let Some(list) = host_list(this) else { return };
// SAFETY: the title passes one of our lists.
let state = unsafe { &(*this.cast::<List>()).state };
f(list, &mut state.lock().unwrap_or_else(|e| e.into_inner()));
}
/// 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> {
@@ -168,13 +202,19 @@ fn new_list(kind: u32, allocator: This, iid: *const Iid, out: *mut This) -> HRES
}
tracing::debug!(kind, "command list");
let list = Box::new(List {
object: Object::new(&LIST_FUNCTIONS),
object: if crate::device::newer() {
Object::new(&NEWER_LIST_FUNCTIONS)
} else {
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],
newer: [0; 256],
uploads: Default::default(),
#[cfg(windows)]
host: crate::host::host().and_then(|h| match h.new_list() {
Ok(list) => Some(list),
@@ -183,6 +223,8 @@ fn new_list(kind: u32, allocator: This, iid: *const Iid, out: *mut This) -> HRES
None
}
}),
#[cfg(windows)]
state: Default::default(),
});
object::hand_out(LIST, list, iid, &LIST_IIDS, out)
}
@@ -216,14 +258,21 @@ extern "system" fn close(this: This) -> HRESULT {
}
S_OK
}
extern "system" fn reset(this: This, allocator: This, _pipeline: This) -> HRESULT {
extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT {
if allocator.is_null() {
return E_INVALIDARG;
}
// Every submission of the list has run (submissions are waited for).
// SAFETY: the title passes one of our lists.
let uploads = unsafe { &(*this.cast::<List>()).uploads };
uploads.lock().unwrap_or_else(|e| e.into_inner()).clear();
#[cfg(windows)]
if let Some(host) = host_list(this) {
with_state(this, |host, state| {
host.reset();
}
state.reset(pipeline);
});
#[cfg(not(windows))]
let _ = (this, pipeline);
S_OK
}
@@ -243,7 +292,7 @@ pub(crate) struct Barrier {
/// 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<Barrier> {
fn host_barrier(list: &crate::host::HostList, b: &Barrier) -> Option<Barrier> {
use windows::core::Interface;
let host = |r: This| crate::resource::host_resource(r).map(|h| h.as_raw().cast_const().cast());
match b.kind {
@@ -253,16 +302,16 @@ fn host_barrier(b: &Barrier) -> Option<Barrier> {
if b.flags & BEGIN_ONLY != 0 {
return None;
}
// shortcut: whole resources, from the state we tracked (see
// `host_transition`); subresources are not told apart.
// shortcut: whole resources, from the state the list tracked
// (`HostList::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)?;
let (texture, before) = list.transition(b.first, wanted)?;
Some(Barrier {
kind: 0,
flags: 0,
first: resource.cast_const().cast(),
first: texture.as_raw().cast_const().cast(),
second: 0xffff_ffff | (u64::from(before) << 32),
last: u64::from(wanted),
last: u64::from(crate::host::legal_state(texture, wanted)),
})
}
1 => Some(Barrier {
@@ -290,6 +339,16 @@ fn host_barrier(b: &Barrier) -> Option<Barrier> {
}
}
/// An unordered access barrier on every resource: earlier shader writes
/// finish before later work reads or writes.
const UAV_BARRIER: Barrier = Barrier {
kind: 2,
flags: 0,
first: std::ptr::null(),
second: 0,
last: 0,
};
/// Returns the console's barrier "actions" (none).
extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 {
#[cfg(windows)]
@@ -298,7 +357,17 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) ->
{
// SAFETY: the title passes `count` barriers.
let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) };
let host: Vec<Barrier> = barriers.iter().filter_map(host_barrier).collect();
let mut host: Vec<Barrier> = barriers
.iter()
.filter_map(|b| host_barrier(list, b))
.collect();
// Buffers have host copies, not resources the barrier can name:
// a barrier on one waits for every shader write before it.
if barriers.iter().any(|b| {
b.kind != 1 && !b.first.is_null() && crate::resource::buffer_bytes(b.first).is_some()
}) {
host.push(UAV_BARRIER);
}
if !host.is_empty() {
use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
const _: () = assert!(size_of::<Barrier>() == size_of::<D3D12_RESOURCE_BARRIER>());
@@ -319,11 +388,10 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) ->
/// 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) {
pub(crate) 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)
{
if let Some((texture, before)) = list.transition(resource, state) {
let state = crate::host::legal_state(texture, 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]) };
@@ -380,6 +448,9 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) {
) {
ensure_state(list, dst, COPY_DEST);
ensure_state(list, src, COPY_SOURCE);
crate::texture::host_written(dst);
#[cfg(feature = "diagnostics")]
list.note_op(|| format!("copy resource {src:?} to {dst:?}"));
// SAFETY: an open list and live textures.
unsafe { list.list.CopyResource(to, from) };
} else if let (Some((to, a)), Some((from, b))) = (
@@ -461,9 +532,26 @@ extern "system" fn copy_texture_region(
from.resource = texture.as_raw().cast_const().cast();
}
ensure_state(list, dst.resource, COPY_DEST);
crate::texture::host_written(dst.resource);
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::<D3D12_BOX>());
#[cfg(feature = "diagnostics")]
list.note_op(|| {
// SAFETY: a live texture; the box is the title's or null.
let (d, b) = unsafe { (to.GetDesc(), host_box.map(|b| *b)) };
format!(
"copy to {:?} {}x{} f{} sub/kind {} at {x},{y},{z} from {:?} kind {} footprint {:?} box {b:?}",
dst.resource,
d.Width,
d.Height,
d.Format.0,
dst.kind,
src.resource,
src.kind,
(src.kind == FOOTPRINT).then_some(src.footprint)
)
});
const _: () =
assert!(size_of::<CopyLocation>() == size_of::<D3D12_TEXTURE_COPY_LOCATION>());
// SAFETY: an open list; both locations in the host's layout, naming
@@ -522,6 +610,9 @@ extern "system" fn resolve(
const RESOLVE_SOURCE: u32 = 0x2000;
ensure_state(list, dst, RESOLVE_DEST);
ensure_state(list, src, RESOLVE_SOURCE);
crate::texture::host_written(dst);
#[cfg(feature = "diagnostics")]
list.note_op(|| format!("resolve {src:?} to {dst:?} format {format}"));
// SAFETY: an open list and live textures; the region is inside both.
unsafe {
let (a, b) = (to.GetDesc(), from.GetDesc());
@@ -594,9 +685,7 @@ extern "system" fn clear_rtv(
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)
{
if let Some((_, before)) = list.transition(record.resource, RENDER_TARGET) {
use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
list.list.ResourceBarrier(&[crate::host::transition(
texture,
@@ -611,9 +700,137 @@ extern "system" fn clear_rtv(
let _ = (this, handle, color, count, rects);
}
/// `ClearDepthStencilView(handle, flags, depth, stencil, count, rects)`;
/// flags: 1 depth, 2 stencil.
extern "system" fn clear_dsv(
this: This,
handle: u64,
flags: u32,
depth: f32,
stencil: u8,
count: u32,
rects: *const Rect,
) {
#[cfg(windows)]
{
use windows::Win32::Graphics::Direct3D12::D3D12_CLEAR_FLAGS;
let (Some(list), Some(record)) = (host_list(this), crate::descriptor::dsv_record(handle))
else {
return;
};
let (Some(texture), Some(host)) = (
crate::resource::host_resource(record.resource),
crate::host::host(),
) 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 DEPTH_WRITE: u32 = 0x10;
ensure_state(list, record.resource, DEPTH_WRITE);
let dsv = host.dsv(texture, record.depth_desc().as_ref());
// SAFETY: an open list, a fresh view of a live texture.
unsafe {
list.list
.ClearDepthStencilView(dsv, D3D12_CLEAR_FLAGS(flags as i32 & 3), depth, stencil, rects)
};
}
#[cfg(not(windows))]
let _ = (this, handle, flags, depth, stencil, count, rects);
}
/// `CopyMemoryToMemoryX(destination, source, size, flags)`: GPU addresses
/// are title memory, copied at submission like buffer copies (if mapped).
extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags: u32) {
#[cfg(windows)]
if let Some(list) = host_list(this)
&& dst != 0
&& src != 0
{
let len = len as usize;
list.defer(move || {
if crate::texture::committed(src as *const u8, len)
&& crate::texture::committed(dst as *const u8, len)
{
// SAFETY: both ranges are committed title memory.
unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len) };
}
});
}
#[cfg(not(windows))]
let _ = (this, dst, src, len);
}
/// `DriverHintX(feature, value)`: no hints for the host.
extern "system" fn driver_hint(_: This, _feature: u64, _value: u64) -> u64 {
0
}
/// `DispatchX(x, y, z, flags)`: a dispatch with console flags, which the
/// host has no use for (the ray-tracing builder dispatches this way).
extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, _flags: u32) {
#[cfg(windows)]
state::dispatch(this, x, y, z);
#[cfg(not(windows))]
{
let _ = (this, x, y, z);
count_dispatch();
}
}
/// `BeginQuery`/`EndQuery(heap, type, index)`: queries are answered when
/// resolved.
extern "system" fn query_mark(_: This, _heap: This, _kind: u32, _index: u32) {}
/// `ResolveQueryData(heap, type, first, count, buffer, offset)`: writes
/// each query's result into the buffer once the list has run. Timestamps
/// (type 2) are the GPU clock then; occlusion counts (0) say a million
/// samples passed and binary occlusion (1) visible, so nothing is culled
/// by a query.
/// shortcut: no query runs on the host GPU; results are plausible values,
/// not measured ones (time spans come out as the submission's length).
extern "system" fn resolve_queries(
this: This,
_heap: This,
kind: u32,
_first: u32,
count: u32,
buffer: This,
offset: u64,
) {
const OCCLUSION: u32 = 0;
const BINARY: u32 = 1;
const TIMESTAMP: u32 = 2;
const PIPELINE_STATISTICS: u32 = 3;
let Some((data, size)) = crate::resource::buffer_bytes(buffer) else {
return;
};
let (what, bytes) = match kind {
OCCLUSION => (Written::Value(1 << 20), 8),
BINARY => (Written::Value(1), 8),
TIMESTAMP => (Written::GpuTimestamp, 8),
PIPELINE_STATISTICS => (Written::Value(0), 88),
_ => (Written::Value(0), 16),
};
if offset + u64::from(count) * bytes > size {
return;
}
for i in 0..u64::from(count) {
// Wider results are written as 8-byte pieces.
for piece in 0..bytes / 8 {
// SAFETY: inside the buffer, checked above.
let at = unsafe { data.add((offset + i * bytes + piece * 8) as usize) };
let what = if piece == 0 { what } else { Written::Value(0) };
defer_write(this, at as u64, what, 8);
}
}
}
/// IUnknown 3, object 4, device child 1, allocator 2.
static ALLOCATOR_FUNCTIONS: Table<10> = {
let mut f = object::d3d12_object(object::missing_table::<ALLOCATOR, 10>());
static ALLOCATOR_FUNCTIONS: Table<24> = {
let mut f = object::d3d12_object(object::missing_table::<ALLOCATOR, 24>());
f[0] = allocator_query as *const ();
f[2] = allocator_release as *const ();
f[7] = object::parent_device as *const (); // 0x38
@@ -622,26 +839,472 @@ static ALLOCATOR_FUNCTIONS: Table<10> = {
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::<LIST, 140>());
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)
};
extern "system" fn set_pipeline(this: This, pipeline: This) {
crate::pipeline::bound(pipeline);
#[cfg(windows)]
with_state(this, |_, state| state.set_pipeline(pipeline));
#[cfg(not(windows))]
let _ = this;
}
/// Pipeline syncs: waits for earlier work and cache flushes, at the top or
/// bottom of the pipe `(flags, control, address, size)`. Host lists order
/// their own work and every submission is waited for, so there is nothing
/// to do.
extern "system" fn sync(_: This, _flags: u32, _control: u32, _address: u64, _size: u64) {}
/// Reset with console flags `(allocator, pipeline, flags)`; the flags only
/// tune the console's command memory.
extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: u32) -> HRESULT {
reset(this, allocator, pipeline)
}
/// Newer lists' 0x4a0 `(size, alignment) -> pointer`: memory the list
/// owns until it is reset, which the CPU writes and the GPU reads at the
/// same address; null on failure. Grand Theft Auto VI's BVH builder puts
/// its instance descriptions there (and wrote through our old
/// `E_NOTIMPL` as a pointer).
extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 {
let align = usize::try_from(alignment).unwrap_or(0).max(16);
let Some(len) = usize::try_from(size).ok().and_then(|s| s.checked_add(align)) else {
return std::ptr::null_mut();
};
if this.is_null() || !align.is_power_of_two() {
return std::ptr::null_mut();
}
let mut block = vec![0u8; len];
let start = block.as_mut_ptr();
// SAFETY: the offset is below `align`, so `size` bytes fit after it.
let at = unsafe { start.add(start.align_offset(align)) };
// SAFETY: the title passes one of our lists.
let uploads = unsafe { &(*this.cast::<List>()).uploads };
// Moving the vector keeps its heap block where it is.
uploads.lock().unwrap_or_else(|e| e.into_inner()).push(block);
at
}
/// Draw state the host has no use for (root signatures: ours come with
/// the pipeline; depth bounds, depth order and shading rate hints): any
/// arguments, nothing returned.
extern "system" fn ignored_state(_: This) {}
/// The title's draw state (decision 0007, step 3), kept for its draws or
/// set on the host list at once. Without a host GPU these do nothing.
#[cfg(windows)]
mod state {
use super::{This, host_list, with_state};
use crate::draw::{IndexView, VertexView};
use windows::Win32::Foundation::RECT;
use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT;
/// `count` items at `items`, or none.
fn items<'a, T>(items: *const T, count: u32) -> &'a [T] {
if items.is_null() || count == 0 {
return &[];
}
// SAFETY: the title passes `count` items.
unsafe { std::slice::from_raw_parts(items, count as usize) }
}
pub(super) extern "system" fn topology(this: This, topology: u32) {
with_state(this, |list, s| s.set_topology(list, topology));
}
pub(super) extern "system" fn viewports(
this: This,
count: u32,
viewports: *const D3D12_VIEWPORT,
) {
if let Some(list) = host_list(this) {
crate::draw::viewports(list, items(viewports, count));
}
}
pub(super) extern "system" fn scissors(this: This, count: u32, rects: *const RECT) {
if let Some(list) = host_list(this) {
crate::draw::scissors(list, items(rects, count));
}
}
pub(super) extern "system" fn blend_factor(this: This, factor: *const [f32; 4]) {
if let Some(list) = host_list(this) {
// SAFETY: the title passes four floats or null.
crate::draw::blend_factor(list, unsafe { factor.as_ref() });
}
}
pub(super) extern "system" fn stencil_ref(this: This, reference: u32) {
if let Some(list) = host_list(this) {
crate::draw::stencil_ref(list, reference);
}
}
pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) {
with_state(this, |_, s| s.set_heaps(items(heaps, count)));
}
pub(super) extern "system" fn compute_table(this: This, slot: u32, handle: u64) {
with_state(this, |_, s| s.set_table(true, slot, handle));
}
pub(super) extern "system" fn graphics_table(this: This, slot: u32, handle: u64) {
with_state(this, |_, s| s.set_table(false, slot, handle));
}
pub(super) extern "system" fn compute_constant(this: This, slot: u32, value: u32, offset: u32) {
with_state(this, |_, s| s.set_constants(true, slot, &[value], offset));
}
pub(super) extern "system" fn graphics_constant(
this: This,
slot: u32,
value: u32,
offset: u32,
) {
with_state(this, |_, s| s.set_constants(false, slot, &[value], offset));
}
pub(super) extern "system" fn compute_constants(
this: This,
slot: u32,
count: u32,
values: *const u32,
offset: u32,
) {
with_state(this, |_, s| {
s.set_constants(true, slot, items(values, count), offset)
});
}
pub(super) extern "system" fn graphics_constants(
this: This,
slot: u32,
count: u32,
values: *const u32,
offset: u32,
) {
with_state(this, |_, s| {
s.set_constants(false, slot, items(values, count), offset)
});
}
/// Root constant buffer, shader resource and unordered access views.
pub(super) extern "system" fn compute_view(this: This, slot: u32, address: u64) {
with_state(this, |_, s| s.set_view(true, slot, address));
}
pub(super) extern "system" fn graphics_view(this: This, slot: u32, address: u64) {
with_state(this, |_, s| s.set_view(false, slot, address));
}
pub(super) extern "system" fn index_buffer(this: This, view: *const IndexView) {
// SAFETY: the title passes a view or null.
with_state(this, |_, s| s.set_index_buffer(unsafe { view.as_ref() }));
}
pub(super) extern "system" fn vertex_buffers(
this: This,
start: u32,
count: u32,
views: *const VertexView,
) {
with_state(this, |_, s| {
s.set_vertex_buffers(start, items(views, count))
});
}
/// `(count, handles, one range, depth)`: with one range, the handles
/// follow the first at the render target view size (128 bytes).
pub(super) extern "system" fn targets(
this: This,
count: u32,
handles: *const u64,
one_range: i32,
depth: *const u64,
) {
let handles: Vec<u64> = if one_range != 0 && !handles.is_null() {
// SAFETY: the title passes the first handle.
let first = unsafe { *handles };
(0..u64::from(count)).map(|i| first + 128 * i).collect()
} else {
items(handles, count).to_vec()
};
// SAFETY: the title passes a handle or null.
let depth = unsafe { depth.as_ref() }.copied().unwrap_or(0);
with_state(this, |list, s| s.set_targets(list, &handles, depth));
}
pub(super) extern "system" fn draw(
this: This,
vertices: u32,
instances: u32,
first: u32,
first_instance: u32,
) {
super::count_draw();
with_state(this, |list, s| {
s.draw(list, vertices, instances, first, first_instance)
});
}
pub(super) extern "system" fn dispatch(this: This, x: u32, y: u32, z: u32) {
super::count_dispatch();
with_state(this, |list, s| s.dispatch(list, x, y, z));
}
/// `DispatchMesh(x, y, z)` (the PC method of List6); the title's mesh
/// programs take `x` groups only.
pub(super) extern "system" fn dispatch_mesh(this: This, x: u32, y: u32, z: u32) {
super::count_draw();
if y * z != 1 {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| tracing::warn!(x, y, z, "a mesh dispatch with y or z groups"));
}
with_state(this, |list, s| s.dispatch_mesh(list, x));
}
/// `DispatchMeshX(x, flags, indirect arguments, payload)`.
/// shortcut: dispatches whose group count is in GPU memory (indirect)
/// are dropped; make them ExecuteIndirect when the title uses them.
pub(super) extern "system" fn dispatch_mesh_x(
this: This,
x: u32,
_flags: u64,
indirect: u64,
_payload: u64,
) {
super::count_draw();
if indirect != 0 {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| tracing::warn!("indirect mesh dispatches dropped"));
return;
}
with_state(this, |list, s| s.dispatch_mesh(list, x));
}
pub(super) extern "system" fn draw_indexed(
this: This,
indices: u32,
instances: u32,
first: u32,
base: i32,
first_instance: u32,
) {
super::count_draw();
with_state(this, |list, s| {
s.draw_indexed(list, indices, instances, first, base, first_instance)
});
}
}
/// Without a host GPU every draw state call is ignored.
#[cfg(not(windows))]
mod state {
pub(super) use super::dispatch;
pub(super) use super::draw;
pub(super) use super::draw as draw_indexed;
pub(super) use super::draw as dispatch_mesh;
pub(super) use super::draw as dispatch_mesh_x;
pub(super) use super::ignored_state as blend_factor;
pub(super) use super::ignored_state as compute_constant;
pub(super) use super::ignored_state as compute_constants;
pub(super) use super::ignored_state as compute_table;
pub(super) use super::ignored_state as compute_view;
pub(super) use super::ignored_state as graphics_constant;
pub(super) use super::ignored_state as graphics_constants;
pub(super) use super::ignored_state as graphics_table;
pub(super) use super::ignored_state as graphics_view;
pub(super) use super::ignored_state as heaps;
pub(super) use super::ignored_state as index_buffer;
pub(super) use super::ignored_state as scissors;
pub(super) use super::ignored_state as stencil_ref;
pub(super) use super::ignored_state as targets;
pub(super) use super::ignored_state as topology;
pub(super) use super::ignored_state as vertex_buffers;
pub(super) use super::ignored_state as viewports;
}
fn count_draw() {
DRAWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
/// Draws of the kinds the host does not run yet (indirect, mesh), and
/// dispatches, counted per frame for the log.
/// shortcut: dropped until their shaders translate (decision 0007).
extern "system" fn draw(_: This) {
count_draw();
}
fn count_dispatch() {
DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
#[cfg(not(windows))]
extern "system" fn dispatch(_: This) {
count_dispatch();
}
static DRAWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static DISPATCHES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Draws (any kind, mesh and indirect included) and compute dispatches
/// recorded since the last call.
pub(crate) fn take_counts() -> (u64, u64) {
use std::sync::atomic::Ordering::Relaxed;
(DRAWS.swap(0, Relaxed), DISPATCHES.swap(0, Relaxed))
}
/// A GPU wait for a memory value `(address, comparison, reference, ...)`.
/// Lists run one after another and to completion, so a value another queue
/// or the CPU has to write first cannot be waited for; nothing to do.
extern "system" fn wait_value(_: This, _address: u64, _comparison: u32, _reference: u64) {}
/// The enhanced barriers `(group count, groups)`: buffer, texture and
/// global barriers with layouts instead of states. Every host use of a
/// title texture (clears, copies) moves its host copy to the state it needs
/// first, so only their ordering matters: one barrier on every shader
/// write (the title's buffer barriers order compute passes).
extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) {
#[cfg(windows)]
if count > 0
&& let Some(list) = host_list(this)
{
use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
// SAFETY: the same layout; no resource named.
let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) };
// SAFETY: an open list.
unsafe { list.list.ResourceBarrier(&[barrier]) };
}
#[cfg(not(windows))]
let _ = (this, count);
}
/// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and
/// 64 bits: done when the list has run, as the GPU would. Flag 1 writes the
/// GPU timestamp instead (64-bit form), flag 2 the system timestamp.
extern "system" fn write32(this: This, address: u64, value: u32, _flush: u32, _flags: u32) {
defer_write(this, address, Written::Value(u64::from(value)), 4);
}
extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, flags: u32) {
const GPU_TIMESTAMP: u32 = 1;
const SYSTEM_TIMESTAMP: u32 = 2;
let what = match flags {
GPU_TIMESTAMP => Written::GpuTimestamp,
SYSTEM_TIMESTAMP => Written::SystemTimestamp,
_ => Written::Value(value),
};
defer_write(this, address, what, 8);
}
fn defer_write(this: This, address: u64, what: Written, bytes: usize) {
if address == 0 {
return;
}
#[cfg(windows)]
if let Some(list) = host_list(this) {
list.defer_write(address as *mut u8, what, bytes);
return;
}
let _ = this;
// Without a host GPU nothing runs later: write now.
what.write(address as *mut u8, bytes);
}
/// The list methods by their slot in older titles' lists (the 2020-era
/// layout): 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): 140 slots.
const METHODS: [(usize, *const ()); 52] = [
(0, list_query as *const ()),
(2, list_release as *const ()),
(7, object::parent_device as *const ()), // 0x38
(8, list_type as *const ()), // 0x40
(9, close as *const ()), // 0x48
(10, reset as *const ()), // 0x50
(12, state::draw as *const ()), // 0x60 instanced
(13, state::draw_indexed as *const ()), // 0x68 indexed
(14, state::dispatch as *const ()), // 0x70
(15, copy_buffer_region as *const ()), // 0x78
(16, copy_texture_region as *const ()), // 0x80
(17, copy_resource as *const ()), // 0x88
(19, resolve as *const ()), // 0x98
(20, state::topology as *const ()), // 0xa0
(21, state::viewports as *const ()), // 0xa8
(22, state::scissors as *const ()), // 0xb0
(23, state::blend_factor as *const ()), // 0xb8
(24, state::stencil_ref as *const ()), // 0xc0
(25, set_pipeline as *const ()), // 0xc8
(26, barrier as *const ()), // 0xd0
(32, state::heaps as *const ()), // 0x100
(33, ignored_state as *const ()), // 0x108 compute root signature
(34, ignored_state as *const ()), // 0x110 graphics root signature
(35, state::compute_table as *const ()), // 0x118
(36, state::graphics_table as *const ()), // 0x120
(37, state::compute_constant as *const ()), // 0x128
(38, state::graphics_constant as *const ()), // 0x130
(39, state::compute_constants as *const ()), // 0x138
(40, state::graphics_constants as *const ()), // 0x140
(41, state::compute_view as *const ()), // 0x148 CBV
(42, state::graphics_view as *const ()), // 0x150 CBV
(43, state::compute_view as *const ()), // 0x158 SRV
(44, state::graphics_view as *const ()), // 0x160 SRV
(45, state::compute_view as *const ()), // 0x168 UAV
(46, state::graphics_view as *const ()), // 0x170 UAV
(47, state::index_buffer as *const ()), // 0x178
(48, state::vertex_buffers as *const ()), // 0x180
(50, state::targets as *const ()), // 0x190
(51, clear_dsv as *const ()), // 0x198
(52, clear_rtv as *const ()), // 0x1a0
(59, draw as *const ()), // 0x1d8 indirect
(60, copy_memory as *const ()), // 0x1e0
(68, ignored_state as *const ()), // 0x220 depth bounds
(69, write32 as *const ()), // 0x228
(70, write64 as *const ()), // 0x230
(71, wait_value as *const ()), // 0x238, 32 bits
(72, wait_value as *const ()), // 0x240, 64 bits
(73, ignored_state as *const ()), // 0x248 pixel shader depth order
(83, copy_texture_region_x as *const ()), // 0x298
(84, copy_resource_x as *const ()), // 0x2a0
(124, ignored_state as *const ()), // 0x3e0 shading rate
(127, state::dispatch_mesh as *const ()), // 0x3f8 mesh dispatch
];
/// The rest of [`METHODS`], kept apart only to stay readable.
const MORE_METHODS: [(usize, *const ()); 9] = [
(28, query_mark as *const ()), // 0xe0 BeginQuery
(29, query_mark as *const ()), // 0xe8 EndQuery
(30, resolve_queries as *const ()), // 0xf0
(78, dispatch_x as *const ()), // 0x270
(98, state::dispatch_mesh_x as *const ()), // 0x310
(99, driver_hint as *const ()), // 0x318
// Pipeline syncs at the top and bottom of the pipe, 0x408 and 0x410.
(129, sync as *const ()),
(130, sync as *const ()),
(137, reset_x as *const ()), // 0x448
];
/// Newer titles' lists have two more methods in the console part of the
/// base list, after the clears (0x198/0x1a0 as before) and before
/// ExecuteIndirect, which moved from 0x1d8 to 0x1e8: every slot from 0x1d8
/// on is two later (taken here as starting exactly at 0x1d8). Inferred from
/// Grand Theft Auto VI's call shapes: ExecuteIndirect 0x1e8, bottom-of-pipe
/// writes 0x238/0x240, waits 0x248/0x250, depth bounds 0x230, shading rate
/// 0x3f0/0x400, syncs 0x418/0x420, ResetX 0x458 (asserts on failure).
const fn newer_slot(slot: usize) -> usize {
if slot >= 59 { slot + 2 } else { slot }
}
/// Methods only newer titles' lists have. 0x490: the enhanced barrier
/// `(group count, groups)`, with 16-byte groups `(type, count, barriers)`
/// and 40-byte buffer barriers (title+0x95e0 builds them). 0x470 `(u64)`,
/// called from Grand Theft Auto VI's state flush with its result unused.
/// shortcut: 0x470's purpose is unknown; ignored until a title shows it
/// matters.
const NEWER_METHODS: [(usize, *const ()); 3] = [
(142, ignored_state as *const ()),
(146, barrier_groups as *const ()),
(148, allocate_upload as *const ()),
];
const fn list_table(newer: bool) -> [*const (); 160] {
let mut f = object::d3d12_object(object::missing_table::<LIST, 160>());
let mut i = 0;
while i < METHODS.len() + MORE_METHODS.len() {
let (slot, method) = if i < METHODS.len() {
METHODS[i]
} else {
MORE_METHODS[i - METHODS.len()]
};
f[if newer { newer_slot(slot) } else { slot }] = method;
i += 1;
}
let mut i = 0;
while newer && i < NEWER_METHODS.len() {
f[NEWER_METHODS[i].0] = NEWER_METHODS[i].1;
i += 1;
}
f
}
/// Every slot up to the limit exists and logs, for the methods newer
/// titles add.
static LIST_FUNCTIONS: Table<160> = Table(list_table(false));
static NEWER_LIST_FUNCTIONS: Table<160> = Table(list_table(true));
#[cfg(test)]
mod tests {
@@ -666,11 +1329,25 @@ mod tests {
(at(0x18), at(0x28), at(0x30))
};
assert!(put >= draw_limit && put >= api_limit);
// The console's ID3D12GraphicsCommandList6, as Grand Theft Auto VI asks.
let mut same = null;
assert_eq!(list_query(list, &LIST_IIDS[7], &mut same), S_OK);
assert_eq!(same, list);
assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x10)(list), 1);
assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x40)(list), 0);
assert_eq!(
slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list),
S_OK
);
// List-owned upload memory: aligned, writable, gone at reset.
let p = allocate_upload(list, 40, 0x100);
assert!(!p.is_null() && (p as usize).is_multiple_of(0x100));
// SAFETY: 40 bytes were handed out.
unsafe { p.write_bytes(0xab, 40) };
assert!(allocate_upload(list, 8, 0x30).is_null(), "not a power of two");
assert_eq!(reset(list, allocator, null), S_OK);
// SAFETY: the list is ours.
assert!(unsafe { &(*list.cast::<List>()).uploads }.lock().unwrap().is_empty());
let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o);
assert_eq!(release(list), 0);
assert_eq!(release(allocator), 0);
+39 -2
View File
@@ -18,7 +18,7 @@ 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(crate) const MORE_DATA: HRESULT = 0x887A_0003_u32 as i32;
pub type Iid = [u8; 16];
@@ -275,19 +275,54 @@ const MAX_SLOTS: usize = 160;
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
/// Logged once per slot, with the caller's offset in its module (the title
/// image for title calls). Wrong for a slot that returns a value instead of
/// an `HRESULT`.
extern "system" fn missing<const KIND: usize, const SLOT: usize>() -> HRESULT {
if !REPORTED[KIND][SLOT].swap(true, Ordering::Relaxed) {
tracing::warn!(
object = KINDS[KIND],
slot = format_args!("{:#x}", SLOT * 8),
caller = caller(),
"method not implemented"
);
}
E_NOTIMPL
}
/// The return address of whoever called our caller, as `+offset` into its
/// module.
#[inline(never)]
fn caller() -> String {
#[cfg(windows)]
{
use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace;
use windows_sys::Win32::System::LibraryLoader::{
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
GetModuleHandleExW,
};
let mut frame = std::ptr::null_mut();
// SAFETY: room for one frame; skips this function and its caller.
if unsafe { RtlCaptureStackBackTrace(2, 1, &mut frame, std::ptr::null_mut()) } == 1 {
let mut module = std::ptr::null_mut();
// SAFETY: looks up the module holding the address, no reference.
let found = unsafe {
GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
| GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
frame as *const u16,
&mut module,
)
};
if found != 0 {
return format!("+{:#x}", frame as usize - module as usize);
}
return format!("{frame:?}");
}
}
String::new()
}
/// Accepts and ignores (debug-only settings).
pub(crate) extern "system" fn ignore() -> HRESULT {
S_OK
@@ -298,6 +333,8 @@ macro_rules! missing {
}
/// A table of `N` slots that log and fail; callers fill in what they have.
/// Tables are made longer than the interfaces we know, so that a method a
/// newer title adds logs instead of jumping into whatever follows the table.
pub(crate) const fn missing_table<const KIND: usize, const N: usize>() -> [*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
+374 -25
View File
@@ -1,15 +1,24 @@
//! 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.
//! then the shader stages (five for graphics, one for compute); streams
//! carry the rest of the graphics state as subobjects of the standard
//! types.
//!
//! 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
//! Host pipelines are made on a pipeline's first draw, not at creation:
//! Grand Theft Auto VI creates some 60,000 pipelines in its first 20
//! seconds and draws with a few dozen (decision 0007, step 3). Shader
//! containers are shared by content hash and translated once, on first
//! use (decision 0003).
//!
//! shortcut: only vertex plus pixel pipelines from streams and compute
//! pipelines get host pipelines; mesh, tessellation and geometry stages,
//! and the plain graphics description, keep their containers only. 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::collections::HashMap;
use std::mem::offset_of;
use std::sync::{Arc, Mutex, OnceLock};
use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, PIPELINE, Table, This, guid};
use crate::resource::PAGEABLE_IIDS;
@@ -45,30 +54,183 @@ pub(crate) struct ComputeHead {
stage: Bytecode,
}
/// A shader container a title passed, shared by every pipeline with the
/// same bytes.
pub(crate) struct Shader {
pub(crate) stage: &'static str,
/// The first 8 bytes of its BLAKE3, as logged.
pub(crate) hash: String,
container: Vec<u8>,
#[cfg(windows)]
translated: OnceLock<Option<Translated>>,
}
impl std::fmt::Debug for Shader {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} {}", self.stage, self.hash)
}
}
/// Every container seen, by full content hash.
static SHADERS: Mutex<Option<HashMap<[u8; 32], Arc<Shader>>>> = Mutex::new(None);
/// The shared container for `bytes`.
fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> {
let full = blake3::hash(bytes);
let mut shaders = SHADERS.lock().unwrap_or_else(|e| e.into_inner());
shaders
.get_or_insert_with(HashMap::new)
.entry(*full.as_bytes())
.or_insert_with(|| {
Arc::new(Shader {
stage,
hash: full.to_hex()[..16].to_owned(),
container: bytes.to_vec(),
#[cfg(windows)]
translated: OnceLock::new(),
})
})
.clone()
}
/// A translated shader and the console resources its code reads.
#[cfg(windows)]
pub(crate) struct Translated {
pub(crate) host: victory_shader::emit::HostShader,
pub(crate) used: Vec<victory_shader::UsedResource>,
}
#[cfg(windows)]
impl Shader {
/// The translation, made on first use; a shader that does not
/// translate is logged once.
pub(crate) fn translated(&self) -> Option<&Translated> {
self.translated
.get_or_init(|| {
let done = translate(&self.container);
match &done {
Ok(t) => tracing::info!(
stage = self.stage,
hash = %self.hash,
user_data = t.host.user_data.len(),
samplers = t.host.samplers.len(),
"shader translated"
),
Err(e) => tracing::warn!(
stage = self.stage,
hash = %self.hash,
error = %e,
"shader does not translate; its pipelines' draws are dropped"
),
}
done.ok()
})
.as_ref()
}
}
#[cfg(windows)]
fn translate(container: &[u8]) -> Result<Translated, String> {
use victory_shader::{Container, FourCC, HwStage};
let host = crate::shader_cache::host_shader(container)?;
let c = Container::parse(container).map_err(|e| e.to_string())?;
let used = match c.part(FourCC::DXIL) {
Some(part) => victory_shader::native_programs(part.data)
.map_err(|e| e.to_string())?
.into_iter()
.find(|p| {
matches!(
p.stage,
HwStage::Vs | HwStage::Ps | HwStage::Ms | HwStage::Cs
)
})
.map(|p| p.used)
.unwrap_or_default(),
None => Vec::new(),
};
Ok(Translated { host, used })
}
#[repr(C)]
struct Pipeline {
object: Object,
packet: [u32; 8],
/// Each stage's container, empty when the stage is unused.
shaders: Vec<Vec<u8>>,
/// Each used stage's container.
shaders: Vec<Arc<Shader>>,
/// Whether a list has bound it yet (its shaders are logged then).
bound: std::sync::atomic::AtomicBool,
/// The rest of a stream's graphics state, for the host pipeline.
#[cfg(windows)]
graphics: Option<Box<host::GraphicsState>>,
#[cfg(windows)]
host: OnceLock<Option<host::HostPipeline>>,
}
const _: () = assert!(offset_of!(Pipeline, packet) == 0x10);
fn copy(stage: &Bytecode) -> Vec<u8> {
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()
/// Stage names, in description order.
const GRAPHICS_STAGES: [&str; 5] = ["vertex", "pixel", "domain", "hull", "geometry"];
fn pipeline<'a>(this: This) -> &'a Pipeline {
// SAFETY: the title passes one of our pipelines.
unsafe { &*this.cast::<Pipeline>() }
}
fn hand_out(shaders: Vec<Vec<u8>>, iid: *const Iid, out: *mut This) -> HRESULT {
let sizes: Vec<usize> = shaders.iter().map(Vec::len).collect();
tracing::debug!(?sizes, "pipeline state");
/// List method: logs each pipeline's shaders the first time a list binds
/// it, so a run lists the shaders its frames need first.
pub(crate) fn bound(this: This) {
if this.is_null() {
return;
}
let p = pipeline(this);
if p.bound.swap(true, std::sync::atomic::Ordering::Relaxed) {
return;
}
let frame = crate::frame::current();
for shader in &p.shaders {
tracing::info!(pipeline = ?this, frame, stage = shader.stage, size = shader.container.len(), hash = %shader.hash, "first bind");
}
}
/// The host pipeline of a title pipeline, made on first use; `None` if one
/// of its shaders does not translate or the host refuses it.
#[cfg(windows)]
pub(crate) fn host_pipeline<'a>(this: This) -> Option<&'a host::HostPipeline> {
if this.is_null() {
return None;
}
let p = pipeline(this);
p.host
.get_or_init(|| host::HostPipeline::new(&p.shaders, p.graphics.as_deref()))
.as_ref()
}
/// The stage's container, if it has one.
fn copy(stage: &'static str, code: &Bytecode) -> Option<Arc<Shader>> {
if code.code.is_null() || code.size == 0 {
return None;
}
// SAFETY: the title passes `size` bytes of shader code.
Some(shader(stage, unsafe {
std::slice::from_raw_parts(code.code, code.size)
}))
}
fn hand_out(
shaders: Vec<Arc<Shader>>,
#[cfg(windows)] graphics: Option<Box<host::GraphicsState>>,
iid: *const Iid,
out: *mut This,
) -> HRESULT {
tracing::trace!(?shaders, "pipeline state");
let pipeline = Box::new(Pipeline {
object: Object::new(&FUNCTIONS),
packet: [0; 8],
shaders,
bound: std::sync::atomic::AtomicBool::new(false),
#[cfg(windows)]
graphics,
#[cfg(windows)]
host: OnceLock::new(),
});
object::hand_out(PIPELINE, pipeline, iid, &PIPELINE_IIDS, out)
}
@@ -84,7 +246,15 @@ pub(crate) extern "system" fn create_graphics(
let Some(desc) = (unsafe { desc.as_ref() }) else {
return E_INVALIDARG;
};
hand_out(desc.stages.iter().map(copy).collect(), iid, out)
let stages = GRAPHICS_STAGES.iter().zip(&desc.stages);
let shaders = stages.filter_map(|(s, c)| copy(s, c)).collect();
hand_out(
shaders,
#[cfg(windows)]
None,
iid,
out,
)
}
/// Device method.
@@ -98,7 +268,115 @@ pub(crate) extern "system" fn create_compute(
let Some(desc) = (unsafe { desc.as_ref() }) else {
return E_INVALIDARG;
};
hand_out(vec![copy(&desc.stage)], iid, out)
hand_out(
copy("compute", &desc.stage).into_iter().collect(),
#[cfg(windows)]
None,
iid,
out,
)
}
/// Device method 0x1f0: the plain compute description plus console
/// extensions `(desc, extension count, extensions, iid, out)`.
/// shortcut: the extensions (console shader settings) are ignored, as is
/// the rest of the description.
pub(crate) extern "system" fn create_compute_x(
this: This,
desc: *const ComputeHead,
_extensions: u32,
_extended: *const u8,
iid: *const Iid,
out: *mut This,
) -> HRESULT {
create_compute(this, desc, iid, out)
}
/// A pipeline described as a stream: its size and the subobjects, each a
/// type then its data, padded to 8 bytes.
#[repr(C)]
pub(crate) struct StreamDesc {
size: usize,
stream: *const u8,
}
/// A subobject type's size (type included), and the stage it is if it is a
/// shader. The console numbers amplification and mesh shaders 23 and 24
/// (PC: 24 and 25); its own types from 25 on are not sized yet.
fn subobject(kind: u32) -> Option<(usize, Option<&'static str>)> {
let stage = |name| Some((24, Some(name)));
match kind {
1 => stage("vertex"),
2 => stage("pixel"),
3 => stage("domain"),
4 => stage("hull"),
5 => stage("geometry"),
6 => stage("compute"),
23 => stage("amplification"),
24 => stage("mesh"),
0 => Some((16, None)),
12 | 19 => Some((24, None)),
7 | 15 => Some((40, None)),
8 => Some((336, None)),
10 => Some((48, None)),
11 => Some((56, None)),
17 => Some((16, None)),
21 => Some((64, None)),
22 => Some((32, None)),
9 | 13 | 14 | 16 | 18 | 20 => Some((8, None)),
_ => None,
}
}
/// Device method: a pipeline from a stream; the shaders are kept, and the
/// graphics state for the host pipeline.
pub(crate) extern "system" fn create_stream(
_: This,
desc: *const StreamDesc,
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.stream.is_null() {
return E_INVALIDARG;
}
let mut shaders = Vec::new();
#[cfg(windows)]
let mut graphics = host::GraphicsState::default();
let mut at = 0;
while at + 8 <= desc.size {
// SAFETY: inside the stream the title passes.
let kind = unsafe { desc.stream.add(at).cast::<u32>().read_unaligned() };
let Some((size, stage)) = subobject(kind) else {
tracing::warn!(
kind,
at,
"pipeline subobject of unknown size; the rest is ignored"
);
break;
};
if let Some(stage) = stage {
// SAFETY: a shader subobject has its bytecode at +8.
let code = unsafe { &*desc.stream.add(at + 8).cast::<Bytecode>() };
shaders.extend(copy(stage, code));
}
#[cfg(windows)]
// SAFETY: a whole subobject of this kind lies at `at`.
unsafe {
graphics.read(kind, desc.stream.add(at))
};
at += size;
}
hand_out(
shaders,
#[cfg(windows)]
Some(Box::new(graphics)),
iid,
out,
)
}
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
@@ -110,19 +388,30 @@ extern "system" fn release(this: This) -> u32 {
}
/// IUnknown 3, object 4, device child 1, pipeline 3.
static FUNCTIONS: Table<11> = {
let mut f = object::d3d12_object(object::missing_table::<PIPELINE, 11>());
static FUNCTIONS: Table<24> = {
let mut f = object::d3d12_object(object::missing_table::<PIPELINE, 24>());
f[0] = query as *const ();
f[2] = release as *const ();
f[7] = object::parent_device as *const (); // 0x38
Table(f)
};
#[cfg(windows)]
pub(crate) mod host;
#[cfg(test)]
mod tests {
use super::*;
use crate::object::{S_OK, slot};
fn shaders(p: This) -> Vec<(&'static str, Vec<u8>)> {
pipeline(p)
.shaders
.iter()
.map(|s| (s.stage, s.container.clone()))
.collect()
}
#[test]
fn pipelines_keep_their_shaders() {
let (vs, ps) = ([1u8, 2, 3], [4u8; 5]);
@@ -151,11 +440,71 @@ mod tests {
create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p),
S_OK
);
// SAFETY: one of our pipelines.
let shaders = unsafe { &(*p.cast::<Pipeline>()).shaders };
assert_eq!(shaders[0], vs);
assert_eq!(shaders[1], ps);
assert!(shaders[2].is_empty());
assert_eq!(
shaders(p),
[("vertex", vs.to_vec()), ("pixel", ps.to_vec())]
);
// A second pipeline with the same pixel shader shares its container.
let mut q = std::ptr::null();
create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut q);
assert!(Arc::ptr_eq(
&pipeline(p).shaders[1],
&pipeline(q).shaders[1]
));
assert_eq!(slot::<extern "system" fn(This) -> u32>(p, 0x10)(p), 0);
}
/// The stream layout Grand Theft Auto VI builds (title+0x86f090): root
/// signature, five shader slots (the first a mesh shader), blend, sample
/// mask, rasterizer, depth-stencil 1, sample description, input layout,
/// topology, render target and depth formats: 0x2b0 bytes.
#[test]
fn streams_yield_their_shaders() {
let (ms, ps) = ([9u8; 7], [4u8; 5]);
let mut stream = vec![0u8; 0x2b0];
let mut put = |at: usize, v: u64| stream[at..at + 8].copy_from_slice(&v.to_le_bytes());
for (at, kind) in [
(0x10, 24),
(0x28, 2),
(0x40, 3),
(0x58, 4),
(0x70, 5),
(0x88, 8),
(0x1d8, 9),
(0x1e0, 10),
(0x210, 21),
(0x250, 17),
(0x260, 12),
(0x278, 14),
(0x280, 15),
(0x2a8, 16),
] {
put(at, kind);
}
put(0x18, ms.as_ptr() as u64);
put(0x20, ms.len() as u64);
put(0x30, ps.as_ptr() as u64);
put(0x38, ps.len() as u64);
// Topology type 3 (triangles), one render target of format 28.
put(0x278, 14 | 3 << 32);
put(0x280, 15 | 28 << 32);
put(0x2a0, 1 << 32);
let desc = StreamDesc {
size: stream.len(),
stream: stream.as_ptr(),
};
let mut p = std::ptr::null();
let hr = create_stream(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p);
assert_eq!(hr, S_OK);
assert_eq!(shaders(p), [("mesh", ms.to_vec()), ("pixel", ps.to_vec())]);
#[cfg(windows)]
{
let g = pipeline(p).graphics.as_deref().unwrap();
assert_eq!(g.topology.0, 3);
assert_eq!(
(g.targets.NumRenderTargets, g.targets.RTFormats[0].0),
(1, 28)
);
}
}
}
+594
View File
@@ -0,0 +1,594 @@
//! Host pipelines for title pipelines (decision 0007, step 3): the
//! title's graphics state with the translated shaders, under a root
//! signature of our own that the translated shaders' bindings define
//! (`victory_shader::emit`): per stage one block of root constants for the
//! user data, root views for the title's root views, static samplers for
//! the immediate samplers, and directly indexed heaps.
use std::ffi::{CStr, CString};
use std::sync::Arc;
use victory_shader::emit::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE};
use windows::Win32::Graphics::Direct3D::ID3DBlob;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows::core::PCSTR;
use super::{Shader, Translated};
use crate::host::host;
/// A stream's graphics state, owned (the title's stream lives only for the
/// creation call). Subobjects the stream leaves out keep D3D12's defaults.
pub(crate) struct GraphicsState {
blend: D3D12_BLEND_DESC,
sample_mask: u32,
rasterizer: D3D12_RASTERIZER_DESC,
depth: D3D12_DEPTH_STENCIL_DESC,
/// Input elements, their names pointing into `names`.
inputs: Vec<D3D12_INPUT_ELEMENT_DESC>,
names: Vec<CString>,
strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE,
pub(crate) topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE,
pub(crate) targets: D3D12_RT_FORMAT_ARRAY,
depth_format: DXGI_FORMAT,
samples: DXGI_SAMPLE_DESC,
}
impl Default for GraphicsState {
fn default() -> Self {
let target = D3D12_RENDER_TARGET_BLEND_DESC {
SrcBlend: D3D12_BLEND_ONE,
DestBlend: D3D12_BLEND_ZERO,
BlendOp: D3D12_BLEND_OP_ADD,
SrcBlendAlpha: D3D12_BLEND_ONE,
DestBlendAlpha: D3D12_BLEND_ZERO,
BlendOpAlpha: D3D12_BLEND_OP_ADD,
LogicOp: D3D12_LOGIC_OP_NOOP,
RenderTargetWriteMask: D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8,
..Default::default()
};
let keep = D3D12_DEPTH_STENCILOP_DESC {
StencilFailOp: D3D12_STENCIL_OP_KEEP,
StencilDepthFailOp: D3D12_STENCIL_OP_KEEP,
StencilPassOp: D3D12_STENCIL_OP_KEEP,
StencilFunc: D3D12_COMPARISON_FUNC_ALWAYS,
};
GraphicsState {
blend: D3D12_BLEND_DESC {
RenderTarget: [target; 8],
..Default::default()
},
sample_mask: u32::MAX,
rasterizer: D3D12_RASTERIZER_DESC {
FillMode: D3D12_FILL_MODE_SOLID,
CullMode: D3D12_CULL_MODE_BACK,
DepthClipEnable: true.into(),
..Default::default()
},
depth: D3D12_DEPTH_STENCIL_DESC {
DepthEnable: true.into(),
DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
DepthFunc: D3D12_COMPARISON_FUNC_LESS,
StencilReadMask: 0xff,
StencilWriteMask: 0xff,
FrontFace: keep,
BackFace: keep,
..Default::default()
},
inputs: Vec::new(),
names: Vec::new(),
strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED,
topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED,
targets: D3D12_RT_FORMAT_ARRAY::default(),
depth_format: DXGI_FORMAT_UNKNOWN,
samples: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
}
}
}
impl GraphicsState {
/// Takes in one subobject of a stream: its type, then its data at +4
/// (+8 for those holding pointers).
///
/// # Safety
/// `at` points at a whole subobject of type `kind`.
pub(crate) unsafe fn read(&mut self, kind: u32, at: *const u8) {
// SAFETY: the caller passes a whole subobject.
unsafe {
let data = at.add(4);
match kind {
8 => self.blend = data.cast::<D3D12_BLEND_DESC>().read_unaligned(),
9 => self.sample_mask = data.cast::<u32>().read_unaligned(),
10 => self.rasterizer = data.cast::<D3D12_RASTERIZER_DESC>().read_unaligned(),
11 => self.depth = data.cast::<D3D12_DEPTH_STENCIL_DESC>().read_unaligned(),
21 => {
// shortcut: the depth bounds test is dropped (the host
// pipeline uses the plain description); bring it back
// with a stream if a title enables it.
let d = data.cast::<D3D12_DEPTH_STENCIL_DESC1>().read_unaligned();
self.depth = D3D12_DEPTH_STENCIL_DESC {
DepthEnable: d.DepthEnable,
DepthWriteMask: d.DepthWriteMask,
DepthFunc: d.DepthFunc,
StencilEnable: d.StencilEnable,
StencilReadMask: d.StencilReadMask,
StencilWriteMask: d.StencilWriteMask,
FrontFace: d.FrontFace,
BackFace: d.BackFace,
};
}
12 => {
let layout = at.add(8).cast::<D3D12_INPUT_LAYOUT_DESC>().read_unaligned();
if layout.pInputElementDescs.is_null() {
return;
}
let elements = std::slice::from_raw_parts(
layout.pInputElementDescs,
layout.NumElements as usize,
);
self.names = elements
.iter()
.map(|e| CStr::from_ptr(e.SemanticName.0.cast()).to_owned())
.collect();
self.inputs = elements
.iter()
.zip(&self.names)
.map(|(e, name)| D3D12_INPUT_ELEMENT_DESC {
SemanticName: PCSTR(name.as_ptr().cast()),
Format: DXGI_FORMAT(
crate::resource::pc_format(e.Format.0 as u32) as i32
),
..*e
})
.collect();
}
13 => {
self.strip_cut =
D3D12_INDEX_BUFFER_STRIP_CUT_VALUE(data.cast::<i32>().read_unaligned())
}
14 => {
self.topology =
D3D12_PRIMITIVE_TOPOLOGY_TYPE(data.cast::<i32>().read_unaligned())
}
15 => {
self.targets = data.cast::<D3D12_RT_FORMAT_ARRAY>().read_unaligned();
for f in &mut self.targets.RTFormats {
f.0 = crate::resource::pc_format(f.0 as u32) as i32;
}
}
16 => {
let f = data.cast::<u32>().read_unaligned();
self.depth_format = DXGI_FORMAT(crate::resource::pc_format(f) as i32);
}
17 => self.samples = data.cast::<DXGI_SAMPLE_DESC>().read_unaligned(),
_ => {}
}
}
}
/// The vertex buffer slots the input layout reads.
fn slots(&self) -> u32 {
self.inputs
.iter()
.fold(0, |m, e| m | 1 << e.InputSlot.min(31))
}
/// The input elements with their byte offsets worked out.
fn elements(&self) -> Vec<Input> {
let mut next = [0u32; 32];
self.inputs
.iter()
.map(|e| {
let slot = e.InputSlot.min(31) as usize;
let format = e.Format.0 as u32;
let offset = if e.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT {
next[slot]
} else {
e.AlignedByteOffset
};
let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32);
next[slot] = offset + bytes;
Input {
slot: slot as u32,
offset,
format,
per_instance: e.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA,
}
})
.collect()
}
}
/// One input element: vertex buffer slot, byte offset, format.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Input {
pub(crate) slot: u32,
pub(crate) offset: u32,
pub(crate) format: u32,
pub(crate) per_instance: bool,
}
/// The console's own primitive topology types.
const RECTANGLES: i32 = 19;
const QUADS: i32 = 32;
/// One stage of a host pipeline and where its bindings go.
pub(crate) struct Stage {
pub(crate) shader: Arc<Shader>,
/// The root parameter of its user data, and its size in dwords.
pub(crate) user_data: Option<(u32, u32)>,
/// Root parameters of its root views: (title root parameter, ours).
pub(crate) root_cbvs: Vec<(u8, u32)>,
pub(crate) root_srvs: Vec<(u8, u32)>,
}
impl Stage {
pub(crate) fn translated(&self) -> &Translated {
self.shader
.translated()
.expect("host pipelines are made from translated shaders")
}
}
pub(crate) struct HostPipeline {
/// A compute pipeline (else graphics).
pub(crate) compute: bool,
/// A mesh pipeline (graphics without vertex input).
pub(crate) mesh: bool,
pub(crate) pso: ID3D12PipelineState,
pub(crate) root: ID3D12RootSignature,
/// Vertex, then pixel stage, or the compute stage.
pub(crate) stages: Vec<Stage>,
/// The vertex buffer slots it reads (bit per slot).
pub(crate) slots: u32,
pub(crate) inputs: Vec<Input>,
/// Its shaders, for reports of slow submissions.
pub(crate) name: String,
}
/// Logs a pipeline that gets no host pipeline, once per reason.
fn refuse(reason: &'static str, shaders: &[Arc<Shader>]) -> Option<HostPipeline> {
static SEEN: std::sync::Mutex<Vec<&str>> = std::sync::Mutex::new(Vec::new());
let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
if !seen.contains(&reason) {
seen.push(reason);
tracing::warn!(?shaders, "no host pipeline: {reason} (logged once)");
}
None
}
impl HostPipeline {
/// A host pipeline for vertex and pixel shaders with the graphics
/// state `g`, or for one compute shader.
pub(crate) fn new(shaders: &[Arc<Shader>], g: Option<&GraphicsState>) -> Option<HostPipeline> {
let find = |stage| shaders.iter().find(|s| s.stage == stage);
let compute = match shaders {
[cs] if cs.stage == "compute" => Some(cs),
_ => None,
};
if compute.is_none()
&& shaders
.iter()
.any(|s| !matches!(s.stage, "vertex" | "pixel" | "mesh"))
{
return refuse(
"only vertex, mesh, pixel and compute stages are translated",
shaders,
);
}
let mesh = find("mesh");
let stages = if let Some(cs) = compute {
vec![(cs, D3D12_SHADER_VISIBILITY_ALL)]
} else {
let first = match (mesh, find("vertex")) {
(Some(ms), _) => (ms, D3D12_SHADER_VISIBILITY_MESH),
(None, Some(vs)) => (vs, D3D12_SHADER_VISIBILITY_VERTEX),
(None, None) => return refuse("no vertex or mesh shader", shaders),
};
let mut stages = vec![first];
stages.extend(find("pixel").map(|ps| (ps, D3D12_SHADER_VISIBILITY_PIXEL)));
stages
};
if mesh.is_some() && !host()?.mesh_shaders() {
return refuse("the host GPU has no mesh shaders (or no shader model 6.6)", shaders);
}
for (s, _) in &stages {
s.translated()?;
}
let host = host()?;
// The root signature the translated shaders' bindings define.
let mut params: Vec<D3D12_ROOT_PARAMETER1> = Vec::new();
let mut samplers = Vec::new();
let mut bound = Vec::new();
for &(shader, visibility) in &stages {
let t = &shader.translated()?.host;
let mut stage = Stage {
shader: shader.clone(),
user_data: None,
root_cbvs: Vec::new(),
root_srvs: Vec::new(),
};
let dwords = t.user_data_dwords();
if dwords > 0 {
stage.user_data = Some((params.len() as u32, dwords));
params.push(D3D12_ROOT_PARAMETER1 {
ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS,
Anonymous: D3D12_ROOT_PARAMETER1_0 {
Constants: D3D12_ROOT_CONSTANTS {
ShaderRegister: 0,
RegisterSpace: USER_DATA_SPACE,
Num32BitValues: dwords,
},
},
ShaderVisibility: visibility,
});
}
for (slots, kind, out) in [
(
&t.root_cbvs,
D3D12_ROOT_PARAMETER_TYPE_CBV,
&mut stage.root_cbvs,
),
(
&t.root_srvs,
D3D12_ROOT_PARAMETER_TYPE_SRV,
&mut stage.root_srvs,
),
] {
for &slot in slots {
out.push((slot, params.len() as u32));
params.push(D3D12_ROOT_PARAMETER1 {
ParameterType: kind,
Anonymous: D3D12_ROOT_PARAMETER1_0 {
Descriptor: D3D12_ROOT_DESCRIPTOR1 {
ShaderRegister: u32::from(slot),
RegisterSpace: ROOT_CBV_SPACE,
Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE,
},
},
ShaderVisibility: visibility,
});
}
}
for (n, s) in t.static_samplers.iter().enumerate() {
samplers.push(D3D12_STATIC_SAMPLER_DESC {
Filter: D3D12_FILTER(s.filter as i32),
AddressU: D3D12_TEXTURE_ADDRESS_MODE(s.address[0] as i32),
AddressV: D3D12_TEXTURE_ADDRESS_MODE(s.address[1] as i32),
AddressW: D3D12_TEXTURE_ADDRESS_MODE(s.address[2] as i32),
MipLODBias: s.mip_lod_bias,
MaxAnisotropy: s.max_anisotropy,
ComparisonFunc: D3D12_COMPARISON_FUNC(s.comparison as i32),
BorderColor: D3D12_STATIC_BORDER_COLOR(s.border as i32),
MinLOD: s.min_lod,
MaxLOD: s.max_lod,
ShaderRegister: n as u32,
RegisterSpace: SAMPLER_SPACE,
ShaderVisibility: visibility,
});
}
bound.push(stage);
}
let root = match root_signature(&host.device, &params, &samplers, compute.is_some()) {
Ok(root) => root,
Err(e) => {
tracing::warn!(error = %e, ?shaders, "host root signature refused");
return None;
}
};
let code = |i: usize| {
stages.get(i).and_then(|(s, _)| s.translated()).map_or(
D3D12_SHADER_BYTECODE::default(),
|t| D3D12_SHADER_BYTECODE {
pShaderBytecode: t.host.dxil.as_ptr().cast(),
BytecodeLength: t.host.dxil.len(),
},
)
};
if compute.is_some() {
let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC {
// SAFETY: a borrowed pointer the description never releases.
pRootSignature: unsafe { std::mem::transmute_copy(&root) },
CS: code(0),
..Default::default()
};
// SAFETY: the description points at live data.
let pso = match unsafe { host.device.CreateComputePipelineState(&desc) } {
Ok(pso) => pso,
Err(e) => {
tracing::warn!(error = %e, ?shaders, "host pipeline refused");
host.log_messages();
return None;
}
};
tracing::info!(?shaders, "host pipeline");
return Some(HostPipeline {
compute: true,
mesh: false,
pso,
root,
stages: bound,
name: format!("{shaders:?}"),
slots: 0,
inputs: Vec::new(),
});
}
let Some(g) = g else {
return refuse("graphics state not kept (plain description)", shaders);
};
if mesh.is_some() {
let pso = match mesh_pipeline(&host.device, &root, code(0), code(1), g) {
Ok(pso) => pso,
Err(e) => {
tracing::warn!(error = %e, ?shaders, "host mesh pipeline refused");
host.log_messages();
return None;
}
};
tracing::info!(?shaders, "host mesh pipeline");
return Some(HostPipeline {
compute: false,
mesh: true,
pso,
root,
stages: bound,
name: format!("{shaders:?}"),
slots: 0,
inputs: Vec::new(),
});
}
let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
// SAFETY: a borrowed pointer the description never releases.
pRootSignature: unsafe { std::mem::transmute_copy(&root) },
VS: code(0),
PS: code(1),
BlendState: g.blend,
SampleMask: g.sample_mask,
RasterizerState: g.rasterizer,
DepthStencilState: g.depth,
InputLayout: D3D12_INPUT_LAYOUT_DESC {
pInputElementDescs: g.inputs.as_ptr(),
NumElements: g.inputs.len() as u32,
},
IBStripCutValue: g.strip_cut,
// The console's rectangle and quad types draw as triangles on
// the host (see `draw`).
PrimitiveTopologyType: match g.topology.0 {
RECTANGLES | QUADS => D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
_ => g.topology,
},
NumRenderTargets: g.targets.NumRenderTargets,
RTVFormats: g.targets.RTFormats,
DSVFormat: g.depth_format,
SampleDesc: g.samples,
..Default::default()
};
// SAFETY: the description points at live data.
let pso = match unsafe { host.device.CreateGraphicsPipelineState(&desc) } {
Ok(pso) => pso,
Err(e) => {
tracing::warn!(error = %e, ?shaders, "host pipeline refused");
host.log_messages();
return None;
}
};
tracing::info!(?shaders, "host pipeline");
tracing::debug!(
?shaders,
depth = ?g.depth,
dsv = g.depth_format.0,
targets = ?&g.targets.RTFormats[..g.targets.NumRenderTargets.min(8) as usize],
blend = ?g.blend.RenderTarget[0],
cull = g.rasterizer.CullMode.0,
"host graphics state"
);
Some(HostPipeline {
compute: false,
mesh: false,
pso,
root,
stages: bound,
name: format!("{shaders:?}"),
slots: g.slots(),
inputs: g.elements(),
})
}
}
/// A mesh pipeline from the title's graphics state: the pipeline-state
/// stream form (no input layout or topology).
fn mesh_pipeline(
device: &ID3D12Device,
root: &ID3D12RootSignature,
ms: D3D12_SHADER_BYTECODE,
ps: D3D12_SHADER_BYTECODE,
g: &GraphicsState,
) -> windows::core::Result<ID3D12PipelineState> {
use windows::core::Interface;
/// A stream subobject: its type, then its description, pointer-aligned.
#[repr(C, align(8))]
struct Sub<T>(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T);
#[repr(C)]
struct Stream {
root: Sub<*mut std::ffi::c_void>,
ms: Sub<D3D12_SHADER_BYTECODE>,
ps: Sub<D3D12_SHADER_BYTECODE>,
blend: Sub<D3D12_BLEND_DESC>,
mask: Sub<u32>,
raster: Sub<D3D12_RASTERIZER_DESC>,
depth: Sub<D3D12_DEPTH_STENCIL_DESC>,
targets: Sub<D3D12_RT_FORMAT_ARRAY>,
dsv: Sub<DXGI_FORMAT>,
samples: Sub<DXGI_SAMPLE_DESC>,
}
let mut stream = Stream {
root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()),
ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms),
ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps),
blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, g.blend),
mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask),
raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer),
depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, g.depth),
targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets),
dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format),
samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples),
};
let desc = D3D12_PIPELINE_STATE_STREAM_DESC {
SizeInBytes: size_of::<Stream>(),
pPipelineStateSubobjectStream: (&raw mut stream).cast(),
};
// SAFETY: the stream holds whole subobjects pointing at live data.
unsafe { device.cast::<ID3D12Device2>()?.CreatePipelineState(&desc) }
}
fn root_signature(
device: &ID3D12Device,
params: &[D3D12_ROOT_PARAMETER1],
samplers: &[D3D12_STATIC_SAMPLER_DESC],
compute: bool,
) -> windows::core::Result<ID3D12RootSignature> {
let input = if compute {
D3D12_ROOT_SIGNATURE_FLAG_NONE
} else {
D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT
};
let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC {
Version: windows::Win32::Graphics::Direct3D12::D3D_ROOT_SIGNATURE_VERSION_1_1,
Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 {
Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 {
NumParameters: params.len() as u32,
pParameters: params.as_ptr(),
NumStaticSamplers: samplers.len() as u32,
pStaticSamplers: samplers.as_ptr(),
Flags: input
| D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED
| D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED,
},
},
};
// SAFETY: the description points at live arrays; the blob is read in
// full before it is released.
unsafe {
let mut blob: Option<ID3DBlob> = None;
let mut error: Option<ID3DBlob> = None;
if let Err(e) = D3D12SerializeVersionedRootSignature(&desc, &mut blob, Some(&mut error)) {
if let Some(error) = error {
let text = std::slice::from_raw_parts(
error.GetBufferPointer().cast::<u8>(),
error.GetBufferSize(),
);
tracing::warn!("root signature: {}", String::from_utf8_lossy(text));
}
return Err(e);
}
let blob = blob.ok_or_else(windows::core::Error::empty)?;
let bytes =
std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize());
device.CreateRootSignature(0, bytes)
}
}
+162
View File
@@ -0,0 +1,162 @@
//! Console primitive types the host lacks. A rectangle list gives three
//! corners per rectangle, the second the one between the other two, and
//! the hardware adds the fourth at `v0 + v2 - v1` (Grand Theft Auto VI's
//! full-screen rectangles come as top left, bottom left, bottom right); on
//! the host each rectangle becomes two triangles, with the fourth vertex
//! made from the other three on the CPU.
//!
//! shortcut: the fourth vertex is computed from vertex inputs, not from
//! vertex shader outputs as the hardware does; that is the same for vertex
//! shaders linear in their inputs (blits, 2D quads). Inputs in formats
//! [`components`] does not know keep the first vertex's value.
/// Expands `rects` rectangles of `stride`-byte vertices from `src` into six
/// vertices each in `dst`: `(v0, v1, v2)` and `(v0, v2, v3)`, so both
/// triangles turn the same way. `elements` are (byte offset, format).
pub(crate) fn expand_rects(src: &[u8], dst: &mut [u8], stride: usize, elements: &[(u32, u32)]) {
for (rect, out) in src
.chunks_exact(3 * stride)
.zip(dst.chunks_exact_mut(6 * stride))
{
let v = |i: usize| &rect[i * stride..(i + 1) * stride];
for (slot, i) in [0, 1, 2, 0, 2].into_iter().enumerate() {
out[slot * stride..(slot + 1) * stride].copy_from_slice(v(i));
}
let fourth = &mut out[5 * stride..];
fourth.copy_from_slice(v(0));
for &(offset, format) in elements {
let at = offset as usize;
let Some((n, kind)) = components(format) else {
continue;
};
for c in 0..n {
let get = |i: usize| kind.read(&v(i)[at..], c);
let value = get(0) + get(2) - get(1);
kind.write(&mut fourth[at..], c, value);
}
}
}
}
#[derive(Clone, Copy)]
enum Kind {
F32,
F16,
Unorm8,
Unorm16,
}
/// Component count and kind of the vertex formats rectangles use.
fn components(format: u32) -> Option<(usize, Kind)> {
Some(match format {
2 => (4, Kind::F32),
6 => (3, Kind::F32),
16 => (2, Kind::F32),
41 => (1, Kind::F32),
10 => (4, Kind::F16),
34 => (2, Kind::F16),
54 => (1, Kind::F16),
11 => (4, Kind::Unorm16),
35 => (2, Kind::Unorm16),
28 | 29 | 87 | 91 => (4, Kind::Unorm8),
_ => return None,
})
}
impl Kind {
fn bytes(self) -> usize {
match self {
Kind::F32 => 4,
Kind::F16 | Kind::Unorm16 => 2,
Kind::Unorm8 => 1,
}
}
fn read(self, at: &[u8], c: usize) -> f32 {
let b = &at[c * self.bytes()..];
match self {
Kind::F32 => f32::from_le_bytes([b[0], b[1], b[2], b[3]]),
Kind::F16 => half_to_f32(u16::from_le_bytes([b[0], b[1]])),
Kind::Unorm16 => f32::from(u16::from_le_bytes([b[0], b[1]])) / 65535.0,
Kind::Unorm8 => f32::from(b[0]) / 255.0,
}
}
fn write(self, at: &mut [u8], c: usize, v: f32) {
let n = self.bytes();
let b = &mut at[c * n..(c + 1) * n];
match self {
Kind::F32 => b.copy_from_slice(&v.to_le_bytes()),
Kind::F16 => b.copy_from_slice(&f32_to_half(v).to_le_bytes()),
Kind::Unorm16 => {
b.copy_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_le_bytes())
}
Kind::Unorm8 => b[0] = (v.clamp(0.0, 1.0) * 255.0).round() as u8,
}
}
}
fn half_to_f32(h: u16) -> f32 {
let sign = u32::from(h >> 15) << 31;
let exp = u32::from((h >> 10) & 0x1f);
let man = u32::from(h & 0x3ff);
let bits = match (exp, man) {
(0, 0) => sign,
// Subnormal: scale the mantissa.
(0, m) => {
let v = m as f32 * 2f32.powi(-24);
return if sign != 0 { -v } else { v };
}
(31, m) => sign | 0x7f80_0000 | m << 13,
(e, m) => sign | (e + 112) << 23 | m << 13,
};
f32::from_bits(bits)
}
fn f32_to_half(v: f32) -> u16 {
let bits = v.to_bits();
let sign = ((bits >> 16) & 0x8000) as u16;
let exp = ((bits >> 23) & 0xff) as i32 - 127 + 15;
let man = bits & 0x7f_ffff;
if exp >= 31 {
return sign | 0x7c00; // too large: infinity
}
if exp <= 0 {
return sign; // too small: zero
}
sign | (exp as u16) << 10 | ((man + 0x1000) >> 13) as u16
}
#[cfg(test)]
mod tests {
use super::*;
/// A rectangle of float2 positions and RGBA8 colors, given as top
/// left, bottom left, bottom right: the fourth corner completes the
/// parallelogram at the top right.
#[test]
fn rectangles_get_their_fourth_corner() {
let vertex = |x: f32, y: f32, r: u8| {
let mut v = Vec::new();
v.extend(x.to_le_bytes());
v.extend(y.to_le_bytes());
v.extend([r, 0, 0, 255]);
v
};
let src: Vec<u8> = [
vertex(-1.0, 1.0, 0),
vertex(-1.0, -1.0, 100),
vertex(1.0, -1.0, 150),
]
.concat();
let mut dst = vec![0u8; 6 * 12];
expand_rects(&src, &mut dst, 12, &[(0, 16), (8, 28)]);
assert_eq!(dst[..36], src[..]);
assert_eq!(dst[36..48], src[..12]);
assert_eq!(dst[48..60], src[24..36]);
assert_eq!(dst[60..], vertex(1.0, 1.0, 50)[..]);
assert_eq!(f32_to_half(1.5), 0x3e00);
assert_eq!(half_to_f32(0x3e00), 1.5);
assert_eq!(half_to_f32(0xc000), -2.0);
}
}
+2 -2
View File
@@ -63,8 +63,8 @@ extern "system" fn release(this: This) -> u32 {
}
/// IUnknown 3, object 4, device child 1.
static FUNCTIONS: Table<8> = {
let mut f = object::d3d12_object(object::missing_table::<QUERY_HEAP, 8>());
static FUNCTIONS: Table<24> = {
let mut f = object::d3d12_object(object::missing_table::<QUERY_HEAP, 24>());
f[0] = query as *const ();
f[2] = release as *const ();
f[7] = object::parent_device as *const (); // 0x38
+354 -27
View File
@@ -1,5 +1,5 @@
//! Command queues. Nothing is executed yet: submitted lists are dropped and
//! fence signals complete at once, as if the GPU were infinitely fast.
//! Command queues. Submitted lists run on the host GPU and are waited for,
//! so fence signals complete at once.
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -54,13 +54,50 @@ pub(crate) extern "system" fn create(
};
tracing::debug!(?desc, "command queue");
let queue = Box::new(Queue {
object: Object::new(&FUNCTIONS),
object: if crate::device::newer() {
Object::new(&NEWER_FUNCTIONS)
} else {
Object::new(&FUNCTIONS)
},
kind: desc.kind,
desc,
});
object::hand_out(QUEUE, queue, iid, &QUEUE_IIDS, out)
}
/// The console's queue description: an engine or pipe and a queue on it
/// in place of PC's priority and node mask.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub(crate) struct QueueDescX {
kind: u32,
flags: u32,
engine_or_pipe: u32,
queue: u32,
}
/// Device method `CreateCommandQueueX`. The host picks engines itself, so
/// the queue is created as on PC.
pub(crate) extern "system" fn create_x(
this: This,
desc: *const QueueDescX,
iid: *const Iid,
out: *mut This,
) -> HRESULT {
// SAFETY: the title passes a description (null is tolerated).
let Some(&x) = (unsafe { desc.as_ref() }) else {
return E_INVALIDARG;
};
tracing::debug!(desc = ?x, "console command queue");
let desc = QueueDesc {
kind: x.kind,
priority: 0,
flags: x.flags,
nodes: 1,
};
create(this, &desc, iid, out)
}
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
object::answer(
QUEUE,
@@ -102,6 +139,22 @@ pub(crate) struct Plane {
count: u32,
resources: *const This,
}
/// Submission tagged with the frame it belongs to `(count, lists, frame
/// token, flags)`; frames are paced elsewhere, so it runs as a plain one.
extern "system" fn execute_x(this: This, count: u32, lists: *const This, _token: u64, _flags: u32) {
execute(this, count, lists);
}
/// Signal with sync settings for the top and bottom of the pipe; our
/// submissions are complete when they return, so it signals at once.
extern "system" fn signal2_x(
this: This,
fence: This,
value: u64,
_bottom: *const u8,
_top: *const u8,
) -> HRESULT {
signal(this, fence, value)
}
/// Markers and events only matter to profilers.
extern "system" fn marker(_: This) {}
extern "system" fn signal(_: This, fence: This, value: u64) -> HRESULT {
@@ -114,15 +167,71 @@ extern "system" fn signal(_: This, fence: This, value: u64) -> HRESULT {
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.
/// Ticks per second of GPU timestamps (see [`Written::GpuTimestamp`]).
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) };
unsafe { out.write(TIMESTAMP_FREQUENCY) };
S_OK
}
const TIMESTAMP_FREQUENCY: u64 = 100_000_000;
/// What a list's bottom-of-pipe write stores when the list has run.
#[derive(Debug, Clone, Copy)]
pub(crate) enum Written {
Value(u64),
/// The GPU clock: [`TIMESTAMP_FREQUENCY`] ticks per second since the
/// process started (our GPU work is done on the CPU's timeline).
GpuTimestamp,
/// The CPU's performance counter.
SystemTimestamp,
}
impl Written {
/// Stores the low `bytes` (4 or 8) of the value at `at`.
pub(crate) fn write(self, at: *mut u8, bytes: usize) {
let value = match self {
Written::Value(v) => v,
Written::GpuTimestamp => {
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
let elapsed = START.get_or_init(std::time::Instant::now).elapsed();
(elapsed.as_nanos() / (1_000_000_000 / u128::from(TIMESTAMP_FREQUENCY))) as u64
}
Written::SystemTimestamp => system_timestamp(),
};
// SAFETY: the title names writable GPU memory (unified with ours).
unsafe {
if bytes == 4 {
at.cast::<u32>().write_unaligned(value as u32);
} else {
at.cast::<u64>().write_unaligned(value);
}
}
}
}
fn system_timestamp() -> u64 {
#[cfg(windows)]
{
let mut count = 0;
// SAFETY: a valid out pointer.
unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut count) };
count as u64
}
#[cfg(not(windows))]
0
}
/// Frames presented so far.
static FRAMES: AtomicU64 = AtomicU64::new(0);
#[cfg(feature = "diagnostics")]
pub(crate) fn presented() -> u64 {
FRAMES.load(Ordering::Relaxed)
}
/// Shows the first plane's first resource in our window.
///
/// shortcut: one plane, no scaling or placement, the source expected in
@@ -133,10 +242,38 @@ extern "system" fn present(
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");
let (draws, dispatches) = crate::list::take_counts();
#[cfg(windows)]
let (drawn, dispatched) = {
static DRAWN: AtomicU64 = AtomicU64::new(0);
static DISPATCHED: AtomicU64 = AtomicU64::new(0);
let since = |last: &AtomicU64, now: u64| now - last.swap(now, Ordering::Relaxed);
(
since(&DRAWN, crate::draw::drawn()),
since(&DISPATCHED, crate::draw::dispatched()),
)
};
#[cfg(not(windows))]
let (drawn, dispatched) = (0, 0);
tracing::info!(
frame,
draws,
drawn,
dispatches,
dispatched,
"frame presented (since the last line: draws and dispatches, and those run on the host)"
);
#[cfg(windows)]
if frame >= 256 {
let (hits, misses) = crate::shader_cache::counts();
tracing::info!(hits, misses, "shaders from the cache and translated so far");
}
}
#[cfg(all(windows, feature = "diagnostics"))]
if crate::capture::listed(frame) {
crate::capture::dump_targets(frame);
}
#[cfg(windows)]
if planes > 0
@@ -152,13 +289,125 @@ extern "system" fn present(
const COPY_SOURCE: u32 = 0x800;
let state = crate::resource::host_transition(resource, COPY_SOURCE)
.map_or(COPY_SOURCE, |(_, before)| before);
host.present(texture, state);
let shown = host.present(texture, state, frame);
crate::resource::host_transition(resource, state);
#[cfg(feature = "diagnostics")]
blinks(frame, resource, state, shown);
#[cfg(not(feature = "diagnostics"))]
let _ = shown;
}
#[cfg(not(windows))]
let _ = (planes, plane_parameters);
S_OK
}
/// Diagnostics: logs a presented frame that is black after one that was
/// not, with what was presented and how many draws ran since.
#[cfg(all(windows, feature = "diagnostics"))]
fn blinks(frame: u64, resource: This, state: u32, shown: Option<bool>) {
static LAST: std::sync::Mutex<(bool, u64, u64)> = std::sync::Mutex::new((false, 0, 0));
let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner());
let drawn = crate::draw::drawn();
let black = shown.unwrap_or(false);
let draws = crate::draw::take_frame();
if black && !last.0 {
last.2 += 1;
tracing::warn!(
frame,
resource = ?resource,
state = format_args!("{state:#x}"),
draws = drawn - last.1,
copied = shown.is_some(),
black_frames = last.2,
levels = ?crate::capture::recent_levels(),
"a black frame after a frame that was not"
);
for d in draws {
tracing::warn!("black frame {frame}: {d}");
}
AFTER.store(frame + 6, Ordering::Relaxed);
}
// Six frames on: the levels around it (a fade or a single drop).
static AFTER: AtomicU64 = AtomicU64::new(0);
if AFTER.load(Ordering::Relaxed) == frame {
tracing::warn!(frame, levels = ?crate::capture::recent_levels(), "levels after the black frame");
}
*last = (black, drawn, last.2);
}
/// A run of destination pages: how they are mapped (0 pool pages from
/// `start` on, 1 pool page `start` each, 2 unmapped, 3 left as they are)
/// and how many.
#[repr(C)]
pub(crate) struct PageRange {
kind: u32,
start: u32,
count: u32,
}
/// The ranges mapped from a destination address on.
#[repr(C)]
pub(crate) struct PageBatch {
destination: u64,
count: u32,
ranges: *const PageRange,
}
/// Bytes per mapped page.
const PAGE: u64 = 64 << 10;
/// `CopyPageMappingsBatchX(count, batches, pool, pool pages, flags)`: maps
/// pages of a pool (memory the title mapped physical pages into) at the
/// batches' addresses. Grand Theft Auto VI streams textures into pool pages
/// and maps them into its tiled heap this way (title+0xf2c470, ranges of
/// one constant page or of unmapped pages). Done at once: every earlier
/// submission has run.
extern "system" fn copy_page_mappings(
_: This,
count: u32,
batches: *const PageBatch,
pool: u64,
pool_pages: u32,
_flags: u32,
) -> HRESULT {
let Some(map) = crate::resource::page_mapper() else {
return E_INVALIDARG;
};
if batches.is_null() && count > 0 {
return E_INVALIDARG;
}
let batches = (count > 0).then(|| {
// SAFETY: the title passes `count` batches.
unsafe { std::slice::from_raw_parts(batches, count as usize) }
});
let mut ok = true;
for b in batches.into_iter().flatten() {
if b.ranges.is_null() {
continue;
}
// SAFETY: each batch holds `count` ranges.
let ranges = unsafe { std::slice::from_raw_parts(b.ranges, b.count as usize) };
let mut at = b.destination;
for r in ranges {
let len = u64::from(r.count) * PAGE;
let inside = |pages: u32| r.start.checked_add(pages).is_some_and(|e| e <= pool_pages);
let source = pool + u64::from(r.start) * PAGE;
ok &= match r.kind {
0 if inside(r.count) => map(at, source, len),
1 if inside(1) => (0..u64::from(r.count)).all(|k| map(at + k * PAGE, source, PAGE)),
2 => map(at, 0, len),
3 => true,
_ => false,
};
at += len;
}
}
if !ok {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed"));
}
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.
@@ -166,30 +415,70 @@ extern "system" fn desc(this: This, out: *mut QueueDesc) {
}
}
/// 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::<QUEUE, 34>());
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)
};
/// The queue methods by their slot in older titles' queues (the 2020-era
/// layout): IUnknown 3, object 4, device child 1, queue 26 (12 as on PC,
/// then console ones).
const METHODS: [(usize, *const ()); 15] = [
(0, query as *const ()),
(2, release as *const ()),
(7, object::parent_device as *const ()), // 0x38
(10, execute as *const ()), // 0x50
(11, marker as *const ()), // 0x58 set marker
(12, marker as *const ()), // 0x60 begin event
(13, marker as *const ()), // 0x68 end event
(14, signal as *const ()), // 0x70
(15, wait as *const ()), // 0x78
(16, timestamp_frequency as *const ()), // 0x80
(26, desc as *const ()), // 0xd0
(29, copy_page_mappings as *const ()), // 0xe8 page mapping batch
(30, present as *const ()), // 0xf0
(33, execute_x as *const ()), // 0x108
(32, signal2_x as *const ()), // 0x100
];
/// Newer titles' queues have two more methods before Signal, which moved
/// from 0x70 to 0x80: every slot from 0x70 on is two later (taken here as
/// starting exactly at 0x70, the methods before it kept in place).
/// Inferred from Grand Theft Auto VI's calls: Signal 0x80 `(fence,
/// value)`, timestamp frequency 0x90 (title+0x24841a6), suspend and resume
/// 0xb8/0xc0, PresentX 0x100, the frame-token submission 0x118 `(count,
/// lists, token, flags)` (title+0x24821dd).
const fn newer_slot(slot: usize) -> usize {
if slot >= 14 { slot + 2 } else { slot }
}
const fn queue_table(newer: bool) -> [*const (); 36] {
let mut f = object::d3d12_object(object::missing_table::<QUEUE, 36>());
let mut i = 0;
while i < METHODS.len() {
let (slot, method) = METHODS[i];
f[if newer { newer_slot(slot) } else { slot }] = method;
i += 1;
}
f
}
static FUNCTIONS: Table<36> = Table(queue_table(false));
static NEWER_FUNCTIONS: Table<36> = Table(queue_table(true));
#[cfg(test)]
mod tests {
use super::*;
use crate::object::slot;
/// Where a queue's signal is: newer layouts have it two slots later.
/// Another test may switch layouts while this one runs, so the queue's
/// own table decides.
fn signal_slot(q: This) -> usize {
// SAFETY: one of our queues; its first field is the table.
let table = unsafe { *q.cast::<*const *const ()>() };
if table == NEWER_FUNCTIONS.0.as_ptr() {
0x80
} else {
0x70
}
}
#[test]
fn queue_signals_complete_at_once() {
let null = std::ptr::null();
@@ -209,7 +498,7 @@ mod tests {
crate::fence::create(null, 0, 0, fence_iid, &mut fence),
S_OK
);
let signal = slot::<extern "system" fn(This, This, u64) -> HRESULT>(q, 0x70);
let signal = slot::<extern "system" fn(This, This, u64) -> HRESULT>(q, signal_slot(q));
assert_eq!(signal(q, fence, 7), S_OK);
assert_eq!(
slot::<extern "system" fn(This) -> u64>(fence, 0x40)(fence),
@@ -217,4 +506,42 @@ mod tests {
);
assert_eq!(slot::<extern "system" fn(This) -> u32>(q, 0x10)(q), 0);
}
/// Grand Theft Auto VI's compute queue: `{COMPUTE, 0, pipe 1, queue 0}`.
#[test]
fn console_queues_are_created_as_on_pc() {
let null = std::ptr::null();
let desc = QueueDescX {
kind: 2,
flags: 0,
engine_or_pipe: 1,
queue: 0,
};
let mut q = null;
assert_eq!(create_x(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK);
assert_eq!(queue(q).desc.kind, 2);
let none = std::ptr::null();
assert_eq!(create_x(null, none, &QUEUE_IIDS[0], &mut q), E_INVALIDARG);
}
#[test]
fn newer_queues_have_their_methods_two_slots_later() {
let (old, new) = (queue_table(false), queue_table(true));
assert_eq!(old[10], new[10]); // submission stays at 0x50
assert_eq!(old[14], new[16]); // signal 0x70 → 0x80
assert_eq!(old[30], new[32]); // present 0xf0 → 0x100
assert_eq!(new[35], execute_x as *const ()); // 0x118
}
#[test]
fn timestamps_and_values_are_written() {
let mut at = [0u64; 2];
Written::Value(0x1_0000_0002).write(at.as_mut_ptr().cast(), 4);
assert_eq!(at[0], 2);
Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8);
let first = at[1];
std::thread::sleep(std::time::Duration::from_millis(2));
Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8);
assert!(at[1] > first);
}
}
+689 -38
View File
@@ -1,15 +1,16 @@
//! 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).
//! Heaps and resources are host memory and a resource's GPU address is its
//! CPU address, as on the console; textures also get a host copy, and
//! buffers a host copy when a draw reads them (`shadow`).
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::alloc::{Layout, alloc_zeroed, dealloc};
use std::ffi::c_void;
use std::ptr::NonNull;
use victory_formats::texture;
use crate::object::{
self, E_INVALIDARG, E_OUTOFMEMORY, HEAP, HRESULT, Iid, Object, RESOURCE, S_OK, Table, This,
guid,
@@ -112,29 +113,83 @@ 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)> {
/// compression), by DXGI format number. `None` for 1-bit and video
/// formats. The console adds 116/117 (10-bit float color), 118-120 (16-bit
/// depth with 8-bit stencil, two planes: 3 bytes per texel), 189 (signed
/// 10-bit color), 190 (two 4-bit channels) and 191 (24/8 color).
pub(crate) 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),
23..=47 | 67 | 87..=93 | 116 | 117 | 189 | 191 => (4, 1),
118..=120 => (3, 1),
48..=59 | 68 | 69 | 85 | 86 | 115 => (2, 1),
60..=65 => (1, 1),
60..=65 | 190 => (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).
/// A texture's layout in console memory, as the console's layout library
/// gives it (`victory-hle`'s `xg` serves the same): the description's
/// layout field is `0x100 | swizzle mode`, 1 linear, 0 the library's pick.
pub(crate) fn texture_layout(desc: &ResourceDesc) -> Option<texture::Texture> {
use texture::{Dimension, Swizzle, TextureDesc};
const TEXTURE_1D: u32 = 2;
const TEXTURE_2D: u32 = 3;
const RENDER_TARGET: u32 = 1;
const DEPTH: u32 = 2;
let dimension = match desc.dimension {
TEXTURE_1D => Dimension::Tex1d,
TEXTURE_2D => Dimension::Tex2d,
TEXTURE_3D => Dimension::Tex3d,
_ => return None,
};
let swizzle = match desc.layout {
0 if dimension == Dimension::Tex1d => Swizzle::LINEAR,
0 if desc.flags & DEPTH != 0 => Swizzle::SW_64KB_Z_X,
0 if desc.flags & RENDER_TARGET != 0 => Swizzle::SW_64KB_R_X,
0 => Swizzle::SW_4KB_S,
1 => Swizzle::LINEAR,
l if l & !0xff == 0x100 => Swizzle(l & 0xff),
_ => return None,
};
texture::Texture::new(&TextureDesc {
dimension,
width: u32::try_from(desc.width).ok()?,
height: desc.height,
depth_or_array: u32::from(desc.depth_or_array_size),
mips: u32::from(desc.mip_levels),
format: desc.format,
samples: desc.sample_count.max(1),
swizzle,
})
.ok()
}
/// Bytes and alignment a resource takes: buffers their width (64 KiB
/// aligned), textures their console layout (formats it does not know:
/// every mip of every array slice and sample, packed, 64 KiB aligned),
/// rounded up to the alignment.
fn footprint(desc: &ResourceDesc) -> Option<AllocationInfo> {
if desc.dimension != BUFFER
&& let Some(t) = texture_layout(desc)
{
// As the console: the layout's own alignment unless more is asked
// (4 KiB for 4 KiB modes, where PC says 64 KiB). Grand Theft Auto
// VI keeps these sizes in its texture tables, and its streaming
// asserts when they disagree with the streamed layout.
let alignment = desc.alignment.max(t.alignment);
if !alignment.is_power_of_two() {
return None;
}
return Some(AllocationInfo {
size: t.size.checked_next_multiple_of(alignment)?,
alignment,
});
}
let bytes = if desc.dimension == BUFFER {
desc.width
} else {
@@ -171,6 +226,72 @@ fn footprint(desc: &ResourceDesc) -> Option<AllocationInfo> {
})
}
/// A format as the host has it. The console's 16-bit depth with stencil
/// (and its typeless views) has no PC format: the 24-bit ones stand in.
pub(crate) fn pc_format(format: u32) -> u32 {
match format {
118 => 45,
119 => 46,
120 => 47,
other => other,
}
}
/// The typeless format of a format's family (itself if it has none).
pub(crate) fn family(format: u32) -> u32 {
const FAMILIES: [(u32, u32); 22] = [
(1, 4),
(5, 8),
(9, 14),
(15, 18),
(19, 22),
(23, 25),
(27, 32),
(33, 38),
(39, 43),
(44, 47),
(48, 52),
(53, 59),
(60, 65),
(70, 72),
(73, 75),
(76, 78),
(79, 81),
(82, 84),
(90, 91),
(92, 93),
(94, 96),
(97, 99),
];
match format {
87 => 90,
88 => 92,
f => FAMILIES
.iter()
.find(|&&(first, last)| (first..=last).contains(&f))
.map_or(f, |&(first, _)| first),
}
}
/// sRGB formats and their linear twins.
pub(crate) const SRGB: [(u32, u32); 3] = [(29, 28), (91, 87), (93, 88)];
/// The format a view of a title texture must name when its host copy is
/// typeless (see [`DEPTH_FORMATS`], [`SRGB`]): the title's own; `None` if
/// the host copy is typed.
pub(crate) fn view_format(this: This) -> Option<u32> {
let own = pc_format(resource(this).desc.format);
let host = host_resource(this)?;
// SAFETY: a live resource.
let format = unsafe { host.GetDesc() }.Format.0 as u32;
(format != own).then_some(own)
}
/// Depth formats with their typeless family: depth textures that shaders
/// read are made typeless on the host, which only allows views of
/// typeless depth resources.
pub(crate) const DEPTH_FORMATS: [(u32, u32); 4] = [(20, 19), (40, 39), (45, 44), (55, 53)];
/// Mip levels, the full chain for 0.
fn mip_count(desc: &ResourceDesc) -> u32 {
let depth = if desc.dimension == TEXTURE_3D {
@@ -342,34 +463,170 @@ pub(crate) extern "system" fn allocation_info(
// SAFETY: the title passes `count` descriptions.
unsafe { std::slice::from_raw_parts(descs, count as usize) }
};
// SAFETY: the caller passes room for the value.
unsafe { out.write(place(descs.iter(), |_, _| ())) };
out
}
/// The newer description: the plain one, then a sampler feedback mip
/// region (width, height, depth).
#[repr(C)]
pub(crate) struct ResourceDesc1 {
desc: ResourceDesc,
mip_region: [u32; 3],
}
const _: () = assert!(size_of::<ResourceDesc1>() == 72);
/// Where one resource goes in [`allocation_info2`]'s placement.
#[repr(C)]
pub(crate) struct AllocationInfo1 {
offset: u64,
alignment: u64,
size: u64,
}
/// Device method 0x360 (`ID3D12Device8`): [`allocation_info`] for newer
/// descriptions, also telling where each resource goes.
pub(crate) extern "system" fn allocation_info2(
out: *mut AllocationInfo,
_: This,
_visible: u32,
count: u32,
descs: *const ResourceDesc1,
each: *mut AllocationInfo1,
) -> *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 total = place(descs.iter().map(|d| &d.desc), |i, info| {
if !each.is_null() {
// SAFETY: the title passes room for `count` entries.
unsafe { each.add(i).write(info) };
}
});
// SAFETY: the caller passes room for the value.
unsafe { out.write(total) };
out
}
/// Resources placed one after another: the whole footprint, telling `each`
/// where every resource goes. Unknown sizes give the documented `u64::MAX`.
fn place<'a>(
descs: impl Iterator<Item = &'a ResourceDesc>,
mut each: impl FnMut(usize, AllocationInfo1),
) -> AllocationInfo {
let mut total = AllocationInfo {
size: 0,
alignment: KIB_64,
};
for desc in descs {
for (i, desc) in descs.enumerate() {
let Some(one) = footprint(desc) else {
tracing::warn!(?desc, "no size for this resource");
total = AllocationInfo {
each(
i,
AllocationInfo1 {
offset: u64::MAX,
alignment: 0,
size: u64::MAX,
},
);
return AllocationInfo {
size: u64::MAX,
alignment: 0,
};
break;
};
total.size = total.size.next_multiple_of(one.alignment) + one.size;
tracing::debug!(?desc, ?one, "allocation info");
let offset = total.size.next_multiple_of(one.alignment);
each(
i,
AllocationInfo1 {
offset,
alignment: one.alignment,
size: one.size,
},
);
total.size = offset + one.size;
total.alignment = total.alignment.max(one.alignment);
}
// SAFETY: the caller passes room for the value.
unsafe { out.write(total) };
out
total
}
/// Zeroed host memory standing in for GPU memory.
pub(crate) struct Memory {
ptr: NonNull<u8>,
layout: Layout,
/// Set when the memory came from the title's allocator, with these
/// allocation attributes (it goes back there).
attributes: Option<u64>,
}
pub type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void;
pub type FreeRoutine = extern "system" fn(*mut c_void, u64);
static ALLOCATOR: std::sync::OnceLock<(AllocRoutine, FreeRoutine)> = std::sync::OnceLock::new();
/// Committed resources get their memory from the title's general
/// allocator, as on the console, where titles hook it to place graphics
/// memory themselves (Grand Theft Auto VI places its back buffers in a
/// block of its own and checks they fill it). The runtime names it before
/// the device exists.
pub fn use_allocator(alloc: AllocRoutine, free: FreeRoutine) {
let _ = ALLOCATOR.set((alloc, free));
}
/// Maps the physical pages behind one range of title memory at another,
/// `(to, from, len)` (`from` 0 unmaps); false on failure.
pub type PageMapper = fn(u64, u64, u64) -> bool;
static PAGE_MAPPER: std::sync::OnceLock<PageMapper> = std::sync::OnceLock::new();
/// The runtime's page mapper, for the queues' page-mapping copies (memory
/// is the runtime's, as on the console).
pub fn use_page_mapper(mapper: PageMapper) {
let _ = PAGE_MAPPER.set(mapper);
}
pub(crate) fn page_mapper() -> Option<PageMapper> {
PAGE_MAPPER.get().copied()
}
/// Allocation attributes for resource memory: allocator id, page size
/// (bits 14-15: 2 MiB pages from 2 MiB up, else 64 KiB), alignment as log2
/// (bits 24-28) and memory type (bits 29-32: write-combined for GPU-only
/// heaps, cacheable for the CPU-visible ones).
/// shortcut: the console runtime's own choice of page size and memory type
/// is not known; this is the plausible one.
fn resource_attributes(info: AllocationInfo, heap_kind: u32) -> u64 {
const GRAPHICS_ALLOCATOR: u64 = 128 << 16;
const DEFAULT_HEAP: u32 = 1;
let pages: u64 = if info.size >= 2 << 20 { 2 } else { 1 };
let memory: u64 = if heap_kind == DEFAULT_HEAP { 1 } else { 3 };
let alignment = u64::from(info.alignment.max(1).trailing_zeros());
GRAPHICS_ALLOCATOR | pages << 14 | alignment << 24 | memory << 29
}
impl Memory {
/// A committed resource's memory: from the title's allocator if the
/// runtime named one, else our own; zeroed either way.
fn for_resource(info: AllocationInfo, heap_kind: u32) -> Result<Memory, HRESULT> {
let Some(&(alloc, _)) = ALLOCATOR.get() else {
return Memory::new(info);
};
let layout = Layout::from_size_align(info.size as usize, info.alignment as usize)
.map_err(|_| E_INVALIDARG)?;
let attributes = resource_attributes(info, heap_kind);
let ptr =
NonNull::new(alloc(layout.size(), attributes).cast::<u8>()).ok_or(E_OUTOFMEMORY)?;
// SAFETY: the allocator handed out `size` bytes.
unsafe { ptr.as_ptr().write_bytes(0, layout.size()) };
Ok(Memory {
ptr,
layout,
attributes: Some(attributes),
})
}
/// `size` zeroed bytes aligned to `alignment` (a power of two).
pub(crate) fn zeroed(size: u64, alignment: u64) -> Result<Memory, HRESULT> {
Memory::new(AllocationInfo { size, alignment })
@@ -388,14 +645,21 @@ impl Memory {
.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 })
Ok(Memory {
ptr,
layout,
attributes: None,
})
}
}
impl Drop for Memory {
fn drop(&mut self) {
match (self.attributes, ALLOCATOR.get()) {
(Some(attributes), Some(&(_, free))) => free(self.ptr.as_ptr().cast(), attributes),
// SAFETY: allocated in `new` with this layout.
unsafe { dealloc(self.ptr.as_ptr(), self.layout) };
_ => unsafe { dealloc(self.ptr.as_ptr(), self.layout) },
}
}
}
@@ -458,7 +722,12 @@ extern "system" fn heap_desc(this: This, out: *mut HeapDesc) {
/// to.
enum Backing {
Committed(Memory),
Placed { heap: This, offset: u64 },
Placed {
heap: This,
offset: u64,
},
/// Memory the title mapped itself, at this address.
Address(*mut u8),
}
impl Drop for Backing {
@@ -499,6 +768,15 @@ pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u
(before != wanted).then(|| (host.as_raw(), before))
}
/// Sets the state the host texture is in after a submission; returns the
/// one it was in.
#[cfg(windows)]
pub(crate) fn swap_host_state(this: This, state: u32) -> u32 {
resource(this)
.host_state
.swap(state, std::sync::atomic::Ordering::Relaxed)
}
/// The host GPU's copy of a title resource, if it has one.
#[cfg(windows)]
pub(crate) fn host_resource<'a>(
@@ -528,6 +806,35 @@ fn host_texture(
d.layout = 0;
d.alignment = 0;
d.flags &= PC_FLAGS;
// PC refuses depth targets that are also unordered-access (the console
// allows both; Grand Theft Auto VI's shadow maps ask for it).
// shortcut: the host copy loses UAV use; give it a second view-only
// copy if draws write it as a UAV.
const DEPTH: u32 = 2;
const UNORDERED: u32 = 4;
if d.flags & DEPTH != 0 {
d.flags &= !UNORDERED;
}
d.format = pc_format(d.format);
const DENY_SHADER_RESOURCE: u32 = 8;
if d.flags & DENY_SHADER_RESOURCE == 0
&& let Some(&(_, typeless)) = DEPTH_FORMATS.iter().find(|&&(f, _)| f == d.format)
{
d.format = typeless;
}
// The host has no sRGB unordered access: such textures are typeless,
// their unordered access views plain UNORM.
if d.flags & UNORDERED != 0 && SRGB.iter().any(|&(srgb, _)| srgb == d.format) {
d.format = family(d.format);
}
// The clear value names the format too: format, then color or depth
// and stencil (5 words).
let clear_value = (!clear.is_null()).then(|| {
// SAFETY: the title passes a whole clear value.
let mut value = unsafe { clear.cast::<[u32; 5]>().read_unaligned() };
value[0] = pc_format(value[0]);
value
});
let heap = D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_DEFAULT,
..Default::default()
@@ -540,18 +847,34 @@ fn host_texture(
&heap,
D3D12_HEAP_FLAG_NONE,
(&raw const d).cast(),
D3D12_RESOURCE_STATES(crate::host::texture_state(state) as i32),
D3D12_RESOURCE_STATES(
crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32,
),
// The same layout: format, then color or depth and stencil.
(!clear.is_null()).then_some(clear.cast()),
clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()),
&mut texture,
)
};
if let Err(e) = made {
tracing::warn!(error = %e, desc = ?d, "no host texture");
}
if let Some(t) = &texture {
crate::host::name(t, || {
format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags)
});
}
texture
}
/// A texture's console memory and description; `None` for buffers.
pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> {
if this.is_null() {
return None;
}
let r = resource(this);
(r.desc.dimension != BUFFER).then(|| (r.data().cast_const(), r.desc))
}
/// 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() {
@@ -573,6 +896,7 @@ impl Resource {
.as_ptr()
.add(offset as usize)
},
Backing::Address(at) => at,
}
}
}
@@ -596,6 +920,8 @@ fn hand_out_resource(
) -> HRESULT {
#[cfg(not(windows))]
let _ = (state, clear);
#[cfg(windows)]
let host = host_texture(&desc, state, clear);
let resource = Box::new(Resource {
object: Object::new(&RESOURCE_FUNCTIONS),
desc,
@@ -603,13 +929,35 @@ fn hand_out_resource(
heap_flags,
backing,
#[cfg(windows)]
host: host_texture(&desc, state, clear),
host_state: host
.as_ref()
.map_or(0, |t| crate::host::legal_state(t, crate::host::texture_state(state)))
.into(),
#[cfg(windows)]
host_state: crate::host::texture_state(state).into(),
host,
});
#[cfg(windows)]
if desc.dimension == BUFFER {
let at = std::ptr::from_ref::<Resource>(&resource) as usize;
crate::shadow::register(at, resource.data() as u64, desc.width);
}
object::hand_out(RESOURCE, resource, iid, &RESOURCE_IIDS, out)
}
#[cfg(windows)]
impl Drop for Resource {
fn drop(&mut self) {
crate::texture::forget(std::ptr::from_ref::<Resource>(self) as usize);
crate::descriptor::forget(std::ptr::from_ref::<Resource>(self) as usize);
if self.desc.dimension == BUFFER {
crate::shadow::unregister(
std::ptr::from_ref::<Resource>(self) as usize,
self.data() as u64,
);
}
}
}
pub(crate) extern "system" fn create_committed(
_: This,
heap: *const HeapProperties,
@@ -634,7 +982,7 @@ pub(crate) extern "system" fn create_committed(
heap = heap.kind,
"committed resource"
);
let memory = match Memory::new(info) {
let memory = match Memory::for_resource(info, heap.kind) {
Ok(memory) => memory,
Err(hr) => return hr,
};
@@ -650,6 +998,159 @@ pub(crate) extern "system" fn create_committed(
)
}
/// Device method 0x3f8, inferred from Grand Theft Auto VI's calls
/// (title+0x193e1b4: its back buffers, heap flag "allow display"): the
/// committed resource creation of the enhanced-barrier interfaces,
/// `(heap, heap flags, desc1, initial layout, clear value, protected
/// session, castable format count, castable formats, iid, out)`. The host
/// copy starts in the common state, as layouts are not tracked.
#[allow(clippy::too_many_arguments)] // the method's own arguments
pub(crate) extern "system" fn create_committed3(
this: This,
heap: *const HeapProperties,
heap_flags: u32,
desc: *const ResourceDesc,
_layout: u32,
clear: *const c_void,
_protected: This,
_castable_count: u32,
_castable: *const u32,
iid: *const Iid,
out: *mut This,
) -> HRESULT {
const COMMON: u32 = 0;
create_committed(this, heap, heap_flags, desc, COMMON, clear, iid, out)
}
/// Registered page pools (64 KiB pages the title maps into tiled
/// resources by page index): first address and page count; a handle is an
/// index plus one, a removed pool leaves `None`.
static PAGE_POOLS: std::sync::Mutex<Vec<Option<(u64, u32)>>> = std::sync::Mutex::new(Vec::new());
fn page_pools() -> std::sync::MutexGuard<'static, Vec<Option<(u64, u32)>>> {
PAGE_POOLS.lock().unwrap_or_else(|e| e.into_inner())
}
/// Device method 0x250: `(address, page count, handle out)`.
pub(crate) extern "system" fn register_page_pool(
_: This,
address: u64,
pages: u32,
out: *mut usize,
) -> HRESULT {
if out.is_null() || pages == 0 || !address.is_multiple_of(KIB_64) {
return E_INVALIDARG;
}
tracing::debug!(address = format_args!("{address:#x}"), pages, "page pool");
let mut pools = page_pools();
pools.push(Some((address, pages)));
// SAFETY: checked non-null; the title passes room for a handle.
unsafe { out.write(pools.len()) };
S_OK
}
/// Device method 0x258.
pub(crate) extern "system" fn unregister_page_pool(_: This, handle: usize) -> HRESULT {
match page_pools().get_mut(handle.wrapping_sub(1)) {
Some(pool @ Some(_)) => {
*pool = None;
S_OK
}
_ => E_INVALIDARG,
}
}
/// Device method 0x428, one of the `ID3D12Device9` to `ID3D12Device11`
/// additions. From Grand Theft Auto VI's call: a resource at a virtual
/// address the title mapped itself, `(address, desc1, initial barrier
/// layout, clear value, iid, out)`, as `CreatePlacedResourceX` with
/// enhanced barriers. GPU addresses are CPU addresses, so the resource is
/// a view of that memory. `D3D12_RESOURCE_DESC1` starts like the plain
/// description; its sampler feedback region is not needed.
pub(crate) extern "system" fn create_at_address(
_: This,
address: u64,
desc: *const ResourceDesc,
layout: 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 address == 0 {
return E_INVALIDARG;
}
tracing::debug!(
address = format_args!("{address:#x}"),
dimension = desc.dimension,
width = desc.width,
layout,
"resource at an address"
);
const COMMON: u32 = 0;
const DEFAULT: HeapProperties = HeapProperties {
kind: 1,
cpu_pages: 0,
pool: 0,
creation_nodes: 1,
visible_nodes: 1,
};
hand_out_resource(
desc,
DEFAULT,
0,
Backing::Address(address as *mut u8),
COMMON,
clear,
iid,
out,
)
}
/// Textures the title placed in its own memory and views without a
/// resource object (device 0x230, Grand Theft Auto VI's streamed and
/// interface textures), by address and description: a resource at that
/// address, made the first time a draw reads one.
/// shortcut: never released (one host texture per distinct address and
/// description viewed); release them when the title unmaps or reuses the
/// memory once streaming grows VRAM use.
#[cfg(windows)]
static PLACED_TEXTURES: std::sync::Mutex<std::collections::BTreeMap<(u64, [u32; 14]), usize>> =
std::sync::Mutex::new(std::collections::BTreeMap::new());
/// The resource for a texture placed at `address` with the resource
/// description `desc` (as words), made on first use.
#[cfg(windows)]
pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> {
let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner());
if let Some(&r) = map.get(&(address, *desc)) {
return Some(r as This);
}
// SAFETY: 56 bytes in the description's layout.
let d = unsafe { desc.as_ptr().cast::<ResourceDesc>().read_unaligned() };
if d.dimension == BUFFER {
return None;
}
let mut out = std::ptr::null();
let made = create_at_address(
std::ptr::null(),
address,
&d,
0,
std::ptr::null(),
&RESOURCE_IIDS[0],
&mut out,
);
if made != S_OK {
return None;
}
map.insert((address, *desc), out as usize);
resource(out).host.is_some().then_some(out)
}
pub(crate) extern "system" fn create_placed(
_: This,
heap: This,
@@ -725,8 +1226,59 @@ extern "system" fn resource_desc(this: This, out: *mut ResourceDesc) {
unsafe { out.write(resource(this).desc) };
}
}
/// Device method `GetCustomHeapProperties`, returning its struct through a
/// hidden first argument: what a standard heap type is as a custom heap.
/// Memory is unified and cache-coherent (as the architecture query says),
/// so every type is in pool L0, default heaps are not CPU-visible and the
/// others are write-back.
pub(crate) extern "system" fn custom_heap_properties(
out: *mut HeapProperties,
_: This,
nodes: u32,
kind: u32,
) -> *mut HeapProperties {
const CUSTOM: u32 = 4;
const NOT_AVAILABLE: u32 = 1;
const WRITE_BACK: u32 = 3;
const L0: u32 = 1;
let nodes = nodes.max(1);
let cpu_pages = match kind {
1 => NOT_AVAILABLE,
2 | 3 => WRITE_BACK,
_ => 0,
};
let properties = HeapProperties {
kind: CUSTOM,
cpu_pages,
pool: if cpu_pages == 0 { 0 } else { L0 },
creation_nodes: nodes,
visible_nodes: nodes,
};
// SAFETY: the title passes room for the result (null is tolerated).
if let Some(out) = unsafe { out.as_mut() } {
*out = properties;
}
out
}
extern "system" fn gpu_address(this: This) -> u64 {
resource(this).data() as u64
let r = resource(this);
let at = r.data() as u64;
// The console's GPU addresses fit in 40 bits; its ray-tracing builder
// refuses others (diagnostics: which memory breaks that).
#[cfg(feature = "diagnostics")]
if at >> 40 != 0 {
static ONCE: [std::sync::Once; 2] = [std::sync::Once::new(), std::sync::Once::new()];
let backing = match r.backing {
Backing::Committed(ref m) => format!("committed, attributes {:?}", m.attributes),
Backing::Placed { offset, .. } => format!("placed in a heap at {offset:#x}"),
Backing::Address(_) => "at a title address".into(),
};
ONCE[usize::from(r.desc.dimension == BUFFER)].call_once(|| {
tracing::warn!(address = format_args!("{at:#x}"), backing, desc = ?r.desc, "a GPU address above 40 bits")
});
}
at
}
extern "system" fn heap_properties(
this: This,
@@ -747,8 +1299,8 @@ extern "system" fn heap_properties(
}
/// IUnknown 3, object 4, device child 1, heap 1.
static HEAP_FUNCTIONS: Table<9> = {
let mut f = object::d3d12_object(object::missing_table::<HEAP, 9>());
static HEAP_FUNCTIONS: Table<24> = {
let mut f = object::d3d12_object(object::missing_table::<HEAP, 24>());
f[0] = heap_query as *const ();
f[2] = heap_release as *const ();
f[7] = object::parent_device as *const (); // 0x38
@@ -758,8 +1310,8 @@ static HEAP_FUNCTIONS: Table<9> = {
/// 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::<RESOURCE, 18>());
static RESOURCE_FUNCTIONS: Table<32> = {
let mut f = object::d3d12_object(object::missing_table::<RESOURCE, 32>());
f[0] = resource_query as *const ();
f[2] = resource_release as *const ();
f[7] = object::parent_device as *const (); // 0x38
@@ -856,15 +1408,114 @@ mod tests {
);
}
#[test]
fn device_setup_heap_properties_and_resources_at_addresses() {
let device = crate::device::device();
// GetCustomHeapProperties (0xd0): the struct comes back through the
// hidden first argument, which is also returned.
type Custom =
extern "system" fn(*mut HeapProperties, This, u32, u32) -> *mut HeapProperties;
let mut p = PROPERTIES;
let back = slot::<Custom>(device, 0xd0)(&mut p, device, 1, 2);
assert_eq!(back, &raw mut p);
assert_eq!(
(
p.kind,
p.cpu_pages,
p.pool,
p.creation_nodes,
p.visible_nodes
),
(4, 3, 1, 1, 1),
"upload: custom, write-back, L0"
);
slot::<Custom>(device, 0xd0)(&mut p, device, 1, 1);
assert_eq!(p.cpu_pages, 1, "default: not CPU-visible");
// 0x428: a buffer over memory the title owns, as GTA VI asks.
type At = extern "system" fn(
This,
u64,
*const ResourceDesc,
u32,
*const c_void,
*const Iid,
*mut This,
) -> HRESULT;
let memory = vec![0u8; 0x1_0000];
let address = memory.as_ptr() as u64;
let mut r = std::ptr::null();
let create = slot::<At>(device, 0x428);
let desc = buffer(0x1_0000);
let null = std::ptr::null();
assert_eq!(
create(
device,
address,
&desc,
u32::MAX,
null,
&RESOURCE_IIDS[0],
&mut r
),
0
);
assert_eq!(slot::<Address>(r, 0x58)(r), address);
assert_eq!(slot::<Release>(r, 0x10)(r), 0);
// The title's memory is still there after the release.
assert_eq!(memory[0xffff], 0);
assert_ne!(
create(device, 0, &desc, u32::MAX, null, &RESOURCE_IIDS[0], &mut r),
0
);
}
#[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));
// Textures take their console layout and its alignment (4 KiB
// standard swizzle when the description leaves it to the library):
// 512x512 BC7 with 10 mips is 0x56000 bytes, 4 KiB aligned, as on
// the console.
let layout = |d: &ResourceDesc| texture_layout(d).unwrap().size;
let rgba = texture(256, 256, 28, 0);
assert_eq!(size(&rgba), Some(layout(&rgba).next_multiple_of(4096)));
let bc7 = footprint(&texture(512, 512, 98, 10));
let console = AllocationInfo {
size: 0x56000,
alignment: 0x1000,
};
assert_eq!(bc7, Some(console));
assert!(layout(&rgba) >= 4 * (256 * 256 * 4) / 3, "every mip");
// 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");
// Linear layout (1) and an explicit mode (64 KiB display, 0x10a).
let linear = ResourceDesc {
layout: 1,
..texture(100, 60, 28, 1)
};
assert_eq!(
texture_layout(&linear).unwrap().planes[0]
.layout
.desc
.swizzle
.0,
0
);
let display = ResourceDesc {
layout: 0x10a,
..texture(100, 60, 28, 1)
};
assert_eq!(
texture_layout(&display).unwrap().planes[0]
.layout
.desc
.swizzle
.0,
10
);
let mut info = AllocationInfo {
size: 0,
@@ -875,7 +1526,7 @@ mod tests {
assert_eq!(
info,
AllocationInfo {
size: (64 + 384) << 10,
size: KIB_64 + size(&descs[1]).unwrap(),
alignment: KIB_64
}
);
+159 -31
View File
@@ -1,12 +1,12 @@
//! 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.
//! Serializing goes to the host's `D3D12SerializeRootSignature` (or its
//! versioned form): 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::ffi::{CStr, c_void};
use std::sync::OnceLock;
use crate::object::{
@@ -37,23 +37,32 @@ pub struct Desc {
flags: u32,
}
/// Every version's description starts with the fields of [`Desc`].
#[repr(C)]
#[derive(Clone, Copy)]
pub struct VersionedDesc {
version: u32,
desc: Desc,
}
type Serialize =
unsafe extern "system" fn(*const Desc, u32, *mut *mut c_void, *mut *mut c_void) -> HRESULT;
type SerializeVersioned =
unsafe extern "system" fn(*const VersionedDesc, *mut *mut c_void, *mut *mut c_void) -> HRESULT;
/// The host's serializer, from `d3d12.dll` in System32.
fn host_serializer() -> Option<Serialize> {
static FUNCTION: OnceLock<Option<usize>> = OnceLock::new();
let address = *FUNCTION.get_or_init(|| {
/// An export of the host's `d3d12.dll` in System32, looked up once.
fn host_export(cache: &OnceLock<Option<usize>>, name: &CStr) -> Option<usize> {
*cache.get_or_init(|| {
#[cfg(windows)]
{
use windows_sys::Win32::System::LibraryLoader::{
GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
};
let name: Vec<u16> = "d3d12.dll".encode_utf16().chain([0]).collect();
let dll: Vec<u16> = "d3d12.dll".encode_utf16().chain([0]).collect();
// SAFETY: a NUL-terminated name; System32 only.
let module = unsafe {
LoadLibraryExW(
name.as_ptr(),
dll.as_ptr(),
std::ptr::null_mut(),
LOAD_LIBRARY_SEARCH_SYSTEM32,
)
@@ -62,14 +71,24 @@ fn host_serializer() -> Option<Serialize> {
return None;
}
// SAFETY: a loaded module and a NUL-terminated name.
unsafe { GetProcAddress(module, c"D3D12SerializeRootSignature".as_ptr().cast()) }
.map(|f| f as usize)
unsafe { GetProcAddress(module, name.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::<usize, Serialize>(a) })
})
}
fn without_console_flags(desc: Desc) -> Desc {
if desc.flags & CONSOLE_FLAGS != 0 {
tracing::debug!(
flags = format_args!("{:#x}", desc.flags),
"console root signature flags dropped"
);
}
Desc {
flags: desc.flags & !CONSOLE_FLAGS,
..desc
}
}
/// `d3d12_xs!D3D12SerializeRootSignature`.
@@ -83,22 +102,68 @@ pub extern "system" fn serialize(
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 {
static FUNCTION: OnceLock<Option<usize>> = OnceLock::new();
let Some(address) = host_export(&FUNCTION, c"D3D12SerializeRootSignature") 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) }
// SAFETY: the export has this signature; it takes what the title passed.
unsafe {
std::mem::transmute::<usize, Serialize>(address)(
&without_console_flags(desc),
version,
blob,
error,
)
}
}
/// `d3d12_xs!D3D12SerializeVersionedRootSignature`.
pub extern "system" fn serialize_versioned(
desc: *const VersionedDesc,
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;
};
static FUNCTION: OnceLock<Option<usize>> = OnceLock::new();
let Some(address) = host_export(&FUNCTION, c"D3D12SerializeVersionedRootSignature") else {
tracing::warn!("no host d3d12.dll to serialize root signatures");
return E_NOTIMPL;
};
let desc = VersionedDesc {
desc: without_console_flags(desc.desc),
..desc
};
// SAFETY: the export has this signature; it takes what the title passed.
unsafe { std::mem::transmute::<usize, SerializeVersioned>(address)(&desc, blob, error) }
}
type Deserialize =
unsafe extern "system" fn(*const u8, usize, *const Iid, *mut *mut c_void) -> HRESULT;
/// `d3d12_xs!D3D12CreateRootSignatureDeserializer`: our blobs are the
/// host's serialization, so the host's deserializer reads them, and its
/// object (IUnknown, then the description getter) is laid out as the
/// console's. Grand Theft Auto VI's upscaler asks with the PC interface id.
pub extern "system" fn create_deserializer(
blob: *const u8,
size: usize,
iid: *const Iid,
out: *mut *mut c_void,
) -> HRESULT {
if blob.is_null() || out.is_null() {
return E_INVALIDARG;
}
static FUNCTION: OnceLock<Option<usize>> = OnceLock::new();
let Some(address) = host_export(&FUNCTION, c"D3D12CreateRootSignatureDeserializer") else {
tracing::warn!("no host d3d12.dll to deserialize root signatures");
return E_NOTIMPL;
};
// SAFETY: the export has this signature; it takes what the title passed.
unsafe { std::mem::transmute::<usize, Deserialize>(address)(blob, size, iid, out) }
}
#[repr(C)]
@@ -139,8 +204,8 @@ extern "system" fn release(this: This) -> u32 {
}
/// IUnknown 3, object 4, device child 1.
static FUNCTIONS: Table<8> = {
let mut f = object::d3d12_object(object::missing_table::<ROOT_SIGNATURE, 8>());
static FUNCTIONS: Table<24> = {
let mut f = object::d3d12_object(object::missing_table::<ROOT_SIGNATURE, 24>());
f[0] = query as *const ();
f[2] = release as *const ();
f[7] = object::parent_device as *const (); // 0x38
@@ -193,4 +258,67 @@ mod tests {
assert_eq!(slot::<extern "system" fn(This) -> u32>(root, 0x10)(root), 0);
slot::<extern "system" fn(This) -> u32>(blob, 0x10)(blob);
}
/// The host's deserializer reads our blobs back (the upscaler's call).
#[cfg(windows)]
#[test]
fn our_blobs_deserialize_on_the_host() {
use windows::Win32::Graphics::Direct3D12::ID3D12RootSignatureDeserializer;
use windows::core::Interface;
let desc = VersionedDesc {
version: 1,
desc: Desc {
parameter_count: 0,
parameters: std::ptr::null(),
sampler_count: 0,
samplers: std::ptr::null(),
flags: 1,
},
};
let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut());
assert_eq!(serialize_versioned(&desc, &mut blob, &mut error), S_OK);
let blob = blob.cast_const().cast::<Object>();
let data = slot::<extern "system" fn(This) -> *const u8>(blob, 0x18)(blob);
let size = slot::<extern "system" fn(This) -> usize>(blob, 0x20)(blob);
let iid: Iid = ID3D12RootSignatureDeserializer::IID.to_u128().to_be_bytes();
let iid = guid(
u32::from_be_bytes(iid[0..4].try_into().unwrap()),
u16::from_be_bytes(iid[4..6].try_into().unwrap()),
u16::from_be_bytes(iid[6..8].try_into().unwrap()),
iid[8..16].try_into().unwrap(),
);
let mut out = std::ptr::null_mut();
assert_eq!(create_deserializer(data, size, &iid, &mut out), S_OK);
// SAFETY: the host handed out this interface.
let deserializer = unsafe { ID3D12RootSignatureDeserializer::from_raw(out) };
// SAFETY: valid while the deserializer lives.
let read = unsafe { &*deserializer.GetRootSignatureDesc() };
assert_eq!((read.NumParameters, read.Flags.0), (0, 1));
slot::<extern "system" fn(This) -> u32>(blob, 0x10)(blob);
}
/// Version 1.0 through the versioned entry point, with a console flag.
#[cfg(windows)]
#[test]
fn versioned_descriptions_serialize_on_the_host() {
let desc = VersionedDesc {
version: 1,
desc: Desc {
parameter_count: 0,
parameters: std::ptr::null(),
sampler_count: 0,
samplers: std::ptr::null(),
flags: 0x0200_0001,
},
};
let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut());
assert_eq!(serialize_versioned(&desc, &mut blob, &mut error), S_OK);
let blob = blob.cast_const().cast::<Object>();
assert!(slot::<extern "system" fn(This) -> usize>(blob, 0x20)(blob) > 0);
slot::<extern "system" fn(This) -> u32>(blob, 0x10)(blob);
assert_eq!(
serialize_versioned(std::ptr::null(), &mut blob.cast_mut().cast(), &mut error),
E_INVALIDARG
);
}
}
+119
View File
@@ -0,0 +1,119 @@
//! Samplers as the host describes them, from the console's sampler
//! description (`CreateSamplerX`), which names the hardware's sampler
//! fields. (Immediate samplers in shader code come decoded with the
//! translation.)
use windows::Win32::Graphics::Direct3D12::*;
/// The fields both forms share.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Fields {
/// Point 0, bilinear 1, anisotropic point 2, anisotropic bilinear 3.
mag: u32,
min: u32,
/// None 0, point 1, linear 2.
mip: u32,
/// Plain 0, minimum 1, maximum 2.
mode: u32,
/// Host address modes.
address: [u32; 3],
anisotropy: u32,
/// Host comparison function.
compare: u32,
min_lod: f32,
max_lod: f32,
bias: f32,
border: [f32; 4],
}
impl Fields {
fn host(&self) -> D3D12_SAMPLER_DESC {
let linear = |f: u32| u32::from(f == 1 || f == 3);
let aniso = self.mag >= 2 || self.min >= 2;
// The console compares when the instruction says so, with the
// sampler's function; the host needs a comparison sampler for that.
// A sampler given a real test (less ... greater-or-equal) is one;
// never, always and none are plain samplers.
const LESS: u32 = 2;
const GREATER_EQUAL: u32 = 7;
let compares = (LESS..=GREATER_EQUAL).contains(&self.compare);
let reduction = match self.mode {
1 => 2,
2 => 3,
_ => u32::from(compares),
};
let filter = if aniso {
0x55
} else {
linear(self.min) << 4 | linear(self.mag) << 2 | u32::from(self.mip == 2)
};
D3D12_SAMPLER_DESC {
Filter: D3D12_FILTER((reduction << 7 | filter) as i32),
AddressU: D3D12_TEXTURE_ADDRESS_MODE(self.address[0] as i32),
AddressV: D3D12_TEXTURE_ADDRESS_MODE(self.address[1] as i32),
AddressW: D3D12_TEXTURE_ADDRESS_MODE(self.address[2] as i32),
MipLODBias: self.bias,
MaxAnisotropy: if aniso {
self.anisotropy.clamp(1, 16)
} else {
1
},
ComparisonFunc: D3D12_COMPARISON_FUNC(self.compare.max(1) as i32),
BorderColor: self.border,
MinLOD: self.min_lod,
// Without a mip filter the console samples mip 0 only.
MaxLOD: if self.mip == 0 {
self.min_lod
} else {
self.max_lod
},
}
}
}
/// The console's sampler description (27 words): flags, magnification,
/// minification, mip and depth filters, filter mode, three address modes,
/// minimum and maximum LOD, LOD bias, secondary bias, anisotropy, its bias
/// and threshold, comparison, border color, then tuning words.
pub(crate) fn console(words: &[u32; 27]) -> D3D12_SAMPLER_DESC {
let f = |i: usize| f32::from_bits(words[i]);
Fields {
mag: words[1],
min: words[2],
mip: words[3],
mode: words[5],
address: [words[6], words[7], words[8]],
min_lod: f(9),
max_lod: f(10),
bias: f(11),
anisotropy: words[13],
compare: words[16],
border: [f(17), f(18), f(19), f(20)],
}
.host()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn console_descriptions_decode() {
let mut w = [0u32; 27];
w[1] = 1; // bilinear magnification
w[2] = 0; // point minification
w[3] = 2; // linear mips
w[6..9].copy_from_slice(&[3, 3, 3]);
w[10] = 1000.0f32.to_bits();
let d = console(&w);
assert_eq!(d.Filter.0, 0x5, "min point, mag and mip linear");
assert_eq!(d.AddressW, D3D12_TEXTURE_ADDRESS_MODE_CLAMP);
assert_eq!(d.MaxLOD, 1000.0);
// A less-or-equal test makes a comparison sampler; never does not.
w[16] = 4;
assert_eq!(console(&w).Filter.0, 0x85);
assert_eq!(console(&w).ComparisonFunc, D3D12_COMPARISON_FUNC_LESS_EQUAL);
w[16] = 1;
assert_eq!(console(&w).Filter.0, 0x5);
}
}
+347
View File
@@ -0,0 +1,347 @@
//! Translated shaders kept on disk (decision 0003): under the configured
//! cache folder, keyed by the container's content and by the VIctory build
//! that translated it (the BLAKE3 of our executable), so a rebuilt
//! translator never serves an old translation. Entries go through
//! `victory-pipeline`'s content-addressed cache, which writes them
//! atomically; an entry that does not read back is translated again.
//!
//! The entry is our own encoding of [`HostShader`]: a field added to it
//! must be added to [`encode`] and [`decode`] too (entries of older builds
//! are ignored anyway).
use std::path::PathBuf;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use victory_pipeline::{Cache, Converter};
use victory_shader::emit::{HostShader, StaticSampler, UserData};
use victory_shader::{HwStage, RootType};
static CACHE: OnceLock<Cache> = OnceLock::new();
static HITS: AtomicU64 = AtomicU64::new(0);
static MISSES: AtomicU64 = AtomicU64::new(0);
/// Keeps translated shaders in `dir` from now on.
pub fn use_shader_cache(dir: PathBuf) {
match Cache::open(dir) {
Ok(cache) => {
let _ = CACHE.set(cache);
}
Err(e) => tracing::warn!(error = %e, "no shader cache"),
}
}
/// Shaders found in the cache and translated since the start.
pub(crate) fn counts() -> (u64, u64) {
(HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed))
}
/// What identifies this build: the BLAKE3 of our executable file.
fn build() -> &'static [u8; 32] {
static BUILD: OnceLock<[u8; 32]> = OnceLock::new();
BUILD.get_or_init(|| {
let exe = std::env::current_exe().and_then(std::fs::read);
match exe {
Ok(bytes) => *blake3::hash(&bytes).as_bytes(),
Err(e) => {
// Without it no entry can be trusted: a fresh key per run.
tracing::warn!(error = %e, "cannot read our executable; shader cache unused");
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default();
*blake3::hash(&now.as_nanos().to_le_bytes()).as_bytes()
}
}
})
}
/// The translation of a console shader container, from the cache when
/// there is one.
pub(crate) fn host_shader(container: &[u8]) -> Result<HostShader, String> {
let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string());
match CACHE.get() {
Some(cache) => cached(cache, build(), container, translate),
None => translate(container),
}
}
/// The cache entry's converter: the build and the container in, the
/// encoded translation out. `ran` tells a miss from a hit.
struct Translate<F> {
translate: F,
ran: AtomicBool,
}
impl<F: Fn(&[u8]) -> Result<HostShader, String> + Send + Sync> Converter for Translate<F> {
fn id(&self) -> &'static str {
"shader.dxil"
}
fn version(&self) -> u32 {
// The build fingerprint in the input does the versioning.
1
}
fn convert(&self, input: &[u8]) -> anyhow::Result<Vec<u8>> {
self.ran.store(true, Ordering::Relaxed);
let shader = (self.translate)(&input[32..]).map_err(anyhow::Error::msg)?;
Ok(encode(&shader))
}
}
fn cached(
cache: &Cache,
build: &[u8; 32],
container: &[u8],
translate: impl Fn(&[u8]) -> Result<HostShader, String> + Send + Sync,
) -> Result<HostShader, String> {
let input = [&build[..], container].concat();
let converter = Translate {
translate,
ran: AtomicBool::new(false),
};
for _ in 0..2 {
let path = cache
.get_or_convert(&converter, &input)
.map_err(|e| format!("{e:#}"))?;
if let Some(shader) = std::fs::read(&path).ok().and_then(|b| decode(&b)) {
let (counter, what) = if converter.ran.load(Ordering::Relaxed) {
(&MISSES, "translated and cached")
} else {
(&HITS, "from the cache")
};
counter.fetch_add(1, Ordering::Relaxed);
tracing::debug!(path = %path.display(), "shader {what}");
return Ok(shader);
}
tracing::debug!(path = %path.display(), "unreadable shader cache entry; translating again");
let _ = std::fs::remove_file(&path);
}
MISSES.fetch_add(1, Ordering::Relaxed);
(converter.translate)(container)
}
const MAGIC: &[u8; 4] = b"VSH1";
const STAGES: [HwStage; 8] = [
HwStage::Ls,
HwStage::Hs,
HwStage::Es,
HwStage::Gs,
HwStage::Vs,
HwStage::Ps,
HwStage::Ms,
HwStage::Cs,
];
fn root_code(r: RootType) -> u32 {
match r {
RootType::Constants => 0,
RootType::Descriptor => 1,
RootType::Table => 2,
RootType::ImmediateSampler => 3,
RootType::ResourceHeap => 4,
RootType::SamplerHeap => 5,
RootType::Other(x) => 6 + x,
}
}
fn root_type(code: u32) -> RootType {
match code {
0 => RootType::Constants,
1 => RootType::Descriptor,
2 => RootType::Table,
3 => RootType::ImmediateSampler,
4 => RootType::ResourceHeap,
5 => RootType::SamplerHeap,
x => RootType::Other(x - 6),
}
}
/// Little-endian words and length-prefixed lists.
fn encode(s: &HostShader) -> Vec<u8> {
let mut out = MAGIC.to_vec();
let word = |out: &mut Vec<u8>, v: u32| out.extend(v.to_le_bytes());
let stage = STAGES.iter().position(|&x| x == s.stage).unwrap_or(0) as u32;
word(&mut out, stage);
word(&mut out, s.dxil.len() as u32);
out.extend(&s.dxil);
word(&mut out, s.user_data.len() as u32);
for u in &s.user_data {
for v in [u.index, u32::from(u.slot), root_code(u.root), u.dword] {
word(&mut out, v);
}
}
word(&mut out, s.samplers.len() as u32);
for sampler in &s.samplers {
for &v in sampler {
word(&mut out, v);
}
}
word(&mut out, s.static_samplers.len() as u32);
for t in &s.static_samplers {
let [u, v, w] = t.address;
let words = [
t.filter,
u,
v,
w,
t.mip_lod_bias.to_bits(),
t.max_anisotropy,
t.comparison,
t.border,
t.min_lod.to_bits(),
t.max_lod.to_bits(),
];
for v in words {
word(&mut out, v);
}
}
for slots in [&s.root_cbvs, &s.root_srvs] {
word(&mut out, slots.len() as u32);
out.extend(slots);
}
out
}
fn decode(bytes: &[u8]) -> Option<HostShader> {
struct Reader<'a>(&'a [u8]);
impl<'a> Reader<'a> {
fn take(&mut self, n: usize) -> Option<&'a [u8]> {
let (head, rest) = self.0.split_at_checked(n)?;
self.0 = rest;
Some(head)
}
fn word(&mut self) -> Option<u32> {
Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?))
}
fn list(&mut self) -> Option<Vec<u8>> {
let n = self.word()? as usize;
Some(self.take(n)?.to_vec())
}
}
let mut r = Reader(bytes);
if r.take(4)? != MAGIC {
return None;
}
let stage = *STAGES.get(r.word()? as usize)?;
let dxil = r.list()?;
let n = r.word()? as usize;
let mut user_data = Vec::with_capacity(n.min(256));
for _ in 0..n {
user_data.push(UserData {
index: r.word()?,
slot: u8::try_from(r.word()?).ok()?,
root: root_type(r.word()?),
dword: r.word()?,
});
}
let n = r.word()? as usize;
let mut samplers = Vec::with_capacity(n.min(256));
for _ in 0..n {
samplers.push([r.word()?, r.word()?, r.word()?, r.word()?]);
}
let n = r.word()? as usize;
let mut static_samplers = Vec::with_capacity(n.min(256));
for _ in 0..n {
static_samplers.push(StaticSampler {
filter: r.word()?,
address: [r.word()?, r.word()?, r.word()?],
mip_lod_bias: f32::from_bits(r.word()?),
max_anisotropy: r.word()?,
comparison: r.word()?,
border: r.word()?,
min_lod: f32::from_bits(r.word()?),
max_lod: f32::from_bits(r.word()?),
});
}
let root_cbvs = r.list()?;
let root_srvs = r.list()?;
r.0.is_empty().then_some(HostShader {
stage,
dxil,
user_data,
samplers,
static_samplers,
root_cbvs,
root_srvs,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn shader() -> HostShader {
HostShader {
stage: HwStage::Ps,
dxil: b"DXBC and the rest".to_vec(),
user_data: vec![UserData {
index: 8,
slot: 1,
root: RootType::Table,
dword: 0,
}],
samplers: vec![[0x400, 0xc0_0000, 0x18f0_0000, 0]],
static_samplers: vec![StaticSampler::from_words([
0x400,
0xc0_0000,
0x18f0_0000,
0,
])],
root_cbvs: vec![2],
root_srvs: vec![0, 3],
}
}
#[test]
fn translations_come_back_from_the_cache() {
let dir = tempfile::tempdir().unwrap();
let cache = Cache::open(dir.path()).unwrap();
let build = [7u8; 32];
let container = b"a console container".as_slice();
let runs = AtomicU64::new(0);
let translate = |_: &[u8]| {
runs.fetch_add(1, Ordering::Relaxed);
Ok(shader())
};
assert_eq!(cached(&cache, &build, container, translate), Ok(shader()));
assert_eq!(cached(&cache, &build, container, translate), Ok(shader()));
assert_eq!(runs.load(Ordering::Relaxed), 1, "the second came from disk");
// Another build translates again.
assert_eq!(cached(&cache, &[8; 32], container, translate), Ok(shader()));
assert_eq!(runs.load(Ordering::Relaxed), 2);
// A damaged entry is a miss, translated and stored again.
for e in walk(dir.path()) {
std::fs::write(e, b"VSH1 broken").unwrap();
}
assert_eq!(cached(&cache, &build, container, translate), Ok(shader()));
assert_eq!(runs.load(Ordering::Relaxed), 3);
assert_eq!(cached(&cache, &build, container, translate), Ok(shader()));
assert_eq!(runs.load(Ordering::Relaxed), 3);
// Failures are not stored.
let fail = |_: &[u8]| Err::<HostShader, _>("unsupported".to_owned());
assert!(cached(&cache, &build, b"other", fail).is_err());
}
fn walk(dir: &std::path::Path) -> Vec<PathBuf> {
let mut files = Vec::new();
for e in std::fs::read_dir(dir).unwrap().flatten() {
if e.path().is_dir() {
files.extend(walk(&e.path()));
} else {
files.push(e.path());
}
}
files
}
#[test]
fn entries_round_trip_and_reject_damage() {
let bytes = encode(&shader());
assert_eq!(decode(&bytes), Some(shader()));
assert_eq!(decode(&bytes[..bytes.len() - 1]), None);
assert_eq!(decode(&[bytes.as_slice(), &[0]].concat()), None);
assert_eq!(decode(b"VSH0"), None);
}
}
+363
View File
@@ -0,0 +1,363 @@
//! Host copies of title buffers (decision 0007, step 3 and "Copies of title
//! memory"). Title buffers are title memory, which the host GPU cannot
//! read, so a buffer a draw uses gets a persistent host buffer of its size
//! on first use (system memory shaders may also write), and the ranges each
//! submission reads (vertex, index and constant data, buffer views) are
//! brought up to date from title memory before it runs: the 64 KiB pages
//! the title wrote since they were last copied ([`crate::watch`]: write
//! watching, or read-only guards on physical-page views), all of it where
//! neither works. A title GPU address inside the buffer is the same offset
//! in its copy. Ranges shaders write go back to title memory after the
//! submission ([`Shadow::gpu_writes`]).
//!
//! shortcut: only the ranges draws are known to read are brought up to
//! date (vertex and index buffer views, constant buffers in tables, root
//! descriptors, buffer views in tables); buffers read through directly
//! indexed heaps keep what their first use copied.
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::{Arc, Mutex};
use windows::Win32::Graphics::Direct3D12::ID3D12Resource;
use crate::host::{HostList, host};
use crate::watch::PAGE;
/// A title buffer's host copy.
pub(crate) struct Shadow {
pub(crate) buffer: ID3D12Resource,
data: *mut u8,
gpu: u64,
/// Where the title buffer starts and how long it is.
start: u64,
len: u64,
/// Per page of title memory from `start`'s on: the write-watch asking
/// after which it was last copied (0: never).
copied: Mutex<Vec<u64>>,
/// Whether the memory is write-watched: unknown, yes, no.
watched: AtomicU8,
/// Ranges shaders of a submission not yet copied back may be writing:
/// title memory there is older than the copy.
pending: Mutex<Vec<(usize, usize)>>,
}
const NOT_WATCHED: u8 = 2;
// SAFETY: D3D12 resources are free-threaded; `data` is a persistent mapping
// written only on the submitting thread.
unsafe impl Send for Shadow {}
// SAFETY: as above.
unsafe impl Sync for Shadow {}
impl Shadow {
/// The host GPU address of a title address inside the buffer.
pub(crate) fn gpu(&self, address: u64) -> u64 {
self.gpu + (address - self.start)
}
/// Bytes from a title address to the buffer's end.
pub(crate) fn left(&self, address: u64) -> u64 {
(self.start + self.len).saturating_sub(address)
}
/// Offset of a title address from the buffer's start.
pub(crate) fn offset(&self, address: u64) -> u64 {
address - self.start
}
/// Brings `len` bytes at `address` up to date when `list` is submitted,
/// and keeps the copy alive until the list is reset.
pub(crate) fn refresh(self: &Arc<Self>, list: &HostList, address: u64, len: u64) {
let len = len.min(self.start + self.len - address);
list.defer_refresh(self, address as usize, len as usize);
}
fn new(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64) -> Shadow {
let pages = (start + len).div_ceil(PAGE as u64) - start / PAGE as u64;
Shadow {
buffer,
data,
gpu,
start,
len,
copied: Mutex::new(vec![0; pages as usize]),
watched: AtomicU8::new(0),
pending: Mutex::default(),
}
}
/// Shaders of `list` may write `[address, address + len)` of the copy
/// (unordered access): after the list's submission has run, the range
/// is copied back into title memory, where the title reads it; until
/// then no refresh copies title memory over it. Call after the
/// [`Shadow::refresh`] that gives the shaders the title's data.
///
/// shortcut: the whole range goes back after every submission that
/// declares it; copy back only what shaders wrote (a GPU-side dirty
/// mask) if big unordered-access buffers make it slow.
pub(crate) fn gpu_writes(self: &Arc<Self>, list: &HostList, address: u64, len: u64) {
let len = len.min(self.left(address));
list.defer_gpu_write(self, address as usize, len as usize);
}
/// At submission: a submitted list's shaders write this range.
pub(crate) fn writing(&self, address: usize, len: usize) {
self.pending
.lock()
.unwrap_or_else(|e| e.into_inner())
.push((address, address + len));
}
/// After the submission ran: copies what its shaders may have written
/// back into title memory (unmapped pages left alone). Pages wholly
/// written are current in this copy, so our own write is not taken for
/// the title's.
pub(crate) fn copy_back(&self, address: usize, len: usize) {
let (start, end) = (self.start as usize, (self.start + self.len) as usize);
let (from, to) = (address.max(start), (address + len).min(end));
if from < to {
// SAFETY: inside the mapping.
let at = unsafe { self.data.add(from - start) };
crate::watch::writing(from, to - from);
crate::host::write_mapped(from as *mut u8, at, to - from);
let (first, last) = (from.div_ceil(PAGE), to / PAGE);
if first < last
&& self.watched.load(Ordering::Relaxed) != NOT_WATCHED
&& let Some((now, _)) = crate::watch::writes(first * PAGE, last * PAGE, true)
{
let base = start / PAGE;
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
copied[first - base..last - base].fill(now);
}
}
let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
if let Some(i) = pending.iter().position(|&r| r == (address, address + len)) {
pending.swap_remove(i);
}
}
/// At submission: copies what changed of `[address, address + len)`
/// since it was last copied (all of it if the memory is not
/// write-watched). Returns the bytes copied.
pub(crate) fn update(&self, address: usize, len: usize) -> usize {
let (start, end) = (self.start as usize, (self.start + self.len) as usize);
let (from, to) = (address.max(start), (address + len).min(end));
if from >= to {
return 0;
}
let mut busy: Vec<(usize, usize)> = self
.pending
.lock()
.unwrap_or_else(|e| e.into_inner())
.iter()
.copied()
.filter(|&(a, e)| a < to && e > from)
.collect();
if !busy.is_empty() {
// Rare: around ranges shaders are writing, everything is copied.
busy.sort_unstable();
let (mut at, mut bytes) = (from, 0);
for (a, e) in busy {
if a > at {
bytes += self.copy(at, a);
}
at = at.max(e);
}
if at < to {
bytes += self.copy(at, to);
}
return bytes;
}
if self.watched.load(Ordering::Relaxed) != NOT_WATCHED {
if let Some((now, written)) = crate::watch::writes(from, to, true) {
self.watched.store(1, Ordering::Relaxed);
let copied = self.copy_stale(from, to, now, &written);
#[cfg(feature = "diagnostics")]
{
use crate::copystat::{C, add};
add(C::Checked, (to - from) as u64);
add(C::Unchanged, (to - from).saturating_sub(copied) as u64);
}
return copied;
}
self.watched.store(NOT_WATCHED, Ordering::Relaxed);
}
self.copy(from, to);
to - from
}
/// Copies the pages of `[from, to)` written after their last copy
/// (`written`: last writes by page, in page order; `now`: this
/// asking), whole pages within the buffer.
fn copy_stale(&self, from: usize, to: usize, now: u64, written: &[(usize, u64)]) -> usize {
let base = self.start as usize / PAGE;
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
let mut writes = written.iter().peekable();
let (mut bytes, mut run) = (0, None);
let last = (to - 1) / PAGE;
for page in from / PAGE..=last {
let write = match writes.peek() {
Some(&&(p, w)) if p == page => {
writes.next();
w
}
_ => 0,
};
let at = &mut copied[page - base];
if *at == 0 || write > *at {
*at = now;
run.get_or_insert(page);
} else if let Some(first) = run.take() {
bytes += self.copy(first * PAGE, page * PAGE);
}
}
if let Some(first) = run {
bytes += self.copy(first * PAGE, (last + 1) * PAGE);
}
bytes
}
/// Copies title memory `[from, to)`, cut to the buffer, into the copy.
fn copy(&self, from: usize, to: usize) -> usize {
let (start, end) = (self.start as usize, (self.start + self.len) as usize);
let (from, to) = (from.max(start), to.min(end));
// SAFETY: inside the mapping (`from` and `to` are within the buffer).
let at = unsafe { self.data.add(from - start) };
crate::host::copy_mapped(at, from as *const u8, to - from, false);
to - from
}
}
struct Entry {
end: u64,
shadow: Option<Arc<Shadow>>,
}
/// Title buffers by (start address, resource), with their copy once made.
static BUFFERS: Mutex<BTreeMap<(u64, usize), Entry>> = Mutex::new(BTreeMap::new());
fn buffers() -> std::sync::MutexGuard<'static, BTreeMap<(u64, usize), Entry>> {
BUFFERS.lock().unwrap_or_else(|e| e.into_inner())
}
/// A title buffer exists at `start` (`len` bytes).
pub(crate) fn register(resource: usize, start: u64, len: u64) {
buffers().insert(
(start, resource),
Entry {
end: start + len,
shadow: None,
},
);
}
/// The title released it; lists that still hold its copy keep it alive.
pub(crate) fn unregister(resource: usize, start: u64) {
buffers().remove(&(start, resource));
}
/// The copy of the innermost title buffer holding `[address, address +
/// len)`, made on first use.
pub(crate) fn find(address: u64, len: u64) -> Option<Arc<Shadow>> {
let end = address.checked_add(len.max(1))?;
let mut map = buffers();
let key = map
.range(..=(address, usize::MAX))
.rev()
.take(64)
.find(|(_, e)| e.end >= end)
.map(|(k, _)| *k);
let Some(key) = key else {
drop(map);
return loose(address, end);
};
let entry = map.get_mut(&key)?;
if entry.shadow.is_none() {
let len = entry.end - key.0;
// Rounded up so that views ending in the buffer's last 256 bytes fit.
// Shaders write some buffers (unordered access), so not upload memory.
let (buffer, data) = host()?.shared_buffer(len.next_multiple_of(1 << 16))?;
crate::host::name(&buffer, || format!("title buffer {:#x}+{len:#x}", key.0));
// SAFETY: a live buffer.
let gpu = unsafe { buffer.GetGPUVirtualAddress() };
if len >= 16 << 20 {
tracing::info!(
start = format_args!("{:#x}", key.0),
len,
"large buffer copied to the host"
);
} else {
tracing::debug!(
start = format_args!("{:#x}", key.0),
len,
"buffer copied to the host"
);
}
entry.shadow = Some(Arc::new(Shadow::new(buffer, data, gpu, key.0, len)));
}
entry.shadow.clone()
}
/// Titles also use memory outside any buffer object as GPU memory (Grand
/// Theft Auto VI's interface vertices, from its own allocator). Such memory
/// gets copies of the aligned windows it touches.
/// shortcut: copies of windows are never freed; key them to the title's
/// allocations if memory use grows.
const WINDOW: u64 = 4 << 20;
/// Copies of title memory outside buffers, by (start, length).
static LOOSE: Mutex<BTreeMap<(u64, u64), Arc<Shadow>>> = Mutex::new(BTreeMap::new());
fn loose(address: u64, end: u64) -> Option<Arc<Shadow>> {
let start = address & !(WINDOW - 1);
let len = end.next_multiple_of(WINDOW) - start;
let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner());
if let Some(shadow) = map.get(&(start, len)) {
return Some(shadow.clone());
}
let (buffer, data) = host()?.shared_buffer(len)?;
crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x}"));
// SAFETY: a live buffer.
let gpu = unsafe { buffer.GetGPUVirtualAddress() };
tracing::debug!(
start = format_args!("{start:#x}"),
len,
"loose memory copied to the host"
);
let shadow = Arc::new(Shadow::new(buffer, data, gpu, start, len));
map.insert((start, len), shadow.clone());
Some(shadow)
}
/// For device-removed reports: the copy of title memory whose host range
/// starts closest below host GPU address `va`, and where `va` is in it.
pub(crate) fn near(va: u64) -> String {
let mut all: Vec<(u64, u64, u64)> = buffers()
.values()
.filter_map(|e| e.shadow.as_deref().map(|s| (s.gpu, s.start, s.len)))
.collect();
all.extend(
LOOSE
.lock()
.unwrap_or_else(|e| e.into_inner())
.values()
.map(|s| (s.gpu, s.start, s.len)),
);
let below = all.iter().filter(|c| c.0 <= va).max();
let above = all.iter().filter(|c| c.0 > va).min();
let mut text = match below {
Some(&(gpu, start, len)) => format!(
"; the nearest title memory copy below it: {start:#x}+{len:#x} at host {gpu:#x}, offset {:#x}",
va - gpu
),
None => "; no title memory copy below it".into(),
};
if let Some(&(gpu, start, len)) = above {
text.push_str(&format!(
"; the nearest above: {start:#x}+{len:#x} at host {gpu:#x} ({} copies in all)",
all.len()
));
}
text
}
+2 -2
View File
@@ -74,8 +74,8 @@ extern "system" fn release(this: This) -> u32 {
}
/// IUnknown 3, object 4, device child 1.
static FUNCTIONS: Table<8> = {
let mut f = object::d3d12_object(object::missing_table::<COMMAND_SIGNATURE, 8>());
static FUNCTIONS: Table<24> = {
let mut f = object::d3d12_object(object::missing_table::<COMMAND_SIGNATURE, 24>());
f[0] = query as *const ();
f[2] = release as *const ();
f[7] = object::parent_device as *const (); // 0x38
+303
View File
@@ -0,0 +1,303 @@
//! Texture contents the title writes itself (decision 0007, "Texture
//! memory"): streamed pages, layout-library copies, movie frames, glyph
//! atlases. Such a texture lives in console memory in its tiled layout;
//! before a submission samples its host copy, the memory is detiled into a
//! staging buffer when its content changed, and the staging buffer is
//! copied into the host texture.
//!
//! "Changed" means a page of the memory was written since the last detiling
//! ([`crate::watch`]), in write-watched memory; in physical-page views,
//! which cannot be watched, a content hash of the whole memory at every
//! submission that samples it.
//!
//! shortcut: a change detiles the whole texture, not the pages written.
//! Only textures read through descriptor tables are brought up to date
//! (directly indexed views are not known per draw); plane 0 is uploaded
//! (every mip and array slice), depth and stencil planes are not.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use windows::Win32::Graphics::Direct3D12::*;
use crate::host::{HostList, host};
use crate::object::This;
macro_rules! once {
($($arg:tt)*) => {{
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| tracing::warn!($($arg)*));
}};
}
/// A texture's upload state: the staging buffer laid out as the host
/// texture's subresources, and what was last detiled.
struct Staging {
buffer: ID3D12Resource,
data: *mut u8,
footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>,
rows: Vec<u32>,
layout: victory_formats::texture::Layout,
/// Mips per array slice.
mips: u32,
memory: *const u8,
last: Mutex<Last>,
}
/// What a texture's staging buffer holds: the hash of the memory detiled
/// (memory not watched), or the write-watch asking it was detiled after,
/// with room to read the memory into.
#[derive(Default)]
struct Last {
hash: Option<blake3::Hash>,
asked: u64,
read: Vec<u8>,
}
// SAFETY: the staging mapping is written only at submission, under
// `last`'s lock; the title memory is only read.
unsafe impl Send for Staging {}
// SAFETY: as above.
unsafe impl Sync for Staging {}
static STAGING: Mutex<Option<HashMap<usize, Arc<Staging>>>> = Mutex::new(None);
/// Textures the host GPU wrote by a copy or resolve: their contents are on
/// the host, not in title memory, which stays as it was.
static HOST_WRITTEN: Mutex<Option<std::collections::HashSet<usize>>> = Mutex::new(None);
/// A host copy or resolve writes `resource`.
pub(crate) fn host_written(resource: This) {
let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
set.get_or_insert_with(Default::default)
.insert(resource as usize);
}
/// The title released a resource.
pub(crate) fn forget(resource: usize) {
let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
if let Some(map) = map.as_mut() {
map.remove(&resource);
}
let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
if let Some(set) = set.as_mut() {
set.remove(&resource);
}
}
/// Whether `resource`'s host copy takes its contents from title memory:
/// a texture the host GPU does not render to or write.
pub(crate) fn title_written(texture: &ID3D12Resource) -> bool {
const TARGET_DEPTH_UNORDERED: i32 = 0x7;
// SAFETY: a live resource.
unsafe { texture.GetDesc() }.Flags.0 & TARGET_DEPTH_UNORDERED == 0
}
/// Records, once per list, the copy of `resource`'s staging buffer into
/// its host copy, and the detiling that refreshes the staging buffer at
/// submission if the memory changed. Leaves the texture in the copy
/// destination state.
pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) {
let host_written = HOST_WRITTEN
.lock()
.unwrap_or_else(|e| e.into_inner())
.as_ref()
.is_some_and(|set| set.contains(&(resource as usize)));
// shortcut: a texture the host copied into keeps the host's contents
// even if the title later writes its memory too.
if host_written || !list.first_use(resource as usize) {
return;
}
let Some(staging) = staging(resource, texture) else {
return;
};
const COPY_DEST: u32 = 0x400;
crate::list::ensure_state(list, resource, COPY_DEST);
for (i, footprint) in staging.footprints.iter().enumerate() {
let to = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: a borrowed pointer the location never releases.
pResource: unsafe { std::mem::transmute_copy(texture) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
SubresourceIndex: i as u32,
},
};
let from = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: as above.
pResource: unsafe { std::mem::transmute_copy(&staging.buffer) },
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: *footprint,
},
};
// SAFETY: an open list; both locations name live resources.
unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
}
list.defer_host(move || staging.refresh());
}
impl Staging {
/// Detiles the texture memory into the staging buffer if it changed
/// since the last time (and is mapped at all).
fn refresh(&self) {
use std::sync::atomic::Ordering::Relaxed;
let started = std::time::Instant::now();
let read = self.refresh_now();
let preparing = &crate::host::PREPARING;
preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed);
preparing[3].fetch_add(read as u64, Relaxed);
}
/// Returns the bytes of title memory read.
fn refresh_now(&self) -> usize {
let size = self.layout.size as usize;
let start = self.memory as usize;
let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner());
let last = &mut *last;
if let Some((now, written)) = crate::watch::writes(start, start + size, false) {
if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) {
return 0;
}
last.asked = now;
// Read through the copy, which stands unmapped pages: memory of
// big pools is too slow to ask page by page.
last.read.resize(size, 0);
crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false);
self.detile(&last.read);
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexWatched, size as u64);
return size;
}
if !committed(self.memory, size) {
#[cfg(feature = "diagnostics")]
tracing::debug!(
memory = ?self.memory,
size,
desc = ?self.layout.desc,
"a sampled texture's memory is not committed"
);
return 0;
}
// SAFETY: committed memory of the texture's layout size.
let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) };
let hash = blake3::hash(tiled);
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexHashed, size as u64);
if last.hash == Some(hash) {
return size;
}
last.hash = Some(hash);
self.detile(tiled);
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexChanged, size as u64);
size
}
/// Detiles `tiled` (the texture's memory) into the staging buffer.
fn detile(&self, tiled: &[u8]) {
#[cfg(feature = "diagnostics")]
if tiled.iter().all(|&b| b == 0) {
tracing::debug!(
memory = ?self.memory,
desc = ?self.layout.desc,
"a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)"
);
}
for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() {
let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips);
let f = footprint.Footprint;
let pitch = f.RowPitch as usize;
let len = pitch * rows as usize * f.Depth as usize;
// SAFETY: the subresource's part of the mapped staging buffer.
let linear = unsafe {
std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len)
};
if let Err(e) =
self.layout
.detile(tiled, mip, slice, linear, pitch, pitch * rows as usize)
{
tracing::warn!(?e, mip, slice, "texture not detiled");
return;
}
}
}
}
/// Whether `[at, at + len)` is committed memory (streamed textures may be
/// unmapped until their pages arrive).
pub(crate) fn committed(at: *const u8, len: usize) -> bool {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery};
let mut p = at as usize;
let end = p + len;
while p < end {
// SAFETY: plain data filled in by the query.
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: a valid out pointer of the right size.
let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) };
if n == 0 || info.State != MEM_COMMIT {
return false;
}
p = info.BaseAddress as usize + info.RegionSize;
}
true
}
/// The staging state of a title texture, made on first use.
fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
let map = map.get_or_insert_with(HashMap::new);
if let Some(s) = map.get(&(resource as usize)) {
return Some(s.clone());
}
let (memory, desc) = crate::resource::texture_memory(resource)?;
let Some(layout) = crate::resource::texture_layout(&desc).map(|t| t.planes[0].layout.clone())
else {
once!(
?desc,
"texture contents without a console layout not uploaded"
);
return None;
};
if layout.desc.swizzle.xor() {
once!(?desc, "texture contents in an XOR mode not uploaded");
return None;
}
let host = host()?;
// SAFETY: a live resource.
let d = unsafe { texture.GetDesc() };
let count = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D {
u32::from(d.MipLevels)
} else {
u32::from(d.MipLevels) * u32::from(d.DepthOrArraySize)
};
let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize];
let mut rows = vec![0u32; count as usize];
let mut total = 0;
// SAFETY: outputs for `count` subresources.
unsafe {
host.device.GetCopyableFootprints(
&d,
0,
count,
0,
Some(footprints.as_mut_ptr()),
Some(rows.as_mut_ptr()),
None,
Some(&mut total),
);
}
let (buffer, data) = host.upload_buffer(total)?;
tracing::debug!(?desc, total, "texture contents uploaded from title memory");
let s = Arc::new(Staging {
buffer,
data,
footprints,
rows,
layout,
mips: u32::from(d.MipLevels),
memory,
last: Mutex::default(),
});
map.insert(resource as usize, s.clone());
Some(s)
}
+367
View File
@@ -0,0 +1,367 @@
//! Which title memory the title wrote since a host copy took it (decision
//! 0007, "Copies of title memory"). The runtime reserves title GPU memory
//! with write watching (`victory-hle` xmem), so the kernel keeps a dirty bit
//! per 4 KiB page; asking for a range's written pages also clears them. Host
//! copies of the same memory can overlap (nested buffers, textures in
//! buffers), so what one asks is kept here for the others: a journal of
//! each page's last write, numbered by the asking.
//!
//! Physical-page views (xmem's sections) cannot be write-watched. There a
//! copy leaves each 64 KiB block it took read-only, and our vectored handler
//! takes the first write to it: it notes the block as written and gives the
//! write access back. The runtime tells us when it maps or unmaps views
//! ([`title_memory_remapped`]), which resets their protection.
//!
//! shortcut: writes into physical pages through another view (xmem's
//! `write_physical`, DirectStorage's page destinations) are not seen at
//! the guarded addresses; they go to the texture pool, whose textures are
//! hashed, not guarded. A system call writing into a guarded block fails
//! (none is known to).
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Mutex;
/// The unit tracked and copied: 64 KiB, the console's page (the kernel's
/// 4 KiB pages fold into it). Finer units made the checks of the world's
/// big buffers cost more than the copies they saved.
pub(crate) const PAGE: usize = 64 << 10;
/// The kernel's page, the unit of its answers.
const KERNEL_PAGE: usize = 4096;
struct Journal {
/// Numbers the askings; 0 is "never".
asked: u64,
/// Page number → the asking that last found it written.
written: BTreeMap<usize, u64>,
/// Room for the kernel's answer.
found: Vec<usize>,
}
static JOURNAL: Mutex<Journal> = Mutex::new(Journal {
asked: 0,
written: BTreeMap::new(),
found: Vec::new(),
});
/// The pages of `[start, end)` (whole pages) as last written, for pages
/// written since tracking began: `(page number, asking)` in page order, and
/// this asking's number, which is higher than any in the list but those the
/// kernel just reported. `None` if the memory is not write-watched (nor,
/// with `guarded`, view memory, which is then guarded).
pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Vec<(usize, u64)>)> {
use windows_sys::Win32::System::Memory::GetWriteWatch;
const WRITE_WATCH_FLAG_RESET: u32 = 1;
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
let j = &mut *j;
let mut count = (last - first) * PAGE / KERNEL_PAGE;
j.found.resize(count.max(j.found.len()), 0);
let mut granularity = 0;
#[cfg(feature = "diagnostics")]
let started = std::time::Instant::now();
// SAFETY: the answer buffer holds `count` entries.
let failed = unsafe {
GetWriteWatch(
WRITE_WATCH_FLAG_RESET,
(first * PAGE) as *const _,
(last - first) * PAGE,
j.found.as_mut_ptr().cast(),
&mut count,
&mut granularity,
)
} != 0;
let guarded = if failed {
count = 0;
if !guarded {
return None;
}
guard(first * PAGE, last * PAGE)?
} else {
Vec::new()
};
#[cfg(feature = "diagnostics")]
{
use crate::copystat::{C, add};
add(C::Watches, 1);
add(C::WatchUs, started.elapsed().as_micros() as u64);
}
j.asked += 1;
let now = j.asked;
let pages = j.found[..count].iter().map(|&at| at / PAGE).chain(guarded);
for page in pages.collect::<Vec<_>>() {
j.written.insert(page, now);
}
Some((
now,
j.written
.range(first..last)
.map(|(&p, &w)| (p, w))
.collect(),
))
}
/// Guarded blocks of view memory.
const BLOCK: usize = PAGE;
struct Guards {
/// Blocks we made read-only.
protected: BTreeSet<usize>,
/// Of those, the ones not written since a copy took them.
clean: BTreeSet<usize>,
}
static GUARDS: Mutex<Guards> = Mutex::new(Guards {
protected: BTreeSet::new(),
clean: BTreeSet::new(),
});
fn guards() -> std::sync::MutexGuard<'static, Guards> {
GUARDS.lock().unwrap_or_else(|e| e.into_inner())
}
/// For view memory: the pages of `[start, end)`'s blocks written since
/// they were last guarded (all of a block's pages), guarding them again
/// before the caller copies them. `None` if the memory is not a view.
fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
use windows_sys::Win32::System::Memory::{MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery};
// SAFETY: plain data filled in by the query.
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: a valid out pointer of the right size.
let n = unsafe { VirtualQuery(start as *const _, &mut info, size_of_val(&info)) };
if n == 0 || info.Type != MEM_MAPPED {
return None;
}
install();
let mut g = guards();
let mut written = Vec::new();
let mut run: Option<usize> = None;
let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
for block in first..=last {
let open = block < last && !g.clean.contains(&block);
if open {
written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE);
if g.protected.contains(&block) {
// Written through the runtime, still read-only.
g.clean.insert(block);
} else {
run.get_or_insert(block);
continue;
}
}
if let Some(from) = run.take() {
protect(&mut g, from, block);
}
}
Some(written)
}
/// Makes blocks `[from, to)` read-only and notes them guarded and clean;
/// block by block if they span views, leaving out any that fail (unmapped).
fn protect(g: &mut Guards, from: usize, to: usize) {
use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect};
let set = |from: usize, to: usize| {
let mut old = 0;
// SAFETY: title view memory; only its protection changes.
unsafe {
VirtualProtect(
(from * BLOCK) as *const _,
(to - from) * BLOCK,
PAGE_READONLY,
&mut old,
) != 0
}
};
let note = |g: &mut Guards, from: usize, to: usize| {
g.protected.extend(from..to);
g.clean.extend(from..to);
};
if set(from, to) {
note(g, from, to);
return;
}
for block in from..to {
if set(block, block + 1) {
note(g, block, block + 1);
}
}
}
/// Gives write access back to the guarded blocks of `[start, end)` and
/// notes them written; true if any was guarded.
fn open(g: &mut Guards, start: usize, end: usize) -> bool {
use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect};
let blocks: Vec<usize> = g
.protected
.range(start / BLOCK..end.div_ceil(BLOCK))
.copied()
.collect();
for &block in &blocks {
g.protected.remove(&block);
g.clean.remove(&block);
let mut old = 0;
// SAFETY: a block we made read-only.
unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) };
}
!blocks.is_empty()
}
/// Before our own write into title memory `[at, at + len)` through the
/// kernel (which does not fault into our handler): opens its guarded blocks.
/// The runtime calls it (as `kernel_will_write`) before the title's kernel
/// reads into its own memory.
pub fn writing(at: usize, len: usize) {
open(&mut guards(), at, at + len);
}
/// The runtime mapped or unmapped title memory `[at, at + len)`: what it
/// shows is new and read-write, so it is no longer guarded.
pub fn title_memory_remapped(at: usize, len: usize) {
let mut g = guards();
let blocks: Vec<usize> = g
.protected
.range(at / BLOCK..(at + len).div_ceil(BLOCK))
.copied()
.collect();
for block in blocks {
g.protected.remove(&block);
g.clean.remove(&block);
}
}
/// Registers the handler that takes writes to guarded blocks, once, ahead
/// of the crash reporter's.
fn install() {
use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS};
use windows_sys::Win32::System::Diagnostics::Debug::{
AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH,
EXCEPTION_POINTERS,
};
unsafe extern "system" fn on_write(info: *mut EXCEPTION_POINTERS) -> i32 {
// SAFETY: the system passes the exception being dispatched.
let r = unsafe { &*(*info).ExceptionRecord };
const WRITE: usize = 1;
if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS
|| r.NumberParameters < 2
|| r.ExceptionInformation[0] != WRITE
{
return EXCEPTION_CONTINUE_SEARCH;
}
let at = r.ExceptionInformation[1];
if open(&mut guards(), at, at + 1) {
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::GuardFaults, 1);
return EXCEPTION_CONTINUE_EXECUTION;
}
// Another thread may have opened the block since this one faulted.
if writable(at) {
EXCEPTION_CONTINUE_EXECUTION
} else {
EXCEPTION_CONTINUE_SEARCH
}
}
static ONCE: std::sync::Once = std::sync::Once::new();
// SAFETY: the handler only touches our guard state and protections.
ONCE.call_once(|| unsafe {
AddVectoredExceptionHandler(1, Some(on_write));
});
}
/// Whether `at` is committed read-write memory now.
fn writable(at: usize) -> bool {
use windows_sys::Win32::System::Memory::{
MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_READWRITE, VirtualQuery,
};
// SAFETY: plain data filled in by the query.
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: a valid out pointer of the right size.
let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) };
n != 0 && info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE
}
#[cfg(test)]
mod tests {
use super::*;
use windows_sys::Win32::System::Memory::{
MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree,
};
const MEM_WRITE_WATCH: u32 = 0x20_0000;
#[test]
fn written_pages_are_reported_to_every_asker() {
// SAFETY: a fresh write-watched allocation, freed at the end.
let p = unsafe {
VirtualAlloc(
std::ptr::null(),
4 * PAGE,
MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH,
PAGE_READWRITE,
)
} as usize;
assert_ne!(p, 0);
let (start, end) = (p, p + 4 * PAGE);
let (_, before) = writes(start, end, false).expect("watched");
assert!(before.is_empty());
// SAFETY: committed pages of ours.
unsafe { ((p + PAGE + 8) as *mut u8).write(1) };
let (now, after) = writes(start, end, false).expect("watched");
assert_eq!(after, [(p / PAGE + 1, now)]);
// Another asker after the kernel's bit was cleared still sees it.
let (later, again) = writes(p + PAGE, p + 2 * PAGE, false).expect("watched");
assert!(later > now);
assert_eq!(again, [(p / PAGE + 1, now)]);
let mut plain = vec![0u8; PAGE];
assert!(
writes(
plain.as_mut_ptr() as usize,
plain.as_ptr() as usize + PAGE,
true
)
.is_none()
);
// SAFETY: our allocation.
unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) };
}
/// A kernel read into a guarded view block fails; opened first, it
/// lands and the block counts as written.
#[test]
fn kernel_reads_into_guarded_blocks_after_opening() {
use std::io::{Read, Seek, Write};
use windows_sys::Win32::System::Memory::{
CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile,
};
// SAFETY: a pagefile section of two blocks, mapped read-write.
let view = unsafe {
let section = CreateFileMappingW(
-1isize as _,
std::ptr::null(),
PAGE_READWRITE,
0,
(2 * BLOCK) as u32,
std::ptr::null(),
);
assert!(!section.is_null());
MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize
};
assert_ne!(view, 0);
assert!(guard(view, view + 2 * BLOCK).is_some()); // now read-only
let mut file = tempfile::tempfile().unwrap();
file.write_all(b"from the disk").unwrap();
// `ReadFile` inside: the kernel writes the view.
let read = |file: &mut std::fs::File| {
file.rewind().unwrap();
// SAFETY: 13 bytes of our view, nothing else refers to them.
let into = unsafe { std::slice::from_raw_parts_mut((view + 100) as *mut u8, 13) };
file.read(into).is_ok_and(|n| n == 13)
};
assert!(!read(&mut file), "the kernel does not fault into our handler");
writing(view + 100, 13);
assert!(read(&mut file));
// SAFETY: the bytes just read.
assert_eq!(unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }, b"from the disk");
assert_eq!(guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect()));
// SAFETY: our view.
unsafe { UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) };
title_memory_remapped(view, 2 * BLOCK);
}
}
+22
View File
@@ -11,23 +11,45 @@ publish.workspace = true
victory-gpu.workspace = true
victory-loader.workspace = true
victory-pe.workspace = true
victory-formats.workspace = true
opus-pure.workspace = true
miniz_oxide.workspace = true
tracing.workspace = true
[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = [
"Win32_Foundation",
"Win32_Globalization",
"Win32_Media",
"Win32_Security",
"Win32_Storage_FileSystem",
"Win32_System_Diagnostics_Debug",
"Win32_System_LibraryLoader",
"Win32_System_Memory",
"Win32_System_Power",
"Win32_System_ProcessStatus",
"Win32_System_Threading",
"Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_Input_XboxController",
"Win32_UI_WindowsAndMessaging",
] }
# Diagnostics only: recording our own audio (`modules::audio::capture`).
windows = { workspace = true, optional = true, features = [
"Win32_Media_Audio",
"Win32_System_Com",
"Win32_System_Com_StructuredStorage",
"Win32_System_Threading",
"Win32_System_Variant",
] }
# `#[implement]` names it.
windows-core = { workspace = true, optional = true }
[dev-dependencies]
tempfile.workspace = true
[features]
# Debugging switches (scripted keys and the like).
diagnostics = ["victory-gpu/diagnostics", "victory-loader/diagnostics", "dep:windows", "dep:windows-core"]
[lints]
workspace = true
+8 -1
View File
@@ -27,12 +27,12 @@ impl Default for HostPolicy {
"ucrtbase.dll",
"vcruntime140*",
"msvcp140*",
// Off-machine traffic is refused in `modules::net`.
"ws2_32.dll",
"bcrypt.dll",
"crypt32.dll",
"ncrypt.dll",
"winhttp.dll",
"dnsapi.dll",
"sspicli.dll",
"cabinet.dll",
"avrt.dll",
@@ -44,6 +44,13 @@ impl Default for HostPolicy {
"ole32.dll",
"advapi32.dll",
"iphlpapi.dll",
// The title's crash handler writes minidumps with it (loaded by name).
"dbghelp.dll",
// Same APIs as the console's (XAudio2 ordinal 1 is XAudio2Create
// on both); Media Foundation reads local media files.
"xaudio2_9.dll",
"mfplat.dll",
"mfreadwrite.dll",
];
HostPolicy {
allow: allow.iter().map(|s| s.to_string()).collect(),
+5 -1
View File
@@ -18,6 +18,7 @@ pub mod runtime;
pub use host::HostPolicy;
pub use registry::{HleExport, HleModule, registry};
pub use victory_gpu::console;
use victory_loader::{ImportResolver, Provenance, Resolution};
use victory_pe::ImportSymbol;
@@ -101,7 +102,10 @@ mod tests {
Some(Provenance::Host)
);
// Console-only DLLs never pass through.
assert_eq!(r.classify("xmem.dll", &name("XMemAllocDefault")), None);
assert_eq!(
r.classify("xmem.dll", &name("XMemSetAllocationHooks")),
None
);
}
#[cfg(windows)]
+524
View File
@@ -0,0 +1,524 @@
//! The console's audio decoder (`xapu.dll`): Opus packets in, float PCM out.
//!
//! A title connects once for one kind of processing, gets a block of memory
//! for its packets and output, and then queues per-stream commands
//! (activate, process, reset, deactivate) and dequeues one result per
//! command. We decode each command when it is queued, so its result is ready
//! at once; the order of results is the order of commands.
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::alloc::Layout;
use std::collections::VecDeque;
use std::ffi::c_void;
use std::sync::Mutex;
use opus_pure::OpusDecoder;
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
use windows_sys::Win32::System::Threading::{CreateEventW, SetEvent};
use super::xasync::E_INVALIDARG;
use super::xgameruntime::{HRESULT, S_OK};
use crate::{HleModule, hle_export};
const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32;
const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
const QUEUE_FULL: HRESULT = 0x8AC8_1000_u32 as i32;
/// No result yet, which titles poll for.
pub(crate) const PENDING_RESULTS: HRESULT = 0x8AC8_1001_u32 as i32;
const INVALID_COMMAND: HRESULT = 0x8AC8_1002_u32 as i32;
const INVALID_STREAM: HRESULT = 0x8AC8_1003_u32 as i32;
const ALREADY_ACTIVE: HRESULT = 0x8AC8_1005_u32 as i32;
const BAD_PACKET: HRESULT = 0x8AC8_1008_u32 as i32;
/// Processing kinds; only plain decoding is implemented.
const DECODE_OPUS: u32 = 1;
const ACTIVATE: u32 = 1;
const DEACTIVATE: u32 = 2;
const PROCESS: u32 = 3;
const NOTIFY: u32 = 4;
const RESET: u32 = 5;
/// Command option: signal the connection's event when the result is ready.
const SIGNAL: u32 = 1;
/// Connect options.
const DEINTERLEAVED_OUTPUT: u32 = 4;
const RESULT_EVENT: u32 = 8;
/// The longest Opus packet duration at 48 kHz (120 ms).
const MAX_FRAMES: usize = 5760;
#[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: HANDLE,
}
/// What every command starts with, and what its result echoes.
#[repr(C, packed)]
#[derive(Clone, Copy)]
pub struct CommandId {
kind: u32,
stream: u32,
sequence: u32,
options: u32,
context: u64,
}
#[repr(C, packed)]
struct Activate {
id: CommandId,
channels: u32,
init_length: u32,
init: *const c_void,
start_pitch: f32,
processing_length: u32,
processing: *mut c_void,
}
#[repr(C, packed)]
#[derive(Clone, Copy)]
struct Process {
id: CommandId,
pitch_ramp: f32,
target_pitch: f32,
first_frame: u32,
frame_count: u32,
input_length: u32,
input: *const u8,
output_length: u32,
output: *mut u8,
}
#[repr(C, packed)]
#[derive(Clone, Copy)]
pub struct ApuResult {
id: CommandId,
state: u32,
state_data: u64,
usec: u64,
error: HRESULT,
frames: u32,
output_length: u32,
output: *mut u8,
pitch: f32,
input_length: u32,
input: *const u8,
}
// SAFETY: the raw pointers are title addresses carried through, never
// dereferenced after the result is made.
unsafe impl Send for ApuResult {}
pub struct Connection {
memory: *mut u8,
layout: Layout,
event: HANDLE,
options: u32,
per_stream: u32,
state: Mutex<State>,
}
struct State {
streams: Vec<Option<OpusDecoder>>,
/// Results not yet dequeued, per stream.
queued: Vec<u32>,
results: VecDeque<ApuResult>,
commands: u32,
dequeued: u32,
}
fn lock(c: &Connection) -> std::sync::MutexGuard<'_, State> {
c.state.lock().unwrap_or_else(|e| e.into_inner())
}
pub extern "system" fn XApuConnect(
input: *const ConnectInput,
output: *mut ConnectOutput,
handle: *mut *mut Connection,
) -> HRESULT {
if input.is_null() || output.is_null() || handle.is_null() {
return E_INVALIDARG;
}
// SAFETY: checked non-null.
let input = unsafe { &*input };
if !(1..=500).contains(&input.streams)
|| !(1..=16).contains(&input.commands_per_stream)
|| input.memory == 0
{
return E_INVALIDARG;
}
if input.process != DECODE_OPUS {
// shortcut: rate conversion (decode-convert, PCM convert) is not
// implemented; add a resampler if a title connects for it.
tracing::warn!(
process = input.process,
"audio decoder: processing kind not implemented"
);
return E_NOTIMPL;
}
if input.frames_per_output != 0 {
return E_INVALIDARG;
}
let Ok(layout) = Layout::from_size_align(input.memory 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;
}
let event = if input.options & RESULT_EVENT != 0 {
// SAFETY: plain auto-reset event, no name.
unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) }
} else {
std::ptr::null_mut()
};
let streams = input.streams as usize;
tracing::info!(
streams,
memory = input.memory,
options = input.options,
"audio decoder connected"
);
let connection = Box::new(Connection {
memory,
layout,
event,
options: input.options,
per_stream: input.commands_per_stream,
state: Mutex::new(State {
streams: (0..streams).map(|_| None).collect(),
queued: vec![0; streams],
results: VecDeque::new(),
commands: 0,
dequeued: 0,
}),
});
// SAFETY: checked non-null.
unsafe {
output.write(ConnectOutput {
memory: memory.cast(),
result_event: event,
});
handle.write(Box::into_raw(connection));
}
S_OK
}
pub extern "system" fn XApuDisconnect(handle: *mut Connection) -> HRESULT {
if handle.is_null() {
return E_INVALIDARG;
}
// SAFETY: made by `XApuConnect`; disconnected once.
let connection = unsafe { Box::from_raw(handle) };
if !connection.event.is_null() {
// SAFETY: our event.
unsafe { CloseHandle(connection.event) };
}
// SAFETY: allocated in `XApuConnect` with this layout.
unsafe { std::alloc::dealloc(connection.memory, connection.layout) };
S_OK
}
pub extern "system" fn XApuEnqueueCommand(
handle: *mut Connection,
command: *const CommandId,
total: *mut u32,
) -> HRESULT {
if handle.is_null() || command.is_null() {
return E_INVALIDARG;
}
// SAFETY: a connection from `XApuConnect`; every command starts with an id.
let (connection, id) = unsafe { (&*handle, command.read_unaligned()) };
let mut state = lock(connection);
let stream = id.stream as usize;
if stream >= state.streams.len() {
return INVALID_STREAM;
}
if state.queued[stream] >= connection.per_stream {
return QUEUE_FULL;
}
let mut result = ApuResult {
id,
state: 0,
state_data: 0,
usec: 0,
error: S_OK,
frames: 0,
output_length: 0,
output: std::ptr::null_mut(),
pitch: 1.0,
input_length: 0,
input: std::ptr::null(),
};
let decoder = &mut state.streams[stream];
match id.kind {
ACTIVATE => {
// SAFETY: an activate command is this struct.
let channels = unsafe { command.cast::<Activate>().read_unaligned() }.channels;
tracing::debug!(stream, channels, "Opus stream activated");
result.error = if decoder.is_some() {
ALREADY_ACTIVE
} else {
match OpusDecoder::new(48_000, channels as usize) {
Ok(d) if (1..=2).contains(&channels) => {
*decoder = Some(d);
S_OK
}
_ => E_INVALIDARG,
}
};
}
DEACTIVATE => *decoder = None,
RESET => {
if let Some(d) = decoder {
let _ = d.reset_state();
}
}
NOTIFY => {}
PROCESS => {
// SAFETY: a process command is this struct.
let command = unsafe { command.cast::<Process>().read_unaligned() };
match decoder {
Some(d) => process(d, connection.options, &command, &mut result),
None => result.error = INVALID_STREAM,
}
}
_ => return INVALID_COMMAND,
}
state.queued[stream] += 1;
state.commands = state.commands.wrapping_add(1);
state.results.push_back(result);
if !total.is_null() {
// SAFETY: optional out parameter.
unsafe { total.write(state.commands) };
}
if id.options & SIGNAL != 0 && !connection.event.is_null() {
// SAFETY: our event.
unsafe { SetEvent(connection.event) };
}
S_OK
}
/// Decodes one packet into the command's output buffer, keeping the frames
/// from `first_frame` on, at most `frame_count` of them.
fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: &mut ApuResult) {
let channels = decoder.channels();
let (input, input_length) = (command.input, command.input_length);
let (output, output_length) = (command.output, command.output_length);
result.input = input;
result.input_length = input_length;
result.output = output;
if input.is_null() || output.is_null() || input_length == 0 {
result.error = E_INVALIDARG;
return;
}
// SAFETY: the title's packet in its connection memory.
let packet = unsafe { std::slice::from_raw_parts(input, input_length as usize) };
let mut pcm = vec![0f32; MAX_FRAMES * channels];
let decoded = match decoder.decode(packet, MAX_FRAMES, &mut pcm) {
Ok(n) => n,
Err(_) => {
result.error = BAD_PACKET;
return;
}
};
let first = (command.first_frame as usize).min(decoded);
let frames = (decoded - first)
.min(command.frame_count as usize)
.min(output_length as usize / (4 * channels));
let kept = &pcm[first * channels..(first + frames) * channels];
// SAFETY: the title's output buffer holds `output_length` bytes.
let out = unsafe { std::slice::from_raw_parts_mut(output.cast::<f32>(), frames * channels) };
if options & DEINTERLEAVED_OUTPUT != 0 && channels == 2 {
for (i, frame) in kept.as_chunks::<2>().0.iter().enumerate() {
(out[i], out[frames + i]) = (frame[0], frame[1]);
}
} else {
out.copy_from_slice(kept);
}
result.frames = frames as u32;
result.output_length = (frames * channels * 4) as u32;
}
pub extern "system" fn XApuDequeueResult(handle: *mut Connection, out: *mut ApuResult) -> HRESULT {
if handle.is_null() || out.is_null() {
return E_INVALIDARG;
}
// SAFETY: a connection from `XApuConnect`.
let mut state = lock(unsafe { &*handle });
let Some(result) = state.results.pop_front() else {
return PENDING_RESULTS;
};
let stream = result.id.stream as usize;
state.queued[stream] -= 1;
state.dequeued = state.dequeued.wrapping_add(1);
// SAFETY: the title passes room for one result.
unsafe { out.write_unaligned(result) };
S_OK
}
pub extern "system" fn XApuGetResultCount(handle: *mut Connection, total: *mut u32) -> u32 {
if handle.is_null() {
return 0;
}
// SAFETY: a connection from `XApuConnect`.
let state = lock(unsafe { &*handle });
if !total.is_null() {
// SAFETY: optional out parameter.
unsafe { total.write(state.dequeued) };
}
state.results.len() as u32
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "apu",
dlls: &["xapu.dll"],
exports: vec![
hle_export!(XApuConnect),
hle_export!(XApuDisconnect),
hle_export!(XApuEnqueueCommand),
hle_export!(XApuDequeueResult),
hle_export!(XApuGetResultCount),
],
}
}
#[cfg(test)]
mod tests {
use super::*;
use opus_pure::{Application, OpusEncoder};
fn id(kind: u32, stream: u32) -> CommandId {
CommandId {
kind,
stream,
sequence: 7,
options: 0,
context: 0x1234,
}
}
#[test]
fn decodes_opus_as_the_title_drives_it() {
assert_eq!(size_of::<ApuResult>(), 0x50);
// 256 mono/stereo streams, two commands each, as the title connects.
let input = ConnectInput {
process: DECODE_OPUS,
streams: 256,
commands_per_stream: 2,
memory: 0x10_4000,
frames_per_output: 0,
options: 1,
};
let mut output = ConnectOutput {
memory: std::ptr::null_mut(),
result_event: std::ptr::null_mut(),
};
let mut handle = std::ptr::null_mut();
assert_eq!(XApuConnect(&input, &mut output, &mut handle), S_OK);
let base = output.memory.cast::<u8>();
let activate = Activate {
id: id(ACTIVATE, 3),
channels: 2,
init_length: 0,
init: std::ptr::null(),
start_pitch: 1.0,
processing_length: 0,
processing: std::ptr::null_mut(),
};
assert_eq!(
XApuEnqueueCommand(handle, (&raw const activate).cast(), std::ptr::null_mut()),
S_OK
);
// A 20 ms stereo packet of a 440 Hz tone.
let tone: Vec<f32> = (0..960 * 2)
.map(|i| ((i / 2) as f32 * 440.0 * std::f32::consts::TAU / 48_000.0).sin() * 0.5)
.collect();
let mut encoder = OpusEncoder::new(48_000, 2, Application::Audio).unwrap();
let mut packet = [0u8; 1500];
let n = encoder.encode(&tone, 960, &mut packet).unwrap();
// SAFETY: inside the connection memory.
unsafe { std::ptr::copy_nonoverlapping(packet.as_ptr(), base, n) };
let process = Process {
id: id(PROCESS, 3),
pitch_ramp: 0.0,
target_pitch: 1.0,
first_frame: 0,
frame_count: 960,
input_length: n as u32,
input: base,
output_length: 0xf00 * 2,
output: base.wrapping_add(0x14000),
};
let mut total = 0;
assert_eq!(
XApuEnqueueCommand(handle, (&raw const process).cast(), &mut total),
S_OK
);
assert_eq!(total, 2);
// Two results queued for stream 3: its queue is full.
assert_eq!(
XApuEnqueueCommand(handle, (&raw const process).cast(), &mut total),
QUEUE_FULL
);
assert_eq!(XApuGetResultCount(handle, std::ptr::null_mut()), 2);
let mut result = std::mem::MaybeUninit::<ApuResult>::zeroed();
assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK);
// SAFETY: written above.
let first = unsafe { result.assume_init() };
let (kind, error, context) = (first.id.kind, first.error, first.id.context);
assert_eq!((kind, error, context), (ACTIVATE, S_OK, 0x1234));
assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK);
// SAFETY: written above.
let decoded = unsafe { result.assume_init() };
let (kind, error, frames, length) = (
decoded.id.kind,
decoded.error,
decoded.frames,
decoded.output_length,
);
assert_eq!((kind, error, frames, length), (PROCESS, S_OK, 960, 960 * 8));
// SAFETY: the decoder wrote 960 stereo frames there.
let pcm =
unsafe { std::slice::from_raw_parts(base.wrapping_add(0x14000).cast::<f32>(), 1920) };
let energy: f32 = pcm.iter().map(|s| s * s).sum::<f32>() / 1920.0;
assert!(energy > 0.01, "decoded a tone, energy {energy}");
assert_eq!(
XApuDequeueResult(handle, result.as_mut_ptr()),
PENDING_RESULTS
);
let mut dequeued = 0;
assert_eq!(XApuGetResultCount(handle, &mut dequeued), 0);
assert_eq!(dequeued, 2);
// A process on a stream that was never activated fails in its result.
let mut stray = process;
stray.id.stream = 4;
assert_eq!(
XApuEnqueueCommand(handle, (&raw const stray).cast(), &mut total),
S_OK
);
assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK);
// SAFETY: written above.
let error = unsafe { result.assume_init() }.error;
assert_eq!(error, INVALID_STREAM);
assert_eq!(XApuDisconnect(handle), S_OK);
}
}
+720 -112
View File
@@ -1,35 +1,36 @@
//! The console's audio hardware (`AcpHal.dll`, `xapu.dll`), enough for
//! middleware to start and then mix in software:
//! The console's audio hardware (`AcpHal.dll`):
//!
//! * 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.
//! * the XMA decoder: enabled XMA contexts are decoded on a thread of ours
//! into their output rings, like the hardware does.
//!
//! 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.
//! SHAPE's other units (rate conversion, EQ, filters, mixing through
//! flowgraphs) are not emulated, so voices that need them stay silent.
//! Mixed audio leaves through the host's WASAPI, which titles and
//! middleware reach through COM like on PC. fmod's console build sets up
//! the coprocessor inside `System_Create` and waits there for its first
//! command to be acknowledged; Grand Theft Auto VI uses only XMA contexts.
#![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::sync::{Mutex, MutexGuard, OnceLock, RwLock, RwLockReadGuard};
use std::time::Instant;
use super::xasync::E_INVALIDARG;
use super::xgameruntime::{HRESULT, S_OK};
use crate::{HleModule, hle_export};
#[cfg(all(windows, feature = "diagnostics"))]
pub mod capture;
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<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
@@ -46,40 +47,110 @@ struct Block {
struct Heap {
/// By host address.
blocks: BTreeMap<usize, Block>,
next_apu: u32,
/// Host address by device address.
by_apu: BTreeMap<u32, usize>,
/// Free device address ranges, start to end, merged with neighbours.
free: BTreeMap<u32, u32>,
/// Set by `ApuCreateHeap` or the first allocation: the heap exists.
created: bool,
}
static HEAP: Mutex<Heap> = Mutex::new(Heap {
blocks: BTreeMap::new(),
next_apu: 0x0001_0000,
by_apu: BTreeMap::new(),
free: BTreeMap::new(),
created: false,
});
/// Device addresses start above 0, which means "none" to titles.
const APU_BASE: u32 = 0x0001_0000;
impl Heap {
/// First fit in the free ranges.
fn take(&mut self, size: u32, align: u32) -> Option<u32> {
if self.free.is_empty() && !self.created {
self.free.insert(APU_BASE, u32::MAX);
}
self.created = true;
let (start, end, apu) = self.free.iter().find_map(|(&start, &end)| {
let apu = start.checked_next_multiple_of(align)?;
(apu.checked_add(size)? <= end).then_some((start, end, apu))
})?;
self.free.remove(&start);
if start < apu {
self.free.insert(start, apu);
}
if apu + size < end {
self.free.insert(apu + size, end);
}
Some(apu)
}
fn give_back(&mut self, mut start: u32, mut end: u32) {
if let Some((&before, &before_end)) = self.free.range(..start).next_back()
&& before_end == start
{
self.free.remove(&before);
start = before;
}
if let Some(after_end) = self.free.remove(&end) {
end = after_end;
}
self.free.insert(start, end);
}
}
/// 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()?)?;
let apu = heap.take(u32::try_from(layout.size()).ok()?, align as u32)?;
// SAFETY: non-zero size.
let ptr = unsafe { std::alloc::alloc_zeroed(layout) };
if ptr.is_null() {
heap.give_back(apu, apu + layout.size() as u32);
return None;
}
heap.next_apu = next;
heap.blocks
.insert(ptr as usize, Block { size, apu, layout });
heap.by_apu.insert(apu, ptr as usize);
Some((ptr, apu))
}
fn heap_free(ptr: *mut u8) {
let block = lock(&HEAP).blocks.remove(&(ptr as usize));
if let Some(block) = block {
let mut heap = lock(&HEAP);
let Some(block) = heap.blocks.remove(&(ptr as usize)) else {
return;
};
heap.by_apu.remove(&block.apu);
heap.give_back(block.apu, block.apu + block.layout.size() as u32);
drop(heap);
// SAFETY: allocated by `heap_alloc` with this layout.
unsafe { std::alloc::dealloc(ptr, block.layout) };
}
/// Sizes the heap once, before anything is allocated from it. The console
/// reserves both parts up front; we allocate per block, so the sizes only
/// decide whether the call is valid.
// shortcut: the cached and non-cached sizes are not enforced as limits;
// enforce them if a title relies on running out.
pub extern "system" fn ApuCreateHeap(cached: u32, _non_cached: u32) -> HRESULT {
const ALREADY_ALLOCATED: HRESULT = 0x8ACA_0001_u32 as i32;
if cached == 0 {
return E_INVALIDARG;
}
let mut heap = lock(&HEAP);
if heap.created {
return ALREADY_ALLOCATED;
}
heap.created = true;
heap.free.insert(APU_BASE, u32::MAX);
S_OK
}
/// The host address of a device address, null outside the heap.
pub extern "system" fn ApuMapApuAddress(apu: u32) -> *mut c_void {
heap_unmap(apu).map_or(std::ptr::null_mut(), |p| p.cast())
}
/// The device address of any byte of a heap block, 0 elsewhere.
@@ -96,10 +167,22 @@ fn heap_map(ptr: usize) -> u32 {
/// 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)
let (&start, &host) = heap.by_apu.range(..=apu).next_back()?;
let block = &heap.blocks[&host];
(apu < start.saturating_add(block.size.max(1) as u32))
.then(|| (host + (apu - start) as usize) as *mut u8)
}
/// `len` bytes of title memory at a device address, if one heap block holds
/// them all.
fn heap_bytes<'a>(apu: u32, len: usize) -> Option<&'a mut [u8]> {
let heap = lock(&HEAP);
let (&start, &host) = heap.by_apu.range(..=apu).next_back()?;
let offset = (apu - start) as usize;
(offset + len <= heap.blocks[&host].size)
// SAFETY: inside a live heap block, which the title and the audio
// hardware share like on the console.
.then(|| unsafe { std::slice::from_raw_parts_mut((host + offset) as *mut u8, len) })
}
pub extern "system" fn ApuAlloc(
@@ -183,12 +266,16 @@ pub extern "system" fn AcpHalAllocateShapeContexts(contexts: *mut ShapeContexts)
std::ptr::addr_of_mut!((*contexts).apu).write_unaligned(addresses);
}
*allocated = Some(arrays.map(|p| p as usize));
let mut xma = XMA.write().unwrap_or_else(|e| e.into_inner());
xma.array = arrays[4] as usize;
xma.voices = (0..counts[4]).map(|_| Mutex::new(None)).collect();
S_OK
}
pub extern "system" fn AcpHalReleaseShapeContexts() -> HRESULT {
match lock(&CONTEXTS).take() {
Some(arrays) => {
*XMA.write().unwrap_or_else(|e| e.into_inner()) = Xma::EMPTY;
arrays.iter().for_each(|&p| heap_free(p as *mut u8));
S_OK
}
@@ -196,6 +283,410 @@ pub extern "system" fn AcpHalReleaseShapeContexts() -> HRESULT {
}
}
// The XMA decoder.
//
// An XMA context (16 words in the shared context array) names up to two
// input buffers of 2 KiB packets, a ring of 256-byte output blocks the
// hardware fills with 16-bit PCM, and the read offset the title advances
// by command. Words and bit fields, as titles write them:
// 0: input 0 size in packets (0-11), loop count (12-19, 255 forever),
// valid inputs (20-21), output size in blocks (22-26), write block
// (27-31, hardware);
// 1: input 1 size (0-11), loop end subframe (12-13), loop start subframes
// to skip (17-19), subframes to skip at the start (24-26), sample rate
// (27-28: 24, 32, 44.1, 48 kHz), stereo (29), output writable (31);
// 2: read position in bits (0-25), error status (26-30), error (31);
// 3: loop start in bits (0-25); 4: loop end in bits (0-25), current input
// (31); 5, 6: input addresses; 7: output address; 8: overlap buffer;
// 9: read block (0-4).
// Titles read back only the write block, "writable" and the read block,
// and take whatever lies between read and write.
// shortcut: each enabled context decodes from a cold state and the overlap
// buffer is ignored (titles copy it between consecutive contexts of one
// voice); keep decoder state there if a title's seams turn out audible.
use victory_formats::xma;
const ENABLE_XMA: u32 = 5;
const ENABLE_XMAS: u32 = 6;
const DISABLE_XMA: u32 = 7;
const DISABLE_XMAS: u32 = 8;
const ADVANCE_XMA_READ: u32 = 18;
const BLOCK_BYTES: usize = 256;
const SAMPLES_PER_BLOCK: usize = BLOCK_BYTES / 2;
/// Error status: the input ran out.
const INPUT_INVALID: u32 = 4;
struct Voice {
decoder: Option<xma::Decoder>,
pcm: VecDeque<i16>,
/// Samples per channel still to drop (start or loop subframe skips).
skip: usize,
ended: bool,
trace: Trace,
}
/// What a voice did, for the debug log when it is disabled.
struct Trace {
since: Instant,
/// Samples per channel written to the ring.
produced: usize,
/// Blocks the title took (command 18), how often, and how often it
/// found the ring less than full.
taken: usize,
takes: u32,
partial_takes: u32,
frames: u32,
bad_frames: u32,
/// The loudest sample written.
peak: i16,
/// Milliseconds after enabling when the input ran out.
ended_ms: Option<u128>,
}
struct Xma {
/// Host address of the context array.
array: usize,
/// One entry per context, `Some` while enabled. Each has its own lock,
/// so a command for one voice never waits for others to decode (the
/// title sends them from its time-critical mixer thread).
voices: Vec<Mutex<Option<Voice>>>,
}
impl Xma {
const EMPTY: Xma = Xma {
array: 0,
voices: Vec::new(),
};
}
/// Written only when the context arrays are allocated or released.
static XMA: RwLock<Xma> = RwLock::new(Xma::EMPTY);
fn xma() -> RwLockReadGuard<'static, Xma> {
XMA.read().unwrap_or_else(|e| e.into_inner())
}
/// A context's words in title memory.
#[derive(Clone, Copy)]
struct Context(*mut u32);
impl Context {
fn get(self, word: usize) -> u32 {
// SAFETY: inside the context array; the title reads and writes it
// concurrently, like the hardware's.
unsafe { self.0.add(word).read_volatile() }
}
fn set(self, word: usize, value: u32) {
// SAFETY: as above.
unsafe { self.0.add(word).write_volatile(value) }
}
fn field(self, word: usize, shift: u32, bits: u32) -> u32 {
(self.get(word) >> shift) & ((1 << bits) - 1)
}
fn set_field(self, word: usize, shift: u32, bits: u32, value: u32) {
let mask = ((1u32 << bits) - 1) << shift;
self.set(word, (self.get(word) & !mask) | ((value << shift) & mask));
}
fn channels(self) -> usize {
1 + self.field(1, 29, 1) as usize
}
}
impl Xma {
fn context(&self, index: u32) -> Option<Context> {
((index as usize) < self.voices.len() && self.array != 0)
.then(|| Context((self.array + index as usize * 64) as *mut u32))
}
fn enable(&self, index: u32) {
let Some(context) = self.context(index) else {
return;
};
let mut slot = lock(&self.voices[index as usize]);
context.set_field(2, 26, 6, 0);
tracing::debug!(
index,
words = ?(0..10).map(|w| format!("{:08x}", context.get(w))).collect::<Vec<_>>(),
"XMA voice enabled"
);
#[cfg(feature = "diagnostics")]
dump_input(index, context);
*slot = Some(Voice {
decoder: None,
pcm: VecDeque::new(),
skip: context.field(1, 24, 3) as usize * xma::SUBFRAME_SAMPLES,
ended: false,
trace: Trace {
since: Instant::now(),
produced: 0,
taken: 0,
takes: 0,
partial_takes: 0,
frames: 0,
bad_frames: 0,
peak: 0,
ended_ms: None,
},
});
drop(slot);
wake_decoder();
}
fn disable(&self, index: u32) {
let Some(context) = self.context(index) else {
return;
};
let Some(voice) = lock(&self.voices[index as usize]).take() else {
return;
};
let t = &voice.trace;
tracing::debug!(
index,
ms = t.since.elapsed().as_millis(),
produced = t.produced,
taken = t.taken * SAMPLES_PER_BLOCK / context.channels(),
takes = t.takes,
partial_takes = t.partial_takes,
frames = t.frames,
bad_frames = t.bad_frames,
peak = t.peak,
input_ended_ms = ?t.ended_ms,
read_bit = context.field(2, 0, 26),
input_bits = context.field(0, 0, 12) * xma::PACKET_BYTES as u32 * 8,
"XMA voice disabled"
);
}
/// Moves the title's read block on, which frees output space.
fn advance_read(&self, index: u32, blocks: u32) {
let Some(context) = self.context(index) else {
return;
};
// The decoder writes the same words.
let mut slot = lock(&self.voices[index as usize]);
let size = context.field(0, 22, 5).max(1);
let read = (context.field(9, 0, 5) + blocks) % size;
context.set_field(9, 0, 5, read);
if blocks > 0 {
context.set_field(1, 31, 1, 1);
}
if let Some(voice) = &mut *slot {
let t = &mut voice.trace;
t.taken += blocks as usize;
t.takes += 1;
t.partial_takes += u32::from(blocks < size);
}
drop(slot);
wake_decoder();
}
/// Fills every enabled context's output as far as it has room.
fn pump(&self) {
let start = Instant::now();
let mut active = 0;
for index in 0..self.voices.len() as u32 {
if let (Some(context), Some(voice)) =
(self.context(index), &mut *lock(&self.voices[index as usize]))
{
pump(context, voice);
active += 1;
}
}
let took = start.elapsed();
if took.as_millis() >= 4 {
tracing::debug!(active, ms = took.as_millis(), "slow XMA decoding pass");
}
}
}
fn pump(context: Context, voice: &mut Voice) {
let size = context.field(0, 22, 5);
if size == 0 {
return;
}
while context.field(1, 31, 1) == 1 {
if voice.pcm.len() < SAMPLES_PER_BLOCK && !decode(context, voice) {
return;
}
let write = context.field(0, 27, 5);
let address = context.get(7) as usize + write as usize * BLOCK_BYTES;
let Some(out) = heap_bytes(address as u32, BLOCK_BYTES) else {
return;
};
for pair in out.as_chunks_mut::<2>().0 {
let sample = voice.pcm.pop_front().unwrap_or(0);
voice.trace.peak = voice.trace.peak.max(sample.saturating_abs());
pair.copy_from_slice(&sample.to_le_bytes());
}
voice.trace.produced += SAMPLES_PER_BLOCK / context.channels();
let write = (write + 1) % size;
context.set_field(0, 27, 5, write);
if write == context.field(9, 0, 5) {
// Full: nothing more until the title advances its read block.
context.set_field(1, 31, 1, 0);
}
}
}
/// Decodes the next frame of the current input into `voice.pcm`; false
/// when there is nothing left to decode.
fn decode(context: Context, voice: &mut Voice) -> bool {
if voice.ended {
return false;
}
let channels = context.channels();
let mut current = context.field(4, 31, 1);
let valid = context.field(0, 20, 2);
if valid & (1 << current) == 0 {
if valid & (1 << (1 - current)) == 0 {
// Out of input: the overlap tail, then nothing.
if let Some(decoder) = &mut voice.decoder {
let mut tail = Vec::new();
decoder.flush(&mut tail);
voice.pcm.extend(tail);
}
voice.ended = true;
voice.trace.ended_ms = Some(voice.trace.since.elapsed().as_millis());
context.set_field(2, 26, 5, INPUT_INVALID);
context.set_field(2, 31, 1, 1);
return !voice.pcm.is_empty();
}
current = 1 - current;
context.set_field(4, 31, 1, current);
context.set_field(2, 0, 26, 0);
}
let (address, packets) = match current {
0 => (context.get(5), context.field(0, 0, 12)),
_ => (context.get(6), context.field(1, 0, 12)),
};
let Some(data) = heap_bytes(address & !0x7ff, packets as usize * xma::PACKET_BYTES) else {
context.set_field(0, 20 + current, 1, 0);
return true;
};
let mut at = context.field(2, 0, 26) as usize;
if at < 32 {
at = 32 + xma::packet(data, 0).map_or(0, |p| p.first_frame_bit as usize);
}
let Some(frame) = xma::read_frame(data, at) else {
// This input is used up.
context.set_field(0, 20 + current, 1, 0);
return true;
};
let decoder = voice.decoder.get_or_insert_with(|| {
const RATES: [u32; 4] = [24_000, 32_000, 44_100, 48_000];
xma::Decoder::new(channels, RATES[context.field(1, 27, 2) as usize])
});
let mut pcm = Vec::with_capacity(xma::FRAME_SAMPLES * channels);
voice.trace.frames += 1;
if let Err(e) = decoder.decode(&frame.data, frame.bits, &mut pcm) {
voice.trace.bad_frames += 1;
if voice.trace.bad_frames <= 2 {
tracing::debug!(
at,
bits = frame.bits,
head = ?&frame.data[..frame.data.len().min(8)],
%e,
"XMA frame did not decode"
);
}
}
let mut next = frame.next.unwrap_or(0);
let loops = context.field(0, 12, 8);
let loop_end = context.field(4, 0, 26) as usize;
let ends_loop = loop_end != 0
&& (frame.start == loop_end
|| (frame.start < loop_end && frame.next.is_none_or(|n| loop_end < n)));
if loops > 0 && ends_loop {
let keep = (context.field(1, 12, 2) as usize + 1) * xma::SUBFRAME_SAMPLES * channels;
pcm.truncate(keep);
next = context.field(3, 0, 26) as usize;
voice.skip = context.field(1, 17, 3) as usize * xma::SUBFRAME_SAMPLES;
if loops != 255 {
context.set_field(0, 12, 8, loops - 1);
}
}
let skip = (voice.skip * channels).min(pcm.len());
voice.skip -= skip / channels;
voice.pcm.extend(&pcm[skip..]);
if next == 0 {
context.set_field(0, 20 + current, 1, 0);
}
context.set_field(2, 0, 26, next as u32);
true
}
/// `VICTORY_XMA_DUMP=<dir>`: saves the context words (`<n>-<index>.ctx`)
/// and input buffer 0 (`.xma`) of the first 32 voices enabled, to test
/// the decoder on a title's streams outside the title.
#[cfg(feature = "diagnostics")]
fn dump_input(index: u32, context: Context) {
static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let Some(dir) = std::env::var_os("VICTORY_XMA_DUMP") else {
return;
};
let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if n >= 32 {
return;
}
let dir = std::path::PathBuf::from(dir);
let words: Vec<u8> = (0..16).flat_map(|w| context.get(w).to_le_bytes()).collect();
let input = heap_bytes(
context.get(5) & !0x7ff,
context.field(0, 0, 12) as usize * xma::PACKET_BYTES,
);
let _ = std::fs::create_dir_all(&dir);
let _ = std::fs::write(dir.join(format!("{n:02}-{index}.ctx")), words);
let _ = std::fs::write(dir.join(format!("{n:02}-{index}.xma")), input.unwrap_or_default());
}
/// Starts the decoding thread on the first enabled voice, and has it fill
/// rings now: a voice just enabled or read from.
fn wake_decoder() {
static DECODER: OnceLock<std::thread::Thread> = OnceLock::new();
DECODER
.get_or_init(|| {
std::thread::Builder::new()
.name("victory XMA decoder".into())
.spawn(|| {
loop {
xma().pump();
// A 256-byte output block lasts 2.7 ms at 48 kHz mono.
std::thread::park_timeout(std::time::Duration::from_millis(2));
}
})
.map_or_else(|_| std::thread::current(), |h| h.thread().clone())
})
.unpark();
}
/// Runs an XMA command; false for one this does not know.
fn xma_command(command: u32, word: impl Fn(usize) -> Option<u32>) -> bool {
let xma = xma();
match command {
ENABLE_XMA => xma.enable(word(0).unwrap_or(u32::MAX)),
DISABLE_XMA => xma.disable(word(0).unwrap_or(u32::MAX)),
ENABLE_XMAS | DISABLE_XMAS => {
for i in 0..xma.voices.len() as u32 {
if word(i as usize / 32).unwrap_or(0) & (1 << (i % 32)) != 0 {
match command {
ENABLE_XMAS => xma.enable(i),
_ => xma.disable(i),
}
}
}
}
ADVANCE_XMA_READ => xma.advance_read(word(0).unwrap_or(u32::MAX), word(1).unwrap_or(0)),
_ => return false,
}
true
}
// The audio coprocessor.
const LOAD_FLOWGRAPH: u32 = 1;
@@ -223,6 +714,10 @@ struct State {
/// Message kinds the title registered for.
mask: u32,
messages: VecDeque<Message>,
/// Queue size given to `connect`.
capacity: usize,
/// Messages lost to a full queue since the last one queued.
dropped: u32,
since: Instant,
}
@@ -235,15 +730,20 @@ impl State {
(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.
/// Queues a registered message; a full queue drops it and counts it in
/// the next one that fits.
fn post(&mut self, kind: u32, data: &[u8]) {
if self.mask & kind == 0 {
return;
}
if self.messages.len() >= self.capacity {
self.dropped = self.dropped.saturating_add(1);
tracing::debug!(kind, dropped = self.dropped, "coprocessor message dropped");
return;
}
let mut message = Message {
kind,
dropped: 0,
dropped: std::mem::take(&mut self.dropped),
usec: self.usec() as u32,
data: [0; 16],
};
@@ -284,11 +784,13 @@ fn state(this: *mut Acp) -> MutexGuard<'static, State> {
lock(unsafe { &(*this).state })
}
extern "system" fn connect(this: *mut Acp, commands: u32, _messages: u32) -> HRESULT {
extern "system" fn connect(this: *mut Acp, commands: u32, messages: u32) -> HRESULT {
if commands == 0 {
return E_INVALIDARG;
}
state(this).connected = true;
let mut state = state(this);
state.connected = true;
state.capacity = messages as usize;
S_OK
}
@@ -330,6 +832,10 @@ extern "system" fn submit(
let flowgraph = word(1).unwrap_or(0);
state.post(FLOWGRAPH_COMPLETED, &flowgraph.to_le_bytes());
}
_ if xma_command(command, word) => {}
// shortcut: context updates and the other SHAPE units' commands are
// acknowledged but not carried out; add them when a title sends
// them (each kind is logged once above).
_ => {}
}
if id != 0 {
@@ -378,6 +884,8 @@ pub extern "system" fn AcpHalCreate(out: *mut *mut Acp) -> HRESULT {
connected: false,
mask: 0,
messages: VecDeque::new(),
capacity: 0,
dropped: 0,
since: Instant::now(),
}),
});
@@ -386,98 +894,20 @@ pub extern "system" fn AcpHalCreate(out: *mut *mut Acp) -> HRESULT {
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"],
dlls: &["acphal.dll"],
exports: vec![
hle_export!(AcpHalAllocateShapeContexts),
hle_export!(AcpHalReleaseShapeContexts),
hle_export!(AcpHalCreate),
hle_export!(ApuAlloc),
hle_export!(ApuCreateHeap),
hle_export!(ApuFree),
hle_export!(ApuIsVirtualAddressValid),
hle_export!(ApuMapApuAddress),
hle_export!(ApuMapVirtualAddress),
hle_export!(XApuConnect),
hle_export!(XApuEnqueueCommand),
hle_export!(XApuDequeueResult),
hle_export!(XApuDisconnect),
],
}
}
@@ -488,6 +918,7 @@ mod tests {
#[test]
fn heap_maps_every_byte_of_a_block() {
let _serial = lock(&CONTEXT_TESTS);
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));
@@ -500,8 +931,185 @@ mod tests {
assert_eq!(ApuAlloc(&mut ptr, &mut apu, 0x100, 6, 1), E_INVALIDARG);
}
/// The context arrays and the heap exist once per process: tests that
/// allocate from them run one at a time (a concurrent allocation could
/// take a freed range a test expects back).
static CONTEXT_TESTS: Mutex<()> = Mutex::new(());
#[test]
fn heap_reuses_freed_addresses() {
let _serial = lock(&CONTEXT_TESTS);
let (mut a, mut b, mut c) = (
std::ptr::null_mut(),
std::ptr::null_mut(),
std::ptr::null_mut(),
);
let (mut apu_a, mut apu_b, mut apu_c) = (0, 0, 0);
assert_eq!(ApuAlloc(&mut a, &mut apu_a, 0x1000, 0x1000, 1), S_OK);
assert_eq!(ApuAlloc(&mut b, &mut apu_b, 0x1000, 0x1000, 1), S_OK);
ApuFree(a);
assert_eq!(ApuAlloc(&mut c, &mut apu_c, 0x800, 0x800, 1), S_OK);
// The freed range is free again, whichever part `c` took.
assert!(
lock(&HEAP)
.free
.iter()
.any(|(&s, &e)| s <= apu_a + 0x800 && apu_a + 0x1000 <= e)
|| apu_c == apu_a
);
assert_eq!(
ApuMapApuAddress(apu_b + 8),
b.cast::<u8>().wrapping_add(8).cast()
);
assert!(ApuMapApuAddress(0).is_null());
assert_eq!(
ApuCreateHeap(64 << 20, 0),
0x8ACA_0001_u32 as i32,
"too late"
);
ApuFree(b);
ApuFree(c);
}
/// Two packets of three silent mono frames each: a fixed one-subframe
/// layout, no transmitted coefficients.
fn silent_stream() -> Vec<u8> {
let mut data = vec![0xffu8; 2 * xma::PACKET_BYTES];
let mut put = |at: usize, value: u32, width: usize| {
for i in 0..width {
let (p, bit) = (at + i, (value >> (width - 1 - i)) & 1);
data[p / 8] = (data[p / 8] & !(0x80 >> (p % 8))) | ((bit as u8) << (7 - p % 8));
}
};
for packet in 0..2 {
let base = packet * xma::PACKET_BYTES * 8;
put(base, 3 << 26, 32);
for frame in 0..3 {
let at = base + 32 + frame * 31;
put(at, 31, 15); // length
put(at + 15, 0b10, 2); // fixed layout, one 512-sample subframe
put(at + 17, 0, 8 + 1 + 3 + 2); // gain, no trim, empty subframe
}
}
data
}
#[test]
fn xma_contexts_decode_into_their_output_rings() {
let _serial = lock(&CONTEXT_TESTS);
let mut request = ShapeContexts {
counts: [0, 0, 0, 0, 4, 0],
arrays: [std::ptr::null_mut(); 6],
apu: [0; 6],
};
assert_eq!(AcpHalAllocateShapeContexts(&mut request), S_OK);
let context = Context(request.arrays[4].cast::<u32>().wrapping_add(16));
let (mut input, mut input_apu) = (std::ptr::null_mut(), 0);
assert_eq!(ApuAlloc(&mut input, &mut input_apu, 0x1000, 0x800, 1), S_OK);
let stream = silent_stream();
// SAFETY: two packets were allocated.
unsafe { std::ptr::copy_nonoverlapping(stream.as_ptr(), input.cast(), stream.len()) };
let (mut output, mut output_apu) = (std::ptr::null_mut(), 0);
assert_eq!(
ApuAlloc(&mut output, &mut output_apu, 0x400, 0x100, 2),
S_OK
);
// SAFETY: the ring was just allocated.
unsafe { output.cast::<u8>().write_bytes(0x55, 0x400) };
// As the title sets one up: two packets, input 0 valid, a ring of
// four blocks, writable, 48 kHz mono, reading from the first frame.
context.set(0, 2 | 1 << 20 | 4 << 22);
context.set(1, 1 << 31 | 3 << 27);
context.set(2, 32);
context.set(5, input_apu);
context.set(7, output_apu);
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, 0x1000, 0x1000), S_OK);
let submit = |command: u32, words: &[u32]| {
assert_eq!(
(m.submit)(acp, command, 0xf1, u32::MAX, words.as_ptr().cast(), 0),
S_OK
);
};
submit(ENABLE_XMA, &[1]);
xma().pump();
// Full: all four blocks written (silence), the write block wrapped
// onto the read block, and the ring no longer writable.
assert_eq!(context.field(0, 27, 5), 0);
assert_eq!(context.field(1, 31, 1), 0);
// SAFETY: the ring.
let ring = unsafe { std::slice::from_raw_parts(output.cast::<u8>(), 0x400) };
assert!(ring.iter().all(|&b| b == 0));
// Read four blocks at a time until the input has run out and the
// ring keeps room (the decoding thread may fill it too).
for _ in 0..20 {
submit(ADVANCE_XMA_READ, &[1, 4]);
xma().pump();
if context.field(2, 31, 1) == 1 && context.field(1, 31, 1) == 1 {
break;
}
}
// Six frames and the flushed tail: 3,328 samples, 26 blocks.
let produced = |x: &Xma| lock(&x.voices[1]).as_ref().map(|v| v.trace.produced);
assert_eq!(produced(&xma()), Some(26 * SAMPLES_PER_BLOCK));
assert_eq!(context.field(0, 20, 2), 0, "input used up");
assert_eq!(context.field(2, 26, 5), INPUT_INVALID);
submit(DISABLE_XMA, &[1]);
assert_eq!(produced(&xma()), None);
(m.release)(acp);
ApuFree(input);
ApuFree(output);
assert_eq!(AcpHalReleaseShapeContexts(), S_OK);
}
#[test]
fn full_message_queues_count_drops() {
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, 16, 2), S_OK);
let mask = COMMAND_COMPLETED;
assert_eq!(
(m.submit)(
acp,
REGISTER_MESSAGES,
0,
u32::MAX,
(&raw const mask).cast(),
0
),
S_OK
);
for id in 1..=4 {
assert_eq!((m.submit)(acp, 12, id, u32::MAX, std::ptr::null(), 0), S_OK);
}
assert_eq!((m.message_count)(acp), 2);
let mut message = Message {
kind: 0,
dropped: 0,
usec: 0,
data: [0; 16],
};
assert!((m.pop_message)(acp, &mut message) && (m.pop_message)(acp, &mut message));
assert_eq!((m.submit)(acp, 12, 5, u32::MAX, std::ptr::null(), 0), S_OK);
assert!((m.pop_message)(acp, &mut message));
let dropped = message.dropped;
assert_eq!(dropped, 2);
(m.release)(acp);
}
#[test]
fn startup_as_fmod_does_it() {
let _serial = lock(&CONTEXT_TESTS);
// Context arrays: rate conversion, DMA and XMA.
let mut request = ShapeContexts {
counts: [0x200, 0, 0, 0x400, 0x200, 0],
@@ -0,0 +1,229 @@
//! Debugging aid: `VICTORY_AUDIO_CAPTURE=<file.wav>` records what the title
//! plays, 48 kHz stereo 16-bit, through process loopback: our own process
//! tree only, never the rest of the host's mix. Stretches where nothing was
//! played are written as silence, so the file keeps real time.
//!
//! The recorder runs in a child copy of this executable: an audio client
//! in the title's process raises that process's timer resolution, which
//! changes how the title's own waits behave.
use std::fs::File;
use std::io::{Seek, SeekFrom, Write};
use std::path::Path;
use std::time::{Duration, Instant};
use windows::Win32::Media::Audio::{
AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY, AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED,
AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_LOOPBACK,
AUDIOCLIENT_ACTIVATION_PARAMS, AUDIOCLIENT_ACTIVATION_PARAMS_0,
AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK, AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS,
ActivateAudioInterfaceAsync, IActivateAudioInterfaceAsyncOperation,
IActivateAudioInterfaceCompletionHandler, IActivateAudioInterfaceCompletionHandler_Impl,
IAudioCaptureClient, IAudioClient, PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE,
VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, WAVE_FORMAT_PCM, WAVEFORMATEX,
};
use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx};
use windows::Win32::Foundation::WAIT_OBJECT_0;
use windows::Win32::System::Threading::{
OpenProcess, PROCESS_SYNCHRONIZE, Sleep, WaitForSingleObject,
};
use windows::core::{HRESULT, IUnknown, Interface, Ref, implement};
const RATE: u32 = 48_000;
const FRAME_BYTES: usize = 4;
/// Activation completes asynchronously; the recording thread polls for it.
#[implement(IActivateAudioInterfaceCompletionHandler)]
struct Activated;
impl IActivateAudioInterfaceCompletionHandler_Impl for Activated_Impl {
fn ActivateCompleted(
&self,
_: Ref<IActivateAudioInterfaceAsyncOperation>,
) -> windows::core::Result<()> {
Ok(())
}
}
/// Names the process to record, in the recorder's environment.
const TARGET: &str = "VICTORY_AUDIO_CAPTURE_OF";
/// Starts the recorder if `VICTORY_AUDIO_CAPTURE` names a file. With this
/// module's debug log, also logs once a second what a `Sleep(1)` takes in
/// this process (the title's millisecond waits get the same).
pub fn start() {
if tracing::enabled!(tracing::Level::DEBUG) {
let _ = std::thread::Builder::new()
.name("victory timing probe".into())
.spawn(|| {
loop {
std::thread::sleep(Duration::from_secs(1));
let at = Instant::now();
// SAFETY: plain wait.
unsafe { Sleep(1) };
let ms = at.elapsed().as_secs_f32() * 1000.0;
tracing::debug!(ms, "Sleep(1) took");
}
});
}
if std::env::var_os("VICTORY_AUDIO_CAPTURE").is_some()
&& let Err(e) = std::env::current_exe().and_then(|exe| {
std::process::Command::new(exe)
.env(TARGET, std::process::id().to_string())
.spawn()
})
{
tracing::warn!("audio capture not started: {e}");
}
}
/// In the recorder (a child started by [`start`]): records until the
/// target exits and returns true; false in any other process.
pub fn child() -> bool {
let (Some(pid), Some(path)) = (
std::env::var(TARGET).ok().and_then(|p| p.parse().ok()),
std::env::var_os("VICTORY_AUDIO_CAPTURE"),
) else {
return false;
};
if let Err(e) = record(pid, Path::new(&path)) {
tracing::warn!("audio capture stopped: {e}");
}
true
}
fn header(frames: u64) -> [u8; 44] {
let data = u32::try_from(frames * FRAME_BYTES as u64).unwrap_or(u32::MAX - 36);
let mut h = [0u8; 44];
let fields: [(&[u8], usize); 11] = [
(b"RIFF", 0),
(&(36 + data).to_le_bytes(), 4),
(b"WAVEfmt ", 8),
(&16u32.to_le_bytes(), 16),
(&1u16.to_le_bytes(), 20),
(&2u16.to_le_bytes(), 22),
(&RATE.to_le_bytes(), 24),
(&(RATE * FRAME_BYTES as u32).to_le_bytes(), 28),
(&(FRAME_BYTES as u16).to_le_bytes(), 32),
(&16u16.to_le_bytes(), 34),
(b"data", 36),
];
for (bytes, at) in fields {
h[at..at + bytes.len()].copy_from_slice(bytes);
}
h[40..].copy_from_slice(&data.to_le_bytes());
h
}
fn record(pid: u32, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
// SAFETY: COM calls with parameters built here; buffers are used only
// between `GetBuffer` and `ReleaseBuffer`.
unsafe {
CoInitializeEx(None, COINIT_MULTITHREADED).ok()?;
let target = OpenProcess(PROCESS_SYNCHRONIZE, false, pid)?;
let params = AUDIOCLIENT_ACTIVATION_PARAMS {
ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,
Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 {
ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS {
TargetProcessId: pid,
ProcessLoopbackMode: PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE,
},
},
};
/// A `PROPVARIANT` holding a blob (`VT_BLOB`).
#[repr(C)]
struct Blob {
vt: u16,
reserved: [u16; 3],
size: u32,
data: *const AUDIOCLIENT_ACTIVATION_PARAMS,
}
let blob = Blob {
vt: 0x41,
reserved: [0; 3],
size: size_of_val(&params) as u32,
data: &params,
};
let handler: IActivateAudioInterfaceCompletionHandler = Activated.into();
let operation = ActivateAudioInterfaceAsync(
VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK,
&IAudioClient::IID,
Some((&raw const blob).cast()),
&handler,
)?;
let client = loop {
let (mut hr, mut client) = (HRESULT(0), None::<IUnknown>);
// Fails (`E_ILLEGAL_METHOD_CALL`) until activation completes.
if operation.GetActivateResult(&mut hr, &mut client).is_ok() {
hr.ok()?;
break client.ok_or("no audio client")?.cast::<IAudioClient>()?;
}
std::thread::sleep(Duration::from_millis(10));
};
let format = WAVEFORMATEX {
wFormatTag: WAVE_FORMAT_PCM as u16,
nChannels: 2,
nSamplesPerSec: RATE,
nAvgBytesPerSec: RATE * FRAME_BYTES as u32,
nBlockAlign: FRAME_BYTES as u16,
wBitsPerSample: 16,
cbSize: 0,
};
client.Initialize(
AUDCLNT_SHAREMODE_SHARED,
AUDCLNT_STREAMFLAGS_LOOPBACK | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM,
10_000_000,
0,
&format,
None,
)?;
let capture: IAudioCaptureClient = client.GetService()?;
let mut file = File::create(path)?;
file.write_all(&header(0))?;
client.Start()?;
tracing::info!(path = %path.display(), "recording the title's audio");
let (mut written, mut first) = (0u64, None);
let mut patched = Instant::now();
loop {
std::thread::sleep(Duration::from_millis(10));
let ended = WaitForSingleObject(target, 0) == WAIT_OBJECT_0;
while capture.GetNextPacketSize()? > 0 {
let (mut data, mut frames, mut flags, mut qpc) = (std::ptr::null_mut(), 0, 0, 0);
capture.GetBuffer(&mut data, &mut frames, &mut flags, None, Some(&mut qpc))?;
// Where this packet belongs, from its time stamp (100 ns).
let at = (qpc - *first.get_or_insert(qpc)) * u64::from(RATE) / 10_000_000;
if at > written + u64::from(RATE / 500) {
tracing::debug!(
ms = (at - written) * 1000 / u64::from(RATE),
"audio capture: nothing played"
);
let silence = vec![0u8; (at - written) as usize * FRAME_BYTES];
file.write_all(&silence)?;
written = at;
}
let bytes = frames as usize * FRAME_BYTES;
if flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0 {
file.write_all(&vec![0u8; bytes])?;
} else {
file.write_all(std::slice::from_raw_parts(data, bytes))?;
}
if flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY.0 as u32 != 0 && written > 0 {
tracing::debug!("audio capture: discontinuity");
}
written += u64::from(frames);
capture.ReleaseBuffer(frames)?;
}
if ended || patched.elapsed() >= Duration::from_secs(1) {
// Valid sizes at any time: runs end by being killed.
file.seek(SeekFrom::Start(0))?;
file.write_all(&header(written))?;
file.seek(SeekFrom::End(0))?;
patched = Instant::now();
}
if ended {
return Ok(());
}
}
}
}
+56 -3
View File
@@ -1,23 +1,76 @@
//! `d3d12_xs.dll`: device creation. The device and everything it creates
//! live in `victory-gpu`.
//! `d3d12_xs.dll`: virtual memory setup, device creation, root signature
//! serialization. The device and everything it creates live in
//! `victory-gpu`.
use std::ffi::c_void;
use victory_gpu::device;
use victory_gpu::object::{HRESULT, Iid, Object};
use crate::{HleExport, HleModule};
/// Device creation; first hands the device the title's general allocator
/// (`XMemAlloc`, which honours the title's hooks) for resource memory.
extern "system" fn create_device(
adapter: *const c_void,
parameters: *const u32,
iid: *const Iid,
out: *mut *const Object,
) -> HRESULT {
victory_gpu::resource::use_allocator(super::xmem::XMemAlloc, super::xmem::XMemFree);
victory_gpu::resource::use_page_mapper(super::xmem::map_alias);
#[cfg(windows)]
victory_gpu::on_failure(host_gpu_failed);
device::create(adapter, parameters, iid, out)
}
/// A host GPU failure ends the run like a crash: reported to the crash log,
/// then the process ends as the console ends a title.
#[cfg(windows)]
fn host_gpu_failed(what: &str) -> ! {
use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess};
victory_loader::log_crash(&format!("VIctory: host GPU failure: {what}"));
const DXGI_ERROR_DEVICE_REMOVED: u32 = 0x887A_0005;
// SAFETY: ends our own process.
unsafe { TerminateProcess(GetCurrentProcess(), DXGI_ERROR_DEVICE_REMOVED) };
unreachable!("the process has ended")
}
/// Keeps the host's translations of the title's shaders in `dir` (a
/// folder of the cache) across runs.
pub fn use_shader_cache(dir: std::path::PathBuf) {
#[cfg(windows)]
victory_gpu::shader_cache::use_shader_cache(dir);
#[cfg(not(windows))]
let _ = dir;
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "d3d12x",
dlls: &["d3d12_xs.dll"],
exports: vec![
HleExport {
name: "D3D12ConfigureVirtualMemoryX",
address: device::configure_virtual_memory as *const () as usize,
},
HleExport {
name: "D3D12XboxCreateDevice",
address: device::create as *const () as usize,
address: create_device as *const () as usize,
},
HleExport {
name: "D3D12SerializeRootSignature",
address: victory_gpu::root::serialize as *const () as usize,
},
HleExport {
name: "D3D12SerializeVersionedRootSignature",
address: victory_gpu::root::serialize_versioned as *const () as usize,
},
// The AMD upscaler's (Series S).
HleExport {
name: "D3D12CreateRootSignatureDeserializer",
address: victory_gpu::root::create_deserializer as *const () as usize,
},
// A data import: the title reads the id at this address.
HleExport {
name: "IID_ID3D12Device",
+195
View File
@@ -0,0 +1,195 @@
//! The display and what the system shell does for a title: HDR mode, screen
//! timeout deferrals, launching URIs, screenshots.
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, add_ref, missing, put, text,
};
/// HDR mode; asked for with this interface id since 2020.
pub const HDR_PROVIDER: Guid = Guid::new(
0x03f0_fe74,
0xfdd9,
0x4e5c,
[0xb6, 0x30, 0xf9, 0x33, 0x9c, 0x47, 0xac, 0xc5],
);
pub const HDR_IID: Guid = Guid::new(
0x35f0_7670,
0x706e,
0x4bfb,
[0x94, 0x76, 0x09, 0x07, 0x98, 0xc5, 0xeb, 0xf3],
);
/// Launching URIs and screen timeout deferrals; the interface id is the
/// provider's.
pub const SHELL: Guid = Guid::new(
0x1b33_9674,
0x328d,
0x4283,
[0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39],
);
/// Screenshots and clips.
pub const CAPTURE_PROVIDER: Guid = Guid::new(
0xa4f1_aee2,
0x4bf1,
0x4485,
[0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27],
);
/// As Grand Theft Auto VI (2026) asks for it; it calls 0x28 (take a
/// screenshot) with the public API's arguments.
pub const CAPTURE_IID_2026: Guid = Guid::new(
0x22e6_72d7,
0xb4e3,
0x406c,
[0xbd, 0x50, 0x8f, 0x0d, 0x25, 0x23, 0x6f, 0x9e],
);
pub static HDR_OBJECT: Object = Object::new("hdr", &HDR_VTABLE);
pub static SHELL_OBJECT: Object = Object::new("shell", &SHELL_VTABLE);
pub static CAPTURE_OBJECT: Object = Object::new("capture", &CAPTURE_VTABLE);
pub const INTERFACES: &[Interface] = &[
(HDR_PROVIDER, HDR_IID, &HDR_OBJECT),
(SHELL, SHELL, &SHELL_OBJECT),
(CAPTURE_PROVIDER, CAPTURE_IID_2026, &CAPTURE_OBJECT),
];
type This = *const Object;
/// 2: disabled. We present in SDR, so the title must render SDR.
// shortcut: HDR output is not done (see the presentation items in
// `TODO.md`); report enabled, with the host display's luminance, once the
// swap chain can present HDR.
extern "system" fn try_enable_hdr(_: This, preference: u32, _info: *mut c_void) -> u32 {
tracing::info!(preference, "HDR mode: disabled (SDR presentation)");
2
}
/// Nothing launches URIs for the title: no store, browser or console app
/// exists here, and the console's are online services.
extern "system" fn launch_uri(_: This, _user: *const c_void, uri: *const c_char) -> HRESULT {
tracing::info!(uri = text(uri).unwrap_or_default(), "URI not launched");
NOT_SUPPORTED
}
/// A deferral keeps the host display on, as on the console, through a
/// power request; the handle is that request.
#[cfg(windows)]
extern "system" fn acquire_deferral(_: This, out: *mut *mut c_void) -> HRESULT {
use windows_sys::Win32::System::Power::{
PowerCreateRequest, PowerRequestDisplayRequired, PowerSetRequest,
};
use windows_sys::Win32::System::Threading::{
POWER_REQUEST_CONTEXT_SIMPLE_STRING, REASON_CONTEXT,
};
if out.is_null() {
return super::xasync::E_INVALIDARG;
}
let mut reason: Vec<u16> = "Title display deferral\0".encode_utf16().collect();
let mut context = REASON_CONTEXT {
Flags: POWER_REQUEST_CONTEXT_SIMPLE_STRING,
..Default::default()
};
context.Reason.SimpleReasonString = reason.as_mut_ptr();
// SAFETY: a valid context; the string is copied by the call.
let request = unsafe { PowerCreateRequest(&context) };
if request as isize == -1 {
return last_error();
}
// SAFETY: the request we just created.
if unsafe { PowerSetRequest(request, PowerRequestDisplayRequired) } == 0 {
let hr = last_error();
// SAFETY: as above; not handed out.
unsafe { windows_sys::Win32::Foundation::CloseHandle(request) };
return hr;
}
put(out, request)
}
#[cfg(windows)]
extern "system" fn close_deferral(_: This, handle: *mut c_void) {
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Power::{PowerClearRequest, PowerRequestDisplayRequired};
if !handle.is_null() {
// SAFETY: a request from `acquire_deferral`.
unsafe {
PowerClearRequest(handle, PowerRequestDisplayRequired);
CloseHandle(handle);
}
}
}
#[cfg(windows)]
fn last_error() -> HRESULT {
// SAFETY: no preconditions.
let code = unsafe { windows_sys::Win32::Foundation::GetLastError() };
(0x8007_0000 | (code & 0xffff)) as i32
}
// shortcut: screenshots fail as if capture were unavailable. Taking one needs
// a hook in the GPU side: the last presented frame read back as BGRA8 (size,
// row pitch, bytes) on request, e.g. `victory_gpu::last_frame() ->
// Option<Frame>`, copied from the back buffer after `PresentX`.
extern "system" fn take_screenshot(_: This, _user: *const c_void, _result: *mut c_void) -> HRESULT {
tracing::info!("screenshot not taken");
NOT_SUPPORTED
}
static HDR_VTABLE: Methods<5> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
missing::<3> as *const (),
try_enable_hdr as *const (), // 0x20
]);
#[cfg(windows)]
static SHELL_VTABLE: Methods<6> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
launch_uri as *const (), // 0x18
acquire_deferral as *const (), // 0x20
close_deferral as *const (), // 0x28
]);
#[cfg(not(windows))]
static SHELL_VTABLE: Methods<4> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
launch_uri as *const (),
]);
static CAPTURE_VTABLE: Methods<6> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
missing::<3> as *const (), // 0x18 diagnostic screenshot
missing::<4> as *const (), // 0x20 diagnostic clip
take_screenshot as *const (), // 0x28
]);
#[cfg(all(test, windows))]
mod tests {
use super::*;
use crate::modules::xgameruntime::{S_OK, method};
#[test]
fn sdr_and_display_deferrals() {
type Hdr = extern "system" fn(This, u32, *mut c_void) -> u32;
assert_eq!(
method::<Hdr>(&HDR_OBJECT, 0x20)(&HDR_OBJECT, 0, std::ptr::null_mut()),
2
);
type Acquire = extern "system" fn(This, *mut *mut c_void) -> HRESULT;
type Close = extern "system" fn(This, *mut c_void);
let mut handle = std::ptr::null_mut();
assert_eq!(
method::<Acquire>(&SHELL_OBJECT, 0x20)(&SHELL_OBJECT, &mut handle),
S_OK
);
assert!(!handle.is_null());
method::<Close>(&SHELL_OBJECT, 0x28)(&SHELL_OBJECT, handle);
}
}
+314
View File
@@ -0,0 +1,314 @@
//! The console's audio DSP (`chad.dll`): streams that convolve blocks of
//! float samples with an impulse response (reverb), or run other block
//! transforms, on a coprocessor.
//!
//! A title connects once with a memory block for the DSP, activates
//! streams, and submits one command per block (gains, an input and an
//! output buffer). Activation hands back a status block whose second word is
//! the ticket of the last completed command and whose fourth is its result;
//! the title checks it one block later and treats a late command as an
//! overrun. Commands complete when submitted here.
//!
//! The transforms themselves are not computed: the hardware takes impulse
//! responses already in its own partitioned frequency-domain layout, which
//! is not known. Outputs are silence, so reverb returns are dry.
// shortcut: no convolution or block transform; outputs are zeros. Needs the
// coprocessor's impulse response and spectrum layouts to do better.
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::c_void;
use std::sync::Mutex;
use super::xasync::E_INVALIDARG;
use super::xgameruntime::{HRESULT, S_OK};
use crate::{HleModule, hle_export};
const E_POINTER: HRESULT = 0x8000_4003_u32 as i32;
const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
const CONVOLUTION: u32 = 1;
/// Option bits that need a stereo stream, and one convolution refuses.
const STEREO_OPTIONS: u32 = 2 | 8;
const NOT_FOR_CONVOLUTION: u32 = 4;
pub struct Dsp {
max_streams: u32,
active: Mutex<u32>,
}
/// What activation describes.
#[repr(C, packed)]
pub struct StreamDesc {
kind: u32,
options: u32,
frames: u32,
channels: u32,
ir_floats: u32,
ir: *const f32,
}
/// The status block a stream's owner polls.
#[repr(C)]
pub struct Status {
submitted: u32,
completed: u32,
reserved: u32,
result: HRESULT,
}
pub struct Stream {
dsp: *mut Dsp,
frames: u32,
channels: u32,
status: Box<Status>,
}
/// One block of work.
#[repr(C)]
pub struct Command {
gains: [f32; 2],
input: *const f32,
output: *mut f32,
reserved: u64,
}
pub extern "system" fn XDspConnectWithMaximumStreamLimit(
base: *mut c_void,
base_length: u32,
ir_seconds: u32,
max_streams: u32,
max_channels: u32,
out: *mut *mut Dsp,
) -> HRESULT {
if base.is_null()
|| !(0x1_0000..=0x1F40_0000).contains(&base_length)
|| ir_seconds > 0x80
|| max_streams > 0x100
|| max_channels > 2
{
return E_INVALIDARG;
}
if out.is_null() {
return E_POINTER;
}
tracing::info!(
base_length,
ir_seconds,
max_streams,
max_channels,
"audio DSP connected"
);
let dsp = Box::new(Dsp {
max_streams,
active: Mutex::new(0),
});
// SAFETY: checked non-null.
unsafe { out.write(Box::into_raw(dsp)) };
S_OK
}
pub extern "system" fn XDspDisconnect(dsp: *mut Dsp) -> HRESULT {
if dsp.is_null() {
return E_INVALIDARG;
}
// SAFETY: made by `XDspConnectWithMaximumStreamLimit`; disconnected
// once, after its streams.
drop(unsafe { Box::from_raw(dsp) });
S_OK
}
fn valid(desc: &StreamDesc) -> bool {
let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels);
let shape = if kind == CONVOLUTION {
(1..=2).contains(&channels)
&& matches!(frames, 0x200 | 0x400)
&& options & NOT_FOR_CONVOLUTION == 0
} else {
channels == 1 && matches!(frames, 0x200 | 0x400 | 0x800)
};
shape && (options & STEREO_OPTIONS == 0 || channels == 2)
}
pub extern "system" fn XDspActivate(
dsp: *mut Dsp,
desc: *const StreamDesc,
status: *mut *const Status,
stream: *mut *mut Stream,
) -> HRESULT {
if status.is_null() || stream.is_null() {
return E_POINTER;
}
if dsp.is_null() || desc.is_null() {
return E_INVALIDARG;
}
// SAFETY: checked non-null; the title passes its description.
let desc = unsafe { &*desc };
if !valid(desc) {
return E_INVALIDARG;
}
let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels);
tracing::debug!(
kind,
options,
frames,
channels,
"audio DSP stream activated"
);
{
// SAFETY: a connection from `XDspConnectWithMaximumStreamLimit`.
let dsp = unsafe { &*dsp };
let mut active = dsp.active.lock().unwrap_or_else(|e| e.into_inner());
if *active >= dsp.max_streams {
return E_OUTOFMEMORY;
}
*active += 1;
}
let new = Box::new(Stream {
dsp,
frames: desc.frames,
channels: desc.channels,
status: Box::new(Status {
submitted: 0,
completed: 0,
reserved: 0,
result: S_OK,
}),
});
// SAFETY: checked non-null.
unsafe {
status.write(&*new.status);
stream.write(Box::into_raw(new));
}
S_OK
}
pub extern "system" fn XDspDeactivate(stream: *mut Stream) -> HRESULT {
if stream.is_null() {
return E_INVALIDARG;
}
// SAFETY: made by `XDspActivate`; deactivated once.
let stream = unsafe { Box::from_raw(stream) };
// SAFETY: the connection outlives its streams.
let dsp = unsafe { &*stream.dsp };
*dsp.active.lock().unwrap_or_else(|e| e.into_inner()) -= 1;
S_OK
}
/// Completes the command at once: its output block is silence.
pub extern "system" fn XDspSubmitCommand(
stream: *mut Stream,
command: *const Command,
ticket: *mut u32,
) -> HRESULT {
if stream.is_null() || command.is_null() {
return E_INVALIDARG;
}
// SAFETY: a stream from `XDspActivate`, the title's command.
let (stream, command) = unsafe { (&mut *stream, &*command) };
if !command.output.is_null() {
let samples = (stream.frames * stream.channels) as usize;
// SAFETY: the title's output buffer holds one block of the stream.
unsafe { std::ptr::write_bytes(command.output, 0, samples) };
}
let status = &mut *stream.status;
let next = status.submitted.wrapping_add(1);
// SAFETY: the status block is read by title code on other threads.
unsafe {
std::ptr::write_volatile(&mut status.submitted, next);
std::ptr::write_volatile(&mut status.result, S_OK);
std::ptr::write_volatile(&mut status.completed, next);
}
if !ticket.is_null() {
// SAFETY: optional out parameter.
unsafe { ticket.write(next) };
}
S_OK
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "dsp",
dlls: &["chad.dll"],
exports: vec![
hle_export!(XDspConnectWithMaximumStreamLimit),
hle_export!(XDspDisconnect),
hle_export!(XDspActivate),
hle_export!(XDspDeactivate),
hle_export!(XDspSubmitCommand),
],
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn convolution_stream_as_the_title_drives_it() {
let mut base = vec![0u8; 0x10_0000];
let mut dsp = std::ptr::null_mut();
assert_eq!(
XDspConnectWithMaximumStreamLimit(
base.as_mut_ptr().cast(),
0x10_0000,
24,
0x80,
1,
&mut dsp
),
S_OK
);
let ir = vec![0f32; 0x800];
// Stereo convolution with option 2, as the title asks for.
let desc = StreamDesc {
kind: CONVOLUTION,
options: 2,
frames: 0x400,
channels: 2,
ir_floats: 0x800,
ir: ir.as_ptr(),
};
let (mut status, mut stream) = (std::ptr::null(), std::ptr::null_mut());
assert_eq!(XDspActivate(dsp, &desc, &mut status, &mut stream), S_OK);
let mut output = vec![1f32; 0x800];
let input = vec![0.5f32; 0x800];
let command = Command {
gains: [1.0, 1.0],
input: input.as_ptr(),
output: output.as_mut_ptr(),
reserved: 0,
};
let mut ticket = 0;
assert_eq!(XDspSubmitCommand(stream, &command, &mut ticket), S_OK);
// SAFETY: the stream's status block.
let (completed, result) = unsafe { ((*status).completed, (*status).result) };
assert_eq!((completed, result), (ticket, S_OK));
assert!(output.iter().all(|&s| s == 0.0));
assert_eq!(XDspDeactivate(stream), S_OK);
// Mono streams refuse stereo options; transforms are mono only.
let bad = StreamDesc {
channels: 1,
..desc
};
assert_eq!(
XDspActivate(dsp, &bad, &mut status, &mut stream),
E_INVALIDARG
);
let transform = StreamDesc {
kind: 2,
options: 0,
channels: 1,
ir_floats: 0,
ir: std::ptr::null(),
..desc
};
assert_eq!(
XDspActivate(dsp, &transform, &mut status, &mut stream),
S_OK
);
assert_eq!(XDspDeactivate(stream), S_OK);
assert_eq!(XDspDisconnect(dsp), S_OK);
}
}
File diff suppressed because it is too large. Load diff
+300 -18
View File
@@ -33,6 +33,7 @@ macro_rules! host {
unsafe { std::mem::transmute::<usize, $ty>(address) }
}};
}
pub(crate) use host;
/// Mounted drives: upper-case letter and host root (UTF-16, no trailing
/// separator, no NUL).
@@ -45,10 +46,7 @@ fn drives() -> MutexGuard<'static, Vec<(u16, Vec<u16>)>> {
/// 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<char> {
let mut wide: Vec<u16> = root.as_os_str().encode_wide().collect();
while wide.len() > 3 && wide.last().is_some_and(|c| SEPARATORS.contains(c)) {
wide.pop();
}
let wide = root_wide(root);
let mut drives = drives();
if let Some(&(letter, _)) = drives.iter().find(|(_, r)| *r == wide) {
return char::from_u32(letter.into());
@@ -63,15 +61,81 @@ pub fn mount(root: &Path) -> Option<char> {
Some(letter.into())
}
/// Gives the host folder `root` a drive letter the console fixes (titles
/// open their package as `G:\..` and temporary files as `T:\..`). A host
/// drive of that letter is hidden from the title.
pub fn mount_at(letter: char, root: &Path) {
let letter = letter.to_ascii_uppercase();
let Some(index) = u32::from(letter)
.checked_sub(u32::from('A'))
.filter(|i| *i < 26)
else {
return;
};
// SAFETY: no arguments.
let hides_host_drive = unsafe { GetLogicalDrives() } >> index & 1 != 0;
tracing::info!(drive = %letter, root = %root.display(), hides_host_drive, "virtual drive");
let mut drives = drives();
drives.retain(|(l, _)| u32::from(*l) != u32::from(letter));
drives.push((letter as u16, root_wide(root)));
}
/// `root` as UTF-16, absolute, without trailing separators (a drive root
/// keeps its own).
fn root_wide(root: &Path) -> Vec<u16> {
let root = std::path::absolute(root).unwrap_or_else(|_| root.to_owned());
let mut wide: Vec<u16> = root.as_os_str().encode_wide().collect();
while wide.len() > 3 && wide.last().is_some_and(|c| SEPARATORS.contains(c)) {
wide.pop();
}
wide
}
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];
/// Host paths from this length on take the `\\?\` form, which lifts the
/// host's MAX_PATH limit (248 characters for a directory, 260 for a file).
const LONG: usize = 248;
/// `root` and the title's `tail` as a `\\?\` path. That form turns off the
/// host's own clean-up, so `/` becomes `\` and `.` and `..` are resolved
/// here (`..` stops at the root).
fn verbatim(root: &[u16], tail: &[u16]) -> Vec<u16> {
let backslash = u16::from(b'\\');
let mut out = if root.starts_with(&VERBATIM) {
root.to_vec()
} else if let Some(unc) = root.strip_prefix(&[backslash; 2][..]) {
let mut out = VERBATIM.to_vec();
out.extend("UNC\\".encode_utf16());
out.extend_from_slice(unc);
out
} else {
[&VERBATIM[..], root].concat()
};
while out.last() == Some(&backslash) {
out.pop();
}
let dot = u16::from(b'.');
let mut parts: Vec<&[u16]> = Vec::new();
for part in tail.split(|c| SEPARATORS.contains(c)) {
match part {
[] => {}
[d] if *d == dot => {}
[d, e] if [*d, *e] == [dot; 2] => drop(parts.pop()),
_ => parts.push(part),
}
}
for part in parts {
out.push(backslash);
out.extend_from_slice(part);
}
out
}
/// 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<Vec<u16>> {
pub(crate) fn translate(path: &[u16]) -> Option<Vec<u16>> {
let (prefix, rest) = match path.strip_prefix(&VERBATIM[..]) {
Some(rest) => (&VERBATIM[..], rest),
None => (&[][..], path),
@@ -87,6 +151,11 @@ fn translate(path: &[u16]) -> Option<Vec<u16>> {
let drives = drives();
let (_, root) = drives.iter().find(|(l, _)| *l == letter)?;
let tail = &rest[2..];
if prefix.is_empty() && root.len() + tail.len() >= LONG {
let mut out = verbatim(root, tail);
out.push(0);
return Some(out);
}
let mut out = prefix.to_vec();
out.extend_from_slice(root);
// `X:` and `X:name` are relative to the root.
@@ -124,7 +193,18 @@ fn wide(path: *const u16) -> Wide {
let len = (0..).take_while(|&i| *path.add(i) != 0).count();
std::slice::from_raw_parts(path, len)
};
Wide(path, translate(path_slice))
let host = translate(path_slice);
trace(path_slice, host.as_deref());
Wide(path, host)
}
/// Every title path at debug level, with the host path if rewritten.
fn trace(path: &[u16], host: Option<&[u16]>) {
tracing::debug!(
path = %String::from_utf16_lossy(path),
host = host.map(|h| String::from_utf16_lossy(&h[..h.len() - 1])),
"title path"
);
}
/// A narrow path (ANSI code page, as the host decodes it) on a virtual
@@ -138,7 +218,10 @@ fn narrow(path: *const c_char) -> Option<Vec<u16>> {
// 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,
_ => {
tracing::debug!(path = %String::from_utf8_lossy(bytes), "title path");
return None;
}
}
let len = i32::try_from(bytes.len()).ok()?;
// SAFETY: sizing call, then a call with room for `n` units.
@@ -148,7 +231,9 @@ fn narrow(path: *const c_char) -> Option<Vec<u16>> {
MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, wide.as_mut_ptr(), n);
wide
};
translate(&wide)
let host = translate(&wide);
trace(&wide, host.as_deref());
host
}
/// An ASCII mode string (`"rb"`, `"w, ccs=UTF-8"`) for a wide CRT call.
@@ -220,6 +305,24 @@ pub extern "system" fn CreateFileA(
}
}
/// Used by Bink.
pub extern "system" fn CreateFile2(
path: *const u16,
access: u32,
share: u32,
disposition: u32,
params: *const c_void,
) -> Handle {
let p = wide(path);
host!("kernel32.dll", "CreateFile2": extern "system" fn(*const u16, u32, u32, u32, *const c_void) -> Handle)(
p.ptr(),
access,
share,
disposition,
params,
)
}
pub extern "system" fn DeleteFileA(path: *const c_char) -> i32 {
match narrow(path) {
Some(p) => {
@@ -231,6 +334,35 @@ pub extern "system" fn DeleteFileA(path: *const c_char) -> i32 {
}
}
pub extern "system" fn DeleteFileW(path: *const u16) -> i32 {
let p = wide(path);
host!("kernel32.dll", "DeleteFileW": extern "system" fn(*const u16) -> i32)(p.ptr())
}
pub extern "system" fn RemoveDirectoryW(path: *const u16) -> i32 {
let p = wide(path);
host!("kernel32.dll", "RemoveDirectoryW": extern "system" fn(*const u16) -> i32)(p.ptr())
}
pub extern "system" fn SetFileAttributesW(path: *const u16, attributes: u32) -> i32 {
let p = wide(path);
host!("kernel32.dll", "SetFileAttributesW": extern "system" fn(*const u16, u32) -> i32)(
p.ptr(),
attributes,
)
}
pub extern "system" fn GetFileAttributesA(path: *const c_char) -> u32 {
match narrow(path) {
Some(p) => GetFileAttributesW(p.as_ptr()),
None => {
host!("kernel32.dll", "GetFileAttributesA": extern "system" fn(*const c_char) -> u32)(
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)(
@@ -252,6 +384,11 @@ pub extern "system" fn GetFileAttributesExW(
)
}
pub extern "system" fn GetFileAttributesW(path: *const u16) -> u32 {
let p = wide(path);
host!("kernel32.dll", "GetFileAttributesW": extern "system" fn(*const u16) -> u32)(p.ptr())
}
pub extern "system" fn GetDiskFreeSpaceExW(
path: *const u16,
available: *mut u64,
@@ -369,6 +506,34 @@ pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> Fi
)
}
// Kernel reads into title memory. The GPU side leaves blocks of title GPU
// buffers read-only to see the title's next write, and the kernel's writes
// fail there instead of faulting into its handler; Grand Theft Auto VI's
// synchronous reads (title+0x313fc0) read straight into 4 KiB-aligned
// destinations and retry a failed `ReadFile` forever. So the destination
// is opened first.
pub extern "system" fn ReadFile(
file: *mut c_void,
buffer: *mut u8,
len: u32,
read: *mut u32,
overlapped: *mut c_void,
) -> i32 {
victory_gpu::kernel_will_write(buffer as usize, len as usize);
host!("kernel32.dll", "ReadFile": extern "system" fn(*mut c_void, *mut u8, u32, *mut u32, *mut c_void) -> i32)(
file, buffer, len, read, overlapped,
)
}
/// The host CRT reads large requests straight into the caller's buffer.
pub extern "C" fn fread(buffer: *mut u8, size: usize, count: usize, stream: File) -> usize {
victory_gpu::kernel_will_write(buffer as usize, size.saturating_mul(count));
host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize)(
buffer, size, count, stream,
)
}
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()),
@@ -391,6 +556,31 @@ pub extern "C" fn fopen_s(out: *mut File, path: *const c_char, mode: *const c_ch
}
}
/// `_open(path, flags[, mode])` is variadic; on x64 the optional integer
/// travels in the same register either way, so it is passed on as is.
pub extern "C" fn _open(path: *const c_char, flags: i32, mode: i32) -> i32 {
match narrow(path) {
Some(p) => host!("ucrtbase.dll", "_wopen": extern "C" fn(*const u16, i32, i32) -> i32)(
p.as_ptr(),
flags,
mode,
),
None => host!("ucrtbase.dll", "_open": extern "C" fn(*const c_char, i32, i32) -> i32)(
path, flags, mode,
),
}
}
/// See [`_open`]; used by libHttpClient.
pub extern "C" fn _wopen(path: *const u16, flags: i32, mode: i32) -> i32 {
let p = wide(path);
host!("ucrtbase.dll", "_wopen": extern "C" fn(*const u16, i32, i32) -> i32)(
p.ptr(),
flags,
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)
@@ -435,17 +625,22 @@ pub extern "C" fn _wutime64(path: *const u16, times: *mut c_void) -> i32 {
// The C++ library: `std::basic_filebuf::open` goes through `_Fiopen`.
const FIOPEN: &str = "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z";
const FIOPEN_WIDE: &str = "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z";
/// `_Fiopen(const wchar_t* path, ios_base::openmode, int protection)`.
extern "C" fn fiopen_wide(path: *const u16, mode: i32, protection: i32) -> File {
let p = wide(path);
host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z": extern "C" fn(*const u16, i32, i32) -> File)(
p.ptr(),
mode,
protection,
)
}
/// `_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,
)
}
Some(p) => fiopen_wide(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,
@@ -469,10 +664,18 @@ pub(crate) fn module() -> HleModule {
"msvcp140.dll",
],
exports: vec![
hle_export!(ReadFile),
hle_export!(fread),
hle_export!(CreateFileW),
hle_export!(CreateFileA),
hle_export!(CreateFile2),
hle_export!(DeleteFileA),
hle_export!(DeleteFileW),
hle_export!(RemoveDirectoryW),
hle_export!(SetFileAttributesW),
hle_export!(GetFileAttributesA),
hle_export!(CreateDirectoryW),
hle_export!(GetFileAttributesW),
hle_export!(GetFileAttributesExW),
hle_export!(GetDiskFreeSpaceExW),
hle_export!(GetDiskFreeSpaceW),
@@ -485,6 +688,8 @@ pub(crate) fn module() -> HleModule {
hle_export!(_wfsopen),
hle_export!(fopen),
hle_export!(fopen_s),
hle_export!(_open),
hle_export!(_wopen),
hle_export!(_wstat64),
hle_export!(_stat64i32),
hle_export!(remove),
@@ -494,6 +699,10 @@ pub(crate) fn module() -> HleModule {
name: FIOPEN,
address: fiopen as *const () as usize,
},
HleExport {
name: FIOPEN_WIDE,
address: fiopen_wide as *const () as usize,
},
],
}
}
@@ -506,6 +715,19 @@ mod tests {
s.encode_utf16().chain([0]).collect()
}
#[test]
fn kernel_reads_reach_the_buffer() {
use std::os::windows::io::AsRawHandle;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("data.bin");
std::fs::write(&path, b"0123456789").unwrap();
let file = std::fs::File::open(&path).unwrap();
let (mut out, mut n) = ([0u8; 10], 0);
let handle = file.as_raw_handle().cast();
assert_ne!(ReadFile(handle, out.as_mut_ptr(), 10, &mut n, std::ptr::null_mut()), 0);
assert_eq!((&out, n), (b"0123456789", 10));
}
fn text(v: &[u16]) -> String {
String::from_utf16_lossy(&v[..v.len() - 1])
}
@@ -535,6 +757,45 @@ mod tests {
assert_eq!(tr(r"C:\Windows".into()), None);
assert_eq!(tr("relative/path".into()), None);
assert_eq!(tr(String::new()), None);
// Fixed letters, as the console's package drive; a later mount of
// the same letter replaces the earlier one.
let package = tempfile::tempdir().unwrap();
mount_at('g', dir.path());
mount_at('G', package.path());
assert_eq!(
tr(r"G:\appdata0.rpf".into()),
Some(format!(r"{}\appdata0.rpf", package.path().display()))
);
assert_ne!(mount(dir.path()), Some('G'), "free letters skip fixed ones");
// Long ones take the `\\?\` form, cleaned up as the host would.
let long = "d".repeat(250);
assert_eq!(
tr(format!(r"G:/a/./b/../{long}//f")),
Some(format!(r"\\?\{}\a\{long}\f", package.path().display()))
);
assert_eq!(
verbatim(&w(r"\\server\share\")[..15], &w("/x/../../y")[..10]),
w(r"\\?\UNC\server\share\y")[..22].to_vec()
);
}
#[test]
fn long_title_paths_work_on_the_host() {
let dir = tempfile::tempdir().unwrap();
let letter = mount(dir.path()).unwrap();
let deep = format!("{letter}:/{}/{}", "a".repeat(200), "b".repeat(100));
let null = std::ptr::null_mut();
let first = w(&deep[..203]);
assert_ne!(CreateDirectoryW(first.as_ptr(), null), 0);
assert_ne!(CreateDirectoryW(w(&deep).as_ptr(), null), 0);
let file = format!("{deep}/../{}/f.txt", "b".repeat(100));
let f = _wfopen(w(&file).as_ptr(), w("wb").as_ptr());
assert!(!f.is_null(), "{file}");
host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32)(f);
assert_ne!(DeleteFileW(w(&format!("{deep}/f.txt")).as_ptr()), 0);
assert_ne!(RemoveDirectoryW(w(&deep).as_ptr()), 0);
}
#[test]
@@ -576,6 +837,27 @@ mod tests {
assert_eq!(remove(path.as_ptr().cast()), 0);
assert!(!dir.path().join("stream.txt").exists());
let f = fiopen_wide(w(&format!("{letter}:/wide.txt")).as_ptr(), OUT, 0x40);
assert!(!f.is_null());
fclose(f);
assert!(dir.path().join("wide.txt").is_file());
const OPEN_EXISTING: u32 = 3;
let path = w(&format!(r"{letter}:\created.bin"));
let h = CreateFile2(path.as_ptr(), GENERIC_WRITE, 0, OPEN_EXISTING, null);
assert_ne!(h as isize, -1);
close(h);
const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX;
assert_ne!(GetFileAttributesW(path.as_ptr()), INVALID_FILE_ATTRIBUTES);
const O_WRONLY: i32 = 1;
const O_CREAT: i32 = 0x100;
const S_IWRITE: i32 = 0x80;
let path = format!("{letter}:/low.bin\0");
let fd = _open(path.as_ptr().cast(), O_WRONLY | O_CREAT, S_IWRITE);
assert!(fd >= 0);
host!("ucrtbase.dll", "_close": extern "C" fn(i32) -> i32)(fd);
assert!(dir.path().join("low.bin").is_file());
// Other paths pass through untouched.
let host_path = format!("{}\0", dir.path().join("plain.txt").display());
File diff suppressed because it is too large. Load diff
+157 -14
View File
@@ -146,8 +146,14 @@ pub extern "system" fn LoadLibraryW(name: *const u16) -> *mut c_void {
/// 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 {
// `NULL` is the process's exe, which for the title is its own image.
let module = if module.is_null() {
runtime::main_image().unwrap_or(0) as *mut c_void
} else {
module
};
let Some(m) = registry().iter().find(|m| handle(m) == module) else {
return host::get_proc_address(module, name);
return host_override(module, name).unwrap_or_else(|| host::get_proc_address(module, name));
};
// Values below 0x10000 are ordinals; we export by name only.
if (name as usize) < 0x1_0000 {
@@ -169,6 +175,25 @@ pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> *
}
}
/// What a host module's `name` (or ordinal) is bound to at import binding
/// when we override it: a title that looks a function up by name must not
/// get past our overrides (the network guard, path rewriting).
fn host_override(module: *mut c_void, name: *const u8) -> Option<*mut c_void> {
if module.is_null() || runtime::image_path(module as usize).is_some() {
return None;
}
let symbol = if (name as usize) < 0x1_0000 {
format!("#{}", name as usize)
} else {
narrow(name)
};
let mut path = [0u16; 260];
let len = host::get_module_file_name_w(module, path.as_mut_ptr(), path.len() as u32) as usize;
let path = String::from_utf16_lossy(&path[..len.min(path.len())]);
let file = path.rsplit('\\').next()?;
crate::registry::lookup(file, &symbol).map(|address| address as *mut c_void)
}
/// Our pseudo modules and the title's images stay loaded: `LoadLibrary`
/// took no reference on them, so the host's count must not drop.
pub extern "system" fn FreeLibrary(module: *mut c_void) -> i32 {
@@ -189,14 +214,18 @@ pub extern "system" fn DisableThreadLibraryCalls(module: *mut c_void) -> i32 {
/// 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() {
tracing::info!(target: "title", "{}", narrow(text).trim_end());
let text = narrow(text);
host::note_title_output(text.trim());
tracing::info!(target: "title", "{}", text.trim_end());
}
}
/// See [`OutputDebugStringA`].
pub extern "system" fn OutputDebugStringW(text: *const u16) {
if !text.is_null() {
tracing::info!(target: "title", "{}", wide(text).trim_end());
let text = wide(text);
host::note_title_output(text.trim());
tracing::info!(target: "title", "{}", text.trim_end());
}
}
@@ -226,6 +255,28 @@ pub extern "C" fn _invalid_parameter_noinfo_noreturn() -> ! {
host::abort()
}
/// The title's unhandled-exception filter. Ours stands in front of it and
/// reports the crash first; the title still gets its own back.
static TITLE_FILTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
pub extern "system" fn SetUnhandledExceptionFilter(filter: usize) -> usize {
host::set_unhandled_exception_filter(report_unhandled);
TITLE_FILTER.swap(filter, std::sync::atomic::Ordering::AcqRel)
}
extern "system" fn report_unhandled(info: *const c_void) -> i32 {
host::report_unhandled(info);
match TITLE_FILTER.load(std::sync::atomic::Ordering::Acquire) {
0 => 0, // EXCEPTION_CONTINUE_SEARCH
filter => {
type Filter = extern "system" fn(*const c_void) -> i32;
// SAFETY: the title registered this filter.
let filter: Filter = unsafe { std::mem::transmute(filter) };
filter(info)
}
}
}
/// 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 {
@@ -240,7 +291,9 @@ fn handle(m: &HleModule) -> *mut c_void {
}
/// The title's images and our console modules by name; `None` leaves the
/// name to the host. With `load`, a title DLL not mapped yet is mapped now.
/// name to the host, which only DLLs `HostPolicy` passes through get (as at
/// import binding); others fail. With `load`, a title DLL not mapped yet is
/// mapped now.
fn find_module(path: &str, load: bool) -> Option<*mut c_void> {
let file = path.rsplit(['\\', '/']).next().unwrap_or(path);
// As the Windows loader does, a name without extension means a DLL.
@@ -249,29 +302,49 @@ fn find_module(path: &str, load: bool) -> Option<*mut c_void> {
} else {
format!("{file}.dll")
};
// Loads go through the title DLL loader first: it waits for a DLL that
// another thread is still initialising, as the Windows loader lock does.
if load {
match runtime::load_title_dll(&file) {
Ok(Some(base)) => return Some(base as *mut c_void),
Ok(None) => {}
// Not the host: it would load the unpatched DLL from the title's folder.
Err(error) => {
tracing::error!(dll = file, %error, "mapping a title DLL failed");
host::set_last_error(ERROR_MOD_NOT_FOUND);
return Some(std::ptr::null_mut());
}
}
}
if let Some(base) = runtime::image_named(&file) {
return Some(base as *mut c_void);
}
// DLLs the host has too are real host modules, whatever `--strict` says.
if !HostPolicy::default().allows(&file)
&& let Some(m) = registry().iter().find(|m| m.serves(&file))
{
let host_dll = HostPolicy::default().allows(&file);
if !host_dll && let Some(m) = registry().iter().find(|m| m.serves(&file)) {
if load {
tracing::info!(dll = file, "loaded as a pseudo module");
}
return Some(handle(m));
}
if !load {
if host_dll {
return None;
}
match runtime::load_title_dll(&file) {
Ok(base) => base.map(|b| b as *mut c_void),
// Not the host: it would load the unpatched DLL from the title's folder.
Err(error) => {
tracing::error!(dll = file, %error, "mapping a title DLL failed");
// Any other host DLL (wininet, urlmon, ...) is beyond what we guard, and
// the console does not have it.
refuse(&file);
host::set_last_error(ERROR_MOD_NOT_FOUND);
Some(std::ptr::null_mut())
}
}
/// Logs a DLL name the title is refused, once.
fn refuse(file: &str) {
static REFUSED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
let file = file.to_ascii_lowercase();
let mut refused = REFUSED.lock().unwrap_or_else(|e| e.into_inner());
if !refused.contains(&file) {
tracing::warn!(dll = file, "a host DLL outside the host policy: refused");
refused.push(file);
}
}
@@ -286,6 +359,7 @@ pub(crate) fn module() -> HleModule {
"api-ms-win-core-libraryloader-*",
"api-ms-win-core-processthreads-*",
"api-ms-win-core-debug-*",
"api-ms-win-core-errorhandling-*",
"api-ms-win-crt-runtime-*",
],
exports: vec![
@@ -307,10 +381,17 @@ pub(crate) fn module() -> HleModule {
hle_export!(terminate),
hle_export!(_invalid_parameter_noinfo_noreturn),
hle_export!(TerminateProcess),
hle_export!(SetUnhandledExceptionFilter),
],
}
}
/// The return addresses above the caller, as `module+rva`, for logs.
#[cfg(feature = "diagnostics")]
pub(crate) fn callers() -> String {
host::callers()
}
#[cfg(windows)]
mod host {
use std::ffi::c_void;
@@ -405,6 +486,27 @@ mod host {
unsafe { TerminateProcess(process, code) }
}
pub(super) fn set_unhandled_exception_filter(filter: extern "system" fn(*const c_void) -> i32) {
// SAFETY: our filter takes the exception pointers as an opaque pointer.
unsafe {
windows_sys::Win32::System::Diagnostics::Debug::SetUnhandledExceptionFilter(
std::mem::transmute::<
extern "system" fn(*const c_void) -> i32,
windows_sys::Win32::System::Diagnostics::Debug::LPTOP_LEVEL_EXCEPTION_FILTER,
>(filter),
)
};
}
pub(super) fn report_unhandled(info: *const c_void) {
// SAFETY: the system's exception pointers, passed to the filter.
unsafe { victory_loader::report_unhandled(info.cast()) };
}
pub(super) fn note_title_output(line: &str) {
victory_loader::note_title_output(line);
}
/// Our caller's callers, as `module+rva`.
pub(super) fn callers() -> String {
let mut frames = [std::ptr::null_mut(); 12];
@@ -479,6 +581,12 @@ mod host {
std::process::exit(code as i32)
}
pub(super) fn set_unhandled_exception_filter(_: extern "system" fn(*const c_void) -> i32) {}
pub(super) fn report_unhandled(_: *const c_void) {}
pub(super) fn note_title_output(_: &str) {}
pub(super) fn callers() -> String {
String::new()
}
@@ -511,6 +619,41 @@ mod tests {
text.encode_utf16().chain(Some(0)).collect()
}
#[cfg(windows)]
#[test]
fn host_lookups_by_name_get_our_overrides() {
let kernel32 = GetModuleHandleW(w("kernel32.dll").as_ptr());
assert!(!kernel32.is_null());
let ours = crate::registry::lookup("kernel32.dll", "CreateFileW").unwrap();
assert_eq!(
GetProcAddress(kernel32, c"CreateFileW".as_ptr().cast()) as usize,
ours
);
// A plain name stays the host's.
let host = host::get_proc_address(kernel32, c"GetTickCount".as_ptr().cast());
assert!(!host.is_null());
assert_eq!(
GetProcAddress(kernel32, c"GetTickCount".as_ptr().cast()),
host
);
// Host DLLs outside the host policy do not exist for the title.
assert!(LoadLibraryW(w("wininet.dll").as_ptr()).is_null());
assert!(LoadLibraryA(c"C:\\Windows\\System32\\urlmon".as_ptr().cast()).is_null());
assert!(GetModuleHandleW(w("WININET.DLL").as_ptr()).is_null());
assert_eq!(
// SAFETY: reads this thread's last error.
unsafe { windows_sys::Win32::Foundation::GetLastError() },
ERROR_MOD_NOT_FOUND
);
assert!(!LoadLibraryW(w("kernel32").as_ptr()).is_null());
// By ordinal too (ws2_32 #4 is `connect`).
let ws2 = LoadLibraryW(w("ws2_32.dll").as_ptr());
assert_eq!(
GetProcAddress(ws2, 4 as *const u8) as usize,
crate::registry::lookup("ws2_32.dll", "connect").unwrap()
);
}
#[test]
fn title_dlls_and_pseudo_modules_are_found_by_name() {
let base = 0x7100_0000_0000usize;
+143 -19
View File
@@ -1,7 +1,8 @@
//! 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.
//! quitting it or launching a new game 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; a new launch then starts
//! `victory` again, which waits for this process to be gone.
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
#![allow(clippy::too_many_arguments)]
@@ -11,7 +12,7 @@ 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::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, RECT, 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};
@@ -72,7 +73,8 @@ pub extern "system" fn CreateWindowExW(
instance: HINSTANCE,
param: *const c_void,
) -> HWND {
// SAFETY: the title's own arguments, forwarded.
let (x, y, width, height) = fit(parent, x, y, width, height);
// SAFETY: the title's own arguments, forwarded (the size fitted).
let hwnd = unsafe {
wm::CreateWindowExW(
ex_style, class, name, style, x, y, width, height, parent, menu, instance, param,
@@ -97,7 +99,8 @@ pub extern "system" fn CreateWindowExA(
instance: HINSTANCE,
param: *const c_void,
) -> HWND {
// SAFETY: the title's own arguments, forwarded.
let (x, y, width, height) = fit(parent, x, y, width, height);
// SAFETY: the title's own arguments, forwarded (the size fitted).
let hwnd = unsafe {
wm::CreateWindowExA(
ex_style, class, name, style, x, y, width, height, parent, menu, instance, param,
@@ -107,6 +110,44 @@ pub extern "system" fn CreateWindowExA(
hwnd
}
/// A console title sizes its window to its render target (Grand Theft
/// Auto VI: 3840x2160 on a Series X), which can exceed the host's screen.
/// A top-level window larger than the work area is shrunk to fit, keeping
/// its proportions, and centred; what it shows is scaled to it (the swap
/// chain stretches).
fn fit(parent: HWND, x: i32, y: i32, width: i32, height: i32) -> (i32, i32, i32, i32) {
let mut area = RECT::default();
// SAFETY: `area` receives the primary monitor's work area.
let known =
unsafe { wm::SystemParametersInfoW(wm::SPI_GETWORKAREA, 0, (&raw mut area).cast(), 0) };
let fitted = fit_into(&area, width, height);
if !parent.is_null() || known == 0 || fitted == (width, height) {
return (x, y, width, height);
}
tracing::info!(width, height, to = ?fitted, "title window fitted to the screen");
let (w, h) = fitted;
let left = area.left + (area.right - area.left - w) / 2;
let top = area.top + (area.bottom - area.top - h) / 2;
(left, top, w, h)
}
/// `width` x `height` scaled down to fit `area`, or unchanged if it fits
/// (or is `CW_USEDEFAULT`).
fn fit_into(area: &RECT, width: i32, height: i32) -> (i32, i32) {
let (aw, ah) = (area.right - area.left, area.bottom - area.top);
if width <= 0 || height <= 0 || aw <= 0 || ah <= 0 || (width <= aw && height <= ah) {
return (width, height);
}
let scale = f64::min(
f64::from(aw) / f64::from(width),
f64::from(ah) / f64::from(height),
);
(
(f64::from(width) * scale) as i32,
(f64::from(height) * scale) as i32,
)
}
/// Puts our procedure in front of the title's.
fn hook(hwnd: HWND) {
if hwnd.is_null() {
@@ -130,7 +171,7 @@ extern "system" fn window_proc(
// 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();
end_title("window closed", Box::new(|| {}));
return 0;
}
// SAFETY: the procedure `hook` stored, called the way the system would.
@@ -144,30 +185,97 @@ extern "system" fn window_proc(
}
}
/// 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) {
/// Suspends the title as the console does when it ends it, runs `then`
/// (once), then ends the process. Returns at once; later calls do nothing.
pub(crate) fn end_title(why: &'static str, then: Box<dyn FnOnce() + Send>) {
static ENDING: AtomicBool = AtomicBool::new(false);
if ENDING.swap(true, Ordering::SeqCst) {
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.
tracing::info!(routines = suspend.len(), "{why}: suspending the title");
// Whoever comes first (the routines or the deadline) runs `then`; the
// other waits for it, so the process never ends halfway through.
let then = std::sync::Arc::new(Mutex::new(Some(then)));
let finish = move |how: &str| {
let mut then = then.lock().unwrap_or_else(|e| e.into_inner());
tracing::info!("{how}; ending the title");
if let Some(then) = then.take() {
then();
}
end();
};
let late = finish.clone();
// Not on the calling thread: titles hand the suspend to their window
// 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();
finish("title suspended");
});
std::thread::spawn(|| {
std::thread::spawn(move || {
std::thread::sleep(SUSPEND_DEADLINE);
tracing::warn!("title did not finish suspending in time; ending it");
end();
late("title did not finish suspending in time");
});
}
/// Set in the environment of a relaunched `victory`: an inherited handle
/// of the process it replaces.
const RELAUNCHED_FROM: &str = "VICTORY_RELAUNCHED_FROM";
/// Starts `victory` again with `args` (after the title has suspended); the
/// new process waits until this one has ended.
pub(crate) fn relaunch(args: Vec<std::ffi::OsString>) {
use windows_sys::Win32::Foundation::{DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE};
let mut me: HANDLE = std::ptr::null_mut();
// SAFETY: an inheritable duplicate of our own process handle.
let duplicated = unsafe {
DuplicateHandle(
GetCurrentProcess(),
GetCurrentProcess(),
GetCurrentProcess(),
&mut me,
0,
1,
DUPLICATE_SAME_ACCESS,
)
} != 0;
let spawned = std::env::current_exe().and_then(|exe| {
let mut command = std::process::Command::new(exe);
command.args(&args);
if duplicated {
command.env(RELAUNCHED_FROM, (me as usize).to_string());
}
command.spawn()
});
match spawned {
Ok(child) => tracing::info!(pid = child.id(), ?args, "relaunched"),
Err(e) => tracing::warn!(%e, "relaunch failed; the title just ends"),
}
}
/// In a relaunched `victory`: waits (30 s at most) for the process it
/// replaces to be gone, so the two never share the title's files.
pub fn wait_for_previous() {
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
use windows_sys::Win32::System::Threading::WaitForSingleObject;
let Some(handle) = std::env::var(RELAUNCHED_FROM)
.ok()
.and_then(|h| h.parse::<usize>().ok())
else {
return;
};
// SAFETY: removing our own variable before any other thread reads it.
unsafe { std::env::remove_var(RELAUNCHED_FROM) };
let handle = handle as HANDLE;
// SAFETY: the inherited process handle the previous process gave us.
unsafe {
WaitForSingleObject(handle, 30_000);
CloseHandle(handle);
}
}
fn end() {
// SAFETY: ends this process, as the console ends a suspended title.
unsafe { TerminateProcess(GetCurrentProcess(), 0) };
@@ -211,6 +319,22 @@ mod tests {
assert_eq!(left, [b]);
}
#[test]
fn oversized_windows_shrink_to_the_screen() {
let area = RECT {
left: 0,
top: 0,
right: 1920,
bottom: 1040,
};
assert_eq!(fit_into(&area, 3840, 2160), (1848, 1040));
assert_eq!(fit_into(&area, 1280, 720), (1280, 720));
assert_eq!(
fit_into(&area, wm::CW_USEDEFAULT, 0),
(wm::CW_USEDEFAULT, 0)
);
}
#[test]
fn hooked_windows_still_reach_the_title_procedure() {
let null = std::ptr::null_mut();
+531
View File
@@ -0,0 +1,531 @@
//! Media Foundation is the host's (`mfplat.dll` passes through), except for
//! the source resolver: the host's would fetch `http`, `rtsp` and other
//! URLs over the network, past `modules::net`. Titles get a proxy that
//! opens local files only, with paths on our virtual drives rewritten to
//! their host folders, and forwards everything else to the host's resolver.
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::collections::HashSet;
use std::ffi::c_void;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Mutex, OnceLock};
use super::files;
use super::xgameruntime::{HRESULT, S_OK};
use crate::{HleModule, hle_export};
const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32;
const E_POINTER: HRESULT = 0x8000_4003_u32 as i32;
/// What Media Foundation answers for a URL scheme it has no handler for.
const UNSUPPORTED_SCHEME: HRESULT = 0xC00D_36C3_u32 as i32;
const IID_IUNKNOWN: [u8; 16] = guid(0x0000_0000, 0x0000, 0x0000, [0xC0, 0, 0, 0, 0, 0, 0, 0x46]);
const IID_RESOLVER: [u8; 16] = guid(
0xFBE5_A32D,
0xA497,
0x4B61,
[0xBB, 0x85, 0x97, 0xB1, 0xA8, 0x48, 0xA6, 0xE3],
);
const fn guid(a: u32, b: u16, c: u16, d: [u8; 8]) -> [u8; 16] {
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],
]
}
// The URL rule.
/// Where a resolver may read `url` from: `Ok` with the NUL-terminated
/// string to hand to the host, or `Err((scheme, host))` for anything that
/// is not a local file.
fn local(url: &[u16]) -> Result<Vec<u16>, (String, String)> {
let text = String::from_utf16_lossy(url);
let drive = |s: &str| {
let b = s.as_bytes();
b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':'
};
let host_of = |rest: &str| rest.split(['/', '\\']).next().unwrap_or("").to_string();
let path = if let Some(rest) = text.strip_prefix(r"\\?\") {
if !drive(rest) {
return Err(("unc".into(), host_of(rest.trim_start_matches("UNC\\"))));
}
text.clone()
} else if let Some(rest) = text.strip_prefix(r"\\").or_else(|| text.strip_prefix("//")) {
return Err(("unc".into(), host_of(rest)));
} else if drive(&text) {
text.clone()
} else if let Some((scheme, rest)) = text.split_once(':').filter(|(s, _)| {
s.len() > 1
&& s.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"+-.".contains(&c))
}) {
let scheme = scheme.to_ascii_lowercase();
let authority = rest.strip_prefix("//");
if scheme != "file" {
return Err((scheme, authority.map(host_of).unwrap_or_default()));
}
let path = match authority {
Some(rest) => {
let host = host_of(rest);
if !host.is_empty() && !host.eq_ignore_ascii_case("localhost") {
return Err((scheme, host));
}
&rest[host.len()..]
}
None => rest,
};
let path = percent_decode(path.trim_start_matches(['/', '\\'])).replace('/', "\\");
if !drive(&path) {
// A local file without a drive: the host resolves it as is.
return Ok(with_nul(url));
}
path
} else {
// A relative path.
return Ok(with_nul(url));
};
let wide: Vec<u16> = path.encode_utf16().collect();
Ok(files::translate(&wide).unwrap_or_else(|| with_nul(&wide)))
}
fn with_nul(s: &[u16]) -> Vec<u16> {
s.iter().copied().chain([0]).collect()
}
fn percent_decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
let hex = b
.get(i + 1..i + 3)
.and_then(|h| std::str::from_utf8(h).ok());
match (b[i], hex.and_then(|h| u8::from_str_radix(h, 16).ok())) {
(b'%', Some(v)) => {
out.push(v);
i += 3;
}
(c, _) => {
out.push(c);
i += 1;
}
}
}
String::from_utf8_lossy(&out).into_owned()
}
/// The URL to give the host, or the refusal (logged once per scheme and
/// host).
fn checked(url: *const u16) -> Result<Vec<u16>, HRESULT> {
if url.is_null() {
return Err(E_POINTER);
}
// SAFETY: a NUL-terminated wide string from the title.
let len = (0..)
.take_while(|&i| unsafe { url.add(i).read() } != 0)
.count();
// SAFETY: as above, `len` characters before the NUL.
let wide = unsafe { std::slice::from_raw_parts(url, len) };
local(wide).map_err(|(scheme, host)| {
static REFUSED: Mutex<Option<HashSet<(String, String)>>> = Mutex::new(None);
let mut refused = REFUSED.lock().unwrap_or_else(|e| e.into_inner());
if refused
.get_or_insert_with(HashSet::new)
.insert((scheme.clone(), host.clone()))
{
tracing::warn!(
scheme,
host,
"media: refused a URL that is not a local file"
);
}
UNSUPPORTED_SCHEME
})
}
// The proxy resolver.
/// The host's resolver, called through its method table.
#[repr(C)]
struct Host {
vtable: *const usize,
}
impl Host {
/// Method `n` of the host object, typed by the caller.
unsafe fn method<F: Copy>(this: *mut Host, n: usize) -> F {
// SAFETY: the caller names the slot's real signature; `this` is the
// host's live resolver.
unsafe { std::mem::transmute_copy(&*(*this).vtable.add(n)) }
}
}
#[repr(C)]
pub struct Resolver {
vtable: &'static Methods,
host: *mut Host,
refs: AtomicU32,
}
type Unknown = *mut c_void;
#[repr(C)]
struct Methods {
query_interface:
extern "system" fn(*mut Resolver, *const [u8; 16], *mut *mut c_void) -> HRESULT,
add_ref: extern "system" fn(*mut Resolver) -> u32,
release: extern "system" fn(*mut Resolver) -> u32,
create_from_url: extern "system" fn(
*mut Resolver,
*const u16,
u32,
Unknown,
*mut u32,
*mut Unknown,
) -> HRESULT,
create_from_stream: extern "system" fn(
*mut Resolver,
Unknown,
*const u16,
u32,
Unknown,
*mut u32,
*mut Unknown,
) -> HRESULT,
begin_from_url: extern "system" fn(
*mut Resolver,
*const u16,
u32,
Unknown,
*mut Unknown,
Unknown,
Unknown,
) -> HRESULT,
end_from_url: extern "system" fn(*mut Resolver, Unknown, *mut u32, *mut Unknown) -> HRESULT,
begin_from_stream: extern "system" fn(
*mut Resolver,
Unknown,
*const u16,
u32,
Unknown,
*mut Unknown,
Unknown,
Unknown,
) -> HRESULT,
end_from_stream: extern "system" fn(*mut Resolver, Unknown, *mut u32, *mut Unknown) -> HRESULT,
cancel: extern "system" fn(*mut Resolver, Unknown) -> HRESULT,
}
static METHODS: Methods = Methods {
query_interface,
add_ref,
release,
create_from_url,
create_from_stream,
begin_from_url,
end_from_url,
begin_from_stream,
end_from_stream,
cancel,
};
fn host(this: *mut Resolver) -> *mut Host {
// SAFETY: title code calls methods on a proxy we made, alive until its
// last release.
unsafe { (*this).host }
}
/// Only the resolver's own interfaces: anything else could hand out the
/// host object unguarded.
extern "system" fn query_interface(
this: *mut Resolver,
iid: *const [u8; 16],
out: *mut *mut c_void,
) -> HRESULT {
if iid.is_null() || out.is_null() {
return E_POINTER;
}
// SAFETY: checked non-null.
let iid = unsafe { *iid };
let found = iid == IID_IUNKNOWN || iid == IID_RESOLVER;
// SAFETY: checked non-null.
unsafe {
out.write(if found {
this.cast()
} else {
std::ptr::null_mut()
})
};
if !found {
return E_NOINTERFACE;
}
add_ref(this);
S_OK
}
extern "system" fn add_ref(this: *mut Resolver) -> u32 {
// SAFETY: as in `host`.
unsafe { (*this).refs.fetch_add(1, Ordering::Relaxed) + 1 }
}
extern "system" fn release(this: *mut Resolver) -> u32 {
// SAFETY: as in `host`.
let left = unsafe { (*this).refs.fetch_sub(1, Ordering::AcqRel) } - 1;
if left == 0 {
// SAFETY: made by `MFCreateSourceResolver`; this was the last
// reference, to the proxy and to the host object it holds.
let proxy = unsafe { Box::from_raw(this) };
// SAFETY: slot 2 is `Release`.
let release: extern "system" fn(*mut Host) -> u32 = unsafe { Host::method(proxy.host, 2) };
release(proxy.host);
}
left
}
extern "system" fn create_from_url(
this: *mut Resolver,
url: *const u16,
flags: u32,
props: Unknown,
kind: *mut u32,
object: *mut Unknown,
) -> HRESULT {
let url = match checked(url) {
Ok(url) => url,
Err(error) => {
if !object.is_null() {
// SAFETY: the title's out parameter.
unsafe { object.write(std::ptr::null_mut()) };
}
return error;
}
};
let host = host(this);
// SAFETY: slot 3 is `CreateObjectFromURL`.
let f: extern "system" fn(
*mut Host,
*const u16,
u32,
Unknown,
*mut u32,
*mut Unknown,
) -> HRESULT = unsafe { Host::method(host, 3) };
f(host, url.as_ptr(), flags, props, kind, object)
}
extern "system" fn begin_from_url(
this: *mut Resolver,
url: *const u16,
flags: u32,
props: Unknown,
cookie: *mut Unknown,
callback: Unknown,
state: Unknown,
) -> HRESULT {
let url = match checked(url) {
Ok(url) => url,
Err(error) => return error,
};
let host = host(this);
// SAFETY: slot 5 is `BeginCreateObjectFromURL`.
let f: extern "system" fn(
*mut Host,
*const u16,
u32,
Unknown,
*mut Unknown,
Unknown,
Unknown,
) -> HRESULT = unsafe { Host::method(host, 5) };
f(host, url.as_ptr(), flags, props, cookie, callback, state)
}
extern "system" fn create_from_stream(
this: *mut Resolver,
stream: Unknown,
url: *const u16,
flags: u32,
props: Unknown,
kind: *mut u32,
object: *mut Unknown,
) -> HRESULT {
let host = host(this);
// SAFETY: slot 4 is `CreateObjectFromByteStream`; the URL is only a
// hint for picking a handler.
let f: extern "system" fn(
*mut Host,
Unknown,
*const u16,
u32,
Unknown,
*mut u32,
*mut Unknown,
) -> HRESULT = unsafe { Host::method(host, 4) };
f(host, stream, url, flags, props, kind, object)
}
extern "system" fn end_from_url(
this: *mut Resolver,
result: Unknown,
kind: *mut u32,
object: *mut Unknown,
) -> HRESULT {
let host = host(this);
// SAFETY: slot 6 is `EndCreateObjectFromURL`.
let f: extern "system" fn(*mut Host, Unknown, *mut u32, *mut Unknown) -> HRESULT =
unsafe { Host::method(host, 6) };
f(host, result, kind, object)
}
#[allow(clippy::too_many_arguments)]
extern "system" fn begin_from_stream(
this: *mut Resolver,
stream: Unknown,
url: *const u16,
flags: u32,
props: Unknown,
cookie: *mut Unknown,
callback: Unknown,
state: Unknown,
) -> HRESULT {
let host = host(this);
// SAFETY: slot 7 is `BeginCreateObjectFromByteStream`.
let f: extern "system" fn(
*mut Host,
Unknown,
*const u16,
u32,
Unknown,
*mut Unknown,
Unknown,
Unknown,
) -> HRESULT = unsafe { Host::method(host, 7) };
f(host, stream, url, flags, props, cookie, callback, state)
}
extern "system" fn end_from_stream(
this: *mut Resolver,
result: Unknown,
kind: *mut u32,
object: *mut Unknown,
) -> HRESULT {
let host = host(this);
// SAFETY: slot 8 is `EndCreateObjectFromByteStream`.
let f: extern "system" fn(*mut Host, Unknown, *mut u32, *mut Unknown) -> HRESULT =
unsafe { Host::method(host, 8) };
f(host, result, kind, object)
}
extern "system" fn cancel(this: *mut Resolver, cookie: Unknown) -> HRESULT {
let host = host(this);
// SAFETY: slot 9 is `CancelObjectCreation`.
let f: extern "system" fn(*mut Host, Unknown) -> HRESULT = unsafe { Host::method(host, 9) };
f(host, cookie)
}
/// The host's resolver behind our proxy.
pub extern "system" fn MFCreateSourceResolver(out: *mut *mut Resolver) -> HRESULT {
if out.is_null() {
return E_POINTER;
}
static CREATE: OnceLock<Option<usize>> = OnceLock::new();
let Some(create) =
*CREATE.get_or_init(|| crate::host::function("mfplat.dll", "MFCreateSourceResolver"))
else {
return UNSUPPORTED_SCHEME;
};
// SAFETY: the host's `MFCreateSourceResolver(IMFSourceResolver**)`.
let create: extern "system" fn(*mut *mut Host) -> HRESULT =
unsafe { std::mem::transmute(create) };
let mut host = std::ptr::null_mut();
let hr = create(&mut host);
if hr < 0 || host.is_null() {
return hr;
}
let proxy = Box::new(Resolver {
vtable: &METHODS,
host,
refs: AtomicU32::new(1),
});
// SAFETY: checked non-null.
unsafe { out.write(Box::into_raw(proxy)) };
S_OK
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "media",
dlls: &["mfplat.dll"],
exports: vec![hle_export!(MFCreateSourceResolver)],
}
}
#[cfg(test)]
mod tests {
use super::*;
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().collect()
}
fn text(v: &[u16]) -> String {
String::from_utf16_lossy(v.strip_suffix(&[0]).unwrap_or(v))
}
#[test]
fn only_local_files_reach_the_host() {
// Network schemes and shares are refused, naming scheme and host.
let refused = |url: &str| local(&wide(url)).unwrap_err();
assert_eq!(
refused("https://cdn.example.com/a.mp4"),
("https".into(), "cdn.example.com".into())
);
assert_eq!(refused("RTSP://10.0.0.1:554/x").0, "rtsp");
assert_eq!(refused("mms://h/x").0, "mms");
assert_eq!(
refused(r"\\server\share\a.mp4"),
("unc".into(), "server".into())
);
assert_eq!(
refused("file://server/share/a.mp4"),
("file".into(), "server".into())
);
// A path on a virtual drive goes to its host folder, also as a
// `file:` URL; other local files pass as they are.
// Checked by opening the files: `files` may spell the host root
// differently (absolute, `\\?\` for long paths) from the temp dir.
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("movies")).unwrap();
std::fs::write(dir.path().join("movies").join("intro.mp4"), b"1").unwrap();
std::fs::write(dir.path().join("movies").join("intro a.mp4"), b"2").unwrap();
let letter = files::mount(dir.path()).expect("a free drive letter");
let host = text(&local(&wide(&format!(r"{letter}:\movies\intro.mp4"))).unwrap());
assert_eq!(
std::fs::read(&host).ok().as_deref(),
Some(&b"1"[..]),
"{host}"
);
let from_url =
text(&local(&wide(&format!("file:///{letter}:/movies/intro%20a.mp4"))).unwrap());
assert_eq!(
std::fs::read(&from_url).ok().as_deref(),
Some(&b"2"[..]),
"{from_url}"
);
assert_eq!(
text(&local(&wide("file:///C:/Windows/a.wav")).unwrap()),
r"C:\Windows\a.wav"
);
assert_eq!(text(&local(&wide("clip.mp4")).unwrap()), "clip.mp4");
}
#[test]
fn interface_ids_are_the_resolvers() {
assert_eq!(&IID_IUNKNOWN[8..], &[0xC0, 0, 0, 0, 0, 0, 0, 0x46]);
assert_eq!(&IID_RESOLVER[..4], &[0x2D, 0xA3, 0xE5, 0xFB]);
}
}
+29
View File
@@ -8,20 +8,37 @@
//! `file` (package paths), `thread` (TLS callbacks for title threads),
//! `xaudio2`, `xstore` stubs.
#[cfg(windows)]
pub mod apu;
pub mod audio;
pub mod d3d12x;
pub mod display;
pub mod dsp;
#[cfg(windows)]
pub mod dstorage;
#[cfg(windows)]
pub mod files;
pub mod gameinput;
pub mod kernel;
#[cfg(windows)]
pub mod lifecycle;
#[cfg(windows)]
pub mod media;
#[cfg(windows)]
pub mod net;
pub mod speech;
pub mod storage;
pub mod xasync;
pub mod xg;
pub mod xgame;
pub mod xgameruntime;
pub mod xgamesave;
pub mod xgameui;
#[cfg(windows)]
pub mod xmem;
pub mod xnetworking;
pub mod xpackage;
pub mod xstore;
pub mod xsystem;
pub mod xuser;
@@ -34,12 +51,24 @@ pub(crate) fn all() -> Vec<HleModule> {
gameinput::module(),
d3d12x::module(),
audio::module(),
dsp::module(),
xg::module(),
];
#[cfg(windows)]
all.push(apu::module());
#[cfg(windows)]
all.push(media::module());
#[cfg(windows)]
all.push(dstorage::module());
#[cfg(windows)]
all.push(files::module());
#[cfg(windows)]
all.push(lifecycle::module());
#[cfg(windows)]
all.push(net::module());
#[cfg(windows)]
all.push(xmem::module());
#[cfg(windows)]
all.push(xsystem::module());
all
}
File diff suppressed because it is too large. Load diff
+151
View File
@@ -0,0 +1,151 @@
//! Accessibility: speech synthesis for the title's narration. No voice is
//! installed here, and every stream is valid WAVE audio of no length, so
//! narration is silent.
// shortcut: silent speech. The host's engine (SAPI through COM, or WinRT
// speech synthesis) needs COM bindings this crate has only in diagnostics
// builds, plus voice enumeration and SSML the title sends (slot 0xa8); the
// title then plays the empty stream and goes on.
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text,
};
/// Closed captions, high contrast, speech to text and synthesis.
pub const PROVIDER: Guid = Guid::new(
0x3e24_1977,
0x6237,
0x41e9,
[0x85, 0x59, 0x10, 0x2c, 0x2d, 0x99, 0x83, 0xf1],
);
/// Unchanged since 2020.
pub const IID: Guid = Guid::new(
0xd722_b373,
0x8c4d,
0x4692,
[0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d],
);
pub static OBJECT: Object = Object::new("accessibility", &VTABLE);
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT)];
/// A WAVE file of 16 kHz mono 16-bit PCM with no samples: RIFF size 36,
/// a 16-byte format chunk (PCM, 1 channel, 16,000 Hz, 32,000 bytes/s,
/// block 2, 16 bits), an empty data chunk.
const SILENCE: [u8; 44] =
*b"RIFF\x24\0\0\0WAVEfmt \x10\0\0\0\x01\0\x01\0\x80\x3e\0\0\0\x7d\0\0\x02\0\x10\0data\0\0\0\0";
/// Synthesizers and streams hold nothing, so their handles are fixed
/// addresses and closing them is free.
static SYNTHESIZER: u8 = 0;
static STREAM: u8 = 0;
type This = *const Object;
/// No voice is installed, so the callback never runs.
extern "system" fn enumerate_voices(
_: This,
_context: *mut c_void,
_callback: *const c_void,
) -> HRESULT {
S_OK
}
extern "system" fn create(_: This, out: *mut *const u8) -> HRESULT {
put(out, &raw const SYNTHESIZER)
}
extern "system" fn close(_: This, _: *const u8) -> HRESULT {
S_OK
}
extern "system" fn set_default_voice(_: This, _: *const u8) -> HRESULT {
S_OK
}
extern "system" fn set_custom_voice(_: This, _: *const u8, _voice: *const c_char) -> HRESULT {
S_OK
}
extern "system" fn create_stream(
_: This,
_: *const u8,
words: *const c_char,
out: *mut *const u8,
) -> HRESULT {
tracing::debug!(text = text(words).unwrap_or_default(), "speech (silent)");
put(out, &raw const STREAM)
}
extern "system" fn stream_size(_: This, _: *const u8, out: *mut usize) -> HRESULT {
put(out, SILENCE.len())
}
extern "system" fn stream_data(
_: This,
_: *const u8,
size: usize,
buffer: *mut u8,
used: *mut usize,
) -> HRESULT {
if buffer.is_null() || size < SILENCE.len() {
return super::xasync::E_NOT_SUFFICIENT_BUFFER;
}
// SAFETY: the buffer holds `size` bytes, checked above.
unsafe { buffer.copy_from_nonoverlapping(SILENCE.as_ptr(), SILENCE.len()) };
if !used.is_null() {
// SAFETY: checked non-null.
unsafe { used.write(SILENCE.len()) };
}
S_OK
}
static VTABLE: Methods<22> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
missing::<3> as *const (), // 0x18 closed captions
missing::<4> as *const (), // 0x20
missing::<5> as *const (), // 0x28 high contrast
missing::<6> as *const (), // 0x30 speech to text
missing::<7> as *const (), // 0x38
enumerate_voices as *const (), // 0x40
create as *const (), // 0x48
close as *const (), // 0x50
set_default_voice as *const (), // 0x58
set_custom_voice as *const (), // 0x60
create_stream as *const (), // 0x68 from text
close as *const (), // 0x70 a stream
stream_size as *const (), // 0x78
stream_data as *const (), // 0x80
missing::<17> as *const (), // 0x88 speech to text
missing::<18> as *const (), // 0x90
missing::<19> as *const (), // 0x98
missing::<20> as *const (), // 0xa0
create_stream as *const (), // 0xa8 from SSML
]);
#[cfg(test)]
mod tests {
use super::*;
use crate::modules::xgameruntime::method;
#[test]
fn streams_are_empty_wave_files() {
let this: This = &OBJECT;
type Create = extern "system" fn(This, *mut *const u8) -> HRESULT;
type Stream = extern "system" fn(This, *const u8, *const c_char, *mut *const u8) -> HRESULT;
type Size = extern "system" fn(This, *const u8, *mut usize) -> HRESULT;
type Data = extern "system" fn(This, *const u8, usize, *mut u8, *mut usize) -> HRESULT;
let (mut synth, mut stream, mut size) = (std::ptr::null(), std::ptr::null(), 0);
assert_eq!(method::<Create>(&OBJECT, 0x48)(this, &mut synth), S_OK);
let say = method::<Stream>(&OBJECT, 0x68);
assert_eq!(say(this, synth, c"Hello".as_ptr(), &mut stream), S_OK);
assert_eq!(method::<Size>(&OBJECT, 0x78)(this, stream, &mut size), S_OK);
let mut wav = vec![0u8; size];
let mut used = 0;
let data = method::<Data>(&OBJECT, 0x80);
assert_eq!(data(this, stream, size, wav.as_mut_ptr(), &mut used), S_OK);
assert_eq!(
(&wav[..4], &wav[8..16], &wav[36..40]),
(&b"RIFF"[..], &b"WAVEfmt "[..], &b"data"[..])
);
assert_eq!(u32::from_le_bytes(wav[24..28].try_into().unwrap()), 16_000);
assert_eq!(used, 44);
}
}
+38 -4
View File
@@ -26,8 +26,17 @@ pub const IID: Guid = Guid::new(
[0x8b, 0x27, 0x95, 0xfc, 0x02, 0xd0, 0xf7, 0x5d],
);
/// As Grand Theft Auto VI (2026) asks for it; it calls 0x20 (path) and 0x28
/// (space) with the same arguments.
pub const IID_2026: Guid = Guid::new(
0x41a4_e10c,
0x5a7e,
0x41d9,
[0x8c, 0x37, 0x37, 0xbd, 0xe6, 0x2a, 0x07, 0xd6],
);
pub static OBJECT: Object = Object::new("persistent local storage", &VTABLE);
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT)];
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT), (PROVIDER, IID_2026, &OBJECT)];
type This = *const Object;
@@ -87,14 +96,38 @@ fn used_bytes(dir: &Path) -> u64 {
.sum()
}
/// What the host disk under `dir` has free (unlimited if unknown).
pub(crate) fn disk_free(dir: &Path) -> u64 {
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
let wide: Vec<u16> = dir.as_os_str().encode_wide().chain([0]).collect();
let mut free = 0;
let null = std::ptr::null_mut();
// SAFETY: a NUL-terminated path and a valid output.
let ok = unsafe {
windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW(
wide.as_ptr(),
&mut free,
null,
null,
)
};
if ok != 0 {
return free;
}
}
let _ = dir;
u64::MAX
}
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,
// Writable now: the quota's rest, as far as the host disk allows.
available_free: free.min(disk_free(&title.storage)),
total_free: free,
used,
total: title.storage_bytes,
@@ -153,6 +186,7 @@ mod tests {
id: 1,
storage: dir.path().to_owned(),
storage_bytes: 1000,
..Default::default()
});
// The path is a drive root, never the host folder.
+265 -13
View File
@@ -100,13 +100,15 @@ impl Port {
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.
// The worker ends once it holds the last reference (every queue
// using the port is closed) and nothing is left to run.
let worker = port.clone();
std::thread::spawn(move || {
loop {
if let Some(task) = worker.take(INFINITE) {
task.run(false);
match worker.take(1000) {
Some(task) => task.run(false),
None if Arc::strong_count(&worker) == 1 => break,
None => {}
}
}
});
@@ -117,9 +119,7 @@ impl 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::ThreadPool => POOL.submit(task),
Mode::Manual | Mode::Serialized => {
lock(&self.tasks).push_back(task);
self.ready.notify_one();
@@ -145,6 +145,49 @@ impl Port {
}
}
/// The thread pool behind thread-pool ports: idle workers are reused, and a
/// new one starts whenever more tasks wait than workers idle, so a callback
/// that blocks on another never starves it. Workers stay for reuse.
struct Pool {
/// Queued tasks and the number of idle workers.
state: Mutex<(VecDeque<Task>, usize)>,
ready: Condvar,
}
static POOL: Pool = Pool {
state: Mutex::new((VecDeque::new(), 0)),
ready: Condvar::new(),
};
impl Pool {
fn submit(&'static self, task: Task) {
let mut state = lock(&self.state);
state.0.push_back(task);
if state.0.len() > state.1 {
std::thread::spawn(move || self.work());
} else {
self.ready.notify_one();
}
}
fn work(&self) {
let mut state = lock(&self.state);
loop {
while state.0.is_empty() {
state.1 += 1;
state = self.ready.wait(state).unwrap_or_else(|e| e.into_inner());
state.1 -= 1;
}
let task = state.0.pop_front();
drop(state);
if let Some(task) = task {
task.run(false);
}
state = lock(&self.state);
}
}
}
/// A queue handle is `Arc::into_raw` of this; duplicating and closing a
/// handle add and drop a reference.
pub struct Queue {
@@ -641,16 +684,167 @@ pub fn XAsyncGetResult(
/// 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 {
finished_with(
block,
identity,
if hr < 0 { Err(hr) } else { Ok(Vec::new()) },
)
}
/// Like [`finished`], with the bytes `XAsyncGetResult` hands out for
/// `identity` (an error has none).
pub fn finished_with(
block: *mut AsyncBlock,
identity: *const c_void,
result: Result<Vec<u8>, HRESULT>,
) -> HRESULT {
type Data = Result<Vec<u8>, HRESULT>;
extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT {
// SAFETY: the runtime passes valid provider data.
// SAFETY: the runtime passes valid provider data; the context is the
// boxed result until cleanup frees it.
let data = unsafe { &*data };
if op == OP_BEGIN {
XAsyncComplete(data.block, data.context as usize as u32 as i32, 0);
let result = data.context.cast::<Data>();
match op {
// SAFETY: boxed in `finished_with`; nothing runs after cleanup.
OP_CLEANUP => drop(unsafe { Box::from_raw(result) }),
OP_BEGIN => {
// SAFETY: as above. Copied out: completing may clean up.
let (hr, len) = match unsafe { &*result } {
Ok(bytes) => (S_OK, bytes.len()),
Err(hr) => (*hr, 0),
};
XAsyncComplete(data.block, hr, len);
}
// SAFETY: as above; the runtime checked the buffer's size.
OP_GET_RESULT => unsafe {
if let Ok(bytes) = &*result {
data.buffer
.cast::<u8>()
.copy_from(bytes.as_ptr(), bytes.len());
}
},
_ => {}
}
S_OK
}
let context = hr as u32 as usize as *mut c_void;
XAsyncBegin(block, context, identity, std::ptr::null(), Some(provider))
let context = Box::into_raw(Box::new(result));
let hr = XAsyncBegin(
block,
context.cast(),
identity,
std::ptr::null(),
Some(provider),
);
if hr < 0 {
// Refused before the call existed, so no cleanup will come.
// SAFETY: still ours.
drop(unsafe { Box::from_raw(context) });
}
hr
}
/// Like [`finished_with`], but the result comes from `work`, run on a
/// thread of ours; the call stays pending until it returns (a dialog, say).
pub fn pending_with(
block: *mut AsyncBlock,
identity: *const c_void,
work: impl FnOnce() -> Result<Vec<u8>, HRESULT> + Send + 'static,
) -> HRESULT {
type Data = Mutex<(Option<Box<dyn FnOnce() -> Result<Vec<u8>, HRESULT> + Send>>, Vec<u8>)>;
extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT {
// SAFETY: the runtime passes valid provider data; the context is the
// boxed state until cleanup frees it.
let data = unsafe { &*data };
let state = data.context.cast::<Data>();
match op {
// SAFETY: boxed in `pending_with`; nothing runs after cleanup.
OP_CLEANUP => drop(unsafe { Box::from_raw(state) }),
OP_BEGIN => {
// SAFETY: as above; cleanup waits for completion.
let work = unsafe { &*state }.lock().unwrap_or_else(|e| e.into_inner()).0.take();
let (block, state) = (data.block as usize, state as usize);
std::thread::spawn(move || {
let result = work.map_or(Err(E_ABORT), |work| work());
let (hr, len) = match &result {
Ok(bytes) => (S_OK, bytes.len()),
Err(hr) => (*hr, 0),
};
if let Ok(bytes) = result {
// SAFETY: the call is pending, so its state lives.
let state = unsafe { &*(state as *const Data) };
state.lock().unwrap_or_else(|e| e.into_inner()).1 = bytes;
}
XAsyncComplete(block as *mut AsyncBlock, hr, len);
});
}
// SAFETY: as above; the runtime checked the buffer's size.
OP_GET_RESULT => unsafe {
let state = (*state).lock().unwrap_or_else(|e| e.into_inner());
data.buffer
.cast::<u8>()
.copy_from(state.1.as_ptr(), state.1.len());
},
_ => {}
}
S_OK
}
let state: Box<Data> = Box::new(Mutex::new((Some(Box::new(work)), Vec::new())));
let context = Box::into_raw(state);
let hr = XAsyncBegin(block, context.cast(), identity, std::ptr::null(), Some(provider));
if hr < 0 {
// SAFETY: refused before the call existed; still ours.
drop(unsafe { Box::from_raw(context) });
}
hr
}
/// The result of a call begun with [`finished_with`] for `identity`, as a
/// `T` written through `out`.
pub fn result<T>(block: *mut AsyncBlock, identity: *const c_void, out: *mut T) -> HRESULT {
XAsyncGetResult(
block,
identity,
size_of::<T>(),
out.cast(),
std::ptr::null_mut(),
)
}
/// The bytes of a value, for [`finished_with`].
pub fn bytes<T: Copy>(value: T) -> Vec<u8> {
// SAFETY: a `Copy` value is plain data; padding bytes are never read.
unsafe { std::slice::from_raw_parts((&raw const value).cast::<u8>(), size_of::<T>()) }.to_vec()
}
type Work = extern "system" fn(*mut AsyncBlock) -> HRESULT;
/// Runs `work` on the block's work port as an async call of its own; its
/// return value is the call's result.
pub fn XAsyncRun(block: *mut AsyncBlock, work: Option<Work>) -> HRESULT {
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 => {
// SAFETY: the context is the `Work` given to `XAsyncRun`.
let work = unsafe { std::mem::transmute::<*mut c_void, Work>(data.context) };
work(data.block)
}
_ => S_OK,
}
}
let Some(work) = work else {
return E_INVALIDARG;
};
let identity = XAsyncRun as *const c_void;
XAsyncBegin(
block,
work as *mut c_void,
identity,
std::ptr::null(),
Some(provider),
)
}
// The object `QueryApiImpl` returns. Each method takes the object first,
@@ -671,6 +865,9 @@ extern "system" fn m_get_result_size(_: This, b: *mut AsyncBlock, out: *mut usiz
extern "system" fn m_cancel(_: This, b: *mut AsyncBlock) {
XAsyncCancel(b)
}
extern "system" fn m_run(_: This, b: *mut AsyncBlock, work: Option<Work>) -> HRESULT {
XAsyncRun(b, work)
}
extern "system" fn m_begin(
_: This,
b: *mut AsyncBlock,
@@ -787,7 +984,7 @@ static VTABLE: Methods<31> = Methods([
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_run as *const (), // 0x30
m_begin as *const (), // 0x38
missing::<8> as *const (), // 0x40
m_schedule as *const (), // 0x48
@@ -927,6 +1124,61 @@ mod tests {
XTaskQueueCloseHandle(q);
}
#[test]
fn run_returns_the_work_result() {
extern "system" fn work(_: *mut AsyncBlock) -> HRESULT {
E_ABORT
}
let mut block = AsyncBlock {
queue: std::ptr::null(),
context: std::ptr::null_mut(),
callback: None,
internal: [0; 4],
};
assert_eq!(
slot::<extern "system" fn(This, *mut AsyncBlock, Option<Work>) -> HRESULT>(0x30)(
&OBJECT,
&mut block,
Some(work)
),
S_OK
);
assert_eq!(XAsyncGetStatus(&mut block, true), E_ABORT);
}
#[test]
fn pool_callbacks_may_wait_for_each_other() {
static SECOND: AtomicBool = AtomicBool::new(false);
static FIRST: AtomicBool = AtomicBool::new(false);
extern "system" fn waits(_: *mut c_void, _: bool) {
let start = std::time::Instant::now();
while !SECOND.load(Ordering::SeqCst) && start.elapsed().as_secs() < 5 {
std::thread::yield_now();
}
FIRST.store(SECOND.load(Ordering::SeqCst), Ordering::SeqCst);
}
extern "system" fn releases(_: *mut c_void, _: bool) {
SECOND.store(true, Ordering::SeqCst);
}
let mut q = std::ptr::null();
assert_eq!(XTaskQueueCreate(1, 1, &mut q), S_OK);
let none = std::ptr::null_mut();
assert_eq!(
XTaskQueueSubmitDelayedCallback(q, WORK, 0, none, Some(waits)),
S_OK
);
assert_eq!(
XTaskQueueSubmitDelayedCallback(q, WORK, 0, none, Some(releases)),
S_OK
);
let start = std::time::Instant::now();
while !FIRST.load(Ordering::SeqCst) && start.elapsed().as_secs() < 10 {
std::thread::sleep(Duration::from_millis(1));
}
assert!(FIRST.load(Ordering::SeqCst));
XTaskQueueCloseHandle(q);
}
#[test]
fn terminate_cancels_what_is_queued() {
static TERMINATED: AtomicBool = AtomicBool::new(false);
+780
View File
@@ -0,0 +1,780 @@
//! `xg_xs.dll`: the console's texture layout library. Titles ask it which
//! swizzle mode a texture should use, how large it is, where each mip and
//! slice lies, and to copy linear data into tiled memory and back. Served
//! from `victory_formats::texture`.
//!
//! Grand Theft Auto VI imports `XGCreateTextureComputer` and
//! `XGSuggestSwizzleMode` and calls these computer methods: Release (0x08),
//! the layout (0x10), copies into (0x40) and out of (0x48) a subresource,
//! and the 64 KiB tiling (0x50). The other slots log and fail.
#![allow(non_snake_case)]
// Title code passes pointers the real library would trust.
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::sync::atomic::{AtomicU32, Ordering};
use victory_formats::texture::{Dimension, Error, Layout, Swizzle, Texture, TextureDesc};
use super::xasync::{E_INVALIDARG, E_NOTIMPL};
use super::xgameruntime::{HRESULT, S_OK};
use crate::{HleModule, hle_export};
const E_FAIL: HRESULT = 0x8000_4005_u32 as i32;
/// `D3D12_RESOURCE_DESC`, whose layout field carries `0x100 | swizzle
/// mode` on the console (1 row major, 0 "pick one").
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct ResourceDesc {
pub dimension: u32,
pub alignment: u64,
pub width: u64,
pub height: u32,
pub depth_or_array: u16,
pub mips: u16,
pub format: u32,
pub samples: u32,
pub quality: u32,
pub layout: u32,
pub flags: u32,
}
const _: () = assert!(size_of::<ResourceDesc>() == 0x38);
const SWIZZLED: u32 = 0x100;
const ROW_MAJOR: u32 = 1;
const ALLOW_RENDER_TARGET: u32 = 1;
const ALLOW_DEPTH_STENCIL: u32 = 2;
const TEXTURE_1D: u32 = 2;
const TEXTURE_3D: u32 = 4;
/// The mode the console's library picks for a description: linear for 1D,
/// the XOR render and depth modes for targets, else 4 KiB standard
/// (`.ttpf` textures without a mode of their own use it).
///
/// shortcut: the rule of the library's older optimal-mode function (any
/// size, 2D, 3D and cubes alike); `XGSuggestSwizzleMode` itself is newer
/// than every copy we could check. Revisit if streamed textures come out
/// scrambled.
fn suggested(desc: &ResourceDesc) -> Swizzle {
if desc.dimension == TEXTURE_1D {
Swizzle::LINEAR
} else if desc.flags & ALLOW_DEPTH_STENCIL != 0 {
Swizzle::SW_64KB_Z_X
} else if desc.flags & ALLOW_RENDER_TARGET != 0 {
Swizzle::SW_64KB_R_X
} else {
Swizzle::SW_4KB_S
}
}
/// `(desc, flags, out layout)`; the title passes flags 0 and puts the
/// result in the description's layout field.
pub extern "system" fn XGSuggestSwizzleMode(
desc: *const ResourceDesc,
_flags: u32,
out: *mut u32,
) -> HRESULT {
// SAFETY: the title passes a description and room for the layout
// (either may be null).
match unsafe { (desc.as_ref(), out.as_mut()) } {
(Some(desc), Some(out)) => {
*out = SWIZZLED | suggested(desc).0;
S_OK
}
_ => E_INVALIDARG,
}
}
#[repr(C)]
pub struct Computer {
vtable: &'static Vtable,
refs: AtomicU32,
desc: ResourceDesc,
mips: u32,
texture: Texture,
}
type This = *mut Computer;
fn computer<'a>(this: This) -> &'a Computer {
// SAFETY: called from computer methods only.
unsafe { &*this }
}
pub extern "system" fn XGCreateTextureComputer(
desc: *const ResourceDesc,
out: *mut This,
) -> HRESULT {
// SAFETY: the title passes a description and room for a pointer.
let (Some(&desc), false) = (unsafe { desc.as_ref() }, out.is_null()) else {
return E_INVALIDARG;
};
let Some(texture) = texture(&desc) else {
tracing::warn!(?desc, "no texture layout");
return E_INVALIDARG;
};
tracing::debug!(
width = desc.width,
height = desc.height,
format = desc.format,
layout = format_args!("{:#x}", desc.layout),
size = texture.size,
"texture computer"
);
let mips = texture.planes[0].layout.mips.len() as u32;
let computer = Box::new(Computer {
vtable: &VTABLE,
refs: AtomicU32::new(1),
desc,
mips,
texture,
});
// SAFETY: checked non-null.
unsafe { out.write(Box::into_raw(computer)) };
S_OK
}
fn texture(desc: &ResourceDesc) -> Option<Texture> {
let dimension = match desc.dimension {
TEXTURE_1D => Dimension::Tex1d,
3 => Dimension::Tex2d,
TEXTURE_3D => Dimension::Tex3d,
_ => return None,
};
let swizzle = match desc.layout {
0 => suggested(desc),
ROW_MAJOR => Swizzle::LINEAR,
l if l & !0xff == SWIZZLED => Swizzle(l & 0xff),
_ => return None,
};
let texture = Texture::new(&TextureDesc {
dimension,
width: u32::try_from(desc.width).ok()?,
height: desc.height,
depth_or_array: u32::from(desc.depth_or_array),
mips: u32::from(desc.mips),
format: desc.format,
samples: desc.samples.max(1),
swizzle,
})
.ok()?;
// The layout struct has room for 15 mips.
(texture.planes[0].layout.mips.len() <= MIPS).then_some(texture)
}
const MIPS: usize = 15;
/// One mip in the layout the title reads (offsets 0x00, 0x08, 0x10 and
/// 0x1c are read by Grand Theft Auto VI; the rest follow the library's
/// older public shape).
#[repr(C)]
#[derive(Debug, Default, Clone, Copy)]
pub struct MipOut {
pub size: u64,
pub offset: u64,
pub slice_size: u64,
pub pitch_texels: u32,
pub pitch_bytes: u32,
pub alignment: u32,
/// Width, height in elements, depth or array size.
pub padded: [u32; 3],
pub elements: [u32; 2],
pub texels: [u32; 2],
pub depth_or_array: u32,
pub samples: u32,
pub swizzle: u32,
pub bank_rotation: [u64; 2],
pub slice_depth: u32,
pub in_tail: u32,
/// Where a tail mip starts in elements: x bits 0-10, y 11-21.
pub tail_position: u32,
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct PlaneOut {
/// 1 data, 7 depth, 8 stencil (metadata planes are not made).
pub usage: u32,
pub size: u64,
pub slice_size: u64,
pub offset: u64,
pub alignment: u64,
pub element_bytes: u32,
pub standard_mips: u32,
pub tail_mips: u32,
pub mips: [MipOut; MIPS],
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct LayoutOut {
pub size: u64,
pub alignment: u64,
pub mips: u32,
pub planes: u32,
pub plane: [PlaneOut; 4],
pub dimension: u32,
}
const _: () = assert!(size_of::<MipOut>() == 0x70);
const _: () = assert!(size_of::<PlaneOut>() == 0x6c8);
const _: () = assert!(size_of::<LayoutOut>() == 0x1b40);
/// The mode a tail mip is reported in: the 256-byte one of its kind (3 for
/// the render kind, which GFX10 lacks), the depth mode itself.
fn tail_swizzle(swizzle: Swizzle) -> u32 {
match swizzle.0 {
2 | 6 | 10 | 18 | 22 | 26 => Swizzle::SW_256B_D.0,
23 | 27 => 3,
24 => swizzle.0,
_ => Swizzle::SW_256B_S.0,
}
}
fn mip_out(desc: &ResourceDesc, l: &Layout, i: usize) -> MipOut {
let m = &l.mips[i];
let bpe = u64::from(l.desc.element_bytes);
let block = l.desc.block;
let three_d = desc.dimension == TEXTURE_3D;
let array = u32::from(desc.depth_or_array).max(1);
let mut out = MipOut {
pitch_texels: m.pitch * block,
pitch_bytes: m.pitch * l.desc.element_bytes,
padded: [m.pitch, m.rows, if three_d { m.depth_pitch } else { array }],
elements: [m.width, m.height],
texels: [((desc.width >> i) as u32).max(1), (desc.height >> i).max(1)],
depth_or_array: if three_d { m.depth } else { array },
samples: l.desc.samples,
slice_depth: l.block[2],
..MipOut::default()
};
let slice = u64::from(m.pitch) * u64::from(m.rows) * bpe;
let depth = u64::from(if three_d { m.depth_pitch } else { 1 });
match m.tail {
None => {
out.offset = m.offset;
out.slice_size = slice * u64::from(l.desc.samples);
out.size = out.slice_size * depth;
out.alignment = l.alignment as u32;
out.swizzle = l.desc.swizzle.0;
}
Some(t) => {
out.in_tail = 1;
out.alignment = 256;
out.swizzle = tail_swizzle(l.desc.swizzle);
if l.thick {
// A 3D tail mip is placed by position, not by offset.
out.slice_size = l.alignment / u64::from(l.block[2]);
out.tail_position = t.x | t.y << 11;
} else {
out.offset = u64::from(t.offset);
out.slice_size = slice;
}
out.size = out.slice_size * depth;
}
}
out
}
extern "system" fn add_ref(this: This) -> u32 {
computer(this).refs.fetch_add(1, Ordering::Relaxed) + 1
}
extern "system" fn release(this: This) -> u32 {
let left = computer(this).refs.fetch_sub(1, Ordering::AcqRel) - 1;
if left == 0 {
// SAFETY: made by `Box::into_raw` in `XGCreateTextureComputer`; the
// last reference is gone.
drop(unsafe { Box::from_raw(this) });
}
left
}
extern "system" fn layout(this: This, out: *mut LayoutOut) -> HRESULT {
if out.is_null() {
return E_INVALIDARG;
}
let c = computer(this);
// SAFETY: the title passes room for the layout; every field is plain
// data, so zeroes are a valid start.
let out = unsafe {
out.write_bytes(0, 1);
&mut *out
};
out.size = c.texture.size;
out.alignment = c.texture.alignment;
out.mips = c.mips;
out.planes = c.texture.planes.len() as u32;
out.dimension = c.desc.dimension;
// The library calls a depth plane "depth" only beside stencil or
// without mips.
let depth =
c.desc.flags & ALLOW_DEPTH_STENCIL != 0 && (c.texture.planes.len() > 1 || c.mips == 1);
for (plane, p) in out.plane.iter_mut().zip(&c.texture.planes) {
let l = &p.layout;
plane.usage = match (p.stencil, depth) {
(true, _) => 8,
(false, true) => 7,
(false, false) => 1,
};
plane.size = l.size;
plane.slice_size = l.slice_size;
plane.offset = p.offset;
plane.alignment = l.alignment;
plane.element_bytes = l.desc.element_bytes;
plane.standard_mips = l.first_tail_mip;
plane.tail_mips = c.mips - l.first_tail_mip;
for (i, mip) in plane.mips.iter_mut().take(l.mips.len()).enumerate() {
*mip = mip_out(&c.desc, l, i);
}
}
S_OK
}
/// The plane, its mip and array slice for a subresource index, and the
/// tiled bytes and the linear bytes the copy touches.
struct CopyArgs<'a> {
layout: &'a Layout,
mip: u32,
slice: u32,
tiled: usize,
linear: usize,
}
fn copy_args(
c: &Computer,
plane: u32,
subresource: u32,
row: u32,
depth: u32,
) -> Option<CopyArgs<'_>> {
let p = c.texture.planes.get(plane as usize)?;
let l = &p.layout;
let (mip, slice) = (subresource % c.mips, subresource / c.mips);
let m = l.mips.get(mip as usize)?;
let bytes = m.width as usize * l.desc.element_bytes as usize;
let depths = l.subresource_depth(mip) as usize;
let linear = (depths - 1) * depth as usize + (m.height as usize - 1) * row as usize + bytes;
Some(CopyArgs {
layout: l,
mip,
slice,
tiled: (p.offset + l.size) as usize,
linear,
})
}
fn result(r: Result<(), Error>) -> HRESULT {
match r {
Ok(()) => S_OK,
Err(Error::Unsupported) => E_NOTIMPL,
Err(_) => E_INVALIDARG,
}
}
/// `(tiled base, plane, subresource, linear, row pitch, depth pitch)`.
extern "system" fn copy_into(
this: This,
tiled: *mut u8,
plane: u32,
subresource: u32,
linear: *const u8,
row: u32,
depth: u32,
) -> HRESULT {
let c = computer(this);
let Some(a) = copy_args(c, plane, subresource, row, depth) else {
return E_INVALIDARG;
};
if tiled.is_null() || linear.is_null() {
return E_INVALIDARG;
}
let offset = c.texture.planes[plane as usize].offset as usize;
// SAFETY: the title's memory holds the whole texture and its rows.
let (tiled, linear) = unsafe {
(
std::slice::from_raw_parts_mut(tiled.add(offset), a.tiled - offset),
std::slice::from_raw_parts(linear, a.linear),
)
};
let r = a
.layout
.tile(tiled, a.mip, a.slice, linear, row as usize, depth as usize);
if r.is_err() {
tracing::warn!(?r, desc = ?c.desc, subresource, "copy into a texture failed");
}
result(r)
}
/// `(linear, plane, subresource, sample, tiled base, row pitch, depth
/// pitch)`.
#[allow(clippy::too_many_arguments)]
extern "system" fn copy_from(
this: This,
linear: *mut u8,
plane: u32,
subresource: u32,
_sample: u32,
tiled: *const u8,
row: u32,
depth: u32,
) -> HRESULT {
let c = computer(this);
let Some(a) = copy_args(c, plane, subresource, row, depth) else {
return E_INVALIDARG;
};
if tiled.is_null() || linear.is_null() {
return E_INVALIDARG;
}
let offset = c.texture.planes[plane as usize].offset as usize;
// SAFETY: the title's memory holds the whole texture and its rows.
let (tiled, linear) = unsafe {
(
std::slice::from_raw_parts(tiled.add(offset), a.tiled - offset),
std::slice::from_raw_parts_mut(linear, a.linear),
)
};
let r = a
.layout
.detile(tiled, a.mip, a.slice, linear, row as usize, depth as usize);
if r.is_err() {
tracing::warn!(?r, desc = ?c.desc, subresource, "copy out of a texture failed");
}
result(r)
}
#[repr(C)]
pub struct PackedMips {
pub standard: u8,
pub packed: u8,
pub tiles: u32,
pub start: u32,
}
#[repr(C)]
pub struct SubresourceTiling {
pub width: u32,
pub height: u16,
pub depth: u16,
pub start: u32,
}
const TILE: u64 = 64 << 10;
/// `(total tiles, packed mips, tile shape in texels, in: room / out:
/// count, first, subresource tilings)`, in 64 KiB tiles of plane 0, for 2D
/// 64 KiB modes only (others fail, as on the console). The mip tail is the
/// packed part, tile 0 of each slice; tilings list the standard mips of
/// every slice in turn. With a tail the console's library lists two slices
/// at most and zeroes all but the first; so do we (the title reads slice 0
/// only).
extern "system" fn tiling(
this: This,
tiles: *mut u32,
packed: *mut PackedMips,
shape: *mut [u32; 3],
count: *mut u32,
first: u32,
out: *mut SubresourceTiling,
) -> HRESULT {
let c = computer(this);
let l = &c.texture.planes[0].layout;
if l.alignment != TILE {
return E_FAIL;
}
if l.thick {
return E_NOTIMPL;
}
let standard = l.first_tail_mip;
let tail = standard < c.mips;
let tail_tiles = match standard {
0 => l.slice_size / TILE,
s if s < c.mips => l.mips[s as usize - 1].offset / TILE,
_ => 0,
};
let block = l.desc.block;
// SAFETY: each output is null or room for its value; `out` has room
// for `*count` entries.
unsafe {
if let Some(t) = tiles.as_mut() {
*t = (l.size / TILE) as u32;
}
if let Some(p) = packed.as_mut() {
*p = PackedMips {
standard: standard as u8,
packed: (c.mips - standard) as u8,
tiles: tail_tiles as u32,
start: 0,
};
}
if let Some(s) = shape.as_mut() {
*s = [l.block[0] * block, l.block[1] * block, l.block[2]];
}
if let Some(n) = count.as_mut() {
let slices = if tail { l.slices.min(2) } else { l.slices };
let wanted = (standard * slices).saturating_sub(first).min(*n);
for i in 0..wanted {
let (slice, mip) = ((first + i) / standard, (first + i) % standard);
let m = &l.mips[mip as usize];
let entry = if tail && slice > 0 {
SubresourceTiling {
width: 0,
height: 0,
depth: 0,
start: 0,
}
} else {
SubresourceTiling {
width: m.pitch / l.block[0],
height: (m.rows / l.block[1]) as u16,
depth: 1,
start: ((u64::from(slice) * l.slice_size + m.offset) / TILE) as u32,
}
};
out.add(i as usize).write(entry);
}
*n = wanted;
}
}
S_OK
}
/// Slot 0x30 `(plane, mip, x, y, z or slice, sample, bit position)`: an
/// element's byte offset from the texture's start. Grand Theft Auto VI reads
/// texels of a 128x4 `4KB_S` texture on the CPU through it (title+0x5151c90);
/// an error returned as an offset made it read wild memory. 0 if outside.
extern "system" fn element_offset(
this: This,
plane: u32,
mip: u32,
x: u64,
y: u32,
z: u32,
_sample: u32,
bit: *mut u32,
) -> u64 {
if !bit.is_null() {
// SAFETY: the caller passes room for the bit position or null.
unsafe { bit.write(0) };
}
let Some(p) = computer(this).texture.planes.get(plane as usize) else {
return 0;
};
let x = u32::try_from(x).unwrap_or(u32::MAX);
match p.layout.offset(mip, x, y, z) {
Ok(at) => p.offset + at,
Err(e) => {
tracing::warn!(?e, mip, x, y, z, "texel outside its texture");
0
}
}
}
/// Slots the title does not call: size, alignment, offsets, coordinates,
/// view descriptor, tiled-resource query.
extern "system" fn unused(this: This) -> HRESULT {
tracing::warn!(desc = ?computer(this).desc, "unimplemented texture computer method");
E_NOTIMPL
}
#[repr(C)]
struct Vtable([*const (); 13]);
// SAFETY: function addresses only.
unsafe impl Sync for Vtable {}
static VTABLE: Vtable = Vtable([
add_ref as *const (), // 0x00
release as *const (), // 0x08
layout as *const (), // 0x10
unused as *const (), // 0x18 size
unused as *const (), // 0x20 alignment
unused as *const (), // 0x28 mip offset
element_offset as *const (), // 0x30
unused as *const (), // 0x38 element coordinate
copy_into as *const (), // 0x40
copy_from as *const (), // 0x48
tiling as *const (), // 0x50
unused as *const (), // 0x58 view descriptor
unused as *const (), // 0x60 tiled resource?
]);
pub(crate) fn module() -> HleModule {
HleModule {
name: "xg",
dlls: &["xg_xs.dll"],
exports: vec![
hle_export!(XGCreateTextureComputer),
hle_export!(XGSuggestSwizzleMode),
],
}
}
#[cfg(test)]
mod tests {
use super::*;
fn desc(width: u64, height: u32, mips: u16, format: u32, layout: u32) -> ResourceDesc {
ResourceDesc {
dimension: 3,
alignment: 0,
width,
height,
depth_or_array: 1,
mips,
format,
samples: 1,
quality: 0,
layout,
flags: 0,
}
}
/// Method `index` of a computer, as the title calls it.
fn slot<T: Copy>(c: This, index: usize) -> T {
// SAFETY: the computer is live; T is the slot's function type.
unsafe { std::mem::transmute_copy(&(*c).vtable.0[index]) }
}
fn create(d: &ResourceDesc) -> This {
let mut c = std::ptr::null_mut();
assert_eq!(XGCreateTextureComputer(d, &mut c), S_OK);
c
}
/// Element offsets: linear rows of 1 KiB (128 elements), 0 outside.
#[test]
fn element_offsets_follow_the_layout() {
type Offset = extern "system" fn(This, u32, u32, u64, u32, u32, u32, *mut u32) -> u64;
let c = create(&desc(128, 4, 1, 11, 0x100));
let offset: Offset = slot(c, 6);
let mut bit = 7;
assert_eq!(offset(c, 0, 0, 3, 1, 0, 0, &mut bit), (128 + 3) * 8);
assert_eq!(bit, 0);
assert_eq!(offset(c, 0, 0, 128, 0, 0, 0, std::ptr::null_mut()), 0);
slot::<extern "system" fn(This) -> u32>(c, 1)(c);
}
#[test]
fn suggestions_follow_the_use() {
let mut out = 0;
let mut d = desc(256, 256, 1, 98, 0);
assert_eq!(XGSuggestSwizzleMode(&d, 0, &mut out), S_OK);
assert_eq!(out, 0x105);
d.flags = ALLOW_RENDER_TARGET;
XGSuggestSwizzleMode(&d, 0, &mut out);
assert_eq!(out, 0x11b);
d.flags = ALLOW_DEPTH_STENCIL;
XGSuggestSwizzleMode(&d, 0, &mut out);
assert_eq!(out, 0x118);
}
/// The title's calls: layout, then a copy in and out of each mip.
#[test]
fn layout_and_copies_through_the_object() {
// 256x256 BC7, full chain, 64 KiB display mode.
let c = create(&desc(256, 256, 0, 98, 0x10a));
// SAFETY: plain data, filled by the call.
let mut l: Box<LayoutOut> = Box::new(unsafe { std::mem::zeroed() });
let get: extern "system" fn(This, *mut LayoutOut) -> HRESULT = slot(c, 2);
assert_eq!(get(c, &mut *l), S_OK);
assert_eq!(
(l.size, l.alignment, l.mips, l.planes),
(131072, 65536, 9, 1)
);
let p = &l.plane[0];
assert_eq!((p.standard_mips, p.tail_mips, p.element_bytes), (1, 8, 16));
assert_eq!((p.mips[0].offset, p.mips[0].pitch_bytes), (65536, 1024));
assert_eq!((p.mips[1].offset, p.mips[1].in_tail), (32768, 1));
type Into = extern "system" fn(This, *mut u8, u32, u32, *const u8, u32, u32) -> HRESULT;
type From =
extern "system" fn(This, *mut u8, u32, u32, u32, *const u8, u32, u32) -> HRESULT;
let (into, from): (Into, From) = (slot(c, 8), slot(c, 9));
let mut tiled = vec![0u8; l.size as usize];
for mip in 0..9u32 {
let m = &p.mips[mip as usize];
let row = m.elements[0] * 16;
let rows: Vec<u8> = (0..row * m.elements[1]).map(|i| (i ^ mip) as u8).collect();
assert_eq!(
into(c, tiled.as_mut_ptr(), 0, mip, rows.as_ptr(), row, 0),
S_OK
);
let mut back = vec![0u8; rows.len()];
assert_eq!(
from(c, back.as_mut_ptr(), 0, mip, 0, tiled.as_ptr(), row, 0),
S_OK
);
assert_eq!(back, rows, "mip {mip}");
}
// 0x50: one tile for the tail, one for mip 0.
type Tiling = extern "system" fn(
This,
*mut u32,
*mut PackedMips,
*mut [u32; 3],
*mut u32,
u32,
*mut SubresourceTiling,
) -> HRESULT;
let tiling: Tiling = slot(c, 10);
let (mut tiles, mut shape, mut n) = (0, [0; 3], 4);
let mut packed = PackedMips {
standard: 0,
packed: 0,
tiles: 0,
start: 0,
};
let mut subs: Vec<SubresourceTiling> = (0..4)
.map(|_| SubresourceTiling {
width: 0,
height: 0,
depth: 0,
start: 0,
})
.collect();
assert_eq!(
tiling(
c,
&mut tiles,
&mut packed,
&mut shape,
&mut n,
0,
subs.as_mut_ptr()
),
S_OK
);
assert_eq!(
(tiles, packed.standard, packed.packed, packed.tiles),
(2, 1, 8, 1)
);
assert_eq!((shape, n, subs[0].start), ([256, 256, 1], 1, 1));
assert_eq!(release(c), 0);
// 4 KiB modes have no 64 KiB tiling.
let null = std::ptr::null_mut::<u8>();
let c = create(&desc(256, 256, 0, 98, 0x105));
assert_eq!(
tiling(
c,
&mut tiles,
null.cast(),
null.cast(),
null.cast(),
0,
null.cast()
),
E_FAIL
);
assert_eq!(release(c), 0);
}
#[test]
fn bad_descriptions_fail() {
let mut c = std::ptr::null_mut();
let bad = desc(256, 256, 1, 0, 0x10a);
assert_eq!(XGCreateTextureComputer(&bad, &mut c), E_INVALIDARG);
let bad = desc(256, 256, 1, 28, 0x103);
assert_eq!(XGCreateTextureComputer(&bad, &mut c), E_INVALIDARG);
assert!(module().exports.len() == 2);
}
}
+77 -8
View File
@@ -6,7 +6,7 @@
use std::ffi::{CStr, c_char, c_void};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, token,
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, token,
};
use crate::runtime;
@@ -62,12 +62,65 @@ extern "system" fn title_id(_: This, out: *mut u32) -> HRESULT {
put(out, runtime::title().id)
}
/// As documented: the title ends (suspended first, as on any end) and the
/// game starts again in a new process; this never returns. Grand Theft
/// Auto VI relaunches itself (its own path from `GetModuleFileNameA`) with
/// arguments from its configuration. The new `victory run` gets the same
/// options, the new executable, and the title's arguments after `--`
/// (the title reads the whole command line).
extern "system" fn launch_new_game(
_: This,
exe: *const c_char,
args: *const c_char,
_user: *const c_void,
) {
let (exe, args) = (text(exe).unwrap_or_default(), text(args).unwrap_or_default());
tracing::info!(exe, args, "XLaunchNewGame");
let current = runtime::main_image()
.and_then(runtime::image_path)
.unwrap_or_default();
let ours: Vec<_> = std::env::args_os().skip(1).collect();
let command = relaunch_args(ours, current.as_os_str(), &exe, &args);
super::lifecycle::end_title(
"XLaunchNewGame",
Box::new(move || super::lifecycle::relaunch(command)),
);
loop {
std::thread::park();
}
}
/// Our own arguments for the relaunch: the title's executable replaced by
/// `exe`, earlier title arguments dropped, `args` after `--`.
fn relaunch_args(
ours: Vec<std::ffi::OsString>,
current: &std::ffi::OsStr,
exe: &str,
args: &str,
) -> Vec<std::ffi::OsString> {
let mut out: Vec<_> = ours.into_iter().take_while(|a| a != "--").collect();
if !exe.is_empty()
&& let Some(slot) = out.iter_mut().find(|a| a.as_os_str() == current)
{
*slot = exe.into();
}
if !args.trim().is_empty() {
out.push("--".into());
out.extend(args.split_whitespace().map(Into::into));
}
out
}
/// 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];
/// serve: accessibility (0), app capture (1), async calls and providers
/// (2, 3), display (4), game (5), invites (6), game saves (7), game UI (8),
/// launcher (9), networking (10), packages (11), persistent local storage
/// (12), speech synthesis (13), store (14), system (15), task queues (16),
/// users (18), error reports (19), game events (20). Not threads (17) or
/// game streaming (21).
const AVAILABLE: [u32; 20] = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20,
];
extern "system" fn is_feature_available(_: This, feature: u32) -> bool {
AVAILABLE.contains(&feature)
@@ -110,7 +163,7 @@ static TITLE_VTABLE: Methods<5> = Methods([
add_ref as *const (),
add_ref as *const (),
title_id as *const (), // 0x18
missing::<4> as *const (), // 0x20 launch another title (returns nothing)
launch_new_game as *const (), // 0x20
]);
static FEATURES_VTABLE: Methods<4> = Methods([
@@ -140,12 +193,28 @@ mod tests {
use super::*;
use crate::modules::xgameruntime::method;
#[test]
fn a_relaunch_keeps_our_options() {
let ours: Vec<std::ffi::OsString> =
["run", "G:/game.exe", "--execute", "--console", "series-s", "--", "-old"]
.map(Into::into)
.into();
let current = std::ffi::OsStr::new("G:/game.exe");
let again = relaunch_args(ours.clone(), current, "G:/game.exe", " -config=x -y ");
let expected = ["run", "G:/game.exe", "--execute", "--console", "series-s", "--"];
assert_eq!(again[..6], expected.map(std::ffi::OsString::from));
assert_eq!(again[6..], ["-config=x", "-y"].map(std::ffi::OsString::from));
let other = relaunch_args(ours, current, "G:/other.exe", "");
assert_eq!(other.len(), 5);
assert_eq!(other[1], "G:/other.exe");
}
#[test]
fn served_areas_are_available_others_not() {
type Check = extern "system" fn(This, u32) -> bool;
let check = method::<Check>(&FEATURES_OBJECT, 0x18);
assert!(check(&FEATURES_OBJECT, 18), "users");
assert!(!check(&FEATURES_OBJECT, 14), "store");
assert!(!check(&FEATURES_OBJECT, 21), "game streaming");
type Register = extern "system" fn(
This,
+51 -6
View File
@@ -8,10 +8,13 @@
//! 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`).
//! whose slots we know. Implemented, as an offline retail console with one
//! signed-in user: task queues and async blocks (`xasync`), the user
//! (`xuser`), system information (`xsystem`), title id, feature checks,
//! invites and events (`xgame`), persistent local storage (`storage`), game
//! saves (`xgamesave`), networking (`xnetworking`), the package
//! (`xpackage`), the store (`xstore`), system dialogs (`xgameui`), speech
//! (`speech`), HDR, URIs, display deferrals and screenshots (`display`).
#![allow(non_snake_case)]
// Title code calls these through its import table, passing pointers the real
// API would trust.
@@ -21,7 +24,10 @@ 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 super::{
display, speech, storage, xasync, xgame, xgamesave, xgameui, xnetworking, xpackage, xstore,
xsystem, xuser,
};
use crate::{HleModule, hle_export};
pub type HRESULT = i32;
@@ -91,12 +97,19 @@ unsafe impl<const N: usize> Sync for Methods<N> {}
/// A (provider, interface id) pair a title may ask for, and our object.
pub type Interface = (Guid, Guid, &'static Object);
const AREAS: [&[Interface]; 5] = [
const AREAS: &[&[Interface]] = &[
xasync::INTERFACES,
xuser::INTERFACES,
xsystem::INTERFACES,
xgame::INTERFACES,
storage::INTERFACES,
xnetworking::INTERFACES,
xpackage::INTERFACES,
display::INTERFACES,
xgamesave::INTERFACES,
xstore::INTERFACES,
xgameui::INTERFACES,
speech::INTERFACES,
];
/// `AddRef` and `Release`.
@@ -146,6 +159,12 @@ pub fn put_string(text: &str, size: usize, buffer: *mut u8, used: *mut usize) ->
S_OK
}
/// The title's NUL-terminated string, if any.
pub fn text(s: *const c_char) -> Option<String> {
// SAFETY: the title passes a NUL-terminated string or null.
(!s.is_null()).then(|| unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned())
}
/// A new registration token for callbacks we never call (events nobody
/// raises offline).
pub fn token() -> u64 {
@@ -181,6 +200,19 @@ pub extern "system" fn InitializeApiImplEx(version: u64, build: u64, flags: u64)
S_OK
}
/// The stub prefers this one when present. It passes the same three values
/// and a pointer to the title's initialisation options, null unless the
/// title initialises with options (Grand Theft Auto VI does not).
pub extern "system" fn InitializeApiImplEx2(
version: u64,
build: u64,
flags: u64,
options: *const c_void,
) -> HRESULT {
tracing::info!(version, build, flags, ?options, "InitializeApiImplEx2");
S_OK
}
pub extern "system" fn UninitializeApiImpl() {
tracing::info!("UninitializeApiImpl");
}
@@ -198,6 +230,17 @@ pub extern "system" fn QueryApiImpl(
else {
return NOT_SUPPORTED;
};
#[cfg(feature = "diagnostics")]
if tracing::enabled!(tracing::Level::DEBUG) {
// Each runtime call site once: which title code uses which area, when.
static CALLS: Mutex<Vec<String>> = Mutex::new(Vec::new());
let from = super::kernel::callers();
let mut calls = CALLS.lock().unwrap_or_else(|e| e.into_inner());
if !calls.contains(&from) {
tracing::debug!(%provider, %iid, %from, "runtime call");
calls.push(from);
}
}
let found = AREAS
.iter()
.flat_map(|area| area.iter())
@@ -236,6 +279,7 @@ pub(crate) fn module() -> HleModule {
hle_export!(XGameRuntimeUninitialize),
hle_export!(InitializeApiImpl),
hle_export!(InitializeApiImplEx),
hle_export!(InitializeApiImplEx2),
hle_export!(UninitializeApiImpl),
hle_export!(QueryApiImpl),
hle_export!(XErrorReport),
@@ -257,6 +301,7 @@ mod tests {
for name in [
c"InitializeApiImpl",
c"InitializeApiImplEx",
c"InitializeApiImplEx2",
c"QueryApiImpl",
c"UninitializeApiImpl",
c"XErrorReport",
File diff suppressed because it is too large. Load diff
+321
View File
@@ -0,0 +1,321 @@
//! System dialogs a title opens (XGameUi). A profile card has nothing to
//! show and closes at once. Text entry opens a small host dialog (title,
//! description, default text, the length limit) on a thread of its own and
//! completes the call with what the user typed, or as cancelled (`E_ABORT`)
//! when the dialog is dismissed or cannot open.
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use super::xasync::{self, AsyncBlock, E_ABORT};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text,
};
pub const PROVIDER: Guid = Guid::new(
0xdfcd_4649,
0x4ff8,
0x4043,
[0xba, 0x07, 0x35, 0xd6, 0x07, 0xdf, 0x98, 0xb0],
);
/// As Grand Theft Auto VI (2026) asks for it; the slots it calls (0x38,
/// 0x40, 0x88-0x98) take the public API's arguments in the 2020 order.
pub const IID_2026: Guid = Guid::new(
0xeaf6_69df,
0x5542,
0x4590,
[0x99, 0xa3, 0x8d, 0xc0, 0x61, 0xf8, 0x37, 0xcc],
);
pub static OBJECT: Object = Object::new("game ui", &VTABLE);
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID_2026, &OBJECT)];
type This = *const Object;
static PROFILE: u8 = 0;
static TEXT: u8 = 0;
extern "system" fn profile_card_async(
_: This,
block: *mut AsyncBlock,
_user: *const c_void,
xuid: u64,
) -> HRESULT {
tracing::info!(xuid, "profile card: nothing to show");
xasync::finished(block, (&raw const PROFILE).cast(), S_OK)
}
extern "system" fn profile_card_result(_: This, block: *mut AsyncBlock) -> HRESULT {
let none = std::ptr::null_mut();
xasync::XAsyncGetResult(block, (&raw const PROFILE).cast(), 0, none, none.cast())
}
/// Grand Theft Auto VI treats `E_ABORT` as cancelled and goes on; any
/// other failure as an error.
extern "system" fn text_entry_async(
_: This,
block: *mut AsyncBlock,
title: *const c_char,
description: *const c_char,
default: *const c_char,
_scope: u32,
max_length: u32,
) -> HRESULT {
let [title, description, default] = [title, description, default].map(|t| text(t).unwrap_or_default());
tracing::info!(title, description, max_length, "text entry");
xasync::pending_with(block, (&raw const TEXT).cast(), move || {
match ask(&title, &description, &default, max_length) {
Some(typed) => {
tracing::info!(length = typed.chars().count(), "text entry: done");
let mut bytes = limit(&typed, max_length).into_bytes();
bytes.push(0);
Ok(bytes)
}
None => {
tracing::info!("text entry: cancelled");
Err(E_ABORT)
}
}
})
}
/// Bytes of the result, its NUL included.
extern "system" fn text_entry_size(_: This, block: *mut AsyncBlock, out: *mut u32) -> HRESULT {
let mut size = 0;
let hr = xasync::XAsyncGetResultSize(block, &mut size);
if hr < 0 {
return hr;
}
put(out, size as u32)
}
extern "system" fn text_entry_result(
_: This,
block: *mut AsyncBlock,
size: u32,
buffer: *mut c_char,
used: *mut u32,
) -> HRESULT {
let mut written = 0;
let identity = (&raw const TEXT).cast();
let hr = xasync::XAsyncGetResult(block, identity, size as usize, buffer.cast(), &mut written);
if hr < 0 || used.is_null() {
return hr;
}
put(used, written as u32)
}
/// At most `max` characters (0: no limit).
fn limit(typed: &str, max: u32) -> String {
match max {
0 => typed.to_owned(),
max => typed.chars().take(max as usize).collect(),
}
}
/// Asks the user in a modal host dialog; `None` if dismissed.
#[cfg(not(test))]
fn ask(title: &str, description: &str, default: &str, max: u32) -> Option<String> {
dialog::ask(title, description, default, max)
}
/// Tests answer for the user: "typed" for a title starting with "Type",
/// cancelled otherwise.
#[cfg(test)]
fn ask(title: &str, _: &str, default: &str, _: u32) -> Option<String> {
title.starts_with("Type").then(|| format!("{default}typed"))
}
mod dialog {
use windows_sys::Win32::Foundation::{HWND, LPARAM, WPARAM};
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
use windows_sys::Win32::UI::Input::KeyboardAndMouse::SetFocus;
use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, DLGTEMPLATE};
const EDIT: i32 = 100;
// Edit control messages (the controls headers).
const EM_SETSEL: u32 = 0xb1;
const EM_LIMITTEXT: u32 = 0xc5;
/// The dialog's state, behind its user data while it runs.
struct Entry {
max: u32,
typed: Option<String>,
}
/// The description, an edit box with the default text, OK and Cancel,
/// from an in-memory template (dialog units, the system font); Enter
/// accepts, Esc cancels.
#[allow(dead_code)] // unused in test builds
pub(super) fn ask(title: &str, description: &str, default: &str, max: u32) -> Option<String> {
let mut t: Vec<u16> = Vec::new();
fn dword(t: &mut Vec<u16>, v: u32) {
t.extend([v as u16, (v >> 16) as u16]);
}
fn text(t: &mut Vec<u16>, s: &str) {
t.extend(s.encode_utf16().filter(|&c| c != 0));
t.push(0);
}
let style = wm::WS_POPUP | wm::WS_CAPTION | wm::WS_SYSMENU;
let flags = (wm::DS_MODALFRAME | wm::DS_CENTER | wm::DS_SETFOREGROUND) as u32;
dword(&mut t, style | flags);
dword(&mut t, wm::WS_EX_TOPMOST);
t.extend([4, 0, 0, 240, 62, 0, 0]); // items, x, y, cx, cy, no menu, default class
text(&mut t, title);
let mut item = |style: u32, rect: [u16; 4], id: u16, class: u16, caption: &str| {
if t.len() % 2 == 1 {
t.push(0); // items start on a DWORD
}
dword(&mut t, wm::WS_CHILD | wm::WS_VISIBLE | style);
dword(&mut t, 0);
t.extend(rect);
t.extend([id, 0xffff, class]);
text(&mut t, caption);
t.push(0); // no creation data
};
let (button, edit, label) = (0x80, 0x81, 0x82);
let tab = wm::WS_TABSTOP;
item(0, [7, 7, 226, 10], 0xffff, label, description);
let edit_style = wm::WS_BORDER | tab | wm::ES_AUTOHSCROLL as u32;
item(edit_style, [7, 20, 226, 12], EDIT as u16, edit, default);
let ok = wm::BS_DEFPUSHBUTTON as u32 | tab;
item(ok, [129, 40, 50, 14], wm::IDOK as u16, button, "OK");
let cancel = wm::BS_PUSHBUTTON as u32 | tab;
item(cancel, [183, 40, 50, 14], wm::IDCANCEL as u16, button, "Cancel");
// The template must start on a DWORD.
let template: Vec<u32> = t
.chunks(2)
.map(|c| u32::from(c[0]) | u32::from(c.get(1).copied().unwrap_or(0)) << 16)
.collect();
let mut entry = Entry { max, typed: None };
// SAFETY: a complete template and our dialog procedure; `entry`
// outlives the modal dialog.
unsafe {
wm::DialogBoxIndirectParamW(
GetModuleHandleW(std::ptr::null()),
template.as_ptr().cast::<DLGTEMPLATE>(),
std::ptr::null_mut(),
Some(procedure),
(&raw mut entry) as LPARAM,
);
}
entry.typed
}
extern "system" fn procedure(dialog: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> isize {
// SAFETY: our dialog; its user data is the `Entry` from `ask`,
// stored at WM_INITDIALOG.
unsafe {
let edit = wm::GetDlgItem(dialog, EDIT);
match message {
wm::WM_INITDIALOG => {
wm::SetWindowLongPtrW(dialog, wm::GWLP_USERDATA, lparam);
let entry = &*(lparam as *const Entry);
wm::SendMessageW(edit, EM_LIMITTEXT, entry.max as WPARAM, 0);
wm::SendMessageW(edit, EM_SETSEL, 0, -1);
SetFocus(edit);
0 // focus set here
}
wm::WM_COMMAND => {
let entry = &mut *(wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA) as *mut Entry);
match (wparam & 0xffff) as i32 {
wm::IDOK => {
let mut buffer = vec![0u16; wm::GetWindowTextLengthW(edit) as usize + 1];
let n = wm::GetWindowTextW(edit, buffer.as_mut_ptr(), buffer.len() as i32);
entry.typed = Some(String::from_utf16_lossy(&buffer[..n.max(0) as usize]));
wm::EndDialog(dialog, 1);
}
wm::IDCANCEL => {
wm::EndDialog(dialog, 0);
}
_ => return 0,
}
1
}
_ => 0,
}
}
}
}
static VTABLE: Methods<20> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
missing::<3> as *const (), // 0x18 message dialog
missing::<4> as *const (), // 0x20
missing::<5> as *const (), // 0x28 send invite
missing::<6> as *const (), // 0x30
profile_card_async as *const (), // 0x38
profile_card_result as *const (), // 0x40
missing::<9> as *const (), // 0x48 achievements
missing::<10> as *const (), // 0x50
missing::<11> as *const (), // 0x58 player picker
missing::<12> as *const (), // 0x60
missing::<13> as *const (), // 0x68
missing::<14> as *const (), // 0x70 error dialog
missing::<15> as *const (), // 0x78
missing::<16> as *const (), // 0x80 notification position
text_entry_async as *const (), // 0x88
text_entry_size as *const (), // 0x90
text_entry_result as *const (), // 0x98
]);
#[cfg(test)]
mod tests {
use super::*;
use crate::modules::xgameruntime::method;
fn block() -> AsyncBlock {
AsyncBlock {
queue: std::ptr::null(),
context: std::ptr::null_mut(),
callback: None,
internal: [0; 4],
}
}
#[test]
fn dialogs_end_with_what_was_typed() {
let this: This = &OBJECT;
let mut b = block();
type Card = extern "system" fn(This, *mut AsyncBlock, *const c_void, u64) -> HRESULT;
type Done = extern "system" fn(This, *mut AsyncBlock) -> HRESULT;
assert_eq!(
method::<Card>(&OBJECT, 0x38)(this, &mut b, std::ptr::null(), 1),
S_OK
);
assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK);
assert_eq!(method::<Done>(&OBJECT, 0x40)(this, &mut b), S_OK);
type Entry = extern "system" fn(
This,
*mut AsyncBlock,
*const c_char,
*const c_char,
*const c_char,
u32,
u32,
) -> HRESULT;
type Size = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT;
type Result_ = extern "system" fn(This, *mut AsyncBlock, u32, *mut c_char, *mut u32) -> HRESULT;
let null = std::ptr::null();
let entry = method::<Entry>(&OBJECT, 0x88);
// Dismissed: cancelled.
let mut b = block();
assert_eq!(entry(this, &mut b, c"Name".as_ptr(), null, null, 0, 16), S_OK);
assert_eq!(xasync::XAsyncGetStatus(&mut b, true), E_ABORT);
let mut size = 0;
assert_eq!(method::<Size>(&OBJECT, 0x90)(this, &mut b, &mut size), E_ABORT);
// Typed: the text, cut to the limit, with its NUL.
let mut b = block();
let default = c"abc".as_ptr();
assert_eq!(entry(this, &mut b, c"Type".as_ptr(), null, default, 0, 6), S_OK);
assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK);
assert_eq!(method::<Size>(&OBJECT, 0x90)(this, &mut b, &mut size), S_OK);
assert_eq!(size, 7);
let mut out = [0 as c_char; 7];
let mut used = 0;
let result = method::<Result_>(&OBJECT, 0x98);
assert_eq!(result(this, &mut b, 7, out.as_mut_ptr(), &mut used), S_OK);
assert_eq!((text(out.as_ptr()).as_deref(), used), (Some("abctyp"), 7));
assert_eq!(limit("\u{e9}t\u{e9}s", 3), "\u{e9}t\u{e9}");
}
}
+634 -35
View File
@@ -8,14 +8,18 @@
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::alloc::{Layout, alloc, dealloc};
use std::collections::{BTreeMap, HashMap};
use std::ffi::c_void;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, LazyLock, Mutex, MutexGuard};
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE};
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,
CreateFileMappingW, MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER,
MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE,
MEM_RESERVE_PLACEHOLDER, MEMORY_BASIC_INFORMATION, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile3,
MemExtendedParameterAddressRequirements, PAGE_NOACCESS, PAGE_READWRITE, SEC_RESERVE,
UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQueryEx,
};
use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
@@ -24,11 +28,6 @@ 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);
@@ -39,6 +38,7 @@ static TRANSFERRED: AtomicUsize = AtomicUsize::new(0);
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;
const PAGES_64K: u32 = PAGES_2M | PAGES_64K_BIT;
/// 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.
@@ -47,16 +47,23 @@ const HOST_PROTECTION: u32 = 0x1ff;
const GRAPHICS: u64 = 3;
/// XMem flag bit of 32-bit graphics memory.
const ADDRESS_32BIT: u64 = 4;
/// The host's write watching (not in windows-sys' memory module).
const MEM_WRITE_WATCH: u32 = 0x20_0000;
/// 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 {
/// The addresses XMem `flags` allow, first and last: the low 4 GiB for
/// 32-bit memory; else from 4 GiB (kept for 32-bit requests, which the
/// title's big pools would otherwise crowd out) up to 46 down to 40 bits
/// from the field at bit 12, or 40 bits without one: the console keeps
/// title memory there, and its ray-tracing structures must be (Grand Theft
/// Auto VI's BVH builder refuses one above; the title asks for its GPU heap
/// with no field). Decision 0001.
fn address_range(flags: u64) -> (usize, usize) {
let bits = match (flags & ADDRESS_32BIT, flags >> 12 & 7) {
(0, 0) => return 0,
(0, 0) => 40,
(0, field) => 47 - field,
_ => 32,
_ => return (0, u32::MAX as usize),
};
(1 << bits) - 1
(1 << 32, (1 << bits) - 1)
}
pub extern "system" fn XMemVirtualAlloc(
@@ -66,42 +73,78 @@ pub extern "system" fn XMemVirtualAlloc(
flags: u64,
protect: u32,
) -> *mut c_void {
let (lowest, highest) = address_range(flags);
let mut requirements = MEM_ADDRESS_REQUIREMENTS {
HighestEndingAddress: highest_address(flags) as *mut c_void,
LowestStartingAddress: lowest as *mut c_void,
HighestEndingAddress: highest 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 {
let mut protect = match protect & HOST_PROTECTION {
0 => PAGE_NOACCESS,
p => p,
};
// A reservation of 64 KiB pages takes physical pages later
// (`XMemMapPhysicalPages`); on the host only a placeholder can.
// shortcut: committing part of such a reservation later would fail
// (Grand Theft Auto VI's 23 calls never do); replace that part of the
// placeholder then.
let placeholder = kind & PAGES_64K == PAGES_64K && kind & MEM_COMMIT == 0;
if placeholder {
if kind & MEM_REPLACE_PLACEHOLDER != 0 {
// Part of a placeholder the title split: it stays one.
return base;
}
protect = PAGE_NOACCESS;
}
let mut kind = kind & !(PAGES_2M | PAGES_64K_BIT);
if placeholder {
kind |= MEM_RESERVE | MEM_RESERVE_PLACEHOLDER;
}
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);
let constrained = base.is_null();
if constrained {
kind |= MEM_RESERVE;
// The GPU side copies only the pages the title wrote since its last
// copy (`victory_gpu`, decision 0007); placeholders cannot be
// watched (their physical-page views are copied whole).
if kind & MEM_RESERVE_PLACEHOLDER == 0 {
kind |= MEM_WRITE_WATCH;
}
}
// SAFETY: the title's own arguments, cleaned of console bits; the
// parameter points at `requirements`, which outlives the call.
unsafe {
let at = unsafe {
VirtualAlloc2(
GetCurrentProcess(),
base,
size,
kind,
protect,
if constrained { &mut parameter } else { std::ptr::null_mut() },
if constrained {
&mut parameter
} else {
std::ptr::null_mut()
},
constrained.into(),
)
};
if base.is_null() {
tracing::debug!(
size,
kind = format_args!("{kind:#x}"),
flags = format_args!("{flags:#x}"),
at = format_args!("{at:p}"),
"XMemVirtualAlloc"
);
}
at
}
/// `MEMORY_BASIC_INFORMATION` (the console's first 0x30 bytes are the
@@ -115,8 +158,9 @@ pub struct BasicInformation {
}
// 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.
// all of it is GPU-reachable here (Grand Theft Auto VI's BVH builder, the
// only caller, wants graphics memory); 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,
@@ -130,7 +174,11 @@ pub extern "system" fn XMemVirtualQuery(
return 0;
}
let info = &mut *out;
info.flags = if info.host.State == MEM_COMMIT { GRAPHICS } else { 0 };
info.flags = if info.host.State == MEM_COMMIT {
GRAPHICS
} else {
0
};
info.tag_code = 0;
info.tag = [0; 4];
}
@@ -151,10 +199,66 @@ fn layout(size: usize, attributes: u64) -> Option<Layout> {
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.
type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void;
type FreeRoutine = extern "system" fn(*mut c_void, u64);
/// The allocation and free routines the title's exe exports as
/// `__XMemAllocationHooks__` (Grand Theft Auto VI does): `XMemAlloc` and
/// `XMemFree` call them, for the title's own calls and its middleware's;
/// the `…Default` exports do not.
fn hooks() -> [usize; 2] {
static AT: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
let at = match AT.get() {
Some(&at) => at,
// Looked up once the title is mapped, which is before it runs.
None => match crate::runtime::main_image() {
Some(base) => *AT.get_or_init(|| {
use windows_sys::Win32::System::LibraryLoader::GetProcAddress;
// SAFETY: a mapped image and a NUL-terminated name.
let at = unsafe {
GetProcAddress(base as _, c"__XMemAllocationHooks__".as_ptr().cast())
}
.map_or(0, |f| f as usize);
tracing::info!(found = at != 0, "xmem allocation hooks");
at
}),
None => 0,
},
};
if at == 0 {
return [0; 2];
}
// SAFETY: the export is two routine pointers.
unsafe { (at as *const [usize; 2]).read() }
}
/// The title's general allocator, for middleware too: its hook if it has
/// one, else [`XMemAllocDefault`].
pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void {
match hooks()[0] {
0 => XMemAllocDefault(size, attributes),
hook => {
// SAFETY: the title's own routine of this type.
let alloc: AllocRoutine = unsafe { std::mem::transmute(hook) };
alloc(size, attributes)
}
}
}
/// See [`XMemAlloc`].
pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) {
match hooks()[1] {
0 => XMemFreeDefault(address, attributes),
hook => {
// SAFETY: the title's own routine of this type.
let free: FreeRoutine = unsafe { std::mem::transmute(hook) };
free(address, attributes)
}
}
}
/// The system allocator behind [`XMemAlloc`].
pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_void {
if attributes & ALLOC_32BIT != 0 {
return XMemVirtualAlloc(
std::ptr::null_mut(),
@@ -167,6 +271,10 @@ pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void {
let Some(layout) = layout(size, attributes) else {
return std::ptr::null_mut();
};
// shortcut: the host heap's addresses lie above 2^40, unlike the
// console's; nothing seen builds ray-tracing structures in this memory
// (Grand Theft Auto VI uses its GPU heap). Sub-allocate from a
// reservation below 2^40 if one does.
// SAFETY: the layout has a non-zero size.
let block = unsafe { alloc(layout) };
if block.is_null() {
@@ -183,8 +291,8 @@ pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void {
}
}
/// Frees what [`XMemAlloc`] returned, given the same attributes.
pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) {
/// Frees what [`XMemAllocDefault`] returned, given the same attributes.
pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) {
if address.is_null() {
return;
}
@@ -204,6 +312,383 @@ pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) {
}
}
/// A retail console has no tools memory.
pub extern "system" fn XMemIsToolsMemAvailable() -> BOOL {
0
}
// Physical pages: on the console, 64 KiB frames a title maps into its own
// reservations, at more than one address if it likes. Here each allocation
// is a pagefile-backed section, its pages are 64 KiB slices of it, and a
// mapping is a view of consecutive slices in place of a host placeholder.
const PAGE: usize = 64 << 10;
struct Section(HANDLE);
// SAFETY: a section handle may be used from any thread.
unsafe impl Send for Section {}
// SAFETY: as above.
unsafe impl Sync for Section {}
impl Drop for Section {
fn drop(&mut self) {
// SAFETY: our handle; views keep the section alive on their own.
unsafe { CloseHandle(self.0) };
}
}
/// Where a page lives, or what a view starts with: a section and a page
/// index in it.
#[derive(Clone)]
struct Slice {
section: Arc<Section>,
index: usize,
}
#[derive(Default)]
struct Physical {
next_page: usize,
pages: HashMap<usize, Slice>,
/// Mapped views by address: their length and what they show.
views: BTreeMap<usize, (usize, Slice)>,
}
static PHYSICAL: LazyLock<Mutex<Physical>> = LazyLock::new(|| {
Mutex::new(Physical {
// Page numbers are opaque to titles; 0 stays unused.
next_page: 0x10_0000,
..Default::default()
})
});
fn physical() -> MutexGuard<'static, Physical> {
PHYSICAL.lock().unwrap_or_else(|e| e.into_inner())
}
/// `count` is in and out (pages wanted, pages given); all or nothing here.
pub extern "system" fn XMemAllocatePhysicalPages(
flags: u64,
count: *mut usize,
pages: *mut usize,
) -> BOOL {
if count.is_null() || pages.is_null() {
return 0;
}
// SAFETY: checked non-null.
let n = unsafe { *count };
let Some(size) = n.checked_mul(PAGE).filter(|&s| s > 0) else {
return 0;
};
// A pagefile-backed section of `size` bytes, its pages committed when
// first mapped or written (`commit`): Grand Theft Auto VI asks for 6.1
// GiB at once, which a busy host often cannot commit (error 1450).
// SAFETY: plain section creation.
let handle = unsafe {
CreateFileMappingW(
INVALID_HANDLE_VALUE,
std::ptr::null(),
PAGE_READWRITE | SEC_RESERVE,
(size as u64 >> 32) as u32,
size as u32,
std::ptr::null(),
)
};
if handle.is_null() {
let error = std::io::Error::last_os_error();
tracing::warn!(n, %error, "XMemAllocatePhysicalPages failed");
// SAFETY: checked non-null.
unsafe { count.write(0) };
return 0;
}
tracing::debug!(
n,
flags = format_args!("{flags:#x}"),
"XMemAllocatePhysicalPages"
);
let section = Arc::new(Section(handle));
let mut physical = physical();
let first = physical.next_page;
physical.next_page += n * FRAMES;
for index in 0..n {
let slice = Slice {
section: section.clone(),
index,
};
let number = first + index * FRAMES;
physical.pages.insert(number, slice);
// SAFETY: the title passes room for `n` page numbers.
unsafe { pages.add(index).write(number) };
}
1
}
/// Page numbers count 4 KiB frames, so a 64 KiB page's is a multiple of
/// 16: Grand Theft Auto VI keeps them as 21-bit `number >> 4` and rebuilds
/// them with `<< 4` (128 GiB of pages at most).
const FRAMES: usize = PAGE >> 12;
/// Pages still mapped stay readable through their views until unmapped.
pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> BOOL {
if pages.is_null() {
return 0;
}
let mut physical = physical();
for i in 0..n {
// SAFETY: the title passes `n` page numbers.
physical.pages.remove(&unsafe { *pages.add(i) });
}
1
}
/// Copies `data` into physical pages, from `offset` bytes into the first,
/// whether or not they are mapped anywhere (DirectStorage destinations).
/// False if a page is unknown or the host fails.
pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> bool {
use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile};
let mut done = 0;
while done < data.len() {
let (page, within) = ((offset + done) / PAGE, (offset + done) % PAGE);
let Some(slice) = pages
.get(page)
.and_then(|p| physical().pages.get(p).cloned())
else {
return false;
};
let at = (slice.index * PAGE) as u64;
// SAFETY: one page of a section we own, mapped for the copy only.
let view = unsafe {
MapViewOfFile(
slice.section.0,
FILE_MAP_WRITE,
(at >> 32) as u32,
at as u32,
PAGE,
)
};
if view.Value.is_null() {
return false;
}
if !commit(view.Value as usize, PAGE) {
// SAFETY: our view.
unsafe { UnmapViewOfFile(view) };
return false;
}
let n = (PAGE - within).min(data.len() - done);
// SAFETY: the view holds `PAGE` bytes; `within + n <= PAGE`.
unsafe {
view.Value
.cast::<u8>()
.add(within)
.copy_from_nonoverlapping(data[done..].as_ptr(), n);
UnmapViewOfFile(view);
}
done += n;
}
true
}
/// Maps `n` pages at `address`, in place of what is mapped there; null
/// `pages` unmaps. Returns `address`, or null if a page or the host fails.
pub extern "system" fn XMemMapPhysicalPages(
address: *mut c_void,
n: usize,
pages: *const usize,
) -> *mut c_void {
let base = address as usize;
let mut physical = physical();
unmap(&mut physical, base, n * PAGE);
if pages.is_null() {
return address;
}
// SAFETY: the title passes `n` page numbers.
let pages = unsafe { std::slice::from_raw_parts(pages, n) };
let mut i = 0;
while i < n {
let Some(first) = physical.pages.get(&pages[i]).cloned() else {
tracing::warn!(page = pages[i], "XMemMapPhysicalPages: unknown page");
return std::ptr::null_mut();
};
// One view per run of consecutive slices of one section.
let run = 1 + pages[i + 1..]
.iter()
.zip(1..)
.take_while(|&(page, k)| {
physical.pages.get(page).is_some_and(|s| {
Arc::ptr_eq(&s.section, &first.section) && s.index == first.index + k
})
})
.count();
if !map(&mut physical, base + i * PAGE, run * PAGE, first) {
return std::ptr::null_mut();
}
i += run;
}
address
}
/// One page at each address; null `pages`, or a page number 0, unmaps
/// (Grand Theft Auto VI passes 0 for addresses to clear).
pub extern "system" fn XMemMapPhysicalPagesScatter(
addresses: *const *mut c_void,
n: usize,
pages: *const usize,
) -> BOOL {
if addresses.is_null() {
return 0;
}
for i in 0..n {
// SAFETY: the title passes `n` addresses and, unless null, `n` pages.
let (address, page) = unsafe {
(
*addresses.add(i),
if pages.is_null() || *pages.add(i) == 0 {
std::ptr::null()
} else {
pages.add(i)
},
)
};
if XMemMapPhysicalPages(address, 1, page).is_null() {
return 0;
}
}
1
}
/// Maps the physical pages shown at `[from, from + len)` at `to` as well,
/// in place of what `to` shows; `from` 0 unmaps. The GPU's page-mapping
/// copies (`victory_gpu`, queue `CopyPageMappingsBatchX`): Grand Theft Auto
/// VI maps pages into a pool view, then has the GPU map them into its tiled
/// heap. Page by page; false if a source page is not mapped physical memory.
pub fn map_alias(to: u64, from: u64, len: u64) -> bool {
let (to, from, len) = (to as usize, from as usize, len as usize);
let mut physical = physical();
unmap(&mut physical, to, len);
for k in (0..len).step_by(PAGE) {
if from == 0 {
break;
}
let at = from + k;
let Some(slice) = physical
.views
.range(..=at)
.next_back()
.filter(|(base, (size, _))| at < *base + size)
.map(|(base, (_, s))| Slice {
index: s.index + (at - base) / PAGE,
section: s.section.clone(),
})
else {
return false;
};
if !map(&mut physical, to + k, PAGE, slice) {
return false;
}
}
true
}
/// Maps `slice` and the slices after it over `[base, base + len)`, which
/// must lie in one placeholder.
fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
// SAFETY: splits the placeholder around the range (failing harmlessly
// when the range is the whole placeholder), then maps the section
// there; both act only on placeholders.
let view = unsafe {
VirtualFree(
base as *mut c_void,
len,
MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
);
MapViewOfFile3(
slice.section.0,
GetCurrentProcess(),
base as *const c_void,
(slice.index * PAGE) as u64,
len,
MEM_REPLACE_PLACEHOLDER,
PAGE_READWRITE,
std::ptr::null_mut(),
0,
)
};
if view.Value as usize != base {
tracing::warn!(
address = format_args!("{base:#x}"),
len,
error = %std::io::Error::last_os_error(),
"mapping physical pages failed (not a placeholder?)"
);
return false;
}
if !commit(base, len) {
// SAFETY: the view just mapped, back to a placeholder.
unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) };
return false;
}
// New contents, read-write: the GPU side's copies no longer guard it.
victory_gpu::title_memory_remapped(base, len);
physical.views.insert(base, (len, slice));
true
}
/// Commits the section pages a view shows (once per page, whichever view).
fn commit(base: usize, len: usize) -> bool {
// SAFETY: `[base, base + len)` is a view of a reserved section.
let done =
!unsafe { VirtualAlloc(base as *const c_void, len, MEM_COMMIT, PAGE_READWRITE) }.is_null();
if !done {
tracing::warn!(
len,
error = %std::io::Error::last_os_error(),
"committing physical pages failed"
);
}
done
}
/// Returns `[base, base + len)` to placeholders; views reaching past it
/// are mapped again outside it.
fn unmap(physical: &mut Physical, base: usize, len: usize) {
let end = base + len;
// Views do not overlap: the one holding `base`, then those starting
// inside (the GPU's page mappings make one view per page).
let first = physical
.views
.range(..=base)
.next_back()
.filter(|(at, (size, _))| *at + size > base)
.map(|(at, _)| *at);
let hit: Vec<usize> = first
.into_iter()
.chain(physical.views.range(base + 1..end).map(|(at, _)| *at))
.collect();
for at in hit {
let Some((size, slice)) = physical.views.remove(&at) else {
continue;
};
victory_gpu::title_memory_remapped(at, size);
// SAFETY: a view we mapped; it becomes a placeholder again.
unsafe {
UnmapViewOfFile2(
GetCurrentProcess(),
MEMORY_MAPPED_VIEW_ADDRESS {
Value: at as *mut c_void,
},
MEM_PRESERVE_PLACEHOLDER,
)
};
if at < base {
map(physical, at, base - at, slice.clone());
}
if at + size > end {
let index = slice.index + (end - at) / PAGE;
map(physical, end, at + size - end, Slice { index, ..slice });
}
}
}
/// The oldest layout we know; newer titles pass other flag values (Minecraft
/// 0x20000001) and read the same leading fields.
#[repr(C)]
@@ -238,10 +723,11 @@ pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut Workin
};
// SAFETY: our own process and a sized structure.
unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) };
let (gpu_optimal, standard) = victory_gpu::console::current().title_memory();
let stats = WorkingSet {
title_limit: GPU_OPTIMAL_LIMIT + STANDARD_LIMIT - TRANSFERRED.load(Ordering::Relaxed),
title_limit: gpu_optimal + standard - TRANSFERRED.load(Ordering::Relaxed),
title_used: counters.PagefileUsage,
gpu_optimal_limit: GPU_OPTIMAL_LIMIT,
gpu_optimal_limit: gpu_optimal,
..Default::default()
};
// SAFETY: checked non-null; the title passes room for the structure.
@@ -260,10 +746,11 @@ pub extern "system" fn XMemTransferMemory(kind: u32, size: usize) -> BOOL {
let Some(size) = size.checked_next_multiple_of(2 * MIB) else {
return 0;
};
let standard = victory_gpu::console::current().title_memory().1;
let moved = kind == TITLE_TO_SYSTEM
&& TRANSFERRED
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |t| {
t.checked_add(size).filter(|&t| t <= STANDARD_LIMIT)
t.checked_add(size).filter(|&t| t <= standard)
})
.is_ok();
moved.into()
@@ -276,6 +763,13 @@ pub(crate) fn module() -> HleModule {
exports: vec![
hle_export!(XMemAlloc),
hle_export!(XMemFree),
hle_export!(XMemAllocDefault),
hle_export!(XMemFreeDefault),
hle_export!(XMemIsToolsMemAvailable),
hle_export!(XMemAllocatePhysicalPages),
hle_export!(XMemFreePhysicalPages),
hle_export!(XMemMapPhysicalPages),
hle_export!(XMemMapPhysicalPagesScatter),
hle_export!(XMemVirtualAlloc),
hle_export!(XMemVirtualQuery),
hle_export!(XMemGetWorkingSetStatistics),
@@ -330,9 +824,36 @@ mod tests {
assert_eq!(info.host.State, MEM_COMMIT);
assert_eq!(info.host.Protect, PAGE_READWRITE);
assert_eq!(info.flags & GRAPHICS, GRAPHICS);
// Write-watched, for the GPU side's copies.
let (mut found, mut count, mut granularity) = ([0usize; 4], 4, 0);
// SAFETY: room for `count` addresses.
let watched = unsafe {
windows_sys::Win32::System::Memory::GetWriteWatch(
0,
p,
4 * MIB,
found.as_mut_ptr().cast(),
&mut count,
&mut granularity,
)
};
assert_eq!(watched, 0);
// SAFETY: our own reservation.
assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0);
assert_eq!(query(p).flags, 0);
// No address field: above the 32-bit range and below 2^40, where
// the console keeps it.
let p = XMemVirtualAlloc(
std::ptr::null_mut(),
16 << 30,
MEM_RESERVE,
GRAPHICS,
PAGE_NOACCESS,
);
assert!(!p.is_null() && (p as usize) >= 1 << 32, "{p:p}");
assert!((p as usize) + (16 << 30) <= 1 << 40, "{p:p}");
// SAFETY: our own reservation.
assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0);
}
#[test]
@@ -342,7 +863,8 @@ mod tests {
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 standard = victory_gpu::console::current().title_memory().1;
assert_eq!(XMemTransferMemory(0, standard), 0, "over budget");
let mut after = WorkingSet::default();
XMemGetWorkingSetStatistics(0x2000_0001, &mut after);
assert_eq!(before.title_limit - after.title_limit, 128 * MIB);
@@ -354,4 +876,81 @@ mod tests {
assert_eq!(size_of::<BasicInformation>(), 0x40);
assert_eq!(std::mem::offset_of!(WorkingSet, gpu_optimal_limit), 0x28);
}
#[test]
fn physical_pages_map_alias_and_unmap() {
let mut pages = [0usize; 3];
let mut n = 3;
assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1);
assert_eq!(n, 3);
// Packed into 21 bits as `number >> 4`, as the title keeps them.
for p in pages {
assert_eq!((p >> 4 & 0x1f_ffff) << 4, p);
}
// Reservations of 64 KiB pages, as titles make them for mapping.
let reserve = || {
XMemVirtualAlloc(
std::ptr::null_mut(),
3 * PAGE,
MEM_RESERVE | PAGES_64K,
0,
PAGE_READWRITE,
)
};
let (a, b) = (reserve(), reserve());
assert!(!a.is_null() && !b.is_null());
let at = |p: *mut c_void, page: usize| p.wrapping_byte_add(page * PAGE);
assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a);
// The same page at a second address shows the same bytes.
assert_eq!(
XMemMapPhysicalPages(at(b, 1), 1, pages[2..].as_ptr()),
at(b, 1)
);
// SAFETY: both pages are mapped read-write.
unsafe {
at(a, 2).cast::<u8>().write(7);
assert_eq!(at(b, 1).cast::<u8>().read(), 7);
a.cast::<u8>().write(1);
}
// Writes into pages (DirectStorage's) show through their views.
assert!(write_physical(&pages[2..], 1, &[9]));
// SAFETY: mapped read-write.
assert_eq!(unsafe { at(b, 1).cast::<u8>().add(1).read() }, 9);
// Unmapping the middle page keeps its neighbours.
assert_eq!(
XMemMapPhysicalPages(at(a, 1), 1, std::ptr::null()),
at(a, 1)
);
assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE);
assert_eq!(query(a).host.State, MEM_COMMIT);
assert_eq!(query(at(a, 2)).host.State, MEM_COMMIT);
// SAFETY: still mapped.
assert_eq!(unsafe { at(a, 2).cast::<u8>().read() }, 7);
// A scattered page lands in the hole.
let addresses = [at(a, 1)];
assert_eq!(
XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, pages.as_ptr()),
1
);
// SAFETY: page 0 is now mapped at both `a` and `a + PAGE`.
assert_eq!(unsafe { at(a, 1).cast::<u8>().read() }, 1);
// Page number 0 unmaps.
assert_eq!(
XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, [0usize].as_ptr()),
1
);
assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE);
// The GPU's page-mapping copy: what `a + 2 pages` shows, at `b`.
assert!(map_alias(b as u64, at(a, 2) as u64, PAGE as u64));
// SAFETY: mapped read-write.
assert_eq!(unsafe { b.cast::<u8>().read() }, 7);
assert!(map_alias(b as u64, 0, PAGE as u64));
assert_eq!(query(b).host.State, MEM_RESERVE);
assert!(!map_alias(b as u64, at(a, 1) as u64, PAGE as u64));
assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1);
assert_eq!(XMemIsToolsMemAvailable(), 0);
}
}
@@ -0,0 +1,210 @@
//! XNetworking as an offline console answers it: the network stack is up
//! (titles wait for that before anything else) but reaches nothing, the
//! connectivity hint never changes, and the title's security allow list,
//! which comes from the service, cannot be fetched.
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use super::xasync::{self, AsyncBlock};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, add_ref, missing, put, text, token,
};
pub const PROVIDER: Guid = Guid::new(
0x37e5_6907,
0x2f10,
0x41e8,
[0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a],
);
/// As Grand Theft Auto VI (2026) asks for it; the slots it calls (0x18-0x88)
/// take the same arguments as under the provider's own id (older titles).
pub const IID_2026: Guid = Guid::new(
0xbf23_46b2,
0x39af,
0x4658,
[0xb5, 0xea, 0x44, 0x71, 0x3c, 0x7e, 0x83, 0xb3],
);
pub static OBJECT: Object = Object::new("networking", &VTABLE);
pub const INTERFACES: &[Interface] =
&[(PROVIDER, PROVIDER, &OBJECT), (PROVIDER, IID_2026, &OBJECT)];
/// `HRESULT_FROM_WIN32(ERROR_NETWORK_UNREACHABLE)`: what needs the service.
pub const UNREACHABLE: HRESULT = 0x8007_04CF_u32 as i32;
/// The documented default for the preferred local UDP multiplayer port.
const UDP_PORT: u16 = 3074;
/// The connectivity hint: level, cost, interface type, then four flags.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConnectivityHint {
pub level: u32,
pub cost: u32,
pub interface_type: u32,
pub initialized: bool,
pub approaching_data_limit: bool,
pub over_data_limit: bool,
pub roaming: bool,
}
/// Initialized, no connectivity (level 1), cost unknown (0).
const OFFLINE: ConnectivityHint = ConnectivityHint {
level: 1,
cost: 0,
interface_type: 0,
initialized: true,
approaching_data_limit: false,
over_data_limit: false,
roaming: false,
};
type This = *const Object;
extern "system" fn udp_port(_: This, out: *mut u16) -> HRESULT {
put(out, UDP_PORT)
}
/// Tells our port queries apart from other calls on the same block.
static PORT: u8 = 0;
extern "system" fn udp_port_async(_: This, block: *mut AsyncBlock) -> HRESULT {
xasync::finished_with(block, (&raw const PORT).cast(), Ok(xasync::bytes(UDP_PORT)))
}
extern "system" fn udp_port_result(_: This, block: *mut AsyncBlock, out: *mut u16) -> HRESULT {
xasync::result(block, (&raw const PORT).cast(), out)
}
static SECURITY: u8 = 0;
/// The allow list comes from the service: unreachable offline.
extern "system" fn security_info_async(
_: This,
url: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
tracing::debug!(
url = text(url).unwrap_or_default(),
"security information: offline"
);
xasync::finished(block, (&raw const SECURITY).cast(), UNREACHABLE)
}
extern "system" fn security_info_size(_: This, block: *mut AsyncBlock, out: *mut usize) -> HRESULT {
xasync::XAsyncGetResultSize(block, out)
}
extern "system" fn security_info_result(
_: This,
block: *mut AsyncBlock,
size: usize,
used: *mut usize,
buffer: *mut u8,
_info: *mut *const c_void,
) -> HRESULT {
xasync::XAsyncGetResult(
block,
(&raw const SECURITY).cast(),
size,
buffer.cast(),
used,
)
}
/// No security information can exist offline, so no certificate passes.
extern "system" fn verify_certificate(
_: This,
_request: *mut c_void,
_info: *const c_void,
) -> HRESULT {
UNREACHABLE
}
extern "system" fn connectivity_hint(_: This, out: *mut ConnectivityHint) -> HRESULT {
put(out, OFFLINE)
}
/// The hint never changes 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
}
static VTABLE: Methods<18> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
udp_port as *const (), // 0x18
udp_port_async as *const (), // 0x20
udp_port_result as *const (), // 0x28
missing::<6> as *const (), // 0x30 port changed
missing::<7> as *const (), // 0x38
security_info_async as *const (), // 0x40
security_info_size as *const (), // 0x48
security_info_result as *const (), // 0x50
missing::<11> as *const (), // 0x58 the same for UTF-16 URLs
missing::<12> as *const (), // 0x60
missing::<13> as *const (), // 0x68
verify_certificate as *const (), // 0x70
connectivity_hint as *const (), // 0x78
register as *const (), // 0x80 hint changed (never)
unregister as *const (), // 0x88
]);
#[cfg(test)]
mod tests {
use super::*;
use crate::modules::xgameruntime::{S_OK, method};
fn block() -> AsyncBlock {
AsyncBlock {
queue: std::ptr::null(),
context: std::ptr::null_mut(),
callback: None,
internal: [0; 4],
}
}
#[test]
fn offline_but_initialized() {
let this: This = &OBJECT;
type Hint = extern "system" fn(This, *mut ConnectivityHint) -> HRESULT;
let mut hint = OFFLINE;
hint.initialized = false;
assert_eq!(method::<Hint>(&OBJECT, 0x78)(this, &mut hint), S_OK);
assert!(hint.initialized && hint.level == 1);
assert_eq!(size_of::<ConnectivityHint>(), 16);
type Begin = extern "system" fn(This, *mut AsyncBlock) -> HRESULT;
type Port = extern "system" fn(This, *mut AsyncBlock, *mut u16) -> HRESULT;
let mut b = block();
assert_eq!(method::<Begin>(&OBJECT, 0x20)(this, &mut b), S_OK);
assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK);
let mut port = 0;
assert_eq!(method::<Port>(&OBJECT, 0x28)(this, &mut b, &mut port), S_OK);
assert_eq!(port, 3074);
type Url = extern "system" fn(This, *const c_char, *mut AsyncBlock) -> HRESULT;
type Size = extern "system" fn(This, *mut AsyncBlock, *mut usize) -> HRESULT;
let mut b = block();
let url = c"https://example.invalid/";
assert_eq!(
method::<Url>(&OBJECT, 0x40)(this, url.as_ptr(), &mut b),
S_OK
);
assert_eq!(xasync::XAsyncGetStatus(&mut b, true), UNREACHABLE);
let mut size = 0;
assert_eq!(
method::<Size>(&OBJECT, 0x48)(this, &mut b, &mut size),
UNREACHABLE
);
}
}
+371
View File
@@ -0,0 +1,371 @@
//! XPackage: the title's own installation, complete and launchable, with
//! every chunk ready; no other package (content, add-ons) is installed.
//! The package is the folder of the title's executable (`G:` to the title).
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use std::path::Path;
use std::sync::OnceLock;
use super::xasync::{self, AsyncBlock};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text, token,
};
use crate::runtime;
pub const PROVIDER: Guid = Guid::new(
0xaf40_6016,
0xe850,
0x4aa8,
[0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e],
);
/// As Grand Theft Auto VI (2026) asks for it. Its slots up to 0xd0 take the
/// arguments the public API lists in the same order; 0x110 uninstalls a
/// package, 0x128/0x130 mount one with UI, 0x138 enumerates packages.
pub const IID_2026: Guid = Guid::new(
0x0b9d_556e,
0xab70,
0x43f4,
[0xba, 0xa0, 0x99, 0x99, 0xac, 0x4c, 0xb0, 0x40],
);
pub static OBJECT: Object = Object::new("package", &VTABLE);
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID_2026, &OBJECT)];
/// The documented "could not resolve an identifier for the package".
pub const NO_PACKAGE: HRESULT = 0x8924_5208_u32 as i32;
/// Our installation's identifier: the title id in hex (titles keep it in 33
/// bytes and hand it back to us).
pub fn identifier() -> String {
format!("{:08X}", runtime::title().id)
}
fn is_ours(id: *const c_char) -> bool {
text(id).is_some_and(|id| id == identifier())
}
/// Bytes in the package folder, counted once.
fn package_bytes() -> u64 {
fn size(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() => size(&e.path()),
Ok(m) => m.len(),
Err(_) => 0,
})
.sum()
}
static BYTES: OnceLock<u64> = OnceLock::new();
*BYTES.get_or_init(|| {
let exe = runtime::main_image().and_then(runtime::image_path);
exe.as_deref().and_then(Path::parent).map_or(0, size)
})
}
type This = *const Object;
extern "system" fn current_identifier(_: This, size: usize, buffer: *mut u8) -> HRESULT {
put_string(&identifier(), size, buffer, std::ptr::null_mut())
}
extern "system" fn is_packaged(_: This) -> bool {
true
}
/// Installation monitors all watch the same finished installation, so the
/// handle is a fixed address.
static MONITOR: u8 = 0;
fn monitor() -> *const c_void {
(&raw const MONITOR).cast()
}
extern "system" fn create_monitor(
_: This,
id: *const c_char,
_selector_count: u32,
_selectors: *const c_void,
_interval_ms: u32,
_queue: *const c_void,
out: *mut *const c_void,
) -> HRESULT {
if !is_ours(id) {
return NO_PACKAGE;
}
put(out, monitor())
}
extern "system" fn close_monitor(_: This, _: *const c_void) {}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Progress {
pub total_bytes: u64,
pub installed_bytes: u64,
pub launch_bytes: u64,
pub launchable: bool,
pub completed: bool,
}
extern "system" fn progress(_: This, _: *const c_void, out: *mut Progress) {
let bytes = package_bytes();
put(
out,
Progress {
total_bytes: bytes,
installed_bytes: bytes,
launch_bytes: bytes,
launchable: true,
completed: true,
},
);
}
/// The installation is complete, so progress never changes.
extern "system" fn register_progress(
_: This,
_monitor: *const c_void,
_context: *mut c_void,
_callback: *const c_void,
out: *mut u64,
) -> HRESULT {
put(out, token())
}
/// 0: ready.
// shortcut: every selector counts as installed, including ones the
// package's layout does not have (the console answers those with an
// invalid-selector error); Grand Theft Auto VI asks only about its own
// chunks, which a full install has.
extern "system" fn find_availability(
_: This,
id: *const c_char,
_selector_count: u32,
_selectors: *const c_void,
out: *mut u32,
) -> HRESULT {
if !is_ours(id) {
return NO_PACKAGE;
}
put(out, 0)
}
extern "system" fn change_order(
_: This,
id: *const c_char,
_count: u32,
_selectors: *const c_void,
) -> HRESULT {
if is_ours(id) { S_OK } else { NO_PACKAGE }
}
static INSTALL: u8 = 0;
/// Everything is installed: done at once, the result is a monitor.
extern "system" fn install_chunks_async(
_: This,
id: *const c_char,
_count: u32,
_selectors: *const c_void,
_interval_ms: u32,
_suppress_confirmation: bool,
block: *mut AsyncBlock,
) -> HRESULT {
let result = if is_ours(id) {
Ok(xasync::bytes(monitor()))
} else {
Err(NO_PACKAGE)
};
xasync::finished_with(block, (&raw const INSTALL).cast(), result)
}
extern "system" fn install_chunks_result(
_: This,
block: *mut AsyncBlock,
out: *mut *const c_void,
) -> HRESULT {
xasync::result(block, (&raw const INSTALL).cast(), out)
}
/// Nothing to download.
extern "system" fn estimate_download(
_: This,
id: *const c_char,
_count: u32,
_selectors: *const c_void,
bytes: *mut u64,
confirm: *mut bool,
) -> HRESULT {
if !is_ours(id) {
return NO_PACKAGE;
}
if !confirm.is_null() {
// SAFETY: checked non-null.
unsafe { confirm.write(false) };
}
put(bytes, 0)
}
// shortcut: accepted but nothing is removed (the package folder is the
// user's), so the chunks stay ready; Grand Theft Auto VI's one call site
// (title+0x293b4b0, its chunk manager) would then see them still installed.
extern "system" fn uninstall_chunks(
_: This,
id: *const c_char,
_count: u32,
_selectors: *const c_void,
) -> HRESULT {
if is_ours(id) { S_OK } else { NO_PACKAGE }
}
/// Mount handles only come from mounting another package, and there is
/// none.
extern "system" fn mount_path(_: This, _: *const c_void, _: usize, _: *mut u8) -> HRESULT {
xasync::E_INVALIDARG
}
extern "system" fn close_mount(_: This, _: *const c_void) {}
/// Only other packages are uninstalled this way, and none is installed.
extern "system" fn uninstall_package(_: This, id: *const c_char) -> bool {
tracing::info!(
id = text(id).unwrap_or_default(),
"package uninstall refused"
);
false
}
static MOUNT: u8 = 0;
extern "system" fn mount_async(_: This, id: *const c_char, block: *mut AsyncBlock) -> HRESULT {
tracing::info!(
id = text(id).unwrap_or_default(),
"package mount: not installed"
);
xasync::finished(block, (&raw const MOUNT).cast(), NO_PACKAGE)
}
extern "system" fn mount_result(
_: This,
block: *mut AsyncBlock,
out: *mut *const c_void,
) -> HRESULT {
xasync::result(block, (&raw const MOUNT).cast(), out)
}
/// Titles enumerate content packages (kind 1); there are none.
// shortcut: the game kind (0) also lists nothing, not this installation;
// Grand Theft Auto VI enumerates only content (kind 1, title+0x2937bf0).
extern "system" fn enumerate(
_: This,
kind: u32,
_scope: u32,
_context: *mut c_void,
_callback: *const c_void,
) -> HRESULT {
tracing::debug!(kind, "packages enumerated: none");
S_OK
}
static VTABLE: Methods<40> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
current_identifier as *const (), // 0x18
is_packaged as *const (), // 0x20
create_monitor as *const (), // 0x28
close_monitor as *const (), // 0x30
progress as *const (), // 0x38
missing::<8> as *const (), // 0x40 update a monitor
register_progress as *const (), // 0x48
missing::<10> as *const (), // 0x50 unregister it
missing::<11> as *const (), // 0x58 user locale
find_availability as *const (), // 0x60
missing::<13> as *const (), // 0x68 enumerate chunk availability
change_order as *const (), // 0x70
missing::<15> as *const (), // 0x78 install chunks
install_chunks_async as *const (), // 0x80
install_chunks_result as *const (), // 0x88
estimate_download as *const (), // 0x90
uninstall_chunks as *const (), // 0x98
missing::<20> as *const (), // 0xa0
missing::<21> as *const (), // 0xa8
missing::<22> as *const (), // 0xb0
missing::<23> as *const (), // 0xb8 mount (deprecated)
missing::<24> as *const (), // 0xc0 mount path size
mount_path as *const (), // 0xc8
close_mount as *const (), // 0xd0
missing::<27> as *const (), // 0xd8
missing::<28> as *const (), // 0xe0 enumerate packages (older)
missing::<29> as *const (), // 0xe8
missing::<30> as *const (), // 0xf0
missing::<31> as *const (), // 0xf8
missing::<32> as *const (), // 0x100
missing::<33> as *const (), // 0x108
uninstall_package as *const (), // 0x110
missing::<35> as *const (), // 0x118
missing::<36> as *const (), // 0x120
mount_async as *const (), // 0x128
mount_result as *const (), // 0x130
enumerate as *const (), // 0x138
]);
#[cfg(test)]
mod tests {
use super::*;
use crate::modules::xgameruntime::method;
#[test]
fn the_installation_is_complete_and_alone() {
let this: This = &OBJECT;
type Id = extern "system" fn(This, usize, *mut u8) -> HRESULT;
let mut id = [0u8; 33];
assert_eq!(method::<Id>(&OBJECT, 0x18)(this, 33, id.as_mut_ptr()), S_OK);
let len = id.iter().position(|&b| b == 0).unwrap();
assert_eq!(std::str::from_utf8(&id[..len]).unwrap(), identifier());
assert!(method::<extern "system" fn(This) -> bool>(&OBJECT, 0x20)(
this
));
type Find =
extern "system" fn(This, *const c_char, u32, *const c_void, *mut u32) -> HRESULT;
let mut availability = 9;
let ours = format!("{}\0", identifier());
let find = method::<Find>(&OBJECT, 0x60);
let none = std::ptr::null();
assert_eq!(
find(this, ours.as_ptr().cast(), 0, none, &mut availability),
S_OK
);
assert_eq!(availability, 0, "ready");
assert_eq!(
find(this, c"dlc".as_ptr(), 0, none, &mut availability),
NO_PACKAGE
);
type Progress_ = extern "system" fn(This, *const c_void, *mut Progress);
let mut p = Progress {
total_bytes: 1,
installed_bytes: 0,
launch_bytes: 0,
launchable: false,
completed: false,
};
method::<Progress_>(&OBJECT, 0x38)(this, monitor(), &mut p);
assert!(p.completed && p.launchable && p.installed_bytes == p.total_bytes);
type Mount = extern "system" fn(This, *const c_char, *mut AsyncBlock) -> HRESULT;
let mut block = AsyncBlock {
queue: std::ptr::null(),
context: std::ptr::null_mut(),
callback: None,
internal: [0; 4],
};
assert_eq!(
method::<Mount>(&OBJECT, 0x128)(this, c"dlc".as_ptr(), &mut block),
S_OK
);
assert_eq!(xasync::XAsyncGetStatus(&mut block, true), NO_PACKAGE);
}
}
+479
View File
@@ -0,0 +1,479 @@
//! XStore as an offline console answers it: the game's own licence is
//! local and active (a full, owned game); the user owns no add-ons; what
//! needs the store service (catalog, consumables, purchase and update
//! pages, collection ids, update checks) fails with the documented store
//! network error.
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use super::xasync::{self, AsyncBlock, E_ILLEGAL_METHOD_CALL};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text, token,
};
use super::xpackage;
use crate::runtime;
pub const PROVIDER: Guid = Guid::new(
0x0dd1_12ac,
0x7c24,
0x448c,
[0xb9, 0x2b, 0x39, 0x60, 0xfb, 0x5b, 0xd3, 0x0c],
);
/// As Grand Theft Auto VI (2026) asks for it; every slot it calls takes
/// the public API's arguments in the 2020 order.
pub const IID_2026: Guid = Guid::new(
0xb09d_803c,
0x2414,
0x4a05,
[0x82, 0xc6, 0x66, 0xdf, 0xdc, 0x9e, 0x9a, 0x44],
);
/// The same table extended by durables licensing (0x238, 0x240).
pub const DURABLES_IID: Guid = Guid::new(
0x2d42_fea5,
0xe71d,
0x4b76,
[0x97, 0xcd, 0xc5, 0x0a, 0xfb, 0xb3, 0xae, 0x5d],
);
pub static OBJECT: Object = Object::new("store", &VTABLE);
pub const INTERFACES: &[Interface] = &[
(PROVIDER, IID_2026, &OBJECT),
(PROVIDER, DURABLES_IID, &OBJECT),
];
/// The documented "failed to communicate with the store network".
pub const NETWORK_ERROR: HRESULT = 0x8924_5301_u32 as i32;
type This = *const Object;
type Handle = *const c_void;
/// Contexts and product queries hold nothing (queries are always empty),
/// so their handles are fixed addresses. A licence handle says whether it
/// is valid by which address it is.
static CONTEXT: u8 = 0;
static QUERY: u8 = 0;
static VALID: u8 = 0;
static INVALID: u8 = 0;
fn handle(of: &'static u8) -> Handle {
(of as *const u8).cast()
}
/// Identifies our calls on a block: one per result shape.
static FAILED: u8 = 0;
static QUERY_CALL: u8 = 0;
static LICENSE_CALL: u8 = 0;
static GAME_LICENSE: u8 = 0;
fn offline(block: *mut AsyncBlock, what: &str) -> HRESULT {
tracing::info!(what, "store call: offline");
xasync::finished(block, (&raw const FAILED).cast(), NETWORK_ERROR)
}
/// The result functions of calls that failed: their status.
extern "system" fn status(_: This, block: *mut AsyncBlock) -> HRESULT {
xasync::XAsyncGetStatus(block, false)
}
extern "system" fn create_context(_: This, _user: *const c_void, out: *mut Handle) -> HRESULT {
put(out, handle(&CONTEXT))
}
extern "system" fn close(_: This, _: Handle) {}
extern "system" fn associated_products_async(
_: This,
_: Handle,
_kinds: u32,
_per_page: u32,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "associated products")
}
/// The user owns no add-ons: an empty query.
extern "system" fn entitled_products_async(
_: This,
_: Handle,
_kinds: u32,
_per_page: u32,
block: *mut AsyncBlock,
) -> HRESULT {
xasync::finished_with(
block,
(&raw const QUERY_CALL).cast(),
Ok(xasync::bytes(handle(&QUERY))),
)
}
extern "system" fn query_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT {
xasync::result(block, (&raw const QUERY_CALL).cast(), out)
}
/// Empty, so the callback never runs.
extern "system" fn enumerate_products(
_: This,
_: Handle,
_: *mut c_void,
_: *const c_void,
) -> HRESULT {
S_OK
}
extern "system" fn has_more_pages(_: This, _: Handle) -> bool {
false
}
/// There is no next page to ask for.
extern "system" fn next_page_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
xasync::finished(block, (&raw const QUERY_CALL).cast(), E_ILLEGAL_METHOD_CALL)
}
fn license_for(owned: bool, block: *mut AsyncBlock) -> HRESULT {
let license = handle(if owned { &VALID } else { &INVALID });
xasync::finished_with(
block,
(&raw const LICENSE_CALL).cast(),
Ok(xasync::bytes(license)),
)
}
/// Only the game's own package is installed, so only its licence is valid.
extern "system" fn license_for_package_async(
_: This,
_: Handle,
package: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
let ours = text(package).is_some_and(|p| p == xpackage::identifier());
license_for(ours, block)
}
/// The user owns no durables: their licences are not valid.
extern "system" fn license_for_durables_async(
_: This,
_: Handle,
store_id: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
tracing::debug!(
store_id = text(store_id).unwrap_or_default(),
"durable not owned"
);
license_for(false, block)
}
extern "system" fn license_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT {
xasync::result(block, (&raw const LICENSE_CALL).cast(), out)
}
extern "system" fn is_license_valid(_: This, license: Handle) -> bool {
license == handle(&VALID)
}
/// The game licence, as the public API lays it out.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct GameLicense {
pub sku_store_id: [u8; 18],
pub is_active: bool,
pub is_trial_owned_by_this_user: bool,
pub is_disc_license: bool,
pub is_trial: bool,
pub trial_seconds_remaining: u32,
pub trial_unique_id: [u8; 64],
pub expiration: i64,
}
/// A full, active licence for the game's SKU (`<store id>/0010`, the
/// store's first SKU), not a trial, without expiry.
fn game_license() -> GameLicense {
let mut sku = [0u8; 18];
let id = format!("{}/0010", runtime::title().store_id);
let len = id.len().min(sku.len() - 1);
sku[..len].copy_from_slice(&id.as_bytes()[..len]);
GameLicense {
sku_store_id: sku,
is_active: true,
is_trial_owned_by_this_user: false,
is_disc_license: false,
is_trial: false,
trial_seconds_remaining: 0,
trial_unique_id: [0; 64],
expiration: 0,
}
}
extern "system" fn game_license_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
let license = xasync::bytes(game_license());
xasync::finished_with(block, (&raw const GAME_LICENSE).cast(), Ok(license))
}
extern "system" fn game_license_result(
_: This,
block: *mut AsyncBlock,
out: *mut GameLicense,
) -> HRESULT {
xasync::result(block, (&raw const GAME_LICENSE).cast(), out)
}
extern "system" fn consumable_balance_async(
_: This,
_: Handle,
_store_id: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "consumable balance")
}
extern "system" fn report_fulfillment_async(
_: This,
_: Handle,
_store_id: *const c_char,
_quantity: u32,
_tracking_id: *const c_void,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "consumable fulfillment")
}
/// Collections and purchase ids alike.
extern "system" fn user_id_async(
_: This,
_: Handle,
_ticket: *const c_char,
_publisher_user_id: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "user store id")
}
extern "system" fn size_status(_: This, block: *mut AsyncBlock, _out: *mut usize) -> HRESULT {
xasync::XAsyncGetStatus(block, false)
}
extern "system" fn string_status(
_: This,
block: *mut AsyncBlock,
_: usize,
_: *mut c_char,
) -> HRESULT {
xasync::XAsyncGetStatus(block, false)
}
extern "system" fn count_status(_: This, block: *mut AsyncBlock, _out: *mut u32) -> HRESULT {
xasync::XAsyncGetStatus(block, false)
}
extern "system" fn array_status(
_: This,
block: *mut AsyncBlock,
_: u32,
_: *mut c_void,
) -> HRESULT {
xasync::XAsyncGetStatus(block, false)
}
extern "system" fn purchase_ui_async(
_: This,
_: Handle,
_store_id: *const c_char,
_name: *const c_char,
_json: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "purchase page")
}
extern "system" fn product_page_ui_async(
_: This,
_: Handle,
_store_id: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "product page")
}
extern "system" fn redeem_ui_async(
_: This,
_: Handle,
_token: *const c_char,
_allowed: *const *const c_char,
_allowed_count: usize,
_disallow_csv: bool,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "redeem page")
}
extern "system" fn updates_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
offline(block, "update check")
}
/// Installing updates or packages by id alike.
extern "system" fn install_async(
_: This,
_: Handle,
_ids: *const *const c_char,
_count: usize,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "package download")
}
/// The game's own store id maps to its installation; nothing else is
/// installed.
extern "system" fn package_identifier(
_: This,
store_id: *const c_char,
size: usize,
buffer: *mut u8,
) -> HRESULT {
let title = runtime::title();
match text(store_id) {
Some(id) if !title.store_id.is_empty() && id == title.store_id => {
put_string(&xpackage::identifier(), size, buffer, std::ptr::null_mut())
}
_ => xpackage::NO_PACKAGE,
}
}
/// Licences never change offline, so these callbacks never run.
extern "system" fn register(
_: This,
_: Handle,
_queue: *const c_void,
_context: *mut c_void,
_callback: *const c_void,
out: *mut u64,
) -> HRESULT {
put(out, token())
}
extern "system" fn unregister(_: This, _: Handle, _token: u64, _wait: bool) -> bool {
true
}
static VTABLE: Methods<76> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
create_context as *const (), // 0x18
close as *const (), // 0x20
associated_products_async as *const (), // 0x28
query_result as *const (), // 0x30
missing::<7> as *const (), // 0x38 products by id
missing::<8> as *const (), // 0x40
entitled_products_async as *const (), // 0x48
query_result as *const (), // 0x50
missing::<11> as *const (), // 0x58 product for the game
missing::<12> as *const (), // 0x60
missing::<13> as *const (), // 0x68 product for a package
missing::<14> as *const (), // 0x70
enumerate_products as *const (), // 0x78
has_more_pages as *const (), // 0x80
next_page_async as *const (), // 0x88
query_result as *const (), // 0x90
close as *const (), // 0x98 a product query
license_for_package_async as *const (), // 0xa0
license_result as *const (), // 0xa8
is_license_valid as *const (), // 0xb0
close as *const (), // 0xb8 a licence
missing::<24> as *const (), // 0xc0 can acquire for store id
missing::<25> as *const (), // 0xc8
missing::<26> as *const (), // 0xd0 can acquire for package
missing::<27> as *const (), // 0xd8
game_license_async as *const (), // 0xe0
game_license_result as *const (), // 0xe8
missing::<30> as *const (), // 0xf0 add-on licences
missing::<31> as *const (), // 0xf8
missing::<32> as *const (), // 0x100
consumable_balance_async as *const (), // 0x108
status as *const (), // 0x110
report_fulfillment_async as *const (), // 0x118
missing::<36> as *const (), // 0x120
user_id_async as *const (), // 0x128 collections id
size_status as *const (), // 0x130
string_status as *const (), // 0x138
user_id_async as *const (), // 0x140 purchase id
size_status as *const (), // 0x148
string_status as *const (), // 0x150
missing::<43> as *const (), // 0x158 licence token
missing::<44> as *const (), // 0x160
missing::<45> as *const (), // 0x168
missing::<46> as *const (), // 0x170
missing::<47> as *const (), // 0x178
missing::<48> as *const (), // 0x180
purchase_ui_async as *const (), // 0x188
missing::<50> as *const (), // 0x190
missing::<51> as *const (), // 0x198 rate and review
missing::<52> as *const (), // 0x1a0
redeem_ui_async as *const (), // 0x1a8
missing::<54> as *const (), // 0x1b0
updates_async as *const (), // 0x1b8
count_status as *const (), // 0x1c0
array_status as *const (), // 0x1c8
missing::<58> as *const (), // 0x1d0 download updates
missing::<59> as *const (), // 0x1d8
install_async as *const (), // 0x1e0 updates
status as *const (), // 0x1e8
install_async as *const (), // 0x1f0 packages by store id
count_status as *const (), // 0x1f8
array_status as *const (), // 0x200
package_identifier as *const (), // 0x208
register as *const (), // 0x210 game licence changed
unregister as *const (), // 0x218
register as *const (), // 0x220 package licence lost
unregister as *const (), // 0x228
missing::<70> as *const (), // 0x230
license_for_durables_async as *const (), // 0x238
license_result as *const (), // 0x240
missing::<73> as *const (), // 0x248 associated products page
missing::<74> as *const (), // 0x250
product_page_ui_async as *const (), // 0x258
]);
#[cfg(test)]
mod tests {
use super::*;
use crate::modules::xgameruntime::method;
fn block() -> AsyncBlock {
AsyncBlock {
queue: std::ptr::null(),
context: std::ptr::null_mut(),
callback: None,
internal: [0; 4],
}
}
#[test]
fn the_game_is_licensed_and_the_store_is_offline() {
let this: This = &OBJECT;
assert_eq!(size_of::<GameLicense>(), 104);
type Begin = extern "system" fn(This, Handle, *mut AsyncBlock) -> HRESULT;
type Result = extern "system" fn(This, *mut AsyncBlock, *mut GameLicense) -> HRESULT;
let mut b = block();
assert_eq!(
method::<Begin>(&OBJECT, 0xe0)(this, handle(&CONTEXT), &mut b),
S_OK
);
assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK);
let mut license = std::mem::MaybeUninit::<GameLicense>::zeroed();
assert_eq!(
method::<Result>(&OBJECT, 0xe8)(this, &mut b, license.as_mut_ptr()),
S_OK
);
// SAFETY: written by the call.
let license = unsafe { license.assume_init() };
assert!(license.is_active && !license.is_trial);
let mut b = block();
assert_eq!(
method::<Begin>(&OBJECT, 0x1b8)(this, handle(&CONTEXT), &mut b),
S_OK
);
assert_eq!(xasync::XAsyncGetStatus(&mut b, true), NETWORK_ERROR);
type Count = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT;
assert_eq!(
method::<Count>(&OBJECT, 0x1c0)(this, &mut b, &mut 0),
NETWORK_ERROR
);
type Durable = extern "system" fn(This, Handle, *const c_char, *mut AsyncBlock) -> HRESULT;
type License = extern "system" fn(This, *mut AsyncBlock, *mut Handle) -> HRESULT;
let mut b = block();
let durable = method::<Durable>(&OBJECT, 0x238);
assert_eq!(
durable(this, handle(&CONTEXT), c"9XYZ".as_ptr(), &mut b),
S_OK
);
assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK);
let mut l = std::ptr::null();
assert_eq!(
method::<License>(&OBJECT, 0x240)(this, &mut b, &mut l),
S_OK
);
assert!(!method::<extern "system" fn(This, Handle) -> bool>(
&OBJECT, 0xb0
)(this, l));
}
}
+248 -2
View File
@@ -1,5 +1,6 @@
//! XSystem: the console's identity and sandbox, and how analytics describe
//! the device. Fixed values: one offline retail Xbox Series X.
//! the device. Fixed values: one offline retail console, the model the user
//! chose ([`victory_gpu::console`]).
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use super::xgameruntime::{
@@ -40,8 +41,18 @@ const DEVICE_ID: &str = "VkljdG9yeSBvZmZsaW5lIGRldmljZSBpZGVudGl0eSE=";
pub static OBJECT: Object = Object::new("system", &VTABLE);
pub static ANALYTICS_OBJECT: Object = Object::new("analytics", &ANALYTICS_VTABLE);
/// The interface as Grand Theft Auto VI (2026) asks for it; it calls the
/// same three slots (0x18, 0x20, 0x28) with the same arguments.
pub const IID_2026: Guid = Guid::new(
0x1861_cf2e,
0xe18b,
0x4834,
[0xa9, 0xf5, 0xb4, 0xa4, 0xe6, 0xef, 0xb4, 0xcf],
);
pub const INTERFACES: &[Interface] = &[
(PROVIDER, IID, &OBJECT),
(PROVIDER, IID_2026, &OBJECT),
(ANALYTICS, ANALYTICS, &ANALYTICS_OBJECT),
];
@@ -96,7 +107,7 @@ extern "system" fn analytics_info(_: This, out: *mut AnalyticsInfo) -> *mut Anal
os: OS,
hosting_os: OS,
family: text("Xbox"),
form: text("Xbox Series X"),
form: text(victory_gpu::console::current().name()),
};
// SAFETY: the caller passes room for the struct.
unsafe { out.write(info) };
@@ -119,6 +130,241 @@ static ANALYTICS_VTABLE: Methods<4> = Methods([
analytics_info as *const (), // 0x18
]);
/// The device type is not a runtime call: code linked into the title reads
/// `ConsoleMode` from this key (`RegOpenKeyW`, `RegQueryValueExW`) and
/// takes a missing value for a PC.
#[cfg(windows)]
mod device_type {
#![allow(non_snake_case)]
use std::ffi::c_void;
use victory_gpu::console::{self, Console};
use crate::modules::files::host;
use crate::{HleModule, hle_export};
type Key = *mut c_void;
const LOCAL_MACHINE: Key = 0xffff_ffff_8000_0002_u64 as Key;
const KEY: &str = r"Software\Microsoft\Windows NT\CurrentVersion\OEM";
const VALUE: &str = "ConsoleMode";
const SUCCESS: u32 = 0;
const FILE_NOT_FOUND: u32 = 2;
const INVALID_PARAMETER: u32 = 87;
const MORE_DATA: u32 = 234;
const DWORD: u32 = 4;
/// Stands for the key; never a host handle value.
static OEM: u8 = 0;
fn oem() -> Key {
(&raw const OEM).cast_mut().cast()
}
/// What the title's code maps to each model's device type.
pub(super) fn console_mode(console: Console) -> u32 {
match console {
Console::SeriesX => 0x64,
Console::SeriesS => 0x60,
}
}
fn is(text: *const u16, expected: &str) -> bool {
if text.is_null() {
return false;
}
// 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))
};
text.eq_ignore_ascii_case(expected)
}
/// Opens our key for its path; the key has no subkeys. `None`: not
/// ours, ask the host.
fn open(root: Key, sub: *const u16, out: *mut Key) -> Option<u32> {
if root == oem() {
return Some(FILE_NOT_FOUND);
}
if root == LOCAL_MACHINE && is(sub, KEY) && !out.is_null() {
// SAFETY: checked non-null; the title passes room for a key.
unsafe { out.write(oem()) };
return Some(SUCCESS);
}
None
}
// Our titles import only these registry functions (and `RegOpenKeyExW`
// below), so no other call can reach the host with our key.
pub extern "system" fn RegOpenKeyW(root: Key, sub: *const u16, out: *mut Key) -> u32 {
open(root, sub, out).unwrap_or_else(|| {
host!("advapi32.dll", "RegOpenKeyW": extern "system" fn(Key, *const u16, *mut Key) -> u32)(
root, sub, out,
)
})
}
pub extern "system" fn RegOpenKeyExW(
root: Key,
sub: *const u16,
options: u32,
access: u32,
out: *mut Key,
) -> u32 {
open(root, sub, out).unwrap_or_else(|| {
host!("advapi32.dll", "RegOpenKeyExW": extern "system" fn(
Key, *const u16, u32, u32, *mut Key,
) -> u32)(root, sub, options, access, out)
})
}
pub extern "system" fn RegQueryValueExW(
key: Key,
name: *const u16,
reserved: *mut u32,
kind: *mut u32,
data: *mut u8,
size: *mut u32,
) -> u32 {
if key != oem() {
return host!("advapi32.dll", "RegQueryValueExW": extern "system" fn(
Key, *const u16, *mut u32, *mut u32, *mut u8, *mut u32,
) -> u32)(key, name, reserved, kind, data, size);
}
if !is(name, VALUE) {
return FILE_NOT_FOUND;
}
if !data.is_null() && size.is_null() {
return INVALID_PARAMETER;
}
// SAFETY: the title passes valid or null pointers, sized by `size`.
unsafe {
if !kind.is_null() {
kind.write(DWORD);
}
if size.is_null() {
return SUCCESS;
}
let room = size.read();
size.write(4);
if data.is_null() {
return SUCCESS;
}
if room < 4 {
return MORE_DATA;
}
data.cast::<u32>()
.write_unaligned(console_mode(console::current()));
}
tracing::debug!(console = console::current().name(), "device type read");
SUCCESS
}
pub extern "system" fn RegCloseKey(key: Key) -> u32 {
if key == oem() {
return SUCCESS;
}
host!("advapi32.dll", "RegCloseKey": extern "system" fn(Key) -> u32)(key)
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "device type",
dlls: &["advapi32.dll", "api-ms-win-core-registry-*"],
exports: vec![
hle_export!(RegOpenKeyW),
hle_export!(RegOpenKeyExW),
hle_export!(RegQueryValueExW),
hle_export!(RegCloseKey),
],
}
}
#[cfg(test)]
mod tests {
use super::*;
fn w(s: &str) -> Vec<u16> {
s.encode_utf16().chain([0]).collect()
}
#[test]
fn titles_read_the_chosen_model() {
assert_eq!(console_mode(Console::SeriesX), 0x64);
assert_eq!(console_mode(Console::SeriesS), 0x60);
let mut key = std::ptr::null_mut();
let path = w(&KEY.to_ascii_lowercase());
assert_eq!(RegOpenKeyW(LOCAL_MACHINE, path.as_ptr(), &mut key), SUCCESS);
let (mut kind, mut value, mut size) = (0, 0u32, 4);
let name = w(VALUE);
let query = |data: *mut u32, size: *mut u32, kind: *mut u32| {
RegQueryValueExW(
key,
name.as_ptr(),
std::ptr::null_mut(),
kind,
data.cast(),
size,
)
};
assert_eq!(query(&mut value, &mut size, &mut kind), SUCCESS);
assert_eq!((kind, size), (DWORD, 4));
assert_eq!(value, console_mode(console::current()));
let mut small = 2;
assert_eq!(query(&mut value, &mut small, &mut kind), MORE_DATA);
assert_eq!(small, 4);
let other = w("Other");
assert_eq!(
RegQueryValueExW(
key,
other.as_ptr(),
std::ptr::null_mut(),
&mut kind,
std::ptr::null_mut(),
&mut size
),
FILE_NOT_FOUND
);
let mut sub = std::ptr::null_mut();
assert_eq!(
RegOpenKeyExW(key, other.as_ptr(), 0, 1, &mut sub),
FILE_NOT_FOUND
);
assert_eq!(RegCloseKey(key), SUCCESS);
let mut again = std::ptr::null_mut();
assert_eq!(
RegOpenKeyExW(LOCAL_MACHINE, path.as_ptr(), 0, 1, &mut again),
SUCCESS
);
assert_eq!(again, oem());
}
#[test]
fn other_keys_reach_the_host() {
let mut key = std::ptr::null_mut();
let path = w(r"Software\Microsoft\Windows NT\CurrentVersion");
assert_eq!(RegOpenKeyW(LOCAL_MACHINE, path.as_ptr(), &mut key), SUCCESS);
assert_ne!(key, oem());
let (mut size, name) = (0, w("ProductName"));
assert_eq!(
RegQueryValueExW(
key,
name.as_ptr(),
std::ptr::null_mut(),
std::ptr::null_mut(),
std::ptr::null_mut(),
&mut size
),
SUCCESS
);
assert!(size > 0);
assert_eq!(RegCloseKey(key), SUCCESS);
}
}
}
#[cfg(windows)]
pub(crate) use device_type::module;
#[cfg(test)]
mod tests {
use super::*;
+110 -9
View File
@@ -4,11 +4,11 @@
//! input device is associated with the user (there are none, `gameinput`).
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::c_void;
use std::ffi::{c_char, 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,
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text, token,
};
/// The user provider.
@@ -81,6 +81,9 @@ pub static DEVICE_OBJECT: Object = Object::new("user devices", &DEVICE_VTABLE);
pub const INTERFACES: &[Interface] = &[
(PROVIDER, IID, &OBJECT),
// Grand Theft Auto VI (2026) asks with the provider's id; its thunks call
// the same slots with the same arguments (0x108/0x110 change events).
(PROVIDER, PROVIDER, &OBJECT),
(PROVIDER, GAMERTAG_IID, &GAMERTAG_OBJECT),
(DEVICE_PROVIDER, DEVICE_IID, &DEVICE_OBJECT),
];
@@ -178,6 +181,65 @@ extern "system" fn check_privilege(
put(has, true)
}
/// 3: adult.
extern "system" fn get_age_group(_: This, _: Handle, out: *mut u32) -> HRESULT {
put(out, 3)
}
static RESOLVE: u8 = 0;
static TOKEN: u8 = 0;
/// Every privilege is granted, so there is nothing to resolve.
extern "system" fn resolve_privilege_async(
_: This,
_: Handle,
_options: u32,
_privilege: u32,
block: *mut AsyncBlock,
) -> HRESULT {
xasync::finished(block, (&raw const RESOLVE).cast(), S_OK)
}
extern "system" fn resolve_privilege_result(_: This, block: *mut AsyncBlock) -> HRESULT {
let none = std::ptr::null_mut();
xasync::XAsyncGetResult(block, (&raw const RESOLVE).cast(), 0, none, none.cast())
}
/// The documented "failed to get token": tokens come from the service.
pub const FAILED_TO_GET_TOKEN: HRESULT = 0x8924_5111_u32 as i32;
#[allow(clippy::too_many_arguments)]
extern "system" fn token_async(
_: This,
_: Handle,
_options: u32,
_method: *const c_char,
url: *const c_char,
_header_count: usize,
_headers: *const c_void,
_body_size: usize,
_body: *const c_void,
block: *mut AsyncBlock,
) -> HRESULT {
tracing::info!(
url = text(url).unwrap_or_default(),
"token and signature: offline"
);
xasync::finished(block, (&raw const TOKEN).cast(), FAILED_TO_GET_TOKEN)
}
extern "system" fn token_size(_: This, block: *mut AsyncBlock, out: *mut usize) -> HRESULT {
xasync::XAsyncGetResultSize(block, out)
}
extern "system" fn token_result(
_: This,
block: *mut AsyncBlock,
size: usize,
buffer: *mut c_void,
_data: *mut *const c_void,
used: *mut usize,
) -> HRESULT {
xasync::XAsyncGetResult(block, (&raw const TOKEN).cast(), size, buffer, used)
}
/// The user never changes and no device is ever associated, so these
/// callbacks are never called.
extern "system" fn register(
@@ -198,7 +260,8 @@ extern "system" fn find_for_device(_: This, _device: *const c_void, _: *mut Hand
USER_NOT_FOUND
}
// Unset slots: gamer pictures, token and signature, issue resolution.
// Unset slots (no title seen calls them): maximum users, gamer pictures,
// the UTF-16 token calls, issue resolution.
static VTABLE: Methods<35> = Methods([
missing::<0> as *const (), // 0x00 QueryInterface
add_ref as *const (), // 0x08 AddRef
@@ -219,13 +282,13 @@ static VTABLE: Methods<35> = Methods([
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
get_age_group as *const (), // 0x98
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
resolve_privilege_async as *const (), // 0xa8 with UI
resolve_privilege_result as *const (), // 0xb0
token_async as *const (), // 0xb8 token and signature
token_size as *const (), // 0xc0
token_result as *const (), // 0xc8
missing::<26> as *const (), // 0xd0 the same, UTF-16: begin
missing::<27> as *const (), // 0xd8 result size
missing::<28> as *const (), // 0xe0 result
@@ -294,5 +357,43 @@ mod tests {
get(this, handle, 0, 2, name.as_mut_ptr(), &mut used),
E_NOT_SUFFICIENT_BUFFER
);
type Age = extern "system" fn(This, Handle, *mut u32) -> HRESULT;
let mut age = 0;
assert_eq!(slot::<Age>(&OBJECT, 0x98)(this, handle, &mut age), S_OK);
assert_eq!(age, 3, "adult");
type Token = extern "system" fn(
This,
Handle,
u32,
*const c_char,
*const c_char,
usize,
*const c_void,
usize,
*const c_void,
*mut AsyncBlock,
) -> HRESULT;
let (null, url) = (std::ptr::null(), c"https://example.invalid/");
let token = slot::<Token>(&OBJECT, 0xb8);
assert_eq!(
token(
this,
handle,
0,
c"GET".as_ptr(),
url.as_ptr(),
0,
null,
0,
null,
&mut block
),
S_OK
);
assert_eq!(
xasync::XAsyncGetStatus(&mut block, true),
FAILED_TO_GET_TOKEN
);
}
}
+112 -16
View File
@@ -32,6 +32,12 @@ pub fn set_image_path(base: usize, path: &Path) {
paths.push((base, path));
}
/// Forgets a title image that was unmapped again.
pub fn forget_image(base: usize) {
let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
paths.retain(|(b, _)| *b != base);
}
pub fn image_path(base: usize) -> Option<PathBuf> {
let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
paths
@@ -70,33 +76,88 @@ pub fn load_title_dll(file: &str) -> Result<Option<usize>, String> {
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Title {
pub id: u32,
/// The store's product id (empty if the manifest has none).
pub store_id: String,
/// Persistent local storage: our folder for it and the title's quota.
/// Game saves live beside it ([`Title::saves`]).
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.
/// Id, store id and storage quota from the manifest (zero or empty
/// where it has none); the storage folder is left for the caller.
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("<PersistentLocalStorage>")
.and_then(|at| element(&text[at..], "SizeMB"))
.and_then(|v| v.parse::<u64>().ok());
let elements = elements(text);
let get = |path: &str| {
elements
.iter()
.find(|(p, _)| p == path)
.map(|(_, text)| text.as_str())
};
let id = get("Game/TitleId").and_then(|v| u32::from_str_radix(v, 16).ok());
let storage_mb = get("Game/PersistentLocalStorage/SizeMB").and_then(|v| v.parse().ok());
Title {
id: id.unwrap_or(0),
store_id: get("Game/StoreId").unwrap_or_default().to_owned(),
storage: PathBuf::new(),
storage_bytes: storage_mb.unwrap_or(0) << 20,
}
}
/// Where game saves live: next to persistent local storage, under the
/// data directory, never the cache.
pub fn saves(&self) -> PathBuf {
self.storage.with_file_name("saves")
}
}
/// Each element of an XML text as its path from the root (`Game/TitleId`)
/// and its trimmed text up to the first child, the predefined entities
/// decoded; comments, CDATA sections, declarations and attributes are
/// skipped.
fn elements(text: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
let mut path: Vec<&str> = Vec::new();
let mut rest = text;
while let Some(open) = rest.find('<') {
rest = &rest[open..];
let end = if rest.starts_with("<!--") {
rest.find("-->").map(|e| e + 3)
} else if rest.starts_with("<![CDATA[") {
rest.find("]]>").map(|e| e + 3)
} else {
rest.find('>').map(|e| e + 1)
};
let Some(end) = end else { break };
let tag = &rest[1..end - 1];
rest = &rest[end..];
if tag.starts_with(['!', '?']) {
continue;
}
if let Some(name) = tag.strip_prefix('/') {
if let Some(at) = path.iter().rposition(|n| *n == name.trim()) {
path.truncate(at);
}
continue;
}
let closed = tag.ends_with('/');
let name = tag
.trim_end_matches('/')
.split_whitespace()
.next()
.unwrap_or("");
path.push(name);
let body = rest[..rest.find('<').unwrap_or(rest.len())].trim();
let body = [("&lt;", "<"), ("&gt;", ">"), ("&quot;", "\""), ("&apos;", "'"), ("&amp;", "&")]
.iter()
.fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c));
out.push((path.join("/"), body));
if closed {
path.pop();
}
}
out
}
static TITLE: Mutex<Option<Title>> = Mutex::new(None);
@@ -114,17 +175,52 @@ pub fn title() -> Title {
.unwrap_or_default()
}
/// Gives the process the console's millisecond timers. Titles pace
/// themselves with short waits (Grand Theft Auto VI's audio mixer sleeps
/// about 4 ms per 5.3 ms block) and cannot tune the timer on the console;
/// a desktop process waits in 15.6 ms ticks unless it asks for finer ones,
/// and Windows 11 drops that request while the window is hidden unless the
/// process opts out. Process-wide, for the whole run.
#[cfg(windows)]
pub fn use_console_timers() {
use windows_sys::Win32::Media::timeBeginPeriod;
use windows_sys::Win32::System::Threading::{
GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION,
PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE,
ProcessPowerThrottling, SetProcessInformation,
};
let keep = PROCESS_POWER_THROTTLING_STATE {
Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION,
ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION,
StateMask: 0,
};
// SAFETY: plain process settings; `keep` outlives the call.
unsafe {
SetProcessInformation(
GetCurrentProcess(),
ProcessPowerThrottling,
(&raw const keep).cast(),
size_of_val(&keep) as u32,
);
timeBeginPeriod(1);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_title_id_and_storage_quota() {
let text = "<Game><Identity Name=\"x\"/>\n <TitleId>639AA8DD</TitleId>\n\
fn reads_title_id_store_id_and_storage_quota() {
let text = "\u{feff}<?xml version=\"1.0\"?>\n<Game configVersion=\"1\">\
<!-- <TitleId>00000000</TitleId> -->\
<Identity Name=\"x\"/>\n <TitleId>639AA8DD</TitleId>\n\
<![CDATA[ <TitleId>1</TitleId> ]]> <StoreId>9&amp;C</StoreId><Other><SizeMB>7</SizeMB></Other>\
<PersistentLocalStorage>\n <SizeMB>1024</SizeMB> <!-- c -->\n\
</PersistentLocalStorage></Game>";
let t = Title::from_manifest(text);
assert_eq!((t.id, t.storage_bytes), (0x639A_A8DD, 1024 << 20));
assert_eq!(t.store_id, "9&C");
assert_eq!(Title::from_manifest("").storage_bytes, 0);
}
}
+5
View File
@@ -20,6 +20,7 @@ windows-sys = { workspace = true, features = [
"Wdk_System_Threading",
"Win32_Foundation",
"Win32_System_Diagnostics_Debug",
"Win32_System_Diagnostics_ToolHelp",
"Win32_System_Kernel",
"Win32_System_LibraryLoader",
"Win32_System_Memory",
@@ -29,5 +30,9 @@ windows-sys = { workspace = true, features = [
[dev-dependencies]
tempfile.workspace = true
[features]
# Debugging switches (scheduled stack dumps and the like).
diagnostics = []
[lints]
workspace = true
+320 -38
View File
@@ -1,77 +1,330 @@
//! 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.
//! A vectored handler sees every exception first, so it only prints the
//! kinds that end a process (access violations and the like, and
//! breakpoints: titles assert with `int3`, fatal without a debugger) as
//! first-chance, since a handler may still take them (ntdll's loader does
//! with its own probes). What nobody handles, of any kind (an uncaught C++
//! exception too), is reported from the unhandled-exception filter
//! (`report_unhandled`, which the runtime calls ahead of the title's own)
//! and appended to the crash log, with the title's last debug output, which
//! often states the reason. Panics of ours go to the crash log too.
use std::ptr::null_mut;
use windows_sys::Win32::Foundation::{
EXCEPTION_ACCESS_VIOLATION, EXCEPTION_ILLEGAL_INSTRUCTION, EXCEPTION_INT_DIVIDE_BY_ZERO,
EXCEPTION_PRIV_INSTRUCTION, EXCEPTION_STACK_OVERFLOW, HMODULE,
EXCEPTION_ACCESS_VIOLATION, EXCEPTION_BREAKPOINT, 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,
AddVectoredExceptionHandler, CONTEXT, EXCEPTION_POINTERS, RtlLookupFunctionEntry,
RtlVirtualUnwind, SetUnhandledExceptionFilter, UNW_FLAG_NHANDLER,
};
use windows_sys::Win32::System::LibraryLoader::{
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
GetModuleFileNameW, GetModuleHandleExW,
};
use windows_sys::Win32::System::Threading::GetCurrentThreadStackLimits;
const EXCEPTION_CONTINUE_SEARCH: i32 = 0;
/// Stack slots scanned for return addresses into a module.
const STACK_SCAN: usize = 64;
/// Frames listed per report.
pub(crate) const MAX_FRAMES: usize = 40;
/// 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)) };
/// Memory saved to files when a crash is reported: (address, length, file).
#[cfg(feature = "diagnostics")]
static SAVE: std::sync::OnceLock<Vec<(usize, usize, std::path::PathBuf)>> =
std::sync::OnceLock::new();
/// Debugging aid: on a reported crash, also write each `[address, address
/// + len)` (readable title memory, e.g. an engine table) to its file.
#[cfg(feature = "diagnostics")]
pub fn save_on_crash(ranges: Vec<(usize, usize, std::path::PathBuf)>) {
let _ = SAVE.set(ranges);
}
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 ![
/// The file crash reports are appended to, besides being printed.
static LOG: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new();
/// Also appends every unhandled-exception report and panic to `file`, so a
/// crash can be read after the console is gone.
pub fn log_crashes_to(file: std::path::PathBuf) {
if LOG.set(file).is_ok() {
let print = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
print(info);
append_to_log(&format!(
"VIctory: panic on thread {:?}: {info}\n{}",
std::thread::current().name().unwrap_or("?"),
title_output()
));
}));
}
}
/// Appends a failure that is not an exception (the host GPU's) to the crash
/// log, with the title's last debug output, and prints it.
pub fn log_crash(text: &str) {
let text = format!("{text}
{}", title_output());
eprint!("{text}");
append_to_log(&text);
}
fn append_to_log(text: &str) {
use std::io::Write;
let Some(file) = LOG.get() else { return };
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let opened = std::fs::OpenOptions::new().create(true).append(true).open(file);
if let Ok(mut f) = opened {
let _ = write!(f, "unix time {now}, process {}\n{text}\n", std::process::id());
}
}
/// The title's last lines of debug output, kept for crash reports.
static SAID: std::sync::Mutex<std::collections::VecDeque<String>> =
std::sync::Mutex::new(std::collections::VecDeque::new());
const SAID_LINES: usize = 8;
/// Keeps a line of the title's debug output for the next crash report.
pub fn note_title_output(line: &str) {
if line.is_empty() {
return;
}
let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
if said.len() == SAID_LINES {
said.pop_front();
}
said.push_back(line.to_owned());
}
/// The kept lines, one per report line; nothing if another thread holds
/// them (it may be the one that faulted).
fn title_output() -> String {
let Ok(said) = SAID.try_lock() else {
return String::new();
};
said.iter().map(|l| format!(" title said: {l}\n")).collect()
}
/// Installs the handlers; call once before running title code.
pub fn report_crashes() {
unsafe extern "system" fn filter(info: *const EXCEPTION_POINTERS) -> i32 {
// SAFETY: the system passes the exception being dispatched.
unsafe { report_unhandled(info) };
EXCEPTION_CONTINUE_SEARCH
}
// SAFETY: registers handlers that only read the exception they are
// given; the title's own filter, once it sets one, takes the place of
// ours and calls `report_unhandled` first.
unsafe {
AddVectoredExceptionHandler(0, Some(handler));
SetUnhandledExceptionFilter(Some(filter));
}
}
/// What the vectored handler reports as it happens.
const FATAL: [i32; 6] = [
EXCEPTION_ACCESS_VIOLATION,
EXCEPTION_ILLEGAL_INSTRUCTION,
EXCEPTION_PRIV_INSTRUCTION,
EXCEPTION_INT_DIVIDE_BY_ZERO,
EXCEPTION_STACK_OVERFLOW,
]
.contains(&code)
{
return EXCEPTION_CONTINUE_SEARCH;
EXCEPTION_BREAKPOINT,
];
unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 {
// SAFETY: the system passes valid exception pointers.
if FATAL.contains(&unsafe { (*(*info).ExceptionRecord).ExceptionCode }) {
// SAFETY: as above.
unsafe { report("first-chance exception", info, false) };
}
EXCEPTION_CONTINUE_SEARCH
}
/// For an unhandled-exception filter: reports the exception that is about
/// to end the process, and appends it to the crash log.
///
/// # Safety
/// `info` comes from the system, for an exception being dispatched.
pub unsafe fn report_unhandled(info: *const EXCEPTION_POINTERS) {
// SAFETY: forwarded from the caller.
unsafe { report("unhandled exception", info, true) };
}
/// MSVC's code for a C++ `throw`, and its magic first parameter.
const CPP_EXCEPTION: i32 = 0xE06D_7363_u32 as i32;
const CPP_MAGIC: usize = 0x1993_0520;
/// What a C++ throw threw: the decorated name of its type, then its value
/// where that names the cause (an integer, e.g. an HRESULT; a standard
/// exception's message).
///
/// # Safety
/// `p` are the parameters of a live MSVC throw (`p[0]` the magic).
unsafe fn thrown(p: &[usize]) -> String {
// SAFETY: the throw's ThrowInfo, its RVAs relative to `p[3]`: catchable
// type array at +12 (count, then type RVAs), each type's descriptor at
// +4, whose decorated name starts at +16; the object is at `p[1]`.
unsafe {
let rva = |at: usize| (at as *const u32).read_unaligned() as usize;
let types = p[3] + rva(p[2] + 12);
let name = |i: usize| {
let descriptor = p[3] + rva(p[3] + rva(types + 4 + 4 * i) + 4);
std::ffi::CStr::from_ptr((descriptor + 16) as *const std::ffi::c_char)
.to_string_lossy()
};
let first = name(0);
let value = match &*first {
// int, unsigned, long (HRESULT), unsigned long
".H" | ".I" | ".J" | ".K" if p[1] != 0 => {
format!(" = {:#010x}", (p[1] as *const u32).read_unaligned())
}
// std::exception keeps its message after the table pointer.
_ if (0..rva(types)).any(|i| name(i) == ".?AVexception@std@@") => {
let message = (p[1] as *const *const std::ffi::c_char).add(1).read();
if message.is_null() {
String::new()
} else {
format!(": {}", std::ffi::CStr::from_ptr(message).to_string_lossy())
}
}
_ => String::new(),
};
format!("{first}{value}")
}
}
/// # Safety
/// See [`report_unhandled`].
unsafe fn report(what: &str, info: *const EXCEPTION_POINTERS, to_file: bool) {
// SAFETY: the system passes valid exception pointers.
let (record, context) = unsafe { (&*(*info).ExceptionRecord, &*(*info).ContextRecord) };
let code = record.ExceptionCode;
let at = record.ExceptionAddress as usize;
let access = if code == EXCEPTION_ACCESS_VIOLATION {
let kind = match record.ExceptionInformation[0] {
let p = record.ExceptionInformation;
let detail = if code == EXCEPTION_ACCESS_VIOLATION {
let kind = match p[0] {
0 => "read",
1 => "write",
_ => "execute",
};
format!(" ({kind} {:#x})", record.ExceptionInformation[1])
format!(" ({kind} {:#x})", p[1])
} else if code == CPP_EXCEPTION && record.NumberParameters >= 4 && p[0] == CPP_MAGIC {
// SAFETY: a live MSVC throw.
format!(" (C++ {} thrown)", unsafe { thrown(&p) })
} else {
String::new()
};
eprintln!(
"VIctory: exception {:#010x} at {}{access}",
// Printed line by line (a fault while unwinding must not lose the
// lines before it), and kept for the file.
let mut text = String::new();
let mut line = |l: String| {
eprintln!("{l}");
text.push_str(&l);
text.push('\n');
};
line(format!(
"VIctory: {what} {:#010x} at {}{detail}",
code as u32,
locate(at)
);
));
line(format!(
" rax {:#x} rbx {:#x} rcx {:#x} rdx {:#x} rsi {:#x} rdi {:#x} rsp {:#x} rbp {:#x}",
context.Rax,
context.Rbx,
context.Rcx,
context.Rdx,
context.Rsi,
context.Rdi,
context.Rsp,
context.Rbp
));
line(format!(
" r8 {:#x} r9 {:#x} r10 {:#x} r11 {:#x} r12 {:#x} r13 {:#x} r14 {:#x} r15 {:#x}",
context.R8,
context.R9,
context.R10,
context.R11,
context.R12,
context.R13,
context.R14,
context.R15
));
for (i, pc) in unwind(*context).into_iter().enumerate() {
line(format!(" #{i:<2} {}", locate(pc as usize)));
}
if to_file {
let said = title_output();
eprint!("{said}");
text.push_str(&said);
append_to_log(&text);
}
#[cfg(feature = "diagnostics")]
for (address, len, file) in SAVE.get().into_iter().flatten() {
// SAFETY: the caller of `save_on_crash` named readable memory.
let bytes = unsafe { std::slice::from_raw_parts(*address as *const u8, *len) };
let saved = std::fs::write(file, bytes);
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
" saved {address:#x}+{len:#x} to {} ({saved:?})",
file.display()
);
// 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);
}
}
/// Return addresses of the faulting thread's frames, from the faulting
/// instruction up, by the unwind data of each image (the Windows loader
/// registered it for title images too). Code without unwind data (our
/// thunks, leaf functions) is taken to have its return address at `rsp`.
fn unwind(context: CONTEXT) -> Vec<u64> {
let (mut low, mut high) = (0, 0);
// SAFETY: writes the current thread's stack bounds.
unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) };
let mut frames = Vec::with_capacity(MAX_FRAMES);
unwind_into(context, low, high, &mut frames);
frames
}
/// [`unwind`] for any thread of the process, its stack being `low..high`;
/// pushes no more than `MAX_FRAMES`, so it does not allocate when `frames`
/// has that capacity (another thread may be suspended holding the heap).
pub(crate) fn unwind_into(mut context: CONTEXT, low: usize, high: usize, frames: &mut Vec<u64>) {
frames.push(context.Rip);
while frames.len() < MAX_FRAMES {
// Stop where reading the stack would fault inside this handler.
let rsp = context.Rsp as usize;
if rsp < low || rsp + 8 > high {
break;
}
let mut image = 0;
// SAFETY: looks up the function table entry covering `Rip`, if any.
let entry = unsafe { RtlLookupFunctionEntry(context.Rip, &mut image, null_mut()) };
if entry.is_null() {
// SAFETY: `rsp` is inside this thread's stack.
context.Rip = unsafe { (rsp as *const u64).read() };
context.Rsp += 8;
} else {
let (mut data, mut frame) = (null_mut(), 0);
// SAFETY: `entry` belongs to `image`; the context is our copy.
unsafe {
RtlVirtualUnwind(
UNW_FLAG_NHANDLER,
image,
context.Rip,
entry,
&mut context,
&mut data,
&mut frame,
null_mut(),
)
};
}
if context.Rip == 0 {
break;
}
frames.push(context.Rip);
}
EXCEPTION_CONTINUE_SEARCH
}
/// `module+rva`, or the bare address.
@@ -99,3 +352,32 @@ fn module_of(address: usize) -> Option<String> {
let name = path.rsplit('\\').next().unwrap_or(&path);
Some(format!("{name}+{:#x}", address - module as usize))
}
#[cfg(test)]
mod tests {
use super::*;
use windows_sys::Win32::System::Diagnostics::Debug::{
RtlCaptureContext, RtlCaptureStackBackTrace,
};
#[test]
#[inline(never)]
fn unwinds_like_the_system_walk() {
// SAFETY: zeroed CONTEXT is valid; both calls write our buffers.
let (frames, walked) = unsafe {
let mut context: CONTEXT = std::mem::zeroed();
RtlCaptureContext(&mut context);
let mut walked = [null_mut(); 8];
let n = RtlCaptureStackBackTrace(0, 8, walked.as_mut_ptr(), null_mut());
(unwind(context), walked[..usize::from(n)].to_vec())
};
// Frame 0 differs (two call sites in this function); callers agree.
assert!(walked.len() >= 4, "{walked:?}");
let ours: Vec<_> = frames[1..walked.len()]
.iter()
.map(|&f| f as usize)
.collect();
let system: Vec<_> = walked[1..].iter().map(|&f| f as usize).collect();
assert_eq!(ours, system);
}
}
+11 -1
View File
@@ -25,6 +25,8 @@
mod crash;
pub mod prepare;
pub mod resolve;
#[cfg(all(windows, feature = "diagnostics"))]
mod stacks;
#[cfg(windows)]
mod threads;
#[cfg(windows)]
@@ -35,9 +37,15 @@ mod tls;
mod windows;
#[cfg(windows)]
pub use crash::{locate, report_crashes};
pub use crash::{
locate, log_crash, log_crashes_to, note_title_output, report_crashes, report_unhandled,
};
#[cfg(all(windows, feature = "diagnostics"))]
pub use crash::save_on_crash;
pub use prepare::{PrepareError, PreparedImage, prepare};
pub use resolve::{ImportResolver, Provenance, Resolution};
#[cfg(all(windows, feature = "diagnostics"))]
pub use stacks::{dump_stacks, dump_stacks_on_schedule};
#[cfg(windows)]
pub use threads::disable_thread_calls;
#[cfg(windows)]
@@ -49,3 +57,5 @@ pub use windows::{
/// `DLL_PROCESS_ATTACH`, for TLS callbacks.
pub const DLL_PROCESS_ATTACH: u32 = 1;
/// `DLL_PROCESS_DETACH`.
pub const DLL_PROCESS_DETACH: u32 = 0;
+224
View File
@@ -0,0 +1,224 @@
//! Where every thread is: `VICTORY_STACKS=<seconds>[,<seconds>...]` prints
//! each thread's unwound stack as `module+rva` that many seconds after
//! [`dump_stacks_on_schedule`], to find what a title waits on.
use std::ffi::c_void;
use windows_sys::Wdk::System::Threading::{
NtQueryInformationThread, ThreadBasicInformation, ThreadQuerySetWin32StartAddress,
};
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE, LocalFree};
use windows_sys::Win32::System::Diagnostics::Debug::{
CONTEXT, CONTEXT_FULL_AMD64, GetThreadContext,
};
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
};
use windows_sys::Win32::System::Threading::{
GetCurrentProcessId, GetCurrentThreadId, GetThreadDescription, OpenThread, ResumeThread,
SuspendThread, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION, THREAD_SUSPEND_RESUME,
};
use crate::crash::{MAX_FRAMES, locate, unwind_into};
/// Reads `VICTORY_STACKS` and, if set, starts a thread that prints every
/// thread's stack at each listed time (seconds from now).
pub fn dump_stacks_on_schedule() {
let Ok(list) = std::env::var("VICTORY_STACKS") else {
return;
};
let mut times: Vec<f64> = list
.split(',')
.filter_map(|t| t.trim().parse().ok())
.collect();
times.sort_by(f64::total_cmp);
let start = std::time::Instant::now();
std::thread::spawn(move || {
for t in times {
let at = std::time::Duration::from_secs_f64(t.max(0.0));
std::thread::sleep(at.saturating_sub(start.elapsed()));
dump_stacks();
}
});
}
/// `THREAD_BASIC_INFORMATION` (ntddk).
#[repr(C)]
struct BasicInfo {
exit_status: i32,
teb: *const usize,
client_id: [usize; 2],
affinity: usize,
priority: i32,
base_priority: i32,
}
/// `GetThreadContext` wants a 16-byte aligned context.
#[repr(C, align(16))]
struct Aligned(CONTEXT);
/// Prints every other thread's stack to stderr. Each thread is suspended
/// only while its context is read and unwound into a buffer allocated
/// beforehand (it may hold the heap lock).
pub fn dump_stacks() {
// SAFETY: plain queries and a snapshot of this process's threads.
let (me, process, snapshot) = unsafe {
(
GetCurrentThreadId(),
GetCurrentProcessId(),
CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0),
)
};
if snapshot == INVALID_HANDLE_VALUE {
return;
}
let mut ids = Vec::new();
// SAFETY: zeroed is a valid THREADENTRY32; its size is set before use.
let mut entry: THREADENTRY32 = unsafe { std::mem::zeroed() };
entry.dwSize = size_of::<THREADENTRY32>() as u32;
// SAFETY: `snapshot` is open; `entry` is sized.
let mut more = unsafe { Thread32First(snapshot, &mut entry) } != 0;
while more {
if entry.th32OwnerProcessID == process && entry.th32ThreadID != me {
ids.push(entry.th32ThreadID);
}
// SAFETY: as above.
more = unsafe { Thread32Next(snapshot, &mut entry) } != 0;
}
// SAFETY: we opened it.
unsafe { CloseHandle(snapshot) };
eprintln!("VIctory: stacks of {} threads", ids.len());
for id in ids {
// SAFETY: opens a thread of our own process.
let thread = unsafe {
OpenThread(
THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION,
0,
id,
)
};
if thread.is_null() {
continue;
}
let (frames, (priority, base)) = frames_of(thread);
eprintln!(
" thread {id} \"{}\" start {} priority {priority} (base {base})",
name_of(thread),
locate(start_of(thread))
);
for (i, pc) in frames.into_iter().enumerate() {
eprintln!(" #{i:<2} {}", locate(pc as usize));
}
// SAFETY: we opened it.
unsafe { CloseHandle(thread) };
}
}
/// The thread's frames and its current and base scheduling priority (0-31).
fn frames_of(thread: HANDLE) -> (Vec<u64>, (i32, i32)) {
let mut frames = Vec::with_capacity(MAX_FRAMES);
let mut info: BasicInfo = BasicInfo {
exit_status: 0,
teb: std::ptr::null(),
client_id: [0; 2],
affinity: 0,
priority: 0,
base_priority: 0,
};
// SAFETY: writes `info`, whose layout and size are the system's.
let status = unsafe {
NtQueryInformationThread(
thread,
ThreadBasicInformation,
(&raw mut info).cast(),
size_of::<BasicInfo>() as u32,
std::ptr::null_mut(),
)
};
if status != 0 || info.teb.is_null() {
return (frames, (0, 0));
}
// SAFETY: the TEB of a live thread of this process: its NT_TIB holds
// the stack base at +8 and the stack limit at +0x10.
let (high, low) = unsafe { (info.teb.add(1).read(), info.teb.add(2).read()) };
// SAFETY: zeroed is a valid CONTEXT.
let mut context = Aligned(unsafe { std::mem::zeroed() });
context.0.ContextFlags = CONTEXT_FULL_AMD64;
// SAFETY: suspends, reads and resumes a thread that is not this one;
// nothing between suspend and resume allocates or takes a lock the
// thread could hold besides the unwinder's own.
unsafe {
if SuspendThread(thread) == u32::MAX {
return (frames, (info.priority, info.base_priority));
}
if GetThreadContext(thread, &mut context.0) != 0 {
unwind_into(context.0, low, high, &mut frames);
}
ResumeThread(thread);
}
(frames, (info.priority, info.base_priority))
}
fn start_of(thread: HANDLE) -> usize {
let mut start = 0usize;
// SAFETY: writes one pointer-sized start address.
unsafe {
NtQueryInformationThread(
thread,
ThreadQuerySetWin32StartAddress,
(&raw mut start).cast(),
size_of::<usize>() as u32,
std::ptr::null_mut(),
)
};
start
}
fn name_of(thread: HANDLE) -> String {
let mut name = std::ptr::null_mut();
// SAFETY: the system allocates the string; we free it with LocalFree.
unsafe {
if GetThreadDescription(thread, &mut name) < 0 || name.is_null() {
return String::new();
}
let len = (0..).take_while(|&i| *name.add(i) != 0).count();
let text = String::from_utf16_lossy(std::slice::from_raw_parts(name, len));
LocalFree(name.cast::<c_void>());
text
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn another_threads_stack_unwinds_to_its_start() {
let (tx, rx) = std::sync::mpsc::channel();
let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>();
let parked = std::thread::spawn(move || {
// SAFETY: plain query.
tx.send(unsafe { GetCurrentThreadId() }).unwrap();
stop_rx.recv().ok();
});
let id = rx.recv().unwrap();
// SAFETY: a thread of this process.
let thread = unsafe {
OpenThread(
THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION,
0,
id,
)
};
assert!(!thread.is_null());
let (frames, _) = frames_of(thread);
// Waiting in the kernel, several frames down from the thread start.
assert!(frames.len() >= 3, "{frames:?}");
assert!(start_of(thread) != 0);
// SAFETY: opened above.
unsafe { CloseHandle(thread) };
dump_stacks();
stop_tx.send(()).unwrap();
parked.join().unwrap();
}
}
+262 -17
View File
@@ -6,9 +6,11 @@
//! callbacks, then a DLL's `DllMain`.
use std::ffi::c_void;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use crate::LoadedImage;
use crate::{DLL_PROCESS_DETACH, LoadedImage};
const DLL_THREAD_ATTACH: u32 = 2;
const DLL_THREAD_DETACH: u32 = 3;
@@ -41,9 +43,143 @@ pub(crate) fn mapped(image: &LoadedImage) {
});
}
/// Its `DLL_PROCESS_ATTACH` is done. The list keeps attach order, which is
/// the Windows loader's initialisation order.
pub(crate) fn attached(base: usize) {
if let Some(m) = images().iter_mut().find(|m| m.image.base() == base) {
let mut images = images();
if let Some(i) = images.iter().position(|m| m.image.base() == base) {
let mut m = images.remove(i);
m.attached = true;
images.push(m);
}
static AT_EXIT: std::sync::Once = std::sync::Once::new();
// Registered before the title's own exit functions, so it runs after
// them, as `ExitProcess` follows `exit`'s functions on Windows.
// SAFETY: registers a function with the host CRT's exit table.
AT_EXIT.call_once(|| unsafe {
atexit(detach_all);
});
}
pub(crate) fn detached(base: usize) {
if let Some(m) = images().iter_mut().find(|m| m.image.base() == base) {
m.attached = false;
}
}
unsafe extern "C" {
fn atexit(f: extern "C" fn()) -> i32;
}
/// Set once the process is ending: no more thread notices.
static EXITING: AtomicBool = AtomicBool::new(false);
/// How long title images may take to detach before the process ends anyway
/// (a thread ended while holding a lock their detach code wants).
const DETACH_DEADLINE: Duration = Duration::from_secs(5);
/// Process exit (the CRT's `exit`, which titles call), in `ExitProcess`'s
/// order: the title's exit functions have run; every other thread ends
/// (title threads and ours); every attached image gets
/// `DLL_PROCESS_DETACH`, DLLs in reverse initialisation order, then the
/// exe's TLS callbacks; then the CRT ends the process.
extern "C" fn detach_all() {
let attached: Vec<_> = images()
.iter_mut()
.filter(|m| m.attached)
.map(|m| {
m.attached = false;
m.image.clone()
})
.collect();
let (dlls, exes): (Vec<_>, Vec<_>) =
attached.into_iter().rev().partition(|i| i.info().is_dll());
tracing::info!(
images = dlls.len() + exes.len(),
"process exit: ending other threads, detaching title images"
);
EXITING.store(true, Ordering::SeqCst);
end_other_threads();
// As on Windows, a lock a thread held when it ended stays taken; detach
// code that waits for one would hang the exit.
std::thread::spawn(|| {
std::thread::sleep(DETACH_DEADLINE);
tracing::warn!("process exit: title images did not detach in time; ending");
// SAFETY: ends this process, which is exiting anyway.
unsafe {
windows_sys::Win32::System::Threading::TerminateProcess(
windows_sys::Win32::System::Threading::GetCurrentProcess(),
1,
)
};
});
for image in dlls.iter().chain(&exes) {
// SAFETY: attached images are bound. A non-null third argument
// tells the entry points the process is ending.
unsafe {
image.notify(
DLL_PROCESS_DETACH,
true,
std::ptr::without_provenance_mut(1),
)
};
}
}
/// Ends every thread of the process but this one (and the ones started
/// while doing so), as `ExitProcess` does first; except the system's
/// thread-pool workers, which `TerminateThread` refuses (the process fails
/// fast) and which run no title code (no title image uses that pool).
fn end_other_threads() {
use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
};
use windows_sys::Win32::System::Threading::{
GetCurrentProcessId, GetCurrentThreadId, OpenThread, THREAD_TERMINATE, TerminateThread,
THREAD_QUERY_INFORMATION,
};
// SAFETY: plain queries of the calling process and thread.
let (process, me) = unsafe { (GetCurrentProcessId(), GetCurrentThreadId()) };
let mut ended = std::collections::HashSet::new();
loop {
// SAFETY: a snapshot of every thread, walked with a sized entry.
let others: Vec<u32> = unsafe {
let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if snapshot == INVALID_HANDLE_VALUE {
break;
}
let mut entry = THREADENTRY32 {
dwSize: size_of::<THREADENTRY32>() as u32,
..std::mem::zeroed()
};
let mut ids = Vec::new();
let mut more = Thread32First(snapshot, &mut entry) != 0;
while more {
if entry.th32OwnerProcessID == process && entry.th32ThreadID != me {
ids.push(entry.th32ThreadID);
}
more = Thread32Next(snapshot, &mut entry) != 0;
}
CloseHandle(snapshot);
ids
};
let new: Vec<u32> = others.into_iter().filter(|id| ended.insert(*id)).collect();
if new.is_empty() {
break;
}
for id in new {
// SAFETY: a thread of this process, which is exiting.
unsafe {
let thread = OpenThread(THREAD_TERMINATE | THREAD_QUERY_INFORMATION, 0, id);
if !thread.is_null() {
if !starts_in(thread, c"ntdll.dll") {
TerminateThread(thread, 0);
}
CloseHandle(thread);
}
}
}
}
}
@@ -71,65 +207,174 @@ pub fn disable_thread_calls(base: usize) -> Option<bool> {
static ON_THREAD: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = on_thread;
unsafe extern "system" fn on_thread(_: *mut c_void, reason: u32, _: *mut c_void) {
if reason != DLL_THREAD_ATTACH && reason != DLL_THREAD_DETACH || started_by_rust() {
if reason != DLL_THREAD_ATTACH && reason != DLL_THREAD_DETACH {
return;
}
if EXITING.load(Ordering::SeqCst) {
return; // our exit watchdog, or threads ending with the process
}
// A snapshot: title code may map and attach another DLL from here.
let notify: Vec<_> = images()
.iter()
.filter(|m| m.attached)
.map(|m| (m.image.clone(), !m.quiet))
.collect();
if notify.is_empty() {
return;
}
// Rust's std sets its threads up after this callback and aborts the
// process if their per-thread state was touched first (the current
// thread's id, which our logging asks for when title code calls us).
// That state is put back as the thread started.
let saved = (reason == DLL_THREAD_ATTACH && started_by_rust()).then(OwnTls::save);
// Starts in load order, ends in reverse, as the Windows loader does.
let notify_one = |(image, dll_main): &(Arc<LoadedImage>, bool)| {
// SAFETY: attached images have their imports bound.
unsafe { image.notify(reason, *dll_main) };
unsafe { image.notify(reason, *dll_main, std::ptr::null_mut()) };
};
if reason == DLL_THREAD_ATTACH {
notify.iter().for_each(notify_one);
} else {
notify.iter().rev().for_each(notify_one);
}
if let Some(saved) = saved {
saved.restore();
}
}
/// Our own image's static TLS block on this thread (Rust's std keeps its
/// per-thread state there), as copied before title code ran.
struct OwnTls {
block: *mut u8,
saved: Vec<u8>,
}
/// The TLS directory the linker emits for our image (the CRT's symbol).
#[repr(C)]
struct TlsDirectory {
start: usize,
end: usize,
index: *const u32,
callbacks: usize,
zero_fill: u32,
characteristics: u32,
}
unsafe extern "C" {
static _tls_used: TlsDirectory;
}
impl OwnTls {
fn save() -> OwnTls {
let array: *const *mut u8;
// SAFETY: reads TEB.ThreadLocalStoragePointer; the directory is our
// image's, and Windows set up its block on this thread before
// calling TLS callbacks.
let (block, len) = unsafe {
std::arch::asm!("mov {}, gs:[0x58]", out(reg) array, options(nostack, readonly));
let dir = &raw const _tls_used;
let block = *array.add((*dir).index.read() as usize);
(block, (*dir).end - (*dir).start + (*dir).zero_fill as usize)
};
// SAFETY: the block is `len` bytes, live for the thread's life.
let saved = unsafe { std::slice::from_raw_parts(block, len) }.to_vec();
OwnTls { block, saved }
}
fn restore(self) {
// SAFETY: the same block on the same thread, no reference to it held.
unsafe { std::ptr::copy_nonoverlapping(self.saved.as_ptr(), self.block, self.saved.len()) };
}
}
/// Whether Rust's std started this thread (its start routine is in our
/// exe): the title's main thread and our runtime's workers. They get no
/// notices: std aborts the process if anything on such a thread asks for
/// the current thread (as stdout and stderr locks do) before its start
/// routine has run, and title code may call our runtime, which logs.
// shortcut: title code on our workers (xasync callbacks) runs without
// thread notices; send them from the worker's start if a title needs them.
/// exe): the title's main thread and our runtime's workers, which run
/// title callbacks.
fn started_by_rust() -> bool {
// SAFETY: the calling thread's pseudo handle.
starts_in(unsafe { windows_sys::Win32::System::Threading::GetCurrentThread() }, c"")
}
/// Whether `thread`'s start routine lies in the module named `module`
/// (empty: our exe).
fn starts_in(thread: windows_sys::Win32::Foundation::HANDLE, module: &std::ffi::CStr) -> bool {
use windows_sys::Wdk::System::Threading::{
NtQueryInformationThread, ThreadQuerySetWin32StartAddress,
};
use windows_sys::Win32::System::LibraryLoader::{
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
GetModuleHandleExW, GetModuleHandleW,
GetModuleHandleA, GetModuleHandleExW,
};
use windows_sys::Win32::System::Threading::GetCurrentThread;
let mut start = 0usize;
// SAFETY: writes one pointer-sized start address.
let status = unsafe {
NtQueryInformationThread(
GetCurrentThread(),
thread,
ThreadQuerySetWin32StartAddress,
(&raw mut start).cast(),
size_of::<usize>() as u32,
std::ptr::null_mut(),
)
};
let mut module = std::ptr::null_mut();
let mut found = std::ptr::null_mut();
let name = if module.is_empty() {
std::ptr::null()
} else {
module.as_ptr().cast()
};
// SAFETY: looks up the module containing an address, taking no reference.
status == 0
&& unsafe {
GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
start as *const u16,
&mut module,
&mut found,
)
} != 0
// SAFETY: our own exe's handle.
&& module == unsafe { GetModuleHandleW(std::ptr::null()) }
// SAFETY: a module handle by name (or our exe's); no reference taken.
&& found == unsafe { GetModuleHandleA(name) }
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
/// In a child process of the next test: ends the other threads and
/// checks that a busy one stopped.
#[test]
fn exit_child() {
if std::env::var_os("VICTORY_EXIT_CHILD").is_none() {
return;
}
static TICKS: AtomicU64 = AtomicU64::new(0);
std::thread::spawn(|| {
loop {
TICKS.fetch_add(1, Ordering::SeqCst);
std::thread::yield_now();
}
});
while TICKS.load(Ordering::SeqCst) == 0 {
std::thread::yield_now();
}
super::end_other_threads();
let at = TICKS.load(Ordering::SeqCst);
std::thread::sleep(Duration::from_millis(50));
let ended = TICKS.load(Ordering::SeqCst) == at;
// The test harness's threads are gone too: leave at once.
println!("{}", if ended { "ENDED" } else { "STILL RUNNING" });
std::process::exit(0);
}
#[test]
fn exit_ends_the_other_threads_first() {
let out = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "threads::tests::exit_child", "--nocapture"])
.env("VICTORY_EXIT_CHILD", "1")
.output()
.unwrap();
let text = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success() && text.contains("ENDED"), "{text}");
}
}
+3 -2
View File
@@ -82,8 +82,9 @@ fn patch(code: &mut [u8], at: usize, thunks: usize) -> usize {
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.
// shortcut: a byte match, not a decode. In Grand Theft Auto VI all
// 53,246 hits are instruction starts and none is missed (checked
// against a full disassembly); decode .text if a title shows one.
if c[0] == 0x65
&& (rex == 0x48 || rex == 0x4C)
&& c[2] == 0x8B
+34 -7
View File
@@ -14,7 +14,10 @@ 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, prepare};
use crate::{
DLL_PROCESS_ATTACH, DLL_PROCESS_DETACH, ImportResolver, PreparedImage, Provenance, Resolution,
prepare,
};
/// A title image mapped into this process. A clone names the same mapping
/// (no reference of its own): unload one copy only.
@@ -308,13 +311,20 @@ impl LoadedImage {
/// # Safety
/// Runs title code. Imports must be bound first.
pub unsafe fn run_tls_callbacks(&self, reason: u32) {
// SAFETY: forwarded from the caller.
unsafe { self.tls_callbacks(reason, std::ptr::null_mut()) }
}
/// # Safety
/// See [`Self::run_tls_callbacks`].
unsafe fn tls_callbacks(&self, reason: u32, reserved: *mut c_void) {
let Some(tls) = &self.info.tls else { return };
for &rva in &tls.callback_rvas {
type TlsCallback = unsafe extern "system" fn(*mut c_void, u32, *mut c_void);
// SAFETY: the RVA came from the image's own TLS directory.
let callback: TlsCallback = unsafe { std::mem::transmute(self.base() + rva as usize) };
// SAFETY: the caller guarantees imports are bound.
unsafe { callback(self.module, reason, std::ptr::null_mut()) };
unsafe { callback(self.module, reason, reserved) };
}
}
@@ -327,22 +337,39 @@ impl LoadedImage {
/// depends on attached.
pub unsafe fn attach(&self) -> Result<()> {
// SAFETY: forwarded from the caller.
if unsafe { self.notify(DLL_PROCESS_ATTACH, true) } == Some(0) {
if unsafe { self.notify(DLL_PROCESS_ATTACH, true, std::ptr::null_mut()) } == Some(0) {
bail!("DllMain returned FALSE");
}
crate::threads::attached(self.base());
Ok(())
}
/// `DLL_PROCESS_DETACH` as `FreeLibrary` sends it (TLS callbacks, then
/// `DllMain`); the image hears of no more threads.
///
/// # Safety
/// Runs title code. The image must have been attached (or its attach
/// failed), and no other thread may be using it.
pub unsafe fn detach(&self) {
crate::threads::detached(self.base());
// SAFETY: forwarded from the caller.
unsafe { self.notify(DLL_PROCESS_DETACH, true, std::ptr::null_mut()) };
}
/// Runs the image's TLS callbacks with `reason`, then, if `dll_main` and
/// the image is a DLL with an entry point, its `DllMain`, whose result
/// is returned.
/// is returned. `reserved` is the entry points' third argument.
///
/// # Safety
/// Runs title code. Imports must be bound first.
pub(crate) unsafe fn notify(&self, reason: u32, dll_main: bool) -> Option<i32> {
pub(crate) unsafe fn notify(
&self,
reason: u32,
dll_main: bool,
reserved: *mut c_void,
) -> Option<i32> {
// SAFETY: forwarded from the caller.
unsafe { self.run_tls_callbacks(reason) };
unsafe { self.tls_callbacks(reason, reserved) };
if !dll_main || !self.info.is_dll() || self.info.entry_rva == 0 {
return None;
}
@@ -351,7 +378,7 @@ impl LoadedImage {
let main: DllMain =
unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) };
// SAFETY: forwarded from the caller.
Some(unsafe { main(self.module, reason, std::ptr::null_mut()) })
Some(unsafe { main(self.module, reason, reserved) })
}
/// Starts the title: on a new thread with the stack size from the image
+20 -2
View File
@@ -39,7 +39,10 @@ fn build_probe() -> PathBuf {
extern "system" fn fake_xgameruntime_initialize() -> i32 {
0x1234
}
/// Asks for the current thread, as our logging does: on a thread std is
/// still starting, that must not abort the process.
extern "system" fn fake_get_tick_count() -> u32 {
let _ = std::thread::current().id();
777
}
extern "system" fn fake_delayed() -> u32 {
@@ -192,8 +195,18 @@ fn loads_binds_and_calls_probe() {
image.attach().unwrap();
let f: extern "system" fn() -> u64 = std::mem::transmute(call("probe_thread_starts"));
let before = f();
// Starting in title code, as a title's threads do (ours start in
// our exe and are left out); the extra argument is ignored.
// A thread std starts, as our runtime's workers are: notified
// before std sets it up, which must still find its state pristine.
let worker = std::thread::Builder::new()
.name("probe-worker".into())
.spawn(|| std::thread::current().name().map(str::to_owned))
.unwrap();
assert_eq!(worker.join().unwrap().as_deref(), Some("probe-worker"));
let mid = f();
assert!(mid >> 32 > before >> 32 && mid as u32 > before as u32);
let before = mid;
// Starting in title code, as a title's threads do; the extra
// argument is ignored.
let start: unsafe extern "system" fn(*mut std::ffi::c_void) -> u32 =
std::mem::transmute(call("probe_pid"));
let thread = CreateThread(
@@ -223,6 +236,11 @@ fn loads_binds_and_calls_probe() {
);
assert_eq!(victory_loader::disable_thread_calls(1), None);
// `FreeLibrary`'s notice, as a failed late load sends it.
let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_detaches"));
assert_eq!(f(), 0);
image.detach();
assert_eq!(f(), 1);
image.unload();
}
}
+25
View File
@@ -11,5 +11,30 @@ publish.workspace = true
thiserror.workspace = true
miniz_oxide.workspace = true
[features]
# Host D3D12 pipeline checks (`emit::host`).
host = ["dep:windows"]
# Debugging switches (emitted-module dumps and the like).
diagnostics = []
[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = ["Win32_System_LibraryLoader"] }
windows = { workspace = true, optional = true, features = [
"Win32_Foundation",
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D12",
"Win32_Graphics_Dxgi",
"Win32_Graphics_Dxgi_Common",
] }
[target.'cfg(windows)'.dev-dependencies]
windows = { workspace = true, features = [
"Win32_Foundation",
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D12",
"Win32_Graphics_Dxgi",
"Win32_Graphics_Dxgi_Common",
] }
[lints]
workspace = true
+2
View File
@@ -22,6 +22,8 @@ impl FourCC {
pub const PSV0: FourCC = FourCC(*b"PSV0");
pub const ISG1: FourCC = FourCC(*b"ISG1");
pub const OSG1: FourCC = FourCC(*b"OSG1");
/// Per-primitive outputs of a mesh shader.
pub const PSG1: FourCC = FourCC(*b"PSG1");
pub const SFI0: FourCC = FourCC(*b"SFI0");
pub const HASH: FourCC = FourCC(*b"HASH");
pub const ILDB: FourCC = FourCC(*b"ILDB");
+986
View File
@@ -0,0 +1,986 @@
//! A DXIL module and its LLVM 3.7 bitcode, written with unabbreviated
//! records only (the format DXIL fixes; codes from LLVM's `LLVMBitCodes.h`).
//!
//! Values are symbolic while the module is built ([`V`]) and numbered when
//! it is written: functions, then constants (all at module level), then the
//! instructions of `main` in block order.
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub(crate) struct Ty(u32);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum TypeDef {
Void,
Int(u32),
Float,
/// Pointee and address space.
Ptr(Ty, u32),
Struct(Option<String>, Vec<Ty>),
Array(u32, Ty),
Func(Ty, Vec<Ty>),
}
/// A value: a global variable, a function, a module constant, or an
/// instruction result.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub(crate) enum V {
Global(u32),
Func(u32),
Const(u32),
Inst(u32),
}
/// A global variable declaration (thread-group shared memory).
struct Global {
name: String,
ty: Ty,
/// Its pointer type.
ptr: Ty,
space: u32,
/// An internal constant with this initialiser (a constant table).
init: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Const {
Int(i64),
Float(u32),
Undef,
Aggregate(Vec<u32>),
}
/// LLVM binary opcodes (the same codes serve the float forms).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Bin {
Add = 0,
Sub = 1,
Mul = 2,
UDiv = 3,
SDiv = 4,
URem = 5,
Shl = 7,
LShr = 8,
AShr = 9,
And = 10,
Or = 11,
Xor = 12,
}
/// `atomicrmw` operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Rmw {
Xchg = 0,
Add = 1,
Sub = 2,
And = 3,
Or = 5,
Xor = 6,
Max = 7,
Min = 8,
UMax = 9,
UMin = 10,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Cast {
Trunc = 0,
ZExt = 1,
SExt = 2,
FpToUi = 3,
FpToSi = 4,
UiToFp = 5,
SiToFp = 6,
Bitcast = 11,
}
/// Compare predicates: floats 0-15, integers 32-41.
pub(crate) mod pred {
pub const FALSE: u8 = 0;
pub const OEQ: u8 = 1;
pub const OGT: u8 = 2;
pub const OGE: u8 = 3;
pub const OLT: u8 = 4;
pub const OLE: u8 = 5;
pub const ONE: u8 = 6;
pub const ORD: u8 = 7;
pub const UNO: u8 = 8;
pub const UEQ: u8 = 9;
pub const UGT: u8 = 10;
pub const UGE: u8 = 11;
pub const ULT: u8 = 12;
pub const ULE: u8 = 13;
pub const UNE: u8 = 14;
pub const TRUE: u8 = 15;
pub const EQ: u8 = 32;
pub const NE: u8 = 33;
pub const IUGT: u8 = 34;
pub const IUGE: u8 = 35;
pub const IULT: u8 = 36;
pub const IULE: u8 = 37;
pub const SGT: u8 = 38;
pub const SGE: u8 = 39;
pub const SLT: u8 = 40;
pub const SLE: u8 = 41;
}
#[derive(Debug, Clone)]
enum Op {
Bin(Bin, V, V),
Cast(Cast, V),
Cmp(u8, V, V),
Select(V, V, V),
Extract(V, u32),
Call(u32, Vec<V>),
/// Filled in later: (value, block).
Phi(Vec<(V, usize)>),
/// `getelementptr` over the pointee type, from a pointer.
Gep(Ty, V, Vec<V>),
Load(V),
/// Pointer, value.
Store(V, V),
AtomicRmw(Rmw, V, V),
/// Pointer, expected, new; returns `{i32, i1}`.
CmpXchg(V, V, V),
}
#[derive(Debug, Clone)]
struct Inst {
ty: Ty,
op: Op,
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum Term {
Br(usize),
CondBr(V, usize, usize),
Ret,
}
#[derive(Debug, Clone, Default)]
struct Block {
phis: Vec<u32>,
body: Vec<u32>,
term: Option<Term>,
}
/// Function attributes of a `dx.op` declaration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Attr {
ReadNone = 1,
NoUnwind = 2,
ReadOnly = 3,
/// Barriers.
NoDuplicate = 4,
}
struct Func {
name: String,
ty: Ty,
attr: Option<Attr>,
body: bool,
}
/// A metadata node operand.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Md(u32);
enum MdDef {
Str(String),
Value(Ty, V),
Node(Vec<Option<Md>>),
}
#[derive(Default)]
pub(crate) struct Module {
types: Vec<TypeDef>,
type_ids: HashMap<TypeDef, u32>,
consts: Vec<(Ty, Const)>,
const_ids: HashMap<(Ty, Const), u32>,
globals: Vec<Global>,
funcs: Vec<Func>,
func_ids: HashMap<String, u32>,
insts: Vec<Inst>,
blocks: Vec<Block>,
mds: Vec<MdDef>,
named: Vec<(String, Vec<Md>)>,
}
impl Module {
fn ty(&mut self, def: TypeDef) -> Ty {
if let Some(&t) = self.type_ids.get(&def) {
return Ty(t);
}
let t = self.types.len() as u32;
self.types.push(def.clone());
self.type_ids.insert(def, t);
Ty(t)
}
pub fn void(&mut self) -> Ty {
self.ty(TypeDef::Void)
}
pub fn int(&mut self, bits: u32) -> Ty {
self.ty(TypeDef::Int(bits))
}
pub fn float(&mut self) -> Ty {
self.ty(TypeDef::Float)
}
pub fn ptr(&mut self, to: Ty) -> Ty {
self.ty(TypeDef::Ptr(to, 0))
}
pub fn ptr_in(&mut self, to: Ty, space: u32) -> Ty {
self.ty(TypeDef::Ptr(to, space))
}
pub fn array(&mut self, n: u32, of: Ty) -> Ty {
self.ty(TypeDef::Array(n, of))
}
pub fn named_struct(&mut self, name: &str, fields: Vec<Ty>) -> Ty {
self.ty(TypeDef::Struct(Some(name.into()), fields))
}
pub fn func_ty(&mut self, ret: Ty, params: Vec<Ty>) -> Ty {
self.ty(TypeDef::Func(ret, params))
}
fn is_void(&self, t: Ty) -> bool {
self.types[t.0 as usize] == TypeDef::Void
}
fn constant(&mut self, ty: Ty, c: Const) -> V {
if let Some(&i) = self.const_ids.get(&(ty, c.clone())) {
return V::Const(i);
}
let i = self.consts.len() as u32;
self.consts.push((ty, c.clone()));
self.const_ids.insert((ty, c), i);
V::Const(i)
}
pub fn int_const(&mut self, ty: Ty, v: i64) -> V {
self.constant(ty, Const::Int(v))
}
pub fn i32(&mut self, v: u32) -> V {
let t = self.int(32);
self.int_const(t, i64::from(v as i32))
}
pub fn i8(&mut self, v: u8) -> V {
let t = self.int(8);
self.int_const(t, i64::from(v as i8))
}
pub fn bool(&mut self, v: bool) -> V {
let t = self.int(1);
self.int_const(t, -i64::from(v))
}
pub fn f32(&mut self, bits: u32) -> V {
let t = self.float();
self.constant(t, Const::Float(bits))
}
pub fn undef(&mut self, ty: Ty) -> V {
self.constant(ty, Const::Undef)
}
/// A constant struct or array of constants.
pub fn aggregate(&mut self, ty: Ty, fields: &[V]) -> V {
let ids = fields
.iter()
.map(|f| match f {
V::Const(i) => *i,
_ => panic!("aggregate of a non-constant"),
})
.collect();
self.constant(ty, Const::Aggregate(ids))
}
/// Gives constant `old` the content of `new` (both stay valid).
pub fn replace_const(&mut self, old: V, new: V) {
if let (V::Const(o), V::Const(n)) = (old, new) {
self.consts[o as usize] = self.consts[n as usize].clone();
}
}
/// A function declaration (or `main` with `body`), found by name.
pub fn function(&mut self, name: &str, ty: Ty, attr: Option<Attr>, body: bool) -> V {
if let Some(&i) = self.func_ids.get(name) {
return V::Func(i);
}
let i = self.funcs.len() as u32;
self.funcs.push(Func {
name: name.into(),
ty,
attr,
body,
});
self.func_ids.insert(name.into(), i);
V::Func(i)
}
/// An external global of type `ty` in address space `space` (DXIL
/// declares thread-group shared memory this way).
pub fn global(&mut self, name: &str, ty: Ty, space: u32) -> V {
let ptr = self.ptr_in(ty, space);
self.globals.push(Global {
name: name.into(),
ty,
ptr,
space,
init: None,
});
V::Global(self.globals.len() as u32 - 1)
}
/// An internal constant global initialised with the constant `init`.
pub fn constant_global(&mut self, name: &str, init: V) -> V {
let V::Const(i) = init else {
panic!("a global initialised with a non-constant")
};
let ty = self.consts[i as usize].0;
let g = self.global(name, ty, 0);
if let V::Global(n) = g {
self.globals[n as usize].init = Some(i);
}
g
}
pub fn new_block(&mut self) -> usize {
self.blocks.push(Block::default());
self.blocks.len() - 1
}
pub fn type_of(&self, v: V) -> Ty {
match v {
V::Global(i) => self.globals[i as usize].ptr,
V::Const(i) => self.consts[i as usize].0,
V::Inst(i) => self.insts[i as usize].ty,
V::Func(i) => {
let t = self.funcs[i as usize].ty;
*self
.type_ids
.get(&TypeDef::Ptr(t, 0))
.map(|t| Ty(*t))
.as_ref()
.expect("function pointer type")
}
}
}
fn push(&mut self, block: usize, ty: Ty, op: Op) -> V {
let i = self.insts.len() as u32;
self.insts.push(Inst { ty, op });
// Terminators are kept apart, so a block can still grow at its end.
self.blocks[block].body.push(i);
V::Inst(i)
}
pub fn bin(&mut self, block: usize, op: Bin, a: V, b: V) -> V {
let ty = self.type_of(a);
self.push(block, ty, Op::Bin(op, a, b))
}
pub fn cast(&mut self, block: usize, op: Cast, v: V, to: Ty) -> V {
self.push(block, to, Op::Cast(op, v))
}
pub fn cmp(&mut self, block: usize, pred: u8, a: V, b: V) -> V {
let t = self.int(1);
self.push(block, t, Op::Cmp(pred, a, b))
}
pub fn select(&mut self, block: usize, c: V, t: V, f: V) -> V {
let ty = self.type_of(t);
self.push(block, ty, Op::Select(c, t, f))
}
pub fn extract(&mut self, block: usize, agg: V, index: u32) -> V {
let ty = match &self.types[self.type_of(agg).0 as usize] {
TypeDef::Struct(_, f) => f[index as usize],
TypeDef::Array(_, t) => *t,
t => panic!("extractvalue from {t:?}"),
};
self.push(block, ty, Op::Extract(agg, index))
}
pub fn call(&mut self, block: usize, f: V, args: Vec<V>) -> V {
let V::Func(i) = f else {
panic!("call of a non-function")
};
let TypeDef::Func(ret, _) = self.types[self.funcs[i as usize].ty.0 as usize] else {
unreachable!()
};
self.push(block, ret, Op::Call(i, args))
}
/// A phi at the top of `block`; incoming values come with [`Module::set_phi`].
pub fn phi(&mut self, block: usize, ty: Ty) -> V {
let i = self.insts.len() as u32;
self.insts.push(Inst {
ty,
op: Op::Phi(Vec::new()),
});
self.blocks[block].phis.push(i);
V::Inst(i)
}
/// The address of element `index` of the array `ptr` points to.
pub fn element(&mut self, block: usize, ptr: V, index: V) -> V {
let TypeDef::Ptr(arr, space) = self.types[self.type_of(ptr).0 as usize] else {
panic!("element of a non-pointer")
};
let TypeDef::Array(_, elem) = self.types[arr.0 as usize] else {
panic!("element of a non-array")
};
let ty = self.ptr_in(elem, space);
let zero = self.i32(0);
self.push(block, ty, Op::Gep(arr, ptr, vec![zero, index]))
}
pub fn load(&mut self, block: usize, ptr: V) -> V {
let TypeDef::Ptr(ty, _) = self.types[self.type_of(ptr).0 as usize] else {
panic!("load from a non-pointer")
};
self.push(block, ty, Op::Load(ptr))
}
pub fn store(&mut self, block: usize, ptr: V, value: V) {
let void = self.void();
self.push(block, void, Op::Store(ptr, value));
}
pub fn atomic(&mut self, block: usize, op: Rmw, ptr: V, value: V) -> V {
let ty = self.type_of(value);
self.push(block, ty, Op::AtomicRmw(op, ptr, value))
}
/// The old value of a compare-exchange.
pub fn cmpxchg(&mut self, block: usize, ptr: V, expected: V, new: V) -> V {
let (i32t, i1) = (self.type_of(new), self.int(1));
let pair = self.ty(TypeDef::Struct(None, vec![i32t, i1]));
let r = self.push(block, pair, Op::CmpXchg(ptr, expected, new));
self.extract(block, r, 0)
}
pub fn set_phi(&mut self, phi: V, incoming: Vec<(V, usize)>) {
let V::Inst(i) = phi else { panic!() };
self.insts[i as usize].op = Op::Phi(incoming);
}
pub fn terminate(&mut self, block: usize, t: Term) {
self.blocks[block].term = Some(t);
}
pub fn md_str(&mut self, s: &str) -> Md {
self.mds.push(MdDef::Str(s.into()));
Md(self.mds.len() as u32 - 1)
}
pub fn md_value(&mut self, v: V) -> Md {
let ty = self.type_of(v);
self.mds.push(MdDef::Value(ty, v));
Md(self.mds.len() as u32 - 1)
}
pub fn md_node(&mut self, ops: Vec<Option<Md>>) -> Md {
self.mds.push(MdDef::Node(ops));
Md(self.mds.len() as u32 - 1)
}
pub fn named_md(&mut self, name: &str, nodes: Vec<Md>) {
self.named.push((name.into(), nodes));
}
/// The module as bitcode.
pub fn write(&self) -> Vec<u8> {
let mut w = Writer::default();
w.bytes(b"BC\xC0\xDE");
w.enter(MODULE_BLOCK, 3);
w.record(1, &[1]); // VERSION: relative value ids
// Attribute groups 1-4 and one list per group.
w.enter(PARAMATTR_GROUP_BLOCK, 3);
for (id, kinds) in [
(1, &[18u64, 20][..]),
(2, &[18]),
(3, &[18, 21]),
(4, &[12, 18]),
] {
let mut r = vec![id, 0xFFFF_FFFF];
for &k in kinds {
r.extend([0, k]);
}
w.record(3, &r);
}
w.exit();
w.enter(PARAMATTR_BLOCK, 3);
for id in 1..=4 {
w.record(2, &[id]);
}
w.exit();
w.enter(TYPE_BLOCK, 4);
w.record(1, &[self.types.len() as u64]);
for t in &self.types {
match t {
TypeDef::Void => w.record(2, &[]),
TypeDef::Float => w.record(3, &[]),
TypeDef::Int(b) => w.record(7, &[u64::from(*b)]),
TypeDef::Ptr(p, space) => w.record(8, &[u64::from(p.0), u64::from(*space)]),
TypeDef::Array(n, e) => w.record(11, &[u64::from(*n), u64::from(e.0)]),
TypeDef::Struct(name, fields) => {
let mut r = vec![0];
r.extend(fields.iter().map(|f| u64::from(f.0)));
match name {
Some(n) => {
w.record(19, &chars(n));
w.record(20, &r);
}
None => w.record(18, &r),
}
}
TypeDef::Func(ret, params) => {
let mut r = vec![0, u64::from(ret.0)];
r.extend(params.iter().map(|p| u64::from(p.0)));
w.record(21, &r);
}
}
}
w.exit();
w.record(2, &chars("dxil-ms-dx"));
w.record(
3,
&chars(
"e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64",
),
);
let first_const = (self.globals.len() + self.funcs.len()) as u64;
for g in &self.globals {
// [type, address space << 2 | explicit type | constant, init id
// + 1, linkage (external 0, internal 3), log2 alignment + 1,
// section]
let (constant, init, linkage) = match g.init {
Some(i) => (1, first_const + u64::from(i) + 1, 3),
None => (0, 0, 0),
};
w.record(
7,
&[
u64::from(g.ty.0),
u64::from(g.space) << 2 | 2 | constant,
init,
linkage,
3,
0,
],
);
}
for f in &self.funcs {
// [type, cc, isproto, linkage, paramattr, align, section,
// visibility, gc, unnamed_addr, prologue, dllstorage, comdat, prefix]
let attr = f.attr.map_or(0, |a| a as u64);
w.record(
8,
&[
u64::from(f.ty.0),
0,
u64::from(!f.body),
0,
attr,
0,
0,
0,
0,
0,
0,
0,
0,
0,
],
);
}
// Value ids: globals, functions, constants, instructions.
let globals = self.globals.len() as u32;
let funcs = globals + self.funcs.len() as u32;
let const_id = |i: u32| u64::from(funcs + i);
w.enter(CONSTANTS_BLOCK, 4);
let mut current = None;
for (ty, c) in &self.consts {
if current != Some(*ty) {
w.record(1, &[u64::from(ty.0)]);
current = Some(*ty);
}
match c {
Const::Undef => w.record(3, &[]),
Const::Int(v) => w.record(4, &[signed(*v)]),
Const::Float(bits) => w.record(6, &[u64::from(*bits)]),
Const::Aggregate(ids) => {
let r: Vec<u64> = ids.iter().map(|&i| const_id(i)).collect();
w.record(7, &r);
}
}
}
w.exit();
// Phis nothing reads are left out (one register per phi makes many).
let mut live = vec![false; self.insts.len()];
let mark = |live: &mut Vec<bool>, v: V| {
if let V::Inst(i) = v
&& !live[i as usize]
{
live[i as usize] = true;
return true;
}
false
};
let operands = |op: &Op| -> Vec<V> {
match op {
Op::Bin(_, a, b) | Op::Cmp(_, a, b) | Op::Store(a, b) | Op::AtomicRmw(_, a, b) => {
vec![*a, *b]
}
Op::Cast(_, v) | Op::Extract(v, _) | Op::Load(v) => vec![*v],
Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => vec![*a, *b, *c],
Op::Call(_, args) => args.clone(),
Op::Phi(inc) => inc.iter().map(|x| x.0).collect(),
Op::Gep(_, p, idx) => std::iter::once(*p).chain(idx.iter().copied()).collect(),
}
};
for b in &self.blocks {
for &i in &b.body {
live[i as usize] = true;
}
if let Some(Term::CondBr(c, ..)) = b.term {
mark(&mut live, c);
}
}
let mut changed = true;
while changed {
changed = false;
for (i, inst) in self.insts.iter().enumerate() {
if live[i] {
for v in operands(&inst.op) {
changed |= mark(&mut live, v);
}
}
}
}
// Blocks are laid out in reverse postorder, so every block follows
// its forward predecessors (drivers take a branch to an earlier
// block for a loop's back edge).
let succs = |b: usize| match self.blocks[b].term {
Some(Term::Br(t)) => vec![t],
Some(Term::CondBr(_, t, f)) => vec![t, f],
_ => vec![],
};
let mut seen = vec![false; self.blocks.len()];
let mut post = Vec::new();
let mut stack = vec![(0usize, 0usize)];
seen[0] = true;
while let Some(top) = stack.last_mut() {
let (b, k) = *top;
top.1 += 1;
match succs(b).get(k) {
Some(&s) if !seen[s] => {
seen[s] = true;
stack.push((s, 0));
}
Some(_) => {}
None => {
post.push(b);
stack.pop();
}
}
}
post.reverse();
let mut pos = vec![u64::MAX; self.blocks.len()];
for (n, &b) in post.iter().enumerate() {
pos[b] = n as u64;
}
// An empty latch (only a branch back to its loop header) is folded
// into its one predecessor, so the exiting block is the latch as in
// DXC's loops; the AMD driver hangs on divergent loops otherwise.
let mut preds = vec![Vec::new(); self.blocks.len()];
for &b in &post {
for s in succs(b) {
preds[s].push(b);
}
}
let mut fold = vec![None; self.blocks.len()];
for &b in &post {
let blk = &self.blocks[b];
if let (Some(Term::Br(h)), true, [p]) = (
blk.term,
blk.phis.is_empty() && blk.body.is_empty(),
&preds[b][..],
) && pos[h] < pos[b]
&& !succs(*p).contains(&h)
{
fold[b] = Some((*p, h));
}
}
let layout: Vec<usize> = post.into_iter().filter(|&b| fold[b].is_none()).collect();
let mut pos = vec![u64::MAX; self.blocks.len()];
for (n, &b) in layout.iter().enumerate() {
pos[b] = n as u64;
}
// Branch targets and phi blocks through folded latches.
let target = |t: usize| fold[t].map_or(pos[t], |(_, h)| pos[h]);
let from = |b: usize| fold[b].map_or(pos[b], |(p, _)| pos[p]);
// Instruction value ids, in layout order.
let base = funcs + self.consts.len() as u32;
let mut ids = vec![u32::MAX; self.insts.len()];
let mut next = base;
for b in layout.iter().map(|&b| &self.blocks[b]) {
for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) {
if !self.is_void(self.insts[i as usize].ty) {
ids[i as usize] = next;
next += 1;
}
}
}
let abs = |v: V| -> u32 {
match v {
V::Global(i) => i,
V::Func(i) => globals + i,
V::Const(i) => funcs + i,
V::Inst(i) => {
let id = ids[i as usize];
assert_ne!(id, u32::MAX, "use of a void value");
id
}
}
};
w.enter(METADATA_BLOCK, 3);
for m in &self.mds {
match m {
MdDef::Str(s) => w.record(1, &chars(s)),
MdDef::Value(ty, v) => w.record(2, &[u64::from(ty.0), u64::from(abs(*v))]),
MdDef::Node(ops) => {
let r: Vec<u64> = ops
.iter()
.map(|o| o.map_or(0, |m| u64::from(m.0) + 1))
.collect();
w.record(3, &r);
}
}
}
for (name, nodes) in &self.named {
w.record(4, &chars(name));
let r: Vec<u64> = nodes.iter().map(|m| u64::from(m.0)).collect();
w.record(10, &r);
}
w.exit();
// The metadata kinds an LLVM 3.7 module declares, as DXC writes them.
w.enter(METADATA_BLOCK, 3);
for (id, kind) in [
"dbg",
"tbaa",
"prof",
"fpmath",
"range",
"tbaa.struct",
"invariant.load",
"alias.scope",
"noalias",
"nontemporal",
"llvm.mem.parallel_loop_access",
"nonnull",
"dereferenceable",
"dereferenceable_or_null",
]
.into_iter()
.enumerate()
{
let mut r = vec![id as u64];
r.extend(chars(kind));
w.record(6, &r);
}
w.exit();
w.enter(VALUE_SYMTAB_BLOCK, 4);
let names = self.globals.iter().map(|g| &g.name);
for (i, name) in names.chain(self.funcs.iter().map(|f| &f.name)).enumerate() {
let mut r = vec![i as u64];
r.extend(chars(name));
w.record(1, &r);
}
w.exit();
w.enter(FUNCTION_BLOCK, 4);
w.record(1, &[layout.len() as u64]);
let mut inst_id = base;
for b in layout.iter().map(|&b| &self.blocks[b]) {
for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) {
let inst = &self.insts[i as usize];
let rel = |v: V| {
let a = abs(v);
assert!(a < inst_id, "forward reference outside a phi");
u64::from(inst_id - a)
};
match &inst.op {
Op::Bin(op, a, b) => w.record(2, &[rel(*a), rel(*b), *op as u64]),
Op::Cast(op, v) => w.record(3, &[rel(*v), u64::from(inst.ty.0), *op as u64]),
Op::Cmp(p, a, b) => w.record(28, &[rel(*a), rel(*b), u64::from(*p)]),
Op::Select(c, t, f) => w.record(29, &[rel(*t), rel(*f), rel(*c)]),
Op::Extract(a, idx) => w.record(26, &[rel(*a), u64::from(*idx)]),
Op::Call(f, args) => {
let mut r = vec![0, 1 << 15, u64::from(self.funcs[*f as usize].ty.0)];
r.push(rel(V::Func(*f)));
r.extend(args.iter().map(|&a| rel(a)));
w.record(34, &r);
}
Op::Phi(incoming) => {
let mut r = vec![u64::from(inst.ty.0)];
for &(v, b) in incoming {
r.push(signed(i64::from(inst_id) - i64::from(abs(v))));
r.push(from(b));
}
w.record(16, &r);
}
Op::Gep(ty, p, idx) => {
let mut r = vec![0, u64::from(ty.0), rel(*p)];
r.extend(idx.iter().map(|&i| rel(i)));
w.record(43, &r);
}
// Alignment 4 (log2 + 1), not volatile.
Op::Load(p) => w.record(20, &[rel(*p), u64::from(inst.ty.0), 3, 0]),
Op::Store(p, v) => w.record(44, &[rel(*p), rel(*v), 3, 0]),
// Sequentially consistent, across threads.
Op::AtomicRmw(op, p, v) => {
w.record(38, &[rel(*p), rel(*v), *op as u64, 0, 6, 1])
}
Op::CmpXchg(p, c, n) => {
w.record(46, &[rel(*p), rel(*c), rel(*n), 0, 6, 1, 6, 0]);
}
}
if !self.is_void(inst.ty) {
inst_id += 1;
}
}
match b.term.expect("unterminated block") {
Term::Ret => w.record(10, &[]),
Term::Br(t) => w.record(11, &[target(t)]),
Term::CondBr(c, t, f) => {
let a = abs(c);
assert!(a < inst_id);
w.record(11, &[target(t), target(f), u64::from(inst_id - a)]);
}
}
}
w.exit();
w.exit();
w.finish()
}
}
const MODULE_BLOCK: u64 = 8;
const PARAMATTR_BLOCK: u64 = 9;
const PARAMATTR_GROUP_BLOCK: u64 = 10;
const CONSTANTS_BLOCK: u64 = 11;
const FUNCTION_BLOCK: u64 = 12;
const VALUE_SYMTAB_BLOCK: u64 = 14;
const METADATA_BLOCK: u64 = 15;
const TYPE_BLOCK: u64 = 17;
fn chars(s: &str) -> Vec<u64> {
s.bytes().map(u64::from).collect()
}
/// LLVM's signed VBR operand: magnitude shifted left, sign in bit 0.
fn signed(v: i64) -> u64 {
if v >= 0 {
(v as u64) << 1
} else {
(v.unsigned_abs() << 1) | 1
}
}
/// The bitstream: little-endian 32-bit words filled from bit 0.
#[derive(Default)]
struct Writer {
words: Vec<u32>,
cur: u64,
bits: u32,
/// Per open block: abbreviation width, index of its length word.
stack: Vec<(u32, usize)>,
}
impl Writer {
fn width(&self) -> u32 {
self.stack.last().map_or(2, |b| b.0)
}
fn emit(&mut self, v: u64, width: u32) {
debug_assert!(width == 64 || v >> width == 0);
self.cur |= v << self.bits;
self.bits += width;
while self.bits >= 32 {
self.words.push(self.cur as u32);
self.cur >>= 32;
self.bits -= 32;
}
}
fn vbr(&mut self, mut v: u64, width: u32) {
let hi = 1u64 << (width - 1);
while v >= hi {
self.emit(v & (hi - 1) | hi, width);
v >>= width - 1;
}
self.emit(v, width);
}
fn align(&mut self) {
if self.bits > 0 {
self.words.push(self.cur as u32);
self.cur = 0;
self.bits = 0;
}
}
fn bytes(&mut self, b: &[u8]) {
for &x in b {
self.emit(u64::from(x), 8);
}
}
fn enter(&mut self, id: u64, width: u32) {
self.emit(1, self.width()); // ENTER_SUBBLOCK
self.vbr(id, 8);
self.vbr(u64::from(width), 4);
self.align();
self.words.push(0);
self.stack.push((width, self.words.len()));
}
fn exit(&mut self) {
self.emit(0, self.width()); // END_BLOCK
self.align();
let (_, start) = self.stack.pop().expect("open block");
self.words[start - 1] = (self.words.len() - start) as u32;
}
/// An unabbreviated record.
fn record(&mut self, code: u64, ops: &[u64]) {
self.emit(3, self.width());
self.vbr(code, 6);
self.vbr(ops.len() as u64, 6);
for &o in ops {
self.vbr(o, 6);
}
}
fn finish(mut self) -> Vec<u8> {
self.align();
self.words.iter().flat_map(|w| w.to_le_bytes()).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn vbr_and_blocks() {
let mut w = Writer::default();
w.vbr(5, 6);
w.vbr(100, 6); // two chunks: 100 = 0b1100100 -> 0b100100 | 32, then 3
assert_eq!(w.cur, 5 | (0b10_0100 << 6) | (3 << 12));
let mut w = Writer::default();
w.enter(8, 3);
w.record(1, &[1]);
w.exit();
let bytes = w.finish();
// header word, length word, one record word, end word.
assert_eq!(bytes.len() % 4, 0);
assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), 1);
assert_eq!(signed(-3), 7);
assert_eq!(signed(2), 4);
}
}
+380
View File
@@ -0,0 +1,380 @@
//! The PC container around emitted DXIL: feature flags (`SFI0`), the
//! signatures (`ISG1`, `OSG1`), pipeline state validation (`PSV0`) and the
//! program (`DXIL`), laid out as validator version 1.6 lays them out, plus
//! the container hash that D3D12 checks.
/// One signature element: one row (D3D12 links stages by semantic).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SigElement {
pub name: String,
pub index: u32,
/// DXIL semantic kind (0 arbitrary, 1 vertex id, 3 position, 16 target...).
pub kind: u8,
/// DXIL component type (4 i32, 5 u32, 9 f32, 1 i1).
pub comp: u8,
/// DXIL interpolation mode (0 for none).
pub interp: u8,
/// Start row, if the element has a register.
pub row: Option<u32>,
pub col: u8,
pub cols: u8,
/// Components read (inputs) or written (outputs), relative to `col`.
pub usage: u8,
/// 16-bit on the console (declared 32-bit here).
pub half: bool,
}
impl SigElement {
fn system_value(&self) -> u32 {
match self.kind {
1 => 6, // vertex id
2 => 8, // instance id
3 => 1, // position
4 => 4, // render target array index
5 => 5, // viewport array index
6 => 2, // clip distance
7 => 3, // cull distance
10 => 7, // primitive id
12 => 10,
13 => 9, // front face
14 => 66,
15 => 70,
16 => 64, // target
17 => 65, // depth
18 => 68,
19 => 67,
20 => 69,
30 => 25, // cull primitive
_ => 0,
}
}
fn sig_comp(&self) -> u32 {
match self.comp {
1 | 5 => 1, // bool and u32
4 => 2,
9 => 3,
_ => 0,
}
}
fn mask(&self) -> u8 {
((1u8 << self.cols) - 1) << self.col
}
}
/// `ISG1`/`OSG1`: 32-byte rows, then the names.
pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec<u8> {
let mut out = Vec::new();
out.extend((elements.len() as u32).to_le_bytes());
out.extend(8u32.to_le_bytes());
// Validator 1.6 writes one name per element in element order, repeats
// included, except that system values share theirs (it keys names by
// the semantic's string, which is one static string per system value);
// the rows sorted by register (unallocated last).
let mut offsets: Vec<u32> = Vec::new();
let mut next = 8 + 32 * elements.len() as u32;
let mut names = Vec::new();
for (i, e) in elements.iter().enumerate() {
let shared = (e.kind != 0)
.then(|| (0..i).find(|&j| elements[j].kind == e.kind))
.flatten();
match shared {
Some(j) => offsets.push(offsets[j]),
None => {
offsets.push(next);
next += e.name.len() as u32 + 1;
names.push(&e.name);
}
}
}
let mut order: Vec<usize> = (0..elements.len()).collect();
order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), elements[i].col));
for i in order {
let (e, offset) = (&elements[i], offsets[i]);
let used = e.usage << e.col;
let rw = if input { used } else { !used & 0xf };
for v in [
0,
offset,
e.index,
e.system_value(),
e.sig_comp(),
e.row.unwrap_or(u32::MAX),
] {
out.extend(v.to_le_bytes());
}
out.extend([e.mask(), rw, 0, 0]);
out.extend(0u32.to_le_bytes());
}
for name in names {
out.extend(name.as_bytes());
out.push(0);
}
out
}
/// A resource bound by register, as `PSV0` lists it.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Binding {
/// PSV resource type: 1 sampler, 2 CBV.
pub kind: u32,
pub space: u32,
pub register: u32,
/// DXIL resource kind (13 cbuffer, 14 sampler).
pub dxil_kind: u32,
}
pub(crate) struct Psv<'a> {
/// PSV shader kind: 0 pixel, 1 vertex, 5 compute.
pub stage: u8,
/// Vertex: writes `SV_Position`. Pixel: writes depth.
pub flag: bool,
pub inputs: &'a [SigElement],
pub outputs: &'a [SigElement],
/// Mesh: per-primitive outputs.
pub prims: &'a [SigElement],
/// Mesh: its state and the group-shared bytes it declares.
pub mesh: Option<(super::shader::Mesh, u32)>,
pub bindings: &'a [Binding],
/// Compute: thread-group size and required wave size.
pub threads: [u32; 3],
pub wave_size: Option<u32>,
}
/// `PSV0` with runtime info version 2 (validator 1.6).
pub(crate) fn psv(p: &Psv) -> Vec<u8> {
let vectors = |els: &[SigElement]| {
els.iter()
.filter_map(|e| e.row)
.map(|r| r + 1)
.max()
.unwrap_or(0)
};
let (in_vectors, out_vectors) = (vectors(p.inputs), vectors(p.outputs));
let mut out = Vec::new();
let u32s = |out: &mut Vec<u8>, vs: &[u32]| {
for v in vs {
out.extend(v.to_le_bytes());
}
};
u32s(&mut out, &[48]);
let mut info = [0u8; 48];
info[0] = u8::from(p.flag);
let (min, max) = p.wave_size.map_or((0, u32::MAX), |n| (n, n));
info[16..20].copy_from_slice(&min.to_le_bytes());
info[20..24].copy_from_slice(&max.to_le_bytes());
info[24] = p.stage;
for (k, n) in p.threads.into_iter().enumerate() {
info[36 + 4 * k..40 + 4 * k].copy_from_slice(&n.to_le_bytes());
}
info[28] = p.inputs.len() as u8;
info[29] = p.outputs.len() as u8;
info[31] = in_vectors as u8;
info[32] = out_vectors as u8;
if let Some((mesh, shared)) = p.mesh {
info[0..4].copy_from_slice(&shared.to_le_bytes());
info[12..14].copy_from_slice(&(mesh.max_vertices as u16).to_le_bytes());
info[14..16].copy_from_slice(&(mesh.max_primitives as u16).to_le_bytes());
info[26] = vectors(p.prims) as u8;
info[27] = mesh.topology;
info[30] = p.prims.len() as u8;
}
out.extend(info);
u32s(&mut out, &[p.bindings.len() as u32]);
if !p.bindings.is_empty() {
u32s(&mut out, &[24]);
for b in p.bindings {
u32s(
&mut out,
&[b.kind, b.space, b.register, b.register, b.dxil_kind, 0],
);
}
}
// Names of arbitrary semantics (system values use ""), then indices.
let mut strings = vec![0u8];
let mut indices: Vec<u32> = Vec::new();
let mut elements = Vec::new();
for e in p.inputs.iter().chain(p.outputs).chain(p.prims) {
let name = if e.kind == 0 {
let needle: Vec<u8> = e.name.bytes().chain([0]).collect();
match find(&strings, &needle) {
Some(at) => at,
None => {
strings.extend(&needle);
strings.len() - needle.len()
}
}
} else {
0
};
let index = match indices.iter().position(|&i| i == e.index) {
Some(at) => at,
None => {
indices.push(e.index);
indices.len() - 1
}
};
let (start, alloc) = match e.row {
Some(r) => (r as u8, 0x40 | (e.col << 4)),
None => (0, 0),
};
elements.push((name as u32, index as u32, start, e.cols | alloc, e));
}
strings.resize(strings.len().next_multiple_of(4), 0);
u32s(&mut out, &[strings.len() as u32]);
out.extend(&strings);
u32s(&mut out, &[indices.len() as u32]);
u32s(&mut out, &indices);
if !elements.is_empty() {
u32s(&mut out, &[16]);
for (name, index, start, cols, e) in elements {
u32s(&mut out, &[name, index]);
out.extend([1, start, cols, e.kind, e.sig_comp() as u8, e.interp, 0, 0]);
}
}
// Input-to-output dependencies, as the view-id state declares them:
// every output scalar on every input scalar.
if in_vectors > 0 && out_vectors > 0 {
let scalars = |els: &[SigElement]| {
els.iter()
.filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols)))
.max()
.unwrap_or(0)
};
let (ni, no) = (scalars(p.inputs), scalars(p.outputs));
let per = (out_vectors * 4).div_ceil(32);
for i in 0..in_vectors * 4 {
for k in 0..per {
let bits = if i < ni {
no.saturating_sub(32 * k).min(32)
} else {
0
};
let mask = if bits == 32 {
u32::MAX
} else {
(1u32 << bits) - 1
};
u32s(&mut out, &[mask]);
}
}
}
out
}
fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
hay.windows(needle.len()).position(|w| w == needle)
}
/// The container: parts in order, hashed.
pub(crate) fn build(parts: &[(&[u8; 4], &[u8])]) -> Vec<u8> {
let table = 0x20 + 4 * parts.len();
let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>();
let mut out = Vec::with_capacity(total);
out.extend(b"DXBC");
out.extend([0; 16]);
out.extend(1u16.to_le_bytes());
out.extend(0u16.to_le_bytes());
out.extend((total as u32).to_le_bytes());
out.extend((parts.len() as u32).to_le_bytes());
let mut offset = table;
for (_, d) in parts {
out.extend((offset as u32).to_le_bytes());
offset += 8 + d.len();
}
for (fourcc, d) in parts {
out.extend(*fourcc);
out.extend((d.len() as u32).to_le_bytes());
out.extend(*d);
}
let digest = hash(&out[20..]);
out[4..20].copy_from_slice(&digest);
out
}
/// The container hash D3D12 checks: MD5 whose last block carries the bit
/// count first and `2 × bytes + 1` last instead of standard padding.
pub(crate) fn hash(data: &[u8]) -> [u8; 16] {
let len = data.len();
let left = len % 64;
let mut tail = Vec::with_capacity(128);
if left < 56 {
tail.extend(((len as u32) << 3).to_le_bytes());
tail.extend(&data[len - left..]);
tail.push(0x80);
tail.resize(60, 0);
} else {
tail.extend(&data[len - left..]);
tail.push(0x80);
tail.resize(64, 0);
tail.extend(((len as u32) << 3).to_le_bytes());
tail.resize(124, 0);
}
tail.extend(((len as u32) << 1 | 1).to_le_bytes());
let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476];
for block in data[..len - left]
.as_chunks::<64>()
.0
.iter()
.chain(tail.as_chunks::<64>().0)
{
md5_block(&mut state, block);
}
let mut out = [0; 16];
for (o, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(state) {
o.copy_from_slice(&s.to_le_bytes());
}
out
}
fn md5_block(state: &mut [u32; 4], block: &[u8; 64]) {
const S: [u32; 16] = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
let x: Vec<u32> = block
.as_chunks::<4>()
.0
.iter()
.map(|c| u32::from_le_bytes(*c))
.collect();
let [mut a, mut b, mut c, mut d] = *state;
for i in 0..64 {
let (f, g) = match i / 16 {
0 => ((b & c) | (!b & d), i),
1 => ((d & b) | (!d & c), (5 * i + 1) % 16),
2 => (b ^ c ^ d, (3 * i + 5) % 16),
_ => (c ^ (b | !d), (7 * i) % 16),
};
let k = ((i as f64 + 1.0).sin().abs() * 4_294_967_296.0) as u32;
let rotated = a
.wrapping_add(f)
.wrapping_add(k)
.wrapping_add(x[g])
.rotate_left(S[(i / 16) * 4 + i % 4]);
(a, b, c, d) = (d, b.wrapping_add(rotated), b, c);
}
for (s, v) in state.iter_mut().zip([a, b, c, d]) {
*s = s.wrapping_add(v);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn md5_core_matches_the_standard() {
// Standard MD5 of "abc" with standard padding, through md5_block.
let mut block = b"abc".to_vec();
block.push(0x80);
block.resize(56, 0);
block.extend(24u64.to_le_bytes());
let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476];
md5_block(&mut state, block.as_slice().try_into().unwrap());
let hex: String = state
.iter()
.flat_map(|s| s.to_le_bytes())
.map(|b| format!("{b:02x}"))
.collect();
assert_eq!(hex, "900150983cd24fb0d6963f7d28e17f72");
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+452
View File
@@ -0,0 +1,452 @@
//! DXIL emission (decision 0003, step 3): a console vertex, pixel, compute
//! or mesh shader as a PC DXIL container (SM 6.6) that host D3D12 accepts.
//! Compute shaders keep the console's thread-group size; one that depends
//! on the lane layout (cross-lane operations) declares the console's wave
//! size (`WaveSize`), so the host device must support it.
//!
//! What the host binds for a translated shader ([`HostShader`]):
//!
//! * **User data** at `b0, space 0` (32-bit root constants or a constant
//! buffer, per stage): dword `index` holds a root parameter's value, as
//! [`UserData`] lists. A root-constant dword is the constant. A
//! descriptor table is the byte offset of its first descriptor in its
//! heap: the descriptor index times 32 for CBV/SRV/UAV tables, times 16
//! for sampler tables (the console's descriptor sizes; the code adds
//! offsets in those units). The heap bases of dynamic resources are 0
//! and not listed.
//! * **Descriptors** through SM 6.6 `ResourceDescriptorHeap[]` and
//! `SamplerDescriptorHeap[]`, at the index the console address gives, so
//! the host heaps keep the title's descriptor order. The root signature
//! needs `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and
//! `SAMPLER_HEAP_DIRECTLY_INDEXED`.
//! * **Immediate samplers** as static samplers `s<n>, space 0`, `n` the
//! position in [`HostShader::samplers`] (the console sampler words) and
//! [`HostShader::static_samplers`] (the same decoded into a D3D12 static
//! sampler description). Comparison sampling (added 2026-11-23): an
//! immediate sampler it uses has a comparison filter there (bit 0x80);
//! a heap sampler it uses must be a comparison sampler on the host.
//! * **Root CBVs and root SRVs** (raw buffers) as root descriptors
//! `b<i>` / `t<i>` in [`ROOT_CBV_SPACE`], `i` the title's root parameter
//! index ([`HostShader::root_cbvs`], [`HostShader::root_srvs`]); the
//! address the title sets is the buffer's.
//! * **Vertex fetch** (added 2026-11-23). Grand Theft Auto VI's mesh and
//! vertex programs fetch vertices themselves with typed-format loads
//! (`tbuffer_load_format_*`): the format (8_8_8_8 unorm, 16_16 snorm,
//! 2_10_10_10 unorm, 8_8_8_8 and 16_16_16_16 uint...) is in the
//! instruction, so the translation reads raw bytes and converts them
//! itself. Their descriptors are built around a root SRV (stride 1, no
//! record limit): the host binds the root SRV `t<slot>` above with the
//! address the title sets, nothing more. The vertex index, the stride
//! and the attribute offset are the shader's own arithmetic on data in
//! that buffer (per-stream headers), not descriptor fields.
//! * **Buffer views in the heap** are declared by how the shader reads
//! them: raw (ByteAddressBuffer) for dword loads and stores, atomics and
//! typed-format loads without an index; structured with the used-resource
//! entry's stride when indexed; typed with four 32-bit float channels for
//! `buffer_load_format_*` and `buffer_store_format_*`. The host's view at
//! that index must be of that kind and start at the console descriptor's
//! base address (raw: `R32_TYPELESS` with the raw flag), whatever kind the
//! title's view description says. Typed-format loads from heap
//! descriptors (1,024 world compute programs, ray-tracing material
//! resolves) read raw views this way.
//!
//! * **Texture atomics** (added 2026-11-23): a texture UAV the shader uses
//! atomically is declared a 32-bit unsigned single-channel view; the
//! host's view at that index must be an R32 integer view (64-bit atomics
//! stop the translation). Global loads from a root SRV read it raw.
//!
//! Entry points: [`translate`] (container bytes as the title passes them
//! at pipeline creation → [`HostShader`]), [`emit`] (the same with the
//! earlier stages already run). The root constants of each stage must
//! cover [`HostShader::user_data_dwords`]. Stability: these types and the
//! binding scheme are what pipeline creation builds on; changes are
//! announced.
//! * **Signatures** as the console container has them (same semantics,
//! registers and masks), so the input layout and stage linking are the
//! title's; pixel outputs are plain 32-bit values.
//! * **Mesh shaders** ([`HwStage::Ms`], `ms_6_6`): user data and
//! descriptors as above (the root constants visible to the mesh stage);
//! the pipeline is a mesh pipeline (pipeline-state stream, no input
//! layout) with the title's pixel shader. The thread group is the
//! console's in lanes (`[numthreads]` in the DXIL), the vertex and
//! primitive maxima its own, triangles only, no wave size required. The
//! console numbers groups in x only: the draw path passes the title's
//! count as `DispatchMesh(x, 1, 1)`. Per-primitive outputs (`PSG1`) are
//! the console's, without `SV_PrimitiveID` and `SV_CullPrimitive` (the
//! console never exports them).
mod bitcode;
mod container;
#[cfg(all(test, windows))]
mod diff_tests;
#[cfg(all(windows, any(test, feature = "host")))]
pub mod host;
mod lower;
mod sampler;
mod shader;
#[cfg(windows)]
pub mod validator;
mod wave;
use crate::dxbc::{Container, FourCC};
use crate::native::{HwStage, NativeProgram, RootType};
use crate::{ShaderError, io, ir, resource, structure};
pub use sampler::StaticSampler;
pub use shader::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE};
/// A translated shader and what the host binds for it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostShader {
pub stage: HwStage,
/// The DXIL container, hashed as D3D12 expects.
pub dxil: Vec<u8>,
/// The user-data dwords the shader reads.
pub user_data: Vec<UserData>,
/// Immediate samplers: the four sampler words of `s<n>`.
pub samplers: Vec<[u32; 4]>,
/// The same samplers decoded, `s<n>` at position n: the static sampler
/// descriptions the host's root signature declares.
pub static_samplers: Vec<StaticSampler>,
/// Root CBVs the shader reads: root parameter indices, each bound as
/// `b<index>` in [`ROOT_CBV_SPACE`].
pub root_cbvs: Vec<u8>,
/// Root SRVs (raw buffers) the shader reads: `t<index>` in
/// [`ROOT_CBV_SPACE`].
pub root_srvs: Vec<u8>,
}
impl HostShader {
/// Size of the user-data buffer the shader declares, in dwords (a
/// multiple of 4; 0 when it reads none). Root constants must cover it.
pub fn user_data_dwords(&self) -> u32 {
let n = self
.user_data
.iter()
.map(|u| u.index + 1)
.max()
.unwrap_or(0);
n.next_multiple_of(4)
}
}
/// One dword of user data and the root parameter that fills it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UserData {
/// Dword in the user-data buffer (the console's user-data index).
pub index: u32,
/// Root parameter index in the title's root signature.
pub slot: u8,
/// `Constants` or `Table` (see the module notes for the value).
pub root: RootType,
/// Dword within the parameter.
pub dword: u32,
}
/// Translates the vertex, pixel, compute or mesh program of a console
/// shader container.
pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> {
let c = Container::parse(container)?;
let dxil = c
.part(FourCC::DXIL)
.ok_or(ShaderError::Malformed("no DXIL part"))?;
let native = crate::native_programs(dxil.data)?
.into_iter()
.find(|p| {
matches!(
p.stage,
HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms
)
})
.ok_or(ShaderError::Unsupported {
offset: 0,
what: "a container without a vertex, pixel, compute or mesh program",
})?;
let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
let res = resource::track(&p, &native.layout, native.stage)?;
let io = io::raise(&p, &native)?;
let st = structure::structure(&p)?;
emit(&c, &native, &p, &st, &io, &res)
}
/// Emits a program whose earlier stages already ran.
pub fn emit(
c: &Container,
native: &NativeProgram,
p: &ir::Program,
st: &structure::Structured,
io: &io::Io,
res: &resource::Resources,
) -> Result<HostShader, ShaderError> {
let sig = |fourcc| -> Result<Vec<container::SigElement>, ShaderError> {
match c.part(fourcc) {
Some(part) => signature(part.data),
None => Ok(Vec::new()),
}
};
let pixel = native.stage == HwStage::Ps;
let mut inputs = sig(FourCC::ISG1)?;
let mut outputs = sig(FourCC::OSG1)?;
// Interpolation as DXC declares it by default; pixel inputs that are
// read get the mode their barycentrics say.
let interpolated = if pixel { &mut inputs } else { &mut outputs };
for e in interpolated {
e.interp = match (e.kind, e.comp) {
(3, _) => 4,
// Constant, as DXC declares it (the AMD compiler crashed on a
// front face without a mode).
(13, _) => 1,
(0 | 6 | 7, 9) => 2,
(0, _) => 1,
_ => 0,
};
}
// Per-primitive outputs are constant. The console never exports a
// primitive id or cull flag a mesh shader writes (it culls with the
// primitive export), so those rows are left out.
let mut prims = sig(FourCC::PSG1)?;
prims.retain(|e| !matches!(e.kind, 10 | 30));
for e in &mut prims {
e.interp = 1;
}
// A mesh group's id arrives multiplied by max(threads, vertices,
// primitives) (the code divides by that); the thread count is in PSV0
// from runtime info version 2 on.
// shortcut: older containers fall back to the group's lane count, right
// when the HLSL group fills its waves (Grand Theft Auto VI's do).
let mesh_stride = match &native.io {
crate::native::StageIo::Ms(ms) => {
let psv = c.part(FourCC::PSV0).map(|p| p.data);
let threads = psv
.filter(|d| crate::dxbc::u32_at(d, 0).is_ok_and(|n| n >= 48))
.and_then(|d| crate::dxbc::u32_at(d, 4 + 36).ok());
threads.map_or(ms.threads, |t| {
t.max(ms.max_vertices).max(ms.max_primitives)
})
}
_ => 0,
};
let l = lower::lower(&lower::Parts {
native,
p,
st,
io,
res,
inputs,
outputs,
prims,
mesh_stride,
})?;
Ok(HostShader {
stage: native.stage,
dxil: l.dxil,
user_data: l.user_data,
static_samplers: l
.samplers
.iter()
.enumerate()
.map(|(n, &w)| {
let mut s = StaticSampler::from_words(w);
if l.cmp_samplers >> n & 1 != 0 {
s.filter |= 0x80;
}
s
})
.collect(),
samplers: l.samplers,
root_cbvs: l.root_cbvs,
root_srvs: l.root_srvs,
})
}
/// The rows of an `ISG1`/`OSG1` part.
fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> {
use crate::dxbc::u32_at;
let count = u32_at(part, 0)? as usize;
let base = u32_at(part, 4)? as usize;
let mut out = Vec::with_capacity(count);
for i in 0..count {
let at = base + 32 * i;
let name_at = u32_at(part, at + 4)? as usize;
let name = part
.get(name_at..)
.and_then(|s| s.split(|&b| b == 0).next())
.ok_or(ShaderError::Malformed("signature name out of bounds"))?;
let mask = *part
.get(at + 24)
.ok_or(ShaderError::Malformed("truncated"))?;
if u32_at(part, at + 28)? != 0 {
return Err(ShaderError::Unsupported {
offset: 0,
what: "a minimum-precision signature element",
});
}
if u32_at(part, at)? != 0 {
return Err(ShaderError::Unsupported {
offset: 0,
what: "a signature element of another stream",
});
}
let kind = match u32_at(part, at + 12)? {
0 => 0,
1 => 3,
2 => 6,
3 => 7,
4 => 4,
5 => 5,
6 => 1,
7 => 10,
8 => 2,
9 => 13,
10 => 12,
64 => 16,
65 => 17,
66 => 14,
67 => 19,
68 => 18,
69 => 20,
70 => 15,
25 => 30, // cull primitive
_ => {
return Err(ShaderError::Unsupported {
offset: 0,
what: "a system value in the signature",
});
}
};
// 16-bit elements are declared 32-bit; reading or writing one
// converts (16-bit values travel packed on the console).
let raw = u32_at(part, at + 16)?;
let comp = match (kind, raw) {
// DXIL declares the front face a uint (the validator insists).
(13, _) => 5,
(_, 1 | 4) => 5,
(_, 2 | 5) => 4,
(_, 3 | 6) => 9,
(_, c) => {
return Err(ShaderError::Unsupported {
offset: 0,
what: match c {
0 => "a signature element of unknown type",
_ => "a 64-bit signature element",
},
});
}
};
let register = u32_at(part, at + 20)?;
out.push(container::SigElement {
name: String::from_utf8_lossy(name).into_owned(),
index: u32_at(part, at + 8)?,
kind,
comp,
interp: 0,
row: (register != u32::MAX).then_some(register),
col: mask.trailing_zeros().min(3) as u8,
cols: mask.count_ones().max(1) as u8,
usage: 0,
half: (4..=6).contains(&raw),
});
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::bitcode::Attr;
use super::container::SigElement;
use super::shader::Shader;
/// A pixel shader writing a constant colour.
fn constant_color() -> Vec<u8> {
let mut s = Shader::new(true);
s.outputs.push(SigElement {
name: "SV_Target".into(),
index: 0,
kind: 16,
comp: 9,
interp: 0,
row: Some(0),
col: 0,
cols: 4,
usage: 15,
half: false,
});
let b = s.entry;
for (c, v) in [1.0f32, 0.5, 0.25, 1.0].into_iter().enumerate() {
let args = [
s.m.i32(0),
s.m.i32(0),
s.m.i8(c as u8),
s.m.f32(v.to_bits()),
];
s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args);
}
s.m.terminate(b, super::bitcode::Term::Ret);
s.finish()
}
#[test]
#[cfg(windows)]
fn stub_pipeline_is_created() {
let Ok(host) = super::host::Host::new(false) else {
eprintln!("no SM 6.6 device; skipped");
return;
};
let ps = super::HostShader {
stage: crate::HwStage::Ps,
dxil: constant_color(),
user_data: Vec::new(),
samplers: Vec::new(),
static_samplers: Vec::new(),
root_cbvs: Vec::new(),
root_srvs: Vec::new(),
};
let file = |var: &str, stage| {
std::env::var(var).ok().map(|p| super::HostShader {
stage,
dxil: std::fs::read(p).unwrap(),
user_data: Vec::new(),
samplers: Vec::new(),
static_samplers: Vec::new(),
root_cbvs: Vec::new(),
root_srvs: Vec::new(),
})
};
let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps);
let vs = file("VICTORY_REF_VS", crate::HwStage::Vs)
.unwrap_or_else(|| super::host::stub_vs(&ps).unwrap());
if let Ok(mut v) = super::validator::Validator::load(
super::validator::Validator::default_path().as_deref(),
) {
v.validate(&mut vs.dxil.clone()).unwrap();
}
host.pipeline(&vs, &ps).unwrap();
// The runtime checks the container hash: no hash or a wrong one is
// refused. (Recent runtimes also take sixteen 0x01 bytes, a bypass
// value; ours works with older ones too.)
let mut wrong = ps.dxil[4..20].to_vec();
wrong[0] ^= 1;
for digest in [&[0u8; 16][..], &wrong] {
let mut other = ps.clone();
other.dxil[4..20].copy_from_slice(digest);
assert!(
host.pipeline(&vs, &other).is_err(),
"digest {digest:02x?} accepted"
);
}
}
#[test]
#[cfg(windows)]
fn constant_color_validates() {
let mut c = constant_color();
let path = super::validator::Validator::default_path();
let Ok(mut v) = super::validator::Validator::load(path.as_deref()) else {
eprintln!("no dxil.dll; skipped");
return;
};
let ours = c[4..20].to_vec();
v.validate(&mut c).unwrap();
assert_eq!(c[4..20], ours[..], "our hash differs from the validator's");
}
}
+125
View File
@@ -0,0 +1,125 @@
//! Immediate samplers: the console's four sampler words (the GPU's public
//! `SQ_IMG_SAMP_WORD0-3` layout) as a D3D12 static sampler.
//!
//! Word 0: address modes x, y, z (bits 0-8, 3 each), log2 of the maximum
//! anisotropy (9-11), comparison function (12-14), reduction (29-30: 0
//! filtering, 1 minimum, 2 maximum). Word 1: minimum and maximum LOD
//! (0-11, 12-23, unsigned 4.8). Word 2: LOD bias (0-13, signed 5.8),
//! magnification and minification filters (20-21, 22-23: point, linear,
//! anisotropic point, anisotropic linear), mip filter (26-27: none, point,
//! linear). Word 3: border colour (30-31: transparent black, opaque black,
//! opaque white, custom).
//!
//! Comparison is the sampling instruction's, not the sampler's: the console
//! encodes a comparison function in every sampler (D3D's default, less or
//! equal, when unused).
/// A static sampler in D3D12 terms; the integers are the `D3D12_FILTER`,
/// `D3D12_TEXTURE_ADDRESS_MODE`, `D3D12_COMPARISON_FUNC` and
/// `D3D12_STATIC_BORDER_COLOR` values.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StaticSampler {
pub filter: u32,
/// U, V, W.
pub address: [u32; 3],
pub mip_lod_bias: f32,
pub max_anisotropy: u32,
pub comparison: u32,
pub border: u32,
pub min_lod: f32,
pub max_lod: f32,
}
// The floats come from fixed-point fields: never NaN.
impl Eq for StaticSampler {}
impl StaticSampler {
/// Decodes the four sampler words.
pub fn from_words(w: [u32; 4]) -> Self {
let bits = |word: u32, at: u32, n: u32| word >> at & ((1 << n) - 1);
// wrap, mirror, clamp, mirror once; the half-border modes have no
// D3D form and become their nearest.
let address = |m: u32| [1, 2, 3, 5, 3, 5, 4, 5][m as usize];
let (mag, min, mip) = (bits(w[2], 20, 2), bits(w[2], 22, 2), bits(w[2], 26, 2));
let reduction = match bits(w[0], 29, 2) {
1 => 2,
2 => 3,
_ => 0,
};
let filter = if mag >= 2 || min >= 2 {
0x55 | reduction << 7
} else {
(min & 1) << 4 | (mag & 1) << 2 | u32::from(mip == 2) | reduction << 7
};
let lod = |v: u32| v as f32 / 256.0;
// Without a mip filter the base level is sampled.
let (min_lod, max_lod) = if mip == 0 {
(0.0, 0.0)
} else {
(lod(bits(w[1], 0, 12)), lod(bits(w[1], 12, 12)))
};
StaticSampler {
filter,
address: [0, 3, 6].map(|at| address(bits(w[0], at, 3))),
mip_lod_bias: ((bits(w[2], 0, 14) << 18) as i32 >> 18) as f32 / 256.0,
max_anisotropy: 1 << bits(w[0], 9, 3).min(4),
comparison: bits(w[0], 12, 3) + 1,
// shortcut: a custom border colour (type 3, a table entry) becomes
// transparent black; upgrade when a title uses one.
border: bits(w[3], 30, 2) % 3,
min_lod,
max_lod,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn console_compiled_samplers_decode() {
// Words the console compiler wrote for static samplers of known
// descriptions.
let point = StaticSampler::from_words([0x3088, 0x0054_0100, 0x1400_0080, 0x8000_0000]);
assert_eq!(
point,
StaticSampler {
filter: 0,
address: [1, 2, 3],
mip_lod_bias: 0.5,
max_anisotropy: 1,
comparison: 4,
border: 2,
min_lod: 1.0,
max_lod: 5.25,
}
);
let aniso = StaticSampler::from_words([0x369E, 0x00FF_F000, 0x18F0_3E00, 0x8000_0000]);
assert_eq!(
(aniso.filter, aniso.address, aniso.max_anisotropy),
(0x55, [4, 5, 3], 8)
);
assert_eq!((aniso.mip_lod_bias, aniso.max_lod), (-2.0, 4095.0 / 256.0));
let compare = StaticSampler::from_words([0x3006, 0x00FF_F000, 0x1450_0000, 0x4000_0000]);
assert_eq!(
(compare.filter, compare.address, compare.border),
(0x14, [4, 1, 1], 1)
);
let minimum =
StaticSampler::from_words([0x2000_3003, 0x00FF_F000, 0x1850_0000, 0x8000_0000]);
assert_eq!((minimum.filter, minimum.address[0]), (0x115, 5));
let mag_mip = StaticSampler::from_words([0x3002, 0, 0x1810_0000, 0x8000_0000]);
assert_eq!((mag_mip.filter, mag_mip.max_lod), (0x05, 0.0));
let max_aniso =
StaticSampler::from_words([0x4000_3800, 0x00FF_F000, 0x18F0_0F00, 0x8000_0000]);
assert_eq!(
(
max_aniso.filter,
max_aniso.max_anisotropy,
max_aniso.mip_lod_bias
),
(0x1D5, 16, 15.0)
);
}
}
+645
View File
@@ -0,0 +1,645 @@
//! A DXIL vertex, pixel, compute or mesh shader under construction: the module,
//! the `dx.op` declarations it calls, its signatures and bound resources,
//! and the metadata and container that wrap it up (SM 6.6, validator 1.6).
use super::bitcode::{Attr, Md, Module, Ty, V};
use super::container::{self, Binding, Psv, SigElement};
/// Where the shader reads its user data: `b0` in this space.
pub const USER_DATA_SPACE: u32 = 0;
/// Where immediate samplers are bound: `s<n>` in this space.
pub const SAMPLER_SPACE: u32 = 0;
/// Where root CBVs and SRVs are bound: `b<root parameter index>` and
/// `t<root parameter index>` in this space.
pub const ROOT_CBV_SPACE: u32 = 1;
/// `ShaderFlags` bits (metadata) and their `SFI0` feature bits.
pub(crate) mod flags {
pub const RAW_BUFFERS: u64 = 1 << 4;
pub const TYPED_UAV_LOADS: u64 = 1 << 13;
pub const WAVE_OPS: u64 = 1 << 19;
pub const INT64: u64 = 1 << 20;
pub const RESOURCE_HEAP: u64 = 1 << 30;
pub const SAMPLER_HEAP: u64 = 1 << 31;
}
pub(crate) struct Types {
pub void: Ty,
pub i1: Ty,
pub i32: Ty,
pub f32: Ty,
pub handle: Ty,
pub props: Ty,
pub bind: Ty,
pub cbuf_ret: Ty,
pub res_ret: Ty,
}
/// What a mesh shader declares beyond its thread-group size.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Mesh {
pub max_vertices: u32,
pub max_primitives: u32,
/// 1 lines, 2 triangles.
pub topology: u8,
}
pub(crate) struct Shader {
pub m: Module,
pub t: Types,
pub pixel: bool,
pub inputs: Vec<SigElement>,
pub outputs: Vec<SigElement>,
/// A mesh shader's per-primitive outputs.
pub prims: Vec<SigElement>,
/// A mesh shader (`threads` is its thread-group size).
pub mesh: Option<Mesh>,
/// Dwords of user data the shader reads (0: no user-data buffer).
pub user_data: u32,
/// Immediate samplers, bound as `s0..` in [`SAMPLER_SPACE`].
pub samplers: u32,
/// Bit n: immediate sampler n is a comparison sampler.
pub cmp_samplers: u64,
/// Root CBVs read, by root parameter index, with their handles.
pub root_cbvs: Vec<(u8, V)>,
/// Root SRVs (raw buffers) read, likewise.
pub root_srvs: Vec<(u8, V)>,
pub flags: u64,
/// A compute shader with this thread-group size.
pub threads: Option<[u32; 3]>,
/// The wave size a compute shader requires (`WaveSize`).
pub wave_size: Option<u32>,
/// Thread-group shared memory, in dwords.
pub lds_dwords: u32,
lds: Option<V>,
main: V,
pub entry: usize,
}
impl Shader {
pub fn new(pixel: bool) -> Self {
let mut m = Module::default();
let void = m.void();
let i1 = m.int(1);
let i8 = m.int(8);
let i32 = m.int(32);
let f32 = m.float();
let i8p = m.ptr(i8);
let handle = m.named_struct("dx.types.Handle", vec![i8p]);
let props = m.named_struct("dx.types.ResourceProperties", vec![i32, i32]);
let bind = m.named_struct("dx.types.ResBind", vec![i32, i32, i32, i8]);
let cbuf_ret = m.named_struct("dx.types.CBufRet.i32", vec![i32, i32, i32, i32]);
let res_ret = m.named_struct("dx.types.ResRet.f32", vec![f32, f32, f32, f32, i32]);
let main_ty = m.func_ty(void, vec![]);
m.ptr(main_ty);
let main = m.function("main", main_ty, None, true);
let entry = m.new_block();
Shader {
m,
t: Types {
void,
i1,
i32,
f32,
handle,
props,
bind,
cbuf_ret,
res_ret,
},
pixel,
inputs: Vec::new(),
outputs: Vec::new(),
prims: Vec::new(),
mesh: None,
user_data: 0,
samplers: 0,
cmp_samplers: 0,
root_cbvs: Vec::new(),
root_srvs: Vec::new(),
flags: 0,
threads: None,
wave_size: None,
lds_dwords: 0,
lds: None,
main,
entry,
}
}
/// The thread-group shared memory: `[lds_dwords x i32]` in address
/// space 3.
pub fn lds(&mut self) -> V {
if let Some(g) = self.lds {
return g;
}
let arr = self.m.array(self.lds_dwords, self.t.i32);
let g = self.m.global("lds", arr, 3);
self.lds = Some(g);
g
}
/// Calls `dx.op.<name>` (class and overload) with `opcode` and `args`.
pub fn op(
&mut self,
block: usize,
name: &str,
attr: Attr,
ret: Ty,
opcode: u32,
args: &[V],
) -> V {
let mut params = vec![self.t.i32];
params.extend(args.iter().map(|&a| self.m.type_of(a)));
let fty = self.m.func_ty(ret, params);
self.m.ptr(fty);
let f = self
.m
.function(&format!("dx.op.{name}"), fty, Some(attr), false);
let mut all = vec![self.m.i32(opcode)];
all.extend(args);
self.m.call(block, f, all)
}
/// The handle of the user-data constant buffer, made in the entry block.
pub fn user_data_handle(&mut self) -> V {
let bind = [
self.m.i32(0),
self.m.i32(0),
self.m.i32(USER_DATA_SPACE),
self.m.i8(2), // CBV
];
let bind = self.m.aggregate(self.t.bind, &bind);
let block = self.entry;
let (i, f) = (self.m.i32(0), self.m.bool(false));
let h = self.op(
block,
"createHandleFromBinding",
Attr::ReadNone,
self.t.handle,
217,
&[bind, i, f],
);
// The size is known in `finish`, which fixes this placeholder.
self.annotate(block, h, 13, u32::MAX)
}
/// The handle of the root CBV of root parameter `slot`, made in the
/// entry block.
pub fn root_cbv_handle(&mut self, slot: u8) -> V {
if let Some(&(_, h)) = self.root_cbvs.iter().find(|r| r.0 == slot) {
return h;
}
let r = self.m.i32(u32::from(slot));
let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(2)];
let bind = self.m.aggregate(self.t.bind, &bind);
let f = self.m.bool(false);
let block = self.entry;
let h = self.op(
block,
"createHandleFromBinding",
Attr::ReadNone,
self.t.handle,
217,
&[bind, r, f],
);
let h = self.annotate(block, h, 13, 65536);
self.root_cbvs.push((slot, h));
h
}
/// The handle of the root SRV (a raw buffer) of root parameter `slot`.
pub fn root_srv_handle(&mut self, slot: u8) -> V {
if let Some(&(_, h)) = self.root_srvs.iter().find(|r| r.0 == slot) {
return h;
}
let r = self.m.i32(u32::from(slot));
let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(0)];
let bind = self.m.aggregate(self.t.bind, &bind);
let f = self.m.bool(false);
let block = self.entry;
let h = self.op(
block,
"createHandleFromBinding",
Attr::ReadNone,
self.t.handle,
217,
&[bind, r, f],
);
let h = self.annotate(block, h, 11, 0);
self.flags |= flags::RAW_BUFFERS;
self.root_srvs.push((slot, h));
h
}
/// The handle of immediate sampler `n` (a comparison sampler when its
/// bit in `cmp_samplers` is set).
pub fn sampler_handle(&mut self, block: usize, n: u32) -> V {
let bind = [
self.m.i32(n),
self.m.i32(n),
self.m.i32(SAMPLER_SPACE),
self.m.i8(3), // sampler
];
let bind = self.m.aggregate(self.t.bind, &bind);
let (i, f) = (self.m.i32(n), self.m.bool(false));
let h = self.op(
block,
"createHandleFromBinding",
Attr::ReadNone,
self.t.handle,
217,
&[bind, i, f],
);
let cmp = if self.cmp_samplers >> n & 1 != 0 {
0x8000
} else {
0
};
self.annotate(block, h, 14 | cmp, 0)
}
pub fn annotate(&mut self, block: usize, h: V, props0: u32, props1: u32) -> V {
let p = [self.m.i32(props0), self.m.i32(props1)];
let p = self.m.aggregate(self.t.props, &p);
self.op(
block,
"annotateHandle",
Attr::ReadNone,
self.t.handle,
216,
&[h, p],
)
}
/// A descriptor heap handle, annotated with `props`.
pub fn heap_handle(&mut self, block: usize, index: V, sampler: bool, props: (u32, u32)) -> V {
self.flags |= if sampler {
flags::SAMPLER_HEAP
} else {
flags::RESOURCE_HEAP
};
let (s, n) = (self.m.bool(sampler), self.m.bool(false));
let h = self.op(
block,
"createHandleFromHeap",
Attr::ReadNone,
self.t.handle,
218,
&[index, s, n],
);
self.annotate(block, h, props.0, props.1)
}
/// The finished container.
pub fn finish(mut self) -> Vec<u8> {
let ud_size = (self.user_data * 4).next_multiple_of(16);
self.fix_user_data_size(ud_size);
let mut resources = None;
let mut bindings = Vec::new();
let i32c = |s: &mut Self, v: u32| {
let c = s.m.i32(v);
s.m.md_value(c)
};
if self.user_data > 0
|| self.samplers > 0
|| !self.root_cbvs.is_empty()
|| !self.root_srvs.is_empty()
{
let empty = self.m.md_str("");
let mut cbvs = None;
let mut cbv_list = Vec::new();
if self.user_data > 0 {
let arr = self.m.array(self.user_data.next_multiple_of(4), self.t.i32);
let ty = self.m.named_struct("UserData", vec![arr]);
let p = self.m.ptr(ty);
let u = self.m.undef(p);
let ops = vec![
Some(i32c(&mut self, 0)),
Some(self.m.md_value(u)),
Some(empty),
Some(i32c(&mut self, USER_DATA_SPACE)),
Some(i32c(&mut self, 0)),
Some(i32c(&mut self, 1)),
Some(i32c(&mut self, ud_size)),
None,
];
cbv_list.push(Some(self.m.md_node(ops)));
bindings.push(Binding {
kind: 2,
space: USER_DATA_SPACE,
register: 0,
dxil_kind: 13,
});
}
let blob = self.m.array(16384, self.t.i32);
let ty = self.m.named_struct("RootCbv", vec![blob]);
let p = self.m.ptr(ty);
let u = self.m.undef(p);
for (slot, _) in self.root_cbvs.clone() {
let ops = vec![
Some(i32c(&mut self, cbv_list.len() as u32)),
Some(self.m.md_value(u)),
Some(empty),
Some(i32c(&mut self, ROOT_CBV_SPACE)),
Some(i32c(&mut self, u32::from(slot))),
Some(i32c(&mut self, 1)),
Some(i32c(&mut self, 65536)),
None,
];
cbv_list.push(Some(self.m.md_node(ops)));
bindings.push(Binding {
kind: 2,
space: ROOT_CBV_SPACE,
register: u32::from(slot),
dxil_kind: 13,
});
}
if !cbv_list.is_empty() {
cbvs = Some(self.m.md_node(cbv_list));
}
let mut srvs = None;
if !self.root_srvs.is_empty() {
let ty = self
.m
.named_struct("struct.ByteAddressBuffer", vec![self.t.i32]);
let p = self.m.ptr(ty);
let u = self.m.undef(p);
let mut list = Vec::new();
for (n, (slot, _)) in self.root_srvs.clone().into_iter().enumerate() {
let ops = vec![
Some(i32c(&mut self, n as u32)),
Some(self.m.md_value(u)),
Some(empty),
Some(i32c(&mut self, ROOT_CBV_SPACE)),
Some(i32c(&mut self, u32::from(slot))),
Some(i32c(&mut self, 1)),
Some(i32c(&mut self, 11)),
Some(i32c(&mut self, 0)),
None,
];
list.push(Some(self.m.md_node(ops)));
bindings.push(Binding {
kind: 4,
space: ROOT_CBV_SPACE,
register: u32::from(slot),
dxil_kind: 11,
});
}
srvs = Some(self.m.md_node(list));
}
let mut samplers = None;
if self.samplers > 0 {
let ty = self.m.named_struct("struct.SamplerState", vec![self.t.i32]);
let p = self.m.ptr(ty);
let u = self.m.undef(p);
let mut list = Vec::new();
for n in 0..self.samplers {
let kind = (self.cmp_samplers >> n & 1) as u32;
let ops = vec![
Some(i32c(&mut self, n)),
Some(self.m.md_value(u)),
Some(empty),
Some(i32c(&mut self, SAMPLER_SPACE)),
Some(i32c(&mut self, n)),
Some(i32c(&mut self, 1)),
// Sampler kind: 1 comparison.
Some(i32c(&mut self, kind)),
None,
];
list.push(Some(self.m.md_node(ops)));
bindings.push(Binding {
kind: 1,
space: SAMPLER_SPACE,
register: n,
dxil_kind: 14,
});
}
samplers = Some(self.m.md_node(list));
}
resources = Some(self.m.md_node(vec![srvs, None, cbvs, samplers]));
// PSV0 lists them as the module does: CBVs, samplers, SRVs.
bindings.sort_by_key(|b| match b.kind {
2 => 0,
1 => 1,
_ => 2,
});
}
if let Some(r) = resources {
self.m.named_md("dx.resources", vec![r]);
}
let graphics = self.threads.is_none() || self.mesh.is_some();
if graphics {
// shortcut: every output is declared to depend on every input; the
// exact sets need a dependence pass. Drivers read this state.
let scalars = |els: &[SigElement]| {
els.iter()
.filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols)))
.max()
.unwrap_or(0)
};
let (ni, no) = (scalars(&self.inputs), scalars(&self.outputs));
let mut view = vec![ni, no];
// Mesh shaders have no inputs: then the primitive outputs' count.
if self.mesh.is_some() {
view.push(scalars(&self.prims));
}
for _ in 0..ni {
for k in 0..no.div_ceil(32) {
let bits = (no - 32 * k).min(32);
view.push(if bits == 32 {
u32::MAX
} else {
(1 << bits) - 1
});
}
}
let arr = self.m.array(view.len() as u32, self.t.i32);
let elems: Vec<V> = view.iter().map(|&v| self.m.i32(v)).collect();
let arr = self.m.aggregate(arr, &elems);
let arr = self.m.md_value(arr);
let view_node = self.m.md_node(vec![Some(arr)]);
self.m.named_md("dx.viewIdState", vec![view_node]);
}
let sigs = if graphics {
let ins = self.signature_md(self.inputs.clone());
let outs = self.signature_md(self.outputs.clone());
let prims = self.signature_md(self.prims.clone());
Some(self.m.md_node(vec![ins, outs, prims]))
} else {
None
};
// Entry properties: shader flags (tag 0), thread-group size (4),
// wave size (11).
let mut props = Vec::new();
if self.flags != 0 {
props.push(i32c(&mut self, 0));
let i64t = self.m.int(64);
let f = self.m.int_const(i64t, self.flags as i64);
props.push(self.m.md_value(f));
}
if let Some(threads) = self.threads {
let t = threads.map(|n| Some(i32c(&mut self, n)));
let t = self.m.md_node(t.to_vec());
match self.mesh {
// Mesh state (tag 9): threads, maximum vertices and
// primitives, topology, payload bytes.
Some(mesh) => {
props.push(i32c(&mut self, 9));
let state = [
mesh.max_vertices,
mesh.max_primitives,
mesh.topology.into(),
0,
]
.map(|n| Some(i32c(&mut self, n)));
let mut node = vec![Some(t)];
node.extend(state);
props.push(self.m.md_node(node));
}
None => {
props.push(i32c(&mut self, 4));
props.push(t);
}
}
}
if let Some(n) = self.wave_size {
props.push(i32c(&mut self, 11));
let n = Some(i32c(&mut self, n));
props.push(self.m.md_node(vec![n]));
}
let props =
(!props.is_empty()).then(|| self.m.md_node(props.into_iter().map(Some).collect()));
let main = self.m.md_value(self.main);
let name = self.m.md_str("main");
let entry = self
.m
.md_node(vec![Some(main), Some(name), sigs, resources, props]);
let ident = self.m.md_str("victory");
let ident = self.m.md_node(vec![Some(ident)]);
self.m.named_md("llvm.ident", vec![ident]);
let one = i32c(&mut self, 1);
let six = i32c(&mut self, 6);
let version = self.m.md_node(vec![Some(one), Some(six)]);
self.m.named_md("dx.version", vec![version]);
self.m.named_md("dx.valver", vec![version]);
// Program kinds: 0 pixel, 1 vertex, 5 compute, 13 mesh.
let (name, kind) = match (self.threads, self.pixel) {
_ if self.mesh.is_some() => ("ms", 13u32),
(Some(_), _) => ("cs", 5u32),
(None, true) => ("ps", 0),
(None, false) => ("vs", 1),
};
let name = self.m.md_str(name);
let sm = self.m.md_node(vec![Some(name), Some(six), Some(six)]);
self.m.named_md("dx.shaderModel", vec![sm]);
self.m.named_md("dx.entryPoints", vec![entry]);
let bitcode = self.m.write();
let mut dxil = Vec::with_capacity(24 + bitcode.len());
dxil.extend((kind << 16 | 0x66).to_le_bytes());
dxil.extend((((24 + bitcode.len()) / 4) as u32).to_le_bytes());
dxil.extend(b"DXIL");
dxil.extend(0x106u32.to_le_bytes());
dxil.extend(16u32.to_le_bytes());
dxil.extend((bitcode.len() as u32).to_le_bytes());
dxil.extend(&bitcode);
let mut features = 0u64;
if self.flags & flags::TYPED_UAV_LOADS != 0 {
features |= 0x800;
}
if self.flags & flags::WAVE_OPS != 0 {
features |= 0x4000;
}
if self.flags & flags::INT64 != 0 {
features |= 0x8000;
}
if self.flags & flags::RESOURCE_HEAP != 0 {
features |= 0x200_0000;
}
if self.flags & flags::SAMPLER_HEAP != 0 {
features |= 0x400_0000;
}
let sfi0 = features.to_le_bytes();
let isg1 = container::signature(&self.inputs, true);
let osg1 = container::signature(&self.outputs, false);
let flag = if self.pixel {
self.outputs.iter().any(|o| (17..=19).contains(&o.kind))
} else {
self.outputs.iter().any(|o| o.kind == 3)
};
let psv0 = container::psv(&Psv {
stage: kind as u8,
flag: flag && self.threads.is_none(),
inputs: &self.inputs,
outputs: &self.outputs,
prims: &self.prims,
mesh: self.mesh.map(|m| (m, self.lds_dwords * 4)),
bindings: &bindings,
threads: self.threads.unwrap_or_default(),
wave_size: self.wave_size,
});
let hash = [0u8; 20];
let psg1 = container::signature(&self.prims, false);
let mut parts: Vec<(&[u8; 4], &[u8])> =
vec![(b"SFI0", &sfi0), (b"ISG1", &isg1), (b"OSG1", &osg1)];
if self.mesh.is_some() {
parts.push((b"PSG1", &psg1));
}
parts.extend([(b"PSV0", &psv0[..]), (b"HASH", &hash), (b"DXIL", &dxil)]);
container::build(&parts)
}
/// The user-data buffer's annotation carries its size, known only now.
fn fix_user_data_size(&mut self, size: u32) {
let old = [self.m.i32(13), self.m.i32(u32::MAX)];
let old = self.m.aggregate(self.t.props, &old);
let new = [self.m.i32(13), self.m.i32(size)];
let new = self.m.aggregate(self.t.props, &new);
self.m.replace_const(old, new);
}
fn signature_md(&mut self, elements: Vec<SigElement>) -> Option<Md> {
if elements.is_empty() {
return None;
}
let mut list = Vec::new();
for (id, e) in elements.iter().enumerate() {
let c32 = |s: &mut Self, v: u32| {
let c = s.m.i32(v);
Some(s.m.md_value(c))
};
let c8 = |s: &mut Self, v: u8| {
let c = s.m.i8(v);
Some(s.m.md_value(c))
};
let idx = c32(self, e.index);
let indices = Some(self.m.md_node(vec![idx]));
let usage = if e.usage != 0 {
let (tag, mask) = (c32(self, 3), c32(self, u32::from(e.usage)));
Some(self.m.md_node(vec![tag, mask]))
} else {
None
};
let ops = vec![
c32(self, id as u32),
Some(self.m.md_str(&e.name)),
c8(self, e.comp),
c8(self, e.kind),
indices,
c8(self, e.interp),
c32(self, 1),
c8(self, e.cols),
c32(self, e.row.unwrap_or(u32::MAX)),
c8(self, if e.row.is_some() { e.col } else { u8::MAX }),
usage,
];
list.push(Some(self.m.md_node(ops)));
}
Some(self.m.md_node(list))
}
}
+221
View File
@@ -0,0 +1,221 @@
//! The DXIL validator in `dxil.dll` (`IDxcValidator`), for tests and the
//! offline batch. Translated shaders do not need it: they carry the
//! container hash we compute ([`super::container::hash`]).
//!
//! The DLL is found at `VICTORY_DXIL` if set, else the newest Windows SDK's
//! `bin\<version>\x64\dxil.dll`, else wherever `LoadLibrary` finds it.
use std::ffi::c_void;
use std::path::PathBuf;
use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW};
type Hresult = i32;
#[repr(C)]
struct Guid(u32, u16, u16, [u8; 8]);
const CLSID_DXC_VALIDATOR: Guid = Guid(
0x8ca3_e215,
0xf728,
0x4cf3,
[0x8c, 0xdd, 0x88, 0xaf, 0x91, 0x75, 0x87, 0xa1],
);
const IID_IDXC_VALIDATOR: Guid = Guid(
0xa6e8_2bd2,
0x1fd7,
0x4826,
[0x98, 0x11, 0x28, 0x57, 0xe7, 0x97, 0xf4, 0x9a],
);
/// `DxcValidatorFlags_InPlaceEdit`: sign the container we pass.
const IN_PLACE_EDIT: u32 = 1;
type CreateInstance =
unsafe extern "system" fn(*const Guid, *const Guid, *mut *mut c_void) -> Hresult;
/// COM object: a pointer to a table of method pointers.
type Object = *mut *const usize;
unsafe fn method<F: Copy>(obj: Object, slot: usize) -> F {
// SAFETY: the caller names a slot of the object's interface.
unsafe { std::mem::transmute_copy(&*(*obj).add(slot)) }
}
unsafe fn release(obj: Object) {
if !obj.is_null() {
// SAFETY: slot 2 of every COM interface is Release.
unsafe { method::<unsafe extern "system" fn(Object) -> u32>(obj, 2)(obj) };
}
}
/// An `IDxcBlob` over our bytes: QueryInterface, AddRef, Release,
/// GetBufferPointer, GetBufferSize. Lives on the caller's stack.
#[repr(C)]
struct Blob {
vtable: *const BlobVtable,
data: *mut u8,
len: usize,
}
/// IUnknown and IDxcBlob, as raw GUID bytes.
const IUNKNOWN: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xc0, 0, 0, 0, 0, 0, 0, 0x46];
const IDXC_BLOB: [u8; 16] = [
0x08, 0xfb, 0xa5, 0x8b, 0x95, 0x51, 0xe2, 0x40, 0xac, 0x58, 0x0d, 0x98, 0x9c, 0x3a, 0x01, 0x02,
];
unsafe extern "system" fn blob_qi(
this: *mut Blob,
iid: *const [u8; 16],
out: *mut *mut c_void,
) -> Hresult {
// SAFETY: the validator passes valid pointers.
unsafe {
if *iid == IUNKNOWN || *iid == IDXC_BLOB {
*out = this.cast();
0
} else {
*out = std::ptr::null_mut();
0x8000_4002_u32 as i32 // E_NOINTERFACE
}
}
}
unsafe extern "system" fn blob_ref(_: *mut Blob) -> u32 {
1
}
unsafe extern "system" fn blob_ptr(this: *mut Blob) -> *mut u8 {
// SAFETY: `this` is our blob.
unsafe { (*this).data }
}
unsafe extern "system" fn blob_len(this: *mut Blob) -> usize {
// SAFETY: `this` is our blob.
unsafe { (*this).len }
}
#[repr(C)]
struct BlobVtable {
qi: unsafe extern "system" fn(*mut Blob, *const [u8; 16], *mut *mut c_void) -> Hresult,
add_ref: unsafe extern "system" fn(*mut Blob) -> u32,
release: unsafe extern "system" fn(*mut Blob) -> u32,
ptr: unsafe extern "system" fn(*mut Blob) -> *mut u8,
len: unsafe extern "system" fn(*mut Blob) -> usize,
}
static BLOB_VTABLE: BlobVtable = BlobVtable {
qi: blob_qi,
add_ref: blob_ref,
release: blob_ref,
ptr: blob_ptr,
len: blob_len,
};
pub struct Validator {
object: Object,
}
// SAFETY: the validator object is free-threaded (DXC's validator has no
// thread affinity); calls are serialised by `&mut self`.
unsafe impl Send for Validator {}
impl Validator {
/// Where `dxil.dll` is looked for.
pub fn default_path() -> Option<PathBuf> {
if let Some(p) = std::env::var_os("VICTORY_DXIL") {
return Some(p.into());
}
let kits = PathBuf::from(r"C:\Program Files (x86)\Windows Kits\10\bin");
let mut versions: Vec<PathBuf> = std::fs::read_dir(&kits)
.ok()?
.filter_map(Result::ok)
.map(|e| e.path().join(r"x64\dxil.dll"))
.filter(|p| p.exists())
.collect();
versions.sort();
versions.pop()
}
/// Loads `path`'s validator (or `dxil.dll` from the DLL search path).
pub fn load(path: Option<&std::path::Path>) -> Result<Self, String> {
let name: Vec<u16> = path
.map_or_else(|| "dxil.dll".into(), |p| p.as_os_str().to_owned())
.to_string_lossy()
.encode_utf16()
.chain([0])
.collect();
// SAFETY: plain Win32 calls with a NUL-terminated name.
unsafe {
let module = LoadLibraryW(name.as_ptr());
if module.is_null() {
return Err(format!("cannot load {}", String::from_utf16_lossy(&name)));
}
let create = GetProcAddress(module, c"DxcCreateInstance".as_ptr().cast())
.ok_or("dxil.dll lacks DxcCreateInstance")?;
let create: CreateInstance = std::mem::transmute(create);
let mut object = std::ptr::null_mut();
let hr = create(&CLSID_DXC_VALIDATOR, &IID_IDXC_VALIDATOR, &mut object);
if hr < 0 || object.is_null() {
return Err(format!("DxcCreateInstance(validator) failed: {hr:#x}"));
}
Ok(Validator {
object: object.cast(),
})
}
}
/// Validates `container` and signs it in place; the error text if it
/// is rejected.
pub fn validate(&mut self, container: &mut [u8]) -> Result<(), String> {
let mut blob = Blob {
vtable: &BLOB_VTABLE,
data: container.as_mut_ptr(),
len: container.len(),
};
// SAFETY: IDxcValidator::Validate (slot 3) with our blob; then
// IDxcOperationResult GetStatus (3) and GetErrorBuffer (5), and
// IDxcBlob GetBufferPointer (3) / GetBufferSize (4).
unsafe {
let mut result: Object = std::ptr::null_mut();
let validate: unsafe extern "system" fn(
Object,
*mut Blob,
u32,
*mut Object,
) -> Hresult = method(self.object, 3);
let hr = validate(self.object, &mut blob, IN_PLACE_EDIT, &mut result);
if hr < 0 || result.is_null() {
return Err(format!("Validate failed: {hr:#x}"));
}
let mut status = 0;
let get_status: unsafe extern "system" fn(Object, *mut Hresult) -> Hresult =
method(result, 3);
get_status(result, &mut status);
let mut text = String::new();
if status < 0 {
let mut errors: Object = std::ptr::null_mut();
let get_errors: unsafe extern "system" fn(Object, *mut Object) -> Hresult =
method(result, 5);
if get_errors(result, &mut errors) >= 0 && !errors.is_null() {
let ptr: unsafe extern "system" fn(Object) -> *const u8 = method(errors, 3);
let len: unsafe extern "system" fn(Object) -> usize = method(errors, 4);
let bytes = std::slice::from_raw_parts(ptr(errors), len(errors));
text = String::from_utf8_lossy(bytes)
.trim_end_matches('\0')
.trim()
.into();
release(errors);
}
if text.is_empty() {
text = format!("rejected ({status:#x})");
}
}
release(result);
if status < 0 { Err(text) } else { Ok(()) }
}
}
}
impl Drop for Validator {
fn drop(&mut self) {
// SAFETY: we own one reference.
unsafe { release(self.object) };
}
}
+679
View File
@@ -0,0 +1,679 @@
//! Whole-wave sections (decision 0003): code between `s_or_saveexec -1`
//! (or `s_nand_saveexec 0`) and the restore of the saved mask runs in every lane of the console's
//! wave, the inactive ones included, which is how the compiler expands
//! HLSL wave reductions and prefix sums (an identity put into the inactive
//! lanes with `v_cndmask`, then DPP, `v_permlanex16` and `v_readlane`
//! steps). A host lane that is elsewhere cannot run that code, so each
//! section is simulated on the console's lanes with symbolic values, and a
//! value it leaves is lowered by what it turned out to be: the reduction or
//! prefix of one operation over the lanes' (masked) inputs, which DXIL's
//! wave operations compute over the host's active lanes. No instruction
//! sequence is matched; any step the simulation does not model leaves the
//! values it writes unknown.
use std::collections::HashMap;
use crate::gfx10::{Dpp, Fields, NULL, Operand};
use crate::ir::{EXEC, Inst, Program, Reg, Value};
/// An associative operation and its identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Op {
AddU,
AddF,
MinU,
MaxU,
MinI,
MaxI,
MinF,
MaxF,
Or,
And,
Xor,
}
impl Op {
fn of(name: &str) -> Option<Op> {
Some(match name {
"v_add_nc_u32" => Op::AddU,
"v_add_f32" => Op::AddF,
"v_min_u32" => Op::MinU,
"v_max_u32" => Op::MaxU,
"v_min_i32" => Op::MinI,
"v_max_i32" => Op::MaxI,
"v_min_f32" => Op::MinF,
"v_max_f32" => Op::MaxF,
"v_or_b32" => Op::Or,
"v_and_b32" => Op::And,
"v_xor_b32" => Op::Xor,
_ => return None,
})
}
/// Whether `k` leaves the other operand unchanged.
fn identity(self, k: u32) -> bool {
match self {
Op::AddU | Op::Or | Op::Xor | Op::MaxU => k == 0,
Op::AddF => k == 0 || k == 0x8000_0000,
Op::MinU | Op::And => k == u32::MAX,
Op::MinI => k == 0x7FFF_FFFF,
Op::MaxI => k == 0x8000_0000,
Op::MinF => k == 0x7F80_0000,
Op::MaxF => k == 0xFF80_0000,
}
}
/// Counting a lane twice changes the result.
fn counts(self) -> bool {
matches!(self, Op::AddU | Op::AddF | Op::Xor)
}
}
/// A lane's value inside a section.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Sym {
Unknown,
K(u32),
/// The lane's own value of a VGPR value from before the section.
Own(Value),
/// A uniform value from before the section.
Uni(Value),
/// `op` over `lanes` of `mask ? src : ident` (`op` none: one lane).
Red {
op: Option<Op>,
src: Value,
mask: Value,
ident: u32,
lanes: u64,
},
}
/// What a value a section leaves holds in every lane.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Shape {
K(u32),
Value(Value),
/// The lane's own `mask ? src : ident`.
Masked(Value, Value, u32),
/// `op` over every lane.
Active(Op, Value, Value, u32),
/// `op` over the lanes below (`inclusive`: and including) each lane.
Prefix(Op, Value, Value, u32, bool),
}
/// The section starting at instruction `start` of a block: its restore
/// index and the shapes of the values it writes.
pub(crate) struct Section {
pub end: usize,
pub shapes: HashMap<Value, Shape>,
}
/// Every whole-wave section of `block`, by start index.
pub(crate) fn sections(p: &Program, block: usize) -> HashMap<usize, Section> {
let insts = &p.blocks[block].insts;
let wave: u32 = if p.wave64 { 64 } else { 32 };
let mut out = HashMap::new();
let mut i = 0;
while i < insts.len() {
let inst = &insts[i];
// EXEC becomes every lane: `s_or_saveexec -1` or `s_nand_saveexec 0`.
let all = match inst.name() {
"s_or_saveexec_b64" | "s_or_saveexec_b32" => Some(Operand::Const(193)),
"s_nand_saveexec_b64" | "s_nand_saveexec_b32" => Some(Operand::Const(128)),
_ => None,
};
let start = all.is_some_and(
|k| matches!(&inst.fields, Fields::Sop { src, .. } if src.first() == Some(&k)),
);
let saved = match &inst.fields {
Fields::Sop {
dst: Some(Operand::Scalar { code, .. }),
..
} if start => inst.write(Reg::S(*code)),
_ => None,
};
let Some(saved) = saved else {
i += 1;
continue;
};
let end = (i + 1..insts.len()).find(|&j| {
insts[j].write(Reg::S(EXEC)).is_some()
&& insts[j].read(Reg::S(saved_code(inst))) == Some(saved)
});
let Some(end) = end else {
break;
};
let shapes = simulate(&insts[i + 1..end], wave, saved);
out.insert(i, Section { end, shapes });
i = end + 1;
}
out
}
fn saved_code(inst: &Inst) -> u8 {
match &inst.fields {
Fields::Sop {
dst: Some(Operand::Scalar { code, .. }),
..
} => *code,
_ => NULL,
}
}
/// The lane `l` reads with DPP, whether it reads 0 instead, and whether it
/// writes; `None` for patterns not modelled.
fn dpp_lane(d: Dpp, l: u32) -> Option<(u32, bool, bool)> {
match d {
Dpp::Lanes { sel, .. } => Some(((l & !7) | (sel >> (3 * (l & 7)) & 7), false, true)),
Dpp::Row {
ctrl,
row_mask,
bank_mask,
bound_ctrl,
..
} => {
let (row, pos, n) = (l & !15, l & 15, u32::from(ctrl & 15));
let enabled = row_mask >> (l >> 4 & 3) & 1 != 0 && bank_mask >> (l >> 2 & 3) & 1 != 0;
let (src, inside) = match ctrl {
0..=0xFF => ((l & !3) | (u32::from(ctrl) >> (2 * (l & 3)) & 3), true),
0x101..=0x10F => (l + n, pos + n < 16),
0x111..=0x11F => (l.wrapping_sub(n), pos >= n),
0x121..=0x12F => (row | (pos.wrapping_sub(n) & 15), true),
0x140 => (l ^ 15, true),
0x141 => (l ^ 7, true),
0x150..=0x15F => (row | n, true),
0x160..=0x16F => (l ^ n, true),
_ => return None,
};
match (inside, bound_ctrl) {
(true, _) => Some((src, false, enabled)),
(false, true) => Some((l, true, enabled)),
(false, false) => Some((l, false, false)),
}
}
}
}
fn combine(op: Op, a: Sym, b: Sym) -> Sym {
match (a, b) {
(Sym::K(k), x) | (x, Sym::K(k)) if op.identity(k) => x,
(
Sym::Red {
op: oa,
src,
mask,
ident,
lanes: la,
},
Sym::Red {
op: ob,
src: sb,
mask: mb,
ident: ib,
lanes: lb,
},
) if (src, mask, ident) == (sb, mb, ib)
&& op.identity(ident)
&& oa.is_none_or(|o| o == op)
&& ob.is_none_or(|o| o == op)
&& (!op.counts() || la & lb == 0) =>
{
Sym::Red {
op: Some(op),
src,
mask,
ident,
lanes: la | lb,
}
}
_ => Sym::Unknown,
}
}
fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> {
let all = if wave == 64 {
u64::MAX
} else {
u64::from(u32::MAX)
};
let mut exec = all;
let mut vec: HashMap<Value, Vec<Sym>> = HashMap::new();
let mut uni: HashMap<Value, Sym> = HashMap::new();
// Masks the section derives from the saved EXEC (`s_and` with it).
let mut masked = vec![saved];
for inst in insts {
let name = inst.name();
if inst.write(Reg::S(EXEC)).is_some() {
// Constant lane sets (prefix sums); anything else ends what
// the simulation can follow.
let lo = name
.starts_with("s_mov_b")
.then(|| constant(inst))
.flatten();
let Some(k) = lo else {
return shapes(vec, uni, wave);
};
exec = if name == "s_mov_b64" {
k
} else {
exec & !0xFFFF_FFFF | k & 0xFFFF_FFFF
};
continue;
}
if inst.write(Reg::S(EXEC + 1)).is_some() {
let Some(k) = name
.starts_with("s_mov_b")
.then(|| constant(inst))
.flatten()
else {
return shapes(vec, uni, wave);
};
exec = exec & 0xFFFF_FFFF | k << 32;
continue;
}
if let Fields::Sop { src, .. } = &inst.fields {
if name.starts_with("s_and_b")
&& src.iter().any(|o| matches!(*o, Operand::Scalar { code, .. } if inst.read(Reg::S(code)).is_some_and(|v| masked.contains(&v))))
&& let Some(&(_, w)) = inst.writes.iter().find(|w| matches!(w.0, Reg::S(_)))
{
masked.push(w);
}
for &(_, w) in &inst.writes {
uni.entry(w).or_insert(Sym::Unknown);
}
continue;
}
let Fields::Valu(v) = &inst.fields else {
for &(_, w) in &inst.writes {
vec.insert(w, vec![Sym::Unknown; wave as usize]);
}
continue;
};
let lanes = |op: &Operand,
vec: &HashMap<Value, Vec<Sym>>,
uni: &HashMap<Value, Sym>|
-> Vec<Sym> {
let one = |s: Sym| vec![s; wave as usize];
match *op {
Operand::Vector { reg, .. } => match inst.read(Reg::V(reg)) {
Some(x) => vec
.get(&x)
.cloned()
.unwrap_or_else(|| (0..wave).map(|_| Sym::Own(x)).collect()),
None => one(Sym::Unknown),
},
Operand::Scalar { code, .. } if code != NULL => match inst.read(Reg::S(code)) {
Some(x) => one(uni.get(&x).copied().unwrap_or(Sym::Uni(x))),
None => one(Sym::Unknown),
},
Operand::Const(c) => one(crate::resource::inline(c).map_or(Sym::Unknown, Sym::K)),
Operand::Literal(x) => one(Sym::K(x)),
_ => one(Sym::Unknown),
}
};
let modifiers = v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 || v.sdwa.is_some();
if name == "v_readlane_b32" {
let (Some(Operand::Scalar { code, .. }), Some(src), Some(lane)) =
(v.dst, v.src.first(), v.src.get(1))
else {
continue;
};
let l = match *lane {
Operand::Const(c) => crate::resource::inline(c),
Operand::Literal(x) => Some(x),
_ => None,
};
let x = lanes(src, &vec, &uni);
if let Some(w) = inst.write(Reg::S(code)) {
let s = l
.and_then(|l| x.get(l as usize).copied())
.unwrap_or(Sym::Unknown);
uni.insert(w, s);
}
continue;
}
let Some(Operand::Vector { reg: dreg, .. }) = v.dst else {
for &(_, w) in &inst.writes {
uni.insert(w, Sym::Unknown);
}
continue;
};
let Some(dst) = inst.write(Reg::V(dreg)) else {
continue;
};
let old = lanes(
&Operand::Vector {
reg: dreg,
dwords: 1,
},
&vec,
&uni,
);
// src0 as each lane fetches it (DPP), with the lanes that write.
let src0 = v.src.first().map(|o| lanes(o, &vec, &uni));
let mut writes = exec;
let fetched: Option<Vec<Sym>> = match (v.dpp, &src0) {
(Some(d), Some(s)) => {
if exec != all {
vec.insert(dst, vec![Sym::Unknown; wave as usize]);
continue;
}
let mut f = Vec::with_capacity(wave as usize);
let mut ok = true;
for l in 0..wave {
match dpp_lane(d, l) {
Some((src, zero, on)) if src < wave => {
f.push(if zero { Sym::K(0) } else { s[src as usize] });
if !on {
writes &= !(1u64 << l);
}
}
_ => ok = false,
}
}
ok.then_some(f)
}
(None, Some(s)) => Some(s.clone()),
_ => None,
};
let src = |k: usize| v.src.get(k).map(|o| lanes(o, &vec, &uni));
let result: Vec<Sym> = match (name, fetched) {
_ if modifiers => vec![Sym::Unknown; wave as usize],
("v_mov_b32", Some(a)) => a,
("v_bfrev_b32", Some(a)) => a
.into_iter()
.map(|s| match s {
Sym::K(k) => Sym::K(k.reverse_bits()),
_ => Sym::Unknown,
})
.collect(),
("v_cndmask_b32", Some(a)) => {
let mask = match v.src.get(2) {
Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
_ => None,
};
let b = src(1).unwrap_or_default();
(0..wave as usize)
.map(|l| match (a[l], b.get(l).copied(), mask) {
(Sym::K(ident), Some(Sym::Own(x)), Some(m)) if masked.contains(&m) => {
Sym::Red {
op: None,
src: x,
mask: m,
ident,
lanes: 1 << l,
}
}
_ => Sym::Unknown,
})
.collect()
}
("v_permlanex16_b32", Some(a)) => {
// Lanes of each row read the other row of their half; lane
// i's pick is nibble i of {src2, src1}.
let sel = |k: usize| match v.src.get(k) {
Some(&Operand::Const(c)) => crate::resource::inline(c),
Some(&Operand::Literal(x)) => Some(x),
_ => None,
};
match (sel(1), sel(2)) {
(Some(s1), Some(s2)) => {
let s = u64::from(s1) | u64::from(s2) << 32;
(0..wave)
.map(|l| {
let other = (l & !31) | ((l & 16) ^ 16);
let pick = (s >> (4 * (l & 15)) & 15) as u32;
a[(other | pick) as usize]
})
.collect()
}
_ => vec![Sym::Unknown; wave as usize],
}
}
("v_sub_nc_u32", Some(a)) => {
// A prefix sum less the lane's own term: the exclusive one.
let b = src(1).unwrap_or_default();
(0..wave as usize)
.map(|l| match (a[l], b.get(l).copied()) {
(
Sym::Red {
op: None | Some(Op::AddU),
src,
mask,
ident: 0,
lanes,
},
Some(Sym::Red {
op: None | Some(Op::AddU),
src: s2,
mask: m2,
ident: 0,
lanes: l2,
}),
) if (src, mask) == (s2, m2) && lanes & l2 == l2 => {
let rest = lanes & !l2;
if rest == 0 {
Sym::K(0)
} else {
Sym::Red {
op: Some(Op::AddU),
src,
mask,
ident: 0,
lanes: rest,
}
}
}
_ => Sym::Unknown,
})
.collect()
}
(n, Some(a)) => match (Op::of(n), src(1)) {
(Some(op), Some(b)) => (0..wave as usize)
.map(|l| combine(op, a[l], b[l]))
.collect(),
_ => vec![Sym::Unknown; wave as usize],
},
_ => vec![Sym::Unknown; wave as usize],
};
let merged = (0..wave as usize)
.map(|l| {
if writes >> l & 1 != 0 {
result[l]
} else {
old[l]
}
})
.collect();
vec.insert(dst, merged);
}
shapes(vec, uni, wave)
}
fn constant(inst: &Inst) -> Option<u64> {
let Fields::Sop { src, .. } = &inst.fields else {
return None;
};
match *src.first()? {
Operand::Const(c) => {
let x = crate::resource::inline(c)?;
Some(if (x as i32) < 0 {
u64::MAX
} else {
u64::from(x)
})
}
Operand::Literal(x) => Some(u64::from(x)),
_ => None,
}
}
/// The shape of each value, where every lane agrees on one.
fn shapes(
vec: HashMap<Value, Vec<Sym>>,
uni: HashMap<Value, Sym>,
wave: u32,
) -> HashMap<Value, Shape> {
let all = if wave == 64 {
u64::MAX
} else {
u64::from(u32::MAX)
};
let mut out = HashMap::new();
let single = |s: Sym| match s {
Sym::K(k) => Some(Shape::K(k)),
Sym::Own(x) | Sym::Uni(x) => Some(Shape::Value(x)),
Sym::Red {
op: Some(op),
src,
mask,
ident,
lanes,
} if lanes == all => Some(Shape::Active(op, src, mask, ident)),
_ => None,
};
for (v, s) in uni {
if let Some(sh) = single(s) {
out.insert(v, sh);
}
}
for (v, lanes) in vec {
if let Some(sh) = per_lane(&lanes, all) {
out.insert(v, sh);
}
}
out
}
fn per_lane(lanes: &[Sym], all: u64) -> Option<Shape> {
let first = lanes[0];
let own = |l: usize, s: Sym| match s {
Sym::Red {
op: None,
src,
mask,
ident,
lanes,
} if lanes == 1 << l => Some((src, mask, ident)),
_ => None,
};
if let Some(m) = own(0, first)
&& lanes.iter().enumerate().all(|(l, &s)| own(l, s) == Some(m))
{
return Some(Shape::Masked(m.0, m.1, m.2));
}
if lanes.iter().all(|&s| s == first) {
return match first {
Sym::K(k) => Some(Shape::K(k)),
Sym::Uni(x) | Sym::Own(x) => Some(Shape::Value(x)),
Sym::Red {
op: Some(op),
src,
mask,
ident,
lanes,
} if lanes == all => Some(Shape::Active(op, src, mask, ident)),
_ => None,
};
}
// Prefixes: lane l holds lanes 0..l (exclusive) or 0..=l (inclusive).
let mut found: Option<(Op, Value, Value, u32, bool)> = None;
for (l, &s) in lanes.iter().enumerate() {
let below = (1u64 << l) - 1;
let (op, src, mask, ident, set) = match s {
Sym::Red {
op,
src,
mask,
ident,
lanes,
} => (op, src, mask, ident, lanes),
// Lane 0 of an exclusive prefix holds the identity.
Sym::K(_) if l == 0 => continue,
_ => return None,
};
let inclusive = set == below | 1 << l;
if !inclusive && set != below {
return None;
}
let op = match (op, found) {
(Some(o), _) => o,
(None, Some(f)) => f.0,
(None, None) => continue,
};
let me = (op, src, mask, ident, inclusive);
match found {
None => found = Some(me),
Some(f) if f == me => {}
_ => return None,
}
}
let (op, src, mask, ident, inclusive) = found?;
if let Sym::K(k) = lanes[0]
&& (inclusive || k != ident)
{
return None;
}
Some(Shape::Prefix(op, src, mask, ident, inclusive))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dpp_lanes_follow_the_isa() {
// row_shr:1 with bound_ctrl: lane 16 reads 0, lane 17 lane 16.
let shr = Dpp::Row {
ctrl: 0x111,
row_mask: 0xF,
bank_mask: 0xF,
bound_ctrl: true,
fi: false,
};
assert_eq!(dpp_lane(shr, 16), Some((16, true, true)));
assert_eq!(dpp_lane(shr, 17), Some((16, false, true)));
// row_mirror: lane 3 reads lane 12.
let mirror = Dpp::Row {
ctrl: 0x140,
row_mask: 0xF,
bank_mask: 0xF,
bound_ctrl: true,
fi: false,
};
assert_eq!(dpp_lane(mirror, 3), Some((12, false, true)));
// dpp8 [1,0,3,2,5,4,7,6] swaps neighbours.
let swap = Dpp::Lanes {
sel: 1 | 3 << 6 | 2 << 9 | 5 << 12 | 4 << 15 | 7 << 18 | 6 << 21,
fi: false,
};
assert_eq!(dpp_lane(swap, 8), Some((9, false, true)));
}
#[test]
fn prefixes_are_recognised() {
let (x, m) = (Value(1), Value(2));
let red = |lanes: u64| Sym::Red {
op: Some(Op::AddU),
src: x,
mask: m,
ident: 0,
lanes,
};
let inclusive: Vec<Sym> = (0..64).map(|l| red(u64::MAX >> (63 - l))).collect();
assert_eq!(
per_lane(&inclusive, u64::MAX),
Some(Shape::Prefix(Op::AddU, x, m, 0, true))
);
let mut exclusive: Vec<Sym> = (0..64).map(|l| red((1u64 << l) - 1)).collect();
exclusive[0] = Sym::K(0);
assert_eq!(
per_lane(&exclusive, u64::MAX),
Some(Shape::Prefix(Op::AddU, x, m, 0, false))
);
assert_eq!(
per_lane(&vec![red(u64::MAX); 64], u64::MAX),
Some(Shape::Active(Op::AddU, x, m, 0))
);
}
}
+693
View File
@@ -0,0 +1,693 @@
//! I/O raising (decision 0003): what a program's input registers, its
//! interpolation and its exports mean.
//!
//! Pixel shaders get the VGPRs `SPI_PS_INPUT_ADDR` enables, in a fixed
//! order (barycentrics, then position, front face...). `v_interp_p1` and
//! `v_interp_p2` (and their f16 forms) evaluate an attribute from a pair of
//! barycentrics; `v_interp_mov` reads one vertex's value. After the 32-bit
//! export patch ([`NativeProgram::patched_code`]) exports carry plain
//! 32-bit values: `mrt<n>` is render target n, `mrtz` depth, stencil and
//! sample mask, `null` nothing. A lane whose EXEC bit is clear at the
//! export that ends the program (`done`) is discarded: that export's guard
//! after structurisation.
//!
//! Vertex shaders that run as the hardware VS get the vertex id in v0, the
//! primitive id in v2 and the instance id in v3; the fetch shader loads
//! channel k of each attribute into its VGPR + k. `exp pos0` is the
//! position, `exp param<n>` the output with parameter n.
//!
//! Attributes and outputs are named by their row: a register of the
//! container's signature part.
//!
//! Compute programs get the thread id in the group in v0-v2 and the group
//! id in the SGPRs after the user data, as `COMPUTE_PGM_RSRC2` enables them.
//!
//! Mesh programs run as one NGG stage. The program computes its thread
//! index from the wave index (s3 bits 24-27) and the lane (`v_mbcnt`), and
//! its group id from v5 of the first lane (`v_readfirstlane`: the group
//! times the group size). Lane n exports vertex n (`exp pos`, `exp param`)
//! and primitive n (`exp prim`: 10-bit vertex indices at bits 0, 10, 20,
//! bit 31 culls); `param` entries with bit 7 are per-primitive outputs. One
//! lane sends the output counts (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices |
//! primitives << 12).
use crate::ShaderError;
use crate::gfx10::{Fields, Operand};
use crate::ir::{Inst, Program, Reg, Value};
use crate::native::{HwStage, NativeProgram, PsInput, StageIo, Usage};
use crate::resource::Site;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Input {
VertexId,
PrimitiveId,
InstanceId,
/// A vertex attribute the fetch shader loads.
Attribute {
row: u8,
channel: u8,
},
/// `index` 0 is i, 1 is j (2 the pull model's w).
Barycentric {
kind: Barycentric,
index: u8,
},
/// Pixel position channel (0-3: x, y, z, w).
Position(u8),
FrontFace,
/// Sample id and other bits.
Ancillary,
SampleCoverage,
FixedPosition,
LineStipple,
/// Compute: thread-group id component (an SGPR).
GroupId(u8),
/// Compute: thread id within the group, component (a VGPR).
ThreadIdInGroup(u8),
/// Compute: the thread-group info SGPR (wave index and count).
GroupInfo,
/// Mesh: v5, the group id times the group size (read as uniform).
MeshGroup,
/// Mesh: s3, the wave's index in the group in bits 24-27.
MergedWaveInfo,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Barycentric {
PerspectiveSample,
PerspectiveCenter,
PerspectiveCentroid,
PerspectivePullModel,
LinearSample,
LinearCenter,
LinearCentroid,
}
/// The pixel input VGPRs in hardware order: one entry per
/// `SPI_PS_INPUT_ADDR` bit.
const PS_VGPRS: [(u8, Option<Barycentric>); 16] = [
(2, Some(Barycentric::PerspectiveSample)),
(2, Some(Barycentric::PerspectiveCenter)),
(2, Some(Barycentric::PerspectiveCentroid)),
(3, Some(Barycentric::PerspectivePullModel)),
(2, Some(Barycentric::LinearSample)),
(2, Some(Barycentric::LinearCenter)),
(2, Some(Barycentric::LinearCentroid)),
(1, None), // line stipple
(1, None), // position x
(1, None), // y
(1, None), // z
(1, None), // w
(1, None), // front face
(1, None), // ancillary
(1, None), // sample coverage
(1, None), // fixed-point position
];
fn ps_system(bit: usize) -> Input {
match bit {
7 => Input::LineStipple,
8..=11 => Input::Position(bit as u8 - 8),
12 => Input::FrontFace,
13 => Input::Ancillary,
14 => Input::SampleCoverage,
_ => Input::FixedPosition,
}
}
/// An attribute channel of the input signature.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Attribute {
pub usage: Usage,
pub row: u8,
pub channel: u8,
/// The upper f16 half of the channel (packed fp16 inputs).
pub high: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Interp {
/// This site's result (`v_interp_p2*`) is the attribute interpolated
/// with `barycentric`; `first` are the `v_interp_p1*` halves it
/// completes (one per path where the compiler shares a first half).
Interpolated {
attribute: Attribute,
barycentric: Barycentric,
first: Vec<Site>,
},
/// One vertex's value (`v_interp_mov_f32`), as encoded: 0 for P10,
/// 1 for P20, 2 for P0 (the provoking vertex).
Vertex { attribute: Attribute, vertex: u8 },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Target {
Color(u8),
/// Depth, stencil, sample mask (channels as `DB_SHADER_CONTROL` enables).
Depth,
Null,
Position(u8),
Param {
usage: Usage,
row: u8,
},
/// `param0` of a vertex shader without outputs: the hardware wants one
/// parameter export regardless.
Unread,
/// The primitive export of a merged or mesh stage.
Primitive,
/// A mesh program's per-primitive output (a row of `PSG1`).
PrimitiveParam {
usage: Usage,
row: u8,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Export {
pub site: Site,
pub target: Target,
/// Per channel, as the instruction enables them.
pub values: [Option<Value>; 4],
/// Two f16 values per dword.
pub compressed: bool,
/// The program's last export (for pixels: kills the lanes not in EXEC).
pub done: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Io {
/// Input values the hardware loads, with their meaning; other VGPRs
/// read before written hold undefined values.
pub inputs: Vec<(Value, Input)>,
pub interps: Vec<(Site, Interp)>,
pub exports: Vec<Export>,
}
/// Raises the I/O of `p`, built from `native`'s patched code. Fails for
/// stages whose stage data is not read and on constructs not covered yet.
pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> {
let unsupported = |offset, what| ShaderError::Unsupported { offset, what };
let (loaded, ps_inputs, params) = match (&native.io, native.stage) {
(
StageIo::Ps {
inputs, input_addr, ..
},
HwStage::Ps,
) => {
// A pixel shader exports no parameters; `[]` never reaches `Unread`.
let loaded = ps_vgprs(*input_addr)
.into_iter()
.map(|(r, i)| (Reg::V(r), i))
.collect();
(loaded, &inputs[..], &[][..])
}
(StageIo::Vs { inputs, outputs }, HwStage::Vs) => {
let mut loaded = vec![
(Reg::V(0), Input::VertexId),
(Reg::V(2), Input::PrimitiveId),
(Reg::V(3), Input::InstanceId),
];
for i in inputs {
for channel in (0..4).filter(|c| i.mask >> c & 1 != 0) {
let input = Input::Attribute {
row: i.row,
channel,
};
loaded.push((Reg::V(i.vgpr + channel), input));
}
}
(loaded, &[][..], &outputs[..])
}
// Compute: thread ids in v0-v2, group ids and the group info in the
// SGPRs after the user data.
(StageIo::Cs(cs), HwStage::Cs) => {
let (ids, info) = cs.system_sgprs();
let mut loaded: Vec<(Reg, Input)> = (0..cs.thread_id_vgprs())
.map(|c| (Reg::V(c), Input::ThreadIdInGroup(c)))
.collect();
for (c, s) in ids.into_iter().enumerate() {
if let Some(s) = s {
loaded.push((Reg::S(s), Input::GroupId(c as u8)));
}
}
loaded.extend(info.map(|s| (Reg::S(s), Input::GroupInfo)));
(loaded, &[][..], &[][..])
}
(StageIo::Ms(ms), HwStage::Ms) => {
let group = p.inputs.iter().find(|i| i.0 == Reg::V(5)).map(|i| i.1);
// The group input holds the same value in every lane only as the
// first lane reads it; a VGPR write reads its old value too.
let per_lane = p.blocks.iter().flat_map(|b| &b.insts).find(|i| {
group.is_some_and(|g| i.reads.contains(&(Reg::V(5), g)))
&& i.name() != "v_readfirstlane_b32"
&& i.write(Reg::V(5)).is_none()
});
if let Some(i) = per_lane {
return Err(unsupported(
i.machine.offset,
"the mesh group input read per lane",
));
}
let loaded = vec![
(Reg::V(5), Input::MeshGroup),
(Reg::S(3), Input::MergedWaveInfo),
];
(loaded, &[][..], &ms.outputs[..])
}
_ => return Err(unsupported(0, "I/O of this stage")),
};
let inputs: Vec<(Value, Input)> = p
.inputs
.iter()
.filter_map(|&(reg, v)| loaded.iter().find(|l| l.0 == reg).map(|l| (v, l.1)))
.collect();
let input_of = |v: Value| inputs.iter().find(|i| i.0 == v).map(|i| i.1);
let attribute = |inst: &Inst, attr: &Operand| match *attr {
Operand::Attr { index, chan, high } => ps_inputs
.iter()
.find(|i: &&PsInput| i.attr == index)
.map(|i| Attribute {
usage: i.usage,
row: i.row,
channel: chan,
high,
})
.ok_or(unsupported(
inst.machine.offset,
"an interpolated attribute the stage data does not list",
)),
_ => Err(unsupported(inst.machine.offset, "an interpolation operand")),
};
// A VGPR value's barycentric kind and index, if it is one as loaded.
let barycentric = |v: Option<Value>| match v.and_then(input_of) {
Some(Input::Barycentric { kind, index }) => Some((kind, index)),
_ => None,
};
let mut io = Io {
inputs: inputs.clone(),
..Io::default()
};
let defs: std::collections::HashMap<Value, Site> = p
.blocks
.iter()
.enumerate()
.flat_map(|(b, block)| {
block
.insts
.iter()
.enumerate()
.flat_map(move |(i, inst)| inst.writes.iter().map(move |w| (w.1, (b, i))))
})
.collect();
let phis: std::collections::HashMap<Value, (usize, usize)> = p
.blocks
.iter()
.enumerate()
.flat_map(|(b, block)| {
block
.phis
.iter()
.enumerate()
.map(move |(i, phi)| (phi.value, (b, i)))
})
.collect();
let halves = Halves {
p,
defs: &defs,
phis: &phis,
};
for (b, block) in p.blocks.iter().enumerate() {
for (i, inst) in block.insts.iter().enumerate() {
let site = (b, i);
let at = inst.machine.offset;
let name = inst.name();
match &inst.fields {
Fields::Vintrp { dst, src, attr } => {
let attribute = attribute(inst, attr)?;
match (name, *src) {
("v_interp_mov_f32", Operand::Const(vertex)) => {
io.interps
.push((site, Interp::Vertex { attribute, vertex }));
}
("v_interp_p1_f32", _) => {}
("v_interp_p2_f32", Operand::Vector { reg, .. }) => {
let Operand::Vector { reg: d, .. } = *dst else {
return Err(unsupported(at, "an interpolation operand"));
};
// The first half's result is this one's old dst.
let interp = halves
.pair(
attr,
inst.read(Reg::V(d)),
inst.read(Reg::V(reg)),
&barycentric,
)
.map_err(|what| unsupported(at, what))?;
io.interps.push((site, interp.with(attribute)));
}
_ => return Err(unsupported(at, "an interpolation form")),
}
}
Fields::Valu(v) if name.starts_with("v_interp_") => match name {
"v_interp_p1ll_f16" => {}
"v_interp_p2_f16" => {
let attribute = attribute(inst, &v.src[0])?;
let read = |k: usize| match v.src.get(k) {
Some(&Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)),
_ => None,
};
let interp = halves
.pair(&v.src[0], read(2), read(1), &barycentric)
.map_err(|what| unsupported(at, what))?;
io.interps.push((site, interp.with(attribute)));
}
_ => return Err(unsupported(at, "an interpolation form")),
},
Fields::Exp {
target,
src,
compr,
done,
..
} => {
let target = match *target {
t @ 0..=7 => Target::Color(t),
8 => Target::Depth,
9 => Target::Null,
t @ 12..=16 => Target::Position(t - 12),
20 => Target::Primitive,
32 if params.is_empty() => Target::Unread,
t @ 32..=63 => {
// Bit 7: a mesh program's per-primitive output.
let o = params.iter().find(|o| o.param & 0x7F == t - 32).ok_or(
unsupported(at, "a parameter export the stage data does not list"),
)?;
let (usage, row) = (o.usage, o.row);
if o.param & 0x80 != 0 {
Target::PrimitiveParam { usage, row }
} else {
Target::Param { usage, row }
}
}
_ => return Err(unsupported(at, "an export target")),
};
let values = src.map(|s| match s {
Some(Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)),
_ => None,
});
io.exports.push(Export {
site,
target,
values,
compressed: *compr,
done: *done,
});
}
_ => {}
}
}
}
Ok(io)
}
/// The pixel input VGPRs that `addr` enables, with their meaning.
fn ps_vgprs(addr: u32) -> Vec<(u8, Input)> {
let mut out = Vec::new();
let mut next = 0u8;
for (bit, &(count, kind)) in PS_VGPRS.iter().enumerate() {
if addr >> bit & 1 == 0 {
continue;
}
for index in 0..count {
let input = match kind {
Some(kind) => Input::Barycentric { kind, index },
None => ps_system(bit),
};
out.push((next + index, input));
}
next += count;
}
out
}
/// An interpolation before its attribute is known.
struct Pair {
barycentric: Barycentric,
first: Vec<Site>,
}
impl Pair {
fn with(self, attribute: Attribute) -> Interp {
Interp::Interpolated {
attribute,
barycentric: self.barycentric,
first: self.first,
}
}
}
/// Finds the first halves of interpolations.
struct Halves<'a> {
p: &'a Program,
defs: &'a std::collections::HashMap<Value, Site>,
phis: &'a std::collections::HashMap<Value, (usize, usize)>,
}
impl Halves<'_> {
/// The interpolation whose second half reads the first half's result
/// `acc`, the barycentric `j`, and attribute `attr`: every first half
/// must read the same attribute channel and the same kind's i.
fn pair(
&self,
attr: &Operand,
acc: Option<Value>,
j: Option<Value>,
barycentric: &impl Fn(Option<Value>) -> Option<(Barycentric, u8)>,
) -> Result<Pair, &'static str> {
let mut first = Vec::new();
self.sites(
acc.ok_or("an interpolation without its first half")?,
&mut Vec::new(),
&mut first,
)?;
let Some((kind, 1)) = barycentric(j) else {
return Err("an interpolation with computed barycentrics");
};
for &(b, i) in &first {
let inst = &self.p.blocks[b].insts[i];
let (a, i) = match &inst.fields {
Fields::Vintrp {
src: Operand::Vector { reg, .. },
attr,
..
} if inst.name() == "v_interp_p1_f32" => (*attr, inst.read(Reg::V(*reg))),
Fields::Valu(v) if inst.name() == "v_interp_p1ll_f16" => match v.src.get(1) {
Some(&Operand::Vector { reg, .. }) => (v.src[0], inst.read(Reg::V(reg))),
_ => return Err("an interpolation without its first half"),
},
_ => return Err("an interpolation without its first half"),
};
if a != *attr {
return Err("interpolation halves of different attributes");
}
if barycentric(i) != Some((kind, 0)) {
return Err("an interpolation with computed barycentrics");
}
}
Ok(Pair {
barycentric: kind,
first,
})
}
/// The instructions `v` comes from, through phis (`seen`: phis on the
/// way; a loop back to one adds nothing).
fn sites(
&self,
v: Value,
seen: &mut Vec<Value>,
out: &mut Vec<Site>,
) -> Result<(), &'static str> {
if let Some(&site) = self.defs.get(&v) {
if !out.contains(&site) {
out.push(site);
}
return Ok(());
}
let &(b, i) = self
.phis
.get(&v)
.ok_or("an interpolation without its first half")?;
if !seen.contains(&v) {
seen.push(v);
for &a in &self.p.blocks[b].phis[i].args {
self.sites(a, seen, out)?;
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::native::ExportPatch;
const S_ENDPGM: u32 = 0xBF81_0000;
fn program(words: &[u32]) -> Program {
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
crate::ir::build(&code, false, 256).unwrap()
}
fn pixel(inputs: Vec<PsInput>, input_addr: u32) -> NativeProgram {
NativeProgram {
stage: HwStage::Ps,
wave64: false,
vgprs: 256,
layout: vec![],
used: vec![],
io: StageIo::Ps {
inputs,
input_addr,
db_shader_control: 0,
patches: Vec::<ExportPatch>::new(),
},
code: vec![],
}
}
const TEXCOORD: PsInput = PsInput {
usage: Usage::Generic,
row: 1,
mask: 3,
attr: 0,
flat: false,
fp16: false,
pack2: false,
row2: 1,
};
#[test]
fn interpolation_pairs_and_color_exports() {
// Blit's pixel shader: TEXCOORD.xy from the perspective-center i/j
// in v0/v1, then exported unconverted to MRT0.
let p = program(&[
0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
0xF800_180F,
0x0302_0102, // exp mrt0, v2, v1, v2, v3 done vm
S_ENDPGM,
]);
let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap();
let input = |reg| p.inputs.iter().find(|i| i.0 == Reg::V(reg)).unwrap().1;
let center = |index| Input::Barycentric {
kind: Barycentric::PerspectiveCenter,
index,
};
assert!(io.inputs.contains(&(input(0), center(0))));
assert!(io.inputs.contains(&(input(1), center(1))));
// v2 and v3 are read before written but hold nothing.
assert!(!io.inputs.iter().any(|i| i.0 == input(3)));
assert_eq!(
io.interps,
[(
(0, 1),
Interp::Interpolated {
attribute: Attribute {
usage: Usage::Generic,
row: 1,
channel: 0,
high: false
},
barycentric: Barycentric::PerspectiveCenter,
first: vec![(0, 0)],
}
)]
);
let [e] = &io.exports[..] else {
panic!("{:?}", io.exports)
};
assert_eq!(
(e.target, e.done, e.compressed),
(Target::Color(0), true, false)
);
assert_eq!(e.values[0], p.blocks[0].insts[1].write(Reg::V(2)));
}
#[test]
fn unpaired_or_unknown_interpolation_fails() {
// p2 alone: its old dst is no p1's result.
let lone = program(&[0xC809_0001, S_ENDPGM]); // v_interp_p2_f32 v2, v1, attr0.x
assert!(raise(&lone, &pixel(vec![TEXCOORD], 2)).is_err());
// attr1 is not in the stage data.
let other = program(&[0xC808_0400, S_ENDPGM]); // v_interp_p1_f32 v2, v0, attr1.x
assert!(raise(&other, &pixel(vec![TEXCOORD], 2)).is_err());
}
#[test]
fn mesh_inputs_and_primitive_export() {
let mesh = |words: &[u32]| {
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
let p = crate::ir::build(&code, true, 256).unwrap();
let native = NativeProgram {
stage: HwStage::Ms,
wave64: true,
vgprs: 256,
layout: vec![],
used: vec![],
io: StageIo::Ms(crate::native::MeshIo {
outputs: vec![],
clip_cntl: 0,
threads: 128,
max_vertices: 128,
max_primitives: 128,
topology: 2,
lds_bytes: 0,
}),
code,
};
raise(&p, &native)
};
let io = mesh(&[
0x7E04_0505, // v_readfirstlane_b32 s2, v5
0xF800_0941,
0x0000_0009, // exp prim, v9, off, off, off done
S_ENDPGM,
])
.unwrap();
assert!(io.inputs.iter().any(|i| i.1 == Input::MeshGroup));
assert_eq!(io.exports[0].target, Target::Primitive);
// The group input is uniform only as the first lane reads it.
assert!(mesh(&[0x7E02_0305, S_ENDPGM]).is_err()); // v_mov_b32 v1, v5
}
#[test]
fn pixel_vgprs_follow_the_input_address() {
// Linear center (bit 5), then position x and y (bits 8, 9).
let v = ps_vgprs(1 << 5 | 1 << 8 | 1 << 9);
assert_eq!(
v,
[
(
0,
Input::Barycentric {
kind: Barycentric::LinearCenter,
index: 0
}
),
(
1,
Input::Barycentric {
kind: Barycentric::LinearCenter,
index: 1
}
),
(2, Input::Position(0)),
(3, Input::Position(1)),
]
);
}
}
+52 -15
View File
@@ -360,7 +360,32 @@ pub(crate) fn irreducible_edge(
index: &[usize],
) -> Option<(usize, usize)> {
let &entry = order.first()?;
let idom = idoms(blocks, order, index);
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
}
/// Each block's immediate dominator (the entry's is itself, unreachable
/// blocks' `usize::MAX`); `order` is reverse postorder, `index` each
/// block's position in it.
pub(crate) fn idoms(blocks: &[Block], order: &[usize], index: &[usize]) -> Vec<usize> {
let mut idom = vec![usize::MAX; blocks.len()];
let Some(&entry) = order.first() else {
return idom;
};
idom[entry] = entry;
let intersect = |idom: &[usize], mut a: usize, mut b: usize| {
while a != b {
@@ -391,21 +416,7 @@ pub(crate) fn irreducible_edge(
}
}
}
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
idom
}
/// Node splitting, before SSA. While a loop is entered at several blocks
@@ -692,6 +703,13 @@ fn effects(
}
if let Some(d) = dst {
regs(d, &mut w)?;
// These change (or may keep) the destination's old value.
if name.starts_with("s_bitset")
|| name.starts_with("s_cmov")
|| matches!(name, "s_addk_i32" | "s_mulk_i32")
{
regs(d, &mut r)?;
}
}
if matches!(name, "s_addc_u32" | "s_subb_u32" | "s_cmovk_i32")
|| name.starts_with("s_cselect_")
@@ -1063,6 +1081,25 @@ mod tests {
}
}
#[test]
fn in_place_scalar_ops_read_their_destination() {
let p = build_words(
&[
0xBE8D_1D94, // s_bitset1_b32 s13, 20
0xB78E_0010, // s_addk_i32 s14, 0x10
0xBE8F_0380, // s_mov_b32 s15, 0
S_ENDPGM,
],
false,
);
let [bitset, addk, mov, _] = &p.blocks[0].insts[..] else {
panic!("{:?}", p.blocks[0].insts)
};
assert_eq!(bitset.read(Reg::S(13)), Some(input(&p, Reg::S(13))));
assert_eq!(addk.read(Reg::S(14)), Some(input(&p, Reg::S(14))));
assert_eq!(mov.read(Reg::S(15)), None);
}
#[test]
fn loops_carry_values_through_phis() {
let p = build_words(
+6 -1
View File
@@ -8,14 +8,19 @@
pub mod dxbc;
pub mod dxil;
pub mod emit;
pub mod gfx10;
pub mod io;
pub mod ir;
pub mod native;
pub mod resource;
pub mod structure;
pub use dxbc::{Container, FourCC, Part};
pub use dxil::{DxilProgram, ShaderKind, XboxExtras};
pub use native::{HwStage, NativeProgram, native_programs};
pub use native::{
HwStage, NativeProgram, ResourceType, RootParam, RootType, UsedResource, native_programs,
};
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ShaderError {
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more