fix(libc): forward writes to truncated macOS mappings #12435

Merged
plexerPK merged 2 commits from upstream-pr/12435 into main 2026-10-30 05:41:07 +00:00
plexerPK commented 2026-10-28 13:31:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by plexerPK on 2026-10-28T13:31:24Z.


What

A CPU store into a watched MAP_SHARED mapping can loop in the macOS signal handler after ftruncate removes its backing. The handler keeps accepting the fault because the recorded page permissions include write access, even though retrying cannot succeed.

Check mprotect before marking a protected page writable. For a fault on an already-writable watched page, use mach_vm_read_overwrite to probe the fault address without recursively dereferencing unavailable backing in the handler. Failed probes forward the original fault. This preserves legitimate delayed faults from concurrent writers; the normal first-write path does not perform a Mach copy.

This follow-up includes the prerequisite changes from #12117 and removes its resolved truncation debt entry. No foreign PR implementation is included. Current-main baseline: 750cf6cf48.

Ownership: inspected all 1,336 open PRs before implementation and refreshed the inventory to 1,343 before publication. #12117 is our prerequisite; #11801 changes forwarding of user-generated signals; #7192 exposes HandleFault. Neither implements backing validation or checks failed protection restoration. No competing truncation fix found.

Tested

macOS 27.0.1, Apple clang 21, native arm64 Release; tests compile the actual GuestWriteWatch.cpp:

  • All 17 standalone CTest cases pass, including three consecutive suite runs.
  • 32 truncation combinations compare watched writes with unwatched native controls: shared/private, read-write/write-only permissions, fresh/armed state, host-write scope, and truncation to zero/one page. Private mappings remain writable on this host and retain correct dirty tracking.
  • 16 intact-mapping controls check successful writes and dirty-page collection.
  • 32 forced pairs of delayed concurrent faults per run check that a second writer arriving after protection restoration still completes. This test and the existing concurrent-writer test each pass 20 consecutive runs.
  • Red control: build the same new tests against the pre-fix production source (prerequisite #12117 applied to current main). Shared truncation and failed mprotect restoration both fail because the child reaches SIGALRM instead of delivering its memory fault. Private, writable, and late-fault controls pass. All five groups pass with this fix.
  • Both standalone executables also compile/link for x86_64. Intel/Rosetta execution of this new change is not available locally; no x86 runtime claim. No full libc/game or GPU execution claim.
  • check_conventions.py and git diff --check pass. Official pr_overlap.py inspected 1,342 open PRs; its incomparable #7192 source diff was reviewed manually. A final 1,343-PR file inventory confirmed the same relevant overlaps. #12117 is the declared prerequisite.

Reproduce: cmake -S core/libs/tests/write_watch -B build-write-watch -DCMAKE_BUILD_TYPE=Release, cmake --build build-write-watch, ctest --test-dir build-write-watch --output-on-failure.

Checklist

  • Based on current main; no other open PR implements the same functions
    • Intentional prerequisite overlap with #12117; no other PR implements this truncation fix.
  • 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: #12117
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5051334020 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12435). Originally posted by [plexerPK](https://github.com/plexerPK) on 2026-10-28T13:31:24Z. --- ### What A CPU store into a watched MAP_SHARED mapping can loop in the macOS signal handler after ftruncate removes its backing. The handler keeps accepting the fault because the recorded page permissions include write access, even though retrying cannot succeed. Check mprotect before marking a protected page writable. For a fault on an already-writable watched page, use mach_vm_read_overwrite to probe the fault address without recursively dereferencing unavailable backing in the handler. Failed probes forward the original fault. This preserves legitimate delayed faults from concurrent writers; the normal first-write path does not perform a Mach copy. This follow-up includes the prerequisite changes from #12117 and removes its resolved truncation debt entry. No foreign PR implementation is included. Current-main baseline: 750cf6cf487f948017295b1f3717af6f886f0f85. Ownership: inspected all 1,336 open PRs before implementation and refreshed the inventory to 1,343 before publication. #12117 is our prerequisite; #11801 changes forwarding of user-generated signals; #7192 exposes HandleFault. Neither implements backing validation or checks failed protection restoration. No competing truncation fix found. ### Tested macOS 27.0.1, Apple clang 21, native arm64 Release; tests compile the actual GuestWriteWatch.cpp: - All 17 standalone CTest cases pass, including three consecutive suite runs. - 32 truncation combinations compare watched writes with unwatched native controls: shared/private, read-write/write-only permissions, fresh/armed state, host-write scope, and truncation to zero/one page. Private mappings remain writable on this host and retain correct dirty tracking. - 16 intact-mapping controls check successful writes and dirty-page collection. - 32 forced pairs of delayed concurrent faults per run check that a second writer arriving after protection restoration still completes. This test and the existing concurrent-writer test each pass 20 consecutive runs. - Red control: build the same new tests against the pre-fix production source (prerequisite #12117 applied to current main). Shared truncation and failed mprotect restoration both fail because the child reaches SIGALRM instead of delivering its memory fault. Private, writable, and late-fault controls pass. All five groups pass with this fix. - Both standalone executables also compile/link for x86_64. Intel/Rosetta execution of this new change is not available locally; no x86 runtime claim. No full libc/game or GPU execution claim. - check_conventions.py and git diff --check pass. Official pr_overlap.py inspected 1,342 open PRs; its incomparable #7192 source diff was reviewed manually. A final 1,343-PR file inventory confirmed the same relevant overlaps. #12117 is the declared prerequisite. Reproduce: `cmake -S core/libs/tests/write_watch -B build-write-watch -DCMAKE_BUILD_TYPE=Release`, `cmake --build build-write-watch`, `ctest --test-dir build-write-watch --output-on-failure`. <!-- OS, title or homebrew, what was checked. "Not tested" is a valid answer. A performance change: the summary lines of main and of this PR from the same machine and scene, with the traces attached, captured as the Performance report issue form describes. --> ### 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 - Intentional prerequisite overlap with #12117; no other PR implements this truncation fix. - [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 --> #12117 - [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
rooklz commented 2026-10-28 15:04:00 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by rooklz on 2026-10-28T15:04:00Z.

Review: COMMENTED


Review of head 1f1da4b0ff on macOS 26, Apple clang, AI-assisted. I only had the host, no console. I ran the standalone core/libs/tests/write_watch project the way the body describes, plus the x86_64 run the body says it could not do.

Results

  • Head passes 17/17 on native arm64 Release and on x86_64 under Rosetta (-DCMAKE_OSX_ARCHITECTURES=x86_64). No build warnings. late and threads also passed 5 back-to-back runs on x86_64.
  • Head passes 17/17 under ASan+UBSan (Debug, arm64) with ASAN_OPTIONS=handle_segv=0:handle_sigbus=0:allow_user_segv_handler=1. Without those options, backing_shared, backing_restore, execute-fault and read-fault fail. That's because ASan's own SIGBUS report makes the child exit instead of dying by signal, so it comes from the test harness, not the code.
  • Red control: I put back the GuestWriteWatch.cpp from eb20686c42 (the #12117 prerequisite; that file, WriteWatch.cpp and the write_watch CMakeLists are identical to #12117's) under the new tests. Only write_watch_backing_shared and write_watch_backing_restore fail, on both arm64 and x86_64. That matches the body.
  • check_conventions passes, and git merge-tree against main 17f8dfad51 is clean.

Mutants (both arches give the same result)

mutant result
back to the unchecked ::mprotect(...) killed by backing_restore
probe always return true killed by backing_shared (hang until SIGALRM)
probe always return false killed by backing_late (bus error: the delayed second writer gets forwarded)
isWriteFault dropped from fault() killed by execute-fault
drop && copied == sizeof(value) survives. I think it's equivalent, since copied is always the full size when the call returns KERN_SUCCESS
set state = ...Written before the mprotect check survives

The last survivor is minor. If restoring protection fails, the page has already been marked Written with Protected cleared, so the next Collect reports a page that was never written. The PR's ordering is correct; nothing tests it. Checking in backing_restore that the page is still unreported after a failed restore would cover it. Not blocking.

Scope note (not blocking, not a regression)
The new probe checks that the page is readable, not that it is writable. I mapped and registered a page as RW, wrote to it, then called plain ::mprotect(page, PROT_READ) without going through GuestWriteWatchProtect, then wrote again. The process hangs until alarm fires (rc 142) on head and on the eb20686c42 base. The recorded state still contains PROT_WRITE, and mach_vm_read_overwrite succeeds on a readable page. Guest mprotect goes through DirectMemory → GuestWriteWatchProtect, so only host-side code that changes protection directly can reach this, and that's outside this PR's truncation topic. If you want to close it later, asking mach_vm_region for the current protection, or doing a one-byte mach_vm_write back of the probed byte, would test writability itself.

So, COMMENT rather than APPROVE: the change is correct and both of its new checks are covered by tests. I'm not approving because it stacks on #12117, which has no reviews yet, and I didn't run the full libs lane.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5684852831 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12435#pullrequestreview-5684852831). Originally posted by [rooklz](https://github.com/rooklz) on 2026-10-28T15:04:00Z. **Review:** COMMENTED --- Review of head 1f1da4b0ff on macOS 26, Apple clang, AI-assisted. I only had the host, no console. I ran the standalone `core/libs/tests/write_watch` project the way the body describes, plus the x86_64 run the body says it could not do. **Results** - Head passes 17/17 on native arm64 Release and on **x86_64 under Rosetta** (`-DCMAKE_OSX_ARCHITECTURES=x86_64`). No build warnings. `late` and `threads` also passed 5 back-to-back runs on x86_64. - Head passes 17/17 under ASan+UBSan (Debug, arm64) with `ASAN_OPTIONS=handle_segv=0:handle_sigbus=0:allow_user_segv_handler=1`. Without those options, `backing_shared`, `backing_restore`, `execute-fault` and `read-fault` fail. That's because ASan's own SIGBUS report makes the child exit instead of dying by signal, so it comes from the test harness, not the code. - Red control: I put back the GuestWriteWatch.cpp from eb20686c42 (the #12117 prerequisite; that file, WriteWatch.cpp and the write_watch CMakeLists are identical to #12117's) under the new tests. Only `write_watch_backing_shared` and `write_watch_backing_restore` fail, on both arm64 and x86_64. That matches the body. - check_conventions passes, and `git merge-tree` against main 17f8dfad51 is clean. **Mutants** (both arches give the same result) | mutant | result | |---|---| | back to the unchecked `::mprotect(...)` | killed by `backing_restore` | | probe always `return true` | killed by `backing_shared` (hang until SIGALRM) | | probe always `return false` | killed by `backing_late` (bus error: the delayed second writer gets forwarded) | | `isWriteFault` dropped from `fault()` | killed by `execute-fault` | | drop `&& copied == sizeof(value)` | survives. I think it's equivalent, since `copied` is always the full size when the call returns KERN_SUCCESS | | set `state = ...Written` **before** the mprotect check | survives | The last survivor is minor. If restoring protection fails, the page has already been marked Written with Protected cleared, so the next Collect reports a page that was never written. The PR's ordering is correct; nothing tests it. Checking in `backing_restore` that the page is still unreported after a failed restore would cover it. Not blocking. **Scope note (not blocking, not a regression)** The new probe checks that the page is *readable*, not that it is *writable*. I mapped and registered a page as RW, wrote to it, then called plain `::mprotect(page, PROT_READ)` without going through `GuestWriteWatchProtect`, then wrote again. The process hangs until `alarm` fires (rc 142) on head **and** on the eb20686c42 base. The recorded state still contains PROT_WRITE, and `mach_vm_read_overwrite` succeeds on a readable page. Guest mprotect goes through DirectMemory → `GuestWriteWatchProtect`, so only host-side code that changes protection directly can reach this, and that's outside this PR's truncation topic. If you want to close it later, asking `mach_vm_region` for the current protection, or doing a one-byte `mach_vm_write` back of the probed byte, would test writability itself. So, COMMENT rather than APPROVE: the change is correct and both of its new checks are covered by tests. I'm not approving because it stacks on #12117, which has no reviews yet, and I didn't run the full libs lane.
MarcZX10 commented 2026-10-28 15:53:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-28T15:53:24Z.

Review: APPROVED


Reviewed exact head 1f1da4b0ff1592c9a545f39e9c112bf935630aaa. The PR is explicitly stacked on #12117; that prerequisite is now approved, and its implementation is unchanged from the dependency content in this branch. The new macOS backing probe only runs when a page is already recorded writable; when mach_vm_read_overwrite cannot read the address (the truncated backing case), the handler forwards the original fault, while normal protected-page writes still use the prior fast path. The failed-mprotect ordering avoids marking a page written before protection restoration succeeds. Independent exact-head macOS testing reports 17/17 on arm64 and x86_64/Rosetta, 17/17 under ASan/UBSan with the signal options needed by this harness, repeated late-fault/thread tests, and red controls for both new behaviors. I independently confirmed the four-file patch applies cleanly to current main and git diff --check passes. I could not run Mach VM tests on this Linux host; hosted macOS write-watch jobs remain queued, so those results are not claimed as completed CI. The reviewer’s non-blocking note about host code changing mapping protection outside GuestWriteWatch is outside the supported protection API and is not a regression from this patch. No blocking issue found.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5685615859 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12435#pullrequestreview-5685615859). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-28T15:53:24Z. **Review:** APPROVED --- Reviewed exact head `1f1da4b0ff1592c9a545f39e9c112bf935630aaa`. The PR is explicitly stacked on #12117; that prerequisite is now approved, and its implementation is unchanged from the dependency content in this branch. The new macOS backing probe only runs when a page is already recorded writable; when `mach_vm_read_overwrite` cannot read the address (the truncated backing case), the handler forwards the original fault, while normal protected-page writes still use the prior fast path. The failed-`mprotect` ordering avoids marking a page written before protection restoration succeeds. Independent exact-head macOS testing reports 17/17 on arm64 and x86_64/Rosetta, 17/17 under ASan/UBSan with the signal options needed by this harness, repeated late-fault/thread tests, and red controls for both new behaviors. I independently confirmed the four-file patch applies cleanly to current `main` and `git diff --check` passes. I could not run Mach VM tests on this Linux host; hosted macOS write-watch jobs remain queued, so those results are not claimed as completed CI. The reviewer’s non-blocking note about host code changing mapping protection outside GuestWriteWatch is outside the supported protection API and is not a regression from this patch. No blocking issue found.
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!12435
No description provided.