From 54c2ce3e8df0b741ec89bda2e4c1351691afa7fd Mon Sep 17 00:00:00 2001 From: Valdi320 <61891540+Valdi320@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:22:50 +0100 Subject: [PATCH] dxbc: recover corroborated descriptors in later compute tables --- runtime/dxbc/src/compute_table.rs | 17 +++- runtime/dxbc/src/tests/compute_table.rs | 50 +++++++++++ tools/check_third_table_atomic.py | 89 +++++++++++++++++++ tools/check_translator_gpu.py | 2 + .../src/tests/hlsl/raw_width.rs | 37 ++++++++ 5 files changed, 192 insertions(+), 3 deletions(-) create mode 100644 tools/check_third_table_atomic.py diff --git a/runtime/dxbc/src/compute_table.rs b/runtime/dxbc/src/compute_table.rs index 1a54ed6c..0dfebdf4 100644 --- a/runtime/dxbc/src/compute_table.rs +++ b/runtime/dxbc/src/compute_table.rs @@ -337,7 +337,8 @@ pub fn uncovered_descriptor( // An embedded root numbers its ranges independently of the shader. A number it gave to // another slot is replaced with one of our own. if root_declares(root, kind, register, space) { - return Some((kind, slot, UNCOVERED_SPACE + table)); + let private_space = UNCOVERED_SPACE + table; + return (!root_declares(root, kind, slot, private_space)).then_some((kind, slot, private_space)); } Some((kind, register, space)) } @@ -489,7 +490,14 @@ fn descriptor_class( resources: &[[u32; 4]], ) -> Option<(u32, u32)> { let location = if stage <= 1 && matches!(class, 0x300 | 0x302 | 0x303) - && (location >> 8) & 0xff == 9 { 0x800 | (location & 0xff) } else { location }; + && (location >> 8) & 0xff == 9 { 0x800 | (location & 0xff) } + // As in read_bindings, later compute tables use the same resource + // encoding as table one. slot_binding separately checks the actual + // parameter and SGPR against the independent user-data record. + else if stage == 5 && matches!(class, 0x300 | 0x302 | 0x303) + && location >> 16 >= 2 && matches!(location & 0xff, 4 | 8) { + 0x10500 | (location & 0xff) + } else { location }; Some(match (class, location) { (0x300, 0x408 | 0x10508) if stage == 5 => (0, 3), (0x300 | 0x303, 0x404 | 0x10504) if stage == 5 => { @@ -553,7 +561,10 @@ fn root_declares(root: &crate::rootsig::RootSig, kind: u32, register: u32, space && register.checked_sub(range.base_register).is_some_and(|delta| delta < range.num) }), RootParamKind::Descriptor { kind: declared, register: reg, space: sp } => { - *declared == kind && *reg == register && *sp == space + // Root parameter types (CBV=2, SRV=3, UAV=4) are not + // descriptor range types (SRV=0, UAV=1, CBV=2). + matches!((*declared, kind), (2, 2) | (3, 0) | (4, 1)) + && *reg == register && *sp == space } RootParamKind::Constants { register: reg, space: sp, .. } => { kind == 2 && *reg == register && *sp == space diff --git a/runtime/dxbc/src/tests/compute_table.rs b/runtime/dxbc/src/tests/compute_table.rs index 3f061414..41e2c61a 100644 --- a/runtime/dxbc/src/tests/compute_table.rs +++ b/runtime/dxbc/src/tests/compute_table.rs @@ -226,3 +226,53 @@ fn same_register_at_two_slots_fails_closed() { assert_eq!(corroborated_descriptor(&image, &resources, 5, 5, 0x320), None); assert_eq!(corroborated_descriptor(&image, &resources, 5, 5, 0x340), None); } + +#[test] +fn third_compute_table_can_recover_corroborated_missing_descriptors() { + // Third table is s6. The root has a raw SRV at slot zero but + // leaves slot two uncovered. Metadata identifies the missing binding. + let mut root = three_tables_srv_constants(); + root.params[2].kind = RootParamKind::Table(vec![RootRange { + range_type: 0, num: 1, base_register: 0, space: 0, offset_in_table: 0, + }]); + for (class, width, shape, ty, kind) in [ + (0x300, 4, 1, 4, 0), (0x303, 4, 1, 7, 1), + (0x302, 4, 0, 2, 2), (0x300, 8, 0, 3, 0), + (0x303, 8, 0, 6, 1), + ] { + let user = [[3, 16, 1, 28, 0x206]]; + let used = [[class, 16, 28, shape, 0x20600 | width]]; + let image = program(&user, &used); + let resources = [[ty, 1, 28, 28]]; + assert_eq!(uncovered_descriptor(&image, &resources, 5, 6, 64, &root), + Some((kind, 28, 1)), "class={class:#x} width={width}"); + let shader = raster_shader(5, &user, &used, &resources); + assert_eq!(missing_root_descriptors(&shader, &root), + vec![Binding { table: 2, kind, register: 28, space: 1, slot: 2 }]); + let mut bad = root.clone(); + bad.params[2].kind = RootParamKind::Constants { register: 28, space: 1, num32: 1 }; + assert_eq!(uncovered_descriptor(&image, &resources, 5, 6, 64, &bad), None); + let bad = program(&[[3,16,1,28,0x106]], &[[class,16,28,shape,0x10600|width]]); + assert_eq!(uncovered_descriptor(&bad, &resources, 5, 6, 64, &root), None); + } +} + +#[test] +fn uncovered_bindings_do_not_collide_with_root_descriptor_names() { + for (class, root_kind, ty, kind, shape) in [ + (0x300, 3, 4, 0, 1), (0x303, 4, 7, 1, 1), (0x302, 2, 2, 2, 0) + ] { + let image = program(&[[3, 16, 1, 28, 0x105]], &[[class, 16, 28, shape, 0x10504]]); + let resources = [[ty, 1, 28, 28]]; + let mut root = root(vec![]); + root.params.push(RootParam { visibility: 0, kind: RootParamKind::Descriptor { + kind: root_kind, register: 28, space: 1, + }}); + assert_eq!(uncovered_descriptor(&image, &resources, 5, 5, 64, &root), + Some((kind, 2, 32701))); + root.params.push(RootParam { visibility: 0, kind: RootParamKind::Descriptor { + kind: root_kind, register: 2, space: 32701, + }}); + assert_eq!(uncovered_descriptor(&image, &resources, 5, 5, 64, &root), None); + } +} diff --git a/tools/check_third_table_atomic.py b/tools/check_third_table_atomic.py new file mode 100644 index 00000000..3513dd9d --- /dev/null +++ b/tools/check_third_table_atomic.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""GPU readback of an atomic UAV recovered from compute root table 2.""" +import argparse +import hashlib +import json +from pathlib import Path +import random +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +from build import find_dxc +from tools.frosty_gpu_guest import run_gpu_guest + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ("hlsl", "provider", "proton", "prefix", "compiler-dir", "work", "output"): + parser.add_argument("--" + name, type=Path, required=True) + parser.add_argument("--adapter", required=True) + a = parser.parse_args() + a.work.mkdir(parents=True, exist_ok=True) + src = a.hlsl.read_text() + marker = " // 0x0000 s_load_dwordx4" + assert src.count(marker) == 1 and "raw_ubuf0.InterlockedAdd(" in src + # Deliberately contend four lanes per word. Only supply live test values; + # the emitted address and operation remain unchanged. + src = src.replace(marker, " v4 = 1u + gtid.x; v5 = 4u * (gtid.x % 16u);\n" + marker) + guest = (ROOT / "tools/reference/independent-shaders/compute.cpp").read_text() + marker = "D3D12_ROOT_SIGNATURE_DESC description{1, &table, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};" + assert guest.count(marker) == 1 + guest = guest.replace(marker, """D3D12_ROOT_PARAMETER parameters[3]{table, table, table}; + D3D12_DESCRIPTOR_RANGE unused0{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_DESCRIPTOR_RANGE unused1{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 1, 0, 0}; + parameters[0].DescriptorTable = {1, &unused0}; + parameters[1].DescriptorTable = {1, &unused1}; + D3D12_DESCRIPTOR_RANGE third[]{{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 2, 0, 0}, {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 2}}; + parameters[2].DescriptorTable = {2, third}; + D3D12_ROOT_SIGNATURE_DESC description{3, parameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};""") + guest = guest.replace("D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1,", "D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 3,") + marker = " device->CreateUnorderedAccessView(out.Get(), nullptr, &uav, heap->GetCPUDescriptorHandleForHeapStart());" + assert guest.count(marker) == 1 + guest = guest.replace(marker, """ auto handle = heap->GetCPUDescriptorHandleForHeapStart(); + D3D12_SHADER_RESOURCE_VIEW_DESC unused{}; + unused.Format = DXGI_FORMAT_R32_TYPELESS; + unused.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + unused.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + unused.Buffer = {0, 1, 0, D3D12_BUFFER_SRV_FLAG_RAW}; + device->CreateShaderResourceView(nullptr, &unused, handle); + handle.ptr += 2 * device->GetDescriptorHandleIncrementSize(hd.Type); + device->CreateUnorderedAccessView(out.Get(), nullptr, &uav, handle);""") + guest = guest.replace("list->SetComputeRootDescriptorTable(0, heap->GetGPUDescriptorHandleForHeapStart());", + "for (UINT i = 0; i < 3; ++i) list->SetComputeRootDescriptorTable(i, heap->GetGPUDescriptorHandleForHeapStart());") + rng = random.Random(0x5336) + dxc = Path(find_dxc(None)).resolve() + with TemporaryDirectory(dir=a.work) as tmp: + trial = Path(tmp) + (trial / "atomic.hlsl").write_text(src) + (trial / "guest.cpp").write_text(guest) + (trial / "context.h").write_text((ROOT / "tools/reference/independent-shaders/context.h").read_text().replace( + '"../compute_buffers.h"', '"' + str(ROOT / "tools/reference/compute_buffers.h") + '"')) + blob = trial / "atomic.cso" + subprocess.run([str(dxc), "-T", "cs_6_0", "-E", "main", "-Fo", str(blob), str(trial / "atomic.hlsl")], check=True, timeout=30) + subprocess.run([str(dxc.with_name("dxv")), str(blob)], check=True, timeout=30) + expected = {} + for case in range(8): + name = f"case{case:02}" + seed = [rng.getrandbits(32) for _ in range(384)] + want = seed.copy() + for lane in range(64): + want[96 + lane % 16] = (want[96 + lane % 16] + lane + 1) & 0xffffffff + (trial / (name + ".seed")).write_bytes(struct.pack("<384I", *seed)) + (trial / (name + ".cso")).hardlink_to(blob) + expected[name] = struct.pack("<384I", *want) + (trial / "cases.txt").write_text("".join(f"{n} 0 raw 1\n" for n in expected)) + _, status, fields = run_gpu_guest(trial / "guest.cpp", "third-table-atomic.exe", trial, a.work, a.proton, a.prefix, a.provider, a.compiler_dir) + assert status == 0 and fields.get("adapter") == a.adapter, fields + assert all((trial / (n + ".bin")).read_bytes() == want for n, want in expected.items()) + result = dict(passed=True, adapter=fields["adapter"], cases=8, compared_words=3072, + result_words=128, preserved_words=2944, mismatches=0, + hlsl_sha256=hashlib.sha256(a.hlsl.read_bytes()).hexdigest()) + a.output.write_text(json.dumps(result, indent=2) + "\n") + print(result) + return 0 + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/check_translator_gpu.py b/tools/check_translator_gpu.py index 7a7ef8f2..5c6b9e7d 100644 --- a/tools/check_translator_gpu.py +++ b/tools/check_translator_gpu.py @@ -75,6 +75,8 @@ def assembled(tool, *extra): "pixel-link-slot86": Check("check_slot86_portable_link", emitter="xshader", dxc=True), "raw-index": Check("check_raw_index", capture=("proven_byte_index_emits_addresses_without_widening_loads", "--hlsl")), + "third-table-atomic": Check("check_third_table_atomic", + capture=("third_compute_table_recovers_a_proven_atomic_uav", "--hlsl")), "dynamic-cbv": Check("check_dynamic_cbv", capture=("bounded_dynamic_cbv", "--hlsl"), dxc=True), "dynamic-code-offset": Check("check_dynamic_code_offset", capture=("bounded_runtime_code_offset", "--hlsl")), diff --git a/tools/shader-compiler/src/tests/hlsl/raw_width.rs b/tools/shader-compiler/src/tests/hlsl/raw_width.rs index 531885d7..882f4f90 100644 --- a/tools/shader-compiler/src/tests/hlsl/raw_width.rs +++ b/tools/shader-compiler/src/tests/hlsl/raw_width.rs @@ -435,3 +435,40 @@ fn dynamic_cbv_rejects_incompatible_reflection_and_range_bounds() { ex.resources[0].upper = 31; assert!(Emitter::new(&ex,disassemble(&ex.isa)).resolve_resources().is_err()); } + +#[test] +fn third_compute_table_recovers_a_proven_atomic_uav() { + use crate::meta::{RootParam, RootParamKind, RootRange}; + // s_load_dwordx4 s[16:19], s[6:7], 0x40; buffer_atomic_add v4,v5,s[16:19],0 offen + let words = [0xf4080403u32, 0xfa000040, 0xe0c81000, 0x80040405, 0xbf810000]; + let isa: Vec = words.into_iter().flat_map(u32::to_le_bytes).collect(); + let mut ex = super::mesh::heap_extract(&[[3,16,1,0,0x206]], 0, &isa); + ex.stage = Stage::Compute; + ex.psv_threads = Some([64,1,1]); + ex.required_features = None; + let used_at = (ex.fssm.len() - 16) as u64; + ex.fssm[0xf0..0xf8].copy_from_slice(&used_at.to_le_bytes()); + ex.fssm[0xfc..0x100].copy_from_slice(&1u32.to_le_bytes()); + ex.fssm.extend([0x303u32,16,0,1,0x20604].into_iter().flat_map(u32::to_le_bytes)); + let size = (ex.fssm.len()-16) as u32; + ex.fssm[8..12].copy_from_slice(&size.to_le_bytes()); + ex.resources.push(crate::psv::PsvResource { res_type: 7, space: 0, lower: 0, upper: 0 }); + let root = ex.root_sig.as_mut().unwrap(); + root.version = 2; + root.params = (0..3).map(|_| RootParam { visibility: 0, kind: RootParamKind::Table(vec![ + RootRange { range_type: 0, num: 1, base_register: 0, space: 0, offset_in_table: 0 }, + ]) }).collect(); + let hlsl = super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains("RWByteAddressBuffer raw_ubuf0 : register(u0)"), "{hlsl}"); + assert!(hlsl.contains("raw_ubuf0.InterlockedAdd("), "{hlsl}"); + println!("BEGIN_HLSL\n{hlsl}\nEND_HLSL"); + // A real SRV occupying this slot is not evidence that an atomic can write it. + let RootParamKind::Table(ranges) = &mut ex.root_sig.as_mut().unwrap().params[2].kind else { unreachable!() }; + ranges[0].num = 3; + assert!(super::translate(&ex).is_err()); + // An uncovered slot without the independent user-data record is refused. + let RootParamKind::Table(ranges) = &mut ex.root_sig.as_mut().unwrap().params[2].kind else { unreachable!() }; + ranges[0].num = 1; + ex.fssm[0xf8..0xfc].fill(0); + assert!(super::translate(&ex).is_err()); +}