Repository navigation
fix(libkernel): fail the stat family with EFAULT when the output struct is not writable guest memory - #9618
Conversation
jotitadev
left a comment
There was a problem hiding this comment.
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. Head bd2c029ef merged --no-commit onto main 17f533556 (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:output pointer result start of a PROT_READpagefstat-1/EFAULT,stat-1/EFAULT,sceKernelFstat0x8002000e,_fstatfs-1. No crash.start of a PROT_NONEpagefstat-1/EFAULT16 bytes before a PROT_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.
|
Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.
|
There was a problem hiding this comment.
The main fix is well targeted: metadata is filled into local FileStat/KernelStatfs values, 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 than EFAULT can fall back to unchecked memcpy. 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.
|
@xXPBSXx a merge-order note: #9478 changes the same |
There was a problem hiding this comment.
I withdraw the earlier #5239 intake-hold objection. I rechecked exact head bd2c029ef713a8d1cbbb582dc5a621e39fa0d207 against current main 3ca07d086d5f44fbe3c00370e7f03953ab46ca1b: 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_patch falls through to memcpy. GuestArenaBeginHostWrite_nid_postfix returns 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, every process_vm_writev error other than EFAULT falls back to memcpy. Errors such as EPERM (for example, syscall filtering) and ENOSYS do 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 base 17f533556272e5f6833ed730172f12308eee08d2 is 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 shared Stdio.cpp comparison is incomplete because it conflicts with main. The author's proposed merge order is reasonable, but preserve the ResolvePathError_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.
adriadam10
left a comment
There was a problem hiding this comment.
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.- Merge order with #9478: keep the
moduleflag inlstat'sResolvePathError_nid_no_patch(path, native, true)when you rebase over it.
Please also rebase onto current main and rerun the focused tests.
|
I’ve noticed that my earlier request to hold this PR based on #5239 was unnecessary. It’s fine to keep submitting PRs; maintainers will handle them in due course. Please disregard that request. |
MarcZX10
left a comment
There was a problem hiding this comment.
Blocking correctness issue: GuestCopyOut_nid_no_patch can still fault instead of returning EFAULT on non-Windows hosts. On Linux, when process_vm_writev fails with anything other than EFAULT (for example EPERM under seccomp or ENOSYS), lines 706–709 fall back to std::memcpy; the non-Linux/non-Windows branch at lines 712–714 always does so. GuestArenaBeginHostWrite_nid_postfix does 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-EFAULT syscall failure and the macOS path before considering this fixed.
|
@adriadam10 @MarcZX10 thanks, both points are addressed in a follow-up commit (no force-push):
AI-assisted (Claude Code). |
jotitadev
left a comment
There was a problem hiding this comment.
macOS run of the new mach_vm_write branch (listed as not tested).
Mac M2 Max, macOS 27.2, Apple clang, x86_64 under Rosetta, Release. main does not build libc/libkernel on macOS yet, so the tree is #8658 (feat/macos-port) @ dc0c8db merged with this PR @ faa3926 (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.- Red/green: with
GuestCopyOut_nid_no_patchput back to the bd2c029 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 HostWrite guard before mach_vm_write is required on macOS, and no test covers it. On macOS, write watch protects watched pages with mprotect (Linux uses userfaultfd async WP instead). mach_vm_write does not raise the fault the watch handler relies on; it returns KERN_PROTECTION_FAILURE. In a local check I registered a page with GuestWriteWatchRegister_nid_postfix and armed it with one Collect:
- raw
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;- the same with the guard limited to
_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_fault would catch that on macOS: register and arm a page, fstat into 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.
|
My earlier note that #9478 "touches different lines, so there is no overlap" was wrong, and I had not run a merge check against #9478 when I wrote it. I have measured it now with
On the order proposed above: either order works for this PR. If #9478 lands first, I rebase this PR and keep the AI-assisted (Claude Code). |
|
@xXPBSXx thanks for measuring it. Since either order works, let's have this PR go first: #9478 is the one-line change, so it re-applies |
MarcZX10
left a comment
There was a problem hiding this comment.
The follow-up addresses the safety blockers from my earlier review: non-EFAULT Linux errors no longer fall through to memcpy, macOS uses mach_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:
- The PR body still describes the first commit (
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. - The overlap discussion on this PR records a merge conflict with open #9478 and #7447 in
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.
|
Thanks @MarcZX10, both items are updated.
AI-assisted (Claude Code). |
Dismissing a stale review: the requested changes were addressed after it (new head and/or updated description with the asked-for runs) and the merge queue blocks on it. Please request changes again if anything is still open.
…ct is not writable guest memory fstat, _fstat, sceKernelFstat, stat, lstat, sceKernelStat and _fstatfs filled the caller's struct in place, or copied into it after a check that only tests for null, so a pointer into unmapped memory crashed the host. Fill a local struct and copy it out with a checked write that fails with EFAULT. FreeBSD 11.4 does the same after the lookup has succeeded: copyout(&ub, uap->sb) in sys_fstat (sys/kern/kern_descrip.c:1328), copyout(&sb, uap->ub) in sys_stat (sys/kern/vfs_syscalls.c:2066) and copyout(sfp, uap->buf) in sys_fstatfs (sys/kern/vfs_syscalls.c:337). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…t errors GuestCopyOut_nid_no_patch fell back to memcpy when process_vm_writev failed with anything but EFAULT, and on every non-Linux/non-Windows host. Throw instead (macOS uses mach_vm_write as Udp.cpp does) and cover read-only and PROT_NONE pages plus a seccomp EPERM child in guest_fstat_fault. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
faa3926 to
c424bd1
Compare
|
Re-checked after the rebase: the source hunks are unchanged ( |
Main's #9618 has lstat fill a local FileStat and copy it out to the guest. The merge keeps that and this branch's module lookup in the same call, so an original .prx name still resolves to its relinked .guest.prx.
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 feat: macOS host support (Apple Silicon via Rosetta 2, Vulkan on MoltenVK) #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