Skip to content

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

Open
kiansaeidnia wants to merge 1 commit into
boykopovar:mainfrom
kiansaeidnia:fix/libkernel-windows-raise-cond-reacquire
Open

kiansaeidnia wants to merge 1 commit into
boykopovar:mainfrom
kiansaeidnia:fix/libkernel-windows-raise-cond-reacquire

Conversation

@kiansaeidnia

@kiansaeidnia kiansaeidnia commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

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

🤖 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.

…Windows

On Windows, a woken scePthreadCondWait or scePthreadCondTimedwait that
loses the spin now takes the mutex back through TimedWait::ParkAcquire,
as scePthreadMutexLock does, instead of the native lock. pthread_once
waiters wait on a TimedWait::Condition instead of a
std::condition_variable, on every host. Both waits are alertable on
Windows, so a raise at a thread blocked behind a stopped thread is
delivered there and the wait resumes, as FreeBSD 11.4 restarts umtx
mutex and once waits after a signal handler. On Linux and macOS the
relock still uses the native lock and pthread_once behaves as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Changes: Synchronization waits and exception handling

Layer / File(s) Summary
Update synchronization paths
core/libs/prx/libkernel/Pthread/Posix/Once.cpp, core/libs/prx/libkernel/Pthread/src/Cond.cpp
Once-state waiting and notification now use TimedWait::Condition. On Windows, WakingLock::lock uses TimedWait::ParkAcquire after SpinAcquire fails; other platforms retain direct native-lock acquisition.
Test and document exception handling
core/libs/tests/GuestRaiseLeavesHostCode.cpp, docs/dev/debt/changes/fix-libkernel-windows-raise-cond-reacquire.md
Tests cover ordinary and timed condition waits with one or three recursive mutex levels, plus exception raises during once initialization and while another thread waits. The documentation describes Windows exception delivery paths and related limitations.

Suggested reviewers: privacyonion, boykopovar, milescoviello, cocoa55

Change: Bug fix

Merge Risk: Minimal · up to 555ff

On Windows, condition-variable mutex relock and pthread_once waits can now receive raised exceptions instead of blocking them. Linux and macOS behavior is unchanged. The changes are small and covered by new tests, with no concrete merge-blocking defect identified. One known limitation remains: the opt-in coarse timed-wait mode does not become alertable, but it behaves as before.

Security architecture risk: Moderate · up to 555ff

Windows threads can now receive guest exceptions during two waits that previously blocked delivery. When a handler returns normally, the thread resumes waiting. If the handler exits the thread instead, shared synchronization state can be left behind and affect other threads in the same process.

Retained concerns

  • Medium · security · inferred: A guest handler that exits its thread can bypass waiter cleanup in both newly alertable paths. The once queue can retain an entry for a departed thread and encounter it during notification for an unrelated once control. The relock path can leave a parked entry eligible for the next wake on the same mutex; an exit during the post-acquisition drain can also leave the native mutex held before guest ownership is restored. The base paths did not expose these wait registrations to guest handlers at these points.
Security review details

Security Blast Radius

  • inferred — The supported exposure is in-process. The once notification queue is shared across controls, so the effect need not stay with the triggering control. A stale mutex park entry can intercept a wake for that mutex; wake selection checks the exact key rather than waking any waiter in the bucket.

Trust Boundaries and Controls

  • observed — The Windows raise path queues an APC for a live guest target marked as waiting. The APC claims delivery once and invokes the registered guest handler on that thread while the host wait is active.

Resilience and Maintainability Implications

  • observed — Coarse mode avoids the intrusive once queue, but the Windows condition relock calls ParkAcquire without a coarse-mode check. The setting is therefore not a fallback for both changes.
Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: dac0b509-bf4d-4a9d-ac7f-a45ec43e1665
Commits

Reviewing files that changed from the base of the PR and between 4814cae and 555fff5.

Files selected for processing: 4

  • core/libs/prx/libkernel/Pthread/Posix/Once.cpp
  • core/libs/prx/libkernel/Pthread/src/Cond.cpp
  • core/libs/tests/GuestRaiseLeavesHostCode.cpp
  • docs/dev/debt/changes/fix-libkernel-windows-raise-cond-reacquire.md

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@Plyxen Plyxen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ligmaSec left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@B-Howell

B-Howell commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

Windows tester result at head 555fff5dec65, merged onto main c776c9ec9489: pass.

  • Windows 11 Pro 26300, WinLibs GCC 15.2.0 r7, Release.
  • guest_raise_leaves_host_code plus 13 nearby cond, once and raise tests (guest_pthread_cond, guest_cond_*, guest_posix_cond_broadcast, guest_kernel_pthread_once, guest_once, guest_libcxx_condition, guest_libcxx_call_once, guest_mutex_raise_exception, guest_raise_in_host_code, guest_pthread_cancel, guest_kernel_cond_timedwait_precedence): 14/14 pass, 3 runs out of 3.
  • Control with main's Cond.cpp and Once.cpp and this PR's test: guest_raise_leaves_host_code aborts (the raise at the relocking or once-waiting thread is not delivered within the deadline).

@github-actions

github-actions Bot commented Dec 5, 2026

Copy link
Copy Markdown

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 18190 core/libs/prx/libkernel/Pthread/Posix/Once.cpp

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants