Loader: extrq/insertq with the field in the instruction jump to SSE2 code after their first fault #3040
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/3042"
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?
Imported from Marvisak/VIctory. Originally posted by 101Leafy on 2026-11-26T05:04:23Z.
Intel CPUs have no SSE4a. Every
extrq/insertqa title runs raises an illegal-instruction exception, whichcrash.rsemulates. 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
jmpto the same work written in SSE2 (psrlq/psllq/pand/por;insertqborrows 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 singlecmpxchg16bon 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.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.rsandcrash.rs). The SSE2 lowering andcmpxchg16bsingle-store patching design is very neat; a few concrete issues need attention before merge:crates/victory-loader/src/sse4a.rs:274):clippy::precedencerejects0xc0 | (x & 7) * 9(should be0xc0 | ((x & 7) * 9)).near()can passNULLtoVirtualAllocand leak unreachable RWX blocks (sse4a.rs:138-150):placesprobesat.checked_sub(d)fordin0x10_0000..0x7000_0000stepped by0x10_0000. Wheneverat & !0xffffis a 1 MiB-aligned address below0x7000_0000(e.g. a 32-bit preferred base or test allocation) and lower candidates fail,at.checked_sub(d)yieldsSome(0). CallingVirtualAlloc(std::ptr::null(), ...)lets Windows allocate anywhere in the 64-bit address space — outside±2 GiBjmp rel32reach — sofits()then fails and leaks a 64 KiBPAGE_EXECUTE_READWRITEallocation on every fault. Filtering out addresses below0x10000(at minimumplace != 0) prevents accidentalNULLfallback.STUBSabandons blocks when two modules >2 GiB apart alternate (sse4a.rs:131, 183-185): Keeping only a singleOption<(usize, usize)>discards remaining capacity in the previous 64 KiB block whenever a fault occurs in a module more than±2 GiBaway (e.g. main executable vs a high-base title DLL). Keeping aVec<(usize, usize)>and scanning for an existing block in range with enough room avoids wasting blocks.Minor non-blocking notes:
sse4a.rs:320): On CPUs with native SSE4a (replaced == false), the test runs the hardware instruction and assertsout[1] == 0. Since AMD64 APM Vol. 4 specifies bits127:64ofextrq/insertqas undefined, checkingout[1] == 0only whenreplaced(or checking onlyout[0]on native SSE4a) avoids depending on microarchitectural zeroing across AMD generations/emulators.decodevscrash.rs:531:decodechecksreg != 0(includingREX.R) onextrq, whilecrash.rs:531checks(modrm >> 3) & 7 != 0(matching hardware, which ignoresREX.Ron/0).FlushInstructionCacheon the newly written stub slice[at_stub..at_stub + body.len()]before exposing the jump (and only advancing*usedifpatchsucceeds) would also tighten the patching path.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 = 0both forms;movq x,xin 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.patchatomically 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.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/insertqfaults a second on Intel CPUs. I read the stub encodings incrates/victory-loader/src/sse4a.rs(stub,decode,patch) and they look right. Thepandmask 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:nearallocates 64 KiB blocks asPAGE_EXECUTE_READWRITEand leaves them RWX.patchmakes the title's code page RWX while it writes. The loader does not do this anywhere today:thunks.rswrites its import stubs and then switches them toPAGE_EXECUTE_READ. Whether VIctory should rewrite title code at all, and on what terms, is a design decision for the maintainer.checkis failing on this head.std::arch::x86_64::cmpxchg16b, used inpatch, 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 inlineasm!withlock cmpxchg16b.crash::sse4anow 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.thunks.rsdoes) instead of leaving it RWX.Generated by Claude Code
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_stubs_do_what_the_instructions_docompares the stubs with the real instruction on an AMD CPU. It covers every defined length and index of immediateinsertqover all 256 xmm pairs (532,480 forms), immediateextrqfor 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.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
clzeroloops on Intel the same way.AI-assisted (Claude Code, Claude Opus 5.5 read ScarlettPort#377 and this thread).
Imported from Marvisak/VIctory. Originally posted by 101Leafy on 2026-11-29T07:27:57Z.
Pushed
0c2def1a48for the review points:lock cmpxchg16b) instead of the unstable intrinsic, so it builds on stable.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.
Imported from Marvisak/VIctory. Originally posted by 101Leafy on 2026-12-01T00:45:15Z.
Pushed
249252552ffor the rest of the static review:clippy -D warningspasses on the crate.near()skips any place below 0x10000, so a block is never reserved at a null base.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.rsdo, 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.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.Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.