Apply the AMD CPU patches automatically on hosts that lack the instructions #1439

Closed
github-bot wants to merge 5 commits from gh-pr/1439/head into gh-pr/1439/base
Owner

@⁠wuboo on GitHub · 2026-10-12 06:54 UTC · original
wuboo:pr/amd-cpu-auto → main · +1148 −30 · 15 files · 5 commits · closed without merging

Problem

The guest is built for an AMD CPU and uses SSE4a (EXTRQ/INSERTQ), and sometimes RDPID / CLWB.
Since 77680ce9 ("Make AMD CPU patch optional") the instruction patcher is off unless --amd-cpu is
given. On a host without those instructions every one of them then raises SIGILL and is emulated in
the signal handler. macOS under Rosetta 2 reports an Intel CPU without SSE4a, so on a Mac the default
run takes about 9,400 signals per frame in the scene measured below, and every one is a trap plus a
handler round trip. Nobody gets the patcher unless they know to ask for it, and in the launcher the
checkbox is hidden on macOS.

What this does

  • The setting becomes three-state: auto (default), on, off.
    • auto patches only when CPUID shows that the host lacks SSE4a, RDPID or CLWB. On a host that has
      all three nothing changes from today (patcher off). The decision and its reason are logged once
      ("AMD CPU compatibility: patching on (auto: host lacks SSE4a), kinds=sse4a").
    • --amd-cpu = on, new --no-amd-cpu = off, KYTY_AMD_CPU=auto|0|1 from the environment
      (a command line flag wins over the variable; an unparsable value is auto).
  • Which instruction groups are rewritten. KYTY_AMD_PATCH=all|none|sse4a,rsqrt,cpuext.
    In auto the default is sse4a only; --amd-cpu (on) still rewrites everything, as before.
    • VRSQRTPS (rsqrt) is opt-in. On Rosetta the patch leaves about 1,080 call sites that still
      trap (+551 SIGILL per frame measured), it measures slower than the native rsqrtps Rosetta
      translates, and its result is an exact reciprocal square root where AMD hardware returns the
      hardware approximation, so it is not a drop-in replacement.
    • RDPID / CLWB (cpuext) are opt-in as well.
  • Launcher. The checkbox is tri-state (checked = on, unchecked = off, partially checked = auto) and
    is saved as amd_cpu_mode. A stored amd_cpu_mode wins. An older amd_cpu_enabled = true maps to
    on; an older amd_cpu_enabled = false maps to auto, not off, because the old default false was
    written for every configuration whether or not the user ever touched the checkbox, so it records no
    choice. A missing key is auto. The checkbox is no longer hidden on macOS.

The decision logic, the parsing and the launcher mapping are header-only (src/common/amdCpuMode.h)
so they can be tested without Qt or a guest.

Measurements

On macOS (Apple silicon, Rosetta 2), the same build, the level scene of one game, patcher off vs auto:

before (off) after (auto = sse4a)
frame time about 185 - 199 ms per flip about 110 - 117 ms per flip
SIGILL handled per frame about 9,400 86

The level renders the same as a reference capture in both modes (checked on 8 runs with auto).
These are numbers from a local stack that carries other work as well; the patcher code is the same.

Tests

  • amd_cpu_mode (CPU, no guest): auto against injected CPUID results (each of SSE4a, RDPID, CLWB
    missing on its own), flag / variable precedence, parsing, KYTY_AMD_PATCH parsing and the per-mode
    defaults, mapping of stored launcher settings. 14 mutants (built at configure time) (the header is copied with one
    edit into the build tree, so the sources carry no test hooks), each must fail the test.
  • amd_trampoline_bitexact (macOS x86-64 only, like macos_sse4a): about 3.7M EXTRQ / INSERTQ
    inputs (immediate and register forms, REX registers, source == destination) against a bit-by-bit
    model of the AMD APM, state preservation of the EXTRQ trampoline (upper YMM, rax/rcx/rdx, CF, red
    zone), VRSQRTPS against the signal emulator, the host rsqrtps and an exact long double, and the
    selection of kinds. 19 mutants of the patcher and the emulator are rejected.
  • Full ctest unchanged against main (tests that need a Vulkan loader skip without one).

Not tested / limits

  • The launcher was not built locally (no Qt on the machine that produced this branch). The change
    there is small (configuration.{h,cpp}, configurationEditDialog.cpp, mainDialog.cpp, the .ui
    tooltip and label) and the mapping logic is in the tested header, but the Qt code has only been
    read, not compiled; the CI launcher builds on Windows, macOS and Linux will be its first compile.
  • The patcher has only been exercised in a game on macOS / Rosetta. On Windows and Linux the same
    auto rule applies: an Intel host without SSE4a now gets the patcher by default (before: off, traps
    emulated by the signal / exception handler). AMD hosts with SSE4a, RDPID and CLWB are unaffected.
  • SetGameSettings (the launcher's key-value interface) no longer knows the key amd_cpu_enabled;
    amd_cpu_mode replaces it. Stored settings of the old key are still read.
  • amd_cpu_mode_tests is built on every platform but, like the other tests, only runs where ctest is
    asked to; the CI test lists are unchanged.
**@⁠wuboo** on GitHub · 2026-10-12 06:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1439) `wuboo:pr/amd-cpu-auto` → `main` · +1148 −30 · 15 files · 5 commits · closed without merging ## Problem The guest is built for an AMD CPU and uses SSE4a (`EXTRQ`/`INSERTQ`), and sometimes `RDPID` / `CLWB`. Since 77680ce9 ("Make AMD CPU patch optional") the instruction patcher is off unless `--amd-cpu` is given. On a host without those instructions every one of them then raises `SIGILL` and is emulated in the signal handler. macOS under Rosetta 2 reports an Intel CPU without SSE4a, so on a Mac the default run takes about 9,400 signals per frame in the scene measured below, and every one is a trap plus a handler round trip. Nobody gets the patcher unless they know to ask for it, and in the launcher the checkbox is hidden on macOS. ## What this does - The setting becomes three-state: **auto** (default), **on**, **off**. - auto patches only when CPUID shows that the host lacks SSE4a, RDPID or CLWB. On a host that has all three nothing changes from today (patcher off). The decision and its reason are logged once ("AMD CPU compatibility: patching on (auto: host lacks SSE4a), kinds=sse4a"). - `--amd-cpu` = on, new `--no-amd-cpu` = off, `KYTY_AMD_CPU=auto|0|1` from the environment (a command line flag wins over the variable; an unparsable value is auto). - **Which instruction groups are rewritten.** `KYTY_AMD_PATCH=all|none|sse4a,rsqrt,cpuext`. In auto the default is **`sse4a` only**; `--amd-cpu` (on) still rewrites everything, as before. - `VRSQRTPS` (`rsqrt`) is opt-in. On Rosetta the patch leaves about 1,080 call sites that still trap (+551 `SIGILL` per frame measured), it measures slower than the native `rsqrtps` Rosetta translates, and its result is an exact reciprocal square root where AMD hardware returns the hardware approximation, so it is not a drop-in replacement. - `RDPID` / `CLWB` (`cpuext`) are opt-in as well. - **Launcher.** The checkbox is tri-state (checked = on, unchecked = off, partially checked = auto) and is saved as `amd_cpu_mode`. A stored `amd_cpu_mode` wins. An older `amd_cpu_enabled = true` maps to on; an older `amd_cpu_enabled = false` maps to **auto**, not off, because the old default `false` was written for every configuration whether or not the user ever touched the checkbox, so it records no choice. A missing key is auto. The checkbox is no longer hidden on macOS. The decision logic, the parsing and the launcher mapping are header-only (`src/common/amdCpuMode.h`) so they can be tested without Qt or a guest. ## Measurements On macOS (Apple silicon, Rosetta 2), the same build, the level scene of one game, patcher off vs auto: | | before (off) | after (auto = sse4a) | |---|---|---| | frame time | about 185 - 199 ms per flip | about 110 - 117 ms per flip | | `SIGILL` handled per frame | about 9,400 | 86 | The level renders the same as a reference capture in both modes (checked on 8 runs with auto). These are numbers from a local stack that carries other work as well; the patcher code is the same. ## Tests - `amd_cpu_mode` (CPU, no guest): auto against injected CPUID results (each of SSE4a, RDPID, CLWB missing on its own), flag / variable precedence, parsing, `KYTY_AMD_PATCH` parsing and the per-mode defaults, mapping of stored launcher settings. 14 mutants (built at configure time) (the header is copied with one edit into the build tree, so the sources carry no test hooks), each must fail the test. - `amd_trampoline_bitexact` (macOS x86-64 only, like `macos_sse4a`): about 3.7M `EXTRQ` / `INSERTQ` inputs (immediate and register forms, REX registers, source == destination) against a bit-by-bit model of the AMD APM, state preservation of the `EXTRQ` trampoline (upper YMM, rax/rcx/rdx, CF, red zone), `VRSQRTPS` against the signal emulator, the host `rsqrtps` and an exact `long double`, and the selection of kinds. 19 mutants of the patcher and the emulator are rejected. - Full `ctest` unchanged against `main` (tests that need a Vulkan loader skip without one). ## Not tested / limits - **The launcher was not built locally** (no Qt on the machine that produced this branch). The change there is small (`configuration.{h,cpp}`, `configurationEditDialog.cpp`, `mainDialog.cpp`, the `.ui` tooltip and label) and the mapping logic is in the tested header, but the Qt code has only been read, not compiled; the CI launcher builds on Windows, macOS and Linux will be its first compile. - The patcher has only been exercised in a game on macOS / Rosetta. On Windows and Linux the same auto rule applies: an Intel host without SSE4a now gets the patcher by default (before: off, traps emulated by the signal / exception handler). AMD hosts with SSE4a, RDPID and CLWB are unaffected. - `SetGameSettings` (the launcher's key-value interface) no longer knows the key `amd_cpu_enabled`; `amd_cpu_mode` replaces it. Stored settings of the old key are still read. - `amd_cpu_mode_tests` is built on every platform but, like the other tests, only runs where ctest is asked to; the CI test lists are unchanged.
Since "Make AMD CPU patch optional" the patcher is off by default. On a host
without SSE4a (macOS/Rosetta reports an Intel CPU) every EXTRQ/INSERTQ of the
guest then raises SIGILL and is emulated in the signal handler: about 9400
signals per frame in a measured scene. --amd-cpu made that scene about 1.5x
faster (0.60-0.73 frame-time ratio, patched over unpatched).

Make the setting three-state: auto (default), on, off.
- auto patches only when CPUID shows the host lacks SSE4a, RDPID or CLWB
  and logs the decision with the reason; on = --amd-cpu, off = --no-amd-cpu.
- KYTY_AMD_CPU=auto|0|1 does the same from the environment; a command line
  flag wins over it.
- Launcher: the checkbox is tri-state, saved as amd_cpu_mode. A stored
  amd_cpu_mode wins. An older amd_cpu_enabled=true maps to on, but an older
  amd_cpu_enabled=false maps to auto, not off: the old default false was
  written for every configuration whether or not the user ever touched the
  checkbox, so it records no choice. A missing key is auto.

The decision logic and the launcher mapping are header-only and covered by
amd_cpu_mode_tests (injected CPUID results, flag/env parsing, precedence,
stored-setting mapping) with nine mutants.
The patcher rewrites three groups: sse4a (EXTRQ/INSERTQ), rsqrt (VRSQRTPS)
and cpuext (RDPID/CLWB). KYTY_AMD_PATCH selects them: all, none, or a comma
list. An unset or unparsable value keeps the default of the mode:
- auto (default) rewrites sse4a only;
- --amd-cpu (on) rewrites everything, as before.

VRSQRTPS and RDPID/CLWB are therefore opt-in in auto. On Rosetta the VRSQRTPS
patch leaves about 1079 call sites that still trap (+551 SIGILL per frame) and
measures slower than the native rsqrtps Rosetta translates; its result is an
exact reciprocal square root where AMD hardware gives the approximation, so
it is not a drop-in replacement.

The patcher takes the kinds mask and the loader logs it with the patching
decision ("AMD CPU compatibility: patching on (...), kinds=sse4a").

amd_trampoline_bitexact_tests runs the patched code on the CPU: ~3.7M EXTRQ
and INSERTQ inputs (immediate and register forms, REX registers, source ==
destination) against a bit-by-bit model of the AMD APM, EXTRQ state
preservation (upper YMM, rax/rcx/rdx, CF, red zone), VRSQRTPS against the
signal emulator, the host rsqrtps and an exact long double, and the kind
selection. 19 mutants of the patcher and the emulator are rejected, plus 5
mutants of the parsing and defaults in amd_cpu_mode_tests.
Auto turned the patcher on whenever the host lacked SSE4a, RDPID or CLWB, although
the default auto kinds only rewrite SSE4a. A host with SSE4a but without CLWB paid
for the trampoline area and the decode of every function and rewrote nothing. The
decision now looks only at the instructions the selected kinds rewrite.

On Windows auto stays off: an unrelocatable EXTRQ/INSERTQ with a live red zone
exits there instead of falling back to the trap handler, which would be a
regression for Intel hosts. An explicit --amd-cpu still patches.

Tests: amd_cpu_mode with mutants kinds_sse4a_ignored, kinds_cpuext_ignored and
auto_allowed_ignored.
GameSettings() exports only amd_cpu_mode, so SetGameSettings rejected older
exports that still carry amd_cpu_enabled as an unknown setting before the
existing legacy mapping could run. The key is now accepted and not compared with
the canonical values; without amd_cpu_mode in the import it decides the mode
(true -> on, false -> auto).
The legacy key was skipped in the canonical comparison, so any string was read as
true. Parse it with ParseLegacyAmdCpuEnabled and accept only "true" and "false".
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:56:44 +00:00
github-bot closed this pull request 2026-11-26 09:56:44 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-12 07:01 UTC · original · edited 2026-10-12 13:58 UTC

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: fe4ef0bf-b487-40bf-a209-1f6309dfe0a5

📥 Commits

Reviewing files that changed from the base of the PR and between 30c4cba442 and 97660188db.


📒 Files selected for processing (4)
  • CMakeLists.txt
  • src/common/amdCpuMode.h
  • src/launcher/src/configuration.cpp
  • tests/AmdCpuModeTests.cpp

🚧 Files skipped from review as they are similar to previous changes (4)
  • tests/AmdCpuModeTests.cpp
  • src/launcher/src/configuration.cpp
  • CMakeLists.txt
  • src/common/amdCpuMode.h

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



📝 Walkthrough

Walkthrough

The change adds automatic, forced-on, and forced-off AMD CPU modes, with patch-kind selection from configuration or environment variables. The launcher stores and displays the mode and passes the corresponding command-line option. Runtime loading evaluates host CPU features and passes the selected patch kinds to the guest instruction patcher. New tests cover mode resolution, patch selection, instruction behavior, trampoline state, and VRSQRTPS results.


Priority: ➖ Normal

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 97660

The reviewed mode and patch-selection paths show no actionable merge-blocking issue; normal build and test checks remain appropriate.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 24.24% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 66 functions across 13 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check Passed The description clearly explains the AMD CPU patching changes, configuration modes, launcher updates, performance measurements, tests, and known limitations.
Title check Passed The title clearly summarizes the primary change: AMD CPU patches now apply automatically when required instructions are unavailable.
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.

Full details: Docstring Coverage

Explanation

Docstring coverage is 24.24% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 66 functions across 13 files. (1 skipped: 1 unsupported.)


  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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-12 07:01 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1439#issuecomment-6119385156) · edited 2026-10-12 13:58 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/1439?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-in-coderabbit-ui-dark.svg?v=3"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3" alt="Review in Change Stack →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary><strong>ℹ️ Recent review info</strong></summary> <dl> <dd> <details> <summary><strong>⚙️ Run configuration</strong></summary> <dl> <dd> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `fe4ef0bf-b487-40bf-a209-1f6309dfe0a5` <hr> </dd> </dl> </details> <details> <summary><strong>📥 Commits</strong></summary> <dl> <dd> Reviewing files that changed from the base of the PR and between 30c4cba4427636f2c69365c5b63a7c8166a6fe0a and 97660188dbd25806d9fdc5b9e0705ab2f050e0e9. <hr> </dd> </dl> </details> <details> <summary><strong>📒 Files selected for processing (4)</strong></summary> <dl> <dd> * `CMakeLists.txt` * `src/common/amdCpuMode.h` * `src/launcher/src/configuration.cpp` * `tests/AmdCpuModeTests.cpp` <hr> </dd> </dl> </details> <details> <summary><strong>🚧 Files skipped from review as they are similar to previous changes (4)</strong></summary> <dl> <dd> * tests/AmdCpuModeTests.cpp * src/launcher/src/configuration.cpp * CMakeLists.txt * src/common/amdCpuMode.h <hr> </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. <hr> </dd> </dl> </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> ## Walkthrough The change adds automatic, forced-on, and forced-off AMD CPU modes, with patch-kind selection from configuration or environment variables. The launcher stores and displays the mode and passes the corresponding command-line option. Runtime loading evaluates host CPU features and passes the selected patch kinds to the guest instruction patcher. New tests cover mode resolution, patch selection, instruction behavior, trampoline state, and VRSQRTPS results. <hr> </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"97660188dbd25806d9fdc5b9e0705ab2f050e0e9" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** **⚪ Minimal** · up to `97660` <!-- final_review_risk_coverage:{"sourceCommitId":"97660188dbd25806d9fdc5b9e0705ab2f050e0e9","coveredCommitId":"97660188dbd25806d9fdc5b9e0705ab2f050e0e9","kind":"reviewed"} --> The reviewed mode and patch-selection paths show no actionable merge-blocking issue; normal build and test checks remain appropriate. <!-- final_review_risk_end --> <!-- 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-v1.svg" width="14" height="17" align="middle" alt="Passed" title="Passed"></picture></sup> 4 | <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v1.svg" width="14" height="17" align="middle" alt="Failed" title="Failed"></picture></sup> 1</strong></summary> <dl> <dd> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :---------------- | :----------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Warning](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg) | Docstring coverage is 24.24% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 66 functions across 13 files. (1 skipped:… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong>✅ Passed checks (4 passed)</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description clearly explains the AMD CPU patching changes, configuration modes, launcher updates, performance measurements, tests, and known limitations. | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly summarizes the primary change: AMD CPU patches now apply automatically when required instructions are unavailable. | | 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. | <hr> </dd> </dl> </details> <details> <summary><strong>Full details: Docstring Coverage</strong></summary> <dl> <dd> **Explanation** Docstring coverage is 24.24% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 66 functions across 13 files. (1 skipped: 1 unsupported.) </dd> </dl> </details> <hr> </dd> </dl> </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">Autofix</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1439)! 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> - [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) <hr> </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-12 07:01 UTC · original · edited 2026-10-12 10:17 UTC
On src/common/amdCpuMode.h line 78 (outdated):

@@ -0,0 +1,144 @@
+#ifndef EMULATOR_INCLUDE_EMULATOR_COMMON_AMDCPUMODE_H_
+#define EMULATOR_INCLUDE_EMULATOR_COMMON_AMDCPUMODE_H_
+
+#include <cstddef>
+#include <cstdint>
+#include <optional>
+#include <string>
+#include <string_view>
+
+namespace Common {
+
+// The guest is built for an AMD CPU. Without the patcher every SSE4a/RDPID/CLWB instruction the
+// host lacks raises SIGILL and is emulated in a signal handler (about ten thousand signals per
+// frame on Rosetta, which reports an Intel CPU without SSE4a). Auto turns the patcher on only when
+// the host lacks one of them.
+enum class AmdCpuMode { Auto, On, Off };
+
+// Instructions the AMD patcher rewrites, as reported by CPUID of the host.
+struct AmdCpuHostSupport {
+	bool sse4a = false;
+	bool rdpid = false;
+	bool clwb  = false;
+};
+
+struct AmdCpuDecision {
+	bool        enabled = false;
+	std::string reason;
+};
+
+// "auto", "on"/"1"/"true", "off"/"0"/"false"; anything else (including empty) is not a mode.
+inline std::optional<AmdCpuMode> ParseAmdCpuMode(std::string_view text) {
+	if (text == "auto") return AmdCpuMode::Auto;
+	if (text == "on" || text == "1" || text == "true") return AmdCpuMode::On;
+	if (text == "off" || text == "0" || text == "false") return AmdCpuMode::Off;
+	return std::nullopt;
+}
+
+inline const char* AmdCpuModeName(AmdCpuMode mode) {
+	return mode == AmdCpuMode::On ? "on" : mode == AmdCpuMode::Off ? "off" : "auto";
+}
+
+// An explicit command line flag wins over KYTY_AMD_CPU; an unset or unparsable variable leaves
+// auto.
+inline AmdCpuMode ResolveAmdCpuMode(std::optional<AmdCpuMode> command_line, const char* env) {
+	if (command_line) return *command_line;
+	if (env != nullptr) {
+		if (const auto mode = ParseAmdCpuMode(env)) return *mode;
+	}
+	return AmdCpuMode::Auto;
+}
+
+// The launcher setting. A stored amd_cpu_mode wins; the older amd_cpu_enabled bool maps true -> on,
+// but false -> auto: that default was written for every configuration whether or not the user
+// touched the checkbox, so it is no choice to honour. Neither key (or an unparsable mode) is auto.
+inline AmdCpuMode AmdCpuModeFromStored(std::optional<std::string_view> mode,
+                                       std::optional<bool>             legacy_enabled) {
+	if (mode) {
+		if (const auto parsed = ParseAmdCpuMode(*mode)) return *parsed;
+	}
+	if (legacy_enabled && *legacy_enabled) return AmdCpuMode::On;
+	return AmdCpuMode::Auto;
+}
+
+inline AmdCpuDecision DecideAmdCpu(AmdCpuMode mode, AmdCpuHostSupport host) {
+	if (mode == AmdCpuMode::On) return {true, "forced on (--amd-cpu or KYTY_AMD_CPU=1)"};
+	if (mode == AmdCpuMode::Off) return {false, "forced off (--no-amd-cpu or KYTY_AMD_CPU=0)"};
+	std::string missing;
+	const auto  add = [&missing](bool supported, const char* name) {
+		if (supported) return;
+		if (!missing.empty()) missing += ", ";
+		missing += name;
+	};
+	add(host.sse4a, "SSE4a");
+	add(host.rdpid, "RDPID");
+	add(host.clwb, "CLWB");
+	if (missing.empty()) return {false, "auto: host supports SSE4a, RDPID and CLWB"};
+	return {true, "auto: host lacks " + missing};
+}

🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Auto mode enables patching even when the selected patch kinds cannot rewrite anything.

DecideAmdCpu enables the patcher when the host lacks any of SSE4a, RDPID or CLWB. The default patch kinds for auto mode contain only AmdPatchSse4a. Consider a host that supports SSE4a but lacks RDPID or CLWB, such as an older AMD CPU without CLWB. On that host, auto mode turns the patcher on. In CollectAmdInstructions, !host_features.sse4a is false, so no site is collected.

For every module, the loader still allocates the 8 MiB trampoline area and decodes every function. On Windows, analyze_red_zone |= emulate_amd also runs red-zone liveness analysis. The log also says "patching on" even though nothing can change.

Base the auto decision on the resolved patch kinds. Enable patching only when at least one selected kind targets an instruction that the host does not support.

♻️ Proposed change
-inline AmdCpuDecision DecideAmdCpu(AmdCpuMode mode, AmdCpuHostSupport host) {
+inline AmdCpuDecision DecideAmdCpu(AmdCpuMode mode, AmdCpuHostSupport host,
+                                   uint32_t kinds = 0xffffffffu) {
 	...
-	add(host.sse4a, "SSE4a");
-	add(host.rdpid, "RDPID");
-	add(host.clwb, "CLWB");
+	add(host.sse4a || (kinds & AmdPatchSse4a) == 0, "SSE4a");
+	add(host.rdpid || (kinds & AmdPatchCpuExt) == 0, "RDPID");
+	add(host.clwb || (kinds & AmdPatchCpuExt) == 0, "CLWB");

The AmdPatchKind enum must be declared before DecideAmdCpu. runtimeLinker.cpp must pass Config::GetAmdPatchKinds().

✅ Addressed in commits eaa8eca to 30c4cba

**@⁠coderabbitai[bot]** on GitHub · 2026-10-12 07:01 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1439#discussion_r4245402131) · edited 2026-10-12 10:17 UTC On `src/common/amdCpuMode.h` line 78 (outdated): ```diff @@ -0,0 +1,144 @@ +#ifndef EMULATOR_INCLUDE_EMULATOR_COMMON_AMDCPUMODE_H_ +#define EMULATOR_INCLUDE_EMULATOR_COMMON_AMDCPUMODE_H_ + +#include <cstddef> +#include <cstdint> +#include <optional> +#include <string> +#include <string_view> + +namespace Common { + +// The guest is built for an AMD CPU. Without the patcher every SSE4a/RDPID/CLWB instruction the +// host lacks raises SIGILL and is emulated in a signal handler (about ten thousand signals per +// frame on Rosetta, which reports an Intel CPU without SSE4a). Auto turns the patcher on only when +// the host lacks one of them. +enum class AmdCpuMode { Auto, On, Off }; + +// Instructions the AMD patcher rewrites, as reported by CPUID of the host. +struct AmdCpuHostSupport { + bool sse4a = false; + bool rdpid = false; + bool clwb = false; +}; + +struct AmdCpuDecision { + bool enabled = false; + std::string reason; +}; + +// "auto", "on"/"1"/"true", "off"/"0"/"false"; anything else (including empty) is not a mode. +inline std::optional<AmdCpuMode> ParseAmdCpuMode(std::string_view text) { + if (text == "auto") return AmdCpuMode::Auto; + if (text == "on" || text == "1" || text == "true") return AmdCpuMode::On; + if (text == "off" || text == "0" || text == "false") return AmdCpuMode::Off; + return std::nullopt; +} + +inline const char* AmdCpuModeName(AmdCpuMode mode) { + return mode == AmdCpuMode::On ? "on" : mode == AmdCpuMode::Off ? "off" : "auto"; +} + +// An explicit command line flag wins over KYTY_AMD_CPU; an unset or unparsable variable leaves +// auto. +inline AmdCpuMode ResolveAmdCpuMode(std::optional<AmdCpuMode> command_line, const char* env) { + if (command_line) return *command_line; + if (env != nullptr) { + if (const auto mode = ParseAmdCpuMode(env)) return *mode; + } + return AmdCpuMode::Auto; +} + +// The launcher setting. A stored amd_cpu_mode wins; the older amd_cpu_enabled bool maps true -> on, +// but false -> auto: that default was written for every configuration whether or not the user +// touched the checkbox, so it is no choice to honour. Neither key (or an unparsable mode) is auto. +inline AmdCpuMode AmdCpuModeFromStored(std::optional<std::string_view> mode, + std::optional<bool> legacy_enabled) { + if (mode) { + if (const auto parsed = ParseAmdCpuMode(*mode)) return *parsed; + } + if (legacy_enabled && *legacy_enabled) return AmdCpuMode::On; + return AmdCpuMode::Auto; +} + +inline AmdCpuDecision DecideAmdCpu(AmdCpuMode mode, AmdCpuHostSupport host) { + if (mode == AmdCpuMode::On) return {true, "forced on (--amd-cpu or KYTY_AMD_CPU=1)"}; + if (mode == AmdCpuMode::Off) return {false, "forced off (--no-amd-cpu or KYTY_AMD_CPU=0)"}; + std::string missing; + const auto add = [&missing](bool supported, const char* name) { + if (supported) return; + if (!missing.empty()) missing += ", "; + missing += name; + }; + add(host.sse4a, "SSE4a"); + add(host.rdpid, "RDPID"); + add(host.clwb, "CLWB"); + if (missing.empty()) return {false, "auto: host supports SSE4a, RDPID and CLWB"}; + return {true, "auto: host lacks " + missing}; +} ``` **🚀 Performance & Scalability** | **🟡 Minor** | **⚡ Quick win** **Auto mode enables patching even when the selected patch kinds cannot rewrite anything.** `DecideAmdCpu` enables the patcher when the host lacks any of SSE4a, RDPID or CLWB. The default patch kinds for auto mode contain only `AmdPatchSse4a`. Consider a host that supports SSE4a but lacks RDPID or CLWB, such as an older AMD CPU without CLWB. On that host, auto mode turns the patcher on. In `CollectAmdInstructions`, `!host_features.sse4a` is false, so no site is collected. For every module, the loader still allocates the 8 MiB trampoline area and decodes every function. On Windows, `analyze_red_zone |= emulate_amd` also runs red-zone liveness analysis. The log also says "patching on" even though nothing can change. Base the auto decision on the resolved patch kinds. Enable patching only when at least one selected kind targets an instruction that the host does not support. <details> <summary>♻️ Proposed change</summary> ```diff -inline AmdCpuDecision DecideAmdCpu(AmdCpuMode mode, AmdCpuHostSupport host) { +inline AmdCpuDecision DecideAmdCpu(AmdCpuMode mode, AmdCpuHostSupport host, + uint32_t kinds = 0xffffffffu) { ... - add(host.sse4a, "SSE4a"); - add(host.rdpid, "RDPID"); - add(host.clwb, "CLWB"); + add(host.sse4a || (kinds & AmdPatchSse4a) == 0, "SSE4a"); + add(host.rdpid || (kinds & AmdPatchCpuExt) == 0, "RDPID"); + add(host.clwb || (kinds & AmdPatchCpuExt) == 0, "CLWB"); ``` The `AmdPatchKind` enum must be declared before `DecideAmdCpu`. `runtimeLinker.cpp` must pass `Config::GetAmdPatchKinds()`. </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:e49da73599ef48eb886db80a --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commits eaa8eca to 30c4cba
@ -33,2 +33,3 @@
KYTY_CFG_SET(renderdoc_enabled);
KYTY_CFG_SET(amd_cpu_enabled);
values.insert(QStringLiteral("amd_cpu_mode"),
QString::fromLatin1(Common::AmdCpuModeName(amd_cpu_mode)));
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-12 07:01 UTC · original · edited 2026-10-12 10:15 UTC

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -nP -C4 '\bSetGameSettings\s*\(' src/launcher
rg -nP -C6 'ImportGameSettings' src/launcher/src

Repository: KytyPS5/KytyPS5

Length of output: 6718


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- current configuration.cpp relevant symbols ---'
rg -n -F -- 'QVariantMap Configuration::GameSettings' src/launcher/src/configuration.cpp
rg -n -F -- 'bool Configuration::SetGameSettings' src/launcher/src/configuration.cpp
rg -n -F -- 'void Configuration::ReadGameSettingsValues' src/launcher/src/configuration.cpp
sed -n '1,230p' src/launcher/src/configuration.cpp
printf '%s\n' '--- merge-base configuration.cpp ---'
git show dad900c61d6c7ff8aefc9e666ca7c3de4bbf4176:src/launcher/src/configuration.cpp | sed -n '1,220p'

Repository: KytyPS5/KytyPS5

Length of output: 12664


Accept amd_cpu_enabled as a legacy import key.

GameSettings() now exports only amd_cpu_mode, but older exports contain amd_cpu_enabled. SetGameSettings rejects that key before ReadGameSettingsValues can apply its existing legacy mapping. This causes the complete import to fail with Unknown game setting: amd_cpu_enabled.

Accept the legacy key without adding it to the canonical comparison. If amd_cpu_mode is absent, remove the default mode before reading the legacy value so true maps to on and false maps to auto.

🐛 Suggested fix
 	auto values = GameSettings();
 	for (auto it = settings.constBegin(); it != settings.constEnd(); ++it) {
-		if (!values.contains(it.key())) {
+		const bool legacy = it.key() == QStringLiteral("amd_cpu_enabled");
+		if (!legacy && !values.contains(it.key())) {
 			return fail(tr("Unknown game setting: %1").arg(it.key()));
 		}
 		if (!it.value().isString()) {
 			return fail(tr("Game setting %1 must be a string.").arg(it.key()));
 		}
 		values.insert(it.key(), it.value().toString());
 	}
+	if (settings.contains(QStringLiteral("amd_cpu_enabled")) &&
+	    !settings.contains(QStringLiteral("amd_cpu_mode"))) {
+		values.remove(QStringLiteral("amd_cpu_mode"));
+	}

 	ReadGameSettingsValues(values);
 	const auto canonical = GameSettings();
 	for (auto it = settings.constBegin(); it != settings.constEnd(); ++it) {
+		if (it.key() == QStringLiteral("amd_cpu_enabled")) {
+			continue;
+		}
 		if (canonical.value(it.key()) != values.value(it.key())) {
 			return fail(tr("Invalid value for game setting: %1").arg(it.key()));
 		}

✅ Addressed in commits eaa8eca to 30c4cba

**@⁠coderabbitai[bot]** on GitHub · 2026-10-12 07:01 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1439#discussion_r4245402139) · edited 2026-10-12 10:15 UTC **🗄️ Data Integrity & Integration** | **🟡 Minor** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash rg -nP -C4 '\bSetGameSettings\s*\(' src/launcher rg -nP -C6 'ImportGameSettings' src/launcher/src ``` Repository: KytyPS5/KytyPS5 Length of output: 6718 --- 🏁 Script executed: ```bash #!/bin/bash set -eu printf '%s\n' '--- current configuration.cpp relevant symbols ---' rg -n -F -- 'QVariantMap Configuration::GameSettings' src/launcher/src/configuration.cpp rg -n -F -- 'bool Configuration::SetGameSettings' src/launcher/src/configuration.cpp rg -n -F -- 'void Configuration::ReadGameSettingsValues' src/launcher/src/configuration.cpp sed -n '1,230p' src/launcher/src/configuration.cpp printf '%s\n' '--- merge-base configuration.cpp ---' git show dad900c61d6c7ff8aefc9e666ca7c3de4bbf4176:src/launcher/src/configuration.cpp | sed -n '1,220p' ``` Repository: KytyPS5/KytyPS5 Length of output: 12664 --- </details> **Accept `amd_cpu_enabled` as a legacy import key.** `GameSettings()` now exports only `amd_cpu_mode`, but older exports contain `amd_cpu_enabled`. `SetGameSettings` rejects that key before `ReadGameSettingsValues` can apply its existing legacy mapping. This causes the complete import to fail with `Unknown game setting: amd_cpu_enabled`. Accept the legacy key without adding it to the canonical comparison. If `amd_cpu_mode` is absent, remove the default mode before reading the legacy value so `true` maps to `on` and `false` maps to `auto`. <details> <summary>🐛 Suggested fix</summary> ```diff auto values = GameSettings(); for (auto it = settings.constBegin(); it != settings.constEnd(); ++it) { - if (!values.contains(it.key())) { + const bool legacy = it.key() == QStringLiteral("amd_cpu_enabled"); + if (!legacy && !values.contains(it.key())) { return fail(tr("Unknown game setting: %1").arg(it.key())); } if (!it.value().isString()) { return fail(tr("Game setting %1 must be a string.").arg(it.key())); } values.insert(it.key(), it.value().toString()); } + if (settings.contains(QStringLiteral("amd_cpu_enabled")) && + !settings.contains(QStringLiteral("amd_cpu_mode"))) { + values.remove(QStringLiteral("amd_cpu_mode")); + } ReadGameSettingsValues(values); const auto canonical = GameSettings(); for (auto it = settings.constBegin(); it != settings.constEnd(); ++it) { + if (it.key() == QStringLiteral("amd_cpu_enabled")) { + continue; + } if (canonical.value(it.key()) != values.value(it.key())) { return fail(tr("Invalid value for game setting: %1").arg(it.key())); } ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:ec0e1e56c7056af04efc04f6 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commits eaa8eca to 30c4cba
@ -1667,3 +1691,3 @@
EXIT_IF(tls_handler_size > UINT64_MAX - program->base_size_aligned);
program->mapped_size = program->base_size_aligned + tls_handler_size;
const bool emulate_amd = Config::AmdCpuEnabled();
const bool emulate_amd = AmdCpuPatchEnabled();
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-12 07:01 UTC · original · edited 2026-10-12 10:16 UTC

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -nP -C3 'cannot safely trap' src/loader
rg -nP -C3 'analyze_red_zone' src/loader/guestInstructionPatcher.cpp

Repository: KytyPS5/KytyPS5

Length of output: 1586


🏁 Script executed:

#!/bin/bash
set -o pipefail
printf '%s\n' '--- runtime linker decision and call sites ---'
rg -n -F -- 'AmdCpuPatchEnabled' src
rg -n -F -- 'PatchGuestInstructions' src/loader src/common src || true
printf '%s\n' '--- AMD decision and patch kinds ---'
rg -n -F -- 'DecideAmdCpu' src
rg -n -F -- 'AmdPatchSse4a' src
rg -n -F -- 'amd_cpu_mode' src
printf '%s\n' '--- relevant source blocks ---'
sed -n '1640,1725p' src/loader/runtimeLinker.cpp
sed -n '940,1020p' src/loader/guestInstructionPatcher.cpp
sed -n '1480,1585p' src/loader/guestInstructionPatcher.cpp
printf '%s\n' '--- changed/base context ---'
git diff dad900c61d6c7ff8aefc9e666ca7c3de4bbf4176 d8c2f32991cb2bfba51d23d244bf25581b5a4b83 -- src/loader/runtimeLinker.cpp src/loader/guestInstructionPatcher.cpp | sed -n '1,260p'

Repository: KytyPS5/KytyPS5

Length of output: 20917


🏁 Script executed:

#!/bin/bash
set -o pipefail
printf '%s\n' '--- AMD mode contract ---'
nl -ba src/common/amdCpuMode.h | sed -n '1,165p'
printf '%s\n' '--- runtime decision and patch call ---'
nl -ba src/loader/runtimeLinker.cpp | sed -n '70,110p;1770,1835p'
printf '%s\n' '--- relocation and trap flow ---'
nl -ba src/loader/guestInstructionPatcher.cpp | sed -n '900,1020p;1020,1185p;1185,1325p'
printf '%s\n' '--- relevant base implementation ---'
git show dad900c61d6c7ff8aefc9e666ca7c3de4bbf4176:src/loader/guestInstructionPatcher.cpp 2>/dev/null | nl -ba | sed -n '900,1040p;1450,1535p'

Repository: KytyPS5/KytyPS5

Length of output: 43844


Keep auto AMD patching disabled on Windows until unrelocated sites have a safe path.

Auto mode enables patching when the host lacks SSE4a, and auto mode selects the SSE4a patch group. On Windows, an unrelocatable EXTRQ or INSERTQ site with a live red zone reaches TrapUnrelocatedInstructions, which calls EXIT. This can terminate program loading instead of preserving the previous trap-handler path.

Suggested fix
-		const auto decision =
+		auto decision =
 		    Common::DecideAmdCpu(Config::GetAmdCpuMode(), {host.sse4a, host.rdpid, host.clwb});
+#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS
+		if (Config::GetAmdCpuMode() == Common::AmdCpuMode::Auto) {
+			decision = {false, "auto: disabled on Windows"};
+		}
+#endif
 		Log::WriteToConsoleAndLog(fmt::format(

✅ Addressed in commits eaa8eca to 30c4cba

**@⁠coderabbitai[bot]** on GitHub · 2026-10-12 07:01 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1439#discussion_r4245402151) · edited 2026-10-12 10:16 UTC **🩺 Stability & Availability** | **🟠 Major** | **🏗️ Heavy lift** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash rg -nP -C3 'cannot safely trap' src/loader rg -nP -C3 'analyze_red_zone' src/loader/guestInstructionPatcher.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 1586 --- 🏁 Script executed: ```bash #!/bin/bash set -o pipefail printf '%s\n' '--- runtime linker decision and call sites ---' rg -n -F -- 'AmdCpuPatchEnabled' src rg -n -F -- 'PatchGuestInstructions' src/loader src/common src || true printf '%s\n' '--- AMD decision and patch kinds ---' rg -n -F -- 'DecideAmdCpu' src rg -n -F -- 'AmdPatchSse4a' src rg -n -F -- 'amd_cpu_mode' src printf '%s\n' '--- relevant source blocks ---' sed -n '1640,1725p' src/loader/runtimeLinker.cpp sed -n '940,1020p' src/loader/guestInstructionPatcher.cpp sed -n '1480,1585p' src/loader/guestInstructionPatcher.cpp printf '%s\n' '--- changed/base context ---' git diff dad900c61d6c7ff8aefc9e666ca7c3de4bbf4176 d8c2f32991cb2bfba51d23d244bf25581b5a4b83 -- src/loader/runtimeLinker.cpp src/loader/guestInstructionPatcher.cpp | sed -n '1,260p' ``` Repository: KytyPS5/KytyPS5 Length of output: 20917 --- 🏁 Script executed: ```bash #!/bin/bash set -o pipefail printf '%s\n' '--- AMD mode contract ---' nl -ba src/common/amdCpuMode.h | sed -n '1,165p' printf '%s\n' '--- runtime decision and patch call ---' nl -ba src/loader/runtimeLinker.cpp | sed -n '70,110p;1770,1835p' printf '%s\n' '--- relocation and trap flow ---' nl -ba src/loader/guestInstructionPatcher.cpp | sed -n '900,1020p;1020,1185p;1185,1325p' printf '%s\n' '--- relevant base implementation ---' git show dad900c61d6c7ff8aefc9e666ca7c3de4bbf4176:src/loader/guestInstructionPatcher.cpp 2>/dev/null | nl -ba | sed -n '900,1040p;1450,1535p' ``` Repository: KytyPS5/KytyPS5 Length of output: 43844 --- </details> **Keep auto AMD patching disabled on Windows until unrelocated sites have a safe path.** Auto mode enables patching when the host lacks SSE4a, and auto mode selects the SSE4a patch group. On Windows, an unrelocatable EXTRQ or INSERTQ site with a live red zone reaches `TrapUnrelocatedInstructions`, which calls `EXIT`. This can terminate program loading instead of preserving the previous trap-handler path. <details> <summary>Suggested fix</summary> ```diff - const auto decision = + auto decision = Common::DecideAmdCpu(Config::GetAmdCpuMode(), {host.sse4a, host.rdpid, host.clwb}); +#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS + if (Config::GetAmdCpuMode() == Common::AmdCpuMode::Auto) { + decision = {false, "auto: disabled on Windows"}; + } +#endif Log::WriteToConsoleAndLog(fmt::format( ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:e244156f2ff76c8f2443895c --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commits eaa8eca to 30c4cba
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-12 07:01 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: 92e8d3c3-d938-4d3b-b3ba-11bc4ae4ec31
📥 Commits

Reviewing files that changed from the base of the PR and between dad900c61d and d8c2f32991.

📒 Files selected for processing (15)
  • CMakeLists.txt
  • src/common/amdCpuMode.h
  • src/common/emulatorConfig.cpp
  • src/common/emulatorConfig.h
  • src/launcher/forms/configuration_edit_dialog.ui
  • src/launcher/include/configuration.h
  • src/launcher/src/configuration.cpp
  • src/launcher/src/configurationEditDialog.cpp
  • src/launcher/src/mainDialog.cpp
  • src/loader/guestInstructionPatcher.cpp
  • src/loader/guestInstructionPatcher.h
  • src/loader/runtimeLinker.cpp
  • src/main.cpp
  • tests/AmdCpuModeTests.cpp
  • tests/amdTrampolineBitExactTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-12 07:01 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1439#pullrequestreview-5487397257) · **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**: `92e8d3c3-d938-4d3b-b3ba-11bc4ae4ec31` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between dad900c61d6c7ff8aefc9e666ca7c3de4bbf4176 and d8c2f32991cb2bfba51d23d244bf25581b5a4b83. </details> <details> <summary>📒 Files selected for processing (15)</summary> * `CMakeLists.txt` * `src/common/amdCpuMode.h` * `src/common/emulatorConfig.cpp` * `src/common/emulatorConfig.h` * `src/launcher/forms/configuration_edit_dialog.ui` * `src/launcher/include/configuration.h` * `src/launcher/src/configuration.cpp` * `src/launcher/src/configurationEditDialog.cpp` * `src/launcher/src/mainDialog.cpp` * `src/loader/guestInstructionPatcher.cpp` * `src/loader/guestInstructionPatcher.h` * `src/loader/runtimeLinker.cpp` * `src/main.cpp` * `tests/AmdCpuModeTests.cpp` * `tests/amdTrampolineBitExactTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=fe330df8-54cc-47fc-9362-42bda97f2159 attempt=e558ef37-8d96-47b5-9f34-89d21d24248f batch=1/1 -->
Author
Owner

@⁠wuboo on GitHub · 2026-10-12 10:09 UTC · original
On src/common/amdCpuMode.h line 78 (outdated):

@@ -0,0 +1,144 @@
+#ifndef EMULATOR_INCLUDE_EMULATOR_COMMON_AMDCPUMODE_H_
+#define EMULATOR_INCLUDE_EMULATOR_COMMON_AMDCPUMODE_H_
+
+#include <cstddef>
+#include <cstdint>
+#include <optional>
+#include <string>
+#include <string_view>
+
+namespace Common {
+
+// The guest is built for an AMD CPU. Without the patcher every SSE4a/RDPID/CLWB instruction the
+// host lacks raises SIGILL and is emulated in a signal handler (about ten thousand signals per
+// frame on Rosetta, which reports an Intel CPU without SSE4a). Auto turns the patcher on only when
+// the host lacks one of them.
+enum class AmdCpuMode { Auto, On, Off };
+
+// Instructions the AMD patcher rewrites, as reported by CPUID of the host.
+struct AmdCpuHostSupport {
+	bool sse4a = false;
+	bool rdpid = false;
+	bool clwb  = false;
+};
+
+struct AmdCpuDecision {
+	bool        enabled = false;
+	std::string reason;
+};
+
+// "auto", "on"/"1"/"true", "off"/"0"/"false"; anything else (including empty) is not a mode.
+inline std::optional<AmdCpuMode> ParseAmdCpuMode(std::string_view text) {
+	if (text == "auto") return AmdCpuMode::Auto;
+	if (text == "on" || text == "1" || text == "true") return AmdCpuMode::On;
+	if (text == "off" || text == "0" || text == "false") return AmdCpuMode::Off;
+	return std::nullopt;
+}
+
+inline const char* AmdCpuModeName(AmdCpuMode mode) {
+	return mode == AmdCpuMode::On ? "on" : mode == AmdCpuMode::Off ? "off" : "auto";
+}
+
+// An explicit command line flag wins over KYTY_AMD_CPU; an unset or unparsable variable leaves
+// auto.
+inline AmdCpuMode ResolveAmdCpuMode(std::optional<AmdCpuMode> command_line, const char* env) {
+	if (command_line) return *command_line;
+	if (env != nullptr) {
+		if (const auto mode = ParseAmdCpuMode(env)) return *mode;
+	}
+	return AmdCpuMode::Auto;
+}
+
+// The launcher setting. A stored amd_cpu_mode wins; the older amd_cpu_enabled bool maps true -> on,
+// but false -> auto: that default was written for every configuration whether or not the user
+// touched the checkbox, so it is no choice to honour. Neither key (or an unparsable mode) is auto.
+inline AmdCpuMode AmdCpuModeFromStored(std::optional<std::string_view> mode,
+                                       std::optional<bool>             legacy_enabled) {
+	if (mode) {
+		if (const auto parsed = ParseAmdCpuMode(*mode)) return *parsed;
+	}
+	if (legacy_enabled && *legacy_enabled) return AmdCpuMode::On;
+	return AmdCpuMode::Auto;
+}
+
+inline AmdCpuDecision DecideAmdCpu(AmdCpuMode mode, AmdCpuHostSupport host) {
+	if (mode == AmdCpuMode::On) return {true, "forced on (--amd-cpu or KYTY_AMD_CPU=1)"};
+	if (mode == AmdCpuMode::Off) return {false, "forced off (--no-amd-cpu or KYTY_AMD_CPU=0)"};
+	std::string missing;
+	const auto  add = [&missing](bool supported, const char* name) {
+		if (supported) return;
+		if (!missing.empty()) missing += ", ";
+		missing += name;
+	};
+	add(host.sse4a, "SSE4a");
+	add(host.rdpid, "RDPID");
+	add(host.clwb, "CLWB");
+	if (missing.empty()) return {false, "auto: host supports SSE4a, RDPID and CLWB"};
+	return {true, "auto: host lacks " + missing};
+}

Good catch, fixed in eaa8eca5. DecideAmdCpu now takes the resolved patch kinds: auto turns the patcher on only when the host lacks an instruction that a selected kind rewrites (SSE4a for sse4a, RDPID/CLWB for cpuext). With the default auto kinds (sse4a) a host that has SSE4a but no CLWB no longer pays for the trampoline area and the decode. runtimeLinker.cpp passes Config::GetAmdPatchKinds(). The AmdPatchKind enum moved above the function. Covered by amd_cpu_mode (new cases for each kind set) with the mutants kinds_sse4a_ignored and kinds_cpuext_ignored.

**@⁠wuboo** on GitHub · 2026-10-12 10:09 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1439#discussion_r4246832042) On `src/common/amdCpuMode.h` line 78 (outdated): ```diff @@ -0,0 +1,144 @@ +#ifndef EMULATOR_INCLUDE_EMULATOR_COMMON_AMDCPUMODE_H_ +#define EMULATOR_INCLUDE_EMULATOR_COMMON_AMDCPUMODE_H_ + +#include <cstddef> +#include <cstdint> +#include <optional> +#include <string> +#include <string_view> + +namespace Common { + +// The guest is built for an AMD CPU. Without the patcher every SSE4a/RDPID/CLWB instruction the +// host lacks raises SIGILL and is emulated in a signal handler (about ten thousand signals per +// frame on Rosetta, which reports an Intel CPU without SSE4a). Auto turns the patcher on only when +// the host lacks one of them. +enum class AmdCpuMode { Auto, On, Off }; + +// Instructions the AMD patcher rewrites, as reported by CPUID of the host. +struct AmdCpuHostSupport { + bool sse4a = false; + bool rdpid = false; + bool clwb = false; +}; + +struct AmdCpuDecision { + bool enabled = false; + std::string reason; +}; + +// "auto", "on"/"1"/"true", "off"/"0"/"false"; anything else (including empty) is not a mode. +inline std::optional<AmdCpuMode> ParseAmdCpuMode(std::string_view text) { + if (text == "auto") return AmdCpuMode::Auto; + if (text == "on" || text == "1" || text == "true") return AmdCpuMode::On; + if (text == "off" || text == "0" || text == "false") return AmdCpuMode::Off; + return std::nullopt; +} + +inline const char* AmdCpuModeName(AmdCpuMode mode) { + return mode == AmdCpuMode::On ? "on" : mode == AmdCpuMode::Off ? "off" : "auto"; +} + +// An explicit command line flag wins over KYTY_AMD_CPU; an unset or unparsable variable leaves +// auto. +inline AmdCpuMode ResolveAmdCpuMode(std::optional<AmdCpuMode> command_line, const char* env) { + if (command_line) return *command_line; + if (env != nullptr) { + if (const auto mode = ParseAmdCpuMode(env)) return *mode; + } + return AmdCpuMode::Auto; +} + +// The launcher setting. A stored amd_cpu_mode wins; the older amd_cpu_enabled bool maps true -> on, +// but false -> auto: that default was written for every configuration whether or not the user +// touched the checkbox, so it is no choice to honour. Neither key (or an unparsable mode) is auto. +inline AmdCpuMode AmdCpuModeFromStored(std::optional<std::string_view> mode, + std::optional<bool> legacy_enabled) { + if (mode) { + if (const auto parsed = ParseAmdCpuMode(*mode)) return *parsed; + } + if (legacy_enabled && *legacy_enabled) return AmdCpuMode::On; + return AmdCpuMode::Auto; +} + +inline AmdCpuDecision DecideAmdCpu(AmdCpuMode mode, AmdCpuHostSupport host) { + if (mode == AmdCpuMode::On) return {true, "forced on (--amd-cpu or KYTY_AMD_CPU=1)"}; + if (mode == AmdCpuMode::Off) return {false, "forced off (--no-amd-cpu or KYTY_AMD_CPU=0)"}; + std::string missing; + const auto add = [&missing](bool supported, const char* name) { + if (supported) return; + if (!missing.empty()) missing += ", "; + missing += name; + }; + add(host.sse4a, "SSE4a"); + add(host.rdpid, "RDPID"); + add(host.clwb, "CLWB"); + if (missing.empty()) return {false, "auto: host supports SSE4a, RDPID and CLWB"}; + return {true, "auto: host lacks " + missing}; +} ``` Good catch, fixed in eaa8eca5. `DecideAmdCpu` now takes the resolved patch kinds: auto turns the patcher on only when the host lacks an instruction that a selected kind rewrites (SSE4a for `sse4a`, RDPID/CLWB for `cpuext`). With the default auto kinds (`sse4a`) a host that has SSE4a but no CLWB no longer pays for the trampoline area and the decode. `runtimeLinker.cpp` passes `Config::GetAmdPatchKinds()`. The `AmdPatchKind` enum moved above the function. Covered by `amd_cpu_mode` (new cases for each kind set) with the mutants `kinds_sse4a_ignored` and `kinds_cpuext_ignored`.
@ -33,2 +33,3 @@
KYTY_CFG_SET(renderdoc_enabled);
KYTY_CFG_SET(amd_cpu_enabled);
values.insert(QStringLiteral("amd_cpu_mode"),
QString::fromLatin1(Common::AmdCpuModeName(amd_cpu_mode)));
Author
Owner

@⁠wuboo on GitHub · 2026-10-12 10:09 UTC · original

Valid, fixed in 30c4cba4. SetGameSettings accepts amd_cpu_enabled, does not compare it with the canonical values, and when the import has no amd_cpu_mode it drops the default mode so that the existing legacy mapping applies (true -> on, false -> auto). Caveat: the launcher needs Qt, which I could not build locally, so this hunk is compile-checked by reading only; the mapping itself (AmdCpuModeFromStored) is already covered by amd_cpu_mode.

**@⁠wuboo** on GitHub · 2026-10-12 10:09 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1439#discussion_r4246832321) Valid, fixed in 30c4cba4. `SetGameSettings` accepts `amd_cpu_enabled`, does not compare it with the canonical values, and when the import has no `amd_cpu_mode` it drops the default mode so that the existing legacy mapping applies (true -> on, false -> auto). Caveat: the launcher needs Qt, which I could not build locally, so this hunk is compile-checked by reading only; the mapping itself (`AmdCpuModeFromStored`) is already covered by `amd_cpu_mode`.
@ -1667,3 +1691,3 @@
EXIT_IF(tls_handler_size > UINT64_MAX - program->base_size_aligned);
program->mapped_size = program->base_size_aligned + tls_handler_size;
const bool emulate_amd = Config::AmdCpuEnabled();
const bool emulate_amd = AmdCpuPatchEnabled();
Author
Owner

@⁠wuboo on GitHub · 2026-10-12 10:09 UTC · original

Agreed that auto must not make this reachable on Windows. The EXIT itself was already there for an explicit --amd-cpu, but auto would have started to hit it on every Intel Windows host. Fixed in eaa8eca5 in a slightly different way than suggested: DecideAmdCpu has an auto_allowed argument, runtimeLinker.cpp passes false on Windows, so auto stays off there (reason is logged) while --amd-cpu/KYTY_AMD_CPU=1 still patches. Tests: amd_cpu_mode with the mutant auto_allowed_ignored. The Windows branch itself is not compiled here (macOS only).

**@⁠wuboo** on GitHub · 2026-10-12 10:09 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1439#discussion_r4246832566) Agreed that auto must not make this reachable on Windows. The `EXIT` itself was already there for an explicit `--amd-cpu`, but auto would have started to hit it on every Intel Windows host. Fixed in eaa8eca5 in a slightly different way than suggested: `DecideAmdCpu` has an `auto_allowed` argument, `runtimeLinker.cpp` passes `false` on Windows, so auto stays off there (reason is logged) while `--amd-cpu`/`KYTY_AMD_CPU=1` still patches. Tests: `amd_cpu_mode` with the mutant `auto_allowed_ignored`. The Windows branch itself is not compiled here (macOS only).
@ -131,2 +153,4 @@
const auto canonical = GameSettings();
for (auto it = settings.constBegin(); it != settings.constEnd(); ++it) {
if (it.key() == QStringLiteral("amd_cpu_enabled")) {
continue; // not exported any more, so there is nothing to compare it with
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-12 10:13 UTC · original · edited 2026-10-12 14:01 UTC

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Inspect legacy-value parsing and the game-settings import path.
ast-grep outline src/launcher/src/configuration.cpp --items all
sed -n '1,175p' src/launcher/src/configuration.cpp

Repository: KytyPS5/KytyPS5

Length of output: 7562


Validate the legacy value before skipping its comparison.

SetGameSettings accepts any string for amd_cpu_enabled, removes the default mode when the legacy key is present alone, and skips that key during canonical-value comparison. An invalid value such as "banana" can therefore be converted to true and select On instead of being rejected. Accept only the legacy export’s boolean strings before applying the legacy value.

✅ Addressed in commit 9766018

**@⁠coderabbitai[bot]** on GitHub · 2026-10-12 10:13 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1439#discussion_r4246866500) · edited 2026-10-12 14:01 UTC **🗄️ Data Integrity & Integration** | **🟡 Minor** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash # Inspect legacy-value parsing and the game-settings import path. ast-grep outline src/launcher/src/configuration.cpp --items all sed -n '1,175p' src/launcher/src/configuration.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 7562 --- </details> **Validate the legacy value before skipping its comparison.** `SetGameSettings` accepts any string for `amd_cpu_enabled`, removes the default mode when the legacy key is present alone, and skips that key during canonical-value comparison. An invalid value such as `"banana"` can therefore be converted to `true` and select `On` instead of being rejected. Accept only the legacy export’s boolean strings before applying the legacy value. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:c4fa3f1c24d8d853d54a89d5 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit 9766018
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-12 10:13 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: d6238a25-0abd-4c89-b592-6258acb92d91
📥 Commits

Reviewing files that changed from the base of the PR and between d8c2f32991 and 30c4cba442.

📒 Files selected for processing (5)
  • CMakeLists.txt
  • src/common/amdCpuMode.h
  • src/launcher/src/configuration.cpp
  • src/loader/runtimeLinker.cpp
  • tests/AmdCpuModeTests.cpp
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/loader/runtimeLinker.cpp
  • tests/AmdCpuModeTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-12 10:13 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1439#pullrequestreview-5489319104) · **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**: `d6238a25-0abd-4c89-b592-6258acb92d91` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between d8c2f32991cb2bfba51d23d244bf25581b5a4b83 and 30c4cba4427636f2c69365c5b63a7c8166a6fe0a. </details> <details> <summary>📒 Files selected for processing (5)</summary> * `CMakeLists.txt` * `src/common/amdCpuMode.h` * `src/launcher/src/configuration.cpp` * `src/loader/runtimeLinker.cpp` * `tests/AmdCpuModeTests.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (2)</summary> * src/loader/runtimeLinker.cpp * tests/AmdCpuModeTests.cpp </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=6313c1a6-04fc-498e-b576-4f6187c30496 attempt=1c173732-c0f1-4c5c-9dd7-be80e75b727a batch=1/1 -->
@ -33,2 +33,3 @@
KYTY_CFG_SET(renderdoc_enabled);
KYTY_CFG_SET(amd_cpu_enabled);
values.insert(QStringLiteral("amd_cpu_mode"),
QString::fromLatin1(Common::AmdCpuModeName(amd_cpu_mode)));
Author
Owner

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

@wuboo Thanks for the fix. The supplied SetGameSettings code addresses all three parts of the finding and preserves the legacy mapping.

The amd_cpu_mode tests cover the mapping helper, not the Qt import path. Launcher compilation remains unverified until CI builds it.


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-12 10:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1439#discussion_r4246884660) `@wuboo` Thanks for the fix. The supplied `SetGameSettings` code addresses all three parts of the finding and preserves the legacy mapping. The `amd_cpu_mode` tests cover the mapping helper, not the Qt import path. Launcher compilation remains unverified until CI builds it. --- <!-- 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=Legacy%20imports%20can%20fail%20when%20old%20keys%20are%20rejected.%20%40coderabbitai%20caught%20the%20fix%3A%20accept%20%60amd_cpu_enabled%60%20and%20preserve%20true%E2%86%92on%2C%20false%E2%86%92auto.%20Try%20it%20for%20sharper%20code%20reviews%20%F0%9F%90%87&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1439%23discussion_r4245402139)? 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 -->
@ -1667,3 +1691,3 @@
EXIT_IF(tls_handler_size > UINT64_MAX - program->base_size_aligned);
program->mapped_size = program->base_size_aligned + tls_handler_size;
const bool emulate_amd = Config::AmdCpuEnabled();
const bool emulate_amd = AmdCpuPatchEnabled();
Author
Owner

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

@wuboo Thanks for the clarification. The supplied runtimeLinker.cpp passes auto_allowed=false on Windows. This addresses the finding by keeping auto patching off while preserving explicit force-on behavior.

The reported auto_allowed_ignored mutant covers the decision logic. Windows compilation remains unverified, as you stated.


✏️ Learnings added
Learnt from: wuboo
Repo: KytyPS5/KytyPS5 PR: 1439
File: src/loader/runtimeLinker.cpp:1693-1693
Timestamp: 2026-10-12T10:16:18.685Z
Learning: In KytyPS5/KytyPS5, Windows AMD CPU auto mode must remain disabled because unrelocatable EXTRQ/INSERTQ sites with a live red zone can reach EXIT in TrapUnrelocatedInstructions. This EXIT path already existed for explicit AMD CPU patching. src/loader/runtimeLinker.cpp passes auto_allowed=false to Common::DecideAmdCpu on Windows; explicit --amd-cpu or KYTY_AMD_CPU=1 remains supported.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


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-12 10:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1439#discussion_r4246888289) `@wuboo` Thanks for the clarification. The supplied `runtimeLinker.cpp` passes `auto_allowed=false` on Windows. This addresses the finding by keeping auto patching off while preserving explicit force-on behavior. The reported `auto_allowed_ignored` mutant covers the decision logic. Windows compilation remains unverified, as you stated. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: wuboo Repo: KytyPS5/KytyPS5 PR: 1439 File: src/loader/runtimeLinker.cpp:1693-1693 Timestamp: 2026-10-12T10:16:18.685Z Learning: In KytyPS5/KytyPS5, Windows AMD CPU auto mode must remain disabled because unrelocatable EXTRQ/INSERTQ sites with a live red zone can reach EXIT in TrapUnrelocatedInstructions. This EXIT path already existed for explicit AMD CPU patching. src/loader/runtimeLinker.cpp passes auto_allowed=false to Common::DecideAmdCpu on Windows; explicit --amd-cpu or KYTY_AMD_CPU=1 remains supported. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> --- <!-- 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%20Windows%20crash%20risk%3A%20auto%20AMD%20patching%20could%20EXIT%20on%20unrelocatable%20instructions.%20Auto%20is%20now%20disabled%20on%20Windows%3B%20explicit%20opt-in%20remains.%20Try%20%40coderabbitai%20for%20safer%20reviews!&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1439%23discussion_r4245402151)? 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

@⁠coderabbitai[bot] on GitHub · 2026-10-12 10:18 UTC · original
On src/common/amdCpuMode.h line 78 (outdated):

@@ -0,0 +1,144 @@
+#ifndef EMULATOR_INCLUDE_EMULATOR_COMMON_AMDCPUMODE_H_
+#define EMULATOR_INCLUDE_EMULATOR_COMMON_AMDCPUMODE_H_
+
+#include <cstddef>
+#include <cstdint>
+#include <optional>
+#include <string>
+#include <string_view>
+
+namespace Common {
+
+// The guest is built for an AMD CPU. Without the patcher every SSE4a/RDPID/CLWB instruction the
+// host lacks raises SIGILL and is emulated in a signal handler (about ten thousand signals per
+// frame on Rosetta, which reports an Intel CPU without SSE4a). Auto turns the patcher on only when
+// the host lacks one of them.
+enum class AmdCpuMode { Auto, On, Off };
+
+// Instructions the AMD patcher rewrites, as reported by CPUID of the host.
+struct AmdCpuHostSupport {
+	bool sse4a = false;
+	bool rdpid = false;
+	bool clwb  = false;
+};
+
+struct AmdCpuDecision {
+	bool        enabled = false;
+	std::string reason;
+};
+
+// "auto", "on"/"1"/"true", "off"/"0"/"false"; anything else (including empty) is not a mode.
+inline std::optional<AmdCpuMode> ParseAmdCpuMode(std::string_view text) {
+	if (text == "auto") return AmdCpuMode::Auto;
+	if (text == "on" || text == "1" || text == "true") return AmdCpuMode::On;
+	if (text == "off" || text == "0" || text == "false") return AmdCpuMode::Off;
+	return std::nullopt;
+}
+
+inline const char* AmdCpuModeName(AmdCpuMode mode) {
+	return mode == AmdCpuMode::On ? "on" : mode == AmdCpuMode::Off ? "off" : "auto";
+}
+
+// An explicit command line flag wins over KYTY_AMD_CPU; an unset or unparsable variable leaves
+// auto.
+inline AmdCpuMode ResolveAmdCpuMode(std::optional<AmdCpuMode> command_line, const char* env) {
+	if (command_line) return *command_line;
+	if (env != nullptr) {
+		if (const auto mode = ParseAmdCpuMode(env)) return *mode;
+	}
+	return AmdCpuMode::Auto;
+}
+
+// The launcher setting. A stored amd_cpu_mode wins; the older amd_cpu_enabled bool maps true -> on,
+// but false -> auto: that default was written for every configuration whether or not the user
+// touched the checkbox, so it is no choice to honour. Neither key (or an unparsable mode) is auto.
+inline AmdCpuMode AmdCpuModeFromStored(std::optional<std::string_view> mode,
+                                       std::optional<bool>             legacy_enabled) {
+	if (mode) {
+		if (const auto parsed = ParseAmdCpuMode(*mode)) return *parsed;
+	}
+	if (legacy_enabled && *legacy_enabled) return AmdCpuMode::On;
+	return AmdCpuMode::Auto;
+}
+
+inline AmdCpuDecision DecideAmdCpu(AmdCpuMode mode, AmdCpuHostSupport host) {
+	if (mode == AmdCpuMode::On) return {true, "forced on (--amd-cpu or KYTY_AMD_CPU=1)"};
+	if (mode == AmdCpuMode::Off) return {false, "forced off (--no-amd-cpu or KYTY_AMD_CPU=0)"};
+	std::string missing;
+	const auto  add = [&missing](bool supported, const char* name) {
+		if (supported) return;
+		if (!missing.empty()) missing += ", ";
+		missing += name;
+	};
+	add(host.sse4a, "SSE4a");
+	add(host.rdpid, "RDPID");
+	add(host.clwb, "CLWB");
+	if (missing.empty()) return {false, "auto: host supports SSE4a, RDPID and CLWB"};
+	return {true, "auto: host lacks " + missing};
+}

@wuboo, thanks for the fix in eaa8eca5. Passing the resolved patch kinds to DecideAmdCpu addresses this finding. The new kind-specific tests and mutants cover the reported regression.


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-12 10:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1439#discussion_r4246901476) On `src/common/amdCpuMode.h` line 78 (outdated): ```diff @@ -0,0 +1,144 @@ +#ifndef EMULATOR_INCLUDE_EMULATOR_COMMON_AMDCPUMODE_H_ +#define EMULATOR_INCLUDE_EMULATOR_COMMON_AMDCPUMODE_H_ + +#include <cstddef> +#include <cstdint> +#include <optional> +#include <string> +#include <string_view> + +namespace Common { + +// The guest is built for an AMD CPU. Without the patcher every SSE4a/RDPID/CLWB instruction the +// host lacks raises SIGILL and is emulated in a signal handler (about ten thousand signals per +// frame on Rosetta, which reports an Intel CPU without SSE4a). Auto turns the patcher on only when +// the host lacks one of them. +enum class AmdCpuMode { Auto, On, Off }; + +// Instructions the AMD patcher rewrites, as reported by CPUID of the host. +struct AmdCpuHostSupport { + bool sse4a = false; + bool rdpid = false; + bool clwb = false; +}; + +struct AmdCpuDecision { + bool enabled = false; + std::string reason; +}; + +// "auto", "on"/"1"/"true", "off"/"0"/"false"; anything else (including empty) is not a mode. +inline std::optional<AmdCpuMode> ParseAmdCpuMode(std::string_view text) { + if (text == "auto") return AmdCpuMode::Auto; + if (text == "on" || text == "1" || text == "true") return AmdCpuMode::On; + if (text == "off" || text == "0" || text == "false") return AmdCpuMode::Off; + return std::nullopt; +} + +inline const char* AmdCpuModeName(AmdCpuMode mode) { + return mode == AmdCpuMode::On ? "on" : mode == AmdCpuMode::Off ? "off" : "auto"; +} + +// An explicit command line flag wins over KYTY_AMD_CPU; an unset or unparsable variable leaves +// auto. +inline AmdCpuMode ResolveAmdCpuMode(std::optional<AmdCpuMode> command_line, const char* env) { + if (command_line) return *command_line; + if (env != nullptr) { + if (const auto mode = ParseAmdCpuMode(env)) return *mode; + } + return AmdCpuMode::Auto; +} + +// The launcher setting. A stored amd_cpu_mode wins; the older amd_cpu_enabled bool maps true -> on, +// but false -> auto: that default was written for every configuration whether or not the user +// touched the checkbox, so it is no choice to honour. Neither key (or an unparsable mode) is auto. +inline AmdCpuMode AmdCpuModeFromStored(std::optional<std::string_view> mode, + std::optional<bool> legacy_enabled) { + if (mode) { + if (const auto parsed = ParseAmdCpuMode(*mode)) return *parsed; + } + if (legacy_enabled && *legacy_enabled) return AmdCpuMode::On; + return AmdCpuMode::Auto; +} + +inline AmdCpuDecision DecideAmdCpu(AmdCpuMode mode, AmdCpuHostSupport host) { + if (mode == AmdCpuMode::On) return {true, "forced on (--amd-cpu or KYTY_AMD_CPU=1)"}; + if (mode == AmdCpuMode::Off) return {false, "forced off (--no-amd-cpu or KYTY_AMD_CPU=0)"}; + std::string missing; + const auto add = [&missing](bool supported, const char* name) { + if (supported) return; + if (!missing.empty()) missing += ", "; + missing += name; + }; + add(host.sse4a, "SSE4a"); + add(host.rdpid, "RDPID"); + add(host.clwb, "CLWB"); + if (missing.empty()) return {false, "auto: host supports SSE4a, RDPID and CLWB"}; + return {true, "auto: host lacks " + missing}; +} ``` `@wuboo`, thanks for the fix in `eaa8eca5`. Passing the resolved patch kinds to `DecideAmdCpu` addresses this finding. The new kind-specific tests and mutants cover the reported regression. --- <!-- 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=Auto%20patching%20now%20respects%20selected%20AMD%20patch%20kinds%2C%20avoiding%20needless%208%20MiB%20trampolines%20and%20function%20decoding%20when%20no%20rewrite%20is%20possible.%20Try%20%40coderabbitai%20for%20sharp%20code%20reviews%20%E2%9A%A1&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1439%23discussion_r4245402131)? 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 -->
@ -131,2 +153,4 @@
const auto canonical = GameSettings();
for (auto it = settings.constBegin(); it != settings.constEnd(); ++it) {
if (it.key() == QStringLiteral("amd_cpu_enabled")) {
continue; // not exported any more, so there is nothing to compare it with
Author
Owner

@⁠wuboo on GitHub · 2026-10-12 13:54 UTC · original

Good catch, fixed in 97660188. The legacy amd_cpu_enabled value is now parsed by a new Common::ParseLegacyAmdCpuEnabled() in amdCpuMode.h, and Configuration::SetGameSettings rejects the import with "Invalid value for game setting: amd_cpu_enabled" unless the string is exactly true or false (the only two forms the old export wrote). So "banana", an empty string, "1" or "True" can no longer be read as true and select On. Covered by amd_cpu_mode (new checks for true, false, banana, empty, 1, True) plus two mutants that must fail: LEGACY_ANY_TRUE (any text is true) and LEGACY_FALSE_DROPPED ("false" is not a bool); both exit 1. Note that I could not build the Qt launcher locally (no Qt installed), so the SetGameSettings call site is covered by review only; the parsing logic is covered by the unit test.

**@⁠wuboo** on GitHub · 2026-10-12 13:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1439#discussion_r4248804900) Good catch, fixed in 97660188. The legacy `amd_cpu_enabled` value is now parsed by a new `Common::ParseLegacyAmdCpuEnabled()` in `amdCpuMode.h`, and `Configuration::SetGameSettings` rejects the import with "Invalid value for game setting: amd_cpu_enabled" unless the string is exactly `true` or `false` (the only two forms the old export wrote). So `"banana"`, an empty string, `"1"` or `"True"` can no longer be read as `true` and select `On`. Covered by `amd_cpu_mode` (new checks for `true`, `false`, `banana`, empty, `1`, `True`) plus two mutants that must fail: `LEGACY_ANY_TRUE` (any text is true) and `LEGACY_FALSE_DROPPED` ("false" is not a bool); both exit 1. Note that I could not build the Qt launcher locally (no Qt installed), so the `SetGameSettings` call site is covered by review only; the parsing logic is covered by the unit test.
@ -131,2 +153,4 @@
const auto canonical = GameSettings();
for (auto it = settings.constBegin(); it != settings.constEnd(); ++it) {
if (it.key() == QStringLiteral("amd_cpu_enabled")) {
continue; // not exported any more, so there is nothing to compare it with
Author
Owner

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

@wuboo Thanks for the fix. The supplied SetGameSettings code validates the legacy value before applying settings or skipping canonical comparison. This addresses the finding.

The reported parser tests cover the invalid strings and both valid values. The Qt launcher call site remains untested locally, as you noted.


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-12 14:01 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1439#discussion_r4248885473) `@wuboo` Thanks for the fix. The supplied `SetGameSettings` code validates the legacy value before applying settings or skipping canonical comparison. This addresses the finding. The reported parser tests cover the invalid strings and both valid values. The Qt launcher call site remains untested locally, as you noted. --- <!-- 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=Validate%20legacy%20%60amd_cpu_enabled%60%20as%20exactly%20%60true%60%20or%20%60false%60%E2%80%94rejecting%20invalid%20values%20like%20%60banana%60%20instead%20of%20silently%20enabling%20CPU%20mode.%20Try%20%40coderabbitai%20%F0%9F%9B%A1%EF%B8%8F&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1439%23discussion_r4246866500)? 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

@⁠Nawid3333 on GitHub · 2026-10-27 20:57 UTC · original

I measured the boot cost of the patcher, since boot time is the reason given in #1196 for keeping --amd-cpu opt-in. ASTRO BOT (PPSA21564) on main ffc81377, Ryzen 5 7600X, red-zone protection off, 3 runs each. Time from start until eboot.bin is relocated:

--amd-cpu runs
off 0.9 s, 0.9 s, 0.8 s
on 8.1 s, 8.0 s, 8.0 s

So --amd-cpu costs about 7 s per boot for this game. eboot.bin has 312,697 functions. On this CPU only VRSQRTPS gets rewritten (9,679 native, 1,079 trapped): it has SSE4a, so the EXTRQ sites #839 found in this game aren't collected here.

With the auto mode in this PR, a host that has SSE4a, RDPID and CLWB doesn't patch and keeps the 0.9 s. A host without SSE4a would pay a patching pass at boot instead of trapping every EXTRQ (#839 measured 810,000 traps/s in this game). I measured --amd-cpu with all groups, not this PR's sse4a-only default, and not on an Intel CPU.

**@⁠Nawid3333** on GitHub · 2026-10-27 20:57 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1439#issuecomment-6453375509) I measured the boot cost of the patcher, since boot time is the reason given in #1196 for keeping `--amd-cpu` opt-in. ASTRO BOT (PPSA21564) on main ffc81377, Ryzen 5 7600X, red-zone protection off, 3 runs each. Time from start until `eboot.bin` is relocated: | `--amd-cpu` | runs | |---|---| | off | 0.9 s, 0.9 s, 0.8 s | | on | 8.1 s, 8.0 s, 8.0 s | So `--amd-cpu` costs about 7 s per boot for this game. `eboot.bin` has 312,697 functions. On this CPU only VRSQRTPS gets rewritten (9,679 native, 1,079 trapped): it has SSE4a, so the EXTRQ sites #839 found in this game aren't collected here. With the auto mode in this PR, a host that has SSE4a, RDPID and CLWB doesn't patch and keeps the 0.9 s. A host without SSE4a would pay a patching pass at boot instead of trapping every EXTRQ (#839 measured 810,000 traps/s in this game). I measured `--amd-cpu` with all groups, not this PR's `sse4a`-only default, and not on an Intel CPU.

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.