d3d12: guard biased raw twins against sub-dword offsets and 32-bit wrap (D3D12-TWIN-BIAS-RDNA3) #2757

Merged
zmasi merged 2 commits from upstream-pr/2757 into main 2026-11-30 18:28:28 +00:00
zmasi commented 2026-11-30 15:52:48 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by zmasi on 2026-11-30T15:52:48Z.


Summary

Fixes #2702 (D3D12-TWIN-BIAS-RDNA3).

Commit 1bb188cf5 (LEONIDA_TWIN_BIAS, active on AMD adapters where raw_views() allocates raw twins) kept raw twins starting at the 16-byte boundary before an unaligned buffer view and recorded the byte delta by (1..15) in bits 24..27 (VIEW_BIAS_MASK) of strides[slot] for translated shaders to add to raw byte offsets. On RDNA 3 (RX 7900 XT), that exposed three bugs that vanish under LEONIDA_TWIN_BIAS=0:

  1. Sub-dword by % 4 != 0 twins accepted by settle_twin (d3d12/crates/leonida-gpu/src/descriptor/host.rs):

    • shader.rs (VIEW_BIAS_MASK doc) and lower.rs (rawBufferLoad / rawBufferStore with alignment = 4, buffer atomics, cbuffer_dword, format_load, and narrow within = byte & 3) assume bias is a multiple of 4 (0, 4, 8, 12).
    • However, twin_window produces by in 1..15 for sub-dword typed views (R16_* at odd FirstElement gives by = 2, 6, 10, 14; R8_* gives odd by), and settle_twin only checked by < 16 && by < bytes, never by.is_multiple_of(4). On GFX11/RDNA 3, misaligned byte offsets fed to 4-byte-aligned raw loads/stores/atomics truncate & !3 or misalign, splicing adjacent half/snorm/index values.
    • settle_twin now requires by.is_multiple_of(4), keeping the primary typed view intact while nulling sub-dword raw twins just as LEONIDA_TWIN_BIAS=0 does.
  2. 32-bit unsigned wrap-around on offset + bias (d3d12/crates/leonida-shader/src/emit/lower.rs):

    • Shaders routinely compute sentinel or underflowed byte offsets such as u32::MAX * stride + field (0xFFFF_FFF4..0xFFFF_FFFC for stride = 4, 8, 12, 24, 48, ...) or x - 4 at x = 0 (0xFFFF_FFFC).
    • With bias == 0, these offsets remain near 4 GiB out of bounds (0 on D3D12 raw loads, dropped on stores/atomics). Adding bias in {4, 8, 12} wrapped modulo 2^32 into [0, 12) — in bounds of the biased twin's 16-byte pre-view prefix, which holds bytes belonging to the preceding suballocation in the ring/heap. Vertex/geometry loads at sentinel -1 read arbitrary preceding bytes as positions (stretching triangles across clip space and spiking rasterizer cost), while UAV stores/atomics at sentinel offsets overwrote preceding buffer allocations.
    • Lower::add_bias now clamps offset > 0xFFFF_FFD0 to out-of-bounds 0xFFFF_FFE0 (oob + 16 = 0xFFFF_FFF0, non-wrapping across 16-byte dwordx4 accesses and constant-folded away by opt.rs on literal offsets), and Lower::narrow guards aligned == 0xFFFF_FFFC before reading aligned + 4.
  3. Stride-word hygiene and ordering (d3d12/crates/leonida-gpu/src/descriptor/host.rs):

    • HostHeap::constant_raw_at (LEONIDA_PORT_CBV) now clears stale VIEW_BIAS_MASK bits in strides[index] when recycling a dynamic slot.
    • HostHeap::{make_at, mirror, make_listed} publish strides[index] before exposing twin descriptors (and make_listed refreshes existing.stride_word on stale_at), and twin_window bounds end - from to u32 so NUM_RECORDS byte counts cannot wrap.

Verification

Tested on Windows 11 (10.0.26200), NVIDIA GeForce RTX 3090 (driver 610.88), and D3D12 WARP with LEONIDA_D3D12_DEBUG=1 and Windows SDK dxil.dll validation:

  • Red -> Green seam & negative-control tests:
    • leonida-shader: emit::twin_bias_tests::sentinel_and_wrapped_offsets_stay_out_of_bounds_on_biased_twins (including buffer_load_dword, buffer_load_dwordx4, buffer_load_ushort at u32::MAX, buffer_store_dword, and buffer_atomic_add against non-zero pre-view canary bytes) and emit::twin_bias_tests::resource_heap_structured_twins_validate_and_guard_wrapped_elements.
    • leonida-gpu: descriptor::host::listed_raw_tests::sub_dword_views_null_twins_and_recycled_raw_cbv_clears_bias (default and LEONIDA_TWIN_BIAS=0 negative control) and listed_off_alignment_raw_twin_readback.
  • Suite & lints:
    • cargo test -p leonida-shader (387 passed, 0 failed)
    • cargo test -p leonida-gpu --lib descriptor:: and port_cbv:: (all passed)
    • cargo clippy -p leonida-shader -p leonida-gpu --tests (0 warnings in touched files)
    • python -I scripts/check_no_game_data.py (rc=0)

AI-assisted: authored with Gemini 4 Carbon (High) and independently reviewed with Gemini 4 Neon (XHigh).

<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5568714058 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2757). Originally posted by [zmasi](https://github.com/zmasi) on 2026-11-30T15:52:48Z. --- ## Summary Fixes #2702 (`D3D12-TWIN-BIAS-RDNA3`). Commit `1bb188cf5` (`LEONIDA_TWIN_BIAS`, active on AMD adapters where `raw_views()` allocates raw twins) kept raw twins starting at the 16-byte boundary before an unaligned buffer view and recorded the byte delta `by` (`1..15`) in bits `24..27` (`VIEW_BIAS_MASK`) of `strides[slot]` for translated shaders to add to raw byte offsets. On RDNA 3 (`RX 7900 XT`), that exposed three bugs that vanish under `LEONIDA_TWIN_BIAS=0`: 1. **Sub-dword `by % 4 != 0` twins accepted by `settle_twin` (`d3d12/crates/leonida-gpu/src/descriptor/host.rs`)**: - `shader.rs` (`VIEW_BIAS_MASK` doc) and `lower.rs` (`rawBufferLoad` / `rawBufferStore` with `alignment = 4`, buffer atomics, `cbuffer_dword`, `format_load`, and `narrow` `within = byte & 3`) assume `bias` is a multiple of 4 (`0, 4, 8, 12`). - However, `twin_window` produces `by` in `1..15` for sub-dword typed views (`R16_*` at odd `FirstElement` gives `by = 2, 6, 10, 14`; `R8_*` gives odd `by`), and `settle_twin` only checked `by < 16 && by < bytes`, never `by.is_multiple_of(4)`. On GFX11/RDNA 3, misaligned byte offsets fed to 4-byte-aligned raw loads/stores/atomics truncate `& !3` or misalign, splicing adjacent half/snorm/index values. - `settle_twin` now requires `by.is_multiple_of(4)`, keeping the primary typed view intact while nulling sub-dword raw twins just as `LEONIDA_TWIN_BIAS=0` does. 2. **32-bit unsigned wrap-around on `offset + bias` (`d3d12/crates/leonida-shader/src/emit/lower.rs`)**: - Shaders routinely compute sentinel or underflowed byte offsets such as `u32::MAX * stride + field` (`0xFFFF_FFF4..0xFFFF_FFFC` for `stride = 4, 8, 12, 24, 48, ...`) or `x - 4` at `x = 0` (`0xFFFF_FFFC`). - With `bias == 0`, these offsets remain near `4 GiB` out of bounds (`0` on D3D12 raw loads, dropped on stores/atomics). Adding `bias` in `{4, 8, 12}` wrapped modulo `2^32` into `[0, 12)` — **in bounds** of the biased twin's 16-byte pre-view prefix, which holds bytes belonging to the preceding suballocation in the ring/heap. Vertex/geometry loads at sentinel `-1` read arbitrary preceding bytes as positions (stretching triangles across clip space and spiking rasterizer cost), while UAV stores/atomics at sentinel offsets overwrote preceding buffer allocations. - `Lower::add_bias` now clamps `offset > 0xFFFF_FFD0` to out-of-bounds `0xFFFF_FFE0` (`oob + 16 = 0xFFFF_FFF0`, non-wrapping across 16-byte `dwordx4` accesses and constant-folded away by `opt.rs` on literal offsets), and `Lower::narrow` guards `aligned == 0xFFFF_FFFC` before reading `aligned + 4`. 3. **Stride-word hygiene and ordering (`d3d12/crates/leonida-gpu/src/descriptor/host.rs`)**: - `HostHeap::constant_raw_at` (`LEONIDA_PORT_CBV`) now clears stale `VIEW_BIAS_MASK` bits in `strides[index]` when recycling a dynamic slot. - `HostHeap::{make_at, mirror, make_listed}` publish `strides[index]` before exposing twin descriptors (and `make_listed` refreshes `existing.stride_word` on `stale_at`), and `twin_window` bounds `end - from` to `u32` so `NUM_RECORDS` byte counts cannot wrap. ## Verification Tested on Windows 11 (`10.0.26200`), NVIDIA GeForce RTX 3090 (driver `610.88`), and D3D12 WARP with `LEONIDA_D3D12_DEBUG=1` and Windows SDK `dxil.dll` validation: - **Red -> Green seam & negative-control tests**: - `leonida-shader`: `emit::twin_bias_tests::sentinel_and_wrapped_offsets_stay_out_of_bounds_on_biased_twins` (including `buffer_load_dword`, `buffer_load_dwordx4`, `buffer_load_ushort` at `u32::MAX`, `buffer_store_dword`, and `buffer_atomic_add` against non-zero pre-view canary bytes) and `emit::twin_bias_tests::resource_heap_structured_twins_validate_and_guard_wrapped_elements`. - `leonida-gpu`: `descriptor::host::listed_raw_tests::sub_dword_views_null_twins_and_recycled_raw_cbv_clears_bias` (default and `LEONIDA_TWIN_BIAS=0` negative control) and `listed_off_alignment_raw_twin_readback`. - **Suite & lints**: - `cargo test -p leonida-shader` (`387` passed, `0` failed) - `cargo test -p leonida-gpu --lib descriptor::` and `port_cbv::` (all passed) - `cargo clippy -p leonida-shader -p leonida-gpu --tests` (`0` warnings in touched files) - `python -I scripts/check_no_game_data.py` (`rc=0`) AI-assisted: authored with Gemini 4 Carbon (High) and independently reviewed with Gemini 4 Neon (XHigh).
OreoFR commented 2026-11-30 15:56:19 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by OreoFR on 2026-11-30T15:56:19Z.


Verified by OreoFR on macOS 27.2.1, Apple M5, Rust (rustup), main 3e74b0d7d merged with head fe7c76d3b. A partial check: the new tests cannot run here.

  • MEASURED: cargo test -p leonida-shader on macOS: 228 passed, 0 failed, 2 ignored (the same count as main: the change to emit/lower.rs breaks none of the tests that build on macOS).
  • READ IN CODE: the new emit/twin_bias_tests.rs and descriptor/host/listed_raw_tests.rs are under #[cfg(all(test, windows))] modules, so they are not run here.
  • MEASURED, type-check only (cargo check --target x86_64-pc-windows-msvc from macOS, C build scripts given a stand-in compiler, nothing linked): -p leonida-shader --tests, -p leonida-gpu --tests --features diagnostics and -p leonida-gpu: no errors. The two new test files compile for Windows.
  • Not covered: running the new tests, red/green, and a run in game. Those need Windows.

AI-assisted: Claude Code

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7283851428 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2757#issuecomment-7283851428). Originally posted by [OreoFR](https://github.com/OreoFR) on 2026-11-30T15:56:19Z. --- Verified by OreoFR on macOS 27.2.1, Apple M5, Rust (rustup), `main` `3e74b0d7d` merged with head `fe7c76d3b`. A partial check: the new tests cannot run here. - MEASURED: `cargo test -p leonida-shader` on macOS: 228 passed, 0 failed, 2 ignored (the same count as `main`: the change to `emit/lower.rs` breaks none of the tests that build on macOS). - READ IN CODE: the new `emit/twin_bias_tests.rs` and `descriptor/host/listed_raw_tests.rs` are under `#[cfg(all(test, windows))]` modules, so they are **not run** here. - MEASURED, type-check only (`cargo check --target x86_64-pc-windows-msvc` from macOS, C build scripts given a stand-in compiler, nothing linked): `-p leonida-shader --tests`, `-p leonida-gpu --tests --features diagnostics` and `-p leonida-gpu`: no errors. The two new test files compile for Windows. - Not covered: running the new tests, red/green, and a run in game. Those need Windows. AI-assisted: Claude Code
KelboLive commented 2026-11-30 16:35:06 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by KelboLive on 2026-11-30T16:35:06Z.


Independent check on Windows (not the author), at fe7c76d3b.

  • cargo test --locked -p leonida-gpu -p leonida-shader --lib (shared warm target): 958 tests, 0 failed — leonida-gpu 571 passed / 52 ignored (13.8 s), leonida-shader 387 passed / 4 ignored (267.8 s).

Environment: Ryzen 9 7950X3D, Windows 11 Pro 10.0.26200.9711, NVIDIA RTX 4070 Ti SUPER (driver 621.01), Rust 1.98.1 pinned.

No regressions in either crate. I did not run the title, so the biased-twin picture behaviour itself needs a game run.

AI-assisted: yes (opencode).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7284903473 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2757#issuecomment-7284903473). Originally posted by [KelboLive](https://github.com/KelboLive) on 2026-11-30T16:35:06Z. --- Independent check on Windows (not the author), at `fe7c76d3b`. - `cargo test --locked -p leonida-gpu -p leonida-shader --lib` (shared warm target): **958 tests, 0 failed** — `leonida-gpu` 571 passed / 52 ignored (13.8 s), `leonida-shader` 387 passed / 4 ignored (267.8 s). Environment: Ryzen 9 7950X3D, Windows 11 Pro 10.0.26200.9711, NVIDIA RTX 4070 Ti SUPER (driver 621.01), Rust 1.98.1 pinned. No regressions in either crate. I did not run the title, so the biased-twin picture behaviour itself needs a game run. AI-assisted: yes (opencode).
MoonEyes commented 2026-11-30 18:24:34 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-11-30T18:24:34Z.


RUN · VERIFY-2757-RTX4060 · by MoonEyes (another person than the author) on head fe7c76d3b, together with #2684 (bb68c6e19), #2685 (903e3731e) and #2757 (fe7c76d3b) merged into main 99167bcaf. Windows 11 Pro 26300, RTX 4060 8 GB, -SeriesS -FrameGen 2, diag build.

  • cargo test -p leonida-shader --locked: 392 passed, 0 failed.
  • Game: two runs of the same build, the person walking in the world from 345 s. First with the shaders translated again (795 s before the title, about 185 s of steady frames), then warm: the steady world after 165 s, about 425 s of it, about 98 m walked, no device loss, no unhandled exception, the process alive at the end. PASS for the gate of 300 s.
  • The three pull requests were in one build, so a fault of one could have been hidden by another only if they cancel out; none was seen. No frame rate is claimed, other work ran on the PC and there is no arm without them.

AI-assisted (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7287806613 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2757#issuecomment-7287806613). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-11-30T18:24:34Z. --- RUN · VERIFY-2757-RTX4060 · by MoonEyes (another person than the author) on head `fe7c76d3b`, together with #2684 (`bb68c6e19`), #2685 (`903e3731e`) and #2757 (`fe7c76d3b`) merged into `main` `99167bcaf`. Windows 11 Pro 26300, RTX 4060 8 GB, `-SeriesS -FrameGen 2`, diag build. - `cargo test -p leonida-shader --locked`: 392 passed, 0 failed. - Game: two runs of the same build, the person walking in the world from 345 s. First with the shaders translated again (795 s before the title, about 185 s of steady frames), then warm: the steady world after 165 s, about 425 s of it, about 98 m walked, no device loss, no unhandled exception, the process alive at the end. PASS for the gate of 300 s. - The three pull requests were in one build, so a fault of one could have been hidden by another only if they cancel out; none was seen. No frame rate is claimed, other work ran on the PC and there is no arm without them. AI-assisted (Claude Code).
MoonEyes commented 2026-11-30 18:28:23 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-11-30T18:28:23Z.


Merging. Head fe7c76d3b merges cleanly with main 4da779252 and does not force a rebase of #2566. Two runs in the game (RTX 4060, the second 425 s steady, no device loss) with #2684, #2685 and #2757 together; cargo test 392 passed; checked by other people too. The shaders are translated again at the first start. Merged by MoonEyes.

AI-assisted (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7287900106 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2757#issuecomment-7287900106). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-11-30T18:28:23Z. --- Merging. Head `fe7c76d3b` merges cleanly with `main` `4da779252` and does not force a rebase of #2566. Two runs in the game (RTX 4060, the second 425 s steady, no device loss) with #2684, #2685 and #2757 together; cargo test 392 passed; checked by other people too. The shaders are translated again at the first start. Merged by MoonEyes. AI-assisted (Claude Code).
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
ProjectLeonida/mandy!2757
No description provided.