loader/windows: batch IAT VirtualProtect calls per 4 KiB page (D3D12-LOADER-BATCHED-IAT-PROTECT) #2891
Open
github-bot
wants to merge 1 commit from
github-bot/gh-2891 into main
AGit
pull from: github-bot/gh-2891
merge into: github:main
github:main
github:perf/darner-title-priority-ceiling
github:gh-readonly-queue/main/pr-3311-b5c45b663dbc5a9c3532bb3f307e5f81b32faefa
github:gh-readonly-queue/main/pr-3088-af22e7847ff5808f72d1a1881c24be2fafd20b54
github:gh-readonly-queue/main/pr-3123-7f3fa026a94c6646e89244f28e1ce22290361867
github:gh-readonly-queue/main/pr-3354-637baa0b77ba47222e7280b17c1a59c6a1781d57
github:gh-readonly-queue/main/pr-3365-d7a0e0196a43834813014b4bd3aa5502a8263b14
github:gh-readonly-queue/main/pr-3361-5dfe8bbd05ed12fb2f2e1718d9af77a7c5f46fd8
github:gh-readonly-queue/main/pr-3366-8da9148204e9d12c585efa9ac2b7cc1ab08c7682
github:fix/runtime-test-conservative-fixtures
github:ci/shard-semantic-linux
github:docs/fg-limit-fps-switch
github:fix/runtime-test-fixture-paths
github:fix/runtime-test-fixture-readers
github:fix/read-file-hard-link
github:fix/book-slot-heap-never-read
github:fix/depth-resolve-spv-path
github:fix/indirect-unused-batched
github:gh-pr/3358/base
github:fix/xmem-refusal-diagnostics
github:gh-pr/3357/base
github:ci/shorten-ci-time
github:fix/alias-later-queued-submissions
github:claude/gallant-sagan-aamatr
github:gh-pr/3342/base
github:gh-pr/3341/base
github:d3d12/agility-sdk-621
github:gh-pr/3293/base
github:gh-pr/3319/base
github:gh-pr/3318/base
github:gh-pr/3315/base
github:gh-pr/3313/base
github:gh-pr/3314/base
github:claude/fervent-curie-m19lnr
github:gh-pr/3216/base
github:gh-pr/3272/base
github:gh-pr/3276/base
github:gh-pr/3279/base
github:gh-pr/3257/base
github:gh-pr/3258/base
github:gh-pr/3271/base
github:codex/skip-no-hit-ray-passes
github:gh-pr/3230/base
github:gh-pr/3266/base
github:gh-pr/3247/base
github:gh-pr/3246/base
github:gh-pr/3244/base
github:claude/sharp-sagan-1jqnp3
github:t3/preserve-fsr-sdk-restart-path
github:t3/propagate-host-failure-hresult
github:t3/launcher-custom-parameters
github:t3/series-x-2160-startup
github:codex/d3d12-uncapped-simulation
github:ci/less-to-run
github:perf/native-compute-shader-forms
github:claude/blissful-franklin-ukp7ag
github:codex/full-precompile-default
github:gh-pr/3166/base
github:gh-pr/3148/base
github:gh-pr/3138/base
github:gh-pr/3106/base
github:gh-pr/3057/base
github:gh-pr/2756/base
github:gh-pr/2812/base
github:gh-pr/3032/base
github:gh-pr/2992/base
github:notes/card-time-and-plant-flicker
github:gh-pr/2986/base
github:gh-pr/3000/base
github:gh-pr/2966/base
github:gh-pr/2924/base
github:gh-pr/726/base
github:gh-pr/2761/base
github:gh-pr/2663/base
github:gh-pr/2861/base
github:gh-pr/2862/base
github:gh-pr/2820/base
github:gh-pr/2811/base
github:gh-pr/2803/base
github:rt-call-trace
github:gh-pr/2802/base
github:gh-pr/2766/base
github:perf/ahead-split
github:gh-pr/2589/base
github:gh-pr/2699/base
github:gh-pr/2696/base
github:docs/readme-runtime-proposal
github:gh-pr/1346/base
github:codex/coord-claim-check-20261124-7e48
No reviewers
Labels
Clear labels
accessibility
Barrier affecting people with disabilities
area: ci
.github/ workflows and settings
area: d3d12
The D3D12 runtime in d3d12/ (Rust: leonida.exe and its crates)
area: docs
Documentation
area: launcher
The launcher (launcher/)
area: runtime (legacy)
The earlier Vulkan runtime in runtime/
area: shader translator
The shader translator (leonida-shader, tools/rdna2spirv) and its tests
area: tools
tools/ and scripts/
area: viewer
The map viewer (viewer/)
bug
Something isn't working
dependencies
Pull requests that update a dependency file
documentation
Improvements or additions to documentation
duplicate
This issue or pull request already exists
enhancement
New feature or request
good first issue
Good for newcomers
help wanted
Extra attention is needed
invalid
This doesn't seem right
missing claim
Needs a claim in #14
needs in-game run
Changes the code a frame runs through: needs the 300 s in-game gate (docs/game_gate.md)
needs rebase
Conflicts with the base branch: rebase it on main
needs-triage
Needs maintainer evaluation before the next triage state
question
Further information is requested
ready-for-agent
Fully specified and ready for an AFK agent
submodules
Pull requests that update submodules code
wontfix
This will not be worked on
No labels
accessibility
area: ci
area: d3d12
area: docs
area: launcher
area: runtime (legacy)
area: shader translator
area: tools
area: viewer
bug
dependencies
documentation
duplicate
enhancement
good first issue
help wanted
invalid
missing claim
needs in-game run
needs rebase
needs-triage
question
ready-for-agent
submodules
wontfix
Milestone
Clear milestone
No items
No milestone
Assignees
Clear assignees
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.
Dependencies
No dependencies set
Reference
github/ubiquitarianism--leonida!2891
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-2891"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@djrolfes on GitHub · 2026-12-01 15:37 UTC · original
djrolfes:djrolfes/loader-batched-iat-protect→main· +173 −18 · 1 files · 1 commits · openClaimed in the coordination issue as:
D3D12-LOADER-BATCHED-IAT-PROTECT.What and why
Batch IAT
VirtualProtectcalls per 4 KiB page insideLoadedImage::write_slots(d3d12/crates/leonida-loader/src/windows.rs) instead of protecting and restoring every 8-byte import slot individually.main,LoadedImage::write_slotsissues twoVirtualProtectsyscalls 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.write_slots_os/write_slots_withind3d12/crates/leonida-loader/src/windows.rs.(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 oneVirtualProtect(page, 4096, PAGE_READWRITE, &mut old)+ restore per page — preserving distinct protections across adjacent pages/sections (e.g..rdatavs.didat).(addr & 4095) > 4088) with an 8-byte unaligned fallback so it never writes past the protected page.D3D12-LOADER-CONTENT-ADDRESSED-IMAGE, verified clean merge viagit merge-tree).d3d12/crates/leonida-loader/src/windows.rs) + red→green unit tests (both mock syscall-count test and realVirtualAlloc+PAGE_READONLY+VirtualQuerytest) + 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.leonida-loaderunit test binary (x86_64-pc-windows-msvc) and ran under Wine:origin/mainunbatched loop (runningwindows::tests::write_slots_batches_virtual_protect_per_pageagainstorigin/main's per-slot loop):ce130c717(rebased onto3e7b34a52):ce130c717, Series S + DLSS Quality1280×720 → 1920×1080, Option Amods/gate_drivermode = roamloaded):310.93 sin-world after world entry at69.46 s; also passed an earlier cold-cache 310.22 s run with0errors).3,273frames after +60 s (3,377total world presents),15.35median FPS (15.77end median FPS),111.32 msp95 frame time,3.188 slongest present gap (<= 10.0 s).6,690 MiBpeak VRAM (<= 7,400 MiB),0device losses (0x887A0005),0crashes,0panics,0faults before stop,0kernelNVRM: Xiderrors.gate_drivernote:mods/gate_driverloaded inmode = roamwith0GATE 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 at15.35FPS.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
main(3e7b34a52) and merges cleanly (a conflicting pull request is labeledneeds rebase).check_no_game_data.pyclean on both source and PR description).docs/design.md, with how it was confirmed. (n/a — loader IAT page-protection batching)@merzleckeier on GitHub · 2026-12-01 16:10 UTC · original
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).
@KelboLive on GitHub · 2026-12-01 17:26 UTC · original · reviewed
Batching itself looks right: stable sort by RVA, grouping on
addr & !4095, and per-page save/restore preserve mixed.rdata/.didatprotections, 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 withlet _ = oldfails both new tests withpage 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, butoldis only page 0's protection and the restore at:500writes it to both, so a mixed RO/RW boundary ends uniformly page 0's protection. I reproduced it on synthetic memory (page0=0x2 page1=0x2for both the new and the old per-slot path). It is pre-existing, not a regression — main's loop did the same — andwrite_unalignedis a genuine improvement overwrite_volatileon 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
:519are 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-343bounds-checksrva+8 <= SizeOfImagebut not 8-byte alignment.@MoonEyes on GitHub · 2026-12-02 12:30 UTC · original
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:mainSHA it was merged onto;mainalone 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 on GitHub · 2026-12-02 15:14 UTC · original
Ran natively on Windows 11, head
ce130c717merged intomain(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.cargo test --locked -p leonida-loadercargo clippy --locked -p leonida-loader --all-targets -- -D warningscargo check --locked --workspace --all-targetsReal images. I wanted real
MEM_IMAGEpages instead of private memory. I took copies of eight stock system DLLs, parsed each withImageInfo::parse(imports plus delay imports) and mapped it withLoadLibraryExW(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 comparedVirtualQueryon every page of the image before and after.VirtualProtectcalls main → PRAll IAT pages were
PAGE_READONLYand 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):
0x000and0xFF8Err. Pages 1 and 2 were written and restored, page 3 was untouched, and no page was left writable0xFFC0xFFC0xFF4,0xFFC,0x1004(debug build)ptr::write_volatile requires that the pointer argument is aligned, at the batch path'swrite_volatile(windows.rs:517on the merge). The release build completesThe 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_volatileaborts 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 throughwrite_unaligned. The others still usewrite_volatileand abort in debug builds. I read the parser code:leonida-peentries()derives every slot asiat_rva + 8*iand does not check alignment. If the fallback stays, saving and restoring each page separately and usingwrite_unalignedin 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 on GitHub · 2026-12-02 18:29 UTC · original
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.rsis Windows-only.ce130c717, merge base3e7b34a52. It merges cleanly intomain45dc41f95. Diff:d3d12/crates/leonida-loader/src/windows.rs, +173/-18.CI failures on this head are not caused by this PR
linux-python-and-viewerfailed intests/test_piecewise_parse.py,test_wave_diff.py,test_wave_trace.py,test_x64_recomp.pyandtest_x64_recomp_qemu_runner.py.checkis the summary job and failed with it. The PR touches none of these files, and it changes no Python.main, each of the five passes withpython -I tests/<name>.py(test_x64_recomp: OK, 34 skipped). CurrentmainCI passeslinux-python-and-viewer. A rerun of the checks should clear both.Review
write_slots_withsorts the slots by RVA. The sort is stable, so a later duplicate still wins. It then makes oneVirtualProtect(page, 4096, RW)call and one restore per 4 KiB page. Image protections are per page, so restoring theoldvalue each page reported is exact for aligned slots.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.main.protectto count the calls; the other runsVirtualAlloc/VirtualQueryon 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.pyon 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
@MoonEyes on GitHub · 2026-12-02 21:35 UTC · original
RUN (independent run on Windows, head
ce130c717a4df69ed9131faa2a6c80796e3dbac9, merged intomainb41763227aeed2d23c98af84bcbc1bddc7acdc90withgit merge --no-ff)Merge was clean (merge base
3e7b34a52, no conflict). The only file changed isd3d12/crates/leonida-loader/src/windows.rs(+173/-18). Native Windows 11, Rust release profile, one shared target directory, noleonida.exerunning during the builds.Green
cargo test -p leonida-loader --release --lockedload_probe2 passed,title_dlls1 passed, 0 failed. Both new tests (write_slots_batches_virtual_protect_per_page,write_slots_os_updates_readonly_pages_and_restores_protection) passcargo test -p leonida-gpu --release --locked --libThe PR touches no
leonida-gpucode and no diagnostics code, so--features diagnosticswas not run. It touches no Python test.leonida-gpudoes not depend onleonida-loader(onlyleonida-hledoes), 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):PAGE_READONLYwrite_slots_withbody replaced by main's per-slot protect/write/restore loopEvery 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
docs/switches.mdentry to regenerate (checked: the diff does not touch it).write_slots_oskeepsunsafewith a documented contract.Errbefore touching that page. Restore failures are ignored, as on main.VirtualProtectcovers 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 onwrite_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.write_volatile, so an unaligned (not straddling) slot would abort in a debug build, as main's loop does. Not a regression.D3D12-LOADER-BATCHED-IAT-PROTECT). I did not re-read the claim table.ce130c717).checkandlinux-python-and-viewerwere 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.windows.rs.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
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 on GitHub · 2026-12-02 22:53 UTC · original
In-game run (batch with #2892, #2911, #2952, #2965 on main
f3865cae87, merged --no-ff): PASSce130c717aAI-assisted (oreofr-agent)
@fiestorra on GitHub · 2026-12-03 04:51 UTC · original
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:El cambio: agrupar las llamadas a
VirtualProtectde 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.
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.