From ec836909edd4b4ef9000a1b88857cb10995e1774 Mon Sep 17 00:00:00 2001 From: EatCodeSleep2 <52021568+EatCodeSleep2@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:27:36 -0800 Subject: [PATCH 01/49] Stop inferring descriptor slots from GPU fault addresses --- crates/victory-gpu/src/descriptor/host.rs | 37 ++++------------------- crates/victory-gpu/src/host.rs | 1 - 2 files changed, 6 insertions(+), 32 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 582f234..2e08ebc 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -35,29 +35,6 @@ pub(crate) struct HostHeap { next: Mutex<(u32, Vec)>, } -/// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for -/// device-removed reports: a shader indexing a heap past its end faults. -static GPU_RANGES: Mutex> = Mutex::new(Vec::new()); - -/// For device-removed reports: where host GPU address `va` lies against -/// the host descriptor heaps. -pub(crate) fn near_heaps(va: u64) -> String { - let ranges = GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()); - let mut text = String::new(); - for &(start, bytes, step, sampler) in ranges.iter() { - let kind = if sampler { "sampler" } else { "view" }; - let place = if va < start { - format!("{:#x} below", start - va) - } else if va < start + bytes { - format!("inside, slot {}", (va - start) / step) - } else { - format!("{:#x} past its end (slot {})", va - start - bytes, (va - start) / step) - }; - text.push_str(&format!("; {kind} heap {start:#x}+{bytes:#x}: {place}")); - } - text -} - /// 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; @@ -128,14 +105,12 @@ impl HostHeap { ) }; tracing::debug!(count, sampler, "host descriptor heap"); - // SAFETY: a live shader-visible heap. - let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr }; - GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push(( - gpu, - u64::from(count + extra) * u64::from(step), - u64::from(step), - sampler, - )); + // DRED identifies matching allocations by name. Descriptor handles + // have their own increment and cannot locate a faulting GPU VA. + crate::host::name(&heap, || { + let kind = if sampler { "sampler" } else { "view" }; + format!("{kind} descriptor heap ({} slots)", count + extra) + }); let h = HostHeap { heap, cpu, diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 6672c1e..46db57e 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -648,7 +648,6 @@ impl Host { } } text.push_str(&crate::shadow::near(va)); - text.push_str(&crate::descriptor::host::near_heaps(va)); } // The plain output: the extended one (with marker texts) came // back without stopped lists on this host. From fd5948937bc66149253e660b0cca3c23ac73e74a Mon Sep 17 00:00:00 2001 From: powplusplus <222417016+powplusplus@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:21:10 +1000 Subject: [PATCH 02/49] GPU: upload a host-copied texture again once the title writes its memory A texture that received a GPU copy or resolve kept the host contents for good, so later title writes (streamed mips, for example) never reached the host copy. Record where the memory stood at the host copy: the write-watch asking for watched memory, a content hash otherwise. Upload skips the texture only while the memory is unchanged since then. Fixes #758 --- crates/victory-gpu/src/texture.rs | 170 +++++++++++++++++++++++++++--- 1 file changed, 153 insertions(+), 17 deletions(-) diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 60eab0c..f022aef 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -65,15 +65,96 @@ unsafe impl Sync for Staging {} static STAGING: Mutex>>> = 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>> = Mutex::new(None); +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum HostWrite { + /// Write-watched memory: the write-watch asking when the host copy happened. + Watched { start: usize, end: usize, asked: u64 }, + /// Non-watched memory (physical-page view): content hash at the host copy. + Hashed { + memory: usize, + size: usize, + hash: Option, + }, + /// Layout unknown or unsupported: keep host contents until released. + Fixed, +} + +/// Textures the host GPU wrote by a copy or resolve: their contents stay on +/// the host until the title writes their memory again. +static HOST_WRITTEN: Mutex>> = Mutex::new(None); + +fn host_write_state(memory: *const u8, size: usize) -> HostWrite { + let start = memory as usize; + if let Some((now, _)) = crate::watch::writes(start, start + size, false) { + return HostWrite::Watched { + start, + end: start + size, + asked: now, + }; + } + let hash = committed(memory, size).then(|| { + // SAFETY: committed memory of the texture's layout size. + let tiled = unsafe { std::slice::from_raw_parts(memory, size) }; + blake3::hash(tiled) + }); + HostWrite::Hashed { + memory: start, + size, + hash, + } +} + +/// Whether `resource`'s host copy is still newer than its title memory. +fn still_host_written(resource: usize) -> bool { + let state = HOST_WRITTEN + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .and_then(|map| map.get(&resource).copied()); + let Some(state) = state else { + return false; + }; + let unchanged = match state { + HostWrite::Fixed => true, + HostWrite::Watched { start, end, asked } => crate::watch::writes(start, end, false) + .is_none_or(|(_, written)| written.iter().all(|&(_, w)| w <= asked)), + HostWrite::Hashed { memory, size, hash } => { + if !committed(memory as *const u8, size) { + true + } else { + // SAFETY: committed memory of the texture's layout size. + let tiled = unsafe { std::slice::from_raw_parts(memory as *const u8, size) }; + hash == Some(blake3::hash(tiled)) + } + } + }; + if !unchanged { + let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(map) = map.as_mut() + && map.get(&resource) == Some(&state) + { + map.remove(&resource); + } + } + unchanged +} /// 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); + if crate::resource::host_resource(resource).is_some_and(|t| !title_written(t)) { + return; + } + let state = crate::resource::texture_memory(resource) + .and_then(|(memory, desc)| { + let layout = crate::resource::texture_layout(&desc)?.planes[0] + .layout + .clone(); + (!layout.desc.swizzle.xor()).then(|| host_write_state(memory, layout.size as usize)) + }) + .unwrap_or(HostWrite::Fixed); + let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + map.get_or_insert_with(HashMap::new) + .insert(resource as usize, state); } /// The title released a resource. @@ -82,9 +163,9 @@ pub(crate) fn forget(resource: usize) { 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); + let mut host_written = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(host_written) = host_written.as_mut() { + host_written.remove(&resource); } } @@ -101,14 +182,7 @@ pub(crate) fn title_written(texture: &ID3D12Resource) -> bool { /// 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) { + if !list.first_use(resource as usize) || still_host_written(resource as usize) { return; } let Some(staging) = staging(resource, texture) else { @@ -342,3 +416,65 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { map.insert(resource as usize, s.clone()); Some(s) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn host_written_clears_after_write_watched_memory_is_written() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + let len = crate::watch::PAGE; + // SAFETY: a fresh write-watched allocation, freed at the end. + let ptr = unsafe { + VirtualAlloc( + std::ptr::null(), + len, + MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, + PAGE_READWRITE, + ) + } as *mut u8; + assert!(!ptr.is_null()); + let key = ptr as usize; + let state = host_write_state(ptr, len); + assert!(matches!(state, HostWrite::Watched { .. })); + { + let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + map.get_or_insert_with(HashMap::new).insert(key, state); + } + assert!(still_host_written(key), "untouched memory stays host-written"); + // SAFETY: committed page of ours. + unsafe { ptr.write(0x42) }; + assert!( + !still_host_written(key), + "writing title memory clears host-written state" + ); + assert!(!still_host_written(key)); + forget(key); + // SAFETY: our allocation. + unsafe { VirtualFree(ptr.cast(), 0, MEM_RELEASE) }; + } + + #[test] + fn host_written_clears_after_non_watched_memory_changes() { + let mut buf = vec![0x11u8; 256]; + let key = buf.as_ptr() as usize; + let state = host_write_state(buf.as_ptr(), buf.len()); + assert!(matches!(state, HostWrite::Hashed { hash: Some(_), .. })); + { + let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + map.get_or_insert_with(HashMap::new).insert(key, state); + } + assert!(still_host_written(key), "unchanged bytes stay host-written"); + buf[0] = 0x22; + assert!( + !still_host_written(key), + "changed title bytes clear host-written state" + ); + assert!(!still_host_written(key)); + forget(key); + } +} From 084d8d2fd9db473ba7516c139214fcf1f346591b Mon Sep 17 00:00:00 2001 From: powplusplus <222417016+powplusplus@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:21:45 +1000 Subject: [PATCH 03/49] Shaders: PSV0 and signatures laid out as the validator expects - PSV0 gets one string per arbitrary semantic element instead of sharing one between elements with the same name. - ISG1 and OSG1 sort elements by row only, so co-packed elements keep their order. - Interpolation modes come from the console container's PSV0 when it has one, falling back to DXC's defaults. --- crates/victory-shader/src/emit/container.rs | 106 ++++++++++-- crates/victory-shader/src/emit/mod.rs | 180 +++++++++++++++++++- 2 files changed, 268 insertions(+), 18 deletions(-) diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs index 8b05b12..4dcce74 100644 --- a/crates/victory-shader/src/emit/container.rs +++ b/crates/victory-shader/src/emit/container.rs @@ -89,7 +89,7 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec { } } let mut order: Vec = (0..elements.len()).collect(); - order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), elements[i].col)); + order.sort_by_key(|&i| elements[i].row.unwrap_or(u32::MAX)); for i in order { let (e, offset) = (&elements[i], offsets[i]); let used = e.usage << e.col; @@ -206,14 +206,10 @@ pub(crate) fn psv(p: &Psv) -> Vec { 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 = e.name.bytes().chain([0]).collect(); - match find(&strings, &needle) { - Some(at) => at, - None => { - strings.extend(&needle); - strings.len() - needle.len() - } - } + let at = strings.len(); + strings.extend(e.name.bytes()); + strings.push(0); + at } else { 0 }; @@ -272,10 +268,6 @@ pub(crate) fn psv(p: &Psv) -> Vec { out } -fn find(hay: &[u8], needle: &[u8]) -> Option { - hay.windows(needle.len()).position(|w| w == needle) -} - /// The container: parts in order, hashed. pub(crate) fn build(parts: &[(&[u8; 4], &[u8])]) -> Vec { let table = 0x20 + 4 * parts.len(); @@ -386,4 +378,92 @@ mod tests { .collect(); assert_eq!(hex, "900150983cd24fb0d6963f7d28e17f72"); } + + #[test] + fn psv_writes_distinct_string_entries_for_repeated_arbitrary_semantics() { + let el = |name: &str, index: u32, kind: u8, row: u32| SigElement { + name: name.into(), + index, + kind, + comp: 9, + interp: 2, + row: Some(row), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }; + let inputs = [ + el("SV_Position", 0, 3, 0), + el("TEXCOORD", 0, 0, 1), + el("TEXCOORD", 1, 0, 2), + ]; + let bytes = psv(&Psv { + stage: 0, + flag: false, + inputs: &inputs, + outputs: &[], + prims: &[], + mesh: None, + bindings: &[], + threads: [0; 3], + wave_size: None, + }); + let u32_at = |off: usize| u32::from_le_bytes(bytes[off..off + 4].try_into().unwrap()); + let info_sz = u32_at(0) as usize; + let mut pos = 4 + info_sz; + assert_eq!(u32_at(pos), 0); // 0 bindings + pos += 4; + let str_len = u32_at(pos) as usize; + pos += 4; + let strings = &bytes[pos..pos + str_len]; + // Leading empty string plus two distinct "TEXCOORD\0" entries. + assert!(strings.starts_with(b"\0TEXCOORD\0TEXCOORD\0")); + pos += str_len; + let idx_cnt = u32_at(pos) as usize; + pos += 4 + idx_cnt * 4; + let el_sz = u32_at(pos) as usize; + assert_eq!(el_sz, 16); + pos += 4; + let name0 = u32_at(pos); + let name1 = u32_at(pos + el_sz); + let name2 = u32_at(pos + 2 * el_sz); + assert_eq!(name0, 0); + assert_eq!(name1, 1); + assert_eq!(name2, 10); + } + + #[test] + fn signature_sorts_by_row_only_preserving_co_packed_order() { + let el = |name: &str, row: u32, col: u8, cols: u8| SigElement { + name: name.into(), + index: 0, + kind: 0, + comp: 9, + interp: 2, + row: Some(row), + col, + cols, + usage: (1 << cols) - 1, + half: false, + }; + let bytes = signature( + &[ + el("SECOND_ROW", 1, 0, 4), + el("HI_HALF", 0, 2, 2), + el("LO_HALF", 0, 0, 2), + ], + true, + ); + let u32_at = |off: usize| u32::from_le_bytes(bytes[off..off + 4].try_into().unwrap()); + assert_eq!(u32_at(0), 3); + let row_name = |i: usize| { + let name_off = u32_at(8 + i * 32 + 4) as usize; + let end = bytes[name_off..].iter().position(|&b| b == 0).unwrap(); + std::str::from_utf8(&bytes[name_off..name_off + end]).unwrap() + }; + assert_eq!(row_name(0), "HI_HALF"); + assert_eq!(row_name(1), "LO_HALF"); + assert_eq!(row_name(2), "SECOND_ROW"); + } } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 89652da..06ed6a6 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -232,11 +232,22 @@ pub fn emit( 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. + // Interpolation as the console container's PSV0 declares it, falling back + // to DXC's defaults when no PSV0 is present; pixel inputs that are read + // also get the mode their barycentrics say. + let psv_modes = c + .part(FourCC::PSV0) + .and_then(|p| psv_interps(p.data, pixel)); let interpolated = if pixel { &mut inputs } else { &mut outputs }; for e in interpolated { - e.interp = match (e.kind, e.comp) { + let from_psv = psv_modes.as_ref().and_then(|m| { + let key = match e.row { + Some(r) => (true, r, e.col, 0), + None => (false, 0, 0, e.kind), + }; + m.get(&key).copied().filter(|&mode| mode != 0) + }); + e.interp = from_psv.unwrap_or(match (e.kind, e.comp) { (3, _) => 4, // Constant, as DXC declares it (the AMD compiler crashed on a // front face without a mode). @@ -244,13 +255,15 @@ pub fn emit( (0 | 6 | 7, 9) => 2, (0, _) => 1, _ => 0, - }; + }); } // With a conservative depth output (SV_DepthLessEqual, GreaterEqual) DXIL // wants the position centroid (or per sample), as DXC declares it then. if pixel && outputs.iter().any(|e| matches!(e.kind, 18 | 19)) { for e in inputs.iter_mut().filter(|e| e.kind == 3) { - e.interp = 5; + if !matches!(e.interp, 5 | 7) { + e.interp = 5; + } } } // Per-primitive outputs are constant. The console never exports a @@ -311,6 +324,57 @@ pub fn emit( }) } +/// Per-element interpolation modes from a console container's `PSV0` part, +/// keyed by `(allocated, row, col, unallocated_kind)`. +fn psv_interps( + d: &[u8], + inputs: bool, +) -> Option> { + use crate::dxbc::u32_at; + let info_sz = u32_at(d, 0).ok()? as usize; + if info_sz < 36 || 4 + info_sz > d.len() { + return None; + } + let in_el = usize::from(*d.get(4 + 28)?); + let out_el = usize::from(*d.get(4 + 29)?); + let mut pos = 4 + info_sz; + let res_cnt = u32_at(d, pos).ok()? as usize; + pos += 4; + if res_cnt > 0 { + let res_sz = u32_at(d, pos).ok()? as usize; + pos = pos.checked_add(4)?.checked_add(res_cnt.checked_mul(res_sz)?)?; + } + let str_len = u32_at(d, pos).ok()? as usize; + pos = pos.checked_add(4)?.checked_add(str_len)?; + let idx_cnt = u32_at(d, pos).ok()? as usize; + pos = pos.checked_add(4)?.checked_add(idx_cnt.checked_mul(4)?)?; + if pos >= d.len() { + return Some(std::collections::HashMap::new()); + } + let el_sz = u32_at(d, pos).ok()? as usize; + pos += 4; + if el_sz < 14 { + return None; + } + let (start, count) = if inputs { (0, in_el) } else { (in_el, out_el) }; + let end = start.checked_add(count)?; + if pos.checked_add(end.checked_mul(el_sz)?)? > d.len() { + return None; + } + let mut out = std::collections::HashMap::with_capacity(count); + for k in start..end { + let e = &d[pos + k * el_sz..pos + (k + 1) * el_sz]; + let alloc = e[10] >> 6 & 1 != 0; + let key = if alloc { + (true, u32::from(e[9]), (e[10] >> 4) & 3, 0) + } else { + (false, 0, 0, e[11]) + }; + out.insert(key, e[13]); + } + Some(out) +} + /// The rows of an `ISG1`/`OSG1` part. fn signature(part: &[u8]) -> Result, ShaderError> { use crate::dxbc::u32_at; @@ -746,4 +810,110 @@ mod tests { // Translated or refused with a reason; it must not panic. let _ = super::emit(&c, &native, &p, &st, &io, &res); } + + #[test] + fn console_psv_interpolation_modes_are_preserved_for_copacked_inputs() { + // A float input co-packed in row 0 alongside a uint input must keep + // the console PSV0's Constant (1) mode instead of defaulting to Linear + // (2), which DXIL validator 1.6 rejects when mixed in one register. + let words = [ + 0xC80E_0000u32, // v_interp_mov_f32 v0, p0, attr0.x + 0xF800_180F, + 0x0000_0000, // exp mrt0, v0, v0, v0, v0 done vm + 0xBF81_0000, + ]; + let native = super::NativeProgram { + stage: super::HwStage::Ps, + wave64: false, + vgprs: 4, + layout: vec![], + used: vec![], + io: crate::native::StageIo::Ps { + inputs: vec![crate::native::PsInput { + usage: crate::native::Usage::Generic, + row: 0, + mask: 0b11, + attr: 0, + flat: true, + fp16: false, + pack2: false, + row2: 0, + }], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let f_flat = SigElement { + name: "TEXCOORD".into(), + index: 0, + kind: 0, + comp: 9, + interp: 1, + row: Some(0), + col: 0, + cols: 1, + usage: 1, + half: false, + }; + let u_flat = SigElement { + name: "TEXCOORD".into(), + index: 1, + kind: 0, + comp: 5, + interp: 1, + row: Some(0), + col: 1, + cols: 1, + usage: 0, + half: false, + }; + let target = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }; + let isg1 = super::container::signature(&[f_flat.clone(), u_flat.clone()], true); + let osg1 = super::container::signature(std::slice::from_ref(&target), false); + let psv0 = super::container::psv(&super::container::Psv { + stage: 0, + flag: false, + inputs: &[f_flat, u_flat], + outputs: &[target], + prims: &[], + mesh: None, + bindings: &[], + threads: [0; 3], + wave_size: None, + }); + let bytes = crate::dxbc::build(&[ + (super::FourCC::ISG1, &isg1), + (super::FourCC::OSG1, &osg1), + (super::FourCC::PSV0, &psv0), + ]); + let c = super::Container::parse(&bytes).unwrap(); + let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = crate::structure::structure(&p).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); + let out = super::emit(&c, &native, &p, &st, &io, &res).unwrap(); + let host = super::Container::parse(&out.dxil).unwrap(); + let modes = super::psv_interps(host.part(super::FourCC::PSV0).unwrap().data, true).unwrap(); + assert_eq!(modes.get(&(true, 0, 0, 0)), Some(&1)); + assert_eq!(modes.get(&(true, 0, 1, 0)), Some(&1)); + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut out.dxil.clone()).unwrap(); + } + } } From 293553878a82643adcea00a588bd7bdedcdc3c0a Mon Sep 17 00:00:00 2001 From: permadiego <339870573+permadiego@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:16:49 -0300 Subject: [PATCH 04/49] Shaders: mask dwords at data joins, and s_bcnt1's SCC of a mask Outside compute a lane mask has no number form, and two patterns made programs fail with "a lane mask read as data" although no lane mask is read as a number: - A join of registers that hold a mask's dword on one edge and data on another (the compiler reuses them once the mask is dead; in mesh programs, s_cselect_b64 s[8:9], exec, 0 on one path and s_buffer_load_dword s9 on the other). The data phi now takes undef on the mask's edge. - s_bcnt1_i32_b64 (b32 in wave32) of a mask whose count is dead and wgit update-ref -d CHERRY_PICK_HEADhose SCC ("some lane is set") picks a branch, as in s_xor_b64 s[12:13], vcc, exec; s_bcnt1_i32_b64 s12, s[12:13]; s_cbranch_scc1. The lane pass now takes that SCC per lane, as for the mask operations themselves. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 10 ++++++++++ crates/victory-shader/src/structure.rs | 15 ++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..4ea8125 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -6909,6 +6909,16 @@ impl<'a> Lower<'a> { (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => { return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values")); } + // A lane mask's dword reaching a join that also takes + // data: the registers are reused once the mask is dead. + // shortcut: undefined on that edge, assuming the program + // reads the joined value only on paths from a data edge. + (Some(Val::Missing(_)), false) + if self.x.st.masks.contains_key(&arg) + || self.x.st.highs.contains_key(&arg) => + { + self.s.m.undef(self.s.t.i32) + } (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => { return Err(Stop::Retry(phi.value, why)); } diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index ae70179..a8a662d 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -632,7 +632,11 @@ impl<'a> Lanes<'a> { .filter(|(lo, hi)| lo != hi) .map(|&(lo, hi)| (hi, lo)) .collect(), - paired_masks: if self.p.wave64 { self.masks } else { Map::default() }, + paired_masks: if self.p.wave64 { + self.masks + } else { + Map::default() + }, active: self.active, bools: self.b, exits, @@ -963,6 +967,15 @@ impl<'a> Lanes<'a> { }; self.scc_lane.insert(scc, m); } + // `s_bcnt1` of a mask: SCC is "some lane is set", as for a + // mask operation. + if takes_mask + && name.strip_prefix("s_bcnt1_i32_b") == Some(width) + && let (Some(scc), [a]) = (inst.write(Reg::Scc), &src[..]) + && let Some((m, _)) = self.operand(inst, a) + { + self.scc_lane.insert(scc, m); + } } Fields::Valu(v) => { let exec = self.exec(inst); From 02ea74cc21b6d48c33befeaa688b9aac9cedce86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:19:57 +0800 Subject: [PATCH 05/49] Loader: fix 4 bounds/overflow bugs in tls.rs and stacks.rs with unit tests --- crates/victory-loader/src/stacks.rs | 50 +++- crates/victory-loader/src/tls.rs | 383 +++++++++++++++++++++++++++- 2 files changed, 421 insertions(+), 12 deletions(-) diff --git a/crates/victory-loader/src/stacks.rs b/crates/victory-loader/src/stacks.rs index 1d30910..9ba72ed 100644 --- a/crates/victory-loader/src/stacks.rs +++ b/crates/victory-loader/src/stacks.rs @@ -27,21 +27,35 @@ pub fn dump_stacks_on_schedule() { let Ok(list) = std::env::var("VICTORY_STACKS") else { return; }; - let mut times: Vec = list - .split(',') - .filter_map(|t| t.trim().parse().ok()) - .collect(); - times.sort_by(f64::total_cmp); + let times = delays(&list); + if times.is_empty() { + return; + } 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)); + for at in times { std::thread::sleep(at.saturating_sub(start.elapsed())); dump_stacks(); } }); } +/// The delays `VICTORY_STACKS` lists, soonest first. Entries that are not a +/// finite number of seconds are dropped: no `Duration` holds them (a huge +/// value overflows it, and `inf` and `NaN` parse but have no length), and +/// taking one would panic the dumping thread instead of timing a dump. A +/// negative time means "now". +fn delays(list: &str) -> Vec { + let mut times: Vec = list + .split(',') + .filter_map(|t| t.trim().parse::().ok()) + .filter(|t| t.is_finite()) + .filter_map(|t| std::time::Duration::try_from_secs_f64(t.max(0.0)).ok()) + .collect(); + times.sort_unstable(); + times +} + /// `THREAD_BASIC_INFORMATION` (ntddk). #[repr(C)] struct BasicInfo { @@ -192,6 +206,28 @@ fn name_of(thread: HANDLE) -> String { mod tests { use super::*; + #[test] + fn the_schedule_keeps_only_delays_a_sleeper_can_wait() { + use std::time::Duration; + // Times are trimmed, bad entries dropped, the rest sorted soonest first. + assert_eq!( + delays("2, 0.5 ,1.5,abc,,0.5"), + [ + Duration::from_millis(500), + Duration::from_millis(500), + Duration::from_millis(1500), + Duration::from_secs(2), + ] + ); + // A negative time means "now". + assert_eq!(delays("-3,1"), [Duration::ZERO, Duration::from_secs(1)]); + // `f64` parses `inf` and `NaN`, and a huge value overflows + // `Duration`: each would panic `from_secs_f64`. + assert_eq!(delays("inf,-inf,NaN,1e300,1"), [Duration::from_secs(1)]); + assert!(delays("").is_empty()); + assert!(delays(" , ,").is_empty()); + } + #[test] fn another_threads_stack_unwinds_to_its_start() { let (tx, rx) = std::sync::mpsc::channel(); diff --git a/crates/victory-loader/src/tls.rs b/crates/victory-loader/src/tls.rs index a234183..6a1d523 100644 --- a/crates/victory-loader/src/tls.rs +++ b/crates/victory-loader/src/tls.rs @@ -23,6 +23,9 @@ const TLS64_ADDRESS_OF_INDEX: usize = 16; /// `mov r64, gs:[0x58]` is `65 REX 8B ModRM 25 58 00 00 00`. const LOAD_LEN: usize = 9; const THUNK_SIZE: usize = 32; +/// The loader hands out TLS indexes below 1088; the thunks' `disp32` also +/// could not hold `index * 8` anywhere near `u32::MAX`. +const MAX_INDEX: u32 = (1 << 28) - 1; /// Redirects the image's TLS-array loads if the OS gave it an index other /// than 0. Returns the number of loads patched. @@ -31,17 +34,30 @@ const THUNK_SIZE: usize = 32; /// `base` is the image `info` describes, mapped and not yet running. pub(crate) unsafe fn redirect(base: usize, info: &ImageInfo) -> Result { let Some(tls) = &info.tls else { return Ok(0) }; + // Header values are untrusted: the directory must hold the index field, + // and the field must name a `u32` inside the image, never elsewhere. + let size = info.size_of_image as usize; + let directory = tls.directory_rva as usize; + if directory + TLS64_ADDRESS_OF_INDEX + size_of::() > size { + bail!("TLS directory at {directory:#x} runs past the image"); + } // SAFETY: the TLS directory and the index it points to are in the image; // the OS relocated the pointer and wrote the index. - let index_at = unsafe { - ((base + tls.directory_rva as usize + TLS64_ADDRESS_OF_INDEX) as *const usize).read() - } as *mut u32; - // SAFETY: as above. + let index_at = + unsafe { ((base + directory + TLS64_ADDRESS_OF_INDEX) as *const usize).read() } as *mut u32; + let at = index_at as usize; + if at < base || at - base + size_of::() > size { + bail!("_tls_index at {at:#x} is outside the image"); + } + // SAFETY: as above; bounded above. let index = unsafe { index_at.read() }; if index == 0 { return Ok(0); } - let thunks = thunks(near(base, info.size_of_image as usize)?, index)?; + if index > MAX_INDEX { + bail!("TLS index {index} is larger than any the loader assigns"); + } + let thunks = thunks(near(base, size)?, index)?; let mut patched = 0; for section in info .sections @@ -50,6 +66,11 @@ pub(crate) unsafe fn redirect(base: usize, info: &ImageInfo) -> Result { { let start = base + section.rva as usize; let len = section.virtual_size as usize; + if len == 0 { + // An empty section has no code and no protection to change; + // `VirtualProtect` refuses a zero length. + continue; + } let mut old = 0; // SAFETY: the section is part of the mapped image. if unsafe { VirtualProtect(start as _, len, PAGE_EXECUTE_READWRITE, &mut old) } == 0 { @@ -173,6 +194,8 @@ fn near(base: usize, size: usize) -> Result<*mut u8> { #[cfg(test)] mod tests { use super::*; + use victory_pe::{SectionInfo, TlsInfo}; + use windows_sys::Win32::System::Memory::{MEM_RELEASE, VirtualFree}; /// Reads the thread's TLS array pointer the way title code does. fn tls_array() -> usize { @@ -182,6 +205,13 @@ mod tests { array } + /// `mov r64, gs:[0x58]`, as compilers spell it for `reg`. + fn load(reg: u8) -> [u8; LOAD_LEN] { + let high = reg >> 3; + let low = (reg & 7) << 3; + [0x65, 0x48 | high << 2, 0x8B, low | 4, 0x25, 0x58, 0, 0, 0] + } + #[test] fn loads_become_calls_that_yield_the_title_slot() { let page = near(tls_array as *const () as usize, 0).unwrap(); @@ -216,4 +246,347 @@ mod tests { unsafe { VirtualProtect(page as _, 4096, PAGE_READWRITE, &mut old) }; } } + + #[test] + fn every_register_load_becomes_a_call_but_the_stack_pointer() { + const AT: usize = 0x1000; + const BLOCK: usize = 0x2000; + for reg in 0..16u8 { + let mut code = load(reg).to_vec(); + code.push(0xC3); + let patched = patch(&mut code, AT, BLOCK); + if reg == 4 { + // A `mov rsp, ...` thunk would move the stack out from under + // its own `ret`, so it is the one register left alone. + assert_eq!(patched, 0); + assert_eq!(&code[..LOAD_LEN], &load(reg)); + assert_eq!(code[LOAD_LEN], 0xC3); + continue; + } + assert_eq!(patched, 1, "r{reg}"); + // `call thunk[reg]`, then a nop that keeps the length at 9. + assert_eq!(code[0], 0xE8, "r{reg}"); + let rel = i64::from(i32::from_le_bytes(code[1..5].try_into().unwrap())); + let callee = (AT + 5) as i64 + rel; + assert_eq!( + callee, + (BLOCK + usize::from(reg) * THUNK_SIZE) as i64, + "r{reg}" + ); + assert_eq!(code[5..9], [0x0F, 0x1F, 0x40, 0x00], "r{reg}"); + assert_eq!(code[9], 0xC3, "r{reg}"); + } + } + + #[test] + fn other_nine_byte_windows_are_left_alone() { + // Each differs from the load in one field: the segment, the opcode, + // the ModRM's mod, the displacement, or the SIB's index. + let cases = [ + [0x64, 0x48, 0x8B, 0x04, 0x25, 0x58, 0, 0, 0], // fs: + [0x65, 0x48, 0x8A, 0x04, 0x25, 0x58, 0, 0, 0], // mov r8, r/m8 + [0x65, 0x48, 0x8B, 0x44, 0x25, 0x58, 0, 0, 0], // mod 01 + [0x65, 0x48, 0x8B, 0x04, 0x25, 0x58, 0, 0, 1], // offset 1 + [0x65, 0x48, 0x8B, 0x04, 0x26, 0x58, 0, 0, 0], // [rsi + 0x58] + ]; + for case in cases { + let mut code = case.to_vec(); + assert_eq!(patch(&mut code, 0x1000, 0x2000), 0, "{case:02X?}"); + assert_eq!(code, case, "{case:02X?}"); + } + } + + #[test] + fn a_window_short_of_a_load_is_not_read() { + // Eight bytes: one short of a whole load, and too short to match. + let mut code = load(5)[..LOAD_LEN - 1].to_vec(); + assert_eq!(patch(&mut code, 0x1000, 0x2000), 0); + assert_eq!(code, load(5)[..LOAD_LEN - 1]); + assert_eq!(patch(&mut [], 0x1000, 0x2000), 0); + } + + #[test] + fn loads_back_to_back_are_each_patched_once() { + let mut code = [load(1), load(9), load(2)].concat(); + assert_eq!(patch(&mut code, 0x1000, 0x2000), 3); + // The second pass finds calls and nops where the loads were. + assert_eq!(patch(&mut code, 0x1000, 0x2000), 0); + } + + #[test] + fn each_thunk_loads_the_array_and_adds_the_slots_offset() { + const INDEX: u32 = 1087; + let block = thunks(near(tls_array as *const () as usize, 0).unwrap(), INDEX).unwrap(); + // SAFETY: `block` is one page of ours, readable; `thunks` made it + // read-execute. + let bytes = unsafe { std::slice::from_raw_parts(block as *const u8, 4096) }; + for reg in 0..16u8 { + let slot = &bytes[usize::from(reg) * THUNK_SIZE..][..THUNK_SIZE]; + let (high, low) = (reg >> 3, reg & 7); + let mut thunk = vec![ + 0x65, + 0x48 | high << 2, + 0x8B, + low << 3 | 4, + 0x25, + 0x58, + 0, + 0, + 0, + // lea r, [r + index * 8]; the SIB says r12/rsp as the base. + 0x48 | high << 2 | high, + 0x8D, + 0x80 | low << 3 | low, + ]; + if low == 4 { + thunk.push(0x24); + } + thunk.extend((INDEX * 8).to_le_bytes()); + thunk.push(0xC3); + assert!(thunk.len() <= THUNK_SIZE); + assert_eq!(&slot[..thunk.len()], &thunk[..], "r{reg}"); + // One thunk's bytes must not run into the next thunk's. + assert!(slot[thunk.len()..].iter().all(|&b| b == 0), "r{reg}"); + } + // Running one only adds to the array pointer (it never reads the + // slot), so any index is safe to check here. + // SAFETY: the page is executable and the thunk ends in `ret`. + let rax: extern "system" fn() -> usize = unsafe { std::mem::transmute(block) }; + assert_eq!(rax(), tls_array() + INDEX as usize * 8); + } + + #[test] + fn near_stays_within_rel32_reach_and_writable() { + let base = tls_array as *const () as usize; + let page = near(base, 0).unwrap(); + assert!((page as usize).abs_diff(base) <= 1 << 30); + assert!(near(base, (1 << 30) - 1).is_ok()); + assert!(near(base, 1 << 30).is_err()); + // SAFETY: a fresh page of ours, writable as `near` promises. + unsafe { + page.write(0xA5); + assert_eq!(page.read(), 0xA5); + } + } + + /// A synthetic mapped image of the shape `redirect` expects: a TLS + /// directory at 0x1000 naming an index `u32` at 0x1100, and one + /// executable section at 0x2000 holding `mov rax, gs:[0x58]; ret`. + /// Only the layout is synthetic; `redirect` is what reads it. + struct Synthetic { + base: *mut u8, + info: ImageInfo, + index: *mut u32, + code: *mut u8, + } + + /// What the header declares, and so what `redirect` may touch. + const SIZE_OF_IMAGE: u32 = 0x2_0000; + /// What is mapped: a page more, so a test can name a plausible index + /// just past the declared image. + const MAPPED: usize = 0x2_1000; + const DIRECTORY: usize = 0x1000; + const INDEX: usize = 0x1100; + const TEXT: usize = 0x2000; + /// `mov rax, gs:[0x58]; ret`. + const CODE: [u8; 10] = [0x65, 0x48, 0x8B, 0x04, 0x25, 0x58, 0, 0, 0, 0xC3]; + /// `IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ`. + const TEXT_FLAGS: u32 = 0x6000_0020; + + impl Synthetic { + /// `tls_index` is the index the OS "wrote" for the image. + fn new(tls_index: u32) -> Self { + let text = SectionInfo { + name: ".text".into(), + rva: TEXT as u32, + virtual_size: 0x10, + file_offset: 0, + file_size: 0x10, + characteristics: TEXT_FLAGS, + }; + // SAFETY: a fresh mapping of ours, filled in as the loader + // would have left it. + unsafe { + let base = VirtualAlloc( + std::ptr::null(), + MAPPED, + MEM_COMMIT | MEM_RESERVE, + PAGE_READWRITE, + ) + .cast::(); + assert!(!base.is_null()); + let index = base.add(INDEX).cast::(); + index.write(tls_index); + // `IMAGE_TLS_DIRECTORY64`: raw data start and end, the + // address of the index, the callbacks, then zero fill. + let fields = [0u64, 0, index as u64, 0, 0, 0]; + for (i, field) in fields.into_iter().enumerate() { + base.add(DIRECTORY).cast::().add(i).write(field); + } + base.add(TEXT) + .copy_from_nonoverlapping(CODE.as_ptr(), CODE.len()); + let mut old = 0; + let exec = + VirtualProtect(base.add(TEXT).cast(), 0x1000, PAGE_EXECUTE_READ, &mut old); + assert_ne!(exec, 0); + Self { + base, + info: ImageInfo { + machine: victory_pe::MACHINE_AMD64, + characteristics: 0x0022, + timestamp: 0, + subsystem: 3, + dll_characteristics: 0, + image_base: base as u64, + size_of_image: SIZE_OF_IMAGE, + entry_rva: 0, + stack_reserve: 0, + stack_commit: 0, + sections: vec![text], + imports: Vec::new(), + delay_imports: Vec::new(), + exports: Vec::new(), + tls: Some(TlsInfo { + directory_rva: DIRECTORY as u32, + callbacks_va: 0, + callback_rvas: Vec::new(), + }), + has_relocations: false, + has_exception_table: false, + has_load_config: false, + codeview: None, + }, + index, + code: base.add(TEXT), + } + } + } + + fn try_patched(&self) -> Result { + // SAFETY: `info` describes this mapping, and nothing runs it. + unsafe { redirect(self.base as usize, &self.info) } + } + + fn patched(&self) -> usize { + self.try_patched().unwrap() + } + + fn index_value(&self) -> u32 { + // SAFETY: the index is in our mapping, and readable. + unsafe { self.index.read() } + } + + fn code_bytes(&self) -> [u8; N] { + // SAFETY: the text page is ours, and `N` is inside it. + unsafe { std::ptr::read(self.code.cast::<[u8; N]>()) } + } + + /// Points the directory's `AddressOfIndex` at `va` instead. + fn set_index_pointer(&mut self, va: u64) { + // SAFETY: the directory is in our mapping, still writable. + unsafe { self.base.add(DIRECTORY).cast::().add(2).write(va) }; + } + + /// Where the header says the image ends, plus `offset` bytes. + fn past_image(&self, offset: usize) -> *mut u64 { + // SAFETY: inside the mapping, which is `MAPPED` long. + unsafe { self.base.add(SIZE_OF_IMAGE as usize + offset).cast() } + } + } + + impl Drop for Synthetic { + fn drop(&mut self) { + // SAFETY: the mapping is ours, and nothing uses it any more. + unsafe { VirtualFree(self.base.cast(), 0, MEM_RELEASE) }; + } + } + + #[test] + fn a_redirected_image_yields_the_slot_the_os_gave_it() { + let image = Synthetic::new(5); + assert_eq!(image.patched(), 1); + let code = image.code_bytes::<10>(); + assert_eq!(code[0], 0xE8); + assert_eq!(code[5..9], [0x0F, 0x1F, 0x40, 0x00]); + assert_eq!(code[9], 0xC3); + // `_tls_index` is 0 from here on, as CRT code inside a DLL expects. + assert_eq!(image.index_value(), 0); + // The patched load returns the slot the OS assigned the image. + // SAFETY: the patched page is executable, and ends in `ret`. + let run: extern "system" fn() -> usize = unsafe { std::mem::transmute(image.code) }; + assert_eq!(run(), tls_array() + 5 * 8); + } + + #[test] + fn index_zero_needs_no_patches() { + let image = Synthetic::new(0); + assert_eq!(image.patched(), 0); + assert_eq!(image.code_bytes::<10>(), CODE); + } + + #[test] + fn an_empty_executable_section_does_not_stop_the_rest() { + let mut image = Synthetic::new(5); + image.info.sections.push(SectionInfo { + name: ".empty".into(), + rva: 0x3000, + virtual_size: 0, + file_offset: 0, + file_size: 0, + characteristics: TEXT_FLAGS, + }); + // `VirtualProtect` refuses a zero length; that must not abort the + // redirect of the sections that do hold code. + assert_eq!(image.patched(), 1); + assert_eq!(image.index_value(), 0); + } + + #[test] + fn an_index_no_loader_assigns_is_an_error() { + // `index * 8` overflows `u32` here; the index is read from the image. + let image = Synthetic::new(u32::MAX); + assert!(image.try_patched().is_err()); + assert_eq!(image.code_bytes::<10>(), CODE); + } + + #[test] + fn an_index_outside_the_image_is_not_written() { + // The directory may name anything; following it would zero a `u32` + // that is not the image's. + let outside = Box::into_raw(Box::new(0x5A5A_u32)); + let mut image = Synthetic::new(5); + image.set_index_pointer(outside as u64); + assert!(image.try_patched().is_err()); + // SAFETY: `outside` is still ours, and allocated. + assert_eq!(unsafe { outside.read() }, 0x5A5A); + // SAFETY: allocated above, never aliased. + unsafe { drop(Box::from_raw(outside)) }; + } + + #[test] + fn a_directory_outside_the_image_is_an_error() { + // The directory sits 8 bytes before the declared end, so its index + // field is past it: reading that field must stop there, not follow + // a header value into memory the image does not own. + let outside = Box::into_raw(Box::new(7_u32)); + let mut image = Synthetic::new(5); + // What the unchecked read would have found 16 bytes in: a readable + // index of 7, just past the declared image. + // SAFETY: inside our mapping, past what the header declares. + unsafe { image.past_image(8).write(outside as u64) }; + image.info.tls.as_mut().unwrap().directory_rva = SIZE_OF_IMAGE - 8; + assert!(image.try_patched().is_err()); + // SAFETY: `outside` is still ours, and allocated. + assert_eq!(unsafe { outside.read() }, 7); + // SAFETY: allocated above, never aliased. + unsafe { drop(Box::from_raw(outside)) }; + } + + #[test] + fn an_image_without_tls_needs_no_redirect() { + let mut image = Synthetic::new(5); + image.info.tls = None; + assert_eq!(image.patched(), 0); + assert_eq!(image.code_bytes::<10>(), CODE); + } } From a4a94d7202993daf5c6beaf8c1c345a4fc1665f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:11:08 +0800 Subject: [PATCH 06/49] HLE: fix self-closing XML element body parsing in runtime.rs and add unit tests --- crates/victory-hle/src/modules/d3d12x.rs | 102 +++++++++++++- crates/victory-hle/src/runtime.rs | 161 ++++++++++++++++++++++- 2 files changed, 255 insertions(+), 8 deletions(-) diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs index 23bbccf..d2418f6 100644 --- a/crates/victory-hle/src/modules/d3d12x.rs +++ b/crates/victory-hle/src/modules/d3d12x.rs @@ -89,20 +89,112 @@ mod tests { use super::*; use crate::{HleResolver, HostPolicy}; use victory_loader::ImportResolver; + use victory_loader::Provenance; use victory_loader::Resolution; use victory_pe::ImportSymbol; + fn symbol(name: &str) -> ImportSymbol { + ImportSymbol::Name { + hint: 0, + name: name.into(), + } + } + #[test] fn the_interface_id_import_is_bound_to_data() { - let symbol = ImportSymbol::Name { - hint: 0, - name: "IID_ID3D12Device".into(), - }; let r = HleResolver::new(HostPolicy::none()); - let Resolution::Found { address, .. } = r.resolve("d3d12_xs.dll", &symbol) else { + let Resolution::Found { address, .. } = + r.resolve("d3d12_xs.dll", &symbol("IID_ID3D12Device")) + else { panic!("not bound"); }; // SAFETY: the address is our static id. assert_eq!(unsafe { *(address as *const [u8; 16]) }, device::IID); } + + #[test] + fn module_serves_the_console_d3d12_dll() { + let m = module(); + assert_eq!(m.name, "d3d12x"); + assert!(m.serves("d3d12_xs.dll")); + assert!(m.serves("D3D12_XS.DLL"), "DLL names are case-insensitive"); + assert!(!m.serves("d3d12.dll")); + assert!(!m.serves("dxgi.dll")); + } + + #[test] + fn exports_are_the_console_entry_points() { + let m = module(); + let mut names: Vec<&str> = m.exports.iter().map(|e| e.name).collect(); + names.sort_unstable(); + let mut expected = [ + "D3D12ConfigureVirtualMemoryX", + "D3D12CreateRootSignatureDeserializer", + "D3D12SerializeRootSignature", + "D3D12SerializeVersionedRootSignature", + "D3D12XboxCreateDevice", + "IID_ID3D12Device", + ]; + expected.sort_unstable(); + assert_eq!(names, expected, "exactly the console's entry points"); + for export in &m.exports { + assert_ne!(export.address, 0, "{} has no address", export.name); + } + } + + #[test] + fn every_export_resolves_as_hle_from_the_dll() { + let resolver = HleResolver::new(HostPolicy::none()); + for export in module().exports { + match resolver.resolve("d3d12_xs.dll", &symbol(export.name)) { + Resolution::Found { + address, + provenance, + } => { + assert_eq!(provenance, Provenance::Hle, "{}", export.name); + assert_eq!(address, export.address, "{}", export.name); + } + Resolution::Missing => panic!("{} is not bound", export.name), + } + } + } + + #[test] + fn the_interface_id_export_points_at_the_device_iid() { + let export = module() + .exports + .into_iter() + .find(|e| e.name == "IID_ID3D12Device") + .expect("the interface id is exported as data"); + assert_eq!(export.address, (&raw const device::IID) as usize); + // SAFETY: the export is the address of our static interface id. + assert_eq!(unsafe { *(export.address as *const [u8; 16]) }, device::IID); + } + + #[test] + fn device_creation_rejects_null_arguments() { + // E_INVALIDARG, the host's error for a missing argument. + const E_INVALIDARG: i32 = 0x8007_0057u32 as i32; + let version: u32 = 0x0002_0004; + // No device parameters. + assert_eq!( + create_device( + std::ptr::null(), + std::ptr::null(), + &device::IID, + std::ptr::null_mut(), + ), + E_INVALIDARG + ); + // No interface id. + assert_eq!( + create_device( + std::ptr::null(), + &version, + std::ptr::null(), + std::ptr::null_mut(), + ), + E_INVALIDARG + ); + } } diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index c8479c5..1a99424 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -148,10 +148,22 @@ fn elements(text: &str) -> Vec<(String, String)> { .next() .unwrap_or(""); path.push(name); - let body = rest[..rest.find('<').unwrap_or(rest.len())].trim(); - let body = [("<", "<"), (">", ">"), (""", "\""), ("'", "'"), ("&", "&")] + // Text up to the first child belongs to this element. A self-closing + // element has none, so whatever follows it belongs to its parent. + let body = if closed { + String::new() + } else { + let body = rest[..rest.find('<').unwrap_or(rest.len())].trim(); + [ + ("<", "<"), + (">", ">"), + (""", "\""), + ("'", "'"), + ("&", "&"), + ] .iter() - .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c)); + .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c)) + }; out.push((path.join("/"), body)); if closed { path.pop(); @@ -210,6 +222,14 @@ pub fn use_console_timers() { mod tests { use super::*; + /// The body recorded for `path`, if any element has it. + fn body<'a>(elements: &'a [(String, String)], path: &str) -> Option<&'a str> { + elements + .iter() + .find(|(p, _)| p == path) + .map(|(_, text)| text.as_str()) + } + #[test] fn reads_title_id_store_id_and_storage_quota() { let text = "\u{feff}\n\ @@ -223,4 +243,139 @@ mod tests { assert_eq!(t.store_id, "9&C"); assert_eq!(Title::from_manifest("").storage_bytes, 0); } + + #[test] + fn elements_record_the_path_of_each_nested_element() { + let found = elements("x"); + for (path, text) in [("A", ""), ("A/B", ""), ("A/B/C", "x")] { + assert_eq!(body(&found, path), Some(text), "{path}"); + } + assert_eq!(found.len(), 3, "one entry per element"); + } + + #[test] + fn a_self_closing_element_owns_no_text() { + // The words after `/>` belong to the parent, not to `Flag`. + let found = elements("owned by the parentok"); + assert_eq!(body(&found, "Game/Flag"), Some("")); + assert_eq!(body(&found, "Game/Name"), Some("ok")); + // Neighbours with nothing between them are still empty. + let neighbours = elements(""); + assert_eq!(body(&neighbours, "R/A"), Some("")); + assert_eq!(body(&neighbours, "R/B"), Some("")); + } + + #[test] + fn comments_cdata_and_declarations_are_skipped() { + let found = + elements("d]]>1"); + assert_eq!(body(&found, "G/X"), None, "inside a comment"); + assert_eq!(body(&found, "G/Y"), None, "inside CDATA"); + assert_eq!(body(&found, "G/Z"), Some("1")); + } + + #[test] + fn predefined_entities_are_decoded_once() { + assert_eq!( + body(&elements("<>&"'"), "A"), + Some("<>&\"'") + ); + // One pass: `&lt;` is the text `<`, not a second `<`. + assert_eq!(body(&elements("&lt;"), "A"), Some("<")); + } + + #[test] + fn unterminated_markup_is_ignored_without_panicking() { + let found = elements("x"); + assert!(elements("<").is_empty()); + } + + #[test] + fn missing_manifest_yields_defaults() { + for text in [ + "", + "", + "1", + ] { + let title = Title::from_manifest(text); + assert_eq!( + (title.id, title.store_id.as_str(), title.storage_bytes), + (0, "", 0), + "{text:?}" + ); + assert_eq!(title.storage, PathBuf::new(), "{text:?}"); + } + } + + #[test] + fn lowercase_hex_id_and_quota_in_bytes() { + let title = Title::from_manifest( + "deadbeef\ + 2", + ); + assert_eq!(title.id, 0xDEAD_BEEF); + assert_eq!(title.storage_bytes, 2 << 20); + } + + #[test] + fn invalid_id_and_missing_quota_are_zero() { + let title = Title::from_manifest("0x12"); + assert_eq!((title.id, title.storage_bytes), (0, 0)); + } + + #[test] + fn store_id_is_trimmed_and_entity_decoded() { + let title = Title::from_manifest(" a&b "); + assert_eq!(title.store_id, "a&b"); + } + + #[test] + fn commented_and_cdata_ids_are_ignored() { + let title = Title::from_manifest( + "x]]>\ + 2", + ); + assert_eq!(title.id, 2); + assert_eq!(title.store_id, ""); + } + + #[test] + fn the_first_element_at_a_path_wins() { + let title = Title::from_manifest("12"); + assert_eq!(title.id, 1); + } + + #[test] + fn saves_live_beside_storage() { + assert_eq!(Title::default().saves(), PathBuf::from("saves")); + let title = Title { + storage: PathBuf::from("data/0000/storage"), + ..Title::default() + }; + assert_eq!(title.saves(), PathBuf::from("data/0000/saves")); + } + + #[test] + fn image_registry_remembers_replaces_and_forgets() { + let base = 0x7DFF_5A5A_0001; + let first = Path::new(r"C:\victory-test\victory-runtime-image.dll"); + let second = Path::new(r"D:\victory-test\victory-renamed-image.dll"); + let name = |path: &Path| path.file_name().unwrap().to_owned(); + + set_image_path(base, first); + assert_eq!(image_path(base).map(|p| name(&p)), Some(name(first))); + assert_eq!(image_named("VICTORY-RUNTIME-IMAGE.DLL"), Some(base)); + + // A second file at the same base replaces the first. + set_image_path(base, second); + assert_eq!(image_path(base).map(|p| name(&p)), Some(name(second))); + assert_eq!(image_named("victory-runtime-image.dll"), None); + assert_eq!(image_named("victory-renamed-image.dll"), Some(base)); + + forget_image(base); + assert_eq!(image_path(base), None); + assert_eq!(image_named("victory-renamed-image.dll"), None); + } } From 8466edd7bb1fb3f9e94e0719ac5c2241b8ff3a07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:11:37 +0800 Subject: [PATCH 07/49] HLE: reject null out in QueryApiImpl before lookup and add xgameruntime unit tests --- .../victory-hle/src/modules/xgameruntime.rs | 265 +++++++++++++++++- 1 file changed, 260 insertions(+), 5 deletions(-) diff --git a/crates/victory-hle/src/modules/xgameruntime.rs b/crates/victory-hle/src/modules/xgameruntime.rs index 3201a90..8223bbd 100644 --- a/crates/victory-hle/src/modules/xgameruntime.rs +++ b/crates/victory-hle/src/modules/xgameruntime.rs @@ -141,7 +141,8 @@ pub fn put(out: *mut T, value: T) -> HRESULT { } /// Copies `text` and a NUL into the title's `size`-byte buffer and reports -/// the bytes used, as the runtime's string getters do. +/// the bytes used, as the runtime's string getters do. A buffer that does +/// not fit is left untouched. pub fn put_string(text: &str, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { let len = text.len() + 1; if buffer.is_null() || size < len { @@ -218,7 +219,8 @@ pub extern "system" fn UninitializeApiImpl() { } /// The object for an implemented (provider, interface id); others fail, -/// each pair logged once. +/// each pair logged once. A null `out` is the title's own error, not a +/// missing area, and is neither logged nor remembered as one. pub extern "system" fn QueryApiImpl( provider: *const Guid, iid: *const Guid, @@ -230,6 +232,9 @@ pub extern "system" fn QueryApiImpl( else { return NOT_SUPPORTED; }; + if out.is_null() { + return xasync::E_INVALIDARG; + } #[cfg(feature = "diagnostics")] if tracing::enabled!(tracing::Level::DEBUG) { // Each runtime call site once: which title code uses which area, when. @@ -245,9 +250,7 @@ pub extern "system" fn QueryApiImpl( .iter() .flat_map(|area| area.iter()) .find(|(p, i, _)| (*p, *i) == (provider, iid)); - if let Some(&(_, _, object)) = found - && !out.is_null() - { + if let Some(&(_, _, object)) = found { // SAFETY: checked non-null; the title passes room for a pointer. unsafe { out.write((object as *const Object).cast_mut().cast()) }; return S_OK; @@ -292,6 +295,258 @@ mod tests { use super::*; use crate::modules::kernel::{FreeLibrary, GetProcAddress, LoadLibraryExA}; + fn first_interface() -> Interface { + AREAS[0][0] + } + + #[test] + fn the_error_codes_are_the_documented_ones() { + assert_eq!(S_OK, 0); + assert_eq!(NOT_SUPPORTED, 0x8007_0032_u32 as i32); + assert_eq!(xasync::E_NOTIMPL, 0x8000_4001_u32 as i32); + assert_eq!(xasync::E_INVALIDARG, 0x8007_0057_u32 as i32); + assert_eq!(xasync::E_NOT_SUFFICIENT_BUFFER, 0x8007_007A_u32 as i32); + } + + #[test] + fn a_guid_prints_the_canonical_form() { + let guid = Guid::new( + 0x0123_4567, + 0x89ab, + 0xcdef, + [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef], + ); + assert_eq!(guid.to_string(), "01234567-89ab-cdef-0123-456789abcdef"); + // Copy and equality: the table lookup compares pairs by value. + assert_eq!( + guid, + Guid::new(guid.data1, guid.data2, guid.data3, guid.data4) + ); + assert_ne!(guid, Guid::new(0, 0, 0, [0; 8])); + } + + #[test] + fn put_writes_through_a_valid_pointer_only() { + let mut count = 0xdead_beef_u32; + assert_eq!(put(&mut count, 7_u32), S_OK); + assert_eq!(count, 7); + let mut flag = false; + assert_eq!(put(&mut flag, true), S_OK); + assert!(flag); + let mut wide = 0_usize; + assert_eq!(put(&mut wide, usize::MAX), S_OK); + assert_eq!(wide, usize::MAX); + assert_eq!(put::(std::ptr::null_mut(), 1), xasync::E_INVALIDARG); + } + + #[test] + fn put_string_copies_the_text_and_its_nul() { + let mut buffer = [0xaa_u8; 8]; + let mut used = 0; + assert_eq!(put_string("abc", 4, buffer.as_mut_ptr(), &mut used), S_OK); + assert_eq!((used, &buffer[..5]), (4, &[b'a', b'b', b'c', 0, 0xaa][..])); + // An empty string still needs room for its NUL. + assert_eq!(put_string("", 1, buffer.as_mut_ptr(), &mut used), S_OK); + assert_eq!((used, buffer[0]), (1, 0)); + // The buffer's size, not the string's, decides what is written. + assert_eq!( + put_string("abc", 8, buffer.as_mut_ptr(), std::ptr::null_mut()), + S_OK + ); + assert_eq!(&buffer[..4], b"abc\0"); + } + + #[test] + fn put_string_refuses_what_it_cannot_fit() { + let mut buffer = [0xaa_u8; 4]; + let pointer = buffer.as_mut_ptr(); + let mut used = 0xdead_beef_usize; + for size in [3, 0] { + assert_eq!( + put_string("abc", size, pointer, &mut used), + xasync::E_NOT_SUFFICIENT_BUFFER, + "size {size}" + ); + } + assert_eq!( + put_string("abc", 4, std::ptr::null_mut(), &mut used), + xasync::E_NOT_SUFFICIENT_BUFFER + ); + assert_eq!( + put_string("abc", usize::MAX, std::ptr::null_mut(), &mut used), + xasync::E_NOT_SUFFICIENT_BUFFER + ); + assert_eq!(buffer, [0xaa; 4], "nothing is written on failure"); + assert_eq!(used, 0xdead_beef, "and no size is reported"); + } + + #[test] + fn text_reads_the_titles_strings() { + assert_eq!(text(std::ptr::null()), None); + assert_eq!(text(c"".as_ptr()).as_deref(), Some("")); + assert_eq!(text(c"Player".as_ptr()).as_deref(), Some("Player")); + // Not UTF-8: the bytes become replacement characters, never a panic. + assert_eq!(text(c"a\xffb".as_ptr()).as_deref(), Some("a\u{fffd}b")); + } + + #[test] + fn tokens_are_nonzero_and_distinct() { + let first = token(); + let second = token(); + assert!(first >= 1 && second > first); + let mut seen: Vec = (0..64).map(|_| token()).collect(); + seen.sort_unstable(); + seen.dedup(); + assert_eq!(seen.len(), 64); + assert!(!seen.contains(&0)); + } + + #[test] + fn every_registered_interface_answers_with_its_object() { + let mut pairs = Vec::new(); + for area in AREAS { + for &(provider, iid, object) in *area { + let mut out: *mut c_void = std::ptr::null_mut(); + assert_eq!( + QueryApiImpl(&provider, &iid, &mut out), + S_OK, + "{provider} {iid}" + ); + assert_eq!( + out as *const Object, object as *const Object, + "{provider} {iid}" + ); + assert!(!object.area.is_empty()); + pairs.push((provider.to_string(), iid.to_string())); + } + } + // A pair listed twice would leave one object unreachable. + let count = pairs.len(); + pairs.sort_unstable(); + pairs.dedup(); + assert_eq!(pairs.len(), count); + } + + #[test] + fn an_unimplemented_area_is_unsupported_and_writes_nothing() { + let unknown = Guid::new(0xdead_beef, 0x1234, 0x5678, [0; 8]); + let untouched = 0x1234 as *mut c_void; + let mut out = untouched; + assert_eq!(QueryApiImpl(&unknown, &unknown, &mut out), NOT_SUPPORTED); + // Again, to exercise the once-only log path. + assert_eq!(QueryApiImpl(&unknown, &unknown, &mut out), NOT_SUPPORTED); + let (provider, _, _) = first_interface(); + assert_eq!(QueryApiImpl(&provider, &unknown, &mut out), NOT_SUPPORTED); + assert_eq!(QueryApiImpl(&unknown, &provider, &mut out), NOT_SUPPORTED); + assert_eq!(out, untouched, "the output is not written on failure"); + // Null GUID pointers are tolerated, never dereferenced. + assert_eq!( + QueryApiImpl(std::ptr::null(), std::ptr::null(), &mut out), + NOT_SUPPORTED + ); + assert_eq!( + QueryApiImpl(std::ptr::null(), &unknown, &mut out), + NOT_SUPPORTED + ); + assert_eq!( + QueryApiImpl(&unknown, std::ptr::null(), &mut out), + NOT_SUPPORTED + ); + assert_eq!(out, untouched); + } + + #[test] + fn a_null_output_is_the_titles_argument_error() { + let (provider, iid, object) = first_interface(); + assert_eq!( + QueryApiImpl(&provider, &iid, std::ptr::null_mut()), + xasync::E_INVALIDARG, + "an implemented area with nowhere to put its object" + ); + // Argument validation comes first, whatever the pair names: a null + // output is not a missing area and must not be remembered as one. + let unknown = Guid::new(0xdead_beef, 0x1234, 0x5678, [0; 8]); + assert_eq!( + QueryApiImpl(&unknown, &unknown, std::ptr::null_mut()), + xasync::E_INVALIDARG + ); + // The same query still answers once there is room for the object. + let mut out: *mut c_void = std::ptr::null_mut(); + assert_eq!(QueryApiImpl(&provider, &iid, &mut out), S_OK); + assert_eq!(out as *const Object, object as *const Object); + } + + extern "system" fn answer(_: *const Object) -> u32 { + 7 + } + + static TEST_METHODS: Methods<4> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + answer as *const (), + missing::<3> as *const (), + ]); + static TEST_OBJECT: Object = Object::new("test", &TEST_METHODS); + + #[test] + fn an_object_points_at_its_method_table() { + assert_eq!(TEST_OBJECT.vtable, TEST_METHODS.0.as_ptr()); + assert_eq!(TEST_OBJECT.area, "test"); + type Slot = extern "system" fn(*const Object) -> u32; + assert_eq!(method::(&TEST_OBJECT, 0x08)(&TEST_OBJECT), 1); + assert_eq!(method::(&TEST_OBJECT, 0x10)(&TEST_OBJECT), 7); + // Reference counting is a no-op: the tables are static, so a null + // handle is harmless too. + assert_eq!(add_ref(std::ptr::null()), 1); + let not_implemented = xasync::E_NOTIMPL as u32; + assert_eq!( + method::(&TEST_OBJECT, 0x00)(&TEST_OBJECT), + not_implemented + ); + assert_eq!( + method::(&TEST_OBJECT, 0x18)(&TEST_OBJECT), + not_implemented + ); + } + + #[test] + fn the_runtime_initialises_and_uninitialises() { + assert_eq!(XGameRuntimeInitialize(), S_OK); + assert_eq!(InitializeApiImpl(1, 2), S_OK); + assert_eq!(InitializeApiImplEx(1, 2, 3), S_OK); + assert_eq!(InitializeApiImplEx2(1, 2, 3, std::ptr::null()), S_OK); + let options = [0_u8; 16]; + assert_eq!(InitializeApiImplEx2(0, 0, 0, options.as_ptr().cast()), S_OK); + UninitializeApiImpl(); + XGameRuntimeUninitialize(); + // Reporting an error is a log: a null message is fine. + XErrorReport(S_OK, std::ptr::null()); + XErrorReport(xasync::E_INVALIDARG, c"bad argument".as_ptr()); + } + + #[test] + fn the_module_serves_the_runtime_dll() { + let module = module(); + assert_eq!(module.name, "xgameruntime"); + assert!(module.serves("XGAMERUNTIME.DLL")); + assert!(!module.serves("xgame.dll")); + let names: Vec<_> = module.exports.iter().map(|export| export.name).collect(); + assert_eq!( + names, + [ + "XGameRuntimeInitialize", + "XGameRuntimeUninitialize", + "InitializeApiImpl", + "InitializeApiImplEx", + "InitializeApiImplEx2", + "UninitializeApiImpl", + "QueryApiImpl", + "XErrorReport", + ] + ); + assert!(module.exports.iter().all(|export| export.address != 0)); + } + #[test] fn title_stub_loads_the_runtime_dynamically() { let load = |name: &CStr| LoadLibraryExA(name.as_ptr().cast(), std::ptr::null_mut(), 0x800); From f4c4bd47daf9612965b631a427fcbaa825a68a43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:14:25 +0800 Subject: [PATCH 08/49] GPU: fix 3 encoding, fallback, and slice-panic bugs in shader_cache.rs with unit tests --- crates/victory-gpu/src/shader_cache.rs | 330 ++++++++++++++++++++++--- 1 file changed, 297 insertions(+), 33 deletions(-) diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 998ec71..dc2fcf1 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -3,7 +3,8 @@ //! 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. +//! atomically; an entry that does not read back is translated again, and a +//! cache that cannot be written is skipped (it never fails a translation). //! //! 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 @@ -11,7 +12,7 @@ use std::path::PathBuf; use std::sync::OnceLock; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicU64, Ordering}; use victory_pipeline::{Cache, Converter}; use victory_shader::emit::{HostShader, StaticSampler, UserData}; @@ -21,6 +22,9 @@ static CACHE: OnceLock = OnceLock::new(); static HITS: AtomicU64 = AtomicU64::new(0); static MISSES: AtomicU64 = AtomicU64::new(0); +/// The build fingerprint in front of every cache input, from [`build`]. +const BUILD_LEN: usize = 32; + /// Keeps translated shaders in `dir` from now on. pub fn use_shader_cache(dir: PathBuf) { match Cache::open(dir) { @@ -39,8 +43,8 @@ pub(crate) fn counts() -> (u64, u64) { /// What identifies this build: the BLAKE3 of our executable file and of /// the translation settings it runs with (the loop limit, which a /// diagnostics build can change at run time). -fn build() -> &'static [u8; 32] { - static BUILD: OnceLock<[u8; 32]> = OnceLock::new(); +fn build() -> &'static [u8; BUILD_LEN] { + static BUILD: OnceLock<[u8; BUILD_LEN]> = OnceLock::new(); BUILD.get_or_init(|| { let exe = std::env::current_exe().and_then(std::fs::read); let limit = victory_shader::emit::loop_limit(); @@ -78,10 +82,11 @@ pub(crate) fn host_shader(container: &[u8]) -> Result { } /// The cache entry's converter: the build and the container in, the -/// encoded translation out. `ran` tells a miss from a hit. +/// encoded translation out. `translated` keeps what it produced, so a +/// store that cannot publish the entry costs no second translation. struct Translate { translate: F, - ran: AtomicBool, + translated: OnceLock, } impl Result + Send + Sync> Converter for Translate { @@ -93,29 +98,46 @@ impl Result + Send + Sync> Converter for Tra 1 } fn convert(&self, input: &[u8]) -> anyhow::Result> { - self.ran.store(true, Ordering::Relaxed); - let shader = (self.translate)(&input[32..]).map_err(anyhow::Error::msg)?; + let Some((_, container)) = input.split_at_checked(BUILD_LEN) else { + anyhow::bail!("shader cache input lacks the build fingerprint"); + }; + let shader = (self.translate)(container).map_err(anyhow::Error::msg)?; + let _ = self.translated.set(shader.clone()); Ok(encode(&shader)) } } fn cached( cache: &Cache, - build: &[u8; 32], + build: &[u8; BUILD_LEN], container: &[u8], translate: impl Fn(&[u8]) -> Result + Send + Sync, ) -> Result { let input = [&build[..], container].concat(); let converter = Translate { translate, - ran: AtomicBool::new(false), + translated: OnceLock::new(), }; for _ in 0..2 { - let path = cache - .get_or_convert(&converter, &input) - .map_err(|e| format!("{e:#}"))?; + let path = match cache.get_or_convert(&converter, &input) { + Ok(path) => path, + // The cache never fails a translation: a store it cannot publish + // still holds the translation (a miss), and a translation that + // failed inside it fails here. + Err(e) => { + let message = format!("{e:#}"); + tracing::debug!(error = %message, "shader cache unusable"); + return match converter.translated.get() { + Some(shader) => { + MISSES.fetch_add(1, Ordering::Relaxed); + Ok(shader.clone()) + } + None => Err(message), + }; + } + }; if let Some(shader) = std::fs::read(&path).ok().and_then(|b| decode(&b)) { - let (counter, what) = if converter.ran.load(Ordering::Relaxed) { + let (counter, what) = if converter.translated.get().is_some() { (&MISSES, "translated and cached") } else { (&HITS, "from the cache") @@ -128,6 +150,11 @@ fn cached( let _ = std::fs::remove_file(&path); } MISSES.fetch_add(1, Ordering::Relaxed); + // A translation that already happened (the store had no usable entry + // afterwards) is used as is. + if let Some(shader) = converter.translated.get() { + return Ok(shader.clone()); + } (converter.translate)(container) } @@ -143,7 +170,11 @@ const STAGES: [HwStage; 8] = [ HwStage::Cs, ]; -fn root_code(r: RootType) -> u32 { +/// The tag of [`RootType::Other`]: a tag cannot hold every `u32`, so its +/// raw value follows it as its own word. +const OTHER_ROOT: u32 = 6; + +fn root_tag(r: RootType) -> u32 { match r { RootType::Constants => 0, RootType::Descriptor => 1, @@ -151,23 +182,12 @@ fn root_code(r: RootType) -> u32 { RootType::ImmediateSampler => 3, RootType::ResourceHeap => 4, RootType::SamplerHeap => 5, - RootType::Other(x) => 6 + x, + RootType::Other(_) => OTHER_ROOT, } } -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. +/// Little-endian words and length-prefixed lists; a root type is its tag, +/// then the raw value for [`RootType::Other`]. fn encode(s: &HostShader) -> Vec { let mut out = MAGIC.to_vec(); let word = |out: &mut Vec, v: u32| out.extend(v.to_le_bytes()); @@ -177,9 +197,13 @@ fn encode(s: &HostShader) -> Vec { 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] { + for v in [u.index, u32::from(u.slot), root_tag(u.root)] { word(&mut out, v); } + if let RootType::Other(raw) = u.root { + word(&mut out, raw); + } + word(&mut out, u.dword); } word(&mut out, s.samplers.len() as u32); for sampler in &s.samplers { @@ -238,10 +262,22 @@ fn decode(bytes: &[u8]) -> Option { let n = r.word()? as usize; let mut user_data = Vec::with_capacity(n.min(256)); for _ in 0..n { + let index = r.word()?; + let slot = u8::try_from(r.word()?).ok()?; + let root = match r.word()? { + 0 => RootType::Constants, + 1 => RootType::Descriptor, + 2 => RootType::Table, + 3 => RootType::ImmediateSampler, + 4 => RootType::ResourceHeap, + 5 => RootType::SamplerHeap, + OTHER_ROOT => RootType::Other(r.word()?), + _ => return None, + }; user_data.push(UserData { - index: r.word()?, - slot: u8::try_from(r.word()?).ok()?, - root: root_type(r.word()?), + index, + slot, + root, dword: r.word()?, }); } @@ -280,6 +316,7 @@ fn decode(bytes: &[u8]) -> Option { #[cfg(test)] mod tests { use super::*; + use victory_pipeline::CacheKey; fn shader() -> HostShader { HostShader { @@ -348,6 +385,41 @@ mod tests { files } + /// A shader with every field at an unusual value. + fn rich_shader() -> HostShader { + HostShader { + stage: HwStage::Gs, + dxil: (0u8..=255).collect(), + user_data: vec![ + UserData { + index: 0, + slot: 0, + root: RootType::Constants, + dword: 1, + }, + UserData { + index: 7, + slot: 255, + root: RootType::Other(0xdead_beef), + dword: u32::MAX, + }, + UserData { + index: u32::MAX, + slot: 2, + root: RootType::SamplerHeap, + dword: 3, + }, + ], + samplers: vec![[1, 2, 3, 4], [0, 0, 0, 0]], + static_samplers: vec![ + StaticSampler::from_words([0x400, 0xc0_0000, 0x18f0_0000, 0]), + StaticSampler::from_words([0, 0, 0, 0]), + ], + root_cbvs: vec![0, 1, 255], + root_srvs: Vec::new(), + } + } + #[test] fn entries_round_trip_and_reject_damage() { let bytes = encode(&shader()); @@ -356,4 +428,196 @@ mod tests { assert_eq!(decode(&[bytes.as_slice(), &[0]].concat()), None); assert_eq!(decode(b"VSH0"), None); } + + #[test] + fn the_whole_shader_survives_the_round_trip() { + assert_eq!(decode(&encode(&rich_shader())), Some(rich_shader())); + } + + #[test] + fn every_stage_round_trips() { + let stages = [ + HwStage::Ls, + HwStage::Hs, + HwStage::Es, + HwStage::Gs, + HwStage::Vs, + HwStage::Ps, + HwStage::Ms, + HwStage::Cs, + ]; + for stage in stages { + let mut s = shader(); + s.stage = stage; + assert_eq!(decode(&encode(&s)), Some(s.clone()), "{stage:?}"); + } + } + + #[test] + fn every_root_type_round_trips() { + let roots = [ + RootType::Constants, + RootType::Descriptor, + RootType::Table, + RootType::ImmediateSampler, + RootType::ResourceHeap, + RootType::SamplerHeap, + RootType::Other(0), + RootType::Other(1), + RootType::Other(6), + RootType::Other(u32::MAX), + ]; + for root in roots { + let mut s = shader(); + s.user_data[0].root = root; + assert_eq!(decode(&encode(&s)), Some(s.clone()), "{root:?}"); + } + } + + #[test] + fn every_truncation_is_not_a_shader() { + let bytes = encode(&rich_shader()); + for n in 0..bytes.len() { + assert_eq!(decode(&bytes[..n]), None, "{n} of {} bytes", bytes.len()); + } + assert_eq!(decode(&bytes), Some(rich_shader())); + } + + #[test] + fn impossible_lengths_are_not_shaders() { + let s = rich_shader(); + let bytes = encode(&s); + + // The DXIL length (after the magic and the stage). + let mut b = bytes.clone(); + b[8..12].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(decode(&b), None, "an oversized DXIL"); + + // The user-data count (after the DXIL). + let at = 12 + s.dxil.len(); + let mut b = bytes.clone(); + b[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(decode(&b), None, "too many user-data entries"); + + // The last list's length: the bytes it promises are not there. + let at = bytes.len() - s.root_srvs.len() - 4; + let mut b = bytes.clone(); + b[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(decode(&b), None, "a root SRV list that is not there"); + } + + #[test] + fn unknown_root_tags_are_not_shaders() { + let s = shader(); + let bytes = encode(&s); + // The first user-data entry: count, index, slot, then the root tag. + let at = 12 + s.dxil.len() + 4 + 4 + 4; + for tag in [7u32, 1000, u32::MAX] { + let mut b = bytes.clone(); + b[at..at + 4].copy_from_slice(&tag.to_le_bytes()); + assert_eq!(decode(&b), None, "{tag}"); + } + } + + #[test] + fn damaged_entries_never_panic() { + let bytes = encode(&rich_shader()); + for at in 0..bytes.len() { + for xor in [0x01u8, 0x80, 0xff] { + let mut b = bytes.clone(); + b[at] ^= xor; + let _ = decode(&b); + } + } + // Entries that are not one of ours: arbitrary bytes behind the magic. + let mut state = 0x9e37_79b9_7f4a_7c15u64; + for len in 0..96 { + let mut b = b"VSH1".to_vec(); + for _ in 0..len { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + b.push(state as u8); + } + let _ = decode(&b); + } + } + + #[test] + fn each_container_and_build_keeps_its_own_entry() { + let dir = tempfile::tempdir().unwrap(); + let cache = Cache::open(dir.path()).unwrap(); + let runs = AtomicU64::new(0); + let translate = |c: &[u8]| { + runs.fetch_add(1, Ordering::Relaxed); + let mut s = shader(); + s.dxil = c.to_vec(); + Ok(s) + }; + let of = |c: &[u8]| { + let mut s = shader(); + s.dxil = c.to_vec(); + s + }; + let (a, b) = (b"first container".as_slice(), b"second container"); + assert_eq!(cached(&cache, &[7; 32], a, translate), Ok(of(a))); + assert_eq!(cached(&cache, &[7; 32], b, translate), Ok(of(b))); + assert_eq!(runs.load(Ordering::Relaxed), 2); + assert_eq!(walk(dir.path()).len(), 2, "one entry per container"); + + assert_eq!(cached(&cache, &[7; 32], a, translate), Ok(of(a))); + assert_eq!(cached(&cache, &[7; 32], b, translate), Ok(of(b))); + assert_eq!(runs.load(Ordering::Relaxed), 2, "both came from the cache"); + + // Another build's translation is a separate entry too. + assert_eq!(cached(&cache, &[8; 32], b, translate), Ok(of(b))); + assert_eq!(runs.load(Ordering::Relaxed), 3); + assert_eq!(walk(dir.path()).len(), 3); + } + + #[test] + fn a_cache_that_cannot_be_written_still_translates() { + // A directory where the entry goes makes the atomic rename fail. + let dir = tempfile::tempdir().unwrap(); + let cache = Cache::open(dir.path()).unwrap(); + let build = [7; 32]; + let container = b"a console container".as_slice(); + let translate = |_: &[u8]| -> Result { Ok(shader()) }; + let converter = Translate { + translate, + translated: OnceLock::new(), + }; + let input = [&build[..], container].concat(); + let path = cache.path_for(&CacheKey::new(&converter, &input)); + std::fs::create_dir_all(&path).unwrap(); + + 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!(runs.load(Ordering::Relaxed), 1, "no second translation"); + assert!(path.is_dir(), "the entry path is still unusable"); + } + + #[test] + fn the_converter_needs_the_build_fingerprint() { + let converter = Translate { + translate: |c: &[u8]| -> Result { + let mut s = shader(); + s.dxil = c.to_vec(); + Ok(s) + }, + translated: OnceLock::new(), + }; + assert!(converter.convert(b"short").is_err()); + let input = [&[0u8; 32][..], b"container"].concat(); + let mut expected = shader(); + expected.dxil = b"container".to_vec(); + assert_eq!( + converter.convert(&input).ok().and_then(|b| decode(&b)), + Some(expected) + ); + } } From 98b761bd1f18de72f5fb5afa1ad14ec95db6942c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:16:11 +0800 Subject: [PATCH 09/49] Loader: fix 4 bounds and cleanup bugs in windows.rs with unit tests --- crates/victory-loader/src/windows.rs | 596 ++++++++++++++++++++++++++- 1 file changed, 592 insertions(+), 4 deletions(-) diff --git a/crates/victory-loader/src/windows.rs b/crates/victory-loader/src/windows.rs index e709d11..27a84dd 100644 --- a/crates/victory-loader/src/windows.rs +++ b/crates/victory-loader/src/windows.rs @@ -82,7 +82,14 @@ pub fn load(prepared: &PreparedImage, dir: &Path) -> Result { // A DLL indexes its TLS properly; only an exe assumes index 0. if !loaded.info.is_dll() { // SAFETY: just mapped, and no title code has run. - unsafe { crate::tls::redirect(loaded.base(), &loaded.info) }?; + if let Err(error) = unsafe { crate::tls::redirect(loaded.base(), &loaded.info) } { + // Nothing has seen this module yet (`threads::mapped` is below), + // so a failed load must not leave it mapped for the life of the + // process. + // SAFETY: no title code has run and the module is not registered. + unsafe { FreeLibrary(module) }; + return Err(error); + } } tracing::info!( base = format_args!("{:#x}", loaded.base()), @@ -287,10 +294,20 @@ impl LoadedImage { /// Protects and restores each slot on its own: import tables can sit in /// sections with different protections (delay-load tables in `.didat`). fn write_slots(&self, slots: &[(u32, usize)]) -> Result<()> { + // The RVAs come from the image's own tables, which `victory-pe` + // checks when it parses them. Check again before touching memory: + // an RVA past the image would write into whatever the loader mapped + // next, and no `VirtualProtect` failure would necessarily stop it. + let size = u64::from(self.info.size_of_image); + for &(rva, _) in slots { + if u64::from(rva) + 8 > size { + bail!("IAT slot {rva:#x} is outside the image ({size:#x} bytes)"); + } + } for &(rva, address) in slots { let slot = (self.base() + rva as usize) as *mut u64; let mut old = 0; - // SAFETY: the parser only yields slots inside the image. + // SAFETY: the checked slot lies inside the image. if unsafe { VirtualProtect(slot as *const c_void, 8, PAGE_READWRITE, &mut old) } == 0 { bail!( "VirtualProtect(IAT slot {rva:#x}) failed: {}", @@ -320,8 +337,18 @@ impl LoadedImage { 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 { + // A callback is code inside the image; RVA 0 is the header, and + // anything past the image belongs to another mapping. Calling + // either would run memory the image does not own. + if rva == 0 || u64::from(rva) >= u64::from(self.info.size_of_image) { + tracing::warn!( + rva = format_args!("{rva:#x}"), + "TLS callback outside the image, skipped" + ); + continue; + } type TlsCallback = unsafe extern "system" fn(*mut c_void, u32, *mut c_void); - // SAFETY: the RVA came from the image's own TLS directory. + // SAFETY: the RVA is inside the image and came from its 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, reserved) }; @@ -373,8 +400,19 @@ impl LoadedImage { if !dll_main || !self.info.is_dll() || self.info.entry_rva == 0 { return None; } + // An entry point outside the image cannot be this image's `DllMain`. + // Report it the way a `DllMain` that refuses the process does, + // rather than call into whatever is mapped past the image. + if u64::from(self.info.entry_rva) >= u64::from(self.info.size_of_image) { + tracing::error!( + entry = format_args!("{:#x}", self.info.entry_rva), + size = format_args!("{:#x}", self.info.size_of_image), + "DllMain outside the image" + ); + return Some(0); + } type DllMain = unsafe extern "system" fn(*mut c_void, u32, *mut c_void) -> i32; - // SAFETY: the entry RVA came from the original image header. + // SAFETY: the entry RVA is inside the image and came from its header. let main: DllMain = unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) }; // SAFETY: forwarded from the caller. @@ -395,6 +433,12 @@ impl LoadedImage { if self.info.entry_rva == 0 { bail!("image has no entry point"); } + if u64::from(self.info.entry_rva) >= u64::from(self.info.size_of_image) { + bail!( + "entry point {:#x} is outside the image", + self.info.entry_rva + ); + } let stack = usize::try_from(self.info.stack_reserve) .unwrap_or(usize::MAX) .max(1 << 20); @@ -430,3 +474,547 @@ impl LoadedImage { unsafe { FreeLibrary(self.module) }; } } + +#[cfg(test)] +mod tests { + use std::sync::atomic::Ordering; + + use victory_pe::{ImportEntry, ImportModule, ImportSymbol, TlsInfo}; + use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READWRITE, + PAGE_READONLY, PAGE_READWRITE, VirtualAlloc, VirtualFree, VirtualQuery, + }; + + use super::*; + use crate::{disable_thread_calls, unimplemented_call_count}; + + const PAGE: usize = 0x1000; + + /// A committed scratch block standing in for a mapped image. + fn alloc(pages: usize, protect: u32) -> usize { + // SAFETY: a fresh anonymous allocation, freed once by `free`. + let at = unsafe { + VirtualAlloc( + std::ptr::null(), + pages * PAGE, + MEM_COMMIT | MEM_RESERVE, + protect, + ) + } as usize; + assert_ne!(at, 0, "VirtualAlloc failed"); + at + } + + fn free(at: usize) { + // SAFETY: `at` is a live block from `alloc`, freed once. + unsafe { VirtualFree(at as *mut c_void, 0, MEM_RELEASE) }; + } + + fn protection(at: usize) -> u32 { + // SAFETY: a zeroed output buffer of the type the call fills. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: `at` is inside a live allocation; `info` is sized for the call. + let n = unsafe { VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) }; + assert_ne!(n, 0, "VirtualQuery failed"); + info.Protect + } + + fn put(at: usize, code: &[u8]) { + // SAFETY: callers pass a range inside a live executable allocation. + unsafe { std::ptr::copy_nonoverlapping(code.as_ptr(), at as *mut u8, code.len()) }; + } + + /// `mov rax, ; inc qword ptr [rax]; ret`. + fn bump(counter: &'static AtomicU64) -> Vec { + let mut code = vec![0x48, 0xB8]; + code.extend_from_slice(&(counter as *const AtomicU64 as u64).to_le_bytes()); + code.extend_from_slice(&[0x48, 0xFF, 0x00]); + code.push(0xC3); + code + } + + /// `mov eax, ; ret`. + fn ret(value: u32) -> Vec { + let mut code = vec![0xB8]; + code.extend_from_slice(&value.to_le_bytes()); + code.push(0xC3); + code + } + + fn import(dll: &str, rva: u32) -> ImportModule { + ImportModule { + dll: dll.to_owned(), + entries: vec![ImportEntry { + symbol: ImportSymbol::Name { + hint: 0, + name: format!("f{rva:x}"), + }, + iat_slot_rva: rva, + }], + } + } + + fn info(size_of_image: u32) -> ImageInfo { + ImageInfo { + machine: victory_pe::MACHINE_AMD64, + characteristics: victory_pe::layout::file_flags::DLL, + timestamp: 0, + subsystem: victory_pe::layout::subsystem::WINDOWS_CUI, + dll_characteristics: 0, + image_base: 0, + size_of_image, + entry_rva: 0, + stack_reserve: 0, + stack_commit: 0, + sections: Vec::new(), + imports: Vec::new(), + delay_imports: Vec::new(), + exports: Vec::new(), + tls: None, + has_relocations: false, + has_exception_table: false, + has_load_config: false, + codeview: None, + } + } + + /// A `LoadedImage` whose `module` is a scratch allocation, not a real PE. + fn image_at(base: usize, info: ImageInfo) -> LoadedImage { + LoadedImage { + module: base as *mut c_void, + path: PathBuf::new(), + info, + } + } + + fn slot(image: &LoadedImage, rva: u32) -> u64 { + // SAFETY: every slot the tests read lies inside a live allocation. + unsafe { ((image.base() + rva as usize) as *const u64).read_volatile() } + } + + fn found(address: usize) -> Resolution { + Resolution::Found { + address, + provenance: Provenance::Hle, + } + } + + fn prepared_own() -> PreparedImage { + let original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); + prepare(&original).unwrap() + } + + fn module_by_name(name: &str) -> usize { + let wide: Vec = name.encode_utf16().chain(Some(0)).collect(); + // SAFETY: a NUL-terminated UTF-16 name; the query takes no reference. + unsafe { GetModuleHandleW(wide.as_ptr()) as usize } + } + + struct Fixed(Resolution); + + impl ImportResolver for Fixed { + fn resolve(&self, _: &str, _: &ImportSymbol) -> Resolution { + self.0 + } + } + + /// Provenance per DLL name, as a title's imports arrive. + struct ByDll; + + impl ImportResolver for ByDll { + fn resolve(&self, dll: &str, _: &ImportSymbol) -> Resolution { + let found = match dll.to_ascii_lowercase().as_str() { + "hle.dll" => Some((0x1111, Provenance::Hle)), + "host.dll" => Some((0x2222, Provenance::Host)), + "title.dll" => Some((0x3333, Provenance::Title)), + _ => None, + }; + found.map_or(Resolution::Missing, |(address, provenance)| { + Resolution::Found { + address, + provenance, + } + }) + } + } + + #[test] + fn maps_and_unloads_a_prepared_copy() { + let prepared = prepared_own(); + let dir = tempfile::tempdir().unwrap(); + let image = load(&prepared, dir.path()).unwrap(); + assert_ne!(image.base(), 0); + assert_eq!(image.base() % PAGE, 0, "the loader page-aligns the mapping"); + assert_eq!(image.info().import_count(), prepared.info.import_count()); + assert_eq!( + std::fs::read(dir.path().join(prepared.file_name())).unwrap(), + prepared.bytes + ); + // The prepared copy is registered as mapped, and keeps its static TLS. + assert_eq!(disable_thread_calls(image.base()), Some(false)); + // SAFETY: never attached, and no pointer into it outlives this test. + unsafe { image.unload() }; + } + + #[test] + fn write_if_changed_rewrites_only_when_the_bytes_differ() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("victory-image-test.dll"); + write_if_changed(&path, b"one").unwrap(); + let read_only = |on: bool| { + let mut permissions = std::fs::metadata(&path).unwrap().permissions(); + permissions.set_readonly(on); + std::fs::set_permissions(&path, permissions).unwrap(); + }; + // Identical bytes: no write happens, so even a read-only file is fine + // (replacing a read-only file on Windows fails). + read_only(true); + write_if_changed(&path, b"one").unwrap(); + read_only(false); + write_if_changed(&path, b"two").unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"two"); + assert!( + !path.with_extension("tmp").exists(), + "the temporary file is renamed, not left behind" + ); + } + + #[test] + fn binds_imports_and_delay_imports_by_provenance() { + let base = alloc(1, PAGE_READONLY); + let mut info = info(PAGE as u32); + info.imports = vec![ + import("hle.dll", 0x100), + import("host.dll", 0x108), + import("title.dll", 0x110), + ]; + info.delay_imports = vec![import("missing.dll", 0x118)]; + let image = image_at(base, info); + let report = image + .bind_imports(&ByDll, UnimplementedPolicy::ReturnZero) + .unwrap(); + assert_eq!((report.hle, report.host, report.title), (1, 1, 1)); + assert_eq!(report.missing.len(), 1); + assert_eq!(report.missing[0].dll, "missing.dll"); + assert_eq!(report.missing[0].symbol, "f118"); + assert_eq!(slot(&image, 0x100), 0x1111); + assert_eq!(slot(&image, 0x108), 0x2222); + assert_eq!(slot(&image, 0x110), 0x3333); + assert_ne!(slot(&image, 0x118), 0, "the delay-import slot got a stub"); + assert_eq!( + protection(base + 0x100), + PAGE_READONLY, + "the slot's protection is restored" + ); + free(base); + } + + #[test] + fn binding_restores_the_protection_of_each_section() { + let base = alloc(2, PAGE_READWRITE); + let mut old = 0; + // SAFETY: the second page is inside the allocation. + let changed = unsafe { + VirtualProtect( + (base + PAGE) as *const c_void, + PAGE, + PAGE_READONLY, + &mut old, + ) + }; + assert_ne!(changed, 0); + let before = (protection(base + 0x100), protection(base + PAGE + 0x100)); + assert_eq!(before, (PAGE_READWRITE, PAGE_READONLY)); + let mut info = info((2 * PAGE) as u32); + info.imports = vec![import("a.dll", 0x100), import("b.dll", PAGE as u32 + 0x100)]; + let image = image_at(base, info); + let report = image + .bind_imports(&Fixed(found(0x1234)), UnimplementedPolicy::ReturnZero) + .unwrap(); + assert_eq!(report.hle, 2); + assert_eq!(slot(&image, 0x100), 0x1234); + assert_eq!(slot(&image, PAGE as u32 + 0x100), 0x1234); + assert_eq!( + (protection(base + 0x100), protection(base + PAGE + 0x100)), + before + ); + free(base); + } + + #[test] + fn binding_no_imports_does_nothing() { + let base = alloc(1, PAGE_READWRITE); + let image = image_at(base, info(PAGE as u32)); + let report = image + .bind_imports(&Fixed(Resolution::Missing), UnimplementedPolicy::Trap) + .unwrap(); + assert_eq!((report.hle, report.host, report.title), (0, 0, 0)); + assert!(report.missing.is_empty()); + free(base); + } + + #[test] + fn unresolved_imports_get_a_callable_stub() { + let base = alloc(1, PAGE_READWRITE); + let mut info = info(PAGE as u32); + info.imports = vec![ImportModule { + dll: "missing.dll".into(), + entries: vec![ + ImportEntry { + symbol: ImportSymbol::Name { + hint: 0, + name: "one".into(), + }, + iat_slot_rva: 0x100, + }, + ImportEntry { + symbol: ImportSymbol::Ordinal(7), + iat_slot_rva: 0x108, + }, + ], + }]; + let image = image_at(base, info); + let report = image + .bind_imports(&Fixed(Resolution::Missing), UnimplementedPolicy::ReturnZero) + .unwrap(); + assert_eq!(report.missing.len(), 2); + assert_eq!(report.missing[0].dll, "missing.dll"); + assert_eq!(report.missing[0].symbol, "one"); + assert_eq!(report.missing[1].symbol, "#7"); + let before = unimplemented_call_count(); + for rva in [0x100, 0x108] { + // SAFETY: the loader wrote a stub to this slot; the stub ignores + // its arguments and returns 0 under `ReturnZero`. + let stub: unsafe extern "system" fn() -> u64 = + unsafe { std::mem::transmute::(slot(&image, rva)) }; + // SAFETY: as above. + assert_eq!(unsafe { stub() }, 0); + } + assert!(unimplemented_call_count() >= before + 2); + free(base); + } + + #[test] + fn an_iat_slot_outside_the_image_is_refused_before_memory_is_touched() { + let base = alloc(2, PAGE_READWRITE); + const CANARY: u64 = 0xDEAD_BEEF_CAFE_F00D; + // SAFETY: the second page is inside the allocation. + unsafe { ((base + PAGE) as *mut u64).write(CANARY) }; + for rva in [PAGE as u32, PAGE as u32 - 4] { + let mut info = info(PAGE as u32); + info.imports = vec![import("x.dll", rva)]; + let image = image_at(base, info); + let error = image + .bind_imports(&Fixed(found(0x1111)), UnimplementedPolicy::ReturnZero) + .unwrap_err(); + assert!(error.to_string().contains("outside the image"), "{error:#}"); + // SAFETY: the canary is inside the allocation. + let canary = unsafe { ((base + PAGE) as *const u64).read() }; + assert_eq!( + canary, CANARY, + "nothing past the image was written (slot {rva:#x})" + ); + } + // The last slot that fits wholly inside the image is written. + let mut info = info(PAGE as u32); + info.imports = vec![import("x.dll", PAGE as u32 - 8)]; + let image = image_at(base, info); + image + .bind_imports(&Fixed(found(0x1111)), UnimplementedPolicy::ReturnZero) + .unwrap(); + assert_eq!(slot(&image, PAGE as u32 - 8), 0x1111); + free(base); + } + + #[test] + fn a_failed_tls_redirect_unmaps_the_image() { + let mut original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); + // A unique build hash, so the module name belongs to this test alone. + original[16] ^= 0xFF; + let prepared = prepare(&original).unwrap(); + assert!(!prepared.info.is_dll()); + assert!( + prepared.info.tls.is_some(), + "the test binary uses static TLS" + ); + let mut info = prepared.info.clone(); + // The TLS thunk search refuses images this large, so `redirect` fails + // after `load` has already mapped the copy. + info.size_of_image = 1 << 30; + let prepared = PreparedImage { + info, + bytes: prepared.bytes.clone(), + original_hash: prepared.original_hash, + }; + let name = prepared.file_name(); + assert_eq!(module_by_name(&name), 0, "no module with this name yet"); + let dir = tempfile::tempdir().unwrap(); + let error = load(&prepared, dir.path()).unwrap_err(); + let text = format!("{error:#}").to_ascii_lowercase(); + assert!( + text.contains("tls"), + "expected the TLS redirect to fail: {text}" + ); + assert_eq!( + module_by_name(&name), + 0, + "a load that failed after mapping must unmap" + ); + } + + static HEADER_CALLS: AtomicU64 = AtomicU64::new(0); + static IMAGE_CALLS: AtomicU64 = AtomicU64::new(0); + static OUTSIDE_CALLS: AtomicU64 = AtomicU64::new(0); + + #[test] + fn tls_callbacks_outside_the_image_are_not_called() { + let base = alloc(2, PAGE_EXECUTE_READWRITE); + put(base, &bump(&HEADER_CALLS)); + put(base + 0x800, &bump(&IMAGE_CALLS)); + put(base + PAGE, &bump(&OUTSIDE_CALLS)); + let mut info = info(PAGE as u32); + info.tls = Some(TlsInfo { + directory_rva: 0, + callbacks_va: 0, + callback_rvas: vec![0, 0x800, PAGE as u32], + }); + let image = image_at(base, info); + HEADER_CALLS.store(0, Ordering::SeqCst); + IMAGE_CALLS.store(0, Ordering::SeqCst); + OUTSIDE_CALLS.store(0, Ordering::SeqCst); + // SAFETY: the "callbacks" only bump a static counter and return. + unsafe { image.run_tls_callbacks(DLL_PROCESS_ATTACH) }; + assert_eq!( + IMAGE_CALLS.load(Ordering::SeqCst), + 1, + "the in-image callback runs" + ); + assert_eq!( + HEADER_CALLS.load(Ordering::SeqCst), + 0, + "the image header is not code" + ); + assert_eq!( + OUTSIDE_CALLS.load(Ordering::SeqCst), + 0, + "nothing past the image is called" + ); + free(base); + } + + #[test] + fn a_dll_main_outside_the_image_does_not_run() { + let base = alloc(2, PAGE_EXECUTE_READWRITE); + put(base + 0x800, &ret(7)); + put(base + PAGE, &ret(7)); + let mut info = info(PAGE as u32); + info.entry_rva = PAGE as u32; + let mut image = image_at(base, info.clone()); + // SAFETY: the entry point (if it ran) only returns 7. + let outcome = unsafe { image.notify(DLL_PROCESS_ATTACH, true, std::ptr::null_mut()) }; + assert_eq!( + outcome, + Some(0), + "an entry point outside the image is reported as DllMain failing" + ); + info.entry_rva = 0x800; + image.info = info; + // SAFETY: as above; this entry point is inside the image. + let outcome = unsafe { image.notify(DLL_PROCESS_ATTACH, true, std::ptr::null_mut()) }; + assert_eq!(outcome, Some(7)); + free(base); + } + + #[test] + fn spawn_main_refuses_an_entry_outside_the_image() { + let base = alloc(2, PAGE_EXECUTE_READWRITE); + put(base + PAGE, &ret(9)); + let mut info = info(PAGE as u32); + info.characteristics = 0; // an exe, as the main image is + info.entry_rva = PAGE as u32; + let image = Arc::new(image_at(base, info)); + // SAFETY: the entry point (if it ran) only returns 9. + match unsafe { image.spawn_main(Vec::new()) } { + Err(error) => assert!(error.to_string().contains("outside the image"), "{error:#}"), + Ok(thread) => { + let code = thread.join().unwrap(); + free(base); + panic!("an entry point outside the image ran and returned {code:?}"); + } + } + free(base); + } + + #[test] + fn exports_are_looked_up_by_name() { + let title = tempfile::tempdir().unwrap(); + std::fs::copy( + r"C:\Windows\System32\version.dll", + title.path().join("v.dll"), + ) + .unwrap(); + let loaded = load_title_dll("v.dll", title.path(), title.path(), &|_| true).unwrap(); + assert_eq!(loaded.len(), 1); + let image = &loaded[0].1; + assert!(image.export("GetFileVersionInfoW").is_some()); + assert!(image.export("NoSuchExport").is_none()); + assert!( + image.export("Get\0FileVersionInfoW").is_none(), + "an interior NUL is refused" + ); + assert!( + image.export("getfileversioninfow").is_none(), + "export names are case-sensitive" + ); + assert!( + image + .export_symbol(&ImportSymbol::Name { + hint: 0, + name: "GetFileVersionInfoW".into(), + }) + .is_some() + ); + assert!(image.export_symbol(&ImportSymbol::Ordinal(0)).is_none()); + for (_, dll) in loaded { + // SAFETY: never attached, and no pointer into it outlives the test. + unsafe { dll.unload() }; + } + } + + #[test] + fn title_dlls_are_mapped_once_and_named_in_lowercase() { + let title = tempfile::tempdir().unwrap(); + let cache = tempfile::tempdir().unwrap(); + std::fs::copy( + r"C:\Windows\System32\version.dll", + title.path().join("Late.dll"), + ) + .unwrap(); + let mut main = info(PAGE as u32); + main.imports = vec![import("Late.dll", 0), import("LATE.DLL", 0)]; + main.delay_imports = vec![import("late.dll", 0)]; + let dlls = + load_title_dlls(&main, title.path(), cache.path(), &|dll| dll == "late.dll").unwrap(); + assert_eq!(dlls.len(), 1, "one mapping for three spellings"); + assert_eq!(dlls[0].0, "late.dll"); + assert!(dlls[0].1.export("GetFileVersionInfoW").is_some()); + // `wanted` refuses it, or the folder has no such file: nothing maps. + assert!( + load_title_dlls(&main, title.path(), cache.path(), &|_| false) + .unwrap() + .is_empty() + ); + let mut absent = info(PAGE as u32); + absent.imports = vec![import("absent.dll", 0)]; + assert!( + load_title_dlls(&absent, title.path(), cache.path(), &|_| true) + .unwrap() + .is_empty() + ); + for (_, dll) in dlls { + // SAFETY: never attached, and no pointer into it outlives the test. + unsafe { dll.unload() }; + } + } +} From 9ffb7a19235b3823c6e714b867e3e50da76dadd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:16:20 +0800 Subject: [PATCH 10/49] Shaders: fix 4 DXIL validator bugs and add synthetic container/validator tests --- crates/victory-shader/src/emit/container.rs | 309 ++++++++++++++ crates/victory-shader/src/emit/validator.rs | 427 +++++++++++++++++++- 2 files changed, 719 insertions(+), 17 deletions(-) diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs index 8b05b12..652e69f 100644 --- a/crates/victory-shader/src/emit/container.rs +++ b/crates/victory-shader/src/emit/container.rs @@ -368,8 +368,44 @@ fn md5_block(state: &mut [u32; 4], block: &[u8; 64]) { #[cfg(test)] mod tests { + use super::super::shader::Mesh; use super::*; + fn words(bytes: &[u8]) -> Vec { + let (words, remainder) = bytes.as_chunks::<4>(); + assert!(remainder.is_empty()); + words.iter().copied().map(u32::from_le_bytes).collect() + } + + fn element(name: &str, row: Option, col: u8, cols: u8) -> SigElement { + SigElement { + name: name.into(), + index: 0, + kind: 0, + comp: 9, + interp: 0, + row, + col, + cols, + usage: 1, + half: false, + } + } + + fn empty_psv(stage: u8) -> Psv<'static> { + Psv { + stage, + flag: false, + inputs: &[], + outputs: &[], + prims: &[], + mesh: None, + bindings: &[], + threads: [0; 3], + wave_size: None, + } + } + #[test] fn md5_core_matches_the_standard() { // Standard MD5 of "abc" with standard padding, through md5_block. @@ -386,4 +422,277 @@ mod tests { .collect(); assert_eq!(hex, "900150983cd24fb0d6963f7d28e17f72"); } + + #[test] + fn hash_matches_synthetic_vectors_at_padding_boundaries() { + // Calculated independently by applying MD5 compression to the + // retail-format padded byte sequences 0, 1, ..., len - 1. + let vectors = [ + ( + 0, + [ + 0x14, 0x0d, 0x60, 0xf6, 0xb7, 0x75, 0xe2, 0xba, 0x4e, 0x4a, 0xbe, 0xd4, 0x01, + 0xb2, 0xe9, 0xa1, + ], + ), + ( + 55, + [ + 0x84, 0x2e, 0x55, 0x53, 0x4b, 0xa9, 0x3d, 0xaa, 0x93, 0xe9, 0x4b, 0xd5, 0xaf, + 0x9b, 0x0c, 0x03, + ], + ), + ( + 56, + [ + 0x00, 0xf9, 0xcc, 0x96, 0x4f, 0xf2, 0xec, 0x81, 0x95, 0x9d, 0x4a, 0x3f, 0x09, + 0x2c, 0xe6, 0x3f, + ], + ), + ( + 63, + [ + 0x44, 0x00, 0xd4, 0x28, 0xa4, 0x1d, 0x0e, 0x75, 0xdc, 0x98, 0xb9, 0x36, 0x69, + 0x3f, 0x7b, 0xfb, + ], + ), + ( + 64, + [ + 0xf4, 0x2e, 0xb0, 0x6c, 0xa9, 0x21, 0xc8, 0x78, 0xe4, 0x35, 0xe3, 0xb8, 0xd4, + 0xf9, 0x2b, 0x13, + ], + ), + ( + 119, + [ + 0xba, 0x3a, 0x67, 0xec, 0xd4, 0x64, 0x1c, 0xe4, 0xed, 0x08, 0xf2, 0x91, 0x89, + 0x6e, 0x1b, 0xc6, + ], + ), + ( + 120, + [ + 0x88, 0x2f, 0xce, 0x4f, 0x4c, 0x95, 0x19, 0x43, 0x92, 0xe7, 0xad, 0xef, 0xd5, + 0x3f, 0xe3, 0x43, + ], + ), + ]; + let data: Vec = (0..120).collect(); + for (len, expected) in vectors { + assert_eq!(hash(&data[..len]), expected, "length {len}"); + } + } + + #[test] + fn empty_container_has_only_the_signed_header() { + let bytes = build(&[]); + assert_eq!(&bytes[..4], b"DXBC"); + assert_eq!(&bytes[20..], &[1, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0]); + assert_eq!( + words(&bytes[4..20]), + [0x4c07_86fe, 0xe9c2_2f40, 0xa34f_0f0e, 0xc05b_06bf] + ); + } + + #[test] + fn container_offsets_are_contiguous_after_an_unpadded_signature() { + let bytes = build(&[ + (b"ISG1", &[0x11, 0x22, 0x33]), + (b"OSG1", &[]), + (b"PRIV", &[]), + ]); + assert_eq!(&bytes[..4], b"DXBC"); + assert_eq!(words(&bytes[20..44]), [1, 71, 3, 44, 55, 63]); + assert_eq!(&bytes[44..55], b"ISG1\x03\0\0\0\x11\x22\x33"); + assert_eq!(&bytes[55..63], b"OSG1\0\0\0\0"); + assert_eq!(&bytes[63..], b"PRIV\0\0\0\0"); + assert_eq!( + words(&bytes[4..20]), + [0xe8e8_9b79, 0x8857_cd6c, 0xf7ec_2ab3, 0x137d_e43d] + ); + } + + #[test] + fn signature_sorts_rows_and_preserves_legacy_name_offsets_and_masks() { + assert_eq!(words(&signature(&[], true)), [0, 8]); + let elements = [ + SigElement { + index: 7, + ..element("COLOR", Some(1), 2, 2) + }, + SigElement { + index: 1, + kind: 16, + usage: 15, + ..element("SV_Target", Some(3), 0, 4) + }, + SigElement { + index: 8, + comp: 4, + usage: 2, + ..element("COLOR", Some(1), 0, 2) + }, + SigElement { + kind: 16, + usage: 15, + ..element("SV_Target", Some(2), 0, 4) + }, + SigElement { + kind: 17, + ..element("SV_Depth", None, 0, 1) + }, + ]; + let input = signature(&elements, true); + let output = signature(&elements, false); + let rows = [ + [0, 184, 8, 0, 2, 1, 0x0203, 0], + [0, 168, 7, 0, 3, 1, 0x040c, 0], + [0, 174, 0, 64, 3, 2, 0x0f0f, 0], + [0, 174, 1, 64, 3, 3, 0x0f0f, 0], + [0, 190, 0, 65, 3, u32::MAX, 0x0101, 0], + ]; + assert_eq!(words(&input[..8]), [5, 8]); + assert_eq!(words(&output[..8]), [5, 8]); + assert_eq!(&input[168..], b"COLOR\0SV_Target\0COLOR\0SV_Depth\0"); + assert_eq!(&output[168..], &input[168..]); + for (i, (row, output_mask)) in rows.into_iter().zip([0x0d, 0x0b, 0, 0, 0x0e]).enumerate() { + let start = 8 + 32 * i; + assert_eq!(words(&input[start..start + 32]), row); + let mut expected = row; + expected[6] = (row[6] & 0xff) | (output_mask << 8); + assert_eq!(words(&output[start..start + 32]), expected); + } + } + + #[test] + fn compute_psv_contains_thread_and_wave_sizes_with_empty_tables() { + let bytes = psv(&Psv { + threads: [8, 4, 2], + wave_size: Some(32), + ..empty_psv(5) + }); + assert_eq!( + words(&bytes), + [48, 0, 0, 0, 0, 32, 32, 5, 0, 0, 8, 4, 2, 0, 4, 0, 0] + ); + } + + #[test] + fn pixel_sample_frequency_depends_on_sample_interpolation_or_semantic() { + for (interp, kind, expected) in [(5, 0, 0), (6, 0, 1), (7, 0, 1), (0, 12, 1)] { + let inputs = [SigElement { + interp, + kind, + ..element("UV", Some(0), 0, 1) + }]; + let bytes = psv(&Psv { + flag: true, + inputs: &inputs, + ..empty_psv(0) + }); + assert_eq!(&bytes[4..8], &[1, expected, 0, 0]); + assert_eq!(words(&bytes[20..28]), [0, u32::MAX]); + } + } + + #[test] + fn vertex_psv_encodes_bindings_tables_and_cross_word_dependencies() { + let inputs = [SigElement { + index: 3, + interp: 2, + ..element("COLOR", Some(0), 1, 2) + }]; + let outputs = [SigElement { + index: 3, + ..element("OR", Some(8), 1, 1) + }]; + let bytes = psv(&Psv { + inputs: &inputs, + outputs: &outputs, + bindings: &[ + Binding { + kind: 1, + space: 6, + register: 9, + dxil_kind: 14, + }, + Binding { + kind: 2, + space: 7, + register: 2, + dxil_kind: 13, + }, + ], + ..empty_psv(1) + }); + assert_eq!(&bytes[28..40], &[1, 0, 0, 0, 1, 1, 0, 1, 9, 0, 0, 0]); + assert_eq!( + words(&bytes[52..112]), + [2, 24, 1, 6, 9, 9, 14, 0, 2, 7, 2, 2, 13, 0, 8] + ); + assert_eq!(&bytes[112..120], b"\0COLOR\0\0"); + assert_eq!(words(&bytes[120..132]), [1, 3, 16]); + assert_eq!( + words(&bytes[132..164]), + [1, 0, 0x0052_0001, 0x0203, 4, 0, 0x0051_0801, 3] + ); + assert_eq!( + words(&bytes[164..]), + [u32::MAX, 3, u32::MAX, 3, u32::MAX, 3, 0, 0] + ); + } + + #[test] + fn mesh_psv_encodes_shared_memory_and_primitive_outputs() { + let outputs = [SigElement { + kind: 3, + ..element("SV_Position", Some(0), 0, 4) + }]; + let prims = [SigElement { + kind: 30, + comp: 1, + index: 2, + ..element("SV_CullPrimitive", Some(1), 3, 1) + }]; + let bytes = psv(&Psv { + outputs: &outputs, + prims: &prims, + mesh: Some(( + Mesh { + max_vertices: 64, + max_primitives: 127, + topology: 2, + }, + 1024, + )), + threads: [32, 1, 1], + ..empty_psv(13) + }); + assert_eq!(words(&bytes[..20]), [48, 1024, 0, 0, 0x007f_0040]); + assert_eq!(&bytes[28..40], &[13, 0, 2, 2, 0, 1, 1, 0, 1, 0, 0, 0]); + assert_eq!( + words(&bytes[40..]), + [ + 32, + 1, + 1, + 0, + 4, + 0, + 2, + 0, + 2, + 16, + 0, + 0, + 0x0344_0001, + 3, + 0, + 1, + 0x1e71_0101, + 1 + ] + ); + } } diff --git a/crates/victory-shader/src/emit/validator.rs b/crates/victory-shader/src/emit/validator.rs index 32171c7..f8e31be 100644 --- a/crates/victory-shader/src/emit/validator.rs +++ b/crates/victory-shader/src/emit/validator.rs @@ -8,6 +8,7 @@ use std::ffi::c_void; use std::path::PathBuf; +use windows_sys::Win32::Foundation::{FreeLibrary, HMODULE}; use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; type Hresult = i32; @@ -32,6 +33,7 @@ const IN_PLACE_EDIT: u32 = 1; type CreateInstance = unsafe extern "system" fn(*const Guid, *const Guid, *mut *mut c_void) -> Hresult; +type FreeModule = unsafe extern "system" fn(HMODULE) -> i32; /// COM object: a pointer to a table of method pointers. type Object = *mut *const usize; @@ -108,12 +110,27 @@ static BLOB_VTABLE: BlobVtable = BlobVtable { len: blob_len, }; +struct LoadedModule { + handle: HMODULE, + free: FreeModule, +} + +impl Drop for LoadedModule { + fn drop(&mut self) { + // SAFETY: construction transfers one reference to the module. + unsafe { (self.free)(self.handle) }; + } +} + pub struct Validator { object: Object, + // Field drops run after Validator::drop releases the COM interface. + _module: Option, } // SAFETY: the validator object is free-threaded (DXC's validator has no -// thread affinity); calls are serialised by `&mut self`. +// thread affinity); calls are serialised by `&mut self`. The module reference +// belongs to the process and can be released from another thread. unsafe impl Send for Validator {} impl Validator { @@ -147,20 +164,37 @@ impl Validator { 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(), + Self::from_module(module, FreeLibrary, |module| { + 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(object.cast()) }) } } + // SAFETY: `module` is one owned reference accepted by `free`. On success, + // `create` returns one owned reference to a live validator interface. + unsafe fn from_module( + module: HMODULE, + free: FreeModule, + create: impl FnOnce(HMODULE) -> Result, + ) -> Result { + let module = LoadedModule { + handle: module, + free, + }; + Ok(Self { + object: create(module.handle)?, + _module: Some(module), + }) + } + /// Validates `container` and signs it in place; the error text if it /// is rejected. pub fn validate(&mut self, container: &mut [u8]) -> Result<(), String> { @@ -187,7 +221,11 @@ impl Validator { let mut status = 0; let get_status: unsafe extern "system" fn(Object, *mut Hresult) -> Hresult = method(result, 3); - get_status(result, &mut status); + let hr = get_status(result, &mut status); + if hr < 0 { + release(result); + return Err(format!("GetStatus failed: {hr:#x}")); + } let mut text = String::new(); if status < 0 { let mut errors: Object = std::ptr::null_mut(); @@ -196,11 +234,17 @@ impl Validator { 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(); + let len = len(errors); + if len != 0 { + let ptr = ptr(errors); + if !ptr.is_null() { + let bytes = std::slice::from_raw_parts(ptr, len); + text = String::from_utf8_lossy(bytes) + .trim_end_matches('\0') + .trim() + .into(); + } + } release(errors); } if text.is_empty() { @@ -219,3 +263,352 @@ impl Drop for Validator { unsafe { release(self.object) }; } } + +#[cfg(test)] +mod tests { + use super::*; + + const E_FAIL: Hresult = 0x8000_4005_u32 as Hresult; + const E_INVALIDARG: Hresult = 0x8007_0057_u32 as Hresult; + + #[derive(Default)] + struct Scenario { + validate_hr: Hresult, + omit_result: bool, + status_hr: Hresult, + status: Hresult, + errors_hr: Hresult, + diagnostic: Option<&'static [u8]>, + } + + #[repr(C)] + struct MockHeader { + vtable: *const usize, + releases: u32, + } + + #[repr(C)] + struct Mock { + header: MockHeader, + data: T, + } + + impl Mock { + fn new(vtable: &[usize], data: T) -> Self { + Self { + header: MockHeader { + vtable: vtable.as_ptr(), + releases: 0, + }, + data, + } + } + + fn object(&mut self) -> Object { + std::ptr::from_mut(self).cast() + } + } + + struct MockValidator { + hr: Hresult, + result: Object, + } + + struct MockResult { + status_hr: Hresult, + status: Hresult, + errors_hr: Hresult, + errors: Object, + error_queries: u32, + } + + struct MockErrors { + bytes: &'static [u8], + pointer_queries: u32, + } + + unsafe extern "system" fn mock_release(this: Object) -> u32 { + // SAFETY: every mock object starts with MockHeader. + unsafe { (*this.cast::()).releases += 1 }; + 0 + } + + unsafe extern "system" fn mock_validate( + this: Object, + blob: *mut Blob, + flags: u32, + out: *mut Object, + ) -> Hresult { + // SAFETY: validation invokes this slot on Mock with a + // live input blob and a writable result pointer. + unsafe { + let data = &(*this.cast::>()).data; + let vtable = &*(*blob).vtable; + if flags != IN_PLACE_EDIT || (vtable.len)(blob) != 3 { + return E_INVALIDARG; + } + *(vtable.ptr)(blob).add(1) = 0x5a; + *out = data.result; + data.hr + } + } + + unsafe extern "system" fn mock_status(this: Object, out: *mut Hresult) -> Hresult { + // SAFETY: this slot belongs to Mock and out is writable. + unsafe { + let data = &(*this.cast::>()).data; + if data.status_hr >= 0 { + *out = data.status; + } + data.status_hr + } + } + + unsafe extern "system" fn mock_errors(this: Object, out: *mut Object) -> Hresult { + // SAFETY: this slot belongs to Mock and out is writable. + unsafe { + let data = &mut (*this.cast::>()).data; + data.error_queries += 1; + if data.errors_hr >= 0 { + *out = data.errors; + } + data.errors_hr + } + } + + unsafe extern "system" fn mock_error_ptr(this: Object) -> *const u8 { + // SAFETY: this slot belongs to Mock. + unsafe { + let data = &mut (*this.cast::>()).data; + data.pointer_queries += 1; + if data.bytes.is_empty() { + std::ptr::null() + } else { + data.bytes.as_ptr() + } + } + } + + unsafe extern "system" fn mock_error_len(this: Object) -> usize { + // SAFETY: this slot belongs to Mock. + let data = unsafe { &(*this.cast::>()).data }; + data.bytes.len() + } + + fn validate_mock(scenario: Scenario) -> (Result<(), String>, [u8; 3], [u32; 4]) { + let release = mock_release as *const () as usize; + let validate_vtable = [0, 0, release, mock_validate as *const () as usize]; + let result_vtable = [ + 0, + 0, + release, + mock_status as *const () as usize, + 0, + mock_errors as *const () as usize, + ]; + let errors_vtable = [ + 0, + 0, + release, + mock_error_ptr as *const () as usize, + mock_error_len as *const () as usize, + ]; + let mut errors = Mock::new( + &errors_vtable, + MockErrors { + bytes: scenario.diagnostic.unwrap_or_default(), + pointer_queries: 0, + }, + ); + let mut result = Mock::new( + &result_vtable, + MockResult { + status_hr: scenario.status_hr, + status: scenario.status, + errors_hr: scenario.errors_hr, + errors: scenario + .diagnostic + .map_or(std::ptr::null_mut(), |_| errors.object()), + error_queries: 0, + }, + ); + let mut validator = Mock::new( + &validate_vtable, + MockValidator { + hr: scenario.validate_hr, + result: if scenario.omit_result || scenario.validate_hr < 0 { + std::ptr::null_mut() + } else { + result.object() + }, + }, + ); + let mut bytes = [0x11, 0x22, 0x33]; + let outcome = Validator { + object: validator.object(), + _module: None, + } + .validate(&mut bytes); + assert_eq!(validator.header.releases, 1); + let calls = [ + result.header.releases, + result.data.error_queries, + errors.header.releases, + errors.data.pointer_queries, + ]; + (outcome, bytes, calls) + } + + #[test] + fn failed_status_query_is_an_error_and_releases_the_result() { + let (outcome, _, calls) = validate_mock(Scenario { + status_hr: E_FAIL, + ..Scenario::default() + }); + assert_eq!(outcome, Err("GetStatus failed: 0x80004005".into())); + assert_eq!(calls, [1, 0, 0, 0]); + } + + #[test] + fn empty_diagnostic_needs_no_buffer_pointer() { + let (outcome, _, calls) = validate_mock(Scenario { + status: E_INVALIDARG, + diagnostic: Some(b""), + ..Scenario::default() + }); + assert_eq!(outcome, Err("rejected (0x80070057)".into())); + assert_eq!(calls, [1, 1, 1, 0]); + } + + #[test] + fn validation_passes_the_live_bytes_and_releases_the_result() { + let (outcome, bytes, calls) = validate_mock(Scenario { + validate_hr: 1, + status_hr: 1, + status: 1, + ..Scenario::default() + }); + assert_eq!(outcome, Ok(())); + assert_eq!(bytes, [0x11, 0x5a, 0x33]); + assert_eq!(calls, [1, 0, 0, 0]); + } + + #[test] + fn failed_validation_or_missing_result_is_an_error() { + for (validate_hr, expected) in [(E_FAIL, "0x80004005"), (0, "0x0")] { + let (outcome, _, calls) = validate_mock(Scenario { + validate_hr, + omit_result: true, + ..Scenario::default() + }); + assert_eq!(outcome, Err(format!("Validate failed: {expected}"))); + assert_eq!(calls, [0; 4]); + } + } + + #[test] + fn rejection_returns_trimmed_lossy_diagnostic_and_releases_both_objects() { + let (outcome, _, calls) = validate_mock(Scenario { + status: E_INVALIDARG, + diagnostic: Some(b" invalid \xff signature\r\n\0\0"), + ..Scenario::default() + }); + assert_eq!(outcome, Err("invalid \u{fffd} signature".into())); + assert_eq!(calls, [1, 1, 1, 1]); + } + + #[test] + fn rejection_falls_back_to_status_without_a_diagnostic() { + for (errors_hr, diagnostic, diagnostic_releases) in [ + (E_FAIL, Some(&b"unavailable"[..]), 0), + (0, None, 0), + (0, Some(&b" \r\n\0"[..]), 1), + ] { + let (outcome, _, calls) = validate_mock(Scenario { + status: E_INVALIDARG, + errors_hr, + diagnostic, + ..Scenario::default() + }); + assert_eq!(outcome, Err("rejected (0x80070057)".into())); + assert_eq!(calls, [1, 1, diagnostic_releases, diagnostic_releases]); + } + } + + #[test] + fn blob_exposes_only_iunknown_and_idxcblob() { + let mut bytes = [1, 2, 3]; + let mut blob = Blob { + vtable: &BLOB_VTABLE, + data: bytes.as_mut_ptr(), + len: bytes.len(), + }; + let this = std::ptr::from_mut(&mut blob); + // SAFETY: the vtable belongs to the live stack blob and each query + // uses an initialized IID and a writable output slot. + unsafe { + let mut out = std::ptr::null_mut(); + for iid in [IUNKNOWN, IDXC_BLOB] { + assert_eq!((BLOB_VTABLE.qi)(this, &iid, &mut out), 0); + assert_eq!(out, this.cast()); + } + assert_eq!( + (BLOB_VTABLE.qi)(this, &[0xff; 16], &mut out), + 0x8000_4002_u32 as Hresult + ); + assert!(out.is_null()); + assert_eq!((BLOB_VTABLE.add_ref)(this), 1); + assert_eq!((BLOB_VTABLE.release)(this), 1); + } + } + + #[derive(Default)] + struct MockModule { + object: Object, + frees: u32, + object_releases_at_free: u32, + } + + unsafe extern "system" fn mock_free(module: HMODULE) -> i32 { + // SAFETY: the test supplies a live MockModule and, when present, a + // live object whose first field is a MockHeader. + unsafe { + let module = &mut *module.cast::(); + module.frees += 1; + if !module.object.is_null() { + module.object_releases_at_free = (*module.object.cast::()).releases; + } + } + 1 + } + + #[test] + fn failed_validator_creation_frees_the_module() { + let mut module = MockModule::default(); + let handle = std::ptr::from_mut(&mut module).cast(); + // SAFETY: mock_free accepts this live mock module. + let outcome = + unsafe { Validator::from_module(handle, mock_free, |_| Err("creation failed".into())) }; + assert_eq!(outcome.err().as_deref(), Some("creation failed")); + assert_eq!(module.frees, 1); + } + + #[test] + fn dropping_validator_releases_the_object_before_freeing_the_module() { + let vtable = [0, 0, mock_release as *const () as usize]; + let mut object = Mock::new(&vtable, ()); + let object = object.object(); + let mut module = MockModule { + object, + ..MockModule::default() + }; + let handle = std::ptr::from_mut(&mut module).cast(); + // SAFETY: the mock module, interface and vtable outlive the validator. + let validator = + unsafe { Validator::from_module(handle, mock_free, |_| Ok(object)) }.unwrap(); + assert_eq!(module.frees, 0); + drop(validator); + assert_eq!(module.frees, 1); + assert_eq!(module.object_releases_at_free, 1); + } +} From e3c9dd0d53d92d7a1dc7b86d75147d3ed390c61a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:24:15 +0800 Subject: [PATCH 11/49] GPU: guard zero/overflowing stride in expand_rects and add primitive.rs unit tests --- crates/victory-gpu/src/primitive.rs | 89 ++++++++++++++++++++++++++++- 1 file changed, 87 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index d925048..5fca6a2 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -16,9 +16,15 @@ /// 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)]) { + if stride == 0 { + return; + } + let (Some(in_rect), Some(out_rect)) = (stride.checked_mul(3), stride.checked_mul(6)) else { + return; + }; for (rect, out) in src - .chunks_exact(3 * stride) - .zip(dst.chunks_exact_mut(6 * stride)) + .chunks_exact(in_rect) + .zip(dst.chunks_exact_mut(out_rect)) { let v = |i: usize| &rect[i * stride..(i + 1) * stride]; for (slot, i) in [0, 1, 2, 0, 2].into_iter().enumerate() { @@ -228,4 +234,83 @@ mod tests { assert_eq!(f32_to_half(1.5), 0x3e00); assert_eq!(half_to_f32(0x0001), 2f32.powi(-24)); } + + #[test] + fn zero_or_overflowing_stride_is_ignored_without_panicking() { + let mut dst = [0xAAu8; 16]; + expand_rects(&[1, 2, 3], &mut dst, 0, &[(0, 16)]); + assert_eq!(dst, [0xAAu8; 16]); + expand_rects(&[1, 2, 3], &mut dst, usize::MAX / 2, &[(0, 16)]); + assert_eq!(dst, [0xAAu8; 16]); + } + + #[test] + fn unorm16_unorm8_clamping_and_unknown_formats_expand_correctly() { + // Vertex layout (12 bytes): + // 0..4: R16G16_UNORM (format 35) + // 4..8: R8G8B8A8_UNORM (format 28) — tests clamping below 0 and above 1 + // 8..12: unknown format (999) — must keep v0's bytes verbatim + let v = |u0: u16, u1: u16, c: [u8; 4], raw: [u8; 4]| { + let mut b = Vec::with_capacity(12); + b.extend(u0.to_le_bytes()); + b.extend(u1.to_le_bytes()); + b.extend(c); + b.extend(raw); + b + }; + let src = [ + v( + 10_000, + 50_000, + [10, 200, 100, 255], + [0xDE, 0xAD, 0xBE, 0xEF], + ), + v(20_000, 10_000, [100, 50, 100, 255], [1, 2, 3, 4]), + v(30_000, 20_000, [20, 200, 100, 255], [5, 6, 7, 8]), + ] + .concat(); + let mut dst = vec![0u8; 6 * 12]; + expand_rects(&src, &mut dst, 12, &[(0, 35), (4, 28), (8, 999)]); + let fourth = &dst[60..72]; + // u0: 10000 + 30000 - 20000 = 20000; u1: 50000 + 20000 - 10000 = 60000 + assert_eq!(u16::from_le_bytes([fourth[0], fourth[1]]), 20_000); + assert_eq!(u16::from_le_bytes([fourth[2], fourth[3]]), 60_000); + // c0: 10 + 20 - 100 -> clamped to 0; c1: 200 + 200 - 50 -> clamped to 255 + assert_eq!(&fourth[4..8], &[0, 255, 100, 255]); + // Unknown format keeps v0 bytes + assert_eq!(&fourth[8..12], &[0xDE, 0xAD, 0xBE, 0xEF]); + } + + #[test] + fn multiple_rectangles_and_f32_f16_vector_formats_expand_in_sequence() { + // Two rectangles of R32G32B32_FLOAT (format 6, 12 bytes) + R16G16_FLOAT (format 34, 4 bytes) = 16 bytes + let v = |p: [f32; 3], uv: [f32; 2]| { + let mut b = Vec::with_capacity(16); + for x in p { + b.extend(x.to_le_bytes()); + } + for x in uv { + b.extend(f32_to_half(x).to_le_bytes()); + } + b + }; + let src = [ + // Rect 0 + v([0.0, 1.0, 0.5], [0.0, 0.0]), + v([0.0, 0.0, 0.5], [0.0, 1.0]), + v([2.0, 0.0, 0.5], [1.0, 1.0]), + // Rect 1 + v([10.0, 20.0, 1.0], [0.25, 0.5]), + v([10.0, 10.0, 1.0], [0.25, 1.0]), + v([14.0, 10.0, 1.0], [0.75, 1.0]), + ] + .concat(); + let mut dst = vec![0u8; 12 * 16]; + expand_rects(&src, &mut dst, 16, &[(0, 6), (12, 34)]); + assert_eq!(&dst[5 * 16..6 * 16], &v([2.0, 1.0, 0.5], [1.0, 0.0])[..]); + assert_eq!( + &dst[11 * 16..12 * 16], + &v([14.0, 20.0, 1.0], [0.75, 0.5])[..] + ); + } } From ef0c3e944916e2273457626be3d34f8dd5591eb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:30:43 +0800 Subject: [PATCH 12/49] GPU: validate null args in create_deserializer to prevent d3d12 AV and add root.rs tests --- crates/victory-gpu/src/root.rs | 262 ++++++++++++++++++++++++++++++++- 1 file changed, 260 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/root.rs b/crates/victory-gpu/src/root.rs index 10368e9..3ae533f 100644 --- a/crates/victory-gpu/src/root.rs +++ b/crates/victory-gpu/src/root.rs @@ -154,7 +154,10 @@ pub extern "system" fn create_deserializer( iid: *const Iid, out: *mut *mut c_void, ) -> HRESULT { - if blob.is_null() || out.is_null() { + // The host dereferences the interface id without checking it, so a null + // one is answered here instead of crashing there; an empty blob is + // malformed and rejected the same way. + if blob.is_null() || size == 0 || iid.is_null() || out.is_null() { return E_INVALIDARG; } static FUNCTION: OnceLock> = OnceLock::new(); @@ -215,7 +218,218 @@ static FUNCTIONS: Table<24> = { #[cfg(test)] mod tests { use super::*; - use crate::object::{S_OK, slot}; + use crate::object::{E_NOINTERFACE, E_POINTER, S_FALSE, S_OK, slot}; + + /// An interface we do not implement. + const OTHER_IID: Iid = guid(0x5a5a_5a5a, 0x5a5a, 0x5a5a, [0x5a; 8]); + + /// The shim hands the blob to the host unchanged; `create` keeps it, so + /// any bytes serve. + const BLOB: [u8; 4] = [0x01, 0x02, 0x03, 0x04]; + + fn created(iid: &Iid) -> This { + let mut out = std::ptr::null(); + let hr = create( + std::ptr::null(), + 0, + BLOB.as_ptr(), + BLOB.len(), + iid, + &mut out, + ); + assert_eq!(hr, S_OK); + assert!(!out.is_null()); + out + } + + /// The host's structures, field for field (64-bit layout). + #[cfg(target_pointer_width = "64")] + #[test] + fn descriptions_keep_the_pc_layout() { + assert_eq!(std::mem::size_of::(), 40); + assert_eq!(std::mem::offset_of!(Desc, parameter_count), 0); + assert_eq!(std::mem::offset_of!(Desc, parameters), 8); + assert_eq!(std::mem::offset_of!(Desc, sampler_count), 16); + assert_eq!(std::mem::offset_of!(Desc, samplers), 24); + assert_eq!(std::mem::offset_of!(Desc, flags), 32); + assert_eq!(std::mem::size_of::(), 48); + assert_eq!(std::mem::offset_of!(VersionedDesc, version), 0); + assert_eq!(std::mem::offset_of!(VersionedDesc, desc), 8); + } + + #[test] + fn console_flags_are_dropped_and_the_rest_kept() { + assert_eq!(CONSOLE_FLAGS, 0xff00_0000); + let desc = Desc { + parameter_count: 2, + parameters: BLOB.as_ptr().cast(), + sampler_count: 1, + samplers: BLOB.as_ptr().cast(), + flags: 0xffff_ffff, + }; + let plain = without_console_flags(desc); + assert_eq!(plain.flags, 0x00ff_ffff); + assert_eq!((plain.parameter_count, plain.sampler_count), (2, 1)); + assert!(std::ptr::eq(plain.parameters, desc.parameters)); + assert!(std::ptr::eq(plain.samplers, desc.samplers)); + + let low = Desc { + flags: 0x00ab_cdef, + ..desc + }; + assert_eq!(without_console_flags(low).flags, 0x00ab_cdef); + let none = Desc { flags: 0, ..desc }; + assert_eq!(without_console_flags(none).flags, 0); + } + + #[test] + fn serializers_reject_a_null_description() { + let mut blob = std::ptr::null_mut(); + let mut error = std::ptr::null_mut(); + assert_eq!( + serialize(std::ptr::null(), 1, &mut blob, &mut error), + E_INVALIDARG + ); + assert_eq!( + serialize_versioned(std::ptr::null(), &mut blob, &mut error), + E_INVALIDARG + ); + assert!(blob.is_null() && error.is_null()); + } + + /// A null `riid` used to be forwarded to the host, which dereferences it + /// (an access violation in `d3d12.dll`); an empty blob is malformed. + #[test] + fn deserializer_creation_rejects_missing_arguments() { + let iid = ROOT_SIGNATURE_IIDS[0]; + let mut out = std::ptr::null_mut(); + assert_eq!( + create_deserializer(std::ptr::null(), BLOB.len(), &iid, &mut out), + E_INVALIDARG + ); + assert_eq!( + create_deserializer(BLOB.as_ptr(), BLOB.len(), std::ptr::null(), &mut out), + E_INVALIDARG + ); + assert_eq!( + create_deserializer(BLOB.as_ptr(), 0, &iid, &mut out), + E_INVALIDARG + ); + assert_eq!( + create_deserializer(BLOB.as_ptr(), BLOB.len(), &iid, std::ptr::null_mut()), + E_INVALIDARG + ); + assert!(out.is_null()); + } + + #[test] + fn creating_a_root_signature_checks_its_arguments() { + let iid = ROOT_SIGNATURE_IIDS[0]; + let mut out = std::ptr::null(); + assert_eq!( + create( + std::ptr::null(), + 0, + std::ptr::null(), + BLOB.len(), + &iid, + &mut out + ), + E_INVALIDARG + ); + assert_eq!( + create(std::ptr::null(), 0, BLOB.as_ptr(), 0, &iid, &mut out), + E_INVALIDARG + ); + assert!(out.is_null()); + + // An unknown interface is dropped, and the answer is null. + assert_eq!( + create( + std::ptr::null(), + 0, + BLOB.as_ptr(), + BLOB.len(), + &OTHER_IID, + &mut out + ), + E_NOINTERFACE + ); + assert!(out.is_null()); + assert_eq!( + create( + std::ptr::null(), + 0, + BLOB.as_ptr(), + BLOB.len(), + std::ptr::null(), + &mut out + ), + E_NOINTERFACE + ); + assert!(out.is_null()); + + // Nowhere to write means the title only asked whether creation works. + assert_eq!( + create( + std::ptr::null(), + 0, + BLOB.as_ptr(), + BLOB.len(), + &iid, + std::ptr::null_mut() + ), + S_FALSE + ); + } + + #[test] + fn every_known_interface_creates_a_working_object() { + let root = created(&ROOT_SIGNATURE_IIDS[0]); + let query = slot:: HRESULT>(root, 0); + for iid in &ROOT_SIGNATURE_IIDS { + let mut out = std::ptr::null(); + assert_eq!(query(root, iid, &mut out), S_OK); + assert!(std::ptr::eq(out, root)); + assert_eq!(object::release(out), 1, "the original reference remains"); + } + let mut out = std::ptr::null(); + assert_eq!(query(root, &OTHER_IID, &mut out), E_NOINTERFACE); + assert!(out.is_null()); + assert_eq!(query(root, std::ptr::null(), &mut out), E_NOINTERFACE); + assert_eq!( + query(root, &ROOT_SIGNATURE_IIDS[0], std::ptr::null_mut()), + E_POINTER + ); + assert_eq!(object::release(root), 0); + } + + #[test] + fn the_table_has_the_object_and_device_child_slots() { + let root = created(&ROOT_SIGNATURE_IIDS[1]); + // SetPrivateDataInterface is the one object method left out. + assert_eq!( + slot:: HRESULT>(root, 0x28)(), + E_NOTIMPL + ); + assert_eq!( + slot:: HRESULT>(root, 0x30)( + root, + std::ptr::null() + ), + S_OK + ); + // GetDevice: an unknown interface is answered, not dereferenced. + let mut device = std::ptr::null(); + let get_device = + slot:: HRESULT>(root, 0x38); + assert_eq!( + get_device(root, std::ptr::null(), &mut device), + E_NOINTERFACE + ); + assert!(device.is_null()); + assert_eq!(object::release(root), 0); + } /// One 32-bit constant at b0, serialized by the host, then created. #[cfg(windows)] @@ -321,4 +535,48 @@ mod tests { E_INVALIDARG ); } + + /// Truncated and nonsense blobs reach the host, which rejects them + /// without writing an object. + #[cfg(windows)] + #[test] + fn malformed_blobs_are_rejected_by_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::(); + let data = slot:: *const u8>(blob, 0x18)(blob); + let size = slot:: 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 - 1, &iid, &mut out), + E_INVALIDARG + ); + assert!(out.is_null()); + let garbage = [0xffu8; 64]; + assert_eq!( + create_deserializer(garbage.as_ptr(), garbage.len(), &iid, &mut out), + E_INVALIDARG + ); + assert!(out.is_null()); + slot:: u32>(blob, 0x10)(blob); + } } From 649c6e5274efcf58ac5f608482f751486d9cb0fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:32:51 +0800 Subject: [PATCH 13/49] GPU: validate input layouts and aligned vertex offsets in pipeline/host.rs with unit tests --- crates/victory-gpu/src/pipeline/host.rs | 680 +++++++++++++++++++++--- 1 file changed, 611 insertions(+), 69 deletions(-) diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 00aa9aa..d2c6fc5 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -24,9 +24,8 @@ pub(crate) struct GraphicsState { sample_mask: u32, rasterizer: D3D12_RASTERIZER_DESC, depth: D3D12_DEPTH_STENCIL_DESC, - /// Input elements, their names pointing into `names`. - inputs: Vec, - names: Vec, + /// `None` if the stream supplied an invalid input layout. + input_layout: Option, strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, pub(crate) topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE, pub(crate) targets: D3D12_RT_FORMAT_ARRAY, @@ -75,8 +74,7 @@ impl Default for GraphicsState { BackFace: keep, ..Default::default() }, - inputs: Vec::new(), - names: Vec::new(), + input_layout: Some(InputLayout::default()), strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED, targets: D3D12_RT_FORMAT_ARRAY::default(), @@ -94,7 +92,10 @@ impl GraphicsState { /// (+8 for those holding pointers). /// /// # Safety - /// `at` points at a whole subobject of type `kind`. + /// `at` points at a whole subobject of type `kind`. When an input layout + /// has a nonzero, in-range count and a non-null, aligned descriptor + /// pointer, that pointer must reference an array of that many initialized + /// elements. Each non-null semantic name read must point to a C string. pub(crate) unsafe fn read(&mut self, kind: u32, at: *const u8) { // SAFETY: the caller passes a whole subobject. unsafe { @@ -122,28 +123,7 @@ impl GraphicsState { } 12 => { let layout = at.add(8).cast::().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(); + self.input_layout = InputLayout::read(layout); } 13 => { self.strip_cut = @@ -172,19 +152,10 @@ impl GraphicsState { /// Everything the state holds, as text: part of a pipeline's name in /// the library and of the key a title pipeline is started early by. pub(crate) fn describe(&self) -> String { - let inputs: Vec = self - .inputs - .iter() - .zip(&self.names) - .map(|(e, name)| { - format!( - "{name:?} {} {} {} {} {} {}", - e.SemanticIndex, e.Format.0, e.InputSlot, e.AlignedByteOffset, e.InputSlotClass.0, e.InstanceDataStepRate - ) - }) - .collect(); + let inputs = self.input_layout.as_ref().map(InputLayout::describe); + let inputs = inputs.as_deref().unwrap_or(""); format!( - "{:?} {} {:?} {:?} {inputs:?} {} {} {:?} {} {:?}", + "{:?} {} {:?} {:?} {inputs} {} {} {:?} {} {:?}", self.blend, self.sample_mask, self.rasterizer, @@ -196,35 +167,104 @@ impl GraphicsState { self.samples ) } +} + +#[derive(Default)] +struct InputLayout { + /// Input elements, their names pointing into `names`. + inputs: Vec, + names: Vec, +} + +impl InputLayout { + /// # Safety + /// The input layout's pointers must meet the requirements of `GraphicsState::read`. + unsafe fn read(layout: D3D12_INPUT_LAYOUT_DESC) -> Option { + let count = layout.NumElements; + if count == 0 { + return Some(Self::default()); + } + let ptr = layout.pInputElementDescs; + if count > D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT + || ptr.is_null() + || !ptr.is_aligned() + { + return None; + } + + let count = count as usize; + // SAFETY: the pointer passed the shape checks and the caller supplies + // the complete array. + let elements = unsafe { std::slice::from_raw_parts(ptr, count) }; + let mut owned = Self { + inputs: Vec::with_capacity(count), + names: Vec::with_capacity(count), + }; + for e in elements { + if e.InputSlot >= D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT || e.SemanticName.is_null() + { + return None; + } + // SAFETY: the caller supplies a C string for each non-null name. + let name = unsafe { CStr::from_ptr(e.SemanticName.0.cast()) }.to_owned(); + owned.inputs.push(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 + }); + owned.names.push(name); + } + Some(owned) + } + + fn describe(&self) -> String { + let inputs: Vec = self + .inputs + .iter() + .zip(&self.names) + .map(|(e, name)| { + format!( + "{name:?} {} {} {} {} {} {}", + e.SemanticIndex, + e.Format.0, + e.InputSlot, + e.AlignedByteOffset, + e.InputSlotClass.0, + e.InstanceDataStepRate, + ) + }) + .collect(); + format!("{inputs:?}") + } /// 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)) + self.inputs.iter().fold(0, |m, e| m | 1 << e.InputSlot) } /// The input elements with their byte offsets worked out. - fn elements(&self) -> Vec { - let mut next = [0u32; 32]; + fn elements(&self) -> Option> { + let mut next = [0u32; D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT as usize]; self.inputs .iter() .map(|e| { - let slot = e.InputSlot.min(31) as usize; + let slot = e.InputSlot as usize; let format = e.Format.0 as u32; + let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32); let offset = if e.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT { - next[slot] + // The input assembler caps natural element alignment at 4 bytes. + let alignment = bytes.min(4).next_power_of_two(); + next[slot].checked_next_multiple_of(alignment)? } 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, + next[slot] = offset.checked_add(bytes)?; + Some(Input { + slot: e.InputSlot, offset, format, per_instance: e.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, - } + }) }) .collect() } @@ -321,7 +361,10 @@ impl HostPipeline { stages }; if mesh.is_some() && !host()?.mesh_shaders() { - return refuse("the host GPU has no mesh shaders (or no shader model 6.6)", shaders); + return refuse( + "the host GPU has no mesh shaders (or no shader model 6.6)", + shaders, + ); } for (s, _) in &stages { s.translated()?; @@ -401,13 +444,14 @@ impl HostPipeline { } bound.push(stage); } - let (root, root_blob) = match root_signature(&host.device, ¶ms, &samplers, compute.is_some()) { - Ok(root) => root, - Err(e) => { - tracing::warn!(error = %e, ?shaders, "host root signature refused"); - return None; - } - }; + let (root, root_blob) = + match root_signature(&host.device, ¶ms, &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(), @@ -486,6 +530,12 @@ impl HostPipeline { }); } + let Some(layout) = &g.input_layout else { + return refuse("invalid input layout", shaders); + }; + let Some(inputs) = layout.elements() else { + return refuse("input layout byte offset overflow", shaders); + }; let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { // SAFETY: a borrowed pointer the description never releases. pRootSignature: unsafe { std::mem::transmute_copy(&root) }, @@ -496,8 +546,8 @@ impl HostPipeline { RasterizerState: g.rasterizer, DepthStencilState: g.depth, InputLayout: D3D12_INPUT_LAYOUT_DESC { - pInputElementDescs: g.inputs.as_ptr(), - NumElements: g.inputs.len() as u32, + pInputElementDescs: layout.inputs.as_ptr(), + NumElements: layout.inputs.len() as u32, }, IBStripCutValue: g.strip_cut, // The console's rectangle and quad types draw as triangles on @@ -551,8 +601,8 @@ impl HostPipeline { root, stages: bound, name: format!("{shaders:?}"), - slots: g.slots(), - inputs: g.elements(), + slots: layout.slots(), + inputs, }) } } @@ -585,15 +635,27 @@ fn mesh_pipeline( samples: Sub, } let mut stream = Stream { - root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), + 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), + 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), + 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 { @@ -616,7 +678,8 @@ fn code_bytes(code: &D3D12_SHADER_BYTECODE) -> Vec { return Vec::new(); } // SAFETY: a translation's own bytes, alive while its shader is. - unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::(), code.BytecodeLength) }.to_vec() + unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::(), code.BytecodeLength) } + .to_vec() } fn root_signature( @@ -665,3 +728,482 @@ fn root_signature( Ok((device.CreateRootSignature(0, bytes)?, bytes.to_vec())) } } + +#[cfg(test)] +mod tests { + use super::*; + + fn read_subobject( + state: &mut GraphicsState, + kind: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, + data: T, + ) { + #[repr(C, align(8))] + struct Subobject(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); + + let subobject = Subobject(kind, data); + // SAFETY: the test supplies the payload type for the given kind and + // keeps any data it references alive for the call. + unsafe { state.read(kind.0 as u32, (&raw const subobject).cast()) }; + } + + fn read_layout(state: &mut GraphicsState, elements: &[D3D12_INPUT_ELEMENT_DESC]) { + read_subobject( + state, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, + D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: elements.as_ptr(), + NumElements: elements.len() as u32, + }, + ); + } + + fn input(slot: u32, format: DXGI_FORMAT, offset: u32) -> D3D12_INPUT_ELEMENT_DESC { + D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(c"SYNTHETIC".as_ptr().cast()), + Format: format, + InputSlot: slot, + AlignedByteOffset: offset, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + ..Default::default() + } + } + + #[test] + fn empty_input_layout_replaces_existing_elements() { + let mut state = GraphicsState::default(); + let element = input(3, DXGI_FORMAT_R32_FLOAT, 0); + for ptr in [std::ptr::null(), &raw const element] { + read_layout(&mut state, &[element]); + assert_eq!(state.input_layout.as_ref().unwrap().slots(), 1 << 3); + + read_subobject( + &mut state, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, + D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: ptr, + NumElements: 0, + }, + ); + let layout = state.input_layout.as_ref().unwrap(); + assert_eq!(layout.slots(), 0); + assert!(layout.elements().unwrap().is_empty()); + assert_eq!(state.describe(), GraphicsState::default().describe()); + } + } + + #[test] + fn oversized_input_layout_is_discarded() { + let mut state = GraphicsState::default(); + let element = input(0, DXGI_FORMAT_R32_FLOAT, 0); + let elements: [_; 33] = std::array::from_fn(|i| D3D12_INPUT_ELEMENT_DESC { + SemanticIndex: i as u32, + ..element + }); + read_layout(&mut state, &elements[..32]); + assert_eq!(state.input_layout.as_ref().unwrap().inputs.len(), 32); + + read_layout(&mut state, &elements); + assert!(state.input_layout.is_none()); + } + + #[test] + fn out_of_range_input_slot_is_discarded() { + let mut state = GraphicsState::default(); + read_layout(&mut state, &[input(32, DXGI_FORMAT_R32_FLOAT, 0)]); + + assert!(state.input_layout.is_none()); + } + + #[test] + fn nonempty_input_layout_requires_an_aligned_non_null_array() { + let mut state = GraphicsState::default(); + let element = input(0, DXGI_FORMAT_R32_FLOAT, 0); + let misaligned = (&raw const element).cast::().wrapping_add(1).cast(); + for ptr in [std::ptr::null(), misaligned] { + read_layout(&mut state, &[element]); + read_subobject( + &mut state, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, + D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: ptr, + NumElements: 1, + }, + ); + assert!(state.input_layout.is_none()); + } + } + + #[test] + fn null_semantic_name_discards_the_layout() { + let mut state = GraphicsState::default(); + let valid = input(0, DXGI_FORMAT_R32_FLOAT, 0); + let invalid = D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR::null(), + ..input(1, DXGI_FORMAT_R32_FLOAT, 0) + }; + read_layout(&mut state, &[valid]); + read_layout(&mut state, &[valid, invalid]); + assert!(state.input_layout.is_none()); + assert_ne!(state.describe(), GraphicsState::default().describe()); + + read_layout(&mut state, &[valid]); + assert_eq!(state.input_layout.as_ref().unwrap().slots(), 1); + } + + #[test] + fn input_layout_owns_semantic_names_and_describes_their_values() { + let mut state = GraphicsState::default(); + let element = D3D12_INPUT_ELEMENT_DESC { + SemanticIndex: 7, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, + InstanceDataStepRate: 3, + ..input(2, DXGI_FORMAT(119), 12) + }; + { + let name = CString::new("SYNTHETIC").unwrap(); + let source = D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(name.as_ptr().cast()), + ..element + }; + read_layout(&mut state, &[source]); + assert_ne!( + state.input_layout.as_ref().unwrap().inputs[0].SemanticName, + source.SemanticName, + ); + } + let stored = state.input_layout.as_ref().unwrap().inputs[0]; + // SAFETY: the state still owns the copied string. + let copied_name = unsafe { CStr::from_ptr(stored.SemanticName.0.cast()) }; + assert_eq!(copied_name, c"SYNTHETIC"); + assert_eq!( + stored, + D3D12_INPUT_ELEMENT_DESC { + SemanticName: stored.SemanticName, + Format: DXGI_FORMAT_R24_UNORM_X8_TYPELESS, + ..element + }, + ); + + let mut other = GraphicsState::default(); + read_layout(&mut other, &[element]); + assert_eq!(state.describe(), other.describe()); + read_layout( + &mut other, + &[D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(c"OTHER".as_ptr().cast()), + ..element + }], + ); + assert_ne!(state.describe(), other.describe()); + } + + #[test] + fn appended_inputs_respect_format_alignment_per_slot() { + let mut state = GraphicsState::default(); + let append = D3D12_APPEND_ALIGNED_ELEMENT; + let mut instance = input(31, DXGI_FORMAT_R16_UINT, append); + instance.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA; + instance.InstanceDataStepRate = 2; + let mut instance_next = instance; + instance_next.Format = DXGI_FORMAT_R32_FLOAT; + read_layout( + &mut state, + &[ + input(0, DXGI_FORMAT_R8_UINT, 0), + instance, + input(0, DXGI_FORMAT_R16_UINT, append), + instance_next, + input(0, DXGI_FORMAT_R32G32B32_FLOAT, append), + input(0, DXGI_FORMAT_R8_UINT, append), + input(0, DXGI_FORMAT_R32_FLOAT, 24), + input(0, DXGI_FORMAT_R32_FLOAT, append), + ], + ); + + let layout = state.input_layout.as_ref().unwrap(); + assert_eq!(layout.slots(), 1 | (1 << 31)); + let elements = layout.elements().unwrap(); + let locations: Vec<_> = elements + .iter() + .map(|e| (e.slot, e.offset, e.format, e.per_instance)) + .collect(); + assert_eq!( + locations, + [ + (0, 0, 62, false), + (31, 0, 57, true), + (0, 2, 57, false), + (31, 4, 41, true), + (0, 4, 6, false), + (0, 16, 62, false), + (0, 24, 41, false), + (0, 28, 41, false), + ], + ); + } + + #[test] + fn input_offset_overflow_is_rejected() { + let mut state = GraphicsState::default(); + read_layout(&mut state, &[input(0, DXGI_FORMAT_R32_FLOAT, u32::MAX - 3)]); + assert!(state.input_layout.as_ref().unwrap().elements().is_none()); + + read_layout( + &mut state, + &[ + input(0, DXGI_FORMAT_R8_UINT, u32::MAX - 1), + input(0, DXGI_FORMAT_R32_FLOAT, D3D12_APPEND_ALIGNED_ELEMENT), + ], + ); + assert!(state.input_layout.as_ref().unwrap().elements().is_none()); + } + + #[test] + fn omitted_subobjects_use_d3d12_defaults() { + let state = GraphicsState::default(); + assert!(!state.blend.AlphaToCoverageEnable.as_bool()); + assert!(!state.blend.IndependentBlendEnable.as_bool()); + for target in state.blend.RenderTarget { + assert!(!target.BlendEnable.as_bool()); + assert!(!target.LogicOpEnable.as_bool()); + assert_eq!(target.SrcBlend, D3D12_BLEND_ONE); + assert_eq!(target.DestBlend, D3D12_BLEND_ZERO); + assert_eq!(target.BlendOp, D3D12_BLEND_OP_ADD); + assert_eq!(target.SrcBlendAlpha, D3D12_BLEND_ONE); + assert_eq!(target.DestBlendAlpha, D3D12_BLEND_ZERO); + assert_eq!(target.BlendOpAlpha, D3D12_BLEND_OP_ADD); + assert_eq!(target.LogicOp, D3D12_LOGIC_OP_NOOP); + assert_eq!(target.RenderTargetWriteMask, 0xf); + } + assert_eq!(state.sample_mask, u32::MAX); + assert_eq!(state.rasterizer.FillMode, D3D12_FILL_MODE_SOLID); + assert_eq!(state.rasterizer.CullMode, D3D12_CULL_MODE_BACK); + assert!(!state.rasterizer.FrontCounterClockwise.as_bool()); + assert!(state.rasterizer.DepthClipEnable.as_bool()); + assert_eq!(state.rasterizer.DepthBias, 0); + assert!(state.depth.DepthEnable.as_bool()); + assert_eq!(state.depth.DepthWriteMask, D3D12_DEPTH_WRITE_MASK_ALL); + assert_eq!(state.depth.DepthFunc, D3D12_COMPARISON_FUNC_LESS); + assert!(!state.depth.StencilEnable.as_bool()); + assert_eq!(state.depth.StencilReadMask, 0xff); + assert_eq!(state.depth.StencilWriteMask, 0xff); + for face in [state.depth.FrontFace, state.depth.BackFace] { + assert_eq!(face.StencilFailOp, D3D12_STENCIL_OP_KEEP); + assert_eq!(face.StencilDepthFailOp, D3D12_STENCIL_OP_KEEP); + assert_eq!(face.StencilPassOp, D3D12_STENCIL_OP_KEEP); + assert_eq!(face.StencilFunc, D3D12_COMPARISON_FUNC_ALWAYS); + } + assert_eq!(state.strip_cut, D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED); + assert_eq!(state.topology, D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED); + assert_eq!(state.targets.NumRenderTargets, 0); + assert_eq!(state.targets.RTFormats, [DXGI_FORMAT_UNKNOWN; 8]); + assert_eq!(state.depth_format, DXGI_FORMAT_UNKNOWN); + assert_eq!( + state.samples, + DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0 + } + ); + } + + #[test] + fn reads_blend_and_rasterizer_state() { + let mut state = GraphicsState::default(); + let mut blend = D3D12_BLEND_DESC { + AlphaToCoverageEnable: true.into(), + IndependentBlendEnable: true.into(), + RenderTarget: state.blend.RenderTarget, + }; + blend.RenderTarget[0] = D3D12_RENDER_TARGET_BLEND_DESC { + BlendEnable: true.into(), + SrcBlend: D3D12_BLEND_SRC_ALPHA, + DestBlend: D3D12_BLEND_INV_SRC_ALPHA, + BlendOp: D3D12_BLEND_OP_REV_SUBTRACT, + SrcBlendAlpha: D3D12_BLEND_DEST_ALPHA, + DestBlendAlpha: D3D12_BLEND_INV_DEST_ALPHA, + BlendOpAlpha: D3D12_BLEND_OP_MAX, + RenderTargetWriteMask: 0x5, + ..blend.RenderTarget[0] + }; + blend.RenderTarget[7].LogicOpEnable = true.into(); + blend.RenderTarget[7].LogicOp = D3D12_LOGIC_OP_XOR; + let raster = D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_WIREFRAME, + CullMode: D3D12_CULL_MODE_FRONT, + FrontCounterClockwise: true.into(), + DepthBias: -7, + DepthBiasClamp: 0.5, + SlopeScaledDepthBias: -1.25, + DepthClipEnable: false.into(), + MultisampleEnable: true.into(), + AntialiasedLineEnable: true.into(), + ForcedSampleCount: 4, + ConservativeRaster: D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON, + }; + read_subobject(&mut state, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, blend); + read_subobject( + &mut state, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, + raster, + ); + assert_eq!(state.blend, blend); + assert_eq!(state.rasterizer, raster); + } + + #[test] + fn reads_both_depth_stencil_subobjects() { + let mut state = GraphicsState::default(); + let depth = D3D12_DEPTH_STENCIL_DESC { + DepthEnable: false.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, + DepthFunc: D3D12_COMPARISON_FUNC_GREATER, + StencilEnable: true.into(), + StencilReadMask: 0x31, + StencilWriteMask: 0xe7, + FrontFace: D3D12_DEPTH_STENCILOP_DESC { + StencilFailOp: D3D12_STENCIL_OP_ZERO, + StencilDepthFailOp: D3D12_STENCIL_OP_REPLACE, + StencilPassOp: D3D12_STENCIL_OP_INCR_SAT, + StencilFunc: D3D12_COMPARISON_FUNC_EQUAL, + }, + BackFace: D3D12_DEPTH_STENCILOP_DESC { + StencilFailOp: D3D12_STENCIL_OP_INVERT, + StencilDepthFailOp: D3D12_STENCIL_OP_DECR, + StencilPassOp: D3D12_STENCIL_OP_INCR, + StencilFunc: D3D12_COMPARISON_FUNC_NOT_EQUAL, + }, + }; + let depth1 = D3D12_DEPTH_STENCIL_DESC1 { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, + DepthFunc: D3D12_COMPARISON_FUNC_GREATER_EQUAL, + StencilEnable: false.into(), + StencilReadMask: 0x52, + StencilWriteMask: 0xa5, + FrontFace: depth.BackFace, + BackFace: depth.FrontFace, + DepthBoundsTestEnable: true.into(), + }; + read_subobject( + &mut state, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, + depth, + ); + assert_eq!(state.depth, depth); + read_subobject( + &mut state, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, + depth1, + ); + assert_eq!( + state.depth, + D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, + DepthFunc: D3D12_COMPARISON_FUNC_GREATER_EQUAL, + StencilEnable: false.into(), + StencilReadMask: 0x52, + StencilWriteMask: 0xa5, + FrontFace: depth.BackFace, + BackFace: depth.FrontFace, + }, + ); + } + + #[test] + fn translates_render_target_and_depth_formats() { + let mut state = GraphicsState::default(); + let mut formats = [DXGI_FORMAT_R8G8B8A8_UNORM; 8]; + formats[6] = DXGI_FORMAT(119); + formats[7] = DXGI_FORMAT(120); + read_subobject( + &mut state, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + D3D12_RT_FORMAT_ARRAY { + RTFormats: formats, + NumRenderTargets: 8, + }, + ); + formats[6] = DXGI_FORMAT_R24_UNORM_X8_TYPELESS; + formats[7] = DXGI_FORMAT_X24_TYPELESS_G8_UINT; + assert_eq!(state.targets.NumRenderTargets, 8); + assert_eq!(state.targets.RTFormats, formats); + + for (title, native) in [ + (118, DXGI_FORMAT_D24_UNORM_S8_UINT), + (40, DXGI_FORMAT_D32_FLOAT), + (0, DXGI_FORMAT_UNKNOWN), + ] { + read_subobject( + &mut state, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, + DXGI_FORMAT(title), + ); + assert_eq!(state.depth_format, native); + } + } + + #[test] + fn reads_scalar_and_sample_state_and_ignores_unknown_subobjects() { + let mut state = GraphicsState::default(); + let mut storage = [0u64; 2]; + let kind = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK.0 as u32; + let at = storage.as_mut_ptr().cast::().wrapping_add(1); + let mask = 0xfe01_1234u32; + // SAFETY: both u32 writes are inside the storage at the stream's + // type/data offsets. The read is of that whole subobject. + unsafe { + at.cast::().write_unaligned(kind); + at.add(4).cast::().write_unaligned(mask); + state.read(kind, at); + } + assert_eq!(state.sample_mask, mask); + + let strip_cut = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF; + let topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE; + let samples = DXGI_SAMPLE_DESC { + Count: 4, + Quality: 3, + }; + read_subobject( + &mut state, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, + strip_cut, + ); + read_subobject( + &mut state, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, + topology, + ); + read_subobject( + &mut state, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, + samples, + ); + assert_eq!(state.strip_cut, strip_cut); + assert_eq!(state.topology, topology); + assert_eq!(state.samples, samples); + + let before = state.describe(); + read_subobject(&mut state, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(99), 0u32); + assert_eq!(state.describe(), before); + } + + #[test] + fn shader_bytecode_is_copied_by_length() { + assert!(code_bytes(&D3D12_SHADER_BYTECODE::default()).is_empty()); + let copy = { + let bytes = [8u8, 0, 32, 91]; + let mut desc = D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: 0, + }; + assert!(code_bytes(&desc).is_empty()); + desc.BytecodeLength = 3; + code_bytes(&desc) + }; + assert_eq!(copy, [8, 0, 32]); + } +} From bcce91fa689cb817671872c2ed930208df3fc9df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:52:29 +0800 Subject: [PATCH 14/49] Shaders: fix GFX10 independent a16/g16 gradient dword packing in fields.rs with 21 tests --- crates/victory-shader/src/gfx10/fields.rs | 1155 ++++++++++++++++++++- 1 file changed, 1151 insertions(+), 4 deletions(-) diff --git a/crates/victory-shader/src/gfx10/fields.rs b/crates/victory-shader/src/gfx10/fields.rs index 7fe66b0..3cfe4b4 100644 --- a/crates/victory-shader/src/gfx10/fields.rs +++ b/crates/victory-shader/src/gfx10/fields.rs @@ -768,7 +768,9 @@ fn data_dwords(name: &str) -> u8 { } /// Address dwords of an image opcode: offset, bias, compare, derivatives, -/// coordinates, then LOD/clamp/mip, packed in pairs with `a16`. +/// coordinates, then LOD/clamp/mip. `a16` packs two coordinate components per +/// dword; the `_g16` form packs the gradients instead, and `a16` alone leaves +/// them at one dword each (RDNA2 supports both, so they are independent). fn image_addr_dwords(name: &str, dim: u8, a16: bool) -> u8 { // (coordinates, derivatives per direction) for 1D 2D 3D CUBE 1D_ARRAY // 2D_ARRAY 2D_MSAA 2D_MSAA_ARRAY. @@ -805,9 +807,1154 @@ fn image_addr_dwords(name: &str, dim: u8, a16: bool) -> u8 { } else if name.contains("_mip") { packed += 1; } - if a16 { - whole + 2 * derivs.div_ceil(2) + packed.div_ceil(2) + // Two gradients per direction, and the packed forms round each direction's + // pair up to a whole dword. + let gradients = if name.contains("_g16") { + 2 * derivs.div_ceil(2) } else { - whole + 2 * derivs + packed + 2 * derivs + }; + let coordinates = if a16 { packed.div_ceil(2) } else { packed }; + whole + gradients + coordinates +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gfx10::opcodes; + + fn table(encoding: Encoding) -> &'static [(u16, &'static str)] { + match encoding { + Encoding::Sop2 => opcodes::SOP2, + Encoding::Sopk => opcodes::SOPK, + Encoding::Sop1 => opcodes::SOP1, + Encoding::Sopc => opcodes::SOPC, + Encoding::Sopp => opcodes::SOPP, + Encoding::Smem => opcodes::SMEM, + Encoding::Vop2 => opcodes::VOP2, + Encoding::Vop1 => opcodes::VOP1, + Encoding::Vopc => opcodes::VOPC, + Encoding::Vop3 => opcodes::VOP3, + Encoding::Vop3p => opcodes::VOP3P, + Encoding::Vintrp => opcodes::VINTRP, + Encoding::Ds => opcodes::DS, + Encoding::Mubuf => opcodes::MUBUF, + Encoding::Mtbuf => opcodes::MTBUF, + Encoding::Mimg => opcodes::MIMG, + Encoding::Flat => opcodes::FLAT, + Encoding::Global => opcodes::GLOBAL, + Encoding::Scratch => opcodes::SCRATCH, + Encoding::Exp => &[], + } + } + + fn opcode(encoding: Encoding, name: &str) -> u16 { + table(encoding) + .iter() + .find(|(_, n)| *n == name) + .unwrap_or_else(|| panic!("{name} is not {encoding:?}")) + .0 + } + + fn inst_raw(encoding: Encoding, opcode: u16, words: &[u32]) -> Instruction { + Instruction { + offset: 0, + encoding, + opcode, + words: words.to_vec(), + } + } + + fn inst(encoding: Encoding, name: &str, words: &[u32]) -> Instruction { + inst_raw(encoding, opcode(encoding, name), words) + } + + /// VOP1/VOP2/VOPC dw0: source 0, then the opcode (VOP1) or src1 (VOP2) and + /// the destination. + fn vop(vdst: u32, field: u32, src0: u32) -> u32 { + src0 | field << 9 | vdst << 17 + } + + /// VOP3/VOP3P dw0: destination, then abs/neg_hi, opsel, clamp and opcode. + fn dw0(opcode: u16, vdst: u32, hi: u32, sel: u32, clamp: bool) -> u32 { + vdst | hi << 8 | sel << 11 | u32::from(clamp) << 15 | u32::from(opcode) << 16 + } + + /// VOP3/VOP3P dw1: three 9-bit sources, then omod/opsel_hi and neg. + fn dw1(src: [u32; 3], hi: u32, neg: u32) -> u32 { + src[0] | src[1] << 9 | src[2] << 18 | hi << 27 | neg << 29 + } + + fn sgpr(code: u8, dwords: u8) -> Operand { + Operand::Scalar { code, dwords } + } + + fn vgpr(reg: u8, dwords: u8) -> Operand { + Operand::Vector { reg, dwords } + } + + fn valu_raw(encoding: Encoding, opcode: u16, words: &[u32], wave64: bool) -> Valu { + let Fields::Valu(v) = inst_raw(encoding, opcode, words).fields(wave64) else { + panic!("not a VALU instruction"); + }; + v + } + + fn valu(encoding: Encoding, name: &str, words: &[u32], wave64: bool) -> Valu { + valu_raw(encoding, opcode(encoding, name), words, wave64) + } + + #[test] + fn source_codes() { + assert_eq!(source(0, 1, 0), sgpr(0, 1)); + assert_eq!(source(127, 4, 0), sgpr(127, 4)); + // Inline integers 0-64, then -1 to -16. + assert_eq!(source(128, 1, 0), Operand::Const(128)); + assert_eq!(source(192, 1, 0), Operand::Const(192)); + assert_eq!(source(193, 1, 0), Operand::Const(193)); + assert_eq!(source(208, 1, 0), Operand::Const(208)); + // Floats and the read-only special sources. + assert_eq!(source(240, 1, 0), Operand::Const(240)); + assert_eq!(source(254, 1, 0), Operand::Const(254)); + // 255 takes the literal that follows; 256 and up are VGPRs. + assert_eq!(source(255, 2, 0xDEAD_BEEF), Operand::Literal(0xDEAD_BEEF)); + assert_eq!(source(256, 1, 0), vgpr(0, 1)); + assert_eq!(source(511, 2, 0), vgpr(255, 2)); + } + + #[test] + fn scalar_alu_widths() { + assert_eq!(salu_dwords("s_mov_b32"), (1, 1, 1)); + assert_eq!(salu_dwords("s_mov_b64"), (2, 2, 2)); + assert_eq!(salu_dwords("s_and_b64"), (2, 2, 2)); + assert_eq!(salu_dwords("s_lshl_b64"), (2, 2, 1)); + assert_eq!(salu_dwords("s_bfm_b64"), (2, 1, 1)); + assert_eq!(salu_dwords("s_bitreplicate_b64_b32"), (2, 1, 1)); + assert_eq!(salu_dwords("s_bcnt0_i32_b64"), (1, 2, 2)); + assert_eq!(salu_dwords("s_flbit_i32_i64"), (1, 2, 2)); + assert_eq!(salu_dwords("s_cmp_eq_u64"), (2, 2, 2)); + assert_eq!(salu_dwords("s_sext_i32_i8"), (1, 1, 1)); + } + + #[test] + fn vector_alu_widths() { + assert_eq!(valu_dwords("v_add_f32"), (1, [1, 1, 1])); + assert_eq!(valu_dwords("v_add_f64"), (2, [2, 2, 2])); + assert_eq!(valu_dwords("v_lshlrev_b64"), (2, [1, 2, 2])); + assert_eq!(valu_dwords("v_ldexp_f64"), (2, [2, 1, 2])); + assert_eq!(valu_dwords("v_mad_u64_u32"), (2, [1, 1, 2])); + assert_eq!(valu_dwords("v_mqsad_u32_u8"), (4, [2, 1, 4])); + assert_eq!(valu_dwords("v_frexp_exp_i32_f64"), (1, [2, 2, 2])); + assert_eq!(valu_dwords("v_cvt_f32_f16"), (1, [1, 1, 1])); + assert_eq!(valu_dwords("v_cvt_f64_f32"), (2, [1, 1, 1])); + assert_eq!(valu_dwords("v_cvt_f32_f64"), (1, [2, 2, 2])); + assert_eq!(valu_dwords("v_cvt_pkrtz_f16_f32"), (1, [1, 1, 1])); + } + + #[test] + fn data_widths() { + assert_eq!(data_dwords("buffer_load_ubyte"), 1); + assert_eq!(data_dwords("buffer_load_dword"), 1); + assert_eq!(data_dwords("buffer_load_dwordx2"), 2); + assert_eq!(data_dwords("flat_load_dwordx3"), 3); + assert_eq!(data_dwords("flat_load_dwordx4"), 4); + assert_eq!(data_dwords("global_load_sbyte"), 1); + assert_eq!(data_dwords("global_load_b64"), 2); + assert_eq!(data_dwords("global_load_b96"), 3); + assert_eq!(data_dwords("global_load_b128"), 4); + assert_eq!(data_dwords("ds_write_b128"), 4); + // A compare-and-swap moves both the comparison and the replacement. + assert_eq!(data_dwords("buffer_atomic_cmpswap_x2"), 4); + assert_eq!(data_dwords("s_atomic_cmpswap_x2"), 4); + // Packed 16-bit textels halve the data. + assert_eq!(data_dwords("tbuffer_load_format_xy"), 2); + assert_eq!(data_dwords("tbuffer_load_format_d16_xyzw"), 2); + } + + #[test] + fn lds_pairs() { + assert!(ds_pair("ds_read2_b32")); + assert!(ds_pair("ds_write2_b64")); + assert!(ds_pair("ds_wrxchg2st64_rtn_b32")); + assert!(!ds_pair("ds_read_b64")); + assert!(!ds_pair("ds_write_b128")); + } + + #[test] + fn image_address_dwords() { + // (coordinates, derivatives per direction) for each dimension: + // 1D 2D 3D CUBE 1D_ARRAY 2D_ARRAY 2D_MSAA 2D_MSAA_ARRAY. + let cases: &[(&str, u8, bool, u8)] = &[ + ("image_sample", 1, false, 2), + ("image_sample", 1, true, 1), + ("image_sample", 0, true, 1), + ("image_sample", 2, true, 2), + // LOD, bias, compare and offsets are whole dwords; a16 leaves them + // alone and packs only the coordinates. + ("image_sample_l", 1, false, 3), + ("image_sample_l", 1, true, 2), + ("image_sample_l", 2, true, 2), + ("image_sample_b", 1, false, 3), + ("image_sample_b", 1, true, 2), + ("image_sample_c", 1, true, 2), + ("image_sample_c_l", 3, true, 3), + ("image_sample_o", 2, true, 3), + ("image_sample_lz", 1, false, 2), + ("image_gather4", 3, false, 3), + ("image_gather4", 3, true, 2), + ("image_gather4_l", 1, true, 2), + ("image_get_lod", 1, true, 1), + // Explicit derivatives: 2 * components, packed only by g16. + ("image_sample_d", 0, false, 3), + ("image_sample_d", 1, false, 6), + ("image_sample_d", 1, true, 5), + ("image_sample_d", 2, false, 9), + ("image_sample_d_g16", 1, false, 4), + ("image_sample_d_g16", 1, true, 3), + ("image_sample_d_g16", 2, false, 7), + ("image_sample_d_g16", 2, true, 6), + ("image_sample_c_d", 1, true, 6), + ("image_sample_c_d_g16", 1, false, 5), + ("image_sample_c_d_cl", 3, true, 7), + // Coarse derivatives and their compare form. + ("image_sample_cd", 1, true, 5), + ("image_sample_c_cd", 1, true, 6), + ("image_sample_cd_cl", 1, false, 7), + ("image_sample_cd_cl", 1, true, 6), + // Loads, stores, multi-sample and mip chains. + ("image_load", 1, false, 2), + ("image_load", 1, true, 1), + ("image_load_mip", 1, true, 2), + ("image_store_mip", 0, false, 2), + ("image_store_mip", 0, true, 1), + ("image_msaa_load", 6, false, 3), + ("image_msaa_load", 6, true, 2), + ("image_msaa_load", 7, true, 2), + ("image_atomic_add", 1, true, 1), + ("image_get_resinfo", 1, false, 1), + ("image_get_resinfo", 1, true, 1), + ("image_bvh_intersect_ray", 0, false, 11), + ("image_bvh_intersect_ray", 0, true, 8), + ("image_bvh64_intersect_ray", 0, false, 12), + ("image_bvh64_intersect_ray", 0, true, 9), + ]; + for &(name, dim, a16, expected) in cases { + assert_eq!( + image_addr_dwords(name, dim, a16), + expected, + "{name} dim {dim} a16 {a16}" + ); + } + } + + #[test] + fn scalar_instructions() { + // s_and_b64 s[2:3], exec, s[4:5] + let Fields::Sop { dst, src, imm } = + inst(Encoding::Sop2, "s_and_b64", &[(2 << 16) | (4 << 8) | 126]).fields(false) + else { + panic!("not SOP"); + }; + assert_eq!(dst, Some(sgpr(2, 2))); + assert_eq!(src, [sgpr(126, 2), sgpr(4, 2)]); + assert_eq!(imm, None); + + // s_add_u32 s0, s1, literal + let Fields::Sop { dst, src, .. } = + inst(Encoding::Sop2, "s_add_u32", &[255 << 8 | 1, 0xDEAD_BEEF]).fields(false) + else { + panic!("not SOP"); + }; + assert_eq!(dst, Some(sgpr(0, 1))); + assert_eq!(src, [sgpr(1, 1), Operand::Literal(0xDEAD_BEEF)]); + + // s_getpc_b64 writes the pair; s_setpc_b64 only reads one. + let Fields::Sop { dst, src, .. } = + inst(Encoding::Sop1, "s_getpc_b64", &[4 << 16]).fields(false) + else { + panic!("not SOP"); + }; + assert_eq!(dst, Some(sgpr(4, 2))); + assert!(src.is_empty()); + let Fields::Sop { dst, src, .. } = inst(Encoding::Sop1, "s_setpc_b64", &[4]).fields(false) + else { + panic!("not SOP"); + }; + assert_eq!(dst, None); + assert_eq!(src, [sgpr(4, 2)]); + + let Fields::Sop { dst, src, .. } = + inst(Encoding::Sopc, "s_cmp_eq_u64", &[3 << 8]).fields(false) + else { + panic!("not SOP"); + }; + assert!(dst.is_none()); + assert_eq!(src, [sgpr(0, 2), sgpr(3, 2)]); + + // SOPK: the destination field becomes a source for compares. + let Fields::Sop { dst, src, imm } = + inst(Encoding::Sopk, "s_cmpk_lg_u32", &[(5 << 16) | 0x1234]).fields(false) + else { + panic!("not SOP"); + }; + assert_eq!(dst, None); + assert_eq!(src, [sgpr(5, 1)]); + assert_eq!(imm, Some(0x1234)); + + let Fields::Sop { dst, imm, .. } = + inst(Encoding::Sopk, "s_call_b64", &[(8 << 16) | 4]).fields(false) + else { + panic!("not SOP"); + }; + assert_eq!(dst, Some(sgpr(8, 2))); + assert_eq!(imm, Some(4)); + + let Fields::Sop { dst, src, imm } = + inst(Encoding::Sopk, "s_setreg_imm32_b32", &[0x10, 1]).fields(false) + else { + panic!("not SOP"); + }; + assert_eq!(dst, None); + assert_eq!(src, [Operand::Literal(1)]); + assert_eq!(imm, Some(0x10)); + + let Fields::Sop { dst, .. } = + inst(Encoding::Sopk, "s_movk_i32", &[(6 << 16) | 0xFFFF]).fields(false) + else { + panic!("not SOP"); + }; + assert_eq!(dst, Some(sgpr(6, 1))); + + let op = u32::from(opcode(Encoding::Sopp, "s_waitcnt")); + let Fields::Sopp { imm } = + inst(Encoding::Sopp, "s_waitcnt", &[(op << 16) | 0xFC7F]).fields(false) + else { + panic!("not SOPP"); + }; + assert_eq!(imm, 0xFC7F); + } + + #[test] + fn scalar_memory() { + // s_load_dwordx2 s[4:5], s[8:9], s3 offset:-8 glc dlc + let w0 = 4 | (4 << 6) | (1 << 14) | (1 << 16); + let w1 = 0x1F_FFF8 | (3 << 25); + let Fields::Smem { + data, + base, + offset, + soffset, + cache, + } = inst(Encoding::Smem, "s_load_dwordx2", &[w0, w1]).fields(false) + else { + panic!("not SMEM"); + }; + assert_eq!(data, Some(sgpr(4, 2))); + assert_eq!(base, sgpr(8, 2)); + assert_eq!(offset, -8); + assert_eq!(soffset, sgpr(3, 1)); + assert_eq!( + cache, + Cache { + glc: true, + slc: false, + dlc: true + } + ); + + // The offset is 21 bits, signed. + let Fields::Smem { offset, .. } = + inst(Encoding::Smem, "s_load_dword", &[0, 0x0F_FFFF]).fields(false) + else { + panic!("not SMEM"); + }; + assert_eq!(offset, 1_048_575); + let Fields::Smem { offset, .. } = + inst(Encoding::Smem, "s_load_dword", &[0, 0x100_000]).fields(false) + else { + panic!("not SMEM"); + }; + assert_eq!(offset, -1_048_576); + + // Buffer descriptors are four SGPRs; memtime returns a pair. + let Fields::Smem { data, base, .. } = + inst(Encoding::Smem, "s_buffer_load_dwordx4", &[1 | (20 << 6), 0]).fields(false) + else { + panic!("not SMEM"); + }; + assert_eq!(data, Some(sgpr(20, 4))); + assert_eq!(base, sgpr(2, 4)); + let Fields::Smem { data, .. } = + inst(Encoding::Smem, "s_memtime", &[12 << 6, 0]).fields(false) + else { + panic!("not SMEM"); + }; + assert_eq!(data, Some(sgpr(12, 2))); + let Fields::Smem { data, .. } = inst(Encoding::Smem, "s_dcache_inv", &[0, 0]).fields(false) + else { + panic!("not SMEM"); + }; + assert_eq!(data, None); + } + + #[test] + fn vop1_sources_and_destinations() { + let v = valu(Encoding::Vop1, "v_mov_b32", &[vop(3, 0, 256 + 5)], false); + assert_eq!(v.dst, Some(vgpr(3, 1))); + assert_eq!(v.src, [vgpr(5, 1)]); + + let v = valu( + Encoding::Vop1, + "v_readfirstlane_b32", + &[vop(5, 0, 256 + 2)], + false, + ); + assert_eq!(v.dst, Some(sgpr(5, 1))); + assert_eq!(v.src, [vgpr(2, 1)]); + + // No operands: the console compiler keeps a shader hash in the fields. + let v = valu(Encoding::Vop1, "v_nop", &[0xFFFF_FFFF, 0xFFFF_FFFF], false); + assert_eq!(v, Valu::default()); + } + + #[test] + fn sdwa_fields() { + // dst_sel 3, dst_unused 1, clamp, omod 2, src0_sel 1, sext 3, neg 1, + // abs 2, src1_sel 4; src0 is an SGPR (S0), src1 a VGPR. + let ext = 0x2C99_AB08; + let v = valu(Encoding::Vop2, "v_add_f32", &[vop(1, 5, 0xF9), ext], false); + assert_eq!(v.dst, Some(vgpr(1, 1))); + assert_eq!(v.src, [sgpr(8, 1), vgpr(5, 1)]); + let sdwa = v.sdwa.expect("SDWA"); + assert_eq!((sdwa.dst_sel, sdwa.dst_unused), (3, 1)); + assert_eq!(sdwa.src_sel, [1, 4]); + assert_eq!(sdwa.sext, 3); + assert_eq!((v.neg, v.abs), (1, 2)); + assert!(v.clamp); + assert_eq!(v.omod, 2); + + // Bit 31 makes src1 an SGPR: the 8-bit field is the register. + let v = valu( + Encoding::Vop2, + "v_add_f32", + &[vop(1, 6, 0xF9), (1 << 31) | 5], + false, + ); + assert_eq!(v.src, [vgpr(5, 1), sgpr(6, 1)]); + } + + #[test] + fn dpp_permutations() { + let ext = 4 + | (0x101 << 8) + | (1 << 18) + | (1 << 19) + | (1 << 20) + | (1 << 21) + | (1 << 22) + | (1 << 23) + | (0xA << 24) + | (5 << 28); + let v = valu(Encoding::Vop2, "v_add_f32", &[vop(2, 6, 0xFA), ext], false); + assert_eq!(v.src, [vgpr(4, 1), vgpr(6, 1)]); + assert_eq!((v.neg, v.abs), (3, 3)); + assert_eq!( + v.dpp, + Some(Dpp::Row { + ctrl: 0x101, + row_mask: 5, + bank_mask: 0xA, + bound_ctrl: true, + fi: true, + }) + ); + + let ext = 4 | (0x12_3456 << 8); + let v = valu(Encoding::Vop2, "v_add_f32", &[vop(2, 6, 0xE9), ext], false); + assert_eq!( + v.dpp, + Some(Dpp::Lanes { + sel: 0x12_3456, + fi: false + }) + ); + let v = valu(Encoding::Vop2, "v_add_f32", &[vop(2, 6, 0xEA), ext], false); + assert_eq!( + v.dpp, + Some(Dpp::Lanes { + sel: 0x12_3456, + fi: true + }) + ); + } + + #[test] + fn vop2_implicit_operands() { + let v = valu(Encoding::Vop2, "v_cndmask_b32", &[vop(1, 2, 0)], false); + assert_eq!(v.src, [sgpr(0, 1), vgpr(2, 1), sgpr(106, 1)]); + assert_eq!(v.carry, None); + let v = valu(Encoding::Vop2, "v_cndmask_b32", &[vop(1, 2, 0)], true); + assert_eq!(v.src[2], sgpr(106, 2)); + + let v = valu( + Encoding::Vop2, + "v_add_co_ci_u32", + &[vop(3, 4, 256 + 1)], + true, + ); + assert_eq!(v.src, [vgpr(1, 1), vgpr(4, 1), sgpr(106, 2)]); + assert_eq!(v.carry, Some(sgpr(106, 2))); + + // v_madmk takes the literal second, v_madak third. + let v = valu( + Encoding::Vop2, + "v_madmk_f32", + &[vop(1, 3, 256 + 2), 0x3F00_0000], + false, + ); + assert_eq!( + v.src, + [vgpr(2, 1), Operand::Literal(0x3F00_0000), vgpr(3, 1)] + ); + let v = valu( + Encoding::Vop2, + "v_madak_f32", + &[vop(1, 3, 256 + 2), 0x3F00_0000], + false, + ); + assert_eq!( + v.src, + [vgpr(2, 1), vgpr(3, 1), Operand::Literal(0x3F00_0000)] + ); + } + + #[test] + fn compares_write_lane_masks() { + let words = [vop(0, 3, 240)]; + let v = valu(Encoding::Vopc, "v_cmp_gt_f32", &words, false); + assert_eq!(v.dst, Some(sgpr(106, 1))); + assert_eq!(v.src, [Operand::Const(240), vgpr(3, 1)]); + let v = valu(Encoding::Vopc, "v_cmp_gt_f32", &words, true); + assert_eq!(v.dst, Some(sgpr(106, 2))); + let v = valu(Encoding::Vopc, "v_cmpx_gt_f32", &words, false); + assert_eq!(v.dst, Some(sgpr(126, 1))); + } + + #[test] + fn vop3_modifiers() { + let op = opcode(Encoding::Vop3, "v_add_f64"); + let v = valu( + Encoding::Vop3, + "v_add_f64", + &[dw0(op, 2, 2, 0xA, true), dw1([0x101, 0x102, 0], 1, 3)], + false, + ); + assert_eq!(v.dst, Some(vgpr(2, 2))); + assert_eq!(v.src, [vgpr(1, 2), vgpr(2, 2)]); + assert_eq!((v.neg, v.abs, v.opsel), (3, 2, 0xA)); + assert!(v.clamp); + assert_eq!(v.omod, 1); + + // A VOP3-encoded compare writes an SGPR. + let op = opcode(Encoding::Vopc, "v_cmp_gt_f32"); + let v = valu_raw( + Encoding::Vop3, + op, + &[dw0(op, 6, 0, 0, false), dw1([0x101, 0x102, 0], 0, 0)], + true, + ); + assert_eq!(v.dst, Some(sgpr(6, 2))); + assert_eq!(v.src, [vgpr(1, 1), vgpr(2, 1)]); + + // VOP3B: bits 14:8 hold the carry-out SGPR instead of abs/opsel. + let op = opcode(Encoding::Vop3, "v_div_scale_f32"); + let w0 = 1 | (6 << 8) | (u32::from(op) << 16); + let v = valu( + Encoding::Vop3, + "v_div_scale_f32", + &[w0, dw1([0x101, 0x102, 0x103], 0, 0)], + true, + ); + assert_eq!(v.carry, Some(sgpr(6, 2))); + assert_eq!(v.src, [vgpr(1, 1), vgpr(2, 1), vgpr(3, 1)]); + assert_eq!((v.abs, v.opsel), (0, 0)); + + // The literal of a nine-bit source field is the third dword. + let v = valu( + Encoding::Vop3, + "v_div_scale_f32", + &[ + 1 | (u32::from(op) << 16), + dw1([0x101, 0x102, 255], 0, 0), + 0x4120_0000, + ], + false, + ); + assert_eq!(v.src[2], Operand::Literal(0x4120_0000)); + + // v_readlane writes an SGPR; v_interp reads an attribute in src0. + let op = opcode(Encoding::Vop3, "v_readlane_b32"); + let v = valu( + Encoding::Vop3, + "v_readlane_b32", + &[dw0(op, 5, 0, 0, false), dw1([0x102, 3, 0], 0, 0)], + false, + ); + assert_eq!(v.dst, Some(sgpr(5, 1))); + assert_eq!(v.src, [vgpr(2, 1), sgpr(3, 1)]); + + let op = opcode(Encoding::Vop3, "v_interp_p1ll_f16"); + let code = 5 | (2 << 6) | (1 << 8); + let v = valu( + Encoding::Vop3, + "v_interp_p1ll_f16", + &[dw0(op, 1, 0, 0, false), dw1([code, 0x104, 0], 0, 0)], + false, + ); + assert_eq!( + v.src, + [ + Operand::Attr { + index: 5, + chan: 2, + high: true + }, + vgpr(4, 1) + ] + ); + } + + #[test] + fn vop3p_halves() { + let op = opcode(Encoding::Vop3p, "v_pk_add_f16"); + let v = valu( + Encoding::Vop3p, + "v_pk_add_f16", + &[ + dw0(op, 1, 7, 5, false) | (1 << 14), + dw1([0x101, 0x102, 0], 2, 5), + ], + false, + ); + assert_eq!(v.src, [vgpr(1, 1), vgpr(2, 1)]); + assert_eq!((v.neg, v.neg_hi, v.opsel, v.opsel_hi), (5, 7, 5, 6)); + + let op = opcode(Encoding::Vop3p, "v_pk_fma_f16"); + let v = valu( + Encoding::Vop3p, + "v_pk_fma_f16", + &[dw0(op, 1, 0, 0, false), dw1([0x101, 0x102, 0x103], 0, 0)], + false, + ); + assert_eq!(v.src.len(), 3); + + let op = opcode(Encoding::Vop3p, "v_fma_mix_f32"); + let v = valu( + Encoding::Vop3p, + "v_fma_mix_f32", + &[dw0(op, 1, 0, 0, false), dw1([0x101, 0x102, 0x103], 0, 0)], + false, + ); + assert_eq!(v.src.len(), 3); + } + + #[test] + fn interpolation() { + let op = u32::from(opcode(Encoding::Vintrp, "v_interp_p1_f32")); + let w0 = (0x32 << 26) | (op << 16) | (2 << 18) | (5 << 10) | (1 << 8) | 4; + let Fields::Vintrp { dst, src, attr } = + inst(Encoding::Vintrp, "v_interp_p1_f32", &[w0]).fields(false) + else { + panic!("not VINTRP"); + }; + assert_eq!(dst, vgpr(2, 1)); + assert_eq!(src, vgpr(4, 1)); + assert_eq!( + attr, + Operand::Attr { + index: 5, + chan: 1, + high: false + } + ); + + // The destination is the full 8-bit field at 25:18. + let w0 = (0x32 << 26) | (op << 16) | (1 << 25) | (2 << 18); + let Fields::Vintrp { dst, .. } = + inst(Encoding::Vintrp, "v_interp_p1_f32", &[w0]).fields(false) + else { + panic!("not VINTRP"); + }; + assert_eq!(dst, vgpr(130, 1)); + + // v_interp_mov's second field is a parameter, not a VGPR. + let Fields::Vintrp { src, .. } = inst( + Encoding::Vintrp, + "v_interp_mov_f32", + &[(0x32 << 26) | (1 << 8) | 1], + ) + .fields(false) else { + panic!("not VINTRP"); + }; + assert_eq!(src, Operand::Const(1)); + } + + #[test] + fn lds_operands() { + // ds_read2_b32 v[6:7], v1 offset0:2 offset1:3 gds + let Fields::Ds { + dst, + addr, + data, + offset0, + offset1, + gds, + } = inst( + Encoding::Ds, + "ds_read2_b32", + &[2 | (3 << 8) | (1 << 17), (6 << 24) | 1], + ) + .fields(false) + else { + panic!("not DS"); + }; + assert_eq!(dst, Some(vgpr(6, 2))); + assert_eq!(addr, Some(vgpr(1, 1))); + assert!(data.is_empty()); + assert_eq!((offset0, offset1, gds), (2, 3, true)); + + // A 128-bit store is one four-dword range, not four fields. + let Fields::Ds { dst, data, .. } = + inst(Encoding::Ds, "ds_write_b128", &[0, (2 << 8) | 1]).fields(false) + else { + panic!("not DS"); + }; + assert!(dst.is_none()); + assert_eq!(data, [vgpr(2, 4)]); + + // ds_append returns a value but takes no address. + let Fields::Ds { + dst, addr, data, .. + } = inst(Encoding::Ds, "ds_append", &[0, 3 << 24]).fields(false) + else { + panic!("not DS"); + }; + assert_eq!(dst, Some(vgpr(3, 1))); + assert!(addr.is_none()); + assert!(data.is_empty()); + + // GWS operations have neither an address nor data. + let Fields::Ds { + dst, addr, data, .. + } = inst(Encoding::Ds, "ds_gws_sema_v", &[0, 0]).fields(false) + else { + panic!("not DS"); + }; + assert!(dst.is_none() && addr.is_none() && data.is_empty()); + + let Fields::Ds { + dst, addr, data, .. + } = inst( + Encoding::Ds, + "ds_add_rtn_u32", + &[0, (4 << 24) | (6 << 8) | 5], + ) + .fields(false) + else { + panic!("not DS"); + }; + assert_eq!(dst, Some(vgpr(4, 1))); + assert_eq!(addr, Some(vgpr(5, 1))); + assert_eq!(data, [vgpr(6, 1)]); + + // Compare-and-swap and the two-address forms take both data fields. + let Fields::Ds { data, .. } = + inst(Encoding::Ds, "ds_cmpst_b32", &[0, (3 << 16) | (2 << 8) | 1]).fields(false) + else { + panic!("not DS"); + }; + assert_eq!(data, [vgpr(2, 1), vgpr(3, 1)]); + let Fields::Ds { dst, data, .. } = inst( + Encoding::Ds, + "ds_write2_b64", + &[0, (3 << 16) | (2 << 8) | 1], + ) + .fields(false) else { + panic!("not DS"); + }; + assert!(dst.is_none()); + assert_eq!(data, [vgpr(2, 2), vgpr(3, 2)]); + } + + #[test] + fn buffer_operands() { + let Fields::Buffer { + data, + addr, + rsrc, + soffset, + offset, + offen, + idxen, + format, + lds, + tfe, + cache, + } = inst( + Encoding::Mubuf, + "buffer_load_dwordx4", + &[0xE034_7010, 0x0102_0402], + ) + .fields(false) + else { + panic!("not a buffer instruction"); + }; + assert_eq!(data, Some(vgpr(4, 4))); + assert_eq!(addr, vgpr(2, 2)); + assert_eq!(rsrc, sgpr(8, 4)); + assert_eq!(soffset, sgpr(1, 1)); + assert_eq!(offset, 16); + assert!(offen && idxen && !lds && !tfe); + assert_eq!(format, None); + assert_eq!( + cache, + Cache { + glc: true, + slc: false, + dlc: false + } + ); + + // TFE returns one more dword; lds loads into shared memory. + let Fields::Buffer { data, tfe, .. } = inst( + Encoding::Mubuf, + "buffer_load_dword", + &[0, (1 << 23) | (4 << 8) | 2], + ) + .fields(false) else { + panic!("not a buffer instruction"); + }; + assert!(tfe); + assert_eq!(data, Some(vgpr(4, 2))); + let Fields::Buffer { lds, .. } = + inst(Encoding::Mubuf, "buffer_load_dword", &[1 << 16, 0]).fields(false) + else { + panic!("not a buffer instruction"); + }; + assert!(lds); + + // MTBUF's unified format; format_d16 halves 3d data. + let Fields::Buffer { + data, + addr, + rsrc, + soffset, + offset, + format, + lds, + .. + } = inst( + Encoding::Mtbuf, + "tbuffer_load_format_d16_xyzw", + &[ + (17 << 19) | 16 | (1 << 12) | (1 << 13), + (3 << 24) | (4 << 8) | 1 | (2 << 16), + ], + ) + .fields(false) + else { + panic!("not a buffer instruction"); + }; + assert_eq!(format, Some(17)); + assert_eq!(offset, 16); + assert!(!lds); + assert_eq!(data, Some(vgpr(4, 2))); + assert_eq!(addr, vgpr(1, 2)); + assert_eq!(rsrc, sgpr(8, 4)); + assert_eq!(soffset, sgpr(3, 1)); + + // Stores have no destination; the stored dwords are the data. + let Fields::Buffer { data, .. } = + inst(Encoding::Mubuf, "buffer_store_dwordx2", &[0, (4 << 8) | 1]).fields(false) + else { + panic!("not a buffer instruction"); + }; + assert_eq!(data, Some(vgpr(4, 2))); + } + + #[test] + fn image_operands() { + // image_sample_lz v[8:9], [v1,v5], s[16:23], s[4:7] dmask:0x7 d16: + // three channels pack into two dwords, and the NSA form lists the + // addresses one VGPR each. + let Fields::Image { + data, + addr, + rsrc, + sampler, + dmask, + dim, + unorm, + r128, + a16, + d16, + tfe, + lwe, + cache, + } = inst( + Encoding::Mimg, + "image_sample_lz", + &[0xF09C_070A, 0x8024_0801, 0x0000_0005], + ) + .fields(false) + else { + panic!("not an image instruction"); + }; + assert_eq!(data, vgpr(8, 2)); + assert_eq!(addr, [vgpr(1, 1), vgpr(5, 1)]); + assert_eq!(rsrc, sgpr(16, 8)); + assert_eq!(sampler, Some(sgpr(4, 4))); + assert_eq!((dmask, dim), (7, 1)); + assert!(!unorm && !r128 && !a16 && d16 && !tfe && !lwe); + assert_eq!(cache, Cache::default()); + + // Most flags at once: dim 3D has three coordinates and six gradients; + // the coordinates pack with a16 while the gradients stay whole dwords. + let w0 = 0xF000_0000 + | 0x0F00 + | 0x10 + | (1 << 25) + | (1 << 16) + | (1 << 15) + | (1 << 13) + | (1 << 12) + | (1 << 7); + let w1 = 0xC062_0401; + let Fields::Image { + data, + addr, + rsrc, + sampler, + dim, + unorm, + r128, + a16, + d16, + tfe, + lwe, + cache, + .. + } = inst(Encoding::Mimg, "image_sample_d", &[w0, w1]).fields(false) + else { + panic!("not an image instruction"); + }; + assert_eq!(dim, 2); + assert!(unorm && r128 && a16 && d16 && tfe && !lwe); + assert_eq!( + cache, + Cache { + glc: true, + slc: true, + dlc: true + } + ); + assert_eq!(rsrc, sgpr(8, 4)); + assert_eq!(sampler, Some(sgpr(12, 4))); + assert_eq!(data, vgpr(4, 3)); + assert_eq!(addr, [vgpr(1, 8)]); + + // lwe appends a dword of its own. + let w0 = 0xF000_0000 | 0x10 | (1 << 8) | (1 << 17); + let Fields::Image { data, lwe, .. } = + inst(Encoding::Mimg, "image_load", &[w0, 0x0002_0401]).fields(false) + else { + panic!("not an image instruction"); + }; + assert!(lwe); + assert_eq!(data, vgpr(4, 2)); + + // The NSA address dwords carry four VGPRs each. + let w0 = 0xF000_0000 | 0x6 | 0x10 | 0x0F00; + let Fields::Image { addr, .. } = inst( + Encoding::Mimg, + "image_sample_d", + &[w0, 0x0002_0401, 0x0403_0201, 0x0807_0605, 0], + ) + .fields(false) else { + panic!("not an image instruction"); + }; + assert_eq!( + addr, + [ + vgpr(1, 1), + vgpr(1, 1), + vgpr(2, 1), + vgpr(3, 1), + vgpr(4, 1), + vgpr(5, 1), + vgpr(6, 1), + vgpr(7, 1), + vgpr(8, 1) + ] + ); + + // Loads take no sampler. + let Fields::Image { sampler, .. } = + inst(Encoding::Mimg, "image_load", &[0, 0]).fields(false) + else { + panic!("not an image instruction"); + }; + assert_eq!(sampler, None); + } + + #[test] + fn flat_global_and_scratch() { + // flat_load_dwordx3 v[4:6], v[2:3] inst_offset:2047, every cache flag + let w0 = 0xDC00_0000 | 2047 | (1 << 12) | (1 << 13) | (1 << 16) | (1 << 17); + let Fields::Flat { + dst, + addr, + data, + offset, + lds, + cache, + .. + } = inst(Encoding::Flat, "flat_load_dwordx3", &[w0, 0x0400_0402]).fields(false) + else { + panic!("not FLAT"); + }; + assert_eq!(dst, Some(vgpr(4, 3))); + assert_eq!(addr, Some(vgpr(2, 2))); + assert_eq!(data, None); + assert_eq!(offset, 2047); + assert!(lds); + assert_eq!( + cache, + Cache { + glc: true, + slc: true, + dlc: true + } + ); + + // GLOBAL's offset is 12 bits, signed. + let Fields::Flat { offset, .. } = inst( + Encoding::Global, + "global_load_dwordx2", + &[0xDC00_0FFF, (4 << 8) | 2], + ) + .fields(false) else { + panic!("not GLOBAL"); + }; + assert_eq!(offset, -1); + let Fields::Flat { offset, .. } = + inst(Encoding::Global, "global_load_dwordx2", &[0xDC00_07FF, 0]).fields(false) + else { + panic!("not GLOBAL"); + }; + assert_eq!(offset, 2047); + + // A null saddr adds a VGPR to the address; scratch always has 32 bits. + let Fields::Flat { + addr, saddr, data, .. + } = inst( + Encoding::Global, + "global_load_dwordx2", + &[0, (125 << 16) | (4 << 8) | 2], + ) + .fields(false) + else { + panic!("not GLOBAL"); + }; + assert_eq!(addr, Some(vgpr(2, 2))); + assert_eq!(saddr, Some(sgpr(125, 2))); + assert_eq!(data, None); + + let Fields::Flat { addr, saddr, .. } = inst( + Encoding::Scratch, + "scratch_load_dword", + &[0, (125 << 16) | (4 << 8) | 1], + ) + .fields(false) else { + panic!("not SCRATCH"); + }; + assert_eq!(addr, Some(vgpr(1, 1))); + assert_eq!(saddr, Some(sgpr(125, 1))); + let Fields::Flat { addr, saddr, .. } = inst( + Encoding::Scratch, + "scratch_load_dword", + &[0, (3 << 16) | (4 << 8) | 1], + ) + .fields(false) else { + panic!("not SCRATCH"); + }; + assert_eq!(addr, None); + assert_eq!(saddr, Some(sgpr(3, 1))); + + // A store has no destination; a returning atomic keeps the old value. + let Fields::Flat { dst, data, .. } = + inst(Encoding::Global, "global_store_dword", &[0, (4 << 8) | 2]).fields(false) + else { + panic!("not GLOBAL"); + }; + assert!(dst.is_none()); + assert_eq!(data, Some(vgpr(4, 1))); + let Fields::Flat { dst, data, .. } = inst( + Encoding::Global, + "global_atomic_cmpswap_x2", + &[1 << 16, (6 << 24) | (4 << 8) | 1], + ) + .fields(false) else { + panic!("not GLOBAL"); + }; + assert_eq!(dst, Some(vgpr(6, 2))); + assert_eq!(data, Some(vgpr(4, 4))); + } + + #[test] + fn exports() { + let Fields::Exp { + target, + src, + compr, + done, + vm, + } = inst_raw(Encoding::Exp, 0, &[0xF800_1C0F, 0x0000_0302]).fields(false) + else { + panic!("not EXP"); + }; + assert_eq!(target, 0); + assert_eq!( + src, + [ + Some(vgpr(2, 1)), + Some(vgpr(2, 1)), + Some(vgpr(3, 1)), + Some(vgpr(3, 1)) + ] + ); + assert!(compr && done && vm); + + let Fields::Exp { + target, + src, + compr, + done, + vm, + } = inst_raw( + Encoding::Exp, + 0, + &[ + 0xF800_0000 | 0b0101 | (12 << 4), + 4 | (5 << 8) | (6 << 16) | (7 << 24), + ], + ) + .fields(false) + else { + panic!("not EXP"); + }; + assert_eq!(target, 12); + assert_eq!(src, [Some(vgpr(4, 1)), None, Some(vgpr(6, 1)), None]); + assert!(!compr && !done && !vm); } } From 420189a8ef87db09b78a2f912f9a228d5f854859 Mon Sep 17 00:00:00 2001 From: chiragmadhuprasad Date: Tue, 24 Nov 2026 21:49:56 +0530 Subject: [PATCH 15/49] Improve shadow buffer allocation diagnostics --- crates/victory-gpu/src/shadow.rs | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index c7b390b..e8de19f 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -155,7 +155,8 @@ impl Shadow { .push((address, address + len)); let (from, to) = self.inside(address, len); // SAFETY: inside the mapping. - let host = |a: usize, b: usize| unsafe { std::slice::from_raw_parts(self.data.add(a), b - a) }; + let host = + |a: usize, b: usize| unsafe { std::slice::from_raw_parts(self.data.add(a), b - a) }; let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); let (start, end) = match &*before { Some((at, bytes)) => ((*at).min(from), (at + bytes.len()).max(to)), @@ -419,9 +420,8 @@ pub(crate) fn find(address: u64, len: u64) -> Option> { let gpu = unsafe { buffer.GetGPUVirtualAddress() }; if len >= 16 << 20 { tracing::info!( - start = format_args!("{:#x}", key.0), - len, - "large buffer copied to the host" + "large buffer copied to the host: start={:#x}, len={len}", + key.0 ); } else { tracing::debug!( @@ -456,11 +456,7 @@ fn loose(address: u64, end: u64) -> Option> { 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" - ); + tracing::debug!("loose memory copied to the host: start={start:#x}, len={len}"); let shadow = Arc::new(Shadow::new(buffer, data, gpu, start, len)); map.insert((start, len), shadow.clone()); Some(shadow) From 643fc6dfecffbd06de7313897b7d4bc4ffef6564 Mon Sep 17 00:00:00 2001 From: divyeshganta Date: Tue, 24 Nov 2026 21:53:04 +0530 Subject: [PATCH 16/49] HLE: avoid misaligned f32 output slice in XApu --- crates/victory-hle/src/modules/apu.rs | 176 ++++++++++++++++++++++++-- 1 file changed, 165 insertions(+), 11 deletions(-) diff --git a/crates/victory-hle/src/modules/apu.rs b/crates/victory-hle/src/modules/apu.rs index 0668f0d..9027da0 100644 --- a/crates/victory-hle/src/modules/apu.rs +++ b/crates/victory-hle/src/modules/apu.rs @@ -181,7 +181,13 @@ pub extern "system" fn XApuConnect( } 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()) } + let event = unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) }; + if event.is_null() { + // SAFETY: allocated above with `layout`. + unsafe { std::alloc::dealloc(memory, layout) }; + return E_OUTOFMEMORY; + } + event } else { std::ptr::null_mut() }; @@ -271,13 +277,15 @@ pub extern "system" fn XApuEnqueueCommand( tracing::debug!(stream, channels, "Opus stream activated"); result.error = if decoder.is_some() { ALREADY_ACTIVE + } else if !(1..=2).contains(&channels) { + E_INVALIDARG } else { match OpusDecoder::new(48_000, channels as usize) { - Ok(d) if (1..=2).contains(&channels) => { + Ok(d) => { *decoder = Some(d); S_OK } - _ => E_INVALIDARG, + Err(_) => E_INVALIDARG, } }; } @@ -340,17 +348,27 @@ fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: & .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::(), 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]); + let bytes = frames * channels * 4; + if bytes > 0 { + // SAFETY: `output` is non-null and holds at least `bytes <= output_length` bytes; + // writing raw bytes avoids requiring 4-byte alignment on the title's `*mut u8`. + let out = unsafe { std::slice::from_raw_parts_mut(output, bytes) }; + if options & DEINTERLEAVED_OUTPUT != 0 && channels == 2 { + let (left, right) = out.split_at_mut(frames * 4); + let (left, _) = left.as_chunks_mut::<4>(); + let (right, _) = right.as_chunks_mut::<4>(); + for (i, frame) in kept.as_chunks::<2>().0.iter().enumerate() { + left[i] = frame[0].to_le_bytes(); + right[i] = frame[1].to_le_bytes(); + } + } else { + for (dst, &sample) in out.as_chunks_mut::<4>().0.iter_mut().zip(kept) { + *dst = sample.to_le_bytes(); + } } - } else { - out.copy_from_slice(kept); } result.frames = frames as u32; - result.output_length = (frames * channels * 4) as u32; + result.output_length = bytes as u32; } pub extern "system" fn XApuDequeueResult(handle: *mut Connection, out: *mut ApuResult) -> HRESULT { @@ -521,4 +539,140 @@ mod tests { assert_eq!(error, INVALID_STREAM); assert_eq!(XApuDisconnect(handle), S_OK); } + + #[test] + fn decodes_into_unaligned_output_interleaved_and_deinterleaved() { + let tone: Vec = (0..960 * 2) + .map(|i| { + let phase = (i / 2) as f32 * std::f32::consts::TAU / 48_000.0; + if i % 2 == 0 { + (phase * 440.0).sin() * 0.5 + } else { + (phase * 880.0).sin() * 0.25 + } + }) + .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(); + + for (options, deinterleaved) in [(0u32, false), (DEINTERLEAVED_OUTPUT, true)] { + let input = ConnectInput { + process: DECODE_OPUS, + streams: 4, + commands_per_stream: 4, + memory: 0x4_0000, + frames_per_output: 0, + options, + }; + 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::(); + + // Invalid channel counts fail cleanly without activating the stream. + for bad_channels in [0u32, 3, u32::MAX] { + let bad = Activate { + id: id(ACTIVATE, 0), + channels: bad_channels, + 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 bad).cast(), std::ptr::null_mut()), + S_OK + ); + let mut res = std::mem::MaybeUninit::::zeroed(); + assert_eq!(XApuDequeueResult(handle, res.as_mut_ptr()), S_OK); + // SAFETY: written by `XApuDequeueResult`. + let err = unsafe { res.assume_init() }.error; + assert_eq!(err, E_INVALIDARG, "channels={bad_channels}"); + } + + // Activate two identical stereo decoders so aligned and unaligned outputs match bit-for-bit. + for stream in [0u32, 1] { + let activate = Activate { + id: id(ACTIVATE, stream), + 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 + ); + let mut res = std::mem::MaybeUninit::::zeroed(); + assert_eq!(XApuDequeueResult(handle, res.as_mut_ptr()), S_OK); + // SAFETY: written by `XApuDequeueResult`. + let err = unsafe { res.assume_init() }.error; + assert_eq!(err, S_OK); + } + + // SAFETY: inside the connection memory. + unsafe { std::ptr::copy_nonoverlapping(packet.as_ptr(), base, n) }; + let aligned_out = base.wrapping_add(0x10000); + let unaligned_out = base.wrapping_add(0x20001); // 1 mod 4: misaligned for f32 + + for (stream, out_ptr, frame_count) in [ + (0u32, aligned_out, 960u32), + (1u32, unaligned_out, 960u32), + (1u32, base.wrapping_add(0x30003), 0u32), // zero frames at misaligned ptr + ] { + let proc_cmd = Process { + id: id(PROCESS, stream), + pitch_ramp: 0.0, + target_pitch: 1.0, + first_frame: 0, + frame_count, + input_length: n as u32, + input: base, + output_length: 960 * 8, + output: out_ptr, + }; + assert_eq!( + XApuEnqueueCommand(handle, (&raw const proc_cmd).cast(), std::ptr::null_mut()), + S_OK + ); + let mut res = std::mem::MaybeUninit::::zeroed(); + assert_eq!(XApuDequeueResult(handle, res.as_mut_ptr()), S_OK); + // SAFETY: written by `XApuDequeueResult`. + let decoded = unsafe { res.assume_init() }; + let (err, frames, len) = (decoded.error, decoded.frames, decoded.output_length); + assert_eq!((err, frames, len), (S_OK, frame_count, frame_count * 8)); + } + + // SAFETY: both output regions are inside connection memory and hold 960 * 8 bytes. + let (aligned_bytes, unaligned_bytes) = unsafe { + ( + std::slice::from_raw_parts(aligned_out, 960 * 8), + std::slice::from_raw_parts(unaligned_out, 960 * 8), + ) + }; + assert_eq!( + unaligned_bytes, aligned_bytes, + "unaligned output must match aligned output (deinterleaved={deinterleaved})" + ); + let samples: Vec = unaligned_bytes + .as_chunks::<4>() + .0 + .iter() + .map(|c| f32::from_le_bytes(*c)) + .collect(); + let energy: f32 = samples.iter().map(|s| s * s).sum::() / samples.len() as f32; + assert!( + energy > 0.01, + "expected decoded tone (deinterleaved={deinterleaved}), energy={energy}" + ); + assert_eq!(XApuDisconnect(handle), S_OK); + } + } } From a2e532d155a27c166bd1a6f78431958a4052bb44 Mon Sep 17 00:00:00 2001 From: neonbyte1 <186292855+neonbyte1@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:48:31 +0100 Subject: [PATCH 17/49] GPU: the copies timing no longer counts the flush before a title copy twice --- crates/victory-gpu/src/host.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 6672c1e..be69e15 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1168,7 +1168,7 @@ impl HostList { #[cfg(feature = "diagnostics")] use crate::copystat::{C, add}; for step in &self.deferred().copies { - let started = std::time::Instant::now(); + let mut started = std::time::Instant::now(); let copied = match step { &Step::Copy(dst, src, len) => { #[cfg(feature = "diagnostics")] @@ -1177,6 +1177,8 @@ impl HostList { add(C::CopyBytes, len as u64); } batch.title_written(); + // The flush counted its own time; the copy starts here. + started = std::time::Instant::now(); copy_mapped(dst as *mut u8, src as *const u8, len, true); len } @@ -1201,6 +1203,10 @@ impl HostList { Step::Run(work) | Step::Host(work) => { if matches!(step, Step::Run(_)) { batch.title_written(); + #[cfg(feature = "diagnostics")] + { + started = std::time::Instant::now(); + } } work(); #[cfg(feature = "diagnostics")] From 13b1beb0b99e83b717b824165624bff9afc9823d Mon Sep 17 00:00:00 2001 From: chiragmadhuprasad Date: Tue, 24 Nov 2026 21:58:13 +0530 Subject: [PATCH 18/49] Document experimental compatibility findings --- docs/compatibility.md | 99 ++++++++++++++++++++++++++++++++++ docs/debugging.md | 123 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 222 insertions(+) create mode 100644 docs/compatibility.md create mode 100644 docs/debugging.md diff --git a/docs/compatibility.md b/docs/compatibility.md new file mode 100644 index 0000000..eeccaed --- /dev/null +++ b/docs/compatibility.md @@ -0,0 +1,99 @@ +# Compatibility investigation: Grand Theft Auto VI + +**Status:** Experimental; not confirmed playable +**Last updated:** 2026-11-24 + +This document records an independent compatibility investigation using +VIctory. It is a development report, not an official compatibility claim. + +## Test environment + +| Component | Configuration | +|---|---| +| CPU | Intel Core i7-8700K | +| GPU | AMD Radeon RX 5600 XT, 6 GB | +| RAM | 16 GB DDR4 | +| Operating system | Windows | +| Graphics API | Direct3D 12 | +| GPU architecture | AMD RDNA 1 (Navi 10) | + +## Test target + +- Title executable: `game_scarlett_master.exe` +- Game files are supplied locally by the tester. +- No proprietary game assets or executable contents are included in this repository. + +## Shader translation results + +A translation scan reported: + +| Metric | Result | +|---|---:| +| Containers scanned | 26,599 | +| Programs translated | 26,148 / 26,148 | +| Vertex/pixel DXIL emitted | 12,250 / 14,039 | +| Compute DXIL emitted | 1,441 / 2,582 | +| Mesh DXIL emitted | 8,278 / 8,713 | +| DXIL validated | 21,783 / 21,969 | + +Approximately 99.15% of emitted DXIL programs passed validation. + +These figures describe translation and validation only. They do not +demonstrate that the title can render or run correctly. + +Pipeline investigation also encountered failures involving mesh pipelines. +Host mesh-shader support and pipeline creation remain areas for further +investigation. + +## Runtime observations + +The title progresses into GPU initialization and resource activity but +does not reach confirmed playable gameplay. + +Observed issues include: + +- Direct3D 12 `E_OUTOFMEMORY` errors (`0x8007000E`). +- Failed allocation of a 94,371,840-byte shared buffer (90 MiB). +- Command-list submission or closing failure following allocation errors. +- D3D12 resource-state validation warnings involving + `UNORDERED_ACCESS` and `VERTEX_AND_CONSTANT_BUFFER`. + +The shared buffer uses a CPU-visible, system-memory allocation path. +Therefore, the allocation failure alone does not establish that dedicated +GPU VRAM was exhausted. + +The resource-state warnings occurred shortly before an allocation failure +in one captured run. Their causal relationship has not been established. + +## Current assessment + +**Confirmed:** +- The workspace builds successfully in release mode with GPU and core + diagnostics enabled. +- Shader translation completes for the reported program counts. +- Most emitted DXIL passes validation. +- Runtime resource allocation failures occur. + +**Not yet established:** +- The root cause of the shared-buffer allocation failure. +- Whether resource-state mismatches contribute to the failure. +- Whether the observed allocation behaviour is a memory leak, + fragmentation, budget exhaustion, or another issue. +- Whether the title can reach stable gameplay on this configuration. + +## Next investigation areas + +1. Measure shared-buffer allocations and lifetimes. +2. Investigate the lifetime and growth of loose shadow-memory allocations. +3. Trace D3D12 resource-state transitions around the first failure. +4. Determine whether allocation failures are reproducible. +5. Re-test after any targeted fixes. + +## Reporting and reproducibility + +Results depend on the exact VIctory commit, game build, graphics driver, +configuration and test conditions. + +Diagnostic logs and translation outputs are retained separately from +this repository. They may contain machine-specific information and +should be reviewed before sharing. diff --git a/docs/debugging.md b/docs/debugging.md new file mode 100644 index 0000000..d984b43 --- /dev/null +++ b/docs/debugging.md @@ -0,0 +1,123 @@ +# D3D12 debugging notes + +This document records diagnostic procedures and observations from the +experimental VIctory compatibility investigation. + +## Diagnostic build + +Build the workspace with GPU and core diagnostics enabled: + +```powershell +cargo build --release --workspace --features victory-gpu/diagnostics,victory-core/diagnostics +``` + +## Runtime diagnostic capture + +Set the diagnostic environment variables: + +```powershell +$env:VICTORY_D3D12_DEBUG = "1" +$env:VICTORY_D3D12_DRED = "1" +$env:VICTORY_GPU_TIMING = "1" +$env:VICTORY_LOG = "victory_gpu::shadow=debug,info" +``` + +Run the title using locally supplied game files: + +```powershell +.\target\release\victory.exe run "PATH_TO_TITLE_EXECUTABLE" --execute *> .\victory-debug.log +``` + +Replace `PATH_TO_TITLE_EXECUTABLE` with the local executable path. + +These settings enable the D3D12 debug layer, DRED diagnostics, GPU timing +and shadow-memory logging. Diagnostic availability depends on the build +features and host graphics driver. + +## Observed allocation failure + +One captured run reported: + +```text +E_OUTOFMEMORY (0x8007000E) +no shared buffer +size=94371840 +``` + +The failed allocation was 94,371,840 bytes (90 MiB). + +The shared-buffer allocation path uses a CPU-visible D3D12 custom heap +with WRITE_BACK CPU page properties and the L0 memory pool. + +This is a system-memory allocation path. The error does not, by itself, +prove that dedicated GPU VRAM was exhausted. + +## Resource-state validation + +The D3D12 debug layer also reported resource-state mismatches involving: + +- `UNORDERED_ACCESS` +- `VERTEX_AND_CONSTANT_BUFFER` + +These warnings appeared shortly before an allocation failure in one +captured run. Their relationship to the allocation failure is unknown. + +Resource transitions and command-list state tracking require further +investigation. + +## Shadow-memory observations + +The shadow-memory implementation maintains host-visible copies of title +memory. + +Relevant investigation areas include: + +- Registered title buffers and their shadow allocations. +- Loose shadow-memory allocations and cache lifetime. +- Allocation sizes and alignment. +- Resource references retained by command lists. +- Allocation reuse and release behaviour. + +A previous log contained eight distinct registered buffers of at least +16 MiB, totalling approximately 446.92 MiB. + +A separate run recorded 55 unique loose-memory allocation keys totalling +approximately 252 MiB. These figures came from different runs and must +not be combined into one memory total. + +The loose-memory cache currently warrants investigation because its +entries are retained in a map. This is a hypothesis for possible +allocation growth, not a confirmed cause of the runtime failure. + +## Interpreting results + +Do not assume that `E_OUTOFMEMORY` means physical VRAM exhaustion. + +Investigate the following independently: + +1. System-memory availability at the time of failure. +2. D3D12 resource allocation sizes and heap types. +3. Resource lifetime and reference retention. +4. GPU resource-state validation messages. +5. Command-list submission and synchronization. +6. Reproducibility across repeated runs. + +A diagnostic warning occurring before an allocation failure does not +establish causation. + +## Reporting a reproducible issue + +When reporting a failure, include: + +- VIctory commit hash. +- CPU, GPU, RAM and driver version. +- Operating-system version. +- Diagnostic build features. +- Exact command and environment variables. +- First allocation failure and surrounding log messages. +- Resource-state warnings preceding the failure. +- Whether the failure reproduces on another run. + +Review logs before sharing them. Remove machine-specific paths and never +include proprietary game assets, executables, shader dumps or extracted +game data in the repository. From 312ff569264b2380440654df3552fd591be4076c Mon Sep 17 00:00:00 2001 From: Jithu Chilukuri <2420030078cse@gmail.com> Date: Tue, 24 Nov 2026 16:35:19 +0000 Subject: [PATCH 19/49] Report bound descriptor tables accurately in DRED breadcrumbs --- crates/victory-gpu/src/draw.rs | 123 +++++++++++++++++++++++++++++---- 1 file changed, 108 insertions(+), 15 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index d2537cc..49e6f8f 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -51,6 +51,13 @@ pub(crate) struct IndexView { format: u32, } +/// The root data sent to the host for one stage of the current draw. +#[cfg(feature = "diagnostics")] +struct BoundUserData { + values: Vec, + rebuilt_tables: Vec<(u8, u32)>, +} + /// What one title list has set, and what its host list was last given. #[derive(Default)] pub(crate) struct State { @@ -79,6 +86,9 @@ pub(crate) struct State { dynamic: Vec<(usize, u32, u32)>, /// A fresh table of the stage being bound could not be made. table_failed: bool, + /// The values sent to each stage for the next device-removed marker. + #[cfg(feature = "diagnostics")] + bound_user_data: Vec, } impl Drop for State { @@ -417,6 +427,12 @@ impl State { /// not be made. fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool { let l = &list.list; + #[cfg(feature = "diagnostics")] + let record_bindings = crate::host::dred_on(); + #[cfg(feature = "diagnostics")] + if record_bindings { + self.bound_user_data.clear(); + } // Heaps first: a root signature with directly indexed heaps must be // set after them. if self.host_heaps != self.heaps { @@ -471,8 +487,9 @@ impl State { } return false; } + let mut values = Vec::new(); if let Some((param, dwords)) = stage.user_data { - let mut values = vec![0u32; dwords as usize]; + values.resize(dwords as usize, 0); for u in &t.host.user_data { let fresh = made .iter() @@ -491,6 +508,13 @@ impl State { } } } + #[cfg(feature = "diagnostics")] + if record_bindings { + self.bound_user_data.push(BoundUserData { + values, + rebuilt_tables: made, + }); + } 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)) @@ -550,9 +574,8 @@ impl State { } /// 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. + /// (diagnostics): the pipeline, then each stage's bound user data, + /// descriptor table bases, root view addresses and known table entries. #[cfg(feature = "diagnostics")] fn op_text(&self, kind: String, compute: bool) -> String { use std::fmt::Write; @@ -560,19 +583,11 @@ impl State { 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 { + for (stage, bound) in p.stages.iter().zip(&self.bound_user_data) { 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}]"); - } + self.note_user_data(&mut text, compute, u, bound); } 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)) { @@ -582,10 +597,54 @@ impl State { } } } - let _ = write!(text, " tables {:?}", self.reads(compute)); + let _ = write!(text, " title tables {:?}", self.reads(compute)); text } + #[cfg(feature = "diagnostics")] + fn note_user_data( + &self, + text: &mut String, + compute: bool, + data: &victory_shader::emit::UserData, + bound: &BoundUserData, + ) { + use std::fmt::Write; + let Some(&value) = bound.values.get(data.index as usize) else { + return; + }; + let _ = write!(text, " u{}={value:#x}", data.index); + if data.root != RootType::Table { + return; + } + if bound + .rebuilt_tables + .iter() + .any(|&(slot, _)| slot == data.slot) + { + // Rebuilt tables use dynamic view slots, which have no mirror + // record. The offset is in 32-byte console view descriptors. + let _ = write!(text, " [rebuilt view table base {}]", value / 32); + return; + } + let table = match self.roots_ref(compute).get(usize::from(data.slot)) { + Some(Root::Table(handle)) => self + .heap_of(*handle) + .and_then(|heap| heap.index(*handle).map(|index| (heap, index))), + _ => None, + }; + if let Some((heap, index)) = table { + let kind = if heap.samplers() { "sampler" } else { "view" }; + let _ = write!(text, " [{kind} table base {index}"); + if let Some(record) = heap.host().and_then(|h| h.describe_slot(index)) { + let _ = write!(text, ": {record}"); + } + text.push(']'); + } else { + text.push_str(" [unbound table]"); + } + } + /// 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) { @@ -1215,3 +1274,37 @@ pub(crate) fn stencil_ref(list: &HostList, reference: u32) { // SAFETY: an open list. unsafe { list.list.OMSetStencilRef(reference) }; } + +#[cfg(all(test, feature = "diagnostics"))] +mod tests { + use super::*; + use victory_shader::emit::UserData; + + #[test] + fn breadcrumbs_distinguish_constants_rebuilt_tables_and_missing_tables() { + let mut state = State::default(); + state.set_table(false, 1, 0x1000); + let bound = BoundUserData { + values: vec![0x1234, 0x8000, 0], + rebuilt_tables: vec![(1, 0x8000)], + }; + let mut text = String::new(); + for (index, root) in [ + (0, RootType::Constants), + (1, RootType::Table), + (2, RootType::Table), + ] { + let data = UserData { + index, + slot: index as u8, + root, + dword: 0, + }; + state.note_user_data(&mut text, false, &data, &bound); + } + assert_eq!( + text, + " u0=0x1234 u1=0x8000 [rebuilt view table base 1024] u2=0x0 [unbound table]" + ); + } +} From 591932ac8ce4645e42d702bf72f0d96b298987bf Mon Sep 17 00:00:00 2001 From: Jithu Chilukuri <2420030078cse@gmail.com> Date: Tue, 24 Nov 2026 16:42:04 +0000 Subject: [PATCH 20/49] Grow DirectStorage BCPack intermediates as zlib inflates --- crates/victory-hle/src/modules/dstorage.rs | 44 ++++++++++++++++++---- 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index c94146f..7db9b18 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -821,10 +821,10 @@ fn execute(request: &Request) -> Result<(), HRESULT> { let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?; // The console's order: zlib first, then BCPack. let source = if bc != 0 && options & ZLIB != 0 { - let mut packed = vec![0; request.intermediate_size as usize]; - let n = inflate(&source, &mut packed).map_err(|hr| fail(hr, "zlib"))?; - packed.truncate(n); - Cow::Owned(packed) + Cow::Owned( + inflate_intermediate(&source, request.intermediate_size as usize) + .map_err(|hr| fail(hr, "zlib"))?, + ) } else { source }; @@ -848,10 +848,19 @@ fn execute(request: &Request) -> Result<(), HRESULT> { /// nothing says that is required. fn inflate(source: &[u8], out: &mut [u8]) -> Result { miniz_oxide::inflate::decompress_slice_iter_to_slice(out, std::iter::once(source), true, false) - .map_err(|status| { - tracing::debug!(?status, "dstorage: zlib stream"); - INVALID_DATA - }) + .map_err(inflate_error) +} + +/// The BCPack intermediate may be shorter than its limit. Grow its +/// storage as bytes arrive instead of reserving the entire limit up front. +fn inflate_intermediate(source: &[u8], limit: usize) -> Result, HRESULT> { + miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(source, limit) + .map_err(|error| inflate_error(error.status)) +} + +fn inflate_error(status: miniz_oxide::inflate::TINFLStatus) -> HRESULT { + tracing::debug!(?status, "dstorage: zlib stream"); + INVALID_DATA } /// The BCPack format's constant tables, parsed once for the process. If @@ -1352,6 +1361,25 @@ mod tests { assert_eq!(results(), (INVALID_DATA, S_OK)); } + #[test] + fn zlib_intermediate_grows_with_output_and_respects_its_limit() { + let data = [0x69; 2048]; + let mut encoded = miniz_oxide::deflate::compress_to_vec_zlib(&data, 6); + let limit = 64 << 20; + let decoded = inflate_intermediate(&encoded, limit).unwrap(); + assert_eq!(decoded, data); + assert!(decoded.capacity() < limit); + assert_eq!(inflate_intermediate(&encoded, data.len()).unwrap(), data); + assert_eq!( + inflate_intermediate(&encoded, data.len() - 1), + Err(INVALID_DATA) + ); + + // The checksum is still checked, even with room left over. + *encoded.last_mut().unwrap() ^= 1; + assert_eq!(inflate_intermediate(&encoded, limit), Err(INVALID_DATA)); + } + #[test] fn zlib_then_bcpack() { with_test_tables(); From b4e464738d6e54d7fbc342c657ddc58a70d276bc Mon Sep 17 00:00:00 2001 From: BastienRdz <58186763+BastienRodz@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:11:48 +0000 Subject: [PATCH 21/49] GPU: a half exactly halfway between two rounds to the even one, not up f32_to_half adds 0x1000 before dropping the low 13 mantissa bits, so a value exactly halfway between two halves always rounds up: 1 + 2^-11 packs as 0x3c01 instead of 0x3c00. A rectangle's fourth corner computed on such a value gets a half one ulp off. fuzeofficlal measured it in native draws of the direct path on RTX 5090 and WARP (10 of 16 reference pixels before, 16 of 16 after) and wrote the fix: the retained bit decides halfway cases. Co-Authored-By: fuzeofficlal Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/primitive.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index d925048..f71e01b 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -141,10 +141,12 @@ fn f32_to_half(v: f32) -> u16 { let m = q + u32::from(r > halfway || (r == halfway && (q & 1) != 0)); return sign | m as u16; } - // Rounded to nearest: a carry out of the mantissa is added into the - // exponent (`2 - 2^-12` is 2.0); at most it reaches infinity, 0x7c00. + // Rounded to nearest, halfway cases to even (the retained bit decides); + // a carry out of the mantissa is added into the exponent (`2 - 2^-12` + // is 2.0); at most it reaches infinity, 0x7c00. let half = (exp as u32) << 10; - sign | (half + ((man + 0x1000) >> 13)) as u16 + let retained = (man >> 13) & 1; + sign | (half + ((man + 0x0fff + retained) >> 13)) as u16 } #[cfg(test)] @@ -198,6 +200,16 @@ mod tests { assert_eq!(dst[10..], 0x4000_u16.to_le_bytes()); } + /// Halfway between two halves, the even one: 1 + 2^-11 lies between + /// 0x3c00 and 0x3c01, 1 + 3 * 2^-11 between 0x3c01 and 0x3c02. + #[test] + fn half_midpoints_round_to_even() { + assert_eq!(f32_to_half(1.0 + 2f32.powi(-11)), 0x3c00); + assert_eq!(f32_to_half(1.0 + 3.0 * 2f32.powi(-11)), 0x3c02); + // Just past a midpoint still rounds up. + assert_eq!(f32_to_half(1.0 + 2f32.powi(-11) + 2f32.powi(-20)), 0x3c01); + } + /// An element that reaches past the stride (float4 at 4 in 8-byte /// vertices, RGBA8 at the stride itself): the components inside get /// the fourth corner, the rest keep the first vertex's bytes. The old From 57d00fdcb1b201545290bfd7b4c80caeb41e1761 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:15:41 +0800 Subject: [PATCH 22/49] Shaders: pre-validate DXBC headers before dxil.dll and trim load error NUL --- crates/victory-shader/src/emit/validator.rs | 54 ++++++++++++++++++--- 1 file changed, 46 insertions(+), 8 deletions(-) diff --git a/crates/victory-shader/src/emit/validator.rs b/crates/victory-shader/src/emit/validator.rs index f8e31be..088a799 100644 --- a/crates/victory-shader/src/emit/validator.rs +++ b/crates/victory-shader/src/emit/validator.rs @@ -5,7 +5,8 @@ //! The DLL is found at `VICTORY_DXIL` if set, else the newest Windows SDK's //! `bin\\x64\dxil.dll`, else wherever `LoadLibrary` finds it. -use std::ffi::c_void; +use std::ffi::{OsStr, c_void}; +use std::os::windows::ffi::OsStrExt; use std::path::PathBuf; use windows_sys::Win32::Foundation::{FreeLibrary, HMODULE}; @@ -152,17 +153,13 @@ impl Validator { /// Loads `path`'s validator (or `dxil.dll` from the DLL search path). pub fn load(path: Option<&std::path::Path>) -> Result { - let name: Vec = path - .map_or_else(|| "dxil.dll".into(), |p| p.as_os_str().to_owned()) - .to_string_lossy() - .encode_utf16() - .chain([0]) - .collect(); + let target: &OsStr = path.map_or(OsStr::new("dxil.dll"), |p| p.as_os_str()); + let name: Vec = target.encode_wide().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))); + return Err(format!("cannot load {}", target.to_string_lossy())); } Self::from_module(module, FreeLibrary, |module| { let create = GetProcAddress(module, c"DxcCreateInstance".as_ptr().cast()) @@ -198,6 +195,13 @@ impl Validator { /// Validates `container` and signs it in place; the error text if it /// is rejected. pub fn validate(&mut self, container: &mut [u8]) -> Result<(), String> { + // `dxil.dll` trusts header size/part fields on `"DXBC"` blobs before + // checking `IDxcBlob::GetBufferSize()`, causing an access violation on + // truncated/malformed containers. Pre-validate DXBC framing in safe Rust + // while leaving non-DXBC unit-test stubs untouched. + if container.starts_with(b"DXBC") { + crate::dxbc::Container::parse(container).map_err(|e| e.to_string())?; + } let mut blob = Blob { vtable: &BLOB_VTABLE, data: container.as_mut_ptr(), @@ -611,4 +615,38 @@ mod tests { assert_eq!(module.frees, 1); assert_eq!(module.object_releases_at_free, 1); } + + #[test] + fn load_error_has_no_trailing_nul() { + let missing = std::path::Path::new(r"Z:\nonexistent\victory_missing_dxil_test.dll"); + let err = Validator::load(Some(missing)).err().unwrap(); + assert!(!err.contains('\0'), "error string had trailing NUL: {err:?}"); + assert!(err.contains("victory_missing_dxil_test.dll")); + } + + #[test] + fn truncated_dxbc_container_is_rejected_before_calling_dxil() { + unsafe extern "system" fn panic_validate( + _: Object, + _: *mut Blob, + _: u32, + _: *mut Object, + ) -> Hresult { + panic!("IDxcValidator::Validate must not be called on malformed DXBC"); + } + let vtable = [ + 0, + 0, + mock_release as *const () as usize, + panic_validate as *const () as usize, + ]; + let mut validator_mock = Mock::new(&vtable, ()); + let mut validator = Validator { + object: validator_mock.object(), + _module: None, + }; + // Starts with "DXBC" magic but is truncated (< 32-byte header). + let mut truncated = b"DXBC\x00\x00\x00\x00".to_vec(); + assert!(validator.validate(&mut truncated).is_err()); + } } From ae0b48e6daf7dbbad8c5d8af504726f5efac1bf4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:15:55 +0800 Subject: [PATCH 23/49] Shaders: align Lower::image VGPR unpacking with a16/g16 gradient rules --- crates/victory-shader/src/emit/lower.rs | 58 ++++++++++++++----------- 1 file changed, 33 insertions(+), 25 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..8be2550 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5625,14 +5625,15 @@ impl<'a> Lower<'a> { regs.extend((0..dwords).map(|k| reg + k)); } } - // With a16, two 16-bit components per VGPR, low half first. - let addr_val = |l: &mut Self, k: usize| -> Result { + // Address component from VGPRs starting at `base`; when `half` is set, + // two 16-bit components pack per VGPR, low half first. + let addr_at = |l: &mut Self, base: usize, half: bool, k: usize| -> Result { let r = *regs - .get(if *a16 { k / 2 } else { k }) + .get(base + if half { k / 2 } else { k }) .ok_or("an image address")?; let v = inst.read(Reg::V(r)).ok_or("an image address")?; let x = l.i32_of(v)?; - if !*a16 { + if !half { return Ok(x); } let c = l.cur; @@ -5640,6 +5641,7 @@ impl<'a> Lower<'a> { let x = l.s.m.bin(c, Bin::LShr, x, sh); Ok(l.s.m.bin(c, Bin::And, x, mask)) }; + let addr_val = |l: &mut Self, k: usize| -> Result { addr_at(l, 0, *a16, k) }; let src = self .descriptors .get(&(site, false)) @@ -5784,7 +5786,7 @@ impl<'a> Lower<'a> { "image_sample_lz" | "image_sample_l" => (62, true), "image_sample_b" => (61, true), "image_sample_c_lz" => (65, true), - "image_sample_d" => (63, true), + "image_sample_d" | "image_sample_d_g16" => (63, true), "image_get_lod" if self.s.pixel => (81, true), // Implicit derivatives: pixel shaders only. "image_sample_c" if self.s.pixel => (64, true), @@ -5801,7 +5803,7 @@ impl<'a> Lower<'a> { let mip = if uav { self.s.m.undef(self.s.t.i32) } else { - addr_val(self, 0)? + addr_at(self, 0, false, 0)? }; let i32t = self.s.t.i32; let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); @@ -5846,19 +5848,25 @@ impl<'a> Lower<'a> { return Err("a comparison sample of 16-bit coordinates or several channels"); } let sh = self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?; - // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13, - // signed (programmable offsets: gathers only). + // Texel offsets (`_o`) come first as a whole dword: x in bits 0-5, + // y in 8-13, signed (programmable offsets: gathers only). let offset_word = name.ends_with("_o"); let first = usize::from(offset_word) + usize::from(name == "image_sample_b") + usize::from(cmp); // Coordinates the size divides (not the array slice); explicit - // gradients (x then y) come before the coordinates. + // gradients (x then y) come before the coordinates, packed only + // when `_g16` is set (independently of `a16`). let spatial = coords - usize::from(kind == 6 || kind == 7); - let grads = if op == 63 { 2 * spatial } else { 0 }; + let g16 = name.ends_with("_g16"); + let grad_regs = if op == 63 { + if g16 { spatial.div_ceil(2) } else { spatial } + } else { + 0 + }; + let coord_base = first + 2 * grad_regs; let mut cs = vec![fu; 4]; - // With a16, sampling coordinates and LOD are f16. - let to_float = |l: &mut Self, x: V| { - if *a16 { + let to_float = |l: &mut Self, half: bool, x: V| { + if half { let f = l.s.t.f32; l.s.op(l.cur, "legacyF16ToF32", Attr::ReadNone, f, 131, &[x]) } else { @@ -5866,8 +5874,8 @@ impl<'a> Lower<'a> { } }; for (k, slot) in cs.iter_mut().enumerate().take(coords) { - let x = addr_val(self, first + grads + k)?; - *slot = to_float(self, x); + let x = addr_at(self, coord_base, *a16, k)?; + *slot = to_float(self, *a16, x); } if kind == 5 { if *unorm || op == 63 || op == 81 { @@ -5928,7 +5936,7 @@ impl<'a> Lower<'a> { if offset_word { // DXIL takes immediate offsets in -8..=7; the // console's are 6-bit and may be computed. - let w = addr_val(self, 0)?; + let w = addr_at(self, 0, false, 0)?; let w = self .s .m @@ -5950,7 +5958,7 @@ impl<'a> Lower<'a> { .op(c, "sample.f32", Attr::ReadOnly, self.s.t.res_ret, 60, &args) } 61 => { - let bias = addr_val(self, 0)?; + let bias = addr_at(self, usize::from(offset_word), false, 0)?; let bias = self.as_float(bias); args.extend(&os); args.extend([bias, fu]); @@ -5966,10 +5974,10 @@ impl<'a> Lower<'a> { 63 => { let mut g = vec![fu; 6]; for k in 0..spatial { - let x = addr_val(self, first + k)?; - g[k] = to_float(self, x); - let y = addr_val(self, first + spatial + k)?; - g[3 + k] = to_float(self, y); + let x = addr_at(self, first, g16, k)?; + g[k] = to_float(self, g16, x); + let y = addr_at(self, first + grad_regs, g16, k)?; + g[3 + k] = to_float(self, g16, y); } args.extend(&os); args.extend(g); @@ -5984,7 +5992,7 @@ impl<'a> Lower<'a> { ) } 64 | 65 => { - let reference = addr_val(self, first - 1)?; + let reference = addr_at(self, first - 1, false, 0)?; let reference = self.as_float(reference); args.extend(&os); args.push(reference); @@ -5999,8 +6007,8 @@ impl<'a> Lower<'a> { } 62 => { let lod = if name == "image_sample_l" { - let x = addr_val(self, coords)?; - to_float(self, x) + let x = addr_at(self, coord_base, *a16, coords)?; + to_float(self, *a16, x) } else { self.s.m.f32(0) }; @@ -6023,7 +6031,7 @@ impl<'a> Lower<'a> { return Err("a gather of several channels"); } if offset_word { - let w = addr_val(self, 0)?; + let w = addr_at(self, 0, false, 0)?; for (k, at) in [(0, 26), (1, 18)] { // Bits at..at+5 sign-extended: shift up, then down. let left = self.s.m.i32(at); From f8aeeeca94d4e92eb4a77a4797a9290dc2f590be Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:09:49 +0530 Subject: [PATCH 24/49] GPU: report retained loose shadow memory --- crates/victory-gpu/src/shadow.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index e8de19f..aa19fde 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -445,6 +445,17 @@ const WINDOW: u64 = 4 << 20; /// Copies of title memory outside buffers, by (start, length). static LOOSE: Mutex>> = Mutex::new(BTreeMap::new()); +/// The number and total size of loose host copies currently retained. +#[cfg(feature = "diagnostics")] +pub(crate) fn cache_stats() -> (usize, u64) { + LOOSE.lock() + .unwrap_or_else(|e| e.into_inner()) + .values() + .fold((0, 0), |(count, bytes), shadow| { + (count + 1, bytes.saturating_add(shadow.len)) + }) +} + fn loose(address: u64, end: u64) -> Option> { let start = address & !(WINDOW - 1); let len = end.next_multiple_of(WINDOW) - start; From d76cfdd66917d6302844b71817192442ea92d2c9 Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:09:52 +0530 Subject: [PATCH 25/49] GPU: report retained placed texture allocations --- crates/victory-gpu/src/resource.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 46c5c71..47a2bed 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1147,6 +1147,21 @@ pub(crate) extern "system" fn create_at_address( static PLACED_TEXTURES: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); +/// The number and estimated allocation size of placed textures retained by the cache. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn placed_texture_cache_stats() -> (usize, u64) { + PLACED_TEXTURES + .lock() + .unwrap_or_else(|e| e.into_inner()) + .keys() + .fold((0, 0), |(count, bytes), &(_, words)| { + // SAFETY: the cache key stores the original 56-byte resource description. + let desc = unsafe { words.as_ptr().cast::().read_unaligned() }; + let size = footprint(&desc).map_or(0, |info| info.size); + (count + 1, bytes.saturating_add(size)) + }) +} + /// The resource for a texture placed at `address` with the resource /// description `desc` (as words), made on first use. #[cfg(windows)] From f3233fc8b6091b228e8a35dc8411cc7016123cbb Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:10:07 +0530 Subject: [PATCH 26/49] GPU: count descriptor-held resources for diagnostics --- crates/victory-gpu/src/descriptor/host.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 582f234..f15a324 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -13,6 +13,15 @@ use windows::Win32::Graphics::Dxgi::Common::*; use super::{VIEW_TAG, View, view_at}; use crate::host::host; +/// Number of shader-visible descriptor slots retaining a host resource. +#[cfg(feature = "diagnostics")] +static KEPT_SLOTS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +#[cfg(feature = "diagnostics")] +pub(crate) fn kept_slots() -> usize { + KEPT_SLOTS.load(std::sync::atomic::Ordering::Relaxed) +} + pub(crate) struct HostHeap { pub(crate) heap: ID3D12DescriptorHeap, cpu: usize, @@ -302,6 +311,15 @@ impl HostHeap { fn keep(&self, index: u32, resource: Option) { let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); if let Some(slot) = kept.get_mut(index as usize) { + #[cfg(feature = "diagnostics")] + if slot.is_some() != resource.is_some() { + use std::sync::atomic::Ordering::Relaxed; + if resource.is_some() { + KEPT_SLOTS.fetch_add(1, Relaxed); + } else { + KEPT_SLOTS.fetch_sub(1, Relaxed); + } + } *slot = resource; } } From e649d5b0c2892968452c9c82918d135d59a229b5 Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:10:10 +0530 Subject: [PATCH 27/49] GPU: log retained mirror and descriptor cache sizes --- crates/victory-gpu/src/copystat.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 8b7d13d..63e7d77 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -127,6 +127,14 @@ pub(crate) fn log(frames: f64) { mb(c[C::TexHashed as usize]), mb(c[C::TexChanged as usize]), ); + let (loose_count, loose_bytes) = crate::shadow::cache_stats(); + let (placed_count, placed_bytes) = crate::resource::placed_texture_cache_stats(); + let kept_slots = crate::descriptor::host::kept_slots(); + tracing::info!( + "retained GPU mirrors: {loose_count} loose shadows ({:.1} MiB), {placed_count} placed textures ({:.1} MiB estimated), {kept_slots} descriptor slots holding resources", + loose_bytes as f64 / (1 << 20) as f64, + placed_bytes as f64 / (1 << 20) as f64, + ); 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)); From 07b6d16415efd3ce26da01bdc7a6868ff31d5c8c Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:10:20 +0530 Subject: [PATCH 28/49] GPU: account for descriptor resources when heaps are dropped --- crates/victory-gpu/src/descriptor/host.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index f15a324..f0a6a64 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -213,6 +213,22 @@ impl HostHeap { } } +impl Drop for HostHeap { + fn drop(&mut self) { + #[cfg(feature = "diagnostics")] + { + let retained = self + .kept + .get_mut() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .filter(|slot| slot.is_some()) + .count(); + KEPT_SLOTS.fetch_sub(retained, std::sync::atomic::Ordering::Relaxed); + } + } +} + /// A plain point sampler at `at`. fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) { let Some(host) = host() else { return }; From 185845da2d80d233a8fe616013913dd5c9aad5a8 Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:10:36 +0530 Subject: [PATCH 29/49] GPU: tidy retained mirror diagnostic --- crates/victory-gpu/src/copystat.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 63e7d77..ef2d154 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -131,7 +131,7 @@ pub(crate) fn log(frames: f64) { let (placed_count, placed_bytes) = crate::resource::placed_texture_cache_stats(); let kept_slots = crate::descriptor::host::kept_slots(); tracing::info!( - "retained GPU mirrors: {loose_count} loose shadows ({:.1} MiB), {placed_count} placed textures ({:.1} MiB estimated), {kept_slots} descriptor slots holding resources", + "retained GPU mirrors: {loose_count} loose shadows ({:.1} MiB); {placed_count} placed textures ({:.1} MiB estimated); {kept_slots} descriptor slots holding resources", loose_bytes as f64 / (1 << 20) as f64, placed_bytes as f64 / (1 << 20) as f64, ); From ce8bbaf06a16758d008807ba503aca89386f8168 Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:21:31 +0530 Subject: [PATCH 30/49] GPU: report failed shadow allocations with title addresses --- crates/victory-gpu/src/shadow.rs | 36 ++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index aa19fde..53adc66 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -414,7 +414,15 @@ pub(crate) fn find(address: u64, len: u64) -> Option> { 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))?; + let Some(host) = host() else { return None }; + let Some((buffer, data)) = host.shared_buffer(len.next_multiple_of(1 << 16)) else { + tracing::warn!( + address = format_args!("{:#x}", key.0), + len, + "could not allocate host copy for title buffer" + ); + return None; + }; crate::host::name(&buffer, || format!("title buffer {:#x}+{len:#x}", key.0)); // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; @@ -445,15 +453,23 @@ const WINDOW: u64 = 4 << 20; /// Copies of title memory outside buffers, by (start, length). static LOOSE: Mutex>> = Mutex::new(BTreeMap::new()); -/// The number and total size of loose host copies currently retained. +/// The number and total size of registered and loose host copies retained. #[cfg(feature = "diagnostics")] -pub(crate) fn cache_stats() -> (usize, u64) { - LOOSE.lock() +pub(crate) fn cache_stats() -> (usize, u64, usize, u64) { + let (registered_count, registered_bytes) = buffers() + .values() + .filter_map(|entry| entry.shadow.as_ref()) + .fold((0, 0), |(count, bytes), shadow| { + (count + 1, bytes.saturating_add(shadow.len)) + }); + let (loose_count, loose_bytes) = LOOSE + .lock() .unwrap_or_else(|e| e.into_inner()) .values() .fold((0, 0), |(count, bytes), shadow| { (count + 1, bytes.saturating_add(shadow.len)) - }) + }); + (registered_count, registered_bytes, loose_count, loose_bytes) } fn loose(address: u64, end: u64) -> Option> { @@ -463,7 +479,15 @@ fn loose(address: u64, end: u64) -> Option> { if let Some(shadow) = map.get(&(start, len)) { return Some(shadow.clone()); } - let (buffer, data) = host()?.shared_buffer(len)?; + let Some(host) = host() else { return None }; + let Some((buffer, data)) = host.shared_buffer(len) else { + tracing::warn!( + address = format_args!("{start:#x}"), + len, + "could not allocate host copy for loose title memory" + ); + return None; + }; crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x}")); // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; From 48677614c068d15e6ef70c6901ab0f5a4631b3be Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:21:38 +0530 Subject: [PATCH 31/49] GPU: report registered shadow cache size --- crates/victory-gpu/src/copystat.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index ef2d154..9f7729e 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -127,11 +127,13 @@ pub(crate) fn log(frames: f64) { mb(c[C::TexHashed as usize]), mb(c[C::TexChanged as usize]), ); - let (loose_count, loose_bytes) = crate::shadow::cache_stats(); + let (registered_count, registered_bytes, loose_count, loose_bytes) = + crate::shadow::cache_stats(); let (placed_count, placed_bytes) = crate::resource::placed_texture_cache_stats(); let kept_slots = crate::descriptor::host::kept_slots(); tracing::info!( - "retained GPU mirrors: {loose_count} loose shadows ({:.1} MiB); {placed_count} placed textures ({:.1} MiB estimated); {kept_slots} descriptor slots holding resources", + "retained GPU mirrors: {registered_count} registered shadows ({:.1} MiB); {loose_count} loose shadows ({:.1} MiB); {placed_count} placed textures ({:.1} MiB estimated); {kept_slots} descriptor slots holding resources", + registered_bytes as f64 / (1 << 20) as f64, loose_bytes as f64 / (1 << 20) as f64, placed_bytes as f64 / (1 << 20) as f64, ); From 4b632f1986c4c531910534578c8c45e36777f154 Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:24:38 +0530 Subject: [PATCH 32/49] GPU: specify shadow cache counter types --- crates/victory-gpu/src/shadow.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 53adc66..e32c0d6 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -459,14 +459,14 @@ pub(crate) fn cache_stats() -> (usize, u64, usize, u64) { let (registered_count, registered_bytes) = buffers() .values() .filter_map(|entry| entry.shadow.as_ref()) - .fold((0, 0), |(count, bytes), shadow| { + .fold((0usize, 0u64), |(count, bytes), shadow| { (count + 1, bytes.saturating_add(shadow.len)) }); let (loose_count, loose_bytes) = LOOSE .lock() .unwrap_or_else(|e| e.into_inner()) .values() - .fold((0, 0), |(count, bytes), shadow| { + .fold((0usize, 0u64), |(count, bytes), shadow| { (count + 1, bytes.saturating_add(shadow.len)) }); (registered_count, registered_bytes, loose_count, loose_bytes) From fee820b7030654d317018157edea64082cb95aa8 Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:39:57 +0530 Subject: [PATCH 33/49] GPU: track shadow buffer resource state --- crates/victory-gpu/src/shadow.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index e32c0d6..32dd9c3 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -16,7 +16,7 @@ //! indexed heaps keep what their first use copied. use std::collections::BTreeMap; -use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::atomic::{AtomicU32, AtomicU8, Ordering}; use std::sync::{Arc, Mutex}; use windows::Win32::Graphics::Direct3D12::ID3D12Resource; @@ -27,6 +27,8 @@ use crate::watch::PAGE; /// A title buffer's host copy. pub(crate) struct Shadow { pub(crate) buffer: ID3D12Resource, + /// The D3D12 state of this host copy between submissions (buffers decay to COMMON). + pub(crate) state: AtomicU32, data: *mut u8, gpu: u64, /// Where the title buffer starts and how long it is. @@ -110,6 +112,7 @@ impl Shadow { let pages = (start + len).div_ceil(PAGE as u64) - start / PAGE as u64; Shadow { buffer, + state: AtomicU32::new(0), data, gpu, start, From f8479d3daf7f3683d373622092f48f0377f29a09 Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:40:02 +0530 Subject: [PATCH 34/49] GPU: track shadow buffer transitions per command list --- crates/victory-gpu/src/host.rs | 58 +++++++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 6672c1e..640f051 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -294,6 +294,8 @@ pub(crate) struct HostList { /// list names alive until it is reset, even if the title releases the /// resource first. states: Mutex, + /// Shadow buffers and their first/last states in this command list. + shadow_states: Mutex, /// The list that runs those transitions just before this one. prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList), /// The pipelines the list binds, for reports of slow submissions. @@ -323,6 +325,10 @@ type States = std::collections::HashMap< usize, (u32, u32, std::sync::Arc), >; +type ShadowStates = std::collections::HashMap< + usize, + (u32, u32, std::sync::Arc), +>; /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics /// builds). @@ -478,6 +484,7 @@ impl Host { deferred: Mutex::default(), scratch: Mutex::default(), states: Mutex::default(), + shadow_states: Mutex::default(), prelude: (prelude_allocator, prelude), pipelines: Mutex::default(), budget: OnceLock::new(), @@ -537,6 +544,13 @@ impl Host { match waited { Ok(()) => { WaitForSingleObject(self.event, INFINITE); + if groups.len() > 1 { + runs[i].decay_shadows(); + } else { + for list in runs { + list.decay_shadows(); + } + } } Err(e) => tracing::warn!(error = %e, "host submission not waited for"), } @@ -882,6 +896,7 @@ impl HostList { pub(crate) fn reset(&self) { *self.deferred() = Deferred::default(); self.states.lock().unwrap_or_else(|e| e.into_inner()).clear(); + self.shadow_states.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear(); #[cfg(feature = "diagnostics")] self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear(); @@ -925,12 +940,41 @@ impl HostList { } } + /// Moves a shadow buffer to `wanted` in this list. Its real state is + /// tracked separately because D3D12 buffers decay to COMMON after each + /// ExecuteCommandLists operation. + pub(crate) fn transition_shadow( + &self, + shadow: &std::sync::Arc, + wanted: u32, + ) -> Option<(ID3D12Resource, u32)> { + let mut states = self.shadow_states.lock().unwrap_or_else(|e| e.into_inner()); + match states.entry(std::sync::Arc::as_ptr(shadow) as usize) { + std::collections::hash_map::Entry::Vacant(v) => { + v.insert((wanted, wanted, shadow.clone())); + None + } + std::collections::hash_map::Entry::Occupied(mut o) => { + let before = std::mem::replace(&mut o.get_mut().1, wanted); + (before != wanted).then(|| (shadow.buffer.clone(), before)) + } + } + } + + /// Buffers decay to COMMON after a completed ExecuteCommandLists call. + fn decay_shadows(&self) { + let states = self.shadow_states.lock().unwrap_or_else(|e| e.into_inner()); + for (_, (_, _, shadow)) in states.iter() { + shadow.state.store(0, Ordering::Relaxed); + } + } + /// At submission: the list that moves each texture this list uses from /// its real state to the one the list starts with; the textures' real /// states become those the list ends with. fn prelude(&self) -> Option { let states = self.states.lock().unwrap_or_else(|e| e.into_inner()); - let barriers: Vec = states + let mut barriers: Vec = states .values() .filter_map(|(first, last, copy)| { let real = copy.state.swap(*last, Ordering::Relaxed); @@ -943,6 +987,18 @@ impl HostList { }) }) .collect(); + drop(states); + let shadows = self.shadow_states.lock().unwrap_or_else(|e| e.into_inner()); + barriers.extend(shadows.values().filter_map(|(first, last, shadow)| { + let real = shadow.state.swap(*last, Ordering::Relaxed); + (real != *first).then(|| { + transition( + &shadow.buffer, + D3D12_RESOURCE_STATES(real as i32), + D3D12_RESOURCE_STATES(*first as i32), + ) + }) + })); if barriers.is_empty() { return None; } From 364b5f9bad590e5b65cf25819c0b1ca7e258fd4f Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:40:06 +0530 Subject: [PATCH 35/49] GPU: add shadow buffer state barriers --- crates/victory-gpu/src/list.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 7adb4e4..fa6ddb1 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -398,6 +398,21 @@ pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: } } +/// Moves a shadow buffer to the state required by its next GPU use. +#[cfg(windows)] +pub(crate) fn ensure_shadow_state( + list: &crate::host::HostList, + shadow: &std::sync::Arc, + state: u32, +) { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State; + if let Some((buffer, before)) = list.transition_shadow(shadow, state) { + let barrier = crate::host::transition(&buffer, State(before as i32), State(state as i32)); + // SAFETY: an open list and a live shadow buffer. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + } +} + #[cfg(windows)] const COPY_DEST: u32 = 0x400; #[cfg(windows)] From d8b8f9b9a42a3edb90d14299871435969bedd86f Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:40:09 +0530 Subject: [PATCH 36/49] GPU: transition shadow buffers before draw and shader use --- crates/victory-gpu/src/draw.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index d2537cc..95394ac 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -143,6 +143,11 @@ fn root_view(list: &HostList, address: u64, srv: bool) -> Option { .min(if srv { 1 << 20 } else { 1 << 16 }); let gpu = shadow.gpu(address); if srv || gpu % 256 == 0 { + crate::list::ensure_shadow_state( + list, + &shadow, + if srv { 0x40 | 0x80 } else { 0x1 }, + ); shadow.refresh(list, address, len); return Some(gpu); } @@ -370,6 +375,7 @@ impl State { let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else { continue; }; + crate::list::ensure_shadow_state(list, &shadow, 0x1); shadow.refresh(list, v.address, u64::from(v.size)); *view = D3D12_VERTEX_BUFFER_VIEW { BufferLocation: shadow.gpu(v.address), @@ -388,6 +394,7 @@ impl State { let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else { return false; }; + crate::list::ensure_shadow_state(list, &shadow, 0x2); shadow.refresh(list, v.address, u64::from(v.size)); let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: shadow.gpu(v.address), @@ -1109,10 +1116,20 @@ fn readable(list: &HostList, u: &UsedResource, view: &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) + let range = match view { + View::Constant(address, size) => Some((*address, u64::from(*size))), + _ => crate::descriptor::host::buffer_range(view), + }; + if let Some((address, len)) = range && len > 0 && let Some(shadow) = crate::shadow::find(address, len) { + let state = match u.kind { + ResourceType::Cbv => 0x1, + ResourceType::Srv => SHADER_RESOURCE, + ResourceType::Uav => UNORDERED_ACCESS, + }; + crate::list::ensure_shadow_state(list, &shadow, state); shadow.refresh(list, address, len); if u.kind == ResourceType::Uav { shadow.gpu_writes(list, address, len); From 62a3cbc3ca24ec623b1f14cac047c2a5a7dc2777 Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:40:31 +0530 Subject: [PATCH 37/49] GPU: track indirect shadow buffer state changes --- crates/victory-gpu/src/host.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 640f051..93b8c14 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -961,6 +961,21 @@ impl HostList { } } + /// Records a state change already emitted by a helper such as the + /// indirect-argument clamp, without adding another barrier. + pub(crate) fn note_shadow_state( + &self, + shadow: &std::sync::Arc, + state: u32, + ) { + let mut states = self.shadow_states.lock().unwrap_or_else(|e| e.into_inner()); + let key = std::sync::Arc::as_ptr(shadow) as usize; + states + .entry(key) + .and_modify(|entry| entry.1 = state) + .or_insert_with(|| (state, state, shadow.clone())); + } + /// Buffers decay to COMMON after a completed ExecuteCommandLists call. fn decay_shadows(&self) { let states = self.shadow_states.lock().unwrap_or_else(|e| e.into_inner()); From f9afc300b7b4b5ba83a023bbea0866dfc80a9ef9 Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:40:36 +0530 Subject: [PATCH 38/49] GPU: track indirect argument shadow states --- crates/victory-gpu/src/draw.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 95394ac..e8a74d2 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1018,11 +1018,18 @@ impl State { if let Some((s, at)) = &counter { s.refresh(list, *at, 4); } + // The clamp writes the argument shadow as UAV, then leaves it + // in INDIRECT_ARGUMENT for ExecuteIndirect. + crate::list::ensure_shadow_state(list, &args, 0x8); // Bounded first: the clamp binds a compute pipeline of its own. if !crate::indirect::bound(list, &args.buffer, args.gpu(arguments), (kind, stride, max)) { why("not bounded (no clamp, or arguments not 4-byte aligned)"); return false; } + list.note_shadow_state(&args, 0x200); + if let Some((shadow, _)) = &counter { + crate::list::ensure_shadow_state(list, shadow, 0x200); + } self.host_pipeline = 0; self.host_roots[1] = 0; let ran = match kind { @@ -1060,6 +1067,7 @@ impl State { ) }; crate::indirect::done(list, &args.buffer); + list.note_shadow_state(&args, 0x8); if kind == DISPATCH { DISPATCHED.fetch_add(1, Ordering::Relaxed); } else { From 92b4e2f6c34e44ed7f27b0aa3bd4ea7bccd7cd93 Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:41:36 +0530 Subject: [PATCH 39/49] GPU: handle other shader resource kinds in state tracking --- crates/victory-gpu/src/draw.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e8a74d2..d587068 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1136,8 +1136,11 @@ fn readable(list: &HostList, u: &UsedResource, view: &View) { ResourceType::Cbv => 0x1, ResourceType::Srv => SHADER_RESOURCE, ResourceType::Uav => UNORDERED_ACCESS, + ResourceType::Other(_) | ResourceType::Sampler => 0, }; - crate::list::ensure_shadow_state(list, &shadow, state); + if state != 0 { + crate::list::ensure_shadow_state(list, &shadow, state); + } shadow.refresh(list, address, len); if u.kind == ResourceType::Uav { shadow.gpu_writes(list, address, len); From 490b63f50d984be9d7e41d03ce34f1855b06b5ca Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:41:54 +0530 Subject: [PATCH 40/49] GPU: keep indirect failure path state in sync --- crates/victory-gpu/src/draw.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index d587068..d27091c 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1043,6 +1043,7 @@ impl State { }; if !ran { crate::indirect::done(list, &args.buffer); + list.note_shadow_state(&args, 0x8); #[cfg(feature = "diagnostics")] match crate::pipeline::host_pipeline(self.pipeline as This) { None => crate::pipeline::note_drop(self.pipeline as This), From 2d50e8a47d9a52f22f450884c69faea10de7d7a9 Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:47:19 +0530 Subject: [PATCH 41/49] Prepare shadow state preludes in submission order --- crates/victory-gpu/src/host.rs | 61 ++++++++++++---------------------- 1 file changed, 22 insertions(+), 39 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 93b8c14..d54a55a 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -496,47 +496,38 @@ impl Host { } } - /// Runs closed lists and waits for them. + /// Runs closed lists in order and waits for each before preparing the next. pub(crate) fn execute(&self, runs: &[&HostList]) { // One submission at a time from preparation to copy-back: snapshots // and the ranges shaders write are per host copy, not per submission. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::Submissions, 1); - let mut lists: Vec> = Vec::with_capacity(2 * runs.len()); - // Where each run's lists start in `lists`. - let mut firsts = Vec::with_capacity(runs.len()); + crate::copystat::add(crate::copystat::C::Submissions, runs.len() as u64); + let mut batch = Batch::default(); for list in runs { list.run_deferred(&mut batch); - firsts.push(lists.len()); - if let Some(prelude) = list.prelude() { - lists.push(Some(prelude)); - } - lists.push(list.list.cast().ok()); } batch.flush(); let prepared = std::time::Instant::now(); - // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`). - #[cfg(feature = "diagnostics")] - let groups: Vec<&[Option]> = if timing() { - firsts - .iter() - .zip(firsts.iter().skip(1).chain([&lists.len()])) - .map(|(&a, &b)| &lists[a..b]) - .collect() - } else { - vec![&lists[..]] - }; - #[cfg(not(feature = "diagnostics"))] - let groups = [&lists[..]]; - for (i, group) in groups.iter().enumerate() { + + // A run's prelude must be recorded immediately before that run is + // submitted. Preparing all preludes up front is incorrect when two + // runs use the same shadow: the later prelude would assume a state + // transition that the earlier command list has not executed yet. + for list in runs { + let mut group: Vec> = Vec::with_capacity(2); + if let Some(prelude) = list.prelude() { + group.push(Some(prelude)); + } + group.push(list.list.cast().ok()); + *submitted += 1; - let started = std::time::Instant::now(); + let list_started = std::time::Instant::now(); // SAFETY: closed lists; the fence and event are ours. unsafe { - self.queue.ExecuteCommandLists(group); + self.queue.ExecuteCommandLists(&group); let waited = self .queue .Signal(&self.fence, *submitted) @@ -544,30 +535,22 @@ impl Host { match waited { Ok(()) => { WaitForSingleObject(self.event, INFINITE); - if groups.len() > 1 { - runs[i].decay_shadows(); - } else { - for list in runs { - list.decay_shadows(); - } - } + list.decay_shadows(); } Err(e) => tracing::warn!(error = %e, "host submission not waited for"), } } #[cfg(feature = "diagnostics")] - if groups.len() > 1 && started.elapsed() > std::time::Duration::from_millis(50) { + if runs.len() > 1 && list_started.elapsed() > std::time::Duration::from_millis(50) { // SAFETY: a plain query. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); - let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len(); - tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list"); - for (ms, op) in runs[i].slowest(frequency, 6) { + let commands = list.notes.lock().unwrap_or_else(|e| e.into_inner()).len(); + tracing::warn!(ms = list_started.elapsed().as_millis(), commands, "slow host list"); + for (ms, op) in list.slowest(frequency, 6) { tracing::warn!("slow list command, {ms:.1} ms: {op}"); } } - let _ = (i, started); } - let _ = &firsts; let gpu = prepared.elapsed(); SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed); SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); From 1a7ad95c510d3e5afc5b3e32e9faedfd1c2d878d Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:47:41 +0530 Subject: [PATCH 42/49] Remove obsolete per-list timing switch --- crates/victory-gpu/src/host.rs | 9 --------- 1 file changed, 9 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index d54a55a..ddee018 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -339,15 +339,6 @@ pub(crate) fn dred_on() -> bool { }) } -/// Whether each list of a submission runs and is timed on its own, slow -/// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics -/// builds; the commands are noted with `VICTORY_D3D12_DRED` on). -#[cfg(feature = "diagnostics")] -fn timing() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_GPU_TIMING").is_some()) -} - /// Names a host object for the device-removed report, which names the /// allocations a page fault hit (only with device-removed data on). pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) { From a19f38d9090b4b935db5c3897166fecb6bddbd60 Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Tue, 24 Nov 2026 23:51:16 +0530 Subject: [PATCH 43/49] Restore GPU timing diagnostics helper --- crates/victory-gpu/src/host.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index ddee018..191e2b7 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -330,6 +330,13 @@ type ShadowStates = std::collections::HashMap< (u32, u32, std::sync::Arc), >; +/// Whether GPU timestamp diagnostics are enabled (`VICTORY_GPU_TIMING`). +#[cfg(feature = "diagnostics")] +fn timing() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_GPU_TIMING").is_some()) +} + /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics /// builds). pub(crate) fn dred_on() -> bool { From c3beb4a2628b4f50bc8a02de9616e7f027ef9185 Mon Sep 17 00:00:00 2001 From: Chirag_Madhuprasad Date: Wed, 25 Nov 2026 00:04:29 +0530 Subject: [PATCH 44/49] Trace shadow resource state transitions --- crates/victory-gpu/src/host.rs | 49 +++++++++++++++++++++++++++++----- 1 file changed, 43 insertions(+), 6 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 191e2b7..dd679fd 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -937,7 +937,18 @@ impl HostList { } std::collections::hash_map::Entry::Occupied(mut o) => { let before = std::mem::replace(&mut o.get_mut().1, wanted); - (before != wanted).then(|| (shadow.buffer.clone(), before)) + if before != wanted { + tracing::debug!( + list = format_args!("{:#x}", self.list.as_raw() as usize), + resource = format_args!("{:#x}", shadow.buffer.as_raw() as usize), + before, + wanted, + "shadow state transition recorded" + ); + Some((shadow.buffer.clone(), before)) + } else { + None + } } } } @@ -951,16 +962,32 @@ impl HostList { ) { let mut states = self.shadow_states.lock().unwrap_or_else(|e| e.into_inner()); let key = std::sync::Arc::as_ptr(shadow) as usize; + let previous = states + .get(&key) + .map(|entry| entry.1); states .entry(key) .and_modify(|entry| entry.1 = state) .or_insert_with(|| (state, state, shadow.clone())); + tracing::debug!( + list = format_args!("{:#x}", self.list.as_raw() as usize), + resource = format_args!("{:#x}", shadow.buffer.as_raw() as usize), + previous, + state, + "shadow state set by helper" + ); } /// Buffers decay to COMMON after a completed ExecuteCommandLists call. fn decay_shadows(&self) { let states = self.shadow_states.lock().unwrap_or_else(|e| e.into_inner()); - for (_, (_, _, shadow)) in states.iter() { + for (_, (_, last, shadow)) in states.iter() { + tracing::debug!( + list = format_args!("{:#x}", self.list.as_raw() as usize), + resource = format_args!("{:#x}", shadow.buffer.as_raw() as usize), + last, + "shadow state decayed to COMMON" + ); shadow.state.store(0, Ordering::Relaxed); } } @@ -987,13 +1014,23 @@ impl HostList { let shadows = self.shadow_states.lock().unwrap_or_else(|e| e.into_inner()); barriers.extend(shadows.values().filter_map(|(first, last, shadow)| { let real = shadow.state.swap(*last, Ordering::Relaxed); - (real != *first).then(|| { - transition( + if real != *first { + tracing::debug!( + list = format_args!("{:#x}", self.list.as_raw() as usize), + resource = format_args!("{:#x}", shadow.buffer.as_raw() as usize), + real, + first, + last, + "shadow submission prelude transition" + ); + Some(transition( &shadow.buffer, D3D12_RESOURCE_STATES(real as i32), D3D12_RESOURCE_STATES(*first as i32), - ) - }) + )) + } else { + None + } })); if barriers.is_empty() { return None; From ed34099f830656f40ee84ccd82d25b00f74db0ea Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Tue, 24 Nov 2026 18:55:04 +0000 Subject: [PATCH 45/49] wave-5 fixups: rsrc2/HostShader fields in tests, clippy lints Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/draw.rs | 7 ++----- crates/victory-gpu/src/host.rs | 18 +++++++++--------- crates/victory-gpu/src/pipeline/host.rs | 1 - crates/victory-gpu/src/shader_cache.rs | 4 +++- crates/victory-gpu/src/shadow.rs | 6 +++--- crates/victory-gpu/src/texture.rs | 11 +++++++++-- crates/victory-shader/src/emit/mod.rs | 5 ++++- crates/victory-shader/src/emit/validator.rs | 5 ++++- 8 files changed, 34 insertions(+), 23 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 3108532..aa88842 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -161,11 +161,7 @@ fn root_view(list: &HostList, address: u64, srv: bool) -> Option { .min(if srv { 1 << 20 } else { 1 << 16 }); let gpu = shadow.gpu(address); if srv || gpu % 256 == 0 { - crate::list::ensure_shadow_state( - list, - &shadow, - if srv { 0x40 | 0x80 } else { 0x1 }, - ); + crate::list::ensure_shadow_state(list, &shadow, if srv { 0x40 | 0x80 } else { 0x1 }); shadow.refresh(list, address, len); return Some(gpu); } @@ -1586,6 +1582,7 @@ mod tests { assert_eq!(state.fresh_tables[&accepted_key], accepted_first); drop(state); crate::object::slot:: u32>(title_heap, 0x10)(title_heap); + } } #[cfg(all(test, feature = "diagnostics"))] diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index a398ef3..14ca868 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -327,10 +327,8 @@ type Note = (String, Option<(u64, u64)>); type States = std::collections::HashMap)>; -type ShadowStates = std::collections::HashMap< - usize, - (u32, u32, std::sync::Arc), ->; +type ShadowStates = + std::collections::HashMap)>; /// Whether GPU timestamp diagnostics are enabled (`VICTORY_GPU_TIMING`). #[cfg(feature = "diagnostics")] @@ -539,6 +537,7 @@ impl Host { group.push(list.list.cast().ok()); *submitted += 1; + #[cfg(feature = "diagnostics")] let list_started = std::time::Instant::now(); // SAFETY: closed lists; the fence and event are ours. unsafe { @@ -938,7 +937,10 @@ impl HostList { .lock() .unwrap_or_else(|e| e.into_inner()) .clear(); - self.shadow_states.lock().unwrap_or_else(|e| e.into_inner()).clear(); + self.shadow_states + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clear(); self.pipelines .lock() .unwrap_or_else(|e| e.into_inner()) @@ -1026,9 +1028,7 @@ impl HostList { ) { let mut states = self.shadow_states.lock().unwrap_or_else(|e| e.into_inner()); let key = std::sync::Arc::as_ptr(shadow) as usize; - let previous = states - .get(&key) - .map(|entry| entry.1); + let previous = states.get(&key).map(|entry| entry.1); states .entry(key) .and_modify(|entry| entry.1 = state) @@ -1045,7 +1045,7 @@ impl HostList { /// Buffers decay to COMMON after a completed ExecuteCommandLists call. fn decay_shadows(&self) { let states = self.shadow_states.lock().unwrap_or_else(|e| e.into_inner()); - for (_, (_, last, shadow)) in states.iter() { + for (_, last, shadow) in states.values() { tracing::debug!( list = format_args!("{:#x}", self.list.as_raw() as usize), resource = format_args!("{:#x}", shadow.buffer.as_raw() as usize), diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index ad663d4..83ea69a 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -1115,7 +1115,6 @@ mod tests { assert_eq!(ba, bb); } - fn read_subobject( state: &mut GraphicsState, kind: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 8e0f1cb..bbbb090 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -429,7 +429,9 @@ mod tests { StaticSampler::from_words([0, 0, 0, 0]), ], root_cbvs: vec![0, 1, 255], - root_srvs: Vec::new(), + root_srvs: vec![2], + address_map: true, + descriptor_words: true, } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 4a4560f..9dd397f 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -16,7 +16,7 @@ //! indexed heaps keep what their first use copied. use std::collections::BTreeMap; -use std::sync::atomic::{AtomicU32, AtomicU8, Ordering}; +use std::sync::atomic::{AtomicU8, AtomicU32, Ordering}; use std::sync::{Arc, Mutex}; use windows::Win32::Graphics::Direct3D12::ID3D12Resource; @@ -422,7 +422,7 @@ pub(crate) fn find(address: u64, len: u64) -> Option> { 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 Some(host) = host() else { return None }; + let host = host()?; let Some((buffer, data)) = host.shared_buffer(len.next_multiple_of(1 << 16)) else { tracing::warn!( address = format_args!("{:#x}", key.0), @@ -487,7 +487,7 @@ fn loose(address: u64, end: u64) -> Option> { if let Some(shadow) = map.get(&(start, len)) { return Some(shadow.clone()); } - let Some(host) = host() else { return None }; + let host = host()?; let Some((buffer, data)) = host.shared_buffer(len) else { tracing::warn!( address = format_args!("{start:#x}"), diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index c01bb6a..7371d5d 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -124,7 +124,11 @@ static STAGING: Mutex>>> = Mutex::new(None); #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum HostWrite { /// Write-watched memory: the write-watch asking when the host copy happened. - Watched { start: usize, end: usize, asked: u64 }, + Watched { + start: usize, + end: usize, + asked: u64, + }, /// Non-watched memory (physical-page view): content hash at the host copy. Hashed { memory: usize, @@ -589,7 +593,10 @@ mod tests { let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); map.get_or_insert_with(HashMap::new).insert(key, state); } - assert!(still_host_written(key), "untouched memory stays host-written"); + assert!( + still_host_written(key), + "untouched memory stays host-written" + ); // SAFETY: committed page of ours. unsafe { ptr.write(0x42) }; assert!( diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 3b58022..a53d4d2 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -369,7 +369,9 @@ fn psv_interps( pos += 4; if res_cnt > 0 { let res_sz = u32_at(d, pos).ok()? as usize; - pos = pos.checked_add(4)?.checked_add(res_cnt.checked_mul(res_sz)?)?; + pos = pos + .checked_add(4)? + .checked_add(res_cnt.checked_mul(res_sz)?)?; } let str_len = u32_at(d, pos).ok()? as usize; pos = pos.checked_add(4)?.checked_add(str_len)?; @@ -1327,6 +1329,7 @@ mod tests { pack2: false, row2: 0, }], + rsrc2: 0, input_addr: 0, db_shader_control: 0, patches: vec![], diff --git a/crates/victory-shader/src/emit/validator.rs b/crates/victory-shader/src/emit/validator.rs index 088a799..5951f8a 100644 --- a/crates/victory-shader/src/emit/validator.rs +++ b/crates/victory-shader/src/emit/validator.rs @@ -620,7 +620,10 @@ mod tests { fn load_error_has_no_trailing_nul() { let missing = std::path::Path::new(r"Z:\nonexistent\victory_missing_dxil_test.dll"); let err = Validator::load(Some(missing)).err().unwrap(); - assert!(!err.contains('\0'), "error string had trailing NUL: {err:?}"); + assert!( + !err.contains('\0'), + "error string had trailing NUL: {err:?}" + ); assert!(err.contains("victory_missing_dxil_test.dll")); } From 358c4b10092215d36470292bf17de4104a776a72 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Tue, 24 Nov 2026 18:56:33 +0000 Subject: [PATCH 46/49] Strip UTF-8 BOMs from ported docs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- docs/compatibility.md | 2 +- docs/debugging.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/compatibility.md b/docs/compatibility.md index eeccaed..0c2ac78 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -1,4 +1,4 @@ -# Compatibility investigation: Grand Theft Auto VI +# Compatibility investigation: Grand Theft Auto VI **Status:** Experimental; not confirmed playable **Last updated:** 2026-11-24 diff --git a/docs/debugging.md b/docs/debugging.md index d984b43..cfe5788 100644 --- a/docs/debugging.md +++ b/docs/debugging.md @@ -1,4 +1,4 @@ -# D3D12 debugging notes +# D3D12 debugging notes This document records diagnostic procedures and observations from the experimental VIctory compatibility investigation. From 5cd22b9169cb38865151c7749eb058c66bc65fd5 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Tue, 24 Nov 2026 18:59:04 +0000 Subject: [PATCH 47/49] Enumerate runs for diagnostics slow-list reporting Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/host.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 14ca868..1fc7c37 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -529,7 +529,8 @@ impl Host { // submitted. Preparing all preludes up front is incorrect when two // runs use the same shadow: the later prelude would assume a state // transition that the earlier command list has not executed yet. - for list in runs { + #[allow(unused_variables)] + for (i, list) in runs.iter().enumerate() { let mut group: Vec> = Vec::with_capacity(2); if let Some(prelude) = list.prelude() { group.push(Some(prelude)); From cfdf22f04e6b0ba790cb42a11f8eef8b532c4fe9 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Tue, 24 Nov 2026 19:03:17 +0000 Subject: [PATCH 48/49] Align PSV0/signature tests with validator-exact encoding (no name dedup, row-only sort) Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-shader/src/emit/container.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs index cad58c5..9e5e4b0 100644 --- a/crates/victory-shader/src/emit/container.rs +++ b/crates/victory-shader/src/emit/container.rs @@ -565,8 +565,8 @@ mod tests { let input = signature(&elements, true); let output = signature(&elements, false); let rows = [ - [0, 184, 8, 0, 2, 1, 0x0203, 0], [0, 168, 7, 0, 3, 1, 0x040c, 0], + [0, 184, 8, 0, 2, 1, 0x0203, 0], [0, 174, 0, 64, 3, 2, 0x0f0f, 0], [0, 174, 1, 64, 3, 3, 0x0f0f, 0], [0, 190, 0, 65, 3, u32::MAX, 0x0101, 0], @@ -575,7 +575,7 @@ mod tests { assert_eq!(words(&output[..8]), [5, 8]); assert_eq!(&input[168..], b"COLOR\0SV_Target\0COLOR\0SV_Depth\0"); assert_eq!(&output[168..], &input[168..]); - for (i, (row, output_mask)) in rows.into_iter().zip([0x0d, 0x0b, 0, 0, 0x0e]).enumerate() { + for (i, (row, output_mask)) in rows.into_iter().zip([0x0b, 0x0d, 0, 0, 0x0e]).enumerate() { let start = 8 + 32 * i; assert_eq!(words(&input[start..start + 32]), row); let mut expected = row; @@ -648,16 +648,16 @@ mod tests { assert_eq!(&bytes[28..40], &[1, 0, 0, 0, 1, 1, 0, 1, 9, 0, 0, 0]); assert_eq!( words(&bytes[52..112]), - [2, 24, 1, 6, 9, 9, 14, 0, 2, 7, 2, 2, 13, 0, 8] + [2, 24, 1, 6, 9, 9, 14, 0, 2, 7, 2, 2, 13, 0, 12] ); - assert_eq!(&bytes[112..120], b"\0COLOR\0\0"); - assert_eq!(words(&bytes[120..132]), [1, 3, 16]); + assert_eq!(&bytes[112..124], b"\0COLOR\0OR\0\0\0"); + assert_eq!(words(&bytes[124..136]), [1, 3, 16]); assert_eq!( - words(&bytes[132..164]), - [1, 0, 0x0052_0001, 0x0203, 4, 0, 0x0051_0801, 3] + words(&bytes[136..168]), + [1, 0, 0x0052_0001, 0x0203, 7, 0, 0x0051_0801, 3] ); assert_eq!( - words(&bytes[164..]), + words(&bytes[168..]), [u32::MAX, 3, u32::MAX, 3, u32::MAX, 3, 0, 0] ); } From 51d121bffae1c7fd930fbc3961648207157978a1 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Tue, 24 Nov 2026 19:07:19 +0000 Subject: [PATCH 49/49] Keep and drain write-watched test allocations so stale watch state cannot flake tests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/texture.rs | 10 ++++++---- crates/victory-gpu/src/watch.rs | 11 ++++++++--- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 7371d5d..952c201 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -572,11 +572,12 @@ mod tests { #[test] fn host_written_clears_after_write_watched_memory_is_written() { use windows_sys::Win32::System::Memory::{ - MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, }; const MEM_WRITE_WATCH: u32 = 0x20_0000; let len = crate::watch::PAGE; - // SAFETY: a fresh write-watched allocation, freed at the end. + // SAFETY: a fresh write-watched allocation, kept (not freed: a reused + // address carries stale watch state into another test's first read). let ptr = unsafe { VirtualAlloc( std::ptr::null(), @@ -587,6 +588,9 @@ mod tests { } as *mut u8; assert!(!ptr.is_null()); let key = ptr as usize; + // Drain watch state a reused address may carry from a freed + // allocation, so the snapshot below sees a clean slate. + let _ = crate::watch::writes(key, key + len, false); let state = host_write_state(ptr, len); assert!(matches!(state, HostWrite::Watched { .. })); { @@ -605,8 +609,6 @@ mod tests { ); assert!(!still_host_written(key)); forget(key); - // SAFETY: our allocation. - unsafe { VirtualFree(ptr.cast(), 0, MEM_RELEASE) }; } #[test] diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 6d29824..77043d9 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -536,7 +536,7 @@ fn writable(at: usize) -> bool { mod tests { use super::*; use windows_sys::Win32::System::Memory::{ - MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, }; const MEM_WRITE_WATCH: u32 = 0x20_0000; @@ -553,6 +553,10 @@ mod tests { } as usize; assert_ne!(p, 0); let (start, end) = (p, p + 4 * PAGE); + // A reused address can carry stale watch state (kernel bits, journal + // entries) left by a freed allocation: drain it, then ask fresh. + let _ = writes(start, end, false); + new_submission(); let (_, before) = writes(start, end, false).expect("watched"); assert!(before.is_empty()); // SAFETY: committed pages of ours. @@ -574,8 +578,9 @@ mod tests { ) .is_none() ); - // SAFETY: our allocation. - unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; + // Kept, not freed: another test given this address would see its + // watch state as its own first read (the kernel's bits and the + // journal's entries outlive the allocation they were made for). } /// Under Wine, a write after a range was asked about in a submission