feat(libkernel): deliver sceKernelRaiseException on Windows #760

Merged
merwie merged 9 commits from upstream-pr/760 into main 2026-10-07 20:27:40 +00:00
merwie commented 2026-10-05 21:33:58 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by merwie on 2026-10-05T21:33:58Z.


What

sceKernelRaiseException(thread, signum) threw. On Windows it now runs the handler recorded by sceKernelInstallExceptionHandler (#724) on the target thread, with a PS5 ucontext of the interrupted state (16-byte uc_sigmask, 48 bytes, FreeBSD amd64 mcontext at 0x40, mc_rsp at 0xf8; checked with static_assert), as proposed in #727:

  • Calling thread: the handler runs directly with the captured context.
  • Thread in a libkernel wait: the TimedWait waits (Condition signal waits, timer waits, sleeps) are alertable and count themselves in a per-thread wait state (PthreadPrivate::waitState). If the suspended target is in such a wait, the delivery is queued with QueueUserAPC; the handler runs on the target inside its wait, with a context captured there, and the wait continues afterwards (an APC returns WAIT_IO_COMPLETION, which the waits retry).
  • Running thread: SuspendThread + GetThreadContext, copy the delivery onto the target's own stack below its 128-byte red zone, with the entry's 32-byte home area below that copy (refused if those pages are not committed), and redirect rip to an entry that builds the ucontext, calls the handler, writes back the possibly modified registers and returns with RtlRestoreContext.

Only SIGUSR1 (30) can be raised, as in shadPS4; other signals return SCE_KERNEL_ERROR_EINVAL, a null thread SCE_KERNEL_ERROR_ESRCH, and raising without an installed handler throws. Linux still throws (the host signal choice is open in #727). Known limits, also in #727: a thread blocked in a host wait outside TimedWait (or with APS5_COARSE_TIMED_WAITS) does not run the handler until it returns to guest code or enters such a wait; signal masks are not consulted.

  • New Windows test guest_raise_exception, which checks:
    • raising an unsupported signal, and raising without a handler;
    • raising on the calling thread;
    • 100 raises on a busy worker and 100 on a worker blocked in sceKernelWaitSema. Each checks that the handler ran on that worker, that mc_rsp is set and lies above the handler's frame, and that the worker continues (the blocked one returns from its wait once the semaphore is signaled).
    • HostBlocked, 20 rounds: a worker blocked on a host std::mutex, a non-alertable wait in a system call. That wait takes the redirect path, so the handler runs only once the wait returns to guest code. The thread then resumes through sysret, which overwrites rcx/r11. Each round raises while the worker is blocked, releases the mutex, and expects exactly one delivery on that worker. This pins that the redirect entry takes the delivery from rsp and the live registers (the wait gets its real result in rax), not from rcx or the stale snapshot.
    • Raising on a thread that has returned but is not yet joined returns ESRCH.

Tested

Windows 11, WinLibs GCC 15.2.0 r7, Ryzen 7 9800X3D, Radeon RX 9070 XT.

  • ctest: 317/319 passed, including guest_raise_exception (also 10 consecutive runs, 2000 deliveries). agc_driver_lds_atomics64 and agc_driver_vopc_compare_table fail on this machine on main as well (Vulkan device tests).
  • PPSA12544 (Hollow Knight: Silksong, Unity IL2CPP): its GC stop-the-world (PS5Util, see #726) raises SIGUSR1 on threads blocked in libkernel waits; the handlers run and return, the collector proceeds, and the title goes on to load level0.

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: #724 (its commit is included here)
  • AI-assisted: yes

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4751025048 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/760). Originally posted by [merwie](https://github.com/merwie) on 2026-10-05T21:33:58Z. --- ### What `sceKernelRaiseException(thread, signum)` threw. On Windows it now runs the handler recorded by `sceKernelInstallExceptionHandler` (#724) on the target thread, with a PS5 `ucontext` of the interrupted state (16-byte `uc_sigmask`, 48 bytes, FreeBSD amd64 `mcontext` at 0x40, `mc_rsp` at 0xf8; checked with `static_assert`), as proposed in #727: - **Calling thread:** the handler runs directly with the captured context. - **Thread in a libkernel wait:** the `TimedWait` waits (`Condition` signal waits, timer waits, sleeps) are alertable and count themselves in a per-thread wait state (`PthreadPrivate::waitState`). If the suspended target is in such a wait, the delivery is queued with `QueueUserAPC`; the handler runs on the target inside its wait, with a context captured there, and the wait continues afterwards (an APC returns `WAIT_IO_COMPLETION`, which the waits retry). - **Running thread:** `SuspendThread` + `GetThreadContext`, copy the delivery onto the target's own stack below its 128-byte red zone, with the entry's 32-byte home area below that copy (refused if those pages are not committed), and redirect `rip` to an entry that builds the `ucontext`, calls the handler, writes back the possibly modified registers and returns with `RtlRestoreContext`. Only SIGUSR1 (30) can be raised, as in shadPS4; other signals return `SCE_KERNEL_ERROR_EINVAL`, a null thread `SCE_KERNEL_ERROR_ESRCH`, and raising without an installed handler throws. Linux still throws (the host signal choice is open in #727). Known limits, also in #727: a thread blocked in a host wait outside `TimedWait` (or with `APS5_COARSE_TIMED_WAITS`) does not run the handler until it returns to guest code or enters such a wait; signal masks are not consulted. - New Windows test `guest_raise_exception`, which checks: - raising an unsupported signal, and raising without a handler; - raising on the calling thread; - 100 raises on a busy worker and 100 on a worker blocked in `sceKernelWaitSema`. Each checks that the handler ran on that worker, that `mc_rsp` is set and lies above the handler's frame, and that the worker continues (the blocked one returns from its wait once the semaphore is signaled). - `HostBlocked`, 20 rounds: a worker blocked on a host `std::mutex`, a non-alertable wait in a system call. That wait takes the redirect path, so the handler runs only once the wait returns to guest code. The thread then resumes through `sysret`, which overwrites `rcx`/`r11`. Each round raises while the worker is blocked, releases the mutex, and expects exactly one delivery on that worker. This pins that the redirect entry takes the delivery from `rsp` and the live registers (the wait gets its real result in `rax`), not from `rcx` or the stale snapshot. - Raising on a thread that has returned but is not yet joined returns `ESRCH`. ### Tested Windows 11, WinLibs GCC 15.2.0 r7, Ryzen 7 9800X3D, Radeon RX 9070 XT. - `ctest`: 317/319 passed, including `guest_raise_exception` (also 10 consecutive runs, 2000 deliveries). `agc_driver_lds_atomics64` and `agc_driver_vopc_compare_table` fail on this machine on `main` as well (Vulkan device tests). - PPSA12544 (Hollow Knight: Silksong, Unity IL2CPP): its GC stop-the-world (PS5Util, see #726) raises SIGUSR1 on threads blocked in libkernel waits; the handlers run and return, the collector proceeds, and the title goes on to load `level0`. ### Checklist - [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 - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed in TechnicalDebt - [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: #724 (its commit is included here) - [x] AI-assisted: yes 🤖 Generated with [Claude Code](https://claude.com/claude-code)
oneandonlydean commented 2026-10-05 22:56:51 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-05T22:56:51Z.


Thanks for this. One thing in the redirect path for a running thread:

RedirectedEntry is an ordinary MinGW function, so it uses the Windows x64 convention, where the callee owns the 32-byte home area above its return address. With Rsp = ((Rsp - 128) & ~15) - 8, that home area is [new Rsp + 8, new Rsp + 40), and it starts at or just below old Rsp - 128. So the top of it falls inside the guest's 128-byte red zone, which the description says the entry stays below. GCC can spill rcx (the Delivery*) there, which would overwrite live guest data. Reserving another 32 bytes, for example ((Rsp - 128 - 32) & ~15) - 8, keeps it clear.

Related, and smaller: RedirectedEntry frees the Delivery with delete on the interrupted thread. If that thread was suspended inside the heap (the heap lock is recursive for its owner), the free runs on a heap that is half updated. Copying the Delivery onto the target's stack below that gap before SetThreadContext, and passing its address in rcx, avoids the heap on that thread entirely.

The rest looks right to me: the ucontext offsets match the static_asserts, waits retry after an APC, and Linux behaviour is unchanged apart from the new EINVAL/ESRCH returns ahead of the throw.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6004893782 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/760#issuecomment-6004893782). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-05T22:56:51Z. --- Thanks for this. One thing in the redirect path for a running thread: `RedirectedEntry` is an ordinary MinGW function, so it uses the Windows x64 convention, where the callee owns the 32-byte home area above its return address. With `Rsp = ((Rsp - 128) & ~15) - 8`, that home area is `[new Rsp + 8, new Rsp + 40)`, and it starts at or just below `old Rsp - 128`. So the top of it falls inside the guest's 128-byte red zone, which the description says the entry stays below. GCC can spill `rcx` (the `Delivery*`) there, which would overwrite live guest data. Reserving another 32 bytes, for example `((Rsp - 128 - 32) & ~15) - 8`, keeps it clear. Related, and smaller: `RedirectedEntry` frees the `Delivery` with `delete` on the interrupted thread. If that thread was suspended inside the heap (the heap lock is recursive for its owner), the free runs on a heap that is half updated. Copying the `Delivery` onto the target's stack below that gap before `SetThreadContext`, and passing its address in `rcx`, avoids the heap on that thread entirely. The rest looks right to me: the `ucontext` offsets match the `static_assert`s, waits retry after an APC, and Linux behaviour is unchanged apart from the new `EINVAL`/`ESRCH` returns ahead of the throw.
merwie commented 2026-10-06 07:59:41 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by merwie on 2026-10-06T07:59:41Z.


Thanks, both fixed in b550545b. The delivery is now copied onto the target stack at (rsp - 128 - sizeof(Delivery)) & ~15, and the entry starts at slot - 32 - 8, so its home area is [slot - 32, slot), below the copy and below the red zone. rcx points at the copy, and nothing on the interrupted thread touches the heap. Before writing, VirtualQuery checks that the pages from the home area up to rsp - 128 are committed, read-write and not a guard page. Otherwise the raise throws, because writing a guard page from the raising thread would break the target's stack growth. Also merged main (the TechnicalDebt line next to #796's, and #761's SetStackFromHost next to waitState in Thread.cpp). Non-GPU tests pass, and guest_raise_exception passed 5 repeated runs.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6011982877 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/760#issuecomment-6011982877). Originally posted by [merwie](https://github.com/merwie) on 2026-10-06T07:59:41Z. --- Thanks, both fixed in b550545b. The delivery is now copied onto the target stack at `(rsp - 128 - sizeof(Delivery)) & ~15`, and the entry starts at `slot - 32 - 8`, so its home area is `[slot - 32, slot)`, below the copy and below the red zone. `rcx` points at the copy, and nothing on the interrupted thread touches the heap. Before writing, `VirtualQuery` checks that the pages from the home area up to `rsp - 128` are committed, read-write and not a guard page. Otherwise the raise throws, because writing a guard page from the raising thread would break the target's stack growth. Also merged `main` (the TechnicalDebt line next to #796's, and #761's `SetStackFromHost` next to `waitState` in `Thread.cpp`). Non-GPU tests pass, and `guest_raise_exception` passed 5 repeated runs.
merwie commented 2026-10-06 13:41:32 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by merwie on 2026-10-06T13:41:32Z.


Found and fixed a real bug in the redirect path while testing PPSA12544 past its intro (3cd2ff91). A thread suspended inside a Windows system call (here Unity's SaveDataProcessQueue, blocked in a host wait) resumes through sysret, which overwrites rcx and r11. So the Delivery* passed in rcx was garbage, and the handler call faulted (call *%r9 with instruction bytes as the pointer). The snapshot from GetThreadContext also still had the system call number in rax, not its result, so restoring it after the handler would have handed the wait a bogus status.

The redirected rip is now a small Aps5RedirectedEntryStub. It stores the live general registers into the delivery's context (static_asserts pin the offsets), takes the delivery from its fixed place 40 bytes above rsp, and jumps to the C++ entry. For a thread interrupted in user mode the live registers equal the snapshot, since rcx is no longer modified. GuestRaiseException gains a case that raises at a thread blocked on a host mutex, in 20 rounds, and expects each delivery once the wait returns. It fails without the change. Non-GPU tests pass.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6017557747 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/760#issuecomment-6017557747). Originally posted by [merwie](https://github.com/merwie) on 2026-10-06T13:41:32Z. --- Found and fixed a real bug in the redirect path while testing PPSA12544 past its intro (3cd2ff91). A thread suspended inside a Windows system call (here Unity's `SaveDataProcessQueue`, blocked in a host wait) resumes through `sysret`, which overwrites `rcx` and `r11`. So the `Delivery*` passed in `rcx` was garbage, and the handler call faulted (`call *%r9` with instruction bytes as the pointer). The snapshot from `GetThreadContext` also still had the system call number in `rax`, not its result, so restoring it after the handler would have handed the wait a bogus status. The redirected `rip` is now a small `Aps5RedirectedEntryStub`. It stores the live general registers into the delivery's context (static_asserts pin the offsets), takes the delivery from its fixed place 40 bytes above `rsp`, and jumps to the C++ entry. For a thread interrupted in user mode the live registers equal the snapshot, since `rcx` is no longer modified. `GuestRaiseException` gains a case that raises at a thread blocked on a host mutex, in 20 rounds, and expects each delivery once the wait returns. It fails without the change. Non-GPU tests pass.
oneandonlydean commented 2026-10-06 22:02:45 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-06T22:02:45Z.


Thanks. #724 (exception handler recording) is merged now, and this branch conflicts with main in core/libs/prx/libkernel/CMakeLists.txt and System/src/Exception.cpp. Could you merge or rebase onto main, keeping your delivery code on top of #724's handler recording?

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6026270324 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/760#issuecomment-6026270324). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-06T22:02:45Z. --- Thanks. #724 (exception handler recording) is merged now, and this branch conflicts with main in `core/libs/prx/libkernel/CMakeLists.txt` and `System/src/Exception.cpp`. Could you merge or rebase onto main, keeping your delivery code on top of #724's handler recording?
merwie commented 2026-10-07 05:45:53 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by merwie on 2026-10-07T05:45:53Z.


Merged main (as a merge, so the review history stays). main's Exception.cpp was identical to the #724 commit this branch already built on, so the delivery code sits unchanged on top of #724's handler recording. In CMakeLists.txt I kept the guest_raise_exception registration next to #724's guest_exception_handler. Non-GPU tests pass (232), including both exception tests.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6031812753 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/760#issuecomment-6031812753). Originally posted by [merwie](https://github.com/merwie) on 2026-10-07T05:45:53Z. --- Merged `main` (as a merge, so the review history stays). `main`'s `Exception.cpp` was identical to the #724 commit this branch already built on, so the delivery code sits unchanged on top of #724's handler recording. In `CMakeLists.txt` I kept the `guest_raise_exception` registration next to #724's `guest_exception_handler`. Non-GPU tests pass (232), including both exception tests.
adriadam10 commented 2026-10-07 15:55:20 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-07T15:55:20Z.

Review: CHANGES_REQUESTED


Thanks, the redirect path and the asm stub look right to me (field offsets of Delivery/CONTEXT match the static_asserts, entry stack is 8 mod 16). A few things before this can go in:

  • Exception.cpp:198: new Delivery runs while the target is suspended. If the target holds the allocator/CRT lock when suspended, the raising thread deadlocks. Allocate before SuspendThread (and don't allocate in any path between suspend and resume, including the throw sites, which should resume first, as the others do).
  • Exception.cpp:197, Thread.cpp:177/411: waitState points into the target's thread_local. Raising on a thread that has already exited but isn't joined (or an adopted thread that exited) reads freed TLS. Please clear the pointer at thread exit (or keep the state in PthreadPrivate) and say what happens when the target already finished (ESRCH?).
  • Exception.cpp:208: only CONTEXT_FULL | CONTEXT_FLOATING_POINT is saved, so the upper halves of YMM are not preserved if the handler or the entry uses AVX. Either capture the XState or document it as a known limit.
  • The limits listed in the description (waits outside TimedWait and APS5_COARSE_TIMED_WAITS, signal masks not consulted, ucontext layout taken from FreeBSD, Linux still throwing) need lines in docs/dev/TechnicalDebt.md (criterion: every unverified choice gets a line, under the right ### section and not at the end of it).
  • The description doesn't mention the third test case (HostBlocked, 20 rounds with a host mutex); please describe what it pins, since it relies on the handler running only after the thread returns to guest code.

Windows runtime behaviour can't be run on our side; the Windows CI job is green, so these are code-review points.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5444875601 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/760#pullrequestreview-5444875601). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-07T15:55:20Z. **Review:** CHANGES_REQUESTED --- Thanks, the redirect path and the asm stub look right to me (field offsets of `Delivery`/`CONTEXT` match the `static_assert`s, entry stack is 8 mod 16). A few things before this can go in: - `Exception.cpp:198`: `new Delivery` runs while the target is suspended. If the target holds the allocator/CRT lock when suspended, the raising thread deadlocks. Allocate before `SuspendThread` (and don't allocate in any path between suspend and resume, including the `throw` sites, which should resume first, as the others do). - `Exception.cpp:197`, `Thread.cpp:177`/`411`: `waitState` points into the target's `thread_local`. Raising on a thread that has already exited but isn't joined (or an adopted thread that exited) reads freed TLS. Please clear the pointer at thread exit (or keep the state in `PthreadPrivate`) and say what happens when the target already finished (`ESRCH`?). - `Exception.cpp:208`: only `CONTEXT_FULL | CONTEXT_FLOATING_POINT` is saved, so the upper halves of YMM are not preserved if the handler or the entry uses AVX. Either capture the XState or document it as a known limit. - The limits listed in the description (waits outside `TimedWait` and `APS5_COARSE_TIMED_WAITS`, signal masks not consulted, `ucontext` layout taken from FreeBSD, Linux still throwing) need lines in `docs/dev/TechnicalDebt.md` (criterion: every unverified choice gets a line, under the right `###` section and not at the end of it). - The description doesn't mention the third test case (`HostBlocked`, 20 rounds with a host mutex); please describe what it pins, since it relies on the handler running only after the thread returns to guest code. Windows runtime behaviour can't be run on our side; the Windows CI job is green, so these are code-review points.
merwie commented 2026-10-07 19:11:00 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by merwie on 2026-10-07T19:11:00Z.


Thanks, all addressed in 51b6079b:

  • Allocation while suspended: the APC Delivery is now allocated before SuspendThread (released to the APC only once queued). The redirect path keeps its copy on our stack. Every throw after the suspend resumes the thread first.
  • waitState into freed TLS: the counter is now a member of PthreadPrivate (waitCount), which outlives the thread. TimedWait counts into it through a thread-local pointer bound when the thread starts (adopted threads too), and falls back to a thread-local counter on threads without one. A raise on a thread that has already finished returns ESRCH. The test raises on a returned, not-yet-joined thread and expects that.
  • YMM upper halves: documented as a known limit rather than capturing the XState.
  • TechnicalDebt: one line each, in Functional, next to #724's (which now says only raised signals are delivered): Windows only (Linux throws); FreeBSD ucontext layout; signal mask not consulted; YMM upper halves; threads outside an alertable TimedWait wait (including APS5_COARSE_TIMED_WAITS and host waits) run the handler only when the wait returns.
  • Description: now covers the HostBlocked case and what it pins.

The exception tests pass 3 runs in a row, and the non-GPU tests pass (232).

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6044955839 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/760#issuecomment-6044955839). Originally posted by [merwie](https://github.com/merwie) on 2026-10-07T19:11:00Z. --- Thanks, all addressed in 51b6079b: - **Allocation while suspended:** the APC `Delivery` is now allocated before `SuspendThread` (released to the APC only once queued). The redirect path keeps its copy on our stack. Every throw after the suspend resumes the thread first. - **`waitState` into freed TLS:** the counter is now a member of `PthreadPrivate` (`waitCount`), which outlives the thread. `TimedWait` counts into it through a thread-local pointer bound when the thread starts (adopted threads too), and falls back to a thread-local counter on threads without one. A raise on a thread that has already finished returns `ESRCH`. The test raises on a returned, not-yet-joined thread and expects that. - **YMM upper halves:** documented as a known limit rather than capturing the XState. - **TechnicalDebt:** one line each, in *Functional*, next to #724's (which now says only raised signals are delivered): Windows only (Linux throws); FreeBSD `ucontext` layout; signal mask not consulted; YMM upper halves; threads outside an alertable `TimedWait` wait (including `APS5_COARSE_TIMED_WAITS` and host waits) run the handler only when the wait returns. - **Description:** now covers the `HostBlocked` case and what it pins. The exception tests pass 3 runs in a row, and the non-GPU tests pass (232).
tv7 commented 2026-10-07 19:25:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by tv7 on 2026-10-07T19:25:24Z.


Data point: PPSA03306 (Silt, Unity) needs this too. On main (cea1ef13) with #1141 and #1196, and its Unity modules relinked to Media/Modules (#716/#717), the title aborts with sceKernelRaiseException not implemented, called from Il2CppUserAssemblies.prx. With this PR merged locally, it gets past that point and loads unity default resources and mscorlib.dll-resources.dat. It later stops at a ud2 in its own libc.prx, right after sceKernelDebugRaiseException(0xa0020008), which looks unrelated to this change. Windows 11, GCC 15.2.0, RTX 3070.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6045207883 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/760#issuecomment-6045207883). Originally posted by [tv7](https://github.com/tv7) on 2026-10-07T19:25:24Z. --- Data point: PPSA03306 (Silt, Unity) needs this too. On `main` (`cea1ef13`) with #1141 and #1196, and its Unity modules relinked to `Media/Modules` (#716/#717), the title aborts with `sceKernelRaiseException not implemented`, called from `Il2CppUserAssemblies.prx`. With this PR merged locally, it gets past that point and loads `unity default resources` and `mscorlib.dll-resources.dat`. It later stops at a `ud2` in its own `libc.prx`, right after `sceKernelDebugRaiseException(0xa0020008)`, which looks unrelated to this change. Windows 11, GCC 15.2.0, RTX 3070.
adriadam10 commented 2026-10-07 20:02:52 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-07T20:02:52Z.

Review: CHANGES_REQUESTED


Thanks, everything from the last round is addressed (allocation before suspend, waitCount in PthreadPrivate, ESRCH on a finished thread, the TechnicalDebt lines). Build and ctest are green on our side against current main, and the Windows job runs guest_raise_exception 3/3. Two new things in the wait path, plus a minor one:

  • TimedWait.cpp:26-31 (AlertableWait, same in AlertableSleep): there is a window after WaitForMultipleObjectsEx returns and before fetch_sub. If RaiseOn suspends the target there, it sees waitCount > 0 and queues an APC (Exception.cpp:199). The thread then leaves the wait and returns to guest code, so the APC only runs at its next alertable TimedWait wait, which may never come. A stop-the-world collector waiting for that handler would hang. One way to close it: after the decrement, drain pending APCs before returning (SleepEx(0, TRUE), or NtTestAlert if yielding is a concern). A raise that suspends the thread after the decrement takes the redirect path anyway.
  • TimedWait.cpp:172: Condition::waitSignalUntil calls EventSet(waiter->event, 0) while holding queueLock, and EventSet is now alertable. A pending APC would run the guest handler with the condition's queueLock held. If the handler notifies that condition, it deadlocks on the non-recursive mutex. That poll is 0 ms anyway, so a non-alertable wait there avoids the problem.
  • Minor, Exception.cpp:276/198: a target that exits between the _finished check and SuspendThread/GetThreadContext/QueueUserAPC makes the raise throw instead of returning ESRCH. Checking WaitForSingleObject(native, 0) == WAIT_OBJECT_0 after the suspend (then resume and return ESRCH) would cover it.
<!-- greyfinch-sync:boykopovar/AnyPS5:review:5447672028 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/760#pullrequestreview-5447672028). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-07T20:02:52Z. **Review:** CHANGES_REQUESTED --- Thanks, everything from the last round is addressed (allocation before suspend, `waitCount` in `PthreadPrivate`, `ESRCH` on a finished thread, the TechnicalDebt lines). Build and ctest are green on our side against current `main`, and the Windows job runs `guest_raise_exception` 3/3. Two new things in the wait path, plus a minor one: - `TimedWait.cpp:26-31` (`AlertableWait`, same in `AlertableSleep`): there is a window after `WaitForMultipleObjectsEx` returns and before `fetch_sub`. If `RaiseOn` suspends the target there, it sees `waitCount > 0` and queues an APC (`Exception.cpp:199`). The thread then leaves the wait and returns to guest code, so the APC only runs at its next alertable `TimedWait` wait, which may never come. A stop-the-world collector waiting for that handler would hang. One way to close it: after the decrement, drain pending APCs before returning (`SleepEx(0, TRUE)`, or `NtTestAlert` if yielding is a concern). A raise that suspends the thread after the decrement takes the redirect path anyway. - `TimedWait.cpp:172`: `Condition::waitSignalUntil` calls `EventSet(waiter->event, 0)` while holding `queueLock`, and `EventSet` is now alertable. A pending APC would run the guest handler with the condition's `queueLock` held. If the handler notifies that condition, it deadlocks on the non-recursive mutex. That poll is 0 ms anyway, so a non-alertable wait there avoids the problem. - Minor, `Exception.cpp:276`/`198`: a target that exits between the `_finished` check and `SuspendThread`/`GetThreadContext`/`QueueUserAPC` makes the raise throw instead of returning `ESRCH`. Checking `WaitForSingleObject(native, 0) == WAIT_OBJECT_0` after the suspend (then resume and return `ESRCH`) would cover it.
merwie commented 2026-10-07 20:11:44 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by merwie on 2026-10-07T20:11:44Z.


Thanks. All three are addressed in 2654e3a4:

  • Window after the wait: AlertableWait and AlertableSleep now run pending APCs right after the count drops (NtTestAlert, with SleepEx(0, TRUE) as a fallback if it can't be resolved). A raise that suspends the thread after the decrement takes the redirect path, as you said. The new Leaving part of guest_raise_exception signals a semaphore and raises at staggered delays while the target leaves its wait, then spins without waiting again (200 rounds). Without the drain it hung 5 of 5 runs; with it, it passes 5 of 5.
  • waitSignalUntil: the 0 ms poll under queueLock is a plain WaitForSingleObject now, so no APC can run with the lock held.
  • Exit during the raise: after SuspendThread, a signalled thread handle resumes and returns ESRCH. A failed suspend on an exited thread also returns ESRCH.

Merged main before this too (TechnicalDebt conflict). Non-GPU tests pass (235).

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6045961414 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/760#issuecomment-6045961414). Originally posted by [merwie](https://github.com/merwie) on 2026-10-07T20:11:44Z. --- Thanks. All three are addressed in 2654e3a4: - **Window after the wait:** `AlertableWait` and `AlertableSleep` now run pending APCs right after the count drops (`NtTestAlert`, with `SleepEx(0, TRUE)` as a fallback if it can't be resolved). A raise that suspends the thread after the decrement takes the redirect path, as you said. The new `Leaving` part of `guest_raise_exception` signals a semaphore and raises at staggered delays while the target leaves its wait, then spins without waiting again (200 rounds). Without the drain it hung 5 of 5 runs; with it, it passes 5 of 5. - **`waitSignalUntil`:** the 0 ms poll under `queueLock` is a plain `WaitForSingleObject` now, so no APC can run with the lock held. - **Exit during the raise:** after `SuspendThread`, a signalled thread handle resumes and returns `ESRCH`. A failed suspend on an exited thread also returns `ESRCH`. Merged `main` before this too (TechnicalDebt conflict). Non-GPU tests pass (235).
adriadam10 commented 2026-10-07 20:27:37 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-07T20:27:37Z.

Review: APPROVED


Thanks, all three points are addressed in 2654e3a4 (APC drain after the count drops, with the Leaving test; non-alertable 0 ms poll under queueLock; ESRCH when the target exits after the suspend). Build and ctest green against current main; the Windows job covers guest_raise_exception. Merging once CI is green.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5447943121 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/760#pullrequestreview-5447943121). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-07T20:27:37Z. **Review:** APPROVED --- Thanks, all three points are addressed in 2654e3a4 (APC drain after the count drops, with the `Leaving` test; non-alertable 0 ms poll under `queueLock`; `ESRCH` when the target exits after the suspend). Build and ctest green against current `main`; the Windows job covers `guest_raise_exception`. Merging once CI is green.
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!760
No description provided.