feat(libkernel): deliver host faults to sceKernelInstallExceptionHandler handlers #7192
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/7192"
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 Jev1337 on 2026-10-17T15:42:46Z.
What
sceKernelInstallExceptionHandlerrecorded handlers for signals 4, 8, 10 and 11 but never called them: a host fault always ended the process (see the removed entry indocs/dev/debt/libkernel.md). Handlers now receive the faults raised in title code, and execution resumes from the context the handler leaves, as FreeBSD'ssendsig/sigreturndo.trap()andtrap.h: #UD → SIGILL,mc_trapno1 (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) withmc_addr= fault address andmc_err= page-fault error code. Other traps leavemc_addr0, as exception.S does. Linux #NP/#SS also map to SIGBUS 26/27..elfsections of relinked images (the whole executable when not relinked) on Windows, the executable and.guest.prxmodules on Linux. Faults in the system libraries, the host runtime and drivers still go to the crash report.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 theCONTEXTtoAps5FaultEntryStubbelow the red zone and returnsEXCEPTION_CONTINUE_EXECUTION; the stub saves YMM0-15 and the handler runs outside the exception dispatcher (so it canlongjmpout or fault again), then resumes through the existingAps5RedirectedExit/RtlRestoreContextpath ofsceKernelRaiseException.SA_NODEFER) classify byREG_TRAPNO(Linux reports #GP as SIGSEGV), take only kernel-generated faults (si_code > 0) and chain everything else to the previous handlers.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 ofException.cpp, and #4630/#5918 edit neighbouring lines ofdocs/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 newtrapargument ofCallHandlerdefaults to zero (theirCallHandler(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.guest_exception_fault: null read (trapno, addr, err U only), write to a read-only page (err P|W|U),ud2, idiv by 0 andINT_MIN / -1, unmasked SSEdivssby 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,longjmpout 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 withmprotectand 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 theInstallFaultDeliverycall removed the test dies with SegFault.086c0686c(keeping main'sQueueWaitingDelivery/Redirectdelivery):guest_exception_fault,guest_exception_handler,guest_raise_exceptionandguest_sigaltstackpass 3 runs of 3, and all 191 tests matchingraise|exception|signal|sigaltpass (guest_raise_in_system_call*,guest_raise_in_host_code,guest_raise_leaves_host_code,guest_raise_short_sleep*,windows_exceptionsamong them). The full suite was not rerun on this base; the next line is from the previous one.cteston0c6a5bd59: 1869/1876 pass.agc_driver_sample_order,agc_driver_sample_order_grid_referenceandagc_driver_sample_order_recipe_depth_locationsfail onmaintoo on this GPU (RTX 3070);agc_driver_image_array_window_past_layer_limitdoes not build with MinGW onmain(alignas(65536));guest_video_out_high_frame_rate,guest_memoryandguest_raise_in_system_callfailed under-j 12and pass alone.guest_raise_in_system_calltimes out 2 of 30 runs next to an 11-jobagc_load with this branch and withmainalike.ubuntu-latestrunner (Ubuntu, GCC, AMD EPYC 7763), the same configure as CI withBUILD_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_lifecycleandagc_write_watch_coveragepass, 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; withdladdr1the chained case was about 8 us slower (run). Thelinuxjob ofbuild.ymlneeds the self-hosted runner, so the full Linux suite still needs a maintainer run.guest_exception_faultthree runs in a row (run on my fork).Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)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.
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
sceKernelInstallExceptionHandlerfor 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:
GuestWriteWatchCoverssays the faulting address is watched, before delivering to the guest handler.Two non-blocking questions:
GuestCodetreats an emptyl_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".dladdr1isn't async-signal-safe. It's only reached afterClassifysucceeds and a handler exists, so it seems acceptable, but it's worth a line in the debt doc.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 withUFFD_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 newGuestWriteWatchHandleFault, and the handler is skipped only if the watch actually claims it. UsingCoversalone would also catch real protection faults on watched pages (say a game makes one read-only withsceKernelMprotectand then writes to it), and those should still reach the game's handler.The test you asked for is in:
TestWatchedStoreinstalls 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", likeGuestMemory.cppdoes.Your two questions:
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-rosettaconversion 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.elfsections 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.Imported from boykopovar/AnyPS5. Originally posted by blawesom on 2026-10-18T10:41:30Z.
Rebase handoff — rebased onto current
main(authorship unchanged). Two conflicts inGuestWriteWatch:main's newerOverlapsmachinery kept alongside yourHandleFaultdelivery (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 knownmainregression (agc_driver_tessellationsegfault — Mesa, #5444), not this PR (your fault-delivery entry is Apple-gated and skips on Linux).To pick it up:
Head is
ab3957816.Imported from boykopovar/AnyPS5. Originally posted by Jev1337 on 2026-10-18T12:51:34Z.
Thanks for picking this up!
mainhad 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:Overlapsstays andHandleFaultgoes next to it. Small nit on yours: the closing brace ofOverlapslost its indentation (line 394). That's fixed in mine.One correction: only the write-watch
HandleFaulthook 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, andguest_exception_faultruns 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.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()andtrap.h), the "only title code gets faults" rule and the Windows redirect through a stub (so the handler runs outside the exception dispatcher and canlongjmp) 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.sceKernelInstallExceptionHandlerfor 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 withSA_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.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.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
Deliveryinitializers.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 WindowsReportCrash. So a write-watched workload never gets intoDeliverFault, whichTestWatchedStorechecks 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_objectlike libc's unwinder already does; older glibc keepsdladdr1. 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):
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.
sendsigandsys_sigreturnin 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:
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
KiUserExceptionDispatcherframe directly below the faulting rsp with no gap. ReactOS doesUserRsp = (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 belowmc_rspsees 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
sceKernelRaiseExceptionor context-conversion branches but install no fault handler: nosigactionfor 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'sCallHandler(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/__faultvaddrinstead ofREG_TRAPNO, andGuestWriteWatchHandleFaultis 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 inException.cppand 37 in libc.