fix(libkernel): notify a POSIX semaphore waiter before sem_post releases its lock #8616

Merged
Lindamea1 merged 1 commit from upstream-pr/8616 into main 2026-10-25 22:02:29 +00:00
Lindamea1 commented 2026-10-20 18:31:07 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Lindamea1 on 2026-10-20T18:31:07Z.


What

On main, sem_post (Sem.cpp#L108-L118) raises the count under semaphore->lock, releases the lock, and only then calls semaphore->available.NotifyOne() on the heap PosixSemaphore. A thread that takes the count in that gap (sem_trywait, or sem_wait/sem_timedwait finding the count already raised) may call sem_destroy, which deletes the object (L61-L67), and the poster's NotifyOne then runs on freed memory. With main's Sem.cpp, the new test crashes in the posting thread (gdb, paths shortened):

Thread 3 "guest_posix_sem" received signal SIGSEGV, Segmentation fault.
#0  0x00007ffff7798394 in pthread_mutex_lock () from /usr/lib64/libc.so.6
#1  0x00007ffff7f78459 in TimedWait::Condition::NotifyOne() () from .../unpatched/libkernel.prx
#2  0x00007ffff7f33092 in sem_post_nid_postfix () from .../unpatched/libkernel.prx

The mutex address it was given (rdi) is 0, read from the freed object. No title is known to reach this.

Reference: on FreeBSD 11.4 a thread may destroy the semaphore as soon as its wait returns. _sem_post publishes the token with atomic_cmpset_rel_int on the caller's sem_t and afterwards only calls usem_wake if USEM_HAS_WAITERS was set; the kernel side, do_sem2_wake, reads and updates only that sem_t, through the fault-tolerant fueword32 and casueword32. _sem_destroy only clears _magic. POSIX sem_destroy: "It is safe to destroy an initialized semaphore upon which no threads are currently blocked." glibc states the consequence for sem_post in sem_waitcommon.c: "sem_post must not access the semaphore struct anymore after it has made a token available".

  • sem_post now calls NotifyOne after the increment, while semaphore->lock is still held. A thread takes the count only under that lock, so the unlock is the poster's last access to the object.
  • Return values and errno are unchanged; at 0x7fffffff it still fails with EOVERFLOW (84) without a wakeup.
  • NotifyOne takes only the condition's own lock, which a waiter already takes while it holds semaphore->lock (in libstdc++'s condition_variable_any::wait, and in Condition::enqueue on Windows), so no new lock order is added.
  • #6711 (merged) made the same change for rwlocks, and open #6740 makes it for scePthreadSemPost; sceKernelSignalSema already notifies under its lock (Semaphore.cpp#L46-L60).

Differences from the reference: none known in what this changes. Not measured on a console.

Tested

  • Gentoo Linux, kernel 7.2.8, GCC 16.2.1, glibc 2.43, Ninja; Release build with BUILD_TESTING=ON on upstream main 1b08a33b1; after rebasing onto main b85d972f4, guest_posix_sem_post and guest_posix_sem_init pass again (10 of 10 runs).
  • guest_posix_sem_post (core/libs/tests/GuestPosixSem.cpp) now ends with 20,000 rounds: the main thread initializes a semaphore at 0 and hands it to a poster thread, which calls sem_post; the main thread spins on sem_trywait (yielding after 4,096 tries) until it gets the count, then calls sem_destroy. sem_init, sem_post and sem_destroy must each return 0. With this change it passed 20 of 20 runs of ctest --repeat until-fail:20 (0.02 s each), before and again after the negative control, 50 of 50 direct runs (63 ms at most), 10 of 10 pinned to two cores (93 ms at most) and 10 of 10 pinned to one core (761 ms at most).
  • Negative control, with this branch's test and main's Sem.cpp: guest_posix_sem_post failed 20 of 20 ctest runs with ***Exception: SegFault (0.01 s), and 10 of 10 direct runs pinned to two cores with exit 139. Pinned to one core it passed 10 of 10, since the race needs two threads running at once.
  • tools/select_tests.py picked 1415 of 1715 tests: 1398 passed and 16 skipped (the 13 video_out_flip_* tests, video_out_frame_dump_queue and video_out_telemetry_caption under SDL's offscreen driver, and agc_driver_stencil_ref_export, which needs VK_EXT_shader_stencil_export). The one failure, video_out_hdr_present, calls no semaphore export and passed 6 of 6 runs alone; the same selection on main's source also ended with one unrelated GPU test failing.
  • x86_64-w64-mingw32-g++ 16.2.0 -std=gnu++20 -fsyntax-only -Wall -Wextra on the two changed .cpp files: no errors or warnings. This is a syntax check, not a Windows build or run.
  • tools/check_compile.py --base upstream/main: 2 translation units compile.
  • tools/check_conventions.py --base upstream/main with this title and body: all checks passed.
  • tools/pr_overlap.py --branch fix/libkernel-posix-sem-post-notify-under-lock: no overlap found. It could not compare #6044, which conflicts with main; #6044 only moves core/libs/tests/GuestPosixSem.cpp to core/libs/tests/threads/ without changing it.
  • Not run on Windows, macOS or a console.

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

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4940497174 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8616). Originally posted by [Lindamea1](https://github.com/Lindamea1) on 2026-10-20T18:31:07Z. --- ### What On `main`, `sem_post` ([Sem.cpp#L108-L118](https://github.com/boykopovar/AnyPS5/blob/1b08a33b121e23a4f9e84999c233e094b5055893/core/libs/prx/libkernel/Pthread/Posix/Sem.cpp#L108-L118)) raises the count under `semaphore->lock`, releases the lock, and only then calls `semaphore->available.NotifyOne()` on the heap `PosixSemaphore`. A thread that takes the count in that gap (`sem_trywait`, or `sem_wait`/`sem_timedwait` finding the count already raised) may call `sem_destroy`, which deletes the object ([L61-L67](https://github.com/boykopovar/AnyPS5/blob/1b08a33b121e23a4f9e84999c233e094b5055893/core/libs/prx/libkernel/Pthread/Posix/Sem.cpp#L61-L67)), and the poster's `NotifyOne` then runs on freed memory. With `main`'s `Sem.cpp`, the new test crashes in the posting thread (gdb, paths shortened): ``` Thread 3 "guest_posix_sem" received signal SIGSEGV, Segmentation fault. #0 0x00007ffff7798394 in pthread_mutex_lock () from /usr/lib64/libc.so.6 #1 0x00007ffff7f78459 in TimedWait::Condition::NotifyOne() () from .../unpatched/libkernel.prx #2 0x00007ffff7f33092 in sem_post_nid_postfix () from .../unpatched/libkernel.prx ``` The mutex address it was given (`rdi`) is 0, read from the freed object. No title is known to reach this. Reference: on FreeBSD 11.4 a thread may destroy the semaphore as soon as its wait returns. [`_sem_post`](https://github.com/freebsd/freebsd-src/blob/releng/11.4/lib/libc/gen/sem_new.c#L453-L470) publishes the token with `atomic_cmpset_rel_int` on the caller's `sem_t` and afterwards only calls `usem_wake` if `USEM_HAS_WAITERS` was set; the kernel side, [`do_sem2_wake`](https://github.com/freebsd/freebsd-src/blob/releng/11.4/sys/kern/kern_umtx.c#L3275-L3311), reads and updates only that `sem_t`, through the fault-tolerant `fueword32` and `casueword32`. [`_sem_destroy`](https://github.com/freebsd/freebsd-src/blob/releng/11.4/lib/libc/gen/sem_new.c#L310-L323) only clears `_magic`. POSIX [`sem_destroy`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_destroy.html): "It is safe to destroy an initialized semaphore upon which no threads are currently blocked." glibc states the consequence for `sem_post` in [sem_waitcommon.c](https://github.com/bminor/glibc/blob/04e750e75b73957cf1c791535a3f4319534a52fc/nptl/sem_waitcommon.c#L46-L53): "sem_post must not access the semaphore struct anymore after it has made a token available". - `sem_post` now calls `NotifyOne` after the increment, while `semaphore->lock` is still held. A thread takes the count only under that lock, so the unlock is the poster's last access to the object. - Return values and errno are unchanged; at `0x7fffffff` it still fails with `EOVERFLOW` (84) without a wakeup. - `NotifyOne` takes only the condition's own lock, which a waiter already takes while it holds `semaphore->lock` (in libstdc++'s `condition_variable_any::wait`, and in `Condition::enqueue` on Windows), so no new lock order is added. - #6711 (merged) made the same change for rwlocks, and open #6740 makes it for `scePthreadSemPost`; `sceKernelSignalSema` already notifies under its lock ([Semaphore.cpp#L46-L60](https://github.com/boykopovar/AnyPS5/blob/1b08a33b121e23a4f9e84999c233e094b5055893/core/libs/prx/libkernel/Semaphore/src/Semaphore.cpp#L46-L60)). Differences from the reference: none known in what this changes. Not measured on a console. ### Tested <!-- OS, title or homebrew, what was checked. "Not tested" is a valid answer. A performance change: the summary lines of main and of this PR from the same machine and scene, with the traces attached, captured as the Performance report issue form describes. --> - Gentoo Linux, kernel 7.2.8, GCC 16.2.1, glibc 2.43, Ninja; Release build with `BUILD_TESTING=ON` on upstream `main` `1b08a33b1`; after rebasing onto `main` `b85d972f4`, `guest_posix_sem_post` and `guest_posix_sem_init` pass again (10 of 10 runs). - `guest_posix_sem_post` (`core/libs/tests/GuestPosixSem.cpp`) now ends with 20,000 rounds: the main thread initializes a semaphore at 0 and hands it to a poster thread, which calls `sem_post`; the main thread spins on `sem_trywait` (yielding after 4,096 tries) until it gets the count, then calls `sem_destroy`. `sem_init`, `sem_post` and `sem_destroy` must each return 0. With this change it passed 20 of 20 runs of `ctest --repeat until-fail:20` (0.02 s each), before and again after the negative control, 50 of 50 direct runs (63 ms at most), 10 of 10 pinned to two cores (93 ms at most) and 10 of 10 pinned to one core (761 ms at most). - Negative control, with this branch's test and `main`'s `Sem.cpp`: `guest_posix_sem_post` failed 20 of 20 ctest runs with `***Exception: SegFault` (0.01 s), and 10 of 10 direct runs pinned to two cores with exit 139. Pinned to one core it passed 10 of 10, since the race needs two threads running at once. - `tools/select_tests.py` picked 1415 of 1715 tests: 1398 passed and 16 skipped (the 13 `video_out_flip_*` tests, `video_out_frame_dump_queue` and `video_out_telemetry_caption` under SDL's offscreen driver, and `agc_driver_stencil_ref_export`, which needs `VK_EXT_shader_stencil_export`). The one failure, `video_out_hdr_present`, calls no semaphore export and passed 6 of 6 runs alone; the same selection on `main`'s source also ended with one unrelated GPU test failing. - `x86_64-w64-mingw32-g++` 16.2.0 `-std=gnu++20 -fsyntax-only -Wall -Wextra` on the two changed `.cpp` files: no errors or warnings. This is a syntax check, not a Windows build or run. - `tools/check_compile.py --base upstream/main`: 2 translation units compile. - `tools/check_conventions.py --base upstream/main` with this title and body: all checks passed. - `tools/pr_overlap.py --branch fix/libkernel-posix-sem-post-notify-under-lock`: no overlap found. It could not compare #6044, which conflicts with `main`; #6044 only moves `core/libs/tests/GuestPosixSem.cpp` to `core/libs/tests/threads/` without changing it. - Not run on Windows, macOS or a console. ### 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 <!-- #PR, or none --> - [x] Fixes: none <!-- issue it closes as Fixes #N, or none --> - [x] Unblocks: none <!-- title ID and Game bring-up discussion, e.g. PPSA01325 #3232, or none --> - [x] GPUs tested: n/a <!-- for AGC, shader recompiler or VideoOut changes: vendor, model, driver and OS of each GPU the GPU tests ran on; otherwise n/a --> - [x] AI-assisted: yes <!-- yes / no --> 🤖 Generated with [Claude Code](https://claude.com/claude-code)
ycbuzi commented 2026-10-21 04:46:13 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ycbuzi on 2026-10-21T04:46:13Z.


Windows run of 47b5a750ad merged onto main aa408677b0 (cebf714597, clean). Windows 11 Home 10.0.26200, MinGW-w64 GCC 15.2.0 (ucrt-posix-seh r7), Release, BUILD_TESTING=ON, Ryzen 9 7900 (12 cores, so the two threads of the 20,000-round test run at once).

ctest -R "^guest_posix_sem_(init|post)$" --repeat until-fail:20: both pass every repeat (guest_posix_sem_post 0.11 s a run). Not run: the negative control with main's Sem.cpp.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6308271493 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8616#issuecomment-6308271493). Originally posted by [ycbuzi](https://github.com/ycbuzi) on 2026-10-21T04:46:13Z. --- Windows run of 47b5a750ad merged onto `main` aa408677b0 (cebf714597, clean). Windows 11 Home 10.0.26200, MinGW-w64 GCC 15.2.0 (ucrt-posix-seh r7), Release, `BUILD_TESTING=ON`, Ryzen 9 7900 (12 cores, so the two threads of the 20,000-round test run at once). `ctest -R "^guest_posix_sem_(init|post)$" --repeat until-fail:20`: both pass every repeat (`guest_posix_sem_post` 0.11 s a run). Not run: the negative control with `main`'s `Sem.cpp`.
MarcZX10 commented 2026-10-22 00:00:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T00:00:24Z.

Review: APPROVED


The lifetime race is real: after sem_post increments the count, a concurrent sem_trywait can consume it and destroy the semaphore before a later NotifyOne() touches the condition variable. Keeping the notification under semaphore->lock makes that unlock the poster's final access; a waiter cannot consume the token until the notification has completed. The notification and wait paths retain the semaphore-then-condition lock order described in the PR.

The added 20,000-round test exercises post/consume/destroy, and the reported negative control fails against main's implementation. I also checked the overlap warning: #6044 only renames GuestPosixSem.cpp to threads/GuestPosixSem.cpp without changing its contents, and the two heads combine cleanly. No other overlap was reported. Eligibility, intake, conventions, labels, and report checks pass. Linux and Windows test results are contributor-reported; hosted product jobs are skipped under repository policy, and I did not run a local build.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5607680711 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8616#pullrequestreview-5607680711). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-22T00:00:24Z. **Review:** APPROVED --- The lifetime race is real: after `sem_post` increments the count, a concurrent `sem_trywait` can consume it and destroy the semaphore before a later `NotifyOne()` touches the condition variable. Keeping the notification under `semaphore->lock` makes that unlock the poster's final access; a waiter cannot consume the token until the notification has completed. The notification and wait paths retain the semaphore-then-condition lock order described in the PR. The added 20,000-round test exercises post/consume/destroy, and the reported negative control fails against `main`'s implementation. I also checked the overlap warning: #6044 only renames `GuestPosixSem.cpp` to `threads/GuestPosixSem.cpp` without changing its contents, and the two heads combine cleanly. No other overlap was reported. Eligibility, intake, conventions, labels, and report checks pass. Linux and Windows test results are contributor-reported; hosted product jobs are skipped under repository policy, and I did not run a local build.
ahmadmuj commented 2026-10-25 11:08:11 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ahmadmuj on 2026-10-25T11:08:11Z.

Review: APPROVED


Linux run of 47b5a750ad merged onto main 66e6772ca2 (clean merge). WSL2 Ubuntu 24.04, GCC 13.3, glibc 2.39, 24 cores. I built only guest_posix_sem_tests.

  • ASan (-DANYPS5_ENABLE_ASAN=ON, RelWithDebInfo, ASAN_OPTIONS=detect_leaks=0): guest_posix_sem_tests post passed 50/50, and 10/10 pinned to two cores. init passes.
  • Negative control, same ASan build, this test with main's Sem.cpp: 20/20 heap-use-after-free. READ of size 8 in condition_variable_any::notify_one <- TimedWait::Condition::NotifyOne (TimedWait.cpp:388) <- sem_post_nid_postfix (Sem.cpp:175), freed by sem_destroy_nid_postfix (Sem.cpp:123) from CheckRetire.
  • Plain Release, no ASan: with this PR, ctest -R "^guest_posix_sem_(init|post)$" --repeat until-fail:20 passes. With main's Sem.cpp, 16/20 direct runs segfault (exit 139) and ctest fails on the first repeat. So the test catches it without a sanitizer too.

Code: since this branch, main added named semaphores (9497840de). They post through the same sem_post, and the last sem_close + sem_unlink frees the PosixSemaphore, so this fix covers that case too. NotifyOne only takes the condition's own lock (condition_variable_any's internal mutex, or queueLock on the Windows queue path), and the cancelled-waiter path in Cancel.hpp already calls it with the semaphore lock held. So no new lock order.

Unrelated, for anyone running this under ASan: with leak detection on, post fails here and on main with a 168-byte leak. The "blocked semaphore" from sem_init at line 92 (69 on main) gets re-initialized at line 109 without a sem_destroy. It's pre-existing, not from this PR, and CI doesn't run the libkernel tests under ASan.

Not run: Windows, macOS, console.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5642863883 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8616#pullrequestreview-5642863883). Originally posted by [ahmadmuj](https://github.com/ahmadmuj) on 2026-10-25T11:08:11Z. **Review:** APPROVED --- Linux run of 47b5a750ad merged onto `main` 66e6772ca2 (clean merge). WSL2 Ubuntu 24.04, GCC 13.3, glibc 2.39, 24 cores. I built only `guest_posix_sem_tests`. - ASan (`-DANYPS5_ENABLE_ASAN=ON`, RelWithDebInfo, `ASAN_OPTIONS=detect_leaks=0`): `guest_posix_sem_tests post` passed 50/50, and 10/10 pinned to two cores. `init` passes. - Negative control, same ASan build, this test with `main`'s `Sem.cpp`: 20/20 heap-use-after-free. READ of size 8 in `condition_variable_any::notify_one` <- `TimedWait::Condition::NotifyOne` (TimedWait.cpp:388) <- `sem_post_nid_postfix` (Sem.cpp:175), freed by `sem_destroy_nid_postfix` (Sem.cpp:123) from `CheckRetire`. - Plain Release, no ASan: with this PR, `ctest -R "^guest_posix_sem_(init|post)$" --repeat until-fail:20` passes. With `main`'s `Sem.cpp`, 16/20 direct runs segfault (exit 139) and ctest fails on the first repeat. So the test catches it without a sanitizer too. Code: since this branch, main added named semaphores (9497840de). They post through the same `sem_post`, and the last `sem_close` + `sem_unlink` frees the `PosixSemaphore`, so this fix covers that case too. `NotifyOne` only takes the condition's own lock (`condition_variable_any`'s internal mutex, or `queueLock` on the Windows queue path), and the cancelled-waiter path in `Cancel.hpp` already calls it with the semaphore lock held. So no new lock order. Unrelated, for anyone running this under ASan: with leak detection on, `post` fails here and on main with a 168-byte leak. The "blocked semaphore" from `sem_init` at line 92 (69 on main) gets re-initialized at line 109 without a `sem_destroy`. It's pre-existing, not from this PR, and CI doesn't run the libkernel tests under ASan. Not run: Windows, macOS, console.
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!8616
No description provided.