fix(libkernel): deliver a raised exception at the guest return of a thread in host code #10666

Merged
WallisSkill merged 4 commits from upstream-pr/10666 into main 2026-10-27 01:59:26 +00:00
WallisSkill commented 2026-10-24 16:01:13 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by WallisSkill on 2026-10-24T16:01:13Z.


What

sceKernelRaiseException on Windows no longer redirects a thread that is in host code. Before, RaiseOn suspended the target and, while it sat in host code (libkernel, libc, the HLE modules, the C runtime, ntdll), resampled it until a 50 ms limit and then redirected it into the handler right there. A handler that waits, as Unity's GC thread-stop handler does, then kept whatever host lock the thread held.

In Graveyard Keeper 2 that froze the load after New game in about 1 of 15 runs. The capture of one freeze: the GC thread waited in sceKernelWaitSema with 39 of 40 stop acknowledgements; 39 threads waited on the resume event in the handler; the missing job worker sat at Aps5RedirectedEntryStub because it had been redirected while blocked in a winpthreads lock wait inside Driver::RegisterShader (a redirect only takes effect when the kernel wait ends), and the holder of that lock had been redirected out of ShaderRecompiler::SpecializeSpirv after the 50 ms limit and was parked in the handler.

Now a target in host code is never interrupted where it is. The first of these to reach it delivers (one atomic taken flag per delivery):

  • for a target in a libkernel wait (Pthread::waitCount above 0, the point where the handler already ran before), an APC queued to that wait;
  • for a target anywhere else in host code, running or blocked, an execute breakpoint in debug register 0 at the frame's return address into guest code, found by unwinding the host frames with the image's own .pdata table and RtlVirtualUnwind; the search stops at frames that push a machine frame and is guarded against faults; the return site must follow a call instruction; a vectored handler takes the single-step, clears the breakpoint and runs the handler on the thread;
  • a host deliverer thread that keeps sampling the target (with the debug registers re-armed when the return address moves) and redirects it once it is in guest code.

The raise returns as soon as the delivery is queued. A target in guest code is still redirected at once, and a target inside NtContinue still makes the raise throw after 1 s. The technical debt entry is rewritten for the new behaviour and its gaps (the handler's context holds no vector registers beyond what the C runtime context saves; a target that stays in host code waiting on a thread already stopped is never stopped; debug register 0 used by a debugger or the title is not modeled).

New test guest_raise_leaves_host_code: the handler checks that the interrupted rip lies in the test executable, for a target blocked in WaitForSingleObject (each raise must return in under 500 ms), one busy in MultiByteToWideChar over 64 MiB, and one in an alertable WaitForSingleObjectEx, where the handler must also run only after the wait was released (an APC for every host-code target, the first version of this PR, fails it), 10 rounds each.

Related: #8592 defers Windows exceptions during shader preparation, a different approach to a similar deadlock; #10630 changes the guest_raise_in_system_call test only.

Tested

Windows 11 Pro 10.0.26200, AMD Ryzen 7 9800X3D, MinGW Release build with BUILD_TESTING=ON on this branch (main 3fcb5e4d7 + this commit).

  • ctest -R "raise|semaphore|equeue|signal|sync_on_address|umtx" at efb57d464: 15 of 15 pass, among them guest_raise_exception, guest_raise_in_host_code, guest_raise_in_system_call, guest_mutex_raise_exception, guest_raise_nested_sleep and the new guest_raise_leaves_host_code. The raise tests passed 5 repeated runs (--repeat until-fail:5).
  • Graveyard Keeper 2 (PPSA35943), with every library built at efb57d464: 8 loads in a row from the main menu into the first dungeon without a freeze. With the first commit alone: 30 loads from the main menu into the first dungeon (20 in a row, then 10) without a freeze, and about 40 more loads into the same room in measurement runs since; before the change the same load froze in 3 of about 45 runs.

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: PPSA35943 #8628
  • GPUs tested: n/a
  • AI-assisted: yes

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4996910362 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10666). Originally posted by [WallisSkill](https://github.com/WallisSkill) on 2026-10-24T16:01:13Z. --- ### What `sceKernelRaiseException` on Windows no longer redirects a thread that is in host code. Before, `RaiseOn` suspended the target and, while it sat in host code (libkernel, libc, the HLE modules, the C runtime, ntdll), resampled it until a 50 ms limit and then redirected it into the handler right there. A handler that waits, as Unity's GC thread-stop handler does, then kept whatever host lock the thread held. In Graveyard Keeper 2 that froze the load after New game in about 1 of 15 runs. The capture of one freeze: the GC thread waited in `sceKernelWaitSema` with 39 of 40 stop acknowledgements; 39 threads waited on the resume event in the handler; the missing job worker sat at `Aps5RedirectedEntryStub` because it had been redirected while blocked in a winpthreads lock wait inside `Driver::RegisterShader` (a redirect only takes effect when the kernel wait ends), and the holder of that lock had been redirected out of `ShaderRecompiler::SpecializeSpirv` after the 50 ms limit and was parked in the handler. Now a target in host code is never interrupted where it is. The first of these to reach it delivers (one atomic `taken` flag per delivery): - for a target in a libkernel wait (`Pthread::waitCount` above 0, the point where the handler already ran before), an APC queued to that wait; - for a target anywhere else in host code, running or blocked, an execute breakpoint in debug register 0 at the frame's return address into guest code, found by unwinding the host frames with the image's own `.pdata` table and `RtlVirtualUnwind`; the search stops at frames that push a machine frame and is guarded against faults; the return site must follow a call instruction; a vectored handler takes the single-step, clears the breakpoint and runs the handler on the thread; - a host deliverer thread that keeps sampling the target (with the debug registers re-armed when the return address moves) and redirects it once it is in guest code. The raise returns as soon as the delivery is queued. A target in guest code is still redirected at once, and a target inside NtContinue still makes the raise throw after 1 s. The technical debt entry is rewritten for the new behaviour and its gaps (the handler's context holds no vector registers beyond what the C runtime context saves; a target that stays in host code waiting on a thread already stopped is never stopped; debug register 0 used by a debugger or the title is not modeled). New test `guest_raise_leaves_host_code`: the handler checks that the interrupted `rip` lies in the test executable, for a target blocked in `WaitForSingleObject` (each raise must return in under 500 ms), one busy in `MultiByteToWideChar` over 64 MiB, and one in an alertable `WaitForSingleObjectEx`, where the handler must also run only after the wait was released (an APC for every host-code target, the first version of this PR, fails it), 10 rounds each. Related: #8592 defers Windows exceptions during shader preparation, a different approach to a similar deadlock; #10630 changes the `guest_raise_in_system_call` test only. ### Tested Windows 11 Pro 10.0.26200, AMD Ryzen 7 9800X3D, MinGW Release build with `BUILD_TESTING=ON` on this branch (`main` 3fcb5e4d7 + this commit). - `ctest -R "raise|semaphore|equeue|signal|sync_on_address|umtx"` at efb57d464: 15 of 15 pass, among them `guest_raise_exception`, `guest_raise_in_host_code`, `guest_raise_in_system_call`, `guest_mutex_raise_exception`, `guest_raise_nested_sleep` and the new `guest_raise_leaves_host_code`. The raise tests passed 5 repeated runs (`--repeat until-fail:5`). - Graveyard Keeper 2 (PPSA35943), with every library built at efb57d464: 8 loads in a row from the main menu into the first dungeon without a freeze. With the first commit alone: 30 loads from the main menu into the first dungeon (20 in a row, then 10) without a freeze, and about 40 more loads into the same room in measurement runs since; before the change the same load froze in 3 of about 45 runs. ### 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: PPSA35943 #8628 - [x] GPUs tested: n/a - [x] AI-assisted: yes 🤖 Generated with [Claude Code](https://claude.com/claude-code)
MarcZX10 commented 2026-10-24 16:03:13 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-24T16:03:13Z.

Review: CHANGES_REQUESTED


At the current head, APC delivery is queued unconditionally for a target classified as host code (QueueDelivery in TryDeliver, then WaitingEntry calls Deliver directly). If that host code is in an alertable wait, Windows runs the APC before the wait returns, so the guest handler runs inside host code while its locks are still held. This reproduces the lock-retention/reentrancy hazard that the change is intended to avoid, and contradicts the new test’s invariant that the handler never runs outside the guest image. The debt entry acknowledges this for host code that holds a lock across an alertable wait, but this path is a core delivery route rather than an incidental edge case. Please constrain APC delivery to contexts where the wait/lock state is known safe (such as the existing libkernel deferral points), or otherwise defer it until the guest return, and add a regression using an alertable host wait that verifies the handler’s saved RIP is in the guest image and the host lock can be acquired after delivery.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5638883020 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10666#pullrequestreview-5638883020). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-24T16:03:13Z. **Review:** CHANGES_REQUESTED --- At the current head, APC delivery is queued unconditionally for a target classified as host code (`QueueDelivery` in `TryDeliver`, then `WaitingEntry` calls `Deliver` directly). If that host code is in an alertable wait, Windows runs the APC before the wait returns, so the guest handler runs inside host code while its locks are still held. This reproduces the lock-retention/reentrancy hazard that the change is intended to avoid, and contradicts the new test’s invariant that the handler never runs outside the guest image. The debt entry acknowledges this for host code that holds a lock across an alertable wait, but this path is a core delivery route rather than an incidental edge case. Please constrain APC delivery to contexts where the wait/lock state is known safe (such as the existing libkernel deferral points), or otherwise defer it until the guest return, and add a regression using an alertable host wait that verifies the handler’s saved RIP is in the guest image and the host lock can be acquired after delivery.
MarcZX10 commented 2026-10-24 19:33:57 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-24T19:33:57Z.

Review: CHANGES_REQUESTED


The current head still queues WaitingEntry for every target classified as host code (TryDeliver, around line 715); WaitingEntry then calls Deliver as soon as that APC runs. A target already inside an alertable host wait can therefore run the guest handler inside the host call, before the wait returns, retaining any host locks the change is intended to protect. The new GuestRaiseLeavesHostCode.cpp tests a non-alertable WaitForSingleObject and a busy conversion, but contains no alertable WaitForSingleObjectEx case despite the description saying it does. Please prevent generic host APC delivery from invoking the handler inside host code and add the alertable-wait regression, checking the saved RIP is in the guest image and delivery occurs only after the wait is released.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5639642421 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10666#pullrequestreview-5639642421). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-24T19:33:57Z. **Review:** CHANGES_REQUESTED --- The current head still queues `WaitingEntry` for every target classified as host code (`TryDeliver`, around line 715); `WaitingEntry` then calls `Deliver` as soon as that APC runs. A target already inside an alertable host wait can therefore run the guest handler inside the host call, before the wait returns, retaining any host locks the change is intended to protect. The new `GuestRaiseLeavesHostCode.cpp` tests a non-alertable `WaitForSingleObject` and a busy conversion, but contains no alertable `WaitForSingleObjectEx` case despite the description saying it does. Please prevent generic host APC delivery from invoking the handler inside host code and add the alertable-wait regression, checking the saved RIP is in the guest image and delivery occurs only after the wait is released.
MarcZX10 commented 2026-10-24 20:26:59 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-24T20:26:59Z.

Review: COMMENTED


Correction to my prior review on this exact head: I said GuestRaiseLeavesHostCode.cpp did not contain an alertable WaitForSingleObjectEx case. I re-opened the file at efb57d464d7f242ed4b8bb32dfc6db4b79195512; the test is present. It repeatedly raises while the target is in that alertable wait, releases it only after a delay, and asserts the handler did not run before release and that saved RIP stays in the test image. The implementation also queues the APC only when Pthread::waitCount indicates a libkernel wait; otherwise it arms delivery for return to guest code. My earlier statement that the test was missing was incorrect.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5639822977 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10666#pullrequestreview-5639822977). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-24T20:26:59Z. **Review:** COMMENTED --- Correction to my prior review on this exact head: I said `GuestRaiseLeavesHostCode.cpp` did not contain an alertable `WaitForSingleObjectEx` case. I re-opened the file at `efb57d464d7f242ed4b8bb32dfc6db4b79195512`; the test is present. It repeatedly raises while the target is in that alertable wait, releases it only after a delay, and asserts the handler did not run before release and that saved RIP stays in the test image. The implementation also queues the APC only when `Pthread::waitCount` indicates a libkernel wait; otherwise it arms delivery for return to guest code. My earlier statement that the test was missing was incorrect.
MarcZX10 commented 2026-10-24 20:27:01 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-24T20:27:01Z.

Review: APPROVED


Re-reviewed exact head efb57d464d7f242ed4b8bb32dfc6db4b79195512 and confirmed the alertable-wait regression is present. Delivery is queued as an APC for a thread in a libkernel wait; host-code targets outside such a wait retain the return breakpoint/sampling path, preventing handler invocation from an unrelated alertable host wait. The test checks the saved RIP against the executable image, delays release of WaitForSingleObjectEx until after the raise, and verifies delivery occurs after release over ten rounds. The PR reports the 15 focused Windows tests passing, including five repeated raise-test runs; I did not independently run this Windows-only test here. The author also reports compatibility testing in Graveyard Keeper 2. The overlap with #9573 is documented by the author as compatible in either order, with only the shared debt entry requiring a rebase adjustment. No blocking issue remains.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5639823172 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10666#pullrequestreview-5639823172). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-24T20:27:01Z. **Review:** APPROVED --- Re-reviewed exact head `efb57d464d7f242ed4b8bb32dfc6db4b79195512` and confirmed the alertable-wait regression is present. Delivery is queued as an APC for a thread in a libkernel wait; host-code targets outside such a wait retain the return breakpoint/sampling path, preventing handler invocation from an unrelated alertable host wait. The test checks the saved RIP against the executable image, delays release of `WaitForSingleObjectEx` until after the raise, and verifies delivery occurs after release over ten rounds. The PR reports the 15 focused Windows tests passing, including five repeated raise-test runs; I did not independently run this Windows-only test here. The author also reports compatibility testing in Graveyard Keeper 2. The overlap with #9573 is documented by the author as compatible in either order, with only the shared debt entry requiring a rebase adjustment. No blocking issue remains.
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!10666
No description provided.