fix(libkernel): skip the host-only pages around a guest thread stack in mprotect on Linux #15040

Open
Ragbie wants to merge 11 commits from upstream-pr/15040 into main
Ragbie commented 2026-11-02 11:42:45 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Ragbie on 2026-11-02T11:42:45Z.


What

On Linux, mprotect and sceKernelMprotect over the host-only pages around a guest thread's stack now return 0 and leave those pages unchanged. Before, they returned -1 with EACCES. The sceKernelMprotect debt entry recorded the gap ("On Linux a range over the host-only pages around a guest thread's stack still fails with EACCES, where Windows returns 0"), and the #9882 discussion left the Linux return of the straddling range as a follow-up.

The same debt entry records the PS5 (firmware 13.60) measurement: mprotect and sceKernelMprotect change the mapped parts of a range, skip its gaps and return 0. On FreeBSD 11.4, libthr places the stack guard in the stack's own mapping (thr_stack.c), so on the console the pages around a thread stack are guest memory.

On Linux a guest thread's stack is a guest allocation (AllocateGuestStack) that the host thread runs on. The guard, the spare host stack below the guest stack and the host's frames above it are host-only. 9b6e7f66c4 keeps the guest from changing them by refusing any range that touches them. This PR treats them as gaps instead:

  • GuestThreadStackHostRanges returns the host-only ranges a range meets. GuestThreadStackHostRangeOverlaps is built on it.
  • DoMprotect cuts the request around those ranges and protects the parts beside them.
  • A part inside a guest stack goes through the existing stack path, which works on host pages, so its precision is unchanged.
  • Any other part (a GPU protection bit, or a thread that is starting or exiting) goes through the general path, which rounds to 16 KiB. Such a part is first shrunk away from any 16 KiB page that holds host bytes, so the rounding cannot reach them.
  • The batch map and memory pool protect operations, which require a mapped start, return EINVAL when the range starts in a skipped page, as for an unmapped start.
  • The general-path parts are handled in one registry mutation: every span of every part is checked for a pin before the first is protected, as the single-range path did.

The debt entry now states what is left: those pages are skipped where the console's guard takes the protection.

Tested

guest_kernel_stack_protect:

  • Linux: a protect of the host guard page below a guest thread stack returns 0 and leaves the page unchanged (was -1).
  • All hosts: the range that straddles the bottom of the stack returns 0 (Windows already checked this; the Linux return was unchecked) and leaves the page below the stack unchanged.
  • Linux: a read-only protect of a three-page range starting below the stack makes the stack page inside it read-only.
  • All hosts: the straddling range with a GPU read bit (0x11) leaves the page below the stack unchanged.
  • Linux: a pinned later part. A guest page is mapped just below the stack's mapping and the stack's registry range is held, so it counts as pinned. A 0x11 protect from that page into the stack splits into two general-path parts around the host guard. The pin waiter hook records whether the earlier page already changed when the pin is found, then releases the pin. The test requires the earlier page unchanged at that point, and both parts protected after the call returns 0.

Linux (Ubuntu 24.04 container, GCC 13.3.0):

  • Without the fix: GuestKernelStackProtect failed at line 235 (the host guard page returns -1).
  • First version of the fix, which let the general path round over host pages: the GPU-bit case failed at line 268. Kept as the reason for the shrink.
  • Per-part pin checks (4c52e758e0) with the new test: GuestKernelStackProtect failed at line 254. The waiter ran (line 253 passed), but the earlier part had already been protected.
  • With the fix, rebased on 28a71b481e: of the 239 tests matching mprotect|memory|stack|pthread|mmap|thread|mtype|apr|ampr|flexible|pool|mlock|protection outside agc, all pass. guest_mmap_executable skips itself.

Linux ASan + UBSan (flags of the Sanitizers workflow, same container, ASLR off with setarch -R), guest_kernel_stack_protect, 30 runs each:

  • Before 9bda0c0326: 30 of 30 fail at line 245. The worker stack sits at the start of the guest arena, so no guest page can be mapped below it.
  • With 9bda0c0326: 30 of 30 pass. The test maps a guest page before it starts the worker, so the worker stack lies above the arena start, and unmaps that page before the check.

Windows 11 Pro, Intel Core i5-14600KF, NVIDIA GPU, WinLibs GCC 15.2.0, full Release build with libs, base 28a71b481e:

  • Full ctest: 99% tests passed, 8 tests failed out of 6249. None of them is caused by this branch:
    • performance_bisect fails with WinError 1314, because this user cannot create symbolic links.
    • agc_driver_upload_cache_read_only_flush is not built: UploadCacheReadOnlyFlush.cpp calls setenv, which main does not declare on Windows (#19899, #22373 and #22634 fix it).
    • agc_driver_image_plane_address_on_line, agc_driver_image_sample_lod_clamp and agc_driver_stencil_plane_memory also fail on the base commit. agc_driver_image_sample_lod_clamp_shader_lane and agc_driver_msaa_dcc_unwatch also fail with the base commit's libraries.
    • agc_driver_store_over_untracked is intermittent on the base commit too: it fails 26 of 40 runs there and 26 of 40 and 30 of 40 on this branch, with the same message.

macOS: not tested. GuestThreadStackHostRanges returns no ranges there, so DoMprotect keeps its path; the GPU-bit case runs there as on Windows.

The three-page read-only case is Linux-only because Windows skips the whole straddling range: the host thread stack is not in the guest allocation registry, so the stack part is not protected either. That is a separate Windows gap and goes in its own PR.

Overlaps: #7149 and #7631 also change DoMprotect; both conflict with main already, and a trial merge with this branch conflicts in the same files only. #14466, #9684 and #7532 merge with this branch without conflicts (git merge-tree). #16401 adds #include <vector> at the same line of Pthread.hpp; whichever lands second keeps both includes, so either order works. #18314 is merged: the parts now share the address the caller asked for, so a foreign image is still refused only where that address lies.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5119731642 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/15040). Originally posted by [Ragbie](https://github.com/Ragbie) on 2026-11-02T11:42:45Z. --- ### What On Linux, `mprotect` and `sceKernelMprotect` over the host-only pages around a guest thread's stack now return 0 and leave those pages unchanged. Before, they returned -1 with `EACCES`. The `sceKernelMprotect` debt entry recorded the gap ("On Linux a range over the host-only pages around a guest thread's stack still fails with `EACCES`, where Windows returns 0"), and the #9882 discussion left the Linux return of the straddling range as a follow-up. The same debt entry records the PS5 (firmware 13.60) measurement: `mprotect` and `sceKernelMprotect` change the mapped parts of a range, skip its gaps and return 0. On FreeBSD 11.4, libthr places the stack guard in the stack's own mapping ([`thr_stack.c`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/lib/libthr/thread/thr_stack.c#L273-L279)), so on the console the pages around a thread stack are guest memory. On Linux a guest thread's stack is a guest allocation (`AllocateGuestStack`) that the host thread runs on. The guard, the spare host stack below the guest stack and the host's frames above it are host-only. 9b6e7f66c4 keeps the guest from changing them by refusing any range that touches them. This PR treats them as gaps instead: - `GuestThreadStackHostRanges` returns the host-only ranges a range meets. `GuestThreadStackHostRangeOverlaps` is built on it. - `DoMprotect` cuts the request around those ranges and protects the parts beside them. - A part inside a guest stack goes through the existing stack path, which works on host pages, so its precision is unchanged. - Any other part (a GPU protection bit, or a thread that is starting or exiting) goes through the general path, which rounds to 16 KiB. Such a part is first shrunk away from any 16 KiB page that holds host bytes, so the rounding cannot reach them. - The batch map and memory pool protect operations, which require a mapped start, return `EINVAL` when the range starts in a skipped page, as for an unmapped start. - The general-path parts are handled in one registry mutation: every span of every part is checked for a pin before the first is protected, as the single-range path did. The debt entry now states what is left: those pages are skipped where the console's guard takes the protection. ### Tested `guest_kernel_stack_protect`: - **Linux:** a protect of the host guard page below a guest thread stack returns 0 and leaves the page unchanged (was `-1`). - **All hosts:** the range that straddles the bottom of the stack returns 0 (Windows already checked this; the Linux return was unchecked) and leaves the page below the stack unchanged. - **Linux:** a read-only protect of a three-page range starting below the stack makes the stack page inside it read-only. - **All hosts:** the straddling range with a GPU read bit (`0x11`) leaves the page below the stack unchanged. - **Linux:** a pinned later part. A guest page is mapped just below the stack's mapping and the stack's registry range is held, so it counts as pinned. A `0x11` protect from that page into the stack splits into two general-path parts around the host guard. The pin waiter hook records whether the earlier page already changed when the pin is found, then releases the pin. The test requires the earlier page unchanged at that point, and both parts protected after the call returns 0. Linux (Ubuntu 24.04 container, GCC 13.3.0): - **Without the fix:** `GuestKernelStackProtect failed at line 235` (the host guard page returns -1). - **First version of the fix, which let the general path round over host pages:** the GPU-bit case failed at line 268. Kept as the reason for the shrink. - **Per-part pin checks (`4c52e758e0`) with the new test:** `GuestKernelStackProtect failed at line 254`. The waiter ran (line 253 passed), but the earlier part had already been protected. - **With the fix, rebased on `28a71b481e`:** of the 239 tests matching `mprotect|memory|stack|pthread|mmap|thread|mtype|apr|ampr|flexible|pool|mlock|protection` outside `agc`, all pass. `guest_mmap_executable` skips itself. Linux ASan + UBSan (flags of the Sanitizers workflow, same container, ASLR off with `setarch -R`), `guest_kernel_stack_protect`, 30 runs each: - **Before `9bda0c0326`:** 30 of 30 fail at line 245. The worker stack sits at the start of the guest arena, so no guest page can be mapped below it. - **With `9bda0c0326`:** 30 of 30 pass. The test maps a guest page before it starts the worker, so the worker stack lies above the arena start, and unmaps that page before the check. Windows 11 Pro, Intel Core i5-14600KF, NVIDIA GPU, WinLibs GCC 15.2.0, full Release build with `libs`, base `28a71b481e`: - Full `ctest`: `99% tests passed, 8 tests failed out of 6249`. None of them is caused by this branch: - `performance_bisect` fails with `WinError 1314`, because this user cannot create symbolic links. - `agc_driver_upload_cache_read_only_flush` is not built: `UploadCacheReadOnlyFlush.cpp` calls `setenv`, which `main` does not declare on Windows (#19899, #22373 and #22634 fix it). - `agc_driver_image_plane_address_on_line`, `agc_driver_image_sample_lod_clamp` and `agc_driver_stencil_plane_memory` also fail on the base commit. `agc_driver_image_sample_lod_clamp_shader_lane` and `agc_driver_msaa_dcc_unwatch` also fail with the base commit's libraries. - `agc_driver_store_over_untracked` is intermittent on the base commit too: it fails 26 of 40 runs there and 26 of 40 and 30 of 40 on this branch, with the same message. macOS: not tested. `GuestThreadStackHostRanges` returns no ranges there, so `DoMprotect` keeps its path; the GPU-bit case runs there as on Windows. The three-page read-only case is Linux-only because Windows skips the whole straddling range: the host thread stack is not in the guest allocation registry, so the stack part is not protected either. That is a separate Windows gap and goes in its own PR. **Overlaps:** #7149 and #7631 also change `DoMprotect`; both conflict with `main` already, and a trial merge with this branch conflicts in the same files only. #14466, #9684 and #7532 merge with this branch without conflicts (`git merge-tree`). #16401 adds `#include <vector>` at the same line of `Pthread.hpp`; whichever lands second keeps both includes, so either order works. #18314 is merged: the parts now share the address the caller asked for, so a foreign image is still refused only where that address lies. ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: <!-- #PR, or none --> none - [x] Fixes: <!-- issue it closes as Fixes #N, or none --> none - [x] Unblocks: <!-- title ID and Game bring-up discussion, e.g. PPSA01325 #3232, or none --> none - [x] GPUs tested: <!-- for AGC, shader recompiler or VideoOut changes: vendor, model, driver and OS of each GPU the GPU tests ran on; otherwise n/a --> n/a - [x] AI-assisted: <!-- yes / no --> yes
mashingaan commented 2026-11-02 11:45:09 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by mashingaan on 2026-11-02T11:45:09Z.

Review: CHANGES_REQUESTED


I found a pin-safety regression in the split protection path. The existing single-range path gathers every registered span and calls RequireUnpinned on all of them before the first protection change. Here each part is sent through ProtectGuestRange separately, and each recursive call checks and then protects its own spans. If a later part beyond a host-stack gap is pinned, the call can fail after an earlier part has already changed protection. Please preflight all surviving spans across every part before applying any protection, and add a focused regression for a pinned later span.

The affected call is core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp:1463 at head 4c52e758e0b9f2f6c39833871cc1bb6d4bdab525.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5736035100 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/15040#pullrequestreview-5736035100). Originally posted by [mashingaan](https://github.com/mashingaan) on 2026-11-02T11:45:09Z. **Review:** CHANGES_REQUESTED --- I found a pin-safety regression in the split protection path. The existing single-range path gathers every registered span and calls `RequireUnpinned` on all of them before the first protection change. Here each part is sent through `ProtectGuestRange` separately, and each recursive call checks and then protects its own spans. If a later part beyond a host-stack gap is pinned, the call can fail after an earlier part has already changed protection. Please preflight all surviving spans across every part before applying any protection, and add a focused regression for a pinned later span. The affected call is `core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp:1463` at head `4c52e758e0b9f2f6c39833871cc1bb6d4bdab525`.
MarcZX10 commented 2026-11-20 21:25:57 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-20T21:25:57Z.

Review: APPROVED


Reviewed — looks good

The reviewed change is consistent with its stated goal and I found no blocking defects in the changed code.

What I ran

Reviewed head 9bda0c03264d407581859e0dc552b448b5df9098 against base main using repo_read.py to inspect the prepared diff and targeted source context. No shell commands, builds, or tests were run in this review.

Results

Check Result Note
Changed code review passed All five changed files reviewed
Build and tests not run Author-reported results were not rerun

Findings

Blocking

None.

Non-blocking

None.

Not verified

Runtime behavior and test results were not independently verified. The author reports Linux and Windows test runs; macOS and physical-console behavior were not tested. The changed files reviewed were core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp, core/libs/prx/libkernel/Pthread/include/Pthread.hpp, core/libs/prx/libkernel/Pthread/src/Thread.cpp, core/libs/tests/GuestKernelStackProtect.cpp, and docs/dev/debt/libkernel.md. No changed files were excluded.

To get this to a good state

Nothing is required.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5999627647 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/15040#pullrequestreview-5999627647). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-20T21:25:57Z. **Review:** APPROVED --- # Reviewed — looks good The reviewed change is consistent with its stated goal and I found no blocking defects in the changed code. ## What I ran Reviewed head `9bda0c03264d407581859e0dc552b448b5df9098` against base `main` using `repo_read.py` to inspect the prepared diff and targeted source context. No shell commands, builds, or tests were run in this review. ## Results | Check | Result | Note | |---|---|---| | Changed code review | passed | All five changed files reviewed | | Build and tests | not run | Author-reported results were not rerun | ## Findings ### Blocking None. ### Non-blocking None. ## Not verified Runtime behavior and test results were not independently verified. The author reports Linux and Windows test runs; macOS and physical-console behavior were not tested. The changed files reviewed were `core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp`, `core/libs/prx/libkernel/Pthread/include/Pthread.hpp`, `core/libs/prx/libkernel/Pthread/src/Thread.cpp`, `core/libs/tests/GuestKernelStackProtect.cpp`, and `docs/dev/debt/libkernel.md`. No changed files were excluded. ## To get this to a good state Nothing is required.
MarcZX10 commented 2026-11-25 12:42:30 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-25T12:42:30Z.

Review: APPROVED


Reviewed — looks good

Nothing blocks this change; I found no verified blocking defect in the changed code.

What I ran

Reviewed head e9b10a8e1d7d684acdb166c30a0cda15686b83dc. I inspected the prepared diff and all five changed files listed as reviewed in the manifest. No commands or tests were run in this review; test results below are author-reported.

Results

Check Result Note
Diff and source review passed All changed files reviewed
Reported Linux tests not run Author reports targeted tests passed
Reported Windows tests not run Author reports known base failures
macOS and console behavior not run Not confirmed in this review

Findings

Blocking

None.

Non-blocking

None.

Not verified

I did not run tests or builds and did not independently verify the author-reported Linux, Windows, or firmware results. No changed files were excluded: DirectMemory.cpp, Pthread.hpp, Thread.cpp, GuestKernelStackProtect.cpp, and libkernel.md were all read; files.json was not available in the prepared review listing, so its excluded-file list was not independently checked.

To get this to a good state

Nothing is required.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6057798211 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/15040#pullrequestreview-6057798211). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-25T12:42:30Z. **Review:** APPROVED --- # Reviewed — looks good Nothing blocks this change; I found no verified blocking defect in the changed code. ## What I ran Reviewed head `e9b10a8e1d7d684acdb166c30a0cda15686b83dc`. I inspected the prepared diff and all five changed files listed as reviewed in the manifest. No commands or tests were run in this review; test results below are author-reported. ## Results | Check | Result | Note | |---|---|---| | Diff and source review | passed | All changed files reviewed | | Reported Linux tests | not run | Author reports targeted tests passed | | Reported Windows tests | not run | Author reports known base failures | | macOS and console behavior | not run | Not confirmed in this review | ## Findings ### Blocking None. ### Non-blocking None. ## Not verified I did not run tests or builds and did not independently verify the author-reported Linux, Windows, or firmware results. No changed files were excluded: `DirectMemory.cpp`, `Pthread.hpp`, `Thread.cpp`, `GuestKernelStackProtect.cpp`, and `libkernel.md` were all read; `files.json` was not available in the prepared review listing, so its excluded-file list was not independently checked. ## To get this to a good state Nothing is required.
ligmaSec commented 2026-12-03 13:16:33 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ligmaSec on 2026-12-03T13:16:33Z.

Review: COMMENTED


Checked the branch sources and built the focused tests against the existing Linux runtime. GuestKernelStackProtect passed.

AI-assisted: yes.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6170527799 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/15040#pullrequestreview-6170527799). Originally posted by [ligmaSec](https://github.com/ligmaSec) on 2026-12-03T13:16:33Z. **Review:** COMMENTED --- Checked the branch sources and built the focused tests against the existing Linux runtime. `GuestKernelStackProtect` passed. AI-assisted: yes.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/15040:upstream-pr/15040'
git switch 'upstream-pr/15040'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/15040'
git switch 'upstream-pr/15040'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/15040'
git switch 'upstream-pr/15040'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/15040'
git switch 'main'
git merge --squash 'upstream-pr/15040'
git switch 'main'
git merge --ff-only 'upstream-pr/15040'
git switch 'main'
git merge 'upstream-pr/15040'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!15040
No description provided.