loader: replace SSE4a EXTRQ with native trampolines on hosts without SSE4a #839

Manually merged
github merged 1 commit from gh-pr/839/head into gh-pr/839/base 2026-11-26 09:34:29 +00:00
Owner

@⁠ew-sudo on GitHub · 2026-09-25 21:11 UTC · original
ew-sudo:extrq-native-trampolines → main · +583 −150 · 4 files · 1 commits · merged 2026-10-03 15:40 UTC

Problem

EXTRQ is an AMD-only SSE4a instruction. On CPUs without SSE4a (Intel), every EXTRQ raises an illegal-instruction exception and is emulated in the exception handler (TryEmulateSse4a in x64InstructionEmulator.cpp). The result is correct but each execution costs a full exception round trip.

Astro Bot (PPSA21564, 01.007) executes EXTRQ in hot code. With a temporary counter in the trap handler I measured about 810,000 EXTRQ traps per second on an Intel Core Ultra 7 155H, and the game spent its time in exception handling instead of reaching the title screen.

Fix

When the host lacks SSE4a, the red-zone patcher now also collects EXTRQ sites (both the immediate form and the XMM register form) and relocates them to a trampoline that computes the result with ordinary x86-64 instructions:

  • the trampoline steps over the guest red zone and saves/restores RFLAGS, RAX, RCX and RDX;
  • the bit field is extracted with a shift and a mask (a length of 0 means 64 bits; length + index > 64 keeps the full mask, matching the existing trap emulator);
  • the result is written back with legacy SSE2 MOVQ, which clears bits 64-127 like the trap emulator does (dest[1] = 0) and leaves the upper YMM half untouched.

The generator is adapted from shadPS4's GenerateEXTRQ (src/core/cpu_patches.cpp), the same project redZonePatcher.cpp already comes from. The patcher logs SSE4a EXTRQ native patching: found=N, patched=M per module. INSERTQ, MOVNTSS and MOVNTSD still go through the existing trap emulation.

Testing

  • Windows 11, Intel Core Ultra 7 155H, RTX 4070 Laptop GPU, launched with --redzone.
  • Astro Bot PPSA21564 01.007: found=97, patched=97; the trap counter dropped from ~810,000/s to 0 for EXTRQ, and the game reaches the title screen and gameplay.
  • Tested on top of #780 (needed to get past the intro on my setup) and #838; this commit does not depend on them and applies cleanly on main.

Notes

  • The native path only runs where the red-zone patcher runs (Windows, with --redzone or --amd-cpu). Without it, EXTRQ keeps using the trap emulator. I put it there because that patcher already has the decoding, relocation and trampoline machinery, which kept this PR small.

  • Longer term, I don't think this belongs in the red-zone patcher. Replacing AMD-only instructions is a CPU-compatibility concern, not a red-zone one. I would suggest a separate "CPU compatibility" patching pass that:

    • is enabled automatically when the host lacks the feature (e.g. SSE4a on Intel), without requiring --redzone;
    • is not limited to Windows (Linux and macOS on Intel have the same trap cost);
    • also covers INSERTQ, MOVNTSS and MOVNTSD, which are still trap-emulated.

    It could reuse the existing decoder/relocation code. I kept this PR minimal on purpose and would be happy to work on that split as a follow-up if you agree with the direction.

  • Related: #720 also improves Intel compatibility, but keeps EXTRQ trap-based (it protects the red zone around the trap). This PR removes the trap for EXTRQ instead.

I used Claude for this commit too, but I built and tested it myself and reviewed the code.

**@⁠ew-sudo** on GitHub · 2026-09-25 21:11 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/839) `ew-sudo:extrq-native-trampolines` → `main` · +583 −150 · 4 files · 1 commits · merged 2026-10-03 15:40 UTC ### Problem EXTRQ is an AMD-only SSE4a instruction. On CPUs without SSE4a (Intel), every EXTRQ raises an illegal-instruction exception and is emulated in the exception handler (`TryEmulateSse4a` in `x64InstructionEmulator.cpp`). The result is correct but each execution costs a full exception round trip. Astro Bot (PPSA21564, 01.007) executes EXTRQ in hot code. With a temporary counter in the trap handler I measured about **810,000 EXTRQ traps per second** on an Intel Core Ultra 7 155H, and the game spent its time in exception handling instead of reaching the title screen. ### Fix When the host lacks SSE4a, the red-zone patcher now also collects EXTRQ sites (both the immediate form and the XMM register form) and relocates them to a trampoline that computes the result with ordinary x86-64 instructions: - the trampoline steps over the guest red zone and saves/restores RFLAGS, RAX, RCX and RDX; - the bit field is extracted with a shift and a mask (a length of 0 means 64 bits; `length + index > 64` keeps the full mask, matching the existing trap emulator); - the result is written back with legacy SSE2 `MOVQ`, which clears bits 64-127 like the trap emulator does (`dest[1] = 0`) and leaves the upper YMM half untouched. The generator is adapted from shadPS4's `GenerateEXTRQ` (`src/core/cpu_patches.cpp`), the same project `redZonePatcher.cpp` already comes from. The patcher logs `SSE4a EXTRQ native patching: found=N, patched=M` per module. INSERTQ, MOVNTSS and MOVNTSD still go through the existing trap emulation. ### Testing - Windows 11, Intel Core Ultra 7 155H, RTX 4070 Laptop GPU, launched with `--redzone`. - Astro Bot PPSA21564 01.007: `found=97, patched=97`; the trap counter dropped from ~810,000/s to 0 for EXTRQ, and the game reaches the title screen and gameplay. - Tested on top of #780 (needed to get past the intro on my setup) and #838; this commit does not depend on them and applies cleanly on `main`. ### Notes - The native path only runs where the red-zone patcher runs (Windows, with `--redzone` or `--amd-cpu`). Without it, EXTRQ keeps using the trap emulator. I put it there because that patcher already has the decoding, relocation and trampoline machinery, which kept this PR small. - **Longer term, I don't think this belongs in the red-zone patcher.** Replacing AMD-only instructions is a CPU-compatibility concern, not a red-zone one. I would suggest a separate "CPU compatibility" patching pass that: - is enabled automatically when the host lacks the feature (e.g. SSE4a on Intel), without requiring `--redzone`; - is not limited to Windows (Linux and macOS on Intel have the same trap cost); - also covers INSERTQ, MOVNTSS and MOVNTSD, which are still trap-emulated. It could reuse the existing decoder/relocation code. I kept this PR minimal on purpose and would be happy to work on that split as a follow-up if you agree with the direction. - Related: #720 also improves Intel compatibility, but keeps EXTRQ trap-based (it protects the red zone around the trap). This PR removes the trap for EXTRQ instead. I used Claude for this commit too, but I built and tested it myself and reviewed the code.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:34:28 +00:00
github manually merged commit 8f387108f0 into gh-pr/839/base 2026-11-26 09:34:29 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 21:17 UTC · original

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 0e0e641a-a986-4e30-b6f1-ed1a21011a72

📥 Commits

Reviewing files that changed from the base of the PR and between 497166009c and 8c4224908b758abd91cf3a3f36fbe1be1b2f5e0a.

📒 Files selected for processing (1)
  • src/loader/redZonePatcher.cpp

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

The patcher now recognizes supported EXTRQ forms and generates replacement sequences to emulate them. On Windows hosts without SSE4a, PatchGuestInstructions collects these sites and applies the generated sequence during relocation. The sequence steps past the guest red zone, saves and restores the registers and flags it uses, and writes the result with legacy SSE2 MOVQ semantics. The patcher logs the number of sites found and the number already patched.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 8c422

No merge-blocking issue is identified; the change is ready for normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 8c422

The new path is limited to supported instructions on Windows hosts without SSE4a when guest patching is enabled. Review found no demonstrated new security vulnerability, but incomplete evidence about interrupted patch installation prevents a minimal-risk assessment.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The newly affected scope is supported EXTRQ in executable guest modules entering the enabled Windows patch pipeline on non-SSE4a hosts. The inspected caller does not establish a new service, tenant, or credential authority; it does place additional guest-derived instructions into executable trampoline code in the emulator process.

Trust Boundaries and Controls

  • observed — The caller checks ELF validity before loading, the patcher restricts function starts to the supplied segment, and EXTRQ recognition restricts operand forms. These controls do not establish that arbitrary guest files are trusted; they delimit the instructions handled by this replacement path.

Resilience and Maintainability Implications

  • inferred — Loading before the program is added to the linker's program list and serializing per-module patch calls limit ordinary publication and patch-call races. The inspected evidence does not prove that every dynamic-load circumstance prevents concurrent guest execution or repairs an interrupted site write.

Hardening Proposals

  • proposed — For the shared executable-patching pipeline, establish or document execution quiescence and an idempotent repair strategy for interrupted installation, including EXTRQ-only spans. This is a hardening proposal, not a verified PR-introduced failure.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 1 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: replacing SSE4a EXTRQ instructions with native trampolines on hosts without SSE4a.
Description check ✅ Passed The description directly explains the EXTRQ compatibility problem, the native trampoline solution, supported forms, scope, and test results.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 21:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/839#issuecomment-5839757055) <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/839"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> Navigate logical layers of code changes, visualize relationships, and explore their blast radius. <!-- review_stack_entry_end --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary>ℹ️ Recent review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `0e0e641a-a986-4e30-b6f1-ed1a21011a72` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 497166009c8c0dd663fa1ffce3805a31bdc40d0e and 8c4224908b758abd91cf3a3f36fbe1be1b2f5e0a. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/loader/redZonePatcher.cpp` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 8 remain after this review. </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough The patcher now recognizes supported EXTRQ forms and generates replacement sequences to emulate them. On Windows hosts without SSE4a, `PatchGuestInstructions` collects these sites and applies the generated sequence during relocation. The sequence steps past the guest red zone, saves and restores the registers and flags it uses, and writes the result with legacy SSE2 MOVQ semantics. The patcher logs the number of sites found and the number already patched. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"8c4224908b758abd91cf3a3f36fbe1be1b2f5e0a" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _⚪ Minimal_ · up to `8c422` <!-- final_review_risk_coverage:{"sourceCommitId":"8c4224908b758abd91cf3a3f36fbe1be1b2f5e0a","coveredCommitId":"8c4224908b758abd91cf3a3f36fbe1be1b2f5e0a","kind":"reviewed"} --> No merge-blocking issue is identified; the change is ready for normal checks. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🔵 Low_ · up to `8c422` The new path is limited to supported instructions on Windows hosts without SSE4a when guest patching is enabled. Review found no demonstrated new security vulnerability, but incomplete evidence about interrupted patch installation prevents a minimal-risk assessment. **Retained concerns** No architecture-level concerns identified. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — The newly affected scope is supported EXTRQ in executable guest modules entering the enabled Windows patch pipeline on non-SSE4a hosts. The inspected caller does not establish a new service, tenant, or credential authority; it does place additional guest-derived instructions into executable trampoline code in the emulator process. **Trust Boundaries and Controls** - _observed_ — The caller checks ELF validity before loading, the patcher restricts function starts to the supplied segment, and EXTRQ recognition restricts operand forms. These controls do not establish that arbitrary guest files are trusted; they delimit the instructions handled by this replacement path. **Resilience and Maintainability Implications** - _inferred_ — Loading before the program is added to the linker's program list and serializing per-module patch calls limit ordinary publication and patch-call races. The inspected evidence does not prove that every dynamic-load circumstance prevents concurrent guest execution or repairs an interrupted site write. **Hardening Proposals** - _proposed_ — For the shared executable-patching pipeline, establish or document execution quiescence and an idempotent repair strategy for interrupted installation, including EXTRQ-only spans. This is a hardening proposal, not a verified PR-introduced failure. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 1 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ✅ Passed | The title clearly and concisely describes the main change: replacing SSE4a EXTRQ instructions with native trampolines on hosts without SSE4a. | | Description check | ✅ Passed | The description directly explains the EXTRQ compatibility problem, the native trampoline solution, supported forms, scope, and test results. | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠wuboo on GitHub · 2026-10-02 19:22 UTC · original

Data point from Apple Silicon: the same problem hits macOS, because Rosetta 2 does not expose SSE4a either, so every EXTRQ traps there too.

Setup: M3 Max, macOS 26, Rosetta 2 + MoltenVK, Astro Bot (PPSA21564) on the macOS bring-up stack (#715 and related). I did not run this PR's code itself; I tested an equivalent patch (EXTRQ register and immediate forms, plus INSERTQ immediate, relocated into SSE2/GPR trampolines) on that stack.

  • In the first level, ~95% of about 41,000 SIGILL/s were EXTRQ (register form), from ~97 sites in eboot that all execute in lockstep.
  • One illegal-instruction round trip costs about 18 µs under Rosetta (micro-benchmark: ud2 → handler → return). The handler itself is ~0.5 µs; the rest is signal delivery.
  • A/B on the same binary, patch on vs off:
    • first level: 4.65 → 5.61 flips/s, stalls over 1 s: 34 (54 s total over ~5 min) → 0. The "random" ~1.7 s hitches every ~10 s of movement were these traps.
    • intro chase sequence: 4.42 → 9.86 flips/s; ship interior: 5.57 → 6.86.
    • Rendering unchanged (screenshots compared at fixed times).

So +1 for this from the macOS side. One caveat: on current main redZonePatcher.cpp only does real work under _WIN32 (xbyak), so on macOS, where Rosetta has no SSE4a, EXTRQ would still go through TryEmulateSse4a. If useful, I can follow up with a non-Windows variant; the trampoline I tested is written as raw bytes and does not need xbyak.

**@⁠wuboo** on GitHub · 2026-10-02 19:22 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/839#issuecomment-5959767849) Data point from Apple Silicon: the same problem hits macOS, because Rosetta 2 does not expose SSE4a either, so every EXTRQ traps there too. Setup: M3 Max, macOS 26, Rosetta 2 + MoltenVK, Astro Bot (PPSA21564) on the macOS bring-up stack (#715 and related). I did not run this PR's code itself; I tested an equivalent patch (EXTRQ register and immediate forms, plus INSERTQ immediate, relocated into SSE2/GPR trampolines) on that stack. - In the first level, ~95% of about 41,000 SIGILL/s were EXTRQ (register form), from ~97 sites in eboot that all execute in lockstep. - One illegal-instruction round trip costs about 18 µs under Rosetta (micro-benchmark: `ud2` → handler → return). The handler itself is ~0.5 µs; the rest is signal delivery. - A/B on the same binary, patch on vs off: - first level: 4.65 → 5.61 flips/s, stalls over 1 s: 34 (54 s total over ~5 min) → 0. The "random" ~1.7 s hitches every ~10 s of movement were these traps. - intro chase sequence: 4.42 → 9.86 flips/s; ship interior: 5.57 → 6.86. - Rendering unchanged (screenshots compared at fixed times). So +1 for this from the macOS side. One caveat: on current main `redZonePatcher.cpp` only does real work under `_WIN32` (xbyak), so on macOS, where Rosetta has no SSE4a, EXTRQ would still go through `TryEmulateSse4a`. If useful, I can follow up with a non-Windows variant; the trampoline I tested is written as raw bytes and does not need xbyak.
Author
Owner

@⁠ew-sudo on GitHub · 2026-10-02 19:32 UTC · original

Yeah, I’m doing this with Xbyak since it already works with shadPS4. I just didn’t want to overcomplicate things.

**@⁠ew-sudo** on GitHub · 2026-10-02 19:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/839#issuecomment-5959942981) Yeah, I’m doing this with Xbyak since it already works with shadPS4. I just didn’t want to overcomplicate things.
Author
Owner

@⁠wuboo on GitHub · 2026-10-02 19:52 UTC · original

Makes sense, keeping xbyak is fine. xbyak is already linked on every platform (xbyak::xbyak is in the main link list), so the only thing keeping the EXTRQ path off on macOS is the _WIN32 guards in redZonePatcher.cpp, including RegisterRedZonePatchModule being a no-op outside Windows. Once this lands, I can send a small follow-up that enables just the SSE4a patching on non-Windows hosts and test it under Rosetta on Astro Bot. If you would rather fold it in here, I'm happy to test a branch.

**@⁠wuboo** on GitHub · 2026-10-02 19:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/839#issuecomment-5960272188) Makes sense, keeping xbyak is fine. xbyak is already linked on every platform (`xbyak::xbyak` is in the main link list), so the only thing keeping the EXTRQ path off on macOS is the `_WIN32` guards in `redZonePatcher.cpp`, including `RegisterRedZonePatchModule` being a no-op outside Windows. Once this lands, I can send a small follow-up that enables just the SSE4a patching on non-Windows hosts and test it under Rosetta on Astro Bot. If you would rather fold it in here, I'm happy to test a branch.
Author
Owner

@⁠ew-sudo on GitHub · 2026-10-02 19:56 UTC · original

Yeah, I think a small follow-up PR would be cleaner. I don't have a Mac, so I wouldn't be able to test the macOS/Rosetta part myself. If you want to handle the non-Windows SSE4a patching in a follow-up, that works fine for me.

**@⁠ew-sudo** on GitHub · 2026-10-02 19:56 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/839#issuecomment-5960362399) Yeah, I think a small follow-up PR would be cleaner. I don't have a Mac, so I wouldn't be able to test the macOS/Rosetta part myself. If you want to handle the non-Windows SSE4a patching in a follow-up, that works fine for me.
Author
Owner

@⁠Nmzik on GitHub · 2026-10-03 15:37 UTC · original

@⁠ew-sudo Fixed. EXTRQ native trampoline works with --amd-cpu

**@⁠Nmzik** on GitHub · 2026-10-03 15:37 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/839#issuecomment-5970652375) @⁠ew-sudo Fixed. EXTRQ native trampoline works with --amd-cpu
This discussion has been locked. Commenting is limited to contributors.
No description provided.