loader: attribute guest faults to modules and print a backtrace #836

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

@⁠theantipopau on GitHub · 2026-09-25 20:43 UTC · original
theantipopau:guest-fault-backtrace → main · +664 −2 · 5 files · 5 commits · closed without merging

Problem

An unhandled guest exception prints the faulting thread, the register file, 96 bytes around the
faulting pc and a raw word dump of the top of the stack, but it never says which module the
faulting address belongs to. Game-compatibility issues quote this log verbatim, so triage starts
with guessing which of the game's modules a 0x9000... code address lives in.

libC.cpp already does the right thing for guest abort(): it annotates every stack word that
resolves to a loaded module with module+offset and prints a RuntimeLinker::StackTrace backtrace.
The fault reporter is the one crash path that does not.

Astro Bot (PPSA21564) is a live example. #835 reports a read of 0xffffffffffffffff at
pc=0x9000006a1 on the SceSndzAudioOutMain thread, and the log cannot attribute that address
to any module, so the report cannot be acted on as it stands.

Changes

  • Attribute the faulting pc: a new fault pc: 0x... module+0xoffset line before the register dump.
  • Print a backtrace: section, walked with the existing WalkGuestStack the same way guest
    abort() does it.
  • Annotate the existing stack: dump: any word that resolves to a loaded module now carries
    module+0xoffset. Words that do not resolve still print their raw value, so the report loses
    no information it had before.
  • RuntimeLinker::Current(), a non-constructing accessor for the live linker.
  • RuntimeLinker::TryFindProgramByAddr(), the segment walk used by the reporter.
  • Loader::FormatGuestFrame(), the module+0xoffset rendering.

The last two exist because the reporter has to stay safe to run from an exception handler:

  • Common::Singleton<RuntimeLinker>::Instance() constructs on first use, so calling it from the
    reporter would allocate a linker inside the handler if the fault happens before the game is
    linked. Allocating there can fault again and wedge the reporting thread. Current() returns the
    pointer the constructor already publishes, and nullptr when nothing is linked yet.
  • TryFindProgramByAddr() takes the linker mutex with TryLock instead of blocking. A guest fault
    can land on a thread that already owns the mutex, e.g. during a concurrent load or unload, and a
    blocking lock would hang the crash report. When the lock is contended it returns nullptr and
    the report degrades to module=<unknown>, which is better than a hang. It also skips programs
    whose Elf64 is not loaded yet rather than dereferencing it, and never raises, so it cannot
    recurse into its own handler.

Testing

Windows, clang-cl + Ninja, Release:

  • virtual_memory_allocation_tests: all cases passed, including the new
    GuestFaultFrameAttribution case. It checks the exact rendering, the zero-offset and
    maximum-offset ends of the range, the null and empty module name, and the offset clamp for an
    address below the module base.
  • kyty_emulator: clean build and link.

This is build and unit test evidence only. It was not verified against a real game, and the local
driver cannot run the production rasterization tests
(VK_EXT_attachment_feedback_loop_dynamic_state is missing), so the new report lines have not been
observed in a live crash log yet.

Risk

Low, and diagnostics only. The report is already fatal and already exits, so the only behaviour
change is what it prints before it does. Nothing is added to the non-fault path, and no decode,
load, or memory behaviour changes. The two new accessors are additive; FindProgramByAddr and
Singleton<> are left untouched for existing callers.

Next

#835 is a good first exercise of the new output: the next reporter of that crash should get the
module name for the faulting pc and a backtrace through the audio thread, instead of a bare address.

**@⁠theantipopau** on GitHub · 2026-09-25 20:43 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836) `theantipopau:guest-fault-backtrace` → `main` · +664 −2 · 5 files · 5 commits · closed without merging Problem An unhandled guest exception prints the faulting thread, the register file, 96 bytes around the faulting pc and a raw word dump of the top of the stack, but it never says which module the faulting address belongs to. Game-compatibility issues quote this log verbatim, so triage starts with guessing which of the game's modules a `0x9000...` code address lives in. `libC.cpp` already does the right thing for guest `abort()`: it annotates every stack word that resolves to a loaded module with `module+offset` and prints a `RuntimeLinker::StackTrace` backtrace. The fault reporter is the one crash path that does not. Astro Bot (PPSA21564) is a live example. #835 reports a read of `0xffffffffffffffff` at `pc=0x9000006a1` on the `SceSndzAudioOutMain` thread, and the log cannot attribute that address to any module, so the report cannot be acted on as it stands. Changes - Attribute the faulting pc: a new `fault pc: 0x... module+0xoffset` line before the register dump. - Print a `backtrace:` section, walked with the existing `WalkGuestStack` the same way guest `abort()` does it. - Annotate the existing `stack:` dump: any word that resolves to a loaded module now carries `module+0xoffset`. Words that do not resolve still print their raw value, so the report loses no information it had before. - `RuntimeLinker::Current()`, a non-constructing accessor for the live linker. - `RuntimeLinker::TryFindProgramByAddr()`, the segment walk used by the reporter. - `Loader::FormatGuestFrame()`, the `module+0xoffset` rendering. The last two exist because the reporter has to stay safe to run from an exception handler: - `Common::Singleton<RuntimeLinker>::Instance()` constructs on first use, so calling it from the reporter would allocate a linker inside the handler if the fault happens before the game is linked. Allocating there can fault again and wedge the reporting thread. `Current()` returns the pointer the constructor already publishes, and `nullptr` when nothing is linked yet. - `TryFindProgramByAddr()` takes the linker mutex with `TryLock` instead of blocking. A guest fault can land on a thread that already owns the mutex, e.g. during a concurrent load or unload, and a blocking lock would hang the crash report. When the lock is contended it returns `nullptr` and the report degrades to `module=<unknown>`, which is better than a hang. It also skips programs whose `Elf64` is not loaded yet rather than dereferencing it, and never raises, so it cannot recurse into its own handler. Testing Windows, clang-cl + Ninja, Release: - `virtual_memory_allocation_tests`: all cases passed, including the new `GuestFaultFrameAttribution` case. It checks the exact rendering, the zero-offset and maximum-offset ends of the range, the null and empty module name, and the offset clamp for an address below the module base. - `kyty_emulator`: clean build and link. This is build and unit test evidence only. It was not verified against a real game, and the local driver cannot run the production rasterization tests (`VK_EXT_attachment_feedback_loop_dynamic_state` is missing), so the new report lines have not been observed in a live crash log yet. Risk Low, and diagnostics only. The report is already fatal and already exits, so the only behaviour change is what it prints before it does. Nothing is added to the non-fault path, and no decode, load, or memory behaviour changes. The two new accessors are additive; `FindProgramByAddr` and `Singleton<>` are left untouched for existing callers. Next #835 is a good first exercise of the new output: the next reporter of that crash should get the module name for the faulting pc and a backtrace through the audio thread, instead of a bare address.
An unhandled guest exception reports the faulting register file, the
faulting code bytes and a raw word dump of the top of the stack, but never
names the module the faulting address belongs to. Game-compatibility
issues quote this log verbatim, so triage starts with guessing which of the
game's modules a 0x9000... code address belongs to.

The guest abort() handler in libC.cpp already annotates stack words with
module+offset and prints a backtrace; the fault reporter did not. Reuse the
same machinery there: attribute the faulting pc, walk the frame-pointer
chain through WalkGuestStack, and label the stack words that resolve to a
loaded module. Unresolved words still print their raw value, so the report
loses nothing.

The reporter has to stay safe to run from an exception handler, so two
access paths are added rather than reusing the existing ones:
RuntimeLinker::Current() returns the live linker without going through
Common::Singleton<>::Instance(), which constructs on demand and would
allocate inside the handler; and TryFindProgramByAddr() takes the linker
mutex with TryLock, so a fault that lands on a thread which already owns
the mutex reports "module=<unknown>" instead of deadlocking, and it skips
programs whose Elf64 is not loaded yet rather than dereferencing it.

FormatGuestFrame is free of loader state and unit tested, including the
offset clamp, since the report is the only place a wrapped offset would
otherwise be visible to a user.

Astro Bot (PPSA21564, #835) crashes on the SceSndzAudioOutMain thread with
a read of -1 at 0x9000006a1, which this report could not attribute to any
module.

Testing
Windows, clang-cl + Ninja, Release:
virtual_memory_allocation_tests: all cases passed, including the new
GuestFaultFrameAttribution case;
kyty_emulator: clean build and link.

Not verified on a real game, and the local driver cannot run the
production rasterization tests (missing
VK_EXT_attachment_feedback_loop_dynamic_state), so this is build and unit
test evidence only.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
A missing base or index resolves to a constant the resolver already
computes, so those operands were wrongly labeled unresolved. The real
unresolvable case is an fs:/gs: base, whose segment base is not in the
reported register file; those stay unresolved and no longer report their
segment-relative offset as the fault address.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:34:14 +00:00
github-bot closed this pull request 2026-11-26 09:34:14 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 20:50 UTC · original · edited 2026-09-26 03:16 UTC

Review in Change Stack →

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: fa2def9b-105c-43db-b5c6-2593b2cbf005

📥 Commits

Reviewing files that changed from the base of the PR and between 1cd7a72cb4 and 484c0dc41a.

📒 Files selected for processing (1)
  • src/loader/x64InstructionDecoder.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/loader/x64InstructionDecoder.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.


📝 Walkthrough

Walkthrough

The fault report decodes the instruction at a readable fault PC using captured guest registers. It reports the instruction text and length, memory access type, and effective address when available, while retaining the code-byte dump. The runtime linker returns copied module metadata for address and stack-word attribution. Its current-instance pointer now uses atomic operations. A report gate coordinates fault reporting with linker teardown. Tests cover instruction decoding, address resolution, memory access classification, and incomplete input.

Priority: ⬇️ Low

Change: Feature

Merge Risk: ⚪ Minimal · up to 484c0

The inspected fault-report paths do not show a merge-blocking issue; the change is ready for normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 1cd7a

Crash reports gain useful fault details, but module attribution may allocate memory while handling a fault and holding locks. That creates a limited risk that a guest-triggered failure prevents orderly reporting or shutdown. No broader privilege or service-boundary change is established.

Retained concerns

  • Low · reliability · inferred: Guest-triggered fault reporting constructs strings while holding the teardown gate and linker mutex. If that work throws or faults, the normal unlock and fatal-exit sequence is not established.
Security review details

Security Blast Radius

  • inferred — Guest fault addresses and stack values can drive repeated attribution work in the host fault reporter. The supported exposure is the running emulator process and its crash-reporting path; broader downstream exposure is not established.

Security Findings and Attack Paths

  • inferred — A guest-triggered fatal fault can reach string allocation during attribution. A secondary failure at that point may replace an orderly crash report and exit with interrupted reporting or teardown; no privilege gain or cross-process attack path is established.

Trust Boundaries and Controls

  • observed — Readable-range checks and bounded decoding constrain reads from faulting guest code. Nonblocking linker lookup, copied metadata, and gate-coordinated teardown constrain normal concurrent attribution.

Resilience and Maintainability Implications

  • inferred — Normal reporting releases the gate, but source evidence does not establish cleanup if formatting, output, or a nested fault interrupts the handler before its explicit unlock.

Hardening Proposals

  • proposed — Use bounded, non-allocating attribution formatting in the fault handler and ensure gate ownership has a defined interruption path, while preserving the existing unknown-module fallback.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main changes: guest fault module attribution and backtrace reporting.
Description check ✅ Passed The description is detailed and directly explains the guest fault reporting changes, safety considerations, testing, and limitations.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 20:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836#issuecomment-5839409218) · edited 2026-09-26 03:16 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/836"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> Navigate logical layers of code changes, visualize relationships, and explore their blast radius. <!-- review_stack_entry_end --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary>ℹ️ Recent review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `fa2def9b-105c-43db-b5c6-2593b2cbf005` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 1cd7a72cb4a8468685ba9a03a8f8c72f17545ff3 and 484c0dc41a9a8d9eebf95ea9b104436e26c3477a. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/loader/x64InstructionDecoder.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary> * src/loader/x64InstructionDecoder.cpp </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. </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough The fault report decodes the instruction at a readable fault PC using captured guest registers. It reports the instruction text and length, memory access type, and effective address when available, while retaining the code-byte dump. The runtime linker returns copied module metadata for address and stack-word attribution. Its current-instance pointer now uses atomic operations. A report gate coordinates fault reporting with linker teardown. Tests cover instruction decoding, address resolution, memory access classification, and incomplete input. </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ⬇️ Low <!-- change_assessment_commit:"484c0dc41a9a8d9eebf95ea9b104436e26c3477a" --> **Change:** Feature <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _⚪ Minimal_ · up to `484c0` <!-- final_review_risk_coverage:{"sourceCommitId":"484c0dc41a9a8d9eebf95ea9b104436e26c3477a","coveredCommitId":"484c0dc41a9a8d9eebf95ea9b104436e26c3477a","kind":"reviewed"} --> The inspected fault-report paths do not show a merge-blocking issue; the change is ready for normal checks. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🔵 Low_ · up to `1cd7a` Crash reports gain useful fault details, but module attribution may allocate memory while handling a fault and holding locks. That creates a limited risk that a guest-triggered failure prevents orderly reporting or shutdown. No broader privilege or service-boundary change is established. **Retained concerns** - **Low · reliability · inferred:** Guest-triggered fault reporting constructs strings while holding the teardown gate and linker mutex. If that work throws or faults, the normal unlock and fatal-exit sequence is not established. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — Guest fault addresses and stack values can drive repeated attribution work in the host fault reporter. The supported exposure is the running emulator process and its crash-reporting path; broader downstream exposure is not established. **Security Findings and Attack Paths** - _inferred_ — A guest-triggered fatal fault can reach string allocation during attribution. A secondary failure at that point may replace an orderly crash report and exit with interrupted reporting or teardown; no privilege gain or cross-process attack path is established. **Trust Boundaries and Controls** - _observed_ — Readable-range checks and bounded decoding constrain reads from faulting guest code. Nonblocking linker lookup, copied metadata, and gate-coordinated teardown constrain normal concurrent attribution. **Resilience and Maintainability Implications** - _inferred_ — Normal reporting releases the gate, but source evidence does not establish cleanup if formatting, output, or a nested fault interrupts the handler before its explicit unlock. **Hardening Proposals** - _proposed_ — Use bounded, non-allocating attribution formatting in the fault handler and ensure gate ownership has a defined interruption path, while preserving the existing unknown-module fallback. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 5 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :------------------------------------------------------------------------------------------------------------------------------------ | | Title check | ✅ Passed | The title clearly identifies the main changes: guest fault module attribution and backtrace reporting. | | Description check | ✅ Passed | The description is detailed and directly explains the guest fault reporting changes, safety considerations, testing, and limitations. | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 20:50 UTC · original · edited 2026-09-26 01:36 UTC
On src/loader/runtimeLinker.cpp line 1242 (outdated):

@@ -1178,14 +1235,22 @@ void RuntimeLinker::UnloadProgram(Program* program) {
 	DeleteProgram(program);
 }
 
+RuntimeLinker* RuntimeLinker::s_current = nullptr;
+
 RuntimeLinker::RuntimeLinker(): m_symbols(std::make_unique<SymbolDatabase>()) {
 	EXIT_NOT_IMPLEMENTED(!Common::Thread::IsMainThread());
+	s_current = this;

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

Synchronize access to the current linker.

A worker thread can enter KytyExceptionHandler() while the main thread destroys RuntimeLinker. The handler reads s_current through Current(), while the constructor and destructor write that plain pointer. This is a data race, and a loaded pointer does not keep the linker alive during reporting. Synchronize publication and teardown with fault reporting; an atomic pointer alone does not solve the lifetime race.

Also applies to: 1246-1246, 1250-1251

✅ Addressed in commits ce8132c to da13cfc

**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 20:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836#discussion_r4108519073) · edited 2026-09-26 01:36 UTC On `src/loader/runtimeLinker.cpp` line 1242 (outdated): ```diff @@ -1178,14 +1235,22 @@ void RuntimeLinker::UnloadProgram(Program* program) { DeleteProgram(program); } +RuntimeLinker* RuntimeLinker::s_current = nullptr; + RuntimeLinker::RuntimeLinker(): m_symbols(std::make_unique<SymbolDatabase>()) { EXIT_NOT_IMPLEMENTED(!Common::Thread::IsMainThread()); + s_current = this; ``` _🩺 Stability & Availability_ | _🟠 Major_ | _🏗️ Heavy lift_ **Synchronize access to the current linker.** A worker thread can enter `KytyExceptionHandler()` while the main thread destroys `RuntimeLinker`. The handler reads `s_current` through `Current()`, while the constructor and destructor write that plain pointer. This is a data race, and a loaded pointer does not keep the linker alive during reporting. Synchronize publication and teardown with fault reporting; an atomic pointer alone does not solve the lifetime race. Also applies to: 1246-1246, 1250-1251 <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:0268e21e1433fdc095ad0156 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commits ce8132c to da13cfc
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 20:50 UTC · original · edited 2026-09-26 01:36 UTC
On src/loader/runtimeLinker.cpp line 1596 (outdated):

@@ -1495,6 +1560,42 @@ Program* RuntimeLinker::FindProgramByFileName(const std::filesystem::path& elf_n
 	return nullptr;
 }
 
+// Same segment walk as FindProgramByAddr, but usable from the fatal fault reporter: it takes
+// no lock when the linker is busy, tolerates a program whose Elf64 is not loaded yet and never
+// raises, so a crash report cannot hang or recurse inside its own handler.
+Program* RuntimeLinker::TryFindProgramByAddr(uint64_t vaddr) {
+	if (!m_mutex.TryLock()) {
+		return nullptr;
+	}
+	Program* found = nullptr;
+	for (auto* p: m_programs) {
+		if (p == nullptr || p->elf == nullptr) {
+			continue;
+		}
+		const auto* ehdr = p->elf->GetEhdr();
+		const auto* phdr = p->elf->GetPhdr();
+		if (ehdr == nullptr || phdr == nullptr) {
+			continue;
+		}
+		for (Elf64_Half i = 0; i < ehdr->e_phnum; i++) {
+			if (phdr[i].p_memsz != 0 &&
+			    (phdr[i].p_type == PT_LOAD || phdr[i].p_type == PT_OS_RELRO)) {
+				const uint64_t segment_addr = phdr[i].p_vaddr + p->base_vaddr;
+				const uint64_t segment_size = GetAlignedSize(phdr + i);
+				if (vaddr >= segment_addr && vaddr < segment_addr + segment_size) {
+					found = p;
+					break;
+				}
+			}
+		}
+		if (found != nullptr) {
+			break;
+		}
+	}
+	m_mutex.Unlock();
+	return found;

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

Keep the program alive through report formatting.

TryFindProgramByAddr() releases m_mutex before it returns found. If another thread calls UnloadProgram(), that thread can delete the returned Program before ReportGuestAddress() or the stack dump reads its name and base_vaddr. Return a diagnostic snapshot made under the lock, or hold a lifetime guard through formatting. Based on learnings, readers of objects referenced by a mutable collection must use the mutex that protects deletion.

Source: Learnings

✅ Addressed in commits ce8132c to da13cfc

**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 20:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836#discussion_r4108519079) · edited 2026-09-26 01:36 UTC On `src/loader/runtimeLinker.cpp` line 1596 (outdated): ```diff @@ -1495,6 +1560,42 @@ Program* RuntimeLinker::FindProgramByFileName(const std::filesystem::path& elf_n return nullptr; } +// Same segment walk as FindProgramByAddr, but usable from the fatal fault reporter: it takes +// no lock when the linker is busy, tolerates a program whose Elf64 is not loaded yet and never +// raises, so a crash report cannot hang or recurse inside its own handler. +Program* RuntimeLinker::TryFindProgramByAddr(uint64_t vaddr) { + if (!m_mutex.TryLock()) { + return nullptr; + } + Program* found = nullptr; + for (auto* p: m_programs) { + if (p == nullptr || p->elf == nullptr) { + continue; + } + const auto* ehdr = p->elf->GetEhdr(); + const auto* phdr = p->elf->GetPhdr(); + if (ehdr == nullptr || phdr == nullptr) { + continue; + } + for (Elf64_Half i = 0; i < ehdr->e_phnum; i++) { + if (phdr[i].p_memsz != 0 && + (phdr[i].p_type == PT_LOAD || phdr[i].p_type == PT_OS_RELRO)) { + const uint64_t segment_addr = phdr[i].p_vaddr + p->base_vaddr; + const uint64_t segment_size = GetAlignedSize(phdr + i); + if (vaddr >= segment_addr && vaddr < segment_addr + segment_size) { + found = p; + break; + } + } + } + if (found != nullptr) { + break; + } + } + m_mutex.Unlock(); + return found; ``` _🩺 Stability & Availability_ | _🟠 Major_ | _🏗️ Heavy lift_ **Keep the program alive through report formatting.** `TryFindProgramByAddr()` releases `m_mutex` before it returns `found`. If another thread calls `UnloadProgram()`, that thread can delete the returned `Program` before `ReportGuestAddress()` or the stack dump reads its name and `base_vaddr`. Return a diagnostic snapshot made under the lock, or hold a lifetime guard through formatting. Based on learnings, readers of objects referenced by a mutable collection must use the mutex that protects deletion. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:8881dfcdfd1b191a781770de --> _Source: Learnings_ <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commits ce8132c to da13cfc
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 20:50 UTC · original · reviewed

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: cc86d522-00ae-46fb-8523-3f96dfd42e19

📥 Commits

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

📒 Files selected for processing (3)
  • src/loader/runtimeLinker.cpp
  • src/loader/runtimeLinker.h
  • tests/VirtualMemoryAllocationTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 20:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836#pullrequestreview-5322576722) · **reviewed** **Actionable comments posted: 2** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `cc86d522-00ae-46fb-8523-3f96dfd42e19` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 497166009c8c0dd663fa1ffce3805a31bdc40d0e and d875ddd9f9a62f904bc986267b7925487cb7096f. </details> <details> <summary>📒 Files selected for processing (3)</summary> * `src/loader/runtimeLinker.cpp` * `src/loader/runtimeLinker.h` * `tests/VirtualMemoryAllocationTests.cpp` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠theantipopau on GitHub · 2026-09-26 01:30 UTC · original
On src/loader/runtimeLinker.cpp line 1596 (outdated):

@@ -1495,6 +1560,42 @@ Program* RuntimeLinker::FindProgramByFileName(const std::filesystem::path& elf_n
 	return nullptr;
 }
 
+// Same segment walk as FindProgramByAddr, but usable from the fatal fault reporter: it takes
+// no lock when the linker is busy, tolerates a program whose Elf64 is not loaded yet and never
+// raises, so a crash report cannot hang or recurse inside its own handler.
+Program* RuntimeLinker::TryFindProgramByAddr(uint64_t vaddr) {
+	if (!m_mutex.TryLock()) {
+		return nullptr;
+	}
+	Program* found = nullptr;
+	for (auto* p: m_programs) {
+		if (p == nullptr || p->elf == nullptr) {
+			continue;
+		}
+		const auto* ehdr = p->elf->GetEhdr();
+		const auto* phdr = p->elf->GetPhdr();
+		if (ehdr == nullptr || phdr == nullptr) {
+			continue;
+		}
+		for (Elf64_Half i = 0; i < ehdr->e_phnum; i++) {
+			if (phdr[i].p_memsz != 0 &&
+			    (phdr[i].p_type == PT_LOAD || phdr[i].p_type == PT_OS_RELRO)) {
+				const uint64_t segment_addr = phdr[i].p_vaddr + p->base_vaddr;
+				const uint64_t segment_size = GetAlignedSize(phdr + i);
+				if (vaddr >= segment_addr && vaddr < segment_addr + segment_size) {
+					found = p;
+					break;
+				}
+			}
+		}
+		if (found != nullptr) {
+			break;
+		}
+	}
+	m_mutex.Unlock();
+	return found;

Fixed in da13cfc7 — TryFindProgramByAddr is now TryDescribeProgramByAddr and returns a value instead of a pointer:

struct GuestModuleInfo {
    bool        found = false;
    std::string name;
    uint64_t    base_vaddr = 0;
};
GuestModuleInfo TryDescribeProgramByAddr(uint64_t vaddr);

The segment walk is unchanged, but the module name and base are copied into the result while m_mutex is still held, and the lock is released only after the copy. Both call sites (ReportGuestAddress and the stack annotation) then format from the snapshot, so no Program* escapes the lock and UnloadProgram can no longer free it underneath the report.

GetProgramModuleName reads only dynamic_info->so_name and file_name and takes no lock, so calling it under TryLock is safe and does not nest.

**@⁠theantipopau** on GitHub · 2026-09-26 01:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836#discussion_r4109730972) On `src/loader/runtimeLinker.cpp` line 1596 (outdated): ```diff @@ -1495,6 +1560,42 @@ Program* RuntimeLinker::FindProgramByFileName(const std::filesystem::path& elf_n return nullptr; } +// Same segment walk as FindProgramByAddr, but usable from the fatal fault reporter: it takes +// no lock when the linker is busy, tolerates a program whose Elf64 is not loaded yet and never +// raises, so a crash report cannot hang or recurse inside its own handler. +Program* RuntimeLinker::TryFindProgramByAddr(uint64_t vaddr) { + if (!m_mutex.TryLock()) { + return nullptr; + } + Program* found = nullptr; + for (auto* p: m_programs) { + if (p == nullptr || p->elf == nullptr) { + continue; + } + const auto* ehdr = p->elf->GetEhdr(); + const auto* phdr = p->elf->GetPhdr(); + if (ehdr == nullptr || phdr == nullptr) { + continue; + } + for (Elf64_Half i = 0; i < ehdr->e_phnum; i++) { + if (phdr[i].p_memsz != 0 && + (phdr[i].p_type == PT_LOAD || phdr[i].p_type == PT_OS_RELRO)) { + const uint64_t segment_addr = phdr[i].p_vaddr + p->base_vaddr; + const uint64_t segment_size = GetAlignedSize(phdr + i); + if (vaddr >= segment_addr && vaddr < segment_addr + segment_size) { + found = p; + break; + } + } + } + if (found != nullptr) { + break; + } + } + m_mutex.Unlock(); + return found; ``` Fixed in da13cfc7 — `TryFindProgramByAddr` is now `TryDescribeProgramByAddr` and returns a value instead of a pointer: ```cpp struct GuestModuleInfo { bool found = false; std::string name; uint64_t base_vaddr = 0; }; GuestModuleInfo TryDescribeProgramByAddr(uint64_t vaddr); ``` The segment walk is unchanged, but the module name and base are copied into the result *while `m_mutex` is still held*, and the lock is released only after the copy. Both call sites (`ReportGuestAddress` and the stack annotation) then format from the snapshot, so no `Program*` escapes the lock and `UnloadProgram` can no longer free it underneath the report. `GetProgramModuleName` reads only `dynamic_info->so_name` and `file_name` and takes no lock, so calling it under `TryLock` is safe and does not nest.
Author
Owner

@⁠theantipopau on GitHub · 2026-09-26 01:30 UTC · original
On src/loader/runtimeLinker.cpp line 1242 (outdated):

@@ -1178,14 +1235,22 @@ void RuntimeLinker::UnloadProgram(Program* program) {
 	DeleteProgram(program);
 }
 
+RuntimeLinker* RuntimeLinker::s_current = nullptr;
+
 RuntimeLinker::RuntimeLinker(): m_symbols(std::make_unique<SymbolDatabase>()) {
 	EXIT_NOT_IMPLEMENTED(!Common::Thread::IsMainThread());
+	s_current = this;

Partly fixed in da13cfc7, and I want to be precise about the part that is not.

s_current is now std::atomic<RuntimeLinker*>: the constructor stores, the destructor stores nullptr before Clear(), and Current() loads. That removes the data race on the pointer itself, which is real UB and was introduced by adding a cross-thread reader in the fault reporter.

What is not fixed is the lifetime half of your point, and you are right that the atomic alone does not address it. A reporter that has already loaded a non-null pointer can still race with ~RuntimeLinker tearing down state. Closing that properly needs either a refcount that the reporter pins, or deferring teardown until in-flight reports drain — both are a much larger change than this PR, and blocking in a destructor on a thread that may be the one taking the fault is its own hazard.

I would rather not pretend the atomic settles this. Suggesting it as a follow-up rather than half-implementing a lifetime scheme here, unless you would rather I attempt the pin-or-defer version in this PR.

The store order in the destructor is deliberate: s_current.store(nullptr) happens before Clear(), so any report that starts once teardown begins sees nullptr rather than a half-destroyed linker. That narrows the window to reports already in flight; it does not close it.

**@⁠theantipopau** on GitHub · 2026-09-26 01:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836#discussion_r4109731114) On `src/loader/runtimeLinker.cpp` line 1242 (outdated): ```diff @@ -1178,14 +1235,22 @@ void RuntimeLinker::UnloadProgram(Program* program) { DeleteProgram(program); } +RuntimeLinker* RuntimeLinker::s_current = nullptr; + RuntimeLinker::RuntimeLinker(): m_symbols(std::make_unique<SymbolDatabase>()) { EXIT_NOT_IMPLEMENTED(!Common::Thread::IsMainThread()); + s_current = this; ``` Partly fixed in da13cfc7, and I want to be precise about the part that is not. `s_current` is now `std::atomic<RuntimeLinker*>`: the constructor stores, the destructor stores `nullptr` before `Clear()`, and `Current()` loads. That removes the data race on the pointer itself, which is real UB and was introduced by adding a cross-thread reader in the fault reporter. What is *not* fixed is the lifetime half of your point, and you are right that the atomic alone does not address it. A reporter that has already loaded a non-null pointer can still race with `~RuntimeLinker` tearing down state. Closing that properly needs either a refcount that the reporter pins, or deferring teardown until in-flight reports drain — both are a much larger change than this PR, and blocking in a destructor on a thread that may be the one taking the fault is its own hazard. I would rather not pretend the atomic settles this. Suggesting it as a follow-up rather than half-implementing a lifetime scheme here, unless you would rather I attempt the pin-or-defer version in this PR. The store order in the destructor is deliberate: `s_current.store(nullptr)` happens before `Clear()`, so any report that starts once teardown begins sees `nullptr` rather than a half-destroyed linker. That narrows the window to reports already in flight; it does not close it.
@ -0,0 +208,4 @@
}
result.effective_address = address;
}
} break;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 01:36 UTC · original · edited 2026-09-26 03:15 UTC

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Classify memory access from hidden operands too.

The loop visits only operand_count_visible operands. Zydis marks implicit memory operands as hidden. Examples are [rdi]/[rsi] for movs/stos/cmps/scas and the stack slot for push/call. The common fault sites below therefore report reads_memory == writes_memory == false and no effective address:

  • memcpy/memset loops that use rep movsb or rep stosq.
  • Stack overflow on push or call.

The header states that these fields are true "when the instruction actually touches memory". The report then says the instruction does not access memory, which is wrong. Keep the text rendering limited to visible operands. Run the access-classification pass over all instruction.operand_count operands. operands already holds ZYDIS_MAX_OPERAND_COUNT entries, so the extra pass allocates nothing.

♻️ Proposed change
-	for (uint8_t index = 0; index < instruction.operand_count_visible; index++) {
+	for (uint8_t index = 0; index < instruction.operand_count; index++) {
 		const auto& operand = operands[index];
-		used = Append(result.text, sizeof(result.text), used, index == 0 ? " " : ", ");
+		const bool visible = index < instruction.operand_count_visible;
+		if (!visible) {
+			if (operand.type == ZYDIS_OPERAND_TYPE_MEMORY && !computes_address_only &&
+			    (operand.actions & memory_access) != 0 && !result.reads_memory &&
+			    !result.writes_memory) {
+				result.reads_memory  = (operand.actions & ZYDIS_OPERAND_ACTION_MASK_READ) != 0;
+				result.writes_memory = (operand.actions & ZYDIS_OPERAND_ACTION_MASK_WRITE) != 0;
+				result.effective_address = ResolveMemoryOperand(instruction, operand, registers);
+			}
+			continue;
+		}
+		used = Append(result.text, sizeof(result.text), used, index == 0 ? " " : ", ");

✅ Addressed in commit 484c0dc

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 01:36 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836#discussion_r4109749888) · edited 2026-09-26 03:15 UTC _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **Classify memory access from hidden operands too.** The loop visits only `operand_count_visible` operands. Zydis marks implicit memory operands as hidden. Examples are `[rdi]`/`[rsi]` for `movs`/`stos`/`cmps`/`scas` and the stack slot for `push`/`call`. The common fault sites below therefore report `reads_memory == writes_memory == false` and no effective address: - memcpy/memset loops that use `rep movsb` or `rep stosq`. - Stack overflow on `push` or `call`. The header states that these fields are true "when the instruction actually touches memory". The report then says the instruction does not access memory, which is wrong. Keep the text rendering limited to visible operands. Run the access-classification pass over all `instruction.operand_count` operands. `operands` already holds `ZYDIS_MAX_OPERAND_COUNT` entries, so the extra pass allocates nothing. <details> <summary>♻️ Proposed change</summary> ```diff - for (uint8_t index = 0; index < instruction.operand_count_visible; index++) { + for (uint8_t index = 0; index < instruction.operand_count; index++) { const auto& operand = operands[index]; - used = Append(result.text, sizeof(result.text), used, index == 0 ? " " : ", "); + const bool visible = index < instruction.operand_count_visible; + if (!visible) { + if (operand.type == ZYDIS_OPERAND_TYPE_MEMORY && !computes_address_only && + (operand.actions & memory_access) != 0 && !result.reads_memory && + !result.writes_memory) { + result.reads_memory = (operand.actions & ZYDIS_OPERAND_ACTION_MASK_READ) != 0; + result.writes_memory = (operand.actions & ZYDIS_OPERAND_ACTION_MASK_WRITE) != 0; + result.effective_address = ResolveMemoryOperand(instruction, operand, registers); + } + continue; + } + used = Append(result.text, sizeof(result.text), used, index == 0 ? " " : ", "); ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:186e0afb4dfe529937f686d1 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 484c0dc
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 01:36 UTC · original · edited 2026-09-26 03:17 UTC
On src/loader/x64InstructionDecoder.cpp line 189 (outdated):

@@ -0,0 +1,218 @@
+#include "loader/x64InstructionDecoder.h"
+
+#include <Zydis/Zydis.h>
+
+#include <array>
+#include <cinttypes>
+#include <cstdarg>
+#include <cstdio>
+
+namespace Loader {
+
+namespace {
+
+// One decoder, shared with the rest of the loader the same way redZonePatcher keeps its own.
+// ZydisDecoderInit only fills a plain struct, so constructing it lazily from the fault reporter
+// is cheap and cannot allocate.
+ZydisDecoder& GuestDecoder() {
+	static ZydisDecoder decoder = [] {
+		ZydisDecoder value {};
+		ZydisDecoderInit(&value, ZYDIS_MACHINE_MODE_LONG_64, ZYDIS_STACK_WIDTH_64);
+		return value;
+	}();
+	return decoder;
+}
+
+// Read a general purpose guest register. Anything else (segments, flags, SIMD) is not addressable
+// through a legacy memory operand, so reporting 0 for it cannot make a real fault address wrong.
+uint64_t ReadGuestRegister(ZydisRegister reg, const GuestX64Registers& registers) {
+	const auto wide =
+	    ZydisRegisterGetLargestEnclosing(ZYDIS_MACHINE_MODE_LONG_64, reg);
+	switch (wide) {
+		case ZYDIS_REGISTER_RAX: return registers.rax;
+		case ZYDIS_REGISTER_RBX: return registers.rbx;
+		case ZYDIS_REGISTER_RCX: return registers.rcx;
+		case ZYDIS_REGISTER_RDX: return registers.rdx;
+		case ZYDIS_REGISTER_RSI: return registers.rsi;
+		case ZYDIS_REGISTER_RDI: return registers.rdi;
+		case ZYDIS_REGISTER_RBP: return registers.rbp;
+		case ZYDIS_REGISTER_RSP: return registers.rsp;
+		case ZYDIS_REGISTER_R8: return registers.r8;
+		case ZYDIS_REGISTER_R9: return registers.r9;
+		case ZYDIS_REGISTER_R10: return registers.r10;
+		case ZYDIS_REGISTER_R11: return registers.r11;
+		case ZYDIS_REGISTER_R12: return registers.r12;
+		case ZYDIS_REGISTER_R13: return registers.r13;
+		case ZYDIS_REGISTER_R14: return registers.r14;
+		case ZYDIS_REGISTER_R15: return registers.r15;
+		case ZYDIS_REGISTER_RIP: return registers.rip;
+		default: return 0;
+	}
+}
+
+bool IsGeneralPurposeRegister(ZydisRegister reg) {
+	switch (ZydisRegisterGetLargestEnclosing(ZYDIS_MACHINE_MODE_LONG_64, reg)) {
+		case ZYDIS_REGISTER_RAX:
+		case ZYDIS_REGISTER_RBX:
+		case ZYDIS_REGISTER_RCX:
+		case ZYDIS_REGISTER_RDX:
+		case ZYDIS_REGISTER_RSI:
+		case ZYDIS_REGISTER_RDI:
+		case ZYDIS_REGISTER_RBP:
+		case ZYDIS_REGISTER_RSP:
+		case ZYDIS_REGISTER_R8:
+		case ZYDIS_REGISTER_R9:
+		case ZYDIS_REGISTER_R10:
+		case ZYDIS_REGISTER_R11:
+		case ZYDIS_REGISTER_R12:
+		case ZYDIS_REGISTER_R13:
+		case ZYDIS_REGISTER_R14:
+		case ZYDIS_REGISTER_R15:
+		case ZYDIS_REGISTER_RIP: return true;
+		default: return false;
+	}
+}
+
+// ZydisCalcAbsoluteAddress only covers relative immediates and RIP-relative or absolute memory, so
+// a base+index*scale+disp operand has to be resolved from the register file by hand.
+uint64_t ResolveMemoryOperand(const ZydisDecodedInstruction& instruction,
+                              const ZydisDecodedOperand&         operand,
+                              const GuestX64Registers&            registers) {
+	// RIP-relative operands are already anchored past the end of the instruction.
+	const auto base =
+	    operand.mem.base == ZYDIS_REGISTER_RIP
+	        ? registers.rip + instruction.length
+	        : ReadGuestRegister(operand.mem.base, registers);
+	uint64_t index = 0;
+	if (operand.mem.index != ZYDIS_REGISTER_NONE &&
+	    operand.mem.index != ZYDIS_REGISTER_RIP) {
+		index = ReadGuestRegister(operand.mem.index, registers);
+	}
+	return base + index * static_cast<uint64_t>(operand.mem.scale) +
+	       static_cast<uint64_t>(operand.mem.disp.value);
+}
+
+// The AT&T-style width prefix, so a memory operand keeps the size a reader needs. Without it
+// "[0x1000]" is ambiguous between a byte load and a 16-byte one.
+const char* OperandWidthName(uint16_t bits) {
+	switch (bits) {
+		case 8: return "byte ptr ";
+		case 16: return "word ptr ";
+		case 32: return "dword ptr ";
+		case 64: return "qword ptr ";
+		case 128: return "xmmword ptr ";
+		case 256: return "ymmword ptr ";
+		case 512: return "zmmword ptr ";
+		default: return "";
+	}
+}
+
+// Bounded append into a fixed buffer: this runs on the fatal path, where a truncation is fine but
+// an overrun is not.
+size_t Append(char* text, size_t capacity, size_t used, const char* format, ...) {
+	if (used >= capacity) {
+		return used;
+	}
+	va_list args;
+	va_start(args, format);
+	const int written = std::vsnprintf(text + used, capacity - used, format, args);
+	va_end(args);
+	if (written < 0) {
+		return used;
+	}
+	const auto advance = static_cast<size_t>(written);
+	return advance < capacity - used ? used + advance : capacity - 1;
+}
+
+} // namespace
+
+GuestFaultingInstruction DecodeGuestFaultingInstruction(const uint8_t* code, size_t available,
+                                                        const GuestX64Registers& registers) {
+	GuestFaultingInstruction result;
+	if (code == nullptr || available == 0) {
+		std::snprintf(result.text, sizeof(result.text), "<no readable instruction bytes>");
+		return result;
+	}
+
+	ZydisDecodedInstruction instruction {};
+	std::array<ZydisDecodedOperand, ZYDIS_MAX_OPERAND_COUNT> operands {};
+	const auto status = ZydisDecoderDecodeFull(&GuestDecoder(), code, available, &instruction,
+	                                           operands.data());
+	if (!ZYAN_SUCCESS(status) || instruction.length == 0) {
+		std::snprintf(result.text, sizeof(result.text), "<undecodable instruction>");
+		return result;
+	}
+
+	result.decoded = true;
+	result.length  = instruction.length;
+
+	size_t used = 0;
+	used = Append(result.text, sizeof(result.text), used, "%s",
+	              ZydisMnemonicGetString(instruction.mnemonic));
+
+	// LEA and the padding NOPs name an address without touching it, so they must not be reported
+	// as the memory access that faulted.
+	const bool computes_address_only = instruction.mnemonic == ZYDIS_MNEMONIC_LEA ||
+	                                   instruction.mnemonic == ZYDIS_MNEMONIC_NOP;
+	constexpr ZydisOperandActions memory_access =
+	    ZYDIS_OPERAND_ACTION_MASK_READ | ZYDIS_OPERAND_ACTION_MASK_WRITE;
+
+	for (uint8_t index = 0; index < instruction.operand_count_visible; index++) {
+		const auto& operand = operands[index];
+		used = Append(result.text, sizeof(result.text), used, index == 0 ? " " : ", ");
+
+		switch (operand.type) {
+			case ZYDIS_OPERAND_TYPE_REGISTER:
+				used = Append(result.text, sizeof(result.text), used, "%s",
+				              ZydisRegisterGetString(operand.reg.value));
+				break;
+
+			case ZYDIS_OPERAND_TYPE_IMMEDIATE: {
+				if (operand.imm.is_relative) {
+					uint64_t target = 0;
+					if (ZYAN_SUCCESS(ZydisCalcAbsoluteAddress(&instruction, &operand,
+					                                          registers.rip, &target))) {
+						used = Append(result.text, sizeof(result.text), used,
+						              "0x%016" PRIx64, target);
+						break;
+					}
+				}
+				used = Append(result.text, sizeof(result.text), used, "0x%" PRIx64,
+				              operand.imm.value.u);
+			} break;
+
+			case ZYDIS_OPERAND_TYPE_MEMORY: {
+				const uint64_t address = ResolveMemoryOperand(instruction, operand, registers);
+				const bool     resolved =
+				    IsGeneralPurposeRegister(operand.mem.base) &&
+				    (operand.mem.index == ZYDIS_REGISTER_NONE ||
+				     IsGeneralPurposeRegister(operand.mem.index));

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Fix the "unresolved" labeling rule.

resolved requires IsGeneralPurposeRegister(operand.mem.base). ZYDIS_REGISTER_NONE is not a general purpose register. The rule is wrong in two ways:

  • Absolute and index-only operands: for [0x1000], moffs and [rcx*8+disp], ResolveMemoryOperand computes the correct address. The text still shows unresolved.
  • fs:/gs: operands: for fs:[rax] or gs:[0x28], the segment base is not included. The operand can still be labeled resolved, and effective_address records the wrong address.

Treat a missing base or index as resolved. Mark FS/GS-segment operands unresolved, and do not report their effective_address as the fault address.

🐛 Proposed fix
-				const bool     resolved =
-				    IsGeneralPurposeRegister(operand.mem.base) &&
-				    (operand.mem.index == ZYDIS_REGISTER_NONE ||
-				     IsGeneralPurposeRegister(operand.mem.index));
+				const bool     segment_based = operand.mem.segment == ZYDIS_REGISTER_FS ||
+				                               operand.mem.segment == ZYDIS_REGISTER_GS;
+				const bool     resolved =
+				    !segment_based &&
+				    (operand.mem.base == ZYDIS_REGISTER_NONE ||
+				     IsGeneralPurposeRegister(operand.mem.base)) &&
+				    (operand.mem.index == ZYDIS_REGISTER_NONE ||
+				     IsGeneralPurposeRegister(operand.mem.index));
📝 Committable suggestion

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

				const bool     segment_based = operand.mem.segment == ZYDIS_REGISTER_FS ||
				                               operand.mem.segment == ZYDIS_REGISTER_GS;
				const bool     resolved =
				    !segment_based &&
				    (operand.mem.base == ZYDIS_REGISTER_NONE ||
				     IsGeneralPurposeRegister(operand.mem.base)) &&
				    (operand.mem.index == ZYDIS_REGISTER_NONE ||
				     IsGeneralPurposeRegister(operand.mem.index));

✅ Addressed in commit 484c0dc

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 01:36 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836#discussion_r4109749891) · edited 2026-09-26 03:17 UTC On `src/loader/x64InstructionDecoder.cpp` line 189 (outdated): ```diff @@ -0,0 +1,218 @@ +#include "loader/x64InstructionDecoder.h" + +#include <Zydis/Zydis.h> + +#include <array> +#include <cinttypes> +#include <cstdarg> +#include <cstdio> + +namespace Loader { + +namespace { + +// One decoder, shared with the rest of the loader the same way redZonePatcher keeps its own. +// ZydisDecoderInit only fills a plain struct, so constructing it lazily from the fault reporter +// is cheap and cannot allocate. +ZydisDecoder& GuestDecoder() { + static ZydisDecoder decoder = [] { + ZydisDecoder value {}; + ZydisDecoderInit(&value, ZYDIS_MACHINE_MODE_LONG_64, ZYDIS_STACK_WIDTH_64); + return value; + }(); + return decoder; +} + +// Read a general purpose guest register. Anything else (segments, flags, SIMD) is not addressable +// through a legacy memory operand, so reporting 0 for it cannot make a real fault address wrong. +uint64_t ReadGuestRegister(ZydisRegister reg, const GuestX64Registers& registers) { + const auto wide = + ZydisRegisterGetLargestEnclosing(ZYDIS_MACHINE_MODE_LONG_64, reg); + switch (wide) { + case ZYDIS_REGISTER_RAX: return registers.rax; + case ZYDIS_REGISTER_RBX: return registers.rbx; + case ZYDIS_REGISTER_RCX: return registers.rcx; + case ZYDIS_REGISTER_RDX: return registers.rdx; + case ZYDIS_REGISTER_RSI: return registers.rsi; + case ZYDIS_REGISTER_RDI: return registers.rdi; + case ZYDIS_REGISTER_RBP: return registers.rbp; + case ZYDIS_REGISTER_RSP: return registers.rsp; + case ZYDIS_REGISTER_R8: return registers.r8; + case ZYDIS_REGISTER_R9: return registers.r9; + case ZYDIS_REGISTER_R10: return registers.r10; + case ZYDIS_REGISTER_R11: return registers.r11; + case ZYDIS_REGISTER_R12: return registers.r12; + case ZYDIS_REGISTER_R13: return registers.r13; + case ZYDIS_REGISTER_R14: return registers.r14; + case ZYDIS_REGISTER_R15: return registers.r15; + case ZYDIS_REGISTER_RIP: return registers.rip; + default: return 0; + } +} + +bool IsGeneralPurposeRegister(ZydisRegister reg) { + switch (ZydisRegisterGetLargestEnclosing(ZYDIS_MACHINE_MODE_LONG_64, reg)) { + case ZYDIS_REGISTER_RAX: + case ZYDIS_REGISTER_RBX: + case ZYDIS_REGISTER_RCX: + case ZYDIS_REGISTER_RDX: + case ZYDIS_REGISTER_RSI: + case ZYDIS_REGISTER_RDI: + case ZYDIS_REGISTER_RBP: + case ZYDIS_REGISTER_RSP: + case ZYDIS_REGISTER_R8: + case ZYDIS_REGISTER_R9: + case ZYDIS_REGISTER_R10: + case ZYDIS_REGISTER_R11: + case ZYDIS_REGISTER_R12: + case ZYDIS_REGISTER_R13: + case ZYDIS_REGISTER_R14: + case ZYDIS_REGISTER_R15: + case ZYDIS_REGISTER_RIP: return true; + default: return false; + } +} + +// ZydisCalcAbsoluteAddress only covers relative immediates and RIP-relative or absolute memory, so +// a base+index*scale+disp operand has to be resolved from the register file by hand. +uint64_t ResolveMemoryOperand(const ZydisDecodedInstruction& instruction, + const ZydisDecodedOperand& operand, + const GuestX64Registers& registers) { + // RIP-relative operands are already anchored past the end of the instruction. + const auto base = + operand.mem.base == ZYDIS_REGISTER_RIP + ? registers.rip + instruction.length + : ReadGuestRegister(operand.mem.base, registers); + uint64_t index = 0; + if (operand.mem.index != ZYDIS_REGISTER_NONE && + operand.mem.index != ZYDIS_REGISTER_RIP) { + index = ReadGuestRegister(operand.mem.index, registers); + } + return base + index * static_cast<uint64_t>(operand.mem.scale) + + static_cast<uint64_t>(operand.mem.disp.value); +} + +// The AT&T-style width prefix, so a memory operand keeps the size a reader needs. Without it +// "[0x1000]" is ambiguous between a byte load and a 16-byte one. +const char* OperandWidthName(uint16_t bits) { + switch (bits) { + case 8: return "byte ptr "; + case 16: return "word ptr "; + case 32: return "dword ptr "; + case 64: return "qword ptr "; + case 128: return "xmmword ptr "; + case 256: return "ymmword ptr "; + case 512: return "zmmword ptr "; + default: return ""; + } +} + +// Bounded append into a fixed buffer: this runs on the fatal path, where a truncation is fine but +// an overrun is not. +size_t Append(char* text, size_t capacity, size_t used, const char* format, ...) { + if (used >= capacity) { + return used; + } + va_list args; + va_start(args, format); + const int written = std::vsnprintf(text + used, capacity - used, format, args); + va_end(args); + if (written < 0) { + return used; + } + const auto advance = static_cast<size_t>(written); + return advance < capacity - used ? used + advance : capacity - 1; +} + +} // namespace + +GuestFaultingInstruction DecodeGuestFaultingInstruction(const uint8_t* code, size_t available, + const GuestX64Registers& registers) { + GuestFaultingInstruction result; + if (code == nullptr || available == 0) { + std::snprintf(result.text, sizeof(result.text), "<no readable instruction bytes>"); + return result; + } + + ZydisDecodedInstruction instruction {}; + std::array<ZydisDecodedOperand, ZYDIS_MAX_OPERAND_COUNT> operands {}; + const auto status = ZydisDecoderDecodeFull(&GuestDecoder(), code, available, &instruction, + operands.data()); + if (!ZYAN_SUCCESS(status) || instruction.length == 0) { + std::snprintf(result.text, sizeof(result.text), "<undecodable instruction>"); + return result; + } + + result.decoded = true; + result.length = instruction.length; + + size_t used = 0; + used = Append(result.text, sizeof(result.text), used, "%s", + ZydisMnemonicGetString(instruction.mnemonic)); + + // LEA and the padding NOPs name an address without touching it, so they must not be reported + // as the memory access that faulted. + const bool computes_address_only = instruction.mnemonic == ZYDIS_MNEMONIC_LEA || + instruction.mnemonic == ZYDIS_MNEMONIC_NOP; + constexpr ZydisOperandActions memory_access = + ZYDIS_OPERAND_ACTION_MASK_READ | ZYDIS_OPERAND_ACTION_MASK_WRITE; + + for (uint8_t index = 0; index < instruction.operand_count_visible; index++) { + const auto& operand = operands[index]; + used = Append(result.text, sizeof(result.text), used, index == 0 ? " " : ", "); + + switch (operand.type) { + case ZYDIS_OPERAND_TYPE_REGISTER: + used = Append(result.text, sizeof(result.text), used, "%s", + ZydisRegisterGetString(operand.reg.value)); + break; + + case ZYDIS_OPERAND_TYPE_IMMEDIATE: { + if (operand.imm.is_relative) { + uint64_t target = 0; + if (ZYAN_SUCCESS(ZydisCalcAbsoluteAddress(&instruction, &operand, + registers.rip, &target))) { + used = Append(result.text, sizeof(result.text), used, + "0x%016" PRIx64, target); + break; + } + } + used = Append(result.text, sizeof(result.text), used, "0x%" PRIx64, + operand.imm.value.u); + } break; + + case ZYDIS_OPERAND_TYPE_MEMORY: { + const uint64_t address = ResolveMemoryOperand(instruction, operand, registers); + const bool resolved = + IsGeneralPurposeRegister(operand.mem.base) && + (operand.mem.index == ZYDIS_REGISTER_NONE || + IsGeneralPurposeRegister(operand.mem.index)); ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **Fix the "unresolved" labeling rule.** `resolved` requires `IsGeneralPurposeRegister(operand.mem.base)`. `ZYDIS_REGISTER_NONE` is not a general purpose register. The rule is wrong in two ways: - **Absolute and index-only operands:** for `[0x1000]`, `moffs` and `[rcx*8+disp]`, `ResolveMemoryOperand` computes the correct address. The text still shows `unresolved`. - **`fs:`/`gs:` operands:** for `fs:[rax]` or `gs:[0x28]`, the segment base is not included. The operand can still be labeled resolved, and `effective_address` records the wrong address. Treat a missing base or index as resolved. Mark FS/GS-segment operands unresolved, and do not report their `effective_address` as the fault address. <details> <summary>🐛 Proposed fix</summary> ```diff - const bool resolved = - IsGeneralPurposeRegister(operand.mem.base) && - (operand.mem.index == ZYDIS_REGISTER_NONE || - IsGeneralPurposeRegister(operand.mem.index)); + const bool segment_based = operand.mem.segment == ZYDIS_REGISTER_FS || + operand.mem.segment == ZYDIS_REGISTER_GS; + const bool resolved = + !segment_based && + (operand.mem.base == ZYDIS_REGISTER_NONE || + IsGeneralPurposeRegister(operand.mem.base)) && + (operand.mem.index == ZYDIS_REGISTER_NONE || + IsGeneralPurposeRegister(operand.mem.index)); ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion const bool segment_based = operand.mem.segment == ZYDIS_REGISTER_FS || operand.mem.segment == ZYDIS_REGISTER_GS; const bool resolved = !segment_based && (operand.mem.base == ZYDIS_REGISTER_NONE || IsGeneralPurposeRegister(operand.mem.base)) && (operand.mem.index == ZYDIS_REGISTER_NONE || IsGeneralPurposeRegister(operand.mem.index)); ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:5f95591b40f3ab6480146b3a --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit 484c0dc
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 01:36 UTC · original · reviewed

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: f1c27df5-6f38-42d2-9713-c822fbbb508a

📥 Commits

Reviewing files that changed from the base of the PR and between d875ddd9f9 and da13cfc77e.

📒 Files selected for processing (5)
  • src/loader/runtimeLinker.cpp
  • src/loader/runtimeLinker.h
  • src/loader/x64InstructionDecoder.cpp
  • src/loader/x64InstructionDecoder.h
  • tests/VirtualMemoryAllocationTests.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/loader/runtimeLinker.h

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 01:36 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836#pullrequestreview-5324036495) · **reviewed** **Actionable comments posted: 2** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `f1c27df5-6f38-42d2-9713-c822fbbb508a` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between d875ddd9f9a62f904bc986267b7925487cb7096f and da13cfc77e30f6c34004b45015aab6ece2f42a9b. </details> <details> <summary>📒 Files selected for processing (5)</summary> * `src/loader/runtimeLinker.cpp` * `src/loader/runtimeLinker.h` * `src/loader/x64InstructionDecoder.cpp` * `src/loader/x64InstructionDecoder.h` * `tests/VirtualMemoryAllocationTests.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary> * src/loader/runtimeLinker.h </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 01:36 UTC · original
On src/loader/runtimeLinker.cpp line 1596 (outdated):

@@ -1495,6 +1560,42 @@ Program* RuntimeLinker::FindProgramByFileName(const std::filesystem::path& elf_n
 	return nullptr;
 }
 
+// Same segment walk as FindProgramByAddr, but usable from the fatal fault reporter: it takes
+// no lock when the linker is busy, tolerates a program whose Elf64 is not loaded yet and never
+// raises, so a crash report cannot hang or recurse inside its own handler.
+Program* RuntimeLinker::TryFindProgramByAddr(uint64_t vaddr) {
+	if (!m_mutex.TryLock()) {
+		return nullptr;
+	}
+	Program* found = nullptr;
+	for (auto* p: m_programs) {
+		if (p == nullptr || p->elf == nullptr) {
+			continue;
+		}
+		const auto* ehdr = p->elf->GetEhdr();
+		const auto* phdr = p->elf->GetPhdr();
+		if (ehdr == nullptr || phdr == nullptr) {
+			continue;
+		}
+		for (Elf64_Half i = 0; i < ehdr->e_phnum; i++) {
+			if (phdr[i].p_memsz != 0 &&
+			    (phdr[i].p_type == PT_LOAD || phdr[i].p_type == PT_OS_RELRO)) {
+				const uint64_t segment_addr = phdr[i].p_vaddr + p->base_vaddr;
+				const uint64_t segment_size = GetAlignedSize(phdr + i);
+				if (vaddr >= segment_addr && vaddr < segment_addr + segment_size) {
+					found = p;
+					break;
+				}
+			}
+		}
+		if (found != nullptr) {
+			break;
+		}
+	}
+	m_mutex.Unlock();
+	return found;
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
ast-grep outline src/loader/runtimeLinker.h --match 'GuestModuleInfo|TryDescribeProgramByAddr' --view expanded || true
ast-grep outline src/loader/runtimeLinker.cpp --match 'TryDescribeProgramByAddr|ReportGuestAddress|GetProgramModuleName|UnloadProgram' --view expanded || true
rg -n -C 5 'GuestModuleInfo|TryDescribeProgramByAddr|TryFindProgramByAddr|GetProgramModuleName|void RuntimeLinker::UnloadProgram' src/loader/runtimeLinker.h src/loader/runtimeLinker.cpp

Length of output: 9557


@theantipopau, thanks for the shell results. They verify that TryDescribeProgramByAddr() copies the module name and base address while m_mutex is held. Both report paths use the returned snapshot, so the reported Program* lifetime issue is fixed. My earlier statement that repository verification was unavailable was incorrect.

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 01:36 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836#discussion_r4109751359) On `src/loader/runtimeLinker.cpp` line 1596 (outdated): ```diff @@ -1495,6 +1560,42 @@ Program* RuntimeLinker::FindProgramByFileName(const std::filesystem::path& elf_n return nullptr; } +// Same segment walk as FindProgramByAddr, but usable from the fatal fault reporter: it takes +// no lock when the linker is busy, tolerates a program whose Elf64 is not loaded yet and never +// raises, so a crash report cannot hang or recurse inside its own handler. +Program* RuntimeLinker::TryFindProgramByAddr(uint64_t vaddr) { + if (!m_mutex.TryLock()) { + return nullptr; + } + Program* found = nullptr; + for (auto* p: m_programs) { + if (p == nullptr || p->elf == nullptr) { + continue; + } + const auto* ehdr = p->elf->GetEhdr(); + const auto* phdr = p->elf->GetPhdr(); + if (ehdr == nullptr || phdr == nullptr) { + continue; + } + for (Elf64_Half i = 0; i < ehdr->e_phnum; i++) { + if (phdr[i].p_memsz != 0 && + (phdr[i].p_type == PT_LOAD || phdr[i].p_type == PT_OS_RELRO)) { + const uint64_t segment_addr = phdr[i].p_vaddr + p->base_vaddr; + const uint64_t segment_size = GetAlignedSize(phdr + i); + if (vaddr >= segment_addr && vaddr < segment_addr + segment_size) { + found = p; + break; + } + } + } + if (found != nullptr) { + break; + } + } + m_mutex.Unlock(); + return found; ``` <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ```shell #!/bin/bash set -euo pipefail ast-grep outline src/loader/runtimeLinker.h --match 'GuestModuleInfo|TryDescribeProgramByAddr' --view expanded || true ast-grep outline src/loader/runtimeLinker.cpp --match 'TryDescribeProgramByAddr|ReportGuestAddress|GetProgramModuleName|UnloadProgram' --view expanded || true rg -n -C 5 'GuestModuleInfo|TryDescribeProgramByAddr|TryFindProgramByAddr|GetProgramModuleName|void RuntimeLinker::UnloadProgram' src/loader/runtimeLinker.h src/loader/runtimeLinker.cpp ``` Length of output: 9557 --- </details> `@theantipopau`, thanks for the shell results. They verify that `TryDescribeProgramByAddr()` copies the module name and base address while `m_mutex` is held. Both report paths use the returned snapshot, so the reported `Program*` lifetime issue is fixed. My earlier statement that repository verification was unavailable was incorrect. ✅ 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-09-26 01:37 UTC · original
On src/loader/runtimeLinker.cpp line 1242 (outdated):

@@ -1178,14 +1235,22 @@ void RuntimeLinker::UnloadProgram(Program* program) {
 	DeleteProgram(program);
 }
 
+RuntimeLinker* RuntimeLinker::s_current = nullptr;
+
 RuntimeLinker::RuntimeLinker(): m_symbols(std::make_unique<SymbolDatabase>()) {
 	EXIT_NOT_IMPLEMENTED(!Common::Thread::IsMainThread());
+	s_current = this;

@theantipopau, thanks for the precise distinction. The atomic s_current removes the data race on the pointer. Storing nullptr before Clear() prevents later loads from obtaining the linker, but it does not protect a reporter that already loaded the pointer.

I would leave the lifetime concern open rather than ask for a partial pin-or-defer scheme in this PR. A follow-up should define how in-flight reporters finish before linker teardown without making the fault handler wait on a lock. Would you like me to open a GitHub issue for that work?


✏️ Learnings added
Learnt from: theantipopau
Repo: KytyPS5/KytyPS5 PR: 836
File: src/loader/runtimeLinker.cpp:0-0
Timestamp: 2026-09-26T01:37:09.382Z
Learning: In `src/loader/runtimeLinker.cpp`, `RuntimeLinker::s_current` is an atomic pointer read by the guest fault reporter. `RuntimeLinker::~RuntimeLinker()` stores `nullptr` before `Clear()`, which addresses the pointer data race but does not protect a reporter that loaded the pointer before teardown. A lifetime fix must account for in-flight fault reports without assuming that an atomic pointer pins the `RuntimeLinker`.

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.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 01:37 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836#discussion_r4109752136) On `src/loader/runtimeLinker.cpp` line 1242 (outdated): ```diff @@ -1178,14 +1235,22 @@ void RuntimeLinker::UnloadProgram(Program* program) { DeleteProgram(program); } +RuntimeLinker* RuntimeLinker::s_current = nullptr; + RuntimeLinker::RuntimeLinker(): m_symbols(std::make_unique<SymbolDatabase>()) { EXIT_NOT_IMPLEMENTED(!Common::Thread::IsMainThread()); + s_current = this; ``` `@theantipopau`, thanks for the precise distinction. The atomic `s_current` removes the data race on the pointer. Storing `nullptr` before `Clear()` prevents later loads from obtaining the linker, but it does not protect a reporter that already loaded the pointer. I would leave the lifetime concern open rather than ask for a partial pin-or-defer scheme in this PR. A follow-up should define how in-flight reporters finish before linker teardown without making the fault handler wait on a lock. Would you like me to open a GitHub issue for that work? --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: theantipopau Repo: KytyPS5/KytyPS5 PR: 836 File: src/loader/runtimeLinker.cpp:0-0 Timestamp: 2026-09-26T01:37:09.382Z Learning: In `src/loader/runtimeLinker.cpp`, `RuntimeLinker::s_current` is an atomic pointer read by the guest fault reporter. `RuntimeLinker::~RuntimeLinker()` stores `nullptr` before `Clear()`, which addresses the pointer data race but does not protect a reporter that loaded the pointer before teardown. A lifetime fix must account for in-flight fault reports without assuming that an atomic pointer pins the `RuntimeLinker`. ``` > 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> _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠theantipopau on GitHub · 2026-09-26 02:00 UTC · original
On src/loader/runtimeLinker.cpp line 1242 (outdated):

@@ -1178,14 +1235,22 @@ void RuntimeLinker::UnloadProgram(Program* program) {
 	DeleteProgram(program);
 }
 
+RuntimeLinker* RuntimeLinker::s_current = nullptr;
+
 RuntimeLinker::RuntimeLinker(): m_symbols(std::make_unique<SymbolDatabase>()) {
 	EXIT_NOT_IMPLEMENTED(!Common::Thread::IsMainThread());
+	s_current = this;

Closed in 1cd7a72c, with a report gate rather than a pin or deferred teardown.

s_current being atomic was never the hard part; the hard part is that a report must not be holding a pointer to a linker whose state is being freed. So publication and teardown are now gated together:

static Common::Mutex g_report_gate;

The reporter takes it with TryLock for the whole attribution pass, and the destructor takes it with a real lock before clearing the pointer:

RuntimeLinker::~RuntimeLinker() {
    {
        Common::LockGuard lock(g_report_gate);
        s_current.store(nullptr);
    }
    Clear();
}

That gives the ordering the atomic alone could not: once the destructor's gate section completes, no report can obtain a non-null pointer, and any report that already had one has finished, because it held the gate for its entire use of the linker. Clear() then runs with no reader.

Two details worth calling out:

  • TryLock, not Lock, in the reporter. A fault must never block. Losing the race against teardown costs only the module names and falls back to the same module=<unknown> output a busy linker already produces, which is why the existing TryDescribeProgramByAddr is already written to degrade that way.
  • s_current is tested before the gate is touched, and re-read under it. Testing first means a fault that arrives before this translation unit is dynamically initialised never touches an unconstructed Common::Mutex. Re-reading under the gate is what makes the pairing airtight: if the destructor cleared the pointer between the first read and the lock, the re-read returns null and attribution is skipped rather than reading a linker mid-destruction.

Verified: kyty_emulator builds and virtual_memory_allocation_tests passes, including GuestFaultFrameAttribution and GuestFaultInstructionDecoding.

One thing I did not do: add a unit test. The existing tests deliberately cover only the pure parts of this path (FormatGuestFrame) without loading a program, and a deterministic test for this race needs a real RuntimeLinker being constructed and destroyed on the main thread while a worker reads — which is not something the current test harness can host. So this is verified by construction and review rather than by a targeted test, and I would rather say that than add a test that only appears to cover it.

**@⁠theantipopau** on GitHub · 2026-09-26 02:00 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836#discussion_r4109814152) On `src/loader/runtimeLinker.cpp` line 1242 (outdated): ```diff @@ -1178,14 +1235,22 @@ void RuntimeLinker::UnloadProgram(Program* program) { DeleteProgram(program); } +RuntimeLinker* RuntimeLinker::s_current = nullptr; + RuntimeLinker::RuntimeLinker(): m_symbols(std::make_unique<SymbolDatabase>()) { EXIT_NOT_IMPLEMENTED(!Common::Thread::IsMainThread()); + s_current = this; ``` Closed in `1cd7a72c`, with a report gate rather than a pin or deferred teardown. `s_current` being atomic was never the hard part; the hard part is that a report must not be holding a pointer to a linker whose state is being freed. So publication and teardown are now gated together: ```cpp static Common::Mutex g_report_gate; ``` The reporter takes it with `TryLock` for the whole attribution pass, and the destructor takes it with a real lock before clearing the pointer: ```cpp RuntimeLinker::~RuntimeLinker() { { Common::LockGuard lock(g_report_gate); s_current.store(nullptr); } Clear(); } ``` That gives the ordering the atomic alone could not: once the destructor's gate section completes, no report can obtain a non-null pointer, and any report that already had one has finished, because it held the gate for its entire use of the linker. `Clear()` then runs with no reader. Two details worth calling out: - **`TryLock`, not `Lock`, in the reporter.** A fault must never block. Losing the race against teardown costs only the module names and falls back to the same `module=<unknown>` output a busy linker already produces, which is why the existing `TryDescribeProgramByAddr` is already written to degrade that way. - **`s_current` is tested before the gate is touched, and re-read under it.** Testing first means a fault that arrives before this translation unit is dynamically initialised never touches an unconstructed `Common::Mutex`. Re-reading under the gate is what makes the pairing airtight: if the destructor cleared the pointer between the first read and the lock, the re-read returns null and attribution is skipped rather than reading a linker mid-destruction. Verified: `kyty_emulator` builds and `virtual_memory_allocation_tests` passes, including `GuestFaultFrameAttribution` and `GuestFaultInstructionDecoding`. One thing I did **not** do: add a unit test. The existing tests deliberately cover only the pure parts of this path (`FormatGuestFrame`) without loading a program, and a deterministic test for this race needs a real `RuntimeLinker` being constructed and destroyed on the main thread while a worker reads — which is not something the current test harness can host. So this is verified by construction and review rather than by a targeted test, and I would rather say that than add a test that only appears to cover it.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 02:14 UTC · original
On src/loader/runtimeLinker.cpp line 1242 (outdated):

@@ -1178,14 +1235,22 @@ void RuntimeLinker::UnloadProgram(Program* program) {
 	DeleteProgram(program);
 }
 
+RuntimeLinker* RuntimeLinker::s_current = nullptr;
+
 RuntimeLinker::RuntimeLinker(): m_symbols(std::make_unique<SymbolDatabase>()) {
 	EXIT_NOT_IMPLEMENTED(!Common::Thread::IsMainThread());
+	s_current = this;
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
fd -i 'threads\.(h|cpp)$' .
rg -n -C 5 'class Mutex\b|struct Mutex\b|bool TryLock\s*\(|void Lock\s*\(|void Unlock\s*\(' src/common -g '*threads*'
git status --short
git rev-parse --short HEAD

Length of output: 1051


🏁 Script executed:

#!/bin/bash
set -euo pipefail
ast-grep outline src/common/threads.cpp --match Mutex --view expanded
rg -n -C 12 'Mutex::(Mutex|~Mutex|Lock|Unlock|TryLock)\s*\(' src/common/threads.cpp

Length of output: 1744


@theantipopau, thanks for the verification details. Common::Mutex::TryLock() uses a non-blocking platform call, and Lock() waits for the gate. In 1cd7a72, the reporter re-reads s_current after taking the gate and holds it throughout linker attribution. The destructor clears s_current under the same gate before Clear(). This addresses the reported lifetime race. I agree that the existing tests do not directly exercise this race.


🧠 Learnings used
Learnt from: theantipopau
Repo: KytyPS5/KytyPS5

Timestamp: 2026-09-26T01:37:13.538Z
Learning: In `src/loader/runtimeLinker.cpp`, `RuntimeLinker::s_current` is an atomic pointer read by the guest fault reporter. `RuntimeLinker::~RuntimeLinker()` stores `nullptr` before `Clear()`, which addresses the pointer data race but does not protect a reporter that loaded the pointer before teardown. A lifetime fix must account for in-flight fault reports without assuming that an atomic pointer pins the `RuntimeLinker`.

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 02:14 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836#discussion_r4109849022) On `src/loader/runtimeLinker.cpp` line 1242 (outdated): ```diff @@ -1178,14 +1235,22 @@ void RuntimeLinker::UnloadProgram(Program* program) { DeleteProgram(program); } +RuntimeLinker* RuntimeLinker::s_current = nullptr; + RuntimeLinker::RuntimeLinker(): m_symbols(std::make_unique<SymbolDatabase>()) { EXIT_NOT_IMPLEMENTED(!Common::Thread::IsMainThread()); + s_current = this; ``` <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ```shell #!/bin/bash set -euo pipefail fd -i 'threads\.(h|cpp)$' . rg -n -C 5 'class Mutex\b|struct Mutex\b|bool TryLock\s*\(|void Lock\s*\(|void Unlock\s*\(' src/common -g '*threads*' git status --short git rev-parse --short HEAD ``` Length of output: 1051 --- 🏁 Script executed: ```shell #!/bin/bash set -euo pipefail ast-grep outline src/common/threads.cpp --match Mutex --view expanded rg -n -C 12 'Mutex::(Mutex|~Mutex|Lock|Unlock|TryLock)\s*\(' src/common/threads.cpp ``` Length of output: 1744 --- </details> `@theantipopau`, thanks for the verification details. `Common::Mutex::TryLock()` uses a non-blocking platform call, and `Lock()` waits for the gate. In `1cd7a72`, the reporter re-reads `s_current` after taking the gate and holds it throughout linker attribution. The destructor clears `s_current` under the same gate before `Clear()`. This addresses the reported lifetime race. I agree that the existing tests do not directly exercise this race. --- <details> <summary>🧠 Learnings used</summary> ``` Learnt from: theantipopau Repo: KytyPS5/KytyPS5 Timestamp: 2026-09-26T01:37:13.538Z Learning: In `src/loader/runtimeLinker.cpp`, `RuntimeLinker::s_current` is an atomic pointer read by the guest fault reporter. `RuntimeLinker::~RuntimeLinker()` stores `nullptr` before `Clear()`, which addresses the pointer data race but does not protect a reporter that loaded the pointer before teardown. A lifetime fix must account for in-flight fault reports without assuming that an atomic pointer pins the `RuntimeLinker`. ``` </details> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠theantipopau on GitHub · 2026-09-26 03:15 UTC · original
On src/loader/x64InstructionDecoder.cpp line 189 (outdated):

@@ -0,0 +1,218 @@
+#include "loader/x64InstructionDecoder.h"
+
+#include <Zydis/Zydis.h>
+
+#include <array>
+#include <cinttypes>
+#include <cstdarg>
+#include <cstdio>
+
+namespace Loader {
+
+namespace {
+
+// One decoder, shared with the rest of the loader the same way redZonePatcher keeps its own.
+// ZydisDecoderInit only fills a plain struct, so constructing it lazily from the fault reporter
+// is cheap and cannot allocate.
+ZydisDecoder& GuestDecoder() {
+	static ZydisDecoder decoder = [] {
+		ZydisDecoder value {};
+		ZydisDecoderInit(&value, ZYDIS_MACHINE_MODE_LONG_64, ZYDIS_STACK_WIDTH_64);
+		return value;
+	}();
+	return decoder;
+}
+
+// Read a general purpose guest register. Anything else (segments, flags, SIMD) is not addressable
+// through a legacy memory operand, so reporting 0 for it cannot make a real fault address wrong.
+uint64_t ReadGuestRegister(ZydisRegister reg, const GuestX64Registers& registers) {
+	const auto wide =
+	    ZydisRegisterGetLargestEnclosing(ZYDIS_MACHINE_MODE_LONG_64, reg);
+	switch (wide) {
+		case ZYDIS_REGISTER_RAX: return registers.rax;
+		case ZYDIS_REGISTER_RBX: return registers.rbx;
+		case ZYDIS_REGISTER_RCX: return registers.rcx;
+		case ZYDIS_REGISTER_RDX: return registers.rdx;
+		case ZYDIS_REGISTER_RSI: return registers.rsi;
+		case ZYDIS_REGISTER_RDI: return registers.rdi;
+		case ZYDIS_REGISTER_RBP: return registers.rbp;
+		case ZYDIS_REGISTER_RSP: return registers.rsp;
+		case ZYDIS_REGISTER_R8: return registers.r8;
+		case ZYDIS_REGISTER_R9: return registers.r9;
+		case ZYDIS_REGISTER_R10: return registers.r10;
+		case ZYDIS_REGISTER_R11: return registers.r11;
+		case ZYDIS_REGISTER_R12: return registers.r12;
+		case ZYDIS_REGISTER_R13: return registers.r13;
+		case ZYDIS_REGISTER_R14: return registers.r14;
+		case ZYDIS_REGISTER_R15: return registers.r15;
+		case ZYDIS_REGISTER_RIP: return registers.rip;
+		default: return 0;
+	}
+}
+
+bool IsGeneralPurposeRegister(ZydisRegister reg) {
+	switch (ZydisRegisterGetLargestEnclosing(ZYDIS_MACHINE_MODE_LONG_64, reg)) {
+		case ZYDIS_REGISTER_RAX:
+		case ZYDIS_REGISTER_RBX:
+		case ZYDIS_REGISTER_RCX:
+		case ZYDIS_REGISTER_RDX:
+		case ZYDIS_REGISTER_RSI:
+		case ZYDIS_REGISTER_RDI:
+		case ZYDIS_REGISTER_RBP:
+		case ZYDIS_REGISTER_RSP:
+		case ZYDIS_REGISTER_R8:
+		case ZYDIS_REGISTER_R9:
+		case ZYDIS_REGISTER_R10:
+		case ZYDIS_REGISTER_R11:
+		case ZYDIS_REGISTER_R12:
+		case ZYDIS_REGISTER_R13:
+		case ZYDIS_REGISTER_R14:
+		case ZYDIS_REGISTER_R15:
+		case ZYDIS_REGISTER_RIP: return true;
+		default: return false;
+	}
+}
+
+// ZydisCalcAbsoluteAddress only covers relative immediates and RIP-relative or absolute memory, so
+// a base+index*scale+disp operand has to be resolved from the register file by hand.
+uint64_t ResolveMemoryOperand(const ZydisDecodedInstruction& instruction,
+                              const ZydisDecodedOperand&         operand,
+                              const GuestX64Registers&            registers) {
+	// RIP-relative operands are already anchored past the end of the instruction.
+	const auto base =
+	    operand.mem.base == ZYDIS_REGISTER_RIP
+	        ? registers.rip + instruction.length
+	        : ReadGuestRegister(operand.mem.base, registers);
+	uint64_t index = 0;
+	if (operand.mem.index != ZYDIS_REGISTER_NONE &&
+	    operand.mem.index != ZYDIS_REGISTER_RIP) {
+		index = ReadGuestRegister(operand.mem.index, registers);
+	}
+	return base + index * static_cast<uint64_t>(operand.mem.scale) +
+	       static_cast<uint64_t>(operand.mem.disp.value);
+}
+
+// The AT&T-style width prefix, so a memory operand keeps the size a reader needs. Without it
+// "[0x1000]" is ambiguous between a byte load and a 16-byte one.
+const char* OperandWidthName(uint16_t bits) {
+	switch (bits) {
+		case 8: return "byte ptr ";
+		case 16: return "word ptr ";
+		case 32: return "dword ptr ";
+		case 64: return "qword ptr ";
+		case 128: return "xmmword ptr ";
+		case 256: return "ymmword ptr ";
+		case 512: return "zmmword ptr ";
+		default: return "";
+	}
+}
+
+// Bounded append into a fixed buffer: this runs on the fatal path, where a truncation is fine but
+// an overrun is not.
+size_t Append(char* text, size_t capacity, size_t used, const char* format, ...) {
+	if (used >= capacity) {
+		return used;
+	}
+	va_list args;
+	va_start(args, format);
+	const int written = std::vsnprintf(text + used, capacity - used, format, args);
+	va_end(args);
+	if (written < 0) {
+		return used;
+	}
+	const auto advance = static_cast<size_t>(written);
+	return advance < capacity - used ? used + advance : capacity - 1;
+}
+
+} // namespace
+
+GuestFaultingInstruction DecodeGuestFaultingInstruction(const uint8_t* code, size_t available,
+                                                        const GuestX64Registers& registers) {
+	GuestFaultingInstruction result;
+	if (code == nullptr || available == 0) {
+		std::snprintf(result.text, sizeof(result.text), "<no readable instruction bytes>");
+		return result;
+	}
+
+	ZydisDecodedInstruction instruction {};
+	std::array<ZydisDecodedOperand, ZYDIS_MAX_OPERAND_COUNT> operands {};
+	const auto status = ZydisDecoderDecodeFull(&GuestDecoder(), code, available, &instruction,
+	                                           operands.data());
+	if (!ZYAN_SUCCESS(status) || instruction.length == 0) {
+		std::snprintf(result.text, sizeof(result.text), "<undecodable instruction>");
+		return result;
+	}
+
+	result.decoded = true;
+	result.length  = instruction.length;
+
+	size_t used = 0;
+	used = Append(result.text, sizeof(result.text), used, "%s",
+	              ZydisMnemonicGetString(instruction.mnemonic));
+
+	// LEA and the padding NOPs name an address without touching it, so they must not be reported
+	// as the memory access that faulted.
+	const bool computes_address_only = instruction.mnemonic == ZYDIS_MNEMONIC_LEA ||
+	                                   instruction.mnemonic == ZYDIS_MNEMONIC_NOP;
+	constexpr ZydisOperandActions memory_access =
+	    ZYDIS_OPERAND_ACTION_MASK_READ | ZYDIS_OPERAND_ACTION_MASK_WRITE;
+
+	for (uint8_t index = 0; index < instruction.operand_count_visible; index++) {
+		const auto& operand = operands[index];
+		used = Append(result.text, sizeof(result.text), used, index == 0 ? " " : ", ");
+
+		switch (operand.type) {
+			case ZYDIS_OPERAND_TYPE_REGISTER:
+				used = Append(result.text, sizeof(result.text), used, "%s",
+				              ZydisRegisterGetString(operand.reg.value));
+				break;
+
+			case ZYDIS_OPERAND_TYPE_IMMEDIATE: {
+				if (operand.imm.is_relative) {
+					uint64_t target = 0;
+					if (ZYAN_SUCCESS(ZydisCalcAbsoluteAddress(&instruction, &operand,
+					                                          registers.rip, &target))) {
+						used = Append(result.text, sizeof(result.text), used,
+						              "0x%016" PRIx64, target);
+						break;
+					}
+				}
+				used = Append(result.text, sizeof(result.text), used, "0x%" PRIx64,
+				              operand.imm.value.u);
+			} break;
+
+			case ZYDIS_OPERAND_TYPE_MEMORY: {
+				const uint64_t address = ResolveMemoryOperand(instruction, operand, registers);
+				const bool     resolved =
+				    IsGeneralPurposeRegister(operand.mem.base) &&
+				    (operand.mem.index == ZYDIS_REGISTER_NONE ||
+				     IsGeneralPurposeRegister(operand.mem.index));

Fixed in 484c0dc4.

resolved now requires only that any present base/index be a general-purpose register — ZYDIS_REGISTER_NONE for either no longer forces "unresolved", so [0x1000], moffs and index-only operands like [rcx*8+disp] now print without the label.

For fs:/gs: I went with the conservative half of your second point rather than reporting an address: GuestX64Registers carries no segment bases, so there is nothing to resolve against, and a seg:[offset] value is not a linear address. Those operands are marked unresolved and, because the consumer at runtimeLinker.cpp:791 prints fault addr from insn whenever reads_memory || writes_memory, the resolved flag now also gates the access flags — so fs:/gs: accesses never report their segment-relative offset as effective_address.

Rebuilt kyty_emulator + virtual_memory_allocation_tests; the suite including GuestFaultInstructionDecoding passes (after the usual 13824 MB reservation retry).

**@⁠theantipopau** on GitHub · 2026-09-26 03:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836#discussion_r4109995229) On `src/loader/x64InstructionDecoder.cpp` line 189 (outdated): ```diff @@ -0,0 +1,218 @@ +#include "loader/x64InstructionDecoder.h" + +#include <Zydis/Zydis.h> + +#include <array> +#include <cinttypes> +#include <cstdarg> +#include <cstdio> + +namespace Loader { + +namespace { + +// One decoder, shared with the rest of the loader the same way redZonePatcher keeps its own. +// ZydisDecoderInit only fills a plain struct, so constructing it lazily from the fault reporter +// is cheap and cannot allocate. +ZydisDecoder& GuestDecoder() { + static ZydisDecoder decoder = [] { + ZydisDecoder value {}; + ZydisDecoderInit(&value, ZYDIS_MACHINE_MODE_LONG_64, ZYDIS_STACK_WIDTH_64); + return value; + }(); + return decoder; +} + +// Read a general purpose guest register. Anything else (segments, flags, SIMD) is not addressable +// through a legacy memory operand, so reporting 0 for it cannot make a real fault address wrong. +uint64_t ReadGuestRegister(ZydisRegister reg, const GuestX64Registers& registers) { + const auto wide = + ZydisRegisterGetLargestEnclosing(ZYDIS_MACHINE_MODE_LONG_64, reg); + switch (wide) { + case ZYDIS_REGISTER_RAX: return registers.rax; + case ZYDIS_REGISTER_RBX: return registers.rbx; + case ZYDIS_REGISTER_RCX: return registers.rcx; + case ZYDIS_REGISTER_RDX: return registers.rdx; + case ZYDIS_REGISTER_RSI: return registers.rsi; + case ZYDIS_REGISTER_RDI: return registers.rdi; + case ZYDIS_REGISTER_RBP: return registers.rbp; + case ZYDIS_REGISTER_RSP: return registers.rsp; + case ZYDIS_REGISTER_R8: return registers.r8; + case ZYDIS_REGISTER_R9: return registers.r9; + case ZYDIS_REGISTER_R10: return registers.r10; + case ZYDIS_REGISTER_R11: return registers.r11; + case ZYDIS_REGISTER_R12: return registers.r12; + case ZYDIS_REGISTER_R13: return registers.r13; + case ZYDIS_REGISTER_R14: return registers.r14; + case ZYDIS_REGISTER_R15: return registers.r15; + case ZYDIS_REGISTER_RIP: return registers.rip; + default: return 0; + } +} + +bool IsGeneralPurposeRegister(ZydisRegister reg) { + switch (ZydisRegisterGetLargestEnclosing(ZYDIS_MACHINE_MODE_LONG_64, reg)) { + case ZYDIS_REGISTER_RAX: + case ZYDIS_REGISTER_RBX: + case ZYDIS_REGISTER_RCX: + case ZYDIS_REGISTER_RDX: + case ZYDIS_REGISTER_RSI: + case ZYDIS_REGISTER_RDI: + case ZYDIS_REGISTER_RBP: + case ZYDIS_REGISTER_RSP: + case ZYDIS_REGISTER_R8: + case ZYDIS_REGISTER_R9: + case ZYDIS_REGISTER_R10: + case ZYDIS_REGISTER_R11: + case ZYDIS_REGISTER_R12: + case ZYDIS_REGISTER_R13: + case ZYDIS_REGISTER_R14: + case ZYDIS_REGISTER_R15: + case ZYDIS_REGISTER_RIP: return true; + default: return false; + } +} + +// ZydisCalcAbsoluteAddress only covers relative immediates and RIP-relative or absolute memory, so +// a base+index*scale+disp operand has to be resolved from the register file by hand. +uint64_t ResolveMemoryOperand(const ZydisDecodedInstruction& instruction, + const ZydisDecodedOperand& operand, + const GuestX64Registers& registers) { + // RIP-relative operands are already anchored past the end of the instruction. + const auto base = + operand.mem.base == ZYDIS_REGISTER_RIP + ? registers.rip + instruction.length + : ReadGuestRegister(operand.mem.base, registers); + uint64_t index = 0; + if (operand.mem.index != ZYDIS_REGISTER_NONE && + operand.mem.index != ZYDIS_REGISTER_RIP) { + index = ReadGuestRegister(operand.mem.index, registers); + } + return base + index * static_cast<uint64_t>(operand.mem.scale) + + static_cast<uint64_t>(operand.mem.disp.value); +} + +// The AT&T-style width prefix, so a memory operand keeps the size a reader needs. Without it +// "[0x1000]" is ambiguous between a byte load and a 16-byte one. +const char* OperandWidthName(uint16_t bits) { + switch (bits) { + case 8: return "byte ptr "; + case 16: return "word ptr "; + case 32: return "dword ptr "; + case 64: return "qword ptr "; + case 128: return "xmmword ptr "; + case 256: return "ymmword ptr "; + case 512: return "zmmword ptr "; + default: return ""; + } +} + +// Bounded append into a fixed buffer: this runs on the fatal path, where a truncation is fine but +// an overrun is not. +size_t Append(char* text, size_t capacity, size_t used, const char* format, ...) { + if (used >= capacity) { + return used; + } + va_list args; + va_start(args, format); + const int written = std::vsnprintf(text + used, capacity - used, format, args); + va_end(args); + if (written < 0) { + return used; + } + const auto advance = static_cast<size_t>(written); + return advance < capacity - used ? used + advance : capacity - 1; +} + +} // namespace + +GuestFaultingInstruction DecodeGuestFaultingInstruction(const uint8_t* code, size_t available, + const GuestX64Registers& registers) { + GuestFaultingInstruction result; + if (code == nullptr || available == 0) { + std::snprintf(result.text, sizeof(result.text), "<no readable instruction bytes>"); + return result; + } + + ZydisDecodedInstruction instruction {}; + std::array<ZydisDecodedOperand, ZYDIS_MAX_OPERAND_COUNT> operands {}; + const auto status = ZydisDecoderDecodeFull(&GuestDecoder(), code, available, &instruction, + operands.data()); + if (!ZYAN_SUCCESS(status) || instruction.length == 0) { + std::snprintf(result.text, sizeof(result.text), "<undecodable instruction>"); + return result; + } + + result.decoded = true; + result.length = instruction.length; + + size_t used = 0; + used = Append(result.text, sizeof(result.text), used, "%s", + ZydisMnemonicGetString(instruction.mnemonic)); + + // LEA and the padding NOPs name an address without touching it, so they must not be reported + // as the memory access that faulted. + const bool computes_address_only = instruction.mnemonic == ZYDIS_MNEMONIC_LEA || + instruction.mnemonic == ZYDIS_MNEMONIC_NOP; + constexpr ZydisOperandActions memory_access = + ZYDIS_OPERAND_ACTION_MASK_READ | ZYDIS_OPERAND_ACTION_MASK_WRITE; + + for (uint8_t index = 0; index < instruction.operand_count_visible; index++) { + const auto& operand = operands[index]; + used = Append(result.text, sizeof(result.text), used, index == 0 ? " " : ", "); + + switch (operand.type) { + case ZYDIS_OPERAND_TYPE_REGISTER: + used = Append(result.text, sizeof(result.text), used, "%s", + ZydisRegisterGetString(operand.reg.value)); + break; + + case ZYDIS_OPERAND_TYPE_IMMEDIATE: { + if (operand.imm.is_relative) { + uint64_t target = 0; + if (ZYAN_SUCCESS(ZydisCalcAbsoluteAddress(&instruction, &operand, + registers.rip, &target))) { + used = Append(result.text, sizeof(result.text), used, + "0x%016" PRIx64, target); + break; + } + } + used = Append(result.text, sizeof(result.text), used, "0x%" PRIx64, + operand.imm.value.u); + } break; + + case ZYDIS_OPERAND_TYPE_MEMORY: { + const uint64_t address = ResolveMemoryOperand(instruction, operand, registers); + const bool resolved = + IsGeneralPurposeRegister(operand.mem.base) && + (operand.mem.index == ZYDIS_REGISTER_NONE || + IsGeneralPurposeRegister(operand.mem.index)); ``` Fixed in 484c0dc4. `resolved` now requires only that any present base/index be a general-purpose register — `ZYDIS_REGISTER_NONE` for either no longer forces "unresolved", so `[0x1000]`, `moffs` and index-only operands like `[rcx*8+disp]` now print without the label. For fs:/gs: I went with the conservative half of your second point rather than reporting an address: `GuestX64Registers` carries no segment bases, so there is nothing to resolve against, and a seg:[offset] value is not a linear address. Those operands are marked `unresolved` and, because the consumer at runtimeLinker.cpp:791 prints `fault addr from insn` whenever `reads_memory || writes_memory`, the `resolved` flag now also gates the access flags — so fs:/gs: accesses never report their segment-relative offset as `effective_address`. Rebuilt `kyty_emulator` + `virtual_memory_allocation_tests`; the suite including `GuestFaultInstructionDecoding` passes (after the usual 13824 MB reservation retry).
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 03:17 UTC · original
On src/loader/x64InstructionDecoder.cpp line 189 (outdated):

@@ -0,0 +1,218 @@
+#include "loader/x64InstructionDecoder.h"
+
+#include <Zydis/Zydis.h>
+
+#include <array>
+#include <cinttypes>
+#include <cstdarg>
+#include <cstdio>
+
+namespace Loader {
+
+namespace {
+
+// One decoder, shared with the rest of the loader the same way redZonePatcher keeps its own.
+// ZydisDecoderInit only fills a plain struct, so constructing it lazily from the fault reporter
+// is cheap and cannot allocate.
+ZydisDecoder& GuestDecoder() {
+	static ZydisDecoder decoder = [] {
+		ZydisDecoder value {};
+		ZydisDecoderInit(&value, ZYDIS_MACHINE_MODE_LONG_64, ZYDIS_STACK_WIDTH_64);
+		return value;
+	}();
+	return decoder;
+}
+
+// Read a general purpose guest register. Anything else (segments, flags, SIMD) is not addressable
+// through a legacy memory operand, so reporting 0 for it cannot make a real fault address wrong.
+uint64_t ReadGuestRegister(ZydisRegister reg, const GuestX64Registers& registers) {
+	const auto wide =
+	    ZydisRegisterGetLargestEnclosing(ZYDIS_MACHINE_MODE_LONG_64, reg);
+	switch (wide) {
+		case ZYDIS_REGISTER_RAX: return registers.rax;
+		case ZYDIS_REGISTER_RBX: return registers.rbx;
+		case ZYDIS_REGISTER_RCX: return registers.rcx;
+		case ZYDIS_REGISTER_RDX: return registers.rdx;
+		case ZYDIS_REGISTER_RSI: return registers.rsi;
+		case ZYDIS_REGISTER_RDI: return registers.rdi;
+		case ZYDIS_REGISTER_RBP: return registers.rbp;
+		case ZYDIS_REGISTER_RSP: return registers.rsp;
+		case ZYDIS_REGISTER_R8: return registers.r8;
+		case ZYDIS_REGISTER_R9: return registers.r9;
+		case ZYDIS_REGISTER_R10: return registers.r10;
+		case ZYDIS_REGISTER_R11: return registers.r11;
+		case ZYDIS_REGISTER_R12: return registers.r12;
+		case ZYDIS_REGISTER_R13: return registers.r13;
+		case ZYDIS_REGISTER_R14: return registers.r14;
+		case ZYDIS_REGISTER_R15: return registers.r15;
+		case ZYDIS_REGISTER_RIP: return registers.rip;
+		default: return 0;
+	}
+}
+
+bool IsGeneralPurposeRegister(ZydisRegister reg) {
+	switch (ZydisRegisterGetLargestEnclosing(ZYDIS_MACHINE_MODE_LONG_64, reg)) {
+		case ZYDIS_REGISTER_RAX:
+		case ZYDIS_REGISTER_RBX:
+		case ZYDIS_REGISTER_RCX:
+		case ZYDIS_REGISTER_RDX:
+		case ZYDIS_REGISTER_RSI:
+		case ZYDIS_REGISTER_RDI:
+		case ZYDIS_REGISTER_RBP:
+		case ZYDIS_REGISTER_RSP:
+		case ZYDIS_REGISTER_R8:
+		case ZYDIS_REGISTER_R9:
+		case ZYDIS_REGISTER_R10:
+		case ZYDIS_REGISTER_R11:
+		case ZYDIS_REGISTER_R12:
+		case ZYDIS_REGISTER_R13:
+		case ZYDIS_REGISTER_R14:
+		case ZYDIS_REGISTER_R15:
+		case ZYDIS_REGISTER_RIP: return true;
+		default: return false;
+	}
+}
+
+// ZydisCalcAbsoluteAddress only covers relative immediates and RIP-relative or absolute memory, so
+// a base+index*scale+disp operand has to be resolved from the register file by hand.
+uint64_t ResolveMemoryOperand(const ZydisDecodedInstruction& instruction,
+                              const ZydisDecodedOperand&         operand,
+                              const GuestX64Registers&            registers) {
+	// RIP-relative operands are already anchored past the end of the instruction.
+	const auto base =
+	    operand.mem.base == ZYDIS_REGISTER_RIP
+	        ? registers.rip + instruction.length
+	        : ReadGuestRegister(operand.mem.base, registers);
+	uint64_t index = 0;
+	if (operand.mem.index != ZYDIS_REGISTER_NONE &&
+	    operand.mem.index != ZYDIS_REGISTER_RIP) {
+		index = ReadGuestRegister(operand.mem.index, registers);
+	}
+	return base + index * static_cast<uint64_t>(operand.mem.scale) +
+	       static_cast<uint64_t>(operand.mem.disp.value);
+}
+
+// The AT&T-style width prefix, so a memory operand keeps the size a reader needs. Without it
+// "[0x1000]" is ambiguous between a byte load and a 16-byte one.
+const char* OperandWidthName(uint16_t bits) {
+	switch (bits) {
+		case 8: return "byte ptr ";
+		case 16: return "word ptr ";
+		case 32: return "dword ptr ";
+		case 64: return "qword ptr ";
+		case 128: return "xmmword ptr ";
+		case 256: return "ymmword ptr ";
+		case 512: return "zmmword ptr ";
+		default: return "";
+	}
+}
+
+// Bounded append into a fixed buffer: this runs on the fatal path, where a truncation is fine but
+// an overrun is not.
+size_t Append(char* text, size_t capacity, size_t used, const char* format, ...) {
+	if (used >= capacity) {
+		return used;
+	}
+	va_list args;
+	va_start(args, format);
+	const int written = std::vsnprintf(text + used, capacity - used, format, args);
+	va_end(args);
+	if (written < 0) {
+		return used;
+	}
+	const auto advance = static_cast<size_t>(written);
+	return advance < capacity - used ? used + advance : capacity - 1;
+}
+
+} // namespace
+
+GuestFaultingInstruction DecodeGuestFaultingInstruction(const uint8_t* code, size_t available,
+                                                        const GuestX64Registers& registers) {
+	GuestFaultingInstruction result;
+	if (code == nullptr || available == 0) {
+		std::snprintf(result.text, sizeof(result.text), "<no readable instruction bytes>");
+		return result;
+	}
+
+	ZydisDecodedInstruction instruction {};
+	std::array<ZydisDecodedOperand, ZYDIS_MAX_OPERAND_COUNT> operands {};
+	const auto status = ZydisDecoderDecodeFull(&GuestDecoder(), code, available, &instruction,
+	                                           operands.data());
+	if (!ZYAN_SUCCESS(status) || instruction.length == 0) {
+		std::snprintf(result.text, sizeof(result.text), "<undecodable instruction>");
+		return result;
+	}
+
+	result.decoded = true;
+	result.length  = instruction.length;
+
+	size_t used = 0;
+	used = Append(result.text, sizeof(result.text), used, "%s",
+	              ZydisMnemonicGetString(instruction.mnemonic));
+
+	// LEA and the padding NOPs name an address without touching it, so they must not be reported
+	// as the memory access that faulted.
+	const bool computes_address_only = instruction.mnemonic == ZYDIS_MNEMONIC_LEA ||
+	                                   instruction.mnemonic == ZYDIS_MNEMONIC_NOP;
+	constexpr ZydisOperandActions memory_access =
+	    ZYDIS_OPERAND_ACTION_MASK_READ | ZYDIS_OPERAND_ACTION_MASK_WRITE;
+
+	for (uint8_t index = 0; index < instruction.operand_count_visible; index++) {
+		const auto& operand = operands[index];
+		used = Append(result.text, sizeof(result.text), used, index == 0 ? " " : ", ");
+
+		switch (operand.type) {
+			case ZYDIS_OPERAND_TYPE_REGISTER:
+				used = Append(result.text, sizeof(result.text), used, "%s",
+				              ZydisRegisterGetString(operand.reg.value));
+				break;
+
+			case ZYDIS_OPERAND_TYPE_IMMEDIATE: {
+				if (operand.imm.is_relative) {
+					uint64_t target = 0;
+					if (ZYAN_SUCCESS(ZydisCalcAbsoluteAddress(&instruction, &operand,
+					                                          registers.rip, &target))) {
+						used = Append(result.text, sizeof(result.text), used,
+						              "0x%016" PRIx64, target);
+						break;
+					}
+				}
+				used = Append(result.text, sizeof(result.text), used, "0x%" PRIx64,
+				              operand.imm.value.u);
+			} break;
+
+			case ZYDIS_OPERAND_TYPE_MEMORY: {
+				const uint64_t address = ResolveMemoryOperand(instruction, operand, registers);
+				const bool     resolved =
+				    IsGeneralPurposeRegister(operand.mem.base) &&
+				    (operand.mem.index == ZYDIS_REGISTER_NONE ||
+				     IsGeneralPurposeRegister(operand.mem.index));
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
git rev-parse --short HEAD
git show -s --format='%h %s' 484c0dc4 || true
ast-grep outline src/loader/x64InstructionDecoder.cpp --match 'DecodeGuestFaultingInstruction|ResolveMemoryOperand' --view expanded
ast-grep outline src/loader/runtimeLinker.cpp --match 'fault|Fault' --view expanded | head -100
ast-grep outline tests/VirtualMemoryAllocationTests.cpp --match 'TestGuestFaultInstructionDecoding' --view expanded
rg -n -C 12 'segment_based|const bool[[:space:]]+resolved|reads_memory|writes_memory|fault addr from insn|GuestFaultInstructionDecoding|ZYDIS_REGISTER_FS|ZYDIS_REGISTER_GS' src/loader/x64InstructionDecoder.cpp src/loader/runtimeLinker.cpp tests/VirtualMemoryAllocationTests.cpp

Length of output: 19417


@theantipopau, I can verify the fix now. Commit 484c0dc allows absent base and index registers, marks FS/GS operands unresolved, and prevents those operands from setting the memory-access flags that trigger fault addr from insn. This addresses the finding. Thanks for the test results.


✏️ Learnings added
Learnt from: theantipopau
Repo: KytyPS5/KytyPS5 PR: 836
File: src/loader/x64InstructionDecoder.cpp:0-0
Timestamp: 2026-09-26T03:17:36.774Z
Learning: In `src/loader/x64InstructionDecoder.cpp`, `GuestX64Registers` does not provide FS/GS segment bases. `DecodeGuestFaultingInstruction` must treat FS/GS memory operands as unresolved and must not set their memory-access flags or report their segment-relative offset as a linear fault address. `src/loader/runtimeLinker.cpp` prints `fault addr from insn` when those memory-access flags are set.

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.

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 03:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836#discussion_r4110000844) On `src/loader/x64InstructionDecoder.cpp` line 189 (outdated): ```diff @@ -0,0 +1,218 @@ +#include "loader/x64InstructionDecoder.h" + +#include <Zydis/Zydis.h> + +#include <array> +#include <cinttypes> +#include <cstdarg> +#include <cstdio> + +namespace Loader { + +namespace { + +// One decoder, shared with the rest of the loader the same way redZonePatcher keeps its own. +// ZydisDecoderInit only fills a plain struct, so constructing it lazily from the fault reporter +// is cheap and cannot allocate. +ZydisDecoder& GuestDecoder() { + static ZydisDecoder decoder = [] { + ZydisDecoder value {}; + ZydisDecoderInit(&value, ZYDIS_MACHINE_MODE_LONG_64, ZYDIS_STACK_WIDTH_64); + return value; + }(); + return decoder; +} + +// Read a general purpose guest register. Anything else (segments, flags, SIMD) is not addressable +// through a legacy memory operand, so reporting 0 for it cannot make a real fault address wrong. +uint64_t ReadGuestRegister(ZydisRegister reg, const GuestX64Registers& registers) { + const auto wide = + ZydisRegisterGetLargestEnclosing(ZYDIS_MACHINE_MODE_LONG_64, reg); + switch (wide) { + case ZYDIS_REGISTER_RAX: return registers.rax; + case ZYDIS_REGISTER_RBX: return registers.rbx; + case ZYDIS_REGISTER_RCX: return registers.rcx; + case ZYDIS_REGISTER_RDX: return registers.rdx; + case ZYDIS_REGISTER_RSI: return registers.rsi; + case ZYDIS_REGISTER_RDI: return registers.rdi; + case ZYDIS_REGISTER_RBP: return registers.rbp; + case ZYDIS_REGISTER_RSP: return registers.rsp; + case ZYDIS_REGISTER_R8: return registers.r8; + case ZYDIS_REGISTER_R9: return registers.r9; + case ZYDIS_REGISTER_R10: return registers.r10; + case ZYDIS_REGISTER_R11: return registers.r11; + case ZYDIS_REGISTER_R12: return registers.r12; + case ZYDIS_REGISTER_R13: return registers.r13; + case ZYDIS_REGISTER_R14: return registers.r14; + case ZYDIS_REGISTER_R15: return registers.r15; + case ZYDIS_REGISTER_RIP: return registers.rip; + default: return 0; + } +} + +bool IsGeneralPurposeRegister(ZydisRegister reg) { + switch (ZydisRegisterGetLargestEnclosing(ZYDIS_MACHINE_MODE_LONG_64, reg)) { + case ZYDIS_REGISTER_RAX: + case ZYDIS_REGISTER_RBX: + case ZYDIS_REGISTER_RCX: + case ZYDIS_REGISTER_RDX: + case ZYDIS_REGISTER_RSI: + case ZYDIS_REGISTER_RDI: + case ZYDIS_REGISTER_RBP: + case ZYDIS_REGISTER_RSP: + case ZYDIS_REGISTER_R8: + case ZYDIS_REGISTER_R9: + case ZYDIS_REGISTER_R10: + case ZYDIS_REGISTER_R11: + case ZYDIS_REGISTER_R12: + case ZYDIS_REGISTER_R13: + case ZYDIS_REGISTER_R14: + case ZYDIS_REGISTER_R15: + case ZYDIS_REGISTER_RIP: return true; + default: return false; + } +} + +// ZydisCalcAbsoluteAddress only covers relative immediates and RIP-relative or absolute memory, so +// a base+index*scale+disp operand has to be resolved from the register file by hand. +uint64_t ResolveMemoryOperand(const ZydisDecodedInstruction& instruction, + const ZydisDecodedOperand& operand, + const GuestX64Registers& registers) { + // RIP-relative operands are already anchored past the end of the instruction. + const auto base = + operand.mem.base == ZYDIS_REGISTER_RIP + ? registers.rip + instruction.length + : ReadGuestRegister(operand.mem.base, registers); + uint64_t index = 0; + if (operand.mem.index != ZYDIS_REGISTER_NONE && + operand.mem.index != ZYDIS_REGISTER_RIP) { + index = ReadGuestRegister(operand.mem.index, registers); + } + return base + index * static_cast<uint64_t>(operand.mem.scale) + + static_cast<uint64_t>(operand.mem.disp.value); +} + +// The AT&T-style width prefix, so a memory operand keeps the size a reader needs. Without it +// "[0x1000]" is ambiguous between a byte load and a 16-byte one. +const char* OperandWidthName(uint16_t bits) { + switch (bits) { + case 8: return "byte ptr "; + case 16: return "word ptr "; + case 32: return "dword ptr "; + case 64: return "qword ptr "; + case 128: return "xmmword ptr "; + case 256: return "ymmword ptr "; + case 512: return "zmmword ptr "; + default: return ""; + } +} + +// Bounded append into a fixed buffer: this runs on the fatal path, where a truncation is fine but +// an overrun is not. +size_t Append(char* text, size_t capacity, size_t used, const char* format, ...) { + if (used >= capacity) { + return used; + } + va_list args; + va_start(args, format); + const int written = std::vsnprintf(text + used, capacity - used, format, args); + va_end(args); + if (written < 0) { + return used; + } + const auto advance = static_cast<size_t>(written); + return advance < capacity - used ? used + advance : capacity - 1; +} + +} // namespace + +GuestFaultingInstruction DecodeGuestFaultingInstruction(const uint8_t* code, size_t available, + const GuestX64Registers& registers) { + GuestFaultingInstruction result; + if (code == nullptr || available == 0) { + std::snprintf(result.text, sizeof(result.text), "<no readable instruction bytes>"); + return result; + } + + ZydisDecodedInstruction instruction {}; + std::array<ZydisDecodedOperand, ZYDIS_MAX_OPERAND_COUNT> operands {}; + const auto status = ZydisDecoderDecodeFull(&GuestDecoder(), code, available, &instruction, + operands.data()); + if (!ZYAN_SUCCESS(status) || instruction.length == 0) { + std::snprintf(result.text, sizeof(result.text), "<undecodable instruction>"); + return result; + } + + result.decoded = true; + result.length = instruction.length; + + size_t used = 0; + used = Append(result.text, sizeof(result.text), used, "%s", + ZydisMnemonicGetString(instruction.mnemonic)); + + // LEA and the padding NOPs name an address without touching it, so they must not be reported + // as the memory access that faulted. + const bool computes_address_only = instruction.mnemonic == ZYDIS_MNEMONIC_LEA || + instruction.mnemonic == ZYDIS_MNEMONIC_NOP; + constexpr ZydisOperandActions memory_access = + ZYDIS_OPERAND_ACTION_MASK_READ | ZYDIS_OPERAND_ACTION_MASK_WRITE; + + for (uint8_t index = 0; index < instruction.operand_count_visible; index++) { + const auto& operand = operands[index]; + used = Append(result.text, sizeof(result.text), used, index == 0 ? " " : ", "); + + switch (operand.type) { + case ZYDIS_OPERAND_TYPE_REGISTER: + used = Append(result.text, sizeof(result.text), used, "%s", + ZydisRegisterGetString(operand.reg.value)); + break; + + case ZYDIS_OPERAND_TYPE_IMMEDIATE: { + if (operand.imm.is_relative) { + uint64_t target = 0; + if (ZYAN_SUCCESS(ZydisCalcAbsoluteAddress(&instruction, &operand, + registers.rip, &target))) { + used = Append(result.text, sizeof(result.text), used, + "0x%016" PRIx64, target); + break; + } + } + used = Append(result.text, sizeof(result.text), used, "0x%" PRIx64, + operand.imm.value.u); + } break; + + case ZYDIS_OPERAND_TYPE_MEMORY: { + const uint64_t address = ResolveMemoryOperand(instruction, operand, registers); + const bool resolved = + IsGeneralPurposeRegister(operand.mem.base) && + (operand.mem.index == ZYDIS_REGISTER_NONE || + IsGeneralPurposeRegister(operand.mem.index)); ``` <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ```shell #!/bin/bash set -euo pipefail git rev-parse --short HEAD git show -s --format='%h %s' 484c0dc4 || true ast-grep outline src/loader/x64InstructionDecoder.cpp --match 'DecodeGuestFaultingInstruction|ResolveMemoryOperand' --view expanded ast-grep outline src/loader/runtimeLinker.cpp --match 'fault|Fault' --view expanded | head -100 ast-grep outline tests/VirtualMemoryAllocationTests.cpp --match 'TestGuestFaultInstructionDecoding' --view expanded rg -n -C 12 'segment_based|const bool[[:space:]]+resolved|reads_memory|writes_memory|fault addr from insn|GuestFaultInstructionDecoding|ZYDIS_REGISTER_FS|ZYDIS_REGISTER_GS' src/loader/x64InstructionDecoder.cpp src/loader/runtimeLinker.cpp tests/VirtualMemoryAllocationTests.cpp ``` Length of output: 19417 --- </details> `@theantipopau`, I can verify the fix now. Commit `484c0dc` allows absent base and index registers, marks FS/GS operands unresolved, and prevents those operands from setting the memory-access flags that trigger `fault addr from insn`. This addresses the finding. Thanks for the test results. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: theantipopau Repo: KytyPS5/KytyPS5 PR: 836 File: src/loader/x64InstructionDecoder.cpp:0-0 Timestamp: 2026-09-26T03:17:36.774Z Learning: In `src/loader/x64InstructionDecoder.cpp`, `GuestX64Registers` does not provide FS/GS segment bases. `DecodeGuestFaultingInstruction` must treat FS/GS memory operands as unresolved and must not set their memory-access flags or report their segment-relative offset as a linear fault address. `src/loader/runtimeLinker.cpp` prints `fault addr from insn` when those memory-access flags are set. ``` > 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> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠Nmzik on GitHub · 2026-09-27 11:57 UTC · original

This is unnecessary private debug code. Let’s keep it out of the main repository

**@⁠Nmzik** on GitHub · 2026-09-27 11:57 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836#issuecomment-5855612004) This is unnecessary private debug code. Let’s keep it out of the main repository
Author
Owner

@⁠theantipopau on GitHub · 2026-09-27 13:04 UTC · original

Understood, thanks for taking the time to look. Dropping it.

For the record on what was in there, in case it is useful: the branch was the
guest-fault report path in src/loader/runtimeLinker.cpp — a faulting-address
backtrace with a Loader::SymbolDatabase lookup, plus a decoder change so a
missing base/index is reported as resolved and fs:/gs: segment-relative
addresses are not printed as the fault address. None of the reporting should
have been in main in that form, and I have not opened a replacement.

One narrow question, so I do not re-propose something you have already ruled
out: is the decoder half on its own (marking a missing base/index as
resolved, and leaving fs:/gs: as unresolved) a correctness fix you
would take, or is that report text as a whole considered debug-only? I will
leave it alone either way.

**@⁠theantipopau** on GitHub · 2026-09-27 13:04 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/836#issuecomment-5856111405) Understood, thanks for taking the time to look. Dropping it. For the record on what was in there, in case it is useful: the branch was the guest-fault report path in `src/loader/runtimeLinker.cpp` — a faulting-address backtrace with a `Loader::SymbolDatabase` lookup, plus a decoder change so a missing base/index is reported as `resolved` and `fs:`/`gs:` segment-relative addresses are not printed as the fault address. None of the reporting should have been in `main` in that form, and I have not opened a replacement. One narrow question, so I do not re-propose something you have already ruled out: is the decoder half on its own (marking a missing base/index as `resolved`, and leaving `fs:`/`gs:` as `unresolved`) a correctness fix you would take, or is that report text as a whole considered debug-only? I will leave it alone either way.

Pull request closed

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