feat(libkernel): deliver sceKernelRaiseException on Linux #1431

Merged
Zaid-Talib merged 2 commits from upstream-pr/1431 into main 2026-10-11 09:22:31 +00:00
Zaid-Talib commented 2026-10-08 05:51:22 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Zaid-Talib on 2026-10-08T05:51:22Z.


What

sceKernelRaiseException threw NotImplemented on Linux, so a title whose garbage collector stops threads with it (Unity's PS5Util module: installs a SIGUSR1 handler with sceKernelInstallExceptionHandler, raises it on each thread and reads mc_rsp from the context) could not run there. Two commits:

  1. feat(libkernel): deliver sceKernelRaiseException on Linux: the raise sends the host SIGUSR1 to the target thread with pthread_kill (model: shadPS4 exception.cpp, a sigaction wrapper with SA_SIGINFO | SA_RESTART). The host handler builds the FreeBSD-layout ucontext the Windows path already uses (general registers, rip, rsp, rflags, cs, ss, 512-byte FXSAVE area), calls the guest handler on the target's own stack and writes the registers back. Only the 416 bytes up to XMM15 are written back: the rest of the FXSAVE area holds the kernel's XSAVE frame marker. A raise on another thread blocks the host signal, takes the target's join lock and returns ESRCH once the thread has finished. The handler table is lock-free because the host handler reads it.
  2. fix(libkernel): keep raises off unregistered threads and clamp the handler's MXCSR: scePthreadCreate blocks all signals around pthread_create and RunThread restores the creator's mask once the thread is registered, so a raise right after creation cannot reach a thread whose scePthreadSelf() would adopt a second handle. The MXCSR a handler leaves is masked with MXCSR_MASK (0xffbf when it reads 0), as FreeBSD's fpusetregs does, on both platforms; without it a reserved bit made rt_sigreturn fail with SIGSEGV.

guest_raise_exception is now registered on every platform. TechnicalDebt: the "throws on Linux" line is replaced by what still differs from the console (the handler runs wherever the thread was interrupted, host waits resume, calls Linux does not restart return early or EINTR).

Tested

Rebased onto main ac2c5c08c (the reviewer resolved the conflicts with the pthread_create thread start and the Windows-only test). Linux, GCC, libkernel scope: guest_raise_exception passes 20/20 in a row, guest_signals, guest_exception_handler and the guest_pthread_* tests pass; the new test fails without the source changes. Covers: self, busy, waiting in sceKernelWaitSema, blocked on a host mutex, leaving a wait; register round trip (r12, r13, xmm8, MXCSR including a reserved bit); 50 raises right after scePthreadCreate checking scePthreadSelf() in the handler; a finished thread returns ESRCH.
Third parties: Hollow Knight: Silksong (PPSA12544, Arch, RX 9070 XT, @hugodearaujo) gets past sceKernelRaiseException not implemented; God of War Sons of Sparta (PPSA28997, Arch, RTX 3050, @GustavoGamarra95) boots and plays several levels with this branch and #1482. Windows: not run here; @popcoder565 ran the pre-split branch on Windows 10.

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 in TechnicalDebt
  • 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
  • AI-assisted: yes

Cloud credits project contribution

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4782446689 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1431). Originally posted by [Zaid-Talib](https://github.com/Zaid-Talib) on 2026-10-08T05:51:22Z. --- ### What `sceKernelRaiseException` threw `NotImplemented` on Linux, so a title whose garbage collector stops threads with it (Unity's PS5Util module: installs a SIGUSR1 handler with `sceKernelInstallExceptionHandler`, raises it on each thread and reads `mc_rsp` from the context) could not run there. Two commits: 1. `feat(libkernel): deliver sceKernelRaiseException on Linux`: the raise sends the host SIGUSR1 to the target thread with `pthread_kill` (model: [shadPS4 `exception.cpp`](https://github.com/shadps4-emu/shadPS4/blob/main/src/core/libraries/kernel/threads/exception.cpp), a `sigaction` wrapper with `SA_SIGINFO | SA_RESTART`). The host handler builds the FreeBSD-layout `ucontext` the Windows path already uses (general registers, rip, rsp, rflags, cs, ss, 512-byte FXSAVE area), calls the guest handler on the target's own stack and writes the registers back. Only the 416 bytes up to XMM15 are written back: the rest of the FXSAVE area holds the kernel's XSAVE frame marker. A raise on another thread blocks the host signal, takes the target's join lock and returns `ESRCH` once the thread has finished. The handler table is lock-free because the host handler reads it. 2. `fix(libkernel): keep raises off unregistered threads and clamp the handler's MXCSR`: `scePthreadCreate` blocks all signals around `pthread_create` and `RunThread` restores the creator's mask once the thread is registered, so a raise right after creation cannot reach a thread whose `scePthreadSelf()` would adopt a second handle. The MXCSR a handler leaves is masked with `MXCSR_MASK` (0xffbf when it reads 0), as FreeBSD's `fpusetregs` does, on both platforms; without it a reserved bit made `rt_sigreturn` fail with SIGSEGV. `guest_raise_exception` is now registered on every platform. TechnicalDebt: the "throws on Linux" line is replaced by what still differs from the console (the handler runs wherever the thread was interrupted, host waits resume, calls Linux does not restart return early or `EINTR`). ### Tested Rebased onto `main` ac2c5c08c (the reviewer resolved the conflicts with the `pthread_create` thread start and the Windows-only test). Linux, GCC, libkernel scope: `guest_raise_exception` passes 20/20 in a row, `guest_signals`, `guest_exception_handler` and the `guest_pthread_*` tests pass; the new test fails without the source changes. Covers: self, busy, waiting in `sceKernelWaitSema`, blocked on a host mutex, leaving a wait; register round trip (r12, r13, xmm8, MXCSR including a reserved bit); 50 raises right after `scePthreadCreate` checking `scePthreadSelf()` in the handler; a finished thread returns `ESRCH`. Third parties: Hollow Knight: Silksong (PPSA12544, Arch, RX 9070 XT, @hugodearaujo) gets past `sceKernelRaiseException not implemented`; God of War Sons of Sparta (PPSA28997, Arch, RTX 3050, @GustavoGamarra95) boots and plays several levels with this branch and #1482. Windows: not run here; @popcoder565 ran the pre-split branch on Windows 10. ### 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 in [TechnicalDebt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/TechnicalDebt.md#silent-stubs) - [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] AI-assisted: yes [Cloud credits project contribution](https://claude.ai/code/session_01LwJx7AHrSUaMGSpEGhL1Kb)
oneandonlydean commented 2026-10-08 06:37:32 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-08T06:37:32Z.


Please split this into separate PRs: the per-thread sigprocmask with FreeBSD's bit layout, sceKernelRaiseException on Linux, and the sleepUs EINTR fix in AudioOut. One topic per PR; at +773 lines across those it can't be reviewed or gated as one. For the Linux raise, the title ID and the log line where it stops on main would show the need.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6054015516 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1431#issuecomment-6054015516). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-08T06:37:32Z. --- Please split this into separate PRs: the per-thread `sigprocmask` with FreeBSD's bit layout, `sceKernelRaiseException` on Linux, and the `sleepUs` EINTR fix in AudioOut. One topic per PR; at +773 lines across those it can't be reviewed or gated as one. For the Linux raise, the title ID and the log line where it stops on main would show the need.
popcoder565 commented 2026-10-08 07:09:04 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by popcoder565 on 2026-10-08T07:09:04Z.


Since Windows wasn't run, I ran it there before the split, in case it helps the Windows half: Windows 10 (19045), MinGW-w64 GCC 15.2.0 (WinLibs), Release, main bc1fbe81 merged with 24f89cf0.

  • guest_signals passes 10 of 10 runs and guest_exception_handler 5 of 5.
  • guest_raise_exception hangs in 10 of 10 runs (ctest timeout). In 9 runs it hangs in the new toggling phase. The 10th hangs in the busy phase, which is the NtContinue race #1421 fixes, independent of this PR.

In the toggling hang, main waits in scePthreadJoin, and both toggling threads are stuck in the same place:

#0 libwinpthread-1.dll
#1 libwinpthread-1.dll
#2 __gthread_getspecific              gthr-default.h
#3 __emutls_get_address (obj=__emutls_v._ZL13currentThread)
#4 scePthreadSelf                     libkernel.prx

MinGW's thread_local goes through emutls and winpthreads' pthread_getspecific, which takes a per-thread spinlock (spin_keys in mingw-w64's pthread.c). _sigprocmask_nid_postfix calls scePthreadSelf() before it claims SIGUSR1's bit, so a raise can land while the thread holds that spinlock. The delivery then ends in DeliverUnblocked, which self-raises the SIGUSR1 that went pending, and RaiseOn checks thread == scePthreadSelf() on that same thread. It spins on the lock the interrupted frame holds. Any emutls thread_local read on the delivery path can do the same, for example currentThread and the TimedWait wait state.

A way out could be to identify the current thread on the delivery path without emutls: compare GetCurrentThreadId() with the target's native thread id, or pass the PthreadPrivate& that Deliver already has to a self-delivery helper instead of going through sceKernelRaiseException.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6054562503 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1431#issuecomment-6054562503). Originally posted by [popcoder565](https://github.com/popcoder565) on 2026-10-08T07:09:04Z. --- Since Windows wasn't run, I ran it there before the split, in case it helps the Windows half: Windows 10 (19045), MinGW-w64 GCC 15.2.0 (WinLibs), Release, `main` bc1fbe81 merged with 24f89cf0. - `guest_signals` passes 10 of 10 runs and `guest_exception_handler` 5 of 5. - `guest_raise_exception` hangs in 10 of 10 runs (ctest timeout). In 9 runs it hangs in the new toggling phase. The 10th hangs in the busy phase, which is the `NtContinue` race #1421 fixes, independent of this PR. In the toggling hang, main waits in `scePthreadJoin`, and both toggling threads are stuck in the same place: ``` #0 libwinpthread-1.dll #1 libwinpthread-1.dll #2 __gthread_getspecific gthr-default.h #3 __emutls_get_address (obj=__emutls_v._ZL13currentThread) #4 scePthreadSelf libkernel.prx ``` MinGW's `thread_local` goes through emutls and winpthreads' `pthread_getspecific`, which takes a per-thread spinlock (`spin_keys` in mingw-w64's `pthread.c`). `_sigprocmask_nid_postfix` calls `scePthreadSelf()` before it claims SIGUSR1's bit, so a raise can land while the thread holds that spinlock. The delivery then ends in `DeliverUnblocked`, which self-raises the SIGUSR1 that went pending, and `RaiseOn` checks `thread == scePthreadSelf()` on that same thread. It spins on the lock the interrupted frame holds. Any emutls `thread_local` read on the delivery path can do the same, for example `currentThread` and the `TimedWait` wait state. A way out could be to identify the current thread on the delivery path without emutls: compare `GetCurrentThreadId()` with the target's native thread id, or pass the `PthreadPrivate&` that `Deliver` already has to a self-delivery helper instead of going through `sceKernelRaiseException`.
popcoder565 commented 2026-10-08 07:45:16 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by popcoder565 on 2026-10-08T07:45:16Z.


Follow-up: the same deadlock reproduces on main without this PR, when a handler reads a thread_local while the target is interrupted inside scePthreadSelf. #1421 now retries any raise that finds its target inside libwinpthread-1.dll (384078c9), so the toggling phase should stop hanging once this is rebased on it.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6055210362 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1431#issuecomment-6055210362). Originally posted by [popcoder565](https://github.com/popcoder565) on 2026-10-08T07:45:16Z. --- Follow-up: the same deadlock reproduces on `main` without this PR, when a handler reads a `thread_local` while the target is interrupted inside `scePthreadSelf`. #1421 now retries any raise that finds its target inside `libwinpthread-1.dll` (384078c9), so the toggling phase should stop hanging once this is rebased on it.
oneandonlydean commented 2026-10-09 09:22:08 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-09T09:22:08Z.


The branch now has only the Linux sceKernelRaiseException delivery and the MXCSR clamp, but the title and description still describe the five-commit version (per-thread sigprocmask, AudioOut). Please update them to match the diff.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6078118463 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1431#issuecomment-6078118463). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-09T09:22:08Z. --- The branch now has only the Linux `sceKernelRaiseException` delivery and the MXCSR clamp, but the title and description still describe the five-commit version (per-thread `sigprocmask`, AudioOut). Please update them to match the diff.
hugodearaujo commented 2026-10-09 12:41:07 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hugodearaujo on 2026-10-09T12:41:07Z.


Also gets Hollow Knight: Silksong (PPSA12544) further on Linux (Arch, GCC, RX 9070 XT). On current main (d70b89989) with #1836 applied (without it, the title stops earlier at shader registration), it stops at:

terminate called after throwing an instance of 'std::runtime_error'
  what():  sceKernelRaiseException not implemented

With this branch merged on top as well, that raise is delivered. The title loads globalgamemanagers, unity default resources and sharedassets0, and opens level0. It then stops on an uncaught Il2CppExceptionWrapper, which looks unrelated to signal delivery. It is most likely a Unity plugin that cannot start on Linux yet (#846).

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6081089166 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1431#issuecomment-6081089166). Originally posted by [hugodearaujo](https://github.com/hugodearaujo) on 2026-10-09T12:41:07Z. --- Also gets Hollow Knight: Silksong (PPSA12544) further on Linux (Arch, GCC, RX 9070 XT). On current `main` (`d70b89989`) with #1836 applied (without it, the title stops earlier at shader registration), it stops at: ``` terminate called after throwing an instance of 'std::runtime_error' what(): sceKernelRaiseException not implemented ``` With this branch merged on top as well, that raise is delivered. The title loads `globalgamemanagers`, `unity default resources` and `sharedassets0`, and opens `level0`. It then stops on an uncaught `Il2CppExceptionWrapper`, which looks unrelated to signal delivery. It is most likely a Unity plugin that cannot start on Linux yet (#846).
adriadam10 commented 2026-10-09 21:27:40 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-09T21:27:40Z.

Review: CHANGES_REQUESTED


Thanks for splitting this. Two things before it can be reviewed and merged:

  • The branch conflicts with main in core/libs/tests/GuestRaiseException.cpp (#1478 changed it). Please rebase and rerun guest_raise_exception and guest_signals.
  • The title and description still describe the five-commit version (per-thread sigprocmask, AudioOut sleepUs, 409 ctest results, stress runs, mutation checks for code that is no longer here), as @oneandonlydean asked on Oct 9. Please rewrite them for the current diff: Linux sceKernelRaiseException delivery, the startup signal block in scePthreadCreate, and the MXCSR clamp. Update "Tested" with what you ran on this head, and the list of overlapping PRs.

Useful for the description: the Silksong (PPSA12544) log @hugodearaujo posted, where main stops at sceKernelRaiseException not implemented.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5475510145 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1431#pullrequestreview-5475510145). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-09T21:27:40Z. **Review:** CHANGES_REQUESTED --- Thanks for splitting this. Two things before it can be reviewed and merged: - The branch conflicts with `main` in `core/libs/tests/GuestRaiseException.cpp` (#1478 changed it). Please rebase and rerun `guest_raise_exception` and `guest_signals`. - The title and description still describe the five-commit version (per-thread `sigprocmask`, AudioOut `sleepUs`, 409 ctest results, stress runs, mutation checks for code that is no longer here), as @oneandonlydean asked on Oct 9. Please rewrite them for the current diff: Linux `sceKernelRaiseException` delivery, the startup signal block in `scePthreadCreate`, and the MXCSR clamp. Update "Tested" with what you ran on this head, and the list of overlapping PRs. Useful for the description: the Silksong (PPSA12544) log @hugodearaujo posted, where `main` stops at `sceKernelRaiseException not implemented`.
GustavoGamarra95 commented 2026-10-11 02:48:09 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by GustavoGamarra95 on 2026-10-11T02:48:09Z.


Another title this gets further on Linux: God of War Sons of Sparta (PPSA28997, Unity IL2CPP). Its GC stops threads with sceKernelRaiseException, so on main it stops with sceKernelRaiseException not implemented right after creating its job workers. With this branch (head 77143010) the raise is delivered, and the title boots and plays through several levels on Arch Linux (RTX 3050), together with #1482.

To test it I had to rebase it onto main 942a174e myself. The conflicts included Pthread.hpp, Exception.cpp, Thread.cpp and GuestRaiseException.cpp:

  • Thread.cpp: main now creates guest threads with pthread_create instead of std::thread. I blocked all signals around pthread_create, restored the creator's mask on both the success and the failure path, and set the saved mask in RunThread as the branch does.
  • GuestRaiseException.cpp: I did not merge it, because main added Windows checks in the same places as the branch's Linux ones.

I can share the resolved diff if it helps.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6104749910 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1431#issuecomment-6104749910). Originally posted by [GustavoGamarra95](https://github.com/GustavoGamarra95) on 2026-10-11T02:48:09Z. --- Another title this gets further on Linux: God of War Sons of Sparta (PPSA28997, Unity IL2CPP). Its GC stops threads with `sceKernelRaiseException`, so on `main` it stops with `sceKernelRaiseException not implemented` right after creating its job workers. With this branch (head 77143010) the raise is delivered, and the title boots and plays through several levels on Arch Linux (RTX 3050), together with #1482. To test it I had to rebase it onto `main` 942a174e myself. The conflicts included `Pthread.hpp`, `Exception.cpp`, `Thread.cpp` and `GuestRaiseException.cpp`: - **`Thread.cpp`:** `main` now creates guest threads with `pthread_create` instead of `std::thread`. I blocked all signals around `pthread_create`, restored the creator's mask on both the success and the failure path, and set the saved mask in `RunThread` as the branch does. - **`GuestRaiseException.cpp`:** I did not merge it, because `main` added Windows checks in the same places as the branch's Linux ones. I can share the resolved diff if it helps.
adriadam10 commented 2026-10-11 09:20:10 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-11T09:20:10Z.

Review: APPROVED


Rebased onto current main (c356112f3) and fixed the two points from the earlier review ourselves:

  • Conflicts resolved: guest threads now start with pthread_create, so the startup signal block wraps that call and RunThread restores the creator's mask; GuestRaiseException.cpp now runs on every platform, with the Windows-only parts under #ifdef _WIN32; removed the duplicated handlerSelf.
  • Title and description rewritten for the current diff (Linux delivery, startup signal block, MXCSR clamp), with the Silksong and God of War: Sons of Sparta reports.

Checked: guest_raise_exception 20/20 in a row, guest_signals, guest_exception_handler and guest_pthread_* green on Linux; the test fails without the source changes. Windows not run here.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5482734188 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1431#pullrequestreview-5482734188). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-11T09:20:10Z. **Review:** APPROVED --- Rebased onto current `main` (c356112f3) and fixed the two points from the earlier review ourselves: - Conflicts resolved: guest threads now start with `pthread_create`, so the startup signal block wraps that call and `RunThread` restores the creator's mask; `GuestRaiseException.cpp` now runs on every platform, with the Windows-only parts under `#ifdef _WIN32`; removed the duplicated `handlerSelf`. - Title and description rewritten for the current diff (Linux delivery, startup signal block, MXCSR clamp), with the Silksong and God of War: Sons of Sparta reports. Checked: `guest_raise_exception` 20/20 in a row, `guest_signals`, `guest_exception_handler` and `guest_pthread_*` green on Linux; the test fails without the source changes. Windows not run here.
github-actions[bot] commented 2026-10-11 09:21:44 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-11T09:21:44Z.


Progress report (e272b92 → c356112)

📈 System libraries: 85.48% (+0.03%, +1 implemented functions)

✅ 1 implemented
Library Name
libkernel sceKernelRaiseException
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6107538431 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1431#issuecomment-6107538431). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-11T09:21:44Z. --- <!-- progress-report --> ### Progress report (e272b92 → c356112) 📈 **System libraries**: 85.48% (+0.03%, +1 implemented functions) <details> <summary>✅ 1 implemented</summary> | Library | Name | | - | - | | libkernel | `sceKernelRaiseException` | </details>
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!1431
No description provided.