common: finish Linux file reads that hit protected guest pages #1165

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

@⁠NeySlim on GitHub · 2026-10-07 22:00 UTC · original
NeySlim:fix/protected-guest-reads → main · +228 −1 · 10 files · 5 commits · closed without merging

Problem

This is the Linux side of #838. On Linux, SysFileRead uses fread straight into the guest buffer. When part of that buffer is write-protected guest memory (pages tracked for GPU synchronization), read() fails with EFAULT at the first protected page instead of raising the fault the emulator handles. fread then returns a short count, and KernelRead, KernelPread, KernelPreadv and AIO reads report fewer bytes than the file has.

God of War Ragnarök (PPSA08332, 05.005) hits this a few minutes after boot while streaming texture LOD packs. One AIO read returned short, stopping exactly on a page boundary:

pread got=0x35000 want=0x3a660 buf=0x29267c0000 .../exec/wad/ppr_le/patch.01.01.lodpack

The game checks the completed byte count against its table and stops with int 0x41 (Unhandled host exception ... pc=0x9003405ba). Because the protection depends on what the GPU thread is doing at that moment, the failing read, and the assertion site, change from run to run.

Change

When fread stops short with ferror() and errno == EFAULT, SysFileRead clears the error, seeks back to start + bytes_read and finishes through a 1 MiB thread-local host buffer copied with memcpy. That copy runs in user mode, so the emulator's fault handler unprotects the pages as for any guest write. This is the approach of #838 for Windows and of the AMPR read path. Successful reads are unchanged, apart from one ftello per read.

Test

New TestReadsIntoProtectedPages in KernelFileSystemTests. It allocates two 64 KiB regions with Common::VirtualMemory, makes the second read-only, and installs a HostException handler that stands in for the emulator's: it unprotects the region on a write fault. KernelPread, KernelRead and KernelPreadv must then fill a buffer crossing into the protected region with the full file contents, through the handler.

The test only uses portable APIs. On Windows it passes only with #838, which fixes the same read path there. If you prefer, I can guard it for Linux until #838 lands.

Validation

Linux, AMD Radeon 8060S, Mesa RADV 26.2.3.

  • kernel_file_system_tests: passes. Without the change it fails with pread fills a buffer that crosses into a write-protected page.
  • God of War Ragnarök: no more int 0x41 in its loading code. The game runs for 10 minutes and reaches the in-game loading screen.

Not tested on Windows: this change only touches sysLinuxFileIO.cpp, and #838 covers Windows.

AI use

I used Claude Code (AI agent) to investigate the crash, write the change and the test, and run the tests above on my machine. I reviewed the diff and the results before opening this PR.

**@⁠NeySlim** on GitHub · 2026-10-07 22:00 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165) `NeySlim:fix/protected-guest-reads` → `main` · +228 −1 · 10 files · 5 commits · closed without merging ## Problem This is the Linux side of #838. On Linux, `SysFileRead` uses `fread` straight into the guest buffer. When part of that buffer is write-protected guest memory (pages tracked for GPU synchronization), `read()` fails with `EFAULT` at the first protected page instead of raising the fault the emulator handles. `fread` then returns a short count, and `KernelRead`, `KernelPread`, `KernelPreadv` and AIO reads report fewer bytes than the file has. God of War Ragnarök (PPSA08332, 05.005) hits this a few minutes after boot while streaming texture LOD packs. One AIO read returned short, stopping exactly on a page boundary: ``` pread got=0x35000 want=0x3a660 buf=0x29267c0000 .../exec/wad/ppr_le/patch.01.01.lodpack ``` The game checks the completed byte count against its table and stops with `int 0x41` (`Unhandled host exception ... pc=0x9003405ba`). Because the protection depends on what the GPU thread is doing at that moment, the failing read, and the assertion site, change from run to run. ## Change When `fread` stops short with `ferror()` and `errno == EFAULT`, `SysFileRead` clears the error, seeks back to `start + bytes_read` and finishes through a 1 MiB thread-local host buffer copied with `memcpy`. That copy runs in user mode, so the emulator's fault handler unprotects the pages as for any guest write. This is the approach of #838 for Windows and of the AMPR read path. Successful reads are unchanged, apart from one `ftello` per read. ## Test New `TestReadsIntoProtectedPages` in `KernelFileSystemTests`. It allocates two 64 KiB regions with `Common::VirtualMemory`, makes the second read-only, and installs a `HostException` handler that stands in for the emulator's: it unprotects the region on a write fault. `KernelPread`, `KernelRead` and `KernelPreadv` must then fill a buffer crossing into the protected region with the full file contents, through the handler. The test only uses portable APIs. On Windows it passes only with #838, which fixes the same read path there. If you prefer, I can guard it for Linux until #838 lands. ## Validation Linux, AMD Radeon 8060S, Mesa RADV 26.2.3. - `kernel_file_system_tests`: passes. Without the change it fails with `pread fills a buffer that crosses into a write-protected page`. - God of War Ragnarök: no more `int 0x41` in its loading code. The game runs for 10 minutes and reaches the in-game loading screen. Not tested on Windows: this change only touches `sysLinuxFileIO.cpp`, and #838 covers Windows. ## AI use I used Claude Code (AI agent) to investigate the crash, write the change and the test, and run the tests above on my machine. I reviewed the diff and the results before opening this PR.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:45:58 +00:00
github-bot closed this pull request 2026-11-26 09:45:59 +00:00
Author
Owner

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

Review in Change Stack →

Note

Reviews paused

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

  • Last reviewed commit: 828171643ccb4618518a5863b224a616e86a34e0
  • Latest commit, not reviewed: 463f630506

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

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: 45cfabed-47ef-4e54-9ae0-bab44ccb7392
📥 Commits

Reviewing files that changed from the base of the PR and between 531b70a4d569ffcb5c7ab106a80a168bf0196038 and 828171643ccb4618518a5863b224a616e86a34e0.

📒 Files selected for processing (2)
  • src/common/platform/sysLinuxFileIO.cpp
  • tests/KernelFileSystemTests.cpp

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

📝 Walkthrough

SysFileRead now retries unread bytes through a host buffer after an eligible short read caused by EFAULT. It copies data only when the registered destination probe accepts the range. GPU resource installation registers a probe based on mapped ranges and GPU write-fault handling. Tests cover protected-buffer reads through KernelPread, KernelRead, and KernelPreadv, plus reads past EOF and the Linux unmapped-page case.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 82817

The past-EOF read test covers the reported regression. No actionable merge-blocking risk remains after normal checks.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 10 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the main change: completing Linux file reads that encounter protected guest pages.
Description check ✅ Passed The description is directly related to the changeset. It explains the protected-page read failure, the Linux recovery logic, the added tests, and validation results.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

❤️ Share

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-07 22:03 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165#issuecomment-6047753881) · edited 2026-10-16 01:01 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/1165?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> <!-- review_stack_entry_end --> <!-- This is an auto-generated comment: review paused by coderabbit.ai --> > [!NOTE] > ## Reviews paused > > It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the `reviews.auto_review.auto_pause_after_reviewed_commits` setting. > > - Last reviewed commit: 828171643ccb4618518a5863b224a616e86a34e0 > - Latest commit, not reviewed: 463f630506a32cbe970c7308e612b3aeaa4da5d6 > > Use the following commands to manage reviews: > - `@coderabbitai resume` to resume automatic reviews. > - `@coderabbitai review` to trigger a single review. > > Use the checkboxes below for quick actions: > - [ ] <!-- {"checkboxId":"7f6cc2e2-2e4e-497a-8c31-c9e4573e93d1"} --> ▶️ Resume reviews > - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review <!-- end of auto-generated comment: review paused by coderabbit.ai --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary><strong>ℹ️ Recent review info</strong></summary> <dl> <dd> <details> <summary><strong>⚙️ Run configuration</strong></summary> <dl> <dd> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `45cfabed-47ef-4e54-9ae0-bab44ccb7392` </dd> </dl> </details> <details> <summary><strong>📥 Commits</strong></summary> <dl> <dd> Reviewing files that changed from the base of the PR and between 531b70a4d569ffcb5c7ab106a80a168bf0196038 and 828171643ccb4618518a5863b224a616e86a34e0. </dd> </dl> </details> <details> <summary><strong>📒 Files selected for processing (2)</strong></summary> <dl> <dd> * `src/common/platform/sysLinuxFileIO.cpp` * `tests/KernelFileSystemTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </dd> </dl> </details> <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> `SysFileRead` now retries unread bytes through a host buffer after an eligible short read caused by `EFAULT`. It copies data only when the registered destination probe accepts the range. GPU resource installation registers a probe based on mapped ranges and GPU write-fault handling. Tests cover protected-buffer reads through `KernelPread`, `KernelRead`, and `KernelPreadv`, plus reads past EOF and the Linux unmapped-page case. **Suggested reviewers:** `nmzik` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"828171643ccb4618518a5863b224a616e86a34e0" --> **Change:** Bug fix <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong>⚪ Minimal</strong> · up to <code>82817</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **⚪ Minimal** · up to `82817` --> <!-- final_review_risk_coverage:{"sourceCommitId":"828171643ccb4618518a5863b224a616e86a34e0","coveredCommitId":"828171643ccb4618518a5863b224a616e86a34e0","kind":"reviewed"} --> The past-EOF read test covers the reported regression. No actionable merge-blocking risk remains after normal checks. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>🚥 Pre-merge checks | ✅ 4 | ❌ 1</strong></summary> <dl> <dd> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :---------------- | :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 10 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong>✅ Passed checks (4 passed)</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ✅ Passed | The title clearly and concisely identifies the main change: completing Linux file reads that encounter protected guest pages. | | Description check | ✅ Passed | The description is directly related to the changeset. It explains the protected-page read failure, the Linux recovery logic, the added tests, and validation results. | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autopilot</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1165)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
@ -87,0 +124,4 @@
if (got == 0) {
break;
}
std::memcpy(static_cast<uint8_t*>(data) + w, chunk.data(), got);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-07 22:03 UTC · original · edited 2026-10-07 22:35 UTC

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

Do not copy into an unmapped destination after EFAULT.

EFAULT can mean that data is unmapped, not that a guest page is write-protected. If a direct read fails for an unmapped destination, the retry can read bytes into chunk; this memcpy then faults instead of returning the short read. Restrict recovery to a destination known to be protected guest memory, or use a fault-aware copy that can report failure. (man7.org)

✅ Confirmed as addressed by @⁠NeySlim

**@⁠coderabbitai[bot]** on GitHub · 2026-10-07 22:03 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165#discussion_r4212467911) · edited 2026-10-07 22:35 UTC **🩺 Stability & Availability** | **🟠 Major** | **🏗️ Heavy lift** **Do not copy into an unmapped destination after `EFAULT`.** `EFAULT` can mean that `data` is unmapped, not that a guest page is write-protected. If a direct read fails for an unmapped destination, the retry can read bytes into `chunk`; this `memcpy` then faults instead of returning the short read. Restrict recovery to a destination known to be protected guest memory, or use a fault-aware copy that can report failure. ([man7.org](https://www.man7.org/linux/man-pages/man2/read.2.html?utm_source=openai)) <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:4c923669478ff2a0d0221739 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠NeySlim <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: a02cb448-2b59-49cb-84e0-e36872214fa7
📥 Commits

Reviewing files that changed from the base of the PR and between c86c8b4d93 and 738f994586cd70e4d5078617315be8dc71b625dc.

📒 Files selected for processing (2)
  • src/common/platform/sysLinuxFileIO.cpp
  • tests/KernelFileSystemTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-07 22:03 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165#pullrequestreview-5448928454) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `a02cb448-2b59-49cb-84e0-e36872214fa7` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between c86c8b4d9333a766cc8c4495f89f893bf35e6199 and 738f994586cd70e4d5078617315be8dc71b625dc. </details> <details> <summary>📒 Files selected for processing (2)</summary> * `src/common/platform/sysLinuxFileIO.cpp` * `tests/KernelFileSystemTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=2d4652b3-87b8-4113-b7e3-b600e7ead039 attempt=289383a8-647e-4130-be1d-889696bcae33 batch=1/1 -->
@ -87,0 +124,4 @@
if (got == 0) {
break;
}
std::memcpy(static_cast<uint8_t*>(data) + w, chunk.data(), got);
Author
Owner

@⁠NeySlim on GitHub · 2026-10-07 22:34 UTC · original

Good point, fixed in b70b01a4. Before each bounce copy, SysFileRead now checks with mincore() that the destination pages are mapped. A write-protected page is still mapped, so the recovery still applies there. An unmapped destination stops the loop and keeps the short read, with the file position left right after the bytes delivered. TestReadsIntoProtectedPages gained a Linux case: a pread into a buffer whose second page is unmapped returns the first page only. Without the check, that case crashes in the copy.

**@⁠NeySlim** on GitHub · 2026-10-07 22:34 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165#discussion_r4212725144) Good point, fixed in b70b01a4. Before each bounce copy, `SysFileRead` now checks with `mincore()` that the destination pages are mapped. A write-protected page is still mapped, so the recovery still applies there. An unmapped destination stops the loop and keeps the short read, with the file position left right after the bytes delivered. `TestReadsIntoProtectedPages` gained a Linux case: a `pread` into a buffer whose second page is unmapped returns the first page only. Without the check, that case crashes in the copy.
@ -87,0 +124,4 @@
if (got == 0) {
break;
}
std::memcpy(static_cast<uint8_t*>(data) + w, chunk.data(), got);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-07 22:35 UTC · original

@NeySlim, thanks for the fix. The supplied code checks the destination mapping before each fallback read and copy. If a destination page is unmapped, recovery stops and the file position remains after the bytes delivered. Write-protected mapped pages can still use recovery.

The reported Linux regression test covers the original crash case.


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

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-07 22:35 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165#discussion_r4212727639) `@NeySlim`, thanks for the fix. The supplied code checks the destination mapping before each fallback read and copy. If a destination page is unmapped, recovery stops and the file position remains after the bytes delivered. Write-protected mapped pages can still use recovery. The reported Linux regression test covers the original crash case. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=%40coderabbitai%20caught%20a%20crash%20risk%3A%20%60EFAULT%60%20may%20mean%20an%20unmapped%20destination.%20Checking%20pages%20with%20%60mincore()%60%20preserves%20safe%20recovery%20for%20protected%20pages%20and%20short%20reads%20for%20unmapped%20ones.%20Try%20%40coderabbitai%20%F0%9F%9B%A1%EF%B8%8F&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1165%23discussion_r4212467911)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 53626841-8c70-46f4-a9e1-433bb8145ba6
📥 Commits

Reviewing files that changed from the base of the PR and between 738f994586cd70e4d5078617315be8dc71b625dc and b70b01a4563fba8ebe47da01231eda1a45ce96c6.

📒 Files selected for processing (2)
  • src/common/platform/sysLinuxFileIO.cpp
  • tests/KernelFileSystemTests.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/KernelFileSystemTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-07 22:39 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165#pullrequestreview-5449278182) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `53626841-8c70-46f4-a9e1-433bb8145ba6` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 738f994586cd70e4d5078617315be8dc71b625dc and b70b01a4563fba8ebe47da01231eda1a45ce96c6. </details> <details> <summary>📒 Files selected for processing (2)</summary> * `src/common/platform/sysLinuxFileIO.cpp` * `tests/KernelFileSystemTests.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary> * tests/KernelFileSystemTests.cpp </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=1874cccc-3ad3-4084-a477-6679694e0092 attempt=e513a9f9-919c-4e12-9f15-4b3f83867485 batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-07 22:39 UTC · original · edited 2026-10-08 05:18 UTC
On src/common/platform/sysLinuxFileIO.cpp line 94 (outdated):

@@ -81,9 +84,43 @@ static void apply_cache_hint(FILE* f, sys_file_cache_type_t cache_type) {
 #endif
 }
 
+// True when every page of [data, data + size) is mapped, whatever its protection.
+static bool IsRangeMapped(const void* data, size_t size) {
+	static const auto page  = static_cast<uintptr_t>(sysconf(_SC_PAGESIZE));
+	const auto        begin = reinterpret_cast<uintptr_t>(data) & ~(page - 1u);
+	const auto        end   = (reinterpret_cast<uintptr_t>(data) + size + page - 1u) & ~(page - 1u);
+	thread_local std::vector<unsigned char> residency;
+	residency.resize((end - begin) / page);
+	return mincore(reinterpret_cast<void*>(begin), end - begin, residency.data()) == 0;

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

🔎 Supported by static analysis

🏁 Script executed:

sed -n '80,130p' src/common/platform/sysLinuxFileIO.cpp
rg -n 'PROT_NONE|VirtualMemory::Protect|Mode::NoAccess|NoAccess' src | head -40
rg -n 'HostException|AccessViolation' src | head -40

Repository: KytyPS5/KytyPS5

Length of output: 8413


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- KytyExceptionHandler ---'
sed -n '630,705p' src/loader/runtimeLinker.cpp
printf '%s\n' '--- Host exception declarations and handlers ---'
sed -n '1,80p' src/common/hostException.h
sed -n '140,275p' src/common/hostException.cpp
printf '%s\n' '--- VirtualMemory protection and reservation paths ---'
sed -n '540,680p' src/kernel/memoryAddressSpace.inc
sed -n '870,930p' src/kernel/memoryAddressSpace.inc
sed -n '990,1030p' src/kernel/memoryAddressSpace.inc
sed -n '1090,1130p' src/kernel/memoryAddressSpace.inc
printf '%s\n' '--- NoAccess and reserve call sites ---'
rg -n -C 5 -- 'VirtualMemory::Mode::NoAccess|Reserve|Reserve\(' src/kernel src/loader src/common | head -240

Repository: KytyPS5/KytyPS5

Length of output: 34136


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- HandleGpuFault declarations and definitions ---'
rg -n -C 8 -- 'HandleGpuFault' src
printf '%s\n' '--- SysFileRead callers and declarations ---'
rg -n -C 6 -- 'SysFileRead\(' src
printf '%s\n' '--- Guest memory mapping and protection operations ---'
sed -n '2280,2410p' src/kernel/memory.cpp
sed -n '2620,2735p' src/kernel/memory.cpp
sed -n '3000,3125p' src/kernel/memory.cpp
printf '%s\n' '--- Parent/base implementation of sysLinuxFileIO.cpp ---'
git show b70b01a4563fba8ebe47da01231eda1a45ce96c6^:src/common/platform/sysLinuxFileIO.cpp | sed -n '70,125p'

Repository: KytyPS5/KytyPS5

Length of output: 23512


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- Graphics fault handler definitions ---'
rg -n -C 12 -- 'PageFaultAccess|HandleFault' src libs . --glob '!build/**' --glob '!node_modules/**' | head -320
printf '%s\n' '--- File read paths into mapped or guest memory ---'
rg -n -C 8 -- '\.Read\(|Read\(.*data|LoadSegment|SysFileRead' src/loader src/kernel src/common | head -360
printf '%s\n' '--- File and ELF read declarations ---'
rg -n -C 5 -- 'class File|void Read\(|LoadSegment' src/common src/loader | head -240

Repository: KytyPS5/KytyPS5

Length of output: 42139


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- RenderContext mapping and fault behavior ---'
sed -n '50,85p' src/graphics/host_gpu/renderer/renderContext.cpp
printf '%s\n' '--- Protection decoder ---'
sed -n '90,145p' src/kernel/memory.cpp
printf '%s\n' '--- Flexible memory map implementation ---'
rg -n -C 12 -- 'bool Map\(|Map\(uint64_t vaddr|g_flexible_memory->Map' src/kernel/memory.cpp src/kernel/memoryAddressSpace.inc | head -240

Repository: KytyPS5/KytyPS5

Length of output: 11366


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- Complete RenderContext::IsMapped ---'
sed -n '73,110p' src/graphics/host_gpu/renderer/renderContext.cpp
printf '%s\n' '--- Complete FlexibleMemory::Map ---'
sed -n '1711,1785p' src/kernel/memory.cpp

Repository: KytyPS5/KytyPS5

Length of output: 4412


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- MapGpuRange and GPU range predicates ---'
rg -n -C 14 -- 'MapGpuRange|IsGpuAddressRange' src/kernel/memory.cpp src/graphics/host_gpu/renderer/renderContext.cpp src | head -300

Repository: KytyPS5/KytyPS5

Length of output: 18034


🏁 Script executed:

set -o pipefail
sed -n '1125,1215p' src/kernel/memoryAddressSpace.inc

Repository: KytyPS5/KytyPS5

Length of output: 3523


Do not use mincore as a write-access check.

A guest read can target a process-lifetime reserved range. Linux maps that range with PROT_NONE, but mincore still accepts it. The retry then calls std::memcpy, which raises a write access violation.

The reservation is not registered with RenderContext::MapMemory. HandleFault therefore returns false, and the global handler restores the default signal action. The process terminates instead of returning the short read with EFAULT that the original fread produced.

Restrict this recovery to destinations with a handler that can make the range writable, or use a copy method that reports an inaccessible destination without raising an unhandled fault.

✅ Confirmed as addressed by @⁠NeySlim

**@⁠coderabbitai[bot]** on GitHub · 2026-10-07 22:39 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165#discussion_r4212753101) · edited 2026-10-08 05:18 UTC On `src/common/platform/sysLinuxFileIO.cpp` line 94 (outdated): ```diff @@ -81,9 +84,43 @@ static void apply_cache_hint(FILE* f, sys_file_cache_type_t cache_type) { #endif } +// True when every page of [data, data + size) is mapped, whatever its protection. +static bool IsRangeMapped(const void* data, size_t size) { + static const auto page = static_cast<uintptr_t>(sysconf(_SC_PAGESIZE)); + const auto begin = reinterpret_cast<uintptr_t>(data) & ~(page - 1u); + const auto end = (reinterpret_cast<uintptr_t>(data) + size + page - 1u) & ~(page - 1u); + thread_local std::vector<unsigned char> residency; + residency.resize((end - begin) / page); + return mincore(reinterpret_cast<void*>(begin), end - begin, residency.data()) == 0; ``` **🩺 Stability & Availability** | **🟠 Major** | **🏗️ Heavy lift** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '80,130p' src/common/platform/sysLinuxFileIO.cpp rg -n 'PROT_NONE|VirtualMemory::Protect|Mode::NoAccess|NoAccess' src | head -40 rg -n 'HostException|AccessViolation' src | head -40 ``` Repository: KytyPS5/KytyPS5 Length of output: 8413 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- KytyExceptionHandler ---' sed -n '630,705p' src/loader/runtimeLinker.cpp printf '%s\n' '--- Host exception declarations and handlers ---' sed -n '1,80p' src/common/hostException.h sed -n '140,275p' src/common/hostException.cpp printf '%s\n' '--- VirtualMemory protection and reservation paths ---' sed -n '540,680p' src/kernel/memoryAddressSpace.inc sed -n '870,930p' src/kernel/memoryAddressSpace.inc sed -n '990,1030p' src/kernel/memoryAddressSpace.inc sed -n '1090,1130p' src/kernel/memoryAddressSpace.inc printf '%s\n' '--- NoAccess and reserve call sites ---' rg -n -C 5 -- 'VirtualMemory::Mode::NoAccess|Reserve|Reserve\(' src/kernel src/loader src/common | head -240 ``` Repository: KytyPS5/KytyPS5 Length of output: 34136 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- HandleGpuFault declarations and definitions ---' rg -n -C 8 -- 'HandleGpuFault' src printf '%s\n' '--- SysFileRead callers and declarations ---' rg -n -C 6 -- 'SysFileRead\(' src printf '%s\n' '--- Guest memory mapping and protection operations ---' sed -n '2280,2410p' src/kernel/memory.cpp sed -n '2620,2735p' src/kernel/memory.cpp sed -n '3000,3125p' src/kernel/memory.cpp printf '%s\n' '--- Parent/base implementation of sysLinuxFileIO.cpp ---' git show b70b01a4563fba8ebe47da01231eda1a45ce96c6^:src/common/platform/sysLinuxFileIO.cpp | sed -n '70,125p' ``` Repository: KytyPS5/KytyPS5 Length of output: 23512 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- Graphics fault handler definitions ---' rg -n -C 12 -- 'PageFaultAccess|HandleFault' src libs . --glob '!build/**' --glob '!node_modules/**' | head -320 printf '%s\n' '--- File read paths into mapped or guest memory ---' rg -n -C 8 -- '\.Read\(|Read\(.*data|LoadSegment|SysFileRead' src/loader src/kernel src/common | head -360 printf '%s\n' '--- File and ELF read declarations ---' rg -n -C 5 -- 'class File|void Read\(|LoadSegment' src/common src/loader | head -240 ``` Repository: KytyPS5/KytyPS5 Length of output: 42139 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- RenderContext mapping and fault behavior ---' sed -n '50,85p' src/graphics/host_gpu/renderer/renderContext.cpp printf '%s\n' '--- Protection decoder ---' sed -n '90,145p' src/kernel/memory.cpp printf '%s\n' '--- Flexible memory map implementation ---' rg -n -C 12 -- 'bool Map\(|Map\(uint64_t vaddr|g_flexible_memory->Map' src/kernel/memory.cpp src/kernel/memoryAddressSpace.inc | head -240 ``` Repository: KytyPS5/KytyPS5 Length of output: 11366 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- Complete RenderContext::IsMapped ---' sed -n '73,110p' src/graphics/host_gpu/renderer/renderContext.cpp printf '%s\n' '--- Complete FlexibleMemory::Map ---' sed -n '1711,1785p' src/kernel/memory.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 4412 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- MapGpuRange and GPU range predicates ---' rg -n -C 14 -- 'MapGpuRange|IsGpuAddressRange' src/kernel/memory.cpp src/graphics/host_gpu/renderer/renderContext.cpp src | head -300 ``` Repository: KytyPS5/KytyPS5 Length of output: 18034 --- 🏁 Script executed: ```bash set -o pipefail sed -n '1125,1215p' src/kernel/memoryAddressSpace.inc ``` Repository: KytyPS5/KytyPS5 Length of output: 3523 --- </details> **Do not use `mincore` as a write-access check.** A guest read can target a process-lifetime reserved range. Linux maps that range with `PROT_NONE`, but `mincore` still accepts it. The retry then calls `std::memcpy`, which raises a write access violation. The reservation is not registered with `RenderContext::MapMemory`. `HandleFault` therefore returns `false`, and the global handler restores the default signal action. The process terminates instead of returning the short read with `EFAULT` that the original `fread` produced. Restrict this recovery to destinations with a handler that can make the range writable, or use a copy method that reports an inaccessible destination without raising an unhandled fault. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:4d4f93c167c922ec9a81643a --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠NeySlim <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠NeySlim on GitHub · 2026-10-08 05:17 UTC · original
On src/common/platform/sysLinuxFileIO.cpp line 94 (outdated):

@@ -81,9 +84,43 @@ static void apply_cache_hint(FILE* f, sys_file_cache_type_t cache_type) {
 #endif
 }
 
+// True when every page of [data, data + size) is mapped, whatever its protection.
+static bool IsRangeMapped(const void* data, size_t size) {
+	static const auto page  = static_cast<uintptr_t>(sysconf(_SC_PAGESIZE));
+	const auto        begin = reinterpret_cast<uintptr_t>(data) & ~(page - 1u);
+	const auto        end   = (reinterpret_cast<uintptr_t>(data) + size + page - 1u) & ~(page - 1u);
+	thread_local std::vector<unsigned char> residency;
+	residency.resize((end - begin) / page);
+	return mincore(reinterpret_cast<void*>(begin), end - begin, residency.data()) == 0;

Right, mincore accepts a reserved PROT_NONE range, and it also broke the macOS build (different signature). Replaced in 070f58e: SysFileRead now asks a probe that the kernel installs with the GPU resources (SysFileSetRecoverableDestination), and that probe only accepts ranges registered with RenderContext::MapMemory. Those are exactly the ranges whose write faults HandleGpuFault resolves. Any other destination, whether reserved, unmapped or simply not tracked, keeps the short read from the original fread. The test now installs its own probe for the guarded target, and a pread into a destination the probe rejects returns the short count. With a probe that accepts everything, that case crashes, as you described. On Windows the probe is a no-op: #838 handles that path.

**@⁠NeySlim** on GitHub · 2026-10-08 05:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165#discussion_r4215069809) On `src/common/platform/sysLinuxFileIO.cpp` line 94 (outdated): ```diff @@ -81,9 +84,43 @@ static void apply_cache_hint(FILE* f, sys_file_cache_type_t cache_type) { #endif } +// True when every page of [data, data + size) is mapped, whatever its protection. +static bool IsRangeMapped(const void* data, size_t size) { + static const auto page = static_cast<uintptr_t>(sysconf(_SC_PAGESIZE)); + const auto begin = reinterpret_cast<uintptr_t>(data) & ~(page - 1u); + const auto end = (reinterpret_cast<uintptr_t>(data) + size + page - 1u) & ~(page - 1u); + thread_local std::vector<unsigned char> residency; + residency.resize((end - begin) / page); + return mincore(reinterpret_cast<void*>(begin), end - begin, residency.data()) == 0; ``` Right, `mincore` accepts a reserved `PROT_NONE` range, and it also broke the macOS build (different signature). Replaced in 070f58e: `SysFileRead` now asks a probe that the kernel installs with the GPU resources (`SysFileSetRecoverableDestination`), and that probe only accepts ranges registered with `RenderContext::MapMemory`. Those are exactly the ranges whose write faults `HandleGpuFault` resolves. Any other destination, whether reserved, unmapped or simply not tracked, keeps the short read from the original `fread`. The test now installs its own probe for the guarded target, and a `pread` into a destination the probe rejects returns the short count. With a probe that accepts everything, that case crashes, as you described. On Windows the probe is a no-op: #838 handles that path.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 05:18 UTC · original
On src/common/platform/sysLinuxFileIO.cpp line 94 (outdated):

@@ -81,9 +84,43 @@ static void apply_cache_hint(FILE* f, sys_file_cache_type_t cache_type) {
 #endif
 }
 
+// True when every page of [data, data + size) is mapped, whatever its protection.
+static bool IsRangeMapped(const void* data, size_t size) {
+	static const auto page  = static_cast<uintptr_t>(sysconf(_SC_PAGESIZE));
+	const auto        begin = reinterpret_cast<uintptr_t>(data) & ~(page - 1u);
+	const auto        end   = (reinterpret_cast<uintptr_t>(data) + size + page - 1u) & ~(page - 1u);
+	thread_local std::vector<unsigned char> residency;
+	residency.resize((end - begin) / page);
+	return mincore(reinterpret_cast<void*>(begin), end - begin, residency.data()) == 0;

@NeySlim Thanks for the fix and the clarification. SysFileRead now checks the recovery probe before copying from the host buffer. If the probe is absent or rejects the destination, it preserves the short count. This addresses the unhandled write-fault concern.

The probe-rejection test also covers the failure case raised in this thread.


✏️ Learnings added
Learnt from: NeySlim
Repo: KytyPS5/KytyPS5 PR: 1165
File: src/common/platform/sysLinuxFileIO.cpp:0-0
Timestamp: 2026-10-08T05:17:53.322Z
Learning: In KytyPS5, Linux SysFileRead recovery must use SysFileSetRecoverableDestination to check whether a destination has a write-fault handler. The kernel-installed probe accepts only ranges registered with RenderContext::MapMemory, whose write faults HandleGpuFault resolves. Mapping alone is insufficient: reserved PROT_NONE ranges must not qualify for recovery. Windows keeps its existing recovery path; its probe setter is a no-op.

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


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

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 05:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165#discussion_r4215074336) On `src/common/platform/sysLinuxFileIO.cpp` line 94 (outdated): ```diff @@ -81,9 +84,43 @@ static void apply_cache_hint(FILE* f, sys_file_cache_type_t cache_type) { #endif } +// True when every page of [data, data + size) is mapped, whatever its protection. +static bool IsRangeMapped(const void* data, size_t size) { + static const auto page = static_cast<uintptr_t>(sysconf(_SC_PAGESIZE)); + const auto begin = reinterpret_cast<uintptr_t>(data) & ~(page - 1u); + const auto end = (reinterpret_cast<uintptr_t>(data) + size + page - 1u) & ~(page - 1u); + thread_local std::vector<unsigned char> residency; + residency.resize((end - begin) / page); + return mincore(reinterpret_cast<void*>(begin), end - begin, residency.data()) == 0; ``` `@NeySlim` Thanks for the fix and the clarification. `SysFileRead` now checks the recovery probe before copying from the host buffer. If the probe is absent or rejects the destination, it preserves the short count. This addresses the unhandled write-fault concern. The probe-rejection test also covers the failure case raised in this thread. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: NeySlim Repo: KytyPS5/KytyPS5 PR: 1165 File: src/common/platform/sysLinuxFileIO.cpp:0-0 Timestamp: 2026-10-08T05:17:53.322Z Learning: In KytyPS5, Linux SysFileRead recovery must use SysFileSetRecoverableDestination to check whether a destination has a write-fault handler. The kernel-installed probe accepts only ranges registered with RenderContext::MapMemory, whose write faults HandleGpuFault resolves. Mapping alone is insufficient: reserved PROT_NONE ranges must not qualify for recovery. Windows keeps its existing recovery path; its probe setter is a no-op. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=%60mincore%60%20accepts%20PROT_NONE%20ranges%2C%20so%20a%20retrying%20%60memcpy%60%20can%20crash%20instead%20of%20returning%20EFAULT.%20%40coderabbitai%20spots%20critical%20edge%20cases%E2%80%94try%20it!%20%F0%9F%9B%A1%EF%B8%8F&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1165%23discussion_r4212753101)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 05:22 UTC · original · edited 2026-10-08 05:43 UTC
On src/kernel/memory.cpp line 938 (outdated):

@@ -929,6 +930,15 @@ void InvalidateMemory(uint64_t vaddr, uint64_t size) {
 void InstallGpuResources(Graphics::RenderContext* resources) noexcept {
 	EXIT_IF(resources != nullptr && g_gpu_resources != nullptr);
 	g_gpu_resources = resources;
+	// Write faults in GPU-mapped guest memory are resolved by HandleGpuFault.
+	SysFileRecoverableDestination probe = nullptr;
+	if (resources != nullptr) {
+		probe = [](const void* data, uint64_t size) {
+			return g_gpu_resources != nullptr &&
+			       g_gpu_resources->IsMapped(reinterpret_cast<uint64_t>(data), size);

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

🔎 Supported by static analysis

🏁 Script executed:

set -u
printf '%s\n' '--- changed files ---'
git diff --stat bb98f26433fa9e711c219aac1711fe8ecba5bf3a 070f58e3f0544cb689e8e91eabfce7bfa10d244b
printf '%s\n' '--- relevant diff ---'
git diff --unified=80 bb98f26433fa9e711c219aac1711fe8ecba5bf3a 070f58e3f0544cb689e8e91eabfce7bfa10d244b -- src/kernel/memory.cpp src/kernel/sysFileIO.cpp src/kernel/sysFileIO.h
printf '%s\n' '--- symbol locations ---'
rg -n -F --glob '*.{cpp,h,hpp}' -- 'HandleFault' src
rg -n -F --glob '*.{cpp,h,hpp}' -- 'IsMapped' src
rg -n -F --glob '*.{cpp,h,hpp}' -- 'MapGpuRange' src
rg -n -F --glob '*.{cpp,h,hpp}' -- 'SysFileRead' src

Repository: KytyPS5/KytyPS5

Length of output: 11067


🏁 Script executed:

set -u
printf '%s\n' '--- changed files ---'
git diff --stat bb98f26433fa9e711c219aac1711fe8ecba5bf3a 070f58e3f0544cb689e8e91eabfce7bfa10d244b
printf '%s\n' '--- relevant diff ---'
git diff --unified=80 bb98f26433fa9e711c219aac1711fe8ecba5bf3a 070f58e3f0544cb689e8e91eabfce7bfa10d244b -- src/kernel/memory.cpp src/kernel/sysFileIO.cpp src/kernel/sysFileIO.h
printf '%s\n' '--- symbol locations ---'
rg -n -F --glob '*.{cpp,h,hpp}' -- 'HandleFault' src || test "$?" -eq 1
rg -n -F --glob '*.{cpp,h,hpp}' -- 'IsMapped' src || test "$?" -eq 1
rg -n -F --glob '*.{cpp,h,hpp}' -- 'MapGpuRange' src || test "$?" -eq 1
rg -n -F --glob '*.{cpp,h,hpp}' -- 'SysFileRead' src || test "$?" -eq 1

Repository: KytyPS5/KytyPS5

Length of output: 11067


🏁 Script executed:

printf '%s\n' '--- RenderContext implementation ---'
nl -ba src/graphics/host_gpu/renderer/renderContext.cpp | sed -n '1,115p'
printf '%s\n' '--- RenderContext declarations and access enum ---'
nl -ba src/graphics/host_gpu/renderer/renderContext.h | sed -n '1,95p'
rg -n -F -- 'enum class PageFaultAccess' src/graphics src/kernel src/common || true
printf '%s\n' '--- Linux file I/O implementation ---'
nl -ba src/common/platform/sysLinuxFileIO.cpp | sed -n '1,180p'
printf '%s\n' '--- file I/O contract ---'
nl -ba src/common/platform/sysFileIO.h | sed -n '1,80p'
printf '%s\n' '--- mapping and protection logic ---'
nl -ba src/kernel/memory.cpp | sed -n '70,110p'
rg -n -F -- 'DecodeMemoryProtection' src/kernel/memory.cpp src || true

Repository: KytyPS5/KytyPS5

Length of output: 24825


🏁 Script executed:

printf '%s\n' '--- fault handling references ---'
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'HandleGpuFault' src || true
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'PageFaultAccess::Write' src || true
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'InvalidateMemory' src/graphics/host_gpu src/common src/kernel | head -120
printf '%s\n' '--- cache declarations and implementations ---'
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'class BufferCache' src/graphics/host_gpu
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'class TextureCache' src/graphics/host_gpu

Repository: KytyPS5/KytyPS5

Length of output: 4007


🏁 Script executed:

printf '%s\n' '--- runtime fault dispatcher ---'
nl -ba src/loader/runtimeLinker.cpp | sed -n '630,705p'
printf '%s\n' '--- buffer invalidation ---'
nl -ba src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '215,285p'
printf '%s\n' '--- texture invalidation ---'
nl -ba src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1645,1725p'
printf '%s\n' '--- fault manager references ---'
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'FaultManager' src/graphics/host_gpu src/loader src/common || true
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'Unprotect' src | head -100

Repository: KytyPS5/KytyPS5

Length of output: 12238


🏁 Script executed:

printf '%s\n' '--- memory tracker symbols ---'
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'InvalidateRegion' src/graphics/host_gpu src
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'class MemoryTracker' src
printf '%s\n' '--- CPU alias invalidation symbols ---'
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'InvalidateCpuAliases' src/graphics/host_gpu
printf '%s\n' '--- host protection calls ---'
rg -n -E --glob '*.cpp' --glob '*.h' --glob '*.hpp' 'Protect|protect|VirtualProtect|mprotect|Mode::Read|Mode::ReadWrite' src/common src/graphics/host_gpu src/kernel | head -180

Repository: KytyPS5/KytyPS5

Length of output: 1213


🏁 Script executed:

printf '%s\n' '--- memory tracker ---'
nl -ba src/graphics/host_gpu/memoryTracker.h | sed -n '1,130p'
printf '%s\n' '--- CPU alias invalidation ---'
nl -ba src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1870,1945p'
printf '%s\n' '--- protection operations ---'
rg -n --glob '*.cpp' --glob '*.h' --glob '*.hpp' -e 'VirtualProtect' -e 'mprotect' -e 'Protect' -e 'protect' src/common src/graphics/host_gpu src/kernel || true

Repository: KytyPS5/KytyPS5

Length of output: 24763


🏁 Script executed:

printf '%s\n' '--- memory tracker iteration ---'
nl -ba src/graphics/host_gpu/memoryTracker.h | sed -n '117,190p'
printf '%s\n' '--- region manager protection state ---'
nl -ba src/graphics/host_gpu/regionManager.h | sed -n '1,180p'
printf '%s\n' '--- page manager registration/protection ---'
nl -ba src/graphics/host_gpu/pageManager.cpp | sed -n '170,225p'

Repository: KytyPS5/KytyPS5

Length of output: 11087


🏁 Script executed:

printf '%s\n' '--- GPU mapping call sites ---'
rg -n -C 8 -F -- 'MapGpuRange(' src/kernel/memory.cpp
printf '%s\n' '--- cache tracking registration ---'
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'TrackMemory' src/graphics/host_gpu src/kernel
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'RegisterMemory' src/graphics/host_gpu src/kernel
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'RegisterRegion' src/graphics/host_gpu src/kernel
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'MapMemory(' src/graphics/host_gpu src/kernel/memory.cpp

Repository: KytyPS5/KytyPS5

Length of output: 5770


Restrict the probe to destinations with recoverable GPU-tracking state.

IsMapped only checks mapped-range membership. HandleFault returns true for every mapped write fault, but MemoryTracker::InvalidateRegion removes host protection only for existing tracking regions. An untracked mapped range can therefore pass the probe, resume after the fault handler, and fault again when SysFileRead calls memcpy.

Use a write-fault eligibility check from the GPU resource or cache-tracking layer. Do not use IsMapped alone.

✅ Confirmed as addressed by @⁠NeySlim

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 05:22 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165#discussion_r4215106490) · edited 2026-10-08 05:43 UTC On `src/kernel/memory.cpp` line 938 (outdated): ```diff @@ -929,6 +930,15 @@ void InvalidateMemory(uint64_t vaddr, uint64_t size) { void InstallGpuResources(Graphics::RenderContext* resources) noexcept { EXIT_IF(resources != nullptr && g_gpu_resources != nullptr); g_gpu_resources = resources; + // Write faults in GPU-mapped guest memory are resolved by HandleGpuFault. + SysFileRecoverableDestination probe = nullptr; + if (resources != nullptr) { + probe = [](const void* data, uint64_t size) { + return g_gpu_resources != nullptr && + g_gpu_resources->IsMapped(reinterpret_cast<uint64_t>(data), size); ``` **🩺 Stability & Availability** | **🟠 Major** | **🏗️ Heavy lift** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash set -u printf '%s\n' '--- changed files ---' git diff --stat bb98f26433fa9e711c219aac1711fe8ecba5bf3a 070f58e3f0544cb689e8e91eabfce7bfa10d244b printf '%s\n' '--- relevant diff ---' git diff --unified=80 bb98f26433fa9e711c219aac1711fe8ecba5bf3a 070f58e3f0544cb689e8e91eabfce7bfa10d244b -- src/kernel/memory.cpp src/kernel/sysFileIO.cpp src/kernel/sysFileIO.h printf '%s\n' '--- symbol locations ---' rg -n -F --glob '*.{cpp,h,hpp}' -- 'HandleFault' src rg -n -F --glob '*.{cpp,h,hpp}' -- 'IsMapped' src rg -n -F --glob '*.{cpp,h,hpp}' -- 'MapGpuRange' src rg -n -F --glob '*.{cpp,h,hpp}' -- 'SysFileRead' src ``` Repository: KytyPS5/KytyPS5 Length of output: 11067 --- 🏁 Script executed: ```bash set -u printf '%s\n' '--- changed files ---' git diff --stat bb98f26433fa9e711c219aac1711fe8ecba5bf3a 070f58e3f0544cb689e8e91eabfce7bfa10d244b printf '%s\n' '--- relevant diff ---' git diff --unified=80 bb98f26433fa9e711c219aac1711fe8ecba5bf3a 070f58e3f0544cb689e8e91eabfce7bfa10d244b -- src/kernel/memory.cpp src/kernel/sysFileIO.cpp src/kernel/sysFileIO.h printf '%s\n' '--- symbol locations ---' rg -n -F --glob '*.{cpp,h,hpp}' -- 'HandleFault' src || test "$?" -eq 1 rg -n -F --glob '*.{cpp,h,hpp}' -- 'IsMapped' src || test "$?" -eq 1 rg -n -F --glob '*.{cpp,h,hpp}' -- 'MapGpuRange' src || test "$?" -eq 1 rg -n -F --glob '*.{cpp,h,hpp}' -- 'SysFileRead' src || test "$?" -eq 1 ``` Repository: KytyPS5/KytyPS5 Length of output: 11067 --- 🏁 Script executed: ```bash printf '%s\n' '--- RenderContext implementation ---' nl -ba src/graphics/host_gpu/renderer/renderContext.cpp | sed -n '1,115p' printf '%s\n' '--- RenderContext declarations and access enum ---' nl -ba src/graphics/host_gpu/renderer/renderContext.h | sed -n '1,95p' rg -n -F -- 'enum class PageFaultAccess' src/graphics src/kernel src/common || true printf '%s\n' '--- Linux file I/O implementation ---' nl -ba src/common/platform/sysLinuxFileIO.cpp | sed -n '1,180p' printf '%s\n' '--- file I/O contract ---' nl -ba src/common/platform/sysFileIO.h | sed -n '1,80p' printf '%s\n' '--- mapping and protection logic ---' nl -ba src/kernel/memory.cpp | sed -n '70,110p' rg -n -F -- 'DecodeMemoryProtection' src/kernel/memory.cpp src || true ``` Repository: KytyPS5/KytyPS5 Length of output: 24825 --- 🏁 Script executed: ```bash printf '%s\n' '--- fault handling references ---' rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'HandleGpuFault' src || true rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'PageFaultAccess::Write' src || true rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'InvalidateMemory' src/graphics/host_gpu src/common src/kernel | head -120 printf '%s\n' '--- cache declarations and implementations ---' rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'class BufferCache' src/graphics/host_gpu rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'class TextureCache' src/graphics/host_gpu ``` Repository: KytyPS5/KytyPS5 Length of output: 4007 --- 🏁 Script executed: ```bash printf '%s\n' '--- runtime fault dispatcher ---' nl -ba src/loader/runtimeLinker.cpp | sed -n '630,705p' printf '%s\n' '--- buffer invalidation ---' nl -ba src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '215,285p' printf '%s\n' '--- texture invalidation ---' nl -ba src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1645,1725p' printf '%s\n' '--- fault manager references ---' rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'FaultManager' src/graphics/host_gpu src/loader src/common || true rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'Unprotect' src | head -100 ``` Repository: KytyPS5/KytyPS5 Length of output: 12238 --- 🏁 Script executed: ```bash printf '%s\n' '--- memory tracker symbols ---' rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'InvalidateRegion' src/graphics/host_gpu src rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'class MemoryTracker' src printf '%s\n' '--- CPU alias invalidation symbols ---' rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'InvalidateCpuAliases' src/graphics/host_gpu printf '%s\n' '--- host protection calls ---' rg -n -E --glob '*.cpp' --glob '*.h' --glob '*.hpp' 'Protect|protect|VirtualProtect|mprotect|Mode::Read|Mode::ReadWrite' src/common src/graphics/host_gpu src/kernel | head -180 ``` Repository: KytyPS5/KytyPS5 Length of output: 1213 --- 🏁 Script executed: ```bash printf '%s\n' '--- memory tracker ---' nl -ba src/graphics/host_gpu/memoryTracker.h | sed -n '1,130p' printf '%s\n' '--- CPU alias invalidation ---' nl -ba src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1870,1945p' printf '%s\n' '--- protection operations ---' rg -n --glob '*.cpp' --glob '*.h' --glob '*.hpp' -e 'VirtualProtect' -e 'mprotect' -e 'Protect' -e 'protect' src/common src/graphics/host_gpu src/kernel || true ``` Repository: KytyPS5/KytyPS5 Length of output: 24763 --- 🏁 Script executed: ```bash printf '%s\n' '--- memory tracker iteration ---' nl -ba src/graphics/host_gpu/memoryTracker.h | sed -n '117,190p' printf '%s\n' '--- region manager protection state ---' nl -ba src/graphics/host_gpu/regionManager.h | sed -n '1,180p' printf '%s\n' '--- page manager registration/protection ---' nl -ba src/graphics/host_gpu/pageManager.cpp | sed -n '170,225p' ``` Repository: KytyPS5/KytyPS5 Length of output: 11087 --- 🏁 Script executed: ```bash printf '%s\n' '--- GPU mapping call sites ---' rg -n -C 8 -F -- 'MapGpuRange(' src/kernel/memory.cpp printf '%s\n' '--- cache tracking registration ---' rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'TrackMemory' src/graphics/host_gpu src/kernel rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'RegisterMemory' src/graphics/host_gpu src/kernel rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'RegisterRegion' src/graphics/host_gpu src/kernel rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- 'MapMemory(' src/graphics/host_gpu src/kernel/memory.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 5770 --- </details> **Restrict the probe to destinations with recoverable GPU-tracking state.** `IsMapped` only checks mapped-range membership. `HandleFault` returns `true` for every mapped write fault, but `MemoryTracker::InvalidateRegion` removes host protection only for existing tracking regions. An untracked mapped range can therefore pass the probe, resume after the fault handler, and fault again when `SysFileRead` calls `memcpy`. Use a write-fault eligibility check from the GPU resource or cache-tracking layer. Do not use `IsMapped` alone. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:1065ffd4d5640d5905429cd0 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠NeySlim <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 05:22 UTC · original · reviewed

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5bf92774-c0a4-4567-99de-6b3eae8f2f7f
📥 Commits

Reviewing files that changed from the base of the PR and between b70b01a4563fba8ebe47da01231eda1a45ce96c6 and 070f58e3f0544cb689e8e91eabfce7bfa10d244b.

📒 Files selected for processing (5)
  • src/common/platform/sysFileIO.h
  • src/common/platform/sysLinuxFileIO.cpp
  • src/common/platform/sysWindowsFileIO.cpp
  • src/kernel/memory.cpp
  • tests/KernelFileSystemTests.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/KernelFileSystemTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 05:22 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165#pullrequestreview-5451869773) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `5bf92774-c0a4-4567-99de-6b3eae8f2f7f` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between b70b01a4563fba8ebe47da01231eda1a45ce96c6 and 070f58e3f0544cb689e8e91eabfce7bfa10d244b. </details> <details> <summary>📒 Files selected for processing (5)</summary> * `src/common/platform/sysFileIO.h` * `src/common/platform/sysLinuxFileIO.cpp` * `src/common/platform/sysWindowsFileIO.cpp` * `src/kernel/memory.cpp` * `tests/KernelFileSystemTests.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary> * tests/KernelFileSystemTests.cpp </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=b670d108-466c-44ae-90bb-6d564ecbef7d attempt=6b95351b-557a-4d36-836f-912dc72855b4 batch=1/1 -->
Author
Owner

@⁠NeySlim on GitHub · 2026-10-08 05:43 UTC · original
On src/kernel/memory.cpp line 938 (outdated):

@@ -929,6 +930,15 @@ void InvalidateMemory(uint64_t vaddr, uint64_t size) {
 void InstallGpuResources(Graphics::RenderContext* resources) noexcept {
 	EXIT_IF(resources != nullptr && g_gpu_resources != nullptr);
 	g_gpu_resources = resources;
+	// Write faults in GPU-mapped guest memory are resolved by HandleGpuFault.
+	SysFileRecoverableDestination probe = nullptr;
+	if (resources != nullptr) {
+		probe = [](const void* data, uint64_t size) {
+			return g_gpu_resources != nullptr &&
+			       g_gpu_resources->IsMapped(reinterpret_cast<uint64_t>(data), size);

Agreed, IsMapped is too broad: HandleFault returns true for any mapped write fault, but only pages with a write watcher get their protection removed. A destination the guest mapped read-only would fault again in memcpy. Fixed in 531b70a: the probe now walks the guest ranges of the destination. Guest-writable pages are accepted, since they do not fault. Any other page must be watched by the PageManager (new PageManager::IsWatched, through RenderContext::ResolvesWriteFaults), which is the case where the fault handler restores write access. Everything else keeps the short read. PageManagerTests covers IsWatched for untracked, watched, partially watched and released pages. The check is platform-independent; only the Linux read path uses the probe.

**@⁠NeySlim** on GitHub · 2026-10-08 05:43 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165#discussion_r4215271282) On `src/kernel/memory.cpp` line 938 (outdated): ```diff @@ -929,6 +930,15 @@ void InvalidateMemory(uint64_t vaddr, uint64_t size) { void InstallGpuResources(Graphics::RenderContext* resources) noexcept { EXIT_IF(resources != nullptr && g_gpu_resources != nullptr); g_gpu_resources = resources; + // Write faults in GPU-mapped guest memory are resolved by HandleGpuFault. + SysFileRecoverableDestination probe = nullptr; + if (resources != nullptr) { + probe = [](const void* data, uint64_t size) { + return g_gpu_resources != nullptr && + g_gpu_resources->IsMapped(reinterpret_cast<uint64_t>(data), size); ``` Agreed, `IsMapped` is too broad: `HandleFault` returns `true` for any mapped write fault, but only pages with a write watcher get their protection removed. A destination the guest mapped read-only would fault again in `memcpy`. Fixed in 531b70a: the probe now walks the guest ranges of the destination. Guest-writable pages are accepted, since they do not fault. Any other page must be watched by the `PageManager` (new `PageManager::IsWatched`, through `RenderContext::ResolvesWriteFaults`), which is the case where the fault handler restores write access. Everything else keeps the short read. `PageManagerTests` covers `IsWatched` for untracked, watched, partially watched and released pages. The check is platform-independent; only the Linux read path uses the probe.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 05:43 UTC · original
On src/kernel/memory.cpp line 938 (outdated):

@@ -929,6 +930,15 @@ void InvalidateMemory(uint64_t vaddr, uint64_t size) {
 void InstallGpuResources(Graphics::RenderContext* resources) noexcept {
 	EXIT_IF(resources != nullptr && g_gpu_resources != nullptr);
 	g_gpu_resources = resources;
+	// Write faults in GPU-mapped guest memory are resolved by HandleGpuFault.
+	SysFileRecoverableDestination probe = nullptr;
+	if (resources != nullptr) {
+		probe = [](const void* data, uint64_t size) {
+			return g_gpu_resources != nullptr &&
+			       g_gpu_resources->IsMapped(reinterpret_cast<uint64_t>(data), size);

@NeySlim Thanks for the fix and clarification. The supplied probe now accepts guest-writable ranges and requires ResolvesWriteFaults for other ranges. This addresses the original concern: mapped-range membership alone does not establish write-fault recovery.


✏️ Learnings added
Learnt from: NeySlim
Repo: KytyPS5/KytyPS5 PR: 1165
File: src/kernel/memory.cpp:0-0
Timestamp: 2026-10-08T05:43:46.172Z
Learning: In KytyPS5's C++ GPU memory handling, mapped-range membership alone does not establish write-fault recovery. RenderContext::HandleFault can report success for a mapped write fault even when no write watcher removes host protection. The recoverable-destination probe in src/kernel/memory.cpp must accept guest-writable ranges or require write-watcher coverage through RenderContext::ResolvesWriteFaults and PageManager::IsWatched for other ranges.

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


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

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 05:43 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165#discussion_r4215275017) On `src/kernel/memory.cpp` line 938 (outdated): ```diff @@ -929,6 +930,15 @@ void InvalidateMemory(uint64_t vaddr, uint64_t size) { void InstallGpuResources(Graphics::RenderContext* resources) noexcept { EXIT_IF(resources != nullptr && g_gpu_resources != nullptr); g_gpu_resources = resources; + // Write faults in GPU-mapped guest memory are resolved by HandleGpuFault. + SysFileRecoverableDestination probe = nullptr; + if (resources != nullptr) { + probe = [](const void* data, uint64_t size) { + return g_gpu_resources != nullptr && + g_gpu_resources->IsMapped(reinterpret_cast<uint64_t>(data), size); ``` `@NeySlim` Thanks for the fix and clarification. The supplied probe now accepts guest-writable ranges and requires `ResolvesWriteFaults` for other ranges. This addresses the original concern: mapped-range membership alone does not establish write-fault recovery. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: NeySlim Repo: KytyPS5/KytyPS5 PR: 1165 File: src/kernel/memory.cpp:0-0 Timestamp: 2026-10-08T05:43:46.172Z Learning: In KytyPS5's C++ GPU memory handling, mapped-range membership alone does not establish write-fault recovery. RenderContext::HandleFault can report success for a mapped write fault even when no write watcher removes host protection. The recoverable-destination probe in src/kernel/memory.cpp must accept guest-writable ranges or require write-watcher coverage through RenderContext::ResolvesWriteFaults and PageManager::IsWatched for other ranges. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=Mapped%20%E2%89%A0%20writable%3A%20untracked%20destinations%20can%20refault%20in%20%60memcpy%60.%20%40coderabbitai%20recommends%20probing%20for%20guest-writable%20or%20GPU-watched%20pages%20first.%20Try%20it%20for%20sharper%20code%20reviews%20%F0%9F%A9%BA&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1165%23discussion_r4215106490)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 05:50 UTC · original · reviewed

Caution

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

⚠️ Outside diff range comments (1)

🟡 Minor · Bound the recovery probe by the remaining file bytes. · sysLinuxFileIO.cpp:107-112

src/common/platform/sysLinuxFileIO.cpp:107-112
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Bound the recovery probe by the remaining file bytes.

When EOF occurs before an unmapped suffix, SysFileRead can probe beyond EOF and reject the retry. A 6000-byte read with 4096 bytes already read can therefore return 4096, even though the remaining 1904 bytes fit in the recoverable mapped page.

Limit step to the remaining regular-file bytes. This still rejects an unmapped page when the file reaches that page.

Suggested fix
 				if (fseeko(f.f, start + static_cast<off_t>(w), SEEK_SET) == 0) {
+					const off_t retry_start = start + static_cast<off_t>(w);
+					size_t       file_remaining = size - w;
+					struct stat  file_stat {};
+					if (fstat(fileno(f.f), &file_stat) == 0) {
+						file_remaining =
+						    file_stat.st_size > retry_start
+						        ? std::min(file_remaining,
+						                   static_cast<size_t>(file_stat.st_size - retry_start))
+						        : 0;
+					}
-					while (w < size) {
-						const size_t step = std::min<size_t>(size - w, chunk.size());
+					while (w < size && file_remaining != 0) {
+						const size_t step =
+						    std::min({size - w, chunk.size(), file_remaining});
 						const auto   recoverable =
 						    g_recoverable_destination.load(std::memory_order_acquire);
 						if (recoverable == nullptr ||
 							!recoverable(static_cast<uint8_t*>(data) + w, step)) {
 							break;
@@
 						}
 						std::memcpy(static_cast<uint8_t*>(data) + w, chunk.data(), got);
 						w += got;
+						file_remaining -= got;
+						if (got < step) {
+							break;
+						}
 					}

ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5b297ce6-35cb-455c-a363-f0688c3e58ec
📥 Commits

Reviewing files that changed from the base of the PR and between 070f58e3f0544cb689e8e91eabfce7bfa10d244b and 531b70a4d569ffcb5c7ab106a80a168bf0196038.

📒 Files selected for processing (6)
  • src/graphics/host_gpu/pageManager.cpp
  • src/graphics/host_gpu/pageManager.h
  • src/graphics/host_gpu/renderer/renderContext.cpp
  • src/graphics/host_gpu/renderer/renderContext.h
  • src/kernel/memory.cpp
  • tests/PageManagerTests.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/kernel/memory.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 05:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165#pullrequestreview-5452120326) · **reviewed** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (1)** > > <details> > <summary><strong>🟡 Minor</strong> · Bound the recovery probe by the remaining file bytes. · <code>sysLinuxFileIO.cpp:107-112</code></summary><blockquote> > > `src/common/platform/sysLinuxFileIO.cpp:107-112` > **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** > > **Bound the recovery probe by the remaining file bytes.** > > When EOF occurs before an unmapped suffix, `SysFileRead` can probe beyond EOF and reject the retry. A 6000-byte read with 4096 bytes already read can therefore return 4096, even though the remaining 1904 bytes fit in the recoverable mapped page. > > Limit `step` to the remaining regular-file bytes. This still rejects an unmapped page when the file reaches that page. > > <details> > <summary>Suggested fix</summary> > > ```diff > if (fseeko(f.f, start + static_cast<off_t>(w), SEEK_SET) == 0) { > + const off_t retry_start = start + static_cast<off_t>(w); > + size_t file_remaining = size - w; > + struct stat file_stat {}; > + if (fstat(fileno(f.f), &file_stat) == 0) { > + file_remaining = > + file_stat.st_size > retry_start > + ? std::min(file_remaining, > + static_cast<size_t>(file_stat.st_size - retry_start)) > + : 0; > + } > - while (w < size) { > - const size_t step = std::min<size_t>(size - w, chunk.size()); > + while (w < size && file_remaining != 0) { > + const size_t step = > + std::min({size - w, chunk.size(), file_remaining}); > const auto recoverable = > g_recoverable_destination.load(std::memory_order_acquire); > if (recoverable == nullptr || > !recoverable(static_cast<uint8_t*>(data) + w, step)) { > break; > @@ > } > std::memcpy(static_cast<uint8_t*>(data) + w, chunk.data(), got); > w += got; > + file_remaining -= got; > + if (got < step) { > + break; > + } > } > ``` > > </details> > > <!-- cr-comment:v1:cf7a163e50f3b2ab9b64288a --> > > </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `5b297ce6-35cb-455c-a363-f0688c3e58ec` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 070f58e3f0544cb689e8e91eabfce7bfa10d244b and 531b70a4d569ffcb5c7ab106a80a168bf0196038. </details> <details> <summary>📒 Files selected for processing (6)</summary> * `src/graphics/host_gpu/pageManager.cpp` * `src/graphics/host_gpu/pageManager.h` * `src/graphics/host_gpu/renderer/renderContext.cpp` * `src/graphics/host_gpu/renderer/renderContext.h` * `src/kernel/memory.cpp` * `tests/PageManagerTests.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary> * src/kernel/memory.cpp </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=8116483a-21fc-44c8-a573-10cc0edfbd9e attempt=44bf1cc2-f32f-4b9a-a916-899584907d2a batch=1/1 -->
Author
Owner

@⁠NeySlim on GitHub · 2026-10-08 10:09 UTC · original

@⁠coderabbitai Good catch on the EOF case, fixed in 8281716. The retry loop now bounds each chunk by the bytes the file can still supply (fstat on regular files), so the probe never covers the tail of a request past EOF, and the loop stops on a short chunk. New case in TestReadsIntoProtectedPages: a pread that starts at a protected page, reaches EOF before leaving the recoverable range, and asks for more than that range. It returns the remaining file bytes. Without the bound, it returns 0.

**@⁠NeySlim** on GitHub · 2026-10-08 10:09 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165#issuecomment-6057567098) @⁠coderabbitai Good catch on the EOF case, fixed in 8281716. The retry loop now bounds each chunk by the bytes the file can still supply (`fstat` on regular files), so the probe never covers the tail of a request past EOF, and the loop stops on a short chunk. New case in `TestReadsIntoProtectedPages`: a `pread` that starts at a protected page, reaches EOF before leaving the recoverable range, and asks for more than that range. It returns the remaining file bytes. Without the bound, it returns 0.
Author
Owner

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

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
git show --format=fuller --stat 8281716
ast-grep outline src/common/platform/sysLinuxFileIO.cpp --match SysFileRead --view expanded
ast-grep outline tests/KernelFileSystemTests.cpp --match TestReadsIntoProtectedPages --view expanded
git show 8281716 -- src/common/platform/sysLinuxFileIO.cpp tests/KernelFileSystemTests.cpp

Length of output: 4049


🏁 Script executed:

#!/bin/bash
set -euo pipefail
sed -n '85,145p' src/common/platform/sysLinuxFileIO.cpp
sed -n '171,235p' tests/KernelFileSystemTests.cpp

Length of output: 6223


@NeySlim Thanks for the fix. I verified that 8281716 bounds the recovery probe by the remaining regular-file bytes and stops after a short chunk.

The new TestReadsIntoProtectedPages case checks the returned byte count, the guard fault, and the copied data when the request extends past EOF and the recoverable range. This addresses the EOF concern. I did not run the tests.


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

Thank you for using CodeRabbit!

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 10:10 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165#issuecomment-6057583242) <!-- This is an auto-generated reply by CodeRabbit --> > [!TIP] > For best results, initiate chat on the files or code changes. <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ```shell #!/bin/bash set -euo pipefail git show --format=fuller --stat 8281716 ast-grep outline src/common/platform/sysLinuxFileIO.cpp --match SysFileRead --view expanded ast-grep outline tests/KernelFileSystemTests.cpp --match TestReadsIntoProtectedPages --view expanded git show 8281716 -- src/common/platform/sysLinuxFileIO.cpp tests/KernelFileSystemTests.cpp ``` Length of output: 4049 --- 🏁 Script executed: ```shell #!/bin/bash set -euo pipefail sed -n '85,145p' src/common/platform/sysLinuxFileIO.cpp sed -n '171,235p' tests/KernelFileSystemTests.cpp ``` Length of output: 6223 --- </details> `@NeySlim` Thanks for the fix. I verified that `8281716` bounds the recovery probe by the remaining regular-file bytes and stops after a short chunk. The new `TestReadsIntoProtectedPages` case checks the returned byte count, the guard fault, and the copied data when the request extends past EOF and the recoverable range. This addresses the EOF concern. I did not run the tests. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=EOF%20edge%20case%20fixed%3A%20retry%20chunks%20are%20bounded%20by%20remaining%20file%20bytes%2C%20and%20a%20regression%20test%20confirms%20%60pread%60%20returns%20them%20correctly.%20Catch%20bugs%20faster%20with%20%40coderabbitai%20%F0%9F%90%87%E2%9C%85&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1165)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> _You are interacting with an AI system._
Author
Owner

@⁠ali-commits on GitHub · 2026-10-15 01:41 UTC · original

Additional Linux test evidence for current head 828171643ccb4618518a5863b224a616e86a34e0 (including the current recoverable-destination probe and page-manager changes):

Check Result
Build kernel_file_system_tests and page_manager_tests Passed
Current PR head: both registered CTests 2/2 passed
Negative control: disable only the SysFileRead EFAULT recovery branch with false &&, rebuild Filesystem test fails at pread fills a buffer that crosses into a write-protected page
Restore exact PR code, rebuild, rerun both 2/2 passed; working tree clean

Full test logs and reproduction commands. Host: Intel i7-13700, Linux 7.2.9-2-cachyos, Clang 23.1.1 Release, CMake 4.4.4. The negative control is a recovery-disabled version of this head, not a full pre-PR base checkout.

This supports the Linux protected-page recovery behavior and shows that the regression test detects removal of the recovery. It is useful evidence for moving the fix forward through maintainer review. It is not a blanket merge certification: real GPU synchronization, race behavior, Astro/God of War gameplay and Windows were not validated in this test. Our separate successful Astro playtest used the Jetsku fork, so it is not attributed to this PR.

Published by GPT-6 Astra on behalf of @⁠ali-commits, at their explicit request. AI prepared and ran these checks and wrote this comment. No independent human code review is asserted.

**@⁠ali-commits** on GitHub · 2026-10-15 01:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1165#issuecomment-6182435512) Additional Linux test evidence for current head **828171643ccb4618518a5863b224a616e86a34e0** (including the current recoverable-destination probe and page-manager changes): | Check | Result | |---|---| | Build `kernel_file_system_tests` and `page_manager_tests` | Passed | | Current PR head: both registered CTests | 2/2 passed | | Negative control: disable only the SysFileRead EFAULT recovery branch with `false &&`, rebuild | Filesystem test fails at `pread fills a buffer that crosses into a write-protected page` | | Restore exact PR code, rebuild, rerun both | 2/2 passed; working tree clean | [Full test logs and reproduction commands](https://gist.github.com/ali-commits/8b4366e3f670499602c936f24e9a5c1c). Host: Intel i7-13700, Linux 7.2.9-2-cachyos, Clang 23.1.1 Release, CMake 4.4.4. The negative control is a recovery-disabled version of this head, not a full pre-PR base checkout. This supports the Linux protected-page recovery behavior and shows that the regression test detects removal of the recovery. It is useful evidence for moving the fix forward through maintainer review. It is not a blanket merge certification: real GPU synchronization, race behavior, Astro/God of War gameplay and Windows were not validated in this test. Our separate successful Astro playtest used the Jetsku fork, so it is not attributed to this PR. Published by GPT-6 Astra on behalf of @⁠ali-commits, at their explicit request. AI prepared and ran these checks and wrote this comment. No independent human code review is asserted.

Pull request closed

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