diff --git a/README.md b/README.md index b1733bbe08..0860ff63f3 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,10 @@ Original author's Git Mirror: https://git.notrexed.dev/notrexed/Leonida **Early. Nothing is playable yet.** On `main`, the game boots from your own copy on native Windows and on Linux through Proton: it shows the launch movie, the first-run pages and the landing prompt, which respond to a pad or the keyboard pad, then runs the story load to its end and enters the world phase. A first world frame has not been -verified yet on any test machine. [First-run UI on Windows](docs/first_run_ui.md) has the build and launch steps; +verified yet on any test machine. On native Windows a scripted pad alone (`LEONIDA_INPUT_SCRIPT`, no keyboard or +controller) gets through every first-run page, including the legal-terms page whose Confirm waits for both boxes, to +the loading screen of the story load ([the route](docs/first_run_ui.md#through-the-first-run-pages-with-the-scripted-pad)). +[First-run UI on Windows](docs/first_run_ui.md) has the build and launch steps; [the Linux/Proton report](docs/linux_proton.md) has the timings and where it stops. | What | Status | diff --git a/docs/README.md b/docs/README.md index 1e4aaa2e48..8db9cc0801 100644 --- a/docs/README.md +++ b/docs/README.md @@ -67,7 +67,7 @@ method, scope and caveats. No game data is included. |---|---| | [d3d12_vulkan.md](d3d12_vulkan.md) | Xbox D3D12 to Vulkan plan and status; device proxy, queues, command lists, barriers, copies. | | [mobile.md](mobile.md) | arm64/mobile path: the x86-64 → arm64 static-recompiler groundwork (`tools/x64_recomp.py`), the `.pdata` coverage census (`tools/recomp_census.py`), and what still blocks iOS. | -| [first_run_ui.md](first_run_ui.md) | Build the Windows integration and display the offline first-run controller prompts. | +| [first_run_ui.md](first_run_ui.md) | Build the Windows integration and display the offline first-run controller prompts; the scripted-pad route through the first-run pages to the story load. | | [boot.md](boot.md) | The first real boot: the `gta6rt --trace`/`--trace-d3d12` runbook, the startup + D3D12 trace summary (`tools/boot_trace.py`), the triage order and the Q1–Q22 checklist. | | [retail_boot_chain.md](retail_boot_chain.md) | How far `gta6rt --run` gets with the retail executable: the stops in order and what clears each, the physical-page export shapes, device slots 26, 48 and 73, and the device slots the executable calls, counted from the file (`tools/d3d12_device_calls.py`). | | [retail_boot_intel_host.md](retail_boot_intel_host.md) | The retail boot on an Intel host with 16 GB: which stops of the two boot pages hold there with #7111, the commit-limit stop at the 6.1 GiB physical-page request that #7556 clears, the frame loop to the 900 s timeout with stub pipelines, and what the layer refuses at that depth (the console mesh-shader subobject among it). | diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 91c4fd3334..6076f436d5 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -96,7 +96,7 @@ enough for the bundled middleware's `d3d12_xs` calls, not for the game. The laye out)`, `n` = 1..4 records of 0x14c bytes: a u32 tag, then the payload at +4) patches a copy of that stream and creates the PSO through the same path. Tags 0 (`D3D12_DEPTH_STENCIL_DESC`, on DEPTH_STENCIL or DEPTH_STENCIL1), 1 (`D3D12_RASTERIZER_DESC`), 2 (`D3D12_BLEND_DESC`) and 3 (sample mask) are the TomBox layout (GPL-3.0, - `create_derived_pso_x`), checked against the title's record writes in the retail build (RVA 0x2479f40): tag 1 is the + `create_derived_pso_x`), checked against the title's record writes in the retail build: tag 1 is the rasterizer (0x2c bytes, always record 0 when present), tag 0 the DEPTH_STENCIL (0x34), tag 2 the BLEND (0x148). Tag 3 (sample mask, from TomBox) is served although that function does not write it. Tag 5 (0x16 bytes: 16 zero bytes, then the StencilReadMask and StencilWriteMask bytes at the DEPTH_STENCIL offsets 0x10/0x11, then zeros) overlays only those two bytes of the base's @@ -4269,8 +4269,12 @@ to be recovered from call sites (or the NDA GDK headers, if a developer has acce | Mesh shader tier | Public `D3D12_MESH_SHADER_TIER` | `VK_EXT_mesh_shader`; the 9,282 translated mesh shaders make this a hard requirement for any content that uses them. | | Wave MMA | Public `D3D12_WAVE_MMA_TIER` | Not used: no shader sets `WAVE_MMA` in SFI0 and none contains `v_mfma`/`v_wmma` (all 26,503, `tools/feature_scan.py`). Answer the tier query truthfully; no cooperative-matrix mapping is needed. | | Enhanced barriers | Public Xbox Series `D3D12_BARRIER_GROUP` | `VK_KHR_synchronization2`; implement directly. | +| List slot 146: texture barrier with no resource | The retail title records `D3D12_BARRIER_TYPE_TEXTURE` barriers whose `pResource` is null in its `Barrier(NumBarrierGroups, pBarrierGroups)` calls; on the console such a barrier is a global memory and execution barrier | `d3d12_xs_device.cpp` turns each into a `D3D12_GLOBAL_BARRIER` with the same `SyncBefore`/`SyncAfter`/`AccessBefore`/`AccessAfter` (layouts, subresource range and flags dropped) before it calls GCL7 `Barrier` (PC slot 80). A texture group with both kinds is split into runs, in order, in storage that lives for the call; a call with nothing to convert goes through with the title's own pointer. Without this the PC list goes into its error state, `Close` fails and `ExecuteCommandLists` drops the submission. A group array the proxy cannot read safely (null with a nonzero count, a group type it does not know, more than 1,024 groups or 65,536 barriers in one group) is refused whole, nothing recorded, and logged once per reason. **Confirmed by the mock tests only** (`xs_proxy_mock_test`), not by a retail run. | +| List slot 52: clear of an RTV made with no resource | The title creates some render-target views with `CreateRenderTargetView(nullptr, ...)` and clears them every frame; on the console that clear does nothing | The device proxy marks the real handle when device slot 20 gets no resource; a view made there with a resource removes the mark, and `CopyDescriptors`/`CopyDescriptorsSimple` of RTVs move it with the descriptors. Releasing an RTV heap drops the marks in its real CPU range, so a heap made later at the same address starts unmarked. List slot 52 skips the clear of a marked view (logged the first time) and the list stays valid. The mark is the proxy's own because the real descriptor cannot tell: the Vulkan layer writes the same empty record for a view it could not make, and a PC runtime's handles are opaque. Any other view, valid or not, still reaches `ClearRenderTargetView` (PC slot 48); RTV records the title copies with its own `memcpy` are not followed. **Confirmed by the mock tests only** (`xs_proxy_mock_test`), not by a retail run. | | XDXR batched/streaming BVH | `XboxBvhBuilder.dll` exports | See 4.8. | +The null-resource barrier and null-view clear behaviour were first reported by luizwidmer/palmetto. + ### 4.10 Debug markers and private data Games and middleware call these every frame (PIX events), so they must be cheap and never fail. Implemented diff --git a/docs/design.md b/docs/design.md index dcbbd4d63f..eee5be2cc4 100644 --- a/docs/design.md +++ b/docs/design.md @@ -442,7 +442,7 @@ How the generated SPIR-V expects the runtime to work: | Wave-uniform branches | VCC and EXEC are wave-wide registers, but one invocation holds only its own lane's bit. `s_cbranch_vccz/vccnz/execz/execnz` therefore reduce the condition across the subgroup (`OpGroupNonUniformAny`), so the whole wave takes the branch together, as on hardware. Before this, each lane decided alone. A lane could skip scalar instructions that the hardware wave executes (its SGPRs went stale for later code), and cross-lane ops or barriers inside the block saw a split wave. `v_cmp`/`v_cmp_class`/64-bit compares now write 0 for inactive lanes (hardware VOPC behaviour), so the reduction sees the true mask. GPU-checked with `runtime/test/shaders/ps_uniform_branch.asm`: lanes whose own VCC bit is 0 run the block's scalar add when their wave has any set bit. `s_cbranch_scc0/1` stay per lane; SCC is uniform as long as the SGPRs feeding it are. | | Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. Counted over all 2,689 CS listings of 1.0.2.1 by the SGPRs each reads before writing (operand roles from `shader_meta._split_operands`, over the code `translate()` keeps; in wave64 code a lane mask printed as one SGPR covers the pair; an earlier check gave 2,281 exact): 2,540 read nothing past the user SGPRs and enabled TGIDs (2,193 up to the last of them, 342 fewer, 5 none), and the other 149 overshoot only through loop-carried registers in the straight-line check: every extra read follows a branch, and the register is written later in program order. Followed through the CFG (written on every path before the read), 22 still overshoot; each extra register is written on some other path (only loop-carried ones in 15), so these are values undefined on some path, not a missing input. Read raw, 268 overshoot: the other 119 are listings with embedded data words, decoded as instructions. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. With TG_SIZE_EN (none of the 2,689; 91 compute programs of the pipeline library, [shader_library.md](shader_library.md)) the next SGPR is the thread-group word, which the prologue writes: the number of waves in the group in bits [5:0] and this wave's index in it in bits [11:6], the wave index again in bits [24:20] and bit 31 set in the group's first wave (measured on gfx1036 through `tools/hw_oracle`, #6446: wave32 x 128 threads gives `80000004 00100044 00200084 003000c4`; one library program reads [24:20]; not measured on gfx1013) (Mesa `ac_nir_lower_intrinsics_to_args.c`, GFX6-10: `load_num_subgroups` and `load_subgroup_id` read those fields, and a wave64 compute shader's local invocation index is `mbcnt(~0, tg_size & 0xfc0)`; the library programs read it as `s_and_b32 sN, sTG, 0xfc0`, most of them then `v_mbcnt_lo_u32_b32`). Thread i is in wave i / W, as for `s_get_waveid_in_workgroup`. CPU-checked by `tests/semantic/test_cs_tg_size.py`, including the gfx1036 words. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | | Scalar copies through VCC | SGPRs 106 and 107 can hold two data words, including a buffer descriptor's count and format. A 64-bit move through VCC preserves both when its reads within the block use them as data. Predicate users and live-out VCC constrain this inference. A wide scalar load into a tuple ending in VCC writes both physical words. The synthetic descriptor fixture checks numeric copies, a round trip, and a subsequent tuple load on wave32 and emulated wave64. | -| Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. `clamp` and `op_sel`/`op_sel_hi` are translated and checked against the same `gfx1036` hardware table: `clamp` saturates `v_dot4_i32_i8` to signed 32-bit `[-2^31, 2^31-1]` (both overflowing sets), and `op_sel`/`op_sel_hi` pick the 16-bit half of S0/S1 for byte pairs 0..1 and 2..3 (e.g. `op_sel` 2 / `op_sel_hi` 5 exchanges the 16-bit halves of S1, matching all 5 measured sets — the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)); non-default S2 half selection stays refused. `neg_lo`/`neg_hi`, which `llvm-mc` accepts on `v_dot4_i32_i8` only, are not ignored (`neg_lo` flips bit 15 and `neg_hi` bit 31 of S0 or S1, and on S2 `neg_hi` clears bit 31 before `neg_lo` flips it; 5 sets under 8 forms, 45 words): any set bit stays Unsupported, while an all-zero field is the plain instruction. Counts: the 29 FSPX programs use the pair 27,271 times (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458), all in 13 programs; none of the game's own 26,503 shaders has either encoding (0 of the 12,791 words `llvm-mc` cannot decode there with gfx1013). The translator recovers the measured unclamped form from a gap in the listing and restores the stored high-half selector when LLVM normalizes an inline integer on S1. | +| Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. `clamp` and `op_sel`/`op_sel_hi` are translated and checked against the same `gfx1036` hardware table: `clamp` saturates `v_dot4_i32_i8` to signed 32-bit `[-2^31, 2^31-1]` (both overflowing sets), and `op_sel`/`op_sel_hi` pick the 16-bit half of S0/S1 for byte pairs 0..1 and 2..3 (e.g. `op_sel` 2 / `op_sel_hi` 5 exchanges the 16-bit halves of S1, matching all 5 measured sets — the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)); non-default S2 half selection stays refused. How each `op_sel`/`op_sel_hi` form that can reach the translator is confirmed: (1) `op_sel` 2 / `op_sel_hi` 5 without `clamp` or `neg`, which `llvm-mc` rejects: measured on `gfx1036` (the 5 sets above); `shader_disasm.py` prints it with its real encoding (`tests/semantic/test_fspx_dot4_op_sel_disasm.py`) and `skipped_form` recovers it from a gap in a listing made without that pass. (2) `op_sel` 0 / `op_sel_hi` 5 with an inline integer S1 and no `clamp` or `neg`, which `llvm-mc` decodes but prints with the default `op_sel_hi` 7: `restore_dot4_inline_sel` takes the stored field back, in a clean listing (`check_printed_encodings`) and in both re-anchoring paths; `op_sel_hi[1]` clear makes byte pairs 2..3 read S1's low half, the selection measured in (1), but the word itself was not run on hardware; confirmed by a count over the corpus (29 FidelityFX DLL programs, 1.0.2.1, LLVM 21.1.8: 22 translate without it, 24 with it, all 24 pass `spirv-val`; Code-embedded data row) and pinned by `tests/semantic/test_reanchor_dot4_inline_sel.py`. (3) Every other form `llvm-mc` decodes but prints with the default fields (for example `op_sel_hi` 5 with a VGPR S1, or `op_sel` 1 / `op_sel_hi` 6) is not measured and is refused as a dropped field; `tests/semantic/test_dot4_printed_op_sel.py` checks forms (2) and (3) with hand-built words. A general rule that took the stored fields of any such word (from luizwidmer/palmetto) was not taken for that reason. `neg_lo`/`neg_hi`, which `llvm-mc` accepts on `v_dot4_i32_i8` only, are not ignored (`neg_lo` flips bit 15 and `neg_hi` bit 31 of S0 or S1, and on S2 `neg_hi` clears bit 31 before `neg_lo` flips it; 5 sets under 8 forms, 45 words): any set bit stays Unsupported, while an all-zero field is the plain instruction. Counts: the 29 FSPX programs use the pair 27,271 times (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458), all in 13 programs; none of the game's own 26,503 shaders has either encoding (0 of the 12,791 words `llvm-mc` cannot decode there with gfx1013). The measured unclamped `op_sel` 2 / `op_sel_hi` 5 form is also recovered from the bytes on a gap in a listing that `shader_disasm.py` did not print it into (`skipped_form`, #984). | | Workgroup barriers | `s_barrier` (cs/ms) is one `OpControlBarrier` (workgroup scope, workgroup memory). On RDNA every `s_barrier` counts against the same workgroup barrier and a wave that has ended no longer counts, while Vulkan requires a barrier to be reached by every invocation in uniform control flow. Under `--wave64-emulate` the round loop keeps a single barrier at the top level, so this holds. **Native wave32 compute shaders run in barrier rounds** when an `s_barrier` sits anywhere but a top-level block of the structured tree (one every invocation runs): under a guard, in a loop, or in the dispatch loop (`needs_barrier_rounds`, `bar_scheduler`). That is the emulated loop without its cross-lane part: `s_barrier` ends a segment, each invocation runs its blocks until its next `s_barrier` or the end, then the whole workgroup meets at one `OpControlBarrier` (the same workgroup/acquire-release/workgroup-memory semantics) at the end of the round. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3) ends the loop. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3, or a borrowed LDS word with a large LDS: "Barrier-round count in LDS (SHADER-579)") ends the loop. Cross-lane operations stay subgroup operations, as in the dispatch loop, since a wave's lanes run the same segment. A barrier in a top-level block keeps the single `OpControlBarrier` in place. In the 1.0.2.1 corpus 43 of the 55 wave32 cs shaders with `s_barrier` have one nested (SHADER-91's count), so those 43 now run in rounds. Why: an Intel GPU does not survive the nested form. `cs_barrier_divergent.asm` (two barrier sites in different branches), `cs_barrier_early_end.asm` (the other waves end without a barrier) and `cs_barrier_loop.asm` (a barrier in a loop whose trip count differs per wave) each lose the device (`vkQueueWaitIdle` → `VK_ERROR_DEVICE_LOST`) on an Intel Arrow Lake Xe-LPG iGPU (Windows 32.0.101.8132), and `cs_barrier_divergent` hangs or writes nothing on a UHD 770 (101.6129, #634). With barrier rounds all three pass there and on an RTX 5070 Ti Laptop (617.42). NVIDIA passed them before too (RTX 4070 Ti on 610.88 and 621.24, RTX 5090 on Linux 595.99, RTX 5070 Ti). **Still not proven on the native wave64 path** (wave64 cs and every ms, run natively only on AMD's 64-wide subgroups): there the barrier stays where `s_barrier` is, inside a selection or loop construct in every ms and most wave64 cs shaders of the corpus. Branches are scalar, so whole waves take the same path, and RDNA's own barrier counts the way the shader expects. | | Barrier-round count in LDS (SHADER-579) | Barrier rounds (see "Workgroup barriers") count the invocations not done in `%x_buf`, three `Workgroup` dwords (#930). On a full 32 KiB LDS that made 32,780 B, 12 bytes over the 32,768 B `maxComputeSharedMemorySize` of the AMD Windows (RX 9070 XT) and Intel (UHD 770) drivers, so the runtime refused those pipelines (2 native wave32 cs in towade's 1.0.2.1 corpus, [finding](https://github.com/ItsNotRexed/Leonida/pull/1882#issuecomment-7084298032)). Rule (`bar_counts_in_lds`): when the shader uses its LDS and the LDS array plus 12 bytes is over 16,384 B (the Vulkan minimum limit, so in practice an array of 16, 32 or 64 KiB), there is no `%x_buf`. The count borrows LDS word 0 at the end of each round (`bar_scheduler_tail`): after the round's barrier every invocation is done or waits at `s_barrier`, so no shader code runs; invocation 0 saves the word in a Function variable and clears it, barrier, every invocation not done adds 1 atomically, barrier, all read the count, barrier, invocation 0 stores the saved word back, barrier. The shader sees its LDS bit for bit as before, and the four extra barriers sit where the whole workgroup already waits, so `s_barrier`'s semantics are unchanged; the cost is four more `OpControlBarrier`s per round in those shaders only. Below the threshold `%x_buf` stays (12 bytes fit every device) with one barrier per round; a shader that never touches its LDS also keeps it (no array to borrow from, 12 B in all). A 32 KiB LDS is now exactly 32,768 B and a 64 KiB one 65,536 B (before: 65,548 B, refused or shrunk to its allocation). Not chosen: putting the count in LDS the shader never touches (unprovable with dynamic addresses), or deciding per device (the translator runs offline). Pinned by `tests/semantic/test_cs_barrier_counts_lds.py` (Workgroup bytes from the emitted SPIR-V and `lds_bytes` for 32 KiB, 64 KiB and small LDS, under a 32 KiB `--max-shared-memory`; ring shifts across 10 barriers that read word 0 and an early-ending wave in the workgroup interpreter, whose LDS starts as 0xDEADBEEF, in both wave orders). Confirmed by those CPU tests only; GPU runs on the 32 KiB devices are pending. | | LDS | A `Workgroup` uint array sized from LDS_SIZE, rounded up to a power of two that also covers every constant offset (15 of 486 shaders index past LDS_SIZE). Covers `ds_read/write_b32..b128`, `read2/write2` (+`st64`), `u16`/`i16`/`u8`/`i8` reads (also `ds_read_u16_d16`/`_d16_hi` and, since SHADER-85, `ds_read_u8_d16`/`_d16_hi` and `ds_read_i8_d16`/`_d16_hi`: the byte is zero- or sign-extended 8→16 into one half of the destination VGPR and the other half is kept, per the RDNA2 ISA DS opcode descriptions (opcodes 162–165) and as for the u16 d16 reads; GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race; a 16-bit read or write at byte 3 of a dword also reads or writes byte 0 of the next dword, as llc-15 `-mcpu=gfx1030 -mattr=+unaligned-access-mode` emits one `ds_read_u16`/`ds_write_b16 ... offset:3` for an align-1 halfword; until 2026-11-22 the reads extracted 16 bits at bit 24, undefined in SPIR-V, and the writes kept only byte 3; `tests/semantic/test_lds_u16_cross_dword.py`), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. `ds_permute_b32`, its forward (scatter) form, has no Vulkan equivalent: each source lane that is on in EXEC publishes `((vAddr + offset) >> 2) mod 32` and each destination lane scans the 32 sources of its half and keeps the last one that targets it (a shuffle of target and data per source lane; under `--wave64-emulate` two buffer rounds and a Function variable instead). Per the ISA pseudocode (`tmp[0..63] = 0`; `next if !EXEC[i]` on the source; `VGPR[VDST][i] = tmp[i]` only `if EXEC[i]`): a destination lane nobody targets gets 0, an off source sends nothing, an off destination keeps its VDST, and the half rule above applies as for `ds_bpermute_b32`. When several sources target one lane the ISA leaves the winner unpredictable ("the value from one of the writers"; its pseudocode says the highest-numbered); the translator takes the highest, and nothing may depend on it. Confirmed by the GPU tests `cs_w32_permute.asm` and, per half of a wave64, `cs_w64x_permute.asm` (SHADER-90: rotation, offset, unwritten lane = 0, off destination keeps its value, off source does not win), `cs_w32_partial_permute.asm` (a 20-thread wave32: a launched lane whose source lane was never launched gets 0, and a send to a missing lane is lost; the same words from a raw 20-thread `hw_oracle` kernel on `gfx1036`) and `tests/semantic/test_ds_permute.py`. **Hardware-verified on RDNA2 (`gfx1036`, AMD Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM via `tools/hw_oracle`, wave32 and wave64, SHADER-133)** with `tools/ds_permute_probe.py` (9/9 cases exact in both wave sizes): unaddressed active lanes get 0, off destinations keep VDST, off sources send nothing, 2-/4-/32-way collisions deterministically take the highest-numbered active lane in the 32-lane half (matching the translator), `vAddr + offset` carries from the low 2 bits before `>> 2` mod 32, wave64 runs as two independent 32-lane halves (`+32` wraps within each half), and missing lanes of a partial wave (20 threads in wave32, 40 in wave64) send nothing. A source lane that is off in EXEC reads 0 and an off destination lane keeps its value (RDNA ISA §10.4.4), in wave32 as in wave64. In wave64 the permute also runs as two wave32s: each half reads lanes of its own half. Until 2026-11-21 lanes 32–63 of a 64-wide subgroup read the low half and inactive sources kept their value (`cs_w64x_bpermute`, AMD Radeon 880M); the wave32 path shuffled the raw value until the same day (`cs_bpermute32`: wave32, EXEC without lanes 8–15, so lane 6 reads 0; GPU-checked on RTX 5070 and Radeon 880M). A source lane that doesn't exist, in the missing lanes of a partial wave, also reads 0: the shuffle result is kept only where a ballot of the running invocations has the source lane, since SPIR-V leaves a shuffle from an invocation that isn't running undefined. Before this, RADV returned stale register values that changed between runs (`cs_w64x_partial`, a 40-thread group, native wave64 on AMD RX 6700 XT, RADV Mesa 26.3.1). Writes and atomics run only in active lanes. Indices wrap at the array size, where hardware would return 0 for out-of-range reads. `s_barrier` = `OpControlBarrier` Workgroup/Workgroup, AcquireRelease + WorkgroupMemory. | @@ -488,7 +488,7 @@ How the generated SPIR-V expects the runtime to work: | `s_bfe_u32` / `s_bfe_i32` past bit 31 | offset = S1[4:0], width = S1[22:16] (7 bits; S1 bits 23 to 31 are ignored). When offset + width > 32 the field stops at bit 31: width = min(width, 32 - offset), and `s_bfe_i32` sign-extends from the top bit that exists. Example: `s_bfe_i32 s4, 0xd2f90159, 0x7f001c` gives `0xfffffffd` (4-bit field `0xd`), not `0xd`. SCC = D ≠ 0. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`), and **on RDNA2** (AMD Radeon 680M, `gfx1035`: `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137; and RDNA2 `gfx1036`, Windows 11, driver 26.10.1, `tools/hw_oracle` HIP launcher: `tools/salu_diff.py --oracle translator,hw --bfe-any --ops s_bfe_u32,s_bfe_i32 --programs 2000` with seeds 1, 2 and 3, 6,000 of 6,000 programs pass on both sides, plus seed 4 over every opcode with `--bfe-any`, 2,000 of 2,000, and `int_hw_probe.py`'s `salu_bfe_past31` cases in wave32 and wave64); the translator (`bfe_width`) already did this. `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137); the translator (`bfe_width`) already did this. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, and on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`); the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. **RDNA2 is not measured**; the ISA pseudocode does not say. | | 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair normally carries 64-bit data. In wave64, `s_flbit_i32_b64` can also gather both halves of a lane mask or EXEC before scanning it. The other operations require scalar data. `test_library_compute_forms.py` checks an empty mask and set bits in either half on native and emulated waves; `tests/semantic/test_lane_mask_bitreplicate_flbit.py` runs EXEC and VCC masks on every lane of a wave64 (the 1.0.2.1 pipeline library reads EXEC this way). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. Also **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). | | `v_bfe_u32` / `v_bfe_i32` past bit 31 | offset = S1[4:0] and width = S2[4:0]: the bits above are ignored, so an offset of 36 reads as 4 and a width of 32 as 0 (a width of 0 gives 0). When offset + width > 32 the field stops at bit 31, as for `s_bfe`: width = min(width, 32 - offset), and `v_bfe_i32` sign-extends from bit 31. Example: `v_bfe_i32` of `0xd2f90159` with offset 28 and width 16 gives `0xfffffffd` (4-bit field `0xd`), not `0xd`, and `0x80000000` with offset 31 and width 4 gives `0xffffffff`. The translator (`bfe_width` for VGPR or SGPR offset and width, the same cut folded at translation time for constants) already did this. Source: **measured on RDNA2**, AMD Radeon 610M (`gfx1036`, Windows 11, AMD driver 32.0.11016.14003), wave32 and wave64 identical, 16 words over VGPR, inline-constant and literal operands: `tools/int_hw_probe.py --oracle both --group valu_bfe_past31`, 4/4 cases match the translator. The words are pinned on the CPU by `tests/test_int_hw_probe.py` (`ValuBfeMeasuredOnRdna2`). | -| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. The source must carry scalar data. Bit replication can also write EXEC, or VCC in wave64. Each lane takes source bit `lane // 2`. `test_library_compute_forms.py` checks both halves of VCC and SCC on native and emulated waves; `tests/semantic/test_lane_mask_bitreplicate_flbit.py` checks VCC, which the 1.0.2.1 pipeline library writes from a constant, on every lane of a wave64. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** | +| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. Bit replication can also write EXEC, or VCC in wave64 (in wave32 VCC's high word is data, so it stays `Unsupported`). Each lane takes source bit `lane // 2`. `test_library_compute_forms.py` checks both halves of VCC and SCC on native and emulated waves; `tests/semantic/test_lane_mask_bitreplicate_flbit.py` checks VCC, which the 1.0.2.1 pipeline library writes from a constant, on every lane of a wave64. A 32-bit lane-mask source (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`) of `s_bitreplicate_b64_b32` into a scalar (non-EXEC/VCC) destination reads that half of the wave's mask as data (`Gen.wave_mask`, as `s_ff1_i32_b64` reads one) and replicates it as any scalar (#998, for 6 pipeline-library programs of 1.0.2.1). Confirmed only by the CPU interpreter on every lane of a wave64 (`test_lane_mask_bitreplicate_flbit.py`: EXEC halves and a compare's VCC halves, synthetic lines) and by the ISA pseudocode above; not measured on hardware. Any other lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`), and a lane-mask source with an EXEC/VCC destination, raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** | | 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \ \| D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. `s_nand/nor/xnor_b64` compute `~(S0 op S1)` on both paths (a lane's mask value is 0 or ~0, so the NOT is per lane); until 2026-11-22 they were rejected as unsupported. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 9 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`); **Hardware-verified** on the same part through `tools/hw_oracle` for the plain-data path: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0: SCC = ((D.lo ≠ 0) or (D.hi ≠ 0)). The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo | The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. \| | Constant lane masks (`Gen.mask_src` immediates) | A constant read as a lane mask is one bit per lane: lane L takes bit L. The 64-bit forms (`s_and/or/andn2_saveexec_b64`, `s_andn2_wrexec_b64`, `s_mov_b64`/`s_not_b64` into EXEC or VCC, `s_and/or/xor/andn2/orn2_b64` and `s_cselect_b64` on the lane-mask path) read the 64-bit value, an inline constant sign-extended (`-16` = lanes 4-63) and a literal with a zero high word, as `src64_data` reads 64-bit constants; the b32 forms (`s_*_saveexec_b32`, `s_andn2_wrexec_b32`) read the 32-bit value at bit L mod 32. 0 and -1 still give no lane and every lane, with no per-lane code. `s_bcnt0/1_i32_b64` and `s_ff0/1_i32_b64` of a constant read the constant's 64 bits via `src64_data` (scalar data: inline negative constants sign-extend to 64 bits, so `s_ff0_i32_b64 s0, -1` gives −1 rather than 32, and 32-bit literals zero-extend; CPU-checked in `tests/semantic/test_scalar_bitcmp.py`, **not yet GPU-verified**). `s_bcnt0/1_i32_b64` of a constant counts the constant's 64 bits (scalar data, like `s_ff0/1_i32_b64`). **Before this fix every lane took bit 0 of the constant**: `s_and_saveexec_b32 s7, 0xff00` with all 32 lanes on left none on, `5` left all 32 on, and `s_bcnt1_i32_b64 s0, 0xff00ff` gave 32. llvm-mc rejects a constant as the mask operand of `v_cndmask_b32_e64` / `v_add_co_ci_u32_e64` and decodes one as "Invalid immediate", so those VALU callers never see a constant. **A constant held in an SGPR** (`s_mov_b32 s20, 0x3ffffc00`) is read the same way when it reaches a mask consumer: `mask_src` takes bit L of an SGPR that `holds_lane_mask` doesn't flag (a pair in a wave64 64-bit context: the high SGPR for lanes 32-63). In a wave32 or wave64 program a 32-bit bitwise SALU op (`s_not_b32`, `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC (`exec_lo`/`vcc_lo` in wave32; `exec_lo`/`exec_hi` and mask-holding `vcc_lo`/`vcc_hi` in wave64, including after `s_mov_b64 vcc, 0/-1`) skips scalar constant folding, reads its operands through `Gen._mask_b32_src` / `mask_src` (collecting the opposite half through `wave_mask` if a wave64 op mixes `lo` and `hi` halves), preserves the untouched half of EXEC/VCC in wave64 (`exec_half_write` / `put_mask`), and votes SCC over the wave (wave32) or that 32-lane half (wave64, `scc_any_half`), matching `s_not_b32` and the binary ops on lane-mask SGPRs too; into a plain SGPR with a constant it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. In a wave32 program a 32-bit bitwise SOP2 (`s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC reads both operands through `mask_src` (`Gen.sop2_b32_srcs`); into a plain SGPR it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. A real mask is unchanged: it holds 0 or ~0 per lane, and bit L of that is the same 0 or 1. Until 2026-11-22 these took the value whole, so `s_and_saveexec_b32 s6, s20` with that constant, or `s_and_b32 exec_lo, exec_lo, 0xff00`, left every lane on (found writing `cs_w32_saveexec_ext`, #1771; CPU-checked by `tests/semantic/test_mask_src_sgpr_const.py`, and `tools/cf_diff.py` / `tools/salu_diff.py` still pass). `s_not_b32` on lane masks, `s_and/or/xor_b32` with two immediates into `vcc_lo`, and wave64 half-mask bitwise ops (destination half preservation, `exec_hi`, and `scc_any_half`) are CPU-checked in `tests/semantic/test_salu_b32_lane_masks.py` (wave32, wave64, and `--wave64-emulate`, validated with `spirv-val`) and GPU-checked on gfx1036, RTX 5080 (`--wave64-emulate`), and RX 9060 XT (RADV). Not covered here: a b32 op on one half of a wave64 mask, masks read as data (#293), and a literal with bit 31 set in a 64-bit position (zero- vs sign-extension not measured). GPU-checked with `runtime/test/shaders/cs_w32_mask_imm.asm` and `cs_w64_mask_imm.asm` on an NVIDIA GeForce RTX 5080 (driver 616.92; wave64 with `LEONIDA_W64_EMULATE=1`) and an AMD Radeon RDNA2 iGPU (driver 26.10.1, native 64-wide subgroup): both failed before on both GPUs. Run across every lane in `tests/semantic/test_value_semantics.py` (`LaneMaskConstants`). **A computed value written to EXEC** (`s_lshl_b32`, `s_add_u32`, `s_bfm_b32`, and every other SALU result that reaches `exec_lo`/`exec_hi` through `Gen.dst`) takes each lane's bit too: until 2026-11-24 the generic path tested the value for non-zero, so `s_lshl_b32 exec_lo, 1, s5` ran all 32 lanes of that half (SHADER-1264; `Gen.exec_bit`). The words are the GPU's, recorded in `runtime/test/shaders/cs_w32_exec_computed.asm` and `cs_w64_exec_computed.asm` (RTX 5070), and `tests/semantic/test_exec_computed.py` replays them through the CPU interpreter. A value that already holds this lane's bit of a mask (0 or ~0) gives the same answer. | | Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination, and `s_cmov_b64`, stay `Unsupported`, #210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). | diff --git a/docs/embedded_shaders.md b/docs/embedded_shaders.md index 6ccdbaf417..04569f7115 100644 --- a/docs/embedded_shaders.md +++ b/docs/embedded_shaders.md @@ -294,8 +294,8 @@ The last line also gets `--wave64-emulate` and the fallback flags of the build, emulated modules made at the default cap, `RadixAlloc` is refused (`declares 37084 bytes of workgroup memory`, `0x80004001`) after 28 creations. -**Packed pixel shaders.** The executable also holds two native pixel shaders in SGD5 records. Their header file -offsets are `0x688ecf6` and `0x688f17f`. Both stored lengths include the 12-byte header. Raw deflate yields a +**Packed pixel shaders.** The executable also holds two native pixel shaders in SGD5 records (their file offsets +are measured locally and not kept here). Both stored lengths include the 12-byte header. Raw deflate yields a complete DXBC of 1,324 or 1,052 bytes. Their FSSM SHA-256 keys are `cae1e27820adde6a6cb35e308290164ad8cf7107f0fe147d50a2053d7ceeb4b8` and `879cb2e326c5e5333935a0b2b1dd9c3c2adc1b03e546d1f84f993d912b4f66b0`. The first is diff --git a/docs/first_run_ui.md b/docs/first_run_ui.md index 66b147ddbb..fcfe4114b8 100644 --- a/docs/first_run_ui.md +++ b/docs/first_run_ui.md @@ -32,6 +32,19 @@ Run the title offline. The Winsock shim permits loopback and the WinHTTP shim re The profile selects Vulkan, a 2 GiB graphics address arena, on-demand pipelines, console root-argument layout, frame pacing and the keyboard gamepad in its focused mode (`LEONIDA_KEYBOARD_PAD=1`: keys count only while the title window has focus, so typing into another program presses nothing on a consent page; scripted presses still run). GPU completion labels (`LEONIDA_GPU_LABELS`) are not part of it: the list values land the title's list writes, and two writers of one address could rewind a counter. Explicit environment settings take precedence; a variable that is set but empty does not count. Speech synthesis through the host's own runtime is not part of the profile: `LEONIDA_LOCAL_SPEECH=1` turns it on, and without it the silent voice answers. The switches are listed in [`runtime/README.md`](../runtime/README.md). The package directory is the working directory. Guest output goes under `first-run-ui/overlay` beside the runtime, and sparse physical-memory backing uses `first-run-ui/xmem` on that volume. Use `--overlay DIR` or the absolute directory in `LEONIDA_XMEM_BACKING_DIR` to choose other writable locations. +## Through the first-run pages with the scripted pad + +Measured on 25 November 2026 on native Windows 11 with `scripts/windows-boot/boot.ps1`, an AMD Radeon RX 6800 (driver 32.0.21030.2001) and the shaders of an existing work folder, using no keyboard or controller, only `LEONIDA_INPUT_SCRIPT` (`-InputScript`). After the landing prompt takes A, the title shows these pages in order. None of them reaches the network: the WinHTTP shim refuses outbound requests. + +1. **Navigation experience** (first-run setup): A on the focused option moves on. +2. **Brightness**: A moves on. +3. **Legal notices**: a list of entries. A on an entry opens it instead of moving on. A repeating `a`, `down`, `down` cycle (one cycle every 10 s) got through. +4. **Legal terms and policies**: two check boxes (privacy policy, terms of service) and a Confirm button. Confirm stays greyed out and ignores A until both boxes are ticked. Focus starts on the first box. `down` stops at Confirm, so a script that only presses `a` and `down` gets stuck there with one box unticked. The page looks stuck but is waiting for the box. The steps that worked are `up` to the unticked box, `a` to tick it, `down` to Confirm, then `a`. While a box is focused, the right stick scrolls the text beside it (`rsdown`). The run that ticked the privacy box had scrolled to the end first; whether the box needs that is not measured. + +Confirm shows one black frame and then a dark loading screen with a spinner. The spinner was still turning when the 400-second run ended, about 100 s after Confirm. The frame rate dropped to about 5 presents a second, the session state left its landing value, and there were no device faults. (The game and session states in a `boot.ps1` RESULT now need `LEONIDA_GAME_STATE_RVA` and `LEONIDA_SESSION_STATE_RVA`, measured locally: the script no longer has them built in and reports `?` without them; [scripts/windows-boot/README.md](../scripts/windows-boot/README.md).) + +Timings move by 10 to 20 s between runs on the same machine, because the pipeline cache warms up and the landing prompt arrives earlier. A fixed timeline can therefore press A on the wrong item. A later block that goes back with `up` and retries the legal-terms page makes the script more robust. The run above used the cycle up to about 230 s, then `up,up`, fifteen `rsdown`, `a`, `down,down`, `a`, and from 290 s `up,a,down,a`. The second block is the one that confirmed. + ## Contributions The frame-loop stack comes from [#321](https://github.com/ubiquitarianism/leonida/pull/321). The archive and shader catalog, shader translation, depth and texture support, presentation window and rectangle-list changes retain their upstream commits. Native and derived pipeline support incorporates the work of enx, TomBox, LooperSalty and KkelebekK. Four patches of the published [graphics runtime patches](https://github.com/Sigtryggur-Mani-Gudmundsson/graphics-runtime-patches/tree/d9a0bc1b070d8a36c81b182bc67edd7d24b41bf2) (GPL-3.0, author smg, committed as "Codex") are in this integration almost as published, about 390 lines: `graphics-root-layout` (the switch between the two packings of graphics root arguments, `runtime/shims/d3d12_com.h`), `descriptor-table-refresh` (the title's descriptors pulled into a bound table, and the table scan in the submitting device, `runtime/shims/d3d12_xs_device.cpp` and `runtime/src/vulkan_backend.h`), `descriptor-write-through` (descriptors the layer writes also stored at the title's address, `runtime/shims/d3d12_xs_device.cpp` and `.h`) and `sampler-table-refresh` (title-backed sampler tables, `runtime/shims/d3d12_vulkan_device.cpp`), with their tests in `runtime/test/d3d12_title_va_test.cpp` and `runtime/test/d3d12_m2_textured_test.cpp`. Each region names its patch in a comment. diff --git a/docs/fspx.md b/docs/fspx.md index a959423e40..fad6b166be 100644 --- a/docs/fspx.md +++ b/docs/fspx.md @@ -136,6 +136,15 @@ program whose kind 0 is too short for word 4 keeps the code heuristic. SGPRs (`s[0:1]`, `s4`..`s15`), `M0`, `VCC`, `EXEC` (including inactive lanes across 64 threads) and `SCC` (both 0 and 1) unchanged, and execution resumes cleanly at `+36` bytes. So they are hardware no-ops on RDNA2. - `tools/fspx_unpack.py` disassembles from the end of the prologue. + - **A 24-byte variant**: some programs of the pipeline library in `shaders.rpf` (`tools/shader_library.py`) carry + only the first two of those words, at words 0 and 3, and their code starts at word 6 (`s_inst_prefetch` in all of + them). `code_range` takes that form only when both words are literal-bearing VOP3 opcode-0x180 words of the shape + `tools/fspx_prologue_probe.py` checks (second dword `& 0xFFFE0100 == 0x03FE0100`); a program whose words 0, 3 and + 6 are all prologue words keeps the 36-byte form. Counted on the 1.0.2.1 library with an opcode-only check (#583): + 50 of 2,684 programs; read from word 0 they never decode (the prologue words are invalid encodings and the rest + desyncs), and with the 24-byte start all 50 disassemble with 0 invalid words and 49 translate and pass + `spirv-val` (the other stops at `s_sethalt`). `tests/test_fspx_unpack.py` (`test_short_prologue`) covers the form + and the stricter check. - **Target.** The programs use `v_dot4_i32_i8` (1,458 times) and `v_dot4c_i32_i8` (25,813 times), which fits the provider's name (`FSR4_Int8`). `llvm-mc` (LLVM 23.1.5) decodes them for `gfx1011`, `gfx1012`, `gfx1030`, `gfx1031`, `gfx1033`, `gfx1034` and `gfx1036`, but not for `gfx1010`, `gfx1013` (the target `shader_disasm.py` uses for the @@ -148,11 +157,23 @@ program whose kind 0 is too short for word 4 keeps the code heuristic. - Measured on RDNA2 hardware (gfx1036, through `tools/hw_oracle`, the instruction given as two raw words): with `op_sel` 2 and `op_sel_hi` 5 the result is the dot product with the two 16-bit halves of the second source exchanged, in all 5 operand sets (4 of them give another word under the plain rule). So `op_sel` selects halves - here as it does for the packed 16-bit ops. On a gap in LLVM’s listing, the translator decodes this exact - unclamped, unnegated form from the original bytes, including its source registers and literal. Other - undecodable words retain the reachable-code check. LLVM can also print the default high-half selector for - an inline integer second source. If that selector is the only changed bit, the translator preserves the - stored low-half replication. The hardware measurements are in `tests/semantic/test_alu_dot4_i8.py`. + here as it does for the packed 16-bit ops. The words are in `tests/semantic/test_alu_dot4_i8.py`. + - `tools/shader_disasm.py` (so `fspx_unpack.py --disasm` and `make_game.py`) prints such a word as + `v_dot4_i32_i8 vD, a, b, c op_sel:[0,1,0] op_sel_hi:[1,0,1]` with its real encoding. A dword pair that llvm-mc + rejected, with exactly opcode 0x16, `op_sel` 2, `op_sel_hi` 5, no `clamp` and no `neg`, is decoded with the two + fields at their defaults and then given the fields and the encoding back, so the translator reads it and its + encoding check against the blob passes. Any other `op_sel`/`op_sel_hi` value, `clamp` or `neg` is still + undecodable (only this one was measured). A pair llvm-mc accepted, such as a literal followed by an instruction, + is never touched. `tests/semantic/test_fspx_dot4_op_sel_disasm.py` checks it with llvm-mc (the 5 measured + operand sets, and the forms that stay refused); the 89 words of the real programs are not re-run here, because + that needs the package's DLL. + When a listing lacks that pass, the translator decodes the same exact form from the original bytes on a gap + in the listing (`rdna2spirv.skipped_form`); other undecodable words keep the reachable-code check. LLVM can + also print the default high-half selector for an inline integer second source. If that selector is the only + changed bit, the translator preserves the stored low-half replication (`rdna2spirv.restore_dot4_inline_sel`). + Any other `v_dot4_i32_i8` that llvm-mc decodes but prints with different `op_sel`/`op_sel_hi` fields (for + example `op_sel_hi` 5 with a VGPR second source) is not measured and stays refused as a dropped field + (docs/design.md, "Signed-byte dot products"). ## Kind 7: records @@ -234,7 +255,7 @@ with a blob holding the dword 0, so the DLL creates no compute scratch buffer; w Not done here: using kind 0 at run time beyond what the translated module already carries (its thread-group size and `RSRC2`). -**Slot 57 (`DeserializeGraphicsPipelineStateX`, graphics FSPX).** At `game_scarlett_master.exe+0x2477578`, the retail +**Slot 57 (`DeserializeGraphicsPipelineStateX`, graphics FSPX).** At one call site (measured locally), the retail title calls device slot 57 (`+0x1c8`) with `IID_ID3D12PipelineState` (`{765a30f3-f624-4c6f-a828-ace948622445}`) and a 104-byte description (`+0x00..+0x60`) populated from the zlib-compressed pipeline library in `shaders.rpf` ([shader_library.md](shader_library.md): 25,471 graphics records + 2,693 compute records): diff --git a/docs/movies.md b/docs/movies.md index 252bef7581..02d23c18b8 100644 --- a/docs/movies.md +++ b/docs/movies.md @@ -323,8 +323,8 @@ The loader-side runs behind these numbers are recorded in [`runtime/test/bink_de 1-, 2-, and 4-track samples; later frames were not swept and may return 7,680 or 0 bytes). Which language or mix role the game assigns to track IDs `0, 1, 2, 3` at run time remains unknown. - **Startup playback.** In two boots the title opened the archive twice about 1.2 s after entering the loader. - The separately loaded `Bink2Scarlett.dll` opens metadata at title RVA `0x442ebe6`; playback retains the handle - at `0x442f056` and registers mapped frame buffers at `0x442f9b8`. The frame wrapper at `0x2ef0e0` has a CPU + The separately loaded `Bink2Scarlett.dll` opens the metadata from the title; playback retains the handle + and registers mapped frame buffers. The title's frame wrapper has a CPU multi-worker decode and wait path and a synchronous fallback. Three rotating sets of linear R8 planes (one 3840×2160 and two 1920×1080 per set) reach the slot-133 texture uploader. `VS_Bink` / `PS_BinkNoAlpha` bind the three plane descriptors at table offsets 0x20, 0x40 and 0x60 and draw to an RGBA8 intermediate. The UI diff --git a/docs/shader_library.md b/docs/shader_library.md index 41cea06857..140fe9a71f 100644 --- a/docs/shader_library.md +++ b/docs/shader_library.md @@ -152,8 +152,11 @@ python -I tools/rdna2spirv.py /library/disasm --out /library/spirv * It writes `fspx/.code` and `fspx/.json`, the layout `fspx_unpack.py` writes and `rdna2spirv.py` reads (`native_blob`, `cs_dispatch_state`). A compute program also gets `fspx/.state`, its record's state - blob (FSPX kind 0) as it is, whose SHA-256 is the index's `fspx_state_sha256`; every compute program has exactly one - (2,684 programs, 2,693 records). It also writes `index.json` with each program's stage, and + blob (FSPX kind 0) as it is, whose SHA-256 is the index's `fspx_state_sha256`; in the 1.0.2.1 `shaders.rpf` library, + every compute program has one distinct state-blob index across `library.json`'s `compute` table (2,684 programs, + 2,693 records). A program that records use with different state blobs is written once per distinct state, the + first under its name and each further one as `_state_`, so each pair of keys has an entry + (the library measured above has no such program). It also writes `index.json` with each program's stage, and `library.json` with the header and both pipeline tables, stage to program name. Programs are named `lib__`. * `--disasm` writes `disasm/.s` for the code after the prologue, as `fspx_unpack.py --disasm` does. @@ -162,6 +165,8 @@ python -I tools/rdna2spirv.py /library/disasm --out /library/spirv interface. * `--save` writes the reassembled library. A saved file is also accepted as input. * `--stages` limits the output to some stages. +* `--compute-hashes FILE` instead writes only the compute programs whose code has one of the SHA-256 digests listed + in `FILE` (`fspx_code_sha256`), with every state they are used with. A digest no compute program has is an error. The output is game data and must stay in your work folder. `tests/test_shader_library.py` builds libraries and archives by hand and covers the header, both tables, the size checks, the search in an archive and the digest diff --git a/runtime/README.md b/runtime/README.md index 3fa94e81a6..6d11a59f73 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -348,7 +348,10 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_SHADOW_FULL_WALK` | unset | *Diagnostic.* `1` queries every page of the title-memory shadows at every refresh, as before unchanged generations were skipped. | | `LEONIDA_STRICT_REPLAY` | unset | *Diagnostic.* `1` makes a draw or dispatch with an unresolvable resource fail its command list (`src/vulkan_replay.h`); by default it is dropped and logged. | | `LEONIDA_VOLUME_MIPS` | on | The XG layout of a 3D texture with mips or a block format is computed (`shims/xg_xs_layout.h`). `0` refuses it. | -| `LEONIDA_TITLE_WATCHDOG` | unset (armed) | The title's own hang watchdog stays armed by default, as on the console: if the game's main loop does not report for 30 seconds, the title ends itself. `0` makes `gta6rt --run` keep it from firing while the game thread waits for the driver, for example on the first boot after a driver update (`src/main.cpp`), and only in the build the watchdog was measured in. | +| `LEONIDA_TITLE_WATCHDOG` | unset (armed) | The title's own hang watchdog stays armed by default, as on the console: if the game's main loop does not report for 30 seconds, the title ends itself. `0` makes `gta6rt --run` keep it from firing while the game thread waits for the driver, for example on the first boot after a driver update (`src/main.cpp`). **Since RT-BOOT-COMBINED `0` also needs `LEONIDA_TITLE_WATCHDOG_KICK`**: the watchdog's addresses are no longer built in. With `0` and no `LEONIDA_TITLE_WATCHDOG_KICK`, the loader says once that the watchdog stays armed. | +| `LEONIDA_TITLE_WATCHDOG_KICK` | unset | `,` (hex, measured locally and not kept in the repository): where the watchdog's trap instruction is and the byte the game's main loop sets. Used only with `LEONIDA_TITLE_WATCHDOG=0`, and only when the watchdog's trap instruction is at the first RVA; set without `LEONIDA_TITLE_WATCHDOG=0`, the watchdog stays armed and the loader says so once. | +| `LEONIDA_POOL_DIAG_AT` | unset | *Diagnostic.* `+0x` of the title's transient-pool assert, as the trace prints it (measured locally): the trace dumps the pool's resource list when that int3 is hit (`shims/startup_trace.h`). | +| `LEONIDA_PEEK` | unset | *Diagnostic.* `[:n],,...` (hex): a thread prints the 8-byte values at these RVAs of the title's image (`:n` = n consecutive values) every `LEONIDA_PEEK_SECONDS` (`src/main.cpp`). The RVAs are measured locally and not kept in the repository. `scripts/windows-boot/boot.ps1` no longer sets the game-state and session-state RVAs by default: it sets `LEONIDA_PEEK` only from `LEONIDA_GAME_STATE_RVA` and `LEONIDA_SESSION_STATE_RVA`, and without them its RESULT states read `?` ([scripts/windows-boot/README.md](../scripts/windows-boot/README.md)). | | `LEONIDA_PEEK_SECONDS` | `10` | *Diagnostic.* The period of the `LEONIDA_PEEK` thread (`src/main.cpp`), which prints 8-byte values of the title's image. | | `LEONIDA_INPUT_SCRIPT` | unset | Timed pad presses, `button@seconds` separated by commas (`a@70,a@85,start@120`), each held 300 ms; the clock starts with the shim. Works with and without SDL3: with SDL3 it drives the keyboard pad (`LEONIDA_KEYBOARD_PAD=always`), without SDL3 one scripted pad that is the only device. Controllers and the keyboard pad still need SDL3. Format and buttons in [docs/gameinput.md](../docs/gameinput.md#environment-variables). | | `LEONIDA_INPUT_LOG` | on | The GameInput shim logs every press in `LEONIDA_INPUT_SCRIPT`'s form (`name@seconds`), so a session played by hand can be replayed. `0` turns the lines off. | diff --git a/runtime/shims/d3d12_xs_alloc_size.h b/runtime/shims/d3d12_xs_alloc_size.h index 751f05a4c6..6ad3d02f8e 100644 --- a/runtime/shims/d3d12_xs_alloc_size.h +++ b/runtime/shims/d3d12_xs_alloc_size.h @@ -175,7 +175,7 @@ inline UINT64 console_depth_stencil_size(const D3D12_RESOURCE_DESC& desc) { // // Why exact: the title keeps this size in its streaming tables and reads exactly that many bytes of the texture // from its archives through DirectStorage; a compressed chunk must be read whole, and the title stops on an int3 -// (game+0x4ffd879) when the size it was given is smaller than the chunk. Measured with a debugger at that int3: a +// when the size it was given is smaller than the chunk. Measured with a debugger at that int3: a // request of 0x2000 bytes for a chunk that spans 0x4000, the PC answer for the texture being half the console's. inline bool console_texture_layout(const D3D12_RESOURCE_DESC& desc, UINT64& size, UINT64& alignment) { constexpr UINT gpu_written = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 791c169fc4..87cc26dd33 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -126,6 +126,14 @@ struct DeviceProxy { // The console runtime layout this title was built against (docs/d3d12_xs_console_abi.md §4): the queue proxy // writes it on detection and every object shares it — the queue/list slot tails shift +2 under the newer one. std::atomic console_layout{0}; // 0 unknown, 1 older, 2 newer + // The real (translated) CPU handles that hold a render-target view the title created with no resource (device + // slot 20 with a null resource), for console list slot 52: on the console, clearing such a view does nothing. + // The real device's descriptor cannot tell (the Vulkan layer writes the same empty record for a view it could not + // make, and the PC runtime's handles are opaque), so the proxy keeps the mark itself. A view made there with a + // resource, or a descriptor copy over it, removes it. + std::mutex null_rtv_lock; + std::set null_rtvs; + std::atomic null_rtv_count{0}; // null_rtvs.size(), read without the lock on the clear path // Set by create_device_proxy: false hands real (PC-shaped) lists back from CreateCommandList for callers // compiled against the PC headers. bool console_lists = true; @@ -195,6 +203,10 @@ struct HeapProxy { SIZE_T custom_byte_size; SIZE_T real_cpu_start; DescriptorHeapBackingFree custom_free; + // An RTV heap's real CPU range, [rtv_real_start, +rtv_real_bytes): the null-view marks in it + // (DeviceProxy::null_rtvs) are dropped when the heap goes, so a later heap at the same address starts unmarked. + SIZE_T rtv_real_start = 0; + SIZE_T rtv_real_bytes = 0; }; struct DescriptorRange { @@ -387,6 +399,81 @@ void local_mirror_table(const DeviceProxy* device, std::uint64_t gpu_handle) { } } +// ---- Render-target views made with no resource (DeviceProxy::null_rtvs) ---- + +// Device slot 20 wrote an RTV at the real handle `ptr`: marked when the title passed no resource, unmarked otherwise. +void mark_null_rtv(DeviceProxy* device, SIZE_T ptr, bool no_resource) { + if (!ptr || (!no_resource && device->null_rtv_count.load(std::memory_order_acquire) == 0)) return; + std::lock_guard lock(device->null_rtv_lock); + try { + if (no_resource) + device->null_rtvs.insert(ptr); + else + device->null_rtvs.erase(ptr); + } catch (const std::bad_alloc&) { + // The mark is lost: a clear of this view keeps the PC list's answer, as before the mark existed. + } + device->null_rtv_count.store(device->null_rtvs.size(), std::memory_order_release); +} + +bool is_null_rtv(DeviceProxy* device, SIZE_T ptr) { + if (!ptr || device->null_rtv_count.load(std::memory_order_acquire) == 0) return false; + std::lock_guard lock(device->null_rtv_lock); + return device->null_rtvs.count(ptr) != 0; +} + +// A descriptor copy moves the marks with the descriptors: `count` RTV descriptors from the real handle `src` to +// `dest`, `increment` bytes apart. Caller holds null_rtv_lock. +void copy_null_rtv_marks_locked(DeviceProxy* device, SIZE_T dest, SIZE_T src, UINT count, UINT increment) { + for (UINT i = 0; i < count; ++i) { + const SIZE_T to = dest + static_cast(i) * increment; + if (device->null_rtvs.count(src + static_cast(i) * increment)) + device->null_rtvs.insert(to); + else + device->null_rtvs.erase(to); + } +} + +// CopyDescriptors / CopyDescriptorsSimple of RTVs, after the copy, with the handles the real device got. A null +// size array means ranges of one descriptor, as in D3D12. Nothing to do while no view is marked: a copy can only +// move a mark, never make one. +void copy_null_rtv_marks(DeviceProxy* device, UINT num_dest, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts, + const UINT* dest_sizes, UINT num_src, const D3D12_CPU_DESCRIPTOR_HANDLE* src_starts, + const UINT* src_sizes, D3D12_DESCRIPTOR_HEAP_TYPE type) { + if (type != D3D12_DESCRIPTOR_HEAP_TYPE_RTV || device->null_rtv_count.load(std::memory_order_acquire) == 0) return; + if (!dest_starts || !src_starts) return; + const UINT increment = device->real->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + if (!increment) return; + std::lock_guard lock(device->null_rtv_lock); + try { + UINT d = 0, s = 0, d_used = 0, s_used = 0; + while (d < num_dest && s < num_src) { + const UINT d_size = dest_sizes ? dest_sizes[d] : 1; + const UINT s_size = src_sizes ? src_sizes[s] : 1; + if (d_used == d_size) { ++d; d_used = 0; continue; } + if (s_used == s_size) { ++s; s_used = 0; continue; } + const UINT d_left = d_size - d_used, s_left = s_size - s_used; + const UINT run = d_left < s_left ? d_left : s_left; + copy_null_rtv_marks_locked(device, dest_starts[d].ptr + static_cast(d_used) * increment, + src_starts[s].ptr + static_cast(s_used) * increment, run, increment); + d_used += run; + s_used += run; + } + } catch (const std::bad_alloc&) { + } + device->null_rtv_count.store(device->null_rtvs.size(), std::memory_order_release); +} + +// An RTV heap was released: its real handles can name another heap's views from now on, so no mark may outlive it. +void drop_null_rtv_marks(DeviceProxy* device, SIZE_T start, SIZE_T bytes) { + if (!device || !start || !bytes || device->null_rtv_count.load(std::memory_order_acquire) == 0) return; + const SIZE_T end = start > (std::numeric_limits::max)() - bytes ? (std::numeric_limits::max)() + : start + bytes; + std::lock_guard lock(device->null_rtv_lock); + device->null_rtvs.erase(device->null_rtvs.lower_bound(start), device->null_rtvs.lower_bound(end)); + device->null_rtv_count.store(device->null_rtvs.size(), std::memory_order_release); +} + std::atomic g_hits[kMaxSlots]; std::atomic g_first[kMaxSlots]; std::atomic g_beyond_warned[kMaxSlots]; @@ -825,6 +912,7 @@ unsigned long heap_release(HeapProxy* self) { const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; if (refs == 0) { if (self->custom_cpu_start != 0) unregister_descriptor_range(self); + drop_null_rtv_marks(self->device, self->rtv_real_start, self->rtv_real_bytes); void* const backing = reinterpret_cast(self->custom_cpu_start); const DescriptorHeapBackingFree free_fn = self->custom_free; ID3D12DescriptorHeap* real = self->real; @@ -3312,6 +3400,101 @@ void note_bundle_value_op(ConsoleValueOp op) { op == ConsoleValueOp::write32 || op == ConsoleValueOp::write64 ? "write" : "wait"); } +// ---- Console list slot 146: Barrier(NumBarrierGroups, pBarrierGroups) -> GCL7 Barrier (PC 80) ---- +// +// The title records texture barriers with no resource, which the console takes as a global memory and execution +// barrier. A PC texture barrier needs a resource (the Vulkan layer's list goes into its error state, so Close fails +// and the submission is dropped), so each such barrier becomes a D3D12_GLOBAL_BARRIER with the same sync and access; +// its layouts, subresource range and flags have nothing to apply to. A texture group with both kinds is split into +// runs in their order: texture runs point into the title's array, global runs into the call's own storage. A call +// with nothing to convert is forwarded with the title's own pointer. +constexpr UINT32 kMaxConsoleBarrierGroups = 1024; // the measured calls pass one group +constexpr UINT32 kMaxConsoleBarriersPerGroup = 65536; + +struct ConsoleBarrierStorage { // lives for one call, on the recording thread's stack + std::vector groups; + std::vector globals; +}; + +// The groups to forward: `in` when nothing needs converting, `storage.groups` when something does, null with +// `reason` set when the array cannot be read safely and the call is refused. `out_count` is the group count to pass. +const D3D12_BARRIER_GROUP* console_barrier_groups(UINT32 count, const D3D12_BARRIER_GROUP* in, + ConsoleBarrierStorage& storage, UINT32& out_count, + const char*& reason) { + const auto refuse = [&reason](const char* why) -> const D3D12_BARRIER_GROUP* { + reason = why; + return nullptr; + }; + out_count = count; + if (count == 0) return in; // nothing to read: the PC call is a no-op either way + if (!in) return refuse("null group array with a nonzero count"); + if (count > kMaxConsoleBarrierGroups) return refuse("group count over the limit"); + std::size_t null_textures = 0, texture_barriers = 0; + for (UINT32 g = 0; g < count; ++g) { + const D3D12_BARRIER_GROUP& group = in[g]; + if (group.Type != D3D12_BARRIER_TYPE_GLOBAL && group.Type != D3D12_BARRIER_TYPE_TEXTURE && + group.Type != D3D12_BARRIER_TYPE_BUFFER) + return refuse("unknown barrier group type"); + if (group.NumBarriers > kMaxConsoleBarriersPerGroup) return refuse("barrier count over the limit"); + if (group.NumBarriers && !group.pGlobalBarriers) // the union's pointer, whichever member the type names + return refuse("null barrier array with a nonzero count"); + if (group.Type != D3D12_BARRIER_TYPE_TEXTURE) continue; + texture_barriers += group.NumBarriers; + for (UINT32 i = 0; i < group.NumBarriers; ++i) + if (!group.pTextureBarriers[i].pResource) ++null_textures; + } + if (null_textures == 0) return in; + try { + storage.globals.reserve(null_textures); // exact: the groups point into it, so it never reallocates + storage.groups.reserve(count + texture_barriers); + for (UINT32 g = 0; g < count; ++g) { + const D3D12_BARRIER_GROUP& group = in[g]; + if (group.Type != D3D12_BARRIER_TYPE_TEXTURE) { + storage.groups.push_back(group); + continue; + } + const D3D12_TEXTURE_BARRIER* barriers = group.pTextureBarriers; + for (UINT32 i = 0; i < group.NumBarriers;) { + const UINT32 start = i; + const bool no_resource = !barriers[i].pResource; + while (i < group.NumBarriers && !barriers[i].pResource == no_resource) ++i; + D3D12_BARRIER_GROUP run{}; + run.NumBarriers = i - start; + if (no_resource) { + run.Type = D3D12_BARRIER_TYPE_GLOBAL; + run.pGlobalBarriers = storage.globals.data() + storage.globals.size(); + for (UINT32 k = start; k < i; ++k) + storage.globals.push_back(D3D12_GLOBAL_BARRIER{barriers[k].SyncBefore, barriers[k].SyncAfter, + barriers[k].AccessBefore, + barriers[k].AccessAfter}); + } else { + run.Type = D3D12_BARRIER_TYPE_TEXTURE; + run.pTextureBarriers = barriers + start; + } + storage.groups.push_back(run); + } + } + } catch (const std::bad_alloc&) { + return refuse("out of memory converting the groups"); + } + out_count = static_cast(storage.groups.size()); + return storage.groups.data(); +} + +// Logged once per reason. The call is dropped whole: nothing of it reaches the PC list. +void log_refused_barrier(const char* reason, UINT32 count, const void* groups) { + static std::mutex lock; + static std::set seen; // the reasons are string literals + std::lock_guard guard(lock); + try { + if (!seen.insert(reason).second) return; + } catch (const std::bad_alloc&) { + return; + } + std::fprintf(stderr, "[rt] d3d12_xs: list slot 146 (Barrier) refused, nothing recorded: %s (%u groups at %p)\n", + reason, count, groups); +} + template std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, @@ -3532,6 +3715,36 @@ std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t // ClearRenderTargetView(RenderTargetView, ColorRGBA, NumRects, pRects): translate the RTV handle. a1 = static_cast( translate_cpu_handle(self->device, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a1)}).ptr); + // A view the title made with no resource: the console clear does nothing, and the PC list would + // take the view as invalid and fail its Close. Any other view goes to the PC list as before. + if (is_null_rtv(self->device, static_cast(a1))) { + static std::atomic logged{false}; + if (first_call(logged)) + std::fprintf(stderr, "[rt] d3d12_xs: list slot 52 (ClearRenderTargetView) of a view made with " + "no resource skipped, as on the console (handle 0x%llx)\n", + static_cast(a1)); + return 0; + } + } else if constexpr (Slot == kConsoleBarrier) { + // Barrier(NumBarrierGroups, pBarrierGroups): console_barrier_groups above. + ConsoleBarrierStorage storage; + UINT32 count = 0; + const char* reason = nullptr; + const D3D12_BARRIER_GROUP* groups = console_barrier_groups( + static_cast(a1), reinterpret_cast(a2), storage, count, reason); + if (reason) { + log_refused_barrier(reason, static_cast(a1), reinterpret_cast(a2)); + return 0; + } + if (groups && groups == storage.groups.data()) { + static std::atomic logged{false}; + if (first_call(logged)) + std::fprintf(stderr, "[rt] d3d12_xs: list slot 146 (Barrier): texture barriers with no " + "resource recorded as global barriers, as on the console\n"); + } + return reinterpret_cast(real_vtable[pc])(self->real, count, + reinterpret_cast(groups), a3, a4, + a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); } else if constexpr (Slot == kConsoleClearUavUint || Slot == kConsoleClearUavFloat) { // ClearUnorderedAccessViewUint/Float(ViewGPUHandle, ViewCPUHandle, pResource, Values, NumRects, // pRects): keep GPU handle, translate CPU handle. @@ -4516,6 +4729,15 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H hr = create_heap_proxy(heap, self, *riid, out, custom_cpu_start, custom_byte_size, real_cpu_start, custom_cpu_start ? free_fn : nullptr, stride); + if (SUCCEEDED(hr) && desc && desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_RTV && is_heap_proxy(*out)) { + // The null-view marks are kept by real handle (mark_null_rtv); heap_release drops those in this range. + const UINT inc = self->real->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + auto* proxy = static_cast(*out); + proxy->rtv_real_start = + real_cpu_start ? real_cpu_start : raw_heap_get_cpu_handle(heap, *reinterpret_cast(heap)).ptr; + if (inc && desc->NumDescriptors <= (std::numeric_limits::max)() / inc) + proxy->rtv_real_bytes = static_cast(desc->NumDescriptors) * inc; + } if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC (fsdraw): which CPU start the title gets for this heap static std::atomic logged{0}; if (logged.fetch_add(1) < 32) @@ -4566,7 +4788,9 @@ void proxy_create_uav(DeviceProxy* self, ID3D12Resource* resource, ID3D12Resourc void proxy_create_rtv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_RENDER_TARGET_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(20); - self->real->CreateRenderTargetView(resource, desc, translate_cpu_handle(self, dest)); + const D3D12_CPU_DESCRIPTOR_HANDLE real_dest = translate_cpu_handle(self, dest); + self->real->CreateRenderTargetView(resource, desc, real_dest); + mark_null_rtv(self, real_dest.ptr, resource == nullptr); // for console list slot 52 (DeviceProxy::null_rtvs) } void proxy_create_dsv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_DEPTH_STENCIL_VIEW_DESC* desc, @@ -4587,6 +4811,7 @@ void proxy_copy_descriptors(DeviceProxy* self, UINT num_dest, const D3D12_CPU_DE note_slot(23); if (g_custom_range_count.load(std::memory_order_acquire) == 0) { self->real->CopyDescriptors(num_dest, dest_starts, dest_sizes, num_src, src_starts, src_sizes, type); + copy_null_rtv_marks(self, num_dest, dest_starts, dest_sizes, num_src, src_starts, src_sizes, type); return; } constexpr UINT kInline = 32; @@ -4621,6 +4846,7 @@ void proxy_copy_descriptors(DeviceProxy* self, UINT num_dest, const D3D12_CPU_DE self->real->CopyDescriptors(num_dest, dest_out, dest_sizes, num_src, src_out, src_sizes, type); for (UINT i = 0; dest_starts && i < num_dest; ++i) local_write_through(self, dest_starts[i], dest_sizes ? dest_sizes[i] : 1); + copy_null_rtv_marks(self, num_dest, dest_out, dest_sizes, num_src, src_out, src_sizes, type); } void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D12_CPU_DESCRIPTOR_HANDLE dest_start, @@ -4630,6 +4856,7 @@ void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D1 const D3D12_CPU_DESCRIPTOR_HANDLE src = translate_cpu_handle(self, src_start); self->real->CopyDescriptorsSimple(num_descriptors, dest, src, type); local_write_through(self, dest_start, num_descriptors); + copy_null_rtv_marks(self, 1, &dest, &num_descriptors, 1, &src, &num_descriptors, type); if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC (fsdraw): where the title copies its descriptors, and what lands there static std::atomic copies{0}; const std::uint64_t n = ++copies; diff --git a/runtime/shims/startup_trace.h b/runtime/shims/startup_trace.h index e6902783b9..9a55981297 100644 --- a/runtime/shims/startup_trace.h +++ b/runtime/shims/startup_trace.h @@ -178,8 +178,10 @@ inline std::string debug_text(const EXCEPTION_RECORD& r) { return utf8_from_ansi(a, static_cast(n ? n - 1 : strlen(a))); } -// LOCAL DIAGNOSTIC for one of the title's asserts (docs/re/answers.md, "transient pool"): at the int3 at -// game+0x2473e88 the title has just computed the peak of a list of resources with lifetimes against a fixed pool. +// LOCAL DIAGNOSTIC for one of the title's asserts (docs/re/answers.md, "transient pool"): at that assert's int3 +// the title has just computed the peak of a list of resources with lifetimes against a fixed pool. The int3's +// location is measured locally and not kept here: LEONIDA_POOL_DIAG_AT names it as the trace prints it +// (`+0x`), and the dump is off without it. // rdi = the list (24-byte records: entry pointer, u32 size rounded to 64 KiB), r13 = the count, rax = the peak, // rcx = the pool size. An entry is {record pointer, ..., u32 first pass at +16, u32 last pass at +20}; a record has // its usage word at +14, kind word at +16 and, for a texture, width/height/depth words at +56/+58/+60, the dimension @@ -215,8 +217,13 @@ inline void dump_transient_pool(const CONTEXT& c) { inline void log_exception(const EXCEPTION_POINTERS& info) { const EXCEPTION_RECORD& r = *info.ExceptionRecord; try { - if (r.ExceptionCode == EXCEPTION_BREAKPOINT && info.ContextRecord && - where(reinterpret_cast(r.ExceptionAddress)).ends_with("master.exe+0x2473e88")) + static const std::string pool_diag_at = [] { + char at[128]{}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_POOL_DIAG_AT", at, sizeof(at)); + return n && n < sizeof(at) ? std::string(at, n) : std::string(); + }(); + if (r.ExceptionCode == EXCEPTION_BREAKPOINT && info.ContextRecord && !pool_diag_at.empty() && + where(reinterpret_cast(r.ExceptionAddress)).ends_with(pool_diag_at)) dump_transient_pool(*info.ContextRecord); if (r.ExceptionCode == kDbgPrint || r.ExceptionCode == kDbgPrintWide) { const ULONG_PTR fallback = wide_fallback; diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 4d483ed593..21551e9489 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -40,24 +40,51 @@ namespace { -// The retail executable (1.0.2.1) runs a hang watchdog thread (function at RVA 0x2215a60): when the game's main loop -// has not set its "kick" byte (RVA 0x71b6331) for 30 one-second ticks, it calls a crash callback and then writes to -// address 0 (`movl $0, 0` at RVA 0x2215c35). Under the runtime the game thread can legitimately stall for longer than -// that, e.g. while the driver compiles pipelines against a cold cache (first boot after a driver update), and the -// title then kills itself. By default the watchdog stays armed, as on the console. With LEONIDA_TITLE_WATCHDOG=0, and -// only when that exact trap instruction sits where it does in this build, a runtime thread sets the kick byte twice a -// second so the title's watchdog never fires. -constexpr std::uint32_t kWatchdogTrapRva = 0x2215c35; -constexpr std::uint32_t kWatchdogKickRva = 0x71b6331; +// The retail title runs a hang watchdog thread: when the game's main loop has not set its "kick" byte for 30 +// one-second ticks, it calls a crash callback and then writes to address 0 (`movl $0, 0`). Under the runtime the +// game thread can legitimately stall for longer than that, e.g. while the driver compiles pipelines against a cold +// cache (first boot after a driver update), and the title then kills itself. By default the watchdog stays armed, as +// on the console. LEONIDA_TITLE_WATCHDOG=0 asks to keep it from firing, as before. The two places that takes are +// measured locally and not kept in the repository: LEONIDA_TITLE_WATCHDOG_KICK="," (hex) names +// them, and only with both variables, and only when that exact trap instruction sits at the first RVA, does a +// runtime thread set the byte at the second twice a second, so the title's watchdog never fires. Either variable +// alone leaves the watchdog armed and says so once. constexpr unsigned char kWatchdogTrap[] = {0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0}; // movl $0, 0x0 +bool watchdog_rvas(std::uint32_t& trap_rva, std::uint32_t& kick_rva) { + char value[64]{}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG_KICK", value, sizeof(value)); + if (!n || n >= sizeof(value)) return false; + char* rest = nullptr; + const unsigned long long trap = std::strtoull(value, &rest, 16); + if (!rest || *rest != ',') return false; + const unsigned long long kick = std::strtoull(rest + 1, &rest, 16); + if (!rest || *rest || !trap || !kick || trap > 0xFFFFFFFFull || kick > 0xFFFFFFFFull) return false; + trap_rva = static_cast(trap); + kick_rva = static_cast(kick); + return true; +} + void keep_title_watchdog_kicked(std::uint8_t* base) { - char value[4]{}; - if (GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG", value, sizeof(value)) != 1 || value[0] != '0') return; + char keep[4]{}; + const bool disarm = GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG", keep, sizeof(keep)) == 1 && keep[0] == '0'; + std::uint32_t kWatchdogTrapRva = 0, kWatchdogKickRva = 0; + const bool named = watchdog_rvas(kWatchdogTrapRva, kWatchdogKickRva); + if (!disarm) { + if (named) + std::fprintf(stderr, "[rt] loader: LEONIDA_TITLE_WATCHDOG_KICK is set but LEONIDA_TITLE_WATCHDOG is not 0;" + " the title's hang watchdog stays armed\n"); + return; + } + if (!named) { + std::fprintf(stderr, "[rt] loader: LEONIDA_TITLE_WATCHDOG=0 needs LEONIDA_TITLE_WATCHDOG_KICK=," + " (hex); the title's hang watchdog stays armed\n"); + return; + } MEMORY_BASIC_INFORMATION trap{}, kick{}; if (!VirtualQuery(base + kWatchdogTrapRva, &trap, sizeof(trap)) || trap.State != MEM_COMMIT || std::memcmp(base + kWatchdogTrapRva, kWatchdogTrap, sizeof(kWatchdogTrap)) != 0) - return; // not the build this was measured on: leave the title's watchdog alone + return; // not the trap the RVAs name: leave the title's watchdog alone const DWORD writable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; if (!VirtualQuery(base + kWatchdogKickRva, &kick, sizeof(kick)) || kick.State != MEM_COMMIT || !(kick.Protect & writable)) @@ -79,7 +106,7 @@ void keep_title_watchdog_kicked(std::uint8_t* base) { } } -// LEONIDA_PEEK="0x9e1dac0:3,0x7446510,0x98f828c" (diagnostic): a thread prints the 8-byte values at these RVAs of the +// LEONIDA_PEEK=":3,," (diagnostic): a thread prints the 8-byte values at these RVAs of the // title's image (":n" = n consecutive values, at most 32; "RVA>OFF" reads through the pointer stored at the RVA, at // pointer + OFF, both hex) every LEONIDA_PEEK_SECONDS (default 10). For answering "what does this // global hold at run time" without a debugger: the reverse-engineering notes (docs/re/requests.md) ask for exactly diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 7c671ed1bd..cb350820e9 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -137,11 +137,62 @@ struct Mock { UINT clear_dsv_num_rects; const D3D12_RECT* clear_dsv_rects; D3D_FEATURE_LEVEL max_level; // device: the highest level FEATURE_LEVELS reports (0: the query is refused) + // list: set by a call the Vulkan layer's list takes as invalid (a texture barrier with no resource at slot 80, a + // clear at slot 48 of a view made with no resource); Close (slot 9) then fails, as that list's does. + bool list_error; + // list slot 80 (Barrier): what the last call carried, copied (the proxy's converted groups live for the call). + UINT barrier_group_count; + D3D12_BARRIER_TYPE barrier_group_types[4]; + UINT barrier_group_sizes[4]; + UINT barrier_global_count; + D3D12_GLOBAL_BARRIER barrier_globals[8]; + UINT barrier_texture_count; + D3D12_TEXTURE_BARRIER barrier_textures[8]; }; Mock g_pool[512]; unsigned g_pool_used = 0; +// The real handles the mock device last wrote an RTV with no resource at (device slot 20). A mock list's clear of one +// sets list_error, as the Vulkan layer's empty view record does. +SIZE_T g_mock_null_rtvs[16]; +unsigned g_mock_null_rtv_count = 0; + +void mock_note_rtv(SIZE_T handle, bool no_resource) { + for (unsigned i = 0; i < g_mock_null_rtv_count; ++i) + if (g_mock_null_rtvs[i] == handle) g_mock_null_rtvs[i--] = g_mock_null_rtvs[--g_mock_null_rtv_count]; + if (no_resource && g_mock_null_rtv_count < std::size(g_mock_null_rtvs)) + g_mock_null_rtvs[g_mock_null_rtv_count++] = handle; +} + +bool mock_is_null_rtv(SIZE_T handle) { + for (unsigned i = 0; i < g_mock_null_rtv_count; ++i) + if (g_mock_null_rtvs[i] == handle) return true; + return false; +} + +void mock_barrier(Mock* m, std::uint64_t count, std::uint64_t groups_word) { + const auto* groups = reinterpret_cast(groups_word); + m->barrier_group_count = static_cast(count); + m->barrier_global_count = m->barrier_texture_count = 0; + for (UINT g = 0; groups && g < static_cast(count); ++g) { + const D3D12_BARRIER_GROUP& group = groups[g]; + if (g < std::size(m->barrier_group_types)) { + m->barrier_group_types[g] = group.Type; + m->barrier_group_sizes[g] = group.NumBarriers; + } + for (UINT i = 0; i < group.NumBarriers; ++i) { + if (group.Type == D3D12_BARRIER_TYPE_GLOBAL && m->barrier_global_count < std::size(m->barrier_globals)) { + m->barrier_globals[m->barrier_global_count++] = group.pGlobalBarriers[i]; + } else if (group.Type == D3D12_BARRIER_TYPE_TEXTURE) { + if (!group.pTextureBarriers[i].pResource) m->list_error = true; + if (m->barrier_texture_count < std::size(m->barrier_textures)) + m->barrier_textures[m->barrier_texture_count++] = group.pTextureBarriers[i]; + } + } + } +} + void** mock_vtable(); void** mock_list_vtable(); @@ -384,6 +435,7 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { if (a1) std::memcpy(&m->queue_desc, reinterpret_cast(a1), sizeof(m->queue_desc)); return static_cast(mock_create(m, Kind::queue, a2, a3)); case 9: return static_cast(mock_create(m, Kind::allocator, a2, a3)); // CreateCmdAllocator + case 20: mock_note_rtv(static_cast(a3), a1 == 0); break; // CreateRenderTargetView(res, desc, dest) // Slot 12 (CreateCommandList) never reaches this switch: the device vtable's slot is the dedicated // mock_create_command_list, which needs the sixth word the generic thunk does not declare on some // builds and which picks the list mock's chain breadth from full_chain_lists. @@ -524,6 +576,11 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { m->om_has_dsv = dsv != nullptr; m->om_dsv = dsv ? dsv->ptr : 0; } + if (m->kind == Kind::list || m->kind == Kind::command_list) { + if (slot == 9) return static_cast(m->list_error ? E_INVALIDARG : S_OK); // Close + if (slot == 48 && mock_is_null_rtv(static_cast(a1))) m->list_error = true; // ClearRenderTargetView + if (slot == 80) mock_barrier(m, a1, a2); // Barrier + } return S_OK; } @@ -2419,7 +2476,8 @@ int check_lists() { so_view.BufferFilledSizeLocation = p2; EXPECT(hr_of(raw(list, 49, 0, 1, word(&so_view))) == S_OK && real->calls[45] == 1); // The console tail past the PC chain is refused with E_NOTIMPL only when the mapped PC slot is missing. - EXPECT(hr_of(raw(list, 146, word(list), 0)) == S_OK && real->calls[80] == 1); // enhanced Barrier -> GCL7 80 + // Enhanced Barrier -> GCL7 80; an empty call (no groups) goes through as the PC no-op it is. + EXPECT(hr_of(raw(list, 146, 0, 0)) == S_OK && real->calls[80] == 1); EXPECT(release(list) == 0 && real->refs == 0); EXPECT(release(allocator) == 0 && real_allocator->refs == 0); EXPECT(xs::device_proxy_ref_count(device) == device_refs); @@ -4837,10 +4895,18 @@ int check_console_command_list() { EXPECT(xs::is_command_list_proxy(list7_proxy)); Mock* real_list7 = reinterpret_cast(xs::command_list_proxy_real_list(list7_proxy)); EXPECT(real_list7 != nullptr); - // Console slot 146 -> PC slot 80 (since 80 < 81 slots) - raw(list7_proxy, 146, 0x9999, 0, 0, 0); - EXPECT(real_list7->calls[80] == 1); - EXPECT(real_list7->args[80][0] == 0x9999); + // Console slot 146 -> PC slot 80 (since 80 < 81 slots): a valid group goes through with the title's pointer. + { + const D3D12_GLOBAL_BARRIER global{D3D12_BARRIER_SYNC_ALL, D3D12_BARRIER_SYNC_ALL, + D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS}; + D3D12_BARRIER_GROUP group{}; + group.Type = D3D12_BARRIER_TYPE_GLOBAL; + group.NumBarriers = 1; + group.pGlobalBarriers = &global; + raw(list7_proxy, 146, 1, word(&group), 0, 0); + EXPECT(real_list7->calls[80] == 1); + EXPECT(real_list7->args[80][0] == 1 && real_list7->args[80][1] == word(&group)); + } EXPECT(release(list7_proxy) == 0 && real_list7->refs == 0); // Clean up @@ -4860,6 +4926,249 @@ int check_console_command_list() { return 0; } +// ---- Console list slots 146 and 52: what the console takes as a no-op or a global barrier ---- +// +// The mock list stands in for the Vulkan layer's: a texture barrier with no resource, or a clear of a view made with +// no resource, puts it in its error state and its Close fails (checked directly on the mock first, so the cases +// below mean something). Through the proxy the barrier becomes a global barrier and the clear is skipped. +int check_console_null_barrier_and_clear() { + g_mock_null_rtv_count = 0; + Mock* mock = nullptr; + void* device = make_device(mock, 9, true, true, /*full_chain_lists=*/true); + EXPECT(device); + const IID allocator_iid = __uuidof(ID3D12CommandAllocator); + const IID gcl_iid = __uuidof(ID3D12GraphicsCommandList); + void* allocator = nullptr; + EXPECT(hr_of(raw(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&allocator_iid), word(&allocator))) == S_OK); + void* list = nullptr; + EXPECT(hr_of(raw(device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, word(allocator), 0, word(&gcl_iid), + word(&list))) == S_OK); + Mock* const real = reinterpret_cast(xs::list_proxy_real_list(list)); + EXPECT(real && real->kind == Kind::list); + Mock* const texture_a = new_mock(Kind::resource); // never dereferenced: only the pointers are compared + Mock* const texture_b = new_mock(Kind::resource); + auto* const resource_a = reinterpret_cast(texture_a); + auto* const resource_b = reinterpret_cast(texture_b); + + // A texture barrier with no resource, as the title records it: render target to pixel-shader read. + D3D12_TEXTURE_BARRIER no_resource{}; + no_resource.SyncBefore = D3D12_BARRIER_SYNC_RENDER_TARGET; + no_resource.SyncAfter = D3D12_BARRIER_SYNC_PIXEL_SHADING; + no_resource.AccessBefore = D3D12_BARRIER_ACCESS_RENDER_TARGET; + no_resource.AccessAfter = D3D12_BARRIER_ACCESS_SHADER_RESOURCE; + no_resource.LayoutBefore = D3D12_BARRIER_LAYOUT_RENDER_TARGET; + no_resource.LayoutAfter = D3D12_BARRIER_LAYOUT_SHADER_RESOURCE; + no_resource.Subresources.IndexOrFirstMipLevel = 0xffffffffu; + D3D12_BARRIER_GROUP texture_group{}; + texture_group.Type = D3D12_BARRIER_TYPE_TEXTURE; + texture_group.NumBarriers = 1; + texture_group.pTextureBarriers = &no_resource; + + // The mock models the PC list: the same group sent to it directly fails its Close. + raw(real, 80, 1, word(&texture_group)); + EXPECT(real->list_error && hr_of(raw(real, 9)) == E_INVALIDARG); + real->list_error = false; + real->calls[80] = 0; + + // 1. Through the proxy: one global barrier with the same sync and access, in the call's own storage; the + // title's group and barrier are not written; Close succeeds. + EXPECT(hr_of(raw(list, 146, 1, word(&texture_group))) == S_OK); + EXPECT(real->calls[80] == 1 && real->args[80][0] == 1 && real->args[80][1] != word(&texture_group)); + EXPECT(real->barrier_group_count == 1 && real->barrier_group_types[0] == D3D12_BARRIER_TYPE_GLOBAL && + real->barrier_group_sizes[0] == 1 && real->barrier_global_count == 1 && real->barrier_texture_count == 0); + EXPECT(real->barrier_globals[0].SyncBefore == D3D12_BARRIER_SYNC_RENDER_TARGET && + real->barrier_globals[0].SyncAfter == D3D12_BARRIER_SYNC_PIXEL_SHADING && + real->barrier_globals[0].AccessBefore == D3D12_BARRIER_ACCESS_RENDER_TARGET && + real->barrier_globals[0].AccessAfter == D3D12_BARRIER_ACCESS_SHADER_RESOURCE); + EXPECT(texture_group.Type == D3D12_BARRIER_TYPE_TEXTURE && texture_group.pTextureBarriers == &no_resource && + !no_resource.pResource); + EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); + + // 2. Valid barriers pass unchanged: a texture group with resources goes through with the title's own pointer. + D3D12_TEXTURE_BARRIER with_resource[2] = {no_resource, no_resource}; + with_resource[0].pResource = resource_a; + with_resource[1].pResource = resource_b; + with_resource[1].Subresources = {2, 1, 0, 1, 0, 1}; + D3D12_BARRIER_GROUP valid_group{}; + valid_group.Type = D3D12_BARRIER_TYPE_TEXTURE; + valid_group.NumBarriers = 2; + valid_group.pTextureBarriers = with_resource; + EXPECT(hr_of(raw(list, 146, 1, word(&valid_group))) == S_OK); + EXPECT(real->calls[80] == 2 && real->args[80][0] == 1 && real->args[80][1] == word(&valid_group)); + EXPECT(real->barrier_texture_count == 2 && real->barrier_global_count == 0 && + real->barrier_textures[0].pResource == resource_a && real->barrier_textures[1].pResource == resource_b && + real->barrier_textures[1].LayoutAfter == D3D12_BARRIER_LAYOUT_SHADER_RESOURCE && + real->barrier_textures[1].Subresources.IndexOrFirstMipLevel == 2); + EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); + + // 3. Mixed: a buffer group, then a texture group of [resource, none, none, resource]. The buffer group passes as + // it is and the texture group splits into texture(1), global(2), texture(1), in order. + const D3D12_BUFFER_BARRIER buffer{D3D12_BARRIER_SYNC_COPY, D3D12_BARRIER_SYNC_COMPUTE_SHADING, + D3D12_BARRIER_ACCESS_COPY_DEST, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + resource_a, 0, UINT64_MAX}; + D3D12_TEXTURE_BARRIER mixed[4] = {with_resource[0], no_resource, no_resource, with_resource[1]}; + mixed[2].SyncBefore = D3D12_BARRIER_SYNC_COMPUTE_SHADING; + mixed[2].AccessBefore = D3D12_BARRIER_ACCESS_UNORDERED_ACCESS; + D3D12_BARRIER_GROUP mixed_groups[2]{}; + mixed_groups[0].Type = D3D12_BARRIER_TYPE_BUFFER; + mixed_groups[0].NumBarriers = 1; + mixed_groups[0].pBufferBarriers = &buffer; + mixed_groups[1].Type = D3D12_BARRIER_TYPE_TEXTURE; + mixed_groups[1].NumBarriers = 4; + mixed_groups[1].pTextureBarriers = mixed; + EXPECT(hr_of(raw(list, 146, 2, word(mixed_groups))) == S_OK); + EXPECT(real->calls[80] == 3 && real->args[80][0] == 4); + EXPECT(real->barrier_group_types[0] == D3D12_BARRIER_TYPE_BUFFER && real->barrier_group_sizes[0] == 1 && + real->barrier_group_types[1] == D3D12_BARRIER_TYPE_TEXTURE && real->barrier_group_sizes[1] == 1 && + real->barrier_group_types[2] == D3D12_BARRIER_TYPE_GLOBAL && real->barrier_group_sizes[2] == 2 && + real->barrier_group_types[3] == D3D12_BARRIER_TYPE_TEXTURE && real->barrier_group_sizes[3] == 1); + EXPECT(real->barrier_texture_count == 2 && real->barrier_textures[0].pResource == resource_a && + real->barrier_textures[1].pResource == resource_b); + EXPECT(real->barrier_global_count == 2 && + real->barrier_globals[0].SyncBefore == D3D12_BARRIER_SYNC_RENDER_TARGET && + real->barrier_globals[1].SyncBefore == D3D12_BARRIER_SYNC_COMPUTE_SHADING && + real->barrier_globals[1].AccessBefore == D3D12_BARRIER_ACCESS_UNORDERED_ACCESS && + real->barrier_globals[1].AccessAfter == D3D12_BARRIER_ACCESS_SHADER_RESOURCE); + EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); + + // 4. Arrays that cannot be read safely are refused whole: nothing reaches the list, which stays valid and keeps + // taking calls. + D3D12_BARRIER_GROUP unknown_type = texture_group; + reinterpret_cast(unknown_type.Type) = 7; + D3D12_BARRIER_GROUP null_barriers{}; + null_barriers.Type = D3D12_BARRIER_TYPE_TEXTURE; + null_barriers.NumBarriers = 3; + D3D12_BARRIER_GROUP huge_group = valid_group; + huge_group.NumBarriers = 0x10000000u; + EXPECT(hr_of(raw(list, 146, 1, 0)) == S_OK); // null array, nonzero count + EXPECT(hr_of(raw(list, 146, 1, word(&unknown_type))) == S_OK); // a group type the layer does not know + EXPECT(hr_of(raw(list, 146, 1, word(&null_barriers))) == S_OK); // null barrier array, nonzero count + EXPECT(hr_of(raw(list, 146, 1, word(&huge_group))) == S_OK); // barrier count over the limit + EXPECT(hr_of(raw(list, 146, 0x40000000u, word(&valid_group))) == S_OK); // group count over the limit + // A malformed group after a convertible one refuses the call as well: nothing of it is recorded. + D3D12_BARRIER_GROUP half_bad[2] = {texture_group, unknown_type}; + EXPECT(hr_of(raw(list, 146, 2, word(half_bad))) == S_OK); + EXPECT(real->calls[80] == 3 && !real->list_error); + EXPECT(hr_of(raw(list, 146, 1, word(&texture_group))) == S_OK && real->calls[80] == 4); + EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); + + // 5. ClearRenderTargetView (console 52 -> PC 48) of a view made with no resource is skipped; a view made with a + // resource is still cleared. No custom heap range here, so the handles reach the device unchanged. + const SIZE_T rtv_none = kMockHeapCpuStart + 0x1000; + const SIZE_T rtv_real = rtv_none + kMockDescriptorInc; + const SIZE_T rtv_copy = rtv_none + 4 * kMockDescriptorInc; + const FLOAT color[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + raw(device, 20, 0, 0, rtv_none); // CreateRenderTargetView(nullptr, nullptr, handle) + raw(device, 20, word(resource_a), 0, rtv_real); + EXPECT(mock->calls[20] == 2 && mock_is_null_rtv(rtv_none) && !mock_is_null_rtv(rtv_real)); + raw(real, 48, rtv_none, word(color), 0, 0); // the mock's model: the direct clear fails the list + EXPECT(real->list_error && hr_of(raw(real, 9)) == E_INVALIDARG); + real->list_error = false; + real->calls[48] = 0; + + EXPECT(hr_of(raw(list, 52, rtv_none, word(color), 0, 0)) == S_OK && real->calls[48] == 0); + EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); + const D3D12_RECT rect{0, 0, 4, 4}; + raw(list, 52, rtv_real, word(color), 1, word(&rect)); + EXPECT(real->calls[48] == 1 && real->args[48][0] == rtv_real && real->args[48][1] == word(color) && + real->args[48][2] == 1 && real->args[48][3] == word(&rect)); + EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); + + // A view made again at the same handle with a resource is cleared from then on. + raw(device, 20, word(resource_b), 0, rtv_none); + raw(list, 52, rtv_none, word(color), 0, 0); + EXPECT(real->calls[48] == 2 && real->args[48][0] == rtv_none); + raw(device, 20, 0, 0, rtv_none); // and with no resource again: skipped again + raw(list, 52, rtv_none, word(color), 0, 0); + EXPECT(real->calls[48] == 2); + + // Descriptor copies move the mark: CopyDescriptorsSimple of the empty view, then of the real one over it. + raw(device, 24, 1, rtv_copy, rtv_none, D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + raw(list, 52, rtv_copy, word(color), 0, 0); + EXPECT(real->calls[48] == 2); + raw(device, 24, 1, rtv_copy, rtv_real, D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + raw(list, 52, rtv_copy, word(color), 0, 0); + EXPECT(real->calls[48] == 3 && real->args[48][0] == rtv_copy); + // A copy of another heap type leaves the RTV marks alone. + raw(device, 24, 1, rtv_copy, rtv_none, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + raw(list, 52, rtv_copy, word(color), 0, 0); + EXPECT(real->calls[48] == 4); + // CopyDescriptors with ranges: one destination range of two from two source ranges of one (empty, then real). + const D3D12_CPU_DESCRIPTOR_HANDLE dest_starts[1] = {{rtv_copy}}; + const UINT dest_sizes[1] = {2}; + const D3D12_CPU_DESCRIPTOR_HANDLE src_starts[2] = {{rtv_none}, {rtv_real}}; + const UINT src_sizes[2] = {1, 1}; + raw10(device, 23, {1, word(dest_starts), word(dest_sizes), 2, word(src_starts), word(src_sizes), + D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 0, 0, 0}); + EXPECT(mock->calls[23] == 1); + raw(list, 52, rtv_copy, word(color), 0, 0); + EXPECT(real->calls[48] == 4); + raw(list, 52, rtv_copy + kMockDescriptorInc, word(color), 0, 0); + EXPECT(real->calls[48] == 5 && real->args[48][0] == rtv_copy + kMockDescriptorInc); + EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); + + // Releasing an RTV heap drops the marks in its real range, so a heap made later at the same address starts + // unmarked; a mark outside that range stays. + g_heap_hook.next_ptr = nullptr; // a plain PC heap even if a descriptor-heap hook is registered: real handles + D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc{}; + rtv_heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; + rtv_heap_desc.NumDescriptors = 4; + const IID heap_iid = __uuidof(ID3D12DescriptorHeap); + void* rtv_heap = nullptr; + EXPECT(SUCCEEDED(hr_of(raw(device, 14, word(&rtv_heap_desc), word(&heap_iid), word(&rtv_heap))))); + EXPECT(rtv_heap && xs::is_heap_proxy(rtv_heap) && raw(rtv_heap, 9) == kMockHeapCpuStart); + const SIZE_T in_heap = kMockHeapCpuStart + 2 * kMockDescriptorInc; + raw(device, 20, 0, 0, in_heap); + const unsigned clears = real->calls[48]; + raw(list, 52, in_heap, word(color), 0, 0); + EXPECT(real->calls[48] == clears); // marked while the heap lives: skipped + EXPECT(raw(rtv_heap, 2) == 0); + raw(list, 52, in_heap, word(color), 0, 0); + EXPECT(real->calls[48] == clears + 1 && real->args[48][0] == in_heap); // the mark went with the heap + real->list_error = false; // the mock list still takes its own view there as invalid + raw(list, 52, rtv_none, word(color), 0, 0); + EXPECT(real->calls[48] == clears + 1); // outside the released heap: still skipped + // A second RTV heap at the same address: the view made there with a resource is cleared, and a view made with + // no resource is marked again for as long as that heap lives. + void* rtv_heap2 = nullptr; + EXPECT(SUCCEEDED(hr_of(raw(device, 14, word(&rtv_heap_desc), word(&heap_iid), word(&rtv_heap2))))); + raw(device, 20, word(resource_a), 0, in_heap); + raw(list, 52, in_heap, word(color), 0, 0); + EXPECT(real->calls[48] == clears + 2 && !real->list_error); + raw(device, 20, 0, 0, in_heap); + raw(list, 52, in_heap, word(color), 0, 0); + EXPECT(real->calls[48] == clears + 2); + EXPECT(raw(rtv_heap2, 2) == 0); + EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); + + // The marks are the device's own: another device's clear at a handle marked on the first is forwarded (its mock + // list then takes the view as invalid, which is what that device was told). + Mock* other_mock = nullptr; + void* other = make_device(other_mock, 9, true, true, true); + EXPECT(other); + void* other_allocator = nullptr; + EXPECT(hr_of(raw(other, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&allocator_iid), word(&other_allocator))) == S_OK); + void* other_list = nullptr; + EXPECT(hr_of(raw(other, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, word(other_allocator), 0, word(&gcl_iid), + word(&other_list))) == S_OK); + Mock* const other_real = reinterpret_cast(xs::list_proxy_real_list(other_list)); + raw(other_list, 52, rtv_none, word(color), 0, 0); + EXPECT(other_real->calls[48] == 1 && other_real->args[48][0] == rtv_none); + + EXPECT(release(other_list) == 0 && other_real->refs == 0); + EXPECT(release(other_allocator) == 0); + EXPECT(release(other) == 0 && other_mock->refs == 0); + EXPECT(release(list) == 0 && real->refs == 0); + EXPECT(release(allocator) == 0); + EXPECT(release(device) == 0 && mock->refs == 0); + g_mock_null_rtv_count = 0; + std::printf("%s: list slot 146 turns texture barriers with no resource into global barriers (valid groups pass " + "unchanged, unreadable ones are refused whole) and slot 52 skips the clear of an RTV made with no " + "resource; the list stays valid\n", + g_label); + return 0; +} + // ---- 11. Presentation handler wiring (device slots 78–81 + queue PresentX/SuspendX/ResumeX) ---- struct MockPresenter { @@ -5010,6 +5319,7 @@ int main(int argc, char** argv) { check_slot74() || check_xbox_queue_slots() || check_list_cpu_handles() || + check_console_null_barrier_and_clear() || check_presentation_wiring() || check_queue_copy_page_mappings()) return 1; if (check_placed_resource_x() || check_depth_provider_refusal()) return 1; diff --git a/scripts/windows-boot/README.md b/scripts/windows-boot/README.md index 3a875af4bb..92121a2110 100644 --- a/scripts/windows-boot/README.md +++ b/scripts/windows-boot/README.md @@ -15,7 +15,7 @@ powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DryRun -GameDir D:\GT powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv # Extra or changed switches: trailing KEY=VALUE arguments (KEY= removes one), as run-boot.sh takes them. -powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name split -Seconds 120 LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=0x7446510,0x98f828c,0x78b2818" +powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name split -Seconds 120 LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=,," # Every parameter. Get-Help -Full .\scripts\windows-boot\boot.ps1 @@ -38,7 +38,7 @@ Only when your shell has not set them already (`-DryRun` prints the final list): | `LEONIDA_PIPELINE_CACHE_BYTES` | `4294967296` | pipeline cache size limit | | `LEONIDA_STARTUP_CACHE_CHECKPOINTS` | `1` | save the pipeline cache during startup | | `LEONIDA_PIPELINE_CACHE_DIR` | `\pipeline-cache` | one warmed cache shared by every build you boot | -| `LEONIDA_PEEK` / `_SECONDS` | `0x7446510,0x98f828c` / `5` | game state and session state (low dword), the two numbers every RESULT reports | +| `LEONIDA_PEEK` / `_SECONDS` | the game-state and session-state RVAs from `LEONIDA_GAME_STATE_RVA` and `LEONIDA_SESSION_STATE_RVA` (measured locally, not kept here; unset: no peek) / `5` | game state and session state (low dword), the two numbers every RESULT reports | | `LEONIDA_DEVICE_FAULT` | `1` | on device loss: `VK_EXT_device_fault` info, checkpoints, last replay steps | | `LEONIDA_KEYBOARD_PAD` | `always` (with an input script) | keyboard as a pad even unfocused, so the script's presses arrive | | `LEONIDA_CAPTURE_EVERY` / `_LIMIT` | `60` / `40` | a swapchain read-back every 60 presents, at most 40 | @@ -72,8 +72,15 @@ frames: 14 captured, 0 non-black; last mean rgb 0.00 0.00 0.00; brightest 0.00 states only, which is what goes into a RESULT on the board; the logs, traces, captures and dumps can quote the game and stay on your machine ([AGENTS.md](../../AGENTS.md), "No game data"). -How to read the states: game state `0x7446510` goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing -screen waiting for A), `d` after A. `docs/linux_proton.md` (the same stages apply natively) +How to read the states: game state goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing +screen waiting for A), `d` after A. + +**Changed: the states need two variables now.** The script used to set `LEONIDA_PEEK` to the game-state and +session-state RVAs by default. Those addresses of the retail executable are no longer kept in the repository, so set +`LEONIDA_GAME_STATE_RVA` and `LEONIDA_SESSION_STATE_RVA` (hex, measured locally) in the shell before the boot. +Without them the script warns, sets no `LEONIDA_PEEK`, and the `states:` line and the RESULT show `game=? +session=?`. A `LEONIDA_PEEK` of your own still works for the log, but the digest reads only the two RVAs those +variables name. `docs/linux_proton.md` (the same stages apply natively) section 2 has the healthy sequence with times and section 3 "which blank do you have". ## One game at a time diff --git a/scripts/windows-boot/boot.ps1 b/scripts/windows-boot/boot.ps1 index d052a79da9..7863054b32 100644 --- a/scripts/windows-boot/boot.ps1 +++ b/scripts/windows-boot/boot.ps1 @@ -66,7 +66,7 @@ .PARAMETER EnvPairs Any further arguments, each KEY=VALUE, as scripts/linux-boot/run-boot.sh takes them. These work with - powershell -File too: ... -Name x LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=0x7446510,0x75e8eb0". + powershell -File too: ... -Name x LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=,". Applied after -SetEnv. KEY= removes the variable for this boot. .PARAMETER NoCapture @@ -97,7 +97,7 @@ powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv .EXAMPLE - powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name stall -Seconds 90 -Stacks 40,80 "LEONIDA_PEEK=0x7446510,0x75e8eb0,0x75e8ea0,0x9844898" + powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name stall -Seconds 90 -Stacks 40,80 "LEONIDA_PEEK=," .EXAMPLE powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DigestOnly -Name first @@ -234,7 +234,8 @@ $defaults = [ordered]@{ LEONIDA_PIPELINE_CACHE_BYTES = "4294967296" LEONIDA_STARTUP_CACHE_CHECKPOINTS = "1" LEONIDA_PIPELINE_CACHE_DIR = (Join-Path $OutDir "pipeline-cache") - LEONIDA_PEEK = "0x7446510,0x98f828c" # game state, session state (low dword) + # LEONIDA_PEEK: the game-state and session-state RVAs (measured locally, not kept in the repository) when + # LEONIDA_GAME_STATE_RVA and LEONIDA_SESSION_STATE_RVA name them; see below. LEONIDA_PEEK_SECONDS = "5" LEONIDA_DEVICE_FAULT = "1" # device-loss report (VK_EXT_device_fault, checkpoints) LEONIDA_CAPTURE_EVERY = "60" @@ -243,6 +244,14 @@ $defaults = [ordered]@{ DISABLE_VULKAN_OBS_CAPTURE = "1" } if ($InputScript) { $defaults["LEONIDA_KEYBOARD_PAD"] = "always" } +$gameStateRva = "$env:LEONIDA_GAME_STATE_RVA".ToLowerInvariant() -replace '^0x', '' +$sessionStateRva = "$env:LEONIDA_SESSION_STATE_RVA".ToLowerInvariant() -replace '^0x', '' +if ($gameStateRva -and $sessionStateRva) { $defaults["LEONIDA_PEEK"] = "0x$gameStateRva,0x$sessionStateRva" } +else { + # The two RVAs were built in until they were taken out of the repository; say so rather than report "?" silently. + Write-Warning ("LEONIDA_GAME_STATE_RVA and LEONIDA_SESSION_STATE_RVA are not both set: no LEONIDA_PEEK by default, " + + "so the RESULT game and session states read '?' (scripts/windows-boot/README.md)") +} # Per-run values: always this script's (from its parameters), whatever the shell has. $perRun = [ordered]@{ LEONIDA_CAPTURE = $(if ($NoCapture) { "" } else { $Capture }) @@ -393,8 +402,8 @@ if (Test-Path -LiteralPath $LogFile) { $game = "?"; $session = "?" foreach ($v in $valRx.Matches($m.Groups[2].Value)) { $rva = $v.Groups[1].Value; $val = $v.Groups[2].Value - if ($rva -eq "7446510") { $game = $val } - elseif ($rva -eq "98f828c" -and $val -ne "?") { + if ($gameStateRva -and $rva -eq $gameStateRva) { $game = $val } + elseif ($sessionStateRva -and $rva -eq $sessionStateRva -and $val -ne "?") { $low = $val.PadLeft(16, '0').Substring(8).TrimStart('0') # the session state is the low dword $session = $(if ($low) { $low } else { "0" }) } diff --git a/tests/semantic/test_alu_dot4_i8.py b/tests/semantic/test_alu_dot4_i8.py index e0e23f883c..a074ad8f25 100644 --- a/tests/semantic/test_alu_dot4_i8.py +++ b/tests/semantic/test_alu_dot4_i8.py @@ -15,7 +15,9 @@ op_sel 2 and op_sel_hi 5, which llvm-mc does not decode (docs/fspx.md). Run on the same hardware as two raw words (0xCC165008 0x0C0E0501: v8 = v1 . v2 + v3 with those fields), that form gave the words of MEASURED_OP_SEL: the dot product with the two 16-bit halves of the second source exchanged, as op_sel selects halves for the packed 16-bit -ops. `ref_op_sel` reproduces them. The translator recovers this form from its binary when LLVM omits it. +ops. `ref_op_sel` reproduces them. A listing carries the form since tools/shader_disasm.py prints it +(tests/semantic/test_fspx_dot4_op_sel_disasm.py), and the translator also recovers it from the binary when a +listing lacks it (rdna2spirv.skipped_form). neg_lo and neg_hi. llvm-mc accepts them on v_dot4_i32_i8 for gfx1036 (not on v_dot4c_i32_i8), and the hardware does not ignore them: on the same GPU, 5 operand sets with 8 forms each gave the words of `ref_neg`, 9 of which are in diff --git a/tests/semantic/test_dot4_printed_op_sel.py b/tests/semantic/test_dot4_printed_op_sel.py new file mode 100644 index 0000000000..f25c12be66 --- /dev/null +++ b/tests/semantic/test_dot4_printed_op_sel.py @@ -0,0 +1,130 @@ +"""A v_dot4_i32_i8 whose op_sel/op_sel_hi llvm-mc printed as the defaults: only the measured forms translate. + +llvm-mc decodes a VOP3P v_dot4_i32_i8 with op_sel_hi other than [1,1,1] (op_sel bit 1 clear) but prints and +re-encodes it with op_sel 0 and op_sel_hi 7, so the listing names halves the instruction does not read. The +translator takes the stored field back for one form only: op_sel_hi 5 with an inline integer second source +(rdna2spirv.restore_dot4_inline_sel, counted over the FidelityFX programs; docs/design.md, "Signed-byte dot +products"). The one form measured on hardware, op_sel 2 / op_sel_hi 5, is a word llvm-mc rejects, which +tools/shader_disasm.py prints (test_fspx_dot4_op_sel_disasm.py). Every other form, such as op_sel_hi 5 with a VGPR +second source, is not measured and stays refused. Hand-built listing and blob, the encodings assembled from the VOP3P +field layout; no game data. + + python -I tests/semantic/test_dot4_printed_op_sel.py -v +""" +import os +import struct +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +from support import mrt0_words, rdna2spirv, translate_listing # noqa: E402 + +NAME = "ps_dot4_printed_op_sel" +CODE_START = 0x100 +A, B, C = 0x80FF7F01, 0x12F0FE7F, 0x00001000 +INLINE = 5 # inline integer constant 5: source field 128 + 5 + + +def src_field(src): + """VOP3P source field: a VGPR number, or ("int", n) for an inline integer constant 0..64.""" + return 128 + src[1] if isinstance(src, tuple) else 256 + src + + +def dot4(op_sel=0, op_sel_hi=7, dst=0, srcs=(1, 2, 3)): + """VOP3P v_dot4_i32_i8 (opcode 0x16) vdst, srcs with the given op_sel and op_sel_hi.""" + w0 = 0xCC000000 | (0x16 << 16) | ((op_sel_hi >> 2) & 1) << 14 | (op_sel & 7) << 11 | dst + w1 = ((op_sel_hi & 3) << 27 | src_field(srcs[2]) << 18 | src_field(srcs[1]) << 9 | src_field(srcs[0])) + return struct.pack("<2I", w0, w1).hex(" ") + + +def v_mov(reg, value): + return (f"v_mov_b32_e32 v{reg}, 0x{value:x}", f"ff {2 * reg:02x} 02 7e " + struct.pack("> off) & 0xFF + return v - 256 if v & 0x80 else v + total = addend + for k in range(4): + half = (op_sel if k < 2 else op_sel_hi) + xo = 16 * ((half >> 0) & 1) + 8 * (k & 1) + yo = 16 * ((half >> 1) & 1) + 8 * (k & 1) + total += byte(a, xo) * byte(b, yo) + return total & 0xFFFFFFFF + + +def translate(stored_dot4, printed=PRINTED_VGPR, reanchor=False): + listed = SETUP + [printed] + TAIL + stored = SETUP + [("", stored_dot4)] + TAIL + code = b"".join(bytes.fromhex(enc) for _, enc in stored) + data = listing(listed, CODE_START + len(code)) + blob = bytes(CODE_START) + code + if reanchor: # a listing with an undecodable word after the code goes through the re-anchoring path + data += b"; warning: invalid instruction encoding\n" + blob += b"\xff" * 4 + return translate_listing(NAME, data, fssm=blob) + + +class Dot4PrintedOpSelTest(unittest.TestCase): + def test_reference_is_the_plain_dot_product_for_the_defaults(self): + sb = [lambda x, k=k: (((x >> 8 * k) & 0xFF) ^ 0x80) - 0x80 for k in range(4)] + self.assertEqual(ref(A, B, C), (sum(f(A) * f(B) for f in sb) + C) & 0xFFFFFFFF) + + def test_default_fields_translate_as_printed(self): + self.assertEqual(mrt0_words(translate(dot4())), [ref(A, B, C)] * 4) + + def test_inline_integer_s1_keeps_its_stored_op_sel_hi(self): + # op_sel_hi [1,0,1] with an inline integer S1: byte pairs 2..3 of S1 come from its low half, the halves the + # measured op_sel 2 / op_sel_hi 5 form selects. llvm-mc prints [1,1,1]; restore_dot4_inline_sel takes it back. + stored = dot4(op_sel_hi=5, srcs=(1, ("int", INLINE), 3)) + for reanchor in (False, True): + with self.subTest(reanchor=reanchor): + got = mrt0_words(translate(stored, PRINTED_INLINE, reanchor)) + self.assertEqual(got, [ref(A, INLINE, C, op_sel_hi=5)] * 4) + self.assertNotEqual(ref(A, INLINE, C, op_sel_hi=5), ref(A, INLINE, C)) + + def test_unmeasured_forms_stay_refused(self): + # Not measured on hardware and not the inline-integer form: refused, in a clean listing (a dropped field) + # and when re-anchoring (the stored word never matches the printed one). + for name, stored in (("op_sel_hi 5, VGPR S1", dot4(op_sel_hi=5)), + ("op_sel 1 / op_sel_hi 6", dot4(op_sel=1, op_sel_hi=6)), + ("op_sel_hi 4", dot4(op_sel_hi=4)), + ("non-default S2 half", dot4(op_sel_hi=3))): + for reanchor in (False, True): + with self.subTest(form=name, reanchor=reanchor): + with self.assertRaises(rdna2spirv.Unsupported) as cm: + translate(stored, reanchor=reanchor) + if not reanchor: + self.assertIn("dropped", str(cm.exception)) + + def test_inline_form_with_another_difference_is_refused(self): + # The stored word names v4 as S2, the printed one v3: not just the op_sel_hi field. + with self.assertRaises(rdna2spirv.Unsupported) as cm: + translate(dot4(op_sel_hi=5, srcs=(1, ("int", INLINE), 4)), PRINTED_INLINE) + self.assertIn("dropped", str(cm.exception)) + + def test_the_general_rule_is_not_there(self): + self.assertFalse(hasattr(rdna2spirv, "dot4_op_sel_fields")) + self.assertTrue(callable(rdna2spirv.restore_dot4_inline_sel)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_fspx_dot4_op_sel_disasm.py b/tests/semantic/test_fspx_dot4_op_sel_disasm.py new file mode 100644 index 0000000000..f27b9f9403 --- /dev/null +++ b/tests/semantic/test_fspx_dot4_op_sel_disasm.py @@ -0,0 +1,157 @@ +"""The FidelityFX upscaler's programs (docs/fspx.md) hold 89 v_dot4_i32_i8 words with op_sel 2 and op_sel_hi 5, which +llvm-mc does not decode: it rejects the first dword, reads the second as another instruction, and the translator then +refuses the program ("fall-through into undecodable words"), so 9 of the 29 programs had no pipeline and the DLL's +next pipeline call faulted. tools/shader_disasm.py now prints such a word as the instruction it is, with its +op_sel/op_sel_hi fields and its real encoding, so the translator reads it and checks it against the blob. + +Each case assembles a small program with llvm-mc, turns one v_dot4_i32_i8 into the op_sel 2 / op_sel_hi 5 form by +setting those fields in its two dwords, disassembles the bytes with shader_disasm, and translates the listing in the +FSPX layout (disasm/, fspx/.code and .json). The expected words are the ones measured on gfx1036 +(MEASURED_OP_SEL in test_alu_dot4_i8.py). They need llvm-mc with the AMDGPU target (LLVM_MC, or llvm-mc on PATH) and +skip without it. No GPU and no game files. + + python -I tests/semantic/test_fspx_dot4_op_sel_disasm.py +""" +import json +import os +import struct +import subprocess +import sys +import tempfile +import unittest +import warnings + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +sys.dont_write_bytecode = True +sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) +sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import shader_disasm # noqa: E402 +import spirv_mini_interp as si # noqa: E402 +from test_alu_dot4_i8 import MEASURED_OP_SEL, ref # noqa: E402 + +MCPU = "gfx1030" # fspx_unpack.py's default: LLVM decodes v_dot4_i32_i8 for it and not for gfx1013 +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 2) << 14 + w1 = w1 & ~(3 << 27) | (op_sel_hi & 3) << 27 + return struct.pack("<2I", w0, w1) + + +def program(a, b, addend, middle): + """Code bytes of: v8 = the v_dot4_i32_i8 given by `middle` (its two dwords), v9 = the plain v_dot4_i32_i8 on the + same registers, both written to mrt0. Returns (code, byte offset of the first dot4).""" + head = b"".join(assemble(line) for line in ( + f"v_mov_b32_e32 v1, 0x{a:08x}", f"v_mov_b32_e32 v2, 0x{b:08x}", f"v_mov_b32_e32 v3, 0x{addend:08x}")) + tail = b"".join(assemble(line) for line in ( + "v_dot4_i32_i8 v9, v1, v2, v3", "exp mrt0 v8, v9, v8, v9 done vm", "s_endpgm")) + return head + middle + tail, len(head) + + +def translate_fspx(name, listing, code): + """SPIR-V assembly for a listing in the FSPX layout, with the code bytes it was disassembled from beside it.""" + with tempfile.TemporaryDirectory() as tmp: + for d in ("disasm", "fspx"): + os.mkdir(os.path.join(tmp, d)) + with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: + f.write(STUB_DXBC) + with open(os.path.join(tmp, "fspx", name + ".code"), "wb") as f: + f.write(code) + with open(os.path.join(tmp, "fspx", name + ".json"), "w", encoding="utf-8", newline="\n") as f: + json.dump({}, f) + src = os.path.join(tmp, "disasm", name + ".s") + with open(src, "w", encoding="utf-8", newline="\n") as f: + f.write(listing) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + return rdna2spirv.translate(src) + + +def listing_of(name, code): + asm, bad, err = shader_disasm.disasm(code, MCPU) + return f"; {name} code 0x0..0x{len(code):x} (fspx), {MCPU}, {bad} invalid words\n" + asm, bad + + +@unittest.skipUnless(llvm_decodes_v_dot4(), "needs llvm-mc with the AMDGPU target that decodes v_dot4_i32_i8") +class Dot4OpSelListing(unittest.TestCase): + def plain_pair(self): + return assemble("v_dot4_i32_i8 v8, v1, v2, v3") + + def test_the_listing_carries_the_op_sel_word_and_the_program_runs(self): + for a, b, addend, measured in MEASURED_OP_SEL: + with self.subTest(a=f"{a:#010x}", b=f"{b:#010x}", addend=f"{addend:#010x}"): + middle = with_op_sel(self.plain_pair(), 2, 5) + code, at = program(a, b, addend, middle) + listing, bad = listing_of("ps_fspx_dot4_op_sel", code) + self.assertEqual(bad, 0, listing) + lines = [ln for ln in listing.splitlines() if "v_dot4_i32_i8" in ln] + self.assertEqual(len(lines), 2, listing) + self.assertIn("v_dot4_i32_i8 v8, v1, v2, v3 op_sel:[0,1,0] op_sel_hi:[1,0,1]", lines[0]) + self.assertIn("encoding: [" + ",".join(f"0x{x:02x}" for x in middle) + "]", lines[0]) + self.assertNotIn("op_sel", lines[1]) # the plain instruction next to it stays plain + words = support_words(translate_fspx("ps_fspx_dot4_op_sel", listing, code)) + self.assertEqual(words, [measured, ref(a, b, addend), measured, ref(a, b, addend)]) + + def test_other_op_sel_values_stay_undecodable(self): + # Only op_sel 2 / op_sel_hi 5 was measured on hardware; anything else is still rejected, never guessed. + for op_sel, op_sel_hi in ((1, 5), (4, 5), (2, 7), (0, 5), (2, 4)): + with self.subTest(op_sel=op_sel, op_sel_hi=op_sel_hi): + code, _ = program(1, 1, 0, with_op_sel(self.plain_pair(), op_sel, op_sel_hi)) + listing, bad = listing_of("ps_fspx_dot4_other", code) + self.assertNotIn("op_sel:[0,1,0] op_sel_hi:[1,0,1]", listing) + with self.assertRaises(rdna2spirv.Unsupported): # undecodable, or printed without a dropped field + translate_fspx("ps_fspx_dot4_other", listing, code) + + def test_a_clamp_or_neg_bit_on_the_word_stays_undecodable(self): + for name, shift, dword in (("clamp", 15, 0), ("neg_hi", 8, 0), ("neg_lo", 29, 1)): + with self.subTest(field=name): + middle = list(struct.unpack("<2I", with_op_sel(self.plain_pair(), 2, 5))) + middle[dword] |= 1 << shift + code, _ = program(1, 1, 0, struct.pack("<2I", *middle)) + listing, bad = listing_of("ps_fspx_dot4_mods", code) + self.assertGreaterEqual(bad, 1) + self.assertNotIn("op_sel:[0,1,0]", listing) + + def test_data_that_looks_like_the_word_is_left_alone(self): + # The same two dwords as a 32-bit literal and the instruction after it decode with no invalid word, so they + # are not touched: only a word llvm-mc rejected is read as v_dot4_i32_i8. + pair = struct.unpack("<2I", with_op_sel(self.plain_pair(), 2, 5)) + code = (assemble("v_mov_b32_e32 v4, 0x%08x" % pair[0]) + assemble("v_fmac_legacy_f32 v7, v1, v2") + + assemble("s_endpgm")) + self.assertEqual(struct.unpack_from("<2I", code, 4), pair) + listing, bad = listing_of("ps_fspx_dot4_literal", code) + self.assertEqual(bad, 0, listing) + self.assertNotIn("op_sel", listing) + + +def support_words(spv): + out = si.run_fragment(spv) + return list(out["%out_mrt0"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_lane_mask_bitreplicate_flbit.py b/tests/semantic/test_lane_mask_bitreplicate_flbit.py index 66743bd2cc..ecc55775b2 100644 --- a/tests/semantic/test_lane_mask_bitreplicate_flbit.py +++ b/tests/semantic/test_lane_mask_bitreplicate_flbit.py @@ -4,6 +4,8 @@ RDNA2 ISA, SOP1: - s_bitreplicate_b64_b32: D[2i+1] = D[2i] = S0[i], i in 0..31; SCC is not written. Into VCC, lane L's bit is S0 bit L // 2. + Of a 32-bit lane-mask source (exec_lo/exec_hi, vcc_lo/vcc_hi) into scalar data, S0 is that half of the wave's + mask, read as data (Gen.wave_mask), then replicated as any scalar. - s_flbit_i32_b64: the zeros above the first 1 from bit 63, -1 when S0 is 0. Of EXEC that is 63 minus the wave's last active lane. Synthetic programs only. @@ -60,6 +62,36 @@ def test_flbit_of_vcc(self): "s_endpgm"]) self.assertEqual(mem[OUT_AT], flbit_model((1 << n) - 1)) + def bitreplicate_of(self, setup, src): + mem = run(lane_index() + setup + [f"s_bitreplicate_b64_b32 s[10:11], {src}", "s_mov_b64 exec, -1", + "v_cmpx_eq_u32_e32 0, v1", "v_mov_b32_e32 v20, s10", + "v_mov_b32_e32 v22, s11", f"v_mov_b32_e32 v21, {OUT_AT}", + "buffer_store_dword v20, v21, s[0:3], 0 offen", + "buffer_store_dword v22, v21, s[0:3], 0 offen offset:4", "s_endpgm"]) + return mem[OUT_AT] | mem[OUT_AT + 4] << 32 + + def test_bitreplicate_of_exec_half_into_data(self): + # Every lane that runs the instruction reads the same 32 mask bits; each becomes two bits of s[10:11]. + for mask in (h.ALL64, 0x00000000FFFFFFFF, 0xFFFFFFFF00000000, 0x8000000180000001, 0x0F0F0F0F12345678): + for half, src in ((0, "exec_lo"), (1, "exec_hi")): + with self.subTest(exec=hex(mask), src=src): + word = (mask >> (32 * half)) & 0xFFFFFFFF + got = self.bitreplicate_of([f"s_mov_b32 exec_lo, {mask & 0xFFFFFFFF:#x}", + f"s_mov_b32 exec_hi, {mask >> 32:#x}"], src) + self.assertEqual(got, bitreplicate_model(word)) + + def test_bitreplicate_of_a_compare_into_data(self): + # VCC from a compare: lanes l < n. Its low and high halves replicated as data. + for n in (0, 1, 17, 32, 45, 64): + for half, src in ((0, "vcc_lo"), (1, "vcc_hi")): + with self.subTest(n=n, src=src): + got = self.bitreplicate_of([f"v_cmp_gt_u32_e32 vcc, {n}, v1"], src) + self.assertEqual(got, bitreplicate_model((((1 << n) - 1) >> (32 * half)) & 0xFFFFFFFF)) + + +def bitreplicate_model(word): + return sum(3 << (2 * i) for i in range(32) if (word >> i) & 1) + if __name__ == "__main__": unittest.main() diff --git a/tests/semantic/test_salu_flbit_64.py b/tests/semantic/test_salu_flbit_64.py index 3f46cb567e..3ee0e42f52 100644 --- a/tests/semantic/test_salu_flbit_64.py +++ b/tests/semantic/test_salu_flbit_64.py @@ -123,7 +123,7 @@ def test_inline_source(self): self.assertEqual(run_lines(["s_flbit_i32_b64 s0, 1"])[0], 63) self.assertEqual(run_lines(["s_flbit_i32_i64 s0, -1"])[0], M32) - # b64 of a lane mask reads the whole wave's mask: tests/semantic/test_lane_mask_bitreplicate_flbit.py. + # b64 of a lane mask in wave64 reads the whole wave's mask: tests/semantic/test_lane_mask_bitreplicate_flbit.py. def test_signed_lane_mask_source_is_rejected(self): with self.assertRaises(rdna2spirv.Unsupported): run_lines(["s_flbit_i32_i64 s0, exec"]) diff --git a/tests/semantic/test_salu_quadmask_bitreplicate.py b/tests/semantic/test_salu_quadmask_bitreplicate.py index 9fa67cbbfb..3af4a0ab5b 100644 --- a/tests/semantic/test_salu_quadmask_bitreplicate.py +++ b/tests/semantic/test_salu_quadmask_bitreplicate.py @@ -155,6 +155,14 @@ def test_seeded(self): self.assertEqual(run([f"s_mov_b32 s2, {lo:#x}", "s_bitreplicate_b64_b32 s[10:11], s2"])[:2], (bitreplicate(lo) & M32, bitreplicate(lo) >> 32)) + def test_bitreplicate_into_vcc_in_wave32_is_refused(self): + # In wave32 VCC's high word is data, which a lane mask cannot carry; the wave64 form runs on every lane in + # tests/semantic/test_lane_mask_bitreplicate_flbit.py. + with self.assertRaises(rdna2spirv.Unsupported): + translate(["s_bitreplicate_b64_b32 vcc, 0x0f0f0f0f", + "v_cndmask_b32_e64 v0, 0x40000000, 0x40000001, vcc", + "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]) + def test_lane_masks_rejected(self): for lines in (["v_cmp_gt_u32_e32 vcc, 5, v0", "s_quadmask_b64 s[10:11], vcc"], ["s_quadmask_b32 s10, exec_lo"], diff --git a/tests/semantic/test_vcc_tuple_fallback.py b/tests/semantic/test_vcc_tuple_fallback.py index e0d232c3f1..2e0f0041a6 100644 --- a/tests/semantic/test_vcc_tuple_fallback.py +++ b/tests/semantic/test_vcc_tuple_fallback.py @@ -139,6 +139,39 @@ def test_image_resource_in_vcc(self): with self.subTest(printed_as=variant): self.assertRegex(translate(program, variant), r"OpFunctionCall %\w+ %desc_lookup_fn") + def test_load_with_register_offset_into_vcc(self): + # The widened scalar load with an SGPR soffset and an immediate offset (the form luizwidmer/palmetto's + # docs/boot_frontier.md measured in an FSPX program, built here from the field layout, not copied): + # s_buffer_load_dwordx8 [s100..s105,vcc_lo,vcc_hi], s[4:7], s12 offset:0x40 reads BASE + 0x40 + s12. + load = "02 19 2c f4 40 00 00 18" + program = [SET_SGPR_V[0], SET_SGPR_V[1], ("s_mov_b32 s6, 0x100", "ff 03 86 be 00 01 00 00"), SET_SGPR_V[3], + ("s_mov_b32 s12, 32", "a0 03 8c be"), + (None, load), WAIT, + ("v_mov_b32_e32 v10, s100", "64 02 14 7e"), ("v_mov_b32_e32 v11, s105", "69 02 16 7e"), + ("v_mov_b32_e32 v12, vcc_lo", "6a 02 18 7e"), ("v_mov_b32_e32 v13, vcc_hi", "6b 02 1a 7e"), + ] + STORE_X4 + words = [0x22220000 + i for i in range(8)] + for variant in PROGRAM_VARIANTS: + with self.subTest(printed_as=variant): + mem = run(translate(program, variant), {BASE + 0x60 + 4 * i: w for i, w in enumerate(words)}) + self.assertEqual([mem.get(OUT + 4 * i) for i in range(4)], [words[0], words[5], words[6], words[7]]) + + def test_buffer_store_with_resource_in_vcc(self): + # buffer_store_dword v11, v1, [s104,s105,vcc_lo,vcc_hi], 0 offen: a store through the widened resource too. + store = "00 10 70 e0 01 0b 1a 80" + program = SET_SGPR_V + [ + (None, LOAD_X4_VCC), WAIT, + ("v_mov_b32_e32 v1, 4", "84 02 02 7e"), + ("v_mov_b32_e32 v11, 0x5a5a1234", "ff 02 16 7e 34 12 5a 5a"), + (None, store), WAIT_V, + ("s_endpgm", "00 00 81 bf"), + ] + memory = {BASE + 4 * i: w for i, w in enumerate([OUT, 0, 16, 0x30000000])} + for variant in PROGRAM_VARIANTS: + with self.subTest(printed_as=variant): + mem = run(translate(program, variant), memory) + self.assertEqual(mem.get(OUT + 4), 0x5A5A1234) + def test_junk_that_swallows_the_next_instructions(self): # The junk at the tuple's second word is longer than that word, so it covers the s_mov_b32 after the tuple # (and the first word of the 8-byte one after that, whose literal then prints as junk too). None of them is diff --git a/tests/test_fspx_unpack.py b/tests/test_fspx_unpack.py index 946da380cf..248a9e37ac 100644 --- a/tests/test_fspx_unpack.py +++ b/tests/test_fspx_unpack.py @@ -144,6 +144,33 @@ def test_code_range(self): self.assertEqual(fspx_unpack.code_range(program(with_prologue=False)), (0, 12 + 4)) self.assertEqual(fspx_unpack.code_range(program(endpgm=False))[1], None) + def test_short_prologue(self): + # The 24-byte prologue of some pipeline-library programs: hash carriers at words 0 and 3 only, each a VOP3 + # opcode-0x180 word with a literal in the form tools/fspx_prologue_probe.py checks, then the code at word 6. + carrier = struct.pack(".json the decoded kind-0 entry, the directory and the code range DIR/fspx/.code the kind-6 program DIR/fspx/.state the kind-0 entry as it is (its SHA-256 is the index's fspx_state_sha256) - DIR/disasm/.s with --disasm: tools/shader_disasm.py output for the code after the prologue + DIR/disasm/.s with --disasm: tools/shader_disasm.py output for the code after the prologue (36 or 24 bytes) """ import argparse import json @@ -46,6 +46,11 @@ # kind-7 hash; llvm-mc rejects them. Measured on all 29 shaders of the 1.0.2.1 DLL (docs/fspx.md). PROLOGUE_WORDS = (0, 3, 6) PROLOGUE_SIZE = 36 +# Some programs of the pipeline library in shaders.rpf carry only two of those words (0 and 3): a 24-byte prologue, with +# the code starting at word 6 (50 of the 2,684 library programs of 1.0.2.1, docs/fspx.md). Read from word 0 they never +# decode. +SHORT_PROLOGUE_WORDS = (0, 3) +SHORT_PROLOGUE_SIZE = 24 STAGE_COMPUTE = 5 # PSVRuntimeInfo1 ShaderStage (DirectX): 5 = compute @@ -141,21 +146,34 @@ def decode_kind0(b: bytes) -> dict: def code_range(code: bytes): - """(start, end) of the instructions in a kind-6 program: after the 36-byte prologue when it is there, through + """(start, end) of the instructions in a kind-6 program: after the 36- or 24-byte prologue when it is there, through the first s_endpgm. end is None when the program has no s_endpgm.""" words = struct.unpack_from(f"<{len(code) // 4}I", code) start = PROLOGUE_SIZE if len(words) > 8 and all(words[k] >> 16 == 0xD580 for k in PROLOGUE_WORDS) else 0 # Some pipeline programs have only the two hash carriers. Both must be literal-bearing # VOP3 NOPs of the form in fspx_prologue_probe; the first body instruction starts at byte 24. if not start and len(words) >= 6 and all( - words[k] >> 16 == 0xD580 and words[k + 1] & 0xFFFE0100 == 0x03FE0100 for k in (0, 3)): - start = 24 + words[k] >> 16 == 0xD580 and words[k + 1] & 0xFFFE0100 == 0x03FE0100 for k in SHORT_PROLOGUE_WORDS): + start = SHORT_PROLOGUE_SIZE pos = code.find(ENDPGM, start) while pos >= 0 and pos % 4: pos = code.find(ENDPGM, pos + 1) return start, (pos + 4 if pos >= 0 else None) +def code_range_last(code: bytes): + """code_range through the last 4-byte-aligned s_endpgm instead of the first, as shader_library.code_range: a + program with an early exit branches to code after its first s_endpgm (28 of the 50 pipeline-library programs the + runtime dumped as untranslated: "branch target outside code").""" + start, first = code_range(code) + if first is None: + return start, None + last = code.rfind(ENDPGM) + while last >= first and (last - start) % 4: + last = code.rfind(ENDPGM, 0, last) + return start, max(first, last + 4) + + def psv_stage(container_parts: dict): """PSVRuntimeInfo1 ShaderStage, or None (PSV0 = u32 size of the runtime info, then the info).""" psv = container_parts.get(b"PSV0", b"") @@ -165,12 +183,49 @@ def psv_stage(container_parts: dict): return psv[4 + 24] if size > 24 and len(psv) > 4 + 24 else None -def unpack_payload(payload: bytes): +def branch_targets_inside(asm: str, size: int) -> bool: + """Whether every s_branch / s_cbranch_* of a shader_disasm.py listing lands inside [0, size).""" + pc = 0 + for line in asm.splitlines(): + if "; encoding: [" not in line: + continue + text, enc = line.split("; encoding: [", 1) + length = enc.count(",") + 1 + parts = text.split() + if parts and (parts[0] == "s_branch" or parts[0].startswith("s_cbranch_")) and len(parts) > 1: + try: + k = int(parts[1].rstrip(","), 0) + except ValueError: + k = None + if k is not None: + if k > 0x7FFF: + k -= 0x10000 + target = pc + 4 + 4 * k + if not 0 <= target < size: + return False + pc += length + return True + + +def branch_closed_end(code: bytes, start: int, mcpu: str, disasm) -> int | None: + """The end (after its s_endpgm) of the shortest range from `start` through an aligned s_endpgm whose branches all + stay inside it, or None. Tried from the first s_endpgm on.""" + pos = code.find(ENDPGM, start) + while pos >= 0: + if (pos - start) % 4 == 0: + asm, invalid, _ = disasm.disasm(code[start:pos + 4], mcpu, compute=True) + if asm.strip() and branch_targets_inside(asm, pos + 4 - start): + return pos + 4 + pos = code.find(ENDPGM, pos + 1) + return None + + +def unpack_payload(payload: bytes, last_endpgm: bool = False): status, entries = parse_fspx(payload) if status: return None, status blob = {k: payload[o:o + s] for k, (o, s) in entries.items()} - start, end = code_range(blob[6]) + start, end = (code_range_last if last_endpgm else code_range)(blob[6]) meta = { "version": struct.unpack_from(" int: ap.add_argument("--mcpu", default="gfx1030", help="llvm-mc CPU for --disasm (default gfx1030: the programs use v_dot4 instructions, which " "gfx1010 and gfx1013 do not decode)") + ap.add_argument("--last-endpgm", action="store_true", + help="end each program at its last s_endpgm, not its first (pipeline-library programs the " + "runtime dumped with LEONIDA_DUMP_MISSING: early exits branch past the first)") a = ap.parse_args(argv) # An output in the input folder can replace a .dxbc input and, when the input is the folder itself, # os.makedirs writes there before open() tries to read the folder as a file. Refuse before either. @@ -236,7 +294,7 @@ def main(argv=None) -> int: continue for n, (off, container, payload) in enumerate(items): name = f"{stem}_{n:02d}" if len(items) > 1 else stem - got, status = unpack_payload(payload) + got, status = unpack_payload(payload, a.last_endpgm) if not got: print(f"{name}: FSPX status {status}", file=sys.stderr) bad += 1 @@ -259,7 +317,13 @@ def main(argv=None) -> int: listing = None if disasm and meta["code"]["end"]: start, end = meta["code"]["start"], meta["code"]["end"] - asm, invalid, err = disasm.disasm(blob[6][start:end], a.mcpu, wave32=meta.get("wave32", True)) + if a.last_endpgm: + # The last s_endpgm can lie in data after the code; the first s_endpgm whose listing keeps + # every branch inside the code is the program's end. + end = branch_closed_end(blob[6], start, a.mcpu, disasm) or end + meta["code"]["end"] = end + asm, invalid, err = disasm.disasm(blob[6][start:end], a.mcpu, wave32=meta.get("wave32", True), + compute=True) if not asm.strip(): reason = (err.strip().splitlines() or ["no output"])[0] print(f"{name}: {reason}", file=sys.stderr) diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 8958e1fc62..4311f3100b 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -7775,10 +7775,19 @@ def _insn(self, ins): d, x = a[0], a[1] wide_src = op == "s_quadmask_b64" wide_dst = op != "s_quadmask_b32" + mask_words = None if self.is_mask_op(x): - raise Unsupported(op + " on a lane mask") + # s_bitreplicate_b64_b32 of a 32-bit lane mask into plain scalar data (6 pipeline-library programs of + # 1.0.2.1): the wave's mask word as data, then replicated as any scalar (wave_mask, as s_ff1 reads it). + if op != "s_bitreplicate_b64_b32" or (d["k"] == "special" and d.get("t", "").startswith(("exec", "vcc"))): + raise Unsupported(op + " on a lane mask") + lo, hi = self.wave_mask(x) + half = self.mask_half(x) if self.wave64 else None + mask_words = [hi if half == "hi" else lo] if d["k"] == "special" and d.get("t", "").startswith(("exec", "vcc")): - if op != "s_bitreplicate_b64_b32" or not (d["t"] == "exec" or (self.wave64 and d["t"] == "vcc")): + # VCC only in wave64: in wave32 its high word is data, which a lane mask cannot carry. + if (op != "s_bitreplicate_b64_b32" or not (d["t"] == "exec" or (self.wave64 and d["t"] == "vcc")) + or mask_words is not None): raise Unsupported(op + " on a lane mask") # The mask bit for lane L comes from scalar-source bit L // 2. shift, shifted, bit = (self.tmp() for _ in range(3)) @@ -7791,7 +7800,9 @@ def _insn(self, ins): self.emit(f"{mask} = OpISub %uint {self.cu(0)} {bit}") self.mask_dst(d, mask) return - if wide_src: + if mask_words is not None: + words = mask_words + elif wide_src: lo, hi = self.src64_data(x, op) words = [lo, hi] else: diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py index eda43de957..a81ae1871f 100644 --- a/tools/shader_disasm.py +++ b/tools/shader_disasm.py @@ -30,6 +30,7 @@ TRIPLE = "amdgcn--amdpal" ENDPGM = b"\x00\x00\x81\xbf" +DOT4_I8_OPCODE = 0x16 # VOP3P v_dot4_i32_i8 PROBE = "0x00 0x00 0x81 0xbf" # s_endpgm: the one instruction every shader ends with FAILED = [] # (path, first stderr line) for shaders that produced no disassembly @@ -88,7 +89,19 @@ def probe(mcpu: str) -> None: f"{install_hint()}") -def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True): +def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True, compute: bool = False): + """`compute`: a pipeline-library or FSPX compute program. llvm-mc 21 does not decode SMEM loads whose SOFFSET is + SGPR_NULL (0x7D, e.g. s_load_dwordx8 ... 0xd60 with soffset null): it reports the first dword invalid, then reads + the second (0xFA......) as an 8-byte EXP and the rest of the listing goes out of step (gfx1013 and gfx1030 alike). + In 749 of the 2,684 library programs of 1.0.2.1 that refused 945 programs ('fall-through into undecodable + words'). tools/rdna2_decode.py decodes them; such a program takes its listing when it has fewer invalid words.""" + if compute and backend != "python": + asm, bad, err = disasm(code, mcpu, backend=backend, wave32=wave32) + if bad: + py_asm, py_bad = rdna2_decode.disasm_bytes(code, mcpu=mcpu, wave32=wave32) + if py_bad < bad: + return py_asm, py_bad, "" + return asm, bad, err if backend == "python": asm, bad = rdna2_decode.disasm_bytes(code, mcpu=mcpu, wave32=wave32) return asm, bad, "" @@ -97,6 +110,9 @@ def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True fixed = with_vopc_dpp(code, mcpu, err, wave32) if fixed: return fixed + fixed = with_dot4_op_sel(code, mcpu, bad, err, wave32) + if fixed: + return fixed return asm, bad, err @@ -188,6 +204,60 @@ def with_vopc_dpp(code: bytes, mcpu: str, err: str, wave32: bool = True): return None +def dot4_op_sel_words(code: bytes, offsets) -> dict: + """{offset: (word0, word1)} of the dword pairs at `offsets` that are v_dot4_i32_i8 with op_sel 2 and op_sel_hi 5, + no clamp and no neg: the form 89 words of the FidelityFX upscaler's programs take (docs/fspx.md). llvm-mc has no + decoding for it, and a plain v_dot4_i32_i8 has op_sel 0 and op_sel_hi 7. Only this combination is recognised: + its result was measured on hardware (tests/semantic/test_alu_dot4_i8.py), the other op_sel values were not.""" + found = {} + for at in sorted(offsets): + if at % 4 or at + 8 > len(code): + continue + w0, w1 = struct.unpack_from("<2I", code, at) + if (w0 >> 23 == 0x198 and (w0 >> 16) & 0x7F == DOT4_I8_OPCODE and (w0 >> 8) & 7 == 0 # VOP3P, neg_hi + and (w0 >> 11) & 7 == 2 and (w0 >> 14) & 1 == 1 and (w0 >> 15) & 1 == 0 # op_sel, hi[2], clamp + and (w1 >> 27) & 3 == 1 and (w1 >> 29) & 7 == 0): # op_sel_hi[1:0], neg_lo + found[at] = (w0, w1) + return found + + +def with_dot4_op_sel(code: bytes, mcpu: str, bad: int, err: str, wave32: bool = True): + """The listing of `code` with each rejected v_dot4_i32_i8 op_sel 2 / op_sel_hi 5 word printed as the instruction + it is, or None when there is none. llvm-mc rejects the pair, so it is decoded with the two fields at their + defaults (op_sel 0, op_sel_hi 7), and each such line gets the real fields and the real encoding back: the + translator then reads the instruction and checks its encoding against the blob. A word that is not printed as + v_dot4_i32_i8 at an instruction boundary was not an instruction (it sits in a literal or in data), so it is + left as it was and the pass runs again without it.""" + words = dot4_op_sel_words(code, invalid_offsets(err)) + while words and bad: + patched = bytearray(code) + for at, (w0, w1) in words.items(): + struct.pack_into("<2I", patched, at, w0 & ~(7 << 11), w1 | (2 << 27)) + asm, bad2, err2 = run_mc(bytes(patched), mcpu, wave32) + if not asm.strip(): + return None + invalid, pos, hit, lines = invalid_offsets(err2), 0, set(), [] + for line in asm.split("\n"): + enc = ENCODING.search(line) + if not enc: + lines.append(line) + continue + while pos in invalid: + pos += 4 + if pos in words and line.lstrip("\t").startswith("v_dot4_i32_i8 "): + hit.add(pos) + w0, w1 = words[pos] + original = ",".join(f"0x{b:02x}" for b in struct.pack("<2I", w0, w1)) + line = line[:enc.start()].rstrip() + " op_sel:[0,1,0] op_sel_hi:[1,0,1]" + line = f"{line:<40}; encoding: [{original}]" + lines.append(line) + pos += len(enc.group(1).split(",")) + if hit == set(words): + return "\n".join(lines), bad2, err2 + words = {at: w for at, w in words.items() if at in hit} + return None + + MAX_DATA_DWORDS = 1 << 16 diff --git a/tools/shader_library.py b/tools/shader_library.py index a74a820bb7..943bdd8bbc 100644 --- a/tools/shader_library.py +++ b/tools/shader_library.py @@ -270,7 +270,10 @@ def compute_variants(b: bytes, lib: dict, names: dict): i, state_id = rec["program"], rec["state"] if i is None: continue - state = blob(b, lib, state_id) if state_id is not None else None + if state_id is None: + by_record[i, None] = names[i] + continue + state = blob(b, lib, state_id) states = variants.setdefault(i, {}) if state not in states: states[state] = names[i] if not states else f"{names[i]}_state_{state_id}" @@ -301,7 +304,7 @@ def main(argv=None) -> int: if not a.out and not a.save: ap.error("give --out, --save or both") hashes = None - if a.compute_hashes: + if a.compute_hashes is not None: if not a.out: ap.error("--compute-hashes needs --out") try: @@ -310,7 +313,7 @@ def main(argv=None) -> int: except (OSError, UnicodeError) as error: ap.error(f"cannot read --compute-hashes: {error}") if not hashes or any(not re.fullmatch(r"[0-9a-f]{64}", h) for h in hashes): - ap.error("--compute-hashes needs at least one SHA-256 digest") + ap.error("cannot read --compute-hashes: expected one or more SHA-256 digests of 64 hex digits") with open(a.src, "rb") as f: head = f.read(4) f.seek(0) @@ -346,7 +349,8 @@ def main(argv=None) -> int: selected = [i for i in selected if matching[i] in hashes] missing = hashes - {matching[i] for i in selected} if missing: - raise LibraryError(f"{len(missing)} requested compute code hashes not found in the pipeline library") + raise LibraryError(f"{len(missing)} of the {len(hashes)} --compute-hashes digests match no compute " + f"program of the library, first {min(missing)}") carve_errors = [] sources = carve_digests(a.carve, errors=carve_errors) if a.carve else None @@ -434,7 +438,7 @@ def extraction_paths(): def one(job): entry, name, code, start, end = job - asm, invalid, err = disasm.disasm(code, a.mcpu, wave32=entry.get("wave32", True)) + asm, invalid, err = disasm.disasm(code, a.mcpu, wave32=entry.get("wave32", True), compute=True) entry["invalid_words"] = invalid with open(os.path.join(disasm_dir, name + ".s"), "w", encoding="utf-8", newline="\n") as f: f.write(f"; {name} code 0x{start:x}..0x{end:x} (fspx), {a.mcpu}, {invalid} invalid words\n")