fix(libkernel): prevent use-after-free on pthread semaphore destruction and notification race #6740
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/6740"
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 fogydes on 2026-10-16T08:54:28Z.
What
Two concurrency defects and one ABI exception leak in
libkernel'sscePthreadSem*implementation cause undefined behavior, heap corruption, and premature process termination:Notification Lifetime Race (
scePthreadSemPost):scePthreadSemPostunlockedcurrent->_mutexbefore invokingcurrent->_cv.NotifyOne(). In typical producer-consumer or worker-synchronization patterns, a waiting thread waking inscePthreadSemWaitcan acquire the mutex, decrement_count, returnSCE_OK, and immediately callscePthreadSemDestroy(sem). If destruction occurs while the posting thread is still inside or enteringNotifyOne(),NotifyOne()accesses freed heap memory (PthreadSemPrivate), triggering heap-use-after-free or segmentation faults. Movingcurrent->_cv.NotifyOne()inside the scope ofstd::lock_guard lock(current->_mutex)guarantees the posting thread finishes its notification before any waking waiter can re-acquire_mutexand deallocate the object.Destruction of In-Use Semaphore (
scePthreadSemDestroy):Previously,
scePthreadSemDestroyperformed no waiter accounting and unconditionally deletedcurrenteven when threads were parked insideThreadCancel::WaitUntil. This left waiting threads parked on a destroyed condition variable and attempting to re-lock a deleted mutex upon wake-up.Per FreeBSD 11.4
_sem_destroyand prosper, destroying a semaphore succeeds with 0 even when threads are waiting on it. Active semaphores are managed viastd::shared_ptr<PthreadSemPrivate>stored insemRegistryguarded bystd::shared_mutex semRegistryMutex. Destruction setsowner->_destroyed = true;, notifies all waiting threads on_cv, and unregisters the handle. Waking waiters safely observe_destroyed, clean up waiter tracking, and returnSCE_KERNEL_ERROR_EINVAL(0x80020016). The underlying memory is safely retired once all waiters drop their reference. This behavior is documented indocs/dev/debt/libkernel.mdunder "Unknown function info".Exception Boundary Leak on Destroyed Semaphore:
Calling
scePthreadSemDestroyon a previously destroyed semaphore threw an unhandled C++std::runtime_error("Semaphore is not initialized or has been destroyed")across the guest ABI boundary, causingstd::terminate()and aborting the emulator.scePthreadSemDestroynow returnsSCE_KERNEL_ERROR_EINVAL(0x80020016) for destroyed semaphores, consistent withscePthreadMutexDestroy.Shared Locking for Registry Resolution:
resolveSemusesstd::shared_lockonsemRegistryMutexfor lookups, keeping hot synchronization paths concurrent without global contention.scePthreadSemDestroyon in-use semaphore with active waiter0x0and deleted semaphore while waiter crashed0x0(SCE_OK); waiter wakes safely and returns0x80020016(SCE_KERNEL_ERROR_EINVAL)scePthreadSemDestroyon previously destroyed semaphorestd::runtime_error, aborting process0x80020016(SCE_KERNEL_ERROR_EINVAL)_cvTested
GuestPthreadSemwith 50-iteration concurrent post/destroy stress loop and cancellation cleanup: passes without errors.python tools/check_conventions.py --base origin/mainpassed with 0 warnings.sem_tfunctions (Posix/Sem.cpp), which are tracked separately in #6103.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)Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-16T09:46:09Z.
Review: COMMENTED
Native Linux run on exact head
243db5f7fc3a67dfcb1ad42880336581d2df9750, applied onmain5d9dcc42d.Machine: Intel i7-8700 (6C/12T), Ubuntu 26.04, GCC 15.2, Ninja Release,
BUILD_TESTING=ON, full build. Sanitizer runs use a separateRelWithDebInfobuild with-DANYPS5_ENABLE_ASAN=ON,ASAN_OPTIONS=detect_leaks=0:halt_on_error=1.guest_pthread_cancelregresses. Non-GPU suite (ctest -E "^agc|gpu|vulkan|video_out"): 647/650, versus 648/650 onmain. The twofile_writer_*failures also happen onmainon this machine. The new failure isguest_pthread_cancel, which aborts on every run (3/3 normal, 3/3 ASan; it passes onmain). It fails at the finalRequire(scePthreadSemDestroy(&shared.sem) == SCE_OK), which now returns0x80020010(EBUSY).Cause: a thread cancelled inside
scePthreadSemWaitnever runs~WaiterGuard.ThreadCancel::WaitUntilcallsCheck()→scePthreadExit, which leaves throughstd::longjmp(*threadExitJump, 1)on Linux (_endthreadexon Windows). Neither runs C++ destructors, sosemWaiters[sem]stays at 1 and the semaphore can never be destroyed after one cancelled waiter. The count has to be dropped on the cancel path too (beforeCheck()exits, or through a cleanup handler), not only in a destructor.The race loop does not cover the
scePthreadSemPostchange. I kept this PR'sSem.cppand moved onlyNotifyOne()back outside thelock_guard(themainordering). Under ASan the updatedguest_pthread_semtest still passed 100/100, and 50/50 withtaskset -c 0. After the 50 µs sleep the racer is usually already parked inWaitUntiland needs the notification to wake, so the post-then-destroy window is not reached.Other results:
guest_pthread_sem50/50 normal, 20/20 withtaskset -c 0; ASan 100/100 and 20/20 withtaskset -c 0, no reports.main'sSem.cpp: fails 5/5 withstd::runtime_error("Semaphore is not initialized or has been destroyed")from the second destroy. So the EINVAL part is covered.Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-16T09:57:52Z.
One additional lifetime gap:
WaiterGuardis constructed only afterscePthreadSemWait/Timedwaithas acquiredcurrent->_mutex. A caller can already have returned fromresolveSem()and be queued on that mutex whilesemWaiters[current]is still absent.scePthreadSemDestroy()can then acquiresemInitializationMutex, see no waiters, mark the slot destroyed, and deletecurrent; the queued call will subsequently touch the destroyed mutex/object. The same shape applies to other APIs afterresolveSem()(for example Post or Trywait).Could the lifetime accounting cover API entrants before they can block on the object mutex, and make that accounting cancellation-safe? A regression with a barrier after pointer resolution / before mutex acquisition would force the destroy interleaving; the current waiter-start flag and sleep do not guarantee this window.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-16T10:04:31Z.
I checked the new
0302994commit. It adds unrelatedEventFlag.cppchanges to this semaphore PR, and the delete path still has correctness problems:sceKernelDeleteEventFlagsets_deletedbut never calls_changed.NotifyAll(). A waiter blocked inWaitEventFlagtherefore never rechecks the predicate, so_waiters/_activecannot drain and the object is not retired.WaitEventFlag, the deleted path candelete efwhenlastis true, then immediately executes--ef->_active, accessing the freed object.PollEventFlagincrements_activebefore the single-waiterEPERMreturn, but that branch does not decrement it._activeincrements happen only after acquiringef->_mutex, so a caller queued on that mutex is still invisible to deletion.Could you move the EventFlag work to #6737 (or a separate PR) and fix these lifetime paths there? The original cancellation leak and raw-pointer-before-mutex gap in the semaphore change also remain unaddressed.
Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-16T12:11:32Z.
Review: COMMENTED
Follow-up to my earlier run on
243db5f7f: theguest_pthread_cancelregression I reported is gone.Native Linux, i7-8700, Ubuntu 26.04, GCC 15.2, Ninja Release,
BUILD_TESTING=ON, full build. Exact headc9f72b620d2e87c40fa6f7b096884d7e1f672416merged onmain0615cd2b8(currentmainaff725bf6does not build here, unrelatedPipelineJournal.cppstatic_assert).ctest -E "^agc|gpu|vulkan|video_out"): 648/650, same asmain. The twofile_writer_*failures also happen onmainon this machine.guest_pthread_semandguest_pthread_cancel:--repeat until-fail:50pass;guest_pthread_sem50/50 withtaskset -c 0.cce53d19fI removed only the__pthread_cleanup_push_imp_nid_postfix(CleanupSemaphoreWait, ...)call inscePthreadSemWait, and bothguest_pthread_semandguest_pthread_cancelabort. With the call restored they pass.Not checked here: ASan on this head, and Windows (
_endthreadexpath).Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by fogydes on 2026-10-16T15:14:51Z.
Thanks @jotitadev and @MarcZX100 for the thorough reviews and testing!
Pushed updates addressing the lifetime tracking and cancellation gaps:
EventFlag.cppchanges; all event flag improvements are isolated to #6737. That was an error on my part and commited to the wrong branch.std::shared_ptr<PthreadSemPrivate>tracked insemRegistryundersemInitializationMutex. CallingresolveSem()acquires astd::shared_ptr ownerbefore acquiringowner->_mutex, preventingscePthreadSemDestroyfrom freeing the object out from under callers queued on the mutex.CleanupSemaphoreWaitusing__pthread_cleanup_push_imp_nid_postfix. If a thread waiting inscePthreadSemWaitis cancelled viastd::longjmp/_endthreadex, the cleanup callback decrements_waitersand resets the context's owning reference, resolving the previousEBUSYleak on subsequent destroy calls.APS5_Test_SetPthreadSemApiPause/APS5_Test_ReleasePthreadSemApiPause) and corresponding tests inGuestPthreadSem.cppto deterministically verify pre-mutex destruction races without relying on sleeps.Imported from boykopovar/AnyPS5. Originally posted by fogydes on 2026-10-17T06:38:31Z.
Pushed commit 501a6fa74:
APS5_Test_*) fromAPS5_VABIinSem.cppandGuestPthreadSem.cpp, and defined the static cleanup callbackCleanupSemaphoreWaitusing lambda assignment to keep the progress tracker (tools/progress.py) from counting internal test helpers as PS5 guest library exports.Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-19T08:07:03Z.
Review: CHANGES_REQUESTED
Thanks for the work on the lifetime races; the shared_ptr registry and moving
NotifyOneunder the lock look right. Points to fix:Sem.cpp:107-108:scePthreadSemDestroyreturningSCE_KERNEL_ERROR_EBUSYwhen waiters exist is not what the cited source does. FreeBSD 11.4_sem_destroy(lib/libc/gen/sem_new.c) only validates the semaphore, rejects named ones with EINVAL and clears the magic; there is no waiter check and no EBUSY. prosper'sscePthreadSemDestroyalso always returns 0. Either point to a PS5/PS4 source that returns EBUSY (KytyPS5, shadPS4, prosper), or keep the previous "destroy succeeds" result and only make it memory-safe (waiters hold their ownshared_ptr, so deleting the slot is already safe). Drop the claim from the PR body if no source exists, and add the choice to TechnicalDebt under "Unknown function info".Sem.cpp:21-29,117,220-244and theAPS5_Test_*exports: test-only pause hooks and counters live in the production library (PauseSemApiruns on everyscePthreadSemPost). Test the post/destroy race without a hook in the shipped path (stress loop with many iterations, as your 50-iteration loop already does), or move the hook behind a test-only build definition.Sem.cpp:38:resolveSemnow takes the globalsemInitializationMutexon every Post/Wait/Trywait, serialising all semaphores in the process. Use a shared lock or keep the registry lookup off the hot path if you can.Please push these and I'll re-check.
Imported from boykopovar/AnyPS5. Originally posted by fogydes on 2026-10-19T08:52:04Z.
@adriadam10 Updated and rebased on
main:scePthreadSemDestroysemantics: Removed theEBUSYcheck;scePthreadSemDestroysucceeds with 0 even when waiters exist (memory-safe viastd::shared_ptrregistry and cleanup contexts). Waking waiters observe_destroyed == trueand returnSCE_KERNEL_ERROR_EINVAL. Added technical debt documentation under### Unknown function infoindocs/dev/debt/libkernel.mdand updated the PR description accordingly.PauseSemApilogic, pause atomic state, andAPS5_Test_SetPthreadSemApiPause/APS5_Test_ReleasePthreadSemApiPausehooks fromSem.cppandGuestPthreadSem.cpp. Verified post/destroy racing through a 50-iteration concurrent stress loop without hooks. Kept only the read-onlyAPS5_Test_GetPthreadSemWaiterCounthelper for test synchronization.semInitializationMutextostd::shared_mutex semRegistryMutexusingstd::shared_lockonresolveSem()lookups so hot synchronization paths do not contend on a global exclusive lock.Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-19T09:54:55Z.
Review: CHANGES_REQUESTED
Thanks, the EBUSY removal, the debt line, dropping the pause hooks and the shared lock in
resolveSemall look right. Two points left:GuestPthreadSem.cpp:150-164(queuedSemloop) fails wheneverscePthreadSemDestroycompletes before the post thread reachesresolveSem: the slot then holds the destroyed marker,resolveSemthrowsstd::runtime_error, thecatch (...)stores-2andRequire(postResult == SCE_OK || ...)aborts. That ordering is the common one (thread start is slower than the destroy), so the test is flaky/failing. Either accept the throw as a valid outcome of that race, or make the post thread start before destroy (e.g. a start flag) and only assert the no-crash property.Sem.cpp:209APS5_Test_GetPthreadSemWaiterCountis still test-only code in the production library, which was the second point of the previous review. The tests can synchronise without it (e.g. pollscePthreadSemTimedwait/a flag set by the waiter before it callsscePthreadSemWait, plus a short bounded sleep loop), or keep the counter behind a test-only build definition.Please push these and I'll re-check.
Imported from boykopovar/AnyPS5. Originally posted by fogydes on 2026-10-19T10:33:25Z.
Thanks for the re-review @adriadam10!
Addressed both points:
esolveSem\ throwing upon observing the destroyed slot) as a valid outcome alongside \SCE_OK\ and \SCE_KERNEL_ERROR_EINVAL, asserting the no-crash guarantee without flakiness.
36f60df9ed), \ ools/check_conventions.py --base origin/main\ passed with 0 warnings, and \guest_pthread_sem\ passed 10/10 consecutive runs.