Per maintainer feedback: the real blob is a DXBC container whose RTS0
chunk starts version, numParameters, parametersOffset, numStaticSamplers,
staticSamplersOffset, flags, with parameters as a {type, visibility,
offset} table and payloads at their offsets (d3d types follow
D3D12_ROOT_PARAMETER_TYPE numbering, not the model's enum order).
Also fixes the oracle segfault mechanism: return early when parsing fails
instead of indexing an empty model, and bounds every offset addition in
size_t so hostile containers cannot wrap the guard into an OOB read.
Adds a wild-offset control plus a DXBC-walk test (19 portable checks green
under ASan+UBSan).
The MS serializer returns a DXBC container, not a bare payload (proven
by the CI blob dump starting with DXBC). parse_rts0 now walks the chunk
table like input_signature does and decodes the RTS0 payload.
Also fixed: 'O' (0x4F) vs '0' (0x30) in the FourCC check, which silently
missed every chunk, and u32 arithmetic wrap in the bounds checks (a hostile
offset could wrap off+8 past the guard into an OOB read).
Adds a hand-built DXBC container test covering the walk path.
The command list implements the SDK's GCL8 chain (IID ee936ef9-599d-4d28-938e-23c4ad05ce51), so a GCL8 QueryInterface succeeds and slot 81 (byte offset 0x288) is OMSetFrontAndBackStencilRef(UINT, UINT). The method records both values on the list and Reset clears them. Nothing applies them yet: Vulkan's dynamic stencil reference is per face, but only a pipeline that consumes it can, and the layer has no pipeline or draw path. The call is reported once rather than silently dropped.
d3d12_gcl8_test creates only an allocator and a list (no Vulkan device), checks the interface pointer, the raw slot 81 call, both recorded values and the QueryInterface reference count. It runs under CTest.
What was wrong
An RDNA2 SMEM load can carry a register offset and an immediate at once.
llvm-mc prints that form as "s_buffer_load_dword s12, s[24:27], s40 offset:0x4".
shader_ir.parse_line puts "offset:0x4" in mods, and Gen.scalar_load only read
the third operand, so the immediate was dropped without a diagnostic: the line
translated to the same SPIR-V with and without the modifier, and spirv-val
accepted both.
Evidence
Measured on an AMD Radeon RX 6800 (gfx1030) by running the instructions as a
raw compute kernel: for s_buffer_load_dword/x2/x4/x8 the address is
base + soffset + imm + 4*i, e.g. soffset 8 + imm 4 reads the dword at +12.
s_load_dword* with both offsets was not measured; it shares the SMEM encoding
(soffset_en + imm), so giving it the same rule is an inference.
Change
- scalar_load adds the immediate when the third operand is a register and mods
has offset:N. The no-modifier forms emit the same code as before.
- Forms llvm-mc does not accept (immediate operand plus offset:, two offset:
modifiers, a fourth operand, an unparseable offset) raise Unsupported.
- Not changed, and listed in docs/design.md as known differences: the hardware
truncates base, soffset and imm each to a multiple of 4 and s_buffer_load
returns 0 past NUM_RECORDS; the translator does neither. A negative s_load
immediate is still zero-extended from 32 bits, in both forms (not measured).
Tests
- tests/semantic/test_scalar_mem_smem.py: SmemSoffsetImmTranslatorTests runs
the code scalar_load emits against concrete SGPRs and memory and asserts the
addresses and values read (9 tests; 7 fail on main, where the loads read +8
instead of +12, and the imm-only / soffset-only regression cases pass).
- runtime/test/shaders/cs_smem_soffset_imm.asm, wired into check.py and
scripts/run_gpu_tests.py. Not run on a GPU in this change.
- unittest discover -s tests/semantic: 335 -> 344, all pass.
- pytest tests (--capture=sys, llvm-mc through WSL): 883 -> 893 passed, the
same 6 test_rtti_scan failures before and after (pefile not installed).
- The 27 hand-written GPU shaders: 27 translated, 27 pass spirv-val before and
after, output byte-identical.
AI-assisted.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
LLVM 21 prints the VOP3 form of v_lshlrev_b16, v_add_u16 etc. without _e64. All of them in the game's
shaders are 8-byte VOP3 encodings, so they were translated as VOP2 writes and lost the high half that
the hardware keeps (about 340 shaders). Found by #78's ps_ops5 on the GPU. Both runners now check
ps_ops5/ps_ops6, run_gpu_tests skips the interpreter-only ps_vcc_x2 (it lost the device), and
test_shader_checks derives its total from check.py.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Windows oracle test segfaulted in CI. Most likely cause: an
unbounded static-sampler reserve driven by real-blob bytes under a wrong
layout hypothesis. Both decoders now refuse absurd sampler counts, and the
oracle test prints the blob size plus the first 32 bytes before parsing so
the next CI log shows the true D3D12 layout either way.
check.py and run_gpu_tests.py both died with a FileNotFoundError traceback when vk_compute_test, vk_store_test
or vk_harness was not built, which on Linux happens whenever CMake does not find the Vulkan headers. They now
name the missing programs, how to build them, and the "Vulkan SDK not found" hint, and exit 1.
run_gpu_tests.py checks before translating; check.py checks in run(), which the unit tests mock.
Add --wave64-emulate to tools/rdna2spirv.py. A wave64 compute or mesh
shader then uses no subgroup operation: everything a lane needs from the
rest of its wave (votes for s_cbranch_*/SCC, whole-mask words for
s_bcnt1/s_ff1/v_mbcnt, v_readlane, v_readfirstlane, ds_bpermute,
ds_swizzle, v_permlane16/x16) goes through a Workgroup buffer. The
program runs in rounds that end at one OpControlBarrier in uniform
control flow; a cross-lane op cuts its basic block, and the rest runs one
round later, when all 64 lanes have written. s_barrier becomes a
scheduler state, and conflicting memory accesses in one segment are
ordered by a round. This answers #94 and #101 for compute and mesh
shaders: on 32-wide subgroups (NVIDIA) they are now exact, not
approximate.
Two fixes that apply without the flag:
- v_writelane_b32 in cs/ms selects the lane by the wave lane. On a
32-wide subgroup writes to lanes 32-63 were lost.
- ds_bpermute_b32 in wave64 runs as two wave32s (RDNA ISA 10.4.4): on a
64-wide subgroup lanes 32-63 read the low half, and an inactive source
lane now reads 0.
New hand-written GPU tests cs_w64x_* and ms_w64x_ballot pin down the
cross-half semantics. LEONIDA_W64_EMULATE=1 makes build.py,
run_gpu_tests.py and check.py use the flag. Other translator output is
byte-identical.
Tested on NVIDIA GeForce RTX 5070 Laptop (driver 617.42, subgroup 32) and
AMD Radeon 880M (driver 26.11.2 LLPC, subgroup 64):
run_gpu_tests.py 37/37 on both with the flag (RTX 5070 without it: 21/37;
880M without it: 37/37, was 36/37 before the bpermute fix).
AI-assisted (Claude Code).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The 'build' and 'check' jobs failed with C3861 on MSVC 14.52:
__builtin_memcpy is GCC/Clang-only. std::memcpy (<cstring>) works
everywhere the portable model compiles.
The proxy read device slot 62 as (desc, riid, out), so XboxBvhBuilder's constructor, the only
known caller, got E_POINTER on its first compute PSO and threw it. Recorded on 1.0.2.1: the
DLL calls slot 62 with (desc, 0, 0, &IID_ID3D12PipelineState, out), the shape the prior art
had documented (d3d12_vulkan.md, sections 4.8 and 7). Read the IID and the output from the
fourth and fifth arguments, and log the two extra words once if they are ever non-zero.
device_proxy_test now calls slot 62 in that shape.
AI-assisted (Claude Code).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
map_image pushes a module into order_ before bind_imports maps the modules it
imports, so order_ lists an importer ahead of its DLLs, and initialise() ran
TLS callbacks and DllMain in that order. Keep a separate init_order_ filled
after a module's imports are loaded and initialise from it. modules() stays
mapping order. pe_loader_test checks tiny_dll comes before tiny_exe.
AI-assisted (Muse Spark + explorer fleet).
Implements docs/d3d12_vulkan.md section 3.5 as code: a portable D3D12
root-signature model (1.0/1.1, no d3d12.h) plus a packer that lays root
parameters into the 32 user-SGPR dwords in root-parameter order (constants
take N, views/tables take 2, static samplers take none). Anything that does
not fit - more than 32 user SGPRs (spill layout unknown) or more than the
64-dword D3D12 cost limit - is refused loudly instead of truncated.
tools/root_sig_contract.py reconciles a candidate signature against every
shader's user_sgpr_reads from spirv/index.json (const32 vs constant dwords,
64-bit VAs vs view/table pairs, unpaired-hi detection) and exits nonzero on
the first contradiction; --cluster shows which read-set shapes the game
actually needs.
The RTS0 chunk reader is marked hypothesis until the new Windows oracle
test (synthetic descs serialized by the real d3d12.dll) confirms the layout;
Tier A (model/packer/canonical codec/RTS0 self-consistency/reconciler) runs
everywhere with no game data and no GPU.
Tested: python -m pytest tests/test_root_sig_contract.py (12 passed);
full suite 651 passed, 20 skipped, 1 xfailed; compileall + make_game --help;
portable C++ test 17/17 PASS under g++ -Wall -Wextra -Wpedantic -Werror with
ASan+UBSan; turing atlas on RTX 2060 SUPER (subgroup 32, mesh/bary/m8/heap
true): compute32/ballot64/f16_input/maintenance8 valid, broken_negative
correctly invalid. Windows-only Tier B (oracle + MSVC build) runs in CI.
parse_exports stored base + RVA for every export, but an export whose RVA lands inside the export
directory is a forwarder string ("KERNEL32.Sleep"), not code, so an import of one received a pointer
into the string. Forwarders are now recorded separately and followed when an import asks for one:
bundled modules first, then LoadLibraryEx/GetProcAddress for system DLLs, with a depth cap so two
modules re-exporting each other stop instead of recursing. An unresolvable forwarder records the
import as unimplemented.
The delay-import walk also assumed every descriptor is RVA-based and has a name table. A descriptor
without dlattrRva stores 32-bit virtual addresses, which cannot address an x64 image base, so it is
rejected with a message instead of being misread. A missing address table is rejected, and a missing
name table now reads its entries back through the address table.
Port the #78 value-level cases (ps_ops5, ps_ops6, ps_vcc_x2, ps_flat,
cs_bounds) onto main's semantic suite. Keep main's ps_ops4/ps_legacy_mul
coverage and forward-only execution contract, and extend the mini
interpreter with 64-bit integers, Input/PushConstant seeding, physical
storage buffer memory, OpBranch/OpPhi at forward merges, and the opcodes
the new fixtures use.
- IR: CopyBufferRegion, CopyTextureRegion (subresource or placed footprint,
optional box) and CopyResource, with D3D12's call rules (512-byte footprint
offsets, 256-byte pitches, non-empty boxes).
- Replay: vkCmdCopyBuffer / CopyBufferToImage / CopyImageToBuffer / CopyImage.
Footprint pitch becomes bufferRowLength; BC extents stop at the mip edge;
every range and buffer bound is checked before anything is written. Copies
run in TRANSFER_SRC/DST, or in place in GENERAL for a COMMON texture
(implicit promotion). 2D only.
- Device: buffers expose their VkBuffer; BC1-7 formats; textureCompressionBC
enabled when present; GetCopyableFootprints for buffers and 2D textures.
Compared with the PC runtime over 13 descriptions, which showed planar
depth-stencil rows are padded to 512 bytes.
- Each submission ends with a barrier to the host so readback buffers hold the
GPU's writes after the fence wait. BC textures are not zero-filled on first
use (Vulkan cannot clear them; the validation layer caught the first try).
Tests: d3d12_vulkan_device_test now reads results back through D3D12
(CopyTextureRegion into a readback heap, Map) and adds an upload list: a
pattern into a texture, CopyResource into a COMMON texture, a boxed copy, a BC1
round trip and CopyBufferRegion. command_list_test covers the copy rules. All
GPU tests are clean under the Khronos validation layer; 6/6 ctest.
- d3d12_vulkan_device.cpp: an ID3D12Device11 (PC ABI) the device proxy
forwards to. Creates queues, allocators, command lists (incl.
CreateCommandList1), fences, descriptor heaps (32-byte slots; RTV/DSV hold
TargetViews), render-target and depth-stencil views, committed buffers
(upload/readback mapped and zeroed) and 2D textures in the common formats,
and answers feature-level and architecture queries. Everything else is a
generated stub that logs once.
- First use of a new texture zero-fills it and moves it to the layout the
command expects (vulkan_replay.h initialize), as D3D12 committed resources
start zeroed; no submission at creation. CREATE_NOT_ZEROED skips the fill.
- Children hold the proxy, so GetDevice returns the Xbox-ABI object; COM base
classes moved to d3d12_com_object.h. D3D12 queues share one VkQueue behind a
submit lock.
- D3D12XboxCreateDevice: LEONIDA_D3D12=vulkan creates the Vulkan device on its
own instance and wraps it in the same proxy (gta6rt built with the Vulkan
SDK and Python 3); the host PC device stays the default.
Tests: d3d12_vulkan_device_test calls everything through the proxy (heaps via
slot 14 with RAX start handles, a render target via slot 76 with the Xbox
layout word) and reads colour, depth, stencil and a never-written texture
back; it also runs the standalone device. Clean under the Khronos validation
layer with the other GPU tests; all 6 ctest tests pass.
- Pair ps/vs/ms/gs shaders with partner stubs from <spirv>/stubs/ and compile
real pipelines via vkCreateGraphicsPipelines with Vulkan 1.3 dynamic
rendering (color attachments from outputs, depth attachment when writes_depth,
VK_EXT_mesh_shader for ms, vertex input bindings for vs).
- Enable only optional extensions needed by the selected shaders; report
shaders missing required device features or stubs as skipped rather than failed.
- Add --stage all|cs|graphics (--compute-only / --graphics-only), per-stage
module/pipeline/skip/timing reporting, and guard VK_KHR_maintenance8 for
older Vulkan headers. Preserves PR #28 --jobs, cache, --start/--count, and SLOW.
- Add tools/spirv_stubs.py to emit minimal deduplicated SPIR-V 1.0 VS/PS
partner stubs into <spirv>/stubs/ using only the standard library.
- Record writes_depth, gs_input_locations, and gs_output_locations in
shader_meta() (keeping all existing fields intact and avoiding overlap
with PR #76 / PR #83 fields).
- Generate stubs automatically when rdna2spirv.py or build.py writes index.json.
vk_store_test requested shaderStorageImageReadWithoutFormat for both
modes, so vkCreateDevice failed on GPUs without it (Intel Gen9) and
cs_imgstore failed too, though only image_load needs the feature.
Request it in load mode only, exit 77 when it is missing, and have
check.py list that as skipped instead of failed.
vk_store_test exits 77 when the GPU lacks format-less storage image read/write (Intel Gen9), and check.py
reports it as SKIP. run_gpu_tests.py catches up with check.py: ps_flat (drawn with vs_ids), ps_legacy_mul,
and ps_bitmask_perm judged on lanes 0-31 only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
find_library only searches %LIB%, which a plain shell doesn't set, so configuring with the
Visual Studio generator from a normal terminal (`cmake -S runtime -B runtime/build`, as the
CI workflow's check job does) skipped root_sig_test and device_proxy_test with
"d3d12.lib not found", although the generator links against that SDK. Look in the
generator's target SDK (KitsRoot10/Lib/<version>/um/x64) and in WindowsSdkDir when set.
Tested on Windows 11, VS 2022 Build Tools 14.44, SDK 10.0.26100.0, VS generator from a plain
shell: both libraries found, root_sig_test and device_proxy_test build and pass (WARP).
AI-assisted (Claude Code).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mapping an image never ran anything. TLS callbacks and DllMain were documented as the caller's, and
nothing called them, so a module that needs either could not be brought up at all.
Loader::initialise() now allocates the module's TLS slot, copies the template and SizeOfZeroFill into
it, writes the slot index into the image, runs the TLS callbacks with DLL_PROCESS_ATTACH, then calls
the entry point of a DLL as DllMain. Every address it follows is bounded like the rest of the loader:
the directory, the template, the index, the callback table and each callback, with a 1 MiB ceiling on
the block. Only DLLs get DllMain; an EXE's entry point has a different signature and stays the
caller's to run, and --dry-run still runs nothing.
The tests build an image whose TLS callback and DllMain are real machine-code stubs that store a
sentinel, so they check the code actually executed rather than merely being parsed.