loader: split 256-bit guest stores on macOS so Rosetta does not abort #984

Open
github-bot wants to merge 7 commits from github-bot/gh-984 into main AGit
Owner

@⁠wuboo on GitHub · 2026-10-02 20:42 UTC · original
wuboo:pr/macos-wide-store-split → main · +1010 −4 · 8 files · 7 commits · open

Problem

Under Rosetta, a 256-bit vector store that takes a synchronous fault is not emulated forward. The process is aborted (signal 6) instead of the fault being delivered the way a 128-bit store is.

Astro Bot (PPSA21564) on an M3 Max under Rosetta, without this change, dies during boot with exit status −6. The emulator log ends with:

rosetta error: unexpectedly need to EmulateForward on a synchronous exception x86_rip=0x90737d123 arm_pc=0xfc0504ec60 num_insts=3 inst_index=2 x86 instruction bytes: 0x902484117cc1c4 0x808310fcc50000

The first instruction word is little-endian c4 c1 7c 11 ...: a 3-byte VEX prefix and opcode 11, which is a 256-bit vmovups store.

The same abort is reproduced by macos_wide_store_tests on an unpatched store that crosses into a protected page. The child prints the Rosetta error and is killed by signal 6. That case is expected; the patched cases in the same test pass.

Change

On macOS, while a guest module is loaded, each plain 256-bit vector store is rewritten to a jump into an 8 MiB trampoline placed after the module. The trampoline performs the store as two 128-bit halves and jumps back. RIP-relative addresses are re-encoded for the trampoline.

How the jump is planted, depending on the instruction length and the bytes around it:

  • long enough for a rel32 jump: the store itself becomes the jump
  • short, with int3 or post-jump nop padding in rel8 range: a rel8 jump through that cave to a rel32 jump
  • short, at a site from the hot profile (below), when the following instructions can be moved (register ops, a relative back-edge, not fs/gs, not a direct branch target): those instructions move into the trampoline and the store becomes a rel32 jump. KYTY_WIDE_STORE_MOVE=all also does this at unprofiled sites.
  • otherwise: the store becomes ud2, and the SIGILL handler jumps to the trampoline. A site that hits 1024 times is appended once to KYTY_WIDE_STORE_HOT. The next launch plants a static jump for sites on that list. Duplicates already in the file are not appended again.

By default, splitting is on when the process runs under Rosetta (sysctl.proc_translated) and off on native Intel Macs. KYTY_SPLIT_WIDE_STORES=0 or =1 overrides that. Linux and Windows are unchanged.

SSE4a EXTRQ/INSERTQ is not in this change. That patch is #839.

Testing

macos_wide_store_tests on this branch, Release, macOS x86_64 under Rosetta: exit 0, all checks passed. The unpatched crossing store dies with signal 6, as the test requires. The patched copies (direct jump, cave, ud2, moved instructions, RIP-relative) write every byte and nothing past the target.

Release kyty_emulator builds from this branch. I checked sysctl.proc_translated with a small x86_64 and arm64 test binary on the same machine: it reports 1 under Rosetta and 0 natively.

On my macOS integration tree (the bring-up stack from #715 and related), the same loader logic logged this for Astro Bot's eboot.bin in a level run:

candidates=145672, patched=145672 (via padding=1903, ud2=1008, moved=2898), short=0, unsupported=0, trampoline bytes=3024440

libc.prx: 798 patched (padding 102, ud2 1, moved 15). libSceNpCppWebApi.prx: 1252 patched (padding 5, ud2 0, moved 1). Nothing was left short or unsupported.

Limits

  • I could not run a game on this branch alone: current main does not include the macOS bring-up stack (#715 and related), so the guest does not get far enough there. The game results above come from the integration tree, which runs the same loader code.
  • The trampoline is 8 MiB per module when splitting is on. KYTY_SPLIT_WIDE_STORES=0 skips the allocation.
  • ud2 sites still take a SIGILL until they are on the hot list. After a profiled restart they become direct jumps.
  • Stores with a segment override other than DS/SS are left alone and counted as unsupported. Astro Bot's eboot had none of those.
**@⁠wuboo** on GitHub · 2026-10-02 20:42 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984) `wuboo:pr/macos-wide-store-split` → `main` · +1010 −4 · 8 files · 7 commits · open ### Problem Under Rosetta, a 256-bit vector store that takes a synchronous fault is not emulated forward. The process is aborted (signal 6) instead of the fault being delivered the way a 128-bit store is. Astro Bot (PPSA21564) on an M3 Max under Rosetta, without this change, dies during boot with exit status −6. The emulator log ends with: ``` rosetta error: unexpectedly need to EmulateForward on a synchronous exception x86_rip=0x90737d123 arm_pc=0xfc0504ec60 num_insts=3 inst_index=2 x86 instruction bytes: 0x902484117cc1c4 0x808310fcc50000 ``` The first instruction word is little-endian `c4 c1 7c 11 ...`: a 3-byte VEX prefix and opcode `11`, which is a 256-bit `vmovups` store. The same abort is reproduced by `macos_wide_store_tests` on an unpatched store that crosses into a protected page. The child prints the Rosetta error and is killed by signal 6. That case is expected; the patched cases in the same test pass. ### Change On macOS, while a guest module is loaded, each plain 256-bit vector store is rewritten to a jump into an 8 MiB trampoline placed after the module. The trampoline performs the store as two 128-bit halves and jumps back. RIP-relative addresses are re-encoded for the trampoline. How the jump is planted, depending on the instruction length and the bytes around it: - long enough for a rel32 jump: the store itself becomes the jump - short, with `int3` or post-jump `nop` padding in rel8 range: a rel8 jump through that cave to a rel32 jump - short, at a site from the hot profile (below), when the following instructions can be moved (register ops, a relative back-edge, not `fs`/`gs`, not a direct branch target): those instructions move into the trampoline and the store becomes a rel32 jump. `KYTY_WIDE_STORE_MOVE=all` also does this at unprofiled sites. - otherwise: the store becomes `ud2`, and the SIGILL handler jumps to the trampoline. A site that hits 1024 times is appended once to `KYTY_WIDE_STORE_HOT`. The next launch plants a static jump for sites on that list. Duplicates already in the file are not appended again. By default, splitting is on when the process runs under Rosetta (`sysctl.proc_translated`) and off on native Intel Macs. `KYTY_SPLIT_WIDE_STORES=0` or `=1` overrides that. Linux and Windows are unchanged. SSE4a `EXTRQ`/`INSERTQ` is not in this change. That patch is #839. ### Testing `macos_wide_store_tests` on this branch, Release, macOS x86_64 under Rosetta: exit 0, `all checks passed`. The unpatched crossing store dies with signal 6, as the test requires. The patched copies (direct jump, cave, ud2, moved instructions, RIP-relative) write every byte and nothing past the target. Release `kyty_emulator` builds from this branch. I checked `sysctl.proc_translated` with a small x86_64 and arm64 test binary on the same machine: it reports 1 under Rosetta and 0 natively. On my macOS integration tree (the bring-up stack from #715 and related), the same loader logic logged this for Astro Bot's `eboot.bin` in a level run: ``` candidates=145672, patched=145672 (via padding=1903, ud2=1008, moved=2898), short=0, unsupported=0, trampoline bytes=3024440 ``` `libc.prx`: 798 patched (padding 102, ud2 1, moved 15). `libSceNpCppWebApi.prx`: 1252 patched (padding 5, ud2 0, moved 1). Nothing was left short or unsupported. ### Limits - I could not run a game on this branch alone: current main does not include the macOS bring-up stack (#715 and related), so the guest does not get far enough there. The game results above come from the integration tree, which runs the same loader code. - The trampoline is 8 MiB per module when splitting is on. `KYTY_SPLIT_WIDE_STORES=0` skips the allocation. - `ud2` sites still take a SIGILL until they are on the hot list. After a profiled restart they become direct jumps. - Stores with a segment override other than DS/SS are left alone and counted as unsupported. Astro Bot's eboot had none of those.
Under Rosetta, a 256-bit vector store that faults on a protected page is not
emulated forward; Rosetta aborts the process ('unexpectedly need to
EmulateForward on a synchronous exception'). Guest memory watched by the GPU
caches is write-protected, so this happens in normal play.

While a module loads, each plain 256-bit store is rewritten to reach an 8 MiB
trampoline after the module, where it runs as two 128-bit halves. The jump is
planted directly when the store is long enough, through int3/nop padding in
rel8 range, by moving the following register-only instructions into the
trampoline, or as ud2 handled in the SIGILL handler. ud2 sites that fire often
are appended once to the KYTY_WIDE_STORE_HOT list and get a static jump on the
next start.

Splitting is on by default when the process runs under Rosetta and off on
native Intel Macs; KYTY_SPLIT_WIDE_STORES=0 or =1 overrides it.
The linear sweep only sees direct branch targets. A jump table, computed jump
or landing pad that lands on a moved instruction would run into the rel32 or
the int3 fill, so unprofiled sites now stay on the ud2 path and only sites from
the KYTY_WIDE_STORE_HOT profile get their following instructions moved.
KYTY_WIDE_STORE_MOVE=all restores moving everywhere.

Also run the nop-padding and long-store dead-byte tests, which were defined
but never called.
The test only printed the child's status, so a clean exit also passed. Under
Rosetta (sysctl.proc_translated) it now has to die from a signal; native
x86-64 still exits normally.
Both users of Program::instruction_trampoline_vaddr wrote from the start of the area, so with
the AMD CPU patcher active next to the 256-bit store split the split trampolines overwrote the
patcher's. Ask the patcher how much of the area it used and continue after it.
A 32-byte aligned store cannot cross a page, so only the unaligned forms
(vmovups/vmovupd/vmovdqu) can hit the Rosetta abort. The aligned forms
(vmovaps/vmovapd/vmovdqa) are left alone: they no longer use trampoline
space or a ud2 trap, and keep raising #GP on a misaligned address.
The split used to flush the whole 8 MB trampoline area after every
executable segment. Flush once after the segment loop, only
[cursor_begin, cursor).
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:39:17 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 20:47 UTC · original · edited 2026-10-03 19:05 UTC

Review in Change Stack →

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

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

On macOS, KYTY_SPLIT_WIDE_STORES enables wide-store splitting when set to a value other than "0". When unset, the loader enables splitting if sysctl.proc_translated reports Rosetta translation. The loader reserves trampoline space and rewrites eligible 256-bit stores in executable segments. Trap handling redirects execution to registered trampolines. New tests exercise rewriting and trap paths, and CMake registers the test executable.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Bug fix

Merge Risk: 🔵 Low · up to 8863b

Under Rosetta, the loader also rewrites aligned wide stores, which can never cross a page. These rewrites use trampoline space, and some become slow trap sites in hot loops until the store profile is rebuilt and the game restarted. Correctness is not affected. The change can merge with this follow-up, though excluding the aligned forms is a small fix.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 8863b

The compatibility change alters executable code and fault recovery. Recovery targets can survive module unloading, and an optional optimization can move instructions without accounting for indirect entry points. These risks affect the running application; broader privilege escalation has not been established.

Retained concerns

  • Medium · security · inferred: The new process-global trap registry outlives the module mappings it references. Module deletion frees code and trampolines without retiring their registrations, and lookup validates only the instruction address. If that address is reused without re-registration, an unrelated illegal instruction can be redirected to a stale recovery target, compromising control-flow identity and process-level failure containment.
  • Medium · reliability · inferred: Hot-profile membership or KYTY_WIDE_STORE_MOVE=all authorizes moving following instructions, but the safety analysis explicitly excludes computed jumps, jump tables and landing pads. A frequently executed store is not evidence that its following instructions have no independent entry points. Such entries can reach overwritten bytes rather than the relocated instructions, introducing process-wide execution failures during an optional optimization or a subsequent profiled run.
Security review details

Security Blast Radius

  • inferred — The demonstrated exposure is within the emulator process: enabled guest modules receive executable trampolines, and all registered sites share one 32,768-entry table consulted by exception recovery. Stale metadata or incorrect relocation can affect process execution rather than only the module that created it. Cross-process, service, tenant or privilege escalation has not been established.

Security Findings and Attack Paths

  • inferred — A conditional misdirection path is: guest code produces a trapped store, its module unloads, the address is later reused without updating that registration, and an illegal instruction at the reused address triggers stale redirection. Same-site re-registration updates the target and limits this path; actual address reuse and exploitation were not demonstrated.

Trust Boundaries and Controls

  • observed — Guest executable bytes feed instruction decoding and generated host execution. Eligibility is limited to selected two-operand VEX 256-bit stores; unsupported segment bases are rejected, output is bounded to the supplied trampoline allocation, and illegal-instruction redirection requires a table match. These controls do not establish that the matching registration still belongs to the current mapping.

Resilience and Maintainability Implications

  • observed — The existing module deletion path explicitly unregisters guest-instruction patch metadata before freeing memory, but the new wide-store metadata has no equivalent lifecycle operation. Its fixed-capacity registrations accumulate across module lifetimes, so repeated loading and unloading also consumes recovery capacity without reclamation.

Hardening Proposals

  • proposed — Associate recovery registrations with a module generation and retire them safely before releasing the mapping, accounting for in-flight exception readers. Require established entry-point safety for instruction relocation rather than treating hot-profile membership as that proof; retain the trap path when safety is unknown.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.26% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 43 functions across 7 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 identifies the main change: splitting 256-bit guest stores on macOS to prevent Rosetta aborts.
Description check ✅ Passed The description explains the Rosetta failure, the wide-store trampoline change, its behavior and limits, and reported 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.
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 20:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#issuecomment-5961224634) · edited 2026-10-03 19:05 UTC <!-- 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/984?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><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 --> <!-- This is an auto-generated comment: review paused by coderabbit.ai --> > [!NOTE] > ## Reviews paused > > It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the `reviews.auto_review.auto_pause_after_reviewed_commits` setting. > > Use the following commands to manage reviews: > - `@coderabbitai resume` to resume automatic reviews. > - `@coderabbitai review` to trigger a single review. > > Use the checkboxes below for quick actions: > - [ ] <!-- {"checkboxId":"7f6cc2e2-2e4e-497a-8c31-c9e4573e93d1"} --> ▶️ Resume reviews > - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review <!-- end of auto-generated comment: review paused by coderabbit.ai --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough On macOS, `KYTY_SPLIT_WIDE_STORES` enables wide-store splitting when set to a value other than `"0"`. When unset, the loader enables splitting if `sysctl.proc_translated` reports Rosetta translation. The loader reserves trampoline space and rewrites eligible 256-bit stores in executable segments. Trap handling redirects execution to registered trampolines. New tests exercise rewriting and trap paths, and CMake registers the test executable. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"8863b3d7deb94a49f9956076f22ea3e905d1383e" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _🔵 Low_ · up to `8863b` <!-- final_review_risk_coverage:{"sourceCommitId":"8863b3d7deb94a49f9956076f22ea3e905d1383e","coveredCommitId":"8863b3d7deb94a49f9956076f22ea3e905d1383e","kind":"reviewed"} --> Under Rosetta, the loader also rewrites aligned wide stores, which can never cross a page. These rewrites use trampoline space, and some become slow trap sites in hot loops until the store profile is rebuilt and the game restarted. Correctness is not affected. The change can merge with this follow-up, though excluding the aligned forms is a small fix. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🟡 Moderate_ · up to `8863b` The compatibility change alters executable code and fault recovery. Recovery targets can survive module unloading, and an optional optimization can move instructions without accounting for indirect entry points. These risks affect the running application; broader privilege escalation has not been established. **Retained concerns** - **Medium · security · inferred:** The new process-global trap registry outlives the module mappings it references. Module deletion frees code and trampolines without retiring their registrations, and lookup validates only the instruction address. If that address is reused without re-registration, an unrelated illegal instruction can be redirected to a stale recovery target, compromising control-flow identity and process-level failure containment. - **Medium · reliability · inferred:** Hot-profile membership or KYTY_WIDE_STORE_MOVE=all authorizes moving following instructions, but the safety analysis explicitly excludes computed jumps, jump tables and landing pads. A frequently executed store is not evidence that its following instructions have no independent entry points. Such entries can reach overwritten bytes rather than the relocated instructions, introducing process-wide execution failures during an optional optimization or a subsequent profiled run. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — The demonstrated exposure is within the emulator process: enabled guest modules receive executable trampolines, and all registered sites share one 32,768-entry table consulted by exception recovery. Stale metadata or incorrect relocation can affect process execution rather than only the module that created it. Cross-process, service, tenant or privilege escalation has not been established. **Security Findings and Attack Paths** - _inferred_ — A conditional misdirection path is: guest code produces a trapped store, its module unloads, the address is later reused without updating that registration, and an illegal instruction at the reused address triggers stale redirection. Same-site re-registration updates the target and limits this path; actual address reuse and exploitation were not demonstrated. **Trust Boundaries and Controls** - _observed_ — Guest executable bytes feed instruction decoding and generated host execution. Eligibility is limited to selected two-operand VEX 256-bit stores; unsupported segment bases are rejected, output is bounded to the supplied trampoline allocation, and illegal-instruction redirection requires a table match. These controls do not establish that the matching registration still belongs to the current mapping. **Resilience and Maintainability Implications** - _observed_ — The existing module deletion path explicitly unregisters guest-instruction patch metadata before freeing memory, but the new wide-store metadata has no equivalent lifecycle operation. Its fixed-capacity registrations accumulate across module lifetimes, so repeated loading and unloading also consumes recovery capacity without reclamation. **Hardening Proposals** - _proposed_ — Associate recovery registrations with a module generation and retire them safely before releasing the mapping, accounting for in-flight exception readers. Require established entry-point safety for instruction relocation rather than treating hot-profile membership as that proof; retain the trap path when safety is unknown. </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 23.26% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 43 functions across 7 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 identifies the main change: splitting 256-bit guest stores on macOS to prevent Rosetta aborts. | | Description check | ✅ Passed | The description explains the Rosetta failure, the wide-store trampoline change, its behavior and limits, and reported 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 --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autopilot</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts > Autopilot is currently an internal CodeRabbit preview. <!-- autopilot:end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=984)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
@ -795,0 +1171,4 @@
return value != nullptr && std::strcmp(value, "all") == 0;
}();
if (trap && (move_all || std::binary_search(hot_sites.begin(), hot_sites.end(),
reinterpret_cast<uint64_t>(code)))) {
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 20:47 UTC · original · edited 2026-10-02 21:12 UTC

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Unprofiled trap sites are relocated by default, but only direct branch targets are checked.

move_all is true unless KYTY_WIDE_STORE_MOVE=hot. As a result, every trapped short store that has movable instructions after it is rewritten into a jmp rel32. The bytes of the moved instructions after the first five are filled with 0xCC. That happens even when the site is not in KYTY_WIDE_STORE_HOT.

The only protection is branch_targets. That list holds only the targets of direct relative branches found by the linear sweep. It does not cover:

  • jump-table or computed jmp reg/jmp [mem] targets, such as switch cases that fall through after a store;
  • exception landing pads;
  • branches from other modules or segments.

If one of those targets lands on a moved instruction, execution enters the rel32 operand bytes or the 0xCC fill. The result is a crash or wrong code. The PR description says moved-instruction jumps apply to profiled hot sites on the next launch. Unprofiled sites should stay on the ud2 path by default.

Proposed fix: limit moving to profiled sites unless explicitly enabled
-			// KYTY_WIDE_STORE_MOVE=hot limits moving to sites in the hot profile.
+			// KYTY_WIDE_STORE_MOVE=all also moves instructions at unprofiled sites.
 			static const bool move_all = [] {
 				const char* value = std::getenv("KYTY_WIDE_STORE_MOVE");
-				return value == nullptr || std::strcmp(value, "hot") != 0;
+				return value != nullptr && std::strcmp(value, "all") == 0;
 			}();

✅ Addressed in commit e8f5158

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 20:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#discussion_r4169703115) · edited 2026-10-02 21:12 UTC _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Unprofiled trap sites are relocated by default, but only direct branch targets are checked.** `move_all` is `true` unless `KYTY_WIDE_STORE_MOVE=hot`. As a result, every trapped short store that has movable instructions after it is rewritten into a `jmp rel32`. The bytes of the moved instructions after the first five are filled with `0xCC`. That happens even when the site is not in `KYTY_WIDE_STORE_HOT`. The only protection is `branch_targets`. That list holds only the targets of direct relative branches found by the linear sweep. It does not cover: - jump-table or computed `jmp reg`/`jmp [mem]` targets, such as switch cases that fall through after a store; - exception landing pads; - branches from other modules or segments. If one of those targets lands on a moved instruction, execution enters the rel32 operand bytes or the `0xCC` fill. The result is a crash or wrong code. The PR description says moved-instruction jumps apply to profiled hot sites on the next launch. Unprofiled sites should stay on the `ud2` path by default. <details> <summary>Proposed fix: limit moving to profiled sites unless explicitly enabled</summary> ```diff - // KYTY_WIDE_STORE_MOVE=hot limits moving to sites in the hot profile. + // KYTY_WIDE_STORE_MOVE=all also moves instructions at unprofiled sites. static const bool move_all = [] { const char* value = std::getenv("KYTY_WIDE_STORE_MOVE"); - return value == nullptr || std::strcmp(value, "hot") != 0; + return value != nullptr && std::strcmp(value, "all") == 0; }(); ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:4aaa17bfe07de9be8b9f02bd --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit e8f5158
@ -0,0 +195,4 @@
const auto live_result = Loader::X64InstructionEmulator::SplitWideStores(
reinterpret_cast<uint64_t>(area.code), live.size(), &cursor, area.end);
Check(live_result.via_cave == 0 && live_result.trapped == 1,
"reachable nop not used as a cave");
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 20:47 UTC · original · edited 2026-10-02 21:12 UTC

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

The "reachable nop" expectation is wrong under the default move mode.

In the live sequence, the 4-byte store is followed by a 5-byte nop at offset 4. That nop is not a branch target, and it is not a ret, call, system, or interrupt instruction. Because move_all is the default, the splitter moves the nop. Then length + moved_original = 9 >= 5, so trap becomes false and the site is counted as relocated, not trapped. live_result.trapped == 1 therefore fails.

Choose the fix based on the intended default:

  • If move_all stays the default, assert relocated == 1.
  • If moving is limited to profiled sites (see the comment on src/loader/x64InstructionEmulator.cpp Line 1131-1136), keep trapped == 1.

✅ Addressed in commit e8f5158

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 20:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#discussion_r4169703128) · edited 2026-10-02 21:12 UTC _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **The "reachable nop" expectation is wrong under the default move mode.** In the `live` sequence, the 4-byte store is followed by a 5-byte nop at offset 4. That nop is not a branch target, and it is not a ret, call, system, or interrupt instruction. Because `move_all` is the default, the splitter moves the nop. Then `length + moved_original = 9 >= 5`, so `trap` becomes `false` and the site is counted as `relocated`, not `trapped`. `live_result.trapped == 1` therefore fails. Choose the fix based on the intended default: - If `move_all` stays the default, assert `relocated == 1`. - If moving is limited to profiled sites (see the comment on `src/loader/x64InstructionEmulator.cpp` Line 1131-1136), keep `trapped == 1`. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:aea1b26cf1fbb240f694d711 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit e8f5158
@ -0,0 +301,4 @@
TestShortStoreViaInt3Padding();
TestShortStoreViaNopPadding();
TestShortStoreViaLongStoreDeadBytes();
TestRipRelativeStore();
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 20:47 UTC · original · edited 2026-10-02 21:13 UTC

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

main never calls TestShortStoreViaNopPadding or TestShortStoreViaLongStoreDeadBytes.

Both functions are defined but not called. The nop-padding cave path and the path that chains through a long store's dead bytes are therefore not tested. The PR objectives say the cave checks passed. Both functions sit in an anonymous namespace, so -Wunused-function warns about them. Add the calls. Fix the TestShortStoreViaNopPadding expectation at Line 182 first, or that test fails.

Proposed fix
         TestShortStoreWithoutPaddingTraps();
         TestShortStoreViaInt3Padding();
+        TestShortStoreViaNopPadding();
+        TestShortStoreViaLongStoreDeadBytes();
         TestRipRelativeStore();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        // Reads KYTY_WIDE_STORE_HOT, which the splitter loads once per process:
        // run it first.
        TestHotRelocationSkipsBranchTargets();
        TestUnpatchedAbortsUnderRosetta();
	TestPatchedCrossingStore();
        TestShortStoreWithoutPaddingTraps();
        TestShortStoreViaInt3Padding();
        TestShortStoreViaNopPadding();
        TestShortStoreViaLongStoreDeadBytes();
        TestRipRelativeStore();

✅ Addressed in commit e8f5158

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 20:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#discussion_r4169703133) · edited 2026-10-02 21:13 UTC _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **`main` never calls `TestShortStoreViaNopPadding` or `TestShortStoreViaLongStoreDeadBytes`.** Both functions are defined but not called. The nop-padding cave path and the path that chains through a long store's dead bytes are therefore not tested. The PR objectives say the cave checks passed. Both functions sit in an anonymous namespace, so `-Wunused-function` warns about them. Add the calls. Fix the `TestShortStoreViaNopPadding` expectation at Line 182 first, or that test fails. <details> <summary>Proposed fix</summary> ```diff TestShortStoreWithoutPaddingTraps(); TestShortStoreViaInt3Padding(); + TestShortStoreViaNopPadding(); + TestShortStoreViaLongStoreDeadBytes(); TestRipRelativeStore(); ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion // Reads KYTY_WIDE_STORE_HOT, which the splitter loads once per process: // run it first. TestHotRelocationSkipsBranchTargets(); TestUnpatchedAbortsUnderRosetta(); TestPatchedCrossingStore(); TestShortStoreWithoutPaddingTraps(); TestShortStoreViaInt3Padding(); TestShortStoreViaNopPadding(); TestShortStoreViaLongStoreDeadBytes(); TestRipRelativeStore(); ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:8627c98d0c25bb4009b38faa --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit e8f5158
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 20:47 UTC · original · reviewed

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: 9fb1f61e-7ae1-4c74-829a-34ead4531903

📥 Commits

Reviewing files that changed from the base of the PR and between e317465d8a and 9e9c2de52faf6d422ea67d5690cfc163a4a088b9.

📒 Files selected for processing (6)
  • CMakeLists.txt
  • src/loader/runtimeLinker.cpp
  • src/loader/runtimeLinker.h
  • src/loader/x64InstructionEmulator.cpp
  • src/loader/x64InstructionEmulator.h
  • tests/macosWideStoreTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 20:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#pullrequestreview-5396689284) · **reviewed** **Actionable comments posted: 3** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `9fb1f61e-7ae1-4c74-829a-34ead4531903` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between e317465d8a773b33482ad367ad2f856154c8bc6d and 9e9c2de52faf6d422ea67d5690cfc163a4a088b9. </details> <details> <summary>📒 Files selected for processing (6)</summary> * `CMakeLists.txt` * `src/loader/runtimeLinker.cpp` * `src/loader/runtimeLinker.h` * `src/loader/x64InstructionEmulator.cpp` * `src/loader/x64InstructionEmulator.h` * `tests/macosWideStoreTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
@ -795,0 +1171,4 @@
return value != nullptr && std::strcmp(value, "all") == 0;
}();
if (trap && (move_all || std::binary_search(hot_sites.begin(), hot_sites.end(),
reinterpret_cast<uint64_t>(code)))) {
Author
Owner

@⁠wuboo on GitHub · 2026-10-02 20:54 UTC · original

Agreed. Fixed in e8f5158b: moving the following instructions is now limited to sites from the hot profile, and KYTY_WIDE_STORE_MOVE=all opts into moving everywhere. Unprofiled short stores stay on the ud2 path.

**@⁠wuboo** on GitHub · 2026-10-02 20:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#discussion_r4169751419) Agreed. Fixed in e8f5158b: moving the following instructions is now limited to sites from the hot profile, and `KYTY_WIDE_STORE_MOVE=all` opts into moving everywhere. Unprofiled short stores stay on the ud2 path.
@ -0,0 +195,4 @@
const auto live_result = Loader::X64InstructionEmulator::SplitWideStores(
reinterpret_cast<uint64_t>(area.code), live.size(), &cursor, area.end);
Check(live_result.via_cave == 0 && live_result.trapped == 1,
"reachable nop not used as a cave");
Author
Owner

@⁠wuboo on GitHub · 2026-10-02 20:54 UTC · original

Fixed by the same change (e8f5158b). With moving limited to profiled sites, the live-nop case traps as the test expects, and the test now runs.

**@⁠wuboo** on GitHub · 2026-10-02 20:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#discussion_r4169751669) Fixed by the same change (e8f5158b). With moving limited to profiled sites, the live-nop case traps as the test expects, and the test now runs.
@ -0,0 +301,4 @@
TestShortStoreViaInt3Padding();
TestShortStoreViaNopPadding();
TestShortStoreViaLongStoreDeadBytes();
TestRipRelativeStore();
Author
Owner

@⁠wuboo on GitHub · 2026-10-02 20:54 UTC · original

Fixed in e8f5158b: both tests are called now and pass (macos_wide_store_tests: all checks passed).

**@⁠wuboo** on GitHub · 2026-10-02 20:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#discussion_r4169751879) Fixed in e8f5158b: both tests are called now and pass (`macos_wide_store_tests: all checks passed`).
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 20:58 UTC · original · reviewed

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟡 Minor · Assert the child signal when running under Rosetta. · macosWideStoreTests.cpp:87-104

tests/macosWideStoreTests.cpp:87-104
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the child signal when running under Rosetta.

TestUnpatchedAbortsUnderRosetta only prints the waitpid result. A normal child exit therefore passes the test. Gate the assertion with the same sysctl.proc_translated check used by SplitWideStoresEnabled, because native x86-64 is expected to exit normally.

Suggested fix
 #include <sys/mman.h>
+#include <sys/sysctl.h>
 #include <sys/wait.h>
@@
 bool RunCrossingCopy(CopyFunc copy) {
@@
 }
 
+bool IsRunningUnderRosetta() {
+	int translated = 0;
+	size_t size = sizeof(translated);
+	return sysctlbyname("sysctl.proc_translated", &translated, &size, nullptr, 0) == 0 &&
+	       translated == 1;
+}
+
 void TestUnpatchedAbortsUnderRosetta() {
@@
 	int status = 0;
 	waitpid(child, &status, 0);
+	Check(!IsRunningUnderRosetta() || WIFSIGNALED(status),
+	      "unpatched crossing store aborted under Rosetta");
 	// Documents the Rosetta behaviour this patch works around; native x86-64 runs exit cleanly.
🧹 Nitpick comments (2)
tests/macosWideStoreTests.cpp (2)

117-131: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Exercise the ud2 trap through TryEmulate.

TestShortStoreWithoutPaddingTraps calls SplitWideStores directly. It checks the rewrite bytes and the rewrite counter, but it does not execute the rewritten code or enter the registered SIGILL handler. These assertions can pass even when trap lookup, vector storage, or saved-RIP redirection is broken.

Add a focused test that registers the trap through the normal runtime path, executes the fixture with known ymm0 contents, and asserts the 32-byte destination. Assert that execution resumes at area.code + 4, the instruction after the original four-byte store, by checking the continuation or the saved instruction pointer.


212-233: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add a positive hot-relocation fixture.

TestHotRelocationSkipsBranchTargets only exercises the exclusion case. It expects relocated == 0, so it also passes if safe hot relocation stops working. The executable tests do not assert the default non-relocation of an unprofiled store.

Add a movable hot fixture to the same test setup. Include both addresses in KYTY_WIDE_STORE_HOT, because WideStoreHotSites() caches the profile on its first call.

Suggested fix
 void TestHotRelocationSkipsBranchTargets() {
+  auto movable = MakeCode();
+  const std::array<uint8_t, 9> movable_code = {
+      0xc5, 0xfc, 0x11, 0x07, // vmovups [rdi], ymm0
+      0x48, 0x83, 0xc3, 0x20, // add rbx, 0x20
+      0xc3};
+  std::memcpy(movable.code, movable_code.data(), movable_code.size());
+
   // Direct branch targets must be found: a loop whose head is the instruction
   // after the store. store; L: add rbx, 0x20; dec ecx; jne L; ret
   auto area = MakeCode();
@@
   const int fd = mkstemp(path);
   dprintf(
       fd, "0x%llx\n",
+      static_cast<unsigned long long>(reinterpret_cast<uint64_t>(movable.code)));
+  dprintf(
+      fd, "0x%llx\n",
       static_cast<unsigned long long>(reinterpret_cast<uint64_t>(area.code)));
   close(fd);
   setenv("KYTY_WIDE_STORE_HOT", path, 1);
+
+  auto movable_cursor = movable.trampolines;
+  const auto movable_result = Loader::X64InstructionEmulator::SplitWideStores(
+      reinterpret_cast<uint64_t>(movable.code), movable_code.size(),
+      &movable_cursor, movable.end);
+  Check(movable_result.relocated == 1 && movable_result.trapped == 0,
+        "safe hot store was not relocated");
+
   auto cursor = area.trampolines;

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: 8b12013c-f15e-4413-bb9e-a77173c2a08f

📥 Commits

Reviewing files that changed from the base of the PR and between 9e9c2de52faf6d422ea67d5690cfc163a4a088b9 and e8f5158bb6e581e13acb4a3118cbc41f876bae22.

📒 Files selected for processing (2)
  • src/loader/x64InstructionEmulator.cpp
  • tests/macosWideStoreTests.cpp
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/macosWideStoreTests.cpp
  • src/loader/x64InstructionEmulator.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 20:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#pullrequestreview-5396785269) · **reviewed** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (1)** > > <details> > <summary><em>🟡 Minor</em> · Assert the child signal when running under Rosetta. · <code>macosWideStoreTests.cpp:87-104</code></summary><blockquote> > > `tests/macosWideStoreTests.cpp:87-104` > _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ > > **Assert the child signal when running under Rosetta.** > > `TestUnpatchedAbortsUnderRosetta` only prints the `waitpid` result. A normal child exit therefore passes the test. Gate the assertion with the same `sysctl.proc_translated` check used by `SplitWideStoresEnabled`, because native x86-64 is expected to exit normally. > > <details><summary>Suggested fix</summary> > > ```diff > #include <sys/mman.h> > +#include <sys/sysctl.h> > #include <sys/wait.h> > @@ > bool RunCrossingCopy(CopyFunc copy) { > @@ > } > > +bool IsRunningUnderRosetta() { > + int translated = 0; > + size_t size = sizeof(translated); > + return sysctlbyname("sysctl.proc_translated", &translated, &size, nullptr, 0) == 0 && > + translated == 1; > +} > + > void TestUnpatchedAbortsUnderRosetta() { > @@ > int status = 0; > waitpid(child, &status, 0); > + Check(!IsRunningUnderRosetta() || WIFSIGNALED(status), > + "unpatched crossing store aborted under Rosetta"); > // Documents the Rosetta behaviour this patch works around; native x86-64 runs exit cleanly. > ``` > > </details> > > <!-- cr-comment:v1:b6801bdbb37b692efc5df5a0 --> > > </blockquote></details> <details> <summary>🧹 Nitpick comments (2)</summary><blockquote> <details> <summary>tests/macosWideStoreTests.cpp (2)</summary><blockquote> `117-131`: _🎯 Functional Correctness_ | _🔵 Trivial_ | _⚡ Quick win_ **Exercise the `ud2` trap through `TryEmulate`.** `TestShortStoreWithoutPaddingTraps` calls `SplitWideStores` directly. It checks the rewrite bytes and the rewrite counter, but it does not execute the rewritten code or enter the registered SIGILL handler. These assertions can pass even when trap lookup, vector storage, or saved-RIP redirection is broken. Add a focused test that registers the trap through the normal runtime path, executes the fixture with known `ymm0` contents, and asserts the 32-byte destination. Assert that execution resumes at `area.code + 4`, the instruction after the original four-byte store, by checking the continuation or the saved instruction pointer. <!-- cr-comment:v1:5a72b988ddf7960477dc0314 --> --- `212-233`: _🎯 Functional Correctness_ | _🔵 Trivial_ | _⚡ Quick win_ **Add a positive hot-relocation fixture.** `TestHotRelocationSkipsBranchTargets` only exercises the exclusion case. It expects `relocated == 0`, so it also passes if safe hot relocation stops working. The executable tests do not assert the default non-relocation of an unprofiled store. Add a movable hot fixture to the same test setup. Include both addresses in `KYTY_WIDE_STORE_HOT`, because `WideStoreHotSites()` caches the profile on its first call. <details><summary>Suggested fix</summary> ```diff void TestHotRelocationSkipsBranchTargets() { + auto movable = MakeCode(); + const std::array<uint8_t, 9> movable_code = { + 0xc5, 0xfc, 0x11, 0x07, // vmovups [rdi], ymm0 + 0x48, 0x83, 0xc3, 0x20, // add rbx, 0x20 + 0xc3}; + std::memcpy(movable.code, movable_code.data(), movable_code.size()); + // Direct branch targets must be found: a loop whose head is the instruction // after the store. store; L: add rbx, 0x20; dec ecx; jne L; ret auto area = MakeCode(); @@ const int fd = mkstemp(path); dprintf( fd, "0x%llx\n", + static_cast<unsigned long long>(reinterpret_cast<uint64_t>(movable.code))); + dprintf( + fd, "0x%llx\n", static_cast<unsigned long long>(reinterpret_cast<uint64_t>(area.code))); close(fd); setenv("KYTY_WIDE_STORE_HOT", path, 1); + + auto movable_cursor = movable.trampolines; + const auto movable_result = Loader::X64InstructionEmulator::SplitWideStores( + reinterpret_cast<uint64_t>(movable.code), movable_code.size(), + &movable_cursor, movable.end); + Check(movable_result.relocated == 1 && movable_result.trapped == 0, + "safe hot store was not relocated"); + auto cursor = area.trampolines; ``` </details> <!-- cr-comment:v1:c748e5a7947cbff5208b383f --> </blockquote></details> </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `8b12013c-f15e-4413-bb9e-a77173c2a08f` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 9e9c2de52faf6d422ea67d5690cfc163a4a088b9 and e8f5158bb6e581e13acb4a3118cbc41f876bae22. </details> <details> <summary>📒 Files selected for processing (2)</summary> * `src/loader/x64InstructionEmulator.cpp` * `tests/macosWideStoreTests.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (2)</summary> * tests/macosWideStoreTests.cpp * src/loader/x64InstructionEmulator.cpp </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠wuboo on GitHub · 2026-10-02 20:59 UTC · original

Addressed the outside-diff note in 8934d8d0: TestUnpatchedAbortsUnderRosetta now asserts WIFSIGNALED when sysctl.proc_translated reports Rosetta; native x86-64 still just exits. macos_wide_store_tests passes.

**@⁠wuboo** on GitHub · 2026-10-02 20:59 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#issuecomment-5961392530) Addressed the outside-diff note in 8934d8d0: `TestUnpatchedAbortsUnderRosetta` now asserts `WIFSIGNALED` when `sysctl.proc_translated` reports Rosetta; native x86-64 still just exits. `macos_wide_store_tests` passes.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 21:07 UTC · original · edited 2026-10-02 21:37 UTC
On tests/macosWideStoreTests.cpp line 106 (outdated):

@@ -0,0 +1,294 @@
+// Checks X64InstructionEmulator::SplitWideStores under Rosetta: a 256-bit store that crosses
+// from a writable into a write-protected page aborts the process ("unexpectedly need to
+// EmulateForward on a synchronous exception"), while the split 128-bit form faults cleanly.
+
+#include "loader/x64InstructionEmulator.h"
+
+#include <array>
+#include <csignal>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <sys/sysctl.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+namespace {
+
+int g_failures = 0;
+
+void Check(bool condition, const char* message) {
+	if (!condition) {
+		std::fprintf(stderr, "FAIL: %s\n", message);
+		g_failures++;
+	}
+}
+
+long g_page_size = 0;
+
+void UnprotectOnFault(int /*signal*/, siginfo_t* info, void* /*context*/) {
+	auto page = reinterpret_cast<uintptr_t>(info->si_addr) & ~static_cast<uintptr_t>(g_page_size - 1);
+	mprotect(reinterpret_cast<void*>(page), g_page_size, PROT_READ | PROT_WRITE);
+}
+
+// void copy(uint8_t* dst /*rdi*/, const uint8_t* src /*rsi*/):
+// the store to [rdi + 0x40] is the third instruction of the block and crosses the page boundary.
+constexpr std::array<uint8_t, 24> CopyCode = {
+    0xc5, 0xfc, 0x10, 0x06,       // vmovups ymm0, [rsi]
+    0xc5, 0xfc, 0x10, 0x4e, 0x20, // vmovups ymm1, [rsi + 0x20]
+    0xc5, 0xfc, 0x11, 0x47, 0x40, // vmovups [rdi + 0x40], ymm0
+    0xc5, 0xfc, 0x11, 0x4f, 0x60, // vmovups [rdi + 0x60], ymm1
+    0xc5, 0xf8, 0x77,             // vzeroupper
+    0xc3,                         // ret
+    0xcc,
+};
+
+using CopyFunc = void (*)(uint8_t*, const uint8_t*);
+
+struct CodeArea {
+	uint8_t* code        = nullptr;
+	uint64_t trampolines = 0;
+	uint64_t end         = 0;
+};
+
+CodeArea MakeCode() {
+	constexpr size_t size = 64 * 1024;
+	auto* base = static_cast<uint8_t*>(
+	    mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON | MAP_JIT, -1, 0));
+	if (base == MAP_FAILED) {
+		base = static_cast<uint8_t*>(
+		    mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0));
+	}
+	if (base == MAP_FAILED) {
+		std::perror("mmap");
+		std::exit(2);
+	}
+	std::memcpy(base, CopyCode.data(), CopyCode.size());
+	return {base, reinterpret_cast<uint64_t>(base) + 4096, reinterpret_cast<uint64_t>(base) + size};
+}
+
+// dst + 0x40 is 16 bytes before a write-protected page, so the first store straddles it.
+bool RunCrossingCopy(CopyFunc copy) {
+	auto* data = static_cast<uint8_t*>(
+	    mmap(nullptr, 4 * g_page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0));
+	uint8_t source[64];
+	for (int i = 0; i < 64; i++) {
+		source[i] = static_cast<uint8_t>(i + 1);
+	}
+	uint8_t* boundary = data + 2 * g_page_size;
+	uint8_t* dst      = boundary - 0x50;
+	mprotect(boundary, g_page_size, PROT_READ);
+	copy(dst, source);
+	return std::memcmp(dst + 0x40, source, 64) == 0;
+}
+
+bool IsRunningUnderRosetta() {
+	int    translated = 0;
+	size_t size       = sizeof(translated);
+	return sysctlbyname("sysctl.proc_translated", &translated, &size, nullptr, 0) == 0 &&
+	       translated == 1;
+}
+
+void TestUnpatchedAbortsUnderRosetta() {
+	const pid_t child = fork();
+	if (child == 0) {
+		auto area = MakeCode();
+		RunCrossingCopy(reinterpret_cast<CopyFunc>(area.code));
+		_exit(0);
+	}
+	int status = 0;
+	waitpid(child, &status, 0);
+	// The Rosetta behaviour this patch works around; native x86-64 runs exit cleanly. If a future
+	// Rosetta stops aborting here, this check flags that the split may no longer be needed.
+	Check(!IsRunningUnderRosetta() || WIFSIGNALED(status),

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '70,125p' tests/macosWideStoreTests.cpp

Repository: KytyPS5/KytyPS5

Length of output: 2385


Require a normal zero exit on native x86-64.

When IsRunningUnderRosetta() is false, the current condition passes regardless of the child’s wait status. This lets a native child terminated by a signal or nonzero exit pass the test. This is a test assertion gap, not a production behavior failure.

🐛 Suggested fix
-	Check(!IsRunningUnderRosetta() || WIFSIGNALED(status),
+	Check(IsRunningUnderRosetta() ? WIFSIGNALED(status)
+	                              : WIFEXITED(status) && WEXITSTATUS(status) == 0,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	Check(IsRunningUnderRosetta() ? WIFSIGNALED(status)
	                              : WIFEXITED(status) && WEXITSTATUS(status) == 0,

✅ Addressed in commit 9d7ed9f

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 21:07 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#discussion_r4169845997) · edited 2026-10-02 21:37 UTC On `tests/macosWideStoreTests.cpp` line 106 (outdated): ```diff @@ -0,0 +1,294 @@ +// Checks X64InstructionEmulator::SplitWideStores under Rosetta: a 256-bit store that crosses +// from a writable into a write-protected page aborts the process ("unexpectedly need to +// EmulateForward on a synchronous exception"), while the split 128-bit form faults cleanly. + +#include "loader/x64InstructionEmulator.h" + +#include <array> +#include <csignal> +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <fcntl.h> +#include <sys/mman.h> +#include <sys/sysctl.h> +#include <sys/wait.h> +#include <unistd.h> + +namespace { + +int g_failures = 0; + +void Check(bool condition, const char* message) { + if (!condition) { + std::fprintf(stderr, "FAIL: %s\n", message); + g_failures++; + } +} + +long g_page_size = 0; + +void UnprotectOnFault(int /*signal*/, siginfo_t* info, void* /*context*/) { + auto page = reinterpret_cast<uintptr_t>(info->si_addr) & ~static_cast<uintptr_t>(g_page_size - 1); + mprotect(reinterpret_cast<void*>(page), g_page_size, PROT_READ | PROT_WRITE); +} + +// void copy(uint8_t* dst /*rdi*/, const uint8_t* src /*rsi*/): +// the store to [rdi + 0x40] is the third instruction of the block and crosses the page boundary. +constexpr std::array<uint8_t, 24> CopyCode = { + 0xc5, 0xfc, 0x10, 0x06, // vmovups ymm0, [rsi] + 0xc5, 0xfc, 0x10, 0x4e, 0x20, // vmovups ymm1, [rsi + 0x20] + 0xc5, 0xfc, 0x11, 0x47, 0x40, // vmovups [rdi + 0x40], ymm0 + 0xc5, 0xfc, 0x11, 0x4f, 0x60, // vmovups [rdi + 0x60], ymm1 + 0xc5, 0xf8, 0x77, // vzeroupper + 0xc3, // ret + 0xcc, +}; + +using CopyFunc = void (*)(uint8_t*, const uint8_t*); + +struct CodeArea { + uint8_t* code = nullptr; + uint64_t trampolines = 0; + uint64_t end = 0; +}; + +CodeArea MakeCode() { + constexpr size_t size = 64 * 1024; + auto* base = static_cast<uint8_t*>( + mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON | MAP_JIT, -1, 0)); + if (base == MAP_FAILED) { + base = static_cast<uint8_t*>( + mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0)); + } + if (base == MAP_FAILED) { + std::perror("mmap"); + std::exit(2); + } + std::memcpy(base, CopyCode.data(), CopyCode.size()); + return {base, reinterpret_cast<uint64_t>(base) + 4096, reinterpret_cast<uint64_t>(base) + size}; +} + +// dst + 0x40 is 16 bytes before a write-protected page, so the first store straddles it. +bool RunCrossingCopy(CopyFunc copy) { + auto* data = static_cast<uint8_t*>( + mmap(nullptr, 4 * g_page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0)); + uint8_t source[64]; + for (int i = 0; i < 64; i++) { + source[i] = static_cast<uint8_t>(i + 1); + } + uint8_t* boundary = data + 2 * g_page_size; + uint8_t* dst = boundary - 0x50; + mprotect(boundary, g_page_size, PROT_READ); + copy(dst, source); + return std::memcmp(dst + 0x40, source, 64) == 0; +} + +bool IsRunningUnderRosetta() { + int translated = 0; + size_t size = sizeof(translated); + return sysctlbyname("sysctl.proc_translated", &translated, &size, nullptr, 0) == 0 && + translated == 1; +} + +void TestUnpatchedAbortsUnderRosetta() { + const pid_t child = fork(); + if (child == 0) { + auto area = MakeCode(); + RunCrossingCopy(reinterpret_cast<CopyFunc>(area.code)); + _exit(0); + } + int status = 0; + waitpid(child, &status, 0); + // The Rosetta behaviour this patch works around; native x86-64 runs exit cleanly. If a future + // Rosetta stops aborting here, this check flags that the split may no longer be needed. + Check(!IsRunningUnderRosetta() || WIFSIGNALED(status), ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '70,125p' tests/macosWideStoreTests.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 2385 --- </details> **Require a normal zero exit on native x86-64.** When `IsRunningUnderRosetta()` is false, the current condition passes regardless of the child’s wait status. This lets a native child terminated by a signal or nonzero exit pass the test. This is a test assertion gap, not a production behavior failure. <details> <summary>🐛 Suggested fix</summary> ```diff - Check(!IsRunningUnderRosetta() || WIFSIGNALED(status), + Check(IsRunningUnderRosetta() ? WIFSIGNALED(status) + : WIFEXITED(status) && WEXITSTATUS(status) == 0, ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion Check(IsRunningUnderRosetta() ? WIFSIGNALED(status) : WIFEXITED(status) && WEXITSTATUS(status) == 0, ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:serval --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:164d1140ea9351d38c54b1ce --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit 9d7ed9f
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 21:07 UTC · original · reviewed

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: 4adcfcc0-c9c4-4088-9238-9ea7d3158594

📥 Commits

Reviewing files that changed from the base of the PR and between e8f5158bb6e581e13acb4a3118cbc41f876bae22 and 8934d8d01a66cb4a76ecf8b765c608de5038743a.

📒 Files selected for processing (1)
  • tests/macosWideStoreTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 21:07 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#pullrequestreview-5396861502) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `4adcfcc0-c9c4-4088-9238-9ea7d3158594` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between e8f5158bb6e581e13acb4a3118cbc41f876bae22 and 8934d8d01a66cb4a76ecf8b765c608de5038743a. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `tests/macosWideStoreTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
@ -0,0 +195,4 @@
const auto live_result = Loader::X64InstructionEmulator::SplitWideStores(
reinterpret_cast<uint64_t>(area.code), live.size(), &cursor, area.end);
Check(live_result.via_cave == 0 && live_result.trapped == 1,
"reachable nop not used as a cave");
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 21:12 UTC · original

@wuboo Thanks for fixing this in e8f5158b. Limiting moving to profiled sites makes the live-nop case trap, as the test expects.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 21:12 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#discussion_r4169879776) `@wuboo` Thanks for fixing this in `e8f5158b`. Limiting moving to profiled sites makes the live-nop case trap, as the test expects. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=%40coderabbitai%20caught%20a%20move-mode%20mismatch%3A%20an%20unprofiled%205-byte%20nop%20was%20relocated%2C%20not%20trapped.%20Limiting%20moves%20to%20profiled%20sites%20fixed%20the%20test.%20Try%20CodeRabbit%20for%20sharper%20reviews%20%F0%9F%90%87&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F984%23discussion_r4169703128)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
@ -795,0 +1171,4 @@
return value != nullptr && std::strcmp(value, "all") == 0;
}();
if (trap && (move_all || std::binary_search(hot_sites.begin(), hot_sites.end(),
reinterpret_cast<uint64_t>(code)))) {
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 21:12 UTC · original

@wuboo Thanks for the fix. The supplied code now limits instruction relocation to hot-profile sites by default. KYTY_WIDE_STORE_MOVE=all explicitly enables relocation at unprofiled sites. This addresses the finding.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 21:12 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#discussion_r4169883915) `@wuboo` Thanks for the fix. The supplied code now limits instruction relocation to hot-profile sites by default. `KYTY_WIDE_STORE_MOVE=all` explicitly enables relocation at unprofiled sites. This addresses the finding. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=Unprofiled%20trap%20sites%20may%20hide%20indirect%20targets%2C%20so%20relocating%20them%20risks%20crashes.%20%40coderabbitai%20caught%20it%3A%20move%20only%20hot-profile%20sites%20by%20default.%20Try%20CodeRabbit%20for%20safer%20reviews%20%F0%9F%9B%A1%EF%B8%8F&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F984%23discussion_r4169703115)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠wuboo on GitHub · 2026-10-02 21:29 UTC · original
On tests/macosWideStoreTests.cpp line 106 (outdated):

@@ -0,0 +1,294 @@
+// Checks X64InstructionEmulator::SplitWideStores under Rosetta: a 256-bit store that crosses
+// from a writable into a write-protected page aborts the process ("unexpectedly need to
+// EmulateForward on a synchronous exception"), while the split 128-bit form faults cleanly.
+
+#include "loader/x64InstructionEmulator.h"
+
+#include <array>
+#include <csignal>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <sys/sysctl.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+namespace {
+
+int g_failures = 0;
+
+void Check(bool condition, const char* message) {
+	if (!condition) {
+		std::fprintf(stderr, "FAIL: %s\n", message);
+		g_failures++;
+	}
+}
+
+long g_page_size = 0;
+
+void UnprotectOnFault(int /*signal*/, siginfo_t* info, void* /*context*/) {
+	auto page = reinterpret_cast<uintptr_t>(info->si_addr) & ~static_cast<uintptr_t>(g_page_size - 1);
+	mprotect(reinterpret_cast<void*>(page), g_page_size, PROT_READ | PROT_WRITE);
+}
+
+// void copy(uint8_t* dst /*rdi*/, const uint8_t* src /*rsi*/):
+// the store to [rdi + 0x40] is the third instruction of the block and crosses the page boundary.
+constexpr std::array<uint8_t, 24> CopyCode = {
+    0xc5, 0xfc, 0x10, 0x06,       // vmovups ymm0, [rsi]
+    0xc5, 0xfc, 0x10, 0x4e, 0x20, // vmovups ymm1, [rsi + 0x20]
+    0xc5, 0xfc, 0x11, 0x47, 0x40, // vmovups [rdi + 0x40], ymm0
+    0xc5, 0xfc, 0x11, 0x4f, 0x60, // vmovups [rdi + 0x60], ymm1
+    0xc5, 0xf8, 0x77,             // vzeroupper
+    0xc3,                         // ret
+    0xcc,
+};
+
+using CopyFunc = void (*)(uint8_t*, const uint8_t*);
+
+struct CodeArea {
+	uint8_t* code        = nullptr;
+	uint64_t trampolines = 0;
+	uint64_t end         = 0;
+};
+
+CodeArea MakeCode() {
+	constexpr size_t size = 64 * 1024;
+	auto* base = static_cast<uint8_t*>(
+	    mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON | MAP_JIT, -1, 0));
+	if (base == MAP_FAILED) {
+		base = static_cast<uint8_t*>(
+		    mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0));
+	}
+	if (base == MAP_FAILED) {
+		std::perror("mmap");
+		std::exit(2);
+	}
+	std::memcpy(base, CopyCode.data(), CopyCode.size());
+	return {base, reinterpret_cast<uint64_t>(base) + 4096, reinterpret_cast<uint64_t>(base) + size};
+}
+
+// dst + 0x40 is 16 bytes before a write-protected page, so the first store straddles it.
+bool RunCrossingCopy(CopyFunc copy) {
+	auto* data = static_cast<uint8_t*>(
+	    mmap(nullptr, 4 * g_page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0));
+	uint8_t source[64];
+	for (int i = 0; i < 64; i++) {
+		source[i] = static_cast<uint8_t>(i + 1);
+	}
+	uint8_t* boundary = data + 2 * g_page_size;
+	uint8_t* dst      = boundary - 0x50;
+	mprotect(boundary, g_page_size, PROT_READ);
+	copy(dst, source);
+	return std::memcmp(dst + 0x40, source, 64) == 0;
+}
+
+bool IsRunningUnderRosetta() {
+	int    translated = 0;
+	size_t size       = sizeof(translated);
+	return sysctlbyname("sysctl.proc_translated", &translated, &size, nullptr, 0) == 0 &&
+	       translated == 1;
+}
+
+void TestUnpatchedAbortsUnderRosetta() {
+	const pid_t child = fork();
+	if (child == 0) {
+		auto area = MakeCode();
+		RunCrossingCopy(reinterpret_cast<CopyFunc>(area.code));
+		_exit(0);
+	}
+	int status = 0;
+	waitpid(child, &status, 0);
+	// The Rosetta behaviour this patch works around; native x86-64 runs exit cleanly. If a future
+	// Rosetta stops aborting here, this check flags that the split may no longer be needed.
+	Check(!IsRunningUnderRosetta() || WIFSIGNALED(status),

Fixed in 9d7ed9fb. On native x86-64 the test now requires WIFEXITED(status) && WEXITSTATUS(status) == 0, and under Rosetta it still requires WIFSIGNALED. A child killed by a signal on real hardware no longer passes. I checked that the test fails when the native branch is forced.

**@⁠wuboo** on GitHub · 2026-10-02 21:29 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#discussion_r4169991522) On `tests/macosWideStoreTests.cpp` line 106 (outdated): ```diff @@ -0,0 +1,294 @@ +// Checks X64InstructionEmulator::SplitWideStores under Rosetta: a 256-bit store that crosses +// from a writable into a write-protected page aborts the process ("unexpectedly need to +// EmulateForward on a synchronous exception"), while the split 128-bit form faults cleanly. + +#include "loader/x64InstructionEmulator.h" + +#include <array> +#include <csignal> +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <fcntl.h> +#include <sys/mman.h> +#include <sys/sysctl.h> +#include <sys/wait.h> +#include <unistd.h> + +namespace { + +int g_failures = 0; + +void Check(bool condition, const char* message) { + if (!condition) { + std::fprintf(stderr, "FAIL: %s\n", message); + g_failures++; + } +} + +long g_page_size = 0; + +void UnprotectOnFault(int /*signal*/, siginfo_t* info, void* /*context*/) { + auto page = reinterpret_cast<uintptr_t>(info->si_addr) & ~static_cast<uintptr_t>(g_page_size - 1); + mprotect(reinterpret_cast<void*>(page), g_page_size, PROT_READ | PROT_WRITE); +} + +// void copy(uint8_t* dst /*rdi*/, const uint8_t* src /*rsi*/): +// the store to [rdi + 0x40] is the third instruction of the block and crosses the page boundary. +constexpr std::array<uint8_t, 24> CopyCode = { + 0xc5, 0xfc, 0x10, 0x06, // vmovups ymm0, [rsi] + 0xc5, 0xfc, 0x10, 0x4e, 0x20, // vmovups ymm1, [rsi + 0x20] + 0xc5, 0xfc, 0x11, 0x47, 0x40, // vmovups [rdi + 0x40], ymm0 + 0xc5, 0xfc, 0x11, 0x4f, 0x60, // vmovups [rdi + 0x60], ymm1 + 0xc5, 0xf8, 0x77, // vzeroupper + 0xc3, // ret + 0xcc, +}; + +using CopyFunc = void (*)(uint8_t*, const uint8_t*); + +struct CodeArea { + uint8_t* code = nullptr; + uint64_t trampolines = 0; + uint64_t end = 0; +}; + +CodeArea MakeCode() { + constexpr size_t size = 64 * 1024; + auto* base = static_cast<uint8_t*>( + mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON | MAP_JIT, -1, 0)); + if (base == MAP_FAILED) { + base = static_cast<uint8_t*>( + mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0)); + } + if (base == MAP_FAILED) { + std::perror("mmap"); + std::exit(2); + } + std::memcpy(base, CopyCode.data(), CopyCode.size()); + return {base, reinterpret_cast<uint64_t>(base) + 4096, reinterpret_cast<uint64_t>(base) + size}; +} + +// dst + 0x40 is 16 bytes before a write-protected page, so the first store straddles it. +bool RunCrossingCopy(CopyFunc copy) { + auto* data = static_cast<uint8_t*>( + mmap(nullptr, 4 * g_page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0)); + uint8_t source[64]; + for (int i = 0; i < 64; i++) { + source[i] = static_cast<uint8_t>(i + 1); + } + uint8_t* boundary = data + 2 * g_page_size; + uint8_t* dst = boundary - 0x50; + mprotect(boundary, g_page_size, PROT_READ); + copy(dst, source); + return std::memcmp(dst + 0x40, source, 64) == 0; +} + +bool IsRunningUnderRosetta() { + int translated = 0; + size_t size = sizeof(translated); + return sysctlbyname("sysctl.proc_translated", &translated, &size, nullptr, 0) == 0 && + translated == 1; +} + +void TestUnpatchedAbortsUnderRosetta() { + const pid_t child = fork(); + if (child == 0) { + auto area = MakeCode(); + RunCrossingCopy(reinterpret_cast<CopyFunc>(area.code)); + _exit(0); + } + int status = 0; + waitpid(child, &status, 0); + // The Rosetta behaviour this patch works around; native x86-64 runs exit cleanly. If a future + // Rosetta stops aborting here, this check flags that the split may no longer be needed. + Check(!IsRunningUnderRosetta() || WIFSIGNALED(status), ``` Fixed in 9d7ed9fb. On native x86-64 the test now requires `WIFEXITED(status) && WEXITSTATUS(status) == 0`, and under Rosetta it still requires `WIFSIGNALED`. A child killed by a signal on real hardware no longer passes. I checked that the test fails when the native branch is forced.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 21:37 UTC · original
On tests/macosWideStoreTests.cpp line 106 (outdated):

@@ -0,0 +1,294 @@
+// Checks X64InstructionEmulator::SplitWideStores under Rosetta: a 256-bit store that crosses
+// from a writable into a write-protected page aborts the process ("unexpectedly need to
+// EmulateForward on a synchronous exception"), while the split 128-bit form faults cleanly.
+
+#include "loader/x64InstructionEmulator.h"
+
+#include <array>
+#include <csignal>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <sys/sysctl.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+namespace {
+
+int g_failures = 0;
+
+void Check(bool condition, const char* message) {
+	if (!condition) {
+		std::fprintf(stderr, "FAIL: %s\n", message);
+		g_failures++;
+	}
+}
+
+long g_page_size = 0;
+
+void UnprotectOnFault(int /*signal*/, siginfo_t* info, void* /*context*/) {
+	auto page = reinterpret_cast<uintptr_t>(info->si_addr) & ~static_cast<uintptr_t>(g_page_size - 1);
+	mprotect(reinterpret_cast<void*>(page), g_page_size, PROT_READ | PROT_WRITE);
+}
+
+// void copy(uint8_t* dst /*rdi*/, const uint8_t* src /*rsi*/):
+// the store to [rdi + 0x40] is the third instruction of the block and crosses the page boundary.
+constexpr std::array<uint8_t, 24> CopyCode = {
+    0xc5, 0xfc, 0x10, 0x06,       // vmovups ymm0, [rsi]
+    0xc5, 0xfc, 0x10, 0x4e, 0x20, // vmovups ymm1, [rsi + 0x20]
+    0xc5, 0xfc, 0x11, 0x47, 0x40, // vmovups [rdi + 0x40], ymm0
+    0xc5, 0xfc, 0x11, 0x4f, 0x60, // vmovups [rdi + 0x60], ymm1
+    0xc5, 0xf8, 0x77,             // vzeroupper
+    0xc3,                         // ret
+    0xcc,
+};
+
+using CopyFunc = void (*)(uint8_t*, const uint8_t*);
+
+struct CodeArea {
+	uint8_t* code        = nullptr;
+	uint64_t trampolines = 0;
+	uint64_t end         = 0;
+};
+
+CodeArea MakeCode() {
+	constexpr size_t size = 64 * 1024;
+	auto* base = static_cast<uint8_t*>(
+	    mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON | MAP_JIT, -1, 0));
+	if (base == MAP_FAILED) {
+		base = static_cast<uint8_t*>(
+		    mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0));
+	}
+	if (base == MAP_FAILED) {
+		std::perror("mmap");
+		std::exit(2);
+	}
+	std::memcpy(base, CopyCode.data(), CopyCode.size());
+	return {base, reinterpret_cast<uint64_t>(base) + 4096, reinterpret_cast<uint64_t>(base) + size};
+}
+
+// dst + 0x40 is 16 bytes before a write-protected page, so the first store straddles it.
+bool RunCrossingCopy(CopyFunc copy) {
+	auto* data = static_cast<uint8_t*>(
+	    mmap(nullptr, 4 * g_page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0));
+	uint8_t source[64];
+	for (int i = 0; i < 64; i++) {
+		source[i] = static_cast<uint8_t>(i + 1);
+	}
+	uint8_t* boundary = data + 2 * g_page_size;
+	uint8_t* dst      = boundary - 0x50;
+	mprotect(boundary, g_page_size, PROT_READ);
+	copy(dst, source);
+	return std::memcmp(dst + 0x40, source, 64) == 0;
+}
+
+bool IsRunningUnderRosetta() {
+	int    translated = 0;
+	size_t size       = sizeof(translated);
+	return sysctlbyname("sysctl.proc_translated", &translated, &size, nullptr, 0) == 0 &&
+	       translated == 1;
+}
+
+void TestUnpatchedAbortsUnderRosetta() {
+	const pid_t child = fork();
+	if (child == 0) {
+		auto area = MakeCode();
+		RunCrossingCopy(reinterpret_cast<CopyFunc>(area.code));
+		_exit(0);
+	}
+	int status = 0;
+	waitpid(child, &status, 0);
+	// The Rosetta behaviour this patch works around; native x86-64 runs exit cleanly. If a future
+	// Rosetta stops aborting here, this check flags that the split may no longer be needed.
+	Check(!IsRunningUnderRosetta() || WIFSIGNALED(status),

@wuboo Thanks for the fix. The native assertion now rejects signal termination and nonzero exits. The Rosetta assertion remains unchanged.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 21:37 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#discussion_r4170042163) On `tests/macosWideStoreTests.cpp` line 106 (outdated): ```diff @@ -0,0 +1,294 @@ +// Checks X64InstructionEmulator::SplitWideStores under Rosetta: a 256-bit store that crosses +// from a writable into a write-protected page aborts the process ("unexpectedly need to +// EmulateForward on a synchronous exception"), while the split 128-bit form faults cleanly. + +#include "loader/x64InstructionEmulator.h" + +#include <array> +#include <csignal> +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <fcntl.h> +#include <sys/mman.h> +#include <sys/sysctl.h> +#include <sys/wait.h> +#include <unistd.h> + +namespace { + +int g_failures = 0; + +void Check(bool condition, const char* message) { + if (!condition) { + std::fprintf(stderr, "FAIL: %s\n", message); + g_failures++; + } +} + +long g_page_size = 0; + +void UnprotectOnFault(int /*signal*/, siginfo_t* info, void* /*context*/) { + auto page = reinterpret_cast<uintptr_t>(info->si_addr) & ~static_cast<uintptr_t>(g_page_size - 1); + mprotect(reinterpret_cast<void*>(page), g_page_size, PROT_READ | PROT_WRITE); +} + +// void copy(uint8_t* dst /*rdi*/, const uint8_t* src /*rsi*/): +// the store to [rdi + 0x40] is the third instruction of the block and crosses the page boundary. +constexpr std::array<uint8_t, 24> CopyCode = { + 0xc5, 0xfc, 0x10, 0x06, // vmovups ymm0, [rsi] + 0xc5, 0xfc, 0x10, 0x4e, 0x20, // vmovups ymm1, [rsi + 0x20] + 0xc5, 0xfc, 0x11, 0x47, 0x40, // vmovups [rdi + 0x40], ymm0 + 0xc5, 0xfc, 0x11, 0x4f, 0x60, // vmovups [rdi + 0x60], ymm1 + 0xc5, 0xf8, 0x77, // vzeroupper + 0xc3, // ret + 0xcc, +}; + +using CopyFunc = void (*)(uint8_t*, const uint8_t*); + +struct CodeArea { + uint8_t* code = nullptr; + uint64_t trampolines = 0; + uint64_t end = 0; +}; + +CodeArea MakeCode() { + constexpr size_t size = 64 * 1024; + auto* base = static_cast<uint8_t*>( + mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON | MAP_JIT, -1, 0)); + if (base == MAP_FAILED) { + base = static_cast<uint8_t*>( + mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0)); + } + if (base == MAP_FAILED) { + std::perror("mmap"); + std::exit(2); + } + std::memcpy(base, CopyCode.data(), CopyCode.size()); + return {base, reinterpret_cast<uint64_t>(base) + 4096, reinterpret_cast<uint64_t>(base) + size}; +} + +// dst + 0x40 is 16 bytes before a write-protected page, so the first store straddles it. +bool RunCrossingCopy(CopyFunc copy) { + auto* data = static_cast<uint8_t*>( + mmap(nullptr, 4 * g_page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0)); + uint8_t source[64]; + for (int i = 0; i < 64; i++) { + source[i] = static_cast<uint8_t>(i + 1); + } + uint8_t* boundary = data + 2 * g_page_size; + uint8_t* dst = boundary - 0x50; + mprotect(boundary, g_page_size, PROT_READ); + copy(dst, source); + return std::memcmp(dst + 0x40, source, 64) == 0; +} + +bool IsRunningUnderRosetta() { + int translated = 0; + size_t size = sizeof(translated); + return sysctlbyname("sysctl.proc_translated", &translated, &size, nullptr, 0) == 0 && + translated == 1; +} + +void TestUnpatchedAbortsUnderRosetta() { + const pid_t child = fork(); + if (child == 0) { + auto area = MakeCode(); + RunCrossingCopy(reinterpret_cast<CopyFunc>(area.code)); + _exit(0); + } + int status = 0; + waitpid(child, &status, 0); + // The Rosetta behaviour this patch works around; native x86-64 runs exit cleanly. If a future + // Rosetta stops aborting here, this check flags that the split may no longer be needed. + Check(!IsRunningUnderRosetta() || WIFSIGNALED(status), ``` `@wuboo` Thanks for the fix. The native assertion now rejects signal termination and nonzero exits. The Rosetta assertion remains unchanged. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=CodeRabbit%20caught%20a%20test%20gap%3A%20native%20x86-64%20must%20exit%20normally%20with%20status%200%3B%20Rosetta%20must%20signal.%20Catch%20subtle%20bugs%20in%20your%20PRs%E2%80%94try%20%40coderabbitai%20%F0%9F%90%87%E2%9C%85&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F984%23discussion_r4169845997)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠wuboo on GitHub · 2026-10-03 17:50 UTC · original

Rebased on main (19a9464b). Main now has a shared guest instruction trampoline area (#839 and the INSERTQ/RDPID/CLWB follow-up), so the split no longer reserves its own area on macOS. It uses instruction_trampoline_*, and PatchReciprocalSquareRoots is gone because main moved that into the patcher.

New commit 8863b3d7: the split starts its trampolines behind the bytes the patcher has already used. Without that, #1014 (patcher on macOS) plus this split would write over each other's trampolines when --amd-cpu is on. On this branch alone the patcher is still stubbed on macOS, so the offset is 0 and nothing changes.

Full CPU ctest is identical to main: 35 pass including macos_wide_store, and 16 GPU tests are skipped on this machine.

**@⁠wuboo** on GitHub · 2026-10-03 17:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#issuecomment-5971840440) Rebased on main (19a9464b). Main now has a shared guest instruction trampoline area (#839 and the INSERTQ/RDPID/CLWB follow-up), so the split no longer reserves its own area on macOS. It uses `instruction_trampoline_*`, and `PatchReciprocalSquareRoots` is gone because main moved that into the patcher. New commit 8863b3d7: the split starts its trampolines behind the bytes the patcher has already used. Without that, #1014 (patcher on macOS) plus this split would write over each other's trampolines when `--amd-cpu` is on. On this branch alone the patcher is still stubbed on macOS, so the offset is 0 and nothing changes. Full CPU ctest is identical to main: 35 pass including `macos_wide_store`, and 16 GPU tests are skipped on this machine.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-03 17:57 UTC · original · edited 2026-10-03 19:05 UTC
On src/loader/x64InstructionEmulator.cpp line 816 (outdated):

@@ -792,6 +805,576 @@ static bool TryEmulateReciprocalSquareRoot(Context& context) {
 
 #endif
 
+static bool IsPlainWideStore(const ZydisDecodedInstruction& instruction,
+                             const ZydisDecodedOperand*     operands) {
+	switch (instruction.mnemonic) {
+		case ZYDIS_MNEMONIC_VMOVUPS:
+		case ZYDIS_MNEMONIC_VMOVAPS:
+		case ZYDIS_MNEMONIC_VMOVUPD:
+		case ZYDIS_MNEMONIC_VMOVAPD:
+		case ZYDIS_MNEMONIC_VMOVDQU:
+		case ZYDIS_MNEMONIC_VMOVDQA: break;

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Exclude aligned stores (VMOVAPS/VMOVAPD/VMOVDQA) from splitting.

The header comment names one failure: a 256-bit store that crosses into a write-protected page. An aligned 256-bit store cannot cross a page:

  • VMOVAPS, VMOVAPD and VMOVDQA raise #GP when the address is not 32-byte aligned.
  • 4096 is a multiple of 32, so a 32-byte-aligned store always stays inside one page.

The splitter still rewrites these stores, and that has a real cost:

  • Each aligned store uses trampoline space from the shared instruction_trampoline_* area. That leaves less room for unaligned stores and for the patcher, and fills the area sooner (unsupported).
  • A short aligned store with no cave in reach becomes ud2. Each execution then takes a SIGILL and runs the handler. Aligned stores are common in hot loops (vectorized memset/memcpy bodies, stack spills to aligned slots). Until the hot profile is rebuilt and the game restarted, such a loop takes one signal per iteration.
  • The split also hides the guest's alignment fault, because vmovups never faults on misalignment.

Only the unaligned forms can cross a page. Match only those forms here. The sweep at Line 1029-1034 can then skip the aligned forms as well.

♻️ Proposed fix
 	switch (instruction.mnemonic) {
+		// Aligned forms fault unless 32-byte aligned and so never cross a page.
 		case ZYDIS_MNEMONIC_VMOVUPS:
-		case ZYDIS_MNEMONIC_VMOVAPS:
 		case ZYDIS_MNEMONIC_VMOVUPD:
-		case ZYDIS_MNEMONIC_VMOVAPD:
-		case ZYDIS_MNEMONIC_VMOVDQU:
-		case ZYDIS_MNEMONIC_VMOVDQA: break;
+		case ZYDIS_MNEMONIC_VMOVDQU: break;
 		default: return false;
 	}

In the sweep:

 				case ZYDIS_MNEMONIC_VMOVUPS:
-				case ZYDIS_MNEMONIC_VMOVAPS:
 				case ZYDIS_MNEMONIC_VMOVUPD:
-				case ZYDIS_MNEMONIC_VMOVAPD:
-				case ZYDIS_MNEMONIC_VMOVDQU:
-				case ZYDIS_MNEMONIC_VMOVDQA: candidates.push_back(offset); break;
+				case ZYDIS_MNEMONIC_VMOVDQU: candidates.push_back(offset); break;

✅ Addressed in commits ad505e7 to e225e7f

**@⁠coderabbitai[bot]** on GitHub · 2026-10-03 17:57 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#discussion_r4174218981) · edited 2026-10-03 19:05 UTC On `src/loader/x64InstructionEmulator.cpp` line 816 (outdated): ```diff @@ -792,6 +805,576 @@ static bool TryEmulateReciprocalSquareRoot(Context& context) { #endif +static bool IsPlainWideStore(const ZydisDecodedInstruction& instruction, + const ZydisDecodedOperand* operands) { + switch (instruction.mnemonic) { + case ZYDIS_MNEMONIC_VMOVUPS: + case ZYDIS_MNEMONIC_VMOVAPS: + case ZYDIS_MNEMONIC_VMOVUPD: + case ZYDIS_MNEMONIC_VMOVAPD: + case ZYDIS_MNEMONIC_VMOVDQU: + case ZYDIS_MNEMONIC_VMOVDQA: break; ``` _🚀 Performance & Scalability_ | _🟠 Major_ | _⚡ Quick win_ **Exclude aligned stores (`VMOVAPS`/`VMOVAPD`/`VMOVDQA`) from splitting.** The header comment names one failure: a 256-bit store that crosses into a write-protected page. An aligned 256-bit store cannot cross a page: - `VMOVAPS`, `VMOVAPD` and `VMOVDQA` raise `#GP` when the address is not 32-byte aligned. - 4096 is a multiple of 32, so a 32-byte-aligned store always stays inside one page. The splitter still rewrites these stores, and that has a real cost: - Each aligned store uses trampoline space from the shared `instruction_trampoline_*` area. That leaves less room for unaligned stores and for the patcher, and fills the area sooner (`unsupported`). - A short aligned store with no cave in reach becomes `ud2`. Each execution then takes a SIGILL and runs the handler. Aligned stores are common in hot loops (vectorized memset/memcpy bodies, stack spills to aligned slots). Until the hot profile is rebuilt and the game restarted, such a loop takes one signal per iteration. - The split also hides the guest's alignment fault, because `vmovups` never faults on misalignment. Only the unaligned forms can cross a page. Match only those forms here. The sweep at Line 1029-1034 can then skip the aligned forms as well. <details> <summary>♻️ Proposed fix</summary> ```diff switch (instruction.mnemonic) { + // Aligned forms fault unless 32-byte aligned and so never cross a page. case ZYDIS_MNEMONIC_VMOVUPS: - case ZYDIS_MNEMONIC_VMOVAPS: case ZYDIS_MNEMONIC_VMOVUPD: - case ZYDIS_MNEMONIC_VMOVAPD: - case ZYDIS_MNEMONIC_VMOVDQU: - case ZYDIS_MNEMONIC_VMOVDQA: break; + case ZYDIS_MNEMONIC_VMOVDQU: break; default: return false; } ``` In the sweep: ```diff case ZYDIS_MNEMONIC_VMOVUPS: - case ZYDIS_MNEMONIC_VMOVAPS: case ZYDIS_MNEMONIC_VMOVUPD: - case ZYDIS_MNEMONIC_VMOVAPD: - case ZYDIS_MNEMONIC_VMOVDQU: - case ZYDIS_MNEMONIC_VMOVDQA: candidates.push_back(offset); break; + case ZYDIS_MNEMONIC_VMOVDQU: candidates.push_back(offset); break; ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:26a5b7b2da4012b6c79c3e86 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commits ad505e7 to e225e7f
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-03 17:57 UTC · original · reviewed

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/loader/runtimeLinker.cpp (1)

2016-2037: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Executable segments that share the trampoline area depend on one cursor; verify that SplitWideStores handles an empty or full area.

The loader flushes the full trampoline area for every segment, even when the split wrote nothing. This is correct but redundant.

Also, GetGuestInstructionTrampolineBytesUsed returns 0 on Apple. The offset is therefore always 0 on this branch. The cursor start is correct only if the shared area is still unused at this point. Confirm that no other code writes to instruction_trampoline_vaddr before this block runs on Apple.

Flush the trampoline area once, after the segment loop. Flush only the bytes written, from the start cursor to the end cursor.

♻️ Proposed change
-		uint64_t cursor = program->instruction_trampoline_vaddr +
-		                  GetGuestInstructionTrampolineBytesUsed(
-		                      reinterpret_cast<void*>(program->base_vaddr));
+		uint64_t cursor = program->instruction_trampoline_vaddr +
+		                  GetGuestInstructionTrampolineBytesUsed(
+		                      reinterpret_cast<void*>(program->base_vaddr));
+		const uint64_t cursor_begin = cursor;
 		for (const auto& [segment_addr, segment_size]: executable_segments) {
 			const auto result = X64InstructionEmulator::SplitWideStores(
 			    segment_addr, segment_size, &cursor,
 			    program->instruction_trampoline_vaddr + program->instruction_trampoline_size);
 			Common::VirtualMemory::FlushInstructionCache(segment_addr, segment_size);
-			Common::VirtualMemory::FlushInstructionCache(program->instruction_trampoline_vaddr,
-			                                             program->instruction_trampoline_size);
 			LOGF(...);
 		}
+		if (cursor > cursor_begin) {
+			Common::VirtualMemory::FlushInstructionCache(cursor_begin, cursor - cursor_begin);
+		}

ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d102773a-afd8-4be2-9c63-15457c2369ee
📥 Commits

Reviewing files that changed from the base of the PR and between 9d7ed9fbd40ea1f4e9d369c006853dd3c4387842 and 8863b3d7de.

📒 Files selected for processing (6)
  • src/loader/guestInstructionPatcher.cpp
  • src/loader/guestInstructionPatcher.h
  • src/loader/runtimeLinker.cpp
  • src/loader/runtimeLinker.h
  • src/loader/x64InstructionEmulator.cpp
  • src/loader/x64InstructionEmulator.h

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-03 17:57 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#pullrequestreview-5401966963) · **reviewed** **Actionable comments posted: 1** <details> <summary>🧹 Nitpick comments (1)</summary><blockquote> <details> <summary>src/loader/runtimeLinker.cpp (1)</summary><blockquote> `2016-2037`: _🚀 Performance & Scalability_ | _🔵 Trivial_ | _💤 Low value_ **Executable segments that share the trampoline area depend on one `cursor`; verify that `SplitWideStores` handles an empty or full area.** The loader flushes the full trampoline area for every segment, even when the split wrote nothing. This is correct but redundant. Also, `GetGuestInstructionTrampolineBytesUsed` returns 0 on Apple. The offset is therefore always 0 on this branch. The `cursor` start is correct only if the shared area is still unused at this point. Confirm that no other code writes to `instruction_trampoline_vaddr` before this block runs on Apple. Flush the trampoline area once, after the segment loop. Flush only the bytes written, from the start cursor to the end cursor. <details> <summary>♻️ Proposed change</summary> ```diff - uint64_t cursor = program->instruction_trampoline_vaddr + - GetGuestInstructionTrampolineBytesUsed( - reinterpret_cast<void*>(program->base_vaddr)); + uint64_t cursor = program->instruction_trampoline_vaddr + + GetGuestInstructionTrampolineBytesUsed( + reinterpret_cast<void*>(program->base_vaddr)); + const uint64_t cursor_begin = cursor; for (const auto& [segment_addr, segment_size]: executable_segments) { const auto result = X64InstructionEmulator::SplitWideStores( segment_addr, segment_size, &cursor, program->instruction_trampoline_vaddr + program->instruction_trampoline_size); Common::VirtualMemory::FlushInstructionCache(segment_addr, segment_size); - Common::VirtualMemory::FlushInstructionCache(program->instruction_trampoline_vaddr, - program->instruction_trampoline_size); LOGF(...); } + if (cursor > cursor_begin) { + Common::VirtualMemory::FlushInstructionCache(cursor_begin, cursor - cursor_begin); + } ``` </details> <!-- cr-comment:v1:46b26a776a28204c07221ca3 --> </blockquote></details> </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `d102773a-afd8-4be2-9c63-15457c2369ee` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 9d7ed9fbd40ea1f4e9d369c006853dd3c4387842 and 8863b3d7deb94a49f9956076f22ea3e905d1383e. </details> <details> <summary>📒 Files selected for processing (6)</summary> * `src/loader/guestInstructionPatcher.cpp` * `src/loader/guestInstructionPatcher.h` * `src/loader/runtimeLinker.cpp` * `src/loader/runtimeLinker.h` * `src/loader/x64InstructionEmulator.cpp` * `src/loader/x64InstructionEmulator.h` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠wuboo on GitHub · 2026-10-03 19:05 UTC · original
On src/loader/x64InstructionEmulator.cpp line 816 (outdated):

@@ -792,6 +805,576 @@ static bool TryEmulateReciprocalSquareRoot(Context& context) {
 
 #endif
 
+static bool IsPlainWideStore(const ZydisDecodedInstruction& instruction,
+                             const ZydisDecodedOperand*     operands) {
+	switch (instruction.mnemonic) {
+		case ZYDIS_MNEMONIC_VMOVUPS:
+		case ZYDIS_MNEMONIC_VMOVAPS:
+		case ZYDIS_MNEMONIC_VMOVUPD:
+		case ZYDIS_MNEMONIC_VMOVAPD:
+		case ZYDIS_MNEMONIC_VMOVDQU:
+		case ZYDIS_MNEMONIC_VMOVDQA: break;

Agreed. A 32-byte aligned store can't cross a page, and the aligned forms must keep raising #GP on a misaligned address. Fixed in ad505e77: IsPlainWideStore and the candidate sweep now match only VMOVUPS/VMOVUPD/VMOVDQU. Added TestAlignedStoresAreNotSplit (VMOVAPS/VMOVAPD/VMOVDQA ymm are left byte-for-byte unchanged and use no trampoline space); the existing crossing-store tests keep covering the unaligned VMOVUPS path.

**@⁠wuboo** on GitHub · 2026-10-03 19:05 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#discussion_r4174457889) On `src/loader/x64InstructionEmulator.cpp` line 816 (outdated): ```diff @@ -792,6 +805,576 @@ static bool TryEmulateReciprocalSquareRoot(Context& context) { #endif +static bool IsPlainWideStore(const ZydisDecodedInstruction& instruction, + const ZydisDecodedOperand* operands) { + switch (instruction.mnemonic) { + case ZYDIS_MNEMONIC_VMOVUPS: + case ZYDIS_MNEMONIC_VMOVAPS: + case ZYDIS_MNEMONIC_VMOVUPD: + case ZYDIS_MNEMONIC_VMOVAPD: + case ZYDIS_MNEMONIC_VMOVDQU: + case ZYDIS_MNEMONIC_VMOVDQA: break; ``` Agreed. A 32-byte aligned store can't cross a page, and the aligned forms must keep raising #GP on a misaligned address. Fixed in ad505e77: `IsPlainWideStore` and the candidate sweep now match only VMOVUPS/VMOVUPD/VMOVDQU. Added `TestAlignedStoresAreNotSplit` (VMOVAPS/VMOVAPD/VMOVDQA ymm are left byte-for-byte unchanged and use no trampoline space); the existing crossing-store tests keep covering the unaligned VMOVUPS path.
Author
Owner

@⁠wuboo on GitHub · 2026-10-03 19:05 UTC · original

On the review nitpick about the trampoline flush: Done in e225e7f7: the trampoline flush now happens once after the segment loop, for [cursor_begin, cursor) only, and is skipped when nothing was written. The per-segment code flush stays, since each segment is patched separately.

**@⁠wuboo** on GitHub · 2026-10-03 19:05 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#issuecomment-5972532495) On the review nitpick about the trampoline flush: Done in e225e7f7: the trampoline flush now happens once after the segment loop, for `[cursor_begin, cursor)` only, and is skipped when nothing was written. The per-segment code flush stays, since each segment is patched separately.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-03 19:06 UTC · original
On src/loader/x64InstructionEmulator.cpp line 816 (outdated):

@@ -792,6 +805,576 @@ static bool TryEmulateReciprocalSquareRoot(Context& context) {
 
 #endif
 
+static bool IsPlainWideStore(const ZydisDecodedInstruction& instruction,
+                             const ZydisDecodedOperand*     operands) {
+	switch (instruction.mnemonic) {
+		case ZYDIS_MNEMONIC_VMOVUPS:
+		case ZYDIS_MNEMONIC_VMOVAPS:
+		case ZYDIS_MNEMONIC_VMOVUPD:
+		case ZYDIS_MNEMONIC_VMOVAPD:
+		case ZYDIS_MNEMONIC_VMOVDQU:
+		case ZYDIS_MNEMONIC_VMOVDQA: break;

@wuboo Thanks for the fix. The supplied code excludes aligned stores from both IsPlainWideStore and the candidate sweep. This preserves their alignment faults and avoids unnecessary trampolines. The reported TestAlignedStoresAreNotSplit covers unchanged bytes and zero trampoline use.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-03 19:06 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/984#discussion_r4174459626) On `src/loader/x64InstructionEmulator.cpp` line 816 (outdated): ```diff @@ -792,6 +805,576 @@ static bool TryEmulateReciprocalSquareRoot(Context& context) { #endif +static bool IsPlainWideStore(const ZydisDecodedInstruction& instruction, + const ZydisDecodedOperand* operands) { + switch (instruction.mnemonic) { + case ZYDIS_MNEMONIC_VMOVUPS: + case ZYDIS_MNEMONIC_VMOVAPS: + case ZYDIS_MNEMONIC_VMOVUPD: + case ZYDIS_MNEMONIC_VMOVAPD: + case ZYDIS_MNEMONIC_VMOVDQU: + case ZYDIS_MNEMONIC_VMOVDQA: break; ``` `@wuboo` Thanks for the fix. The supplied code excludes aligned stores from both `IsPlainWideStore` and the candidate sweep. This preserves their alignment faults and avoids unnecessary trampolines. The reported `TestAlignedStoresAreNotSplit` covers unchanged bytes and zero trampoline use. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=Exclude%20aligned%20AVX%20stores%20from%20splitting%20to%20preserve%20%20semantics%20and%20save%20trampoline%20space.%20Try%20%40coderabbitai%20for%20sharp%2C%20actionable%20code%20reviews!%20%F0%9F%9A%80&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F984%23discussion_r4174218981)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
This pull request has changes conflicting with the target branch.
  • src/loader/guestInstructionPatcher.h
  • src/loader/runtimeLinker.cpp
  • src/loader/runtimeLinker.h
  • src/loader/x64InstructionEmulator.cpp
  • src/loader/x64InstructionEmulator.h
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/984/head:github-bot/gh-984'
git switch 'github-bot/gh-984'

Merge

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