common: retry Windows file reads through a bounce buffer when the guest buffer is protected #838

Closed
github-bot wants to merge 1 commit from gh-pr/838/head into gh-pr/838/base
Owner

@⁠ew-sudo on GitHub · 2026-09-25 20:53 UTC · original
ew-sudo:fix-read-protected-pages → main · +30 −2 · 1 files · 1 commits · closed without merging

Problem

On Windows, SysFileRead calls ReadFile directly on the guest destination buffer and ignores its return value. When that buffer lies in write-protected guest memory (pages tracked for GPU synchronization), ReadFile fails because it writes from kernel mode, which never reaches the emulator's fault handler. The failure is silent: KernelRead/KernelPread return 0 bytes and the game sees an empty file.

In Astro Bot (PPSA21564, 01.007) this happens while loading levels and causes the failures reported in #745:

  • level XML files read as empty, e.g.
    Read 0 bytes from: .../data/prein/levels/diorama_controller_skin/level.lvx
    ASSERT: D:\asobi\6.0\source\engine\app\Module\System\Xml.cpp:819
    Xml file "data/prein/levels/diorama_controller_skin/level.lvx" is broken and failed to load
    
    (the file is 62 KB on disk);
  • an infinite loading tunnel when larger level data reads fail the same way.

With a temporary log added around the call, the failing reads returned two error codes:

  • 998 (ERROR_NOACCESS)
  • 1784 (ERROR_INVALID_USER_BUFFER), mostly for larger transfers (up to 160 MB in one call).

Fix

When ReadFile fails with one of these two errors, rewind to the original file position and read through a 1 MiB thread-local host buffer, copying each chunk into the guest buffer with memcpy. That copy runs in user mode, so the fault handler can unprotect the pages as usual. This is the same approach the AMPR read path already uses (bounce buffer + memcpy). Successful reads are unchanged; the only extra cost on the normal path is one SetFilePointerEx query per read.

Testing

  • Windows 11, Intel Core Ultra 7 155H, RTX 4070 Laptop GPU.
  • Astro Bot PPSA21564 01.007: with this change every failing read was recovered in full (logged as bounce buffer read N of N bytes during testing, for both error codes), the Xml.cpp:819 assert no longer happens, and the level loads from the world map.
  • Because this game needs other fixes to reach that point on my machine, testing was done on top of #780 and a separate EXTRQ change for Intel CPUs. This commit does not depend on either and applies cleanly on main.

Notes

  • Linux uses fread in SysFileRead; a large fread can hit the same class of failure (EFAULT) on protected pages. I have not tested Linux, so this PR only changes the Windows path.
  • Related: #745, #780.

I used Claude to help investigate and write this change; I built and tested it myself and reviewed the code.

**@⁠ew-sudo** on GitHub · 2026-09-25 20:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/838) `ew-sudo:fix-read-protected-pages` → `main` · +30 −2 · 1 files · 1 commits · closed without merging ### Problem On Windows, `SysFileRead` calls `ReadFile` directly on the guest destination buffer and ignores its return value. When that buffer lies in write-protected guest memory (pages tracked for GPU synchronization), `ReadFile` fails because it writes from kernel mode, which never reaches the emulator's fault handler. The failure is silent: `KernelRead`/`KernelPread` return 0 bytes and the game sees an empty file. In Astro Bot (PPSA21564, 01.007) this happens while loading levels and causes the failures reported in #745: - level XML files read as empty, e.g. ``` Read 0 bytes from: .../data/prein/levels/diorama_controller_skin/level.lvx ASSERT: D:\asobi\6.0\source\engine\app\Module\System\Xml.cpp:819 Xml file "data/prein/levels/diorama_controller_skin/level.lvx" is broken and failed to load ``` (the file is 62 KB on disk); - an infinite loading tunnel when larger level data reads fail the same way. With a temporary log added around the call, the failing reads returned two error codes: - `998` (`ERROR_NOACCESS`) - `1784` (`ERROR_INVALID_USER_BUFFER`), mostly for larger transfers (up to 160 MB in one call). ### Fix When `ReadFile` fails with one of these two errors, rewind to the original file position and read through a 1 MiB thread-local host buffer, copying each chunk into the guest buffer with `memcpy`. That copy runs in user mode, so the fault handler can unprotect the pages as usual. This is the same approach the AMPR read path already uses (bounce buffer + `memcpy`). Successful reads are unchanged; the only extra cost on the normal path is one `SetFilePointerEx` query per read. ### Testing - Windows 11, Intel Core Ultra 7 155H, RTX 4070 Laptop GPU. - Astro Bot PPSA21564 01.007: with this change every failing read was recovered in full (logged as `bounce buffer read N of N bytes` during testing, for both error codes), the `Xml.cpp:819` assert no longer happens, and the level loads from the world map. - Because this game needs other fixes to reach that point on my machine, testing was done on top of #780 and a separate EXTRQ change for Intel CPUs. This commit does not depend on either and applies cleanly on `main`. ### Notes - Linux uses `fread` in `SysFileRead`; a large `fread` can hit the same class of failure (`EFAULT`) on protected pages. I have not tested Linux, so this PR only changes the Windows path. - Related: #745, #780. I used Claude to help investigate and write this change; I built and tested it myself and reviewed the code.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:34:25 +00:00
github-bot closed this pull request 2026-11-26 09:34:25 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 21:01 UTC · original

Review in Change Stack →

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: 0d5edaf1-be99-4787-b028-f774a89b15cd

📥 Commits

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

📒 Files selected for processing (1)
  • src/common/platform/sysWindowsFileIO.cpp

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


📝 Walkthrough

Walkthrough

On Windows, SysFileRead now checks the result of the direct ReadFile call. For ERROR_NOACCESS or ERROR_INVALID_USER_BUFFER, it restores the saved file position and retries through a thread-local 1 MiB buffer, copying chunks to the destination. Other direct-read failures report zero bytes read.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 4214c

No actionable merge-blocking defect was established in the Windows read fallback. Merge after normal checks.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 4214c

The change should recover reads into protected guest pages, but the fallback may also encounter invalid destinations or failed position restoration. Those cases could affect host-process availability or the bytes delivered to the guest.

Retained concerns

  • Medium · security · inferred: A non-null invalid guest destination that triggers a selected ReadFile error may reach memcpy in the fallback instead of returning a failed read. Whether the host fault handler safely rejects that copy is unverified.
  • Low · reliability · inferred: If saving or restoring the file position fails during a retry, the fallback can read from an unintended offset while reporting copied bytes as a successful read. An ELF segment caller does not check that count.
Security review details

Security Blast Radius

  • inferred — The affected scope is Windows file-backed reads into caller-supplied memory, including guest-facing file reads and ELF segment loading. The inspected change does not add a file-open route or change file permissions.

Security Findings and Attack Paths

  • inferred — A guest-supplied non-null destination could trigger a selected direct-read error and then be written by the fallback. A resulting host-process fault is possible, but the behavior of the memory fault handler for an invalid destination was not established.

Trust Boundaries and Controls

  • observed — The retry retains the caller's destination and requested size but replaces a failed kernel-mode write with a user-mode copy. KernelRead and KernelPread retain null checks, memory invalidation, and per-file locking.

Resilience and Maintainability Implications

  • inferred — The per-file mutex protects the inspected guest read calls, limiting the apparent same-handle concurrency risk there. Other file owners' synchronization and recovery from a failed rewind are not established.

Hardening Proposals

  • proposed — Distinguish an invalid destination from a protected, recoverable guest page before copying, and preserve a recoverable read failure for the former.
  • proposed — Check position operations and propagate incomplete retry results to callers that require a complete read, particularly executable segment loading.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 1 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the Windows file-read retry and the bounce-buffer workaround for protected guest buffers.
Description check ✅ Passed The description accurately explains the failure, the Windows-specific fix, affected error codes, testing, and scope.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 21:01 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/838#issuecomment-5839566097) <!-- 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/838"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> Navigate logical layers of code changes, visualize relationships, and explore their blast radius. <!-- review_stack_entry_end --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary>ℹ️ Recent review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `0d5edaf1-be99-4787-b028-f774a89b15cd` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 497166009c8c0dd663fa1ffce3805a31bdc40d0e and 4214c331a11849abb41c0effc971735e905bc17f. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/common/platform/sysWindowsFileIO.cpp` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough On Windows, `SysFileRead` now checks the result of the direct `ReadFile` call. For `ERROR_NOACCESS` or `ERROR_INVALID_USER_BUFFER`, it restores the saved file position and retries through a thread-local 1 MiB buffer, copying chunks to the destination. Other direct-read failures report zero bytes read. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"4214c331a11849abb41c0effc971735e905bc17f" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _⚪ Minimal_ · up to `4214c` <!-- final_review_risk_coverage:{"sourceCommitId":"4214c331a11849abb41c0effc971735e905bc17f","coveredCommitId":"4214c331a11849abb41c0effc971735e905bc17f","kind":"reviewed"} --> No actionable merge-blocking defect was established in the Windows read fallback. Merge after normal checks. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🟡 Moderate_ · up to `4214c` The change should recover reads into protected guest pages, but the fallback may also encounter invalid destinations or failed position restoration. Those cases could affect host-process availability or the bytes delivered to the guest. **Retained concerns** - **Medium · security · inferred:** A non-null invalid guest destination that triggers a selected ReadFile error may reach memcpy in the fallback instead of returning a failed read. Whether the host fault handler safely rejects that copy is unverified. - **Low · reliability · inferred:** If saving or restoring the file position fails during a retry, the fallback can read from an unintended offset while reporting copied bytes as a successful read. An ELF segment caller does not check that count. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — The affected scope is Windows file-backed reads into caller-supplied memory, including guest-facing file reads and ELF segment loading. The inspected change does not add a file-open route or change file permissions. **Security Findings and Attack Paths** - _inferred_ — A guest-supplied non-null destination could trigger a selected direct-read error and then be written by the fallback. A resulting host-process fault is possible, but the behavior of the memory fault handler for an invalid destination was not established. **Trust Boundaries and Controls** - _observed_ — The retry retains the caller's destination and requested size but replaces a failed kernel-mode write with a user-mode copy. KernelRead and KernelPread retain null checks, memory invalidation, and per-file locking. **Resilience and Maintainability Implications** - _inferred_ — The per-file mutex protects the inspected guest read calls, limiting the apparent same-handle concurrency risk there. Other file owners' synchronization and recovery from a failed rewind are not established. **Hardening Proposals** - _proposed_ — Distinguish an invalid destination from a protected, recoverable guest page before copying, and preserve a recoverable read failure for the former. - _proposed_ — Check position operations and propagate incomplete retry results to callers that require a complete read, particularly executable segment loading. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 1 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :--------------------------------------------------------------------------------------------------------------------- | | Title check | ✅ Passed | The title clearly identifies the Windows file-read retry and the bounce-buffer workaround for protected guest buffers. | | Description check | ✅ Passed | The description accurately explains the failure, the Windows-specific fix, affected error codes, testing, and scope. | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠SergiioDev on GitHub · 2026-10-07 19:02 UTC · original

@⁠ew-sudo I had the same problem, thanks for the PR. Let's see if we can get this fix merged

**@⁠SergiioDev** on GitHub · 2026-10-07 19:02 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/838#issuecomment-6044799756) @⁠ew-sudo I had the same problem, thanks for the PR. Let's see if we can get this fix merged
Author
Owner

@⁠Kronys256 on GitHub · 2026-10-13 07:18 UTC · original

Tested this PR on Windows with ASTRO BOT PPSA21564 01.007.000 (non-RT patch from #745, both cheats applied): it fixes the level-load crashes for me.

Setup: Windows 11 Pro 25H2, Ryzen 7 5800X3D, RX 9070 XT 16 GB (driver 32.0.31041.1004), 32 GB RAM.

Path: load an existing save, then steer the controller-ship from the hub towards a world.

Without this PR, every run crashed within seconds on a level-loading thread, each time at a different place in guest code:

Build Thread pc Fault
official df5b9b9 LevelTask_ATQT 0x90705147f movzx ecx, word [rax+0x28] with rax=0
BryKytyPS5 a9e1ae5 ProductNextLoad_ATQT 0x90029c326 int 0x41 after mov esi, 0x333, i.e. the Xml.cpp:819 assert from the PR description
BryKytyPS5 a9e1ae5 LevelTask_ATQT / OdxAsyncLoader 0x900388230 linear search for key 0x9ca52db2 with a garbage entry count (0xe0730600, 0x7d65de4e), walks off the mapping at 0x11e8000000

With this PR (only commit 4214c33 merged on top of BryKytyPS5 a9e1ae5, built with that repo's workflow): the world loaded and I finished a whole level, 9 minutes with no crash and a clean exit. Test build: https://github.com/MrGautier256/KytyPS5/releases/tag/BryKytyPS5-2026-10-12-2b5c97f-pr838

I also built df5b9b9 + this PR (https://github.com/MrGautier256/KytyPS5/releases/tag/KytyPS5-2026-10-12-7720a63-pr838) but did not play the level on it.

Full, unedited logs of these four runs will follow in a reply.

**@⁠Kronys256** on GitHub · 2026-10-13 07:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/838#issuecomment-6140414793) Tested this PR on Windows with ASTRO BOT PPSA21564 01.007.000 (non-RT patch from #745, both cheats applied): it fixes the level-load crashes for me. Setup: Windows 11 Pro 25H2, Ryzen 7 5800X3D, RX 9070 XT 16 GB (driver 32.0.31041.1004), 32 GB RAM. Path: load an existing save, then steer the controller-ship from the hub towards a world. **Without this PR**, every run crashed within seconds on a level-loading thread, each time at a different place in guest code: | Build | Thread | pc | Fault | | --- | --- | --- | --- | | official df5b9b9 | `LevelTask_ATQT` | 0x90705147f | `movzx ecx, word [rax+0x28]` with rax=0 | | BryKytyPS5 a9e1ae5 | `ProductNextLoad_ATQT` | 0x90029c326 | `int 0x41` after `mov esi, 0x333`, i.e. the `Xml.cpp:819` assert from the PR description | | BryKytyPS5 a9e1ae5 | `LevelTask_ATQT` / `OdxAsyncLoader` | 0x900388230 | linear search for key 0x9ca52db2 with a garbage entry count (0xe0730600, 0x7d65de4e), walks off the mapping at 0x11e8000000 | **With this PR** (only commit 4214c33 merged on top of BryKytyPS5 a9e1ae5, built with that repo's workflow): the world loaded and I finished a whole level, 9 minutes with no crash and a clean exit. Test build: https://github.com/MrGautier256/KytyPS5/releases/tag/BryKytyPS5-2026-10-12-2b5c97f-pr838 I also built df5b9b9 + this PR (https://github.com/MrGautier256/KytyPS5/releases/tag/KytyPS5-2026-10-12-7720a63-pr838) but did not play the level on it. Full, unedited logs of these four runs will follow in a reply.
Author
Owner

@⁠devklex on GitHub · 2026-10-18 04:21 UTC · original

I ran into the same failed reads in Astro Bot (PPSA21564, 01.007.000) on Windows 11 with an RTX 4090, right after New Game. The symptoms were the OdxAsyncLoader crash from the table above (pc 0x900388230 or 0x900387770, walking off at 0x11e8000000), an endless loop in the same thread, and an internal assert in ProductNextLoad_ATQT. In case it helps review, this is why the destination is protected even though KernelRead, KernelPread and KernelPreadv call Memory::InvalidateMemory first:

  • InvalidateMemory lifts the write protection, but MemoryTracker::InvalidateRegion also queues the range for a BDA sync.
  • The GPU thread's next draw or dispatch with raw-address memory (RenderContext::PrepareBda → BufferCache::SynchronizeBda) uploads those pages and write-protects them again. That can happen while ReadFile is still running. ReadFile then fails at the first protected page, and SysFileRead ignores the failure.

With a fallback like this one, my runs logged 0–4 recovered reads per New Game (37 in 18 runs, each with 0 bytes read directly). They hit level data such as .odxb, .skel and .anim files, and .gnfp textures from 128 KiB to 11 MB. Before the fallback, 5 of 38 runs failed at New Game; with it (and a separate texture-streaming fix), 18 runs in a row got through.

My version differs in two ways, in case either is useful here:

  • It handles the short read in fileSystem.cpp instead of SysFileRead, so it would also cover Linux and macOS. There SysFileRead uses fread, which passes large reads straight to read(2), and that stops with EFAULT at a protected page. I haven't tested those platforms.
  • It has a CI test that write-protects pages of a buffer, checks that a plain ReadFile into them stops short, and checks that the fallback delivers every byte.

If a maintainer wants either, I can open it as a PR or add the test on top of this one.

(Investigated with Claude Code, an AI assistant, which also drafted this comment. I read it before posting, and the runs are from my PC.)

**@⁠devklex** on GitHub · 2026-10-18 04:21 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/838#issuecomment-6245599377) I ran into the same failed reads in Astro Bot (PPSA21564, 01.007.000) on Windows 11 with an RTX 4090, right after New Game. The symptoms were the `OdxAsyncLoader` crash from the table above (pc 0x900388230 or 0x900387770, walking off at 0x11e8000000), an endless loop in the same thread, and an internal assert in `ProductNextLoad_ATQT`. In case it helps review, this is why the destination is protected even though `KernelRead`, `KernelPread` and `KernelPreadv` call `Memory::InvalidateMemory` first: - `InvalidateMemory` lifts the write protection, but `MemoryTracker::InvalidateRegion` also queues the range for a BDA sync. - The GPU thread's next draw or dispatch with raw-address memory (`RenderContext::PrepareBda` → `BufferCache::SynchronizeBda`) uploads those pages and write-protects them again. That can happen while `ReadFile` is still running. `ReadFile` then fails at the first protected page, and `SysFileRead` ignores the failure. With a fallback like this one, my runs logged 0–4 recovered reads per New Game (37 in 18 runs, each with 0 bytes read directly). They hit level data such as `.odxb`, `.skel` and `.anim` files, and `.gnfp` textures from 128 KiB to 11 MB. Before the fallback, 5 of 38 runs failed at New Game; with it (and a separate texture-streaming fix), 18 runs in a row got through. My version differs in two ways, in case either is useful here: - It handles the short read in `fileSystem.cpp` instead of `SysFileRead`, so it would also cover Linux and macOS. There `SysFileRead` uses `fread`, which passes large reads straight to `read(2)`, and that stops with `EFAULT` at a protected page. I haven't tested those platforms. - It has a CI test that write-protects pages of a buffer, checks that a plain `ReadFile` into them stops short, and checks that the fallback delivers every byte. If a maintainer wants either, I can open it as a PR or add the test on top of this one. (Investigated with Claude Code, an AI assistant, which also drafted this comment. I read it before posting, and the runs are from my PC.)
Author
Owner

@⁠ZrDaniel07 on GitHub · 2026-10-24 01:48 UTC · original

Tested on Windows 11 with an RTX 5090 (driver 617.42) and a Ryzen 9 5900X: ASTRO BOT PPSA21564 01.007.000, no game patch. It fixes the level-load faults here too.

Base: @⁠Nawid3333's test/helper-1511 (de0e387 = main @ 6aaa533 + the SRT-walk fix from #1365 + a DS_APPEND fix that avoids the DEVICE_LOST from #1511), built locally, with 4214c331 cherry-picked on top. It applied cleanly.

Build Runs Read 0 bytes lines in _kyty.txt End
de0e387 2 33 in the run whose log I kept, e.g. aerial_aquarium_clouds_1v.jxm (19,462,176 bytes on disk) guest fault in OdxAsyncLoader both times (pc 0x9074d8153 loading the world map, 0x90706b5be loading underwater_aerial_garden)
de0e387 + this PR 3 (the last one also with the local mesh patch mentioned below) 0 in each the level loaded every time; no loading-thread fault

Two of Nawid's lab builds (test/loopcap-1511, without this PR) also faulted at pc=0x900388230 and 0x900388244 looking up key 0x9ca52db2, the same site as in @⁠MrGautier256's table, after 1–2 reads of 0 bytes each.

With this PR the first two runs then stopped at the oversized mesh draw from #624 (mesh draw exceeds host workgroup limits, see #793). With a local fix for that on top, I got into gameplay in the level and closed the game myself; it ran at under 1 FPS with the guest log going to a file.

kernel_file_system_tests exits at startup with 0xC0000028 on this machine both with and without this PR, so I couldn't use it here.

AI use: Claude Code built the branches, applied the PR and compared the logs with me; I ran the game and checked the outputs myself.

**@⁠ZrDaniel07** on GitHub · 2026-10-24 01:48 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/838#issuecomment-6378379985) Tested on Windows 11 with an RTX 5090 (driver 617.42) and a Ryzen 9 5900X: ASTRO BOT PPSA21564 01.007.000, no game patch. It fixes the level-load faults here too. Base: @⁠Nawid3333's `test/helper-1511` (`de0e387` = `main` @ 6aaa533 + the SRT-walk fix from #1365 + a `DS_APPEND` fix that avoids the DEVICE_LOST from #1511), built locally, with `4214c331` cherry-picked on top. It applied cleanly. | Build | Runs | `Read 0 bytes` lines in `_kyty.txt` | End | |---|---|---|---| | `de0e387` | 2 | 33 in the run whose log I kept, e.g. `aerial_aquarium_clouds_1v.jxm` (19,462,176 bytes on disk) | guest fault in `OdxAsyncLoader` both times (`pc` `0x9074d8153` loading the world map, `0x90706b5be` loading `underwater_aerial_garden`) | | `de0e387` + this PR | 3 (the last one also with the local mesh patch mentioned below) | 0 in each | the level loaded every time; no loading-thread fault | Two of Nawid's lab builds (`test/loopcap-1511`, without this PR) also faulted at `pc=0x900388230` and `0x900388244` looking up key `0x9ca52db2`, the same site as in @⁠MrGautier256's table, after 1–2 reads of 0 bytes each. With this PR the first two runs then stopped at the oversized mesh draw from #624 (`mesh draw exceeds host workgroup limits`, see #793). With a local fix for that on top, I got into gameplay in the level and closed the game myself; it ran at under 1 FPS with the guest log going to a file. `kernel_file_system_tests` exits at startup with `0xC0000028` on this machine both with and without this PR, so I couldn't use it here. AI use: Claude Code built the branches, applied the PR and compared the logs with me; I ran the game and checked the outputs myself.
Author
Owner

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

I ran the protected-read cases from #1165 (TestReadsIntoProtectedPages) on Windows: main 0685bffb, clang-cl Release, Windows 11. The full kernel_file_system test stops earlier on Windows for unrelated reasons (the cancel case of TestMutexHandoff and TestSaveTruncate), so I ran that test on its own.

Windows build #1165's cases read into a buffer whose second page is no-access
main fail: pread fills a buffer that crosses into a write-protected page –
main + this PR + #1165 pass the process crashes: the retry's memcpy faults on the no-access page
main + this PR + #1165 + the diff below pass short read (0 bytes)

After ERROR_NOACCESS this PR copies into the whole destination, also into pages the fault handler doesn't resolve (unmapped or no-access guest memory). On main, SysFileRead just returns the bytes ReadFile reported, so such a read comes back short instead (I didn't run the no-access case on main itself); with the retry the process dies. #1165 already checks the destination on Linux (SysFileSetRecoverableDestination, set in InstallGpuResources). Doing the same on Windows puts both platforms on one rule. Diff on top of this PR + #1165:

--- a/src/common/platform/sysWindowsFileIO.cpp
+++ b/src/common/platform/sysWindowsFileIO.cpp
@@ -14,6 +14,7 @@
 #include "common/stringUtils.h"

 #include <algorithm>
+#include <atomic>
 #include <cstdlib>
 #include <cstring>
 #include <vector>
@@ -64,8 +65,11 @@ static DWORD GetCacheAccessType(sys_file_cache_type_t t) {
 	return FILE_ATTRIBUTE_NORMAL;
 }

-// Windows reads are recovered unconditionally in SysFileRead; the probe only serves Linux.
-void SysFileSetRecoverableDestination(SysFileRecoverableDestination /*probe*/) {}
+static std::atomic<SysFileRecoverableDestination> g_recoverable_destination {nullptr};
+
+void SysFileSetRecoverableDestination(SysFileRecoverableDestination probe) {
+	g_recoverable_destination.store(probe, std::memory_order_release);
+}

 void SysFileRead(void* data, uint32_t size, sys_file_t& f, uint32_t* bytes_read) {
 	if (f.type == SYS_FILE_FILE) {
@@ -84,10 +88,26 @@ void SysFileRead(void* data, uint32_t size, sys_file_t& f, uint32_t* bytes_read)
 			if (error == ERROR_NOACCESS || error == ERROR_INVALID_USER_BUFFER) {
 				SetFilePointerEx(f.handle, start, nullptr, FILE_BEGIN);
 				w = 0;
+				// Probe only bytes the file can still supply: the tail past EOF is never written.
+				uint64_t      remaining = size;
+				LARGE_INTEGER file_size {};
+				if (GetFileSizeEx(f.handle, &file_size) != FALSE) {
+					remaining = file_size.QuadPart > start.QuadPart
+					                ? std::min<uint64_t>(remaining,
+					                                     static_cast<uint64_t>(file_size.QuadPart -
+					                                                           start.QuadPart))
+					                : 0;
+				}
 				thread_local std::vector<uint8_t> chunk(1u << 20u);
-				while (w < size) {
-					const DWORD request =
-					    std::min<DWORD>(size - w, static_cast<DWORD>(chunk.size()));
+				while (remaining != 0) {
+					const auto request =
+					    static_cast<DWORD>(std::min<uint64_t>(remaining, chunk.size()));
+					const auto recoverable =
+					    g_recoverable_destination.load(std::memory_order_acquire);
+					if (recoverable == nullptr ||
+					    !recoverable(static_cast<uint8_t*>(data) + w, request)) {
+						break;
+					}
 					DWORD got = 0;
 					if (ReadFile(f.handle, chunk.data(), request, &got, nullptr) == FALSE ||
 					    got == 0) {
@@ -95,6 +115,10 @@ void SysFileRead(void* data, uint32_t size, sys_file_t& f, uint32_t* bytes_read)
 					}
 					std::memcpy(static_cast<uint8_t*>(data) + w, chunk.data(), got);
 					w += got;
+					remaining -= got;
+					if (got < request) {
+						break;
+					}
 				}
 			}
 		}

In ASTRO BOT (PPSA21564, RX 9070 XT) I ran main ffc81377 with this PR, #1165 and the diff on top: a 5-minute scripted run got as far as without them (same shader counts, level loading), no crash and no Read 0 bytes line. The run without them didn't show Read 0 bytes either this time; in my older runs (10-20 to 10-24 builds) it showed up in 6 of 20, on .gnfp texture files.

The no-access case I added at the end of TestReadsIntoProtectedPages (it only uses Common::VirtualMemory, so it should behave the same on Linux; I haven't run it there):

  constexpr uint64_t page_size = 0x1000;
  const auto partly = Common::VirtualMemory::Alloc(0, page_size * 2,
                                                   Common::VirtualMemory::Mode::ReadWrite);
  Check(partly != 0 && Common::VirtualMemory::Protect(partly + page_size, page_size,
                                                      Common::VirtualMemory::Mode::NoAccess),
        "map a read target whose second page is inaccessible");
  const auto got =
      FileSystem::KernelPread(fd, reinterpret_cast<void *>(partly), page_size * 2, 0);
  Check(got >= 0 && static_cast<uint64_t>(got) <= page_size &&
            std::memcmp(reinterpret_cast<void *>(partly), payload.data(),
                        static_cast<size_t>(got)) == 0,
        "pread into a partly inaccessible destination returns a short read");
  Common::VirtualMemory::Free(partly);
**@⁠Nawid3333** on GitHub · 2026-10-27 20:57 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/838#issuecomment-6453372746) I ran the protected-read cases from #1165 (`TestReadsIntoProtectedPages`) on Windows: main 0685bffb, clang-cl Release, Windows 11. The full `kernel_file_system` test stops earlier on Windows for unrelated reasons (the cancel case of `TestMutexHandoff` and `TestSaveTruncate`), so I ran that test on its own. | Windows build | #1165's cases | read into a buffer whose second page is no-access | |---|---|---| | main | fail: `pread fills a buffer that crosses into a write-protected page` | – | | main + this PR + #1165 | pass | the process crashes: the retry's `memcpy` faults on the no-access page | | main + this PR + #1165 + the diff below | pass | short read (0 bytes) | After `ERROR_NOACCESS` this PR copies into the whole destination, also into pages the fault handler doesn't resolve (unmapped or no-access guest memory). On main, `SysFileRead` just returns the bytes `ReadFile` reported, so such a read comes back short instead (I didn't run the no-access case on main itself); with the retry the process dies. #1165 already checks the destination on Linux (`SysFileSetRecoverableDestination`, set in `InstallGpuResources`). Doing the same on Windows puts both platforms on one rule. Diff on top of this PR + #1165: ```diff --- a/src/common/platform/sysWindowsFileIO.cpp +++ b/src/common/platform/sysWindowsFileIO.cpp @@ -14,6 +14,7 @@ #include "common/stringUtils.h" #include <algorithm> +#include <atomic> #include <cstdlib> #include <cstring> #include <vector> @@ -64,8 +65,11 @@ static DWORD GetCacheAccessType(sys_file_cache_type_t t) { return FILE_ATTRIBUTE_NORMAL; } -// Windows reads are recovered unconditionally in SysFileRead; the probe only serves Linux. -void SysFileSetRecoverableDestination(SysFileRecoverableDestination /*probe*/) {} +static std::atomic<SysFileRecoverableDestination> g_recoverable_destination {nullptr}; + +void SysFileSetRecoverableDestination(SysFileRecoverableDestination probe) { + g_recoverable_destination.store(probe, std::memory_order_release); +} void SysFileRead(void* data, uint32_t size, sys_file_t& f, uint32_t* bytes_read) { if (f.type == SYS_FILE_FILE) { @@ -84,10 +88,26 @@ void SysFileRead(void* data, uint32_t size, sys_file_t& f, uint32_t* bytes_read) if (error == ERROR_NOACCESS || error == ERROR_INVALID_USER_BUFFER) { SetFilePointerEx(f.handle, start, nullptr, FILE_BEGIN); w = 0; + // Probe only bytes the file can still supply: the tail past EOF is never written. + uint64_t remaining = size; + LARGE_INTEGER file_size {}; + if (GetFileSizeEx(f.handle, &file_size) != FALSE) { + remaining = file_size.QuadPart > start.QuadPart + ? std::min<uint64_t>(remaining, + static_cast<uint64_t>(file_size.QuadPart - + start.QuadPart)) + : 0; + } thread_local std::vector<uint8_t> chunk(1u << 20u); - while (w < size) { - const DWORD request = - std::min<DWORD>(size - w, static_cast<DWORD>(chunk.size())); + while (remaining != 0) { + const auto request = + static_cast<DWORD>(std::min<uint64_t>(remaining, chunk.size())); + const auto recoverable = + g_recoverable_destination.load(std::memory_order_acquire); + if (recoverable == nullptr || + !recoverable(static_cast<uint8_t*>(data) + w, request)) { + break; + } DWORD got = 0; if (ReadFile(f.handle, chunk.data(), request, &got, nullptr) == FALSE || got == 0) { @@ -95,6 +115,10 @@ void SysFileRead(void* data, uint32_t size, sys_file_t& f, uint32_t* bytes_read) } std::memcpy(static_cast<uint8_t*>(data) + w, chunk.data(), got); w += got; + remaining -= got; + if (got < request) { + break; + } } } } ``` In ASTRO BOT (PPSA21564, RX 9070 XT) I ran main ffc81377 with this PR, #1165 and the diff on top: a 5-minute scripted run got as far as without them (same shader counts, level loading), no crash and no `Read 0 bytes` line. The run without them didn't show `Read 0 bytes` either this time; in my older runs (10-20 to 10-24 builds) it showed up in 6 of 20, on `.gnfp` texture files. The no-access case I added at the end of `TestReadsIntoProtectedPages` (it only uses `Common::VirtualMemory`, so it should behave the same on Linux; I haven't run it there): ```cpp constexpr uint64_t page_size = 0x1000; const auto partly = Common::VirtualMemory::Alloc(0, page_size * 2, Common::VirtualMemory::Mode::ReadWrite); Check(partly != 0 && Common::VirtualMemory::Protect(partly + page_size, page_size, Common::VirtualMemory::Mode::NoAccess), "map a read target whose second page is inaccessible"); const auto got = FileSystem::KernelPread(fd, reinterpret_cast<void *>(partly), page_size * 2, 0); Check(got >= 0 && static_cast<uint64_t>(got) <= page_size && std::memcmp(reinterpret_cast<void *>(partly), payload.data(), static_cast<size_t>(got)) == 0, "pread into a partly inaccessible destination returns a short read"); Common::VirtualMemory::Free(partly); ```
Author
Owner

@⁠ZrDaniel07 on GitHub · 2026-11-14 22:16 UTC · original

Still needed on main 3e226bff (11-14) for ASTRO BOT PPSA21564. Setup: Windows 11, RTX 5090 (driver 621.24), Ryzen 9 5900X.

Without this PR. Build: main 3e226bff plus the MAX_MIP view fallback for the boot exit (same as #2172). Running from the same save, the game reaches the level select (about 78 VS / 77 PS / 60 CS compiled) and stops with:

Unhandled host exception: type=1 code=3221225477 pc=0x000000090029c326 access=1 address=0xffffffffffffffff
 in src/loader/runtimeLinker.cpp:719

This happened in 3 of 3 runs (two fallback variants, one of them also run with --redzone). The same fault (same pc) shows up on eecd9821 and on every good step of a bisect from 11-06 to 11-07. --redzone does not change it (same pc).

With this PR. I ported the retry to the same build, and the Garden level (aerial_garden) loads at 1:44 from launch and plays with no exit.

Rebase. The patch no longer applies. 1a24e34e ("common: trim the File API", 11-04) removed the SYS_FILE_* types, and SysFileRead is now a single ReadFile(f.handle, data, size, &r, nullptr). The port keeps your logic unchanged:

  • save the file position with SetFilePointerEx(..., FILE_CURRENT);
  • on ERROR_NOACCESS / ERROR_INVALID_USER_BUFFER, seek back;
  • re-read through a thread_local 1 MiB buffer and memcpy into guest memory.

It adds <algorithm>, <cstring> and <vector>. Diff (+31/-2, one file) is available if useful.

AI use: Claude Code ported the patch and drafted this with me; I played the game.

**@⁠ZrDaniel07** on GitHub · 2026-11-14 22:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/838#issuecomment-6885053010) Still needed on `main` `3e226bff` (11-14) for ASTRO BOT PPSA21564. Setup: Windows 11, RTX 5090 (driver 621.24), Ryzen 9 5900X. **Without this PR.** Build: `main` `3e226bff` plus the MAX_MIP view fallback for the boot exit (same as #2172). Running from the same save, the game reaches the level select (about 78 VS / 77 PS / 60 CS compiled) and stops with: ``` Unhandled host exception: type=1 code=3221225477 pc=0x000000090029c326 access=1 address=0xffffffffffffffff in src/loader/runtimeLinker.cpp:719 ``` This happened in 3 of 3 runs (two fallback variants, one of them also run with `--redzone`). The same fault (same `pc`) shows up on `eecd9821` and on every good step of a bisect from 11-06 to 11-07. `--redzone` does not change it (same `pc`). **With this PR.** I ported the retry to the same build, and the Garden level (`aerial_garden`) loads at 1:44 from launch and plays with no exit. **Rebase.** The patch no longer applies. `1a24e34e` ("common: trim the File API", 11-04) removed the `SYS_FILE_*` types, and `SysFileRead` is now a single `ReadFile(f.handle, data, size, &r, nullptr)`. The port keeps your logic unchanged: - save the file position with `SetFilePointerEx(..., FILE_CURRENT)`; - on `ERROR_NOACCESS` / `ERROR_INVALID_USER_BUFFER`, seek back; - re-read through a `thread_local` 1 MiB buffer and `memcpy` into guest memory. It adds `<algorithm>`, `<cstring>` and `<vector>`. Diff (`+31/-2`, one file) is available if useful. AI use: Claude Code ported the patch and drafted this with me; I played the game.

Pull request closed

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