diff --git a/d3d12/crates/leonida-gpu/src/descriptor/host.rs b/d3d12/crates/leonida-gpu/src/descriptor/host.rs index 79efb896f9..84fb2b4450 100644 --- a/d3d12/crates/leonida-gpu/src/descriptor/host.rs +++ b/d3d12/crates/leonida-gpu/src/descriptor/host.rs @@ -3864,12 +3864,13 @@ impl HostHeap { pub(crate) fn make_at(&self, index: u32, view: &View) { let kept = make_twinned_info(view, self.at(index), self.twin(index)).0; let bias = take_twin_bias(); - if kept.is_none() { + let is_made = kept.is_some(); + self.write_stride(index, if is_made { with_twin_bias(view_stride_word(view), bias) } else { 0 }); + if !is_made { null_for(view, self.at(index)); } self.put(index); - self.twin_made(index, kept.is_some() && twinned(view)); - self.write_stride(index, if kept.is_some() { with_twin_bias(view_stride_word(view), bias) } else { 0 }); + self.twin_made(index, is_made && twinned(view)); self.keep(index, kept.flatten()); } @@ -3909,11 +3910,13 @@ impl HostHeap { flush_listed(); let (s0, s1) = (views.slot(at), views.slot(at + 1)); let (kept, cast_serial) = make_twinned_info(&view, s0, Some(s1)); + let bias = take_twin_bias(); let Some(kept) = kept else { null_for(&view, s0); if let Some(existing) = views.made.get_mut(&words) { existing.kept = None; existing.twin = false; + existing.stride_word = 0; existing.listed.ready = (0, 0, false); } views.cast_serials.insert(words, u64::MAX); @@ -3921,6 +3924,7 @@ impl HostHeap { }; if let Some(existing) = views.made.get_mut(&words) { existing.kept = kept; + existing.stride_word = with_twin_bias(view_stride_word(&view), bias); existing.listed.ready = (0, 0, false); match cast_serial { Some(cs) => { @@ -3959,9 +3963,9 @@ impl HostHeap { let made = &views.made[&words]; self.copy_listed(index, views.slot(made.at)); if made.twin && twins { + self.write_stride(index, made.stride_word); self.copy_listed(self.raw + index, views.slot(made.at + 1)); self.twins[index as usize].store(true, std::sync::atomic::Ordering::Relaxed); - self.write_stride(index, made.stride_word); } else { self.clear_twin(index); self.write_stride(index, with_twin_bias(made.stride_word, 0)); @@ -4357,6 +4361,12 @@ impl HostHeap { self.put(index); host.device.CreateShaderResourceView(buffer, Some(&raw), twin); } + let mark = if leonida_shader::emit::constant_marks() { + leonida_shader::emit::SLOT_STRIDE_CONSTANT + } else { + 0 + }; + self.write_stride(index, mark); self.twin_made(index, true); self.keep_ref(index, Some(buffer)); true @@ -4672,18 +4682,18 @@ impl HostHeap { make_twinned_info(&view, self.at(index), self.twin(index)) }; let bias = take_twin_bias(); - if kept.is_none() && !self.sampler { - null_for(&view, self.at(index)); - } - if kept.is_some() || !self.sampler { - self.put(index); - } - self.twin_made(index, kept.is_some() && twinned(&view)); let is_made = kept.is_some(); if is_made && bias != 0 { - // (`note_buffer` wrote the word without it.) + // (`note_buffer` wrote the word without it: write before publishing `put`/`twin_made`.) self.write_stride(index, with_twin_bias(view_stride_word(&view), bias)); } + if !is_made && !self.sampler { + null_for(&view, self.at(index)); + } + if is_made || !self.sampler { + self.put(index); + } + self.twin_made(index, is_made && twinned(&view)); self.keep(index, kept.flatten()); self.note_cast_serial(index, cast_serial.filter(|&cs| is_made || cs != 0)); self.quick_is(index, if later || cast_serial.is_some() { 0 } else { key }); @@ -5219,14 +5229,14 @@ fn with_twin_bias(word: u32, bias: u32) -> u32 { /// For a raw twin at `twin` showing from `start` (GPU address) `bytes`, /// `by` bytes before its view ([`twin_window`]): moved to the view -/// ([`move_raw`]) where it can be, else kept with a bias ([`twin_bias`]), -/// else made null. +/// ([`move_raw`]) where it can be, else kept with a dword-aligned bias +/// ([`twin_bias`]), else made null. fn settle_twin(twin: D3D12_CPU_DESCRIPTOR_HANDLE, start: u64, bytes: u32, by: u32) { use std::sync::atomic::Ordering::Relaxed; if by == 0 || (staged(false, 1).is_some_and(|s| s.ptr == twin.ptr) && move_raw(twin, start, bytes, by)) { return; } - if twin_bias() && by < 16 && by < bytes { + if twin_bias() && by < 16 && by.is_multiple_of(4) && by < bytes { TWINS[3].fetch_add(1, Relaxed); TWIN_BIAS.with(|b| b.set(by)); } else { @@ -5287,11 +5297,11 @@ fn twin_window(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bo if end <= start { return None; } - let dwords = u32::try_from((end - from) / 4).ok()?; + let bytes = u32::try_from(end - from).ok()?; if from != start { TWINS[1].fetch_add(1, Relaxed); } - Some((from / 4, dwords, (start - from) as u32)) + Some((from / 4, bytes / 4, (start - from) as u32)) } fn buffer_srv( diff --git a/d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs b/d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs index 675dc31f15..24da6bf47a 100644 --- a/d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs +++ b/d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs @@ -282,3 +282,175 @@ fn dump_buffer_view_descriptor_bytes() { ); } } + +/// Sub-dword unaligned typed buffer views (`by % 4 != 0`, such as `R16_UINT` at an odd element or +/// `R8_UINT` off 4 bytes) must not keep a misaligned raw twin or record an unaligned bias in +/// `strides[slot]`; dword-aligned views (`by` in `[4, 8, 12]`) keep their biased twins; and +/// `constant_raw_at` clears any prior bias when recycling a dynamic slot. +#[test] +fn sub_dword_views_null_twins_and_recycled_raw_cbv_clears_bias() { + if !twin_bias() { + return; + } + const SIZE: u64 = 4096; + let Some(host) = host() else { return }; + let mut heap = HostHeap::new(false, 4).expect("a host view heap"); + if heap.raw == 0 { + // Portable hosts (1,000,000-descriptor cap) still have room inside this test's small heap + // to exercise the exact twin-slot and stride-word machinery. + heap.raw = 64; + heap.twins = (0..32) + .map(|_| std::sync::atomic::AtomicBool::new(false)) + .collect(); + } + let first = heap.dynamic(8).expect("dynamic descriptor slots"); + assert!((first + 8) <= heap.twins.len() as u32); + + let title = Box::new([0u32; SIZE as usize / 4]); + let address = title.as_ptr() as u64; + struct Registration(u64); + impl Drop for Registration { + fn drop(&mut self) { + crate::shadow::unregister(self.0 as usize, self.0); + } + } + crate::shadow::register(address as usize, address, SIZE); + let _registered = Registration(address); + let source = crate::shadow::find(address, SIZE).expect("the registered buffer's host copy"); + let (target, result) = host.shared_buffer(SIZE).expect("a mapped write target"); + let values: [u32; 16] = std::array::from_fn(|i| 0x4567_8000 + i as u32); + // SAFETY: live mapped buffer of SIZE bytes. + unsafe { + let mut data = std::ptr::null_mut(); + source.buffer.Map(0, None, Some(&mut data)).expect("map source"); + data.cast::<[u32; 16]>().write(values); + source.buffer.Unmap(0, None); + } + + let word = |h: &HostHeap, slot: u32| { + let (_, _, data) = h.strides.as_ref().expect("stride table mapping"); + // SAFETY: slot is within `SLOT_STRIDES_COUNT`. + unsafe { (*data as *const u32).add(slot as usize).read_volatile() } + }; + + let code = crate::host::compile(TRANSFER, s!("main"), s!("cs_5_1")).expect("transfer shader"); + // SAFETY: shader blob contains matching root signature. + let (root, pipeline): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { + let root = host.device.CreateRootSignature(0, &code).expect("root signature"); + let pipeline = host + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + }) + .expect("compute pipeline"); + (root, pipeline) + }; + let strides_gpu = heap.strides_gpu().expect("strides GPU address"); + let cpu = ListViews::new().expect("CPU descriptor staging"); + let uav_desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + FirstElement: 0, + NumElements: 16, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + ..Default::default() + }, + }, + }; + // SAFETY: private CPU slot and live target buffer. + unsafe { + host.device.CreateUnorderedAccessView(&target, None::<&ID3D12Resource>, Some(&uav_desc), cpu.slot(0)); + } + let out_uav_slot = first + 7; + heap.copy_from(out_uav_slot, cpu.slot(0)); + + let read_twin = |h: &HostHeap, slot: u32| -> [u32; 2] { + let list = host.new_list().expect("command list"); + // SAFETY: live heap, pipeline, and mapped result buffer. + unsafe { + result.cast::<[u32; 4]>().write([0xfeed_face; 4]); + list.list.SetDescriptorHeaps(&[Some(h.heap.clone())]); + list.list.SetComputeRootSignature(&root); + list.list.SetPipelineState(&pipeline); + list.list.SetComputeRootDescriptorTable(0, h.gpu_handle(h.raw + slot)); + list.list.SetComputeRootDescriptorTable(1, h.gpu_handle(out_uav_slot)); + let constants = [0u32, 0u32, slot]; + list.list.SetComputeRoot32BitConstants(2, 3, constants.as_ptr().cast(), 0); + list.list.SetComputeRootShaderResourceView(3, strides_gpu); + list.list.Dispatch(1, 1, 1); + list.close(); + host.execute(&[&list]); + result.cast::<[u32; 2]>().read_volatile() + } + }; + + let resource = [1, 0, 0, 0, SIZE as u32, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0]; + let mut recording = 1000u64; + let make_via_listed = |recording: &mut u64, view: View| { + let mut rec = [0u32; 8]; + crate::descriptor::record(rec.as_mut_ptr() as u64, view); + *recording += 1; + assert!(heap.make_listed(*recording, [rec[0], rec[1], rec[2]], first).is_some()); + flush_listed(); + }; + // 1. Sub-dword unaligned R16_UINT (format 57, 2 bytes) at odd FirstElement (9 -> byte 18, by = 2; + // 11 -> byte 22, by = 6; 13 -> byte 26, by = 10; 15 -> byte 30, by = 14) and R8_UINT (format 62, + // 1 byte) at FirstElement 17 (by = 1) and 19 (by = 3), both SRV and UAV. + for (format, elem_idx, by) in [(57u32, 9u32, 2u32), (57, 11, 6), (57, 13, 10), (57, 15, 14), (62, 17, 1), (62, 19, 3)] { + for unordered in [false, true] { + let mut desc = [0u32; 16]; + if unordered { + desc[..10].copy_from_slice(&[format, 1, elem_idx, 0, 8, 0, 0, 0, 0, 0]); + } else { + desc[..10].copy_from_slice(&[format, 1, 5768, 0, elem_idx, 0, 8, 0, 0, 0]); + } + (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); + make_via_listed(&mut recording, View::Placed(unordered, resource, desc)); + let bias_bits = (word(&heap, first) & leonida_shader::emit::VIEW_BIAS_MASK) + >> leonida_shader::emit::VIEW_BIAS_SHIFT; + assert_eq!( + bias_bits, 0, + "non-dword-aligned view (format {format}, by={by}, uav={unordered}) must not record an unaligned bias" + ); + if !unordered { + assert_eq!( + read_twin(&heap, first), + [0, 0], + "non-dword-aligned SRV twin (by={by}) must be null, not reading misaligned pre-view bytes" + ); + } + } + } + + // 2. Dword-aligned unaligned R32_UINT (format 42, 4 bytes) at FirstElement = 6 (byte 24, by = 8) + // keeps its biased twin and reads [values[6], values[7]], then `constant_raw_at` on the same + // slot clears the bias bits to 0. + let mut aligned8 = [0u32; 16]; + aligned8[..10].copy_from_slice(&[42, 1, 5768, 0, 6, 0, 2, 0, 0, 0]); + (aligned8[10], aligned8[11]) = (address as u32, (address >> 32) as u32); + make_via_listed(&mut recording, View::Placed(false, resource, aligned8)); + let bias_bits = (word(&heap, first) & leonida_shader::emit::VIEW_BIAS_MASK) + >> leonida_shader::emit::VIEW_BIAS_SHIFT; + assert_eq!(bias_bits, 8, "8-byte-offset R32_UINT view must record bias=8"); + assert_eq!(read_twin(&heap, first), [values[6], values[7]]); + + // Recycle `first` with `constant_raw_at` on a 256-byte-aligned address inside `source.buffer`. + let gpu_base = source.gpu(address); + assert!( + heap.constant_raw_at(first, &source.buffer, gpu_base + 256, 256), + "constant_raw_at should succeed on 16-byte-aligned GPU address" + ); + let recycled_bias = (word(&heap, first) & leonida_shader::emit::VIEW_BIAS_MASK) + >> leonida_shader::emit::VIEW_BIAS_SHIFT; + assert_eq!( + recycled_bias, 0, + "constant_raw_at must clear stale twin bias when recycling a dynamic slot" + ); +} diff --git a/d3d12/crates/leonida-shader/src/emit/lower.rs b/d3d12/crates/leonida-shader/src/emit/lower.rs index faeb2137cf..2d9a11ef4c 100644 --- a/d3d12/crates/leonida-shader/src/emit/lower.rs +++ b/d3d12/crates/leonida-shader/src/emit/lower.rs @@ -9659,11 +9659,23 @@ impl<'a> Lower<'a> { h } + /// `offset` plus `bias` in `block`, keeping 32-bit sentinel and negative + /// offsets (`u32::MAX * stride + field`, `x - 4` at `x = 0`) out of bounds + /// instead of wrapping modulo 2^32 into `[0, 16)`, the bytes before the + /// view (including across a 4-dword vector load or store). + fn add_bias(&mut self, block: usize, offset: V, bias: V) -> V { + let sum = self.s.m.bin(block, Bin::Add, offset, bias); + let ceiling = self.s.m.i32(0xFFFF_FFD0); + let oob = self.s.m.i32(0xFFFF_FFE0); + let wraps = self.s.m.cmp(block, pred::IUGT, offset, ceiling); + self.s.m.select(block, wraps, oob, sum) + } + /// `offset` plus the bias of the raw twin `h` is, if it is one /// ([`Lower::twin_handle`]), in the current block. fn biased(&mut self, h: V, offset: V) -> V { - match self.twin_bias.get(&h) { - Some(&bias) => self.s.m.bin(self.cur, Bin::Add, offset, bias), + match self.twin_bias.get(&h).copied() { + Some(bias) => self.add_bias(self.cur, offset, bias), None => offset, } } @@ -9685,7 +9697,7 @@ impl<'a> Lower<'a> { match (args.first().and_then(|h| self.twin_bias.get(h)).copied(), args.get(at)) { (Some(bias), Some(&offset)) => { let mut moved = args.to_vec(); - moved[at] = self.s.m.bin(block, Bin::Add, offset, bias); + moved[at] = self.add_bias(block, offset, bias); self.s.op(block, name, attr, ret, opcode, &moved) } _ => self.s.op(block, name, attr, ret, opcode, args), @@ -14206,7 +14218,10 @@ impl<'a> Lower<'a> { let aligned = self.s.m.bin(c, Bin::Sub, byte, within); let shift = self.s.m.bin(c, Bin::Shl, within, k3); let four = self.s.m.i32(4); + let at_end = self.s.m.i32(0xFFFF_FFFC); + let wraps = self.s.m.cmp(c, pred::EQ, aligned, at_end); let next = self.s.m.bin(c, Bin::Add, aligned, four); + let next = self.s.m.select(c, wraps, at_end, next); let ones = self.s.m.i32(if bits == 8 { 0xff } else { 0xffff }); let zero = self.s.m.i32(0); let k8 = self.s.m.i32(8); diff --git a/d3d12/crates/leonida-shader/src/emit/twin_bias_tests.rs b/d3d12/crates/leonida-shader/src/emit/twin_bias_tests.rs index 1e75c8eeac..9756ca4f91 100644 --- a/d3d12/crates/leonida-shader/src/emit/twin_bias_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/twin_bias_tests.rs @@ -157,3 +157,318 @@ fn accesses_through_twins_begin_where_the_view_does() { eprintln!("no D3D12 device; the dispatch is skipped"); } } + +fn mubuf(op: u32, vdata: u32, vaddr: u32, srsrc: u32, idxen: bool, offen: bool, offset: u32) -> [u32; 2] { + [ + 0x38 << 26 | op << 18 | u32::from(idxen) << 13 | u32::from(offen) << 12 | (offset & 0xFFF), + 0x80 << 24 | (srsrc >> 2) << 16 | vdata << 8 | vaddr, + ] +} + +fn v_mov_lit(vdst: u32, literal: u32) -> [u32; 2] { + [0x7E00_02FF | (vdst << 17), literal] +} + +/// 32-bit sentinel (`u32::MAX` / `-1`) and negative (`x - 4` at `x = 0`) offsets must stay out of +/// bounds when biased: wrapping `0xFFFF_FFF8 + 8` or `0xFFFF_FFFC + 8` modulo `2^32` would land in +/// the 16-byte prefix before the view and read or corrupt the preceding suballocation. +#[test] +fn sentinel_and_wrapped_offsets_stay_out_of_bounds_on_biased_twins() { + let mut code = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 (structured SRV, stride 8) + 0xF408_0302, + 0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20 (raw SRV, stride 4) + 0xF408_0402, + 0xFA00_0040, // s_load_dwordx4 s[16:19], s[4:5], 0x40 (raw UAV, stride 4) + ]; + // Control: element 0 of structured SRV (stride 8) -> dwords 0 and 1 at UAV +0 and +4. + code.extend_from_slice(&v_mov_lit(1, 0)); + code.extend_from_slice(&mubuf(0x0C, 2, 1, 8, true, false, 0)); + code.extend_from_slice(&mubuf(0x0C, 3, 1, 8, true, false, 4)); + code.extend_from_slice(&mubuf(0x1C, 2, 0, 16, false, false, 0)); + code.extend_from_slice(&mubuf(0x1C, 3, 0, 16, false, false, 4)); + + // Sentinel element = 0xFFFF_FFFF (-1) on structured SRV (stride 8): + // (-1 * 8 + 0) = 0xFFFF_FFF8 and (-1 * 8 + 4) = 0xFFFF_FFFC must both read 0, never twin[0..3]. + code.extend_from_slice(&v_mov_lit(1, u32::MAX)); + code.extend_from_slice(&mubuf(0x0C, 2, 1, 8, true, false, 0)); + code.extend_from_slice(&mubuf(0x0C, 3, 1, 8, true, false, 4)); + code.extend_from_slice(&mubuf(0x1C, 2, 0, 16, false, false, 8)); + code.extend_from_slice(&mubuf(0x1C, 3, 0, 16, false, false, 12)); + + // Raw neighbor lookbehind `x - 4` at `x = 0` (`0xFFFF_FFFC`) and multi-dword `dwordx4` at + // `0xFFFF_FFF0` must read 0 for every component. + code.extend_from_slice(&v_mov_lit(1, 0xFFFF_FFFC)); + code.extend_from_slice(&mubuf(0x0C, 2, 1, 12, false, true, 0)); + code.extend_from_slice(&mubuf(0x1C, 2, 0, 16, false, false, 16)); + code.extend_from_slice(&v_mov_lit(1, 0xFFFF_FFF0)); + code.extend_from_slice(&mubuf(0x0E, 4, 1, 12, false, true, 0)); // buffer_load_dwordx4 v[4:7] + for k in 0..4u32 { + code.extend_from_slice(&mubuf(0x1C, 4 + k, 0, 16, false, false, 20 + 4 * k)); + } + // Straddling sub-dword load `buffer_load_ushort` at `0xFFFF_FFFF` (`within = 3`, + // `aligned = 0xFFFF_FFFC`, `next` clamped instead of wrapping to `0`) must also read 0. + code.extend_from_slice(&v_mov_lit(1, u32::MAX)); + code.extend_from_slice(&mubuf(0x0A, 2, 1, 12, false, true, 0)); + code.extend_from_slice(&mubuf(0x1C, 2, 0, 16, false, false, 40)); + + // Scalar load at soffset = 0xFFFF_FFFC (-4): s_mov_b32 s20, -4; s_buffer_load_dword s21, s[12:15], s20 + code.extend_from_slice(&[ + 0xBE94_03FF, + 0xFFFF_FFFC, + 0xF420_0546, + 0x14 << 25, + ]); + code.push(0x7E04_0215); // v_mov_b32 v2, s21 + code.extend_from_slice(&mubuf(0x1C, 2, 0, 16, false, false, 36)); + + // Out-of-bounds UAV store (`0xFFFF_FFF8`) and UAV atomic add (`0xFFFF_FFFC`) must drop, never + // writing into the pre-view bytes `[0..target_bias)` of the target twin. + code.extend_from_slice(&v_mov_lit(2, 0xBAD0_CAFE)); + code.extend_from_slice(&v_mov_lit(1, 0xFFFF_FFF8)); + code.extend_from_slice(&mubuf(0x1C, 2, 1, 16, false, true, 0)); + code.extend_from_slice(&v_mov_lit(2, 7)); + code.extend_from_slice(&v_mov_lit(1, 0xFFFF_FFFC)); + code.extend_from_slice(&mubuf(0x32, 2, 1, 16, false, true, 0)); + code.push(0xBF81_0000); // s_endpgm + + let entry = |kind, at, stride| crate::UsedResource { + kind, + root: crate::RootType::Table, + table_offset_dwords: at, + lower_bound: at / 8, + stride, + dwords: 4, + user_data: 4, + slot: 1, + }; + let native = super::NativeProgram { + stage: super::HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + crate::RootParam { root: crate::RootType::Constants, table_offset_dwords: 0, sgprs: 4, base_register: 0, user_data: 0, slot: 0 }, + crate::RootParam { root: crate::RootType::Table, table_offset_dwords: 0, sgprs: 1, base_register: 0, user_data: 4, slot: 1 }, + ], + used: vec![ + entry(crate::ResourceType::Srv, 0, 8), + entry(crate::ResourceType::Srv, 8, 4), + entry(crate::ResourceType::Uav, 16, 4), + ], + io: crate::native::StageIo::Cs(crate::native::ComputeIo { rsrc2: 5 << 1, threads: [1, 1, 1] }), + code: code.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + // `RAW_VIEWS` is a power-of-two bit (`index | first`), so 4 slots + 4 twins. + const LOCAL_TWINS: u32 = 4; + super::shader::RAW_VIEWS_HERE.set(Some(LOCAL_TWINS)); + let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); + let st = crate::structure::structure(&p).unwrap(); + let l = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }); + super::shader::RAW_VIEWS_HERE.set(None); + let l = l.unwrap(); + let mut dxil = l.dxil.clone(); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut dxil).unwrap(); + } + let cs = HostShader { + stage: super::HwStage::Cs, + dxil, + user_data: l.user_data.clone(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: l.root_cbvs.clone(), + root_srvs: l.root_srvs.clone(), + root_uavs: l.root_uavs.clone(), + root_indexed_views: Vec::new(), + half_views: Vec::new(), + }; + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + for (backend, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { continue }; + let (root, pso) = host.compute_pipeline(&cs).unwrap_or_else(|e| panic!("{backend}: {e}")); + for (source_bias, target_bias) in [(0u32, 0u32), (4, 8), (8, 12), (12, 8)] { + let s = (source_bias / 4) as usize; + let t = (target_bias / 4) as usize; + // Fill the pre-view prefix `[0..s]` with non-zero poison floats/ints (`0x7f7f_7f7f`) + // and the view's own dwords `[s..]` with known payload. + let mut src_words = vec![0x7f7f_7f7fu32; 32]; + for (offset, slot) in src_words.iter_mut().skip(s).enumerate() { + *slot = 0x6200_0000 | (offset as u32 * 0x0101); + } + let title_dummy = vec![0xdead_beefu32; 32]; + let strides = vec![ + 8 | source_bias << super::VIEW_BIAS_SHIFT, + 4 | source_bias << super::VIEW_BIAS_SHIFT, + 4 | target_bias << super::VIEW_BIAS_SHIFT, + 0, + ]; + let views = [ + View::Buffer { data: &title_dummy, stride: Stride::Raw }, + View::Buffer { data: &title_dummy, stride: Stride::Raw }, + View::RawUav(32), + View::Buffer { data: &title_dummy, stride: Stride::Raw }, + View::Buffer { data: &src_words, stride: Stride::Raw }, + View::Buffer { data: &src_words, stride: Stride::Raw }, + View::RawUav(32), + View::Buffer { data: &title_dummy, stride: Stride::Raw }, + ]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(vec![0; 5])), (1, Root::View { srv: true, data: strides })], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{backend}: {e}")); + let mut want = vec![0u32; 32]; + want[t] = src_words[s]; + want[t + 1] = src_words[s + 1]; + // Slots t + 2 .. t + 9 are all OOB reads and must be 0; pre-view `[0..t]` must stay 0. + let label = format!("{backend}, source_bias={source_bias}, target_bias={target_bias}"); + assert_eq!(out[1], want, "{label}: wrapped OOB accesses touched pre-view twin bytes"); + } + } +} + +/// A program picking structured buffers from `ResourceHeap` (`SLOT_STRIDES`) alongside biased raw +/// twins (`SLOT_TABLE_STRIDES`) validates cleanly and keeps `element = u32::MAX` out of bounds. +#[test] +fn resource_heap_structured_twins_validate_and_guard_wrapped_elements() { + let mut code = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0x8F06_8500, // s_lshl_b32 s6, s0, 5 (slot 0 * 32) + 0x8F07_8501, // s_lshl_b32 s7, s1, 5 (slot 1 * 32) + 0xF408_0202, + 0x06 << 25, // s_load_dwordx4 s[8:11], s[4:5], s6 + 0xF408_0302, + 0x07 << 25, // s_load_dwordx4 s[12:15], s[4:5], s7 + ]; + // Read element `lane` (v0) at offset 4, and sentinel element `-1` at offset 4. + code.extend_from_slice(&mubuf(0x0C, 2, 0, 8, true, false, 4)); + code.extend_from_slice(&v_mov_lit(1, u32::MAX)); + code.extend_from_slice(&mubuf(0x0C, 3, 1, 8, true, false, 4)); + code.push(0x3408_0083); // v_lshlrev_b32 v4, 3, v0 (8 bytes per lane) + code.extend_from_slice(&mubuf(0x1C, 2, 4, 12, false, true, 0)); + code.extend_from_slice(&mubuf(0x1C, 3, 4, 12, false, true, 4)); + code.push(0xBF81_0000); // s_endpgm + + let native = super::NativeProgram { + stage: super::HwStage::Cs, + wave64: false, + vgprs: 6, + layout: vec![ + crate::RootParam { root: crate::RootType::Constants, table_offset_dwords: 0, sgprs: 4, base_register: 0, user_data: 0, slot: 0 }, + crate::RootParam { root: crate::RootType::ResourceHeap, table_offset_dwords: 0, sgprs: 1, base_register: 4, user_data: 4, slot: 1 }, + ], + used: Vec::new(), + io: crate::native::StageIo::Cs(crate::native::ComputeIo { rsrc2: 5 << 1, threads: [2, 1, 1] }), + code: code.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + super::shader::RAW_VIEWS_HERE.set(Some(TWINS)); + let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); + let st = crate::structure::structure(&p).unwrap(); + let l = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }); + super::shader::RAW_VIEWS_HERE.set(None); + let l = l.unwrap(); + assert!( + l.root_srvs.contains(&super::SLOT_STRIDES) + && l.root_srvs.contains(&super::SLOT_TABLE_STRIDES), + "ResourceHeap structured twin program declares both stride SRVs: {:?}", + l.root_srvs + ); + let mut dxil = l.dxil.clone(); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut dxil).unwrap(); + } + let cs = HostShader { + stage: super::HwStage::Cs, + dxil, + user_data: l.user_data.clone(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: l.root_cbvs.clone(), + root_srvs: l.root_srvs.clone(), + root_uavs: l.root_uavs.clone(), + root_indexed_views: Vec::new(), + half_views: Vec::new(), + }; + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + for (backend, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { continue }; + let (root, pso) = host.compute_pipeline(&cs).unwrap_or_else(|e| panic!("{backend}: {e}")); + for bias in [8u32, 12] { + let s = (bias / 4) as usize; + let mut src_words = vec![0x7f80_0001u32; 24]; + for k in s..24 { + src_words[k] = 0x3300_0000 + (k - s) as u32; + } + let dummy = vec![0xdead_beefu32; 24]; + let strides = vec![8 | bias << super::VIEW_BIAS_SHIFT, 1]; + let views = [ + View::Buffer { data: &dummy, stride: Stride::Raw }, + View::RawUav(16), + View::Buffer { data: &src_words, stride: Stride::Raw }, + View::RawUav(16), + ]; + // User data: s0 = 0 (slot 0), s1 = 1 (slot 1), heap base = 0. + let mut user = vec![0u32; cs.user_data_dwords() as usize]; + for u in &cs.user_data { + if u.root == crate::RootType::Constants && u.dword == 1 { + user[u.index as usize] = 1; + } + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(user)), + (1, Root::View { srv: true, data: strides.clone() }), + (2, Root::View { srv: true, data: strides }), + ], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{backend}: {e}")); + let mut want = vec![0u32; 16]; + want[0] = src_words[s + 1]; // lane 0: element 0, +4 bytes + want[1] = 0; // lane 0: element -1, +4 bytes -> OOB 0 + want[2] = src_words[s + 3]; // lane 1: element 1, +4 bytes (stride 8 -> +12 bytes) + want[3] = 0; // lane 1: element -1, +4 bytes -> OOB 0 + assert_eq!(out[1], want, "{backend}, bias={bias}"); + } + } +}