kernel: retry guest file reads that fault on a write-protected page #2356

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

@⁠wuboo on GitHub · 2026-11-17 18:40 UTC · original
wuboo:pr/win-read-efault → main · +660 −8 · 12 files · 1 commits · open

Problem

On Windows, ASTRO BOT (PPSA21564) crashes in its level-loading threads during the transition from the world map to the first planet. The guest hits a trap, or writes through a null pointer:

thread: ProductNextLoad_ATQT   Unhandled host exception ... pc=0x90029c326 access=1 address=0xffffffffffffffff
thread: LevelTask_ATQT         Unhandled host exception ... pc=0x9005c5c17 access=1 address=0xffffffffffffffff
thread: RoomLoad_ATQT          Unhandled host exception ... pc=0x90706b5be access=1 address=0x0000000000000000

On faec1f45e + the PS logo fix, with the same replayed input, 6 of 7 runs ended this way. The one run that did not crash loaded the planet but never started it.

Cause

The GPU resource tracker write-protects guest pages that back GPU buffers and images. The host files are opened unbuffered, so a host read whose destination is on such a page does not fault into the guest page handler; the OS read call fails instead:

  • ReadFile returns ERROR_NOACCESS and delivers 0 bytes;
  • read(2) returns EFAULT.

File::Read ignored the error, so sceKernelRead / pread / preadv returned a short read with no error. The guest's buffer was left partly unfilled. With this change the loader crashes are gone in my runs (see Testing), so I believe that is where the bad pointers come from, but I have not traced a specific read.

The existing InvalidateMemory call before the read does not prevent this. The page can still be protected when the host read runs.

Fix

  • File::ReadEx / SysFileReadEx report the host error. On Windows, ERROR_NOACCESS and ERROR_INVALID_USER_BUFFER are reported as EFAULT, other failures as EIO, and a read at end of file is not an error; POSIX already returns EFAULT (and its errno for other failures).
  • When a read into a guest buffer fails with EFAULT, KernelRead, KernelPread and KernelPreadv retry the rest of the read through a host bounce buffer (in 1 MiB chunks, kernel/guestFileRead.h). The memcpy into the guest buffer takes the normal guest page fault, the tracker unprotects the page, and the guest gets all of its bytes.
  • Two checks guard the stores into the guest buffer, for the part of the buffer the read can fill (the call's size clamped to what is left in the file, so a buffer larger than the file's remainder with an unmapped tail still succeeds):
    • Before the first host read (which stores straight into the buffer), Memory::IsKnownUnwritable rejects only a destination the guest memory map describes as reserved or as mapped without CPU or GPU write access, where a host store would fault and nothing would recover it. Memory the map does not describe passes, as it did before this change. One such buffer is the host buffer the AvPlayer file reader (FileStreamer) passes to the guest's readOffset callback, which reads into it with sceKernelPread. A program image passes only while it is host-writable: SetProgramMemoryProtection leaves it read-write whatever its guest protection and the map records that, while ProtectGuestMemory and mprotect give it the host protection of the guest one, so a read-only page there is rejected like any other. A read rejected here delivers 0 bytes, does not touch the buffer and leaves the file offset unchanged.
    • Before each bounce copy (the host read has already failed with EFAULT), Memory::IsGuestWritable requires committed guest memory with CPU or GPU write access, where the fault is a tracked page that the handler recovers. Any other destination (outside the map, reserved, read-only) fails the call with EFAULT instead of faulting in host code, as the console kernel does, and the file offset stays at the delivered bytes.
  • Any other host read failure fails the call with EIO instead of returning a short read. A short read at end of file is unchanged.

Testing

  • New win_read_efault test. SysFileReadEx: a read into a writable buffer returns the data with no error, a read at end of file is not an error, a read into a protected page (VirtualProtect PAGE_READONLY on Windows, PROT_NONE on POSIX) delivers 0 bytes and reports EFAULT, and other failures report EIO (write-only handle on Windows) or their errno (directory on POSIX). ReadIntoGuest: a short read at end of file returns its bytes with no error; a buffer outside the guest map (a host heap buffer) is read into directly, with no bounce copy; a destination known to be unwritable fails with EFAULT before the first read, with 0 bytes, the buffer untouched and the file offset unchanged (the page is host-writable there, so without the check the read would succeed and fill it); a destination whose host read fails and whose fault would not be recovered fails with EFAULT and is left untouched; a tracked page is retried in full; other failures fail with EIO.
  • New GuestReadDestinationChecks case in virtual_memory_allocation, on real guest mappings. CPU read-write flexible memory passes both checks. CPU read-only memory, reserved memory, and a range reaching either one are rejected by both. GPU-read-write-only memory (host read-write) passes both. A hole in the map and a host buffer pass the first-read check and fail the bounce-copy check. Read-write runtime memory passes; after ProtectGuestMemory(Read) it is rejected. A read-only program segment passes the first-read check only, and is rejected once ProtectGuestMemory(Read) or mprotect makes it host read-only.
  • Both pass on Windows (clang-cl) and macOS. Mutation checks: removing the POSIX error report, the Windows EIO mapping or the EIO result each fails the test. Removing the copy check crashes it. Removing the first-read check, or making it require committed writable memory again (the previous version), fails it. In GuestReadDestinationChecks, rejecting memory the map does not describe, ignoring GPU write access, dropping the program-image exception, widening it to every program range or letting reserved memory pass each fails the case.
  • macOS ctest: the same failures as main (the Vulkan-loader GPU tests, shader_cfg, kernel_file_system), all unrelated. The new tests pass.
  • ASTRO BOT on Windows 11, Ryzen 7 5700X, Radeon RX 9060 XT. Every run used the same replayed pad input and --shader-cache, on top of the PS logo fix:
    • without this change: loader crash in 6/7 runs, and the first planet never started in any run;
    • with this change: 0/2 crashes. One run reaches the first planet (underwater_aerial_garden started) and plays to 19,500 frames with no errors, and the image is correct. The other, with an empty shader cache, loaded the planet without a crash, but my replayed input did not start the level after the 20 s load.
    • That includes the case that crashed most reliably before: the same partial shader cache, on which runs without the fix crashed at the same guest pc right after the planet loaded.
    • After the review changes (EIO mapping, writable-destination check), one more run with an empty effective shader cache: no crash, the planet loaded (23 s) and the run went to 19,600 frames; as in the earlier empty-cache run, my replayed input did not start the level after the long load.
    • The previous version of this PR checked before the first read that the destination was committed, CPU-writable guest memory. On current main (2638b1b07) it crashed 3/3 at the PS logo (guest trap on VideoPlayerLoadUnload_ATQT). The AvPlayer file reader passes a host buffer to the guest's read callback, the check rejected it and the read returned EFAULT. Without this PR, the same build gets past the logo.
    • With the current version, on 2638b1b07 with the same input: the logo, title and world map pass (3,590 frames, empty shader cache). A second run reached transition_next, loaded the first planet (underwater_aerial_garden, 14.6 s) and ran to 20,473 frames with no errors. As before, my replayed input did not start the level after the load. A diagnostic log in that test build showed the reads the previous check rejected: 64 KiB reads into host heap addresses during the PS logo video.

AI use & testing

I used AI coding assistants to help investigate the crash, port the change and write the unit test. I reviewed every line of the diff myself and I am responsible for it.

Testing:

  • Game: ASTRO BOT (world map -> first planet, underwater_aerial_garden).
  • Hardware: Windows 11, Ryzen 7 5700X, Radeon RX 9060 XT (AMD Vulkan driver).
  • Runs with the same replayed input: loader crash 6/7 before -> 0/2 after; first planet played to 19,500 frames without errors after the change. Current version on main 2638b1b07: PS logo -> world map -> first planet loaded, 20,473 frames, no errors.
  • Unit tests: win_read_efault and virtual_memory_allocation (GuestReadDestinationChecks) on Windows and macOS, with mutation checks.
**@⁠wuboo** on GitHub · 2026-11-17 18:40 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356) `wuboo:pr/win-read-efault` → `main` · +660 −8 · 12 files · 1 commits · open ## Problem On Windows, ASTRO BOT (PPSA21564) crashes in its level-loading threads during the transition from the world map to the first planet. The guest hits a trap, or writes through a null pointer: ``` thread: ProductNextLoad_ATQT Unhandled host exception ... pc=0x90029c326 access=1 address=0xffffffffffffffff thread: LevelTask_ATQT Unhandled host exception ... pc=0x9005c5c17 access=1 address=0xffffffffffffffff thread: RoomLoad_ATQT Unhandled host exception ... pc=0x90706b5be access=1 address=0x0000000000000000 ``` On `faec1f45e` + the PS logo fix, with the same replayed input, 6 of 7 runs ended this way. The one run that did not crash loaded the planet but never started it. ## Cause The GPU resource tracker write-protects guest pages that back GPU buffers and images. The host files are opened unbuffered, so a host read whose destination is on such a page does not fault into the guest page handler; the OS read call fails instead: - `ReadFile` returns `ERROR_NOACCESS` and delivers 0 bytes; - `read(2)` returns `EFAULT`. `File::Read` ignored the error, so `sceKernelRead` / `pread` / `preadv` returned a short read with no error. The guest's buffer was left partly unfilled. With this change the loader crashes are gone in my runs (see Testing), so I believe that is where the bad pointers come from, but I have not traced a specific read. The existing `InvalidateMemory` call before the read does not prevent this. The page can still be protected when the host read runs. ## Fix - `File::ReadEx` / `SysFileReadEx` report the host error. On Windows, `ERROR_NOACCESS` and `ERROR_INVALID_USER_BUFFER` are reported as `EFAULT`, other failures as `EIO`, and a read at end of file is not an error; POSIX already returns `EFAULT` (and its errno for other failures). - When a read into a guest buffer fails with `EFAULT`, `KernelRead`, `KernelPread` and `KernelPreadv` retry the rest of the read through a host bounce buffer (in 1 MiB chunks, `kernel/guestFileRead.h`). The `memcpy` into the guest buffer takes the normal guest page fault, the tracker unprotects the page, and the guest gets all of its bytes. - Two checks guard the stores into the guest buffer, for the part of the buffer the read can fill (the call's size clamped to what is left in the file, so a buffer larger than the file's remainder with an unmapped tail still succeeds): - Before the first host read (which stores straight into the buffer), `Memory::IsKnownUnwritable` rejects only a destination the guest memory map describes as reserved or as mapped without CPU or GPU write access, where a host store would fault and nothing would recover it. Memory the map does not describe passes, as it did before this change. One such buffer is the host buffer the AvPlayer file reader (`FileStreamer`) passes to the guest's `readOffset` callback, which reads into it with `sceKernelPread`. A program image passes only while it is host-writable: `SetProgramMemoryProtection` leaves it read-write whatever its guest protection and the map records that, while `ProtectGuestMemory` and `mprotect` give it the host protection of the guest one, so a read-only page there is rejected like any other. A read rejected here delivers 0 bytes, does not touch the buffer and leaves the file offset unchanged. - Before each bounce copy (the host read has already failed with `EFAULT`), `Memory::IsGuestWritable` requires committed guest memory with CPU or GPU write access, where the fault is a tracked page that the handler recovers. Any other destination (outside the map, reserved, read-only) fails the call with `EFAULT` instead of faulting in host code, as the console kernel does, and the file offset stays at the delivered bytes. - Any other host read failure fails the call with `EIO` instead of returning a short read. A short read at end of file is unchanged. ## Testing - New `win_read_efault` test. `SysFileReadEx`: a read into a writable buffer returns the data with no error, a read at end of file is not an error, a read into a protected page (`VirtualProtect PAGE_READONLY` on Windows, `PROT_NONE` on POSIX) delivers 0 bytes and reports `EFAULT`, and other failures report `EIO` (write-only handle on Windows) or their errno (directory on POSIX). `ReadIntoGuest`: a short read at end of file returns its bytes with no error; a buffer outside the guest map (a host heap buffer) is read into directly, with no bounce copy; a destination known to be unwritable fails with `EFAULT` before the first read, with 0 bytes, the buffer untouched and the file offset unchanged (the page is host-writable there, so without the check the read would succeed and fill it); a destination whose host read fails and whose fault would not be recovered fails with `EFAULT` and is left untouched; a tracked page is retried in full; other failures fail with `EIO`. - New `GuestReadDestinationChecks` case in `virtual_memory_allocation`, on real guest mappings. CPU read-write flexible memory passes both checks. CPU read-only memory, reserved memory, and a range reaching either one are rejected by both. GPU-read-write-only memory (host read-write) passes both. A hole in the map and a host buffer pass the first-read check and fail the bounce-copy check. Read-write runtime memory passes; after `ProtectGuestMemory(Read)` it is rejected. A read-only program segment passes the first-read check only, and is rejected once `ProtectGuestMemory(Read)` or `mprotect` makes it host read-only. - Both pass on Windows (clang-cl) and macOS. Mutation checks: removing the POSIX error report, the Windows `EIO` mapping or the `EIO` result each fails the test. Removing the copy check crashes it. Removing the first-read check, or making it require committed writable memory again (the previous version), fails it. In `GuestReadDestinationChecks`, rejecting memory the map does not describe, ignoring GPU write access, dropping the program-image exception, widening it to every program range or letting reserved memory pass each fails the case. - macOS `ctest`: the same failures as `main` (the Vulkan-loader GPU tests, `shader_cfg`, `kernel_file_system`), all unrelated. The new tests pass. - ASTRO BOT on Windows 11, Ryzen 7 5700X, Radeon RX 9060 XT. Every run used the same replayed pad input and `--shader-cache`, on top of the PS logo fix: - without this change: loader crash in 6/7 runs, and the first planet never started in any run; - with this change: 0/2 crashes. One run reaches the first planet (`underwater_aerial_garden` started) and plays to 19,500 frames with no errors, and the image is correct. The other, with an empty shader cache, loaded the planet without a crash, but my replayed input did not start the level after the 20 s load. - That includes the case that crashed most reliably before: the same partial shader cache, on which runs without the fix crashed at the same guest pc right after the planet loaded. - After the review changes (EIO mapping, writable-destination check), one more run with an empty effective shader cache: no crash, the planet loaded (23 s) and the run went to 19,600 frames; as in the earlier empty-cache run, my replayed input did not start the level after the long load. - The previous version of this PR checked before the first read that the destination was committed, CPU-writable guest memory. On current `main` (`2638b1b07`) it crashed 3/3 at the PS logo (guest trap on `VideoPlayerLoadUnload_ATQT`). The AvPlayer file reader passes a host buffer to the guest's read callback, the check rejected it and the read returned `EFAULT`. Without this PR, the same build gets past the logo. - With the current version, on `2638b1b07` with the same input: the logo, title and world map pass (3,590 frames, empty shader cache). A second run reached `transition_next`, loaded the first planet (`underwater_aerial_garden`, 14.6 s) and ran to 20,473 frames with no errors. As before, my replayed input did not start the level after the load. A diagnostic log in that test build showed the reads the previous check rejected: 64 KiB reads into host heap addresses during the PS logo video. ### AI use & testing I used AI coding assistants to help investigate the crash, port the change and write the unit test. I reviewed every line of the diff myself and I am responsible for it. Testing: - Game: ASTRO BOT (world map -> first planet, `underwater_aerial_garden`). - Hardware: Windows 11, Ryzen 7 5700X, Radeon RX 9060 XT (AMD Vulkan driver). - Runs with the same replayed input: loader crash 6/7 before -> 0/2 after; first planet played to 19,500 frames without errors after the change. Current version on `main` 2638b1b07: PS logo -> world map -> first planet loaded, 20,473 frames, no errors. - Unit tests: `win_read_efault` and `virtual_memory_allocation` (`GuestReadDestinationChecks`) on Windows and macOS, with mutation checks.
A guest read buffer can sit on a page the GPU resource tracker keeps
write-protected. The host files are unbuffered, so the read then fails
instead of faulting into the guest handler: read(2) returns EFAULT and
ReadFile returns ERROR_NOACCESS with 0 bytes. The kernel ignored the error
and gave the guest a silent short read of its data.

Report the failure as EFAULT on both hosts (ReadFile's ERROR_NOACCESS and
ERROR_INVALID_USER_BUFFER included, other ReadFile failures as EIO) and
retry the rest of the read through a host bounce buffer, whose copy into
the guest takes the fault that unprotects the page. The copy needs
committed guest memory with CPU or GPU write access, where the fault
handler recovers the fault; any other destination fails the read with
EFAULT instead of faulting in host code.

Before the first host read, a destination the guest memory map describes
as reserved or mapped without write access fails the read with EFAULT,
with 0 bytes delivered and the file offset unchanged. Memory the map does
not describe is read into as before: the AvPlayer file reader hands the
guest's read callback a host buffer, and rejecting it broke the PS logo
video. Neither is a program image that stays host-writable whatever its
guest protection; once it is protected read-only on the host, it is.

Other host read errors fail the call with EIO instead of returning a short
read; a short read at end of file is unchanged. read, pread and preadv use
it.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:18:44 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-17 18:49 UTC · original · edited 2026-11-24 23:22 UTC

Explain Change →

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: 1e7af94ced06dc41e8a9083b5356be5906c913cd
  • Latest commit, not reviewed: 066498b3e6

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review
Walkthrough

The change adds extended file-read APIs that report byte counts and errors. Kernel read operations use a guest-buffer helper that checks guest-memory writability and retries EFAULT reads through a bounce buffer. The change adds cross-platform tests for read errors and guest-buffer recovery. CMake builds and registers the test executable.

Suggested reviewers: nmzik

Change: Bug fix

Merge Risk: Low · previous review 1e7af

Guest file reads into write-protected GPU-tracked buffers are now retried so the page-fault handler can complete them. A small remaining risk is that a guest thread unmapping or re-protecting the destination mid-read could crash the emulator instead of returning an error. This only happens when the guest program itself has that race, so the change is mergeable with owner awareness.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: guest file reads that fault on a write-protected page are retried. The changeset adds ReadEx/SysFileReadEx error reporting, a bounce-buffer retry in KernelRead/KernelP…
Description check Passed The description explains the crash, its cause (host reads into write-protected GPU-tracked pages returning EFAULT, which File::Read ignored), the fix (error reporting, bounce-buffer retry, destination…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: guest file reads that fault on a write-protected page are retried. The changeset adds ReadEx/SysFileReadEx error reporting, a bounce-buffer retry in KernelRead/KernelPread/KernelPreadv, and destination checks (IsKnownUnwritable/IsGuestWritable), all aimed at that case. The title is specific and matches the objectives.

Full details: Description check

Explanation

The description explains the crash, its cause (host reads into write-protected GPU-tracked pages returning EFAULT, which File::Read ignored), the fix (error reporting, bounce-buffer retry, destination checks), and the testing performed. It is directly related to the changeset.

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

Share

**@⁠coderabbitai[bot]** on GitHub · 2026-11-17 18:49 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#issuecomment-6957634052) · edited 2026-11-24 23:22 UTC <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/2356?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg" alt="Explain Change →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- 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: 1e7af94ced06dc41e8a9083b5356be5906c913cd > - Latest commit, not reviewed: 066498b3e6974c2521f1c6a849dfcffeeeb9988b > > Use the following commands to manage reviews: > - `@coderabbitai resume` to resume automatic reviews. > - `@coderabbitai review` to trigger a single review. > > Use the checkboxes below for quick actions: > - [ ] <!-- {"checkboxId":"7f6cc2e2-2e4e-497a-8c31-c9e4573e93d1"} --> Resume reviews > - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> Trigger review <!-- end of auto-generated comment: review paused by coderabbit.ai --> <!-- walkthrough_start --> <details> <summary><strong>Walkthrough</strong></summary> <dl> <dd> <br> The change adds extended file-read APIs that report byte counts and errors. Kernel read operations use a guest-buffer helper that checks guest-memory writability and retries EFAULT reads through a bounce buffer. The change adds cross-platform tests for read errors and guest-buffer recovery. CMake builds and registers the test executable. **Suggested reviewers:** `nmzik` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> <!-- change_assessment_commit:"1e7af94ced06dc41e8a9083b5356be5906c913cd" --> <!-- change_assessment_priority:{"version":1,"urgency":"p2","manual":false} --> **Change:** Bug fix <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/risk-low-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Low</strong> · previous review <code>1e7af</code></summary> <dl> <dd> <br> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🔵 Low** · up to `1e7af` --> <!-- final_review_risk_coverage:{"sourceCommitId":"1e7af94ced06dc41e8a9083b5356be5906c913cd","coveredCommitId":"1e7af94ced06dc41e8a9083b5356be5906c913cd","kind":"reviewed"} --> Guest file reads into write-protected GPU-tracked buffers are now retried so the page-fault handler can complete them. A small remaining risk is that a guest thread unmapping or re-protecting the destination mid-read could crash the emulator instead of returning an error. This only happens when the guest program itself has that race, so the change is mergeable with owner awareness. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4</strong></summary> <dl> <dd> <br> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title names the main change: guest file reads that fault on a write-protected page are retried. The changeset adds ReadEx/SysFileReadEx error reporting, a bounce-buffer retry in KernelRead/KernelP… | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description explains the crash, its cause (host reads into write-protected GPU-tracked pages returning EFAULT, which File::Read ignored), the fix (error reporting, bounce-buffer retry, destination… | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | <details> <summary><strong>Full details: Title check</strong></summary> <dl> <dd> <br> **Explanation** The title names the main change: guest file reads that fault on a write-protected page are retried. The changeset adds ReadEx/SysFileReadEx error reporting, a bounce-buffer retry in KernelRead/KernelPread/KernelPreadv, and destination checks (IsKnownUnwritable/IsGuestWritable), all aimed at that case. The title is specific and matches the objectives. </dd> </dl> </details> <details> <summary><strong>Full details: Description check</strong></summary> <dl> <dd> <br> **Explanation** The description explains the crash, its cause (host reads into write-protected GPU-tracked pages returning EFAULT, which File::Read ignored), the fix (error reporting, bounce-buffer retry, destination checks), and the testing performed. It is directly related to the changeset. </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=2356)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>Share</strong></summary> <dl> <dd> <br> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </dd> </dl> </details> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-17 18:49 UTC · original · edited 2026-11-17 20:59 UTC
On src/common/platform/sysWindowsFileIO.cpp line 49 (outdated):

@@ -30,6 +32,24 @@ constexpr DWORD FILE_SHARE_POSIX = static_cast<DWORD>(FILE_SHARE_READ) |
 constexpr DWORD READ_WRITE_DELETE = static_cast<DWORD>(GENERIC_READ) |
                                     static_cast<DWORD>(GENERIC_WRITE) | static_cast<DWORD>(DELETE);
 
+// ReadFile into a page the GPU resource tracker has made PAGE_READONLY fails with ERROR_NOACCESS
+// and delivers 0 bytes. Report it as EFAULT, as POSIX read does, so the caller retries through a
+// host buffer instead of giving the guest a silent short read.
+void SysFileReadEx(void* data, uint32_t size, sys_file_t& f, uint32_t* bytes_read, int* err) {
+	if (err != nullptr) {
+		*err = 0;
+	}
+	DWORD       w   = 0;
+	const BOOL  ok  = ReadFile(f.handle, data, size, &w, nullptr);
+	const DWORD gle = (ok != 0 ? 0 : GetLastError());
+	if (bytes_read != nullptr) {
+		*bytes_read = w;
+	}
+	if (ok == 0 && err != nullptr && (gle == ERROR_NOACCESS || gle == ERROR_INVALID_USER_BUFFER)) {
+		*err = EFAULT;

Minor · Functional Correctness · Quick win

Return EIO for other failed reads, except end-of-file.

SysFileReadEx reports only ERROR_NOACCESS and ERROR_INVALID_USER_BUFFER as EFAULT. Other failed reads, such as a read that overlaps a range locked by another process, leave *err at 0. In the bounce-retry loop in ReadIntoGuest, such a failure returns true with a short count, so the guest receives a partial buffer as a successful read.

Keep both EFAULT mappings. Map other failures to EIO. Keep ERROR_HANDLE_EOF at 0, because a read that starts at end of file must still return a zero-byte result without an error.

Suggested fix

--- "a/src/common/platform/sysWindowsFileIO.cpp"
+++ "b/src/common/platform/sysWindowsFileIO.cpp"
@@ -45,9 +45,9 @@
 	if (bytes_read != nullptr) {
 		*bytes_read = w;
 	}
-	if (ok == 0 && err != nullptr && (gle == ERROR_NOACCESS || gle == ERROR_INVALID_USER_BUFFER)) {
-		*err = EFAULT;
+	if (ok == 0 && err != nullptr && gle != ERROR_HANDLE_EOF) {
+		*err = (gle == ERROR_NOACCESS || gle == ERROR_INVALID_USER_BUFFER) ? EFAULT : EIO;
 	}
 }
 
 void SysFileRead(void* data, uint32_t size, sys_file_t& f, uint32_t* bytes_read) {
Committable suggestion

IMPORTANT
Review the replacement and indentation, then test before committing.

	if (ok == 0 && err != nullptr && gle != ERROR_HANDLE_EOF) {
		*err = (gle == ERROR_NOACCESS || gle == ERROR_INVALID_USER_BUFFER) ? EFAULT : EIO;

✅ Confirmed as addressed by @⁠wuboo

**@⁠coderabbitai[bot]** on GitHub · 2026-11-17 18:49 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#discussion_r4604207290) · edited 2026-11-17 20:59 UTC On `src/common/platform/sysWindowsFileIO.cpp` line 49 (outdated): ```diff @@ -30,6 +32,24 @@ constexpr DWORD FILE_SHARE_POSIX = static_cast<DWORD>(FILE_SHARE_READ) | constexpr DWORD READ_WRITE_DELETE = static_cast<DWORD>(GENERIC_READ) | static_cast<DWORD>(GENERIC_WRITE) | static_cast<DWORD>(DELETE); +// ReadFile into a page the GPU resource tracker has made PAGE_READONLY fails with ERROR_NOACCESS +// and delivers 0 bytes. Report it as EFAULT, as POSIX read does, so the caller retries through a +// host buffer instead of giving the guest a silent short read. +void SysFileReadEx(void* data, uint32_t size, sys_file_t& f, uint32_t* bytes_read, int* err) { + if (err != nullptr) { + *err = 0; + } + DWORD w = 0; + const BOOL ok = ReadFile(f.handle, data, size, &w, nullptr); + const DWORD gle = (ok != 0 ? 0 : GetLastError()); + if (bytes_read != nullptr) { + *bytes_read = w; + } + if (ok == 0 && err != nullptr && (gle == ERROR_NOACCESS || gle == ERROR_INVALID_USER_BUFFER)) { + *err = EFAULT; ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Return `EIO` for other failed reads, except end-of-file.** `SysFileReadEx` reports only `ERROR_NOACCESS` and `ERROR_INVALID_USER_BUFFER` as `EFAULT`. Other failed reads, such as a read that overlaps a range locked by another process, leave `*err` at 0. In the bounce-retry loop in `ReadIntoGuest`, such a failure returns `true` with a short count, so the guest receives a partial buffer as a successful read. Keep both `EFAULT` mappings. Map other failures to `EIO`. Keep `ERROR_HANDLE_EOF` at 0, because a read that starts at end of file must still return a zero-byte result without an error. <details> <summary>Suggested fix</summary> <dl> <dd> <br> ```diff --- "a/src/common/platform/sysWindowsFileIO.cpp" +++ "b/src/common/platform/sysWindowsFileIO.cpp" @@ -45,9 +45,9 @@ if (bytes_read != nullptr) { *bytes_read = w; } - if (ok == 0 && err != nullptr && (gle == ERROR_NOACCESS || gle == ERROR_INVALID_USER_BUFFER)) { - *err = EFAULT; + if (ok == 0 && err != nullptr && gle != ERROR_HANDLE_EOF) { + *err = (gle == ERROR_NOACCESS || gle == ERROR_INVALID_USER_BUFFER) ? EFAULT : EIO; } } void SysFileRead(void* data, uint32_t size, sys_file_t& f, uint32_t* bytes_read) { ``` </dd> </dl> </details> <!-- suggestion_start --> <details> <summary>Committable suggestion</summary> <dl> <dd> <br> > <picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg" width="20" height="20" align="absmiddle" alt=""></picture> **IMPORTANT** > Review the replacement and indentation, then test before committing. ```suggestion if (ok == 0 && err != nullptr && gle != ERROR_HANDLE_EOF) { *err = (gle == ERROR_NOACCESS || gle == ERROR_INVALID_USER_BUFFER) ? EFAULT : EIO; ``` </dd> </dl> </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:1e0ec39a477b2a36ad28e5f7 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠wuboo <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-17 18:49 UTC · original · edited 2026-11-17 21:00 UTC
On src/kernel/fileSystem.cpp line 212 (outdated):

@@ -179,6 +180,46 @@ static std::vector<uint8_t> PackDirents(const std::vector<Common::File::DirEntry
 	return dirents;
 }
 
+// A guest buffer may be write-protected by the GPU resource tracker. The host files are
+// unbuffered, so the read then fails with EFAULT instead of faulting into the guest handler,
+// and the guest used to get a silent short read. Retry through a host bounce buffer: the
+// memcpy into the guest takes the fault that unprotects the page. On Windows ReadFile fails with
+// ERROR_NOACCESS, which SysFileReadEx reports as EFAULT.
+static bool ReadIntoGuest(File* file, void* buf, uint32_t want, uint64_t pos, uint32_t* got) {
+	int err = 0;
+	file->f.ReadEx(buf, want, got, &err);
+	if (*got >= want || err == 0 || err != EFAULT) {
+		return true;
+	}
+
+	constexpr uint32_t   Chunk = 1u << 20;
+	std::vector<uint8_t> bounce;
+	uint32_t             done = *got;
+	if (!file->f.Seek(pos + done)) {
+		return false;
+	}
+	while (done < want) {
+		const uint32_t count = std::min<uint32_t>(want - done, Chunk);
+		bounce.resize(count);
+		uint32_t r  = 0;
+		int      e2 = 0;
+		file->f.ReadEx(bounce.data(), count, &r, &e2);
+		if (e2 != 0) {
+			*got = done;
+			return false;
+		}
+		if (r != 0) {
+			memcpy(static_cast<uint8_t*>(buf) + done, bounce.data(), r);

Major · Stability & Availability · Quick win

Keep an unrecovered fault on the retry copy from terminating the emulator.

The retry copy writes into buf + done without checking that the guest range is accessible. For an unmapped destination, the write faults in host code. HandleGpuFault returns false for an address the GPU tracker does not map, so KytyExceptionHandler reaches its fatal EXIT. Before this change, the same unmapped buffer returned EFAULT or a short read to the guest. Now the emulator exits. The same path applies when a platform reports EFAULT after a partial read and the next unread page is unmapped.

Require that an inaccessible guest destination, which the GPU tracker does not recover, returns an error to the guest instead of terminating the process. Keep write-protected tracked pages on the fault path, so the tracker can unprotect them.

✅ Confirmed as addressed by @⁠wuboo

**@⁠coderabbitai[bot]** on GitHub · 2026-11-17 18:49 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#discussion_r4604207319) · edited 2026-11-17 21:00 UTC On `src/kernel/fileSystem.cpp` line 212 (outdated): ```diff @@ -179,6 +180,46 @@ static std::vector<uint8_t> PackDirents(const std::vector<Common::File::DirEntry return dirents; } +// A guest buffer may be write-protected by the GPU resource tracker. The host files are +// unbuffered, so the read then fails with EFAULT instead of faulting into the guest handler, +// and the guest used to get a silent short read. Retry through a host bounce buffer: the +// memcpy into the guest takes the fault that unprotects the page. On Windows ReadFile fails with +// ERROR_NOACCESS, which SysFileReadEx reports as EFAULT. +static bool ReadIntoGuest(File* file, void* buf, uint32_t want, uint64_t pos, uint32_t* got) { + int err = 0; + file->f.ReadEx(buf, want, got, &err); + if (*got >= want || err == 0 || err != EFAULT) { + return true; + } + + constexpr uint32_t Chunk = 1u << 20; + std::vector<uint8_t> bounce; + uint32_t done = *got; + if (!file->f.Seek(pos + done)) { + return false; + } + while (done < want) { + const uint32_t count = std::min<uint32_t>(want - done, Chunk); + bounce.resize(count); + uint32_t r = 0; + int e2 = 0; + file->f.ReadEx(bounce.data(), count, &r, &e2); + if (e2 != 0) { + *got = done; + return false; + } + if (r != 0) { + memcpy(static_cast<uint8_t*>(buf) + done, bounce.data(), r); ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Keep an unrecovered fault on the retry copy from terminating the emulator.** The retry copy writes into `buf + done` without checking that the guest range is accessible. For an unmapped destination, the write faults in host code. `HandleGpuFault` returns false for an address the GPU tracker does not map, so `KytyExceptionHandler` reaches its fatal `EXIT`. Before this change, the same unmapped buffer returned `EFAULT` or a short read to the guest. Now the emulator exits. The same path applies when a platform reports `EFAULT` after a partial read and the next unread page is unmapped. Require that an inaccessible guest destination, which the GPU tracker does not recover, returns an error to the guest instead of terminating the process. Keep write-protected tracked pages on the fault path, so the tracker can unprotect them. <!-- fingerprinting:phantom:poseidon:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:cf4debd7be4615a69f2890a1 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠wuboo <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

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

Actionable comments posted: 2

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 4da95bd8d0 and 1974034429806872a0fbc49c9ca2834246373c31.

Files selected for processing: 8

  • CMakeLists.txt
  • src/common/file.cpp
  • src/common/file.h
  • src/common/platform/sysFileIO.h
  • src/common/platform/sysLinuxFileIO.cpp
  • src/common/platform/sysWindowsFileIO.cpp
  • src/kernel/fileSystem.cpp
  • tests/WinReadEfaultTests.cpp

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-11-17 18:49 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#pullrequestreview-5944580328) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 2** <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/4da95bd8d0f389d168812b98e58791055912e880/.coderabbit.yaml>) - **Commit**: [4da95bd](<https://github.com/KytyPS5/KytyPS5/commit/4da95bd8d0f389d168812b98e58791055912e880>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `7fef0ad6-007a-46a3-9686-c6597601aa3e` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 4da95bd8d0f389d168812b98e58791055912e880 and 1974034429806872a0fbc49c9ca2834246373c31. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 8</summary> <dl> <dd> <br> * `CMakeLists.txt` * `src/common/file.cpp` * `src/common/file.h` * `src/common/platform/sysFileIO.h` * `src/common/platform/sysLinuxFileIO.cpp` * `src/common/platform/sysWindowsFileIO.cpp` * `src/kernel/fileSystem.cpp` * `tests/WinReadEfaultTests.cpp` </dd> </dl> </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. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=28c9f3f9-ec5c-41bc-8a95-0ebfbec16388 attempt=e56fb076-a637-4d6a-85c3-53ecd33ebd66 batch=1/1 -->
Author
Owner

@⁠wuboo on GitHub · 2026-11-17 20:46 UTC · original
On src/common/platform/sysWindowsFileIO.cpp line 49 (outdated):

@@ -30,6 +32,24 @@ constexpr DWORD FILE_SHARE_POSIX = static_cast<DWORD>(FILE_SHARE_READ) |
 constexpr DWORD READ_WRITE_DELETE = static_cast<DWORD>(GENERIC_READ) |
                                     static_cast<DWORD>(GENERIC_WRITE) | static_cast<DWORD>(DELETE);
 
+// ReadFile into a page the GPU resource tracker has made PAGE_READONLY fails with ERROR_NOACCESS
+// and delivers 0 bytes. Report it as EFAULT, as POSIX read does, so the caller retries through a
+// host buffer instead of giving the guest a silent short read.
+void SysFileReadEx(void* data, uint32_t size, sys_file_t& f, uint32_t* bytes_read, int* err) {
+	if (err != nullptr) {
+		*err = 0;
+	}
+	DWORD       w   = 0;
+	const BOOL  ok  = ReadFile(f.handle, data, size, &w, nullptr);
+	const DWORD gle = (ok != 0 ? 0 : GetLastError());
+	if (bytes_read != nullptr) {
+		*bytes_read = w;
+	}
+	if (ok == 0 && err != nullptr && (gle == ERROR_NOACCESS || gle == ERROR_INVALID_USER_BUFFER)) {
+		*err = EFAULT;

Done. SysFileReadEx now reports every failed ReadFile except ERROR_HANDLE_EOF: ERROR_NOACCESS/ERROR_INVALID_USER_BUFFER as EFAULT, anything else as EIO. ReadIntoGuest turns any non-EFAULT failure into EIO instead of a short read, and a plain short read at end of file is unchanged. The POSIX side already reported errno through ferror, and the test now covers both platforms.

**@⁠wuboo** on GitHub · 2026-11-17 20:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#discussion_r4605579602) On `src/common/platform/sysWindowsFileIO.cpp` line 49 (outdated): ```diff @@ -30,6 +32,24 @@ constexpr DWORD FILE_SHARE_POSIX = static_cast<DWORD>(FILE_SHARE_READ) | constexpr DWORD READ_WRITE_DELETE = static_cast<DWORD>(GENERIC_READ) | static_cast<DWORD>(GENERIC_WRITE) | static_cast<DWORD>(DELETE); +// ReadFile into a page the GPU resource tracker has made PAGE_READONLY fails with ERROR_NOACCESS +// and delivers 0 bytes. Report it as EFAULT, as POSIX read does, so the caller retries through a +// host buffer instead of giving the guest a silent short read. +void SysFileReadEx(void* data, uint32_t size, sys_file_t& f, uint32_t* bytes_read, int* err) { + if (err != nullptr) { + *err = 0; + } + DWORD w = 0; + const BOOL ok = ReadFile(f.handle, data, size, &w, nullptr); + const DWORD gle = (ok != 0 ? 0 : GetLastError()); + if (bytes_read != nullptr) { + *bytes_read = w; + } + if (ok == 0 && err != nullptr && (gle == ERROR_NOACCESS || gle == ERROR_INVALID_USER_BUFFER)) { + *err = EFAULT; ``` Done. `SysFileReadEx` now reports every failed `ReadFile` except `ERROR_HANDLE_EOF`: `ERROR_NOACCESS`/`ERROR_INVALID_USER_BUFFER` as `EFAULT`, anything else as `EIO`. `ReadIntoGuest` turns any non-EFAULT failure into `EIO` instead of a short read, and a plain short read at end of file is unchanged. The POSIX side already reported errno through `ferror`, and the test now covers both platforms.
Author
Owner

@⁠wuboo on GitHub · 2026-11-17 20:46 UTC · original
On src/kernel/fileSystem.cpp line 212 (outdated):

@@ -179,6 +180,46 @@ static std::vector<uint8_t> PackDirents(const std::vector<Common::File::DirEntry
 	return dirents;
 }
 
+// A guest buffer may be write-protected by the GPU resource tracker. The host files are
+// unbuffered, so the read then fails with EFAULT instead of faulting into the guest handler,
+// and the guest used to get a silent short read. Retry through a host bounce buffer: the
+// memcpy into the guest takes the fault that unprotects the page. On Windows ReadFile fails with
+// ERROR_NOACCESS, which SysFileReadEx reports as EFAULT.
+static bool ReadIntoGuest(File* file, void* buf, uint32_t want, uint64_t pos, uint32_t* got) {
+	int err = 0;
+	file->f.ReadEx(buf, want, got, &err);
+	if (*got >= want || err == 0 || err != EFAULT) {
+		return true;
+	}
+
+	constexpr uint32_t   Chunk = 1u << 20;
+	std::vector<uint8_t> bounce;
+	uint32_t             done = *got;
+	if (!file->f.Seek(pos + done)) {
+		return false;
+	}
+	while (done < want) {
+		const uint32_t count = std::min<uint32_t>(want - done, Chunk);
+		bounce.resize(count);
+		uint32_t r  = 0;
+		int      e2 = 0;
+		file->f.ReadEx(bounce.data(), count, &r, &e2);
+		if (e2 != 0) {
+			*got = done;
+			return false;
+		}
+		if (r != 0) {
+			memcpy(static_cast<uint8_t*>(buf) + done, bounce.data(), r);

Good catch, fixed. Before each copy, the bounce retry now checks Memory::IsGuestWritable (committed, CPU-writable guest memory, where a tracker fault is recovered). Any other destination fails the read with EFAULT without copying, and the file offset only covers the delivered bytes. The retry moved to kernel/guestFileRead.h, and win_read_efault now tests the rejected-destination and tracked-page paths.

**@⁠wuboo** on GitHub · 2026-11-17 20:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#discussion_r4605579900) On `src/kernel/fileSystem.cpp` line 212 (outdated): ```diff @@ -179,6 +180,46 @@ static std::vector<uint8_t> PackDirents(const std::vector<Common::File::DirEntry return dirents; } +// A guest buffer may be write-protected by the GPU resource tracker. The host files are +// unbuffered, so the read then fails with EFAULT instead of faulting into the guest handler, +// and the guest used to get a silent short read. Retry through a host bounce buffer: the +// memcpy into the guest takes the fault that unprotects the page. On Windows ReadFile fails with +// ERROR_NOACCESS, which SysFileReadEx reports as EFAULT. +static bool ReadIntoGuest(File* file, void* buf, uint32_t want, uint64_t pos, uint32_t* got) { + int err = 0; + file->f.ReadEx(buf, want, got, &err); + if (*got >= want || err == 0 || err != EFAULT) { + return true; + } + + constexpr uint32_t Chunk = 1u << 20; + std::vector<uint8_t> bounce; + uint32_t done = *got; + if (!file->f.Seek(pos + done)) { + return false; + } + while (done < want) { + const uint32_t count = std::min<uint32_t>(want - done, Chunk); + bounce.resize(count); + uint32_t r = 0; + int e2 = 0; + file->f.ReadEx(bounce.data(), count, &r, &e2); + if (e2 != 0) { + *got = done; + return false; + } + if (r != 0) { + memcpy(static_cast<uint8_t*>(buf) + done, bounce.data(), r); ``` Good catch, fixed. Before each copy, the bounce retry now checks `Memory::IsGuestWritable` (committed, CPU-writable guest memory, where a tracker fault is recovered). Any other destination fails the read with `EFAULT` without copying, and the file offset only covers the delivered bytes. The retry moved to `kernel/guestFileRead.h`, and `win_read_efault` now tests the rejected-destination and tracked-page paths.
@ -0,0 +38,4 @@
if (want != 0 && known_unwritable(buf, want)) {
return EFAULT;
}
f.ReadEx(buf, want, got, &err);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-17 20:55 UTC · original · edited 2026-11-17 23:08 UTC

Minor · Stability & Availability · Quick win

Small reads into non-writable guest buffers can crash the process instead of returning EFAULT.

The first guest read uses File::ReadEx, which calls fread. For a small read, fread copies into the guest buffer with memcpy. A write fault on a page the GPU resource tracker owns is recovered by KytyExceptionHandler, so the read completes. A write fault on a guest page that is neither tracked nor writable is not recovered. HandleGpuFault returns false, and the fault is reported as a host failure. Large reads take the direct kernel path and can return EFAULT, so the error behavior depends on read size.

Check that the destination is writable before the first read. If it is not writable, return EFAULT without calling fread. Keep the bounce-buffer retry for the tracked-page case.

✅ Confirmed as addressed by @⁠wuboo

**@⁠coderabbitai[bot]** on GitHub · 2026-11-17 20:55 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#discussion_r4605671896) · edited 2026-11-17 23:08 UTC <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** **Small reads into non-writable guest buffers can crash the process instead of returning `EFAULT`.** The first guest read uses `File::ReadEx`, which calls `fread`. For a small read, `fread` copies into the guest buffer with `memcpy`. A write fault on a page the GPU resource tracker owns is recovered by `KytyExceptionHandler`, so the read completes. A write fault on a guest page that is neither tracked nor writable is not recovered. `HandleGpuFault` returns false, and the fault is reported as a host failure. Large reads take the direct kernel path and can return `EFAULT`, so the error behavior depends on read size. Check that the destination is writable before the first read. If it is not writable, return `EFAULT` without calling `fread`. Keep the bounce-buffer retry for the tracked-page case. <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:112d8366b36a73d295a52307 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠wuboo <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

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

Actionable comments posted: 1

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 1974034429806872a0fbc49c9ca2834246373c31 and 475fb0d79b1b369d39426b5adeffcc81c80516b3.

Files selected for processing: 8

  • src/common/file.h
  • src/common/platform/sysFileIO.h
  • src/common/platform/sysWindowsFileIO.cpp
  • src/kernel/fileSystem.cpp
  • src/kernel/guestFileRead.h
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • tests/WinReadEfaultTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-17 20:55 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#pullrequestreview-5946465645) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 1** <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/2638b1b07613dc32a4708d2cd61a75711b84b6cf/.coderabbit.yaml>) - **Commit**: [2638b1b](<https://github.com/KytyPS5/KytyPS5/commit/2638b1b07613dc32a4708d2cd61a75711b84b6cf>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `982bfa66-a04c-417d-8d83-9e43eb742224` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 1974034429806872a0fbc49c9ca2834246373c31 and 475fb0d79b1b369d39426b5adeffcc81c80516b3. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 8</summary> <dl> <dd> <br> * `src/common/file.h` * `src/common/platform/sysFileIO.h` * `src/common/platform/sysWindowsFileIO.cpp` * `src/kernel/fileSystem.cpp` * `src/kernel/guestFileRead.h` * `src/kernel/memory.cpp` * `src/kernel/memory.h` * `tests/WinReadEfaultTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=f4519c06-15d0-474e-930f-5fc97a9da609 attempt=12e82ebe-a40f-4527-945a-116359294bbc batch=1/1 -->
@ -0,0 +38,4 @@
if (want != 0 && known_unwritable(buf, want)) {
return EFAULT;
}
f.ReadEx(buf, want, got, &err);
Author
Owner

@⁠wuboo on GitHub · 2026-11-17 21:06 UTC · original

Good catch. ReadIntoGuest now checks the destination with the same can_write callback (Memory::IsGuestWritable) before the first read; if it is not writable the call returns EFAULT with 0 bytes, without reading, and the file offset is unchanged. The pre-check covers only the part of the buffer the read can fill (the size is clamped to the bytes left in the file), so a buffer larger than the remainder of the file with an unmapped tail still succeeds. The bounce retry for tracked pages is kept, and win_read_efault covers both cases. Also rebased onto current main.

**@⁠wuboo** on GitHub · 2026-11-17 21:06 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#discussion_r4605794679) Good catch. `ReadIntoGuest` now checks the destination with the same `can_write` callback (`Memory::IsGuestWritable`) before the first read; if it is not writable the call returns `EFAULT` with 0 bytes, without reading, and the file offset is unchanged. The pre-check covers only the part of the buffer the read can fill (the size is clamped to the bytes left in the file), so a buffer larger than the remainder of the file with an unmapped tail still succeeds. The bounce retry for tracked pages is kept, and `win_read_efault` covers both cases. Also rebased onto current main.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-17 21:15 UTC · original
On tests/WinReadEfaultTests.cpp line 209 (outdated):

@@ -0,0 +1,283 @@
+// A file read into a page the GPU resource tracker has made unwritable fails in the host
+// read and must be reported as EFAULT, so the guest bounce-buffer retry can run. On Windows
+// ReadFile returns ERROR_NOACCESS; on POSIX, read(2) already returns EFAULT.
+#include "common/file.h"
+#include "common/platform/sysFileIO.h"
+#include "kernel/guestFileRead.h"
+
+#include <cerrno>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <filesystem>
+
+#if defined(_WIN32)
+#include <windows.h>
+#else
+#include <sys/mman.h>
+#include <unistd.h>
+#endif
+
+namespace {
+
+constexpr uint32_t PageSize = 4096;
+
+void Check(bool value, const char* message) {
+	if (!value) {
+		std::fprintf(stderr, "WinReadEfaultTests: failed: %s\n", message);
+		std::exit(1);
+	}
+}
+
+uint8_t Pattern(uint32_t i) {
+	return static_cast<uint8_t>(i * 7u + 3u);
+}
+
+uint8_t* AllocPage() {
+#if defined(_WIN32)
+	auto* page = static_cast<uint8_t*>(
+	    VirtualAlloc(nullptr, PageSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
+	Check(page != nullptr, "alloc page");
+#else
+	auto* page = static_cast<uint8_t*>(
+	    mmap(nullptr, PageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0));
+	Check(page != MAP_FAILED, "alloc page");
+#endif
+	return page;
+}
+
+// Stands in for the tracker: read-only on Windows, as the tracker leaves it; no access on POSIX.
+void ProtectPage(uint8_t* page, bool protect) {
+#if defined(_WIN32)
+	DWORD old = 0;
+	Check(VirtualProtect(page, PageSize, protect ? PAGE_READONLY : PAGE_READWRITE, &old) != 0,
+	      "protect page");
+#else
+	Check(mprotect(page, PageSize, protect ? PROT_NONE : (PROT_READ | PROT_WRITE)) == 0,
+	      "protect page");
+#endif
+}
+
+void FreePage(uint8_t* page) {
+#if defined(_WIN32)
+	VirtualFree(page, 0, MEM_RELEASE);
+#else
+	munmap(page, PageSize);
+#endif
+}
+
+uint8_t* g_tracked_page = nullptr;
+int      g_writable_calls = 0;
+
+// The destination is not guest memory the fault handler recovers.
+bool RejectWrite(const void* /*dst*/, uint64_t /*size*/) {
+	g_writable_calls++;
+	return false;
+}
+
+// Writable for the check before the first read, rejected for the copy after the retry.
+bool RejectCopy(const void* /*dst*/, uint64_t /*size*/) {
+	return ++g_writable_calls == 1;
+}
+
+// The destination is tracked guest memory. The check before the first read only reports it
+// writable; the copy into it takes the fault, so unprotect it there, as the fault handler would.
+bool UnprotectTracked(const void* dst, uint64_t size) {
+	g_writable_calls++;
+	Check(dst == g_tracked_page && size == PageSize, "writable check covers the read");
+	if (g_writable_calls > 1) {
+		ProtectPage(g_tracked_page, false);
+	}
+	return true;
+}
+
+// Only the first page of the destination is writable guest memory.
+bool FirstPageOnly(const void* dst, uint64_t size) {
+	g_writable_calls++;
+	return static_cast<const uint8_t*>(dst) + size <= g_tracked_page + PageSize;
+}
+
+// The destination is plain writable guest memory.
+bool AllowWrite(const void* /*dst*/, uint64_t /*size*/) {
+	g_writable_calls++;
+	return true;
+}
+
+void TestSysFileReadEx(const std::filesystem::path& path) {
+	auto* f = SysFileOpenR(path);
+	Check(f != nullptr, "open temp file");
+
+	uint8_t  writable[PageSize] {};
+	uint32_t got = 0;
+	int      err = 1;
+	SysFileReadEx(writable, sizeof(writable), *f, &got, &err);
+	Check(err == 0 && got == sizeof(writable), "read into a writable buffer succeeds");
+	Check(writable[0] == 3 && writable[1] == 10 && writable[PageSize - 1] == Pattern(PageSize - 1),
+	      "read data matches");
+
+	got = 123;
+	err = 1;
+	SysFileReadEx(writable, sizeof(writable), *f, &got, &err);
+	Check(got == 0 && err == 0, "read at end of file is not an error");
+	Check(SysFileSeek(*f, 0), "seek to start");
+
+	auto* page = AllocPage();
+	ProtectPage(page, true);
+	got = 123;
+	err = 0;
+	SysFileReadEx(page, PageSize, *f, &got, &err);
+	Check(got == 0, "read into a protected page delivers 0 bytes");
+	Check(err == EFAULT, "read into a protected page is reported as EFAULT");
+	ProtectPage(page, false);
+	FreePage(page);
+	SysFileClose(f);
+
+#if defined(_WIN32)
+	// A handle without read access fails with ERROR_ACCESS_DENIED.
+	auto* w = SysFileOpenW(path);
+	Check(w != nullptr, "open temp file for writing");
+	got = 123;
+	err = 0;
+	SysFileReadEx(writable, sizeof(writable), *w, &got, &err);
+	Check(got == 0 && err == EIO, "other read failures are reported as EIO");
+	SysFileClose(w);
+#else
+	// A directory opens for reading, but read(2) fails with EISDIR.
+	const std::filesystem::path dir = "win_read_efault.dir";
+	std::filesystem::create_directory(dir);
+	auto* d = SysFileOpenR(dir);
+	Check(d != nullptr, "open directory");
+	got = 123;
+	err = 0;
+	SysFileReadEx(writable, sizeof(writable), *d, &got, &err);
+	Check(got == 0 && err != 0 && err != EFAULT, "other read failures report their errno");
+	SysFileClose(d);
+	std::filesystem::remove(dir);
+#endif
+}
+
+void TestReadIntoGuest(const std::filesystem::path& path) {
+	using Libs::LibKernel::FileSystem::ReadIntoGuest;
+
+	Common::File f;
+	Check(f.Open(path, Common::File::Mode::Read), "open temp file");
+
+	// Short read at end of file: no error and no bounce copy.
+	static uint8_t twice[PageSize * 2];
+	uint32_t       got = 0;
+	Check(ReadIntoGuest(f, twice, sizeof(twice), 0, &got, AllowWrite) == 0 && got == PageSize,
+	      "short read at end of file returns the bytes read");
+
+	auto* page = AllocPage();
+
+	// Rejected before the first read: the page is host-writable, so a read would succeed and fill
+	// it. EFAULT without reading, touching the destination or moving the file offset.
+	Check(f.Seek(0), "seek to start");
+	g_writable_calls = 0;
+	got              = 123;
+	Check(ReadIntoGuest(f, page, PageSize, 0, &got, RejectWrite) == EFAULT,
+	      "read into a rejected destination fails with EFAULT before the first read");
+	Check(g_writable_calls == 1 && got == 0, "pre-checked destination receives no bytes");
+	Check(f.Tell() == 0, "pre-checked read leaves the file offset unchanged");
+	Check(page[0] == 0 && page[PageSize - 1] == 0, "pre-checked destination is untouched");
+
+	// Rejected for the copy after the retry: EFAULT without touching the destination or moving
+	// past delivered bytes.
+	Check(f.Seek(0), "seek to start");
+	ProtectPage(page, true);
+	g_writable_calls = 0;
+	got              = 123;
+	Check(ReadIntoGuest(f, page, PageSize, 0, &got, RejectCopy) == EFAULT,
+	      "read into a rejected destination fails with EFAULT");
+	Check(g_writable_calls == 2 && got == 0, "rejected destination receives no bytes");
+	Check(f.Tell() == 0, "file offset covers only the delivered bytes");
+	ProtectPage(page, false);
+	Check(page[0] == 0 && page[PageSize - 1] == 0, "rejected destination is unchanged");
+
+	// A guest buffer larger than what is left in the file, with only the part the file fills
+	// mapped: the caller passes the clamped size, so the read succeeds with the file's bytes.
+	{
+		uint8_t* two = nullptr;
+#if defined(_WIN32)
+		two = static_cast<uint8_t*>(
+		    VirtualAlloc(nullptr, PageSize * 2, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
+#else
+		two = static_cast<uint8_t*>(mmap(nullptr, PageSize * 2, PROT_READ | PROT_WRITE,
+		                                 MAP_PRIVATE | MAP_ANON, -1, 0));
+#endif
+		Check(two != nullptr && two != MAP_FAILED, "alloc two pages");

Major · Functional Correctness · Quick win

Keep MAP_FAILED out of the Windows branch.

On Windows, this line still references MAP_FAILED, although the Windows include path does not supply that POSIX sentinel. The platform headers expose Windows APIs, not a mapping compatibility API. This prevents win_read_efault_tests from compiling and blocks kyty_tests, which now depends on it. (raw.githubusercontent.com)

Move the allocation check into each platform branch. Check two != nullptr after VirtualAlloc and two != MAP_FAILED after mmap.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-17 21:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#discussion_r4605891636) On `tests/WinReadEfaultTests.cpp` line 209 (outdated): ```diff @@ -0,0 +1,283 @@ +// A file read into a page the GPU resource tracker has made unwritable fails in the host +// read and must be reported as EFAULT, so the guest bounce-buffer retry can run. On Windows +// ReadFile returns ERROR_NOACCESS; on POSIX, read(2) already returns EFAULT. +#include "common/file.h" +#include "common/platform/sysFileIO.h" +#include "kernel/guestFileRead.h" + +#include <cerrno> +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <filesystem> + +#if defined(_WIN32) +#include <windows.h> +#else +#include <sys/mman.h> +#include <unistd.h> +#endif + +namespace { + +constexpr uint32_t PageSize = 4096; + +void Check(bool value, const char* message) { + if (!value) { + std::fprintf(stderr, "WinReadEfaultTests: failed: %s\n", message); + std::exit(1); + } +} + +uint8_t Pattern(uint32_t i) { + return static_cast<uint8_t>(i * 7u + 3u); +} + +uint8_t* AllocPage() { +#if defined(_WIN32) + auto* page = static_cast<uint8_t*>( + VirtualAlloc(nullptr, PageSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + Check(page != nullptr, "alloc page"); +#else + auto* page = static_cast<uint8_t*>( + mmap(nullptr, PageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0)); + Check(page != MAP_FAILED, "alloc page"); +#endif + return page; +} + +// Stands in for the tracker: read-only on Windows, as the tracker leaves it; no access on POSIX. +void ProtectPage(uint8_t* page, bool protect) { +#if defined(_WIN32) + DWORD old = 0; + Check(VirtualProtect(page, PageSize, protect ? PAGE_READONLY : PAGE_READWRITE, &old) != 0, + "protect page"); +#else + Check(mprotect(page, PageSize, protect ? PROT_NONE : (PROT_READ | PROT_WRITE)) == 0, + "protect page"); +#endif +} + +void FreePage(uint8_t* page) { +#if defined(_WIN32) + VirtualFree(page, 0, MEM_RELEASE); +#else + munmap(page, PageSize); +#endif +} + +uint8_t* g_tracked_page = nullptr; +int g_writable_calls = 0; + +// The destination is not guest memory the fault handler recovers. +bool RejectWrite(const void* /*dst*/, uint64_t /*size*/) { + g_writable_calls++; + return false; +} + +// Writable for the check before the first read, rejected for the copy after the retry. +bool RejectCopy(const void* /*dst*/, uint64_t /*size*/) { + return ++g_writable_calls == 1; +} + +// The destination is tracked guest memory. The check before the first read only reports it +// writable; the copy into it takes the fault, so unprotect it there, as the fault handler would. +bool UnprotectTracked(const void* dst, uint64_t size) { + g_writable_calls++; + Check(dst == g_tracked_page && size == PageSize, "writable check covers the read"); + if (g_writable_calls > 1) { + ProtectPage(g_tracked_page, false); + } + return true; +} + +// Only the first page of the destination is writable guest memory. +bool FirstPageOnly(const void* dst, uint64_t size) { + g_writable_calls++; + return static_cast<const uint8_t*>(dst) + size <= g_tracked_page + PageSize; +} + +// The destination is plain writable guest memory. +bool AllowWrite(const void* /*dst*/, uint64_t /*size*/) { + g_writable_calls++; + return true; +} + +void TestSysFileReadEx(const std::filesystem::path& path) { + auto* f = SysFileOpenR(path); + Check(f != nullptr, "open temp file"); + + uint8_t writable[PageSize] {}; + uint32_t got = 0; + int err = 1; + SysFileReadEx(writable, sizeof(writable), *f, &got, &err); + Check(err == 0 && got == sizeof(writable), "read into a writable buffer succeeds"); + Check(writable[0] == 3 && writable[1] == 10 && writable[PageSize - 1] == Pattern(PageSize - 1), + "read data matches"); + + got = 123; + err = 1; + SysFileReadEx(writable, sizeof(writable), *f, &got, &err); + Check(got == 0 && err == 0, "read at end of file is not an error"); + Check(SysFileSeek(*f, 0), "seek to start"); + + auto* page = AllocPage(); + ProtectPage(page, true); + got = 123; + err = 0; + SysFileReadEx(page, PageSize, *f, &got, &err); + Check(got == 0, "read into a protected page delivers 0 bytes"); + Check(err == EFAULT, "read into a protected page is reported as EFAULT"); + ProtectPage(page, false); + FreePage(page); + SysFileClose(f); + +#if defined(_WIN32) + // A handle without read access fails with ERROR_ACCESS_DENIED. + auto* w = SysFileOpenW(path); + Check(w != nullptr, "open temp file for writing"); + got = 123; + err = 0; + SysFileReadEx(writable, sizeof(writable), *w, &got, &err); + Check(got == 0 && err == EIO, "other read failures are reported as EIO"); + SysFileClose(w); +#else + // A directory opens for reading, but read(2) fails with EISDIR. + const std::filesystem::path dir = "win_read_efault.dir"; + std::filesystem::create_directory(dir); + auto* d = SysFileOpenR(dir); + Check(d != nullptr, "open directory"); + got = 123; + err = 0; + SysFileReadEx(writable, sizeof(writable), *d, &got, &err); + Check(got == 0 && err != 0 && err != EFAULT, "other read failures report their errno"); + SysFileClose(d); + std::filesystem::remove(dir); +#endif +} + +void TestReadIntoGuest(const std::filesystem::path& path) { + using Libs::LibKernel::FileSystem::ReadIntoGuest; + + Common::File f; + Check(f.Open(path, Common::File::Mode::Read), "open temp file"); + + // Short read at end of file: no error and no bounce copy. + static uint8_t twice[PageSize * 2]; + uint32_t got = 0; + Check(ReadIntoGuest(f, twice, sizeof(twice), 0, &got, AllowWrite) == 0 && got == PageSize, + "short read at end of file returns the bytes read"); + + auto* page = AllocPage(); + + // Rejected before the first read: the page is host-writable, so a read would succeed and fill + // it. EFAULT without reading, touching the destination or moving the file offset. + Check(f.Seek(0), "seek to start"); + g_writable_calls = 0; + got = 123; + Check(ReadIntoGuest(f, page, PageSize, 0, &got, RejectWrite) == EFAULT, + "read into a rejected destination fails with EFAULT before the first read"); + Check(g_writable_calls == 1 && got == 0, "pre-checked destination receives no bytes"); + Check(f.Tell() == 0, "pre-checked read leaves the file offset unchanged"); + Check(page[0] == 0 && page[PageSize - 1] == 0, "pre-checked destination is untouched"); + + // Rejected for the copy after the retry: EFAULT without touching the destination or moving + // past delivered bytes. + Check(f.Seek(0), "seek to start"); + ProtectPage(page, true); + g_writable_calls = 0; + got = 123; + Check(ReadIntoGuest(f, page, PageSize, 0, &got, RejectCopy) == EFAULT, + "read into a rejected destination fails with EFAULT"); + Check(g_writable_calls == 2 && got == 0, "rejected destination receives no bytes"); + Check(f.Tell() == 0, "file offset covers only the delivered bytes"); + ProtectPage(page, false); + Check(page[0] == 0 && page[PageSize - 1] == 0, "rejected destination is unchanged"); + + // A guest buffer larger than what is left in the file, with only the part the file fills + // mapped: the caller passes the clamped size, so the read succeeds with the file's bytes. + { + uint8_t* two = nullptr; +#if defined(_WIN32) + two = static_cast<uint8_t*>( + VirtualAlloc(nullptr, PageSize * 2, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); +#else + two = static_cast<uint8_t*>(mmap(nullptr, PageSize * 2, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANON, -1, 0)); +#endif + Check(two != nullptr && two != MAP_FAILED, "alloc two pages"); ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Quick win** **Keep `MAP_FAILED` out of the Windows branch.** On Windows, this line still references `MAP_FAILED`, although the Windows include path does not supply that POSIX sentinel. The platform headers expose Windows APIs, not a mapping compatibility API. This prevents `win_read_efault_tests` from compiling and blocks `kyty_tests`, which now depends on it. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/23ddcf51ffb03b00ff0a998849d7cf1565924b86/src/common/platform/sysFileIO.h)) Move the allocation check into each platform branch. Check `two != nullptr` after `VirtualAlloc` and `two != MAP_FAILED` after `mmap`. <!-- fingerprinting:phantom:poseidon:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:6e791db853e2965708ff35ac --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

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

Actionable comments posted: 1

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 475fb0d79b1b369d39426b5adeffcc81c80516b3 and 23ddcf51ffb03b00ff0a998849d7cf1565924b86.

Files selected for processing: 4

  • CMakeLists.txt
  • src/kernel/fileSystem.cpp
  • src/kernel/guestFileRead.h
  • tests/WinReadEfaultTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-17 21:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#pullrequestreview-5946748495) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 1** <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/2638b1b07613dc32a4708d2cd61a75711b84b6cf/.coderabbit.yaml>) - **Commit**: [2638b1b](<https://github.com/KytyPS5/KytyPS5/commit/2638b1b07613dc32a4708d2cd61a75711b84b6cf>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `488e1d1d-a6a1-41ff-9e64-fd3f235934e5` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 475fb0d79b1b369d39426b5adeffcc81c80516b3 and 23ddcf51ffb03b00ff0a998849d7cf1565924b86. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 4</summary> <dl> <dd> <br> * `CMakeLists.txt` * `src/kernel/fileSystem.cpp` * `src/kernel/guestFileRead.h` * `tests/WinReadEfaultTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=6b1982ee-ac73-40a8-b5b0-6f56e1b205d2 attempt=793236b1-2de0-44f6-adde-03fa0aa62390 batch=1/1 -->
@ -0,0 +38,4 @@
if (want != 0 && known_unwritable(buf, want)) {
return EFAULT;
}
f.ReadEx(buf, want, got, &err);
Author
Owner

@⁠wuboo on GitHub · 2026-11-17 22:52 UTC · original

Follow-up: the writable-destination check before the first read was too strict. It required committed, CPU-writable guest memory, so it rejected valid destinations that the guest map does not describe. The AvPlayer file reader passes a host buffer (FFmpeg's AVIO buffer) to the guest's readOffset callback, and the guest reads into it with sceKernelPread. The read got EFAULT and ASTRO BOT asserted during the PS logo video on current main. Memory mapped with GPU write access only, which the host maps read-write, was rejected too.

There are now two checks. Before the first host read, Memory::IsKnownUnwritable rejects only a range the map describes as reserved or as mapped without CPU or GPU write access, where a host store would fault and nothing would recover it. Program images are exempt, because they stay host-writable whatever their guest protection. Memory outside the map is read into as before. Before each bounce copy, after the host read has already failed with EFAULT, the destination must still be committed guest memory with write access (IsGuestWritable). The only fault there that can be recovered is a tracked page, so anything else, including memory outside the map, fails with EFAULT instead of faulting in host code. Both cases are covered in win_read_efault and in a new GuestReadDestinationChecks case in virtual_memory_allocation, and the game now gets past the PS logo, the world map and loads the first planet on current main.

**@⁠wuboo** on GitHub · 2026-11-17 22:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#discussion_r4606881820) Follow-up: the writable-destination check before the first read was too strict. It required committed, CPU-writable guest memory, so it rejected valid destinations that the guest map does not describe. The AvPlayer file reader passes a host buffer (FFmpeg's AVIO buffer) to the guest's `readOffset` callback, and the guest reads into it with `sceKernelPread`. The read got `EFAULT` and ASTRO BOT asserted during the PS logo video on current `main`. Memory mapped with GPU write access only, which the host maps read-write, was rejected too. There are now two checks. Before the first host read, `Memory::IsKnownUnwritable` rejects only a range the map describes as reserved or as mapped without CPU or GPU write access, where a host store would fault and nothing would recover it. Program images are exempt, because they stay host-writable whatever their guest protection. Memory outside the map is read into as before. Before each bounce copy, after the host read has already failed with `EFAULT`, the destination must still be committed guest memory with write access (`IsGuestWritable`). The only fault there that can be recovered is a tracked page, so anything else, including memory outside the map, fails with `EFAULT` instead of faulting in host code. Both cases are covered in `win_read_efault` and in a new `GuestReadDestinationChecks` case in `virtual_memory_allocation`, and the game now gets past the PS logo, the world map and loads the first planet on current `main`.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-17 23:03 UTC · original · edited 2026-11-18 00:27 UTC
On src/kernel/memory.cpp line 879 (outdated):

@@ -855,6 +855,41 @@ void InvalidateMemory(uint64_t vaddr, uint64_t size) {
 	(void)GetGpuResources().InvalidateMemory(vaddr, size);
 }
 
+// The host mapping of a committed range is writable when the guest may write it from the CPU or
+// the GPU (DecodeMemoryProtection).
+static bool HasHostWriteAccess(const VirtualRanges::Range& range) {
+	return IsCommittedRangeType(range.type) &&
+	       (range.protection & (PROT_CPU_WRITE | PROT_GPU_WRITE)) != 0;
+}
+
+bool IsKnownUnwritable(uint64_t vaddr, uint64_t size) {
+	if (size == 0 || size > UINT64_MAX - vaddr) {
+		return size != 0;
+	}
+	std::vector<VirtualRanges::Range> ranges;
+	std::shared_lock                  state(g_memory_state_mutex);
+	if (g_virtual_ranges == nullptr) {
+		return false;
+	}
+	// Holes are skipped: memory the map does not describe, such as a host buffer that HLE code
+	// hands to a guest callback, is not known to fail. Program images stay host-writable whatever
+	// their guest protection (SetProgramMemoryProtection), so their protection says nothing either.
+	g_virtual_ranges->QueryFragments(vaddr, size, &ranges);
+	return std::any_of(ranges.begin(), ranges.end(), [](const auto& range) {
+		return range.type != VirtualRangeType::Code && !HasHostWriteAccess(range);

Major · Stability & Availability · Quick win

Treat host-read-only Code pages as known unwritable.

The Code exemption at src/kernel/memory.cpp:879 makes IsKnownUnwritable return false for a Code fragment, even when its host protection lacks write access. ProtectGuestMemory and ProtectMemory can make such pages host read-only. For a read into one of those pages, ReadIntoGuest calls ReadEx directly, as its own comment describes. The stdio read then copies into the page in user space. That write can fault in the host and can end the emulator. The header comment expects this case to fail with EFAULT before the store.

Remove the blanket Code exemption, or narrow it so that a Code range without host write access is reported as known unwritable. Program images that SetProgramMemoryProtection leaves host-writable must still read normally. The comment at src/kernel/memory.cpp:876-877, which says program images stay host-writable regardless of guest protection, must be updated with this change.

✅ Confirmed as addressed by @⁠wuboo

**@⁠coderabbitai[bot]** on GitHub · 2026-11-17 23:03 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#discussion_r4606982291) · edited 2026-11-18 00:27 UTC On `src/kernel/memory.cpp` line 879 (outdated): ```diff @@ -855,6 +855,41 @@ void InvalidateMemory(uint64_t vaddr, uint64_t size) { (void)GetGpuResources().InvalidateMemory(vaddr, size); } +// The host mapping of a committed range is writable when the guest may write it from the CPU or +// the GPU (DecodeMemoryProtection). +static bool HasHostWriteAccess(const VirtualRanges::Range& range) { + return IsCommittedRangeType(range.type) && + (range.protection & (PROT_CPU_WRITE | PROT_GPU_WRITE)) != 0; +} + +bool IsKnownUnwritable(uint64_t vaddr, uint64_t size) { + if (size == 0 || size > UINT64_MAX - vaddr) { + return size != 0; + } + std::vector<VirtualRanges::Range> ranges; + std::shared_lock state(g_memory_state_mutex); + if (g_virtual_ranges == nullptr) { + return false; + } + // Holes are skipped: memory the map does not describe, such as a host buffer that HLE code + // hands to a guest callback, is not known to fail. Program images stay host-writable whatever + // their guest protection (SetProgramMemoryProtection), so their protection says nothing either. + g_virtual_ranges->QueryFragments(vaddr, size, &ranges); + return std::any_of(ranges.begin(), ranges.end(), [](const auto& range) { + return range.type != VirtualRangeType::Code && !HasHostWriteAccess(range); ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Treat host-read-only `Code` pages as known unwritable.** The `Code` exemption at `src/kernel/memory.cpp:879` makes `IsKnownUnwritable` return false for a `Code` fragment, even when its host protection lacks write access. `ProtectGuestMemory` and `ProtectMemory` can make such pages host read-only. For a read into one of those pages, `ReadIntoGuest` calls `ReadEx` directly, as its own comment describes. The stdio read then copies into the page in user space. That write can fault in the host and can end the emulator. The header comment expects this case to fail with `EFAULT` before the store. Remove the blanket `Code` exemption, or narrow it so that a `Code` range without host write access is reported as known unwritable. Program images that `SetProgramMemoryProtection` leaves host-writable must still read normally. The comment at `src/kernel/memory.cpp:876-877`, which says program images stay host-writable regardless of guest protection, must be updated with this change. <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:c611e3e05e1eb5656785277c --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠wuboo <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

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

Actionable comments posted: 1

Nitpick comments: 1

tests/WinReadEfaultTests.cpp: 1

272-272: Trivial · Maintainability & Code Quality · Quick win

Cover multi-chunk recovery and failure after partial progress.

The fixture contains only 4096 bytes. This call never crosses the 1 MiB retry boundary, and UnprotectTracked requires one page.

Add cases with a nonzero direct-read prefix and more than one bounce chunk. Include a rejected later chunk. Assert the complete delivered prefix, untouched rejected bytes, got, and final file position. These cases protect the retry loop's address and offset accounting.

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 23ddcf51ffb03b00ff0a998849d7cf1565924b86 and 8af35ad150c26b4fe22d99d4b812200e53a9cce6.

Files selected for processing: 6

  • src/kernel/fileSystem.cpp
  • src/kernel/guestFileRead.h
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • tests/VirtualMemoryAllocationTests.cpp
  • tests/WinReadEfaultTests.cpp

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-11-17 23:03 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#pullrequestreview-5948099699) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 1** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning.svg" width="16" height="16" align="absmiddle" alt=""></picture> Nitpick comments: 1</summary><blockquote> <dl> <dd> <br> <details> <summary>tests/WinReadEfaultTests.cpp: 1</summary><blockquote> <dl> <dd> <br> `272-272`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Maintainability & Code Quality** · **Quick win** **Cover multi-chunk recovery and failure after partial progress.** The fixture contains only 4096 bytes. This call never crosses the 1 MiB retry boundary, and `UnprotectTracked` requires one page. Add cases with a nonzero direct-read prefix and more than one bounce chunk. Include a rejected later chunk. Assert the complete delivered prefix, untouched rejected bytes, `got`, and final file position. These cases protect the retry loop's address and offset accounting. <!-- cr-comment:v1:1c2c5d95c7b3e331c00f2d27 --> </dd> </dl> </blockquote></details> </dd> </dl> </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/2638b1b07613dc32a4708d2cd61a75711b84b6cf/.coderabbit.yaml>) - **Commit**: [2638b1b](<https://github.com/KytyPS5/KytyPS5/commit/2638b1b07613dc32a4708d2cd61a75711b84b6cf>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `f53b9b89-e710-4376-8d52-c85fe6268336` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 23ddcf51ffb03b00ff0a998849d7cf1565924b86 and 8af35ad150c26b4fe22d99d4b812200e53a9cce6. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 6</summary> <dl> <dd> <br> * `src/kernel/fileSystem.cpp` * `src/kernel/guestFileRead.h` * `src/kernel/memory.cpp` * `src/kernel/memory.h` * `tests/VirtualMemoryAllocationTests.cpp` * `tests/WinReadEfaultTests.cpp` </dd> </dl> </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. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=6874a501-57e3-418f-86ae-f5356e5687fa attempt=fa938bdb-a5d8-4c40-8d12-63c7d5f46bae batch=1/1 -->
@ -0,0 +38,4 @@
if (want != 0 && known_unwritable(buf, want)) {
return EFAULT;
}
f.ReadEx(buf, want, got, &err);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-17 23:10 UTC · original

Analysis chain

Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- Revision and repository instructions ---'
git rev-parse HEAD
for f in AGENTS.md src/AGENTS.md src/kernel/AGENTS.md tests/AGENTS.md; do
  if [ -f "$f" ]; then printf '\n--- %s ---\n' "$f"; cat "$f"; fi
done
printf '\n%s\n' '--- Source outlines ---'
for f in src/kernel/guestFileRead.h src/kernel/fileSystem.cpp src/kernel/memory.cpp tests/WinReadEfaultTests.cpp tests/VirtualMemoryAllocationTests.cpp; do
  printf '\n--- %s ---\n' "$f"
  ast-grep outline "$f" --items all --match 'ReadIntoGuest|KernelRead|KernelPread|IsKnownUnwritable|IsGuestWritable|GuestReadDestination|Efault|EFAULT|Fault' 2>&1 | head -100
done
printf '\n%s\n' '--- Current helper ---'
cat -n src/kernel/guestFileRead.h | sed -n '1,140p'
printf '\n%s\n' '--- Predicate and usage locations ---'
rg -n -C 8 'IsKnownUnwritable\s*\(|IsGuestWritable\s*\(|ReadIntoGuest\s*\(' src/kernel/memory.cpp src/kernel/fileSystem.cpp tests/WinReadEfaultTests.cpp tests/VirtualMemoryAllocationTests.cpp
printf '\n%s\n' '--- AvPlayer callback and host buffer evidence ---'
rg -n -C 4 'readOffset|avio_alloc_context|avio_buffer|AVIOContext' src | head -220

Length of output: 27712


Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- Platform read and file buffering ---'
ast-grep outline src/common/platform/sysLinuxFileIO.cpp --items all --match 'SysFileOpen|SysFileRead|SysFileReadEx'
rg -n -C 8 'setvbuf|setbuf|fread\s*\(|SysFileReadEx\s*\(|SysFileOpen\s*\(' src/common/platform/sysLinuxFileIO.cpp src/common/file.cpp
printf '\n%s\n' '--- Memory range and unmap implementation ---'
ast-grep outline src/kernel/memory.cpp --items all --match 'KernelMunmap|Munmap|QueryFragments|SetProgramMemoryProtection'
rg -n -C 6 'QueryFragments\s*\(|KernelMunmap\s*\(|SetProgramMemoryProtection\s*\(' src/kernel/memory.cpp
printf '\n%s\n' '--- AvPlayer callback ---'
cat -n src/libs/avPlayer.cpp | sed -n '580,670p'
printf '\n%s\n' '--- Test platform setup ---'
cat -n tests/WinReadEfaultTests.cpp | sed -n '1,164p'
printf '\n%s\n' '--- Exception handler and fault handling ---'
rg -n -C 5 'KytyExceptionHandler|HandleGpuFault\s*\(' src

Length of output: 24404


web_search executed:

Find Apple macOS Libc source for fread and unbuffered FILE streams setvbuf _IONBF. For a small fread request into an invalid destination, can libc read into an internal one-byte buffer and copy to the destination in userspace rather than passing the destination directly to read(2)? Cite the source and explain the relevant conditions.

Length of output: 13492


Script executed:

#!/bin/bash
set -eu
curl -fsSL --max-time 20 https://raw.githubusercontent.com/apple-oss-distributions/Libc/main/stdio/FreeBSD/fread.c | nl -ba | sed -n '35,210p'

Length of output: 4538


Script executed:

#!/bin/bash
set -eu
curl -fsSL --max-time 20 https://raw.githubusercontent.com/apple-oss-distributions/Libc/main/stdio/FreeBSD/refill.c | nl -ba | sed -n '45,210p'

Length of output: 3434


@wuboo Thanks for clarifying why the first check must allow host buffers.

One case still needs verification. IsKnownUnwritable skips guest-map holes. In Apple’s current fread source, a one-byte unbuffered read can copy from an internal buffer into the destination in userspace. If the destination is an unmapped hole and the file has data, that copy may fault instead of returning EFAULT.

Please check a one-byte sceKernelPread into a guest-map hole on macOS, while preserving support for the AvPlayer host buffer. The existing fault tests use page-sized reads. I have not run this case on macOS, so I am not marking the finding as addressed.


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

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-17 23:10 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#discussion_r4607041868) <!-- coderabbit-ai-generated:v1 --> <details> <summary>Analysis chain</summary> <dl> <dd> <br> Script executed: ```shell #!/bin/bash set -u printf '%s\n' '--- Revision and repository instructions ---' git rev-parse HEAD for f in AGENTS.md src/AGENTS.md src/kernel/AGENTS.md tests/AGENTS.md; do if [ -f "$f" ]; then printf '\n--- %s ---\n' "$f"; cat "$f"; fi done printf '\n%s\n' '--- Source outlines ---' for f in src/kernel/guestFileRead.h src/kernel/fileSystem.cpp src/kernel/memory.cpp tests/WinReadEfaultTests.cpp tests/VirtualMemoryAllocationTests.cpp; do printf '\n--- %s ---\n' "$f" ast-grep outline "$f" --items all --match 'ReadIntoGuest|KernelRead|KernelPread|IsKnownUnwritable|IsGuestWritable|GuestReadDestination|Efault|EFAULT|Fault' 2>&1 | head -100 done printf '\n%s\n' '--- Current helper ---' cat -n src/kernel/guestFileRead.h | sed -n '1,140p' printf '\n%s\n' '--- Predicate and usage locations ---' rg -n -C 8 'IsKnownUnwritable\s*\(|IsGuestWritable\s*\(|ReadIntoGuest\s*\(' src/kernel/memory.cpp src/kernel/fileSystem.cpp tests/WinReadEfaultTests.cpp tests/VirtualMemoryAllocationTests.cpp printf '\n%s\n' '--- AvPlayer callback and host buffer evidence ---' rg -n -C 4 'readOffset|avio_alloc_context|avio_buffer|AVIOContext' src | head -220 ``` Length of output: 27712 --- Script executed: ```shell #!/bin/bash set -u printf '%s\n' '--- Platform read and file buffering ---' ast-grep outline src/common/platform/sysLinuxFileIO.cpp --items all --match 'SysFileOpen|SysFileRead|SysFileReadEx' rg -n -C 8 'setvbuf|setbuf|fread\s*\(|SysFileReadEx\s*\(|SysFileOpen\s*\(' src/common/platform/sysLinuxFileIO.cpp src/common/file.cpp printf '\n%s\n' '--- Memory range and unmap implementation ---' ast-grep outline src/kernel/memory.cpp --items all --match 'KernelMunmap|Munmap|QueryFragments|SetProgramMemoryProtection' rg -n -C 6 'QueryFragments\s*\(|KernelMunmap\s*\(|SetProgramMemoryProtection\s*\(' src/kernel/memory.cpp printf '\n%s\n' '--- AvPlayer callback ---' cat -n src/libs/avPlayer.cpp | sed -n '580,670p' printf '\n%s\n' '--- Test platform setup ---' cat -n tests/WinReadEfaultTests.cpp | sed -n '1,164p' printf '\n%s\n' '--- Exception handler and fault handling ---' rg -n -C 5 'KytyExceptionHandler|HandleGpuFault\s*\(' src ``` Length of output: 24404 --- web_search executed: `Find Apple macOS Libc source for fread and unbuffered FILE streams setvbuf _IONBF. For a small fread request into an invalid destination, can libc read into an internal one-byte buffer and copy to the destination in userspace rather than passing the destination directly to read(2)? Cite the source and explain the relevant conditions.` Length of output: 13492 --- Script executed: ```shell #!/bin/bash set -eu curl -fsSL --max-time 20 https://raw.githubusercontent.com/apple-oss-distributions/Libc/main/stdio/FreeBSD/fread.c | nl -ba | sed -n '35,210p' ``` Length of output: 4538 --- Script executed: ```shell #!/bin/bash set -eu curl -fsSL --max-time 20 https://raw.githubusercontent.com/apple-oss-distributions/Libc/main/stdio/FreeBSD/refill.c | nl -ba | sed -n '45,210p' ``` Length of output: 3434 --- </dd> </dl> </details> `@wuboo` Thanks for clarifying why the first check must allow host buffers. One case still needs verification. `IsKnownUnwritable` skips guest-map holes. In Apple’s [current `fread` source](https://github.com/apple-oss-distributions/Libc/blob/main/stdio/FreeBSD/fread.c), a one-byte unbuffered read can copy from an internal buffer into the destination in userspace. If the destination is an unmapped hole and the file has data, that copy may fault instead of returning `EFAULT`. Please check a one-byte `sceKernelPread` into a guest-map hole on macOS, while preserving support for the AvPlayer host buffer. The existing fault tests use page-sized reads. I have not run this case on macOS, so I am not marking the finding as addressed. --- > 📝 Learnings were not changed: only organization members or users with write access to this repository can add or remove learnings. <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠wuboo on GitHub · 2026-11-18 00:17 UTC · original
On src/kernel/memory.cpp line 879 (outdated):

@@ -855,6 +855,41 @@ void InvalidateMemory(uint64_t vaddr, uint64_t size) {
 	(void)GetGpuResources().InvalidateMemory(vaddr, size);
 }
 
+// The host mapping of a committed range is writable when the guest may write it from the CPU or
+// the GPU (DecodeMemoryProtection).
+static bool HasHostWriteAccess(const VirtualRanges::Range& range) {
+	return IsCommittedRangeType(range.type) &&
+	       (range.protection & (PROT_CPU_WRITE | PROT_GPU_WRITE)) != 0;
+}
+
+bool IsKnownUnwritable(uint64_t vaddr, uint64_t size) {
+	if (size == 0 || size > UINT64_MAX - vaddr) {
+		return size != 0;
+	}
+	std::vector<VirtualRanges::Range> ranges;
+	std::shared_lock                  state(g_memory_state_mutex);
+	if (g_virtual_ranges == nullptr) {
+		return false;
+	}
+	// Holes are skipped: memory the map does not describe, such as a host buffer that HLE code
+	// hands to a guest callback, is not known to fail. Program images stay host-writable whatever
+	// their guest protection (SetProgramMemoryProtection), so their protection says nothing either.
+	g_virtual_ranges->QueryFragments(vaddr, size, &ranges);
+	return std::any_of(ranges.begin(), ranges.end(), [](const auto& range) {
+		return range.type != VirtualRangeType::Code && !HasHostWriteAccess(range);

Good catch, thanks. The map only stores the guest protection, and for program memory that does not tell us the host protection: SetProgramMemoryProtection always keeps the host mapping read-write, while ProtectGuestMemory and mprotect give it the host protection of the guest one, so a Code page can end up host read-only. I removed the blanket Code exception. A range now records whether SetProgramMemoryProtection left it host-writable, and any other protection change clears that. IsKnownUnwritable rejects a range only when it is not flagged host-writable and has no CPU/GPU write access. Program images that SetProgramMemoryProtection leaves host-writable still read normally; a Code page made read-only on the host now fails with EFAULT like any other read-only memory. GuestReadDestinationChecks covers ProtectGuestMemory(Read), re-applying SetProgramMemoryProtection, and mprotect on program memory, and fails when the exception is restored. Still a single commit on current main; tested on Windows (unit tests, and the game through the world map to loading the first planet).

**@⁠wuboo** on GitHub · 2026-11-18 00:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#discussion_r4607573350) On `src/kernel/memory.cpp` line 879 (outdated): ```diff @@ -855,6 +855,41 @@ void InvalidateMemory(uint64_t vaddr, uint64_t size) { (void)GetGpuResources().InvalidateMemory(vaddr, size); } +// The host mapping of a committed range is writable when the guest may write it from the CPU or +// the GPU (DecodeMemoryProtection). +static bool HasHostWriteAccess(const VirtualRanges::Range& range) { + return IsCommittedRangeType(range.type) && + (range.protection & (PROT_CPU_WRITE | PROT_GPU_WRITE)) != 0; +} + +bool IsKnownUnwritable(uint64_t vaddr, uint64_t size) { + if (size == 0 || size > UINT64_MAX - vaddr) { + return size != 0; + } + std::vector<VirtualRanges::Range> ranges; + std::shared_lock state(g_memory_state_mutex); + if (g_virtual_ranges == nullptr) { + return false; + } + // Holes are skipped: memory the map does not describe, such as a host buffer that HLE code + // hands to a guest callback, is not known to fail. Program images stay host-writable whatever + // their guest protection (SetProgramMemoryProtection), so their protection says nothing either. + g_virtual_ranges->QueryFragments(vaddr, size, &ranges); + return std::any_of(ranges.begin(), ranges.end(), [](const auto& range) { + return range.type != VirtualRangeType::Code && !HasHostWriteAccess(range); ``` Good catch, thanks. The map only stores the guest protection, and for program memory that does not tell us the host protection: `SetProgramMemoryProtection` always keeps the host mapping read-write, while `ProtectGuestMemory` and `mprotect` give it the host protection of the guest one, so a Code page can end up host read-only. I removed the blanket `Code` exception. A range now records whether `SetProgramMemoryProtection` left it host-writable, and any other protection change clears that. `IsKnownUnwritable` rejects a range only when it is not flagged host-writable and has no CPU/GPU write access. Program images that `SetProgramMemoryProtection` leaves host-writable still read normally; a Code page made read-only on the host now fails with `EFAULT` like any other read-only memory. `GuestReadDestinationChecks` covers `ProtectGuestMemory(Read)`, re-applying `SetProgramMemoryProtection`, and `mprotect` on program memory, and fails when the exception is restored. Still a single commit on current main; tested on Windows (unit tests, and the game through the world map to loading the first planet).
@ -0,0 +38,4 @@
if (want != 0 && known_unwritable(buf, want)) {
return EFAULT;
}
f.ReadEx(buf, want, got, &err);
Author
Owner

@⁠wuboo on GitHub · 2026-11-18 00:17 UTC · original

This is not something the change makes worse. Before this PR, read/pread/preadv called fread/ReadFile straight into the guest buffer with no check, so a read into an address the guest map does not describe hit the same host store (and the same crash risk, including the one-byte unbuffered fread case on macOS) as it does now. The new check only rejects destinations the map describes as reserved or without write access. Holes are deliberately passed through, because the AvPlayer FileStreamer hands the guest's readOffset callback a host buffer that is not in the map, and rejecting that broke the PS logo video. Turning holes into EFAULT would require the map to know about such HLE buffers, so I left that out of this PR; the behaviour for unmapped memory is unchanged from main.

**@⁠wuboo** on GitHub · 2026-11-18 00:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#discussion_r4607573648) This is not something the change makes worse. Before this PR, `read`/`pread`/`preadv` called `fread`/`ReadFile` straight into the guest buffer with no check, so a read into an address the guest map does not describe hit the same host store (and the same crash risk, including the one-byte unbuffered `fread` case on macOS) as it does now. The new check only rejects destinations the map describes as reserved or without write access. Holes are deliberately passed through, because the AvPlayer `FileStreamer` hands the guest's `readOffset` callback a host buffer that is not in the map, and rejecting that broke the PS logo video. Turning holes into `EFAULT` would require the map to know about such HLE buffers, so I left that out of this PR; the behaviour for unmapped memory is unchanged from main.
@ -876,0 +913,4 @@
std::vector<VirtualRanges::Range> ranges;
std::shared_lock state(g_memory_state_mutex);
return g_virtual_ranges != nullptr && g_virtual_ranges->QuerySpan(vaddr, size, &ranges) &&
std::all_of(ranges.begin(), ranges.end(), HasHostWriteAccess);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-18 00:24 UTC · original · edited 2026-11-18 02:38 UTC

Minor · Stability & Availability · Heavy lift

The bounce-copy store can fault after the destination check passes.

IsGuestWritable releases g_memory_state_mutex when it returns. ReadFileIntoGuest takes no memory-operation lock, and g_memory_operation_mutex is private to memory.cpp. A concurrent KernelMunmap or KernelMprotect can therefore change the destination between the check at src/kernel/guestFileRead.h:68 and the memcpy at line 72. A store to an unmapped or read-only page that the tracker does not recover ends the emulator. A direct read into the same buffer returned EFAULT before this path existed.

Keep the destination writable until the copy completes, or make the copy tolerate a fault that the tracker does not recover. Choosing between these options is a design decision. Holding g_memory_operation_mutex across each 1 MiB bounce chunk would also block other memory operations during file I/O.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-18 00:24 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#discussion_r4607627329) · edited 2026-11-18 02:38 UTC <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Heavy lift** **The bounce-copy store can fault after the destination check passes.** `IsGuestWritable` releases `g_memory_state_mutex` when it returns. `ReadFileIntoGuest` takes no memory-operation lock, and `g_memory_operation_mutex` is private to `memory.cpp`. A concurrent `KernelMunmap` or `KernelMprotect` can therefore change the destination between the check at `src/kernel/guestFileRead.h:68` and the `memcpy` at line 72. A store to an unmapped or read-only page that the tracker does not recover ends the emulator. A direct read into the same buffer returned `EFAULT` before this path existed. Keep the destination writable until the copy completes, or make the copy tolerate a fault that the tracker does not recover. Choosing between these options is a design decision. Holding `g_memory_operation_mutex` across each 1 MiB bounce chunk would also block other memory operations during file I/O. <!-- coderabbit-global-learning v1 gid=a675e3ef26822eb9 scope=practice --> <!-- fingerprinting:phantom:poseidon:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:890d2db5f054f3cc2ad9376a --> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-18 00:24 UTC · original · reviewed

Actionable comments posted: 1

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 8af35ad150c26b4fe22d99d4b812200e53a9cce6 and 1e7af94ced06dc41e8a9083b5356be5906c913cd.

Files selected for processing: 3

  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • tests/VirtualMemoryAllocationTests.cpp

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-11-18 00:24 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#pullrequestreview-5948909779) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 1** <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/2638b1b07613dc32a4708d2cd61a75711b84b6cf/.coderabbit.yaml>) - **Commit**: [2638b1b](<https://github.com/KytyPS5/KytyPS5/commit/2638b1b07613dc32a4708d2cd61a75711b84b6cf>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `8cdb06e3-9c43-4e2a-8b28-261533ddae60` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 8af35ad150c26b4fe22d99d4b812200e53a9cce6 and 1e7af94ced06dc41e8a9083b5356be5906c913cd. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 3</summary> <dl> <dd> <br> * `src/kernel/memory.cpp` * `src/kernel/memory.h` * `tests/VirtualMemoryAllocationTests.cpp` </dd> </dl> </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. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=09a14ea5-6ff7-47be-b9f5-49a2a18b76a0 attempt=35ab18b9-51bb-480a-841e-8b65e62478e6 batch=1/1 -->
@ -0,0 +38,4 @@
if (want != 0 && known_unwritable(buf, want)) {
return EFAULT;
}
f.ReadEx(buf, want, got, &err);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-18 00:27 UTC · original

Analysis chain

Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- Revision and instructions ---'
git rev-parse HEAD
for f in AGENTS.md src/AGENTS.md src/kernel/AGENTS.md src/libs/AGENTS.md; do
  if [ -f "$f" ]; then printf '\n--- %s ---\n' "$f"; cat "$f"; fi
done
printf '\n%s\n' '--- Base revision ---'
base=$(git merge-base HEAD origin/main 2>/dev/null || true)
if [ -z "$base" ]; then base=$(git rev-parse origin/main 2>/dev/null || true); fi
printf 'base=%s\n' "$base"
printf '\n%s\n' '--- Current code outlines ---'
for f in src/kernel/guestFileRead.h src/kernel/fileSystem.cpp src/kernel/memory.cpp src/libs/avPlayer.cpp src/common/file.cpp src/common/platform/sysLinuxFileIO.cpp; do
  if [ -f "$f" ]; then
    printf '\n--- %s ---\n' "$f"
    ast-grep outline "$f" --items all --match 'ReadIntoGuest|KernelRead|KernelPread|IsKnownUnwritable|IsGuestWritable|FileStreamer|ReadEx|SysFileRead' 2>&1 | head -100
  fi
done
printf '\n%s\n' '--- Current relevant source ---'
cat -n src/kernel/guestFileRead.h | sed -n '1,115p'
rg -n -C 6 'IsKnownUnwritable\s*\(|IsGuestWritable\s*\(|ReadIntoGuest\s*\(' src/kernel/fileSystem.cpp src/kernel/memory.cpp
rg -n -C 6 'readOffset|avio_alloc_context|avio_buffer' src/libs/avPlayer.cpp
rg -n -C 5 'SysFileReadEx\s*\(|SysFileRead\s*\(|fread\s*\(|setvbuf\s*\(' src/common/platform/sysLinuxFileIO.cpp
printf '\n%s\n' '--- Base read implementation ---'
if [ -n "$base" ]; then
  tmp=$(mktemp -d)
  for f in src/kernel/fileSystem.cpp src/common/file.cpp src/common/platform/sysLinuxFileIO.cpp; do
    name=$(basename "$f")
    if git show "$base:$f" > "$tmp/$name" 2>/dev/null; then
      printf '\n--- base %s ---\n' "$f"
      ast-grep outline "$tmp/$name" --items all --match 'KernelRead|KernelPread|Read|SysFileRead' 2>&1 | head -80
      case "$f" in
        src/kernel/fileSystem.cpp) rg -n -C 12 'KernelRead\s*\(|KernelPread\s*\(|KernelPreadv\s*\(|\.Read\s*\(' "$tmp/$name";;
        src/common/file.cpp) rg -n -C 8 'File::Read\s*\(|SysFileRead\s*\(' "$tmp/$name";;
        *) rg -n -C 6 'SysFileRead\s*\(|fread\s*\(|setvbuf\s*\(' "$tmp/$name";;
      esac
    fi
  done
  rm -rf "$tmp"
fi

Length of output: 19446


@wuboo You’re right. The base revision already passed the destination to unbuffered fread, so the macOS hole case is not a regression established by this PR. Rejecting every guest-map hole would also reject AvPlayer’s host buffer.

I withdraw my request to verify that case for this PR. I did not run it on macOS.


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

Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-18 00:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#discussion_r4607650519) <!-- coderabbit-ai-generated:v1 --> <details> <summary>Analysis chain</summary> <dl> <dd> <br> Script executed: ```shell #!/bin/bash set -u printf '%s\n' '--- Revision and instructions ---' git rev-parse HEAD for f in AGENTS.md src/AGENTS.md src/kernel/AGENTS.md src/libs/AGENTS.md; do if [ -f "$f" ]; then printf '\n--- %s ---\n' "$f"; cat "$f"; fi done printf '\n%s\n' '--- Base revision ---' base=$(git merge-base HEAD origin/main 2>/dev/null || true) if [ -z "$base" ]; then base=$(git rev-parse origin/main 2>/dev/null || true); fi printf 'base=%s\n' "$base" printf '\n%s\n' '--- Current code outlines ---' for f in src/kernel/guestFileRead.h src/kernel/fileSystem.cpp src/kernel/memory.cpp src/libs/avPlayer.cpp src/common/file.cpp src/common/platform/sysLinuxFileIO.cpp; do if [ -f "$f" ]; then printf '\n--- %s ---\n' "$f" ast-grep outline "$f" --items all --match 'ReadIntoGuest|KernelRead|KernelPread|IsKnownUnwritable|IsGuestWritable|FileStreamer|ReadEx|SysFileRead' 2>&1 | head -100 fi done printf '\n%s\n' '--- Current relevant source ---' cat -n src/kernel/guestFileRead.h | sed -n '1,115p' rg -n -C 6 'IsKnownUnwritable\s*\(|IsGuestWritable\s*\(|ReadIntoGuest\s*\(' src/kernel/fileSystem.cpp src/kernel/memory.cpp rg -n -C 6 'readOffset|avio_alloc_context|avio_buffer' src/libs/avPlayer.cpp rg -n -C 5 'SysFileReadEx\s*\(|SysFileRead\s*\(|fread\s*\(|setvbuf\s*\(' src/common/platform/sysLinuxFileIO.cpp printf '\n%s\n' '--- Base read implementation ---' if [ -n "$base" ]; then tmp=$(mktemp -d) for f in src/kernel/fileSystem.cpp src/common/file.cpp src/common/platform/sysLinuxFileIO.cpp; do name=$(basename "$f") if git show "$base:$f" > "$tmp/$name" 2>/dev/null; then printf '\n--- base %s ---\n' "$f" ast-grep outline "$tmp/$name" --items all --match 'KernelRead|KernelPread|Read|SysFileRead' 2>&1 | head -80 case "$f" in src/kernel/fileSystem.cpp) rg -n -C 12 'KernelRead\s*\(|KernelPread\s*\(|KernelPreadv\s*\(|\.Read\s*\(' "$tmp/$name";; src/common/file.cpp) rg -n -C 8 'File::Read\s*\(|SysFileRead\s*\(' "$tmp/$name";; *) rg -n -C 6 'SysFileRead\s*\(|fread\s*\(|setvbuf\s*\(' "$tmp/$name";; esac fi done rm -rf "$tmp" fi ``` Length of output: 19446 --- </dd> </dl> </details> `@wuboo` You’re right. The base revision already passed the destination to unbuffered `fread`, so the macOS hole case is not a regression established by this PR. Rejecting every guest-map hole would also reject AvPlayer’s host buffer. I withdraw my request to verify that case for this PR. I did not run it on macOS. --- > 📝 Learnings were not changed: only organization members or users with write access to this repository can add or remove learnings. <!-- <review_comment_withdrawn> --> Review thread resolved. <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
@ -876,0 +913,4 @@
std::vector<VirtualRanges::Range> ranges;
std::shared_lock state(g_memory_state_mutex);
return g_virtual_ranges != nullptr && g_virtual_ranges->QuerySpan(vaddr, size, &ranges) &&
std::all_of(ranges.begin(), ranges.end(), HasHostWriteAccess);
Author
Owner

@⁠wuboo on GitHub · 2026-11-18 02:38 UTC · original

Agreed that the window exists, but I'd keep it as is in this PR. It only opens when the guest unmaps or re-protects its own read buffer from another thread while a read into that buffer is still in flight, which is a race in the guest itself (the console gives no defined result for it either). Holding g_memory_operation_mutex across each bounce chunk would serialize every munmap/mprotect behind file I/O for all threads to cover that case, and making the copy fault-tolerant needs a guarded-copy primitive the emulator does not have yet. The bounce path also only runs after the host read has already failed with EFAULT on a tracked page, so it is rare in practice. If a game turns out to hit it, a fault-tolerant guest copy would be the better follow-up.

**@⁠wuboo** on GitHub · 2026-11-18 02:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2356#discussion_r4608533105) Agreed that the window exists, but I'd keep it as is in this PR. It only opens when the guest unmaps or re-protects its own read buffer from another thread while a read into that buffer is still in flight, which is a race in the guest itself (the console gives no defined result for it either). Holding `g_memory_operation_mutex` across each bounce chunk would serialize every `munmap`/`mprotect` behind file I/O for all threads to cover that case, and making the copy fault-tolerant needs a guarded-copy primitive the emulator does not have yet. The bounce path also only runs after the host read has already failed with `EFAULT` on a tracked page, so it is rare in practice. If a game turns out to hit it, a fault-tolerant guest copy would be the better follow-up.
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

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

Merge

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