fix(libkernel): notify a POSIX semaphore waiter before sem_post releases its lock #8616
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/8616"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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 undersemaphore->lock, releases the lock, and only then callssemaphore->available.NotifyOne()on the heapPosixSemaphore. A thread that takes the count in that gap (sem_trywait, orsem_wait/sem_timedwaitfinding the count already raised) may callsem_destroy, which deletes the object (L61-L67), and the poster'sNotifyOnethen runs on freed memory. Withmain'sSem.cpp, the new test crashes in the posting thread (gdb, paths shortened):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_postpublishes the token withatomic_cmpset_rel_inton the caller'ssem_tand afterwards only callsusem_wakeifUSEM_HAS_WAITERSwas set; the kernel side,do_sem2_wake, reads and updates only thatsem_t, through the fault-tolerantfueword32andcasueword32._sem_destroyonly clears_magic. POSIXsem_destroy: "It is safe to destroy an initialized semaphore upon which no threads are currently blocked." glibc states the consequence forsem_postin sem_waitcommon.c: "sem_post must not access the semaphore struct anymore after it has made a token available".sem_postnow callsNotifyOneafter the increment, whilesemaphore->lockis still held. A thread takes the count only under that lock, so the unlock is the poster's last access to the object.0x7fffffffit still fails withEOVERFLOW(84) without a wakeup.NotifyOnetakes only the condition's own lock, which a waiter already takes while it holdssemaphore->lock(in libstdc++'scondition_variable_any::wait, and inCondition::enqueueon Windows), so no new lock order is added.scePthreadSemPost;sceKernelSignalSemaalready notifies under its lock (Semaphore.cpp#L46-L60).Differences from the reference: none known in what this changes. Not measured on a console.
Tested
BUILD_TESTING=ONon upstreammain1b08a33b1; after rebasing ontomainb85d972f4,guest_posix_sem_postandguest_posix_sem_initpass 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 callssem_post; the main thread spins onsem_trywait(yielding after 4,096 tries) until it gets the count, then callssem_destroy.sem_init,sem_postandsem_destroymust each return 0. With this change it passed 20 of 20 runs ofctest --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).main'sSem.cpp:guest_posix_sem_postfailed 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.pypicked 1415 of 1715 tests: 1398 passed and 16 skipped (the 13video_out_flip_*tests,video_out_frame_dump_queueandvideo_out_telemetry_captionunder SDL's offscreen driver, andagc_driver_stencil_ref_export, which needsVK_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 onmain's source also ended with one unrelated GPU test failing.x86_64-w64-mingw32-g++16.2.0-std=gnu++20 -fsyntax-only -Wall -Wextraon the two changed.cppfiles: 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/mainwith 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 withmain; #6044 only movescore/libs/tests/GuestPosixSem.cpptocore/libs/tests/threads/without changing it.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)🤖 Generated with Claude Code
Imported from boykopovar/AnyPS5. Originally posted by ycbuzi on 2026-10-21T04:46:13Z.
Windows run of
47b5a750admerged ontomainaa408677b0(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_post0.11 s a run). Not run: the negative control withmain'sSem.cpp.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T00:00:24Z.
Review: APPROVED
The lifetime race is real: after
sem_postincrements the count, a concurrentsem_trywaitcan consume it and destroy the semaphore before a laterNotifyOne()touches the condition variable. Keeping the notification undersemaphore->lockmakes 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 renamesGuestPosixSem.cpptothreads/GuestPosixSem.cppwithout 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.Imported from boykopovar/AnyPS5. Originally posted by ahmadmuj on 2026-10-25T11:08:11Z.
Review: APPROVED
Linux run of
47b5a750admerged ontomain66e6772ca2(clean merge). WSL2 Ubuntu 24.04, GCC 13.3, glibc 2.39, 24 cores. I built onlyguest_posix_sem_tests.-DANYPS5_ENABLE_ASAN=ON, RelWithDebInfo,ASAN_OPTIONS=detect_leaks=0):guest_posix_sem_tests postpassed 50/50, and 10/10 pinned to two cores.initpasses.main'sSem.cpp: 20/20 heap-use-after-free. READ of size 8 incondition_variable_any::notify_one<-TimedWait::Condition::NotifyOne(TimedWait.cpp:388) <-sem_post_nid_postfix(Sem.cpp:175), freed bysem_destroy_nid_postfix(Sem.cpp:123) fromCheckRetire.ctest -R "^guest_posix_sem_(init|post)$" --repeat until-fail:20passes. Withmain'sSem.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 samesem_post, and the lastsem_close+sem_unlinkfrees thePosixSemaphore, so this fix covers that case too.NotifyOneonly takes the condition's own lock (condition_variable_any's internal mutex, orqueueLockon the Windows queue path), and the cancelled-waiter path inCancel.hppalready calls it with the semaphore lock held. So no new lock order.Unrelated, for anyone running this under ASan: with leak detection on,
postfails here and on main with a 168-byte leak. The "blocked semaphore" fromsem_initat line 92 (69 on main) gets re-initialized at line 109 without asem_destroy. It's pre-existing, not from this PR, and CI doesn't run the libkernel tests under ASan.Not run: Windows, macOS, console.