From 587fc6d20277c0ced1f77476285968ec04d959f9 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Fri, 27 Nov 2026 10:15:29 +0100 Subject: [PATCH 1/3] native: read formatted loads through a byte-address rewritten descriptor formatted_byte_load asked resource() for raw_vector_srv even when the descriptor was the byte-address rewrite (stride cleared in word 1), so a tbuffer_load_format_* through such a window was refused with "non-contiguous resource descriptor", for a table descriptor and for a GPU-selected heap descriptor under the raw_buffer contract. It now picks byte_window_srv by the same rule as the raw MUBUF load. Conversion, the getDimensions element bound and the raw loads are unchanged. Tests: - native_global_srv_heap_replay_check.py: a 32_UINT tbuffer load through the heap window is recorded, compiled and replayed for selections 0 and 1, with the cross-slot mismatch control; the loop guard refuses it; an 8_8_8_8_UNORM load through the window compiles. - native_mtbuf_check.py: the 11-format value check also runs through a byte window of its table SRV (native_store_replay accepts the window binding as the same raw view). - native_direct_container_check.py: compute table windows with both formats compile; without the byte-count product they are refused. Refs #3023 Co-Authored-By: Claude Opus 5.5 (cherry picked from commit e67f10177bbfb097234d1ecf8461142f1489acf1) --- .../native-global-srv-heap-replay.md | 24 ++++++++ src/gfx1013_compute_mtbuf.inl | 9 ++- tests/native_direct_container_check.py | 13 +++++ tests/native_global_srv_heap_replay_check.py | 55 ++++++++++++------- tests/native_mtbuf_check.py | 19 +++++-- tests/native_store_replay.cpp | 3 +- 6 files changed, 96 insertions(+), 27 deletions(-) diff --git a/docs/experiments/native-global-srv-heap-replay.md b/docs/experiments/native-global-srv-heap-replay.md index f267ca20ca..ff3f7a0e22 100644 --- a/docs/experiments/native-global-srv-heap-replay.md +++ b/docs/experiments/native-global-srv-heap-replay.md @@ -141,6 +141,18 @@ ctest --preset dev --no-tests=error -R "^native_global_srv_heap_replay(_warp|_ha - With the high-word check removed, both tests fail at the `mov_high` controls. - `ctest --preset dev --no-tests=error -R "native_|startup_compute|compile_dxil" -j 8`: 415 tests, 404 passed and 11 skipped (77, WARP). +- Formatted loads through the byte window (original #3034 result for #3023): `tbuffer_load_format_*` through the rewritten descriptor now reads + the same raw view as `buffer_load_dword` (`src/gfx1013_compute_mtbuf.inl` picks `byte_window_srv` when word 1 is the + stride-cleared word). Before, it was refused with "non-contiguous resource descriptor". On the local capture with the + raw contract forced and a typed heap load prototyped (both uncommitted), 861 of the 2,689 requests stopped first at + this refusal; with the change they move on to other, already-known refusals. `native_global_srv_heap_replay_hardware` + passes with 94 assertions (record, compile and replay of a 32_UINT `tbuffer_load_format_x` through the heap window + for selections 0 and 1, the cross-slot mismatch control, the loop guard for the formatted load, and a compile-only + 8_8_8_8_UNORM case). `native_mtbuf_hardware` repeats its 11-format value check through a byte window of its table SRV + and matches, including the element at the end of the view that returns 0 (`tests/native_store_replay.cpp` accepts + the window binding as the same raw view). `native_direct_container` compiles both formats through a compute table + window and refuses the window without the byte-count product. Against `837728dd` the heap check fails at the + `twindow_loop` shape (text "non-contiguous resource descriptor"). ## Limits @@ -153,6 +165,18 @@ ctest --preset dev --no-tests=error -R "^native_global_srv_heap_replay(_warp|_ha byte-address rewrite consumes it. The fixture's descriptor words are never evaluated, so a stride above 1 and the size rule of the contract are not exercised. The HLSL path's `heap_stride_srv` (`src/gfx1013_compute_native.cpp`, used by `tests/native_compute_grid.cpp`) is unchanged. +- A formatted load (`tbuffer_load_format_*`) bounds its element with the size of the desktop raw view + (`getDimensions`), not with the guest window's byte count, and returns 0 for the whole element when it does not fit. + A runtime that binds a byte window, as a table view or as a GPU-selected heap slot, must create the raw view with + exactly the guest window's byte count. The descriptor's DST_SEL (word 3) is not applied: only the identity channel + order is translated, and it is not checked. In the startup dispatch, the in-process route + (`translate_compute_natively`, `src/startup_stubs/d3d12_compute_dispatch.inl`) binds only `raw_vector_srv` inputs + and falls through to the manifest route for a byte window. A published manifest names a table byte window as + `srv buf table `, as for the raw byte window; the dispatch then binds the table descriptor as a raw + view of + `max(stride, 1) * num_records` bytes (`indirect_table_buffer`, `src/startup_stubs/d3d12_draw.inl`), the guest + window's byte count, or of the title's own view size for a view token. No fixture runs this manifest path for a + window. - Typed loads (`buffer_load_format_*`) through a heap descriptor and scalar loads through the rewritten descriptor stay refused. The startup runtime does not pass a contract yet, so none of this reaches a title run (#3023). diff --git a/src/gfx1013_compute_mtbuf.inl b/src/gfx1013_compute_mtbuf.inl index 9c8ff13124..2a8a85b88b 100644 --- a/src/gfx1013_compute_mtbuf.inl +++ b/src/gfx1013_compute_mtbuf.inl @@ -1,7 +1,8 @@ // MTBUF uses the instruction's explicit format and the descriptor's byte range. // Format numbers follow tools/disasm_rdna2.py MTBUF_FORMATS. Conversion and // unaligned addressing follow gfx2hlsl.tbuffer / ldu, cross-checked against -// Victory 9376fd6 format_load. Only the runtime-checked identity raw SRV is used. +// Victory 9376fd6 format_load. Only the runtime-checked identity raw SRV is used, or +// its byte window (the byte-address rewrite of the descriptor, read as the same raw view). enum class ChannelNumber { unorm, snorm, uscaled, sscaled, uint_, sint, float_ }; struct MtbufFamily { unsigned first, last, bits, components; @@ -53,7 +54,11 @@ void formatted_byte_load(const Inst &i, const State &s) { refuse(i.pc, "MTBUF destination tuple overflow"); const unsigned width = family->bits; const auto numeric = static_cast(unsigned(family->first_number) + format - family->first); - const auto handle = resource(i, s, (i.b >> 16 & 31) * 4, ComputeViewKind::raw_vector_srv, 4); + // The byte-address rewrite of a descriptor (stride cleared in word 1) is read as the same raw view, as for MUBUF. + const unsigned base = (i.b >> 16 & 31) * 4; + const auto handle = resource(i, s, base, s.at(base + 1).type == Symbol::Type::zero_stride_word + ? ComputeViewKind::byte_window_srv + : ComputeViewKind::raw_vector_srv, 4); const unsigned scalar_offset = i.b >> 24; auto addr = to_string(i.a & 4095); if (scalar_offset != 125 && scalar_offset != 128) diff --git a/tests/native_direct_container_check.py b/tests/native_direct_container_check.py index af6dc525e4..c7c915eda6 100644 --- a/tests/native_direct_container_check.py +++ b/tests/native_direct_container_check.py @@ -401,6 +401,19 @@ def atomic_program(instructions): broken[10] = 0xbf800000 # Leave NUM_RECORDS in elements instead of bytes. check("byte-count-missing-product", "gfx1013-container-ps", patched_pixel(len(broken), broken, table=True), "non-contiguous resource descriptor") + # The same rewrite in compute, read by MTBUF loads through s[28:31] (v_mov_b32 v5, 0 as the offset): + # tbuffer_load_format_x v8, v5, s[28:31], 0 format:[BUF_FMT_32_UINT] offen and + # tbuffer_load_format_xyzw v[8:11], v5, s[28:31], 0 format:[BUF_FMT_8_8_8_8_UNORM] offen. + tbuffer_view = [*byte_view[:13], 0x7e0a0280] + check("compute-tbuffer-byte-window", cs, compute(words(*tbuffer_view, 0xe8a01000, 0x80070805, end), table=True)) + check("compute-tbuffer-byte-window-unorm", cs, + compute(words(*tbuffer_view, 0xe9c31000, 0x80070805, end), table=True)) + # Over-acceptance control only: without the byte-count product the window fields do not match. + tbuffer_broken = tbuffer_view.copy() + tbuffer_broken[10] = 0xbf800000 + check("compute-tbuffer-byte-count-missing-product", cs, + compute(words(*tbuffer_broken, 0xe8a01000, 0x80070805, end), table=True), + "non-contiguous resource descriptor") # Convert v11 to a half in the high word of v6, retaining v6.low. # Widen the selected high word back from a scalar source into v7. halves = [0x7e0c02ff, 0xa5a53600, 0x7e1602ff, 0x3f801000, 0x7e0c14f9, 0x06150b, diff --git a/tests/native_global_srv_heap_replay_check.py b/tests/native_global_srv_heap_replay_check.py index fba18e6179..adade303b3 100644 --- a/tests/native_global_srv_heap_replay_check.py +++ b/tests/native_global_srv_heap_replay_check.py @@ -246,14 +246,18 @@ def without(prefix): load = words_list.index(0xe0301000) # buffer_load_dword v2, v1, s[20:23], 0 offen store = words_list.index(0xe0701000) # buffer_store_dword v2, v1, s[12:15], 0 offen - def window(rewritten=rewrite, prefix=(), store_word=0x80030201): + def window(rewritten=rewrite, prefix=(), store_word=0x80030201, load_words=(0xe0301000, 0x80060201)): """PROGRAM with the rewrite after the heap load and the load through s[24:27].""" program = list(words_list) - program[load + 1] = 0x80060201 # buffer_load_dword v2, v1, s[24:27], 0 offen + program[load:load + 2] = load_words # default: buffer_load_dword v2, v1, s[24:27], 0 offen program[store + 1] = store_word return program[:after_wait] + list(prefix) + list(rewritten) + program[after_wait:] WINDOW = window() + # tbuffer_load_format_x v2, v1, s[24:27], 0 format:[BUF_FMT_32_UINT] offen: a formatted load through the window. + # 32_UINT converts nothing, so the output is the slot data as for WINDOW. + TBUFFER_LOAD = (0xe8a01000, 0x80060201) + TWINDOW = window(load_words=TBUFFER_LOAD) second_load = window([0xbe980320 if w == 0xbe980314 else w for w in rewrite]) second_load[after_wait - 1:after_wait - 1] = [0xf4080801, 0x22000000] # before the s_waitcnt # The branch word sits at after_wait + 1; its target is next pc + 4 * simm16, here the s_lshl_b32 at word lshl. @@ -278,6 +282,9 @@ def window(rewritten=rewrite, prefix=(), store_word=0x80030201): # s_cmp_lg_u32 s16, s16 and s_cbranch_scc1 back to the s_lshl_b32 before the heap load (never taken): the # loop contains the heap load, which would run again for another selection "window_loop": (loop_around_load, "heap byte window loaded inside a loop"), + # the same loop around the heap load, read by the formatted load + "twindow_loop": (window(prefix=loop_around_load[after_wait:after_wait + 2], load_words=TBUFFER_LOAD), + "heap byte window loaded inside a loop"), } for name, (program, expected) in shapes.items(): directory = base / ("shape_" + name) @@ -311,6 +318,10 @@ def shader_request(name, program, **stage): # does not contain the load, which runs once "window_loop_after_load": (window(prefix=(0xbf071010, 0xbf85fffe)), "a loop after the heap load does not refuse the window, a .cso is published"), + # tbuffer_load_format_xyzw v[2:5], v1, s[24:27], 0 format:[BUF_FMT_8_8_8_8_UNORM] offen: a converting format + # through the window (values through a window are checked by native_mtbuf_check.py on a table window) + "twindow_unorm": (window(load_words=(0xe9c31000, 0x80060201)), + "a converting formatted load through the window compiles and publishes a .cso"), } for name, (program, message) in compiled_shapes.items(): directory, window_stem = shader_request(name, program) @@ -319,25 +330,29 @@ def shader_request(name, program, **stage): code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) require(code == 0 and "requests=1 compiled=1 refused=0" in out and (out_dir / (window_stem[len("req_"):] + ".cs.cso")).exists(), "compile_dxil: " + message) - window_outputs = {} - for n in (0, 1): - directory, window_stem = shader_request(f"window{n}", WINDOW) - code, out, err = run([fixture, "record", sdk, cache, directory / (window_stem + ".cdx"), adapter, n, "ok"]) - require(code == 0 and "output matches slot %d data" % n in out, - f"record window select {n}: u0 equals the slot {n} data read through the rewritten descriptor") - out_dir = base / f"window{n}_out" - code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) - cso = out_dir / (window_stem[len("req_"):] + ".cs.cso") - require(code == 0 and "requests=1 compiled=1 refused=0" in out and cso.exists(), - f"compile_dxil window select {n}: compiled and published a .cso") - window_outputs[n] = (directory, window_stem, cso) + # The raw load (window) and the formatted load (twindow) through the rewritten descriptor. + for label, program in (("window", WINDOW), ("twindow", TWINDOW)): + window_outputs = {} + for n in (0, 1): + directory, window_stem = shader_request(f"{label}{n}", program) + code, out, err = run([fixture, "record", sdk, cache, directory / (window_stem + ".cdx"), adapter, n, "ok"]) + require(code == 0 and "output matches slot %d data" % n in out, + f"record {label} select {n}: u0 equals the slot {n} data read through the rewritten descriptor") + out_dir = base / f"{label}{n}_out" + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + cso = out_dir / (window_stem[len("req_"):] + ".cs.cso") + require(code == 0 and "requests=1 compiled=1 refused=0" in out and cso.exists(), + f"compile_dxil {label} select {n}: compiled and published a .cso") + window_outputs[n] = (directory, window_stem, cso) + code, out, err = run([fixture, "replay", sdk, cache, directory / (window_stem + ".cdx"), cso, + directory / (window_stem + ".views"), adapter, "ok", n]) + require(code == 0 and "output matches slot %d data" % n in out, + f"replay {label} select {n}: output equals slot {n} data") + directory, window_stem, cso = window_outputs[0] code, out, err = run([fixture, "replay", sdk, cache, directory / (window_stem + ".cdx"), cso, - directory / (window_stem + ".views"), adapter, "ok", n]) - require(code == 0 and "output matches slot %d data" % n in out, f"replay window select {n}: output equals slot {n} data") - directory, window_stem, cso = window_outputs[0] - code, out, err = run([fixture, "replay", sdk, cache, directory / (window_stem + ".cdx"), cso, - directory / (window_stem + ".views"), adapter, "ok", 1]) - require(code == 1 and "mismatch word 0" in out, "replay window select 0 compared with slot 1 data reports a mismatch") + directory / (window_stem + ".views"), adapter, "ok", 1]) + require(code == 1 and "mismatch word 0" in out, + f"replay {label} select 0 compared with slot 1 data reports a mismatch") missing = base / "missing" / (stem + ".views") code, out, err = replay(selections[0], outputs[0], missing, "refused", 0) diff --git a/tests/native_mtbuf_check.py b/tests/native_mtbuf_check.py index a240b9c145..9838ccfb69 100644 --- a/tests/native_mtbuf_check.py +++ b/tests/native_mtbuf_check.py @@ -15,10 +15,19 @@ PACKED = struct.pack("<6I", 0x7fff8000, 0x40008001, 0x007fff81, 0xfc003c00, 0x0001bc00, 0x42987ec5) -def program(unsigned): +# The byte-address rewrite of the SRV descriptor s[32:35] in place (LLVM 15): s_waitcnt lgkmcnt(0); +# s_bfe_u32 s40, s33, 0xe0010 (stride); s_max_u32 s40, s40, 1; s_mul_i32 s34, s34, s40 (byte count); +# s_and_b32 s33, s33, 0xc000ffff (stride cleared); s_and_b32 s35, s35, 0xcfffffff; s_or_b32 s35, s35, 0x30000000. +BYTE_WINDOW = [0xbf8cc07f, 0x93a8ff21, 0x000e0010, 0x84a88128, 0x93222822, 0x8721ff21, 0xc000ffff, + 0x8723ff23, 0xcfffffff, 0x8823ff23, 0x30000000] + + +def program(unsigned, window=False): # Load a raw SRV and UAV from separate table parameters. One writer per group. + # With window, every MTBUF load reads the byte window of the SRV (same raw view, same expected values). words = [sop1(3, 20, 4), sop1(3, 21, 128), sop1(3, 22, 5), sop1(3, 23, 128), 0xf4080000 | 32 << 6 | 10, 0xfa000020, 0xf4080000 | 36 << 6 | 11, 0xfa000020, + *(BYTE_WINDOW if window else ()), scalar(0x1e, 7, 6, 135), vmove(8, 7), sop1(3, 126, 129)] pos = 0 for index, (fmt, channels, disp) in enumerate(CASES): @@ -76,8 +85,8 @@ def main(cli, gpu, sdk): start = 8 + 32 * group row = expected(group) reference[start:start + len(row)] = row - for unsigned in (False, True): - words = program(unsigned) + for unsigned, window in ((False, False), (True, False), (False, True)): + words = program(unsigned, window) marker = write_request(work, words, root.read_bytes(), sa) dest = work / "result.bin" run = subprocess.run([gpu, sdk, marker, work/"cache", "0", dest, "--direct"]) @@ -90,6 +99,7 @@ def main(cli, gpu, sdk): assert differences and set(differences) <= {8, 9, 40, 41}, differences else: assert not differences, [(i, hex(actual[i]), hex(reference[i])) for i in differences] + words = program(False) # the guards below change the plain (non-window) program insn = next(i for i, w in enumerate(words) if w >> 26 == 0x3a) for op, error in ((words[insn] | (1 << 13), "without index"), (0xe8001000 | 24 << 19 | 3 << 16, "absent component")): @@ -99,7 +109,8 @@ def main(cli, gpu, sdk): reject = subprocess.run([cli, sdk, work/"cache", "gfx1013-direct-cs@0", marker, work/"bad.cso"], capture_output=True, text=True) assert reject.returncode and error in reject.stderr and not (work/"bad.cso").exists(), reject.stderr - print(f"MTBUF matched {2 * len(row)} result words and all guards; changed format, index and component controls passed.") + print(f"MTBUF matched {2 * len(row)} result words, also through the SRV byte window, and all guards; " + "changed format, index and component controls passed.") if __name__ == "__main__": diff --git a/tests/native_store_replay.cpp b/tests/native_store_replay.cpp index 43b7af3df3..9292eee5cc 100644 --- a/tests/native_store_replay.cpp +++ b/tests/native_store_replay.cpp @@ -161,7 +161,8 @@ int wmain(int argc, wchar_t **argv) { if (position>=hd.NumDescriptors) return 2; auto cpu=heap->GetCPUDescriptorHandleForHeapStart();cpu.ptr+=UINT64(position)*step; Window w;w.write=compute_buffer_uav(b.kind); - const bool vector_bytes = b.kind == ComputeViewKind::raw_vector_srv; + // A byte window is the byte-address rewrite of the same raw table view. + const bool vector_bytes = b.kind == ComputeViewKind::raw_vector_srv || b.kind == ComputeViewKind::byte_window_srv; const bool root_bytes = b.kind == ComputeViewKind::root_buffer_srv; if (!w.write && b.kind!=ComputeViewKind::typed_buffer_srv && b.kind!=ComputeViewKind::buffer_srv && !vector_bytes && !root_bytes) return 2; const bool raw=root_bytes || vector_bytes || b.kind==ComputeViewKind::buffer_srv || b.kind==ComputeViewKind::raw_buffer_uav; From 809521892622eee879be56e53951da83a0342444 Mon Sep 17 00:00:00 2001 From: RonLogic <307541314+RonLogic@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:04:00 +0200 Subject: [PATCH 2/3] runtime: validate published MTBUF byte-window channel order --- .../native-global-srv-heap-replay.md | 20 ++-- src/direct_compute_cache.cpp | 9 +- src/gfx1013_compute_mtbuf.inl | 6 +- src/gfx1013_compute_native.h | 1 + src/gfx1013_direct_compute.inl | 7 +- src/startup_stubs/d3d12_compute_dispatch.inl | 9 +- src/startup_stubs/d3d12_draw.inl | 7 +- .../cmake/startup_compute_mtbuf_window.cmake | 10 ++ tests/startup_compute_mtbuf_window_check.py | 112 ++++++++++++++++++ tests/startup_stream_consumer.cpp | 10 ++ 10 files changed, 171 insertions(+), 20 deletions(-) create mode 100644 tests/cmake/startup_compute_mtbuf_window.cmake create mode 100644 tests/startup_compute_mtbuf_window_check.py diff --git a/docs/experiments/native-global-srv-heap-replay.md b/docs/experiments/native-global-srv-heap-replay.md index ff3f7a0e22..2a726fe379 100644 --- a/docs/experiments/native-global-srv-heap-replay.md +++ b/docs/experiments/native-global-srv-heap-replay.md @@ -166,17 +166,15 @@ ctest --preset dev --no-tests=error -R "^native_global_srv_heap_replay(_warp|_ha size rule of the contract are not exercised. The HLSL path's `heap_stride_srv` (`src/gfx1013_compute_native.cpp`, used by `tests/native_compute_grid.cpp`) is unchanged. - A formatted load (`tbuffer_load_format_*`) bounds its element with the size of the desktop raw view - (`getDimensions`), not with the guest window's byte count, and returns 0 for the whole element when it does not fit. - A runtime that binds a byte window, as a table view or as a GPU-selected heap slot, must create the raw view with - exactly the guest window's byte count. The descriptor's DST_SEL (word 3) is not applied: only the identity channel - order is translated, and it is not checked. In the startup dispatch, the in-process route - (`translate_compute_natively`, `src/startup_stubs/d3d12_compute_dispatch.inl`) binds only `raw_vector_srv` inputs - and falls through to the manifest route for a byte window. A published manifest names a table byte window as - `srv buf table `, as for the raw byte window; the dispatch then binds the table descriptor as a raw - view of - `max(stride, 1) * num_records` bytes (`indirect_table_buffer`, `src/startup_stubs/d3d12_draw.inl`), the guest - window's byte count, or of the title's own view size for a view token. No fixture runs this manifest path for a - window. + (`getDimensions`) and returns 0 for the whole element when it does not fit. A runtime that binds a byte window + must create the raw view with the exact guest window's byte count. The heap replay uses identity channel order. + A published table manifest marks the MTBUF window with `srv buf table identity_dst_sel`, including + after a frontend cache hit. The compute binder checks word 3's DST_SEL of the hardware descriptor or the + component mapping of a slot 18 buffer SRV before binding the raw view for the exact range. The in-process + path falls through to that manifest for a byte window. +- `startup_compute_mtbuf_window_{hardware,warp}` compares 12 pairs and the surrounding guards through the published + path for both a hardware descriptor and a buffer SRV token. A 44-byte window holds five full pairs. The partial + pair and the later pairs read zero. Swapped X/Y selectors refuse before Dispatch, and the output keeps its sentinel. - Typed loads (`buffer_load_format_*`) through a heap descriptor and scalar loads through the rewritten descriptor stay refused. The startup runtime does not pass a contract yet, so none of this reaches a title run (#3023). diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index 2c4ad29e47..cddc29dc72 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -90,7 +90,7 @@ Bytes encode(const NativeComputeShader &program) { for (const auto &b : program.bindings) { word(out, static_cast(b.kind)); for (unsigned n : {b.root_parameter, b.byte_offset, b.shader_register, b.required_bytes, b.array_count, - b.array_position, b.image_dimension, unsigned(b.scalar_table)}) + b.array_position, b.image_dimension, unsigned(b.scalar_table), unsigned(b.requires_identity_dst_sel)}) word(out, n); } word(out, static_cast(program.constants.size())); @@ -134,6 +134,7 @@ NativeComputeShader decode(std::string_view bytes) { auto kind = static_cast(in.count(static_cast(ComputeViewKind::float3_texture_uav))); ComputeViewBinding b{kind, in.word(), in.word(), in.word(), in.word(), in.word(), in.word(), in.count(7)}; b.scalar_table = static_cast(in.count(unsigned(ComputeViewBinding::ScalarTable::srv))); + b.requires_identity_dst_sel = in.count(1) != 0; const bool sampler_heap = kind == ComputeViewKind::heap_sampler; if (!b.array_count || b.array_position >= b.array_count || (sampler_heap ? b.root_parameter != compute_sampler_heap @@ -795,8 +796,10 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh return refuse("SRV registers not contiguous"); if (b.kind == ComputeViewKind::buffer_srv || b.kind == ComputeViewKind::raw_vector_srv || b.kind == ComputeViewKind::byte_window_srv) { - srv_lines << "srv " << b.shader_register << " buf table " << b.root_parameter << ' ' << b.byte_offset - << '\n'; + srv_lines << "srv " << b.shader_register << " buf table " << b.root_parameter << ' ' << b.byte_offset; + if (b.requires_identity_dst_sel) + srv_lines << " identity_dst_sel"; + srv_lines << '\n'; } else if (b.kind == ComputeViewKind::texture_srv && b.image_dimension == 1 && b.array_count == 1) { srv_lines << "srv " << b.shader_register << " tex2d table " << b.root_parameter << ' ' << b.byte_offset << '\n'; diff --git a/src/gfx1013_compute_mtbuf.inl b/src/gfx1013_compute_mtbuf.inl index 2a8a85b88b..36a7cfd018 100644 --- a/src/gfx1013_compute_mtbuf.inl +++ b/src/gfx1013_compute_mtbuf.inl @@ -56,9 +56,9 @@ void formatted_byte_load(const Inst &i, const State &s) { const auto numeric = static_cast(unsigned(family->first_number) + format - family->first); // The byte-address rewrite of a descriptor (stride cleared in word 1) is read as the same raw view, as for MUBUF. const unsigned base = (i.b >> 16 & 31) * 4; - const auto handle = resource(i, s, base, s.at(base + 1).type == Symbol::Type::zero_stride_word - ? ComputeViewKind::byte_window_srv - : ComputeViewKind::raw_vector_srv, 4); + const bool window = s.at(base + 1).type == Symbol::Type::zero_stride_word; + const auto kind = window ? ComputeViewKind::byte_window_srv : ComputeViewKind::raw_vector_srv; + const auto handle = resource(i, s, base, kind, 4, nullptr, window); const unsigned scalar_offset = i.b >> 24; auto addr = to_string(i.a & 4095); if (scalar_offset != 125 && scalar_offset != 128) diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index 1ba36eaaa4..ea3382d2cc 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -80,6 +80,7 @@ struct ComputeViewBinding { unsigned image_dimension = 1; // ISA dimension field; 1 denotes Texture2D. enum class ScalarTable { unknown, reflected_cbv, declared_cbv, srv }; ScalarTable scalar_table = ScalarTable::unknown; + bool requires_identity_dst_sel = false; }; bool apply_reflected_table_use(ComputeViewBinding &binding, const GuestShaderStage &stage, std::optional packed_sgpr = {}); diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index f46ebb6c8b..0375e62ddc 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -363,7 +363,7 @@ struct DirectCompute { } std::set> read_write_raw_views; string resource(const Inst &i, const State &s, unsigned base, ComputeViewKind kind, unsigned bytes, - unsigned *bound_register = nullptr) { + unsigned *bound_register = nullptr, bool requires_identity_dst_sel = false) { const auto &symbol = s.at(base); const bool indexed = symbol.type == Symbol::Type::indexed_descriptor; if (indexed && symbol.value == compute_resource_heap) @@ -372,6 +372,8 @@ struct DirectCompute { (kind == ComputeViewKind::buffer_srv || kind == ComputeViewKind::raw_vector_srv || kind == ComputeViewKind::byte_window_srv) && read_write_raw_views.count({symbol.value, symbol.offset})) { + if (requires_identity_dst_sel) + refuse(i.pc, "a writable MTBUF byte window has no verified view contract"); // Both instructions read the same descriptor table entry. A // second, SRV binding would conflict with its writable resource state. kind = ComputeViewKind::raw_buffer_uav; @@ -384,6 +386,9 @@ struct DirectCompute { }); if (it == analysis.result.bindings.end()) throw std::logic_error("missing direct binding"); + if (requires_identity_dst_sel) + for (unsigned j = 0; j < count; ++j) + it[j].requires_identity_dst_sel = true; if (bound_register) *bound_register = it->shader_register; const bool raw = kind == ComputeViewKind::raw_buffer_uav || kind == ComputeViewKind::buffer_srv || kind == ComputeViewKind::raw_vector_srv || kind == ComputeViewKind::byte_window_srv || diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index e0cb2a5a3c..770f4eeca9 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -34,6 +34,7 @@ struct ComputeTranslation { std::uint32_t at = 0, times = 0; Source source = root_constant; D3D12_UAV_DIMENSION uav_dimension = D3D12_UAV_DIMENSION_UNKNOWN; + bool requires_identity_dst_sel = false; bool root = false; bool atomic_uint_texture = false; unsigned channels = 4; @@ -172,6 +173,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 table %d %d identity_dst_sel%n", &i, &a, &b, &used) == 3 && whole() && + i == tr.srvs.size()) { + tr.srvs.push_back({a, b}); + tr.srvs.back().requires_identity_dst_sel = true; + } 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}); @@ -593,7 +599,8 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& } if (!output) { // Each condition of a complete GPU-backed buffer range has its own reason. - const IndirectBufferView view = indirect_table_buffer(self, words, false, &reason, 16u << 20, true); + const IndirectBufferView view = indirect_table_buffer(self, words, false, &reason, 16u << 20, true, + slot.requires_identity_dst_sel); if (view.source == 1) InterlockedIncrement(&compute_inputs_gpu_copied); if (view.source == 2) { InterlockedIncrement(&compute_inputs_snapshot); diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 7d1901c53a..04d2f35429 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2362,7 +2362,7 @@ bool title_input_snapshot_enabled() IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* words, bool allow_address_alias = false, const char** why = nullptr, u64 limit = u64{4} << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP, - bool allow_title_snapshot = false) + bool allow_title_snapshot = false, bool requires_identity_dst_sel = false) { const auto refuse = [why](const char* reason) { if (why) *why = reason; @@ -2379,6 +2379,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor if (words[1] < view_records().size()) record = view_records()[words[1]]; ReleaseSRWLockShared(¬e_lock); if (record.slot == 17 && record.desc_bytes >= 12) { + if (requires_identity_dst_sel) return refuse("an MTBUF byte window requires a buffer SRV"); UINT size = 0; std::memcpy(&address, record.desc, 8); std::memcpy(&size, record.desc + 8, 4); @@ -2386,6 +2387,8 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor } else if (record.slot == 18 && record.desc_bytes >= 40) { D3D12_SHADER_RESOURCE_VIEW_DESC view{}; std::memcpy(&view, record.desc, 40); + if (requires_identity_dst_sel && view.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING) + return refuse("an MTBUF byte window requires identity component mapping"); owner = as_wrapper(reinterpret_cast(record.resource)); if (!owner || owner->own().kind != resource_kind || !owner->own().real || view.ViewDimension != D3D12_SRV_DIMENSION_BUFFER) return refuse("an input view token is not a buffer view of a desktop resource"); @@ -2416,6 +2419,8 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor return refuse("an input view token is not a buffer view of a desktop resource"); } } else { + if (requires_identity_dst_sel && (words[3] & 0xfffu) != 0xfacu) + return refuse("an MTBUF byte window requires identity DST_SEL"); address = words[0] | (u64{words[1] & 0xffff} << 32); stride = (words[1] >> 16) & 0x3fff; bytes = u64{stride ? stride : 1} * words[2]; diff --git a/tests/cmake/startup_compute_mtbuf_window.cmake b/tests/cmake/startup_compute_mtbuf_window.cmake new file mode 100644 index 0000000000..d015bde331 --- /dev/null +++ b/tests/cmake/startup_compute_mtbuf_window.cmake @@ -0,0 +1,10 @@ +if(TARGET compile_dxil AND TARGET startup_stream_consumer AND TARGET offscreen_check AND EXISTS "${INTAKE_PYTHON}" + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_mtbuf_window_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_mtbuf_window_check.py" + "$" "$" "$" + "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(startup_compute_mtbuf_window_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/startup_compute_mtbuf_window_check.py b/tests/startup_compute_mtbuf_window_check.py new file mode 100644 index 0000000000..d24a3e0793 --- /dev/null +++ b/tests/startup_compute_mtbuf_window_check.py @@ -0,0 +1,112 @@ +"""Dispatch a published MTBUF byte window with matching and swapped DST_SEL.""" + +from pathlib import Path +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from native_gather_lod_check import render +from native_mtbuf_check import BYTE_WINDOW +from native_scalar_lds_check import scalar, sop1, vmove +from startup_compute_dispatch_check import dispatch, lines, prepare_case +from startup_compute_translate_check import state_a +from startup_gfx2hlsl_compute_check import SENTINEL, TGID_X, TGID_Y, TGID_Z, USER7, WORDS + + +INPUT = [0x01234567 + 0x1020304 * i & 0xffffffff for i in range(WORDS)] +STATE = state_a((32, 1, 1), USER7 | TGID_X | TGID_Y | TGID_Z) +IDENTITY = 0x0103efac +SWAPPED_XY = 0x0103efa5 +EXPECTED = INPUT[:10] + [0] * 14 + [SENTINEL] * (WORDS - 24) +GUARDS = [SENTINEL] * WORDS +VIEW = 'srv 0 buf table 1 0 identity_dst_sel' + + +def program(): + words = [ + sop1(3, 20, 6), sop1(3, 21, 128), + 0xf408080a, 0xfa000000, # SRV in s[32:35] + 0xf408090a, 0xfa000020, # UAV in s[36:39] + *BYTE_WINDOW, + scalar(0x26, 8, 8, 131), # y * 3 + scalar(0x26, 9, 9, 134), # z * 6 + scalar(0, 11, 7, 8), scalar(0, 11, 11, 9), + scalar(0x1e, 12, 11, 131), # 8 * flattened group + sop1(3, 126, 129), vmove(8, 12), # one writer per group + 0xe8001000 | 62 << 19 | 1 << 16, 0x80080a08, # tbuffer_load_format_xy R32G32_UINT + 0xe0741000, 0x80090a08, # buffer_store_dwordx2 v[10:11], v8 + 0xbf810000, + ] + return struct.pack('<%dI' % len(words), *words) + + +def prepare(work, adapter): + cache, env = prepare_case(work, adapter) + env.pop('X2W_NATIVE_SHADERS', None) + env.pop('X2W_NATIVE_SHADERS_ONLY', None) + (work / 'program').write_bytes(program()) + (work / 'state').write_bytes(STATE) + source = work / 'source.bin' + source.write_bytes(struct.pack('<%dI' % WORDS, *INPUT)) + env['X2W_TEST_DISPATCH_IN'] = str(source) + env['X2W_TEST_DISPATCH_FIELDS'] = str(work / 'fields.bin') + return cache, env + + +def run(work, consumer, env, word3, *, probe=False, mapping=None): + # The 44-byte input window holds five complete pairs and one dword. + (work / 'fields.bin').write_bytes(struct.pack('<6I', 11, 4, word3, 4, WORDS, 0)) + if mapping: + env = dict(env, X2W_TEST_DISPATCH_INPUT_VIEW=mapping) + return dispatch(work, consumer, env, 'dispatch-records32', probe=probe) + + +def compare(got, expected, result): + if got != expected: + word = next(i for i, (actual, want) in enumerate(zip(got, expected)) if actual != want) + raise AssertionError(f'word {word}: expected {expected[word]:08x}, read {got[word]:08x}\n{result.stderr[-3000:]}') + + +def main(cli, consumer, renderer, sdk, adapter): + wave = render(renderer, adapter, '--shader-wave32') + assert wave.returncode == 0, wave.stdout + wave.stderr + with TemporaryDirectory() as temp: + work = Path(temp) + cache, env = prepare(work, adapter) + got, result = run(work, consumer, env, IDENTITY, probe=True) + compare(got, GUARDS, result) + assert lines(result, 'Dispatch(3, 2, 2) refused: no translation'), result.stderr + [request] = cache.glob('req_*.c67') + key = request.stem.removeprefix('req_') + command = [cli, sdk, work / 'native', 'gfx1013-direct-cs@0', '--requests', cache] + for index, dest in enumerate((cache, work / 'warm')): + result = subprocess.run([*command, dest], capture_output=True, text=True, timeout=30) + assert result.returncode == 0 and f'frontend_cache_hit={index}' in result.stdout, result.stdout + result.stderr + manifest = dest / f'{key}.txt' + assert VIEW in manifest.read_text().splitlines(), manifest.read_text() + assert (cache / f'{key}.txt').read_bytes() == (work / 'warm' / f'{key}.txt').read_bytes() + + got, result = run(work, consumer, env, IDENTITY) + compare(got, EXPECTED, result) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1, result.stderr[-3000:] + assert not lines(result, 'refused: '), result.stderr[-3000:] + assert not [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + got, result = run(work, consumer, env, SWAPPED_XY) + compare(got, GUARDS, result) + refusal = 'Dispatch(3, 2, 2) refused: an MTBUF byte window requires identity DST_SEL' + assert len(lines(result, refusal)) == 1, result.stderr[-3000:] + got, result = run(work, consumer, env, IDENTITY, mapping='identity') + compare(got, EXPECTED, result) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1, result.stderr[-3000:] + assert not lines(result, 'refused: '), result.stderr[-3000:] + got, result = run(work, consumer, env, IDENTITY, mapping='swapped') + compare(got, GUARDS, result) + refusal = 'Dispatch(3, 2, 2) refused: an MTBUF byte window requires identity component mapping' + assert len(lines(result, refusal)) == 1, result.stderr[-3000:] + print(f'{adapter}: identity readback matched five pairs, seven out-of-range pairs and all guards. ' + 'Swapped X/Y refused for both descriptor forms. Cold and warm manifests matched.') + + +if __name__ == '__main__': + main(*sys.argv[1:]) diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 9a89c3dfe1..5c7ee9014c 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -363,6 +363,16 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin std::memset(reinterpret_cast(cpu + sizeof(descriptors[0])), 0, sizeof(descriptors[1])); std::memcpy(reinterpret_cast(cpu + 32), descriptors[1], sizeof(descriptors[1])); } + char input_mapping[16]{}; + const auto mapping_chars = GetEnvironmentVariableA("X2W_TEST_DISPATCH_INPUT_VIEW", input_mapping, sizeof(input_mapping)); + if (mode == "dispatch-records32" && mapping_chars && mapping_chars < sizeof(input_mapping)) { + const UINT mapping = std::strcmp(input_mapping, "swapped") == 0 + ? D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(1, 0, 2, 3) + : D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + D3D12_SHADER_RESOURCE_VIEW_DESC view{DXGI_FORMAT_R32_UINT, D3D12_SRV_DIMENSION_BUFFER, mapping}; + view.Buffer.NumElements = fields[0][0] * fields[0][1] / 4; + invoke(device, 18, word(placed[0]), word(&view), cpu); + } void* other_heap = nullptr; if (change_table_heap && (FAILED(static_cast(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), From b450fe44f8fadffd9d21d4c8d80bb3ad6e9bbbba Mon Sep 17 00:00:00 2001 From: romanv9 <154753195+romanv9@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:08:36 +0400 Subject: [PATCH 3/3] test: cover MTBUF byte-window refusals Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../native-global-srv-heap-replay.md | 4 ++-- tests/native_direct_container_check.py | 4 ++++ tests/startup_compute_mtbuf_window_check.py | 6 +++++- tests/startup_stream_consumer.cpp | 17 +++++++++++------ 4 files changed, 22 insertions(+), 9 deletions(-) diff --git a/docs/experiments/native-global-srv-heap-replay.md b/docs/experiments/native-global-srv-heap-replay.md index 2a726fe379..f58bcb9453 100644 --- a/docs/experiments/native-global-srv-heap-replay.md +++ b/docs/experiments/native-global-srv-heap-replay.md @@ -176,7 +176,7 @@ ctest --preset dev --no-tests=error -R "^native_global_srv_heap_replay(_warp|_ha path for both a hardware descriptor and a buffer SRV token. A 44-byte window holds five full pairs. The partial pair and the later pairs read zero. Swapped X/Y selectors refuse before Dispatch, and the output keeps its sentinel. - Typed loads (`buffer_load_format_*`) through a heap descriptor and scalar loads through the rewritten descriptor stay - refused. The startup runtime - does not pass a contract yet, so none of this reaches a title run (#3023). + refused. The startup runtime does not yet pass the required contract for GPU-selected heap loads, so that heap route + does not reach a title run (#3023). - The captured `select` must be the slot index the dispatch addresses; producing it from a title capture is outside this fixture. diff --git a/tests/native_direct_container_check.py b/tests/native_direct_container_check.py index 2d95ee9893..2bc652cf30 100644 --- a/tests/native_direct_container_check.py +++ b/tests/native_direct_container_check.py @@ -500,6 +500,10 @@ def atomic_program(instructions): check("compute-tbuffer-byte-count-missing-product", cs, compute(words(*tbuffer_broken, 0xe8a01000, 0x80070805, end), table=True), "non-contiguous resource descriptor") + # A writable access and the MTBUF read use the same table descriptor; the read has no verified view contract. + check("compute-tbuffer-writable-byte-window", cs, + compute(words(*tbuffer_view, 0xe0701000, 0x80070805, 0xe8a01000, 0x80070805, end), table=True), + "a writable MTBUF byte window has no verified view contract") # Convert v11 to a half in the high word of v6, retaining v6.low. # Widen the selected high word back from a scalar source into v7. halves = [0x7e0c02ff, 0xa5a53600, 0x7e1602ff, 0x3f801000, 0x7e0c14f9, 0x06150b, diff --git a/tests/startup_compute_mtbuf_window_check.py b/tests/startup_compute_mtbuf_window_check.py index d24a3e0793..2018ceeeec 100644 --- a/tests/startup_compute_mtbuf_window_check.py +++ b/tests/startup_compute_mtbuf_window_check.py @@ -104,8 +104,12 @@ def main(cli, consumer, renderer, sdk, adapter): compare(got, GUARDS, result) refusal = 'Dispatch(3, 2, 2) refused: an MTBUF byte window requires identity component mapping' assert len(lines(result, refusal)) == 1, result.stderr[-3000:] + got, result = run(work, consumer, env, IDENTITY, mapping='cbv') + compare(got, GUARDS, result) + refusal = 'Dispatch(3, 2, 2) refused: an MTBUF byte window requires a buffer SRV' + assert len(lines(result, refusal)) == 1, result.stderr[-3000:] print(f'{adapter}: identity readback matched five pairs, seven out-of-range pairs and all guards. ' - 'Swapped X/Y refused for both descriptor forms. Cold and warm manifests matched.') + 'Swapped X/Y and a CBV token refused. Cold and warm manifests matched.') if __name__ == '__main__': diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 102781412e..9bff52d9ae 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -390,12 +390,17 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin char input_mapping[16]{}; const auto mapping_chars = GetEnvironmentVariableA("X2W_TEST_DISPATCH_INPUT_VIEW", input_mapping, sizeof(input_mapping)); if (mode == "dispatch-records32" && mapping_chars && mapping_chars < sizeof(input_mapping)) { - const UINT mapping = std::strcmp(input_mapping, "swapped") == 0 - ? D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(1, 0, 2, 3) - : D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - D3D12_SHADER_RESOURCE_VIEW_DESC view{DXGI_FORMAT_R32_UINT, D3D12_SRV_DIMENSION_BUFFER, mapping}; - view.Buffer.NumElements = fields[0][0] * fields[0][1] / 4; - invoke(device, 18, word(placed[0]), word(&view), cpu); + if (std::strcmp(input_mapping, "cbv") == 0) { + const D3D12_CONSTANT_BUFFER_VIEW_DESC view{invoke(placed[0], 11), 256}; + invoke(device, 17, word(&view), cpu); + } else { + const UINT mapping = std::strcmp(input_mapping, "swapped") == 0 + ? D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(1, 0, 2, 3) + : D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + D3D12_SHADER_RESOURCE_VIEW_DESC view{DXGI_FORMAT_R32_UINT, D3D12_SRV_DIMENSION_BUFFER, mapping}; + view.Buffer.NumElements = fields[0][0] * fields[0][1] / 4; + invoke(device, 18, word(placed[0]), word(&view), cpu); + } } void* other_heap = nullptr; if (change_table_heap &&