fix(libkernel): fail the stat family with EFAULT when the output struct is not writable guest memory #9618
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/9618"
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?
Imported from boykopovar/AnyPS5. Originally posted by xXPBSXx on 2026-10-22T04:40:10Z.
What
Fill a local struct and copy it out with a checked write,
GuestCopyOut_nid_no_patch(new, libc General.cpp:HostWriteguard, thenprocess_vm_writevon Linux and aVirtualQuerywritability walk on Windows), failing with EFAULT. Applied tofstat_nid_disambig1/_fstat,sceKernelFstat,lstat,sceKernelStat(sostat) and_fstatfs. The order of checks is unchanged: descriptor and path errors still come first, the copy-out is last, as insys_fstat/sys_stat/sys_fstatfs.Fixes: #9617
Tested
Head
c424bd17c8(two commits,83f28bd67fandc424bd17c8), rebased ontomainf26434afa3;git merge-treeagainst currentmain38d463a6cfis clean. The diff is 5 files, +148/-12: General.hpp +1, General.cpp +40, Open.cpp +3/-1, Stdio.cpp +15/-11, GuestFstatFault.cpp +89.guest_fstat_faultand the six tests of the earlier description (guest_file_timestamps,guest_kernel_sys,guest_filesystem,guest_posix_filesystem,guest_socket_descriptors,guest_socket_pair), 7 tests, onmainf26434afa3with this head:General.hpp,General.cpp,Open.cppandStdio.cpptaken frommainand the test kept,guest_fstat_faultfails with a SegFault.General.cppput back to its first-commit version (same tree, same build directory, test kept),guest_fstat_faultaborts at the EPERM case.faa3926cdf(before this rebase): jotitadev on Linux (Ubuntu 26.04, GCC 15.2, headbd2c029efmerged ontomain17f533556), review; jotitadev on macOS (Mac M2 Max, macOS 27.2, x86_64 under Rosetta), on the #8658 port branchdc0c8db500merged withfaa3926cdf, not onmain, review. I have not rerun macOS.extern "C"declarations were dropped becausemainnow declares them in the headers, and the_fstatfscall casts toKernelStatfs*. The source hunks are unchanged.check_conventions --base upstream/mainpasses.Relation to other work
#9423 adds
CopyGuestPath_nid_no_patch, a checked read of guest path strings.GuestCopyOut_nid_no_patchhere is the write counterpart for output structs; the two touch different functions and do not overlap, but both use the same host mechanism (process_vm_*on Linux, aVirtualQuerywalk on Windows) and could share one primitive later. If you prefer the check inline in each wrapper instead of a shared helper, say so and I will fold it.Merge order with #9478 and #7447 (they share
Stdio.cpp) is in the comments; this PR does not depend on them.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)AI-assisted (Claude Code).
🤖 Generated with Claude Code
Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-22T04:44:21Z.
Review: COMMENTED
Linux run of the case listed as not tested: an output struct on a mapped page that is not writable.
Machine: Linux x86_64, i7-8700, Ubuntu 26.04 (kernel 7.0.0-38), GCC 15.2, Release,
BUILD_TESTING=ON. Headbd2c029efmerged--no-commitontomain17f533556(clean).The seven tests from the description pass:
guest_fstat_fault,guest_file_timestamps,guest_kernel_sys,guest_filesystem,guest_posix_filesystem,guest_socket_descriptorsandguest_socket_pair.Read-only and inaccessible pages: I added a local probe to
guest_fstat_fault(not pushed). It maps two anonymous pages filled with0xa5, thenmprotects the second one:PROT_READpagefstat-1/EFAULT,stat-1/EFAULT,sceKernelFstat0x8002000e,_fstatfs-1. No crash.PROT_NONEpagefstat-1/EFAULTPROT_READpage (sizeof(FileStat)is 120)fstat-1/EFAULT, and the 16 writable bytes are overwrittenSo
process_vm_writevdoes reject a mapped page that isn't writable, as the description expects, and that case could be asserted the same way as the bad-address cases. The last row is a difference between hosts. On Linux,process_vm_writevwrites up to the fault, so a struct that straddles into a non-writable page gets partly written beforeEFAULT. The WindowsVirtualQuerywalk checks the whole range before itsmemcpy, so it writes nothing. FreeBSD'scopyoutcan also stop partway, so this may be acceptable, but the two hosts don't give the same result.Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T09:27:21Z.
Review: CHANGES_REQUESTED
The main fix is well targeted: metadata is filled into local
FileStat/KernelStatfsvalues, check precedence is retained, and the exact-head tests exercise all six stat-family wrappers with invalid pointers. Current-main conventions and whitespace pass; hosted conventions, eligibility, intake, labels, relinker, registration and ASan checks pass, while product Linux/Windows jobs are skipped. The author reports Windows and WSL red/green runs; an independent Linux reviewer confirms the same focused suite and additionally tested read-only and straddling pages. I did not rerun the full runtime tests locally.Two safety gaps remain in
GuestCopyOut_nid_no_patch: the non-Windows fallback can still dereference invalid output pointers, and Linux errors other thanEFAULTcan fall back to uncheckedmemcpy. Please add a checked copy-out path or fail safely, and cover read-only and partial-write behavior.The linked #9617 is a generic invalid-pointer sweep, not a title-specific stop.
I’ve noticed that holding this PR because of #5239 isn’t necessary. It’s fine for PRs to keep coming in; they’ll be handled in due course. Please disregard my earlier request to hold or defer it.
Imported from boykopovar/AnyPS5. Originally posted by EagleBearerYS on 2026-10-22T11:23:22Z.
@xXPBSXx a merge-order note: #9478 changes the same
ResolvePathError_nid_no_patchcall inlstatthat this PR reworks. It passes the resolver'smoduleflag,ResolvePathError_nid_no_patch(path, native, true), solstatof an original.prxname finds its relinked.guest.prx. This PR fills a localFileStatand copies it out withGuestCopyOut_nid_no_patch. They compose as this PR's version of the function with the flag kept. Since #9478 is a one-line change, I'd propose it goes first and this PR keeps the flag when it rebases; if you'd rather this one went first, #9478 rebases over it instead. #7447 (qpavyros) sets the same call'sarchivedflag too, so the combined call keeps both.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T13:13:12Z.
Review: CHANGES_REQUESTED
I withdraw the earlier #5239 intake-hold objection. I rechecked exact head
bd2c029ef713a8d1cbbb582dc5a621e39fa0d207against current main3ca07d086d5f44fbe3c00370e7f03953ab46ca1b: whitespace and conventions pass, the new regression source and all three changed implementation translation units pass local GCC 12.2 C++20 syntax-only compilation, and the current-main merge tree is clean. The author reports Windows and WSL red/green runs; an independent Linux reviewer confirms the seven focused tests, plus read-only and inaccessible-page probes. I did not run the runtime suite locally. Hosted relinker/register-context/write-watch checks pass; full product jobs are skipped. The exact-head safety issues from the prior review remain: 1. On macOS and other non-Windows/non-Linux hosts,GuestCopyOut_nid_no_patchfalls through tomemcpy.GuestArenaBeginHostWrite_nid_postfixreturns true on non-Windows hosts, so this guard does not validate an arbitrary destination; a bad pointer can still crash the host. Please add a checked copy-out implementation for supported hosts or fail safely without dereferencing invalid guest memory. 2. On Linux, everyprocess_vm_writeverror other thanEFAULTfalls back tomemcpy. Errors such asEPERM(for example, syscall filtering) andENOSYSdo not establish that the destination is writable. Please remove the unchecked fallback or restrict it to a condition that proves the full destination safe. 3. Add a read-only destination regression, as the independent reviewer already probed, and document/assert the partial-write behavior if a structure straddles into an inaccessible page. The branch base17f533556272e5f6833ed730172f12308eee08d2is behind current main; the repository requires keeping branches up to date. Please rebase/update and rerun the focused tests on that head. The overlap bot reports #9478's sharedStdio.cppcomparison is incomplete because it conflicts with main. The author's proposed merge order is reasonable, but preserve theResolvePathError_nid_no_patch(path, native, true)module flag when combining it with #9478, and retain #7447's archived flag if applicable.I’ve noticed that holding this PR because of #5239 isn’t necessary. It’s fine for PRs to keep coming in; they’ll be handled in due course. Please disregard my earlier request to hold or defer it.
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-22T18:56:40Z.
Review: CHANGES_REQUESTED
Thanks, the approach is right: local struct, copy-out last, error order unchanged as in
sys_fstat/sys_stat/sys_fstatfs. Two things still defeat the purpose of the helper (same as @MarcZX10's review):core/libs/prx/libc/src/General.cpp:706-709: anyprocess_vm_writeverror other thanEFAULT(EPERMunder seccomp,ENOSYS) falls back to an uncheckedmemcpy, which crashes on a bad pointer. Return false or throw on those instead (#9161 throws on host failures other thanEFAULT).General.cpp:712-714: on macOS and other hosts the helper is a plainmemcpyafterHostWrite, whoseOpen()is true for any non-arena pointer on non-Windows hosts. Either add a checked path for those hosts (e.g.mach_vm_write/vm_regionon macOS) orNotImplemented_nid_no_patchthere so it does not dereference a bad pointer silently.GuestFstatFault.cpp: add a read-only page case (mmap two pages,mprotectthe secondPROT_READ, expect -1/EFAULTat its start), as @jotitadev probed. Also note in the PR which behaviour you want when the struct straddles into a non-writable page: Linux writes up to the fault, the Windows walk writes nothing. Pick one and assert it, or state that it is unspecified likecopyout.moduleflag inlstat'sResolvePathError_nid_no_patch(path, native, true)when you rebase over it.Please also rebase onto current
mainand rerun the focused tests.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T23:43:48Z.
Review: CHANGES_REQUESTED
Blocking correctness issue:
GuestCopyOut_nid_no_patchcan still fault instead of returningEFAULTon non-Windows hosts. On Linux, whenprocess_vm_writevfails with anything other thanEFAULT(for exampleEPERMunder seccomp orENOSYS), lines 706–709 fall back tostd::memcpy; the non-Linux/non-Windows branch at lines 712–714 always does so.GuestArenaBeginHostWrite_nid_postfixdoes not validate writability on these platforms (it calls the write-watch hook and returns true), so an invalid or read-only destination can still crash in those branches. Please use a copy-out path that safely detects these failures, or fail conservatively when the safe syscall is unavailable, and add regression coverage for a non-EFAULTsyscall failure and the macOS path before considering this fixed.Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-23T04:00:41Z.
Review: COMMENTED
macOS run of the new
mach_vm_writebranch (listed as not tested).Mac M2 Max, macOS 27.2, Apple clang, x86_64 under Rosetta, Release.
maindoes not build libc/libkernel on macOS yet, so the tree is #8658 (feat/macos-port) @dc0c8db500merged with this PR @ faa3926cdf (clean merge).guest_fstat_fault,guest_file_timestamps,guest_kernel_sys,guest_filesystem,guest_posix_filesystem,guest_socket_descriptorsandguest_socket_pair: 7/7 pass.guest_fstat_fault3/3 runs.GuestCopyOut_nid_no_patchput back to the bd2c029ef version (memcpy on non-Linux, non-Windows hosts),guest_fstat_faultfails with a SegFault on macOS.mach_vm_writeon this host (standalone check, arm64 and Rosetta give the same results): addresses1and~0xfff, aPROT_READpage and aPROT_NONEpage all fail. An unaligned stack buffer and a write across two untouched pages succeed. A write that crosses from a writable page into a read-only one fails but leaves the bytes before the boundary written.process_vm_writevbehaves the same way.The
HostWriteguard beforemach_vm_writeis required on macOS, and no test covers it. On macOS, write watch protects watched pages withmprotect(Linux uses userfaultfd async WP instead).mach_vm_writedoes not raise the fault the watch handler relies on; it returnsKERN_PROTECTION_FAILURE. In a local check I registered a page withGuestWriteWatchRegister_nid_postfixand armed it with oneCollect:mach_vm_writeinto the page:kr=1, and no write is collected;fstatandsceKernelFstatinto the page through this PR:0,st_sizecorrect, and the page is collected as written;_WIN32:fstatreturns -1/EFAULT andsceKernelFstatreturns0x8002000E, yetguest_fstat_faultstill passes.So a stat buffer in watched (imported GPU) memory would get a spurious EFAULT on macOS if the guard were ever moved or dropped. A small case in
guest_fstat_faultwould catch that on macOS: register and arm a page,fstatinto it, and expect success plus one collected write. It is optional and does not block this PR.Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-23T20:24:20Z.
Review: DISMISSED
The follow-up addresses the safety blockers from my earlier review: non-EFAULT Linux errors no longer fall through to
memcpy, macOS usesmach_vm_write, and the test now covers read-only/PAGE_NOACCESS or PROT_NONE destinations plus Linux seccomp EPERM. The independent macOS report also confirms the focused regression passes there.Two repository-checklist items still need updating before I can approve:
bd2c029ef7) as the tested change and says macOS/read-only destinations were not tested. The follow-up at current headfaa3926cdf5473ae5d3bf1e39b09a1511f2ce37achanges both the implementation and tests. Please refresh Tested with the follow-up results and their exact head/base, including that the macOS validation used the #8658 port branch rather than currentmain.Stdio.cppand proposes preserving both resolver flags, but the checklist still saysDepends on: none. Please agree the merge order with those authors and record the actual dependency/order in the checklist. Preservemodule=truefrom #9478 andarchived=truefrom #7447 when composingResolvePathError_nid_no_patch.I verified this PR alone merges cleanly with current
upstream/main; the requested coordination is for the reported combined conflicts. AI-assisted review.