Loader: extrq/insertq with the field in the instruction jump to SSE2 code after their first fault #3040

Open
101Leafy wants to merge 3 commits from upstream-pr/3042 into main
101Leafy commented 2026-11-26 05:04:23 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by 101Leafy on 2026-11-26T05:04:23Z.


Intel CPUs have no SSE4a. Every extrq/insertq a title runs raises an illegal-instruction exception, which crash.rs emulates. That works, but each one costs an exception, and titles run these in hot loops: in GTA VI gameplay on an i9-13900K it was 191 to 491 exceptions a second, 442 a second at a single place.

This change keeps the emulation for the first fault, then replaces the instruction's first five bytes with a jmp to the same work written in SSE2 (psrlq/psllq/pand/por; insertq borrows one of xmm0-2, saved on the stack). The stubs live in 64 KB blocks allocated within jump range of the code that faulted; a new block is made when the current one is full or out of reach. The bytes are swapped with a single cmpxchg16b on their aligned 16 bytes, so another thread sees either the old instruction or the jump, never half of each.

Left emulated as before: the forms with the field in a register (0f 79), and places where the five bytes would cross a 16-byte boundary.

The emulation now zeroes the destination's high quadword, as AMD's CPUs do. The SSE2 code does the same, so every run gives one result. AMD documents those bits as undefined; existing tests still pass.

Tested on an i9-13900K (no SSE4a):

  • cargo test -p victory-loader, including a new test that builds each form at different offsets in an executable page, runs it twice (the first pass faults and is replaced; the second runs the SSE2) and checks the result with its high quadword zeroed. It also checks that the source and borrowed registers are kept and that the bytes became a jump only where one fits.
  • GTA VI gameplay with the same change: SSE4a faults went from hundreds a second to 0.
<!-- greyfinch-sync:Marvisak/VIctory:issue:5504328971 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3042). Originally posted by [101Leafy](https://github.com/101Leafy) on 2026-11-26T05:04:23Z. --- Intel CPUs have no SSE4a. Every `extrq`/`insertq` a title runs raises an illegal-instruction exception, which `crash.rs` emulates. That works, but each one costs an exception, and titles run these in hot loops: in GTA VI gameplay on an i9-13900K it was 191 to 491 exceptions a second, 442 a second at a single place. This change keeps the emulation for the first fault, then replaces the instruction's first five bytes with a `jmp` to the same work written in SSE2 (`psrlq`/`psllq`/`pand`/`por`; `insertq` borrows one of xmm0-2, saved on the stack). The stubs live in 64 KB blocks allocated within jump range of the code that faulted; a new block is made when the current one is full or out of reach. The bytes are swapped with a single `cmpxchg16b` on their aligned 16 bytes, so another thread sees either the old instruction or the jump, never half of each. Left emulated as before: the forms with the field in a register (`0f 79`), and places where the five bytes would cross a 16-byte boundary. The emulation now zeroes the destination's high quadword, as AMD's CPUs do. The SSE2 code does the same, so every run gives one result. AMD documents those bits as undefined; existing tests still pass. Tested on an i9-13900K (no SSE4a): - `cargo test -p victory-loader`, including a new test that builds each form at different offsets in an executable page, runs it twice (the first pass faults and is replaced; the second runs the SSE2) and checks the result with its high quadword zeroed. It also checks that the source and borrowed registers are kept and that the bytes became a jump only where one fits. - GTA VI gameplay with the same change: SSE4a faults went from hundreds a second to 0.
fuzeofficlal commented 2026-11-26 05:20:35 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by fuzeofficlal on 2026-11-26T05:20:35Z.

Review: CHANGES_REQUESTED


Static review of 777c8e78 (crates/victory-loader/src/sse4a.rs and crash.rs). The SSE2 lowering and cmpxchg16b single-store patching design is very neat; a few concrete issues need attention before merge:

  1. CI Clippy failure (crates/victory-loader/src/sse4a.rs:274): clippy::precedence rejects 0xc0 | (x & 7) * 9 (should be 0xc0 | ((x & 7) * 9)).
  2. near() can pass NULL to VirtualAlloc and leak unreachable RWX blocks (sse4a.rs:138-150): places probes at.checked_sub(d) for d in 0x10_0000..0x7000_0000 stepped by 0x10_0000. Whenever at & !0xffff is a 1 MiB-aligned address below 0x7000_0000 (e.g. a 32-bit preferred base or test allocation) and lower candidates fail, at.checked_sub(d) yields Some(0). Calling VirtualAlloc(std::ptr::null(), ...) lets Windows allocate anywhere in the 64-bit address space — outside ±2 GiB jmp rel32 reach — so fits() then fails and leaks a 64 KiB PAGE_EXECUTE_READWRITE allocation on every fault. Filtering out addresses below 0x10000 (at minimum place != 0) prevents accidental NULL fallback.
  3. STUBS abandons blocks when two modules >2 GiB apart alternate (sse4a.rs:131, 183-185): Keeping only a single Option<(usize, usize)> discards remaining capacity in the previous 64 KiB block whenever a fault occurs in a module more than ±2 GiB away (e.g. main executable vs a high-base title DLL). Keeping a Vec<(usize, usize)> and scanning for an existing block in range with enough room avoids wasting blocks.

Minor non-blocking notes:

  • Test assertion on AMD CPUs (sse4a.rs:320): On CPUs with native SSE4a (replaced == false), the test runs the hardware instruction and asserts out[1] == 0. Since AMD64 APM Vol. 4 specifies bits 127:64 of extrq/insertq as undefined, checking out[1] == 0 only when replaced (or checking only out[0] on native SSE4a) avoids depending on microarchitectural zeroing across AMD generations/emulators.
  • decode vs crash.rs:531: decode checks reg != 0 (including REX.R) on extrq, while crash.rs:531 checks (modrm >> 3) & 7 != 0 (matching hardware, which ignores REX.R on /0).
  • Calling FlushInstructionCache on the newly written stub slice [at_stub..at_stub + body.len()] before exposing the jump (and only advancing *used if patch succeeds) would also tighten the patching path.
<!-- greyfinch-sync:Marvisak/VIctory:review:6068932365 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3042#pullrequestreview-6068932365). Originally posted by [fuzeofficlal](https://github.com/fuzeofficlal) on 2026-11-26T05:20:35Z. **Review:** CHANGES_REQUESTED --- Static review of `777c8e78` (`crates/victory-loader/src/sse4a.rs` and `crash.rs`). The SSE2 lowering and `cmpxchg16b` single-store patching design is very neat; a few concrete issues need attention before merge: 1. **CI Clippy failure (`crates/victory-loader/src/sse4a.rs:274`)**: `clippy::precedence` rejects `0xc0 | (x & 7) * 9` (should be `0xc0 | ((x & 7) * 9)`). 2. **`near()` can pass `NULL` to `VirtualAlloc` and leak unreachable RWX blocks (`sse4a.rs:138-150`)**: `places` probes `at.checked_sub(d)` for `d` in `0x10_0000..0x7000_0000` stepped by `0x10_0000`. Whenever `at & !0xffff` is a 1 MiB-aligned address below `0x7000_0000` (e.g. a 32-bit preferred base or test allocation) and lower candidates fail, `at.checked_sub(d)` yields `Some(0)`. Calling `VirtualAlloc(std::ptr::null(), ...)` lets Windows allocate anywhere in the 64-bit address space — outside `±2 GiB` `jmp rel32` reach — so `fits()` then fails and leaks a 64 KiB `PAGE_EXECUTE_READWRITE` allocation on every fault. Filtering out addresses below `0x10000` (at minimum `place != 0`) prevents accidental `NULL` fallback. 3. **`STUBS` abandons blocks when two modules >2 GiB apart alternate (`sse4a.rs:131, 183-185`)**: Keeping only a single `Option<(usize, usize)>` discards remaining capacity in the previous 64 KiB block whenever a fault occurs in a module more than `±2 GiB` away (e.g. main executable vs a high-base title DLL). Keeping a `Vec<(usize, usize)>` and scanning for an existing block in range with enough room avoids wasting blocks. Minor non-blocking notes: - **Test assertion on AMD CPUs (`sse4a.rs:320`)**: On CPUs with native SSE4a (`replaced == false`), the test runs the hardware instruction and asserts `out[1] == 0`. Since AMD64 APM Vol. 4 specifies bits `127:64` of `extrq`/`insertq` as undefined, checking `out[1] == 0` only when `replaced` (or checking only `out[0]` on native SSE4a) avoids depending on microarchitectural zeroing across AMD generations/emulators. - **`decode` vs `crash.rs:531`**: `decode` checks `reg != 0` (including `REX.R`) on `extrq`, while `crash.rs:531` checks `(modrm >> 3) & 7 != 0` (matching hardware, which ignores `REX.R` on `/0`). - Calling `FlushInstructionCache` on the newly written stub slice `[at_stub..at_stub + body.len()]` before exposing the jump (and only advancing `*used` if `patch` succeeds) would also tighten the patching path.
kotekompotek commented 2026-11-26 05:29:19 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by kotekompotek on 2026-11-26T05:29:19Z.

Review: APPROVED


Verified: this fixes a real correctness bug too — the existing emulation left the destination's high quadword, where AMD zeroes it (High = 0 both forms; movq x,x in the stubs does the same). The stub generator is sound: extrq's shift-mask, insertq's borrowed xmm0-2 (saved below rsp, REX.R when needed), the pand's RIP-relative disp, each stub's 16-alignment keeping the pand operand aligned. patch atomically swaps the 5 bytes inside the instruction's own cache line via cmpxchg16b — threads see all-old or all-new; the re-decode under the STUBS lock handles same-site races. The test executes real bytes twice per case (fault+emulate+replace, then the SSE2 stub) and checks destination, source and scratch registers.

<!-- greyfinch-sync:Marvisak/VIctory:review:6068991562 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3042#pullrequestreview-6068991562). Originally posted by [kotekompotek](https://github.com/kotekompotek) on 2026-11-26T05:29:19Z. **Review:** APPROVED --- Verified: this fixes a real correctness bug too — the existing emulation left the destination's high quadword, where AMD zeroes it (`High = 0` both forms; `movq x,x` in the stubs does the same). The stub generator is sound: extrq's shift-mask, insertq's borrowed xmm0-2 (saved below rsp, REX.R when needed), the pand's RIP-relative disp, each stub's 16-alignment keeping the pand operand aligned. `patch` atomically swaps the 5 bytes inside the instruction's own cache line via cmpxchg16b — threads see all-old or all-new; the re-decode under the STUBS lock handles same-site races. The test executes real bytes twice per case (fault+emulate+replace, then the SSE2 stub) and checks destination, source and scratch registers.
Marvisak commented 2026-11-26 07:01:45 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Marvisak on 2026-11-26T06:16:35Z.


Automated triage for the maintainers.

The cost this addresses is real: hundreds of extrq/insertq faults a second on Intel CPUs. I read the stub encodings in crates/victory-loader/src/sse4a.rs (stub, decode, patch) and they look right. The pand mask is 16-byte aligned and RIP-relative, and the borrowed register is saved and restored. The change can't be merged as it is, though:

  • It needs the maintainer's decision. The loader would generate machine code at runtime and patch the title's code in place. near allocates 64 KiB blocks as PAGE_EXECUTE_READWRITE and leaves them RWX. patch makes the title's code page RWX while it writes. The loader does not do this anywhere today: thunks.rs writes its import stubs and then switches them to PAGE_EXECUTE_READ. Whether VIctory should rewrite title code at all, and on what terms, is a design decision for the maintainer.
  • CI check is failing on this head. std::arch::x86_64::cmpxchg16b, used in patch, is to my knowledge still an unstable intrinsic, and the repo pins stable 1.98.1. If that is the cause, the 16-byte store needs another route, for example inline asm! with lock cmpxchg16b.
  • The emulation's result changes with no source given. crash::sse4a now zeroes the destination's high quadword. The description says AMD documents those bits as undefined and that AMD CPUs zero them. Please cite a hardware reference or a measurement on an SSE4a-capable CPU, or keep the old behaviour in the emulation and have the stub match it.
  • If this goes ahead, it would be safer to make the stub block read-execute after each write (as thunks.rs does) instead of leaving it RWX.

Generated by Claude Code

<!-- greyfinch-sync:Marvisak/VIctory:comment:7184268367 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3042#issuecomment-7184268367). Originally posted by [Marvisak](https://github.com/Marvisak) on 2026-11-26T06:16:35Z. --- <!-- victory-triage v1 head=777c8e780a914c6d48d1be7d278ba58860e92537 verdict=needs-work at=2026-11-26T06:33:00Z --> Automated triage for the maintainers. The cost this addresses is real: hundreds of `extrq`/`insertq` faults a second on Intel CPUs. I read the stub encodings in `crates/victory-loader/src/sse4a.rs` (`stub`, `decode`, `patch`) and they look right. The `pand` mask is 16-byte aligned and RIP-relative, and the borrowed register is saved and restored. The change can't be merged as it is, though: - **It needs the maintainer's decision.** The loader would generate machine code at runtime and patch the title's code in place. `near` allocates 64 KiB blocks as `PAGE_EXECUTE_READWRITE` and leaves them RWX. `patch` makes the title's code page RWX while it writes. The loader does not do this anywhere today: `thunks.rs` writes its import stubs and then switches them to `PAGE_EXECUTE_READ`. Whether VIctory should rewrite title code at all, and on what terms, is a design decision for the maintainer. - **CI `check` is failing** on this head. `std::arch::x86_64::cmpxchg16b`, used in `patch`, is to my knowledge still an unstable intrinsic, and the repo pins stable 1.98.1. If that is the cause, the 16-byte store needs another route, for example inline `asm!` with `lock cmpxchg16b`. - **The emulation's result changes with no source given.** `crash::sse4a` now zeroes the destination's high quadword. The description says AMD documents those bits as undefined and that AMD CPUs zero them. Please cite a hardware reference or a measurement on an SSE4a-capable CPU, or keep the old behaviour in the emulation and have the stub match it. - If this goes ahead, it would be safer to make the stub block read-execute after each write (as `thunks.rs` does) instead of leaving it RWX. --- _Generated by [Claude Code](https://claude.ai/code)_
upstream-sync closed this pull request 2026-11-26 10:04:40 +00:00
upipibi commented 2026-11-28 02:14:57 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by upipibi on 2026-11-28T02:14:57Z.


In case this is picked up again: another VIctory-derived tree merged the same approach, ZigZagBoi1/ScarlettPort#377 ("replace faulting insertq/extrq sites with SSE2 stubs"). Its description has data for three of the triage points. I read it and ran nothing.

  • The high quadword (point 3). ScarlettPort#377 zeroes it "as the hardware does", and its test the_stubs_do_what_the_instructions_do compares the stubs with the real instruction on an AMD CPU. It covers every defined length and index of immediate insertq over all 256 xmm pairs (532,480 forms), immediate extrq for all 16 registers, and the register forms, checking all 16 xmm registers, rax/rcx/rdx/r8/r9, the flags and rsp. That is a measurement on an SSE4a-capable CPU that would show if those bits were left as they were.
  • The 16-byte store (point 2). It patches with "one cmpxchg16b store, same path as the wait and clzero patches" in that tree, so there is a stable-toolchain route to look at.
  • Why it matters beyond cost. It ties the hot site (a half-float packing routine) to 13th-gen Intel crashes at startup, right after the first emulated insertq, read as a timing race made worse by the fault cost (ScarlettPort#350).

Patching title code is still the maintainer's call (point 1). For comparison, xcl#3082 (open) patches the title's clzero loops on Intel the same way.

AI-assisted (Claude Code, Claude Opus 5.5 read ScarlettPort#377 and this thread).

<!-- greyfinch-sync:Marvisak/VIctory:comment:7232234052 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3042#issuecomment-7232234052). Originally posted by [upipibi](https://github.com/upipibi) on 2026-11-28T02:14:57Z. --- In case this is picked up again: another VIctory-derived tree merged the same approach, ZigZagBoi1/ScarlettPort#377 ("replace faulting insertq/extrq sites with SSE2 stubs"). Its description has data for three of the triage points. I read it and ran nothing. - **The high quadword (point 3).** ScarlettPort#377 zeroes it "as the hardware does", and its test `the_stubs_do_what_the_instructions_do` compares the stubs with the real instruction on an AMD CPU. It covers every defined length and index of immediate `insertq` over all 256 xmm pairs (532,480 forms), immediate `extrq` for all 16 registers, and the register forms, checking all 16 xmm registers, rax/rcx/rdx/r8/r9, the flags and rsp. That is a measurement on an SSE4a-capable CPU that would show if those bits were left as they were. - **The 16-byte store (point 2).** It patches with "one cmpxchg16b store, same path as the wait and clzero patches" in that tree, so there is a stable-toolchain route to look at. - **Why it matters beyond cost.** It ties the hot site (a half-float packing routine) to 13th-gen Intel crashes at startup, right after the first emulated `insertq`, read as a timing race made worse by the fault cost (ScarlettPort#350). Patching title code is still the maintainer's call (point 1). For comparison, xcl#3082 (open) patches the title's `clzero` loops on Intel the same way. AI-assisted (Claude Code, Claude Opus 5.5 read ScarlettPort#377 and this thread).
101Leafy commented 2026-11-29 07:27:57 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by 101Leafy on 2026-11-29T07:27:57Z.


Pushed 0c2def1a48 for the review points:

  • Patching title code: this only runs after an extrq/insertq has already faulted and been emulated. It changes 5 bytes at that address and nothing else, and it can be dropped if you would rather not patch title code at all.
  • No more RWX: each stub gets its own page, written as read-write and then made read-execute before the jump to it is placed, the same as the thunks.
  • cmpxchg16b is now inline asm (lock cmpxchg16b) instead of the unstable intrinsic, so it builds on stable.
  • High quadword: the stub and the emulation both leave it as it was, the way the existing emulation did before this PR. The zeroing came in without a source, so I took it out. If hardware behaviour should win here, it's a one-line change in each place.

Numbers on an i9-13900K (no SSE4a): 191 to 491 faults per second from these instructions during play before, 0 after the first fault at each address.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7252488963 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3042#issuecomment-7252488963). Originally posted by [101Leafy](https://github.com/101Leafy) on 2026-11-29T07:27:57Z. --- Pushed 0c2def1a48 for the review points: - Patching title code: this only runs after an extrq/insertq has already faulted and been emulated. It changes 5 bytes at that address and nothing else, and it can be dropped if you would rather not patch title code at all. - No more RWX: each stub gets its own page, written as read-write and then made read-execute before the jump to it is placed, the same as the thunks. - cmpxchg16b is now inline asm (`lock cmpxchg16b`) instead of the unstable intrinsic, so it builds on stable. - High quadword: the stub and the emulation both leave it as it was, the way the existing emulation did before this PR. The zeroing came in without a source, so I took it out. If hardware behaviour should win here, it's a one-line change in each place. Numbers on an i9-13900K (no SSE4a): 191 to 491 faults per second from these instructions during play before, 0 after the first fault at each address.
101Leafy commented 2026-12-01 00:45:15 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by 101Leafy on 2026-12-01T00:45:15Z.


Pushed 249252552f for the rest of the static review:

  1. Clippy: the line it flagged is gone since the rewrite, and clippy -D warnings passes on the crate.
  2. near() skips any place below 0x10000, so a block is never reserved at a null base.
  3. Stub blocks are kept in a list, and a fault uses the first one in reach with a free page. Two modules more than 2 GiB apart each keep their own block.

From the minor notes: the high quadword is checked only where the stub ran, extrq's reg check ignores REX.R like the hardware and crash.rs do, and a page counts as used only after its stub is written and made read-execute. The cache was already flushed before the jump is placed. The loader's sse4a tests pass on an i9-13900K.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7296698626 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3042#issuecomment-7296698626). Originally posted by [101Leafy](https://github.com/101Leafy) on 2026-12-01T00:45:15Z. --- Pushed 249252552f for the rest of the static review: 1. Clippy: the line it flagged is gone since the rewrite, and `clippy -D warnings` passes on the crate. 2. `near()` skips any place below 0x10000, so a block is never reserved at a null base. 3. Stub blocks are kept in a list, and a fault uses the first one in reach with a free page. Two modules more than 2 GiB apart each keep their own block. From the minor notes: the high quadword is checked only where the stub ran, extrq's reg check ignores REX.R like the hardware and `crash.rs` do, and a page counts as used only after its stub is written and made read-execute. The cache was already flushed before the jump is placed. The loader's sse4a tests pass on an i9-13900K.
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/3042:upstream-pr/3042'
git switch 'upstream-pr/3042'

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