Loader: lazily NOP-patch clwb/monitorx on #UD, emulate rdpid, batch IAT protection, and content-hash cached DLLs #1372

Open
wbkepler wants to merge 1 commit from upstream-pr/1372 into main
wbkepler commented 2026-11-24 17:38:37 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by wbkepler on 2026-11-24T17:38:37Z.


Summary

Rebased cleanly onto upstream/main (ffe310e):

  • crash.rs:
    • Lazily overwrites standalone clwb (not clwb_loop) and monitorx instructions on #UD with canonical x86-64 multi-byte NOPs (1..=15 bytes) using a single hardware-atomic store (AtomicU64::compare_exchange or lock cmpxchg16b), serialized via non-blocking try_lock(), restricted to already-executable pages within a single 4 KiB page, followed by FlushInstructionCache and exact protection restore (falling back to Rip += len if patching is unsafe or refused).
    • Adds rdpid r64 (F3 [REX] 0F C7 /7) emulation returning the current logical processor ID from GetCurrentProcessorNumberEx ((Group << 6) | Number) without modifying EFLAGS.
  • prepare.rs & windows.rs:
    • Batches write_slots() VirtualProtect calls by 4 KiB page (preserving per-section protections and falling back cleanly for page-straddling slots), cutting VirtualProtect calls from 2x slots down to 2x pages.
    • Includes a 16-hex BLAKE3 digest of prepared.bytes in PreparedImage::file_name() so write_if_changed() checks metadata length (0 bytes read on cache hit) and stages misses via unique per-writer temp files before atomic rename.
  • Adds 4 unit tests covering rdpid decoding/emulation, live executable-page atomic NOP patching (AtomicU64 + cmpxchg16b paths + execution + protection restore), page-batched write_slots, and content-hashed cache hits.

Verification

  • cargo clippy -p victory-loader --all-targets — passed
  • cargo test -p victory-loader — passed
  • cargo xtask policy — passed
<!-- greyfinch-sync:Marvisak/VIctory:issue:6587792541 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/1372). Originally posted by [wbkepler](https://github.com/wbkepler) on 2026-11-24T17:38:37Z. --- ## Summary Rebased cleanly onto `upstream/main` (`ffe310e`): - **`crash.rs`**: - Lazily overwrites standalone `clwb` (not `clwb_loop`) and `monitorx` instructions on `#UD` with canonical x86-64 multi-byte NOPs (1..=15 bytes) using a single hardware-atomic store (`AtomicU64::compare_exchange` or `lock cmpxchg16b`), serialized via non-blocking `try_lock()`, restricted to already-executable pages within a single 4 KiB page, followed by `FlushInstructionCache` and exact protection restore (falling back to `Rip += len` if patching is unsafe or refused). - Adds `rdpid r64` (`F3 [REX] 0F C7 /7`) emulation returning the current logical processor ID from `GetCurrentProcessorNumberEx` (`(Group << 6) | Number`) without modifying `EFLAGS`. - **`prepare.rs` & `windows.rs`**: - Batches `write_slots()` `VirtualProtect` calls by 4 KiB page (preserving per-section protections and falling back cleanly for page-straddling slots), cutting `VirtualProtect` calls from 2x slots down to 2x pages. - Includes a 16-hex BLAKE3 digest of `prepared.bytes` in `PreparedImage::file_name()` so `write_if_changed()` checks metadata length (0 bytes read on cache hit) and stages misses via unique per-writer temp files before atomic rename. - Adds 4 unit tests covering `rdpid` decoding/emulation, live executable-page atomic NOP patching (`AtomicU64` + `cmpxchg16b` paths + execution + protection restore), page-batched `write_slots`, and content-hashed cache hits. ## Verification - `cargo clippy -p victory-loader --all-targets` — passed - `cargo test -p victory-loader` — passed - `cargo xtask policy` — passed
catminou4 commented 2026-11-24 18:05:03 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by catminou4 on 2026-11-24T17:42:47Z.

Review: COMMENTED


Loader crash-handler work: lazy NOP-patch of clwb/monitorx on #UD, rdpid emulation via GetCurrentProcessorNumberEx, page-scatter batching with VirtualQuery/VirtualProtect/FlushInstructionCache. All Windows-only (windows_sys), so macOS cannot compile or test it — static review only, and the SAFETY comments on the exception-path pointer reads are the right discipline for this code. Two notes: (1) victory-loader's own tests already fail on macOS/Linux on main (they parse the test binary as PE; 'Unknown file magic') — pre-existing, same class as the victory-pe image tests I flagged on #529, worth a cfg(windows) gate someday; (2) NOP-patching text pages means FlushInstructionCache + VirtualProtect round-trips per patch — the batching described in the title suggests that's handled, but please double-check the patch cache is keyed per-page so repeated #UDs on the same page don't re-patch.

<!-- greyfinch-sync:Marvisak/VIctory:review:6044389793 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/1372#pullrequestreview-6044389793). Originally posted by [catminou4](https://github.com/catminou4) on 2026-11-24T17:42:47Z. **Review:** COMMENTED --- Loader crash-handler work: lazy NOP-patch of clwb/monitorx on #UD, rdpid emulation via GetCurrentProcessorNumberEx, page-scatter batching with VirtualQuery/VirtualProtect/FlushInstructionCache. All Windows-only (windows_sys), so macOS cannot compile or test it — static review only, and the SAFETY comments on the exception-path pointer reads are the right discipline for this code. Two notes: (1) victory-loader's own tests already fail on macOS/Linux on main (they parse the test binary as PE; 'Unknown file magic') — pre-existing, same class as the victory-pe image tests I flagged on #529, worth a cfg(windows) gate someday; (2) NOP-patching text pages means FlushInstructionCache + VirtualProtect round-trips per patch — the batching described in the title suggests that's handled, but please double-check the patch cache is keyed per-page so repeated #UDs on the same page don't re-patch.
Marvisak commented 2026-11-25 02:06:00 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Marvisak on 2026-11-25T01:24:30Z.


Automated triage for the maintainers.

Needs rebase. This pull request conflicts with main (conflicting: crates/victory-loader/src/crash.rs, crates/victory-loader/src/windows.rs). It will be reviewed once it is rebased onto the current main.


Generated by Claude Code

<!-- greyfinch-sync:Marvisak/VIctory:comment:7149513847 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/1372#issuecomment-7149513847). Originally posted by [Marvisak](https://github.com/Marvisak) on 2026-11-25T01:24:30Z. --- <!-- victory-triage v1 head=fa22cba5df93f87a723f97276183d0be7c0e8f5c verdict=needs-rebase at=2026-11-25T01:24:28Z --> Automated triage for the maintainers. **Needs rebase.** This pull request conflicts with `main` (conflicting: `crates/victory-loader/src/crash.rs`, `crates/victory-loader/src/windows.rs`). It will be reviewed once it is rebased onto the current `main`. --- _Generated by [Claude Code](https://claude.ai/code)_
hadrianhola commented 2026-11-26 14:01:52 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by hadrianhola on 2026-11-26T13:29:40Z.


Some measurements for what this PR would save, from a CPU that takes these traps: i7-5820K (Haswell-E, 3.3 GHz, no clwb), Windows 10 19045, main at 63bcca4, Series X profile, 10 minutes (menus, then world entry).

1. How many traps. A local counter in emulate_amd_only (not in any PR), cumulative over the run:

menus (steady, per second) world entry (the 10 s with most traps) whole run (600 s)
clwb ~0 869,387 1,207,926
clzero ~600 ~5,000 324,095
monitorx / mwaitx ~0 ~22,700 each (next 10 s) 51,207 / 51,195
SSE4a ~0 ~700 (next 10 s) 4,388

2. What a trap costs. Cycles spent inside the handler (the counter, rdtsc around the emulation): clwb 202, clzero 1,219, monitorx 51, mwaitx 360. That leaves out the #UD round trip itself. A separate micro-benchmark (ud2 in a loop, a vectored handler that only moves Rip, 5 × 500,000 traps on the same machine) gives 0.91 µs, about 3,000 TSC cycles, per round trip, so the trap costs far more than the emulation.

3. What that adds up to, at ~3,000 + handler cycles per trap:

  • whole run: about 5.6 G cycles in 600 s, ~0.3 % of one core on average;
  • the busiest 10 s (world entry, almost all clwb): about 2.8 G cycles, ~8 % of one core for those 10 s;
  • menus: ~0.1 % of one core.

So on this machine the lazy NOP patch would mostly help the clwb burst at world entry, and only by a few percent of one core there; the frames at that point take 400 ms to 17 s for GPU reasons. Caveats: one run; the round trip was measured in a small test process, not inside the title (where other vectored handlers may run first); and clwb_loop sites count once per loop, not per cache line.

AI-assisted (Claude Code).

<!-- greyfinch-sync:Marvisak/VIctory:comment:7193427428 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/1372#issuecomment-7193427428). Originally posted by [hadrianhola](https://github.com/hadrianhola) on 2026-11-26T13:29:40Z. --- Some measurements for what this PR would save, from a CPU that takes these traps: i7-5820K (Haswell-E, 3.3 GHz, no `clwb`), Windows 10 19045, `main` at `63bcca4`, Series X profile, 10 minutes (menus, then world entry). **1. How many traps.** A local counter in `emulate_amd_only` (not in any PR), cumulative over the run: | | menus (steady, per second) | world entry (the 10 s with most traps) | whole run (600 s) | |---|---:|---:|---:| | `clwb` | ~0 | 869,387 | 1,207,926 | | `clzero` | ~600 | ~5,000 | 324,095 | | `monitorx` / `mwaitx` | ~0 | ~22,700 each (next 10 s) | 51,207 / 51,195 | | SSE4a | ~0 | ~700 (next 10 s) | 4,388 | **2. What a trap costs.** Cycles spent inside the handler (the counter, `rdtsc` around the emulation): `clwb` 202, `clzero` 1,219, `monitorx` 51, `mwaitx` 360. That leaves out the #UD round trip itself. A separate micro-benchmark (`ud2` in a loop, a vectored handler that only moves `Rip`, 5 × 500,000 traps on the same machine) gives **0.91 µs, about 3,000 TSC cycles, per round trip**, so the trap costs far more than the emulation. **3. What that adds up to**, at ~3,000 + handler cycles per trap: - whole run: about 5.6 G cycles in 600 s, **~0.3 % of one core** on average; - the busiest 10 s (world entry, almost all `clwb`): about 2.8 G cycles, **~8 % of one core** for those 10 s; - menus: ~0.1 % of one core. So on this machine the lazy NOP patch would mostly help the `clwb` burst at world entry, and only by a few percent of one core there; the frames at that point take 400 ms to 17 s for GPU reasons. Caveats: one run; the round trip was measured in a small test process, not inside the title (where other vectored handlers may run first); and `clwb_loop` sites count once per loop, not per cache line. _AI-assisted (Claude Code)._
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/1372:upstream-pr/1372'
git switch 'upstream-pr/1372'

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