fix(libkernel): reject exception redirects during thread teardown #1802

Closed
Sanjaysrinivas wants to merge 11 commits from upstream-pr/1802 into main
Sanjaysrinivas commented 2026-10-08 19:32:31 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Sanjaysrinivas on 2026-10-08T19:32:31Z.


What

Fix two Windows exception/exit races from #1668. A target can finish after the initial sceKernelRaiseException check but before suspension takes effect. Redirecting it after guest-thread unregistration makes the handler's scePthreadSelf() adopt a different handle. A terminating native thread can also reject suspension before its Windows handle is signaled, causing a runtime exception instead of ESRCH.

The Windows path now checks guest completion as well as native exit, rechecks _finished after GetThreadContext has stopped the target, and treats context-read failures during completion as ESRCH. Other host API failures retain their diagnostics.

Add guest_exception_wait_recovery with Release-active requirements, atomic gates, five-second progress checks and a 20-second CTest timeout. Each run covers:

  • 60 address-wait cases across the unsuffixed, 8-, 16-, 32- and 64-bit APIs: wake requested before/after handler release, timeout with a wake at another address, handler identity/stack, original join result, and subsequent address reuse.
  • 64 exception/exit races: one acknowledged handler before exit is released, then a raise racing teardown; count accepted/rejected requests and observed handler calls separately, verify target identity, reject a finished but still joinable handle, and retain the original thread result.
  • Null targets and unsupported raise values.

The address-wait tests include the wait-entry race. Publishing a changed value before wake makes both registration orderings valid; these tests do not claim every raise interrupts an already enrolled host wait. Independent raiser/waker threads let the coordinator release a held handler without waiting on host locks it may retain. The raiser is a guest thread and is joined, avoiding leaked adopted host-thread handles.

Update the existing architecture documentation with the delivery flow, rejection ordering, wait invariants, test matrix and support boundaries. Update TechnicalDebt for the remaining teardown and host-lock limits.

Dependencies and coordination

Depends on #1431 at 77143010efe1555449b6f11ee6a91b1517fd4b6d for Linux delivery.

Depends on #1421 at 24dc98d7c035bde08e679e3c62a59402a2b57cc5 for Windows delivery robustness. The new tests exposed MinGW TLS failures without it.

Based on upstream main at 2cc7f09d1d3c90fa3daf4ba2c5b170b036361770. Both prerequisite histories and authors are preserved through merges. Their test-file conflict is resolved by retaining Linux register/startup coverage, guarding Windows-only SEH/continuation cases, and correcting delivery-count offsets for the combined phases. The Linux MXCSR handling and Windows retry/context changes are both retained. The final main refresh adds upstream image-by shader support and leaves the tested kernel source unchanged.

The new change is commit 694a126b, five files. #1562 also changes Windows delivery; its alternative implementation is not stacked here. #1652 changes signal-mask handling, which this follow-up does not implement. #1431's current published head has two commits; this PR does not assume the later mask work described in its body is present.

The overlap bot also flags #1746, which replaces the Linux thread-start promise and preserves configured stack bounds. Its overlap is with startup code included from #1431, not the new Windows teardown guard. Neither #1562 nor #1746 is an additional prerequisite for this PR. Whichever merges second must reconcile the shared code: retain Linux signal masking and native-handle publication alongside #1746's startup changes, and preserve the finished-target rejection if Windows delivery is replaced by #1562. Rerun exception, thread creation and stack tests after integration.

Related cancellation coverage is in #1739. This PR addresses part of workstream B and leaves #1668 open.

Tested

Local Release builds use the production libc/libkernel CMake source lists and test registrations through a small untracked validation parent. They do not replace production functions or build unrelated graphics/relinker dependencies.

Host Toolchain Final regression result
Windows 11 Pro, build 26300 WinLibs r7 MinGW-w64 GCC 15.2.0, C++20 100/100, 25.64 s
Ubuntu 24.04 under WSL2, kernel 6.6.87.2 GCC 13.3.0, C++20 100/100, 24.39 s

That is 6,000 address-wait cases and 6,400 exit races per host. The existing guest_exception_handler, guest_raise_exception and guest_sync_on_address tests also pass three repetitions per host. No title, console or GPU behavior was tested.

Full GitHub CI passes on combined head 0623b090f8955b68a8e481a6df4cf42bda82b5c4: Linux, Windows, conventions, and progress report. The relinker job is skipped by the path filter.

Before the new guard, the regression failed the target-handle identity requirement. With only the post-suspension check, further stress reproduced cannot suspend the target thread during teardown; consulting guest completion in failure paths fixes that window too.

Two temporary Linux mutations were caught: removing address-wake notification failed bounded progress; forcing successful address-wait returns failed the timeout requirement. Production sources were restored byte-for-byte and ten restored runs passed. Conventions, whitespace and native test-registration checks pass.

Standard checkout reproduction:

cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON
cmake --build build --target guest_exception_wait_recovery_tests guest_raise_exception_tests guest_exception_handler_tests guest_sync_on_address_tests
ctest --test-dir build --output-on-failure -R '^guest_(exception_wait_recovery|raise_exception|exception_handler|sync_on_address)$' --repeat until-fail:3 --parallel 4
ctest --test-dir build --output-on-failure -R '^guest_exception_wait_recovery$' --repeat until-fail:100

Remaining limits and reproduced evidence

#1488's host-lock mechanism is reproduced on Windows. A preliminary version kept the handler waiting while the coordinator synchronously called sceKernelSyncOnAddressWake. GDB showed the target paused in Handler, interrupted beneath RtlAllocateHeap during address-wait enqueue, and the coordinator blocked in winpthreads from sceKernelSyncOnAddressWake on the address-queue mutex. The handler's release depended on that wake returning. This is documented, not fixed by the teardown guard; a general host-critical-section deferral design is still needed.

Windows coarse address-wait/delivery races also failed to complete reliably in the preliminary matrix. Their root cause remains unresolved. This CTest explicitly unsets APS5_COARSE_TIMED_WAITS on Windows and claims default alertable-wait coverage only. Linux uses its existing condition-variable path.

Signal masks, teardown delivery-completion guarantees, stale non-null handles, full console context equivalence and Windows upper-YMM preservation remain unverified or unsupported. Accepted raises are not counted as executed handlers during exit races.

Checklist

  • Based on current main; checked overlapping work and explicitly listed prerequisites.
  • One topic: exception delivery and recovery; follow-up is a new PR.
  • No added code comments except repository-permitted forms.
  • Unimplemented behavior and remaining limits remain explicit; no silent stubs added.
  • Investigation notes, logs and repro artifacts stay outside tracked repository files.
  • No third-party dependencies added.
  • Generic behavior; no title-specific checks.
  • Depends on: #1431 and #1421.
  • AI-assisted: yes.
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4791835564 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1802). Originally posted by [Sanjaysrinivas](https://github.com/Sanjaysrinivas) on 2026-10-08T19:32:31Z. --- ### What Fix two Windows exception/exit races from #1668. A target can finish after the initial `sceKernelRaiseException` check but before suspension takes effect. Redirecting it after guest-thread unregistration makes the handler's `scePthreadSelf()` adopt a different handle. A terminating native thread can also reject suspension before its Windows handle is signaled, causing a runtime exception instead of `ESRCH`. The Windows path now checks guest completion as well as native exit, rechecks `_finished` after `GetThreadContext` has stopped the target, and treats context-read failures during completion as `ESRCH`. Other host API failures retain their diagnostics. Add `guest_exception_wait_recovery` with Release-active requirements, atomic gates, five-second progress checks and a 20-second CTest timeout. Each run covers: - 60 address-wait cases across the unsuffixed, 8-, 16-, 32- and 64-bit APIs: wake requested before/after handler release, timeout with a wake at another address, handler identity/stack, original join result, and subsequent address reuse. - 64 exception/exit races: one acknowledged handler before exit is released, then a raise racing teardown; count accepted/rejected requests and observed handler calls separately, verify target identity, reject a finished but still joinable handle, and retain the original thread result. - Null targets and unsupported raise values. The address-wait tests include the wait-entry race. Publishing a changed value before wake makes both registration orderings valid; these tests do not claim every raise interrupts an already enrolled host wait. Independent raiser/waker threads let the coordinator release a held handler without waiting on host locks it may retain. The raiser is a guest thread and is joined, avoiding leaked adopted host-thread handles. Update the existing [architecture documentation](https://github.com/Sanjaysrinivas/AnyPS5/blob/test/exception-address-wait/docs/dev/ARCHITECTURE.md#guest-exceptions-and-wait-recovery) with the delivery flow, rejection ordering, wait invariants, test matrix and support boundaries. Update TechnicalDebt for the remaining teardown and host-lock limits. ### Dependencies and coordination Depends on #1431 at `77143010efe1555449b6f11ee6a91b1517fd4b6d` for Linux delivery. Depends on #1421 at `24dc98d7c035bde08e679e3c62a59402a2b57cc5` for Windows delivery robustness. The new tests exposed MinGW TLS failures without it. Based on upstream `main` at `2cc7f09d1d3c90fa3daf4ba2c5b170b036361770`. Both prerequisite histories and authors are preserved through merges. Their test-file conflict is resolved by retaining Linux register/startup coverage, guarding Windows-only SEH/continuation cases, and correcting delivery-count offsets for the combined phases. The Linux MXCSR handling and Windows retry/context changes are both retained. The final main refresh adds upstream image-by shader support and leaves the tested kernel source unchanged. The new change is commit [`694a126b`](https://github.com/Sanjaysrinivas/AnyPS5/commit/694a126bd412da29728a4a4db360951777fcb2e1), five files. #1562 also changes Windows delivery; its alternative implementation is not stacked here. #1652 changes signal-mask handling, which this follow-up does not implement. #1431's current published head has two commits; this PR does not assume the later mask work described in its body is present. The [overlap bot](https://github.com/boykopovar/AnyPS5/pull/1802#issuecomment-6068291800) also flags #1746, which replaces the Linux thread-start promise and preserves configured stack bounds. Its overlap is with startup code included from #1431, not the new Windows teardown guard. Neither #1562 nor #1746 is an additional prerequisite for this PR. Whichever merges second must reconcile the shared code: retain Linux signal masking and native-handle publication alongside #1746's startup changes, and preserve the finished-target rejection if Windows delivery is replaced by #1562. Rerun exception, thread creation and stack tests after integration. Related cancellation coverage is in #1739. This PR addresses part of workstream B and leaves #1668 open. ### Tested Local Release builds use the production libc/libkernel CMake source lists and test registrations through a small untracked validation parent. They do not replace production functions or build unrelated graphics/relinker dependencies. | Host | Toolchain | Final regression result | | --- | --- | --- | | Windows 11 Pro, build 26300 | WinLibs r7 MinGW-w64 GCC 15.2.0, C++20 | 100/100, 25.64 s | | Ubuntu 24.04 under WSL2, kernel 6.6.87.2 | GCC 13.3.0, C++20 | 100/100, 24.39 s | That is 6,000 address-wait cases and 6,400 exit races per host. The existing `guest_exception_handler`, `guest_raise_exception` and `guest_sync_on_address` tests also pass three repetitions per host. No title, console or GPU behavior was tested. Full GitHub CI passes on combined head `0623b090f8955b68a8e481a6df4cf42bda82b5c4`: [Linux](https://github.com/boykopovar/AnyPS5/actions/runs/37833451547/job/113518706987), [Windows](https://github.com/boykopovar/AnyPS5/actions/runs/37833451547/job/113518706960), [conventions](https://github.com/boykopovar/AnyPS5/actions/runs/37833453003/job/113504419157), and progress report. The relinker job is skipped by the path filter. Before the new guard, the regression failed the target-handle identity requirement. With only the post-suspension check, further stress reproduced `cannot suspend the target thread` during teardown; consulting guest completion in failure paths fixes that window too. Two temporary Linux mutations were caught: removing address-wake notification failed bounded progress; forcing successful address-wait returns failed the timeout requirement. Production sources were restored byte-for-byte and ten restored runs passed. Conventions, whitespace and native test-registration checks pass. Standard checkout reproduction: ```sh cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON cmake --build build --target guest_exception_wait_recovery_tests guest_raise_exception_tests guest_exception_handler_tests guest_sync_on_address_tests ctest --test-dir build --output-on-failure -R '^guest_(exception_wait_recovery|raise_exception|exception_handler|sync_on_address)$' --repeat until-fail:3 --parallel 4 ctest --test-dir build --output-on-failure -R '^guest_exception_wait_recovery$' --repeat until-fail:100 ``` ### Remaining limits and reproduced evidence #1488's host-lock mechanism is reproduced on Windows. A preliminary version kept the handler waiting while the coordinator synchronously called `sceKernelSyncOnAddressWake`. GDB showed the target paused in `Handler`, interrupted beneath `RtlAllocateHeap` during address-wait enqueue, and the coordinator blocked in winpthreads from `sceKernelSyncOnAddressWake` on the address-queue mutex. The handler's release depended on that wake returning. This is documented, not fixed by the teardown guard; a general host-critical-section deferral design is still needed. Windows coarse address-wait/delivery races also failed to complete reliably in the preliminary matrix. Their root cause remains unresolved. This CTest explicitly unsets `APS5_COARSE_TIMED_WAITS` on Windows and claims default alertable-wait coverage only. Linux uses its existing condition-variable path. Signal masks, teardown delivery-completion guarantees, stale non-null handles, full console context equivalence and Windows upper-YMM preservation remain unverified or unsupported. Accepted raises are not counted as executed handlers during exit races. ### Checklist - [x] Based on current `main`; checked overlapping work and explicitly listed prerequisites. - [x] One topic: exception delivery and recovery; follow-up is a new PR. - [x] No added code comments except repository-permitted forms. - [x] Unimplemented behavior and remaining limits remain explicit; no silent stubs added. - [x] Investigation notes, logs and repro artifacts stay outside tracked repository files. - [x] No third-party dependencies added. - [x] Generic behavior; no title-specific checks. - [x] Depends on: #1431 and #1421. - [x] AI-assisted: yes.
github-actions[bot] commented 2026-10-08 19:32:55 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-08T19:32:55Z.


Progress report (2cc7f09 → 0623b09)

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

✅ 1 implemented
Library Name
libkernel sceKernelRaiseException
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6067539786 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1802#issuecomment-6067539786). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-08T19:32:55Z. --- <!-- progress-report --> ### Progress report (2cc7f09 → 0623b09) 📈 **System libraries**: 84.79% (+0.03%, +1 implemented functions) <details> <summary>✅ 1 implemented</summary> | Library | Name | | - | - | | libkernel | `sceKernelRaiseException` | </details>
github-actions[bot] commented 2026-10-08 20:18:40 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-08T20:18:40Z.


Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
#1988 core/libs/prx/libkernel/Pthread/include/Pthread.hpp L14-15, L82
core/libs/prx/libkernel/Pthread/src/Thread.cpp L20-21, L317-335
#2001 core/libs/prx/libkernel/CMakeLists.txt L292-321
core/libs/prx/libkernel/Pthread/src/Thread.cpp L180-181, L420-421
core/libs/prx/libkernel/System/src/Exception.cpp L5-267, L272-275, L280-282, L287-296
core/libs/tests/GuestRaiseException.cpp L1-297
docs/dev/ARCHITECTURE.md L1-69
docs/dev/TechnicalDebt.md L239-254
#2051 core/libs/tests/GuestRaiseException.cpp L283
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6068291800 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1802#issuecomment-6068291800). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-08T20:18:40Z. --- <!-- pr-overlap --> Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in **Depends on**. | Pull request | Conflicting files (lines on `main`) | Same exports | Same new files | |---|---|---|---| | #1988 | `core/libs/prx/libkernel/Pthread/include/Pthread.hpp` [L14-15](https://github.com/boykopovar/AnyPS5/blob/f145139676a48306681d3a4d5fabf83938759daf/core/libs/prx/libkernel/Pthread/include/Pthread.hpp#L14-L15), [L82](https://github.com/boykopovar/AnyPS5/blob/f145139676a48306681d3a4d5fabf83938759daf/core/libs/prx/libkernel/Pthread/include/Pthread.hpp#L82)<br>`core/libs/prx/libkernel/Pthread/src/Thread.cpp` [L20-21](https://github.com/boykopovar/AnyPS5/blob/f145139676a48306681d3a4d5fabf83938759daf/core/libs/prx/libkernel/Pthread/src/Thread.cpp#L20-L21), [L317-335](https://github.com/boykopovar/AnyPS5/blob/f145139676a48306681d3a4d5fabf83938759daf/core/libs/prx/libkernel/Pthread/src/Thread.cpp#L317-L335) | | | | #2001 | `core/libs/prx/libkernel/CMakeLists.txt` [L292-321](https://github.com/boykopovar/AnyPS5/blob/f145139676a48306681d3a4d5fabf83938759daf/core/libs/prx/libkernel/CMakeLists.txt#L292-L321)<br>`core/libs/prx/libkernel/Pthread/src/Thread.cpp` [L180-181](https://github.com/boykopovar/AnyPS5/blob/f145139676a48306681d3a4d5fabf83938759daf/core/libs/prx/libkernel/Pthread/src/Thread.cpp#L180-L181), [L420-421](https://github.com/boykopovar/AnyPS5/blob/f145139676a48306681d3a4d5fabf83938759daf/core/libs/prx/libkernel/Pthread/src/Thread.cpp#L420-L421)<br>`core/libs/prx/libkernel/System/src/Exception.cpp` [L5-267](https://github.com/boykopovar/AnyPS5/blob/f145139676a48306681d3a4d5fabf83938759daf/core/libs/prx/libkernel/System/src/Exception.cpp#L5-L267), [L272-275](https://github.com/boykopovar/AnyPS5/blob/f145139676a48306681d3a4d5fabf83938759daf/core/libs/prx/libkernel/System/src/Exception.cpp#L272-L275), [L280-282](https://github.com/boykopovar/AnyPS5/blob/f145139676a48306681d3a4d5fabf83938759daf/core/libs/prx/libkernel/System/src/Exception.cpp#L280-L282), [L287-296](https://github.com/boykopovar/AnyPS5/blob/f145139676a48306681d3a4d5fabf83938759daf/core/libs/prx/libkernel/System/src/Exception.cpp#L287-L296)<br>`core/libs/tests/GuestRaiseException.cpp` [L1-297](https://github.com/boykopovar/AnyPS5/blob/f145139676a48306681d3a4d5fabf83938759daf/core/libs/tests/GuestRaiseException.cpp#L1-L297)<br>`docs/dev/ARCHITECTURE.md` [L1-69](https://github.com/boykopovar/AnyPS5/blob/f145139676a48306681d3a4d5fabf83938759daf/docs/dev/ARCHITECTURE.md#L1-L69)<br>`docs/dev/TechnicalDebt.md` [L239-254](https://github.com/boykopovar/AnyPS5/blob/f145139676a48306681d3a4d5fabf83938759daf/docs/dev/TechnicalDebt.md#L239-L254) | | | | #2051 | `core/libs/tests/GuestRaiseException.cpp` [L283](https://github.com/boykopovar/AnyPS5/blob/f145139676a48306681d3a4d5fabf83938759daf/core/libs/tests/GuestRaiseException.cpp#L283) | | |
oneandonlydean commented 2026-10-09 08:55:35 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-09T08:55:35Z.


Closing: no title hits this teardown race, and the branch merges #1421 and #1431 in instead of building on main. If a title hits it once those land, please reopen rebased on main, without merge commits or the ARCHITECTURE.md section.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6077717422 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1802#issuecomment-6077717422). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-09T08:55:35Z. --- Closing: no title hits this teardown race, and the branch merges #1421 and #1431 in instead of building on main. If a title hits it once those land, please reopen rebased on main, without merge commits or the ARCHITECTURE.md section.

Pull request closed

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!1802
No description provided.