fix(libkernel): change the protection of guest thread stack pages #2982
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/2982"
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 TheAggie on 2026-10-10T19:29:44Z.
What
On Windows a guest thread runs on its host thread's stack. That stack isn't a registered guest allocation, so
mprotecton any of its pages failed withEINVAL. On the PS5 the stack is ordinary guest memory, and the protection change succeeds.RetroArch's Dolphin core (PPSA99169) hits this at startup:
protect 0x00000000e4f50000+0x10000 prot=0x0withAPS5_TRACE_MEMORY=1.EINVALback and logsWarning - ReadProtectMemory failed!/mprotect: Invalid argument.DoMprotectnow uses the existingGuestThreadStacklookup, the onesceKernelIsStackuses:Tested
New test:
guest_kernel_stack_protect(core/libs/tests/GuestKernelStackProtect.cpp). A guest thread, throughmprotect:VirtualQuerythat the pages arePAGE_NOACCESS;With the
DirectMemory.cppchange reverted, the test fails.Suite:
guest|kernel|memory|pthread|thread|stack|mmap|protect: 243 passed, 1 skipped, 1 failed. The failure isguest_memory, which fails the same way onmainhere (CheckGuestModuleImageProtection'sdlopen).RetroArch: with the Dolphin core and the GameCube 240p Test Suite, the warning is gone and the frame rate is unchanged.
mainalone yet. This run is from my integration branch: amainfrom 2026-10-07 plus my open PRs and others, with this commit cherry-picked unchanged.Setup: Windows 11, MinGW-w64 GCC 15.2.0. Not run on Linux.
Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt.mdfiles or images added to the repository (attach them to this PR)🤖 Generated with Claude Code
Imported from boykopovar/AnyPS5. Originally posted by fma-rc on 2026-10-10T22:00:26Z.
Built 934b986b on main
262c0316on Linux (Arch, GCC 16.2.1, glibc);guest_kernel_stack_protectpasses. Two things showed up when I changed the test:The stack base that
sceKernelIsStackreturns is not page aligned here (start & 0x3fffis 0x3028).mprotect(start, 0x10000, 0)still returns -1 with this change, because the range gets rounded down below the stack and misses the new path. The test roundslowup, so it doesn't see that.If a thread protects 64 KiB at the bottom of its stack with prot 0 and exits without restoring it, the next thread created gets the same stack range (glibc reuses it) and segfaults on a write to those pages. I ran two threads one after the other, the first only doing the
mprotect, the second writing to the same address after checking it is inside its ownsceKernelIsStackrange.Not checked on Windows.
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-10T23:41:57Z.
Review: CHANGES_REQUESTED
Thanks. The approach (reusing
GuestThreadStack) is reasonable, but @fma-rc's Linux findings are real and still open:DirectMemory.cpp:864:sceKernelIsStackcan return a start that isn't page aligned (start & 0x3fff= 0x3028 on Linux).firstis rounded down belowstackStart, somprotect(start, 0x10000, 0)still fails and never reaches the new path. Please decide how a range that touches the partial first page is handled (clamp to the page-aligned interior, or compare after aligning the stack bounds), and make the test callmprotectwith the unroundedstartinstead of roundinglowup (GuestKernelStackProtect.cpp:31).prot=0leaves them protected for the next thread that reuses the same stack (glibc does), which then segfaults on write. The protection needs to be undone when the thread's stack is released (or the call refused where the stack is host-owned), with a test that runs two threads in sequence, the first leaving the range protected.Also please say in the description which of these paths were exercised on Linux, since the change applies there too and the test only had a Windows run.
Imported from boykopovar/AnyPS5. Originally posted by TheAggie on 2026-10-11T00:18:43Z.
Thanks @fma-rc, both are real. Fixed in 2ec306de:
DoMprotectnow checks the range the guest asked for againstGuestThreadStack, not the range after rounding down. It then protects the rounded pages, as FreeBSD rounds the address down. Somprotect(start, 0x10000, 0)withstart & 0x3fff == 0x3028takes the stack path.mprotectof the same pages clears the record. When a thread's stack is unregistered at exit, every recorded range that overlaps it is made readable and writable again. So a reused stack starts clean.guest_kernel_stack_protectnow also protects from the unalignedsceKernelIsStackstart, and runs your two-thread case: one thread leaves its guard in place and exits, and a second thread writes to that address if its own stack covers it.Both cases only show up on Linux. On Windows here the stack base is page-aligned and a new thread never reuses a dead one's stack, so the new checks pass there but can't fail. Could you rerun your two cases on Linux?
AI-assisted (Claude Code).
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-11T07:05:46Z.
Review: CHANGES_REQUESTED
Thanks, the two Linux cases from @fma-rc are covered now. Checked on Linux (PR merged onto main):
guest_kernel_stack_protectpasses and fails with the non-test changes reverted. Remaining points:DirectMemory.cpp:864-867: the range is checked against the stack unrounded, butfirst/bytesare rounded down, so the partial page belowstackStart(not part of the stack;start & 0x3fff == 0x3028on Linux) getsprot=0and is recorded.UnregisterStack(Thread.cpp:150-153) then makes it RW at thread exit, which can drop a guard page or the permissions of whatever neighbours the stack. Please clamp the nativemprotectand the recorded range to the part inside[stackStart, stackEnd)rounded inwards (or only record/restore pages fully inside the stack), and add a test that the page just belowstartkeeps its protection.Thread.cpp:152:RestoreStackPagescan throw whilestackLockis held, from the thread-exit path. Failing to restore at exit shouldn't unwind there; ignore/log the error and keep going so the lock is released and the entry removed.Imported from boykopovar/AnyPS5. Originally posted by TheAggie on 2026-10-11T07:36:29Z.
Thanks @adriadam10. All three are in
f38408ef, on top of a rebase ontomain5c7ceb07:[stackStart, stackEnd). The start is rounded up and the end rounded down to 4 KiB, and both the nativemprotectand the recorded range use that. If nothing is left, the call returns 0 without changing anything. So the page that holdsstackStart - 1is never protected, recorded or restored.RestoreStackPagesisnoexceptnow. If the host call fails it prints one line to stderr and the loop carries on, sostackLockis released and the entry is removed either way./proc/self/mapson Linux,VirtualQueryon Windows). That doesn't depend on the allocator. The second-thread write is still there as well.The test also reads the protection of the byte at
start - 1before and aftermprotect(start, 0x10000, 0)and after setting it back, and requires it unchanged.On Windows the stack base is page-aligned, so the
start - 1check passes with or without the clamp here; it can only fail on Linux.guest_kernel_stack_protectand theguest_pthread*,guest_thread*andguest_signaltests pass on Windows 11. Could you rerun it on Linux, with the clamp reverted too?AI-assisted (Claude Code).
Imported from boykopovar/AnyPS5. Originally posted by fma-rc on 2026-10-11T07:39:05Z.
Reran on Linux (Arch, GCC 16.2.1, glibc) at
f38408ef, built on its own base:guest_kernel_stack_protectpasses 10 of 10 repeats, and it aborts when I putDirectMemory.cpp,Pthread.hppandThread.cppback to the merge base.With a temporary print in the test, five runs:
start & 0x3fffis 0x2c28 andmprotect(start, 0x10000, 0)returns 0. In every run the second thread got the first one's stack range (samesceKernelIsStackstart), its stack covered the guard address and the write happened, so the reuse case is really exercised here.One thing about the test:
WriteLeftGuardonly writes when the stack covers the address and nothing checks that it did, so on a host that does not reuse the range that part passes without testing anything.Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-11T07:52:01Z.
Review: APPROVED
Checked on Linux (PR merged onto main):
guest_kernel_stack_protectpasses 10/10 and fails with the non-test changes reverted. Confirmed by @fma-rc on Arch/glibc, including the stack-reuse case. The partial page below the stack and the restore at thread exit are both handled now; merging.Non-blocking:
WriteLeftGuarddoesn't assert that its stack covered the guard address, so on a host that doesn't reuse the range that part tests nothing. Windows behaviour (VirtualQuery/VirtualProtect) is taken from the author's run.Imported from boykopovar/AnyPS5. Originally posted by orishamir on 2026-10-11T09:55:14Z.
guest_kernel_stack_protectaborts in CI'slinuxjob in every completed run since this merged (38124809181 at 08:26Z through 38128072167 at 09:21Z; the 06:09Z run predates the merge), asSubprocess abortedright after the worker thread starts. It reproduces in a replica of the job (ubuntu 24.04, GCC 13.3, glibc 2.39;maina73a1af9andccf9ff90), 4/4, and it does not depend on #1423 (not in the first failing run) or #3227 (already in the base @fma-rc's Arch run passed on).Under gdb the abort comes from libc's own unwinder resuming the exception the test expects:
So the throw from
replaceRangereaches its cleanup landing pad in the GCC 13 cold partition (.text0x21eee..0x220d6 inlibc.prx, which has its own FDE with a plaindef_cfa_offset 224and six callee-saved offsets) and_Unwind_Resumecannot step from there toGuestAllocationsProtect. With GCC 16 on Arch the test passes 10/10 per the comment above, so it is the unwinder against GCC 13's code for this function, not the stack logic; rebuilding onlyGuestAllocations.cppwith-fno-reorder-blocks-and-partitiondid not change the result in my replica, so I have no fix to suggest, only the stop and the frames.AI-assisted: yes (Claude Code Fable 5.1 xhigh)