From f76adb7e050a794ed354f485ea16e6da4350e687 Mon Sep 17 00:00:00 2001 From: Matheus Sergio <98255852+consolelogkyo@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:03:34 -0300 Subject: [PATCH] startup: bind compute root SRV buffers (`srv buf root `) at Dispatch Record guest compute root SRV addresses and bound bits on the command list in slot 43 (`SetComputeRootShaderResourceView`), clearing them when a different compute root signature is bound in slot 33 or when the list is closed or reset. Extend `ComputeTranslation::Slot` and `load_compute_translation` in `src/startup_stubs/d3d12_compute_dispatch.inl` to parse `srv buf root ` emitted by `tools/startup/gfx2hlsl.py` for compute `global_load_dword` loads through a 64-bit root SRV pointer, rejecting descriptor-word entry values that reference a root SRV slot and refusing indirect dispatches that require root SRV bindings. At translated compute `Dispatch` (slot 14), validate that `` in the bound compute root signature has `D3D12_ROOT_PARAMETER_TYPE_SRV`, was set since the compute root signature was bound or reset, has a non-null 4-byte-aligned guest address at a 16-byte-aligned resource offset inside a recording upload allocation or live aliased placed buffer in `COMMON` state, and does not alias an output UAV buffer, then bind a bounded raw `R32_TYPELESS` `ByteAddressBuffer` view from that offset to the end of its backing range. Add `tests/startup_compute_root_srv_dispatch_check.py` (registered in `tests/cmake/startup_compute_root_srv.cmake`) and `docs/experiments/startup-compute-root-srv.md` verifying single- and two-root-SRV dispatches, non-zero byte offsets, bounded out-of-bounds zero reads, refusal controls, and negative controls on WARP and AMD Radeon RX 9070 XT. Refs #2618, #2274 AI-assisted. --- docs/experiments/startup-compute-root-srv.md | 79 ++++ src/startup_stubs/d3d12_compute_dispatch.inl | 93 ++++- src/startup_stubs/d3d12_xs_device.cpp | 33 +- tests/cmake/startup_compute_root_srv.cmake | 8 + ...startup_compute_root_srv_dispatch_check.py | 345 ++++++++++++++++++ tests/startup_stream_consumer.cpp | 56 ++- 6 files changed, 605 insertions(+), 9 deletions(-) create mode 100644 docs/experiments/startup-compute-root-srv.md create mode 100644 tests/cmake/startup_compute_root_srv.cmake create mode 100644 tests/startup_compute_root_srv_dispatch_check.py diff --git a/docs/experiments/startup-compute-root-srv.md b/docs/experiments/startup-compute-root-srv.md new file mode 100644 index 0000000000..e44bece927 --- /dev/null +++ b/docs/experiments/startup-compute-root-srv.md @@ -0,0 +1,79 @@ +# Startup compute root SRV (`srv buf root `) manifest consumer + +Refs [#2618](https://github.com/R0Y00/Xbox2Windows/issues/2618), +[#2274](https://github.com/R0Y00/Xbox2Windows/issues/2274). +Follows the compute `global_load_dword` lowering in +[#2715](https://github.com/R0Y00/Xbox2Windows/pull/2715) (ticket `C500-01/031`). + +When a translated compute shader loads through a 64-bit root SRV pointer via +`global_load_dword`, `tools/startup/gfx2hlsl.py` emits `srv buf root ` +in the compute manifest (`.txt`) and lowers the read to +`ByteAddressBuffer r : register(t)` in the translated descriptor table. + +The production startup compute manifest consumer in +`src/startup_stubs/d3d12_compute_dispatch.inl` and command-list tracking in +`src/startup_stubs/d3d12_xs_device.cpp` now consume `srv buf root `: + +- Command-list slot 43 (`SetComputeRootShaderResourceView`) records the guest + address and a bound bit per compute root parameter on the open recording while + a compute root signature is bound. Binding a different compute root signature + in slot 33 (`SetComputeRootSignature`), closing the list (slot 9), or + resetting the list (slot 139) clears the recorded compute root SRV bindings; + re-binding the same compute root signature preserves them. +- `load_compute_translation` parses `srv %u buf root %d%n` (requiring an exact + whole-line match, `param >= 0`, and sequential `i == tr.srvs.size()`), and + rejects descriptor-word entry values (`stride`, `descword3`) that reference a + root SRV slot. +- At translated compute `Dispatch` (slot 14), `compute_root_srv_buffer` resolves + each `buf root ` input by verifying that `` in the bound compute + root signature has `D3D12_ROOT_PARAMETER_TYPE_SRV`, was set by slot 43 since + the compute root signature was bound or reset, has a non-null 4-byte-aligned + guest address at a 16-byte-aligned offset (`D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT`) + inside either a recording upload allocation (slot 148) or a live aliased + placed buffer in `COMMON` state (slot 133) with at least one whole dword + remaining, and does not alias an output UAV buffer. The resolved range is + bound as a raw `DXGI_FORMAT_R32_TYPELESS` `ByteAddressBuffer` view from that + offset to the end of its backing allocation or placed buffer (up to 16 MiB). + +## Verification + +`tests/startup_compute_root_srv_dispatch_check.py` (registered in +`tests/cmake/startup_compute_root_srv.cmake`) drives source-built gfx1013 +compute `global_load_dword` programs (1-root-SRV and 2-root-SRV variants) +through slot 67, slot 33, slot 43, slot 37/39, slot 35, and slot 14 in +`startup_stream_consumer` with `X2W_D3D12_DEBUG=1` on both `warp` and `hardware` +(`AMD Radeon RX 9070 XT`): + +- **Single and two-root-SRV dispatches:** 3x2x2 groups of 2x3x4 threads (288 + active lanes, 320 total output words) load at offset `0` and `+128` bytes from + one or two distinct placed input buffers (`srv 0 buf root 2` and + `srv 1 buf root 3`), including re-binding the same compute root signature, + non-zero byte offsets into placed buffers (`+16` bytes on root SRV 0, `+32` + bytes on root SRV 1) and recording upload memory (`+16` bytes via slot 148), + and out-of-bounds loads (`v4 + 128u` past the bounded 1,280-byte backing) + returning `0` rather than reading adjacent `0xdeadbeef` / `0xfeedface` + neighbor words in the same 64 KiB page. +- **Refusal controls:** malformed manifest lines (`root -1`, trailing tokens, + non-sequential SRV index, `udsrc ... stride` on a root SRV), unset root SRV + slot (first or second), root SRV cleared by `Reset` or by binding a different + compute root signature, wrong root parameter kind (`D3D12_ROOT_PARAMETER_TYPE_CBV` + at ``), null guest address, unaligned guest address (`addr + 2`), + non-16-byte-aligned interior resource offset (`addr + 4`), unmapped guest + address between placed buffers, non-aliased copied placed buffer, and + input-aliases-output-UAV hazard all refuse cleanly with their expected log + reasons and leave all 320 output sentinel words (`0xc5c5c5c5`) untouched. +- **Negative controls:** skipping `Dispatch`, swapping `srv 0 buf root 2` and + `srv 1 buf root 3` in the manifest, or dropping the `+ 128u` offset in the + translated HLSL changes all 288 active output words as predicted. + +Reproduce on Windows: + +```powershell +cmake --build --preset release --target d3d12_xs_shim startup_stream_consumer +ctest --preset release -j1 --no-tests=error -R '^startup_compute_root_srv_dispatch_(warp|hardware)$' -V +``` + +What remains a hypothesis: retail title compute dispatches that combine root SRV +pointers with unplaced host memory outside slot-133 placed buffers and slot-148 +recording upload allocations are not yet modelled here and remain refused until +a title call site establishes their backing contract. diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 7115c28500..06e88de2cf 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -1,7 +1,8 @@ // Translated compute programs at Dispatch (list slot 14). A device slot 67 pipeline is a placeholder that keeps // the key of its published request; gfx2hlsl.py --pending answers the request with .txt (`stage cs`) and -// .cs.cso. Bound from the compute tables recorded by slot 35: raw buffers (`srv buf table ` -// inputs, `uav table ` outputs) named by hardware buffer descriptors, and 2D textures +// .cs.cso. Bound from the compute tables recorded by slot 35 and compute root SRVs recorded by slot 43: raw +// buffers (`srv buf table ` and `srv buf root ` inputs, `uav table ` +// outputs) named by hardware buffer descriptors or 64-bit root SRV addresses, and 2D textures // (`srv tex2d table ` inputs, `uav tex2d/tex2da float table channels 4` outputs) named // by the token of a view the title created (device slots 18 and 19). `smp` lines become static samplers. Entry // values come from the compute root constants of slots 37 and 39, or from the descriptor a buffer input or output is @@ -24,6 +25,7 @@ struct ComputeTranslation { std::uint32_t at = 0, times = 0; Source source = root_constant; bool array = false; + bool root = false; }; u64 key = 0; int state = 0; // 0 not loaded, 1 ready, 2 unavailable @@ -112,6 +114,11 @@ const char* load_compute_translation(ComputeTranslation& tr) tr.uds.push_back({a, 0, false, false, -1, 0, 0, 0, source()}); else if (std::sscanf(line.c_str(), "srv %u buf table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) tr.srvs.push_back({a, b}); + else if (std::sscanf(line.c_str(), "srv %u buf root %d%n", &i, &a, &used) == 2 && whole() && a >= 0 && + i == tr.srvs.size()) { + tr.srvs.push_back({a, 0}); + tr.srvs.back().root = true; + } else if (std::sscanf(line.c_str(), "srv %u buf heap rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) tr.srvs.push_back({a, b, false, true}); @@ -151,7 +158,7 @@ const char* load_compute_translation(ComputeTranslation& tr) for (const ComputeTranslation::Slot& ud : tr.uds) { const auto& slots = ud.source >= ComputeTranslation::output_word3 ? tr.uavs : tr.srvs; if (ud.source != ComputeTranslation::root_constant && - (ud.a < 0 || static_cast(ud.a) >= slots.size() || slots[ud.a].texture)) + (ud.a < 0 || static_cast(ud.a) >= slots.size() || slots[ud.a].texture || slots[ud.a].root)) return "an entry value names a descriptor that is not a buffer input or output"; } x2w_startup::ComPtr code; @@ -171,6 +178,74 @@ const char* load_compute_translation(ComputeTranslation& tr) return nullptr; } +// Resolve a compute root SRV (`srv buf root `) from the guest address recorded by slot 43 for +// to the end of its backing upload allocation or aliased placed buffer (up to the 16 MiB compute raw buffer limit). +IndirectBufferView compute_root_srv_buffer(Wrapper* self, const Pass& pass, int param, std::uint32_t (&words)[8], + const char** why) +{ + const auto refuse = [why](const char* reason) { + if (why) *why = reason; + return IndirectBufferView{}; + }; + if (why) *why = nullptr; + const auto* root_params = pass.compute_root_wrapper ? root_info(pass.compute_root_wrapper) : nullptr; + if (!root_params || param < 0 || static_cast(param) >= root_params->size() || + static_cast(param) >= pass.compute_root_srvs.size() || + (*root_params)[param].type != D3D12_ROOT_PARAMETER_TYPE_SRV) + return refuse("a compute root input is not a shader resource view parameter"); + if (!(pass.compute_root_srv_set & (u64{1} << param))) + return refuse("a compute root SRV was not set since the compute root"); + const u64 address = pass.compute_root_srvs[param]; + words[0] = static_cast(address); + words[1] = static_cast(address >> 32); + if (!address) return refuse("a compute root SRV has a null address"); + if (address % 4) return refuse("a compute root SRV address is not 4-byte aligned"); + constexpr u64 limit = 16u << 20; + if (const auto allocation = list_upload_tail(self, address); allocation.resource) { + if (allocation.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) + return refuse("a compute root SRV range is not 16-byte aligned in its resource"); + const u64 bytes = (std::min)(allocation.bytes, limit) & ~u64{3}; + if (bytes < 4) + return refuse("a compute root SRV has fewer than 4 aligned bytes in its upload allocation"); + words[2] = static_cast(bytes); + return {allocation.resource, allocation.offset, bytes, 0, true}; + } + Wrapper* device = self->own().list_device; + const auto first = placed_buffer_range(device, address, 4); + if (first.reject) return refuse("a compute root SRV crosses the end of a placed buffer"); + if (!first.owner) return refuse("a compute root SRV is in title memory outside any placed buffer"); + if (!InterlockedCompareExchange(&first.owner->own().refs, 0, 0)) + return refuse("a compute root SRV's resource is released"); + const auto* info = resource_info(first.owner); + if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON) + return refuse("a compute root SRV's resource was not created in the common state"); + const u64 base = reinterpret_cast(first.owner->own().title_memory); + if (!base || address < base || address - base >= info->bytes) + return refuse("a compute root SRV range is outside its desktop buffer"); + const u64 offset = address - base; + if (offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) + return refuse("a compute root SRV range is not 16-byte aligned in its resource"); + const u64 bytes = (std::min)(info->bytes - offset, limit) & ~u64{3}; + if (bytes < 4) + return refuse("a compute root SRV has fewer than 4 aligned bytes in its placed buffer"); + const auto placed = placed_buffer_range(device, address, bytes); + if (placed.reject || placed.owner != first.owner) + return refuse("a compute root SRV crosses the end of a placed buffer"); + auto* native = static_cast(placed.owner->own().real); + if (!placed.alias && (!native || !list_copied_gpu_range(self, native, offset, bytes))) + return refuse("a compute root SRV is in a placed buffer that does not alias title memory"); + x2w_startup::ComPtr native_device; + if (!native || FAILED(native->GetDevice(IID_PPV_ARGS(native_device.GetAddressOf()))) || + native_device.Get() != device_of(device)) + return refuse("a compute root SRV's resource is on another device"); + const auto desc = native->GetDesc(); + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || (desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || + offset > desc.Width || bytes > desc.Width - offset) + return refuse("a compute root SRV range is outside its desktop buffer"); + words[2] = static_cast(bytes); + return {native, offset, bytes, 0, false}; +} + // Both callers have an open list and a slot 67 request. The indirect caller has checked the signature and argument range. const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& dispatch) { @@ -221,12 +296,22 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& for (std::size_t i = 0; i < count && !reason; ++i) { const bool output = i >= inputs; const ComputeTranslation::Slot slot = output ? tr->uavs[i - inputs] : tr->srvs[i]; - if (dispatch.signature && (slot.heap || slot.texture)) { + if (dispatch.signature && (slot.heap || slot.texture || slot.root)) { reason = "translated indirect Dispatch requires fixed-table raw buffers"; break; } std::uint32_t index = slot.a < 0 || slot.b < 0 ? 0 : pass.compute_constants.word(slot.a, slot.b); std::memset(words, 0, sizeof(words)); + if (!output && slot.root) { + const IndirectBufferView view = compute_root_srv_buffer(self, pass, slot.a, words, &reason); + if (reason && !tr->first_refusal) + log("x2w-draw compute %016llx first refused input %zu (root %d), address 0x%llx", key, i, slot.a, + u64{words[0]} | (u64{words[1]} << 32)); + views[i] = {view.resource, view.offset, view.bytes, !view.upload}; + views[i].stride = view.stride; + std::memcpy(views[i].words, words, sizeof(views[i].words)); + continue; + } if (slot.word_param >= 0) { // The index word is read now from the recording's upload memory, where the title wrote it (no GPU command // writes there), at the dword-aligned 32-bit byte offset the program reads it at. diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 56d4535571..405dba72e1 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1596,6 +1596,25 @@ x2w_upload::Allocation list_upload_range(Wrapper* self, UINT64 address, UINT64 b ReleaseSRWLockShared(&allocator_lock); return allocation; } +x2w_upload::Allocation list_upload_tail(Wrapper* self, UINT64 address) +{ + x2w_upload::Allocation allocation{}; + AcquireSRWLockShared(&allocator_lock); + const auto& state = self->own(); + if (state.list_open && state.list_uploads) { + for (auto it = state.list_uploads->allocations.rbegin(); it != state.list_uploads->allocations.rend(); ++it) { + if (address < it->cpu) continue; + const UINT64 offset = address - it->cpu; + if (offset < it->bytes) { + allocation = {static_cast(address), it->gpu + offset, it->bytes - offset, it->resource, + it->offset + offset}; + break; + } + } + } + ReleaseSRWLockShared(&allocator_lock); + return allocation; +} UINT64 list_upload_gpu(Wrapper* self, UINT64 address, UINT64 bytes) { return list_upload_range(self, address, bytes).gpu; } // Fixture lookup. The full range must belong to this list's open recording. @@ -2601,6 +2620,8 @@ struct Pass { std::uint32_t constants[16][8] = {}; unsigned char constant_words_bound[16] = {}; x2w_root_constants::Store compute_constants; // compute root constants (slots 37 and 39) + std::array compute_root_srvs{}; // title address of each compute root SRV (slot 43) + u64 compute_root_srv_set = 0; // bit per compute root parameter set by slot 43 since slot 33 / Reset Wrapper* compute_root_wrapper = nullptr; // compute root signature last set by slot 33 D3D12_VERTEX_BUFFER_VIEW vb[8] = {}; PlacedVertexView placed_vb[8] = {}; @@ -2730,6 +2751,8 @@ void retire_drop_recording(Wrapper* list) void reset_list_dynamic_state(Wrapper* self) { if (!self->own().pass) return; + pass_of(self).compute_root_srvs.fill(0); + pass_of(self).compute_root_srv_set = 0; pass_of(self).stencil_reference = 0; pass_of(self).viewport_set = false; pass_of(self).scissor_set = false; @@ -2837,7 +2860,11 @@ void __stdcall list_compute_root(Wrapper* self, void* root) Wrapper* w = as_wrapper(root); Pass& pass = pass_of(self); // A different root signature invalidates the title's cached compute root arguments. - if (pass.compute_root_wrapper != w) pass.compute_constants.clear(); + if (pass.compute_root_wrapper != w) { + pass.compute_constants.clear(); + pass.compute_root_srvs.fill(0); + pass.compute_root_srv_set = 0; + } pass.compute_root_wrapper = w; const bool real = w && w->own().kind == root_signature_kind && w->own().real && !root_heap_flags(w); pass.compute_root = real ? static_cast(w->own().real) : nullptr; @@ -3864,6 +3891,10 @@ void __stdcall list_compute_upload_srv(Wrapper* self, UINT parameter, UINT64 add { auto* list = recording(self); auto& pass = pass_of(self); + if (list && pass.compute_root_wrapper && parameter < pass.compute_root_srvs.size()) { + pass.compute_root_srvs[parameter] = address; + pass.compute_root_srv_set |= u64{1} << parameter; + } const auto* params = pass.compute_params; if (!list || !params || parameter >= params->size() || parameter >= pass.desktop_compute_upload_srvs.size() || (*params)[parameter].type != D3D12_ROOT_PARAMETER_TYPE_SRV) return; diff --git a/tests/cmake/startup_compute_root_srv.cmake b/tests/cmake/startup_compute_root_srv.cmake new file mode 100644 index 0000000000..fa30001130 --- /dev/null +++ b/tests/cmake/startup_compute_root_srv.cmake @@ -0,0 +1,8 @@ +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_root_srv_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_root_srv_dispatch_check.py" + "$" "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_compute_root_srv_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/startup_compute_root_srv_dispatch_check.py b/tests/startup_compute_root_srv_dispatch_check.py new file mode 100644 index 0000000000..177462f9c6 --- /dev/null +++ b/tests/startup_compute_root_srv_dispatch_check.py @@ -0,0 +1,345 @@ +"""Startup compute manifest consumer for `srv buf root ` at slot-14 Dispatch (Refs #2618, #2274).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from startup_compute_dispatch_texture_check import clean, lines, run as _run, translate +from startup_compute_global_load_check import ( + GLOBAL_LOAD_DWORD, + encode_global, + encode_mubuf, + encode_smem, + encode_sop1, + encode_sop2, + encode_sopp, + encode_vop2, + encode_vop3a, +) +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_gfx2hlsl_compute_check import ( + KEY, + MASK, + SENTINEL, + STRIDE, + TGID_X, + TGID_Y, + TGID_Z, + WORDS, + tidig, +) + +IN = [(0x8b02a7f1 + i * 0x413b1) & MASK for i in range(WORDS)] +IN2 = [(0x3c6ef372 + i * 0x19660d) & MASK for i in range(WORDS)] +NEIGHBOR0 = [(0xdeadbeef + i) & MASK for i in range(64)] +NEIGHBOR2 = [(0xfeedface + i) & MASK for i in range(64)] +GROUP = (2, 3, 4) + + +def run(directory, consumer, env, mode): + return _run(directory, consumer, env, mode, f"<{WORDS}I") + + +def no_debug_errors(result): + errors = [line for line in lines(result, "x2w-d3d12-debug ") if " sev=0 " in line or " sev=1 " in line] + assert not errors, errors[0] + + +def root_srv_blob(*, two_srvs=False, param2_type=3): + """DXBC RTS0 (v1.1) container matching startup_stream_consumer.cpp root-SRV bindings: + param 0 = 3 root constants at b0 (s4-s6; shader uses s4-s5), + param 1 = descriptor table with 2 UAV slots at u0 (s7; output UAV at table byte 16), + param 2 = root descriptor at register(t1/b1, space0) (s[8:9]; type 3=SRV, 2=CBV), + optional param 3 = root SRV descriptor at register(t2, space0) (s[10:11]). + """ + nparams = 4 if two_srvs else 3 + poff = 24 + coff = poff + 12 * nparams + toff = coff + 12 + roff = toff + 8 + srv2_off = roff + 24 + srv3_off = srv2_off + 12 + soff = (srv3_off + 12) if two_srvs else (srv2_off + 12) + params = [ + struct.pack("<3I", 1, 0, coff), + struct.pack("<3I", 0, 0, toff), + struct.pack("<3I", param2_type, 0, srv2_off), + ] + if two_srvs: + params.append(struct.pack("<3I", 3, 0, srv3_off)) + payload = ( + struct.pack("<3I", 0, 0, 3) + + struct.pack("<2I", 1, roff) + + struct.pack("<6I", 1, 2, 0, 0, 0, 0xffffffff) + + struct.pack("<3I", 1, 0, 0) + ) + if two_srvs: + payload += struct.pack("<3I", 2, 0, 0) + rts0 = struct.pack("<6I", 2, nparams, poff, 0, soff, 0) + b"".join(params) + payload + assert len(rts0) == soff + part = b"RTS0" + struct.pack(", 3 + encode_sop2(0x00, 24, 24, gx), # s_add_u32 s24, s24, s + encode_sop2(0x26, 25, gz, 0x80 + 6), # s_mul_i32 s25, s, 6 + encode_sop2(0x00, 24, 24, 25), # s_add_u32 s24, s24, s25 + encode_sop2(0x26, 24, 24, 0x80 + 24), # s_mul_i32 s24, s24, 24 + encode_vop2(0x25, 3, 24, 3), # v_add_nc_u32 v3, s24, v3 + encode_vop2(0x1a, 4, 0x80 + 2, 3), # v_lshlrev_b32 v4, 2, v3 + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 8, offset=0), # global_load_dword v5, v4, s[8:9] + encode_global(GLOBAL_LOAD_DWORD, 7, 4, second_saddr, offset=128), # global_load_dword v7, v4, s[...] offset:128 + encode_vop3a(0x169, 6, 256 + 3, 5, 0), # v_mul_lo_u32 v6, v3, s5 + encode_vop2(0x25, 6, 4, 6), # v_add_nc_u32 v6, s4, v6 + encode_sopp(0x0c, 0x3f70), # s_waitcnt vmcnt(0) + encode_vop3a(0x169, 5, 256 + 5, 0x80 + 33, 0), # v_mul_lo_u32 v5, v5, 33 + encode_vop2(0x25, 5, 256 + 5, 7), # v_add_nc_u32 v5, v5, v7 + encode_vop2(0x1d, 5, 256 + 5, 6), # v_xor_b32 v5, v5, v6 + encode_mubuf(0x1c, 5, 4, 20, offen=True), # buffer_store_dword v5, v4, s[20:23], 0 offen + encode_sopp(0x01, 0), # s_endpgm + ]) + return code, rsrc2 + + +def reference(*, two_srvs=False, offset0=0, offset1=0, shift1=32, swap_srvs=False, leak_neighbor=False): + src0 = (IN2 if swap_srvs else IN) + (NEIGHBOR2 if swap_srvs else NEIGHBOR0) + src1 = (IN if swap_srvs else (IN2 if two_srvs else IN)) + (NEIGHBOR0 if swap_srvs else (NEIGHBOR2 if two_srvs else NEIGHBOR0)) + off0 = offset1 if swap_srvs else offset0 + off1 = offset0 if swap_srvs else (offset1 if two_srvs else offset0) + bound0 = WORDS - off0 + bound1 = WORDS - off1 + out = [SENTINEL] * WORDS + for i in range(12 * 24): + v5 = src0[off0 + i] if (leak_neighbor or i < bound0) else 0 + idx1 = i + shift1 + v7 = src1[off1 + idx1] if (leak_neighbor or idx1 < bound1) else 0 + out[i] = (((v5 * 33 + v7) & MASK) ^ ((KEY + i * STRIDE) & MASK)) + return out + + +def setup_case(directory, *, two_srvs=False, param2_type=3, adapter="warp"): + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP="1", X2W_D3D12_DEBUG="1") + if adapter == "hardware": + env["X2W_TEST_DISPATCH_HARDWARE"] = "1" + (directory / "compute_root").write_bytes(root_srv_blob(two_srvs=two_srvs, param2_type=param2_type)) + env["X2W_TEST_COMPUTE_ROOT"] = str(directory / "compute_root") + code, rsrc2 = make_program(two_srvs=two_srvs) + (directory / "program").write_bytes(code) + (directory / "data").write_bytes(DATA) + (directory / "state").write_bytes(state_a(GROUP, rsrc2)) + return cache, env + + +def check_single_root_srv(base, consumer, dxc, adapter): + directory = base / "single" + cache, env = setup_case(directory, two_srvs=False, adapter=adapter) + + # First run before translation publishes the request and leaves output sentinels untouched. + got, result = run(directory, consumer, env, "dispatch-root-srv") + assert got == [SENTINEL] * WORDS + assert len(lines(result, "Dispatch(3, 2, 2) refused: no translation")) == 1, result.stderr[-3000:] + key = int(lines(result, "x2w-draw compute request")[0].split()[3], 16) + translate(cache, dxc, key) + + manifest_path = cache / f"{key:016x}.txt" + hlsl_path = cache / f"{key:016x}.cs.hlsl" + cso_path = cache / f"{key:016x}.cs.cso" + manifest = manifest_path.read_text(encoding="utf-8") + hlsl = hlsl_path.read_text(encoding="utf-8") + assert "srv 0 buf root 2" in manifest.splitlines(), manifest + assert "ByteAddressBuffer r0 : register(t0);" in hlsl, hlsl + assert "r0.Load(a)" in hlsl and "r0.Load(a + 128u)" in hlsl, hlsl + + # Manifest parser refusal controls on bad `srv ... buf root ...` lines and descriptor-word udsrc on a root SRV. + for bad_manifest, expected_reason in ( + (manifest.replace("srv 0 buf root 2", "srv 0 buf root -1"), + "a resource that is not a raw table buffer or a 2D texture"), + (manifest.replace("srv 0 buf root 2", "srv 0 buf root 2 trailing"), + "a resource that is not a raw table buffer or a 2D texture"), + (manifest.replace("srv 0 buf root 2", "srv 1 buf root 2"), + "a resource that is not a raw table buffer or a 2D texture"), + (manifest.replace("ud 3\nudsrc 0 rootconst 0 0\nudsrc 1 rootconst 0 1\nudsrc 2 rootconst 0 2", + "ud 4\nudsrc 0 rootconst 0 0\nudsrc 1 rootconst 0 1\nudsrc 2 rootconst 0 2\nudsrc 3 stride 0"), + "an entry value names a descriptor that is not a buffer input or output"), + ): + sub = base / f"bad-manifest-{ abs(hash(bad_manifest)) }" + sub_cache, sub_env = setup_case(sub, two_srvs=False, adapter=adapter) + (sub_cache / f"{key:016x}.txt").write_text(bad_manifest, encoding="utf-8") + (sub_cache / f"{key:016x}.cs.cso").write_bytes(cso_path.read_bytes()) + got, result = run(sub, consumer, sub_env, "dispatch-root-srv") + assert got == [SENTINEL] * WORDS + assert lines(result, f"compute pipeline {key:016x} not translated: {expected_reason}"), result.stderr[-3000:] + + # Translated single-root-SRV dispatch (and re-binding the same compute root signature). + expected0 = reference(two_srvs=False, offset0=0) + for mode in ("dispatch-root-srv", "dispatch-root-srv-same-root"): + got, result = run(directory, consumer, env, mode) + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + debug = clean(result) + assert got == expected0, (mode, sum(a != b for a, b in zip(got, expected0))) + print(f"{adapter}: single root SRV (srv 0 buf root 2) and same-root rebind verified; debug: {debug}", flush=True) + + # Non-zero byte offset into placed buffer (+16 bytes = 4 dwords) and upload allocation (+16 bytes = 4 dwords), + # plus out-of-bounds offset past the bounded backing returning 0 rather than reading neighbor 0xdeadbeef words. + expected_off4 = reference(two_srvs=False, offset0=4) + leaked_off4 = reference(two_srvs=False, offset0=4, leak_neighbor=True) + assert sum(a != b for a, b in zip(expected_off4, leaked_off4)) == 4 + got, result = run(directory, consumer, env, "dispatch-root-srv-offset") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_off4 and got != leaked_off4 + + got, result = run(directory, consumer, env, "dispatch-root-srv-upload") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_off4 and got != leaked_off4 + print(f"{adapter}: single root SRV non-zero offset (+16B placed, +16B upload) and bounded OOB=0 verified", flush=True) + + # Refusal controls leaving output sentinels untouched and logging the exact refusal reason. + for mode, reason in ( + ("dispatch-root-srv-unset", "a compute root SRV was not set since the compute root"), + ("dispatch-root-srv-reset", "a compute root SRV was not set since the compute root"), + ("dispatch-root-srv-root-changed", "a compute root SRV was not set since the compute root"), + ("dispatch-root-srv-null", "a compute root SRV has a null address"), + ("dispatch-root-srv-unaligned", "a compute root SRV address is not 4-byte aligned"), + ("dispatch-root-srv-unaligned-16", "a compute root SRV range is not 16-byte aligned in its resource"), + ("dispatch-root-srv-unmapped", "a compute root SRV is in title memory outside any placed buffer"), + ("dispatch-root-srv-copied", "a compute root SRV is in a placed buffer that does not alias title memory"), + ("dispatch-root-srv-same-buffer", "an output buffer is also an input"), + ): + got, result = run(directory, consumer, env, mode) + assert got == [SENTINEL] * WORDS, mode + refusal = lines(result, "Dispatch(3, 2, 2) refused:") + assert len(refusal) == 1 and refusal[0].endswith(reason), (mode, refusal, result.stderr[-3000:]) + assert not lines(result, "Dispatch(3, 2, 2) translated"), mode + no_debug_errors(result) + print(f"{adapter}: single root SRV refusal controls (unset, reset, root-changed, unaligned, unmapped, copied, UAV alias) verified", flush=True) + + # Wrong root parameter kind refusal control: param 2 declared as root CBV (type 2) instead of root SRV (type 3). + cbv_dir = base / "wrong-kind-cbv" + cbv_cache, cbv_env = setup_case(cbv_dir, two_srvs=False, param2_type=2, adapter=adapter) + got, result = run(cbv_dir, consumer, cbv_env, "dispatch-root-srv") + assert got == [SENTINEL] * WORDS + cbv_key = int(lines(result, "x2w-draw compute request")[0].split()[3], 16) + translate(cbv_cache, dxc, cbv_key) + assert "srv 0 buf root 2" in (cbv_cache / f"{cbv_key:016x}.txt").read_text(encoding="utf-8").splitlines() + got, result = run(cbv_dir, consumer, cbv_env, "dispatch-root-srv") + assert got == [SENTINEL] * WORDS + refusal = lines(result, "Dispatch(3, 2, 2) refused:") + assert len(refusal) == 1 and refusal[0].endswith("a compute root input is not a shader resource view parameter"), ( + refusal, + result.stderr[-3000:], + ) + no_debug_errors(result) + print(f"{adapter}: wrong root parameter kind (root CBV at param 2) refused cleanly", flush=True) + + +def check_two_root_srvs(base, consumer, dxc, adapter): + directory = base / "two" + cache, env = setup_case(directory, two_srvs=True, adapter=adapter) + + got, result = run(directory, consumer, env, "dispatch-root-srv") + assert got == [SENTINEL] * WORDS + assert len(lines(result, "Dispatch(3, 2, 2) refused: no translation")) == 1, result.stderr[-3000:] + key = int(lines(result, "x2w-draw compute request")[0].split()[3], 16) + translate(cache, dxc, key) + + manifest_path = cache / f"{key:016x}.txt" + hlsl_path = cache / f"{key:016x}.cs.hlsl" + cso_path = cache / f"{key:016x}.cs.cso" + manifest = manifest_path.read_text(encoding="utf-8") + hlsl = hlsl_path.read_text(encoding="utf-8") + assert "srv 0 buf root 2" in manifest.splitlines() and "srv 1 buf root 3" in manifest.splitlines(), manifest + assert "ByteAddressBuffer r0 : register(t0);" in hlsl and "ByteAddressBuffer r1 : register(t1);" in hlsl, hlsl + assert "r0.Load(a)" in hlsl and "r1.Load(a + 128u)" in hlsl, hlsl + + expected_two = reference(two_srvs=True, offset0=0, offset1=0) + assert expected_two != reference(two_srvs=False, offset0=0) + got, result = run(directory, consumer, env, "dispatch-root-srv") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_two + print(f"{adapter}: two root SRVs (srv 0 buf root 2, srv 1 buf root 3) verified", flush=True) + + # Non-zero offsets into both placed buffers (+16B = 4 dwords on root SRV 0, +32B = 8 dwords on root SRV 1) + OOB=0 on root SRV 1. + expected_off = reference(two_srvs=True, offset0=4, offset1=8) + leaked_off = reference(two_srvs=True, offset0=4, offset1=8, leak_neighbor=True) + assert sum(a != b for a, b in zip(expected_off, leaked_off)) == 8 + got, result = run(directory, consumer, env, "dispatch-root-srv-offset") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_off and got != leaked_off + print(f"{adapter}: two root SRVs non-zero offsets (+16B/+32B) and bounded OOB=0 (8 OOB lanes) verified", flush=True) + + # Second root SRV unset while first root SRV is set must refuse cleanly. + got, result = run(directory, consumer, env, "dispatch-root-srv-unset-second") + assert got == [SENTINEL] * WORDS + refusal = lines(result, "Dispatch(3, 2, 2) refused:") + assert len(refusal) == 1 and refusal[0].endswith("a compute root SRV was not set since the compute root"), ( + refusal, + result.stderr[-3000:], + ) + no_debug_errors(result) + + # Negative control 1: skipping the Dispatch leaves all 320 output words at SENTINEL (288 mismatches vs expected). + got, result = run(directory, consumer, env, "dispatch-root-srv-none") + assert not lines(result, "Dispatch(3, 2, 2) translated") + assert got == [SENTINEL] * WORDS and sum(a != b for a, b in zip(got, expected_two)) == 288 + + # Negative control 2: mutating the root SRV binding in the manifest (swapping root 2 and root 3) changes all 288 active words. + swapped_manifest = manifest.replace("srv 0 buf root 2\nsrv 1 buf root 3", "srv 0 buf root 3\nsrv 1 buf root 2") + assert swapped_manifest != manifest + manifest_path.write_text(swapped_manifest, encoding="utf-8") + expected_swapped = reference(two_srvs=True, swap_srvs=True) + assert sum(a != b for a, b in zip(expected_swapped, expected_two)) == 288 + got, result = run(directory, consumer, env, "dispatch-root-srv") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_swapped and sum(a != b for a, b in zip(got, expected_two)) == 288 + manifest_path.write_text(manifest, encoding="utf-8") + + # Negative control 3: mutating the translated shader (dropping the +128u byte offset on r1.Load) changes all 288 active words. + mutated_hlsl = hlsl.replace("r1.Load(a + 128u)", "r1.Load(a)") + assert mutated_hlsl != hlsl + hlsl_path.write_text(mutated_hlsl, encoding="utf-8") + subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", cso_path, hlsl_path], check=True) + expected_mutated = reference(two_srvs=True, shift1=0) + assert sum(a != b for a, b in zip(expected_mutated, expected_two)) == 288 + got, result = run(directory, consumer, env, "dispatch-root-srv") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_mutated and sum(a != b for a, b in zip(got, expected_two)) == 288 + print(f"{adapter}: negative controls (skip Dispatch, swap root SRV bindings, mutate HLSL offset) verified", flush=True) + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + check_single_root_srv(base, consumer, dxc, adapter) + check_two_root_srvs(base, consumer, dxc, adapter) + print(f"startup_compute_root_srv_dispatch: PASS on {adapter}") + + +if __name__ == "__main__": + if len(sys.argv) != 4 or sys.argv[3] not in ("warp", "hardware"): + sys.exit(__doc__) + main(*sys.argv[1:4]) diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index eddf880ff0..c100a274f7 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -217,10 +217,12 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin { constexpr UINT words = 320; const bool indirect = mode.rfind("dispatch-indirect-", 0) == 0; + const bool root_srv = mode.rfind("dispatch-root-srv", 0) == 0; const UINT groups = mode == "dispatch-indirect-zero" ? 0u : mode == "dispatch-indirect-2" ? 2u : 5u; - auto* memory = static_cast(VirtualAlloc(nullptr, indirect ? 0x30000 : 0x20000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + auto* memory = static_cast(VirtualAlloc(nullptr, (indirect || root_srv) ? 0x30000 : 0x20000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); if (!memory) return 70; UINT* const buffers[2] = {memory, memory + 0x10000 / sizeof(UINT)}; + UINT* const buffer2 = memory + 0x20000 / sizeof(UINT); for (UINT i = 0; i < words; ++i) { buffers[0][i] = 0x8b02a7f1u + i * 0x413b1u; buffers[1][i] = 0xc5c5c5c5u; @@ -248,7 +250,19 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin std::memcpy(descriptors[mode == "dispatch-swapped" ? 1 - i : i], view, sizeof(view)); } const UINT64 between = reinterpret_cast(memory) + 0x8000; - if (mode == "dispatch-input-copied") { + void* placed2 = nullptr; + if (root_srv) { + for (UINT i = 0; i < words; ++i) buffer2[i] = 0x3c6ef372u + i * 0x19660du; + for (UINT i = 0; i < 64; ++i) { + buffers[0][words + i] = 0xdeadbeefu + i; + buffer2[words + i] = 0xfeedfaceu + i; + } + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + if (FAILED(static_cast(invoke(device, 133, word(buffer2), word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, + word(&__uuidof(ID3D12Resource)), word(&placed2))))) return 71; + } + if (mode == "dispatch-input-copied" || mode == "dispatch-root-srv-copied") { const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; void* copied = nullptr; @@ -343,6 +357,40 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin std::memcpy(reinterpret_cast(cpu + sizeof(descriptors[0])), descriptors[1], sizeof(descriptors[1])); std::memcpy(unplaced + 4, buffers[0], words * sizeof(UINT)); } + if (root_srv && mode != "dispatch-root-srv-unset") { + UINT64 addr0 = reinterpret_cast(buffers[0]); + UINT64 addr1 = reinterpret_cast(buffer2); + if (mode == "dispatch-root-srv-offset") { + addr0 += 16; + addr1 += 32; + } else if (mode == "dispatch-root-srv-upload") { + auto* const up = static_cast(reinterpret_cast(invoke(list, 148, words * sizeof(UINT), 256))); + if (!up) return 81; + std::memcpy(up, buffers[0], words * sizeof(UINT)); + addr0 = reinterpret_cast(up) + 16; + } else if (mode == "dispatch-root-srv-null") { + addr0 = 0; + } else if (mode == "dispatch-root-srv-unaligned") { + addr0 += 2; + } else if (mode == "dispatch-root-srv-unaligned-16") { + addr0 += 4; + } else if (mode == "dispatch-root-srv-unmapped" || mode == "dispatch-root-srv-copied") { + addr0 = between; + } else if (mode == "dispatch-root-srv-same-buffer") { + addr0 = reinterpret_cast(buffers[1]); + } + invoke(list, 43, 2, addr0); + if (mode != "dispatch-root-srv-unset-second") invoke(list, 43, 3, addr1); + } + if (mode == "dispatch-root-srv-root-changed") { + invoke(list, 33, word(slot67_other_root)); + invoke(list, 33, word(slot67_root)); + } else if (mode == "dispatch-root-srv-same-root") { + invoke(list, 33, word(slot67_root)); + } else if (mode == "dispatch-root-srv-reset") { + if (FAILED(static_cast(invoke(list, 9))) || FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; + bind(); + } if (mode != "dispatch-missing-word") invoke(list, 37, 0, constants[0], 0); invoke(list, 40, 0, 2, word(graphics), 0); invoke(list, 39, 0, 1, word(&constants[1]), 1); @@ -352,7 +400,7 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (FAILED(static_cast(invoke(list, 9))) || FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; bind(); } - if (heap_record) invoke(list, 39, 0, 1, word(&constants[2]), 2); + if (heap_record || root_srv) invoke(list, 39, 0, 1, word(&constants[2]), 2); if (heap_word) { // The index buffer of table byte 96, in this recording's upload memory (list slot 148). Byte 288 + 336 * 1 // holds the index, 2; every other word names record 0 or 1, the output's descriptor. @@ -372,7 +420,7 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin mode == "dispatch-indirect-counted", mode == "dispatch-indirect-outside"); else if (mode == "dispatch-reference-2" || mode == "dispatch-reference-5") invoke(list, 14, mode == "dispatch-reference-2" ? 2 : 5, 1, 1); - else if (mode != "dispatch-none") invoke(list, 14, 3, 2, 2); + else if (mode != "dispatch-none" && mode != "dispatch-root-srv-none") invoke(list, 14, 3, 2, 2); if (FAILED(static_cast(invoke(list, 9)))) return 75; invoke(queue, 10, 1, word(&list)); if (FAILED(static_cast(invoke(queue, 14, word(fence), 1)))) return 76;