From 450e25b883f25dfcfe6172f4db82b3957b293385 Mon Sep 17 00:00:00 2001 From: mint17 <52134356+mint17@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:36:11 +1100 Subject: [PATCH] gpu: fix alias liveness check, Memory::heaps drop eviction, and stream Bytecode UB Address three memory-safety and correctness issues in crates/victory-gpu: - Fix resource::is_aliased to verify target liveness (object::is_alive, refs.load(Acquire) > 0) under TARGETS_AT rather than treating dying refs == 0 targets as aliased, and harden object::add_ref_alive with checked_add(1) overflow protection. - Evict Memory::heaps entry on Heap::drop (adapted from Marvisak#2234): add memory::release_heap keyed by HostHeap pointer address and invoke it in Drop for Heap strictly after dropping the SHADER_HEAPS write guard. - Fix unaligned pipeline stream Bytecode read and guard truncated stream subobjects in pipeline::create_stream (adapted from Marvisak#2301) via read_unaligned(), saturating_sub, and checked_add bounds checks. - Add RAII-guarded unit and D3D12 regression tests for all three fixes. --- crates/victory-gpu/src/descriptor.rs | 79 ++++++++++++++++++- crates/victory-gpu/src/memory.rs | 14 ++++ crates/victory-gpu/src/object.rs | 39 +++++++++- crates/victory-gpu/src/pipeline.rs | 96 ++++++++++++++++++++++- crates/victory-gpu/src/resource.rs | 110 ++++++++++++++++++++++----- 5 files changed, 312 insertions(+), 26 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 2176cbf60..a654b4a67 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -898,8 +898,13 @@ pub(crate) fn constant_slot( impl Drop for Heap { fn drop(&mut self) { let at = std::ptr::from_ref::(self) as usize; - let mut heaps = SHADER_HEAPS.write().unwrap_or_else(|e| e.into_inner()); - heaps.retain(|&(_, _, h)| h != at); + { + let mut heaps = SHADER_HEAPS.write().unwrap_or_else(|e| e.into_inner()); + heaps.retain(|&(_, _, h)| h != at); + } + if let Some(Some(host)) = self.host.get() { + crate::memory::release_heap(std::ptr::from_ref(host) as usize); + } } } @@ -2068,6 +2073,76 @@ static FUNCTIONS: Table<24> = { Table(f) }; +#[cfg(all(test, windows))] +mod safety_tests { + use super::*; + use crate::object::S_OK; + + #[test] + fn released_view_heap_evicts_memory_heap_entry() { + #[repr(C)] + struct Extended(HeapDesc, Placement); + + struct HeapGuard(This); + impl HeapGuard { + fn release_now(&mut self) -> u32 { + let ptr = std::mem::replace(&mut self.0, std::ptr::null()); + if ptr.is_null() { 0 } else { release(ptr) } + } + } + impl Drop for HeapGuard { + fn drop(&mut self) { + let _ = self.release_now(); + } + } + + let Some(host) = crate::host::host() else { + return; + }; + let Ok(list) = host.new_list() else { + return; + }; + let extended = Extended( + HeapDesc { + kind: VIEWS_KIND, + count: 64, + flags: SHADER_VISIBLE, + nodes: 1, + }, + Placement { + address: 0, + size: 0, + }, + ); + let mut raw = std::ptr::null(); + assert_eq!( + create_heap(std::ptr::null(), &extended.0, &HEAP_IIDS[0], &mut raw), + S_OK + ); + let mut h = HeapGuard(raw); + let Some(host_heap) = heap(h.0).host() else { + return; + }; + let key = std::ptr::from_ref(host_heap) as usize; + if crate::memory::ready( + &list, + host_heap, + &[], + &[], + &[], + crate::memory::Use::Reads, + None, + ) + .is_none() + { + return; + } + assert!(crate::memory::has_heap(key)); + assert_eq!(h.release_now(), 0); + assert!(!crate::memory::has_heap(key)); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 78faa10f8..738880801 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -1105,6 +1105,20 @@ pub(crate) fn ready( }) } +/// Drops the per-heap slot record when its host view heap is released. +pub(crate) fn release_heap(key: usize) { + let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(m) = guard.as_mut() { + m.heaps.remove(&key); + } +} + +#[cfg(test)] +pub(crate) fn has_heap(key: usize) -> bool { + let guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); + guard.as_ref().is_some_and(|m| m.heaps.contains_key(&key)) +} + /// `VICTORY_BVH_TRACE=1`: the sizes the builder is asked for (its program of /// one thread that stores a structure's compacted size) and when title memory /// has them, and the copies to a place of that size. diff --git a/crates/victory-gpu/src/object.rs b/crates/victory-gpu/src/object.rs index 736e6501e..700682fc7 100644 --- a/crates/victory-gpu/src/object.rs +++ b/crates/victory-gpu/src/object.rs @@ -72,12 +72,25 @@ pub(crate) extern "system" fn add_ref(this: This) -> u32 { } /// A reference more to `this` only while it still has one: `false` if it is -/// being released (its count reached 0). From CuteBooty/victory-8gb (after -/// fxceless, victory-fork d4a528ba), for [`crate::resource::alias_of`]. +/// being released (its count reached 0) or would overflow `u32::MAX`. From +/// CuteBooty/victory-8gb (after fxceless, victory-fork d4a528ba), for +/// [`crate::resource::alias_of`]. +#[cfg_attr(not(windows), allow(dead_code))] pub(crate) fn add_ref_alive(this: This) -> bool { // SAFETY: `this` is one of our objects, not freed yet. let refs = &unsafe { &*this }.refs; - refs.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| (n > 0).then(|| n + 1)).is_ok() + refs.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| { + if n > 0 { n.checked_add(1) } else { None } + }) + .is_ok() +} + +/// Whether `this` still has at least one live reference: `false` once its +/// count has reached 0 and it is being released. +#[cfg_attr(not(windows), allow(dead_code))] +pub(crate) fn is_alive(this: This) -> bool { + // SAFETY: `this` is one of our objects, not freed yet. + unsafe { &*this }.refs.load(Ordering::Acquire) > 0 } pub(crate) extern "system" fn release(this: This) -> u32 { @@ -570,4 +583,24 @@ mod tests { assert!(found.is_null()); slot:: u32>(fence, 0x10)(fence); } + + #[test] + fn add_ref_alive_and_is_alive_check_refcount_bounds() { + static TABLE: Table<0> = Table([]); + let object = Object::new(&TABLE); + let this: This = &object; + assert!(!is_alive(this)); + assert!(!add_ref_alive(this)); + assert_eq!(object.refs.load(Ordering::Relaxed), 0); + + object.refs.store(1, Ordering::Relaxed); + assert!(is_alive(this)); + assert!(add_ref_alive(this)); + assert_eq!(object.refs.load(Ordering::Relaxed), 2); + + object.refs.store(u32::MAX, Ordering::Relaxed); + assert!(is_alive(this)); + assert!(!add_ref_alive(this)); + assert_eq!(object.refs.load(Ordering::Relaxed), u32::MAX); + } } diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index f8cd62849..defaa56b5 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -713,7 +713,7 @@ pub(crate) extern "system" fn create_stream( #[cfg(windows)] let mut graphics = host::GraphicsState::default(); let mut at = 0; - while at + 8 <= desc.size { + while desc.size.saturating_sub(at) >= 8 { // SAFETY: inside the stream the title passes. let kind = unsafe { desc.stream.add(at).cast::().read_unaligned() }; let Some((size, stage)) = subobject(kind) else { @@ -724,10 +724,20 @@ pub(crate) extern "system" fn create_stream( ); break; }; + if at.checked_add(size).is_none_or(|end| end > desc.size) { + tracing::warn!( + kind, + at, + size, + stream = desc.size, + "truncated pipeline subobject; the rest is ignored" + ); + break; + } if let Some(stage) = stage { - // SAFETY: a shader subobject has its bytecode at +8. - let code = unsafe { &*desc.stream.add(at + 8).cast::() }; - shaders.extend(copy(stage, code)); + // SAFETY: a shader subobject has its bytecode at +8 (may be unaligned). + let code = unsafe { desc.stream.add(at + 8).cast::().read_unaligned() }; + shaders.extend(copy(stage, &code)); } #[cfg(windows)] // SAFETY: a whole subobject of this kind lies at `at`. @@ -919,3 +929,81 @@ mod tests { } } } + +#[cfg(test)] +mod safety_tests { + use super::*; + use crate::object::{S_OK, slot}; + + struct PipelineGuard(This); + impl PipelineGuard { + fn release_now(&mut self) -> u32 { + let ptr = std::mem::replace(&mut self.0, std::ptr::null()); + if ptr.is_null() { + 0 + } else { + slot:: u32>(ptr, 0x10)(ptr) + } + } + } + impl Drop for PipelineGuard { + fn drop(&mut self) { + let _ = self.release_now(); + } + } + + fn shaders(p: This) -> Vec<(&'static str, Vec)> { + pipeline(p) + .shaders + .iter() + .map(|s| (s.stage, s.container.clone())) + .collect() + } + + #[test] + fn unaligned_stream_yields_its_shaders() { + let vs = [1u8, 2, 3, 4]; + let mut backing = [0u64; 5]; + // SAFETY: `backing` is 40 contiguous bytes; slicing at +1 leaves 39 + // bytes and guarantees non-8-byte alignment. + let bytes = unsafe { + std::slice::from_raw_parts_mut(backing.as_mut_ptr().cast::(), size_of_val(&backing)) + }; + let stream = &mut bytes[1..25]; + assert_ne!(stream.as_ptr() as usize % 8, 0); + stream[0..4].copy_from_slice(&1u32.to_le_bytes()); + stream[8..16].copy_from_slice(&(vs.as_ptr() as usize).to_le_bytes()); + stream[16..24].copy_from_slice(&vs.len().to_le_bytes()); + + let desc = StreamDesc { + size: stream.len(), + stream: stream.as_ptr(), + }; + let mut raw = std::ptr::null(); + assert_eq!( + create_stream(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut raw), + S_OK + ); + let mut p = PipelineGuard(raw); + assert_eq!(shaders(p.0), [("vertex", vs.to_vec())]); + assert_eq!(p.release_now(), 0); + } + + #[test] + fn truncated_shader_subobject_does_not_read_past_stream() { + let mut stream = [0u8; 16]; + stream[0..4].copy_from_slice(&1u32.to_le_bytes()); + let desc = StreamDesc { + size: stream.len(), + stream: stream.as_ptr(), + }; + let mut raw = std::ptr::null(); + assert_eq!( + create_stream(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut raw), + S_OK + ); + let mut p = PipelineGuard(raw); + assert!(shaders(p.0).is_empty()); + assert_eq!(p.release_now(), 0); + } +} diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 597ede594..0a9225dfc 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1531,12 +1531,12 @@ pub(crate) fn alias_of(this: This) -> Option { alias_with(this, |other| crate::object::add_ref_alive(other).then(|| Held(other))).flatten() } -/// Whether [`alias_of`] would find a texture for `this`, for callers that -/// only ask: nothing is pinned, so none of them can end up dropping the -/// texture's last reference. +/// Whether [`alias_of`] would find a live texture for `this`, for callers +/// that only ask: checks liveness under the table lock without bumping or +/// dropping the texture's reference count. #[cfg(windows)] pub(crate) fn is_aliased(this: This) -> bool { - alias_with(this, |_| ()).is_some() + alias_with(this, crate::object::is_alive).unwrap_or(false) } /// The lookup behind [`alias_of`]: `found` runs on the texture while the @@ -5274,40 +5274,116 @@ float4 lit() : SV_Target { return 1.0; } /// is held while the caller copies it: the title may let go of its own /// reference between the lookup and the copy (or a recording thread /// may), and the copy still needs it. - #[cfg(all(windows, feature = "diagnostics"))] + #[cfg(windows)] #[test] fn an_alias_source_is_held_after_the_title_releases_it() { use std::sync::atomic::Ordering::Relaxed; + struct ResourceGuard(This); + impl ResourceGuard { + fn release_now(&mut self) -> u32 { + let ptr = std::mem::replace(&mut self.0, std::ptr::null()); + if ptr.is_null() { 0 } else { resource_release(ptr) } + } + } + impl Drop for ResourceGuard { + fn drop(&mut self) { + let _ = self.release_now(); + } + } + let Some(_host) = crate::host::host() else { return; }; let null = std::ptr::null(); - let mut source = null; - let mut view = null; + let mut raw_source = null; + let mut raw_view = null; let source_desc = ResourceDesc { flags: 4, ..texture(4, 4, 42, 1) }; assert_eq!( - create_committed(null, &PROPERTIES, 0, &source_desc, 0, null.cast(), &RESOURCE_IIDS[0], &mut source), + create_committed(null, &PROPERTIES, 0, &source_desc, 0, null.cast(), &RESOURCE_IIDS[0], &mut raw_source), S_OK ); + let mut source = ResourceGuard(raw_source); assert_eq!( - create_at_address(null, resource(source).data() as u64, &texture(4, 4, 67, 1), 0, null.cast(), &RESOURCE_IIDS[0], &mut view), + create_at_address(null, resource(source.0).data() as u64, &texture(4, 4, 67, 1), 0, null.cast(), &RESOURCE_IIDS[0], &mut raw_view), S_OK ); - resource(view).host.placed.store(true, Relaxed); - assert!(is_aliased(view), "the lookup alone finds it too"); - let held = alias_of(view).expect("an alias source"); - assert_eq!(held.get(), source); + let mut view = ResourceGuard(raw_view); + resource(view.0).host.placed.store(true, Relaxed); + assert!(is_aliased(view.0), "the lookup alone finds it too"); + let held = alias_of(view.0).expect("an alias source"); + assert_eq!(held.get(), source.0); + let source_addr = source.0 as usize; // The title lets go: the pin, not the title's reference, keeps the // source (and the copy about to be made from it) alive. - resource_release(source); + assert_eq!(source.release_now(), 1); + assert!(is_aliased(view.0), "the pinned source is still live"); assert!(host_resource(held.get()).is_some(), "a held source is still copyable"); - assert!(textures().contains(&(source as usize)), "the held source is not freed"); + assert!(textures().contains(&source_addr), "the held source is not freed"); drop(held); - assert!(!textures().contains(&(source as usize)), "the last reference frees it"); - resource_release(view); + assert!(!textures().contains(&source_addr), "the last reference frees it"); + assert!(!is_aliased(view.0)); + assert!(alias_of(view.0).is_none()); + assert_eq!(view.release_now(), 0); + } + + #[cfg(windows)] + #[test] + fn is_aliased_ignores_dying_target_with_zero_refcount() { + use std::sync::atomic::Ordering::Relaxed; + + struct ResourceGuard(This); + impl ResourceGuard { + fn release_now(&mut self) -> u32 { + let ptr = std::mem::replace(&mut self.0, std::ptr::null()); + if ptr.is_null() { 0 } else { resource_release(ptr) } + } + } + impl Drop for ResourceGuard { + fn drop(&mut self) { + let _ = self.release_now(); + } + } + + struct RefRestore(This); + impl Drop for RefRestore { + fn drop(&mut self) { + crate::object::add_ref(self.0); + } + } + + let null = std::ptr::null(); + let mut raw_source = null; + let mut raw_view = null; + let source_desc = ResourceDesc { + flags: 4, + ..texture(4, 4, 42, 1) + }; + assert_eq!( + create_committed(null, &PROPERTIES, 0, &source_desc, 0, null.cast(), &RESOURCE_IIDS[0], &mut raw_source), + S_OK + ); + let mut source = ResourceGuard(raw_source); + assert_eq!( + create_at_address(null, resource(source.0).data() as u64, &texture(4, 4, 67, 1), 0, null.cast(), &RESOURCE_IIDS[0], &mut raw_view), + S_OK + ); + let mut view = ResourceGuard(raw_view); + resource(view.0).host.placed.store(true, Relaxed); + assert!(is_aliased(view.0)); + { + // Simulate the window between `release_boxed` dropping `refs` to 0 + // and `Resource::drop` removing the entry from `TARGETS_AT`. + assert_eq!(crate::object::release(source.0), 0); + let _restore = RefRestore(source.0); + assert!(!is_aliased(view.0), "dying target must not appear aliased"); + assert!(alias_of(view.0).is_none(), "dying target must not be pinned"); + } + assert!(is_aliased(view.0)); + assert_eq!(source.release_now(), 0); + assert_eq!(view.release_now(), 0); } }