Loader: patch a module's functions faster at load #2260

Open
github-bot wants to merge 1 commit from github-bot/gh-2260 into main AGit
Owner

@⁠jgoyvaerts on GitHub · 2026-11-13 19:10 UTC · original
jgoyvaerts:port/fast-patch → main · +518 −20 · 4 files · 1 commits · open

Faster AMD instruction patch at load (also with --guest-tsc):

Modules with at least 1024 functions are scanned on one thread per CPU through byte filters of the rewritten instruction forms. Those are VRSQRTPS xmm, xmm, EXTRQ/INSERTQ, RDPID, CLWB, and RDTSC/RDTSCP when a guest TSC rate is set. The workers decode only the candidates, at most 64 ahead, and the loading thread patches them in address order as before, so the patched code is the same. A function whose jump table lies outside its own bytes is decoded again at its turn on the loading thread.

Astro Bot (252 MB eboot.bin, 312697 functions): ~7-9 s of patching becomes ~1-2 s. Measured with the same change in a Jetsku-based build: identical patched code and trampolines (hash) and counts.

Tested: guest_instruction_patch_scan_tests (new) compares code, trampolines and counters with a single-threaded pass at 2, 5 and 16 threads. It runs AMD only, AMD with RDTSC, RDTSC only, and red-zone protection, with a switch whose jump table lies in the next function. It also checks the filter on the rewritten encodings and look-alikes.

AI use: the code, tests and this description were written with an LLM (Claude). The tests listed ran on a Linux x86-64 build.

🤖 Generated with Claude Code

**@⁠jgoyvaerts** on GitHub · 2026-11-13 19:10 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2260) `jgoyvaerts:port/fast-patch` → `main` · +518 −20 · 4 files · 1 commits · open Faster AMD instruction patch at load (also with `--guest-tsc`): Modules with at least 1024 functions are scanned on one thread per CPU through byte filters of the rewritten instruction forms. Those are VRSQRTPS xmm, xmm, EXTRQ/INSERTQ, RDPID, CLWB, and RDTSC/RDTSCP when a guest TSC rate is set. The workers decode only the candidates, at most 64 ahead, and the loading thread patches them in address order as before, so the patched code is the same. A function whose jump table lies outside its own bytes is decoded again at its turn on the loading thread. Astro Bot (252 MB eboot.bin, 312697 functions): ~7-9 s of patching becomes ~1-2 s. Measured with the same change in a Jetsku-based build: identical patched code and trampolines (hash) and counts. Tested: `guest_instruction_patch_scan_tests` (new) compares code, trampolines and counters with a single-threaded pass at 2, 5 and 16 threads. It runs AMD only, AMD with RDTSC, RDTSC only, and red-zone protection, with a switch whose jump table lies in the next function. It also checks the filter on the rewritten encodings and look-alikes. AI use: the code, tests and this description were written with an LLM (Claude). The tests listed ran on a Linux x86-64 build. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
The AMD instruction patch decoded every function of a module to find the
few instructions it rewrites. Astro Bot's 252 MB eboot.bin (312697
functions) took ~7-9 s at boot on one core.

Without red-zone protection only VRSQRTPS xmm, xmm, EXTRQ/INSERTQ, RDPID,
CLWB and, with a guest TSC rate, RDTSC/RDTSCP are rewritten. Each lies inside
its function, because decoding stops at the function's end, and contains
fixed bytes (MayContainAmdInstruction, MayReadTimeStampCounter). Modules with
at least 1024 functions are now scanned on one thread per CPU through those
byte filters. The workers decode the candidates at most 64 functions ahead
of the loading thread, which patches them in address order as before.
Patching a function writes only inside it and into the module's
trampolines. A function whose jump table lies outside its own bytes, where
an earlier function's patch may write, is decoded again on the loading
thread at its turn, so every decode sees the bytes a single-threaded pass
sees. Function and instruction counters, which only the red-zone report
prints, no longer count the skipped functions' instructions. With red-zone
protection every function is still decoded, on the workers.

The same change in a Jetsku-based build patches the eboot by 1.9-2.0 s after
launch instead of ~10 s, with identical patched code and trampolines (hash)
and counts (VRSQRTPS: native=10935, trapped=43).
guest_instruction_patch_scan_tests checks the filters on the rewritten
encodings and on similar ones that are not rewritten. It compares code,
trampolines and counters with a single-threaded pass at 2, 5 and 16 threads.
The modes are AMD only, AMD with RDTSC, RDTSC only, and red-zone protection.
The fixture includes a switch whose jump table lies in the next function.

Signed-off-by: Jonathan Goyvaerts <[email protected]>
Assisted-by: LLM
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:17:36 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-13 19:17 UTC · original · edited 2026-11-13 19:35 UTC

Explain Change →

Walkthrough

The patcher adds an AMD-instruction byte filter and a configurable scan-thread count. It scans function candidates serially or in parallel, then decodes and patches candidates in address order. It tracks jump-table reads outside a function and re-analyzes affected functions before patching. New tests compare patched code, trampolines, and counters across thread counts and patching configurations.

Suggested reviewers: nmzik, thecruz

Change: Refactor

Merge Risk: Moderate · up to 6f0a8

The faster parallel patching at load time should reduce load times. An unsynchronized read of another function's bytes during jump-table resolution may still overlap with patch writes. Resolve or explicitly accept that race before merging. The red-zone test fixture should also be strengthened so it actually exercises a protected memory rewrite.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: the loader now patches a module's functions faster at load time. The changeset adds parallel scanning for modules with at least 1,024 functions, and the objectives des…
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.
Description check Passed The description states the purpose of the change: faster AMD instruction patching at load through parallel byte-filter scanning for modules with at least 1024 functions. It lists the rewritten instruc…
Full details: Title check

Explanation

The title names the main change: the loader now patches a module's functions faster at load time. The changeset adds parallel scanning for modules with at least 1,024 functions, and the objectives describe the same goal. The title is specific and accurate.

Full details: Description check

Explanation

The description states the purpose of the change: faster AMD instruction patching at load through parallel byte-filter scanning for modules with at least 1024 functions. It lists the rewritten instruction forms, the 64-candidate decode window, the in-order patching on the loading thread, the performance measurements (Astro Bot, about 7-9 s to 1-2 s), and the new guest_instruction_patch_scan_tests with its configurations. This matches the raw summary of CMakeLists.txt, guestInstructionPatcher.cpp/.h, and the new test file. The description is related to the changeset and is not off-topic.

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-13 19:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2260#issuecomment-6862574539) · edited 2026-11-13 19:35 UTC <!-- coderabbit-ai-generated:v1 --> <!-- 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/2260?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg" alt="Explain Change →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary><strong>Walkthrough</strong></summary> <dl> <dd> <br> The patcher adds an AMD-instruction byte filter and a configurable scan-thread count. It scans function candidates serially or in parallel, then decodes and patches candidates in address order. It tracks jump-table reads outside a function and re-analyzes affected functions before patching. New tests compare patched code, trampolines, and counters across thread counts and patching configurations. **Suggested reviewers:** `nmzik`, `thecruz` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> <!-- change_assessment_commit:"6f0a88fc2c0e9ea646ac7d2b87089192b1ae89d3" --> <!-- change_assessment_priority:{"version":1,"urgency":"p2","manual":false} --> **Change:** Refactor <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/risk-normal-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Moderate</strong> · up to <code>6f0a8</code></summary> <dl> <dd> <br> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🟡 Moderate** · up to `6f0a8` --> <!-- final_review_risk_coverage:{"sourceCommitId":"6f0a88fc2c0e9ea646ac7d2b87089192b1ae89d3","coveredCommitId":"6f0a88fc2c0e9ea646ac7d2b87089192b1ae89d3","kind":"reviewed"} --> The faster parallel patching at load time should reduce load times. An unsynchronized read of another function's bytes during jump-table resolution may still overlap with patch writes. Resolve or explicitly accept that race before merging. The red-zone test fixture should also be strengthened so it actually exercises a protected memory rewrite. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4</strong></summary> <dl> <dd> <br> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title names the main change: the loader now patches a module's functions faster at load time. The changeset adds parallel scanning for modules with at least 1,024 functions, and the objectives des… | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description states the purpose of the change: faster AMD instruction patching at load through parallel byte-filter scanning for modules with at least 1024 functions. It lists the rewritten instruc… | <details> <summary><strong>Full details: Title check</strong></summary> <dl> <dd> <br> **Explanation** The title names the main change: the loader now patches a module's functions faster at load time. The changeset adds parallel scanning for modules with at least 1,024 functions, and the objectives describe the same goal. The title is specific and accurate. </dd> </dl> </details> <details> <summary><strong>Full details: Description check</strong></summary> <dl> <dd> <br> **Explanation** The description states the purpose of the change: faster AMD instruction patching at load through parallel byte-filter scanning for modules with at least 1024 functions. It lists the rewritten instruction forms, the 64-candidate decode window, the in-order patching on the loading thread, the performance measurements (Astro Bot, about 7-9 s to 1-2 s), and the new guest_instruction_patch_scan_tests with its configurations. This matches the raw summary of CMakeLists.txt, guestInstructionPatcher.cpp/.h, and the new test file. The description is related to the changeset and is not off-topic. </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=2260)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>Share</strong></summary> <dl> <dd> <br> - [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) </dd> </dl> </details> <!-- tips_end -->
@ -1604,0 +1809,4 @@
auto function = std::make_unique<DecodedSites>();
function->worker = worker;
analyze(candidates[candidate_index], function->counts, function->function,
function->rewrite_sites);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-13 19:17 UTC · original · edited 2026-11-13 19:37 UTC

Major · Stability & Availability · Heavy lift

Keep jump-table probes away from bytes that the patch pipeline can rewrite.

ResolveBoundedJumpTable reads each table candidate across the whole segment. The read is bounded only by the segment, not the function. A candidate can point into another function. The worker that decodes that function can run up to 64 functions ahead of the loading thread. The loading thread can rewrite those bytes in the meantime. decoded_mutex protects only the pipeline state, not the guest bytes.

A probe that reads rewritten bytes races with the write. The probe can also see different bytes from the single-threaded pass, which has already patched them. The resolved targets, and therefore the decoded instructions and rewrite set, can then differ from run to run. The comment at lines 1702-1705 assumes that scan and decode see the same bytes. These probe reads break that assumption.

Decide how the probe handles bytes that another function's rewrite can change. Either limit the probe to bytes that no rewrite can change, or make the decode of such a candidate wait until the function that owns those bytes is patched. Both options change which tables resolve or how the workers are scheduled, so the chosen option needs a decision.

Source: Learnings

**@⁠coderabbitai[bot]** on GitHub · 2026-11-13 19:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2260#discussion_r4567573172) · edited 2026-11-13 19:37 UTC <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** **Keep jump-table probes away from bytes that the patch pipeline can rewrite.** `ResolveBoundedJumpTable` reads each table candidate across the whole segment. The read is bounded only by the segment, not the function. A candidate can point into another function. The worker that decodes that function can run up to 64 functions ahead of the loading thread. The loading thread can rewrite those bytes in the meantime. `decoded_mutex` protects only the pipeline state, not the guest bytes. A probe that reads rewritten bytes races with the write. The probe can also see different bytes from the single-threaded pass, which has already patched them. The resolved targets, and therefore the decoded instructions and rewrite set, can then differ from run to run. The comment at lines 1702-1705 assumes that scan and decode see the same bytes. These probe reads break that assumption. Decide how the probe handles bytes that another function's rewrite can change. Either limit the probe to bytes that no rewrite can change, or make the decode of such a candidate wait until the function that owns those bytes is patched. Both options change which tables resolve or how the workers are scheduled, so the chosen option needs a decision. <!-- fingerprinting:phantom:medusa:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:0d71eb2c757ee414cba7e278 --> _Source: Learnings_ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-13 19:17 UTC · original · reviewed

Actionable comments posted: 1

Nitpick comments: 1

tests/GuestInstructionPatchScanTests.cpp: 1

76-77: Trivial · Maintainability & Code Quality · Quick win

Exercise the protection-enabled parallel scan.

Every run passes protect_memory=false. The tests therefore do not exercise the new branch that analyzes all functions, merges counts for functions without rewrite sites, and decodes retained candidates again.

Add a protect_memory=true mode. Include functions with live-red-zone memory accesses and functions without rewrite sites. Compare code, trampolines, and counters against the serial run.

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 58ca8d1d7f and 91ea604becb3d0103172621beb63ea6ebe35cae2.

Files selected for processing: 4

  • CMakeLists.txt
  • src/loader/guestInstructionPatcher.cpp
  • src/loader/guestInstructionPatcher.h
  • tests/GuestInstructionPatchScanTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-13 19:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2260#pullrequestreview-5896693464) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 1** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning.svg" width="16" height="16" align="absmiddle" alt=""></picture> Nitpick comments: 1</summary><blockquote> <dl> <dd> <br> <details> <summary>tests/GuestInstructionPatchScanTests.cpp: 1</summary><blockquote> <dl> <dd> <br> `76-77`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Maintainability & Code Quality** · **Quick win** **Exercise the protection-enabled parallel scan.** Every run passes `protect_memory=false`. The tests therefore do not exercise the new branch that analyzes all functions, merges counts for functions without rewrite sites, and decodes retained candidates again. Add a `protect_memory=true` mode. Include functions with live-red-zone memory accesses and functions without rewrite sites. Compare code, trampolines, and counters against the serial run. <!-- cr-comment:v1:e17b45001baf3bf55b830f0a --> </dd> </dl> </blockquote></details> </dd> </dl> </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/58ca8d1d7fd621196a60c0a2bda664f4672815d7/.coderabbit.yaml>) - **Commit**: [58ca8d1](<https://github.com/KytyPS5/KytyPS5/commit/58ca8d1d7fd621196a60c0a2bda664f4672815d7>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `99054c7e-98c0-47b9-b036-cda7a2f68fc7` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 58ca8d1d7fd621196a60c0a2bda664f4672815d7 and 91ea604becb3d0103172621beb63ea6ebe35cae2. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 4</summary> <dl> <dd> <br> * `CMakeLists.txt` * `src/loader/guestInstructionPatcher.cpp` * `src/loader/guestInstructionPatcher.h` * `tests/GuestInstructionPatchScanTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=66a45bc9-6adc-499d-ab05-b9a7450d1f8c attempt=8f073295-c890-4c63-bd62-ed9013f53c46 batch=1/1 -->
@ -1604,0 +1809,4 @@
auto function = std::make_unique<DecodedSites>();
function->worker = worker;
analyze(candidates[candidate_index], function->counts, function->function,
function->rewrite_sites);
Author
Owner

@⁠jgoyvaerts on GitHub · 2026-11-13 19:28 UTC · original

Agreed, fixed in 6f0a88fc. DecodeFunction now marks a function whose jump-table read leaves its own bytes (reads_outside_function). The loading thread decodes such a function again at its turn, so it sees exactly the bytes a single-threaded pass sees; with red-zone protection the scan keeps it as a candidate instead of trusting the early decode. The test fixture adds a switch whose table lies in the next function and whose VRSQRTPS is reachable only through the table; dropping the re-decode's patch fails 27 checks.

**@⁠jgoyvaerts** on GitHub · 2026-11-13 19:28 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2260#discussion_r4567689895) Agreed, fixed in 6f0a88fc. `DecodeFunction` now marks a function whose jump-table read leaves its own bytes (`reads_outside_function`). The loading thread decodes such a function again at its turn, so it sees exactly the bytes a single-threaded pass sees; with red-zone protection the scan keeps it as a candidate instead of trusting the early decode. The test fixture adds a switch whose table lies in the next function and whose VRSQRTPS is reachable only through the table; dropping the re-decode's patch fails 27 checks.
Author
Owner

@⁠jgoyvaerts on GitHub · 2026-11-13 19:29 UTC · original

Nitpick addressed in 6f0a88fc: guest_instruction_patch_scan_tests adds a red-zone protection mode (protect_memory=true) with a function that stores and loads in the red zone. It compares code, trampolines and counters with the serial pass at 2, 5 and 16 threads.

**@⁠jgoyvaerts** on GitHub · 2026-11-13 19:29 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2260#issuecomment-6862820962) Nitpick addressed in 6f0a88fc: `guest_instruction_patch_scan_tests` adds a red-zone protection mode (`protect_memory=true`) with a function that stores and loads in the red zone. It compares code, trampolines and counters with the serial pass at 2, 5 and 16 threads.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-13 19:33 UTC · original · reviewed

Nitpick comments: 1

tests/GuestInstructionPatchScanTests.cpp: 1

74-76: Trivial · Maintainability & Code Quality · Quick win

Add a non-stack memory access to the red-zone fixture.

Both memory operands in red_zone_body use rsp. DecodeCodeInstruction sets accesses_memory only for non-stack-relative operands. CollectRedZoneMemoryInstructions skips instructions without accesses_memory, so neither mov is selected. With protect_memory=true, this function adds nothing to patched_memory_instruction_count. The serial and parallel comparisons can still match when memory-rewrite generation is broken. No assertion checks a nonzero count.

Add a non-stack store between the stack store and the load. The [rsp - 8] slot stays live across that store, so the store is selected for red-zone protection. Keep the body within FunctionSize. Then assert that the serial result reports a nonzero patched_memory_instruction_count in red-zone mode.

Suggested fix

 	const std::vector<uint8_t> red_zone_body {0x48, 0x89, 0x44, 0x24, 0xf8,   // mov [rsp - 8], rax
+	                                          0x48, 0x89, 0x08,               // mov [rax], rcx
 	                                          0x48, 0x8b, 0x4c, 0x24, 0xf8,   // mov rcx, [rsp - 8]
 	                                          0xc3};                          // ret
 		if (protect_memory) {
 			Check(serial.result.red_zone_function_count != 0, "the red-zone function is analyzed");
+			Check(serial.result.patched_memory_instruction_count != 0,
+			      "the red-zone memory rewrite is generated");
Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 91ea604becb3d0103172621beb63ea6ebe35cae2 and 6f0a88fc2c.

Files selected for processing: 2

  • src/loader/guestInstructionPatcher.cpp
  • tests/GuestInstructionPatchScanTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-13 19:33 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2260#pullrequestreview-5896901332) · **reviewed** <!-- coderabbit-ai-generated:v1 --> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning.svg" width="16" height="16" align="absmiddle" alt=""></picture> Nitpick comments: 1</summary><blockquote> <dl> <dd> <br> <details> <summary>tests/GuestInstructionPatchScanTests.cpp: 1</summary><blockquote> <dl> <dd> <br> `74-76`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Maintainability & Code Quality** · **Quick win** **Add a non-stack memory access to the red-zone fixture.** Both memory operands in `red_zone_body` use `rsp`. `DecodeCodeInstruction` sets `accesses_memory` only for non-stack-relative operands. `CollectRedZoneMemoryInstructions` skips instructions without `accesses_memory`, so neither `mov` is selected. With `protect_memory=true`, this function adds nothing to `patched_memory_instruction_count`. The serial and parallel comparisons can still match when memory-rewrite generation is broken. No assertion checks a nonzero count. Add a non-stack store between the stack store and the load. The `[rsp - 8]` slot stays live across that store, so the store is selected for red-zone protection. Keep the body within `FunctionSize`. Then assert that the serial result reports a nonzero `patched_memory_instruction_count` in red-zone mode. <details> <summary>Suggested fix</summary> <dl> <dd> <br> ```diff const std::vector<uint8_t> red_zone_body {0x48, 0x89, 0x44, 0x24, 0xf8, // mov [rsp - 8], rax + 0x48, 0x89, 0x08, // mov [rax], rcx 0x48, 0x8b, 0x4c, 0x24, 0xf8, // mov rcx, [rsp - 8] 0xc3}; // ret ``` ```diff if (protect_memory) { Check(serial.result.red_zone_function_count != 0, "the red-zone function is analyzed"); + Check(serial.result.patched_memory_instruction_count != 0, + "the red-zone memory rewrite is generated"); ``` </dd> </dl> </details> <!-- cr-comment:v1:6f76123e84d88e8a9a7ab984 --> </dd> </dl> </blockquote></details> </dd> </dl> </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/58ca8d1d7fd621196a60c0a2bda664f4672815d7/.coderabbit.yaml>) - **Commit**: [58ca8d1](<https://github.com/KytyPS5/KytyPS5/commit/58ca8d1d7fd621196a60c0a2bda664f4672815d7>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `db7cced1-697a-4f35-b048-d4b3203133a3` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 91ea604becb3d0103172621beb63ea6ebe35cae2 and 6f0a88fc2c0e9ea646ac7d2b87089192b1ae89d3. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 2</summary> <dl> <dd> <br> * `src/loader/guestInstructionPatcher.cpp` * `tests/GuestInstructionPatchScanTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=0ddbe900-368f-4e99-aa1d-af764b1a9487 attempt=2086a16b-46b6-44ea-bb15-63f36a56d137 batch=1/1 -->
@ -1604,0 +1809,4 @@
auto function = std::make_unique<DecodedSites>();
function->worker = worker;
analyze(candidates[candidate_index], function->counts, function->function,
function->rewrite_sites);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-13 19:38 UTC · original

Analysis chain

Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- Current revision ---'
git rev-parse HEAD
printf '%s\n' '--- Repository guidance filenames ---'
fd -H -t f '(^|/)(AGENTS\.md|CLAUDE\.md)$' . -E .git 2>/dev/null || true
printf '%s\n' '--- Patcher outline ---'
ast-grep outline src/loader/guestInstructionPatcher.cpp --items all --match 'ResolveBoundedJumpTable|DecodeFunction|PatchGuestInstructions' 2>/dev/null || true
printf '%s\n' '--- Jump table and pipeline references ---'
rg -n -C 5 'reads_outside_function|memcpy\(&offset|analyze\(candidates\[candidate_index\]|patch\(function->function|patch\(again|decoded_mutex|std::unique_lock lock \{module->mutex\}' src/loader/guestInstructionPatcher.cpp
printf '%s\n' '--- Test outline and table references ---'
ast-grep outline tests/GuestInstructionPatchScanTests.cpp --items all 2>/dev/null || true
rg -n -C 5 'jump.table|switch|table|VRSQRTPS|reads_outside|threads' tests/GuestInstructionPatchScanTests.cpp || true

Length of output: 15594


@jgoyvaerts Thanks for the change. The ordered re-decode addresses stale results, but the original data race remains.

At Line 491, a worker still reads an external table before the loading thread checks reads_outside_function. If that table points into an earlier function while the loading thread patches those bytes, the read and write can overlap. A later re-decode cannot undo that race.

Please defer external table reads until the loading thread handles the candidate, or synchronize those reads with patch writes. The new fixture places the table in the next function; it does not cover this earlier-function overlap. A regression test under ThreadSanitizer would help check it.

I’m not marking the finding as addressed.


📝 Learnings were not changed: only organization members or users with write access to this repository can add or remove learnings.


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

Thank you for using CodeRabbit!

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-13 19:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2260#discussion_r4567789145) <!-- coderabbit-ai-generated:v1 --> <details> <summary>Analysis chain</summary> <dl> <dd> <br> Script executed: ```shell #!/bin/bash set -u printf '%s\n' '--- Current revision ---' git rev-parse HEAD printf '%s\n' '--- Repository guidance filenames ---' fd -H -t f '(^|/)(AGENTS\.md|CLAUDE\.md)$' . -E .git 2>/dev/null || true printf '%s\n' '--- Patcher outline ---' ast-grep outline src/loader/guestInstructionPatcher.cpp --items all --match 'ResolveBoundedJumpTable|DecodeFunction|PatchGuestInstructions' 2>/dev/null || true printf '%s\n' '--- Jump table and pipeline references ---' rg -n -C 5 'reads_outside_function|memcpy\(&offset|analyze\(candidates\[candidate_index\]|patch\(function->function|patch\(again|decoded_mutex|std::unique_lock lock \{module->mutex\}' src/loader/guestInstructionPatcher.cpp printf '%s\n' '--- Test outline and table references ---' ast-grep outline tests/GuestInstructionPatchScanTests.cpp --items all 2>/dev/null || true rg -n -C 5 'jump.table|switch|table|VRSQRTPS|reads_outside|threads' tests/GuestInstructionPatchScanTests.cpp || true ``` Length of output: 15594 --- </dd> </dl> </details> `@jgoyvaerts` Thanks for the change. The ordered re-decode addresses stale results, but the original data race remains. At Line 491, a worker still reads an external table before the loading thread checks `reads_outside_function`. If that table points into an earlier function while the loading thread patches those bytes, the read and write can overlap. A later re-decode cannot undo that race. Please defer external table reads until the loading thread handles the candidate, or synchronize those reads with patch writes. The new fixture places the table in the next function; it does not cover this earlier-function overlap. A regression test under ThreadSanitizer would help check it. I’m not marking the finding as addressed. --- > 📝 Learnings were not changed: only organization members or users with write access to this repository can add or remove learnings. --- <!-- 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=Jump-table%20probes%20can%20race%20with%20rewrites%2C%20making%20decoding%20nondeterministic.%20%40coderabbitai%20caught%20it%3A%20re-decode%20cross-function%20reads%20at%20the%20right%20turn%20for%20stable%20patches.%20Try%20it!%20%F0%9F%9B%A0%EF%B8%8F&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F2260%23discussion_r4567573172)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/2260/head:github-bot/gh-2260'
git switch 'github-bot/gh-2260'

Merge

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