fix(libkernel): make cond relock and pthread_once waits alertable on Windows #27985

Open
kiansaeidnia wants to merge 1 commit from upstream-pr/27985 into main
kiansaeidnia commented 2026-11-28 00:48:56 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by kiansaeidnia on 2026-11-28T00:48:56Z.


What

On Windows, sceKernelRaiseException reaches a target in host code as an APC only while it is in a libkernel wait. Two guest-visible waits did not go through one, so a raise at a thread blocked in them was never delivered:

  • The mutex relock of a condition wait. It runs for scePthreadCondWait, scePthreadCondTimedwait, pthread_cond_wait and pthread_cond_timedwait, and for libc's libc++ std::condition_variable, which forwards to them. After a wake, WakingLock::lock called the native mutex lock once spinning failed.
  • pthread_once waiters. They blocked on a std::condition_variable.

This is the shape of the Unity/IL2CPP stop-the-world freeze:

  1. T1 holds the mutex, signals the condition, and is stopped in its raise handler before it unlocks.
  2. T2 wakes and blocks in the relock.
  3. The raise at T2 never arrives, so the collector waits forever.

#1562 fixed this for scePthreadMutexLock and rwlock waits after a measured God of War: Sons of Sparta (PPSA28997) freeze, and #10666 (Graveyard Keeper 2, PPSA35943) recorded the general gap.

The change:

  • The relock now takes the mutex through TimedWait::ParkAcquire, keyed and woken the way scePthreadMutexLock is. WakingLock::unlock and scePthreadMutexUnlock already unpark that key.
  • pthread_once waits on a TimedWait::Condition.
  • The waits resume afterwards with the same results, as FreeBSD 11.4 restarts umtx mutex and once waits after a signal handler (PCATCH sleeps, then a retry in libthr).
  • On Linux and macOS the relock is unchanged. There TimedWait::Condition is a condition_variable_any, so pthread_once behaves as before.

The debt entry keeps its general wording about waits on an already stopped thread, and lists the waits that remain as examples: pthread_barrier_wait, scePthreadOnce, libc _Mtx_lock, std::call_once and __cxa_guard_acquire. Two of these are left out on purpose: scePthreadOnce is rewritten by #25283, and Dinkumware _Mtx_lock/_Cnd_wait by #18347.

pr_overlap could not compare Once.cpp with #18190, because that PR conflicts with main. Its change to the file is a rename of pthread_once_nid_postfix to _nid_no_patch plus a forwarder, so whichever merges second needs a textual rebase. #26174 rewrites waitUntil in Cond.cpp but leaves WakingLock::lock alone.

Tested

Windows 11, MinGW-w64 GCC 16.2, Release.

guest_raise_leaves_host_code gains five cases, each run for 10 rounds:

  • a relock after scePthreadCondWait, with a normal mutex and with a recursive mutex held 3 times (the count is restored);
  • the same two relocks after scePthreadCondTimedwait;
  • a pthread_once whose initializer thread is stopped in its raise handler.

In the relock cases the main thread holds the mutex while the woken waiter blocks, which is the same delivery point as a stopped holder.

In each case the handler must acknowledge within 2 s. Afterwards the wait must return 0 with the mutex owned, and the initializer must have run exactly once. Each relock round raises twice: the second raise is sent only after the first handler has returned, so it can only land in the relock. With main's Cond.cpp the test aborts on the acknowledgement timeout (0xc0000409).

guest_raise_leaves_host_code and guest_mutex_raise_exception pass with --repeat until-fail:3. The 48 related raise, mutex, cond, once and libc++ condition tests that are built pass with --repeat until-fail:3.

Cond.cpp and Once.cpp were syntax-checked with g++ 11 on Linux (WSL Ubuntu). debt_fold.py --check passes. Not tested in a title.

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 and the licence notice of code adapted from upstream (see AGENTS.md)
  • 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: Unity/IL2CPP GC stops on Windows (the #1562 / #10666 freeze shape with the stopped thread holding a condition's mutex or running a pthread_once initializer)
  • GPUs tested: n/a
  • AI-assisted: yes

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Improved thread synchronization on Windows when exceptions occur during waits or one-time initialization. Threads can resume and complete these operations without remaining stuck, including when recursive mutexes are held.
  • Documentation

    • Added details about Windows exception handling during waits, including known limitations.
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5535082314 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/27985). Originally posted by [kiansaeidnia](https://github.com/kiansaeidnia) on 2026-11-28T00:48:56Z. --- ### What On Windows, `sceKernelRaiseException` reaches a target in host code as an APC only while it is in a libkernel wait. Two guest-visible waits did not go through one, so a raise at a thread blocked in them was never delivered: - **The mutex relock of a condition wait.** It runs for `scePthreadCondWait`, `scePthreadCondTimedwait`, `pthread_cond_wait` and `pthread_cond_timedwait`, and for libc's libc++ `std::condition_variable`, which forwards to them. After a wake, `WakingLock::lock` called the native mutex lock once spinning failed. - **`pthread_once` waiters.** They blocked on a `std::condition_variable`. This is the shape of the Unity/IL2CPP stop-the-world freeze: 1. T1 holds the mutex, signals the condition, and is stopped in its raise handler before it unlocks. 2. T2 wakes and blocks in the relock. 3. The raise at T2 never arrives, so the collector waits forever. #1562 fixed this for `scePthreadMutexLock` and rwlock waits after a measured God of War: Sons of Sparta (PPSA28997) freeze, and #10666 (Graveyard Keeper 2, PPSA35943) recorded the general gap. The change: - The relock now takes the mutex through `TimedWait::ParkAcquire`, keyed and woken the way `scePthreadMutexLock` is. `WakingLock::unlock` and `scePthreadMutexUnlock` already unpark that key. - `pthread_once` waits on a `TimedWait::Condition`. - The waits resume afterwards with the same results, as FreeBSD 11.4 restarts umtx mutex and once waits after a signal handler (`PCATCH` sleeps, then a retry in libthr). - On Linux and macOS the relock is unchanged. There `TimedWait::Condition` is a `condition_variable_any`, so `pthread_once` behaves as before. The debt entry keeps its general wording about waits on an already stopped thread, and lists the waits that remain as examples: `pthread_barrier_wait`, `scePthreadOnce`, libc `_Mtx_lock`, `std::call_once` and `__cxa_guard_acquire`. Two of these are left out on purpose: `scePthreadOnce` is rewritten by #25283, and Dinkumware `_Mtx_lock`/`_Cnd_wait` by #18347. `pr_overlap` could not compare `Once.cpp` with #18190, because that PR conflicts with `main`. Its change to the file is a rename of `pthread_once_nid_postfix` to `_nid_no_patch` plus a forwarder, so whichever merges second needs a textual rebase. #26174 rewrites `waitUntil` in `Cond.cpp` but leaves `WakingLock::lock` alone. ### Tested Windows 11, MinGW-w64 GCC 16.2, Release. `guest_raise_leaves_host_code` gains five cases, each run for 10 rounds: - a relock after `scePthreadCondWait`, with a normal mutex and with a recursive mutex held 3 times (the count is restored); - the same two relocks after `scePthreadCondTimedwait`; - a `pthread_once` whose initializer thread is stopped in its raise handler. In the relock cases the main thread holds the mutex while the woken waiter blocks, which is the same delivery point as a stopped holder. In each case the handler must acknowledge within 2 s. Afterwards the wait must return 0 with the mutex owned, and the initializer must have run exactly once. Each relock round raises twice: the second raise is sent only after the first handler has returned, so it can only land in the relock. With `main`'s `Cond.cpp` the test aborts on the acknowledgement timeout (0xc0000409). `guest_raise_leaves_host_code` and `guest_mutex_raise_exception` pass with `--repeat until-fail:3`. The 48 related raise, mutex, cond, once and libc++ condition tests that are built pass with `--repeat until-fail:3`. `Cond.cpp` and `Once.cpp` were syntax-checked with g++ 11 on Linux (WSL Ubuntu). `debt_fold.py --check` passes. Not tested in a title. ### 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) and the licence notice of code adapted from upstream (see AGENTS.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: Unity/IL2CPP GC stops on Windows (the #1562 / #10666 freeze shape with the stopped thread holding a condition's mutex or running a `pthread_once` initializer) - [x] GPUs tested: n/a - [x] AI-assisted: yes 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Improved thread synchronization on Windows when exceptions occur during waits or one-time initialization. Threads can resume and complete these operations without remaining stuck, including when recursive mutexes are held. * **Documentation** * Added details about Windows exception handling during waits, including known limitations. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Plyxen commented 2026-11-28 07:01:30 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Plyxen on 2026-11-28T07:01:30Z.

Review: APPROVED


Checked head 555fff5dec. All on Windows 11 with WinLibs GCC 15.2 (Release), applied to main 4c7578e0a4 together with #28006, #28002, #28001, #27991, #27987, #28007, #27994. tools/check_conventions.py --head and tools/debt_fold.py --check passed and the full build succeeded. In the full CPU suite (5,135 tests) the only failure is windows_read_trap_unknown, which fails on main too (fixed in #28028).

guest_raise_leaves_host_code passes. Windows is the platform the alertable ParkAcquire and pthread_once waits are for.

AI-assisted: yes (Claude Code)

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6096378957 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/27985#pullrequestreview-6096378957). Originally posted by [Plyxen](https://github.com/Plyxen) on 2026-11-28T07:01:30Z. **Review:** APPROVED --- Checked head `555fff5dec`. All on Windows 11 with WinLibs GCC 15.2 (Release), applied to `main` `4c7578e0a4` together with #28006, #28002, #28001, #27991, #27987, #28007, #27994. `tools/check_conventions.py --head` and `tools/debt_fold.py --check` passed and the full build succeeded. In the full CPU suite (5,135 tests) the only failure is `windows_read_trap_unknown`, which fails on `main` too (fixed in #28028). `guest_raise_leaves_host_code` passes. Windows is the platform the alertable `ParkAcquire` and `pthread_once` waits are for. AI-assisted: yes (Claude Code)
MarcZX10 commented 2026-11-28 07:44:50 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-28T07:44:50Z.

Review: COMMENTED


Reviewed — no blocking findings

Nothing blocks this change; the points below are optional.

What I ran

Reviewed head 555fff5dec658050755d95afaac75bcbc7d54d03. No commands or tests were run; source was inspected through the pinned reader.

Results

Check Result Note
Diff and changed source passed Four changed files read
Tests not run Author-reported results were not independently verified

Findings

Blocking

None.

Non-blocking

  • In GuestRaiseLeavesHostCode.cpp, the relock setup loops on relock.waiting, which is set before the waiter enters the condition wait (:145); the fixed sleeps then assume the signal and mutex reacquisition have progressed to the intended blocking point (:172-177). Consider adding explicit synchronization or an observable wait-state check so this test cannot pass or fail based on scheduling.

Not verified

  • No test execution, build, title run, or physical-console behavior was verified. Test reports in the description are author-reported.
  • All changed files listed in the manifest were read: Once.cpp, Cond.cpp, GuestRaiseLeavesHostCode.cpp, and the technical debt change note. No changed files were excluded in the manifest. files.json was not available as a review-folder document.

To get this to a good state

Nothing is required. The optional test synchronization improvement is noted above.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6096607050 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/27985#pullrequestreview-6096607050). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-28T07:44:50Z. **Review:** COMMENTED --- # Reviewed — no blocking findings Nothing blocks this change; the points below are optional. ## What I ran Reviewed head `555fff5dec658050755d95afaac75bcbc7d54d03`. No commands or tests were run; source was inspected through the pinned reader. ## Results | Check | Result | Note | |---|---|---| | Diff and changed source | passed | Four changed files read | | Tests | not run | Author-reported results were not independently verified | ## Findings ### Blocking None. ### Non-blocking - In `GuestRaiseLeavesHostCode.cpp`, the relock setup loops on `relock.waiting`, which is set before the waiter enters the condition wait (`:145`); the fixed sleeps then assume the signal and mutex reacquisition have progressed to the intended blocking point (`:172-177`). Consider adding explicit synchronization or an observable wait-state check so this test cannot pass or fail based on scheduling. ## Not verified - No test execution, build, title run, or physical-console behavior was verified. Test reports in the description are author-reported. - All changed files listed in the manifest were read: `Once.cpp`, `Cond.cpp`, `GuestRaiseLeavesHostCode.cpp`, and the technical debt change note. No changed files were excluded in the manifest. `files.json` was not available as a review-folder document. ## To get this to a good state Nothing is required. The optional test synchronization improvement is noted above.
ligmaSec commented 2026-12-03 14:05:29 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ligmaSec on 2026-12-03T14:05:29Z.

Review: COMMENTED


The changed pthread_once implementation, condition wait implementation, and raise fixture passed MinGW syntax and type checking. I traced the blocking relock to TimedWait::ParkAcquire and the once wait to TimedWait::Condition::Wait. The local MinGW backend could not emit all three objects, so the five Windows runtime cases remain unverified here.

AI-assisted: yes.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6171330142 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/27985#pullrequestreview-6171330142). Originally posted by [ligmaSec](https://github.com/ligmaSec) on 2026-12-03T14:05:29Z. **Review:** COMMENTED --- The changed `pthread_once` implementation, condition wait implementation, and raise fixture passed MinGW syntax and type checking. I traced the blocking relock to `TimedWait::ParkAcquire` and the once wait to `TimedWait::Condition::Wait`. The local MinGW backend could not emit all three objects, so the five Windows runtime cases remain unverified here. AI-assisted: yes.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/27985:upstream-pr/27985'
git switch 'upstream-pr/27985'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/27985'
git switch 'upstream-pr/27985'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/27985'
git switch 'upstream-pr/27985'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/27985'
git switch 'main'
git merge --squash 'upstream-pr/27985'
git switch 'main'
git merge --ff-only 'upstream-pr/27985'
git switch 'main'
git merge 'upstream-pr/27985'
git push origin 'main'
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!27985
No description provided.