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

Open
github-bot wants to merge 1 commit from github-bot/gh-1372 into main AGit
Owner

@⁠wbkepler on GitHub · 2026-11-24 17:38 UTC · original
wbkepler:loader/intel-ud-patch-and-startup → main · +567 −39 · 3 files · 1 commits · open

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
**@⁠wbkepler** on GitHub · 2026-11-24 17:38 UTC · [original](https://github.com/Marvisak/VIctory/pull/1372) `wbkepler:loader/intel-ud-patch-and-startup` → `main` · +567 −39 · 3 files · 1 commits · open ## 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
- `crash.rs`:
  - Lazily overwrite 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).
  - Add `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`:
  - Batch `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.
  - Include 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.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:29:16 +00:00
Author
Owner

@⁠Marvisak on GitHub · 2026-11-25 01:24 UTC · original

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

**@⁠Marvisak** on GitHub · 2026-11-25 01:24 UTC · [original](https://github.com/Marvisak/VIctory/pull/1372#issuecomment-7149513847) <!-- 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)_
Author
Owner

@⁠catminou4 on GitHub · 2026-11-24 17:42 UTC · original · reviewed

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.

**@⁠catminou4** on GitHub · 2026-11-24 17:42 UTC · [original](https://github.com/Marvisak/VIctory/pull/1372#pullrequestreview-6044389793) · **reviewed** 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.
Author
Owner

@⁠hadrianhola on GitHub · 2026-11-26 13:29 UTC · original

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).

**@⁠hadrianhola** on GitHub · 2026-11-26 13:29 UTC · [original](https://github.com/Marvisak/VIctory/pull/1372#issuecomment-7193427428) 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 has changes conflicting with the target branch.
  • crates/victory-loader/src/crash.rs
  • crates/victory-loader/src/windows.rs
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/1372/head:github-bot/gh-1372'
git switch 'github-bot/gh-1372'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-1372'
git switch 'github-bot/gh-1372'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-1372'
git switch 'github-bot/gh-1372'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-1372'
git switch 'main'
git merge --squash 'github-bot/gh-1372'
git switch 'main'
git merge --ff-only 'github-bot/gh-1372'
git switch 'main'
git merge 'github-bot/gh-1372'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No reviewers
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.

Dependencies

No dependencies set

Reference
github/Marvisak--VIctory!1372
No description provided.