kernel: retry guest file reads that fault on a write-protected page #2356
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
GPU
GUI
help wanted
question
Shaders
Video
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/KytyPS5--KytyPS5!2356
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-2356"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@wuboo on GitHub · 2026-11-17 18:40 UTC · original
wuboo:pr/win-read-efault→main· +660 −8 · 12 files · 1 commits · openProblem
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:
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:
ReadFilereturnsERROR_NOACCESSand delivers 0 bytes;read(2)returnsEFAULT.File::Readignored the error, sosceKernelRead/pread/preadvreturned 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
InvalidateMemorycall before the read does not prevent this. The page can still be protected when the host read runs.Fix
File::ReadEx/SysFileReadExreport the host error. On Windows,ERROR_NOACCESSandERROR_INVALID_USER_BUFFERare reported asEFAULT, other failures asEIO, and a read at end of file is not an error; POSIX already returnsEFAULT(and its errno for other failures).EFAULT,KernelRead,KernelPreadandKernelPreadvretry the rest of the read through a host bounce buffer (in 1 MiB chunks,kernel/guestFileRead.h). Thememcpyinto the guest buffer takes the normal guest page fault, the tracker unprotects the page, and the guest gets all of its bytes.Memory::IsKnownUnwritablerejects 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'sreadOffsetcallback, which reads into it withsceKernelPread. A program image passes only while it is host-writable:SetProgramMemoryProtectionleaves it read-write whatever its guest protection and the map records that, whileProtectGuestMemoryandmprotectgive 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.EFAULT),Memory::IsGuestWritablerequires 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 withEFAULTinstead of faulting in host code, as the console kernel does, and the file offset stays at the delivered bytes.EIOinstead of returning a short read. A short read at end of file is unchanged.Testing
win_read_efaulttest.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_READONLYon Windows,PROT_NONEon POSIX) delivers 0 bytes and reportsEFAULT, and other failures reportEIO(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 withEFAULTbefore 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 withEFAULTand is left untouched; a tracked page is retried in full; other failures fail withEIO.GuestReadDestinationCheckscase invirtual_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; afterProtectGuestMemory(Read)it is rejected. A read-only program segment passes the first-read check only, and is rejected onceProtectGuestMemory(Read)ormprotectmakes it host read-only.EIOmapping or theEIOresult 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. InGuestReadDestinationChecks, 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.ctest: the same failures asmain(the Vulkan-loader GPU tests,shader_cfg,kernel_file_system), all unrelated. The new tests pass.--shader-cache, on top of the PS logo fix:underwater_aerial_gardenstarted) 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.main(2638b1b07) it crashed 3/3 at the PS logo (guest trap onVideoPlayerLoadUnload_ATQT). The AvPlayer file reader passes a host buffer to the guest's read callback, the check rejected it and the read returnedEFAULT. Without this PR, the same build gets past the logo.2638b1b07with the same input: the logo, title and world map pass (3,590 frames, empty shader cache). A second run reachedtransition_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:
underwater_aerial_garden).main2638b1b07: PS logo -> world map -> first planet loaded, 20,473 frames, no errors.win_read_efaultandvirtual_memory_allocation(GuestReadDestinationChecks) on Windows and macOS, with mutation checks.@coderabbitai[bot] on GitHub · 2026-11-17 18:49 UTC · original · edited 2026-11-24 23:22 UTC
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:
nmzikChange: Bug fix
Merge Risk:
Low · previous review
1e7afGuest 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:
4
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 · edited 2026-11-17 20:59 UTC
On
src/common/platform/sysWindowsFileIO.cppline 49 (outdated):Return
EIOfor other failed reads, except end-of-file.SysFileReadExreports onlyERROR_NOACCESSandERROR_INVALID_USER_BUFFERasEFAULT. Other failed reads, such as a read that overlaps a range locked by another process, leave*errat 0. In the bounce-retry loop inReadIntoGuest, such a failure returnstruewith a short count, so the guest receives a partial buffer as a successful read.Keep both
EFAULTmappings. Map other failures toEIO. KeepERROR_HANDLE_EOFat 0, because a read that starts at end of file must still return a zero-byte result without an error.Suggested fix
Committable suggestion
✅ Confirmed as addressed by @wuboo
@coderabbitai[bot] on GitHub · 2026-11-17 18:49 UTC · original · edited 2026-11-17 21:00 UTC
On
src/kernel/fileSystem.cppline 212 (outdated):Keep an unrecovered fault on the retry copy from terminating the emulator.
The retry copy writes into
buf + donewithout checking that the guest range is accessible. For an unmapped destination, the write faults in host code.HandleGpuFaultreturns false for an address the GPU tracker does not map, soKytyExceptionHandlerreaches its fatalEXIT. Before this change, the same unmapped buffer returnedEFAULTor a short read to the guest. Now the emulator exits. The same path applies when a platform reportsEFAULTafter 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 · reviewed
Actionable comments posted: 2
7fef0ad6-007a-46a3-9686-c6597601aa3eReviewing files that changed from the base of the PR and between
4da95bd8d0and 1974034429806872a0fbc49c9ca2834246373c31.CMakeLists.txtsrc/common/file.cppsrc/common/file.hsrc/common/platform/sysFileIO.hsrc/common/platform/sysLinuxFileIO.cppsrc/common/platform/sysWindowsFileIO.cppsrc/kernel/fileSystem.cpptests/WinReadEfaultTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
@wuboo on GitHub · 2026-11-17 20:46 UTC · original
On
src/common/platform/sysWindowsFileIO.cppline 49 (outdated):Done.
SysFileReadExnow reports every failedReadFileexceptERROR_HANDLE_EOF:ERROR_NOACCESS/ERROR_INVALID_USER_BUFFERasEFAULT, anything else asEIO.ReadIntoGuestturns any non-EFAULT failure intoEIOinstead of a short read, and a plain short read at end of file is unchanged. The POSIX side already reported errno throughferror, and the test now covers both platforms.@wuboo on GitHub · 2026-11-17 20:46 UTC · original
On
src/kernel/fileSystem.cppline 212 (outdated):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 withEFAULTwithout copying, and the file offset only covers the delivered bytes. The retry moved tokernel/guestFileRead.h, andwin_read_efaultnow 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);@coderabbitai[bot] on GitHub · 2026-11-17 20:55 UTC · original · edited 2026-11-17 23:08 UTC
Small reads into non-writable guest buffers can crash the process instead of returning
EFAULT.The first guest read uses
File::ReadEx, which callsfread. For a small read,freadcopies into the guest buffer withmemcpy. A write fault on a page the GPU resource tracker owns is recovered byKytyExceptionHandler, so the read completes. A write fault on a guest page that is neither tracked nor writable is not recovered.HandleGpuFaultreturns false, and the fault is reported as a host failure. Large reads take the direct kernel path and can returnEFAULT, so the error behavior depends on read size.Check that the destination is writable before the first read. If it is not writable, return
EFAULTwithout callingfread. 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 · reviewed
Actionable comments posted: 1
982bfa66-a04c-417d-8d83-9e43eb742224Reviewing files that changed from the base of the PR and between 1974034429806872a0fbc49c9ca2834246373c31 and 475fb0d79b1b369d39426b5adeffcc81c80516b3.
src/common/file.hsrc/common/platform/sysFileIO.hsrc/common/platform/sysWindowsFileIO.cppsrc/kernel/fileSystem.cppsrc/kernel/guestFileRead.hsrc/kernel/memory.cppsrc/kernel/memory.htests/WinReadEfaultTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.
@ -0,0 +38,4 @@if (want != 0 && known_unwritable(buf, want)) {return EFAULT;}f.ReadEx(buf, want, got, &err);@wuboo on GitHub · 2026-11-17 21:06 UTC · original
Good catch.
ReadIntoGuestnow checks the destination with the samecan_writecallback (Memory::IsGuestWritable) before the first read; if it is not writable the call returnsEFAULTwith 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, andwin_read_efaultcovers both cases. Also rebased onto current main.@coderabbitai[bot] on GitHub · 2026-11-17 21:15 UTC · original
On
tests/WinReadEfaultTests.cppline 209 (outdated):Keep
MAP_FAILEDout 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 preventswin_read_efault_testsfrom compiling and blockskyty_tests, which now depends on it. (raw.githubusercontent.com)Move the allocation check into each platform branch. Check
two != nullptrafterVirtualAllocandtwo != MAP_FAILEDaftermmap.@coderabbitai[bot] on GitHub · 2026-11-17 21:15 UTC · original · reviewed
Actionable comments posted: 1
488e1d1d-a6a1-41ff-9e64-fd3f235934e5Reviewing files that changed from the base of the PR and between 475fb0d79b1b369d39426b5adeffcc81c80516b3 and 23ddcf51ffb03b00ff0a998849d7cf1565924b86.
CMakeLists.txtsrc/kernel/fileSystem.cppsrc/kernel/guestFileRead.htests/WinReadEfaultTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.
@ -0,0 +38,4 @@if (want != 0 && known_unwritable(buf, want)) {return EFAULT;}f.ReadEx(buf, want, got, &err);@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
readOffsetcallback, and the guest reads into it withsceKernelPread. The read gotEFAULTand ASTRO BOT asserted during the PS logo video on currentmain. 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::IsKnownUnwritablerejects 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 withEFAULT, 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 withEFAULTinstead of faulting in host code. Both cases are covered inwin_read_efaultand in a newGuestReadDestinationCheckscase invirtual_memory_allocation, and the game now gets past the PS logo, the world map and loads the first planet on currentmain.@coderabbitai[bot] on GitHub · 2026-11-17 23:03 UTC · original · edited 2026-11-18 00:27 UTC
On
src/kernel/memory.cppline 879 (outdated):Treat host-read-only
Codepages as known unwritable.The
Codeexemption atsrc/kernel/memory.cpp:879makesIsKnownUnwritablereturn false for aCodefragment, even when its host protection lacks write access.ProtectGuestMemoryandProtectMemorycan make such pages host read-only. For a read into one of those pages,ReadIntoGuestcallsReadExdirectly, 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 withEFAULTbefore the store.Remove the blanket
Codeexemption, or narrow it so that aCoderange without host write access is reported as known unwritable. Program images thatSetProgramMemoryProtectionleaves host-writable must still read normally. The comment atsrc/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 · reviewed
Actionable comments posted: 1
f53b9b89-e710-4376-8d52-c85fe6268336Reviewing files that changed from the base of the PR and between 23ddcf51ffb03b00ff0a998849d7cf1565924b86 and 8af35ad150c26b4fe22d99d4b812200e53a9cce6.
src/kernel/fileSystem.cppsrc/kernel/guestFileRead.hsrc/kernel/memory.cppsrc/kernel/memory.htests/VirtualMemoryAllocationTests.cpptests/WinReadEfaultTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
@ -0,0 +38,4 @@if (want != 0 && known_unwritable(buf, want)) {return EFAULT;}f.ReadEx(buf, want, got, &err);@coderabbitai[bot] on GitHub · 2026-11-17 23:10 UTC · original
Analysis chain
Script executed:
Length of output: 27712
Script executed:
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:
Length of output: 4538
Script executed:
Length of output: 3434
@wubooThanks for clarifying why the first check must allow host buffers.One case still needs verification.
IsKnownUnwritableskips guest-map holes. In Apple’s currentfreadsource, 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 returningEFAULT.Please check a one-byte
sceKernelPreadinto 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.You are interacting with an AI system.
@wuboo on GitHub · 2026-11-18 00:17 UTC · original
On
src/kernel/memory.cppline 879 (outdated):Good catch, thanks. The map only stores the guest protection, and for program memory that does not tell us the host protection:
SetProgramMemoryProtectionalways keeps the host mapping read-write, whileProtectGuestMemoryandmprotectgive it the host protection of the guest one, so a Code page can end up host read-only. I removed the blanketCodeexception. A range now records whetherSetProgramMemoryProtectionleft it host-writable, and any other protection change clears that.IsKnownUnwritablerejects a range only when it is not flagged host-writable and has no CPU/GPU write access. Program images thatSetProgramMemoryProtectionleaves host-writable still read normally; a Code page made read-only on the host now fails withEFAULTlike any other read-only memory.GuestReadDestinationCheckscoversProtectGuestMemory(Read), re-applyingSetProgramMemoryProtection, andmprotecton 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);@wuboo on GitHub · 2026-11-18 00:17 UTC · original
This is not something the change makes worse. Before this PR,
read/pread/preadvcalledfread/ReadFilestraight 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 unbufferedfreadcase 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 AvPlayerFileStreamerhands the guest'sreadOffsetcallback a host buffer that is not in the map, and rejecting that broke the PS logo video. Turning holes intoEFAULTwould 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);@coderabbitai[bot] on GitHub · 2026-11-18 00:24 UTC · original · edited 2026-11-18 02:38 UTC
The bounce-copy store can fault after the destination check passes.
IsGuestWritablereleasesg_memory_state_mutexwhen it returns.ReadFileIntoGuesttakes no memory-operation lock, andg_memory_operation_mutexis private tomemory.cpp. A concurrentKernelMunmaporKernelMprotectcan therefore change the destination between the check atsrc/kernel/guestFileRead.h:68and thememcpyat 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 returnedEFAULTbefore 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_mutexacross 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 · reviewed
Actionable comments posted: 1
8cdb06e3-9c43-4e2a-8b28-261533ddae60Reviewing files that changed from the base of the PR and between 8af35ad150c26b4fe22d99d4b812200e53a9cce6 and 1e7af94ced06dc41e8a9083b5356be5906c913cd.
src/kernel/memory.cppsrc/kernel/memory.htests/VirtualMemoryAllocationTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
@ -0,0 +38,4 @@if (want != 0 && known_unwritable(buf, want)) {return EFAULT;}f.ReadEx(buf, want, got, &err);@coderabbitai[bot] on GitHub · 2026-11-18 00:27 UTC · original
Analysis chain
Script executed:
Length of output: 19446
@wubooYou’re right. The base revision already passed the destination to unbufferedfread, 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.
Review thread resolved.
You are interacting with an AI system.
@ -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);@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_mutexacross each bounce chunk would serialize everymunmap/mprotectbehind 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 withEFAULTon 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.View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.