Skip to content

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

Open
djrolfes wants to merge 1 commit into
ProjectLeonida:mainfrom
djrolfes:djrolfes/loader-batched-iat-protect
Open

djrolfes wants to merge 1 commit into
ProjectLeonida:mainfrom
djrolfes:djrolfes/loader-batched-iat-protect

Conversation

@djrolfes

@djrolfes djrolfes commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

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)

@merzleckeier

Copy link
Copy Markdown
Contributor

Independent test of mixed protections across the fallback boundary at ce130c7 + 0ff8a53. 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).

@KelboLive KelboLive left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants