Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions apps/victory/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,8 @@ pub fn run(
}
let exe_name = exe.file_name().unwrap_or_default().to_string_lossy();
show(&exe_name, image.bind_imports(&with_dlls, policy)?);
#[cfg(windows)]
apply_patches(image.base());
if !execute {
println!("not executing (pass --execute to start the title)");
return Ok(0);
Expand Down Expand Up @@ -514,3 +516,88 @@ mod tests {
pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool, _: Console, _: &[String]) -> Result<u32> {
anyhow::bail!("running titles requires Windows")
}


/// Local build (techniques from Palmwave, an XCL fork, for Grand Theft Auto VI 1.0.2.1): patches
/// of the title's code in memory (the file is never touched), each written only where the bytes
/// it expects are found, so another build of the title is left alone.
/// `VICTORY_PATCH=<rva>:<expected hex>=<new hex>;...` adds patches; `VICTORY_PATCH_DEFAULTS=0`
/// drops the built-in ones (`VICTORY_PATCH_SKIP=<n>,...` drops some of them, by number).
#[cfg(windows)]
fn apply_patches(base: usize) {
#[link(name = "kernel32")]
unsafe extern "system" {
fn VirtualProtect(address: *const core::ffi::c_void, size: usize, protect: u32, old: *mut u32) -> i32;
}
const PAGE_EXECUTE_READWRITE: u32 = 0x40;
// (number, rva, expected, new, what)
const DEFAULTS: [(u32, usize, &str, &str, &str); 10] = [
(1, 0x2215bdc, "732e", "9090", "hang detector"),
(2, 0x2215c70, "7404", "9090", "hang detector"),
(3, 0x2215d84, "7404", "9090", "hang detector"),
(4, 0x22a3b5, "e8a6f7ffff", "31c0909090", "indirect diffuse / stochastic reflection pass"),
(5, 0x22aee6, "e875ecffff", "31c0909090", "indirect diffuse / stochastic reflection pass"),
(6, 0x7b4e6a, "8b8944010000", "b90100000090", "world render resolution mode"),
(7, 0x25d2fe2, "e819a4ffff", "0f1f440000", "alpha-resolve blur / scattering / ray-marched gather"),
(8, 0x327b92e, "7408", "9090", "alpha-resolve blur / scattering / ray-marched gather"),
(9, 0x125912d, "e85ef50102", "0f1f440000", "alpha-resolve blur / scattering / ray-marched gather"),
(10, 0x5267747, "0f84ae050000", "0f8432050000", "audio lock stop after ~2 minutes"),
];
let hex = |s: &str| -> Option<Vec<u8>> {
let s = s.trim();
(s.len() % 2 == 0).then_some(())?;
(0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok()).collect()
};
let mut skip: Vec<u32> = std::env::var("VICTORY_PATCH_SKIP")
.unwrap_or_default()
.split(',')
.filter_map(|n| n.trim().parse().ok())
.collect();
// Patches 4, 5 and 7-9 switch off the title's lighting passes (indirect
// diffuse, scattering, ray-marched gather): with them interiors came out
// black (run vu14 against vu15). Only with VICTORY_PATCH_HEAVY=1.
if std::env::var("VICTORY_PATCH_HEAVY").map_or(true, |v| v.trim() != "1") {
skip.extend([4, 5, 7, 8, 9]);
}
let mut list: Vec<(String, usize, Vec<u8>, Vec<u8>)> = Vec::new();
if std::env::var("VICTORY_PATCH_DEFAULTS").map_or(true, |v| v.trim() != "0") {
for (n, rva, old, new, what) in DEFAULTS {
if !skip.contains(&n) {
list.push((format!("{n} ({what})"), rva, hex(old).unwrap(), hex(new).unwrap()));
}
}
}
for entry in std::env::var("VICTORY_PATCH").unwrap_or_default().split(';').filter(|e| !e.trim().is_empty()) {
let parsed = (|| {
let (rva, rest) = entry.split_once(':')?;
let (old, new) = rest.split_once('=')?;
let rva = usize::from_str_radix(rva.trim().trim_start_matches("0x"), 16).ok()?;
Some((rva, hex(old)?, hex(new)?))
})();
match parsed {
Some((rva, old, new)) if old.len() == new.len() => list.push((entry.trim().to_string(), rva, old, new)),
_ => println!("patch ignored (bad syntax): {entry}"),
}
}
for (name, rva, old, new) in list {
let at = base + rva;
// SAFETY: an address inside the title's image, which we mapped; read and written
// only after checking the expected bytes, with the page made writable for the write.
unsafe {
let here = std::slice::from_raw_parts(at as *const u8, old.len());
if here != old.as_slice() {
println!("patch {name}: not applied (bytes differ: another build?)");
continue;
}
let mut prot = 0u32;
if VirtualProtect(at as *const _, new.len(), PAGE_EXECUTE_READWRITE, &mut prot) == 0 {
println!("patch {name}: not applied (page protection)");
continue;
}
std::ptr::copy_nonoverlapping(new.as_ptr(), at as *mut u8, new.len());
let mut back = 0u32;
VirtualProtect(at as *const _, new.len(), prot, &mut back);
println!("patch {name}: applied at +{rva:#x}");
}
}
}
102 changes: 86 additions & 16 deletions crates/victory-gpu/src/draw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1052,6 +1052,8 @@ impl State {
#[cfg(feature = "diagnostics")]
list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
#[cfg(feature = "diagnostics")]
self.trace_dispatch(&p.name, x, y, z);
#[cfg(feature = "diagnostics")]
self.probe_small(list, true);
// SAFETY: an open list with everything set.
unsafe { list.list.Dispatch(x, y, z) };
Expand Down Expand Up @@ -1340,11 +1342,11 @@ impl State {
let targets: Vec<String> = self
.targets
.iter()
.filter_map(|&t| crate::resource::host_resource(t as This))
.map(|t| {
.filter_map(|&t| {
let res = crate::resource::host_resource(t as This)?;
// SAFETY: a live resource.
let d = unsafe { t.GetDesc() };
format!("{}x{} f{}", d.Width, d.Height, d.Format.0)
let d = unsafe { res.GetDesc() };
Some(format!("{t:#x} {}x{} f{}", d.Width, d.Height, d.Format.0))
})
.collect();
let v = self.vertex[0];
Expand All @@ -1366,6 +1368,22 @@ impl State {
}
}

/// Dispatches in listed frames, at debug level: their pipeline, shaders,
/// and what they read and write (diagnostics builds).
#[cfg(feature = "diagnostics")]
fn trace_dispatch(&self, shaders: &str, x: u32, y: u32, z: u32) {
if !tracing::enabled!(tracing::Level::DEBUG)
|| !crate::capture::listed(crate::queue::presented() + 1)
{
return;
}
tracing::debug!(
"dispatch {x}x{y}x{z} pipeline {:#x} {shaders} reads {:?}",
self.pipeline,
self.reads(true)
);
}

/// In a listed frame: each small buffer (64 bytes at most) the draw's
/// tables name, as title memory now and as its host copy when the list
/// is submitted (before the GPU runs it) and after it has run.
Expand Down Expand Up @@ -1505,6 +1523,15 @@ impl State {
});
text
}
(RootType::Descriptor, Some(Root::View(address))) => {
let rw = match u.kind {
ResourceType::Uav => "uav",
ResourceType::Srv => "srv",
ResourceType::Cbv => "cbv",
_ => "view",
};
format!("{rw} root {address:#x}")
}
(root, _) => format!("{root:?}"),
};
out.push(format!(
Expand Down Expand Up @@ -1936,18 +1963,33 @@ fn describe(view: Option<&View>) -> String {
};
match view {
None => "no view".into(),
Some(v @ View::Shader(r, _)) => texture(*r as This).unwrap_or_else(|| {
let range = crate::descriptor::host::buffer_range(v);
format!("buffer {range:?}{}", small(range))
}),
// A buffer has no host texture: its title range, as for a shader view.
Some(v @ View::Unordered(r, ..)) => texture(*r as This).map_or_else(
|| {
let range = crate::descriptor::host::buffer_range(v);
format!("uav buffer {range:?}{}", small(range))
},
|t| format!("uav {t}"),
),
Some(v @ (View::Shader(r, _) | View::Unordered(r, ..))) => {
let kind = if matches!(v, View::Unordered(..)) {
"uav"
} else {
"srv"
};
match texture(*r as This) {
Some(t) => format!("{kind} {r:#x} {t}"),
None => {
let range = crate::descriptor::host::buffer_range(v);
match range {
Some((at, len)) => {
format!("{kind} {r:#x} buffer {at:#x}+{len}{}", small(range))
}
None => {
let mem = crate::resource::texture_memory(*r as This)
.map_or(0, |(p, _)| p as u64);
if mem != 0 {
format!("{kind} {r:#x} mem {mem:#x}")
} else {
format!("{kind} {r:#x}")
}
}
}
}
}
}
Some(View::Placed(u, r, d)) => format!(
"placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}",
r[0],
Expand Down Expand Up @@ -2809,6 +2851,34 @@ void main() {
// SAFETY: plain device query.
assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok());
}

#[cfg(feature = "diagnostics")]
#[test]
fn describe_includes_kind_and_resource_address() {
assert_eq!(describe(None), "no view");
assert_eq!(describe(Some(&View::Shader(0, None))), "srv 0x0");
assert_eq!(describe(Some(&View::Unordered(0, 0, None))), "uav 0x0");

let buf = buffer(256);
let (addr, _) = crate::resource::buffer_bytes(buf).unwrap();
let addr = addr as u64;
// Raw buffer SRV and UAV (format R32_TYPELESS=39, dim BUFFER=1, raw flag=1).
let srv_words = [39, 1, 0x1688, 0, 0, 0, 64, 0, 1, 0];
let uav_words = [39, 1, 0, 0, 64, 0, 0, 0, 1, 0];
let srv = describe(Some(&View::Shader(buf as usize, Some(srv_words))));
let uav = describe(Some(&View::Unordered(buf as usize, 0, Some(uav_words))));
assert_eq!(srv, format!("srv {:#x} buffer {addr:#x}+256", buf as usize));
assert_eq!(uav, format!("uav {:#x} buffer {addr:#x}+256", buf as usize));

if crate::host::host().is_some() {
let mem = title_memory(1 << 20);
let tex = texture_at_address(mem, &texture_words(64, 64, 28, 0x105, 4));
let tex_srv = describe(Some(&View::Shader(tex as usize, None)));
let tex_uav = describe(Some(&View::Unordered(tex as usize, 0, None)));
assert!(tex_srv.starts_with(&format!("srv {:#x} 64x64 ", tex as usize)), "{tex_srv}");
assert!(tex_uav.starts_with(&format!("uav {:#x} 64x64 ", tex as usize)), "{tex_uav}");
}
}
}

#[cfg(all(test, feature = "diagnostics"))]
Expand Down
106 changes: 100 additions & 6 deletions crates/victory-gpu/src/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,39 @@ struct Layout {
owner: Vec<Option<usize>>,
}

/// `VICTORY_SPARSE_PAGE_BITMAP=0` restores the original bitmap scans.
fn sparse_page_bitmap() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| !std::env::var("VICTORY_SPARSE_PAGE_BITMAP").is_ok_and(|v| v.trim() == "0"))
}

impl Layout {
/// Whether any mark names a missing page or a region with no block.
fn has_misses(&self, marks: &[u32], sparse: bool) -> bool {
let is_missing = |entry: usize| {
entry / BLOCK == 0
|| entry / BLOCK >= self.blocks.len()
|| self.owner.get(entry).is_none_or(Option::is_none)
};
if sparse {
for (w, &mark) in marks.iter().enumerate() {
let mut bits = mark;
while bits != 0 {
let entry = w * 32 + bits.trailing_zeros() as usize;
if is_missing(entry) {
return true;
}
bits &= bits - 1;
}
}
return false;
}
marks.iter().enumerate().any(|(w, &mark)| {
(0..32).filter(|b| mark >> b & 1 != 0).any(|b| is_missing(w * 32 + b))
})
}
}

/// A view heap's page table, shared by every list using title memory with
/// the heap bound, and the view pairs of the copies it names.
struct Shared {
Expand Down Expand Up @@ -395,12 +428,7 @@ pub(crate) fn bind(list: &HostList, key: usize) -> Option<Map> {
let l = layout(key);
// SAFETY: the bitmap is mapped and the list's run is over.
let marks = unsafe { std::slice::from_raw_parts(data as *const u32, words) };
marks.iter().enumerate().any(|(w, &mark)| {
(0..32).filter(|b| mark >> b & 1 != 0).any(|b| {
let entry = w * 32 + b;
entry / BLOCK == 0 || l.blocks.get(entry / BLOCK).is_none() || l.owner.get(entry).is_none_or(|o| o.is_none())
})
})
l.has_misses(marks, sparse_page_bitmap())
});
list.defer_after(move || {
let Layout { copies, blocks, owner } = &*layout(key);
Expand All @@ -412,7 +440,11 @@ pub(crate) fn bind(list: &HostList, key: usize) -> Option<Map> {
let marks = unsafe { std::slice::from_raw_parts_mut(data as *mut u32, words) };
let (mut pages, mut regions, mut missed) = (0, 0, Vec::new());
let mut writes = Vec::new();
let sparse = sparse_page_bitmap();
for (w, mark) in marks.iter_mut().enumerate() {
if sparse && *mark == 0 {
continue;
}
let mut bits = std::mem::take(mark);
while bits != 0 {
let entry = w * 32 + bits.trailing_zeros() as usize;
Expand Down Expand Up @@ -472,6 +504,68 @@ pub(crate) fn bind(list: &HostList, key: usize) -> Option<Map> {
mod tests {
use super::*;

#[test]
fn sparse_page_bitmap_matches_named_pages_and_misses() {
let mut layout = Layout {
blocks: vec![usize::MAX, 1, 2],
owner: vec![Some(0); 3 * BLOCK - 1],
..Layout::default()
};
layout.owner[2 * BLOCK + 32] = None;
for (entries, expected) in [
(vec![], false),
(vec![BLOCK + 31, 2 * BLOCK + 31], false),
(vec![BLOCK + 1, 2 * BLOCK + 32], true),
(vec![31, BLOCK + 31], true),
(vec![3 * BLOCK - 1], true),
(vec![3 * BLOCK + 33], true),
] {
let mut marks = vec![0; (4 * BLOCK) / 32];
for entry in entries {
marks[entry / 32] |= 1 << (entry % 32);
}
assert_eq!(layout.has_misses(&marks, false), expected);
assert_eq!(layout.has_misses(&marks, true), expected);
}
}

#[test]
#[ignore = "offline performance benchmark"]
fn sparse_page_bitmap_benchmark() {
use std::hint::black_box;
use std::time::Instant;

let layout = Layout {
blocks: vec![0; 33],
owner: vec![Some(0); 33 * BLOCK],
..Layout::default()
};
let mut marks = vec![0; ((CAPACITY + 1) * BLOCK) / 32];
for entry in (BLOCK..33 * BLOCK).step_by(1021) {
marks[entry / 32] |= 1 << (entry % 32);
}
for (label, first) in [("all pages named", 0), ("early region miss", 8)] {
marks[0] = first;
let mut times = [Vec::new(), Vec::new()];
for sample in 0..10 {
for mode in [sample % 2, 1 - sample % 2] {
let start = Instant::now();
for _ in 0..40 {
black_box(layout.has_misses(black_box(&marks), mode != 0));
}
if sample > 0 {
times[mode].push(start.elapsed());
}
}
}
for samples in &mut times {
samples.sort_unstable();
}
let medians = times.map(|s| s[s.len() / 2].as_secs_f64() * 1e6 / 40.0);
println!("{label}: {:.2} us per original scan, {:.2} us sparse", medians[0], medians[1]);
}
}

/// The shader's lookup (`victory_shader` lowering) over a table's
/// dwords: the view index and the byte offset in that view.
fn look_up(dwords: &[u32], address: u64) -> (u32, u32) {
Expand Down
Loading