feat(libkernel): deliver host faults to sceKernelInstallExceptionHandler handlers #7192

Merged
Jev1337 merged 6 commits from upstream-pr/7192 into main 2026-11-04 19:19:08 +00:00
Jev1337 commented 2026-10-17 15:42:46 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Jev1337 on 2026-10-17T15:42:46Z.


What

sceKernelInstallExceptionHandler recorded handlers for signals 4, 8, 10 and 11 but never called them: a host fault always ended the process (see the removed entry in docs/dev/debt/libkernel.md). Handlers now receive the faults raised in title code, and execution resumes from the context the handler leaves, as FreeBSD's sendsig/sigreturn do.

  • Mapping follows FreeBSD 11 amd64 trap() and trap.h: #UD → SIGILL, mc_trapno 1 (T_PRIVINFLT); #GP, non-canonical address, privileged instruction → SIGBUS, 9 (T_PROTFLT); #AC → SIGBUS, 14; #DE (incl. INT_MIN / -1) → SIGFPE, 18 (T_DIVIDE); #XM → SIGFPE, 29; x87 #MF → SIGFPE, 6; page fault → SIGSEGV, 12 (T_PAGEFLT) with mc_addr = fault address and mc_err = page-fault error code. Other traps leave mc_addr 0, as exception.S does. Linux #NP/#SS also map to SIGBUS 26/27.
  • Only title code gets faults: the guest arena, the .elf sections of relinked images (the whole executable when not relinked) on Windows, the executable and .guest.prx modules on Linux. Faults in the system libraries, the host runtime and drivers still go to the crash report.
  • Windows: ReportCrash (libc) offers a fault to a hook (LibcSetHostFaultHandler_nid_no_patch) after the arena, write-watch and SSE4a handlers decline. libkernel records the fault, redirects the CONTEXT to Aps5FaultEntryStub below the red zone and returns EXCEPTION_CONTINUE_EXECUTION; the stub saves YMM0-15 and the handler runs outside the exception dispatcher (so it can longjmp out or fault again), then resumes through the existing Aps5RedirectedExit/RtlRestoreContext path of sceKernelRaiseException.
  • Linux: once a handler for a fault signal is installed, host handlers for SIGSEGV/SIGBUS/SIGILL/SIGFPE (SA_NODEFER) classify by REG_TRAPNO (Linux reports #GP as SIGSEGV), take only kernel-generated faults (si_code > 0) and chain everything else to the previous handlers.
  • Processes that never install a handler for 4/8/10/11 are unchanged: the hook stays null and Linux installs nothing.
  • Unverified console behaviour and host limits are recorded in docs/dev/debt/libkernel.md: SIGSEGV (FreeBSD default) vs SIGBUS (fpPS4) for protection faults, stack overflow and in-page errors, SA_NODEFER-style redelivery inside a handler, and the Windows kernel overwriting the faulting function's red zone before any user-mode handler runs.

Overlap: #4630 (macOS sceKernelRaiseException), #6222, #7201 and #7332 (macOS) and #6879 (WebAssembly) add host branches next to the same lines of Exception.cpp, and #4630/#5918 edit neighbouring lines of docs/dev/debt/libkernel.md. None implements fault delivery and none is a prerequisite, so whichever lands second only resolves the textual conflict. To keep their branches building, the new trap argument of CallHandler defaults to zero (their CallHandler(handler, RaisedSignal, ucontext) calls stay valid) and the Linux-only fault code and headers are under __linux__, so macOS and WebAssembly keep today's behaviour (handler recorded, faults not delivered), recorded in the debt entry.

Prior art compared: shadPS4 calls the handler inside its VEH and does not fill mc_trapno/mc_err; fpPS4 delivers only faults in its JIT code.

Tested

Windows 11 Pro 26300, MinGW-w64 GCC 15.2.0 (WinLibs r7), full build with BUILD_TESTING=ON.

  • New guest_exception_fault: null read (trapno, addr, err U only), write to a read-only page (err P|W|U), ud2, idiv by 0 and INT_MIN / -1, unmasked SSE divss by 0 (trapno 29), non-canonical read (SIGBUS, T_PROTFLT), r12 patched by the handler, r13/rbx/xmm8 seen and YMM8 upper half preserved across delivery, a SIGILL raised inside the SIGSEGV handler, longjmp out of the handler three times then a normal fault, and a fault on another thread. A handler that returns the context unchanged runs again on the same fault (three calls, then it resumes), one that makes the page writable with mprotect and returns completes the store after one call, and one that removes itself and returns ends the process with the access violation, checked from a child process with a 10 s timeout (with the removal left out the test fails on that timeout). With the InstallFaultDelivery call removed the test dies with SegFault.
  • After rebasing onto 086c0686c (keeping main's QueueWaitingDelivery/Redirect delivery): guest_exception_fault, guest_exception_handler, guest_raise_exception and guest_sigaltstack pass 3 runs of 3, and all 191 tests matching raise|exception|signal|sigalt pass (guest_raise_in_system_call*, guest_raise_in_host_code, guest_raise_leaves_host_code, guest_raise_short_sleep*, windows_exceptions among them). The full suite was not rerun on this base; the next line is from the previous one.
  • Full ctest on 0c6a5bd59: 1869/1876 pass. agc_driver_sample_order, agc_driver_sample_order_grid_reference and agc_driver_sample_order_recipe_depth_locations fail on main too on this GPU (RTX 3070); agc_driver_image_array_window_past_layer_limit does not build with MinGW on main (alignas(65536)); guest_video_out_high_frame_rate, guest_memory and guest_raise_in_system_call failed under -j 12 and pass alone. guest_raise_in_system_call times out 2 of 30 runs next to an 11-job agc_ load with this branch and with main alike.
  • Linux: GitHub ubuntu-latest runner (Ubuntu, GCC, AMD EPYC 7763), the same configure as CI with BUILD_TESTING=ON: guest_exception_fault (three runs in a row), guest_exception_handler, guest_raise_exception, guest_sigaltstack, guest_memory, guest_memory_lifetime, guest_named_shm_lifecycle and agc_write_watch_coverage pass, including a store from title code to a write-watched range that does not reach the handler and the child-process case (run on my fork). A benchmark kept out of the PR (mprotect R, faulting 8-byte store, handler's mprotect RW; median of 9 x 100k) gives 8160-8299 ns for a host-code fault with a host handler only, 8208-8258 ns with a guest handler for 11 installed and the fault chained, and 9068-9136 ns for a title-code fault delivered to the guest handler; with dladdr1 the chained case was about 8 us slower (run). The linux job of build.yml needs the self-hosted runner, so the full Linux suite still needs a maintainer run.
  • Linux after the same rebase: the same eight tests pass, guest_exception_fault three runs in a row (run on my fork).

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:4901486225 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7192). Originally posted by [Jev1337](https://github.com/Jev1337) on 2026-10-17T15:42:46Z. --- ### What `sceKernelInstallExceptionHandler` recorded handlers for signals 4, 8, 10 and 11 but never called them: a host fault always ended the process (see the removed entry in `docs/dev/debt/libkernel.md`). Handlers now receive the faults raised in title code, and execution resumes from the context the handler leaves, as FreeBSD's `sendsig`/`sigreturn` do. - **Mapping** follows FreeBSD 11 amd64 [`trap()`](https://github.com/freebsd/freebsd-src/blob/stable/11/sys/amd64/amd64/trap.c) and [`trap.h`](https://github.com/freebsd/freebsd-src/blob/stable/11/sys/amd64/include/trap.h): #UD → SIGILL, `mc_trapno` 1 (`T_PRIVINFLT`); #GP, non-canonical address, privileged instruction → SIGBUS, 9 (`T_PROTFLT`); #AC → SIGBUS, 14; #DE (incl. `INT_MIN / -1`) → SIGFPE, 18 (`T_DIVIDE`); #XM → SIGFPE, 29; x87 #MF → SIGFPE, 6; page fault → SIGSEGV, 12 (`T_PAGEFLT`) with `mc_addr` = fault address and `mc_err` = page-fault error code. Other traps leave `mc_addr` 0, as [exception.S](https://github.com/freebsd/freebsd-src/blob/stable/11/sys/amd64/amd64/exception.S) does. Linux #NP/#SS also map to SIGBUS 26/27. - **Only title code** gets faults: the guest arena, the `.elf` sections of relinked images (the whole executable when not relinked) on Windows, the executable and `.guest.prx` modules on Linux. Faults in the system libraries, the host runtime and drivers still go to the crash report. - **Windows**: `ReportCrash` (libc) offers a fault to a hook (`LibcSetHostFaultHandler_nid_no_patch`) after the arena, write-watch and SSE4a handlers decline. libkernel records the fault, redirects the `CONTEXT` to `Aps5FaultEntryStub` below the red zone and returns `EXCEPTION_CONTINUE_EXECUTION`; the stub saves YMM0-15 and the handler runs outside the exception dispatcher (so it can `longjmp` out or fault again), then resumes through the existing `Aps5RedirectedExit`/`RtlRestoreContext` path of `sceKernelRaiseException`. - **Linux**: once a handler for a fault signal is installed, host handlers for SIGSEGV/SIGBUS/SIGILL/SIGFPE (`SA_NODEFER`) classify by `REG_TRAPNO` (Linux reports #GP as SIGSEGV), take only kernel-generated faults (`si_code > 0`) and chain everything else to the previous handlers. - Processes that never install a handler for 4/8/10/11 are unchanged: the hook stays null and Linux installs nothing. - Unverified console behaviour and host limits are recorded in `docs/dev/debt/libkernel.md`: SIGSEGV (FreeBSD default) vs SIGBUS (fpPS4) for protection faults, stack overflow and in-page errors, `SA_NODEFER`-style redelivery inside a handler, and the Windows kernel overwriting the faulting function's red zone before any user-mode handler runs. Overlap: #4630 (macOS `sceKernelRaiseException`), #6222, #7201 and #7332 (macOS) and #6879 (WebAssembly) add host branches next to the same lines of `Exception.cpp`, and #4630/#5918 edit neighbouring lines of `docs/dev/debt/libkernel.md`. None implements fault delivery and none is a prerequisite, so whichever lands second only resolves the textual conflict. To keep their branches building, the new `trap` argument of `CallHandler` defaults to zero (their `CallHandler(handler, RaisedSignal, ucontext)` calls stay valid) and the Linux-only fault code and headers are under `__linux__`, so macOS and WebAssembly keep today's behaviour (handler recorded, faults not delivered), recorded in the debt entry. Prior art compared: shadPS4 calls the handler inside its VEH and does not fill `mc_trapno`/`mc_err`; fpPS4 delivers only faults in its JIT code. ### Tested Windows 11 Pro 26300, MinGW-w64 GCC 15.2.0 (WinLibs r7), full build with `BUILD_TESTING=ON`. - New `guest_exception_fault`: null read (trapno, addr, err U only), write to a read-only page (err P|W|U), `ud2`, idiv by 0 and `INT_MIN / -1`, unmasked SSE `divss` by 0 (trapno 29), non-canonical read (SIGBUS, `T_PROTFLT`), r12 patched by the handler, r13/rbx/xmm8 seen and YMM8 upper half preserved across delivery, a SIGILL raised inside the SIGSEGV handler, `longjmp` out of the handler three times then a normal fault, and a fault on another thread. A handler that returns the context unchanged runs again on the same fault (three calls, then it resumes), one that makes the page writable with `mprotect` and returns completes the store after one call, and one that removes itself and returns ends the process with the access violation, checked from a child process with a 10 s timeout (with the removal left out the test fails on that timeout). With the `InstallFaultDelivery` call removed the test dies with SegFault. - After rebasing onto `086c0686c` (keeping main's `QueueWaitingDelivery`/`Redirect` delivery): `guest_exception_fault`, `guest_exception_handler`, `guest_raise_exception` and `guest_sigaltstack` pass 3 runs of 3, and all 191 tests matching `raise|exception|signal|sigalt` pass (`guest_raise_in_system_call*`, `guest_raise_in_host_code`, `guest_raise_leaves_host_code`, `guest_raise_short_sleep*`, `windows_exceptions` among them). The full suite was not rerun on this base; the next line is from the previous one. - Full `ctest` on `0c6a5bd59`: 1869/1876 pass. `agc_driver_sample_order`, `agc_driver_sample_order_grid_reference` and `agc_driver_sample_order_recipe_depth_locations` fail on `main` too on this GPU (RTX 3070); `agc_driver_image_array_window_past_layer_limit` does not build with MinGW on `main` (`alignas(65536)`); `guest_video_out_high_frame_rate`, `guest_memory` and `guest_raise_in_system_call` failed under `-j 12` and pass alone. `guest_raise_in_system_call` times out 2 of 30 runs next to an 11-job `agc_` load with this branch and with `main` alike. - Linux: GitHub `ubuntu-latest` runner (Ubuntu, GCC, AMD EPYC 7763), the same configure as CI with `BUILD_TESTING=ON`: `guest_exception_fault` (three runs in a row), `guest_exception_handler`, `guest_raise_exception`, `guest_sigaltstack`, `guest_memory`, `guest_memory_lifetime`, `guest_named_shm_lifecycle` and `agc_write_watch_coverage` pass, including a store from title code to a write-watched range that does not reach the handler and the child-process case ([run on my fork](https://github.com/Jev1337/AnyPS5/actions/runs/39673645161)). A benchmark kept out of the PR (mprotect R, faulting 8-byte store, handler's mprotect RW; median of 9 x 100k) gives 8160-8299 ns for a host-code fault with a host handler only, 8208-8258 ns with a guest handler for 11 installed and the fault chained, and 9068-9136 ns for a title-code fault delivered to the guest handler; with `dladdr1` the chained case was about 8 us slower ([run](https://github.com/Jev1337/AnyPS5/actions/runs/39669849217)). The `linux` job of `build.yml` needs the self-hosted runner, so the full Linux suite still needs a maintainer run. - Linux after the same rebase: the same eight tests pass, `guest_exception_fault` three runs in a row ([run on my fork](https://github.com/Jev1337/AnyPS5/actions/runs/41708771925)). ### 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: none - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes
copilot-pull-request-reviewer[bot] commented 2026-10-17 15:42:53 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by copilot-pull-request-reviewer[bot] on 2026-10-17T15:42:53Z.

Review: COMMENTED


Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5558557732 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7192#pullrequestreview-5558557732). Originally posted by [copilot-pull-request-reviewer[bot]](https://github.com/apps/copilot-pull-request-reviewer) on 2026-10-17T15:42:53Z. **Review:** COMMENTED --- Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.
oneandonlydean commented 2026-10-17 16:00:46 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-17T16:00:46Z.


Thanks for this. The trap mapping, the gating on an installed handler, and the Windows path (ReportCrash calls HandleWatch before the new hook) all check out. One blocker on Linux:

Write-watch faults reach the game's handler. Main's write-watch installs its SIGSEGV/SIGBUS handler at libc static init (GuestWriteWatch.cpp:495/619). This PR installs fault delivery later, on the first sceKernelInstallExceptionHandler for 4/8/10/11, so it becomes the outermost handler and only chains when it does not deliver. Once a title has a SIGSEGV handler, a guest store to a write-watched GPU page (SEGV_ACCERR, RIP in title code) goes to the game's handler instead. Write-watch never records the write. A handler that returns re-faults forever, and a crash handler aborts the title.

Ask:

  • On Linux, let write-watch try first. For example, chain to it when GuestWriteWatchCovers says the faulting address is watched, before delivering to the guest handler.
  • Add a Linux test that installs a handler for 11, stores to a watched range from arena code, and requires that the handler is not called and the write is collected.

Two non-blocking questions:

  • Linux GuestCode treats an empty l_name (the main executable) as title code. Is the main executable always the relinked title, never a launcher or a binary with host code statically linked in? The same applies on Windows to "the whole executable when not relinked".
  • dladdr1 isn't async-signal-safe. It's only reached after Classify succeeds and a handler exists, so it seems acceptable, but it's worth a line in the debt doc.
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6236243065 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7192#issuecomment-6236243065). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-17T16:00:46Z. --- Thanks for this. The trap mapping, the gating on an installed handler, and the Windows path (ReportCrash calls HandleWatch before the new hook) all check out. One blocker on Linux: **Write-watch faults reach the game's handler.** Main's write-watch installs its SIGSEGV/SIGBUS handler at libc static init (GuestWriteWatch.cpp:495/619). This PR installs fault delivery later, on the first `sceKernelInstallExceptionHandler` for 4/8/10/11, so it becomes the outermost handler and only chains when it does *not* deliver. Once a title has a SIGSEGV handler, a guest store to a write-watched GPU page (SEGV_ACCERR, RIP in title code) goes to the game's handler instead. Write-watch never records the write. A handler that returns re-faults forever, and a crash handler aborts the title. Ask: - On Linux, let write-watch try first. For example, chain to it when `GuestWriteWatchCovers` says the faulting address is watched, before delivering to the guest handler. - Add a Linux test that installs a handler for 11, stores to a watched range from arena code, and requires that the handler is **not** called and the write **is** collected. Two non-blocking questions: - Linux `GuestCode` treats an empty `l_name` (the main executable) as title code. Is the main executable always the relinked title, never a launcher or a binary with host code statically linked in? The same applies on Windows to "the whole executable when not relinked". - `dladdr1` isn't async-signal-safe. It's only reached after `Classify` succeeds and a handler exists, so it seems acceptable, but it's worth a line in the debt doc.
Jev1337 commented 2026-10-17 16:14:42 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Jev1337 on 2026-10-17T16:14:42Z.


Thanks for going through it.

On the write-watch point: lines 495/619 are inside the #elif defined(__APPLE__) block, so that's the macOS watch. On Linux the watch is the userfaultfd one with UFFD_FEATURE_WP_ASYNC, and the kernel resolves those write-protect faults itself without sending anything to userspace ("no message generated … resolved automatically by the kernel"). So a store to a watched page never turns into a SIGSEGV there. The fault code in this PR is also __linux__ only, so it never sits on top of the macOS sigaction watch.

I still added the "let write-watch go first" step, just not keyed on GuestWriteWatchCovers: a page fault is now offered to the watch through a new GuestWriteWatchHandleFault, and the handler is skipped only if the watch actually claims it. Using Covers alone would also catch real protection faults on watched pages (say a game makes one read-only with sceKernelMprotect and then writes to it), and those should still reach the game's handler.

The test you asked for is in: TestWatchedStore installs a SIGSEGV handler, registers a range, stores to it from the test's own code, and checks that the handler isn't called and the write gets collected. It passes on ubuntu-latest (run). Where the watch isn't available it prints "not tested", like GuestMemory.cpp does.

Your two questions:

  • Main executable: on Linux the relinker patches the title's ELF in place, and the system libraries come in through DT_NEEDED, so no host code gets linked into it, and there's no launcher ("Only the converted executable runs" in USAGE.md). The only non-title code in there is the --to-intel/--to-rosetta conversion stubs; a fault inside one reports the stub's address, which I've written down in the debt entry. On Windows a relinked title always has .elf sections and only those count. The "whole executable when not relinked" case is for executables built natively against the libraries, like the test suite.
  • dladdr1: agreed, added a line about it to the debt entry.
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6236444073 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7192#issuecomment-6236444073). Originally posted by [Jev1337](https://github.com/Jev1337) on 2026-10-17T16:14:42Z. --- Thanks for going through it. On the write-watch point: lines 495/619 are inside the `#elif defined(__APPLE__)` block, so that's the macOS watch. On Linux the watch is the userfaultfd one with `UFFD_FEATURE_WP_ASYNC`, and the kernel resolves those write-protect faults itself without sending anything to userspace (["no message generated … resolved automatically by the kernel"](https://docs.kernel.org/admin-guide/mm/userfaultfd.html)). So a store to a watched page never turns into a SIGSEGV there. The fault code in this PR is also `__linux__` only, so it never sits on top of the macOS sigaction watch. I still added the "let write-watch go first" step, just not keyed on `GuestWriteWatchCovers`: a page fault is now offered to the watch through a new `GuestWriteWatchHandleFault`, and the handler is skipped only if the watch actually claims it. Using `Covers` alone would also catch real protection faults on watched pages (say a game makes one read-only with `sceKernelMprotect` and then writes to it), and those should still reach the game's handler. The test you asked for is in: `TestWatchedStore` installs a SIGSEGV handler, registers a range, stores to it from the test's own code, and checks that the handler isn't called and the write gets collected. It passes on ubuntu-latest ([run](https://github.com/Jev1337/AnyPS5/actions/runs/39048344606)). Where the watch isn't available it prints "not tested", like `GuestMemory.cpp` does. Your two questions: - Main executable: on Linux the relinker patches the title's ELF in place, and the system libraries come in through `DT_NEEDED`, so no host code gets linked into it, and there's no launcher ("Only the converted executable runs" in USAGE.md). The only non-title code in there is the `--to-intel`/`--to-rosetta` conversion stubs; a fault inside one reports the stub's address, which I've written down in the debt entry. On Windows a relinked title always has `.elf` sections and only those count. The "whole executable when not relinked" case is for executables built natively against the libraries, like the test suite. - `dladdr1`: agreed, added a line about it to the debt entry.
blawesom commented 2026-10-18 10:41:30 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by blawesom on 2026-10-18T10:41:30Z.


Rebase handoff — rebased onto current main (authorship unchanged). Two conflicts in GuestWriteWatch: main's newer Overlaps machinery kept alongside your HandleFault delivery (the Apple-gated fault entry and the exception-handler plumbing), with the function tails disentangled.

Verified on Linux (CachyOS, kernel 7.2.9, GCC 16.2.1, Ninja, Release, BUILD_TESTING=ON, AMD RX 9070 XT / RADV): builds; conventions pass; full suite green apart from the known main regression (agc_driver_tessellation segfault — Mesa, #5444), not this PR (your fault-delivery entry is Apple-gated and skips on Linux).

To pick it up:

git fetch https://github.com/blawesom/AnyPS5 rebase/7192
git checkout <your branch>
git merge --ff-only FETCH_HEAD

Head is ab3957816.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6248869560 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7192#issuecomment-6248869560). Originally posted by [blawesom](https://github.com/blawesom) on 2026-10-18T10:41:30Z. --- **Rebase handoff** — rebased onto current `main` (authorship unchanged). Two conflicts in `GuestWriteWatch`: `main`'s newer `Overlaps` machinery kept alongside your `HandleFault` delivery (the Apple-gated fault entry and the exception-handler plumbing), with the function tails disentangled. Verified on Linux (CachyOS, kernel 7.2.9, GCC 16.2.1, Ninja, Release, `BUILD_TESTING=ON`, AMD RX 9070 XT / RADV): builds; conventions pass; **full suite green apart from the known `main` regression** (`agc_driver_tessellation` segfault — Mesa, #5444), not this PR (your fault-delivery entry is Apple-gated and skips on Linux). **To pick it up:** ``` git fetch https://github.com/blawesom/AnyPS5 rebase/7192 git checkout <your branch> git merge --ff-only FETCH_HEAD ``` Head is `ab3957816`.
Jev1337 commented 2026-10-18 12:51:34 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Jev1337 on 2026-10-18T12:51:34Z.


Thanks for picking this up! main had moved again by the time I saw this and the PR was showing conflicts again, so I rebased onto the current head (6efb7261b) myself. I resolved it the same way you did: Overlaps stays and HandleFault goes next to it. Small nit on yours: the closing brace of Overlaps lost its indentation (line 394). That's fixed in mine.

One correction: only the write-watch HandleFault hook is Apple-gated, because on Linux the userfaultfd watch runs in async mode and the kernel handles those writes without raising a signal. The fault delivery itself is live on Linux, and guest_exception_fault runs there. After the rebase I reran on ubuntu-latest with the memory and write-watch tests included this time: run, 8/8. Good to hear the full suite is green on your RADV box too.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6250132483 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7192#issuecomment-6250132483). Originally posted by [Jev1337](https://github.com/Jev1337) on 2026-10-18T12:51:34Z. --- Thanks for picking this up! `main` had moved again by the time I saw this and the PR was showing conflicts again, so I rebased onto the current head (`6efb7261b`) myself. I resolved it the same way you did: `Overlaps` stays and `HandleFault` goes next to it. Small nit on yours: the closing brace of `Overlaps` lost its indentation ([line 394](https://github.com/blawesom/AnyPS5/blob/ab3957816/core/libs/prx/libc/src/GuestWriteWatch.cpp#L394)). That's fixed in mine. One correction: only the write-watch `HandleFault` hook is Apple-gated, because on Linux the userfaultfd watch runs in async mode and the kernel handles those writes without raising a signal. The fault delivery itself is live on Linux, and `guest_exception_fault` runs there. After the rebase I reran on ubuntu-latest with the memory and write-watch tests included this time: [run](https://github.com/Jev1337/AnyPS5/actions/runs/39127908692), 8/8. Good to hear the full suite is green on your RADV box too.
CnRJay commented 2026-10-21 17:56:27 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by CnRJay on 2026-10-21T17:56:27Z.

Review: COMMENTED


The trap-to-signal mapping is well sourced (FreeBSD 11 trap() and trap.h), the "only title code gets faults" rule and the Windows redirect through a stub (so the handler runs outside the exception dispatcher and can longjmp) are the right design, and unverified console behavior is recorded in debt. The parts that concern me are what happens in a process that installs a handler.

  • A title can call sceKernelInstallExceptionHandler for its own crash reporting without expecting it to be invoked. For such a title the hook is no longer null and, on Linux, host handlers for SIGSEGV/SIGBUS/SIGILL/SIGFPE are installed with SA_NODEFER. If any part of the runtime uses a SIGSEGV path as a normal mechanism (write watch on hosts without a hardware dirty-page API, guard pages, lazy mappings), every such fault now goes through the new classification before it is chained to the previous handler. Please say which faults the runtime takes as part of normal operation on Linux, and measure the added cost per fault on a title that installs a handler and takes many (a write-watched workload), or show that they bypass it.
  • "Take only kernel-generated faults (si_code > 0) and chain everything else": a fault raised by the guest in title code is passed to a title handler that may never expect one, where today the process ends with a crash report. For a title that installs a handler for crash reporting, delivering the fault makes the title's own handler run and then resume execution from the context it leaves; a handler that writes a minidump and returns would resume at the faulting instruction and fault forever, or continue after a bad store. State the behavior when the handler returns without changing the context (the process should end with the crash report, not loop), with a test.
  • The Windows path overwrites the context of a faulting thread and resumes it ("EXCEPTION_CONTINUE_EXECUTION"). The debt notes that the kernel overwrites the faulting function's red zone before any user-mode handler runs. Say what is lost (a leaf function's locals) and whether the handler can observe corrupt data, since that is the case a crash-reporting handler is most likely to hit.
  • 843 lines across libc and libkernel for the Windows and Linux branches, with macOS (#4630, #6222, #7201, #7332) and WebAssembly (#6879) branches open beside it. Say which of these must land first, so the same hook isn't implemented twice.
<!-- greyfinch-sync:boykopovar/AnyPS5:review:5603984863 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7192#pullrequestreview-5603984863). Originally posted by [CnRJay](https://github.com/CnRJay) on 2026-10-21T17:56:27Z. **Review:** COMMENTED --- The trap-to-signal mapping is well sourced (FreeBSD 11 `trap()` and `trap.h`), the "only title code gets faults" rule and the Windows redirect through a stub (so the handler runs outside the exception dispatcher and can `longjmp`) are the right design, and unverified console behavior is recorded in debt. The parts that concern me are what happens in a process that installs a handler. - A title can call `sceKernelInstallExceptionHandler` for its own crash reporting without expecting it to be invoked. For such a title the hook is no longer null and, on Linux, host handlers for SIGSEGV/SIGBUS/SIGILL/SIGFPE are installed with `SA_NODEFER`. If any part of the runtime uses a SIGSEGV path as a normal mechanism (write watch on hosts without a hardware dirty-page API, guard pages, lazy mappings), every such fault now goes through the new classification before it is chained to the previous handler. Please say which faults the runtime takes as part of normal operation on Linux, and measure the added cost per fault on a title that installs a handler and takes many (a write-watched workload), or show that they bypass it. - "Take only kernel-generated faults (`si_code > 0`) and chain everything else": a fault raised by the guest in title code is passed to a title handler that may never expect one, where today the process ends with a crash report. For a title that installs a handler for crash reporting, delivering the fault makes the title's own handler run and then resume execution from the context it leaves; a handler that writes a minidump and returns would resume at the faulting instruction and fault forever, or continue after a bad store. State the behavior when the handler returns without changing the context (the process should end with the crash report, not loop), with a test. - The Windows path overwrites the context of a faulting thread and resumes it ("EXCEPTION_CONTINUE_EXECUTION"). The debt notes that the kernel overwrites the faulting function's red zone before any user-mode handler runs. Say what is lost (a leaf function's locals) and whether the handler can observe corrupt data, since that is the case a crash-reporting handler is most likely to hit. - 843 lines across libc and libkernel for the Windows and Linux branches, with macOS (#4630, #6222, #7201, #7332) and WebAssembly (#6879) branches open beside it. Say which of these must land first, so the same hook isn't implemented twice.
Jev1337 commented 2026-10-21 20:58:18 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Jev1337 on 2026-10-21T20:58:18Z.


Thanks for the careful read, these are fair points. I pushed three follow-up commits (a test, a perf fix, and a debt cleanup) and rebased onto current main, since #7652 changed the same Delivery initializers.

On the faults the runtime takes during normal operation: on Linux none of them reach a signal handler. The only SIGSEGV/SIGBUS handlers in core/ are the macOS write watch (under __APPLE__) and the one in this PR. The Linux write watch is userfaultfd in async mode. I double-checked the kernel's userfaultfd docs and the original patch thread: in that mode the kernel clears the write-protect bit itself and sends nothing to userspace. When the feature is missing, the watch reports itself unavailable and the AGC driver records the failed probe. There's no mprotect + SIGSEGV fallback, and the arena's fault handlers are only called from the Windows ReportCrash. So a write-watched workload never gets into DeliverFault, which TestWatchedStore checks with a handler for 11 installed. On Windows the arena, write-watch and SSE4a handlers come before the new hook and return on their own faults.

Your question made me measure the case where something else in the process takes SIGSEGV, like a driver with its own handler installed earlier, and it turned up a real cost. Deciding whether the faulting code was the title's went through dladdr1, which searches the object's symbol table, and that added about 8 µs to every host fault chained past an installed handler (first run). It now uses glibc's _dl_find_object like libc's unwinder already does; older glibc keeps dladdr1. The manual also lists it as AS-Safe, so the async-signal-safety caveat in the debt entry now only applies to glibc older than 2.35.

After the change, on ubuntu-latest (AMD EPYC 7763), 9 rounds of 100k faults, each iteration doing mprotect R, a faulting 8-byte store and the handler's mprotect RW back, median ns per iteration over three runs (run):

ns
host-code fault, host handler only 8160–8299
same, guest handler for 11 installed (classified, then chained) 8208–8258
title-code fault delivered to the guest handler 9068–9136

So chaining is within noise now, and delivering costs a bit under a microsecond more than a plain host handler. That includes the context log line from #7655. The benchmark isn't part of the PR.

On a handler that returns without touching the context: it runs again on the same fault. I looked at what FreeBSD does, and it's the same thing there. sendsig and sys_sigreturn in machdep.c save the trap frame into the ucontext and copy it straight back, so the faulting instruction runs again and a handler that doesn't fix anything loops there as well. I'd rather not turn that into a crash report. The common pattern is to fix the page with mprotect and return the context unchanged (incremental GCs, write barriers), and telling the two apart would mean guessing, which could kill a title that works on the console. The process does end with the crash report when the handler removes itself and returns, or calls exit/abort.

The new commit tests all three cases:

  • returning unchanged calls the handler again (three times here, then it resumes);
  • fixing the page and returning lets the store complete after one call;
  • removing itself and returning ends the process with the access violation.

That last one runs in a child process, so a loop shows up as a 10 s timeout instead of a hung ctest. I made sure it does fail that way when the handler doesn't remove itself. The debt entry now also says the console isn't verified here.

The red zone one bugged me too, so I dug into where Windows puts the exception frame. As far as I can tell it builds the KiUserExceptionDispatcher frame directly below the faulting rsp with no gap. ReactOS does UserRsp = (Context->Rsp - sizeof(KUSER_EXCEPTION_STACK)) & ~15, and this write-up on the dispatcher puts the frame at about 0x5d0 bytes. FreeBSD subtracts 128 first, and Linux skips the red zone too. So what's lost is the 128 bytes below rsp, meaning whatever a leaf function kept in its red zone. Registers, the return address and everything from rsp up are intact. A crash-reporting handler that reads the context, walks the stack and exits sees correct data. One that reads below mc_rsp sees the dispatcher's frame, and one that resumes such a leaf function resumes it without those values. This happens before any user-mode code runs, so the faults the arena, write-watch and SSE4a handlers already resume on main lose it the same way. This PR doesn't add to it, since the stub runs below the red zone.

And on ordering: none of them has to land first. I grepped the full diffs of #4630, #7201 and #6879. They add sceKernelRaiseException or context-conversion branches but install no fault handler: no sigaction for SIGSEGV/SIGBUS/SIGILL/SIGFPE, no vectored handler, no Mach exception port. #6222 and #7332 are closed now. So this is the only place the hook is implemented, and #6879's CallHandler(handler, RaisedSignal, ucontext) still builds because the trap argument defaults to zero. Fault delivery on macOS would be a follow-up on the same POSIX path, using __es.__trapno/__err/__faultvaddr instead of REG_TRAPNO, and GuestWriteWatchHandleFault is already there so the macOS watch would still go first. On size, 602 of the lines are the test; the code is about 330 lines in Exception.cpp and 37 in libc.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6326405345 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7192#issuecomment-6326405345). Originally posted by [Jev1337](https://github.com/Jev1337) on 2026-10-21T20:58:18Z. --- Thanks for the careful read, these are fair points. I pushed three follow-up commits (a test, a perf fix, and a debt cleanup) and rebased onto current main, since #7652 changed the same `Delivery` initializers. On the faults the runtime takes during normal operation: on Linux none of them reach a signal handler. The only SIGSEGV/SIGBUS handlers in `core/` are the macOS write watch (under `__APPLE__`) and the one in this PR. The Linux write watch is userfaultfd in async mode. I double-checked the [kernel's userfaultfd docs](https://docs.kernel.org/admin-guide/mm/userfaultfd.html) and the [original patch thread](https://lore.kernel.org/all/Y9MHM+RVzvigcTTk@x1n/t/): in that mode the kernel clears the write-protect bit itself and sends nothing to userspace. When the feature is missing, the watch reports itself unavailable and the AGC driver records the failed probe. There's no mprotect + SIGSEGV fallback, and the arena's fault handlers are only called from the Windows `ReportCrash`. So a write-watched workload never gets into `DeliverFault`, which `TestWatchedStore` checks with a handler for 11 installed. On Windows the arena, write-watch and SSE4a handlers come before the new hook and return on their own faults. Your question made me measure the case where something else in the process takes SIGSEGV, like a driver with its own handler installed earlier, and it turned up a real cost. Deciding whether the faulting code was the title's went through `dladdr1`, which searches the object's symbol table, and that added about 8 µs to every host fault chained past an installed handler ([first run](https://github.com/Jev1337/AnyPS5/actions/runs/39669849217)). It now uses glibc's [`_dl_find_object`](https://sourceware.org/glibc/manual/latest/html_node/Dynamic-Linker-Introspection.html) like libc's unwinder already does; older glibc keeps `dladdr1`. The manual also lists it as AS-Safe, so the async-signal-safety caveat in the debt entry now only applies to glibc older than 2.35. After the change, on ubuntu-latest (AMD EPYC 7763), 9 rounds of 100k faults, each iteration doing mprotect R, a faulting 8-byte store and the handler's mprotect RW back, median ns per iteration over three runs ([run](https://github.com/Jev1337/AnyPS5/actions/runs/39673645161)): | | ns | |---|---| | host-code fault, host handler only | 8160–8299 | | same, guest handler for 11 installed (classified, then chained) | 8208–8258 | | title-code fault delivered to the guest handler | 9068–9136 | So chaining is within noise now, and delivering costs a bit under a microsecond more than a plain host handler. That includes the context log line from #7655. The benchmark isn't part of the PR. On a handler that returns without touching the context: it runs again on the same fault. I looked at what FreeBSD does, and it's the same thing there. [`sendsig` and `sys_sigreturn` in machdep.c](https://github.com/freebsd/freebsd-src/blob/stable/11/sys/amd64/amd64/machdep.c) save the trap frame into the ucontext and copy it straight back, so the faulting instruction runs again and a handler that doesn't fix anything loops there as well. I'd rather not turn that into a crash report. The common pattern is to fix the page with mprotect and return the context unchanged (incremental GCs, write barriers), and telling the two apart would mean guessing, which could kill a title that works on the console. The process does end with the crash report when the handler removes itself and returns, or calls exit/abort. The new commit tests all three cases: - returning unchanged calls the handler again (three times here, then it resumes); - fixing the page and returning lets the store complete after one call; - removing itself and returning ends the process with the access violation. That last one runs in a child process, so a loop shows up as a 10 s timeout instead of a hung ctest. I made sure it does fail that way when the handler doesn't remove itself. The debt entry now also says the console isn't verified here. The red zone one bugged me too, so I dug into where Windows puts the exception frame. As far as I can tell it builds the `KiUserExceptionDispatcher` frame directly below the faulting rsp with no gap. [ReactOS](https://github.com/reactos/reactos/blob/master/ntoskrnl/ke/amd64/except.c) does `UserRsp = (Context->Rsp - sizeof(KUSER_EXCEPTION_STACK)) & ~15`, and [this write-up on the dispatcher](https://momo5502.com/posts/2024-09-07-a-journey-through-kiuserexceptiondispatcher/) puts the frame at about 0x5d0 bytes. FreeBSD subtracts 128 first, and Linux skips the red zone too. So what's lost is the 128 bytes below rsp, meaning whatever a leaf function kept in its red zone. Registers, the return address and everything from rsp up are intact. A crash-reporting handler that reads the context, walks the stack and exits sees correct data. One that reads below `mc_rsp` sees the dispatcher's frame, and one that resumes such a leaf function resumes it without those values. This happens before any user-mode code runs, so the faults the arena, write-watch and SSE4a handlers already resume on main lose it the same way. This PR doesn't add to it, since the stub runs below the red zone. And on ordering: none of them has to land first. I grepped the full diffs of #4630, #7201 and #6879. They add `sceKernelRaiseException` or context-conversion branches but install no fault handler: no `sigaction` for SIGSEGV/SIGBUS/SIGILL/SIGFPE, no vectored handler, no Mach exception port. #6222 and #7332 are closed now. So this is the only place the hook is implemented, and #6879's `CallHandler(handler, RaisedSignal, ucontext)` still builds because the trap argument defaults to zero. Fault delivery on macOS would be a follow-up on the same POSIX path, using `__es.__trapno`/`__err`/`__faultvaddr` instead of `REG_TRAPNO`, and `GuestWriteWatchHandleFault` is already there so the macOS watch would still go first. On size, 602 of the lines are the test; the code is about 330 lines in `Exception.cpp` and 37 in libc.
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!7192
No description provided.