loader/windows: batch IAT VirtualProtect calls per 4 KiB page (D3D12-LOADER-BATCHED-IAT-PROTECT) #2891

Open
djrolfes wants to merge 1 commit from upstream-pr/2891 into main
djrolfes commented 2026-12-01 15:37:03 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by djrolfes on 2026-12-01T15:37:03Z.


Claimed in the coordination issue as: D3D12-LOADER-BATCHED-IAT-PROTECT.

What and why

Batch IAT VirtualProtect calls per 4 KiB page inside LoadedImage::write_slots (d3d12/crates/leonida-loader/src/windows.rs) instead of protecting and restoring every 8-byte import slot individually.

  • Why: On main, LoadedImage::write_slots issues two VirtualProtect syscalls per import slot (make writable → write 8 bytes → restore). Across hundreds/thousands of bound title imports (and delay-load tables in .didat), this causes two OS page-protection syscalls per import slot on every startup.
  • Change:
    • Extracts write_slots_os / write_slots_with in d3d12/crates/leonida-loader/src/windows.rs.
    • Stable-sorts (rva, address) pairs by RVA (preserving last-writer-wins semantics for duplicate RVAs), groups consecutive slots sharing the same 4 KiB page (addr & !4095), and issues one VirtualProtect(page, 4096, PAGE_READWRITE, &mut old) + restore per page — preserving distinct protections across adjacent pages/sections (e.g. .rdata vs .didat).
    • Defensively handles any unaligned 8-byte slot straddling a 4 KiB boundary ((addr & 4095) > 4088) with an 8-byte unaligned fallback so it never writes past the protected page.
  • Scope discipline: Strictly one topic; content-addressed image caching is split into its own separate PR (D3D12-LOADER-CONTENT-ADDRESSED-IMAGE, verified clean merge via git merge-tree).
  • Evidence classification: READ IN CODE (d3d12/crates/leonida-loader/src/windows.rs) + red→green unit tests (both mock syscall-count test and real VirtualAlloc + PAGE_READONLY + VirtualQuery test) + MEASURED 300 s in-world game gate.

Tested

  • python3 -I scripts/check_no_game_data.py d3d12/crates/leonida-loader/src/windows.rs → exit 0.
  • Cross-compiled leonida-loader unit test binary (x86_64-pc-windows-msvc) and ran under Wine:
    • RED on origin/main unbatched loop (running windows::tests::write_slots_batches_virtual_protect_per_page against origin/main's per-slot loop):
      running 1 test
      thread 'windows::tests::write_slots_batches_virtual_protect_per_page' panicked:
      assertion `left == right` failed
        left: 42 per-slot (8-byte) protect calls
       right: [(0, 4096, 4), (0, 4096, 2), (4096, 4096, 4), (4096, 4096, 17)]
      test result: FAILED. 0 passed; 1 failed; 0 ignored
      
    • GREEN on PR head ce130c717 (rebased onto 3e7b34a52):
      test windows::tests::write_slots_batches_virtual_protect_per_page ... ok
      test windows::tests::write_slots_os_updates_readonly_pages_and_restores_protection ... ok
      test result: ok. 86 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
      
  • 300 s in-world game gate (MEASURED on exact PR head ce130c717, Series S + DLSS Quality 1280×720 → 1920×1080, Option A mods/gate_driver mode = roam loaded):
    • Verdict: PASS (310.93 s in-world after world entry at 69.46 s; also passed an earlier cold-cache 310.22 s run with 0 errors).
    • Frames & pacing: 3,273 frames after +60 s (3,377 total world presents), 15.35 median FPS (15.77 end median FPS), 111.32 ms p95 frame time, 3.188 s longest present gap (<= 10.0 s).
    • Memory & stability: 6,690 MiB peak VRAM (<= 7,400 MiB), 0 device losses (0x887A0005), 0 crashes, 0 panics, 0 faults before stop, 0 kernel NVRM: Xid errors.
    • Option A gate_driver note: mods/gate_driver loaded in mode = roam with 0 GATE FAIL; its 10 s menu-press cadence missed the brief world-entry probe window so the 310.93 s run stayed on the in-world camera cleanly at 15.35 FPS.

GPUs tested: NVIDIA GeForce RTX 3070 Ti 8 GB, driver 620.73.04, Arch Linux (Wine 11.22 + VKD3D-Proton 3.2.0).

AI-assisted: yes (authored by Gemini 4 Neon; reviewed in a separate independent review pass by Gemini 4 Neon).

Checklist

  • Based on current main (3e7b34a52) and merges cleanly (a conflicting pull request is labeled needs rebase).
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (check_no_game_data.py clean on both source and PR description).
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (n/a — loader IAT page-protection batching)
<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5589005310 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2891). Originally posted by [djrolfes](https://github.com/djrolfes) on 2026-12-01T15:37:03Z. --- Claimed in the coordination issue as: [`D3D12-LOADER-BATCHED-IAT-PROTECT`](https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7313473258). ### What and why Batch IAT `VirtualProtect` calls per 4 KiB page inside `LoadedImage::write_slots` (`d3d12/crates/leonida-loader/src/windows.rs`) instead of protecting and restoring every 8-byte import slot individually. - **Why:** On `main`, `LoadedImage::write_slots` issues two `VirtualProtect` syscalls per import slot (make writable → write 8 bytes → restore). Across hundreds/thousands of bound title imports (and delay-load tables in `.didat`), this causes two OS page-protection syscalls per import slot on every startup. - **Change:** - Extracts `write_slots_os` / `write_slots_with` in `d3d12/crates/leonida-loader/src/windows.rs`. - Stable-sorts `(rva, address)` pairs by RVA (preserving last-writer-wins semantics for duplicate RVAs), groups consecutive slots sharing the same 4 KiB page (`addr & !4095`), and issues one `VirtualProtect(page, 4096, PAGE_READWRITE, &mut old)` + restore per page — preserving distinct protections across adjacent pages/sections (e.g. `.rdata` vs `.didat`). - Defensively handles any unaligned 8-byte slot straddling a 4 KiB boundary (`(addr & 4095) > 4088`) with an 8-byte unaligned fallback so it never writes past the protected page. - **Scope discipline:** Strictly one topic; content-addressed image caching is split into its own separate PR (`D3D12-LOADER-CONTENT-ADDRESSED-IMAGE`, verified clean merge via `git merge-tree`). - **Evidence classification:** **READ IN CODE** (`d3d12/crates/leonida-loader/src/windows.rs`) + red→green unit tests (both mock syscall-count test and real `VirtualAlloc` + `PAGE_READONLY` + `VirtualQuery` test) + **MEASURED** 300 s in-world game gate. ### Tested - `python3 -I scripts/check_no_game_data.py d3d12/crates/leonida-loader/src/windows.rs` → exit 0. - Cross-compiled `leonida-loader` unit test binary (`x86_64-pc-windows-msvc`) and ran under Wine: - **RED on `origin/main` unbatched loop** (running `windows::tests::write_slots_batches_virtual_protect_per_page` against `origin/main`'s per-slot loop): ```text running 1 test thread 'windows::tests::write_slots_batches_virtual_protect_per_page' panicked: assertion `left == right` failed left: 42 per-slot (8-byte) protect calls right: [(0, 4096, 4), (0, 4096, 2), (4096, 4096, 4), (4096, 4096, 17)] test result: FAILED. 0 passed; 1 failed; 0 ignored ``` - **GREEN on PR head `ce130c717` (rebased onto `3e7b34a52`)**: ```text test windows::tests::write_slots_batches_virtual_protect_per_page ... ok test windows::tests::write_slots_os_updates_readonly_pages_and_restores_protection ... ok test result: ok. 86 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out ``` - **300 s in-world game gate (MEASURED on exact PR head `ce130c717`, Series S + DLSS Quality `1280×720 → 1920×1080`, Option A `mods/gate_driver` `mode = roam` loaded):** - **Verdict:** **PASS** (`310.93 s` in-world after world entry at `69.46 s`; also passed an earlier cold-cache 310.22 s run with `0` errors). - **Frames & pacing:** `3,273` frames after +60 s (`3,377` total world presents), `15.35` median FPS (`15.77` end median FPS), `111.32 ms` p95 frame time, `3.188 s` longest present gap (`<= 10.0 s`). - **Memory & stability:** `6,690 MiB` peak VRAM (`<= 7,400 MiB`), `0` device losses (`0x887A0005`), `0` crashes, `0` panics, `0` faults before stop, `0` kernel `NVRM: Xid` errors. - **Option A `gate_driver` note:** `mods/gate_driver` loaded in `mode = roam` with `0` `GATE FAIL`; its 10 s menu-press cadence missed the brief world-entry probe window so the 310.93 s run stayed on the in-world camera cleanly at `15.35` FPS. GPUs tested: NVIDIA GeForce RTX 3070 Ti 8 GB, driver 620.73.04, Arch Linux (Wine 11.22 + VKD3D-Proton 3.2.0). AI-assisted: yes (authored by Gemini 4 Neon; reviewed in a separate independent review pass by Gemini 4 Neon). ### Checklist - [x] Based on current `main` (`3e7b34a52`) and merges cleanly (a conflicting pull request is labeled `needs rebase`). - [x] One topic; follow-up work goes in a new pull request. - [x] No game data, keys or decryption (`check_no_game_data.py` clean on both source and PR description). - [ ] A new translator rule is in the contract table of `docs/design.md`, with how it was confirmed. (n/a — loader IAT page-protection batching)
merzleckeier commented 2026-12-01 16:10:02 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by merzleckeier on 2026-12-01T16:10:02Z.


Independent test of mixed protections across the fallback boundary at ce130c71 + 0ff8a532f. The two stock Windows tests passed under Wine 11.22. I added a check on private synthetic memory with adjacent pages initially read-only and read/write. Aligned slots on those pages preserve both protections. With a cross-page slot, the data writes successfully but VirtualQuery shows both pages read-only afterward.

The cross-page VirtualProtect call saves the old protection of the first page, then applies that single value to both pages when restoring. This matches the Win32 API documentation. A local trial saving and restoring the pages separately passed the mixed case and both stock tests. This is a result for the defensive fallback on synthetic memory. I did not verify whether the image parser produces such a slot on a normal load.

MEASURED. AI-assisted (Codex).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7317145951 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2891#issuecomment-7317145951). Originally posted by [merzleckeier](https://github.com/merzleckeier) on 2026-12-01T16:10:02Z. --- Independent test of mixed protections across the fallback boundary at ce130c71 + 0ff8a532f. The two stock Windows tests passed under Wine 11.22. I added a check on private synthetic memory with adjacent pages initially read-only and read/write. Aligned slots on those pages preserve both protections. With a cross-page slot, the data writes successfully but VirtualQuery shows both pages read-only afterward. The cross-page VirtualProtect call saves the old protection of the first page, then applies that single value to both pages when restoring. This matches the [Win32 API documentation](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualprotect). A local trial saving and restoring the pages separately passed the mixed case and both stock tests. This is a result for the defensive fallback on synthetic memory. I did not verify whether the image parser produces such a slot on a normal load. MEASURED. AI-assisted (Codex).
KelboLive commented 2026-12-01 17:26:21 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by KelboLive on 2026-12-01T17:26:21Z.

Review: COMMENTED


Batching itself looks right: stable sort by RVA, grouping on addr & !4095, and per-page save/restore preserve mixed .rdata/.didat protections, duplicate RVAs still last-writer-wins, and the mock test pins the call count (4 calls for 21 slots over 2 pages vs 42 on main). Restore is load-bearing — replacing it with let _ = old fails both new tests with page 0x0 protection not restored. Merge is clean against current main, and it pairs cleanly with #2889 and #2890.

One real gap, and it matches merzleckeier's note: the unaligned-straddle fallback (windows.rs:496-503). VirtualProtect(addr, 8, …) rounds to cover both pages, but old is only page 0's protection and the restore at :500 writes it to both, so a mixed RO/RW boundary ends uniformly page 0's protection. I reproduced it on synthetic memory (page0=0x2 page1=0x2 for both the new and the old per-slot path). It is pre-existing, not a regression — main's loop did the same — and write_unaligned is a genuine improvement over write_volatile on a possibly unaligned pointer (main's loop trips the debug alignment abort). But the doc claim at :478-480 ("preserving each page's original protection") is too strong for this branch, and the added real test only exercises RO/RO.

Suggest: save/restore each page separately in the fallback (or reject unaligned IAT RVAs), extend the real test to page0=RO/page1=RW, and soften that doc sentence either way. Restore errors at :519 are still ignored, same as main, which is fine to leave.

Not verifiable here: the per-page call-count reduction on a real title image and the 300 s in-world gate. Also worth checking whether the PE parser can even yield an unaligned slot — leonida-pe/src/image.rs:337-343 bounds-checks rva+8 <= SizeOfImage but not 8-byte alignment.

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6136429849 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2891#pullrequestreview-6136429849). Originally posted by [KelboLive](https://github.com/KelboLive) on 2026-12-01T17:26:21Z. **Review:** COMMENTED --- Batching itself looks right: stable sort by RVA, grouping on `addr & !4095`, and per-page save/restore preserve mixed `.rdata`/`.didat` protections, duplicate RVAs still last-writer-wins, and the mock test pins the call count (4 calls for 21 slots over 2 pages vs 42 on main). Restore is load-bearing — replacing it with `let _ = old` fails both new tests with `page 0x0 protection not restored`. Merge is clean against current main, and it pairs cleanly with #2889 and #2890. One real gap, and it matches merzleckeier's note: the **unaligned-straddle fallback** (`windows.rs:496-503`). `VirtualProtect(addr, 8, …)` rounds to cover both pages, but `old` is only page 0's protection and the restore at `:500` writes it to both, so a mixed RO/RW boundary ends uniformly page 0's protection. I reproduced it on synthetic memory (`page0=0x2 page1=0x2` for both the new and the old per-slot path). It is **pre-existing, not a regression** — main's loop did the same — and `write_unaligned` is a genuine improvement over `write_volatile` on a possibly unaligned pointer (main's loop trips the debug alignment abort). But the doc claim at `:478-480` ("preserving each page's original protection") is too strong for this branch, and the added real test only exercises RO/RO. Suggest: save/restore each page separately in the fallback (or reject unaligned IAT RVAs), extend the real test to page0=RO/page1=RW, and soften that doc sentence either way. Restore errors at `:519` are still ignored, same as main, which is fine to leave. Not verifiable here: the per-page call-count reduction on a real title image and the 300 s in-world gate. Also worth checking whether the PE parser can even yield an unaligned slot — `leonida-pe/src/image.rs:337-343` bounds-checks `rva+8 <= SizeOfImage` but not 8-byte alignment.
MoonEyes commented 2026-12-02 12:30:37 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-02T12:30:37Z.


This pull request touches the render path, so it needs an in-game run before it can be merged: unit tests and CI do not catch rendering regressions (a device loss after an earlier merge is why this gate exists).

Could you, or anyone with a working setup, post a run report on the current head merged onto current main:

  • the head SHA and the main SHA it was merged onto;
  • GPU, driver and OS;
  • at least 300 s in the world after loading;
  • device lost / crashes (count), and rendered fps (median) if you have them;
  • the same run on main alone for comparison, if you can.

Please do not attach logs or screenshots that show game content. If a run on this exact head is already posted, a link to it in a reply is enough.

AI-assisted (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7345447211 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2891#issuecomment-7345447211). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-02T12:30:37Z. --- This pull request touches the render path, so it needs an in-game run before it can be merged: unit tests and CI do not catch rendering regressions (a device loss after an earlier merge is why this gate exists). Could you, or anyone with a working setup, post a run report on the **current head** merged onto current `main`: - the head SHA and the `main` SHA it was merged onto; - GPU, driver and OS; - at least 300 s in the world after loading; - device lost / crashes (count), and rendered fps (median) if you have them; - the same run on `main` alone for comparison, if you can. Please do not attach logs or screenshots that show game content. If a run on this exact head is already posted, a link to it in a reply is enough. AI-assisted (Claude Code).
Kal0s-design commented 2026-12-02 15:14:09 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Kal0s-design on 2026-12-02T15:14:09Z.


Ran natively on Windows 11, head ce130c717 merged into main (43fc605ed, clean merge; main has since advanced one commit that only touches a PowerShell script), Rust 1.98.1. This adds real mapped-image numbers and three edge cases that the comments above do not cover.

Check on the merge Result
cargo test --locked -p leonida-loader 92 + 2 + 1 passed, 0 failed (both new tests included)
cargo clippy --locked -p leonida-loader --all-targets -- -D warnings clean
cargo check --locked --workspace --all-targets builds

Real images. I wanted real MEM_IMAGE pages instead of private memory. I took copies of eight stock system DLLs, parsed each with ImageInfo::parse (imports plus delay imports) and mapped it with LoadLibraryExW(DONT_RESOLVE_DLL_REFERENCES), so no code runs. Then I wrote a distinct value into every IAT slot. For main I used main's per-slot loop copied verbatim, plus a call counter. I compared VirtualQuery on every page of the image before and after.

DLL slots (delay) IAT pages VirtualProtect calls main → PR time main → PR (µs) pages whose protection changed wrong values
combase 714 (168) 3 1428 → 6 1861 → 263 0 / 0 0 / 0
d3d11 384 (159) 2 768 → 4 935 → 154 0 / 0 0 / 0
d3d12 118 (0) 1 236 → 2 287 → 61 0 / 0 0 / 0
dxgi 468 (167) 3 936 → 6 1137 → 150 0 / 0 0 / 0
mfplat 424 (182) 3 848 → 6 1063 → 187 0 / 0 0 / 0
shell32 2945 (1834) 8 5890 → 16 7042 → 997 0 / 0 0 / 0
user32 1146 (26) 5 2292 → 10 2850 → 200 0 / 0 0 / 0
windows.storage 1664 (956) 6 3328 → 12 4173 → 645 0 / 0 0 / 0

All IAT pages were PAGE_READONLY and none of the slots was unaligned. The timings are rough: debug build, a single run per image, and main's loop always ran first. They come to roughly 2 ms saved per thousand slots. The call counts are the solid result.

Private memory edge cases (PR code):

Case Before After Notes
20 aligned slots on 5 pages, reverse order, including 0x000 and 0xFF8 RX, RO, RWX, RW, RO RX, RO, RWX, RW, RO 10 calls, all values correct
RW request for page 3 fails (injected) RO, RX, RO RO, RX, RO returns Err. Pages 1 and 2 were written and restored, page 3 was untouched, and no page was left writable
Straddling slot at 0xFFC RX, RO RX, RX the data page becomes executable
Straddling slot at 0xFFC RO, RX RO, RO the code page loses execute
Unaligned slots 0xFF4, 0xFFC, 0x1004 (debug build) RO, RO aborts ptr::write_volatile requires that the pointer argument is aligned, at the batch path's write_volatile (windows.rs:517 on the merge). The release build completes

The straddle rows are the known fallback bug from the comments above, now with execute permissions. According to the review above, main's per-slot loop does the same, so it is not a regression. I ran these rows on the PR code only and did not rerun RX/RO on main. The RX/RO case is the same class as the RWX page in #3124: a non-code page ends up executable. The last row is not a regression either, because main's write_volatile aborts on unaligned slots too. What it shows is that the fallback only covers half of the unaligned case. An unaligned IAT makes every one of its slots unaligned, but only the one that crosses the page boundary goes through write_unaligned. The others still use write_volatile and abort in debug builds. I read the parser code: leonida-pe entries() derives every slot as iat_rva + 8*i and does not check alignment. If the fallback stays, saving and restoring each page separately and using write_unaligned in the batch loop (or rejecting an unaligned IAT RVA in the parser) would cover both rows.

Not checked: a real title image and the 300 s in-world gate. Also not checked: an image whose IAT shares a page with code, which matters because the whole 4 KiB page loses execute while it is RW. That was already true on main for that page.

GPUs tested: n/a (CPU-only tests).
AI-assisted: yes (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7349977451 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2891#issuecomment-7349977451). Originally posted by [Kal0s-design](https://github.com/Kal0s-design) on 2026-12-02T15:14:09Z. --- Ran natively on Windows 11, head `ce130c717` merged into `main` (`43fc605ed`, clean merge; main has since advanced one commit that only touches a PowerShell script), Rust 1.98.1. This adds real mapped-image numbers and three edge cases that the comments above do not cover. | Check on the merge | Result | |---|---| | `cargo test --locked -p leonida-loader` | 92 + 2 + 1 passed, 0 failed (both new tests included) | | `cargo clippy --locked -p leonida-loader --all-targets -- -D warnings` | clean | | `cargo check --locked --workspace --all-targets` | builds | **Real images.** I wanted real `MEM_IMAGE` pages instead of private memory. I took copies of eight stock system DLLs, parsed each with `ImageInfo::parse` (imports plus delay imports) and mapped it with `LoadLibraryExW(DONT_RESOLVE_DLL_REFERENCES)`, so no code runs. Then I wrote a distinct value into every IAT slot. For main I used main's per-slot loop copied verbatim, plus a call counter. I compared `VirtualQuery` on every page of the image before and after. | DLL | slots (delay) | IAT pages | `VirtualProtect` calls main → PR | time main → PR (µs) | pages whose protection changed | wrong values | |---|---|---|---|---|---|---| | combase | 714 (168) | 3 | 1428 → 6 | 1861 → 263 | 0 / 0 | 0 / 0 | | d3d11 | 384 (159) | 2 | 768 → 4 | 935 → 154 | 0 / 0 | 0 / 0 | | d3d12 | 118 (0) | 1 | 236 → 2 | 287 → 61 | 0 / 0 | 0 / 0 | | dxgi | 468 (167) | 3 | 936 → 6 | 1137 → 150 | 0 / 0 | 0 / 0 | | mfplat | 424 (182) | 3 | 848 → 6 | 1063 → 187 | 0 / 0 | 0 / 0 | | shell32 | 2945 (1834) | 8 | 5890 → 16 | 7042 → 997 | 0 / 0 | 0 / 0 | | user32 | 1146 (26) | 5 | 2292 → 10 | 2850 → 200 | 0 / 0 | 0 / 0 | | windows.storage | 1664 (956) | 6 | 3328 → 12 | 4173 → 645 | 0 / 0 | 0 / 0 | All IAT pages were `PAGE_READONLY` and none of the slots was unaligned. The timings are rough: debug build, a single run per image, and main's loop always ran first. They come to roughly 2 ms saved per thousand slots. The call counts are the solid result. **Private memory edge cases (PR code):** | Case | Before | After | Notes | |---|---|---|---| | 20 aligned slots on 5 pages, reverse order, including `0x000` and `0xFF8` | RX, RO, RWX, RW, RO | RX, RO, RWX, RW, RO | 10 calls, all values correct | | RW request for page 3 fails (injected) | RO, RX, RO | RO, RX, RO | returns `Err`. Pages 1 and 2 were written and restored, page 3 was untouched, and no page was left writable | | Straddling slot at `0xFFC` | RX, RO | **RX, RX** | the data page becomes executable | | Straddling slot at `0xFFC` | RO, RX | **RO, RO** | the code page loses execute | | Unaligned slots `0xFF4`, `0xFFC`, `0x1004` (debug build) | RO, RO | aborts | `ptr::write_volatile requires that the pointer argument is aligned`, at the batch path's `write_volatile` (`windows.rs:517` on the merge). The release build completes | The straddle rows are the known fallback bug from the comments above, now with execute permissions. According to the review above, main's per-slot loop does the same, so it is not a regression. I ran these rows on the PR code only and did not rerun RX/RO on main. The RX/RO case is the same class as the RWX page in #3124: a non-code page ends up executable. The last row is not a regression either, because main's `write_volatile` aborts on unaligned slots too. What it shows is that the fallback only covers half of the unaligned case. An unaligned IAT makes every one of its slots unaligned, but only the one that crosses the page boundary goes through `write_unaligned`. The others still use `write_volatile` and abort in debug builds. I read the parser code: `leonida-pe` `entries()` derives every slot as `iat_rva + 8*i` and does not check alignment. If the fallback stays, saving and restoring each page separately and using `write_unaligned` in the batch loop (or rejecting an unaligned IAT RVA in the parser) would cover both rows. Not checked: a real title image and the 300 s in-world gate. Also not checked: an image whose IAT shares a page with code, which matters because the whole 4 KiB page loses execute while it is RW. That was already true on main for that page. GPUs tested: n/a (CPU-only tests). AI-assisted: yes (Claude Code).
MoonEyes commented 2026-12-02 18:29:33 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-02T18:29:33Z.


Verification of #2891 (D3D12-LOADER-BATCH IAT VirtualProtect per page): third-party code review plus a CI triage on Linux x86_64. The code was not built: leonida-loader/src/windows.rs is Windows-only.

  • Head: ce130c717, merge base 3e7b34a52. It merges cleanly into main 45dc41f95. Diff: d3d12/crates/leonida-loader/src/windows.rs, +173/-18.

CI failures on this head are not caused by this PR

  • linux-python-and-viewer failed in tests/test_piecewise_parse.py, test_wave_diff.py, test_wave_trace.py, test_x64_recomp.py and test_x64_recomp_qemu_runner.py. check is the summary job and failed with it. The PR touches none of these files, and it changes no Python.
  • On the local merge with current main, each of the five passes with python -I tests/<name>.py (test_x64_recomp: OK, 34 skipped). Current main CI passes linux-python-and-viewer. A rerun of the checks should clear both.

Review

  • write_slots_with sorts the slots by RVA. The sort is stable, so a later duplicate still wins. It then makes one VirtualProtect(page, 4096, RW) call and one restore per 4 KiB page. Image protections are per page, so restoring the old value each page reported is exact for aligned slots.
  • A slot that straddles a page boundary takes the 8-byte fallback (L496-503). As measured earlier in this thread, that fallback restores both pages to the first page's protection. The behaviour was already on main, and the PE format keeps IAT slots 8-byte aligned, so it is not a blocker. A per-page save and restore would close it.
  • Failures of the restore call are ignored, as on main.
  • The tests are good. One injects protect to count the calls; the other runs VirtualAlloc/VirtualQuery on read-only pages. A native Windows run on this head (92+2+1 passed, clippy clean) is posted above.
  • python -I scripts/check_no_game_data.py on the changed file: clean.

Verdict: blocked by CI. The red checks are unrelated to the change and need a rerun. The code is ready apart from the existing straddle-restore note.

AI-assisted verification: Claude Opus (Claude Code), separate agent per batch.


Generated by Claude Code

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7354676873 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2891#issuecomment-7354676873). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-02T18:29:33Z. --- **Verification of #2891 (D3D12-LOADER-BATCH IAT VirtualProtect per page)**: third-party code review plus a CI triage on Linux x86_64. The code was not built: `leonida-loader/src/windows.rs` is Windows-only. - Head: `ce130c717`, merge base `3e7b34a52`. It merges cleanly into `main` `45dc41f95`. Diff: `d3d12/crates/leonida-loader/src/windows.rs`, +173/-18. **CI failures on this head are not caused by this PR** - `linux-python-and-viewer` failed in `tests/test_piecewise_parse.py`, `test_wave_diff.py`, `test_wave_trace.py`, `test_x64_recomp.py` and `test_x64_recomp_qemu_runner.py`. `check` is the summary job and failed with it. The PR touches none of these files, and it changes no Python. - On the local merge with current `main`, each of the five passes with `python -I tests/<name>.py` (`test_x64_recomp`: OK, 34 skipped). Current `main` CI passes `linux-python-and-viewer`. A rerun of the checks should clear both. **Review** - `write_slots_with` sorts the slots by RVA. The sort is stable, so a later duplicate still wins. It then makes one `VirtualProtect(page, 4096, RW)` call and one restore per 4 KiB page. Image protections are per page, so restoring the `old` value each page reported is exact for aligned slots. - A slot that straddles a page boundary takes the 8-byte fallback (L496-503). As measured earlier in this thread, that fallback restores both pages to the first page's protection. The behaviour was already on `main`, and the PE format keeps IAT slots 8-byte aligned, so it is not a blocker. A per-page save and restore would close it. - Failures of the restore call are ignored, as on `main`. - The tests are good. One injects `protect` to count the calls; the other runs `VirtualAlloc`/`VirtualQuery` on read-only pages. A native Windows run on this head (92+2+1 passed, clippy clean) is posted above. - `python -I scripts/check_no_game_data.py` on the changed file: clean. **Verdict:** blocked by CI. The red checks are unrelated to the change and need a rerun. The code is ready apart from the existing straddle-restore note. AI-assisted verification: Claude Opus (Claude Code), separate agent per batch. --- _Generated by [Claude Code](https://claude.ai/code)_
MoonEyes commented 2026-12-02 21:35:00 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-02T21:35:00Z.


RUN (independent run on Windows, head ce130c717a4df69ed9131faa2a6c80796e3dbac9, merged into main b41763227aeed2d23c98af84bcbc1bddc7acdc90 with git merge --no-ff)

Merge was clean (merge base 3e7b34a52, no conflict). The only file changed is d3d12/crates/leonida-loader/src/windows.rs (+173/-18). Native Windows 11, Rust release profile, one shared target directory, no leonida.exe running during the builds.

Green

Command Result
cargo test -p leonida-loader --release --locked lib 92 passed, load_probe 2 passed, title_dlls 1 passed, 0 failed. Both new tests (write_slots_batches_virtual_protect_per_page, write_slots_os_updates_readonly_pages_and_restores_protection) pass
cargo test -p leonida-gpu --release --locked --lib 703 passed, 0 failed, 59 ignored

The PR touches no leonida-gpu code and no diagnostics code, so --features diagnostics was not run. It touches no Python test. leonida-gpu does not depend on leonida-loader (only leonida-hle does), so the gpu run is a sanity run, not evidence for this change.

Red

The new tests live in the changed file, so checking out main's version of that file removes them and a plain red run is impossible. I mutated the new code on the merge instead, restoring the file with git checkout HEAD -- <file> after each run (6 mutations, then a main-style loop):

Mutation Outcome
Batch-page restore removed both tests fail (killed)
Sort by RVA removed the mock test fails (killed); the real-memory test still passes
Straddle fallback disabled the test process aborts before reporting (killed, crash)
Page-change break removed from the grouping loop the mock test fails (killed)
Batch restore hard-coded to PAGE_READONLY the mock test fails (killed); the real-memory test, which only uses read-only pages, still passes
Straddle-path restore removed the real-memory test fails (killed)
write_slots_with body replaced by main's per-slot protect/write/restore loop the mock test fails with 42 per-slot 8-byte protect calls against the expected 4 page calls (killed); the real-memory test passes, as expected, since it checks values and final protection, not call count

Every mutation I tried was killed by at least one test. Surviving behaviour: none among these seven. The mixed-protection straddle case below is not a mutation but a gap in the tests.

Review

  • Default-off switch: none added. The change is unconditional and internal to IAT writing, so there is no docs/switches.md entry to regenerate (checked: the diff does not touch it).
  • Ordering: slots are stable-sorted by RVA, so a later duplicate still wins (the mock test covers it). Each page is made RW, written, then restored, one pair per page.
  • Lifetimes and fences: no GPU object, no fence, no threading involved; the write runs once at load on the mapped image. write_slots_os keeps unsafe with a documented contract.
  • Error path: if the RW request fails, the function returns Err before touching that page. Restore failures are ignored, as on main.
  • Known gap (pre-existing, not a regression): for an 8-byte slot straddling a page boundary, one VirtualProtect covers both pages but only page 0's old protection is saved and written back to both. Two earlier comments on the thread reproduced it on synthetic memory (read-only/read-write pair ends uniformly read-only; a later comment shows exec bits changing). The doc comment on write_slots_with ("preserving each page's original protection") is stronger than the straddle branch delivers, and neither new test covers a mixed pair. A per-page save/restore in the fallback, a softer doc sentence, or rejecting unaligned IAT RVAs in the parser would close it. I did not verify whether real images can yield such a slot; the PE format keeps IAT slots 8-byte aligned.
  • Second note from the thread: the batch loop still uses write_volatile, so an unaligned (not straddling) slot would abort in a debug build, as main's loop does. Not a regression.
  • Claim: the PR body links the claim in the coordination thread under issues/2570 (item D3D12-LOADER-BATCHED-IAT-PROTECT). I did not re-read the claim table.
  • Open reviewer questions: the straddle restore (two reviewers, plus the maintainer verification), still unanswered in code. The head has not changed since (ce130c717).
  • CI on this head: check and linux-python-and-viewer were red on the PR's last run; the maintainer comment attributes this to five unrelated Python tests and says they pass on the merge. I did not run those Python tests here.
  • Overlap: a reviewer says it pairs cleanly with #2889 and #2890. Image caching is stated to be a separate PR. I did not list other open PRs touching windows.rs.
  • In-game runs on this exact head: the PR body reports a 300 s in-world gate on ce130c717 (author's own run, Linux/Wine with an RTX 3070 Ti, 0 device losses). A native Windows run on this head by another contributor covers CPU-only tests and real mapped system DLLs (call counts 1428 to 6, etc.), not the game. I did not reproduce the gate.

Not covered

  • No in-game run by me, no title image, no 300 s gate.
  • Mixed read-only/read-write page pair on a straddling slot (the known gap above).
  • Debug-build behaviour with unaligned slots (release profile only here).
  • The five unrelated Python tests from the red CI job; CI itself was not rerun.
  • Other open PRs touching the same file were not enumerated.

Verdict

PARTIAL. The code does what it says: tests are green on the merge with current main, and every mutation of the new logic is caught. The straddle-restore gap is pre-existing and unfixed, and the doc sentence overstates it. The PR body reports a 300 s in-world gate on this head, but it was not reproduced here and the CI summary was red at the last run; in-game run still required on a native Windows setup if the project wants an independent one.

AI-assisted (Claude Code), models: Claude Opus 5.5 (checker), separate Claude Opus 5.5 judge.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7359485472 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2891#issuecomment-7359485472). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-02T21:35:00Z. --- RUN (independent run on Windows, head `ce130c717a4df69ed9131faa2a6c80796e3dbac9`, merged into `main` `b41763227aeed2d23c98af84bcbc1bddc7acdc90` with `git merge --no-ff`) Merge was clean (merge base `3e7b34a52`, no conflict). The only file changed is `d3d12/crates/leonida-loader/src/windows.rs` (+173/-18). Native Windows 11, Rust release profile, one shared target directory, no `leonida.exe` running during the builds. ## Green | Command | Result | |---|---| | `cargo test -p leonida-loader --release --locked` | lib 92 passed, `load_probe` 2 passed, `title_dlls` 1 passed, 0 failed. Both new tests (`write_slots_batches_virtual_protect_per_page`, `write_slots_os_updates_readonly_pages_and_restores_protection`) pass | | `cargo test -p leonida-gpu --release --locked --lib` | 703 passed, 0 failed, 59 ignored | The PR touches no `leonida-gpu` code and no diagnostics code, so `--features diagnostics` was not run. It touches no Python test. `leonida-gpu` does not depend on `leonida-loader` (only `leonida-hle` does), so the gpu run is a sanity run, not evidence for this change. ## Red The new tests live in the changed file, so checking out main's version of that file removes them and a plain red run is impossible. I mutated the new code on the merge instead, restoring the file with `git checkout HEAD -- <file>` after each run (6 mutations, then a main-style loop): | Mutation | Outcome | |---|---| | Batch-page restore removed | both tests fail (killed) | | Sort by RVA removed | the mock test fails (killed); the real-memory test still passes | | Straddle fallback disabled | the test process aborts before reporting (killed, crash) | | Page-change break removed from the grouping loop | the mock test fails (killed) | | Batch restore hard-coded to `PAGE_READONLY` | the mock test fails (killed); the real-memory test, which only uses read-only pages, still passes | | Straddle-path restore removed | the real-memory test fails (killed) | | `write_slots_with` body replaced by main's per-slot protect/write/restore loop | the mock test fails with 42 per-slot 8-byte protect calls against the expected 4 page calls (killed); the real-memory test passes, as expected, since it checks values and final protection, not call count | Every mutation I tried was killed by at least one test. Surviving behaviour: none among these seven. The mixed-protection straddle case below is not a mutation but a gap in the tests. ## Review - Default-off switch: none added. The change is unconditional and internal to IAT writing, so there is no `docs/switches.md` entry to regenerate (checked: the diff does not touch it). - Ordering: slots are stable-sorted by RVA, so a later duplicate still wins (the mock test covers it). Each page is made RW, written, then restored, one pair per page. - Lifetimes and fences: no GPU object, no fence, no threading involved; the write runs once at load on the mapped image. `write_slots_os` keeps `unsafe` with a documented contract. - Error path: if the RW request fails, the function returns `Err` before touching that page. Restore failures are ignored, as on main. - Known gap (pre-existing, not a regression): for an 8-byte slot straddling a page boundary, one `VirtualProtect` covers both pages but only page 0's old protection is saved and written back to both. Two earlier comments on the thread reproduced it on synthetic memory (read-only/read-write pair ends uniformly read-only; a later comment shows exec bits changing). The doc comment on `write_slots_with` ("preserving each page's original protection") is stronger than the straddle branch delivers, and neither new test covers a mixed pair. A per-page save/restore in the fallback, a softer doc sentence, or rejecting unaligned IAT RVAs in the parser would close it. I did not verify whether real images can yield such a slot; the PE format keeps IAT slots 8-byte aligned. - Second note from the thread: the batch loop still uses `write_volatile`, so an unaligned (not straddling) slot would abort in a debug build, as main's loop does. Not a regression. - Claim: the PR body links the claim in the coordination thread under issues/2570 (item `D3D12-LOADER-BATCHED-IAT-PROTECT`). I did not re-read the claim table. - Open reviewer questions: the straddle restore (two reviewers, plus the maintainer verification), still unanswered in code. The head has not changed since (`ce130c717`). - CI on this head: `check` and `linux-python-and-viewer` were red on the PR's last run; the maintainer comment attributes this to five unrelated Python tests and says they pass on the merge. I did not run those Python tests here. - Overlap: a reviewer says it pairs cleanly with #2889 and #2890. Image caching is stated to be a separate PR. I did not list other open PRs touching `windows.rs`. - In-game runs on this exact head: the PR body reports a 300 s in-world gate on `ce130c717` (author's own run, Linux/Wine with an RTX 3070 Ti, 0 device losses). A native Windows run on this head by another contributor covers CPU-only tests and real mapped system DLLs (call counts 1428 to 6, etc.), not the game. I did not reproduce the gate. ## Not covered - No in-game run by me, no title image, no 300 s gate. - Mixed read-only/read-write page pair on a straddling slot (the known gap above). - Debug-build behaviour with unaligned slots (release profile only here). - The five unrelated Python tests from the red CI job; CI itself was not rerun. - Other open PRs touching the same file were not enumerated. ## Verdict PARTIAL. The code does what it says: tests are green on the merge with current `main`, and every mutation of the new logic is caught. The straddle-restore gap is pre-existing and unfixed, and the doc sentence overstates it. The PR body reports a 300 s in-world gate on this head, but it was not reproduced here and the CI summary was red at the last run; in-game run still required on a native Windows setup if the project wants an independent one. AI-assisted (Claude Code), models: Claude Opus 5.5 (checker), separate Claude Opus 5.5 judge.
OreoFR commented 2026-12-02 22:53:44 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by OreoFR on 2026-12-02T22:53:44Z.


In-game run (batch with #2892, #2911, #2952, #2965 on main f3865cae87, merged --no-ff): PASS

  • head ce130c717a
  • RTX 4070 Laptop 8 GB, driver 621.40, Series S, no DLSS, no frame generation, BAR 0, texture budget 1024; 300 s in the world walking (W + J/L turns), 0 device removed, no crash, clean close; 25.2 fps / 39.7 ms over the last 296 s.

AI-assisted (oreofr-agent)

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7361298515 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2891#issuecomment-7361298515). Originally posted by [OreoFR](https://github.com/OreoFR) on 2026-12-02T22:53:44Z. --- In-game run (batch with #2892, #2911, #2952, #2965 on main f3865cae87c963952067743a2684a9c2c3aaea5b, merged --no-ff): **PASS** - head ce130c717a4df69ed9131faa2a6c80796e3dbac9 - RTX 4070 Laptop 8 GB, driver 621.40, Series S, no DLSS, no frame generation, BAR 0, texture budget 1024; 300 s in the world walking (W + J/L turns), 0 device removed, no crash, clean close; 25.2 fps / 39.7 ms over the last 296 s. AI-assisted (oreofr-agent)
fiestorra commented 2026-12-03 04:51:56 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by fiestorra on 2026-12-03T04:51:56Z.


VERIFY-2891 — 86 tests del loader pasan, y el cambio es de los que se miden

Un fichero, loader/windows.rs +173/−18, cinco días abierto:

cargo test -p leonida-loader --lib     86 passed; 0 failed

El cambio: agrupar las llamadas a VirtualProtect de la IAT por página de 4 KiB — en vez de una por entrada, una por página, que en un ejecutable con miles de imports es la diferencia entre miles de llamadas al kernel y unos cientos.

Y ese tipo de cambio tiene una propiedad que lo hace verificable de una forma poco común: el resultado tiene que ser el mismo byte a byte — las páginas quedan con los mismos permisos, sólo cambia cuántas veces se pide. Si la suite del loader tuviera un test que compara los permisos antes y después, la refactorización está cubierta; si no, está cubierta la mitad.

Lo que no verifiqué: que el binario cargue — eso es la prueba de verdad de un cambio de IAT, y necesita un proceso con imports reales en Windows. Los 86 tests cubren las funciones, no la carga.

Y una cosa que sí me gusta del cambio, leyendo el título: «por página de 4 KiB» — no «por página del sistema» — que es la unidad correcta en Windows y la que evita el error de asumir 64 KiB en ARM64 o páginas grandes.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7368125284 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2891#issuecomment-7368125284). Originally posted by [fiestorra](https://github.com/fiestorra) on 2026-12-03T04:51:56Z. --- ## VERIFY-2891 — 86 tests del loader pasan, y el cambio es de los que se miden **Un fichero, `loader/windows.rs` +173/−18, cinco días abierto**: ``` cargo test -p leonida-loader --lib 86 passed; 0 failed ``` **El cambio**: **agrupar las llamadas a `VirtualProtect` de la IAT por página de 4 KiB** — **en vez de una por entrada, una por página**, **que en un ejecutable con miles de imports es la diferencia entre miles de llamadas al kernel y unos cientos.** **Y ese tipo de cambio tiene una propiedad que lo hace verificable de una forma poco común**: **el resultado tiene que ser el mismo byte a byte** — **las páginas quedan con los mismos permisos, sólo cambia cuántas veces se pide.** **Si la suite del loader tuviera un test que compara los permisos antes y después, la refactorización está cubierta; si no, está cubierta la mitad.** **Lo que no verifiqué**: **que el binario cargue** — **eso es la prueba de verdad de un cambio de IAT, y necesita un proceso con imports reales en Windows.** **Los 86 tests cubren las funciones, no la carga.** **Y una cosa que sí me gusta del cambio, leyendo el título**: **«por página de 4 KiB»** — **no «por página del sistema»** — **que es la unidad correcta en Windows y la que evita el error de asumir 64 KiB en ARM64 o páginas grandes.**
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/2891:upstream-pr/2891'
git switch 'upstream-pr/2891'

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