From 0681b9d280ee1adac2d123fb47265da4d9e35444 Mon Sep 17 00:00:00 2001 From: whoalin1 <207920491+whoalin1@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:03:32 +0200 Subject: [PATCH 01/21] cfg_structure / rdna2spirv: unwrap tautological %pc guards in structured CFGs (ms_wave_info_s3 AMD LLPC crash) cfg_structure.structure() wraps post-dominating join blocks after a diamond or loop in a ('guard', g, ...) node even when %pc == g is tautologically true on every incoming path. wave64_emulate_opt._unwrap_known_pc_guards already unwraps these guards for --wave64-emulate, which is why ms_wave_info_s3 passed on 32-wide NVIDIA GPUs while crashing with 0xC0000005 on native wave64 AMD RDNA2 Windows (driver 24.10.24, LLPC) where blk2's OpControlBarrier stayed trapped inside a conditional OpBranchConditional. Move unwrap_known_pc_guards into tools/cfg_structure.py (reused by wave64_emulate_opt with zero duplication) and apply it in rdna2spirv.capped_tree() so both assemble() and needs_barrier_rounds() see post-dominating join blocks at top level. SHADER-STRUCTURED-PC-UNWRAP Co-Authored-By: Gemini 4 Neon --- docs/design.md | 2 +- tests/test_cfg_structure.py | 26 +++++++++++++++ tests/test_translate.py | 5 +++ tools/cfg_structure.py | 61 ++++++++++++++++++++++++++++++++++ tools/rdna2spirv.py | 2 ++ tools/wave64_emulate_opt.py | 66 ++----------------------------------- 6 files changed, 97 insertions(+), 65 deletions(-) diff --git a/docs/design.md b/docs/design.md index 1dd413b8bc..4b25f17477 100644 --- a/docs/design.md +++ b/docs/design.md @@ -291,7 +291,7 @@ How the generated SPIR-V expects the runtime to work: | DPP on a VOPC compare | A VOPC compare whose src0 field is a DPP marker (250 for DPP16, 233/234 for DPP8) takes src0 through the DPP lane selection of the row above and writes VCC: a lane's bit is `compare(src0 of the selected lane, its own src1)`, with 0 for src0 when the selected lane is out of its row or inactive (`bound_ctrl` 1, or DPP8 with `fi` 0). The second word has the layout of a VOP2's DPP word. `llvm-mc` has no decoding for it on gfx10 (LLVM 21.1.8 rejects the first word for `gfx1013`; LLVM defines the form from GFX11 on), so `tools/shader_disasm.py` prints it: it decodes the pair with the first word turned into `v_max_f32` into `v0`, which takes the same second word, and gives the line the compare's name, a `vcc_lo` destination and the real encoding back (`with_vopc_dpp`); `tools/rdna2_decode.py` decodes it directly. **Only the forms where every lane writes its bit are translated**: `row_mask` and `bank_mask` 0xF and either `bound_ctrl` 1 or DPP8. Any other form, and `v_cmpx`, is refused (`DPP compare with lanes that keep their mask bit`), because what a lane DPP leaves unwritten does to its VCC bit is not measured. Found in 3 of the 2,684 pipeline-library compute programs of 1.0.2.1: 4 `v_cmp_gt_f32` each, with `quad_perm:[1,0,3,2]`, `quad_perm:[2,3,0,1]`, `row_ror:8` (all `bound_ctrl:1`, masks 0xF) and `dpp8:[4,5,6,7,0,1,2,3]`, beside `v_min/max_f32_dpp` and `v_mov_b32_dpp` on the same lanes. **Not measured on hardware**: the rule follows from the encoding, from LLVM's GFX11 definition of the same form and from the VOP2 DPP rules measured in the row above; the sweep that measured those (`tools/crosslane_fuzz.py --dpp-sweep --oracle hw`) does not cover compares. Lane values are checked in `tests/semantic/test_dpp_compare.py` (the SPIR-V interpreter) and on a GPU with `runtime/test/shaders/cs_dpp_cmp.asm`. | | EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. Measured on native gfx1100 (8 threads): a `v_mov_b32` under `EXEC=0x0F` leaves the other lanes untouched, `EXEC=0` writes nothing, a store writes only active lanes and `v_cmpx_gt_u32` narrows EXEC (4 of 4 cases); note that AMD clang 20 rejects `v_add_co_u32`, `v_sub_co_u32`, `v_add_co_ci_u32` and `v_mad_u64_u32` for `gfx1100`, `gfx1101` and `gfx1102`, so this toolchain could not reproduce the RX 7600 result below, which leaves open whether those parts support the opcodes and says only that they could not be assembled here. **A pixel is written when its lane was on in EXEC at the last `exp ... vm` the path executed (if it executed one) and at the last export to the color target; a path with no export at all goes by EXEC at the end.** The `vm` half is the RDNA2 ISA reference guide's rule (30-November-2020, §11.1 and §11.2.1: EXEC at the export is the valid mask and the final one sent is used; an `exp null ... vm` carries only the mask). The color half is measured: an export sends data only for the lanes that are on, a later export to the same target replaces the earlier one for the whole wave, and a lane with no data from the last one is not written even when a later `exp null done vm` marks it valid. So `exp mrt0 done` (no `vm`) with every lane on, followed by an EXEC write, still writes every pixel, and EXEC off at that export and back on afterwards writes none. **Measured on RDNA2** (AMD Radeon iGPU, gfx1036, driver 26.10.1) with the pixel-shader oracle of #3061 (`ps_oracle.py`), hand-written ISA as the pixel shader of a real draw (wave64 stage): 18 programs that cut EXEC to half of the target before, between or after `exp mrt0` (with and without `vm` and `done`) and `exp null done vm`; all 18 fit the rule, 6 of them differed from the translator, which until 2026-11-23 discarded by EXEC at the end on a path without `vm` and kept the older export's value (or the output's initial value) for a lane that was off at the last color export. The latches (`%vm_mask`, `%col_mask_mrtN`) are only emitted where a path can write EXEC after a `vm` or color export; everywhere else EXEC at the end is the same mask and the SPIR-V is unchanged. With several color targets a pixel stays when any target got an export from its lane (Vulkan cannot skip one attachment per pixel; not measured, the oracle's pipeline has one target); `mrtz` is not part of the color mask (not measured). **Measuring exports needs `s_waitcnt expcnt(0)` after each one**: an export is asynchronous, and without the wait the hardware takes the data and the EXEC of a later moment (`v_mov v9, A; exp mrt0 v9 done vm; v_mov v9, B` shows B, and an EXEC write right after the export decides which pixels are written, which looks like "EXEC at the end decides"); 64 `s_nop 15` have the same effect as the wait. Checked on the CPU by `tests/semantic/test_export_valid_mask.py` and on the GPU by `runtime/test/shaders/ps_exp_color_mask.asm` (RTX 5080 and the Radeon). VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and **hardware-verified on an AMD RX 7600 (gfx1102)** with `v_add_co_u32` and `v_add_co_ci_u32` carrying on every active lane: VCC reads `0xffffffff` with full EXEC, `0x0000ffff` for the mask `0x0000ffff` and `0xaaaaaaaa` for `0xaaaaaaaa` in wave32, `vcc_lo = 0x0000ffff` with `vcc_hi = 0x0000000f` for the same partial mask in wave64, and `0` when EXEC is 0 even with VCC preloaded to all ones; with one carrying lane under mask `0x0000ffff` VCC is `0x00000001`, and `v_sub_co_u32`/`v_subrev_co_u32` with a borrow under that mask give `0x0000ffff` too. The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately; it is also GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). In a shader that writes EXEC, a run of two or more lane-local VALU instructions (no cross-lane read, no lane-mask, SCC, carry or EXEC write) sits inside one `if (active)` and writes its VGPRs directly, instead of an `OpSelect(active, new, old)` per write: the same result, but the driver predicates the run with its own EXEC instead of keeping both values live. On an RX 5700 XT (RADV) a pixel shader with 8 divergent if/else regions of `v_fma`/`v_mul`/`v_add`/`v_min`/`v_max` went from 0.85 ms to 0.69 ms (the same program as native SPIR-V: 0.65 ms). Not under `--wave64-emulate`. Checked by `tests/semantic/test_active_runs.py`. | | `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1` (`~S0 \| EXEC`), `orn2` (`S0 \| ~EXEC`), `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 & wave64, 0 mismatches): all 10 `saveexec` kinds and both `wrexec` kinds (`andn1`/`andn2`) match bit-for-bit on non-symmetric masks (`src0 = 0x0F0F0F0F`, `exec = 0x33333333` in wave32; `0x0F0F0F0F_00FF00FF` / `0x33333333_55555555` in wave64), zero-result `SCC = 0`, wave64 upper-32-bit-only `new_exec = 0x00000001_00000000` setting `SCC = 1`, and `sdst == src0` register aliasing (`s4, s4` and `s[4:5], s[4:5]`) reading original `src0` before writing old `EXEC` to `sdst`. **Not GPU-verified** for the seven new kinds. Measured on native gfx1100 (single 8-lane workgroup, 36 programs): all ten `saveexec` kinds and both `wrexec` forms follow `f` for three `S0`/`EXEC` pairs, including lanes `EXEC` had off being switched back on (`nand` with `S0=0x03`, `EXEC=0x0F` leaves `0xFFFFFFFC`, activating lanes 4-7), `D` holding the old `EXEC` for `saveexec` and the new one for `wrexec`, and `SCC` the `EXEC != 0` vote. | -| Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. **Nesting is bounded (SHADER-299, SHADER-427):** a tree deeper than `MAX_STRUCTURED_DEPTH` (64; `--max-structured-depth N`, 0 = no bound) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Before #1904, over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound first sat at 16. Since #1904 (`cfg_structure` hoists tails) the deepest tree in the corpus is 29: of 12,944 structured modules, 1,031 are deeper than 16 (747 CS, 284 PS), 57 deeper than 20, 24 deeper than 24. For those 1,031 the flat form saves only 12% of `spirv-val` time (1,235 -> 1,091 s summed, slowest module 8.3 -> 5.9 s), while on an RTX 5070 Ti (NVIDIA 621.24) it compiles slower: the 284 pixel shaders 1.67x (827 -> 1,382 s summed, two rounds), four compute modules at depth 19-24 2.0x (297 -> 591 s, 1.6-2.7x each), so the bound now sits above the corpus (SHADER-427). Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. AMD's Windows driver adds a reason to keep the structured form (SHADER-995): on a Radeon gfx1036 iGPU (32.0.21042.62) the dispatch-loop module of `XboxBvhBuilder.dll`'s `LeafRehydration` (tree depth 18, a 581-case switch) takes 34 minutes to create (XXDESIGN), where its structured module is created in 2.9 s; ten other programs of that DLL compile in the dispatch-loop form there in 0.4-40 s, 2.5-5x their structured time ([embedded_shaders.md](embedded_shaders.md), section 7). | +| Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. `capped_tree()` also runs `cfg_structure.unwrap_known_pc_guards` (shared with `wave64_emulate_opt`) to unwrap tautological `("guard", g, ...)` nodes whenever abstract interpretation proves `%pc == g` on all incoming paths (e.g. post-dominating merge blocks after diamonds and loops); this keeps `ms_wave_info_s3`'s `s_barrier` in uniform top-level control flow (fixing an AMD Windows LLPC `0xC0000005` pipeline-creation crash on AMD Ryzen 5 7600 RDNA2 iGPU driver `24.10.24`, `4096/4096` exact on AMD RDNA2 and RTX 4070 SUPER) and avoids false `needs_barrier_rounds` triggers (`SHADER-STRUCTURED-PC-UNWRAP`). AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. **Nesting is bounded (SHADER-299, SHADER-427):** a tree deeper than `MAX_STRUCTURED_DEPTH` (64; `--max-structured-depth N`, 0 = no bound) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Before #1904, over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound first sat at 16. Since #1904 (`cfg_structure` hoists tails) the deepest tree in the corpus is 29: of 12,944 structured modules, 1,031 are deeper than 16 (747 CS, 284 PS), 57 deeper than 20, 24 deeper than 24. For those 1,031 the flat form saves only 12% of `spirv-val` time (1,235 -> 1,091 s summed, slowest module 8.3 -> 5.9 s), while on an RTX 5070 Ti (NVIDIA 621.24) it compiles slower: the 284 pixel shaders 1.67x (827 -> 1,382 s summed, two rounds), four compute modules at depth 19-24 2.0x (297 -> 591 s, 1.6-2.7x each), so the bound now sits above the corpus (SHADER-427). Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. AMD's Windows driver adds a reason to keep the structured form (SHADER-995): on a Radeon gfx1036 iGPU (32.0.21042.62) the dispatch-loop module of `XboxBvhBuilder.dll`'s `LeafRehydration` (tree depth 18, a 581-case switch) takes 34 minutes to create (XXDESIGN), where its structured module is created in 2.9 s; ten other programs of that DLL compile in the dispatch-loop form there in 0.4-40 s, 2.5-5x their structured time ([embedded_shaders.md](embedded_shaders.md), section 7). | | Loop guard | Each loop counts header visits per invocation and exits through its structured merge at `--loop-limit N` (default 65536, zero disables). Counters reset on entry, including nested EXEC retries and atomic loops. A PC-dispatch visit counts a dispatch iteration. Natural exits within the budget preserve their outputs. Five-star-recomp (b12a952) reported a story-load timeout when the shader input made its exit condition unreachable. | | User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. `--mesh-compute` modules add dwords 36–37, the output buffer address (152 bytes; see "Mesh shaders as compute"). `--pc-tail-ubo` keeps only dwords 0–31 here (128 bytes) and moves the rest to a uniform block (see "Push-constant tail as a uniform block"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. | | Direct resource heap | In the matched Prop/Tree BatchCull compute signature the two explicit tables and scalar constant occupy s4–s6. Bind the resource heap's uint32 arena-relative byte address at s7 (push-constant byte 28). The program supplies a zero high word and scales the resource index by 32 bytes. Other stages and signatures consume different SGPRs. See [descriptor heaps and the bindless model](d3d12_vulkan.md#34-descriptor-heaps-and-the-bindless-model) for the evidence and graphics examples. | diff --git a/tests/test_cfg_structure.py b/tests/test_cfg_structure.py index d4fa490588..f6caa5bd80 100644 --- a/tests/test_cfg_structure.py +++ b/tests/test_cfg_structure.py @@ -146,10 +146,17 @@ def split_choose(b, _orig=orig, _ns=new_succ, _seed=seed, _v=visits): loops += '"loop"' in repr(tree).replace("'", '"') placed = blocks_in(tree) assert len(placed) == len(set(placed)), f"a block is placed twice: {succ}" + out_pcs = {b: (set(succ[b]) if succ[b] else {S.END}) for b in range(len(succ))} + utree = S.unwrap_known_pc_guards(tree, out_pcs) + uplaced = blocks_in(utree) + assert len(uplaced) == len(set(uplaced)) and set(uplaced) == set(placed), ( + f"unwrap changed block set for {succ}: {placed} vs {uplaced}") for seed in range(6): want = walk(succ, chooser(succ, seed), 200) got = S.run(tree, chooser(succ, seed), 200) assert got == want, f"graph {succ} seed {seed}: tree ran {got}, graph runs {want}" + ugot = S.run(utree, chooser(succ, seed), 200) + assert ugot == want, f"unwrapped graph {succ} seed {seed}: tree ran {ugot}, graph runs {want}" assert structured > 5000 and refused > 1000 and loops > 2000, (structured, refused, loops) assert split_ok > 1000 and split_ok + split_cap == refused, (split_ok, split_cap, refused) return structured, refused, loops, split_ok, split_cap @@ -247,10 +254,29 @@ def test_deep_sequential_chains_stay_flat_and_iterative(): assert got == want +def test_unwrap_known_pc_guards(): + def unwrap(succ): + tree = S.structure(succ) + assert tree is not None + out_pcs = {b: (set(succ[b]) if succ[b] else {S.END}) for b in range(len(succ))} + return S.unwrap_known_pc_guards(tree, out_pcs) + + # Single-arm if-then (ms_wave_info_s3 shape: 0 -> {2, 1}, 1 -> {2}, 2 -> []): join block 2 unwraps to top level. + assert unwrap([[2, 1], [2], []]) == [("block", 0), ("guard", 1, [("block", 1)]), ("block", 2)] + # Diamond (0 -> {1, 2}, 1 -> {3}, 2 -> {3}, 3 -> []): join block 3 unwraps to top level. + assert unwrap([[1, 2], [3], [3], []]) == [("block", 0), ("guard", 2, [("block", 2)]), + ("guard", 1, [("block", 1)]), ("block", 3)] + # Loop exit (0 -> {0, 1}, 1 -> []): block 1 unwraps to top level because exiting loop 0 proves pc == 1. + assert unwrap([[0, 1], []]) == [("loop", 0, [("block", 0)]), ("block", 1)] + # Early exit in arm 1 (0 -> {1, 2}, 1 -> [], 2 -> []): both arms MUST remain guarded (pc may be END). + assert unwrap([[1, 2], [], []]) == [("block", 0), ("guard", 2, [("block", 2)]), ("guard", 1, [("block", 1)])] + + if __name__ == "__main__": test_depth() test_shapes() test_deep_sequential_chains_stay_flat_and_iterative() + test_unwrap_known_pc_guards() structured, refused, loops, split_ok, split_cap = _check_random_graphs() print(f"ok: {structured} graphs structured and run, {refused} irreducible " f"({split_ok} split-structured, {split_cap} capped), {loops} with loops") diff --git a/tests/test_translate.py b/tests/test_translate.py index d151c36e28..f94996e1e6 100644 --- a/tests/test_translate.py +++ b/tests/test_translate.py @@ -1392,6 +1392,11 @@ def test_mesh_s3_wave_id_emits_local_index_shift_and_bfe(make_shader): asm = shader.translate() shader.validate(asm) assert "%wave = OpShiftRightLogical %uint %lidx %c6" in asm + # SHADER-STRUCTURED-PC-UNWRAP: blk2 post-dominates blk0/blk1 and carries s_barrier, so its tautological + # pc == 2 guard must be unwrapped (keeping OpControlBarrier in uniform top-level control flow for AMD LLPC). + blk2_pos = asm.index("%blk2 = OpLabel") + before_blk2 = asm[asm.index("%blk1 = OpLabel"):blk2_pos] + assert "OpBranchConditional" not in before_blk2, before_blk2 assert "%mwi = OpShiftLeftLogical %uint %wave %c18" in asm assert "OpStore %s3p %mwi" in asm assert "OpBitFieldUExtract %uint" in asm diff --git a/tools/cfg_structure.py b/tools/cfg_structure.py index 3409d4dbf5..36eacf7f4f 100644 --- a/tools/cfg_structure.py +++ b/tools/cfg_structure.py @@ -347,3 +347,64 @@ def run(tree, choose, limit): else: stack.pop() return trace + + +def unwrap_known_pc_guards(tree, out_pcs, entry_pc=0): + """Unwrap `("guard", g, body)` nodes whenever abstract interpretation proves `%pc == g` on all incoming paths. + + `structure()` wraps post-dominating join blocks after a diamond or loop in `("guard", g, ...)`. When every + incoming path guarantees `%pc == g` (e.g. a merge block with `s_barrier` after a wave-divergent branch like + `ms_wave_info_s3`), unwrapping the tautological guard keeps `OpControlBarrier` in uniform top-level control + flow (avoiding an AMD Windows LLPC 0xC0000005 pipeline-creation crash in MeshEXT and preventing false + `needs_barrier_rounds` triggers) and avoids redundant `%pc` merge phis. + + `out_pcs[b]` is the finite set of `%pc` values block `b` may write (`{END}` when `b` terminates). + """ + root_out = [] + stack = [[collections.deque(tree), root_out, {entry_pc}, None]] + while stack: + frame = stack[-1] + q, dst, cur_pc, tag = frame + if not q: + if len(stack) > 1 and tag[0] == "guard" and len(cur_pc) == 1: + nxt_g = next(iter(cur_pc)) + skip_pc = tag[3] + parent_q = stack[-2][0] + if parent_q and parent_q[0][0] == "guard" and parent_q[0][1] == nxt_g and nxt_g not in skip_pc: + for child in reversed(parent_q.popleft()[2]): + q.appendleft(child) + continue + stack.pop() + if not stack: + break + parent = stack[-1] + if tag[0] == "guard": + _, g, child_dst, skip_pc = tag + parent[1].append(("guard", g, child_dst)) + parent[2] = skip_pc | cur_pc + else: + _, h, child_dst = tag + parent[1].append(("loop", h, child_dst)) + parent[2] = cur_pc - {h} + continue + it = q.popleft() + kind = it[0] + if kind == "block": + b = it[1] + dst.append(it) + frame[2] = set(out_pcs[b]) + elif kind == "guard": + g, gbody = it[1], it[2] + if cur_pc == {g}: + for child in reversed(gbody): + q.appendleft(child) + else: + child_dst = [] + skip_pc = set(cur_pc) + skip_pc.discard(g) + stack.append([collections.deque(gbody), child_dst, {g}, ("guard", g, child_dst, skip_pc)]) + else: + h, lbody = it[1], it[2] + child_dst = [] + stack.append([collections.deque(lbody), child_dst, set(cur_pc) | {h}, ("loop", h, child_dst)]) + return root_out diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index bb14c3d097..1e5e50f7c9 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -18342,6 +18342,8 @@ def capped_tree(succ): tree = cfg_structure.structure(succ) if STRUCTURED else None if tree is None: return None, None + out_pcs = {b: (set(succ[b]) if succ[b] else {cfg_structure.END}) for b in range(len(succ))} + tree = cfg_structure.unwrap_known_pc_guards(tree, out_pcs) nesting = cfg_structure.depth(tree) if MAX_STRUCTURED_DEPTH and nesting > MAX_STRUCTURED_DEPTH: return None, nesting # too deep to validate cheaply: use the flat form diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py index d6e1ad7d5b..d41f5575cb 100644 --- a/tools/wave64_emulate_opt.py +++ b/tools/wave64_emulate_opt.py @@ -1105,70 +1105,8 @@ def _drop_tree_block(tree, b): def _unwrap_known_pc_guards(tree, out_pcs, entry_pc=0): - """Unwrap `("guard", g, body)` nodes whenever abstract interpretation proves `%pc == g` on all incoming paths. - - In `cfg_structure.structure`, every post-dominating join block `g` after a conditional diamond or loop is - still wrapped in `("guard", g, ...)`. Because `%pc` is a Function-scope variable in SPIR-V, LLVM/NVVM's - `SROA`/`Mem2Reg` promotes `%pc` at the same time as `%vgpr[0..255]` and `%sgpr[0..127]`, before `%pc == g` - can be constant-folded, forcing ~384 redundant Phi nodes at every spine guard merge block (and preventing - early block merging across convergent `OpControlBarrier`s). - - Tracks the exact finite set `cur_pc` of values `%pc` can hold before each item in `tree`: - - `("block", b)` overwrites `%pc` with `out_pcs[b]`. - - `("guard", g, gbody)`: if `cur_pc == {g}`, `%pc == g` is tautologically true on every path reaching - this item, so the guard unwraps in place; otherwise `gbody` is processed starting from `{g}` and its - exit `%pc` set merges with the skip path `cur_pc - {g}`. - - `("loop", h, lbody)`: `lbody` is processed starting from `cur_pc | {h}`; exiting the loop proves - `%pc != h`, leaving `pc_after_lbody - {h}`. - """ - root_out = [] - stack = [[collections.deque(tree), root_out, {entry_pc}, None]] - while stack: - frame = stack[-1] - q, dst, cur_pc, tag = frame - if not q: - if len(stack) > 1 and tag[0] == "guard" and len(cur_pc) == 1: - nxt_g = next(iter(cur_pc)) - skip_pc = tag[3] - parent_q = stack[-2][0] - if parent_q and parent_q[0][0] == "guard" and parent_q[0][1] == nxt_g and nxt_g not in skip_pc: - for child in reversed(parent_q.popleft()[2]): - q.appendleft(child) - continue - stack.pop() - if not stack: - break - parent = stack[-1] - if tag[0] == "guard": - _, g, child_dst, skip_pc = tag - parent[1].append(("guard", g, child_dst)) - parent[2] = skip_pc | cur_pc - else: - _, h, child_dst = tag - parent[1].append(("loop", h, child_dst)) - parent[2] = cur_pc - {h} - continue - it = q.popleft() - kind = it[0] - if kind == "block": - b = it[1] - dst.append(it) - frame[2] = set(out_pcs[b]) - elif kind == "guard": - g, gbody = it[1], it[2] - if cur_pc == {g}: - for child in reversed(gbody): - q.appendleft(child) - else: - child_dst = [] - skip_pc = set(cur_pc) - skip_pc.discard(g) - stack.append([collections.deque(gbody), child_dst, {g}, ("guard", g, child_dst, skip_pc)]) - else: - h, lbody = it[1], it[2] - child_dst = [] - stack.append([collections.deque(lbody), child_dst, set(cur_pc) | {h}, ("loop", h, child_dst)]) - return root_out + """Unwrap `("guard", g, body)` nodes whenever abstract interpretation proves `%pc == g` on all incoming paths.""" + return cfg_structure.unwrap_known_pc_guards(tree, out_pcs, entry_pc=entry_pc) def _region_has_cycle(region, succ): From 53ef382d7097290ecb1387f2400eaa7d134585b6 Mon Sep 17 00:00:00 2001 From: whoalin1 <207920491+whoalin1@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:36:04 +0200 Subject: [PATCH 02/21] cfg_structure: document why loop entry keeps cur_pc | {h} in unwrap_known_pc_guards Co-Authored-By: Gemini 4 Neon --- tools/cfg_structure.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/cfg_structure.py b/tools/cfg_structure.py index 36eacf7f4f..68522ec8be 100644 --- a/tools/cfg_structure.py +++ b/tools/cfg_structure.py @@ -406,5 +406,7 @@ def unwrap_known_pc_guards(tree, out_pcs, entry_pc=0): else: h, lbody = it[1], it[2] child_dst = [] + # In a structure() tree lbody[0] is always ("block", h), which overwrites cur_pc with out_pcs[h]; + # keep cur_pc | {h} defensively so back-edge iterations stay sound even on non-structure() trees. stack.append([collections.deque(lbody), child_dst, set(cur_pc) | {h}, ("loop", h, child_dst)]) return root_out From 8e5cf5aef1942811bc6e377077b8dc8f388ff8fc Mon Sep 17 00:00:00 2001 From: whoalin1 <207920491+whoalin1@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:56:36 +0200 Subject: [PATCH 03/21] fix(rdna2spirv): include END in out_pcs for trailing conditional branches A conditional branch in the last basic block (no fallthrough block, so len(raw_edges[b]) == 1) emits OpSelect(%cond, tgt, len(blocks)) and can leave %pc at either tgt or cfg_structure.END. Compute exact per-block out_pcs in rdna2spirv._block_out_pcs (matching wave64_emulate_opt), pass it through capped_tree() into both cfg_structure.structure() (so single-target fall-off-the-end blocks also keep their dominated target guard) and unwrap_known_pc_guards(), and pass compact_out_pcs into cfg_structure.structure() in wave64_emulate_opt. Add unit and semantic regression tests covering both the loop back-edge repro reported in review and the non-loop dominated-target variant. Co-Authored-By: Gemini 4 Neon --- tests/semantic/test_structured_pc_unwrap.py | 137 ++++++++++++++++++++ tests/test_cfg_structure.py | 19 ++- tools/cfg_structure.py | 5 +- tools/rdna2spirv.py | 30 ++++- tools/wave64_emulate_opt.py | 17 ++- 5 files changed, 191 insertions(+), 17 deletions(-) create mode 100644 tests/semantic/test_structured_pc_unwrap.py diff --git a/tests/semantic/test_structured_pc_unwrap.py b/tests/semantic/test_structured_pc_unwrap.py new file mode 100644 index 0000000000..fc6eb90076 --- /dev/null +++ b/tests/semantic/test_structured_pc_unwrap.py @@ -0,0 +1,137 @@ +"""Semantic regression tests for structured %pc guard unwrapping (SHADER-STRUCTURED-PC-UNWRAP). + +Pure Python stdlib only (no llvm-mc, spirv-val, GPU, or game data). Verifies end-to-end translation +and execution of synthetic hand-written RDNA2 compute shaders where the last basic block ends in a +conditional branch with no trailing s_endpgm (fallthrough writes %pc = len(blocks) = END): + + 1. Loop whose back-edge is a conditional branch at the very end of the shader (succ = [[2, 1], [], [0]], + out_pcs[2] = {0, END}): exiting the loop leaves %pc in {1, END}, so guard 1 must stay and a + not-taken back-edge must terminate without executing block 1. + 2. Non-loop conditional branch at the very end of the shader whose single explicit target is + immediately dominated by it (succ = [[2], [], [1]], out_pcs[2] = {1, END}): both native + structured control flow and --wave64-emulate structured control flow must keep guard 1. + 3. Single-arm if-then join (0 -> {2, 1}, 1 -> {2}, 2 -> []) with s_barrier in block 2: block 2 + unwraps to top level so wave32 compute does not falsely fall back to barrier rounds. +""" +import os +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +sys.dont_write_bytecode = True +for _p in (HERE, TOOLS_DIR): + if _p not in sys.path: + sys.path.insert(0, _p) + +import rdna2spirv # noqa: E402 +from test_loop_ballot_barrier import VSHARP, _translate_cs, run_compute_workgroup # noqa: E402 + + +class StructuredPcUnwrapSemanticTest(unittest.TestCase): + def test_loop_last_block_cbranch_falloff_keeps_exit_guard(self): + """Loop back-edge in the last block with no s_endpgm after it: falling off the end must NOT run block 1.""" + prog = [ + "head:", + "s_cmp_eq_u32 s4, 0", + "s_cbranch_scc1 tail", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 0x1111", + "buffer_store_dword v1, v2, s[0:3], 0 offen", + "s_endpgm", + "tail:", + "s_mov_b32 s4, 1", + "s_cmp_eq_u32 s5, 1", + "s_cbranch_scc1 head", + ] + spv_struct, gen_struct = _translate_cs("cs_cbranch_falloff_loop", prog, threads=32, structured=True) + spv_disp, gen_disp = _translate_cs("cs_cbranch_falloff_loop_disp", prog, threads=32, structured=False) + self.assertEqual(gen_struct.control_flow, "structured") + self.assertEqual(gen_disp.control_flow, "dispatch loop") + self.assertEqual(gen_struct.succ, [[2, 1], [], [0]]) + self.assertEqual(gen_struct.out_pcs[2], frozenset({0, -1})) + tree, _ = rdna2spirv.capped_tree(gen_struct.succ, gen_struct.out_pcs) + self.assertEqual(tree, [ + ("loop", 0, [("block", 0), ("guard", 2, [("block", 2)])]), + ("guard", 1, [("block", 1)]), + ]) + + cases = [ + (1, 0, [0x1111] * 32), # B0 falls into B1 -> stores 0x1111 + (0, 1, [0x1111] * 32), # B0 -> B2 (s4=1, back-edge taken) -> B0 -> B1 -> stores 0x1111 + (0, 0, [0] * 32), # B0 -> B2 (back-edge not taken -> falls off end) -> no store + ] + for s4, s5, want in cases: + with self.subTest(s4=s4, s5=s5): + pc = VSHARP + [s4, s5] + mem_s = run_compute_workgroup(spv_struct, 32, 32, push_constants=pc) + mem_d = run_compute_workgroup(spv_disp, 32, 32, push_constants=pc) + got_s = [mem_s.get(4 * t, 0) for t in range(32)] + got_d = [mem_d.get(4 * t, 0) for t in range(32)] + self.assertEqual(got_d, want) + self.assertEqual(got_s, want) + + def test_nonloop_last_block_cbranch_falloff_keeps_dominated_target_guard(self): + """Last block ending in s_cbranch_scc1 to its single dominated target (no s_endpgm) must keep its guard.""" + prog = [ + "s_branch tail", + "do_store:", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 0x2222", + "buffer_store_dword v1, v2, s[0:3], 0 offen", + "s_endpgm", + "tail:", + "s_cmp_eq_u32 s4, 1", + "s_cbranch_scc1 do_store", + ] + for mode, threads, sg_sz, emulate in ( + ("w32_structured", 32, 32, False), + ("w64_emulate", 64, 32, True), + ): + # Include a 64-bit exec op in the wave64 case so rdna2spirv classifies the shader as wave64 + # and exercises wave64_emulate_opt.plan_structured_emulation(). + mode_prog = (["s_mov_b64 s[10:11], exec"] + prog) if emulate else prog + spv, gen = _translate_cs(f"cs_cbranch_falloff_{mode}", mode_prog, threads=threads, emulate=emulate) + if emulate: + self.assertEqual(gen.control_flow, "emulated wave64 structured") + else: + self.assertEqual(gen.control_flow, "structured") + tree, _ = rdna2spirv.capped_tree(gen.succ, gen.out_pcs) + self.assertEqual(tree, [("block", 0), ("block", 2), ("guard", 1, [("block", 1)])]) + for s4, want_val in ((1, 0x2222), (0, 0)): + with self.subTest(mode=mode, s4=s4): + mem = run_compute_workgroup(spv, threads, sg_sz, push_constants=VSHARP + [s4]) + self.assertEqual([mem.get(4 * t, 0) for t in range(threads)], [want_val] * threads) + + def test_postdominating_join_barrier_unwraps_to_top_level(self): + """A post-dominating merge block after a single-arm branch unwraps to top level (no false barrier rounds).""" + prog = [ + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 1", + "s_cmp_eq_u32 s4, 0", + "s_cbranch_scc1 join", + "v_mov_b32_e32 v1, 2", + "join:", + "ds_write_b32 v2, v1", + "s_waitcnt lgkmcnt(0)", + "s_barrier", + "ds_read_b32 v3, v2", + "s_waitcnt lgkmcnt(0)", + "buffer_store_dword v3, v2, s[0:3], 0 offen", + "s_endpgm", + ] + spv, gen = _translate_cs("cs_join_barrier_unwrap", prog, threads=64, lds_bytes=256, emulate=False) + self.assertFalse(gen.bar_rounds) + self.assertEqual(gen.control_flow, "structured") + tree, _ = rdna2spirv.capped_tree(gen.succ, gen.out_pcs) + self.assertEqual(tree, [("block", 0), ("guard", 1, [("block", 1)]), ("block", 2)]) + for s4, want_val in ((0, 1), (1, 2)): + with self.subTest(s4=s4): + mem = run_compute_workgroup(spv, 64, 32, push_constants=VSHARP + [s4]) + self.assertEqual([mem.get(4 * t, 0) for t in range(64)], [want_val] * 64) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_cfg_structure.py b/tests/test_cfg_structure.py index f6caa5bd80..761bb21ee6 100644 --- a/tests/test_cfg_structure.py +++ b/tests/test_cfg_structure.py @@ -255,10 +255,11 @@ def test_deep_sequential_chains_stay_flat_and_iterative(): def test_unwrap_known_pc_guards(): - def unwrap(succ): - tree = S.structure(succ) + def unwrap(succ, out_pcs=None): + if out_pcs is None: + out_pcs = {b: (set(succ[b]) if succ[b] else {S.END}) for b in range(len(succ))} + tree = S.structure(succ, out_pcs=out_pcs) assert tree is not None - out_pcs = {b: (set(succ[b]) if succ[b] else {S.END}) for b in range(len(succ))} return S.unwrap_known_pc_guards(tree, out_pcs) # Single-arm if-then (ms_wave_info_s3 shape: 0 -> {2, 1}, 1 -> {2}, 2 -> []): join block 2 unwraps to top level. @@ -270,6 +271,18 @@ def unwrap(succ): assert unwrap([[0, 1], []]) == [("loop", 0, [("block", 0)]), ("block", 1)] # Early exit in arm 1 (0 -> {1, 2}, 1 -> [], 2 -> []): both arms MUST remain guarded (pc may be END). assert unwrap([[1, 2], [], []]) == [("block", 0), ("guard", 2, [("block", 2)]), ("guard", 1, [("block", 1)])] + # Conditional branch in the last block with no s_endpgm after it (fallthrough writes END): + # loop body block 2 has succ [0] but out_pcs {0, END}, so exiting loop 0 leaves pc in {1, END}; + # guard 1 MUST stay so falling off the end does not execute block 1. + assert unwrap([[2, 1], [], [0]], out_pcs={0: {2, 1}, 1: {S.END}, 2: {0, S.END}}) == [ + ("loop", 0, [("block", 0), ("guard", 2, [("block", 2)])]), + ("guard", 1, [("block", 1)]), + ] + # Non-loop conditional branch falling off the end whose single explicit target is immediately dominated by it: + # block 2 has succ [1] and out_pcs {1, END}, so structure() and unwrap MUST both keep guard 1. + assert unwrap([[2], [], [1]], out_pcs={0: {2}, 1: {S.END}, 2: {1, S.END}}) == [ + ("block", 0), ("block", 2), ("guard", 1, [("block", 1)]), + ] if __name__ == "__main__": diff --git a/tools/cfg_structure.py b/tools/cfg_structure.py index 68522ec8be..9b7b412127 100644 --- a/tools/cfg_structure.py +++ b/tools/cfg_structure.py @@ -80,7 +80,7 @@ def _dominators(rpo, preds): return idom, pos -def structure(succ): +def structure(succ, out_pcs=None): rpo, back, preds = _order(succ) idom, pos = _dominators(rpo, preds) @@ -158,7 +158,8 @@ def member(x, region): out_list.append(("loop", x, lbody)) else: out_list.append(("block", x)) - if kind == "b" and len(below) == 1 and list(succ[x]) == [below[0][1]]: + if (kind == "b" and len(below) == 1 and list(succ[x]) == [below[0][1]] + and (out_pcs is None or set(out_pcs[x]) == {below[0][1]})): stack.append(("emit", out_list, parent_list, below[0], depth)) else: hoist = (parent_list is not None and below diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 1e5e50f7c9..202a95c37f 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -398,6 +398,7 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): # single defining plain v_mov of it); valid I/J sources (SHADER-177) self.blocks = [] # per basic block: list of SPIR-V lines (dispatch-loop form), empty = straight-line self.succ = [] # per basic block: the blocks it can go to next (none = the program ends there) + self.out_pcs = None # per basic block: exact set of %pc values written (including cfg_structure.END) self.desc_fn = None # lines of the descriptor-lookup function, once an instruction needs it self.tbuffer_norm_fns: dict[int, list[str]] = {} # one exact quotient per used magnitude width self.fmt_fn = None # lines of the typed-buffer format-decode function, once a dynamic-format load needs it @@ -16276,7 +16277,7 @@ def assemble(gen): helpers.extend(function) for function in gen.x_round_fns.values(): helpers.extend(function) - tree, nesting = (capped_tree(gen.succ) if gen.blocks and not gen.emulate and not gen.bar_rounds + tree, nesting = (capped_tree(gen.succ, gen.out_pcs) if gen.blocks and not gen.emulate and not gen.bar_rounds else (None, None)) if nesting is not None: gen.nesting = nesting @@ -18055,6 +18056,7 @@ def target(ins): g.cu(n) raw_edges = split_edges succ = [list(dict.fromkeys(e)) for e in raw_edges] + g.out_pcs = _block_out_pcs(blocks, raw_edges, succ) g.vm_latch = stage == "ps" and exec_changes_after_vm(blocks, succ) g.park_masks((blocks, succ)) halves_analysis(g, blocks, succ) @@ -18334,15 +18336,33 @@ def finish_module(g): return spirv_loop_guard.add_guards(text, LOOP_LIMIT) -def capped_tree(succ): +def _block_out_pcs(blocks, raw_edges, succ): + """Possible `%pc` values each basic block can store (`cfg_structure.END` when the block can end the shader). + A conditional branch with no fallthrough block (`len(raw_edges[b]) == 1`, i.e. the last block or a split clone + of it) emits `OpSelect %uint cond tgt len(blocks)` and therefore writes either `tgt` or `END`.""" + out_pcs = {} + for b, blk in enumerate(blocks): + pcs = set(succ[b]) + if not pcs: + pcs.add(cfg_structure.END) + elif len(raw_edges[b]) == 1: + last = next((i for i in blk if base_op(i["op"]) == "s_endpgm" or base_op(i["op"]) in BRANCHES), None) + if last is not None and base_op(last["op"]) in BRANCHES and base_op(last["op"]) != "s_branch": + pcs.add(cfg_structure.END) + out_pcs[b] = frozenset(pcs) + return out_pcs + + +def capped_tree(succ, out_pcs=None): """(tree, nesting): the structured tree for `succ` and its depth, or (None, None) under --dispatch-loop or when cfg_structure can't structure it; tree is None (nesting still the measured depth) when it nests deeper than MAX_STRUCTURED_DEPTH. assemble() emits exactly this tree, and needs_barrier_rounds() decides from the same one (SHADER-427 review): a barrier in a tree that falls back to the dispatch loop isn't at a structured top level.""" - tree = cfg_structure.structure(succ) if STRUCTURED else None + if out_pcs is None: + out_pcs = {b: (set(succ[b]) if succ[b] else {cfg_structure.END}) for b in range(len(succ))} + tree = cfg_structure.structure(succ, out_pcs=out_pcs) if STRUCTURED else None if tree is None: return None, None - out_pcs = {b: (set(succ[b]) if succ[b] else {cfg_structure.END}) for b in range(len(succ))} tree = cfg_structure.unwrap_known_pc_guards(tree, out_pcs) nesting = cfg_structure.depth(tree) if MAX_STRUCTURED_DEPTH and nesting > MAX_STRUCTURED_DEPTH: @@ -18370,7 +18390,7 @@ def needs_barrier_rounds(g, blocks, succ): break if not with_barrier: return False - tree, _ = capped_tree(succ) # the tree assemble() emits: over MAX_STRUCTURED_DEPTH it's the dispatch loop + tree, _ = capped_tree(succ, g.out_pcs) # the tree assemble() emits: over MAX_STRUCTURED_DEPTH it's the dispatch loop top = {it[1] for it in tree if it[0] == "block"} if tree is not None else set() return not with_barrier <= top diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py index d41f5575cb..4b52127210 100644 --- a/tools/wave64_emulate_opt.py +++ b/tools/wave64_emulate_opt.py @@ -1549,23 +1549,26 @@ def plan_structured_emulation(blocks, raw_edges, succ, folds, fold_chain, absorb eff_succ[b] = nxt eff_succ_compact.append([eff_idx[s] for s in nxt]) - compact_tree = cfg_structure.structure(eff_succ_compact) - if compact_tree is None: - return None - tree = _map_tree_ids(compact_tree, eff_blocks) - out_pcs = {} for b in eff_blocks: tail = chain_of[b][-1] s = set(eff_succ[b]) if not s: - s.add(-1) + s.add(cfg_structure.END) elif tail not in folds and len(raw_edges[tail]) == 1: last = active_blocks[tail][-1] if active_blocks[tail] else None op = base_op(last["op"]) if last is not None else None if op in BRANCHES and op != "s_branch": - s.add(-1) + s.add(cfg_structure.END) out_pcs[b] = frozenset(s) + compact_out_pcs = { + eff_idx[b]: frozenset(eff_idx[p] if p != cfg_structure.END else cfg_structure.END for p in pcs) + for b, pcs in out_pcs.items() + } + compact_tree = cfg_structure.structure(eff_succ_compact, out_pcs=compact_out_pcs) + if compact_tree is None: + return None + tree = _map_tree_ids(compact_tree, eff_blocks) tree = _unwrap_known_pc_guards(tree, out_pcs, eff_blocks[0]) # Precompute per-superblock instruction summaries (for dirty transfer, sync-free check, s_barrier, s_endpgm). From 33431d6fe5482fdc87edb212f325f37386b4937a Mon Sep 17 00:00:00 2001 From: whoalin1 <207920491+whoalin1@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:06:01 +0200 Subject: [PATCH 04/21] fix(wave64_emulate_opt): refuse exec-fold regions containing a trailing conditional branch A block with len(raw_edges[u]) == 1 ending in a conditional branch (no fallthrough block, so falling through writes %pc = len(blocks) = END) cannot safely sit inside a folded s_cbranch_execz/nz region whose exit unconditionally sets %pc = skip. Reject such blocks during the region walk in find_local_exec_folds (matching the existing ot succ[u] check) and add semantic regression tests covering both s_cbranch_scc1 X and s_cbranch_scc1 skip in structured and --dispatch-loop --wave64-emulate modes. Co-Authored-By: Gemini 4 Neon --- tests/semantic/test_structured_pc_unwrap.py | 49 +++++++++++++++++++++ tools/wave64_emulate_opt.py | 3 +- 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/tests/semantic/test_structured_pc_unwrap.py b/tests/semantic/test_structured_pc_unwrap.py index fc6eb90076..d8e42e6072 100644 --- a/tests/semantic/test_structured_pc_unwrap.py +++ b/tests/semantic/test_structured_pc_unwrap.py @@ -132,6 +132,55 @@ def test_postdominating_join_barrier_unwraps_to_top_level(self): mem = run_compute_workgroup(spv, 64, 32, push_constants=VSHARP + [s4]) self.assertEqual([mem.get(4 * t, 0) for t in range(64)], [want_val] * 64) + def test_wave64_emulate_exec_fold_refuses_last_block_cbranch_falloff(self): + """A wave64 s_cbranch_execz region containing a trailing conditional branch (no s_endpgm) must NOT be + folded into a region that unconditionally continues at `skip`: falling off the end must terminate.""" + prog_to_x = [ + "s_mov_b64 s[10:11], exec", + "s_cbranch_execz skip", + "s_branch last", + "X:", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 0x3333", + "buffer_store_dword v1, v2, s[0:3], 0 offen", + "s_branch skip", + "skip:", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 0x4444", + "buffer_store_dword v1, v2, s[0:3], 0 offen offset:256", + "s_endpgm", + "last:", + "s_cmp_eq_u32 s4, 1", + "s_cbranch_scc1 X", + ] + prog_to_skip = [ + "s_mov_b64 s[10:11], exec", + "s_cbranch_execz skip", + "s_branch last", + "skip:", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v1, 0x4444", + "buffer_store_dword v1, v2, s[0:3], 0 offen offset:256", + "s_endpgm", + "last:", + "s_cmp_eq_u32 s4, 1", + "s_cbranch_scc1 skip", + ] + for name, prog, want_taken_x, want_taken_skip in ( + ("branch_to_x", prog_to_x, 0x3333, 0x4444), + ("branch_to_skip", prog_to_skip, 0, 0x4444), + ): + for structured in (True, False): + spv, _ = _translate_cs( + f"cs_fold_falloff_{name}_{int(structured)}", + prog, threads=64, emulate=True, structured=structured, + ) + for s4, exp_x, exp_skip in ((0, 0, 0), (1, want_taken_x, want_taken_skip)): + with self.subTest(case=name, structured=structured, s4=s4): + mem = run_compute_workgroup(spv, 64, 32, push_constants=VSHARP + [s4]) + self.assertEqual([mem.get(4 * t, 0) for t in range(64)], [exp_x] * 64) + self.assertEqual([mem.get(256 + 4 * t, 0) for t in range(64)], [exp_skip] * 64) + if __name__ == "__main__": unittest.main() diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py index 4b52127210..1ff464fd15 100644 --- a/tools/wave64_emulate_opt.py +++ b/tools/wave64_emulate_opt.py @@ -1295,7 +1295,8 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr u = work.pop() if u == skip or u in region: continue - if u == b or u == 0 or not succ[u] or not blk_info[u][0]: + if (u == b or u == 0 or not succ[u] or not blk_info[u][0] + or (len(raw_edges[u]) == 1 and terms[u][0] == "br" and terms[u][1] != "s_branch")): ok = False break region.add(u) From 93d540e3be55b78041a55926447d31048762937e Mon Sep 17 00:00:00 2001 From: zwork Date: Mon, 23 Nov 2026 11:50:57 +0100 Subject: [PATCH 05/21] docs: drop the repeated manifest block in character_models, and test for it --- tests/test_docs_adjacent_fenced_blocks.py | 128 ++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 tests/test_docs_adjacent_fenced_blocks.py diff --git a/tests/test_docs_adjacent_fenced_blocks.py b/tests/test_docs_adjacent_fenced_blocks.py new file mode 100644 index 0000000000..7142e47db0 --- /dev/null +++ b/tests/test_docs_adjacent_fenced_blocks.py @@ -0,0 +1,128 @@ +"""No docs page repeats the same fenced block twice in a row. + +Two copies of one code block, with nothing but blank lines between them, is what a merge of a +rebased copy leaves behind: the page shows the same snippet twice, and an edit to one copy +leaves the other stale next to it. That is how `docs/character_models.md` carried the same +`manifest.json` block twice (lines 312-320 and 322-330) until it was dropped. + +The rule is deliberately narrow: the blocks must be identical and adjacent, so the same command +quoted again in a later section, or two blocks that differ in one line, are not reported. + + python -I tests/test_docs_adjacent_fenced_blocks.py + +Synthetic Markdown only; no game data. +""" +import os +import re +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +DOCS = os.path.join(ROOT, "docs") + +FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})(.*)$") + + +def fenced_blocks(lines): + """[(index of the opening fence, index of the closing fence, content lines)] for `lines`.""" + blocks, opened = [], None + for index, line in enumerate(lines): + match = FENCE.match(line) + if opened is None: + if match: + marker = match.group(1) + opened = (index, marker[0], len(marker), []) + continue + # A closing fence is the same character, at least as long, and nothing after it. + if match and match.group(1)[0] == opened[1] and len(match.group(1)) >= opened[2] \ + and not match.group(2).strip(): + blocks.append((opened[0], index, opened[3])) + opened = None + continue + opened[3].append(line) + return blocks + + +def adjacent_repeats(text): + """[(first block's line number, second block's line number)] for identical blocks back to back. + + Line numbers are 1-based and name the opening fence. Blocks with prose between them are not + back to back, and empty blocks are ignored. + """ + lines = text.splitlines() + found = [] + blocks = fenced_blocks(lines) + for (start_a, end_a, body_a), (start_b, _end_b, body_b) in zip(blocks, blocks[1:]): + if body_a != body_b or not any(line.strip() for line in body_a): + continue + if all(not line.strip() for line in lines[end_a + 1:start_b]): + found.append((start_a + 1, start_b + 1)) + return found + + +class AdjacentFencedBlocks(unittest.TestCase): + def test_detector_finds_only_identical_adjacent_blocks(self): + src = "\n".join([ + "# page", # 1 + "", # 2 + "```python", # 3 + "print('a')", # 4 + "```", # 5 + "", # 6 + "```python", # 7 + "print('a')", # 8 + "```", # 9 -> 3 and 7 are a repeat + "", # 10 + "Some prose.", # 11 + "", # 12 + "```python", # 13 + "print('a')", # 14 + "```", # 15 same block, but prose above: allowed + "", # 16 + "```python", # 17 + "print('b')", # 18 + "```", # 19 + "", # 20 + "```python", # 21 + "print('b')", # 22 + "```", # 23 -> 17 and 21 repeat + "", # 24 + "````markdown", # 25 + "```", # 26 a shorter fence does not close it + "print('c')", # 27 + "````", # 28 + "", # 29 + "~~~~", # 30 + "print('d')", # 31 + "~~~~", # 32 + ]) + self.assertEqual(adjacent_repeats(src), [(3, 7), (17, 21)]) + + def test_detector_ignores_one_line_differences_and_empty_blocks(self): + src = "\n".join([ + "```sh", # 1 + "run --one", # 2 + "```", # 3 + "```sh", # 4 + "run --two", # 5 + "```", # 6 + "```", # 7 empty + "```", # 8 empty + ]) + self.assertEqual(adjacent_repeats(src), []) + + def test_no_page_repeats_a_block_back_to_back(self): + if not os.path.isdir(DOCS): + self.skipTest("no docs directory") + pages = sorted(name for name in os.listdir(DOCS) if name.endswith(".md")) + self.assertGreater(len(pages), 40, "the scan found almost no pages; is the layout different?") + bad = [] + for name in pages: + with open(os.path.join(DOCS, name), encoding="utf-8", errors="replace") as handle: + for first, second in adjacent_repeats(handle.read()): + bad.append(f"docs/{name}: the block at line {first} is repeated at line {second}") + self.assertEqual(bad, []) + + +if __name__ == "__main__": + unittest.main() From 34739cff3e818eecf49fdd5b7d07a80903529b29 Mon Sep 17 00:00:00 2001 From: Salim Hammami Date: Mon, 23 Nov 2026 12:37:20 +0100 Subject: [PATCH 06/21] tests: compare the fence's info string too, so two languages are not one duplicate --- tests/test_docs_adjacent_fenced_blocks.py | 28 +++++++++++++++-------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/tests/test_docs_adjacent_fenced_blocks.py b/tests/test_docs_adjacent_fenced_blocks.py index 7142e47db0..0eacf8b050 100644 --- a/tests/test_docs_adjacent_fenced_blocks.py +++ b/tests/test_docs_adjacent_fenced_blocks.py @@ -5,8 +5,9 @@ leaves the other stale next to it. That is how `docs/character_models.md` carried the same `manifest.json` block twice (lines 312-320 and 322-330) until it was dropped. -The rule is deliberately narrow: the blocks must be identical and adjacent, so the same command -quoted again in a later section, or two blocks that differ in one line, are not reported. +The rule is deliberately narrow: the blocks must be identical, carry the same language tag, and be adjacent, so the +same command quoted again in a later section, two blocks that differ in one line, or one expression shown for two +languages are not reported. python -I tests/test_docs_adjacent_fenced_blocks.py @@ -24,22 +25,22 @@ def fenced_blocks(lines): - """[(index of the opening fence, index of the closing fence, content lines)] for `lines`.""" + """[(opening fence index, closing fence index, info string, content lines)] for `lines`.""" blocks, opened = [], None for index, line in enumerate(lines): match = FENCE.match(line) if opened is None: if match: marker = match.group(1) - opened = (index, marker[0], len(marker), []) + opened = (index, marker[0], len(marker), match.group(2).strip().lower(), []) continue # A closing fence is the same character, at least as long, and nothing after it. if match and match.group(1)[0] == opened[1] and len(match.group(1)) >= opened[2] \ and not match.group(2).strip(): - blocks.append((opened[0], index, opened[3])) + blocks.append((opened[0], index, opened[3], opened[4])) opened = None continue - opened[3].append(line) + opened[4].append(line) return blocks @@ -47,13 +48,14 @@ def adjacent_repeats(text): """[(first block's line number, second block's line number)] for identical blocks back to back. Line numbers are 1-based and name the opening fence. Blocks with prose between them are not - back to back, and empty blocks are ignored. + back to back, blocks with different info strings are different examples even when the text matches + (a Python and a Ruby snippet can read the same), and empty blocks are ignored. """ lines = text.splitlines() found = [] blocks = fenced_blocks(lines) - for (start_a, end_a, body_a), (start_b, _end_b, body_b) in zip(blocks, blocks[1:]): - if body_a != body_b or not any(line.strip() for line in body_a): + for (start_a, end_a, info_a, body_a), (start_b, _end_b, info_b, body_b) in zip(blocks, blocks[1:]): + if body_a != body_b or info_a != info_b or not any(line.strip() for line in body_a): continue if all(not line.strip() for line in lines[end_a + 1:start_b]): found.append((start_a + 1, start_b + 1)) @@ -95,6 +97,14 @@ def test_detector_finds_only_identical_adjacent_blocks(self): "~~~~", # 30 "print('d')", # 31 "~~~~", # 32 + "", # 33 + "~~~python", # 34 + "print('e')", # 35 + "~~~", # 36 + "", # 37 + "~~~ruby", # 38 + "print('e')", # 39 + "~~~", # 40 same text, another language: allowed ]) self.assertEqual(adjacent_repeats(src), [(3, 7), (17, 21)]) From a759e1ebc6950449cdbb3399b429cae32561b947 Mon Sep 17 00:00:00 2001 From: kirigayakazima <46666711+kirigayakazima@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:14:04 +0800 Subject: [PATCH 07/21] tools: guard ps_helper_probe.py empty coverage and atomic --json writes --- tests/test_ps_helper_probe.py | 88 +++++++++++++++++++++ tools/ps_helper_probe.py | 141 ++++++++++++++++++++++++++-------- 2 files changed, 198 insertions(+), 31 deletions(-) diff --git a/tests/test_ps_helper_probe.py b/tests/test_ps_helper_probe.py index 1f1b28162c..8a9ba56625 100644 --- a/tests/test_ps_helper_probe.py +++ b/tests/test_ps_helper_probe.py @@ -1,10 +1,15 @@ """tools/ps_helper_probe.py: the analysis on a CPU model of what gfx1036 does (each check, and that it fails when the model breaks that rule), the programs' shape, and (with LEONIDA_PS_ORACLE_BUILD set to a runtime build and an AMD GPU selected) the measurement itself. Standard library only.""" +import contextlib +import io +import json import os import struct import sys +import tempfile import unittest +from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "tools")) @@ -107,6 +112,89 @@ def test_every_program_ends_and_exports_once(self): self.assertEqual("s_wqm_b64 exec, exec" in lines, H.PROGRAMS[name][0]) +class CliAndJsonTests(unittest.TestCase): + def test_empty_coverage_does_not_crash_and_fails_coverage_checks(self): + res = {name: {(x, y): H.CLEAR for y in range(Hh) for x in range(W)} for name in H.PROGRAMS} + checks = H.analyze(res) + self.assertEqual(len(checks), 10) + by_name = {name: ok for name, ok, _ in checks} + for name, ok in by_name.items(): + if not name.startswith("an exp"): + self.assertFalse(ok, f"expected {name!r} to fail when nothing is covered") + + def test_json_preflight_rejects_bad_paths_before_measure(self): + with tempfile.TemporaryDirectory() as tmp: + blocker = os.path.join(tmp, "not_a_dir") + with open(blocker, "w", encoding="utf-8", newline="\n") as f: + f.write("x") + for bad in ("", " ", tmp, tmp + os.sep, os.path.join(blocker, "out.json")): + with self.subTest(bad=bad): + err = io.StringIO() + with mock.patch.object(H, "measure", side_effect=AssertionError("should not run GPU")), \ + contextlib.redirect_stderr(err): + rc = H.main(["--build", "dummy", "--json", bad]) + self.assertEqual(rc, 2) + self.assertTrue(err.getvalue().strip()) + + def test_json_write_is_atomic_has_trailing_newline_and_preserves_existing_on_failure(self): + res = model() + with tempfile.TemporaryDirectory() as tmp: + out_json = os.path.join(tmp, "nested", "probe.json") + with mock.patch.object(H, "measure", return_value=("mock-gpu", res)), \ + contextlib.redirect_stdout(io.StringIO()): + rc = H.main(["--build", "dummy", "--json", out_json]) + self.assertEqual(rc, 0) + with open(out_json, "rb") as f: + raw = f.read() + self.assertTrue(raw.endswith(b"\n")) + self.assertNotIn(b"\r\n", raw) + doc = json.loads(raw.decode("utf-8")) + self.assertEqual(doc["device"], "mock-gpu") + + before = b'{"keep": true}\n' + with open(out_json, "wb") as f: + f.write(before) + nested_dir = os.path.dirname(out_json) + + def fail_dump(*_args, **_kwargs): + raise OSError("disk full") + + for target_obj, attr, side_effect in ( + (H.json, "dump", fail_dump), + (os, "replace", OSError("replace failed")), + ): + with self.subTest(mock_attr=attr): + err = io.StringIO() + with mock.patch.object(H, "measure", return_value=("mock-gpu", res)), \ + mock.patch.object(target_obj, attr, side_effect=side_effect), \ + contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): + rc = H.main(["--build", "dummy", "--json", out_json]) + self.assertEqual(rc, 2) + self.assertNotIn("Traceback", err.getvalue()) + with open(out_json, "rb") as f: + self.assertEqual(f.read(), before) + self.assertEqual(sorted(os.listdir(nested_dir)), ["probe.json"]) + + def test_symlinked_json_updates_target_in_place(self): + res = model() + with tempfile.TemporaryDirectory() as tmp: + real_path = os.path.join(tmp, "real.json") + with open(real_path, "wb") as f: + f.write(b"{}\n") + link_path = os.path.join(tmp, "link.json") + try: + os.symlink(real_path, link_path) + except OSError as exc: + self.skipTest(f"symlink unavailable: {exc}") + with mock.patch.object(H, "measure", return_value=("mock-gpu", res)), \ + contextlib.redirect_stdout(io.StringIO()): + rc = H.main(["--build", "dummy", "--json", link_path]) + self.assertEqual(rc, 0) + self.assertTrue(os.path.islink(link_path)) + with open(real_path, encoding="utf-8") as f: + self.assertEqual(json.load(f)["device"], "mock-gpu") + + @unittest.skipUnless(os.environ.get("LEONIDA_PS_ORACLE_BUILD"), "set LEONIDA_PS_ORACLE_BUILD to a runtime build " "and select an AMD GPU (LEONIDA_VK_DEVICE) to measure helper lanes on hardware") class OnHardware(unittest.TestCase): diff --git a/tools/ps_helper_probe.py b/tools/ps_helper_probe.py index d05ffe1a4d..db5d2fb0d5 100644 --- a/tools/ps_helper_probe.py +++ b/tools/ps_helper_probe.py @@ -32,8 +32,11 @@ import tempfile HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, HERE) +if HERE not in sys.path: + sys.path.insert(0, HERE) +from file_mode import published_mode # noqa: E402 import ps_oracle # noqa: E402 +from replace_retry import replace as replace_retry # noqa: E402 SIZE = (16, 16) TRI = ((-1.0, -1.0), (1.3, -1.0), (-1.0, 0.9)) @@ -180,34 +183,46 @@ def analyze(res, size=SIZE, tri=TRI): waves = {} for p in cov: waves.setdefault(entry[p], []).append(p) - entry_ok, wqm_ok, packed, detail = True, True, True, [] - for e, pix in sorted(waves.items()): - lanes = [lane[p] for p in pix] - quads = {ln // 4 for ln in lanes} - w = {wqm[p] for p in pix} + if cov: + entry_ok, wqm_ok, packed, detail = True, True, True, [] bits = lambda m: {i for i in range(64) if m >> i & 1} # noqa: E731 - entry_ok &= len(set(lanes)) == len(lanes) and bits(e) == set(lanes) - wqm_ok &= len(w) == 1 and bits(w.pop() if len(w) == 1 else 0) == {4 * q + i for q in quads for i in range(4)} - packed &= quads == set(range(len(quads))) - detail.append(f"0x{e:016x}: {len(pix)} covered lanes in {len(quads)} quads") - out.append(("entry EXEC = the covered pixels (helpers off)", entry_ok, f"{len(waves)} waves: " + "; ".join(detail))) + for e, pix in sorted(waves.items()): + lanes = [lane[p] for p in pix] + quads = {ln // 4 for ln in lanes} + w = {wqm[p] for p in pix} + entry_ok &= len(set(lanes)) == len(lanes) and bits(e) == set(lanes) + wqm_ok &= len(w) == 1 and bits(w.pop() if len(w) == 1 else 0) == {4 * q + i for q in quads for i in range(4)} + packed &= quads == set(range(len(quads))) + detail.append(f"0x{e:016x}: {len(pix)} covered lanes in {len(quads)} quads") + waves_detail = f"{len(waves)} waves: " + "; ".join(detail) + else: + entry_ok = wqm_ok = packed = False + waves_detail = "0 waves (no covered pixels)" + out.append(("entry EXEC = the covered pixels (helpers off)", entry_ok, waves_detail)) out.append(("s_wqm turns on exactly the quads with a covered pixel", wqm_ok, "")) out.append(("quads packed from lane 0; none without a covered pixel", packed, "")) - order = {(p[0] & 1) + 2 * (p[1] & 1) == lane[p] % 4 for p in cov} - out.append(("lane % 4 = (x & 1) + 2 (y & 1): 0 top-left, 1 top-right, 2 bottom-left, 3 bottom-right", - order == {True}, "")) - err_c = max(max(abs(f32(res["self"][p][2]) - ndc(p, size)[0]), abs(f32(res["self"][p][3]) - ndc(p, size)[1])) - for p in cov) - err_h = 0.0 - for p, k in helpers: - got = {1: res["nb12"][p][0:2], 2: res["nb12"][p][2:4], 3: res["nb3"][p][0:2]}[k] - ex = ndc(neighbour(p, k), size) - err_h = max(err_h, abs(f32(got[0]) - ex[0]), abs(f32(got[1]) - ex[1])) - out.append(("after s_wqm a helper interpolates its own pixel centre, as precisely as a covered pixel", - err_h <= 1.5 * err_c + 1e-6, f"helper |error| max {err_h:.2e}, covered {err_c:.2e}")) - nm = res["nowqm_masks"] - out.append(("without s_wqm EXEC stays the entry mask", all( - (nm[p][1] | nm[p][2] << 32) == entry[p] and nm[p][3] == entry[p] & 0xFFFFFFFF for p in cov), "")) + if cov: + order = {(p[0] & 1) + 2 * (p[1] & 1) == lane[p] % 4 for p in cov} + out.append(("lane % 4 = (x & 1) + 2 (y & 1): 0 top-left, 1 top-right, 2 bottom-left, 3 bottom-right", + order == {True}, "")) + err_c = max(max(abs(f32(res["self"][p][2]) - ndc(p, size)[0]), abs(f32(res["self"][p][3]) - ndc(p, size)[1])) + for p in cov) + err_h = 0.0 + for p, k in helpers: + got = {1: res["nb12"][p][0:2], 2: res["nb12"][p][2:4], 3: res["nb3"][p][0:2]}[k] + ex = ndc(neighbour(p, k), size) + err_h = max(err_h, abs(f32(got[0]) - ex[0]), abs(f32(got[1]) - ex[1])) + out.append(("after s_wqm a helper interpolates its own pixel centre, as precisely as a covered pixel", + err_h <= 1.5 * err_c + 1e-6, f"helper |error| max {err_h:.2e}, covered {err_c:.2e}")) + nm = res["nowqm_masks"] + out.append(("without s_wqm EXEC stays the entry mask", all( + (nm[p][1] | nm[p][2] << 32) == entry[p] and nm[p][3] == entry[p] & 0xFFFFFFFF for p in cov), "")) + else: + out.append(("lane % 4 = (x & 1) + 2 (y & 1): 0 top-left, 1 top-right, 2 bottom-left, 3 bottom-right", + False, "no covered pixels")) + out.append(("after s_wqm a helper interpolates its own pixel centre, as precisely as a covered pixel", + False, "no covered pixels")) + out.append(("without s_wqm EXEC stays the entry mask", False, "no covered pixels")) h1 = [p for p in cov if neighbour(p, 1) not in cov] ij = {p: (f32(res["nowqm_ij"][p][0]), f32(res["nowqm_ij"][p][1])) for p in h1} err_ij = max([max(abs(g[0] - bary(neighbour(p, 1), size, tri)[0]), abs(g[1] - bary(neighbour(p, 1), size, tri)[1])) @@ -251,11 +266,69 @@ def _run(o): o.close() +def _validate_json_out(raw_path): + """Validate --json output path before running the GPU harness; return (abs_path, err_msg).""" + if not raw_path.strip(): + return None, "--json path must not be empty" + if raw_path.endswith(("/", "\\")) or (os.sep and raw_path.endswith(os.sep)): + return None, f"--json is a directory path: {raw_path}" + out_path = os.path.abspath(raw_path) + if os.path.isdir(out_path): + return None, f"--json is a directory: {out_path}" + cur = os.path.dirname(out_path) + while cur: + if os.path.exists(cur): + if not os.path.isdir(cur): + return None, f"--json parent path is not a directory: {cur}" + break + parent = os.path.dirname(cur) + if parent == cur: + break + cur = parent + return out_path, None + + +def _write_json_atomic(path, payload): + dest = os.path.realpath(path) + parent = os.path.dirname(dest) or "." + os.makedirs(parent, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=parent, prefix=".tmp-", suffix=".json") + try: + try: + f = os.fdopen(fd, "w", encoding="utf-8", newline="\n") + except BaseException: + os.close(fd) + raise + with f: + json.dump(payload, f, indent=1) + f.write("\n") + f.flush() + os.fsync(f.fileno()) + os.chmod(tmp, published_mode(dest)) + replace_retry(tmp, dest) + except BaseException: + try: + os.chmod(tmp, 0o600) + except OSError: + pass + try: + os.unlink(tmp) + except OSError: + pass + raise + + def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("--build", required=True, help="runtime build folder with vk_harness") ap.add_argument("--json", help="write {device, checks, words} here") a = ap.parse_args(argv) + out_path = None + if a.json is not None: + out_path, err_msg = _validate_json_out(a.json) + if err_msg: + print(f"ps_helper_probe: {err_msg}", file=sys.stderr) + return 2 try: device, res = measure(a.build) except ps_oracle.Unavailable as e: @@ -273,11 +346,17 @@ def main(argv=None): print(f"{'ok ' if ok else 'FAIL'} {name}" + (f" ({detail})" if detail else "")) good = sum(ok for _n, ok, _d in checks) print(f"{good}/{len(checks)} checks hold") - if a.json: - with open(a.json, "w", encoding="utf-8", newline="\n") as fh: - json.dump({"device": device, "checks": [[n, ok, d] for n, ok, d in checks], - "words": {n: {f"{x},{y}": list(w) for (x, y), w in px.items()} for n, px in res.items()}}, - fh, indent=1) + if out_path is not None: + payload = { + "device": device, + "checks": [[n, ok, d] for n, ok, d in checks], + "words": {n: {f"{x},{y}": list(w) for (x, y), w in px.items()} for n, px in res.items()}, + } + try: + _write_json_atomic(out_path, payload) + except OSError as e: + print(f"ps_helper_probe: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) + return 2 return 0 if good == len(checks) else 1 From abe47df11e9292817db3c387be33137cb8935756 Mon Sep 17 00:00:00 2001 From: kirigayakazima <46666711+kirigayakazima@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:21:02 +0800 Subject: [PATCH 08/21] tools: handle corrupt XBCH zlib, case-insensitive extensions and index errors in pal_stages.py --- tests/test_pal_stages.py | 51 ++++++++++++++++++++++++++++++++++++++++ tools/pal_stages.py | 15 ++++++++---- 2 files changed, 61 insertions(+), 5 deletions(-) diff --git a/tests/test_pal_stages.py b/tests/test_pal_stages.py index dd48a04043..aaf3277241 100644 --- a/tests/test_pal_stages.py +++ b/tests/test_pal_stages.py @@ -11,6 +11,7 @@ import sys import tempfile import unittest +import unittest.mock import zlib ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -203,6 +204,56 @@ def test_limit_below_one_is_refused(self): self.assertIn("--limit", result.stderr) self.assertIn("at least 1", result.stderr) + def test_corrupt_xbch_zlib_records_error_row_instead_of_crashing(self): + corrupt_zlib = b"\x78\x9c\xff\xff\xff\xff" + bad_xbch = b"XBCH" + struct.pack(" Date: Wed, 25 Nov 2026 20:25:15 +0800 Subject: [PATCH 09/21] tools: harden bcpack_tables_bptc.py section validation, bounds and file cache --- tests/test_bcpack_tables_bptc.py | 85 +++++++++++++++++++ tools/bcpack_tables_bptc.py | 140 ++++++++++++++++++------------- 2 files changed, 167 insertions(+), 58 deletions(-) diff --git a/tests/test_bcpack_tables_bptc.py b/tests/test_bcpack_tables_bptc.py index a9363cf059..8c6bc8cc7b 100644 --- a/tests/test_bcpack_tables_bptc.py +++ b/tests/test_bcpack_tables_bptc.py @@ -15,6 +15,7 @@ import sys import tempfile import unittest +from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TOOLS_DIR = os.path.join(ROOT, "tools") @@ -638,5 +639,89 @@ def test_validation_errors(self) -> None: bptc.load_bc7({"bc7": bad_sec}) +class TestSecurityAndEdgeValidation(unittest.TestCase): + """Regression tests for section validation, recursion bounds, bit-shift bounds, and cache identity.""" + + def test_non_dict_codec_section_raises_value_error(self) -> None: + for bad in ([], 123, "bad"): + with self.subTest(bad=bad): + with self.assertRaisesRegex(ValueError, "JSON object"): + bptc.load_bc6h({"bc6h": bad}) + with self.assertRaisesRegex(ValueError, "JSON object"): + bptc.load_bc7({"bc7": bad}) + + def test_recursion_error_in_json_raises_value_error(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "deep.json") + with open(path, "w", encoding="utf-8", newline="\n") as fh: + fh.write("{}") + bptc._FILE_CACHE.pop(os.path.realpath(path), None) + bptc._FILE_CACHE.pop(os.path.abspath(path), None) + with mock.patch.object(bptc.json, "load", side_effect=RecursionError("too deep")): + for fn in ( + lambda: bptc.load_bc6h(path), + lambda: bptc.load_bc7(path), + lambda: bptc.load_bc_history(1, path), + ): + with self.assertRaisesRegex(ValueError, "too deep"): + fn() + + def test_bc7_low2_fit_confirmed_bits_above_8_raises_value_error_not_negative_shift(self) -> None: + sec = { + "historyEndpoints": {"0": [0x80] * 24}, + "historyEndpointBits": {"0": [4] * 24}, + "historyEndpointConfirmedBits": {"0": [9] + [0] * 23}, + "historyEndpointLow2Fits": [[0, 0, 1]], + } + with self.assertRaisesRegex(ValueError, "out of bounds"): + bptc.load_bc7({"bc7": sec}) + for bad_fits in (123, [[0, 0]], [[True, 0, 1]], [[0, 0, "1"]]): + with self.subTest(bad_fits=bad_fits): + bad_sec = { + "historyEndpoints": {"0": [0x80] * 24}, + "historyEndpointBits": {"0": [4] * 24}, + "historyEndpointLow2Fits": bad_fits, + } + with self.assertRaises(ValueError): + bptc.load_bc7({"bc7": bad_sec}) + + def test_bc7_last_resort_scalar_or_out_of_bounds_raises_value_error(self) -> None: + for bad_lr in (123, [123], [[256, 0]], [[-1, 0]], [[0, 24]], [[0, 3, 0, 0]], [[0, 0, 2, 0]], [[0, 0, 0, 4]]): + with self.subTest(bad_lr=bad_lr): + with self.assertRaises(ValueError): + bptc.load_bc7({"bc7": {"historyEndpointLastResort": bad_lr}}) + + def test_bc6h_scalar_row_raises_value_error(self) -> None: + for bad_sec in ( + {"endpointHistory": {"0": 123}}, + {"endpointHistory": {"0": [123, [0] * 4, [0] * 4]}}, + {"indexHistory": {"0": 123}}, + {"endpointConfirmedBits": {"0": 123}}, + {"indexConfirmedBits": {"0": 123}}, + ): + with self.subTest(bad_sec=bad_sec): + with self.assertRaises(ValueError): + bptc.load_bc6h({"bc6h": bad_sec}) + + def test_file_cache_invalidates_on_same_size_mtime_inode_replacement(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + hist = os.path.join(tmp, "hist.json") + staged = os.path.join(tmp, "staged.json") + payload_a = json.dumps({"bc6h": {"endpointClass": {"0": 1}}}) + payload_b = json.dumps({"bc6h": {"endpointClass": {"0": 2}}}) + self.assertEqual(len(payload_a), len(payload_b)) + with open(hist, "w", encoding="utf-8", newline="\n") as fh: + fh.write(payload_a) + st = os.stat(hist) + self.assertEqual(bptc.load_bc6h(hist)[2][0], 1) + + with open(staged, "w", encoding="utf-8", newline="\n") as fh: + fh.write(payload_b) + os.utime(staged, ns=(st.st_atime_ns, st.st_mtime_ns)) + os.replace(staged, hist) + os.utime(hist, ns=(st.st_atime_ns, st.st_mtime_ns)) + self.assertEqual(bptc.load_bc6h(hist)[2][0], 2) + + if __name__ == "__main__": unittest.main() diff --git a/tools/bcpack_tables_bptc.py b/tools/bcpack_tables_bptc.py index a7449e58e4..ae86ea1352 100644 --- a/tools/bcpack_tables_bptc.py +++ b/tools/bcpack_tables_bptc.py @@ -140,35 +140,45 @@ def _bc7_static(): return _BC7_STATIC_CACHE +def _load_json_file(path): + """Load and cache a JSON object file, keyed by resolved realpath and stat identity.""" + real = os.path.realpath(path) + st = os.stat(real) + cache_key = (st.st_mtime_ns, st.st_size, st.st_dev, st.st_ino) + cached = _FILE_CACHE.get(real) + if cached is not None and cached[0] == cache_key: + return cached[1] + with open(real, "r", encoding="utf-8-sig") as fh: + try: + data = json.load(fh) + except RecursionError: + raise ValueError(f"{path}: JSON nesting too deep") from None + if not isinstance(data, dict): + raise ValueError(f"{path}: expected a JSON object") + _FILE_CACHE[real] = (cache_key, data) + return data + + def _read_history_section(history, codec_key, marker_key): """Resolve `history` (None, dict, JSON file, or directory) for one codec.""" if history is None: return None if isinstance(history, dict): - if codec_key in history: - return history[codec_key] - return history if marker_key in history else None - path = os.fspath(history) - if os.path.isdir(path): - candidate = os.path.join(path, f"{codec_key}.json") - if not os.path.isfile(candidate): - return None - path = candidate - abspath = os.path.abspath(path) - st = os.stat(abspath) - cache_key = (st.st_mtime_ns, st.st_size) - cached = _FILE_CACHE.get(abspath) - if cached is not None and cached[0] == cache_key: - data = cached[1] + container = history else: - with open(abspath, "r", encoding="utf-8-sig") as fh: - data = json.load(fh) - if not isinstance(data, dict): - raise ValueError(f"{path}: expected a JSON object") - _FILE_CACHE[abspath] = (cache_key, data) - if codec_key in data: - return data[codec_key] - return data if marker_key in data else None + path = os.fspath(history) + if os.path.isdir(path): + candidate = os.path.join(path, f"{codec_key}.json") + if not os.path.isfile(candidate): + return None + path = candidate + container = _load_json_file(path) + if codec_key in container: + sec = container[codec_key] + if sec is not None and not isinstance(sec, dict): + raise ValueError(f"{codec_key} history section must be a JSON object") + return sec + return container if marker_key in container else None def _iter_entries(obj, count=256): @@ -227,11 +237,13 @@ def load_bc6h(history=None, *, with_confirmed_bits=False): ec = list(_EMPTY_BC6H_CLS) ic = list(_EMPTY_BC6H_CLS) for i, channels in _iter_entries(sec.get("endpointHistory")): - if len(channels) != 3 or any(len(ch) != 4 for ch in channels): + if not isinstance(channels, (list, tuple)) or len(channels) != 3 or any( + not isinstance(ch, (list, tuple)) or len(ch) != 4 for ch in channels + ): raise ValueError(f"BC6H endpointHistory[{i}] must be 3x4 integers") eh[i] = tuple(tuple(int(v) for v in ch) for ch in channels) for i, pixels in _iter_entries(sec.get("indexHistory")): - if len(pixels) != 16: + if not isinstance(pixels, (list, tuple)) or len(pixels) != 16: raise ValueError(f"BC6H indexHistory[{i}] must have 16 integers") ih[i] = tuple(int(v) for v in pixels) for i, cls in _iter_entries(sec.get("endpointClass")): @@ -250,12 +262,14 @@ def load_bc6h(history=None, *, with_confirmed_bits=False): target[:] = empty for i, row in _iter_entries(sec[key]): if key == "endpointConfirmedBits": - if len(row) != 3 or any(len(ch) != 4 for ch in row): + if not isinstance(row, (list, tuple)) or len(row) != 3 or any( + not isinstance(ch, (list, tuple)) or len(ch) != 4 for ch in row + ): raise ValueError(f"BC6H {key}[{i}] must be 3x4 integers") value = tuple(tuple(int(v) for v in ch) for ch in row) valid = all(0 <= v <= widths[q] for ch in value for q, v in enumerate(ch)) else: - if len(row) != 16: + if not isinstance(row, (list, tuple)) or len(row) != 16: raise ValueError(f"BC6H {key}[{i}] must have 16 integers") value = tuple(int(v) for v in row) valid = all(0 <= v <= 4 for v in value) @@ -318,26 +332,47 @@ def load_bc7(history=None): ) # Optional same-stream red parity fits, applied after midpoint fill. Preserve # all leading sibling/reference bits and keep the available precision unchanged. - for k, field, low in sec.get("historyEndpointLow2Fits") or (): - if not (0 <= k < 256 and field in (0, 4, 8, 12, 16, 20) and 0 <= low < 4): - raise ValueError("invalid BC7 low-bit endpoint fit") - depth = ep_b[k][field] - old = ep[k][field] - value = (old & ~3) | low - if not 4 <= depth < 8 or (old ^ value) >> (8 - max(depth, ep_cb[k][field])): - raise ValueError("BC7 low-bit fit changes a known prefix") - row = list(ep[k]) - row[field] = value - ep[k] = tuple(row) + low2 = sec.get("historyEndpointLow2Fits") + if low2 is not None: + if not isinstance(low2, (list, tuple)): + raise ValueError("historyEndpointLow2Fits must be a list") + for item in low2: + if not isinstance(item, (list, tuple)) or len(item) != 3 or not all(type(x) is int for x in item): + raise ValueError("invalid BC7 low-bit endpoint fit") + k, field, low = item + if not (0 <= k < 256 and field in (0, 4, 8, 12, 16, 20) and 0 <= low < 4): + raise ValueError("invalid BC7 low-bit endpoint fit") + depth = ep_b[k][field] + cb = ep_cb[k][field] + if not 0 <= cb <= 8: + raise ValueError("BC7 confirmed bit depth out of bounds") + old = ep[k][field] + value = (old & ~3) | low + if not 4 <= depth < 8 or (old ^ value) >> (8 - max(depth, cb)): + raise ValueError("BC7 low-bit fit changes a known prefix") + row = list(ep[k]) + row[field] = value + ep[k] = tuple(row) last_resort = set() - for item in sec.get("historyEndpointLastResort") or (): - if len(item) == 4: - k, sub, e, c = (int(x) for x in item) - last_resort.add((k, sub * 8 + e * 4 + c)) - elif len(item) == 2: - last_resort.add((int(item[0]), int(item[1]))) - else: - raise ValueError("historyEndpointLastResort entries must have 2 or 4 integers") + last_resort_raw = sec.get("historyEndpointLastResort") + if last_resort_raw is not None: + if not isinstance(last_resort_raw, (list, tuple)): + raise ValueError("historyEndpointLastResort must be a list") + for item in last_resort_raw: + if not isinstance(item, (list, tuple)): + raise ValueError("historyEndpointLastResort entries must have 2 or 4 integers") + if len(item) == 4: + k, sub, e, c = (int(x) for x in item) + if not (0 <= k < 256 and 0 <= sub < 3 and 0 <= e < 2 and 0 <= c < 4): + raise ValueError("historyEndpointLastResort index out of bounds") + last_resort.add((k, sub * 8 + e * 4 + c)) + elif len(item) == 2: + k, field = int(item[0]), int(item[1]) + if not (0 <= k < 256 and 0 <= field < 24): + raise ValueError("historyEndpointLastResort index out of bounds") + last_resort.add((k, field)) + else: + raise ValueError("historyEndpointLastResort entries must have 2 or 4 integers") return { **static, "history_endpoints": tuple(ep), @@ -387,18 +422,7 @@ def load_bc_history(codec, history=None): if not os.path.isfile(candidate): return None path = candidate - abspath = os.path.abspath(path) - st = os.stat(abspath) - cache_key = (st.st_mtime_ns, st.st_size) - cached = _FILE_CACHE.get(abspath) - if cached is not None and cached[0] == cache_key: - data = cached[1] - else: - with open(abspath, "r", encoding="utf-8-sig") as fh: - data = json.load(fh) - if not isinstance(data, dict): - raise ValueError(f"{path}: expected a JSON object") - _FILE_CACHE[abspath] = (cache_key, data) + data = _load_json_file(path) if codec_key in data: sec = data[codec_key] elif data.get("codec") == codec_key: From 59eadb0be5ec32363711a447f305a35f36b0da34 Mon Sep 17 00:00:00 2001 From: kirigayakazima <46666711+kirigayakazima@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:27:21 +0800 Subject: [PATCH 10/21] tools: make script_qtable.py --json writes atomic and validate paths and hex stems --- tests/test_script_qtable.py | 85 +++++++++++++++++++++++++++++++++++++ tools/script_qtable.py | 54 ++++++++++++++++++----- 2 files changed, 129 insertions(+), 10 deletions(-) diff --git a/tests/test_script_qtable.py b/tests/test_script_qtable.py index c405620c7f..249fb40af1 100644 --- a/tests/test_script_qtable.py +++ b/tests/test_script_qtable.py @@ -5,6 +5,8 @@ Every fixture is synthetic: 40-byte header + u64 offset table + 16-byte-aligned struct, wrapper and array records linked by 0x71717171-tagged pointers. """ +import contextlib +import io import json import os import struct @@ -13,6 +15,7 @@ import tempfile import time import unittest +from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TOOLS = os.path.join(ROOT, "tools") @@ -378,6 +381,88 @@ def test_type_query_sorts_histograms_numerically(self): rep = script_qtable.parse_qtable(blob, type_hash=0xBBBB0001) self.assertEqual(list(rep["type_query"]["struct_sizes"].keys()), ["32", "112"]) + def test_empty_whitespace_and_trailing_sep_json_paths_are_usage_errors(self): + with tempfile.TemporaryDirectory() as tmp: + bin_path = os.path.join(tmp, "qtable.bin") + with open(bin_path, "wb") as f: + f.write(build_synthetic_qtable()) + for bad in ("", " ", os.path.join(tmp, "newdir") + os.sep): + with self.subTest(bad=bad): + err = io.StringIO() + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): + rc = script_qtable.main([bin_path, "--json", bad]) + self.assertEqual(rc, 2) + self.assertTrue(err.getvalue().startswith("ERROR:"), err.getvalue()) + + def test_json_write_is_atomic_has_trailing_newline_and_preserves_existing_on_failure(self): + with tempfile.TemporaryDirectory() as tmp: + bin_path = os.path.join(tmp, "qtable.bin") + out_dir = os.path.join(tmp, "reports") + out_json = os.path.join(out_dir, "report.json") + with open(bin_path, "wb") as f: + f.write(build_synthetic_qtable()) + with contextlib.redirect_stdout(io.StringIO()): + rc = script_qtable.main([bin_path, "--json", out_json]) + self.assertEqual(rc, 0) + with open(out_json, "rb") as f: + raw = f.read() + self.assertTrue(raw.endswith(b"\n")) + self.assertNotIn(b"\r\n", raw) + + before = b'{"keep": true}\n' + with open(out_json, "wb") as f: + f.write(before) + + def fail_dump(_data, handle, **_kwargs): + handle.write("{") + raise OSError("disk full") + + for target_obj, attr, side_effect in ( + (script_qtable.json, "dump", fail_dump), + (os, "replace", PermissionError("locked")), + ): + with self.subTest(mock_attr=attr): + err = io.StringIO() + with mock.patch.object(target_obj, attr, side_effect=side_effect), \ + contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): + rc = script_qtable.main([bin_path, "--json", out_json]) + self.assertEqual(rc, 2) + self.assertTrue(err.getvalue().startswith("ERROR: cannot write "), err.getvalue()) + with open(out_json, "rb") as f: + self.assertEqual(f.read(), before) + self.assertEqual(os.listdir(out_dir), ["report.json"]) + + def test_symlinked_json_updates_target_in_place(self): + with tempfile.TemporaryDirectory() as tmp: + bin_path = os.path.join(tmp, "qtable.bin") + real_json = os.path.join(tmp, "real.json") + link_json = os.path.join(tmp, "link.json") + with open(bin_path, "wb") as f: + f.write(build_synthetic_qtable()) + with open(real_json, "wb") as f: + f.write(b"{}\n") + try: + os.symlink(real_json, link_json) + except OSError as exc: + self.skipTest(f"symlink unavailable: {exc}") + with contextlib.redirect_stdout(io.StringIO()): + rc = script_qtable.main([bin_path, "--json", link_json]) + self.assertEqual(rc, 0) + self.assertTrue(os.path.islink(link_json)) + with open(real_json, encoding="utf-8") as f: + self.assertTrue(json.load(f)["valid"]) + + def test_bin_folder_does_not_parse_negative_hex_stem_as_negative_offset(self): + with tempfile.TemporaryDirectory() as tmp: + with open(os.path.join(tmp, "-10.bin"), "wb") as f: + f.write(b"JUNK") + with open(os.path.join(tmp, "000000001000.bin"), "wb") as f: + f.write(build_synthetic_qtable()) + src = script_qtable._BinFolderSource(tmp) + by_name = {row["_name"]: row["off"] for row in src.rows} + self.assertEqual(by_name["000000001000.bin"], 0x1000) + self.assertGreater(by_name["-10.bin"], 0x1000) + if __name__ == "__main__": unittest.main() diff --git a/tools/script_qtable.py b/tools/script_qtable.py index 6c29a52602..d2e9096cfb 100644 --- a/tools/script_qtable.py +++ b/tools/script_qtable.py @@ -22,14 +22,17 @@ import os import struct import sys +import tempfile # -I keeps the script directory off sys.path, so add it explicitly before importing sibling helpers. TOOLS = os.path.dirname(os.path.abspath(__file__)) if TOOLS not in sys.path: sys.path.insert(0, TOOLS) +from file_mode import published_mode # noqa: E402 import gamedata_index as gi # noqa: E402 import gamedata_maps as gm # noqa: E402 +from replace_retry import replace as replace_retry # noqa: E402 from report_paths import same_report_path # noqa: E402 HEADER_BYTES = 40 @@ -480,12 +483,11 @@ def __init__(self, directory: str): if not os.path.isfile(full): continue sz = os.path.getsize(full) - try: - off = int(os.path.splitext(name)[0], 16) - except ValueError: - other_rows.append((name, sz)) + stem = os.path.splitext(name)[0] + if stem and all(c in "0123456789abcdefABCDEF" for c in stem): + hex_rows.append((int(stem, 16), name, sz)) else: - hex_rows.append((off, name, sz)) + other_rows.append((name, sz)) hex_rows.sort(key=lambda item: (item[0], item[1])) next_off = (hex_rows[-1][0] + 0x10000) if hex_rows else 0 self.rows = [{"off": off, "stored": sz, "size": sz, "_name": name} for off, name, sz in hex_rows] @@ -534,6 +536,10 @@ def load_qtable_payload(target: str) -> tuple[bytes, dict]: def check_report_path(out_path: str, target: str, rows: list[dict] | None = None) -> None: """Refuse a --json destination that is a directory or collides with any input.""" + if not out_path.strip(): + raise UsageError("--json path must not be empty") + if out_path.endswith(("/", "\\")) or (os.sep and out_path.endswith(os.sep)): + raise UsageError(f"--json is a directory path: {out_path}") if os.path.isdir(out_path): raise UsageError(f"--json is a directory: {out_path}") if os.path.isdir(target): @@ -589,6 +595,36 @@ def _print_summary(report: dict) -> None: ) +def _write_json_atomic(path: str, payload: dict) -> None: + dest = os.path.realpath(path) + parent = os.path.dirname(dest) or "." + os.makedirs(parent, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=parent, prefix=".tmp-", suffix=".json") + try: + try: + f = os.fdopen(fd, "w", encoding="utf-8", newline="\n") + except BaseException: + os.close(fd) + raise + with f: + json.dump(payload, f, indent=1) + f.write("\n") + f.flush() + os.fsync(f.fileno()) + os.chmod(tmp, published_mode(dest)) + replace_retry(tmp, dest) + except BaseException: + try: + os.chmod(tmp, 0o600) + except OSError: + pass + try: + os.unlink(tmp) + except OSError: + pass + raise + + def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("target", help="carved script directory, script.rpf archive, or joined .bin file") @@ -600,7 +636,7 @@ def main(argv=None) -> int: try: root_h = _parse_hex_u32(a.root_hash) if a.root_hash is not None else None type_h = _parse_hex_u32(a.type_hash) if a.type_hash is not None else None - if a.json: + if a.json is not None: rows = gm._read_index_rows(a.target) if os.path.isdir(a.target) and os.path.isfile(os.path.join(a.target, "index.json")) else None check_report_path(a.json, a.target, rows=rows) blob, meta = load_qtable_payload(a.target) @@ -621,11 +657,9 @@ def main(argv=None) -> int: out = {"location": meta, **report} _print_summary(out) - if a.json: + if a.json is not None: try: - gm._make_parent(a.json) - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(out, f, indent=1) + _write_json_atomic(a.json, out) except OSError as e: print(f"ERROR: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) return 2 From def89c3aa53f9f60993283cbc041929c4c6cf0fe Mon Sep 17 00:00:00 2001 From: kirigayakazima <46666711+kirigayakazima@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:29:24 +0800 Subject: [PATCH 11/21] tools: make gamedata_sps1.py --json writes atomic, validate paths and avoid duplicate index read --- tests/test_gamedata_sps1_atomic.py | 131 +++++++++++++++++++++++++++++ tools/gamedata_sps1.py | 51 +++++++++-- 2 files changed, 176 insertions(+), 6 deletions(-) create mode 100644 tests/test_gamedata_sps1_atomic.py diff --git a/tests/test_gamedata_sps1_atomic.py b/tests/test_gamedata_sps1_atomic.py new file mode 100644 index 0000000000..d008b71079 --- /dev/null +++ b/tests/test_gamedata_sps1_atomic.py @@ -0,0 +1,131 @@ +"""Atomic --json write, path validation, and index-read tests for tools/gamedata_sps1.py. + + python -I tests/test_gamedata_sps1_atomic.py +""" +import contextlib +import io +import json +import os +import struct +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOLS = os.path.join(ROOT, "tools") +if TOOLS not in sys.path: + sys.path.insert(0, TOOLS) + +import gamedata_sps1 # noqa: E402 + + +def _sps1_blob(entries: list[tuple[str, str, int]]) -> bytes: + buf = bytearray(b"SPS1" + struct.pack(" list[dict]: return out -def read_payloads(target: str) -> list[dict]: +def read_payloads(target: str, rows: list[dict] | None = None) -> list[dict]: """Load SPS1 payloads from a carve directory, a raw .bin file, or an .rpf archive.""" if os.path.isdir(target): - rows = gm._read_index_rows(target) + if rows is None: + rows = gm._read_index_rows(target) return _load_from_source(rows, lambda r: gm._read_row(target, r)) if not os.path.isfile(target): raise FileNotFoundError(target) @@ -322,6 +326,36 @@ def _public(payload: dict) -> dict: return {k: v for k, v in payload.items() if not k.startswith("_")} +def _write_json_atomic(path: str, payload: dict) -> None: + dest = os.path.realpath(path) + parent = os.path.dirname(dest) or "." + os.makedirs(parent, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=parent, prefix=".tmp-", suffix=".json") + try: + try: + f = os.fdopen(fd, "w", encoding="utf-8", newline="\n") + except BaseException: + os.close(fd) + raise + with f: + json.dump(payload, f, indent=1) + f.write("\n") + f.flush() + os.fsync(f.fileno()) + os.chmod(tmp, published_mode(dest)) + replace_retry(tmp, dest) + except BaseException: + try: + os.chmod(tmp, 0o600) + except OSError: + pass + try: + os.unlink(tmp) + except OSError: + pass + raise + + def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("target", help="rpf9_carve.py directory, common.rpf archive, or SPS1 .bin file") @@ -337,6 +371,12 @@ def main(argv=None) -> int: ap.error("--preset-hash expects up to eight hexadecimal digits") target_hash = int(a.preset_hash, 16) + if a.json is not None: + if not a.json.strip(): + ap.error("--json path must not be empty") + if a.json.endswith(("/", "\\")) or (os.sep and a.json.endswith(os.sep)): + ap.error(f"--json is a directory path: {a.json}") + # A missing input path is a usage error (exit 2), not a failed run, as in BUILD-1046. for path in (a.target, a.shaders): if path is not None and not os.path.exists(path): @@ -346,11 +386,12 @@ def main(argv=None) -> int: try: if a.json: check_report_path(a.json, a.target, a.shaders) + rows = None if os.path.isdir(a.target): rows = gm._read_index_rows(a.target) if a.json: check_report_path(a.json, a.target, a.shaders, rows=rows) - payloads = read_payloads(a.target) + payloads = read_payloads(a.target, rows=rows) xref = cross_reference_sgd5(payloads, a.shaders) if a.shaders else None matches = lookup_preset_hash(payloads, target_hash) if target_hash is not None else None except (OSError, ValueError, KeyError, TypeError, struct.error, RuntimeError) as e: @@ -387,9 +428,7 @@ def main(argv=None) -> int: if matches is not None: out["hash_matches"] = matches try: - gm._make_parent(a.json) - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(out, f, indent=1) + _write_json_atomic(a.json, out) except OSError as e: print(f"error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) return 1 From c90092b284ec264e93503c770d2c5b2d6137d78b Mon Sep 17 00:00:00 2001 From: DadaCap <167002618+DadaCap@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:05:05 +0100 Subject: [PATCH 12/21] d3d12: changed console heap slots are fixed without a time limit by default, not given to shaders as null (RT-CONSOLE-FIX-BUDGET-NULL) Co-Authored-By: Claude Opus 5.5 --- runtime/CMakeLists.txt | 2 +- runtime/README.md | 2 +- runtime/shims/d3d12_vulkan_device.cpp | 11 ++++++----- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index e9cb8d4345..4096c7f59f 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3456,7 +3456,7 @@ if(TARGET Vulkan::Headers) target_compile_definitions(d3d12_unmapped_vsharp_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) target_compile_options(d3d12_unmapped_vsharp_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_unmapped_vsharp COMMAND d3d12_unmapped_vsharp_test) - set_tests_properties(d3d12_unmapped_vsharp PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_CONSOLE_FIX_US=0") + set_tests_properties(d3d12_unmapped_vsharp PROPERTIES SKIP_RETURN_CODE 77) add_executable(d3d12_indirect_zero_test test/d3d12_indirect_zero_test.cpp) target_link_libraries(d3d12_indirect_zero_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) target_compile_definitions(d3d12_indirect_zero_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) diff --git a/runtime/README.md b/runtime/README.md index 1573b8883c..3bc9052e93 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -362,7 +362,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_WINDOW` | unset | `WxH` resizes the title's window when the presenter attaches to it. | | `LEONIDA_PRESENT_DUMP` | unset | *Diagnostic.* `DIR` or `DIR,N` writes every Nth presented frame (60 by default) as a PNG into `DIR` (`src/present_dump.h`). The files are pictures of the title: keep them out of commits, issues and pull requests. | | `LEONIDA_LOCAL_SPEECH` | unset | `1` forwards the title's speech-synthesis calls to the host's installed `xgameruntime.dll` where there is one. Unset, and wherever that library is missing, the silent voice answers. No profile sets it. | -| `LEONIDA_CONSOLE_FIX_US` | `4000` | Microseconds one submission may spend fixing the changed slots of a console descriptor heap's copy. Past it, each further changed slot is written as a null descriptor and queued for `LEONIDA_CONSOLE_RETRY_US`, so a shader reads it as empty until its turn comes. `0` removes the limit. | +| `LEONIDA_CONSOLE_FIX_US` | `0` | Microseconds one submission may spend fixing the changed slots of a console descriptor heap's copy; `0` sets no limit. Past it, each further changed slot is written as a null descriptor and queued for `LEONIDA_CONSOLE_RETRY_US`, so a shader reads it as empty until its turn comes: a limit changes results, and can hang the GPU. | | `LEONIDA_CONSOLE_RETRY_US` | `500` | Microseconds one submission may spend retrying, round robin, the console heap slots not settled yet (a T# whose texture does not exist yet, or one deferred by `LEONIDA_CONSOLE_FIX_US`). `0` retries all of them at every submission. | | `LEONIDA_SHADOW_ALIAS_MS` | `0` | The shortest time, in milliseconds, between two copies of the title-memory pages that XMem maps at two addresses (no write guard can watch them) into the slot-133 shadows and title windows. `0` copies them at every submission; a larger value lets a GPU read of them be up to that many milliseconds behind the title's writes. | | `LEONIDA_REFRESH_PER_FRAME` | `0` | Trades correctness for speed. `1`: the slot-133 shadows, title windows and geometry copies are brought up to date only by the first submission after each present, not by every submission; `2`: the console descriptor heaps too. A GPU read of them can then be a frame behind the title's writes (wrong pixels). `0` refreshes all of them at every submission. | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 49743d0c1d..7d331ad644 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3290,15 +3290,16 @@ struct DeviceState { // The slots on [offset, offset + bytes) of a heap copy's mirror, just brought up to date: each that differs from // what its arena slot was made from is written there and fixed up. - // Past LEONIDA_CONSOLE_FIX_US of fixing in one submission (4000 by default, 0: no limit), a changed slot is written - // as a null descriptor and left to retry_console_slots: after the story load the title rewrote up to 3.7 MiB of - // its heap at once and one submission spent 28 s fixing it (speed-8). A shader reads such a slot as empty until - // its turn comes. + // LEONIDA_CONSOLE_FIX_US limits the fixing in one submission (0, the default: no limit). Past it a changed slot is + // written as a null descriptor and left to retry_console_slots: after the story load the title rewrote up to + // 3.7 MiB of its heap at once and one submission spent 28 s fixing it (speed-8). A shader reads such a slot as + // empty until its turn comes, so a limit changes results: at the first world frame lib_cs_01144 read the size it + // divides by from a nulled buffer slot and its loops never ended, which lost the device. void fix_console_slots(ConsoleHeap& heap, std::size_t offset, std::size_t bytes) { static const std::uint64_t budget_us = [] { char text[16] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_FIX_US", text, sizeof(text)); - return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 4000ull; + return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 0ull; }(); const std::size_t end = std::min(offset + bytes, std::size_t(heap.bytes)); if (!heap.resource_heap) { From 6e85823da41528fd8fcc21379b3a9f58a2d44f24 Mon Sep 17 00:00:00 2001 From: cheltyis <67891221+cheltyi@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:05:38 +0300 Subject: [PATCH 13/21] gamedata_reader: preserve empty polymorphic objects --- docs/gamedata.md | 7 ++-- tests/test_gamedata_reader.py | 61 +++++++++++++++++++++++++++++++++++ tools/gamedata_reader.py | 5 ++- 3 files changed, 70 insertions(+), 3 deletions(-) diff --git a/docs/gamedata.md b/docs/gamedata.md index a05fd1ea56..bcaa55f4d3 100644 --- a/docs/gamedata.md +++ b/docs/gamedata.md @@ -1416,7 +1416,8 @@ bounded by the largest field. The generic conversion follows the parser's own co - `x/y/z/w` is a vector tuple. - `content=` is the array body. `short_array`, `float_array` and `float16_array` give number lists; `vector2_array`, `vec3v_array`, `matrix33` and `matrix34` give tuples. -- `type="Class"` is a polymorphic object `{"$type": ...}`, and `type="NULL"` is `None`. +- `type="Class"` is a polymorphic object `{"$type": ...}`, including an empty object with no fields or text. + Explicit scalar/vector/array/reference conventions and nonempty text keep their values; `type="NULL"` is `None`. - `ref=` is `{"$ref": ...}`. - All-`Item` children are a list, or a dict when every one carries `key=`. A repeated tag is a list. A text-only element is its text. Any other attribute is kept as `"@name"`. @@ -1440,11 +1441,13 @@ On the 1.0.2.1 carve of `common.rpf` the run takes about 5 s, with 0 conversion | arrays | 13,449 | | lists | 13,465 | | keyed maps | 526 | -| polymorphic objects | 6,490 (317 `type` classes over 6,903 typed elements) | +| polymorphic objects | 6,663 (317 `type` classes over 6,903 typed elements) | | `NULL` pointers | 278 | | references | 924 | | elements with extra attributes | 5,262 | +The object count includes 173 empty instances across 13 documents (54 types). + The 7 roots missing from the 118 occur only in documents that are not well-formed. Counts only: the JSON that `--out` writes is the game's data and stays local. `tests/test_gamedata_reader.py` checks every convention, both dispatch tables, that streaming equals a whole-tree conversion, and the CLI, on synthetic XML. diff --git a/tests/test_gamedata_reader.py b/tests/test_gamedata_reader.py index 1d8d9e081f..af1717eeb0 100644 --- a/tests/test_gamedata_reader.py +++ b/tests/test_gamedata_reader.py @@ -103,6 +103,42 @@ def test_polymorphic_root_and_list_root(self): self.assertEqual(reader.read(b'')[2], [1, 2]) self.assertEqual(reader.read(b'leaf')[2], "leaf") + def test_empty_typed_objects_keep_class_in_roots_lists_and_maps(self): + cases = ( + (b'', {"$type": "CEmpty"}, 1), + (b' \t\n ', {"$type": "CEmpty"}, 1), + (b'\n', + [{"$type": "CEmpty"}, {"$type": "CEmpty", "@name": "named", "@userFlags": 3}], 2), + (b'', + {"first": {"$type": "CEmpty"}, "second": {"$type": "CEmpty"}}, 2), + ) + for raw, expected, object_count in cases: + with self.subTest(raw=raw): + stream_reader = R.Reader(root_handlers={}, type_handlers={}) + whole_reader = R.Reader(root_handlers={}, type_handlers={}) + self.assertEqual(stream_reader.read(raw)[2], expected) + self.assertEqual(whole_reader.convert(ET.fromstring(raw)), expected) + self.assertEqual(stream_reader.stats, whole_reader.stats) + self.assertEqual(stream_reader.types, {"CEmpty": object_count}) + self.assertEqual(stream_reader.types, whole_reader.types) + self.assertEqual(stream_reader.stats["object"], object_count) + self.assertEqual(stream_reader.stats["text"], 0) + + def test_empty_objects_do_not_change_other_leaf_conventions(self): + raw = (b' leaf ' + b'' + b'') + expected = {"plain": "", "null": None, "text": "leaf", "scalar": 0, "vector": (1.0, 2.0), + "array": [], "ref": {"$ref": "target"}} + stream_reader = R.Reader(root_handlers={}, type_handlers={}) + whole_reader = R.Reader(root_handlers={}, type_handlers={}) + self.assertEqual(stream_reader.read(raw)[2], expected) + self.assertEqual(whole_reader.convert(ET.fromstring(raw)), expected) + self.assertEqual(stream_reader.stats, whole_reader.stats) + self.assertEqual(stream_reader.types, whole_reader.types) + self.assertEqual(stream_reader.stats["object"], 0) + self.assertEqual(stream_reader.stats["text"], 2) + def test_vector_with_extra_attributes_and_non_vector_xyzw(self): reader = R.Reader(root_handlers={}, type_handlers={}) self.assertEqual( @@ -165,6 +201,31 @@ def spy_iterparse(*args, **kwargs): class Dispatch(unittest.TestCase): + def test_empty_type_handler_can_use_generic_class_without_double_counting(self): + def empty(el, reader): + generic = reader.convert(el, use_type_handler=False) + return {**generic, "default": 7} + + raw = b'' + reader = R.Reader(root_handlers={}, type_handlers={"CEmpty": empty}) + self.assertEqual(reader.read(raw)[2], [{"$type": "CEmpty", "@name": "named", "default": 7}]) + self.assertEqual(reader.types, {"CEmpty": 1}) + self.assertEqual(reader.stats["type handler"], 1) + self.assertEqual(reader.stats["object"], 1) + self.assertEqual(reader.stats["extra attributes"], 1) + + calls = [] + + def root(el, reader): + calls.append((el.tag, el.attrib["type"])) + return "root default" + + root_reader = R.Reader(root_handlers={"Root": root}, type_handlers={"CEmpty": empty}) + self.assertEqual(root_reader.read(b'')[2], "root default") + self.assertEqual(calls, [("Root", "CEmpty")]) + self.assertEqual(root_reader.stats["root handler"], 1) + self.assertEqual(root_reader.stats["type handler"], 0) + def test_type_handler(self): calls = [] diff --git a/tools/gamedata_reader.py b/tools/gamedata_reader.py index c9d4ae40fe..0d8dd7e835 100644 --- a/tools/gamedata_reader.py +++ b/tools/gamedata_reader.py @@ -174,8 +174,11 @@ def _convert(self, el, use_type_handler=True): return {"$ref": a["ref"]} kids = list(el) if not kids: + text = (el.text or "").strip() + if t is not None and not text: + return self._typed_object(t, {}) self.stats["text"] += 1 - return (el.text or "").strip() + return text return self._typed_object(t, self.children(kids)) def _typed_object(self, t, value): From 71c86830f58db2b70b35570689a68d60bece8fde Mon Sep 17 00:00:00 2001 From: kirigayakazima <46666711+kirigayakazima@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:08:25 +0800 Subject: [PATCH 14/21] tools/int_hw_probe: write --json atomically and reject trailing-separator paths --- tests/test_int_hw_probe.py | 54 +++++++++++++++++++++++++++++++++++++- tools/int_hw_probe.py | 39 ++++++++++++++++++++++----- 2 files changed, 86 insertions(+), 7 deletions(-) diff --git a/tests/test_int_hw_probe.py b/tests/test_int_hw_probe.py index 89a3b2d073..b59ff5c647 100644 --- a/tests/test_int_hw_probe.py +++ b/tests/test_int_hw_probe.py @@ -148,13 +148,65 @@ def test_json_write_oserror_returns_2_without_traceback(self): jpath = os.path.join(tmp, "out.json") out, err = io.StringIO(), io.StringIO() with unittest.mock.patch.object(probe, "run_translator", return_value={"s_bfe_i32_past31": [0], "s_bfe_u32_past31": [0], "s_bfe_i32_width0": [0]}), \ - unittest.mock.patch("builtins.open", side_effect=OSError("disk full")), \ + unittest.mock.patch.object(probe.json, "dump", side_effect=OSError("disk full")), \ redirect_stdout(out), redirect_stderr(err): rc = probe.main(["--oracle", "translator", "--group", "salu_bfe_past31", "--json", jpath]) self.assertEqual(rc, 2) self.assertIn("ERROR:", err.getvalue()) self.assertIn("disk full", err.getvalue()) + def test_json_preflight_rejects_trailing_separators(self): + with tempfile.TemporaryDirectory() as tmp: + for bad in (os.path.join(tmp, "out.json") + os.sep, os.path.join(tmp, "out.json") + "/", "/"): + with self.subTest(json_path=bad): + err = io.StringIO() + with unittest.mock.patch.object(probe, "run_translator", side_effect=AssertionError("ran translator")), \ + unittest.mock.patch.object(hw_runner, "open_oracle", side_effect=AssertionError("opened oracle")), \ + redirect_stderr(err): + rc = probe.main(["--oracle", "both", "--group", "salu_bfe_past31", "--json", bad]) + self.assertEqual(rc, 2) + self.assertIn("ERROR:", err.getvalue()) + + def test_json_write_failure_preserves_existing_file_and_cleans_staging(self): + fake_tr = {"s_bfe_i32_past31": [0], "s_bfe_u32_past31": [0], "s_bfe_i32_width0": [0]} + with tempfile.TemporaryDirectory() as tmp: + jpath = os.path.join(tmp, "existing.json") + Path(jpath).write_text('{"keep": true}\n', encoding="utf-8", newline="\n") + out, err = io.StringIO(), io.StringIO() + with unittest.mock.patch.object(probe, "run_translator", return_value=fake_tr), \ + unittest.mock.patch.object(probe.json, "dump", side_effect=OSError("disk full")), \ + redirect_stdout(out), redirect_stderr(err): + rc = probe.main(["--oracle", "translator", "--group", "salu_bfe_past31", "--json", jpath]) + self.assertEqual(rc, 2) + self.assertEqual(Path(jpath).read_text(encoding="utf-8"), '{"keep": true}\n') + self.assertEqual([n for n in os.listdir(tmp) if n.startswith(".int-hw-probe-")], []) + + def test_json_publish_uses_replace_retry_and_cleans_on_failure(self): + fake_tr = {"s_bfe_i32_past31": [0], "s_bfe_u32_past31": [0], "s_bfe_i32_width0": [0]} + with tempfile.TemporaryDirectory() as tmp: + jpath = os.path.join(tmp, "existing.json") + Path(jpath).write_text('{"keep": true}\n', encoding="utf-8", newline="\n") + out, err = io.StringIO(), io.StringIO() + with unittest.mock.patch.object(probe, "run_translator", return_value=fake_tr), \ + unittest.mock.patch.object(probe.replace_retry, "replace", side_effect=PermissionError("locked")), \ + redirect_stdout(out), redirect_stderr(err): + rc = probe.main(["--oracle", "translator", "--group", "salu_bfe_past31", "--json", jpath]) + self.assertEqual(rc, 2) + self.assertEqual(Path(jpath).read_text(encoding="utf-8"), '{"keep": true}\n') + self.assertEqual([n for n in os.listdir(tmp) if n.startswith(".int-hw-probe-")], []) + + out2 = io.StringIO() + with unittest.mock.patch.object(probe, "run_translator", return_value=fake_tr), \ + unittest.mock.patch.object(probe.replace_retry, "replace", wraps=probe.replace_retry.replace) as spy_replace, \ + redirect_stdout(out2): + rc2 = probe.main(["--oracle", "translator", "--group", "salu_bfe_past31", "--json", jpath]) + self.assertEqual(rc2, 0) + spy_replace.assert_called_once() + raw = Path(jpath).read_text(encoding="utf-8") + self.assertTrue(raw.endswith("\n")) + self.assertEqual(json.loads(raw)["waves"], [32, 64]) + self.assertEqual([n for n in os.listdir(tmp) if n.startswith(".int-hw-probe-")], []) + # v_bfe_u32 / v_bfe_i32 words measured natively on an AMD Radeon 610M (gfx1036, RDNA2), wave32 and wave64 identical: # `python -I tools/int_hw_probe.py --oracle both --group valu_bfe_past31`. A field that would run past bit 31 stops diff --git a/tools/int_hw_probe.py b/tools/int_hw_probe.py index c76b659781..467fbfb6d6 100644 --- a/tools/int_hw_probe.py +++ b/tools/int_hw_probe.py @@ -57,7 +57,9 @@ sys.path.insert(0, p) import rdna2spirv # noqa: E402 +import replace_retry # noqa: E402 import spirv_mini_interp # noqa: E402 +from file_mode import published_mode # noqa: E402 STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" Date: Wed, 25 Nov 2026 21:10:56 +0800 Subject: [PATCH 15/21] tools/ab_control_flow: handle UTF-8-SIG/CRLF inputs, subprocess encoding and atomic outcomes.tsv --- tests/test_ab_control_flow.py | 90 +++++++++++++++++++++++++++++++++++ tools/ab_control_flow.py | 49 ++++++++++++++----- 2 files changed, 128 insertions(+), 11 deletions(-) diff --git a/tests/test_ab_control_flow.py b/tests/test_ab_control_flow.py index 403d0af1dc..ac12184256 100644 --- a/tests/test_ab_control_flow.py +++ b/tests/test_ab_control_flow.py @@ -1129,5 +1129,95 @@ def side_effect(args, **kwargs): self.assertEqual(content, f"ps_test\t{expected}\n") +class HardeningRegressionTest(unittest.TestCase): + def test_select_candidates_strips_bom_crlf_and_blank_lines(self): + with tempfile.TemporaryDirectory() as tmp: + names = os.path.join(tmp, "names.txt") + with open(names, "wb") as f: + f.write(b"\xef\xbb\xbfps_alpha\r\n\r\n ps_beta \r\n\n") + self.assertEqual( + AB.select_candidates({}, tmp, tmp, names_file=names), + ["ps_alpha", "ps_beta"], + ) + + def test_main_reads_utf8_bom_index_json(self): + import json + + with tempfile.TemporaryDirectory() as tmp: + repo = os.path.join(tmp, "repo") + shaders = os.path.join(tmp, "shaders") + out = os.path.join(tmp, "out") + os.makedirs(os.path.join(repo, "runtime", "build")) + os.makedirs(os.path.join(shaders, "dxbc", "disasm")) + os.makedirs(os.path.join(shaders, "spirv")) + with open(os.path.join(shaders, "spirv", "index.json"), "wb") as f: + f.write(b"\xef\xbb\xbf" + json.dumps({"ps_bom": {"stage": "ps"}}).encode("utf-8")) + with open(os.path.join(shaders, "dxbc", "disasm", "ps_bom.s"), "w", encoding="utf-8", newline="\n") as f: + f.write("\ts_cbranch_scc0 10\n\ts_branch 20\n\ts_endpgm\n") + with open(os.path.join(shaders, "spirv", "ps_bom.spv"), "wb") as f: + f.write(b"stub") + + def side_effect(args, **kwargs): + if "spirv-as" in str(args[0]): + with open(args[-1], "wb") as fh: + fh.write(b"vs") + return SimpleNamespace(returncode=0, stdout="ok") + if "spirv-val" in str(args[0]): + return SimpleNamespace(returncode=0, stdout="ok") + if "rdna2spirv.py" in str(args): + out_dir = args[args.index("--out") + 1] + os.makedirs(out_dir, exist_ok=True) + with open(os.path.join(out_dir, "ps_bom.spvasm"), "w", encoding="utf-8", newline="\n") as fh: + fh.write("%out_mrt0 = OpVariable %po Output\n") + with open(os.path.join(out_dir, "ps_bom.spv"), "wb") as fh: + fh.write(b"spv") + return SimpleNamespace(returncode=0, stdout="1 pass spirv-val\n") + with open(args[3], "wb") as fh: + fh.write(bytes(AB.READBACK_BYTES)) + return SimpleNamespace(returncode=0, stdout="ok") + + with patch("subprocess.run", side_effect=side_effect), contextlib.redirect_stdout(io.StringIO()): + rc = AB.main([repo, shaders, out, "--count", "1", "--harness", "dummy.exe"]) + self.assertEqual(rc, 0) + with open(os.path.join(out, "outcomes.tsv"), encoding="utf-8") as f: + self.assertEqual(f.read(), "ps_bom\tidentical MRT0: non-clear\n") + + def test_write_outcomes_atomic_preserves_existing_on_replace_failure(self): + with tempfile.TemporaryDirectory() as tmp: + target = os.path.join(tmp, "outcomes.tsv") + with open(target, "w", encoding="utf-8", newline="\n") as f: + f.write("prev\tidentical\n") + with patch.object(AB.replace_retry, "replace", side_effect=PermissionError("locked")): + with self.assertRaises(PermissionError): + AB.write_outcomes(tmp, [("new", "DIFFERENT")]) + with open(target, encoding="utf-8") as f: + self.assertEqual(f.read(), "prev\tidentical\n") + self.assertEqual([n for n in os.listdir(tmp) if n.startswith(".outcomes-")], []) + + with patch.object(AB.replace_retry, "replace", wraps=AB.replace_retry.replace) as spy: + out_path = AB.write_outcomes(tmp, [("new", "DIFFERENT")]) + spy.assert_called_once() + with open(out_path, encoding="utf-8") as f: + self.assertEqual(f.read(), "new\tDIFFERENT\n") + + def test_render_targets_passes_utf8_replace_to_subprocess(self): + with tempfile.TemporaryDirectory() as tmp: + dir_a, dir_b, out = os.path.join(tmp, "a"), os.path.join(tmp, "b"), os.path.join(tmp, "out") + for d in (dir_a, dir_b, out): + os.makedirs(d) + seen = [] + + def fake_run(cmd, **kwargs): + seen.append(kwargs) + return SimpleNamespace(returncode=1) + + with patch("subprocess.run", side_effect=fake_run): + AB.render_targets((("old", dir_a), ("new", dir_b)), "ps_x", "harness", "vs", out, 1, 5, [0], [0], False) + self.assertEqual(len(seen), 2) + for kw in seen: + self.assertEqual(kw.get("encoding"), "utf-8") + self.assertEqual(kw.get("errors"), "replace") + + if __name__ == "__main__": unittest.main() diff --git a/tools/ab_control_flow.py b/tools/ab_control_flow.py index ddc67da22b..85b14eea58 100644 --- a/tools/ab_control_flow.py +++ b/tools/ab_control_flow.py @@ -27,6 +27,13 @@ import struct import subprocess import sys +import tempfile + +_HERE = os.path.dirname(os.path.abspath(__file__)) +if _HERE not in sys.path: + sys.path.insert(0, _HERE) +import replace_retry # noqa: E402 +from file_mode import published_mode # noqa: E402 # Left out: anything that writes memory or images, LDS, and the rare instructions the harness has no setup for. # Loads are fine: with empty user data they read zeros from the start of the harness's heap, the same for both. @@ -74,8 +81,8 @@ def select_candidates(index, disasm_dir, spirv_dir, count=150, loops="none", nam if count < 1: # the check below runs after the first append, so 0 or less still picked one shader raise ValueError("count must be at least 1") if names_file: - with open(names_file, encoding="utf-8") as f: - return [name for name in f.read().split("\n") if name] + with open(names_file, encoding="utf-8-sig") as f: + return [name for line in f.read().splitlines() if (name := line.strip())] picked = [] for name in supported_pixel_shaders(index): @@ -120,12 +127,31 @@ def classify_result(translation_valid, dispatch_runs, structured_runs): def write_outcomes(out_dir, outcomes): - """Write (shader name, outcome) pairs to the harness's tab-separated report.""" + """Write (shader name, outcome) pairs to the harness's tab-separated report atomically.""" os.makedirs(out_dir, exist_ok=True) - path = os.path.join(out_dir, "outcomes.tsv") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write("".join(f"{name}\t{outcome}\n" for name, outcome in outcomes)) - return path + dest = os.path.realpath(os.path.join(out_dir, "outcomes.tsv")) + dest_dir = os.path.dirname(dest) or out_dir + fd, tmp = tempfile.mkstemp(dir=dest_dir, prefix=".outcomes-", suffix=".tmp") + try: + try: + f = os.fdopen(fd, "w", encoding="utf-8", newline="\n") + except BaseException: + os.close(fd) + raise + with f: + f.write("".join(f"{name}\t{outcome}\n" for name, outcome in outcomes)) + f.flush() + os.fsync(f.fileno()) + os.chmod(tmp, published_mode(dest)) + replace_retry.replace(tmp, dest) + except BaseException: + try: + os.chmod(tmp, 0o600) + os.unlink(tmp) + except OSError: + pass + raise + return dest def test_vertex_shader(out_dir, runner=None): @@ -216,7 +242,7 @@ def render_targets(forms, name, harness, vs, out, runs, timeout, observed, decla failure = None try: h = subprocess.run([harness, vs, spirv, raw, *args], capture_output=True, text=True, - timeout=timeout) + encoding="utf-8", errors="replace", timeout=timeout) if all_attachments and h.returncode == 3: failure = "timeout" if h.returncode == 0 and os.path.isfile(raw): @@ -261,7 +287,7 @@ def main(argv=None): import json index_path = os.path.join(old, "index.json") try: - with open(index_path, encoding="utf-8") as f: + with open(index_path, encoding="utf-8-sig") as f: index = json.load(f) except (OSError, ValueError, RecursionError) as e: ap.error(f"cannot read {index_path}: {getattr(e, 'strerror', None) or e}") @@ -333,9 +359,10 @@ def note(name, what): tool = os.path.join(a.repo, "tools", "rdna2spirv.py") for name in picked: src = os.path.join(disasm, name + ".s") - r1 = subprocess.run([sys.executable, "-I", tool, src, "--out", new], capture_output=True, text=True) + r1 = subprocess.run([sys.executable, "-I", tool, src, "--out", new], + capture_output=True, text=True, encoding="utf-8", errors="replace") r2 = subprocess.run([sys.executable, "-I", tool, src, "--out", loopdir, "--dispatch-loop"], - capture_output=True, text=True) + capture_output=True, text=True, encoding="utf-8", errors="replace") if "1 pass spirv-val" not in r1.stdout or "1 pass spirv-val" not in r2.stdout: note(name, "a translation is invalid") continue From 93a0f21f490dc892616d78ae45e38e9d79f76c26 Mon Sep 17 00:00:00 2001 From: thiefyzheng Date: Wed, 25 Nov 2026 13:16:50 +0000 Subject: [PATCH 16/21] BUILD-STAGES: report a stage that raises instead of failing silently A stage that raises outright (not through fail()) was swallowed by the run_build_stages exception handlers: the build stopped with exit 1 and an empty stderr, so a permission or copy failure gave no visible cause (board #1608 comment 7163281819). Report the stage name and the exception once per stage on stderr from the series loop, the wait handler and the final drain; fail()'s own diagnostics are unchanged and RuntimeError from its sys.exit is not re-reported. Tested: tests/test_leonida_tui.py UnexpectedStageExceptionTest (both overlap modes, fails without the fix); test_make_game_* and stage suites pass. --- make_game.py | 24 +++++++++++++++++--- tests/test_leonida_tui.py | 47 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 3 deletions(-) diff --git a/make_game.py b/make_game.py index 3eb0899458..b8c90a11f9 100644 --- a/make_game.py +++ b/make_game.py @@ -61,6 +61,7 @@ import tempfile import threading import time +import traceback from concurrent.futures import ThreadPoolExecutor if __name__ == "__main__" and sys.version_info < (3, 12): # before code an older Python can't run @@ -2912,6 +2913,20 @@ def fn_pipelines(): "pipelines": fn_pipelines, } + reported: set[str] = set() + + def report_unexpected(name: str, exc: BaseException) -> None: + """A stage that fails through fail() already printed a diagnostic; one that raises outright did + not. Report the stage and the exception once per stage, so a failure is never silent.""" + if isinstance(exc, RuntimeError) and str(exc).startswith("stage exited with "): + return # fail() called sys.exit; its diagnostic already went out + key = f"{name}: {exc!r}" + if key in reported: + return + reported.add(key) + print(f"\nERROR: stage '{name}' failed with an unexpected exception: {exc!r}", file=sys.stderr) + traceback.print_exc(file=sys.stderr) + if not overlap: order = [s for s in ("shaders", "assets", "runtime", "pipelines") if s in stages] if not order: @@ -2921,7 +2936,8 @@ def fn_pipelines(): try: _invoke_stage(name, builders[name]) progress.complete(name) - except Exception: + except Exception as exc: + report_unexpected(name, exc) sys.exit(1) return @@ -2950,7 +2966,8 @@ def wait(name: str) -> bool: futures[name].result() progress.complete(name) return True - except Exception: + except Exception as exc: + report_unexpected(name, exc) failed = True return False @@ -2968,7 +2985,8 @@ def wait(name: str) -> bool: try: fut.result() progress.complete(name) - except Exception: + except Exception as exc: + report_unexpected(name, exc) failed = True ex.shutdown(wait=True) except KeyboardInterrupt: diff --git a/tests/test_leonida_tui.py b/tests/test_leonida_tui.py index e921e4f89d..72e9c2f323 100644 --- a/tests/test_leonida_tui.py +++ b/tests/test_leonida_tui.py @@ -4,6 +4,7 @@ """ import ctypes import os +import io import sys import tempfile import unittest @@ -443,5 +444,51 @@ def fake_key(timeout_s=0.05): self.assertFalse(cfg.overlap) + +class UnexpectedStageExceptionTest(unittest.TestCase): + """A stage that raises outright (not through fail()) must still print a stage + exception + diagnostic once, in both overlap modes; the failure itself surfaces as before.""" + + def _run(self, overlap): + def boom(*a, **k): + raise PermissionError(13, "Permission denied", "synthetic-output") + + err = io.StringIO() + with tempfile.TemporaryDirectory() as tmp: + game = os.path.join(tmp, "g") + out = os.path.join(tmp, "o") + work = os.path.join(tmp, "w") + os.makedirs(game) + with mock.patch.object(make_game, "shaders", side_effect=boom), \ + mock.patch.object(make_game, "assets"), \ + mock.patch.object(make_game, "runtime"), \ + mock.patch.object(make_game, "pipelines"), \ + mock.patch.object(make_game, "log"), \ + mock.patch.object(make_game, "pipeline_check_exe", return_value="x"), \ + mock.patch.object(make_game.sys, "stderr", err), \ + self.assertRaises(SystemExit) as ctx: + make_game.run_build_stages( + ["shaders", "assets", "runtime", "pipelines"], + game=game, work=work, out=out, v={}, wav=False, jobs=2, + runtime_build=None, emulate=False, keep_emulated=True, fallbacks=(), + overlap=overlap) + return ctx.exception.code, err.getvalue() + + def test_overlap_false_reports_stage_and_exception(self): + code, err = self._run(overlap=False) + self.assertEqual(code, 1) + self.assertIn("shaders", err) + self.assertIn("PermissionError", err) + self.assertEqual(err.count("failed with an unexpected exception"), 1) + + def test_overlap_true_reports_stage_and_exception(self): + code, err = self._run(overlap=True) + self.assertEqual(code, 1) + self.assertIn("shaders", err) + self.assertIn("PermissionError", err) + # wait() and the final drain must not report the same stage twice + self.assertEqual(err.count("failed with an unexpected exception"), 1) + + if __name__ == "__main__": unittest.main() From daf31b820b5b9fe5d7d119836657bff1f8fd1ea0 Mon Sep 17 00:00:00 2001 From: OreoFR <29048345+OreoFR@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:48:26 +0100 Subject: [PATCH 17/21] replay: copies between depth formats that differ go through transfer scratch (RT-DEPTH-FORMAT-COPY-STAGED) A CopyTextureRegion of the depth plane from a D32_SFLOAT_S8_UINT image into a D32_SFLOAT one was replayed as vkCmdCopyImage. Vulkan requires depth/stencil formats to match exactly (VUID-vkCmdCopyImage-srcImage-01548), and the NVIDIA driver (RTX 4070 Laptop, 621.40) wrote past the end of the D32 image: the world-start WRITE_INVALID device loss, with the fault at the first byte after a 2560x1440 D32_SFLOAT image (VK_EXT_device_address_binding_report) and this VUID reported by the validation layer just before the loss. depth_format_pair: two depth formats with the same depth encoding but not the same VkFormat (D32 / D32S8, D16 / D16S8, X8_D24 / D24S8) take the image -> scratch -> image path depth <-> colour and A8 copies already use; the depth aspect has the same texel layout in a buffer on both sides. replay_copy_offset_test: the D32S8 -> D32 and D32 -> D32S8 depth-plane copies are staged (no vkCmdCopyImage, depth aspect, 4 bytes a texel), and D32 -> D32 keeps vkCmdCopyImage. Fails without the change (6 checks). Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 7 +++ runtime/src/vulkan_replay.h | 24 +++++++- runtime/test/replay_copy_offset_test.cpp | 74 +++++++++++++++++++++++- 3 files changed, 103 insertions(+), 2 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index aa7913060a..c2e36319e2 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -484,6 +484,13 @@ What is implemented (all of it testable without the game): `E_INVALIDARG` for such a render target, since no other format can view its image. Without that format, render targets are refused as before; depth-stencil and UAV creation are unsupported for this format. + - A `CopyTextureRegion` of the depth plane between two depth formats with the same depth encoding but not the + same `VkFormat` (`D32_SFLOAT_S8_UINT` and `D32_SFLOAT`, `D16_UNORM_S8_UINT` and `D16_UNORM`, + `D24_UNORM_S8_UINT` and `X8_D24_UNORM_PACK32`) goes image → transfer scratch → image too, depth aspect on both + sides (`vulkan_replay.h`, `depth_format_pair`; `replay_copy_offset_test`). `vkCmdCopyImage` requires + depth/stencil formats to match exactly (`VUID-vkCmdCopyImage-srcImage-01548`), and an NVIDIA driver (RTX 4070 + Laptop, 621.40) handed the `D32_SFLOAT_S8_UINT` → `D32_SFLOAT` pair wrote past the end of the `D32_SFLOAT` + image: the world-start `WRITE_INVALID` device loss, with the fault at the first byte after the image. - reserved resources and `GetResourceTiling` (section 4.2); - query heaps for occlusion, timestamps and pipeline statistics, and `GetTimestampFrequency` on the queue (section 4.6); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index e20a291057..0caf3bbc19 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -548,6 +548,27 @@ inline bool a8_mixed_backing(VkFormat a, VkFormat b) { #endif } +// Two depth formats whose depth aspect has the same encoding but which are not the same VkFormat: D32_SFLOAT and +// D32_SFLOAT_S8_UINT, D16_UNORM and D16_UNORM_S8_UINT, X8_D24_UNORM_PACK32 and D24_UNORM_S8_UINT. D3D12 copies the +// depth plane between them; Vulkan's vkCmdCopyImage requires depth/stencil formats to match exactly +// (VUID-vkCmdCopyImage-srcImage-01548), and an NVIDIA driver handed D32_SFLOAT_S8_UINT -> D32_SFLOAT writes past the +// end of the D32 image (the world-start WRITE_INVALID). The replay stages these through a buffer, where the depth +// aspect has the same texel layout on both sides. +inline bool depth_format_pair(VkFormat a, VkFormat b) { + const auto encoding = [](VkFormat format) -> int { + switch (format) { + case VK_FORMAT_D32_SFLOAT: + case VK_FORMAT_D32_SFLOAT_S8_UINT: return 32; + case VK_FORMAT_X8_D24_UNORM_PACK32: + case VK_FORMAT_D24_UNORM_S8_UINT: return 24; + case VK_FORMAT_D16_UNORM: + case VK_FORMAT_D16_UNORM_S8_UINT: return 16; + default: return 0; + } + }; + return a != b && encoding(a) && encoding(a) == encoding(b); +} + inline bool depth_colour_pair(const ResourceBinding& a, const ResourceBinding& b) { const auto family = [](VkFormat format) -> int { switch (format) { @@ -3627,7 +3648,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } if (result == ReplayResult::success && !p.image_copies.empty() && (p.image_copies[0].srcSubresource.aspectMask != p.image_copies[0].dstSubresource.aspectMask || - a8_mixed_backing(p.source.format, p.binding.format))) { + a8_mixed_backing(p.source.format, p.binding.format) || + depth_format_pair(p.source.format, p.binding.format))) { // Depth <-> colour: vkCmdCopyImage cannot mix aspects, so each region goes image -> scratch -> image, // tightly packed. Depth aspects want 4-byte buffer offsets; 16 covers every texel size here. The two // backings of A8_UNORM take the same route: one byte per texel on both sides, but Vulkan does not diff --git a/runtime/test/replay_copy_offset_test.cpp b/runtime/test/replay_copy_offset_test.cpp index 515befb3cd..6fb26718ed 100644 --- a/runtime/test/replay_copy_offset_test.cpp +++ b/runtime/test/replay_copy_offset_test.cpp @@ -49,8 +49,12 @@ VKAPI_ATTR void VKAPI_CALL rec_copy_i2b(VkCommandBuffer, VkImage, VkImageLayout, for (std::uint32_t i = 0; i < count; ++i) i2b_copies.push_back(regions[i]); } +std::vector image_copies; + VKAPI_ATTR void VKAPI_CALL noop_copy_image(VkCommandBuffer, VkImage, VkImageLayout, VkImage, VkImageLayout, - std::uint32_t, const VkImageCopy*) {} + std::uint32_t count, const VkImageCopy* regions) { + for (std::uint32_t i = 0; i < count; ++i) image_copies.push_back(regions[i]); +} template T handle(std::uintptr_t n) { @@ -138,6 +142,25 @@ int main(int argc, char** argv) { rgb96_img.samples = 1; rgb96_img.rgb96 = true; + // A depth-stencil texture and a depth-only one of the same size, both 32-bit float depth (D32_FLOAT_S8X24 and + // D32_FLOAT in D3D12). + ResourceBinding d32s8_img{}; + d32s8_img.image = handle(6); + d32s8_img.format = VK_FORMAT_D32_SFLOAT_S8_UINT; + d32s8_img.aspects = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + d32s8_img.width = 64; + d32s8_img.height = 32; + d32s8_img.mip_levels = 1; + d32s8_img.array_layers = 1; + d32s8_img.depth = 1; + d32s8_img.samples = 1; + ResourceBinding d32_img = d32s8_img; + d32_img.image = handle(7); + d32_img.format = VK_FORMAT_D32_SFLOAT; + d32_img.aspects = VK_IMAGE_ASPECT_DEPTH_BIT; + ResourceBinding d32_img2 = d32_img; + d32_img2.image = handle(8); + const auto resolve = [&](ResourceId id) -> const ResourceBinding* { switch (id) { case 1: return &src_buf; @@ -145,6 +168,9 @@ int main(int argc, char** argv) { case 3: return &rgba_img; case 4: return &d24_img; case 5: return &rgb96_img; + case 6: return &d32s8_img; + case 7: return &d32_img; + case 8: return &d32_img2; default: return nullptr; } }; @@ -155,6 +181,7 @@ int main(int argc, char** argv) { transfer_writes_ordered = false; b2i_copies.clear(); i2b_copies.clear(); + image_copies.clear(); depth24_jobs.clear(); return replay(list, VK_NULL_HANDLE, resolve, vk); }; @@ -440,6 +467,51 @@ int main(int argc, char** argv) { dst_buf = saved_dst; } + // 7. CopyTextureRegion of the depth plane between two depth formats with the same encoding but not the same + // VkFormat (D32_SFLOAT_S8_UINT and D32_SFLOAT): vkCmdCopyImage requires depth/stencil formats to match exactly + // (VUID-vkCmdCopyImage-srcImage-01548), and an NVIDIA driver handed the D32S8 -> D32 pair wrote past the end of the + // D32 image (the world-start WRITE_INVALID). The copy goes image -> transfer scratch -> image, depth aspect on + // both sides, 4 bytes a texel. The same format on both sides keeps vkCmdCopyImage. + { + VkDeviceSize scratch_bytes = 0; + vk.copy_scratch = [&](VkDeviceSize bytes, VkBuffer& out, VkDeviceSize& base) { + scratch_bytes = bytes; + out = handle(0x9100); + base = 256; + return true; + }; + const auto staged_depth = [&](ResourceId dst, ResourceId src, const char* what) { + const CopyLocation to{dst, false, 0, 0, 0, 0, 0, 0}, from{src, false, 0, 0, 0, 0, 0, 0}; + CommandList list; + expect(list.copy_texture({to, 0, 0, 0, from, false, {}}) && list.close(), what); + expect(run(list) == ReplayResult::success, what); + expect(image_copies.empty(), "a depth copy between different depth formats does not use vkCmdCopyImage"); + expect(i2b_copies.size() == 1 && b2i_copies.size() == 1, "the depth plane is staged through a buffer"); + if (i2b_copies.size() == 1 && b2i_copies.size() == 1) { + const VkBufferImageCopy &read = i2b_copies[0], &write = b2i_copies[0]; + expect(read.imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT && + write.imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT, + "both staged halves name the depth aspect"); + expect(read.imageExtent.width == 64 && read.imageExtent.height == 32 && read.imageExtent.depth == 1 && + write.imageExtent.width == 64 && write.imageExtent.height == 32, + "the staged depth copy covers the whole 64x32 plane"); + expect(read.bufferOffset == 256 && write.bufferOffset == 256, + "the read and the write share one scratch range"); + } + expect(scratch_bytes >= VkDeviceSize(64) * 32 * 4, "the scratch holds 4 bytes a depth texel"); + }; + staged_depth(7, 6, "D32_SFLOAT_S8_UINT depth plane into D32_SFLOAT"); + staged_depth(6, 7, "D32_SFLOAT into the depth plane of D32_SFLOAT_S8_UINT"); + + const CopyLocation to{8, false, 0, 0, 0, 0, 0, 0}, from{7, false, 0, 0, 0, 0, 0, 0}; + CommandList same; + expect(same.copy_texture({to, 0, 0, 0, from, false, {}}) && same.close(), "record D32_SFLOAT copy"); + expect(run(same) == ReplayResult::success, "D32_SFLOAT into D32_SFLOAT replays"); + expect(image_copies.size() == 1 && i2b_copies.empty() && b2i_copies.empty(), + "the same depth format on both sides keeps vkCmdCopyImage"); + vk.copy_scratch = {}; + } + if (failures) return 1; std::printf("replay_copy_offset: CopyResource and CopyTexture apply ResourceBinding::buffer_offset\n"); return 0; From 14f04ce2d26e185b880ab09c93f882adc7d4729d Mon Sep 17 00:00:00 2001 From: ecox982745 <196405083+ecox982745@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:52:29 +1000 Subject: [PATCH 18/21] d3d12: stage title textures when the image cannot take host copies Select the upload path after checking both format features and image usage. Keep required staging available for mapped linear textures and only retry host backing when the image supports it. Exercise both capability failures with synthetic GPU readback. AI-assisted-by: OpenAI Codex (gpt-6.2-astra) --- docs/d3d12_vulkan.md | 11 +++--- runtime/shims/d3d12_vulkan_device.cpp | 28 +++++++-------- runtime/test/d3d12_existing_heap_test.cpp | 43 +++++++++++++++++++++++ 3 files changed, 63 insertions(+), 19 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index aa7913060a..312bfba6f0 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2901,11 +2901,12 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv - Sampled title images can use device-local memory even when Vulkan host image copies require a host-visible memory type. The runtime queries the same image with and without host-transfer usage. When only the latter permits plain device-local backing, it detiles the complete image into a reusable - staging buffer and transfers all its mips and layers together. Linear slot-133 placements retain host - copies. On a device without `VK_EXT_host_image_copy` every colour title image, linear placements too, takes the - staged upload: the refresh before a submission has no other way to fill one, and without it the title's textures - stayed zero (a flat green intro movie). An allocation failure retries the original host-copyable image. - `LEONIDA_TITLE_IMAGE_STAGING=0` + staging buffer and transfers all its mips and layers together. Linear slot-133 placements use host + copies when the image supports them. + If the device, format, or combination of image usages lacks host-transfer support, a CPU-visible, + single-sampled colour title image that needs no format conversion uses the staged upload. This also + fills mapped linear movie planes during refresh. When both placements are available, an allocation + failure on the staged path retries the original host-copyable image. `LEONIDA_TITLE_IMAGE_STAGING=0` restores the original placement policy. With `LEONIDA_MEM_PROBE`, each title image class logs its Vulkan memory type mask, mask without host transfer, and selected type. - `WriteToSubresource`/`ReadFromSubresource` (implemented in `d3d12_vulkan_device.cpp`) complete before they diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 428132a688..620b7a8e7d 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -6190,8 +6190,8 @@ class Resource final // Textures the CPU reads and writes (WriteToSubresource/ReadFromSubresource) copy on the host when they can. // (A D24 texture stored as D32 goes through the staged copy: the host copy would not convert. Nor would it // repack a 96-bit texture's 12-byte texels.) - host_transfer_ = cpu_visible() && samples == 1 && !format.d24_as_float && !format.rgb96 && - device_.host_transfer_format(format.format); + const bool cpu_copyable = cpu_visible() && samples == 1 && !format.d24_as_float && !format.rgb96; + host_transfer_ = cpu_copyable && device_.host_transfer_format(format.format); rgb96_ = format.rgb96; if (host_transfer_) info.usage |= VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; HRESULT support = device_.check_image_support(info); @@ -6240,30 +6240,30 @@ class Resource final shared_zero_ = device_.zero_sampled_image(desc_, format, footprint.size); } std::uint32_t plain_bits = 0; - // A device without host copies has no other way to fill a title image: a refresh before a submission may not - // use a staged copy through the queue (host_copy_now). Its linear movie planes are staged too. - const bool no_host_copy = !device_.copy_memory_to_image && cpu_visible() && samples == 1 && - !format.d24_as_float && !format.rgb96; - if (stage_title && !shared_zero_ && allow_staged_title && origin != TitleImageOrigin::ordinary && - (no_host_copy || (!linear_placement && host_transfer_)) && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT && - device_.image_requirements) { + const bool can_stage = stage_title && allow_staged_title && !shared_zero_ && cpu_copyable && + origin != TitleImageOrigin::ordinary && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT; + // A refresh must queue an upload when this image cannot take host copies, including linear movie planes. + const bool needs_staging = can_stage && !host_transfer_; + if (needs_staging) { + staged_title_ = true; + plain_bits = UINT32_MAX; // the image already lacks HOST_TRANSFER; any compatible memory type will do + } else if (can_stage && !linear_placement && device_.image_requirements) { for (std::uint32_t i = 0; i < device_.memory.memoryTypeCount; ++i) { const auto flags = device_.memory.memoryTypes[i].propertyFlags; if ((flags & (VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) plain_bits |= 1u << i; } - if (no_host_copy) plain_bits = UINT32_MAX; // nothing to compare with: any memory type will do VkMemoryRequirements with{}, without{}; auto staged = info; staged.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; - if (plain_bits && (no_host_copy || (device_.memory_requirements(info, with) && - !(with.memoryTypeBits & plain_bits))) && + if (plain_bits && device_.memory_requirements(info, with) && !(with.memoryTypeBits & plain_bits) && device_.memory_requirements(staged, without) && (without.memoryTypeBits & plain_bits)) { staged_title_ = true; host_transfer_ = false; info.usage = staged.usage; } } + const bool can_retry_host = staged_title_ && !needs_staging; auto retry_host = [&] { if (image_) vk.vkDestroyImage(device_.info.device, image_, nullptr); if (memory_) vk.vkFreeMemory(device_.info.device, memory_, nullptr); @@ -6288,7 +6288,7 @@ class Resource final } return E_OUTOFMEMORY; }; - if (HRESULT hr = create_image(); FAILED(hr)) return staged_title_ ? retry_host() : hr; + if (HRESULT hr = create_image(); FAILED(hr)) return can_retry_host ? retry_host() : hr; VkMemoryRequirements requirements{}; std::uint32_t type = UINT32_MAX; const bool stream = origin == TitleImageOrigin::streamed || origin == TitleImageOrigin::pending_stream; @@ -6325,7 +6325,7 @@ class Resource final // A title image (placed or streamed) takes the title image pool or an allocation of its own, of the memory // types its placement allows; the shared texture blocks below are for the layer's ordinary textures. if (!bind_texture_memory(stream, allowed, requirements, type)) { - if (staged_title_) return retry_host(); + if (can_retry_host) return retry_host(); std::fprintf(stderr, "[rt] d3d12: texture memory unavailable: %llu bytes, alignment %llu, type bits 0x%x (vk " "format %d %ux%u)\n", diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index f1ebbe7203..01a11cf142 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -1859,6 +1859,37 @@ int check_mapped_bc_array(ID3D12Device* device) { return 0; } +// Model a device that supports host image copies, with two per-image exceptions. +PFN_vkGetInstanceProcAddr original_instance_proc; +PFN_vkGetPhysicalDeviceFormatProperties2 original_format_properties; +PFN_vkGetPhysicalDeviceImageFormatProperties2 original_image_properties; + +VKAPI_ATTR void VKAPI_CALL without_r8_host_transfer(VkPhysicalDevice device, VkFormat format, + VkFormatProperties2* properties) { + original_format_properties(device, format, properties); + if (format != VK_FORMAT_R8_UNORM) return; + for (auto* p = static_cast(properties->pNext); p; p = p->pNext) + if (p->sType == VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3) + reinterpret_cast(p)->optimalTilingFeatures &= + ~VK_FORMAT_FEATURE_2_HOST_IMAGE_TRANSFER_BIT_EXT; +} + +VKAPI_ATTR VkResult VKAPI_CALL without_bc1_host_usage(VkPhysicalDevice device, + const VkPhysicalDeviceImageFormatInfo2* info, + VkImageFormatProperties2* properties) { + if (info->format == VK_FORMAT_BC1_RGBA_UNORM_BLOCK && (info->usage & VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT)) + return VK_ERROR_FORMAT_NOT_SUPPORTED; + return original_image_properties(device, info, properties); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL per_format_instance_proc(VkInstance instance, const char* name) { + if (std::strcmp(name, "vkGetPhysicalDeviceFormatProperties2") == 0) + return reinterpret_cast(without_r8_host_transfer); + if (std::strcmp(name, "vkGetPhysicalDeviceImageFormatProperties2") == 0) + return reinterpret_cast(without_bc1_host_usage); + return original_instance_proc(instance, name); +} + void print_cases(const std::vector& cases, const char* who) { for (const Case& c : cases) std::printf("%s: %-44s hr=0x%08lX size=%llu align=%llu type=%d cpu=%d pool=%d flags=0x%x\n", who, c.name, @@ -1903,6 +1934,18 @@ int main() { failures += check_shared_bc_placements(ours.p); failures += check_mapped_plane(ours.p); failures += check_mapped_bc_array(ours.p); + + original_instance_proc = vk.instance_proc; + original_format_properties = + vk.instance_fn("vkGetPhysicalDeviceFormatProperties2"); + original_image_properties = + vk.instance_fn("vkGetPhysicalDeviceImageFormatProperties2"); + auto per_format = info; + per_format.get_instance_proc = per_format_instance_proc; + Ref limited; + if (FAILED(rt::d3d12::create_vulkan_device(per_format, IID_PPV_ARGS(&limited.p)))) return 1; + failures += check_mapped_plane(limited.p); + failures += check_mapped_bc_array(limited.p); } { // Without host image copies a title image is filled through the staged upload, a linear plane too. From e500e994940dce9f2f9edb2ff2a29003bea162eb Mon Sep 17 00:00:00 2001 From: DadaCap <167002618+DadaCap@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:14:30 +0100 Subject: [PATCH 19/21] d3d12: CPU-fillable placed BC images share a zero image without host copies too Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 3 ++- runtime/shims/d3d12_vulkan_device.cpp | 26 +++++++++++++++-------- runtime/test/d3d12_existing_heap_test.cpp | 5 ++++- 3 files changed, 23 insertions(+), 11 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index c2e36319e2..c51efb7999 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2885,7 +2885,8 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv the driver's), as on D3D12. - GPU-writable slot-133 images on a default heap bind memory when replay, presentation or creation of a shader view first needs their Vulkan image. D3D12 placement and logical attachment views can precede that bind. - A CPU-fillable, typed BC texture can initially sample an immutable zero image of the same format, extent, + A CPU-fillable, typed BC texture (filled by host copies or the staged upload) can initially sample + an immutable zero image of the same format, extent, layer count and mip count. A CPU upload or explicit GPU command gives the placement private backing and republishes its existing descriptor keys. The cache holds at most 256 MiB. `LEONIDA_PLACED_IMAGE_DEFER=0` restores eager binding. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index d2681ad6c4..20b0362ca5 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -6229,9 +6229,17 @@ class Resource final const char* value = std::getenv("LEONIDA_PLACED_IMAGE_DEFER"); return !value || std::strcmp(value, "0"); }(); + // A device without host copies has no other way to fill a title image: a refresh before a submission may not + // use a staged copy through the queue (host_copy_now). Its linear movie planes are staged too. + const bool no_host_copy = !device_.copy_memory_to_image && cpu_visible() && samples == 1 && + !format.d24_as_float && !format.rgb96; // Private BC copies start with the exact same zero blocks as the shared image. The host // transition and clear complete before a private view is published, including during command prepare. - if (defer_placed && origin == TitleImageOrigin::placed && host_transfer_ && device_.bindless && + // Without host copies the staged upload fills the private image, and the first shader submission clears what + // it has not filled. + const bool can_fill = host_transfer_ || (no_host_copy && stage_title && allow_staged_title && + device_.image_requirements); + if (defer_placed && origin == TitleImageOrigin::placed && can_fill && device_.bindless && desc_.Flags == D3D12_RESOURCE_FLAG_NONE && desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc_.SampleDesc.Count == 1 && asked_castable.empty() && !format.typeless && leonida::block_format(format.format, format.aspects).block > 1) { @@ -6240,11 +6248,7 @@ class Resource final shared_zero_ = device_.zero_sampled_image(desc_, format, footprint.size); } std::uint32_t plain_bits = 0; - // A device without host copies has no other way to fill a title image: a refresh before a submission may not - // use a staged copy through the queue (host_copy_now). Its linear movie planes are staged too. - const bool no_host_copy = !device_.copy_memory_to_image && cpu_visible() && samples == 1 && - !format.d24_as_float && !format.rgb96; - if (stage_title && !shared_zero_ && allow_staged_title && origin != TitleImageOrigin::ordinary && + if (stage_title && (!shared_zero_ || no_host_copy) && allow_staged_title && origin != TitleImageOrigin::ordinary && (no_host_copy || (!linear_placement && host_transfer_)) && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT && device_.image_requirements) { for (std::uint32_t i = 0; i < device_.memory.memoryTypeCount; ++i) { @@ -6270,6 +6274,7 @@ class Resource final image_ = VK_NULL_HANDLE; memory_ = VK_NULL_HANDLE; staged_title_ = false; + shared_zero_ = VK_NULL_HANDLE; log_once("no room for a staged title image; retrying host-copyable backing, format", int(info.format)); return create_texture(format, asked_castable, origin, false); }; @@ -6495,6 +6500,7 @@ class Resource final } if (shared_zero_) { if (host_transfer_ && !host_initialize()) return false; + if (!host_transfer_) device_.context->note_shader_image(id()); // zeros until something fills it publish_streamed_texture(); } return true; @@ -7214,10 +7220,11 @@ class Resource final std::shared_ptr heap_range_; }; -// One immutable, host-zeroed BC image per exact view shape. It has the right sampled format, extent, +// One immutable, zeroed BC image per exact view shape (zeroed on the host, or by the first shader submission). It has +// the right sampled format, extent, // mip count and zero-block decoding even before the title first supplies data or copies into the placement. VkImage DeviceState::zero_sampled_image(const D3D12_RESOURCE_DESC& d, const Format& format, VkDeviceSize bytes) { - if (!host_transfer_format(format.format)) return VK_NULL_HANDLE; + if (copy_memory_to_image && !host_transfer_format(format.format)) return VK_NULL_HANDLE; const ZeroShape key{d.Format, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels}; std::lock_guard lock(zero_image_mutex); if (auto it = zero_images.find(key); it != zero_images.end()) return it->second ? it->second->image() : VK_NULL_HANDLE; @@ -7226,12 +7233,13 @@ VkImage DeviceState::zero_sampled_image(const D3D12_RESOURCE_DESC& d, const Form if (used >= limit || bytes > limit - used) return VK_NULL_HANDLE; const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0, 1, 1}; auto* zero = new Resource(*this, d, heap, D3D12_HEAP_FLAG_NONE); - if (FAILED(zero->create_texture(format)) || !zero->host_initialized_image() || + if (FAILED(zero->create_texture(format)) || (copy_memory_to_image && !zero->host_initialized_image()) || zero->image_backing_bytes() > limit - used) { zero->Release(); zero_images.emplace(key, nullptr); return VK_NULL_HANDLE; } + if (!zero->host_initialized_image()) context->note_shader_image(zero->id()); // cleared before a shader reads it zero_images.emplace(key, zero); zero_image_bytes.fetch_add(zero->image_backing_bytes(), std::memory_order_relaxed); return zero->image(); diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 3d65fc7409..2c7b25b1cf 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -1236,7 +1236,7 @@ int check_placed_target_backing(ID3D12Device* device) { // Two sampled BC placements have distinct T#s. A CPU write to the first and a GPU copy into // the second must each promote only their destination and keep previously copied descriptors usable. -int check_shared_bc_placements(ID3D12Device* device) { +int check_shared_bc_placements(ID3D12Device* device, bool must_share = false) { const char* who = "shared slot-133 BC images"; if (!rt::d3d12::bindless_set_layout(device)) return 0; constexpr UINT width = 32, height = 32, pitch = width / 4 * 8; @@ -1259,6 +1259,8 @@ int check_shared_bc_placements(ID3D12Device* device) { const auto second = rt::d3d12::bindless_hash_lookup(device, bv); EXPECT(first && second && first != second); const bool shared = !rt::d3d12::vulkan_memory_flags(a.p); + const char* defer = std::getenv("LEONIDA_PLACED_IMAGE_DEFER"); + EXPECT(shared || !must_share || (defer && !std::strcmp(defer, "0"))); EXPECT(bool(rt::d3d12::vulkan_memory_flags(b.p)) == !shared); std::array pattern{}, result{}; for (std::size_t i = 0; i < pattern.size(); ++i) pattern[i] = std::uint8_t(i * 13 + 71); @@ -2036,6 +2038,7 @@ int main(int argc, char** argv) { no_host_copy.host_image_copy = false; Ref staged; if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; + failures += check_shared_bc_placements(staged.p, true); failures += check_mapped_plane(staged.p); failures += check_mapped_bc_array(staged.p); } From 06ba2eb2de6459faf78bf11ef40f22ffec7526bc Mon Sep 17 00:00:00 2001 From: ecox982745 <196405083+ecox982745@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:21:47 +1000 Subject: [PATCH 20/21] d3d12: stage title images when host transfer has no memory type Check the host-transfer memory requirements before selecting the backing for a CPU-fillable title texture. Exercise the mapped linear R8 plane with a driver shim that returns no compatible memory types for the host-transfer image. Reported-by: qhukz13 (PR #1894) AI-assisted-by: OpenAI Codex (gpt-6.2-astra) --- docs/d3d12_vulkan.md | 9 +++-- runtime/shims/d3d12_vulkan_device.cpp | 22 ++++++---- runtime/test/d3d12_existing_heap_test.cpp | 49 +++++++++++++++++++++++ 3 files changed, 69 insertions(+), 11 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 312bfba6f0..4f267752d8 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2903,10 +2903,11 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv When only the latter permits plain device-local backing, it detiles the complete image into a reusable staging buffer and transfers all its mips and layers together. Linear slot-133 placements use host copies when the image supports them. - If the device, format, or combination of image usages lacks host-transfer support, a CPU-visible, - single-sampled colour title image that needs no format conversion uses the staged upload. This also - fills mapped linear movie planes during refresh. When both placements are available, an allocation - failure on the staged path retries the original host-copyable image. `LEONIDA_TITLE_IMAGE_STAGING=0` + A CPU-visible, single-sampled colour title image that needs no format conversion uses the staged upload + if the device, format or image usage lacks host-transfer support, or if the host-transfer image has no + compatible memory type. The latter occurs on GTX 1050 Ti for a mapped linear R8 movie plane. + When both placements are available, an allocation failure on the staged path retries the original + host-copyable image. `LEONIDA_TITLE_IMAGE_STAGING=0` restores the original placement policy. With `LEONIDA_MEM_PROBE`, each title image class logs its Vulkan memory type mask, mask without host transfer, and selected type. - `WriteToSubresource`/`ReadFromSubresource` (implemented in `d3d12_vulkan_device.cpp`) complete before they diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 620b7a8e7d..0d65708595 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -6218,6 +6218,16 @@ class Resource final const char* value = std::getenv("LEONIDA_TITLE_IMAGE_STAGING"); return !value || std::strcmp(value, "0"); }(); + const bool can_stage_title = stage_title && allow_staged_title && cpu_copyable && + origin != TitleImageOrigin::ordinary && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT; + VkMemoryRequirements with_host{}; + const bool have_host_requirements = can_stage_title && host_transfer_ && device_.memory_requirements(info, with_host); + // Pascal accepts HOST_TRANSFER for a linear R8 plane but can give that image no bindable memory type. + if (have_host_requirements && !with_host.memoryTypeBits) { + info.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; + host_transfer_ = false; + if (HRESULT hr = device_.check_image_support(info); FAILED(hr)) return hr; + } // Keep placed movie planes with a known linear CPU layout on the host-copy path, where there is one. // Map on a staged placement still returns the title's pages and participates in the refresh. std::uint32_t xg_layout = 0; @@ -6235,13 +6245,11 @@ class Resource final desc_.Flags == D3D12_RESOURCE_FLAG_NONE && desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc_.SampleDesc.Count == 1 && asked_castable.empty() && !format.typeless && leonida::block_format(format.format, format.aspects).block > 1) { - VkMemoryRequirements footprint{}; - if (device_.memory_requirements(info, footprint)) - shared_zero_ = device_.zero_sampled_image(desc_, format, footprint.size); + if (have_host_requirements || device_.memory_requirements(info, with_host)) + shared_zero_ = device_.zero_sampled_image(desc_, format, with_host.size); } std::uint32_t plain_bits = 0; - const bool can_stage = stage_title && allow_staged_title && !shared_zero_ && cpu_copyable && - origin != TitleImageOrigin::ordinary && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT; + const bool can_stage = can_stage_title && !shared_zero_; // A refresh must queue an upload when this image cannot take host copies, including linear movie planes. const bool needs_staging = can_stage && !host_transfer_; if (needs_staging) { @@ -6253,10 +6261,10 @@ class Resource final if ((flags & (VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) plain_bits |= 1u << i; } - VkMemoryRequirements with{}, without{}; + VkMemoryRequirements without{}; auto staged = info; staged.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; - if (plain_bits && device_.memory_requirements(info, with) && !(with.memoryTypeBits & plain_bits) && + if (plain_bits && have_host_requirements && !(with_host.memoryTypeBits & plain_bits) && device_.memory_requirements(staged, without) && (without.memoryTypeBits & plain_bits)) { staged_title_ = true; host_transfer_ = false; diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 01a11cf142..c300da5a87 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -1890,6 +1890,48 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL per_format_instance_proc(VkInstance ins return original_instance_proc(instance, name); } +// Pascal can create the mapped R8 movie plane with HOST_TRANSFER yet offer no memory for it. +// Use the bound-image requirements API for both the probe and the eventual allocation. +PFN_vkGetDeviceProcAddr original_device_proc; +std::atomic host_plane{}; + +VKAPI_ATTR VkResult VKAPI_CALL track_plane(VkDevice device, const VkImageCreateInfo* info, + const VkAllocationCallbacks* allocator, VkImage* image) { + auto create = reinterpret_cast(original_device_proc(device, "vkCreateImage")); + const VkResult result = create(device, info, allocator, image); + if (result == VK_SUCCESS && info->format == VK_FORMAT_R8_UNORM && + info->extent.width == 256 && info->extent.height == 8 && (info->usage & VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT)) + host_plane = *image; + return result; +} + +VKAPI_ATTR void VKAPI_CALL untrack_plane(VkDevice device, VkImage image, const VkAllocationCallbacks* allocator) { + VkImage expected = image; + host_plane.compare_exchange_strong(expected, VK_NULL_HANDLE); + reinterpret_cast(original_device_proc(device, "vkDestroyImage"))(device, image, allocator); +} + +VKAPI_ATTR void VKAPI_CALL plane_requirements(VkDevice device, VkImage image, VkMemoryRequirements* requirements) { + auto get = reinterpret_cast( + original_device_proc(device, "vkGetImageMemoryRequirements")); + get(device, image, requirements); + if (image == host_plane) requirements->memoryTypeBits = 0; +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL plane_device_proc(VkDevice device, const char* name) { + if (!std::strcmp(name, "vkGetDeviceImageMemoryRequirements") || + !std::strcmp(name, "vkGetDeviceImageMemoryRequirementsKHR")) return nullptr; + if (!std::strcmp(name, "vkCreateImage")) return reinterpret_cast(track_plane); + if (!std::strcmp(name, "vkDestroyImage")) return reinterpret_cast(untrack_plane); + if (!std::strcmp(name, "vkGetImageMemoryRequirements")) return reinterpret_cast(plane_requirements); + return original_device_proc(device, name); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL plane_instance_proc(VkInstance instance, const char* name) { + if (!std::strcmp(name, "vkGetDeviceProcAddr")) return reinterpret_cast(plane_device_proc); + return original_instance_proc(instance, name); +} + void print_cases(const std::vector& cases, const char* who) { for (const Case& c : cases) std::printf("%s: %-44s hr=0x%08lX size=%llu align=%llu type=%d cpu=%d pool=%d flags=0x%x\n", who, c.name, @@ -1946,6 +1988,13 @@ int main() { if (FAILED(rt::d3d12::create_vulkan_device(per_format, IID_PPV_ARGS(&limited.p)))) return 1; failures += check_mapped_plane(limited.p); failures += check_mapped_bc_array(limited.p); + + original_device_proc = vk.device_proc; + auto no_plane_memory = info; + no_plane_memory.get_instance_proc = plane_instance_proc; + Ref restricted; + if (FAILED(rt::d3d12::create_vulkan_device(no_plane_memory, IID_PPV_ARGS(&restricted.p)))) return 1; + failures += check_mapped_plane(restricted.p); } { // Without host image copies a title image is filled through the staged upload, a linear plane too. From 2d258c8cd4f9dda5c14be980884a97c7c40c7b03 Mon Sep 17 00:00:00 2001 From: ecox982745 <196405083+ecox982745@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:16:59 +1000 Subject: [PATCH 21/21] d3d12: log the title staging fallback once per Vulkan format Record which title image formats have no bindable host-transfer memory type. Document the three formats observed on the GTX 1050 Ti by qhukz13. Suggested-by: qhukz13 (PR #1894) AI-assisted-by: OpenAI Codex (gpt-6.2-astra) --- docs/d3d12_vulkan.md | 4 +++- runtime/shims/d3d12_vulkan_device.cpp | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 4f267752d8..e4b3de9745 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2905,7 +2905,9 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv copies when the image supports them. A CPU-visible, single-sampled colour title image that needs no format conversion uses the staged upload if the device, format or image usage lacks host-transfer support, or if the host-transfer image has no - compatible memory type. The latter occurs on GTX 1050 Ti for a mapped linear R8 movie plane. + compatible memory type. The runtime logs that last case once per Vulkan format. A GTX 1050 Ti on + NVIDIA 582.66 reported it for R8_UNORM, R8G8B8A8_UNORM and BC1_RGBA_UNORM_BLOCK. + [GTX 1050 Ti test results](https://github.com/ubiquitarianism/leonida/pull/1894#issuecomment-7174515492) When both placements are available, an allocation failure on the staged path retries the original host-copyable image. `LEONIDA_TITLE_IMAGE_STAGING=0` restores the original placement policy. With `LEONIDA_MEM_PROBE`, each title image class logs its diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0d65708595..62927f3bf9 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -6222,11 +6222,12 @@ class Resource final origin != TitleImageOrigin::ordinary && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT; VkMemoryRequirements with_host{}; const bool have_host_requirements = can_stage_title && host_transfer_ && device_.memory_requirements(info, with_host); - // Pascal accepts HOST_TRANSFER for a linear R8 plane but can give that image no bindable memory type. + // A driver can accept HOST_TRANSFER for the image yet give it no bindable memory type. if (have_host_requirements && !with_host.memoryTypeBits) { info.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; host_transfer_ = false; if (HRESULT hr = device_.check_image_support(info); FAILED(hr)) return hr; + log_once("title image has no host-transfer memory type, using staging for Vulkan format", int(info.format)); } // Keep placed movie planes with a known linear CPU layout on the host-copy path, where there is one. // Map on a staged placement still returns the title's pages and participates in the refresh.