loader: replace whole-byte insertq with a stub of moves at its first fault #440

Open
github-bot wants to merge 2 commits from github-bot/gh-440 into main AGit
Owner

@⁠TreXito on GitHub · 2026-12-04 04:13 UTC · original
TreXito:pr/insertq-stub → main · +273 −11 · 2 files · 2 commits · open

On a CPU without SSE4a (any Intel), every insertq faults and is emulated in the exception handler. While driving that is about 1,450 to 1,700 exceptions a second, each a round trip through Wine's exception dispatch.

The immediate form with a field of whole bytes (length and index multiples of 8) is now replaced at its first fault by a jump to a stub of plain moves, the same way the clzero loop and the wait instructions already are:

  • lea rsp, [rsp-32], both registers to the stack, push rax, the field copied in 8/4/2/1-byte pieces through rax, pop rax, movq back (the high quadword zero, as the emulation leaves it), lea rsp, [rsp+32], jmp back.
  • Only moves, lea, push and pop: no flags change, no other register changes, the scratch is stack below the caller's.
  • Fields that are not whole bytes, and the register form, stay emulated.
  • The replacement is a 5-byte jump plus int3 padding inside one aligned 16 bytes (patch), so no thread can be inside the rest of the instruction.
  • A thread that faulted on the old instruction while another one replaced it finds the jump at its rip and simply retries (the first try without this crashed at the jump bytes).
  • VICTORY_INSERTQ_PATCH=0 keeps every insertq emulated.

Tests

  • an_insertq_stub_does_what_the_emulation_does runs stubs for eight field shapes in a page of its own and compares them with decode::insertq: low quadword equal, high quadword zero, source, rax and the arithmetic flags unchanged. Non-whole-byte fields and fields past the quadword get no stub.
  • victory-loader's 85 library tests pass under Wine (GE-Proton10-34), the six console_insn ones also with --test-threads=1.
  • Before this, a standalone harness ran the generated stubs natively for every whole-byte length/index pair and all 16 source/destination register pairs: 3072 of 3072 matched the emulation, with the other xmm registers, rax and the flags preserved.

Measured

i5-13600KF, RX 7800 XT, release build, 300 s standing, two runs per side (ABAB):

avg fps p10
patched 27.23 23.6
VICTORY_INSERTQ_PATCH=0 26.81 23.15

+1.6% average. A 7-minute ride with the patch logged 0 insertq exceptions after the first pass over each site, and no crashes in any run. On AMD CPUs nothing changes: insertq runs natively and never faults.

🤖 Generated with Claude Code

https://claude.ai/code/session_01WNCfbX5dPKJzSkgbf16GX4

**@⁠TreXito** on GitHub · 2026-12-04 04:13 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/440) `TreXito:pr/insertq-stub` → `main` · +273 −11 · 2 files · 2 commits · open On a CPU without SSE4a (any Intel), every `insertq` faults and is emulated in the exception handler. While driving that is about 1,450 to 1,700 exceptions a second, each a round trip through Wine's exception dispatch. The immediate form with a field of whole bytes (length and index multiples of 8) is now replaced at its first fault by a jump to a stub of plain moves, the same way the `clzero` loop and the wait instructions already are: - `lea rsp, [rsp-32]`, both registers to the stack, `push rax`, the field copied in 8/4/2/1-byte pieces through `rax`, `pop rax`, `movq` back (the high quadword zero, as the emulation leaves it), `lea rsp, [rsp+32]`, `jmp` back. - Only moves, `lea`, `push` and `pop`: no flags change, no other register changes, the scratch is stack below the caller's. - Fields that are not whole bytes, and the register form, stay emulated. - The replacement is a 5-byte jump plus `int3` padding inside one aligned 16 bytes (`patch`), so no thread can be inside the rest of the instruction. - A thread that faulted on the old instruction while another one replaced it finds the jump at its `rip` and simply retries (the first try without this crashed at the jump bytes). - `VICTORY_INSERTQ_PATCH=0` keeps every `insertq` emulated. ### Tests - `an_insertq_stub_does_what_the_emulation_does` runs stubs for eight field shapes in a page of its own and compares them with `decode::insertq`: low quadword equal, high quadword zero, source, `rax` and the arithmetic flags unchanged. Non-whole-byte fields and fields past the quadword get no stub. - `victory-loader`'s 85 library tests pass under Wine (GE-Proton10-34), the six `console_insn` ones also with `--test-threads=1`. - Before this, a standalone harness ran the generated stubs natively for every whole-byte length/index pair and all 16 source/destination register pairs: 3072 of 3072 matched the emulation, with the other xmm registers, `rax` and the flags preserved. ### Measured i5-13600KF, RX 7800 XT, release build, 300 s standing, two runs per side (ABAB): | | avg fps | p10 | |---|---|---| | patched | 27.23 | 23.6 | | `VICTORY_INSERTQ_PATCH=0` | 26.81 | 23.15 | +1.6% average. A 7-minute ride with the patch logged 0 `insertq` exceptions after the first pass over each site, and no crashes in any run. On AMD CPUs nothing changes: `insertq` runs natively and never faults. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WNCfbX5dPKJzSkgbf16GX4
On a CPU without SSE4a every insertq faults and is emulated in the
exception handler, about 1,450 to 1,700 times a second while driving.
The immediate form with a field of whole bytes is now patched at its
first fault into a jump to a stub of plain moves, as the clzero loop and
the wait instructions already are. Other fields and the register form
stay emulated; VICTORY_INSERTQ_PATCH=0 keeps every insertq emulated.

i5-13600KF, release, 300 s standing, ABAB: 27.23 fps vs 26.81 (+1.6%).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WNCfbX5dPKJzSkgbf16GX4
github-bot locked as GitHub sync and limited conversation to collaborators 2026-12-04 04:14:10 +00:00
Author
Owner

@⁠Kal0s-design on GitHub · 2026-12-04 04:30 UTC · original

Tested 9c3c84c natively on Windows 11 (MSVC toolchain, not under Wine).

cargo test -p victory-loader passes, 85 lib tests against 84 on the merge base, the new one being the only difference, and nothing is ignored natively. an_insertq_stub_does_what_the_emulation_does passed 20 of 20 runs. Clippy shows the same 4 transmute warnings as the base and nothing new.

I also ran a local differential (not pushed). All 256 destination/source pairs, including same register and xmm8 to xmm15, times 70 whole-byte length/index encodings, 430,080 runs on a stack of their own, all matched decode::insertq with the high quadword zero, the other xmm registers, rax, the arithmetic flags and rsp unchanged, and nothing written outside the 40 bytes under the caller's rsp. Driving patch_insertq on fake code also worked for 6 and 7 byte forms and left the ones crossing their 16 bytes alone.

A few things.

  • The retry check and the decode in emulate read the live bytes at rip twice. If another thread's patch lands between the 0xe9 test and decode::decode, decode sees the jump, returns None and the handler returns 0, which is the same crash the check was added for, just in a smaller window. Copying the bytes into a local array once and using that for both, or checking for the stub jump again when decode fails, would close it.
  • used grows before patch is known to succeed, so a lost race wastes 64 bytes of the stub area. patch_clzero does the same and it is unlikely to matter, but bumping it only on success would be cleaner.
  • Sites that cross their aligned 16 bytes take the STUBS lock and build a stub on every fault before being rejected. Doing the alignment and length checks before the lock would make that path cheap.
  • The stub writes 40 bytes under the title's rsp. Is it known that the title never keeps anything in the red zone at these sites? If not sure, the lea could step past 128 bytes first (that needs the disp32 form, a few bytes longer).

AI-assisted: yes

**@⁠Kal0s-design** on GitHub · 2026-12-04 04:30 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/440#issuecomment-7401309051) Tested 9c3c84c natively on Windows 11 (MSVC toolchain, not under Wine). `cargo test -p victory-loader` passes, 85 lib tests against 84 on the merge base, the new one being the only difference, and nothing is ignored natively. `an_insertq_stub_does_what_the_emulation_does` passed 20 of 20 runs. Clippy shows the same 4 transmute warnings as the base and nothing new. I also ran a local differential (not pushed). All 256 destination/source pairs, including same register and xmm8 to xmm15, times 70 whole-byte length/index encodings, 430,080 runs on a stack of their own, all matched `decode::insertq` with the high quadword zero, the other xmm registers, rax, the arithmetic flags and rsp unchanged, and nothing written outside the 40 bytes under the caller's rsp. Driving `patch_insertq` on fake code also worked for 6 and 7 byte forms and left the ones crossing their 16 bytes alone. A few things. - The retry check and the decode in `emulate` read the live bytes at `rip` twice. If another thread's patch lands between the `0xe9` test and `decode::decode`, decode sees the jump, returns `None` and the handler returns 0, which is the same crash the check was added for, just in a smaller window. Copying the bytes into a local array once and using that for both, or checking for the stub jump again when decode fails, would close it. - `used` grows before `patch` is known to succeed, so a lost race wastes 64 bytes of the stub area. `patch_clzero` does the same and it is unlikely to matter, but bumping it only on success would be cleaner. - Sites that cross their aligned 16 bytes take the `STUBS` lock and build a stub on every fault before being rejected. Doing the alignment and length checks before the lock would make that path cheap. - The stub writes 40 bytes under the title's rsp. Is it known that the title never keeps anything in the red zone at these sites? If not sure, the `lea` could step past 128 bytes first (that needs the disp32 form, a few bytes longer). AI-assisted: yes
Author
Owner

@⁠Luxuride on GitHub · 2026-12-04 11:16 UTC · original

I hand-decoded the generated bytes rather than trusting the comments, and they are right: F3 44 0F 7F is movdqu [rsp+disp], xmm with REX.R only for reg >= 8, F3 44 0F 7E zeroes 127:64 exactly as the emulation's d.High = 0 (crates/victory-loader/src/console_insn.rs:706) requires, and the lea rsp,[rsp-32] frame puts dst at [rsp+8] and src at [rsp+24] as documented, with every disp8 in range. The field gate (len & 63, idx & 63, bits == 64 for 0) matches crates/victory-loader/src/console_insn_decode.rs:50-54,70-71, so the stub reproduces the same rules the decoder applies. Stub-before-jump, then patch()'s cmpxchg16b verify, then the jump with int3 padding inside one aligned 16 bytes — that ordering is right, as is the re-entry guard for a thread that faulted on the old instruction.

Three things before merge, none of them deep:

  • /// Room for [clzero_stub]s near the title's code at console_insn.rs:201, and near() at :205, now describe an arena that also holds insertq_stubs. Reword to "stubs" — the allocation and next_multiple_of(16) accounting is shared now, and the doc will be read as a promise about clzero alone.
  • VICTORY_INSERTQ_PATCH (console_insn.rs:198) is the only escape hatch on this path that is missing from the "Runtime-only settings" table in docs/SETTINGS.md, and it is the one thing that lets a user compare patched against emulated runs. documented_switches_are_read only enforces docs -> source, so nothing fails today.
  • The test does not cover dst == src, which the code handles correctly (both copies are taken before either is written) but which production will hit. A (1, 1) case costs nothing.

The 40 bytes below rsp are fine on Windows x64 — there is no red zone to violate, and a guard page there just grows the stack — but it is the one place where leaf-function behaviour is assumed rather than shown.

**@⁠Luxuride** on GitHub · 2026-12-04 11:16 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/440#issuecomment-7409870141) I hand-decoded the generated bytes rather than trusting the comments, and they are right: `F3 44 0F 7F` is `movdqu [rsp+disp], xmm` with REX.R only for `reg >= 8`, `F3 44 0F 7E` zeroes 127:64 exactly as the emulation's `d.High = 0` (`crates/victory-loader/src/console_insn.rs:706`) requires, and the `lea rsp,[rsp-32]` frame puts dst at `[rsp+8]` and src at `[rsp+24]` as documented, with every disp8 in range. The field gate (`len & 63`, `idx & 63`, `bits == 64` for 0) matches `crates/victory-loader/src/console_insn_decode.rs:50-54,70-71`, so the stub reproduces the same rules the decoder applies. Stub-before-jump, then `patch()`'s cmpxchg16b verify, then the jump with `int3` padding inside one aligned 16 bytes — that ordering is right, as is the re-entry guard for a thread that faulted on the old instruction. Three things before merge, none of them deep: - `/// Room for [`clzero_stub`]s near the title's code` at `console_insn.rs:201`, and `near()` at `:205`, now describe an arena that also holds `insertq_stub`s. Reword to "stubs" — the allocation and `next_multiple_of(16)` accounting is shared now, and the doc will be read as a promise about `clzero` alone. - `VICTORY_INSERTQ_PATCH` (`console_insn.rs:198`) is the only escape hatch on this path that is missing from the "Runtime-only settings" table in `docs/SETTINGS.md`, and it is the one thing that lets a user compare patched against emulated runs. `documented_switches_are_read` only enforces docs -> source, so nothing fails today. - The test does not cover `dst == src`, which the code handles correctly (both copies are taken before either is written) but which production will hit. A `(1, 1)` case costs nothing. The 40 bytes below `rsp` are fine on Windows x64 — there is no red zone to violate, and a guard page there just grows the stack — but it is the one place where leaf-function behaviour is assumed rather than shown.
- emulate copies the faulting bytes once: the check for another thread's
  jump and the decode see the same bytes (a patch landing between the two
  reads could still end in the crash the check is for).
- patch_insertq and patch_clzero check the 16-byte fit before taking the
  stub lock, and take stub room only once the patch is in.
- The stub area's doc names both stubs.
- The test also runs one register as both source and destination.
- VICTORY_INSERTQ_PATCH=0 is in the runtime-only settings table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WNCfbX5dPKJzSkgbf16GX4
Author
Owner

@⁠TreXito on GitHub · 2026-12-04 11:48 UTC · original

Thanks both. Fixed in b0d7eae:

  • emulate now copies the faulting bytes into a local array once, and both the check for another thread's jump and decode::decode read that copy, so a patch landing between them can no longer end in the handler returning 0.
  • patch_insertq and patch_clzero check the 16-byte fit before taking the STUBS lock, so a site that crosses its 16 bytes no longer builds a stub on every fault before it is rejected.
  • used grows only once patch succeeds. A lost race leaves its stub bytes unreferenced, and the next stub reuses that space.
  • The STUBS doc now names both stubs.
  • The test also runs one register as both destination and source (xmm1, xmm1 at three field shapes) and checks it against decode::insertq(d, d, ..).
  • VICTORY_INSERTQ_PATCH=0 is now in the runtime-only settings table.

On the 40 bytes under rsp: Windows x64 has no red zone. The ABI treats memory below rsp as volatile, and the OS can overwrite it at any time on the same stack (exception dispatch, APCs), so the title cannot keep anything there. That matches what Luxuride says above.

Checked after the change:

  • victory-loader lib tests: 85 of 85 pass under Wine, including the new same-register cases.
  • Release build on an i5-13600KF, 209 s standing in the world: 26.9 fps average, p10 23.4, no crash. That is in line with the patched numbers in the description.

AI-assisted: yes

**@⁠TreXito** on GitHub · 2026-12-04 11:48 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/440#issuecomment-7410594090) Thanks both. Fixed in b0d7eae: - `emulate` now copies the faulting bytes into a local array once, and both the check for another thread's jump and `decode::decode` read that copy, so a patch landing between them can no longer end in the handler returning 0. - `patch_insertq` and `patch_clzero` check the 16-byte fit before taking the `STUBS` lock, so a site that crosses its 16 bytes no longer builds a stub on every fault before it is rejected. - `used` grows only once `patch` succeeds. A lost race leaves its stub bytes unreferenced, and the next stub reuses that space. - The `STUBS` doc now names both stubs. - The test also runs one register as both destination and source (`xmm1, xmm1` at three field shapes) and checks it against `decode::insertq(d, d, ..)`. - `VICTORY_INSERTQ_PATCH=0` is now in the runtime-only settings table. On the 40 bytes under `rsp`: Windows x64 has no red zone. The ABI treats memory below `rsp` as volatile, and the OS can overwrite it at any time on the same stack (exception dispatch, APCs), so the title cannot keep anything there. That matches what Luxuride says above. Checked after the change: - `victory-loader` lib tests: 85 of 85 pass under Wine, including the new same-register cases. - Release build on an i5-13600KF, 209 s standing in the world: 26.9 fps average, p10 23.4, no crash. That is in line with the patched numbers in the description. AI-assisted: yes
Author
Owner

@⁠Kal0s-design on GitHub · 2026-12-04 13:57 UTC · original

Re-tested b0d7eae natively on Windows 11 (MSVC toolchain, not under Wine).

cargo test -p victory-loader --lib -- --test-threads=2 gives 85 passed, 0 failed, 0 ignored, twice. an_insertq_stub_does_what_the_emulation_does passed 20 of 20 runs on its own.

What I checked in the new commit.

  • The copy in emulate (console_insn.rs:526-529) reads n bytes into a 16 byte array, and n still comes from the same readable(rip, n) probe as before (:514, readable at :436-449 checks the whole range lies in one committed region). So it reads no further than main's slice could, and the 0xe9 check and decode::decode now see the same bytes.
  • The fit checks now run before the lock (:157 for insertq, :246 for clzero), and used only grows when patch returns true (:194-196, :268-270). Because the STUBS lock is held from :161 through the patch, two threads never build at the same offset at once, so a loser's stub can only be overwritten after a winner has already moved used past its own stub. I checked this with a local test I'm not pushing: 6 threads racing patch_insertq on 8 fake sites per round, 120 rounds. Every site had exactly one winner, every jump pointed below used at a byte-for-byte intact stub of its own, running the sites (old rounds included) gave decode::insertq, and used ended at 46,080 for 960 stubs, so 48 each with nothing lost to the 4,800 failed attempts. As a control, leaving used unbumped makes the same test fail on the first site.
  • The same-register case (:824-848) checks against decode::insertq(d, d, ..), which is what the emulation does, since it copies the source before writing the destination (:708, :715). As a control I added a pxor of the destination right after its copy, before the source is saved. The eight old cases still passed and the new one failed at xmm1, xmm1, len 8 idx 8, so it catches exactly that ordering mistake.
  • VICTORY_INSERTQ_PATCH=0 is in docs/SETTINGS.md:155.

Agree on the red zone, nothing more from me there. Looks good to me.

AI-assisted: yes

**@⁠Kal0s-design** on GitHub · 2026-12-04 13:57 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/440#issuecomment-7413617454) Re-tested b0d7eae natively on Windows 11 (MSVC toolchain, not under Wine). `cargo test -p victory-loader --lib -- --test-threads=2` gives 85 passed, 0 failed, 0 ignored, twice. `an_insertq_stub_does_what_the_emulation_does` passed 20 of 20 runs on its own. What I checked in the new commit. - The copy in `emulate` (`console_insn.rs:526-529`) reads `n` bytes into a 16 byte array, and `n` still comes from the same `readable(rip, n)` probe as before (`:514`, `readable` at `:436-449` checks the whole range lies in one committed region). So it reads no further than main's slice could, and the `0xe9` check and `decode::decode` now see the same bytes. - The fit checks now run before the lock (`:157` for insertq, `:246` for clzero), and `used` only grows when `patch` returns true (`:194-196`, `:268-270`). Because the `STUBS` lock is held from `:161` through the patch, two threads never build at the same offset at once, so a loser's stub can only be overwritten after a winner has already moved `used` past its own stub. I checked this with a local test I'm not pushing: 6 threads racing `patch_insertq` on 8 fake sites per round, 120 rounds. Every site had exactly one winner, every jump pointed below `used` at a byte-for-byte intact stub of its own, running the sites (old rounds included) gave `decode::insertq`, and `used` ended at 46,080 for 960 stubs, so 48 each with nothing lost to the 4,800 failed attempts. As a control, leaving `used` unbumped makes the same test fail on the first site. - The same-register case (`:824-848`) checks against `decode::insertq(d, d, ..)`, which is what the emulation does, since it copies the source before writing the destination (`:708`, `:715`). As a control I added a `pxor` of the destination right after its copy, before the source is saved. The eight old cases still passed and the new one failed at `xmm1, xmm1, len 8 idx 8`, so it catches exactly that ordering mistake. - `VICTORY_INSERTQ_PATCH=0` is in `docs/SETTINGS.md:155`. Agree on the red zone, nothing more from me there. Looks good to me. AI-assisted: yes
This pull request has changes conflicting with the target branch.
  • docs/SETTINGS.md
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/440/head:github-bot/gh-440'
git switch 'github-bot/gh-440'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-440'
git switch 'github-bot/gh-440'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-440'
git switch 'github-bot/gh-440'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-440'
git switch 'main'
git merge --squash 'github-bot/gh-440'
git switch 'main'
git merge --ff-only 'github-bot/gh-440'
git switch 'main'
git merge 'github-bot/gh-440'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.