d3d12 port 2: wrap RTL/safe copy imports & GetProcAddress and mark beside-guard view stores (#3259) #3306

Open
zmasi wants to merge 1 commit from upstream-pr/3306 into main
zmasi commented 2026-12-03 07:55:14 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by zmasi on 2026-12-03T07:55:14Z.


Fixes #3259 (D3D12-PORT-DESCRIPTORS-MISSED-WRITERS, claimed in https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7369624822).

Root Cause

Under LEONIDA_PORT_DESCRIPTORS=1, three gaps produced missed shader-visible view records (~6 per frame in the fallback scan) and misattributed their writer= addresses:

  1. Unwrapped OS/CRT copy variants and GetProcAddress lookups:
    • port_descriptors::import (and titlewrite::import) only wrapped static IAT imports named "memcpy" and "memmove". The ~10,700 memcpy/memmove calls per frame into the +0x4d9f400 frame allocator are non-view constants and list nodes (0 VIEW_TAG records), whereas view-record copies through RtlMoveMemory / RtlCopyMemory (ntdll.dll / kernel32.dll, matching the 0x7ffc... 0xe5-byte span in #3259), memcpy_s / memmove_s (ucrtbase / api-ms-win-crt-string-*), or dynamic kernel::GetProcAddress lookups bypassed port_descriptors::copied entirely.
  2. Sparse beside-guard stores (LEONIDA_STORE_BESIDE=1) bypassed port_descriptors completely:
    • watch.rs executes sparse faulting stores (<= 4 in a 64 KiB guarded block) through titlewrite::store and returns EXCEPTION_CONTINUE_EXECUTION before port_descriptors::faulted runs. Any unpatched sparse store writing a VIEW_TAG record beside a guard was neither marked in MARKS nor recorded in a.writers.
  3. Self-blaming block faults in a.writers[(off >> 16)] (base - 0x70000 at +0x00 / +0x80):
    • console_insn::near places descriptor_sites::apply's six patched vmovups stubs at base - 0x70000 (+0x00 = SITES[0], +0x40 = SITES[1], +0x80 = SITES[2]). Those stubs mark their own slots properly (0.0 told and not taken yet), but because a.writers tracks one last-faulting RIP per 64 KiB block (2,048 descriptors), whenever a patched stub, wrapped copy, or descriptor::copy_simple / descriptor::record call unguarded a 64 KiB block, its RIP overwrote a.writers and masked unmarked writers in the same block.
  4. Pending-slot tabled counter skew:
    • port_descriptors::missed incremented CHECKED[4] (of draws' tables) before checking marked(a, index) (told and not taken yet).

Changes

  • port_descriptors.rs & titlewrite.rs:
    • Extend import (REAL[6]) to wrap RtlCopyMemory/CopyMemory, RtlMoveMemory/MoveMemory, memcpy_s, and memmove_s with ABI-matched wrappers, null/self-wrap guards, overflow-safe scan_copied_range, and race-free write-once compare_exchange binding.
    • Add port_descriptors::note_store called from titlewrite::store so sparse beside-guard stores writing VIEW_TAG records into the adopted heap mark their slot immediately and record the faulting RIP in a.writers.
    • Register [start, end) ranges of descriptor_sites stubs (register_stubs) and wrap tracked copies/view writes in thread-local in_tracked_copy so faults from already-marking stubs/wrappers/views neither blame themselves nor clobber unmarked writers in a.writers.
    • Move CHECKED[4] (tabled) after the marked(a, index) early return in missed.
  • leonida-hle/src/{host.rs, modules/kernel.rs}:
    • Route both HostPolicy::resolve and kernel::GetProcAddress through an OS/CRT system-DLL allow-list (is_system_copy_dll) and pin the backing module via GetModuleHandleExW(FROM_ADDRESS | PIN) (handling forwarders such as kernel32!RtlMoveMemory -> ntdll) so FreeLibrary cannot unload cached targets and non-system DLLs cannot overwrite global wrapper slots.
  • descriptor.rs, descriptor_sites.rs, apps/leonida/src/run.rs:
    • Return installed stub ranges via descriptor_sites::apply_with_stubs and register them at startup; pre-mark destination view slots in descriptor::copy_simple without double-counting MARKED_BY_US.

Verification (No Game Files)

  • python -I scripts/red_green.py HEAD --no-fetch --base origin/main: verdict: red then green (7 red -> green, 1,117 pass on both across leonida, leonida-gpu, leonida-hle, and leonida-loader, 0 regressions).
  • cargo test --locked --target x86_64-pc-windows-msvc (default and --features diagnostics): port_descriptors:: (9/9), port_descriptors_copy_wrap (1/1), titlewrite:: (5/5), descriptor:: (89/89), leonida-hle (259/259), leonida-loader (92/92), leonida (48/48).
  • Clean 3-way merge verified against open PRs #2831 and #2832; tools/d3d12_switches.py --check d3d12/docs/switches.md and scripts/check_no_game_data.py clean.
  • Note: Not yet tested in-game (LEONIDA_GAME_DIR absent here); synthetic VEH/guard-page, copy-import, and GetProcAddress tests cover the exact fault and copy paths.

AI-assisted: Gemini 4 Neon (XHigh) and Gemini 4 Carbon (High).

<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5622338879 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3306). Originally posted by [zmasi](https://github.com/zmasi) on 2026-12-03T07:55:14Z. --- Fixes #3259 (`D3D12-PORT-DESCRIPTORS-MISSED-WRITERS`, claimed in https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7369624822). ### Root Cause Under `LEONIDA_PORT_DESCRIPTORS=1`, three gaps produced missed shader-visible view records (`~6` per frame in the fallback scan) and misattributed their `writer=` addresses: 1. **Unwrapped OS/CRT copy variants and `GetProcAddress` lookups**: - `port_descriptors::import` (and `titlewrite::import`) only wrapped static IAT imports named `"memcpy"` and `"memmove"`. The ~10,700 `memcpy`/`memmove` calls per frame into the `+0x4d9f400` frame allocator are non-view constants and list nodes (`0` `VIEW_TAG` records), whereas view-record copies through `RtlMoveMemory` / `RtlCopyMemory` (`ntdll.dll` / `kernel32.dll`, matching the `0x7ffc...` `0xe5`-byte span in #3259), `memcpy_s` / `memmove_s` (`ucrtbase` / `api-ms-win-crt-string-*`), or dynamic `kernel::GetProcAddress` lookups bypassed `port_descriptors::copied` entirely. 2. **Sparse beside-guard stores (`LEONIDA_STORE_BESIDE=1`) bypassed `port_descriptors` completely**: - `watch.rs` executes sparse faulting stores (`<= 4` in a 64 KiB guarded block) through `titlewrite::store` and returns `EXCEPTION_CONTINUE_EXECUTION` before `port_descriptors::faulted` runs. Any unpatched sparse store writing a `VIEW_TAG` record beside a guard was neither marked in `MARKS` nor recorded in `a.writers`. 3. **Self-blaming block faults in `a.writers[(off >> 16)]` (`base - 0x70000` at `+0x00` / `+0x80`)**: - `console_insn::near` places `descriptor_sites::apply`'s six patched `vmovups` stubs at `base - 0x70000` (`+0x00` = `SITES[0]`, `+0x40` = `SITES[1]`, `+0x80` = `SITES[2]`). Those stubs mark their own slots properly (`0.0 told and not taken yet`), but because `a.writers` tracks one last-faulting RIP per 64 KiB block (`2,048` descriptors), whenever a patched stub, wrapped copy, or `descriptor::copy_simple` / `descriptor::record` call unguarded a 64 KiB block, its RIP overwrote `a.writers` and masked unmarked writers in the same block. 4. **Pending-slot `tabled` counter skew**: - `port_descriptors::missed` incremented `CHECKED[4]` (`of draws' tables`) before checking `marked(a, index)` (`told and not taken yet`). ### Changes - **`port_descriptors.rs` & `titlewrite.rs`**: - Extend `import` (`REAL[6]`) to wrap `RtlCopyMemory`/`CopyMemory`, `RtlMoveMemory`/`MoveMemory`, `memcpy_s`, and `memmove_s` with ABI-matched wrappers, null/self-wrap guards, overflow-safe `scan_copied_range`, and race-free write-once `compare_exchange` binding. - Add `port_descriptors::note_store` called from `titlewrite::store` so sparse beside-guard stores writing `VIEW_TAG` records into the adopted heap mark their slot immediately and record the faulting RIP in `a.writers`. - Register `[start, end)` ranges of `descriptor_sites` stubs (`register_stubs`) and wrap tracked copies/view writes in thread-local `in_tracked_copy` so faults from already-marking stubs/wrappers/views neither blame themselves nor clobber unmarked writers in `a.writers`. - Move `CHECKED[4]` (`tabled`) after the `marked(a, index)` early return in `missed`. - **`leonida-hle/src/{host.rs, modules/kernel.rs}`**: - Route both `HostPolicy::resolve` and `kernel::GetProcAddress` through an OS/CRT system-DLL allow-list (`is_system_copy_dll`) and pin the backing module via `GetModuleHandleExW(FROM_ADDRESS | PIN)` (handling forwarders such as `kernel32!RtlMoveMemory` -> `ntdll`) so `FreeLibrary` cannot unload cached targets and non-system DLLs cannot overwrite global wrapper slots. - **`descriptor.rs`, `descriptor_sites.rs`, `apps/leonida/src/run.rs`**: - Return installed stub ranges via `descriptor_sites::apply_with_stubs` and register them at startup; pre-mark destination view slots in `descriptor::copy_simple` without double-counting `MARKED_BY_US`. ### Verification (No Game Files) - `python -I scripts/red_green.py HEAD --no-fetch --base origin/main`: **`verdict: red then green`** (`7` `red -> green`, `1,117` `pass on both` across `leonida`, `leonida-gpu`, `leonida-hle`, and `leonida-loader`, `0` regressions). - `cargo test --locked --target x86_64-pc-windows-msvc` (default and `--features diagnostics`): `port_descriptors::` (`9/9`), `port_descriptors_copy_wrap` (`1/1`), `titlewrite::` (`5/5`), `descriptor::` (`89/89`), `leonida-hle` (`259/259`), `leonida-loader` (`92/92`), `leonida` (`48/48`). - Clean 3-way merge verified against open PRs #2831 and #2832; `tools/d3d12_switches.py --check d3d12/docs/switches.md` and `scripts/check_no_game_data.py` clean. - Note: Not yet tested in-game (`LEONIDA_GAME_DIR` absent here); synthetic VEH/guard-page, copy-import, and `GetProcAddress` tests cover the exact fault and copy paths. AI-assisted: Gemini 4 Neon (XHigh) and Gemini 4 Carbon (High).
lixonik commented 2026-12-03 08:38:06 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by lixonik on 2026-12-03T08:38:06Z.


RUN (in game, RTX 5070 12 GB, 315 s in-world gate) -- PASS

  • Head tested: f8751e2a3 merged onto main (d9b618f10)
  • Preflight:
    • python -I scripts/check_no_game_data.py -- PASS
    • cargo test -p leonida-gpu --lib --locked port_descriptors:: -- 9 passed, 0 failed
    • cargo build --profile diag --features "diagnostics,dlss,mimalloc" --locked -- PASS
  • In-game run (Windows 10, RTX 5070 12 GB, Series S preset, DLSS, no Frame Generation, 315 s in world, 437.4 s total, 64 world samples, max 5,239 draws):
    • Runtime errors: 0; device lost: 0
    • Frame rate: median 26.9 fps (37.2 ms; slowest tenth 21.9, fastest tenth 28.1); 3000-4999 draws bucket: 27.1 fps (58 samples)
    • Matched main (d9b618f10) baseline on the same machine/preset: median 27.0 fps (37.1 ms; slowest tenth 20.2, fastest tenth 27.9); 3000-4999 draws bucket: 27.1 fps (55 samples; +0%)
    • Port 2 telemetry note (final periodic sample): 60,910 slots told (5,189 marked by our calls), 4,312 title memcpy/memmove calls into the heap with 0 view records marked, fallback ~16.0 pages / ~1.50 missed view records per frame (in line with matched main at 59,735 slots told, 4,142 heap copies / 0 marked, ~16.0 pages / ~1.21 missed per frame).

AI-assisted: yes (Antigravity -- Gemini 4 Neon).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7372533481 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3306#issuecomment-7372533481). Originally posted by [lixonik](https://github.com/lixonik) on 2026-12-03T08:38:06Z. --- RUN (in game, RTX 5070 12 GB, 315 s in-world gate) -- PASS - Head tested: `f8751e2a3` merged onto `main` (`d9b618f10`) - Preflight: - `python -I scripts/check_no_game_data.py` -- PASS - `cargo test -p leonida-gpu --lib --locked port_descriptors::` -- 9 passed, 0 failed - `cargo build --profile diag --features "diagnostics,dlss,mimalloc" --locked` -- PASS - In-game run (Windows 10, RTX 5070 12 GB, Series S preset, DLSS, no Frame Generation, 315 s in world, 437.4 s total, 64 world samples, max 5,239 draws): - Runtime errors: 0; device lost: 0 - Frame rate: median **26.9 fps** (37.2 ms; slowest tenth 21.9, fastest tenth 28.1); `3000-4999` draws bucket: **27.1 fps** (58 samples) - Matched `main` (`d9b618f10`) baseline on the same machine/preset: median **27.0 fps** (37.1 ms; slowest tenth 20.2, fastest tenth 27.9); `3000-4999` draws bucket: **27.1 fps** (55 samples; +0%) - Port 2 telemetry note (final periodic sample): 60,910 slots told (5,189 marked by our calls), 4,312 title `memcpy`/`memmove` calls into the heap with 0 view records marked, fallback ~16.0 pages / ~1.50 missed view records per frame (in line with matched `main` at 59,735 slots told, 4,142 heap copies / 0 marked, ~16.0 pages / ~1.21 missed per frame). AI-assisted: yes (Antigravity -- Gemini 4 Neon).
fiestorra commented 2026-12-03 08:39:05 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by fiestorra on 2026-12-03T08:39:05Z.


Las dos nuevas, corridas

#3306  d3d12 port 2: wrap RTL/safe copy imports & GetProcAddress    8 files, +878/−39
       cargo test -p leonida-gpu --lib  →  720 passed; 1 failed; 59 ignored

#3307  Report Cargo test targets that exit early in red-green       3 files, +106/−16
       pytest tests/test_red_green.py   →  42 passed + 10 subtests  (97 s)

En #3306 el fallo es el de siempre (views_are_made_beside…, la iGPU de esta máquina), y 720 contra los 715 de main — cinco tests más, medidos en el diff.

Y el cambio es de los que no se pueden probar sin el juego: envolver los GetProcAddress del port 2 y marcar las importaciones «al lado» — o sea, hacer que una llamada que no existe en la DLL del juego se vea como tal y no como un salto a la nada. Lo que el test cubre es el envoltorio; lo que no cubre es una DLL real sin ese símbolo.

En #3307 la proporción vuelve a ser la buena: 106 líneas, de las cuales la mayoría son test (+10 subtests sobre los 8 que tenía), en una herramienta de medición. Y es la tercera de la noche sobre red_green (con #3304 y el propio fichero), que empieza a ser el instrumento más revisado del repositorio — y con razón: es el que dice si algo está rojo.

Lo que no verifiqué en ninguna: el caso que las motiva — una DLL del juego sin el símbolo (#3306) y una suite mutada que sale antes de tiempo (#3307). Los dos necesitan un binario concreto, y los dos están simulados en los tests.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7372555295 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3306#issuecomment-7372555295). Originally posted by [fiestorra](https://github.com/fiestorra) on 2026-12-03T08:39:05Z. --- ## Las dos nuevas, corridas ``` #3306 d3d12 port 2: wrap RTL/safe copy imports & GetProcAddress 8 files, +878/−39 cargo test -p leonida-gpu --lib → 720 passed; 1 failed; 59 ignored #3307 Report Cargo test targets that exit early in red-green 3 files, +106/−16 pytest tests/test_red_green.py → 42 passed + 10 subtests (97 s) ``` **En `#3306` el fallo es el de siempre** (**`views_are_made_beside…`, la iGPU de esta máquina**), **y `720` contra los `715` de `main`** — **cinco tests más, medidos en el diff.** **Y el cambio es de los que no se pueden probar sin el juego**: **envolver los `GetProcAddress` del *port* 2 y marcar las importaciones «al lado»** — **o sea, hacer que una llamada que no existe en la DLL del juego se vea como tal y no como un salto a la nada.** **Lo que el test cubre es el envoltorio; lo que no cubre es una DLL real sin ese símbolo.** **En `#3307` la proporción vuelve a ser la buena**: **106 líneas, de las cuales la mayoría son test** (**+10 subtests** sobre los 8 que tenía), **en una herramienta de medición.** **Y es la tercera de la noche sobre `red_green`** (**con `#3304` y el propio fichero**), **que empieza a ser el instrumento más revisado del repositorio** — **y con razón: es el que dice si algo está rojo.** **Lo que no verifiqué en ninguna**: **el caso que las motiva** — **una DLL del juego sin el símbolo** (`#3306`) **y una suite mutada que sale antes de tiempo** (`#3307`). **Los dos necesitan un binario concreto, y los dos están simulados en los tests.**
icdmkg2 commented 2026-12-03 11:47:44 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by icdmkg2 on 2026-12-03T11:47:44Z.


Verified natively on Windows 11 (MSVC, no game files): \python -I scripts/red_green.py 3306\ against \origin/main\ (\053a1813, head \ 8751e2a3) across \leonida, \leonida-gpu, \leonida-hle, and \leonida-loader\ — *\ erdict: red then green* (7 red→green tests including \port_descriptors_copy_wrap\ and \get_proc_address_wraps_host_copy_exports_for_port_descriptors, 1117 pass on both). AI-assisted: Gemini 4 Neon (Antigravity).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7377188116 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3306#issuecomment-7377188116). Originally posted by [icdmkg2](https://github.com/icdmkg2) on 2026-12-03T11:47:44Z. --- Verified natively on Windows 11 (MSVC, no game files): \python -I scripts/red_green.py 3306\ against \origin/main\ (\053a1813\, head \ 8751e2a3\) across \leonida\, \leonida-gpu\, \leonida-hle\, and \leonida-loader\ — **\ erdict: red then green\** (**7** red→green tests including \port_descriptors_copy_wrap\ and \get_proc_address_wraps_host_copy_exports_for_port_descriptors\, **1117** pass on both). AI-assisted: Gemini 4 Neon (Antigravity).
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3306:upstream-pr/3306'
git switch 'upstream-pr/3306'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/3306'
git switch 'upstream-pr/3306'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3306'
git switch 'upstream-pr/3306'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3306'
git switch 'main'
git merge --squash 'upstream-pr/3306'
git switch 'main'
git merge --ff-only 'upstream-pr/3306'
git switch 'main'
git merge 'upstream-pr/3306'
git push origin 'main'
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!3306
No description provided.