fix(libkernel): prevent use-after-free on pthread semaphore destruction and notification race #6740

Merged
fogydes merged 1 commit from upstream-pr/6740 into main 2026-11-12 19:28:28 +00:00
fogydes commented 2026-10-16 08:54:28 +00:00 (Migrated from github.com)

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's scePthreadSem* implementation cause undefined behavior, heap corruption, and premature process termination:

  1. Notification Lifetime Race (scePthreadSemPost):
    scePthreadSemPost unlocked current->_mutex before invoking current->_cv.NotifyOne(). In typical producer-consumer or worker-synchronization patterns, a waiting thread waking in scePthreadSemWait can acquire the mutex, decrement _count, return SCE_OK, and immediately call scePthreadSemDestroy(sem). If destruction occurs while the posting thread is still inside or entering NotifyOne(), NotifyOne() accesses freed heap memory (PthreadSemPrivate), triggering heap-use-after-free or segmentation faults. Moving current->_cv.NotifyOne() inside the scope of std::lock_guard lock(current->_mutex) guarantees the posting thread finishes its notification before any waking waiter can re-acquire _mutex and deallocate the object.

  2. Destruction of In-Use Semaphore (scePthreadSemDestroy):
    Previously, scePthreadSemDestroy performed no waiter accounting and unconditionally deleted current even when threads were parked inside ThreadCancel::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_destroy and prosper, destroying a semaphore succeeds with 0 even when threads are waiting on it. Active semaphores are managed via std::shared_ptr<PthreadSemPrivate> stored in semRegistry guarded by std::shared_mutex semRegistryMutex. Destruction sets owner->_destroyed = true;, notifies all waiting threads on _cv, and unregisters the handle. Waking waiters safely observe _destroyed, clean up waiter tracking, and return SCE_KERNEL_ERROR_EINVAL (0x80020016). The underlying memory is safely retired once all waiters drop their reference. This behavior is documented in docs/dev/debt/libkernel.md under "Unknown function info".

  3. Exception Boundary Leak on Destroyed Semaphore:
    Calling scePthreadSemDestroy on a previously destroyed semaphore threw an unhandled C++ std::runtime_error("Semaphore is not initialized or has been destroyed") across the guest ABI boundary, causing std::terminate() and aborting the emulator. scePthreadSemDestroy now returns SCE_KERNEL_ERROR_EINVAL (0x80020016) for destroyed semaphores, consistent with scePthreadMutexDestroy.

  4. Shared Locking for Registry Resolution:
    resolveSem uses std::shared_lock on semRegistryMutex for lookups, keeping hot synchronization paths concurrent without global contention.

Test Scenario Before (origin/main) After (this PR)
scePthreadSemDestroy on in-use semaphore with active waiter Returned 0x0 and deleted semaphore while waiter crashed Returns 0x0 (SCE_OK); waiter wakes safely and returns 0x80020016 (SCE_KERNEL_ERROR_EINVAL)
scePthreadSemDestroy on previously destroyed semaphore Threw std::runtime_error, aborting process Returns 0x80020016 (SCE_KERNEL_ERROR_EINVAL)
Post-to-destroy lifetime race (50 rapid wake-and-destroy cycles) Intermittent access violation on freed _cv 50/50 cycles passed cleanly without memory faults

Tested

  • Host: Windows 11 Home 64-bit, MinGW-w64 GCC 15.2.0, C++20.
  • Empirical verification:
    • Unit test GuestPthreadSem with 50-iteration concurrent post/destroy stress loop and cancellation cleanup: passes without errors.
    • Conventions verification: python tools/check_conventions.py --base origin/main passed with 0 warnings.
  • Caveats:
    • Does not change POSIX sem_t functions (Posix/Sem.cpp), which are tracked separately in #6103.

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
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4885923615 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6740). Originally posted by [fogydes](https://github.com/fogydes) on 2026-10-16T08:54:28Z. --- ### What Two concurrency defects and one ABI exception leak in `libkernel`'s `scePthreadSem*` implementation cause undefined behavior, heap corruption, and premature process termination: 1. **Notification Lifetime Race (`scePthreadSemPost`):** `scePthreadSemPost` unlocked `current->_mutex` before invoking `current->_cv.NotifyOne()`. In typical producer-consumer or worker-synchronization patterns, a waiting thread waking in `scePthreadSemWait` can acquire the mutex, decrement `_count`, return `SCE_OK`, and immediately call `scePthreadSemDestroy(sem)`. If destruction occurs while the posting thread is still inside or entering `NotifyOne()`, `NotifyOne()` accesses freed heap memory (`PthreadSemPrivate`), triggering heap-use-after-free or segmentation faults. Moving `current->_cv.NotifyOne()` inside the scope of `std::lock_guard lock(current->_mutex)` guarantees the posting thread finishes its notification before any waking waiter can re-acquire `_mutex` and deallocate the object. 2. **Destruction of In-Use Semaphore (`scePthreadSemDestroy`):** Previously, `scePthreadSemDestroy` performed no waiter accounting and unconditionally deleted `current` even when threads were parked inside `ThreadCancel::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_destroy` and prosper, destroying a semaphore succeeds with 0 even when threads are waiting on it. Active semaphores are managed via `std::shared_ptr<PthreadSemPrivate>` stored in `semRegistry` guarded by `std::shared_mutex semRegistryMutex`. Destruction sets `owner->_destroyed = true;`, notifies all waiting threads on `_cv`, and unregisters the handle. Waking waiters safely observe `_destroyed`, clean up waiter tracking, and return `SCE_KERNEL_ERROR_EINVAL` (`0x80020016`). The underlying memory is safely retired once all waiters drop their reference. This behavior is documented in `docs/dev/debt/libkernel.md` under "Unknown function info". 3. **Exception Boundary Leak on Destroyed Semaphore:** Calling `scePthreadSemDestroy` on a previously destroyed semaphore threw an unhandled C++ `std::runtime_error("Semaphore is not initialized or has been destroyed")` across the guest ABI boundary, causing `std::terminate()` and aborting the emulator. `scePthreadSemDestroy` now returns `SCE_KERNEL_ERROR_EINVAL` (`0x80020016`) for destroyed semaphores, consistent with `scePthreadMutexDestroy`. 4. **Shared Locking for Registry Resolution:** `resolveSem` uses `std::shared_lock` on `semRegistryMutex` for lookups, keeping hot synchronization paths concurrent without global contention. | Test Scenario | Before (origin/main) | After (this PR) | | --- | --- | --- | | `scePthreadSemDestroy` on in-use semaphore with active waiter | Returned `0x0` and deleted semaphore while waiter crashed | Returns `0x0` (`SCE_OK`); waiter wakes safely and returns `0x80020016` (`SCE_KERNEL_ERROR_EINVAL`) | | `scePthreadSemDestroy` on previously destroyed semaphore | Threw `std::runtime_error`, aborting process | Returns `0x80020016` (`SCE_KERNEL_ERROR_EINVAL`) | | Post-to-destroy lifetime race (50 rapid wake-and-destroy cycles) | Intermittent access violation on freed `_cv` | 50/50 cycles passed cleanly without memory faults | ### Tested - Host: Windows 11 Home 64-bit, MinGW-w64 GCC 15.2.0, C++20. - Empirical verification: - Unit test `GuestPthreadSem` with 50-iteration concurrent post/destroy stress loop and cancellation cleanup: passes without errors. - Conventions verification: `python tools/check_conventions.py --base origin/main` passed with 0 warnings. - Caveats: - Does not change POSIX `sem_t` functions (`Posix/Sem.cpp`), which are tracked separately in #6103. ### 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 - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes
jotitadev commented 2026-10-16 09:46:09 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-16T09:46:09Z.

Review: COMMENTED


Native Linux run on exact head 243db5f7fc3a67dfcb1ad42880336581d2df9750, applied on main 5d9dcc42d.

Machine: Intel i7-8700 (6C/12T), Ubuntu 26.04, GCC 15.2, Ninja Release, BUILD_TESTING=ON, full build. Sanitizer runs use a separate RelWithDebInfo build with -DANYPS5_ENABLE_ASAN=ON, ASAN_OPTIONS=detect_leaks=0:halt_on_error=1.

guest_pthread_cancel regresses. Non-GPU suite (ctest -E "^agc|gpu|vulkan|video_out"): 647/650, versus 648/650 on main. The two file_writer_* failures also happen on main on this machine. The new failure is guest_pthread_cancel, which aborts on every run (3/3 normal, 3/3 ASan; it passes on main). It fails at the final Require(scePthreadSemDestroy(&shared.sem) == SCE_OK), which now returns 0x80020010 (EBUSY).

Cause: a thread cancelled inside scePthreadSemWait never runs ~WaiterGuard. ThreadCancel::WaitUntil calls Check() → scePthreadExit, which leaves through std::longjmp(*threadExitJump, 1) on Linux (_endthreadex on Windows). Neither runs C++ destructors, so semWaiters[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 (before Check() exits, or through a cleanup handler), not only in a destructor.

The race loop does not cover the scePthreadSemPost change. I kept this PR's Sem.cpp and moved only NotifyOne() back outside the lock_guard (the main ordering). Under ASan the updated guest_pthread_sem test still passed 100/100, and 50/50 with taskset -c 0. After the 50 µs sleep the racer is usually already parked in WaitUntil and needs the notification to wake, so the post-then-destroy window is not reached.

Other results:

  • PR as is: guest_pthread_sem 50/50 normal, 20/20 with taskset -c 0; ASan 100/100 and 20/20 with taskset -c 0, no reports.
  • Test applied to main's Sem.cpp: fails 5/5 with std::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.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5545930787 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6740#pullrequestreview-5545930787). Originally posted by [jotitadev](https://github.com/jotitadev) on 2026-10-16T09:46:09Z. **Review:** COMMENTED --- Native Linux run on exact head `243db5f7fc3a67dfcb1ad42880336581d2df9750`, applied on `main` `5d9dcc42d`. Machine: Intel i7-8700 (6C/12T), Ubuntu 26.04, GCC 15.2, Ninja Release, `BUILD_TESTING=ON`, full build. Sanitizer runs use a separate `RelWithDebInfo` build with `-DANYPS5_ENABLE_ASAN=ON`, `ASAN_OPTIONS=detect_leaks=0:halt_on_error=1`. **`guest_pthread_cancel` regresses.** Non-GPU suite (`ctest -E "^agc|gpu|vulkan|video_out"`): 647/650, versus 648/650 on `main`. The two `file_writer_*` failures also happen on `main` on this machine. The new failure is `guest_pthread_cancel`, which aborts on every run (3/3 normal, 3/3 ASan; it passes on `main`). It fails at the final `Require(scePthreadSemDestroy(&shared.sem) == SCE_OK)`, which now returns `0x80020010` (EBUSY). Cause: a thread cancelled inside `scePthreadSemWait` never runs `~WaiterGuard`. `ThreadCancel::WaitUntil` calls `Check()` → `scePthreadExit`, which leaves through `std::longjmp(*threadExitJump, 1)` on Linux (`_endthreadex` on Windows). Neither runs C++ destructors, so `semWaiters[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 (before `Check()` exits, or through a cleanup handler), not only in a destructor. **The race loop does not cover the `scePthreadSemPost` change.** I kept this PR's `Sem.cpp` and moved only `NotifyOne()` back outside the `lock_guard` (the `main` ordering). Under ASan the updated `guest_pthread_sem` test still passed 100/100, and 50/50 with `taskset -c 0`. After the 50 µs sleep the racer is usually already parked in `WaitUntil` and needs the notification to wake, so the post-then-destroy window is not reached. Other results: - PR as is: `guest_pthread_sem` 50/50 normal, 20/20 with `taskset -c 0`; ASan 100/100 and 20/20 with `taskset -c 0`, no reports. - Test applied to `main`'s `Sem.cpp`: fails 5/5 with `std::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.
MarcZX10 commented 2026-10-16 09:57:52 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-16T09:57:52Z.


One additional lifetime gap: WaiterGuard is constructed only after scePthreadSemWait/Timedwait has acquired current->_mutex. A caller can already have returned from resolveSem() and be queued on that mutex while semWaiters[current] is still absent. scePthreadSemDestroy() can then acquire semInitializationMutex, see no waiters, mark the slot destroyed, and delete current; the queued call will subsequently touch the destroyed mutex/object. The same shape applies to other APIs after resolveSem() (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.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6212968536 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6740#issuecomment-6212968536). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-16T09:57:52Z. --- One additional lifetime gap: `WaiterGuard` is constructed only after `scePthreadSemWait`/`Timedwait` has acquired `current->_mutex`. A caller can already have returned from `resolveSem()` and be queued on that mutex while `semWaiters[current]` is still absent. `scePthreadSemDestroy()` can then acquire `semInitializationMutex`, see no waiters, mark the slot destroyed, and delete `current`; the queued call will subsequently touch the destroyed mutex/object. The same shape applies to other APIs after `resolveSem()` (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.
MarcZX10 commented 2026-10-16 10:04:31 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-16T10:04:31Z.


I checked the new 0302994 commit. It adds unrelated EventFlag.cpp changes to this semaphore PR, and the delete path still has correctness problems:

  • sceKernelDeleteEventFlag sets _deleted but never calls _changed.NotifyAll(). A waiter blocked in WaitEventFlag therefore never rechecks the predicate, so _waiters/_active cannot drain and the object is not retired.
  • In WaitEventFlag, the deleted path can delete ef when last is true, then immediately executes --ef->_active, accessing the freed object.
  • PollEventFlag increments _active before the single-waiter EPERM return, but that branch does not decrement it.
  • The _active increments happen only after acquiring ef->_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.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6213083909 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6740#issuecomment-6213083909). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-16T10:04:31Z. --- I checked the new `0302994` commit. It adds unrelated `EventFlag.cpp` changes to this semaphore PR, and the delete path still has correctness problems: - `sceKernelDeleteEventFlag` sets `_deleted` but never calls `_changed.NotifyAll()`. A waiter blocked in `WaitEventFlag` therefore never rechecks the predicate, so `_waiters`/`_active` cannot drain and the object is not retired. - In `WaitEventFlag`, the deleted path can `delete ef` when `last` is true, then immediately executes `--ef->_active`, accessing the freed object. - `PollEventFlag` increments `_active` before the single-waiter `EPERM` return, but that branch does not decrement it. - The `_active` increments happen only after acquiring `ef->_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.
jotitadev commented 2026-10-16 12:11:32 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-16T12:11:32Z.

Review: COMMENTED


Follow-up to my earlier run on 243db5f7f: the guest_pthread_cancel regression I reported is gone.

Native Linux, i7-8700, Ubuntu 26.04, GCC 15.2, Ninja Release, BUILD_TESTING=ON, full build. Exact head c9f72b620d2e87c40fa6f7b096884d7e1f672416 merged on main 0615cd2b8 (current main aff725bf6 does not build here, unrelated PipelineJournal.cpp static_assert).

  • Non-GPU suite (ctest -E "^agc|gpu|vulkan|video_out"): 648/650, same as main. The two file_writer_* failures also happen on main on this machine.
  • guest_pthread_sem and guest_pthread_cancel: --repeat until-fail:50 pass; guest_pthread_sem 50/50 with taskset -c 0.
  • The new cancel case does guard the cleanup path: on the previous head cce53d19f I removed only the __pthread_cleanup_push_imp_nid_postfix(CleanupSemaphoreWait, ...) call in scePthreadSemWait, and both guest_pthread_sem and guest_pthread_cancel abort. With the call restored they pass.

Not checked here: ASan on this head, and Windows (_endthreadex path).

Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5547584576 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6740#pullrequestreview-5547584576). Originally posted by [jotitadev](https://github.com/jotitadev) on 2026-10-16T12:11:32Z. **Review:** COMMENTED --- Follow-up to my earlier run on `243db5f7f`: the `guest_pthread_cancel` regression I reported is gone. Native Linux, i7-8700, Ubuntu 26.04, GCC 15.2, Ninja Release, `BUILD_TESTING=ON`, full build. Exact head `c9f72b620d2e87c40fa6f7b096884d7e1f672416` merged on `main` `0615cd2b8` (current `main` `aff725bf6` does not build here, unrelated `PipelineJournal.cpp` static_assert). - Non-GPU suite (`ctest -E "^agc|gpu|vulkan|video_out"`): 648/650, same as `main`. The two `file_writer_*` failures also happen on `main` on this machine. - `guest_pthread_sem` and `guest_pthread_cancel`: `--repeat until-fail:50` pass; `guest_pthread_sem` 50/50 with `taskset -c 0`. - The new cancel case does guard the cleanup path: on the previous head `cce53d19f` I removed only the `__pthread_cleanup_push_imp_nid_postfix(CleanupSemaphoreWait, ...)` call in `scePthreadSemWait`, and both `guest_pthread_sem` and `guest_pthread_cancel` abort. With the call restored they pass. Not checked here: ASan on this head, and Windows (`_endthreadex` path). Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
fogydes commented 2026-10-16 15:14:51 +00:00 (Migrated from github.com)

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:

  1. Scope Cleanliness: Removed unrelated EventFlag.cpp changes; all event flag improvements are isolated to #6737. That was an error on my part and commited to the wrong branch.
  2. Pre-Mutex Lifetime Protection: Replaced raw pointer lifetime management with std::shared_ptr<PthreadSemPrivate> tracked in semRegistry under semInitializationMutex. Calling resolveSem() acquires a std::shared_ptr owner before acquiring owner->_mutex, preventing scePthreadSemDestroy from freeing the object out from under callers queued on the mutex.
  3. Cancellation-Safe Waiter Tracking: As verified by @jotitadev, registered CleanupSemaphoreWait using __pthread_cleanup_push_imp_nid_postfix. If a thread waiting in scePthreadSemWait is cancelled via std::longjmp / _endthreadex, the cleanup callback decrements _waiters and resets the context's owning reference, resolving the previous EBUSY leak on subsequent destroy calls.
  4. Deterministic Race Coverage: Added API pause hooks (APS5_Test_SetPthreadSemApiPause / APS5_Test_ReleasePthreadSemApiPause) and corresponding tests in GuestPthreadSem.cpp to deterministically verify pre-mutex destruction races without relying on sleeps.
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6218568559 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6740#issuecomment-6218568559). Originally posted by [fogydes](https://github.com/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: 1. **Scope Cleanliness**: Removed unrelated `EventFlag.cpp` changes; all event flag improvements are isolated to #6737. That was an error on my part and commited to the wrong branch. 2. **Pre-Mutex Lifetime Protection**: Replaced raw pointer lifetime management with `std::shared_ptr<PthreadSemPrivate>` tracked in `semRegistry` under `semInitializationMutex`. Calling `resolveSem()` acquires a `std::shared_ptr owner` before acquiring `owner->_mutex`, preventing `scePthreadSemDestroy` from freeing the object out from under callers queued on the mutex. 3. **Cancellation-Safe Waiter Tracking**: As verified by @jotitadev, registered `CleanupSemaphoreWait` using `__pthread_cleanup_push_imp_nid_postfix`. If a thread waiting in `scePthreadSemWait` is cancelled via `std::longjmp` / `_endthreadex`, the cleanup callback decrements `_waiters` and resets the context's owning reference, resolving the previous `EBUSY` leak on subsequent destroy calls. 4. **Deterministic Race Coverage**: Added API pause hooks (`APS5_Test_SetPthreadSemApiPause` / `APS5_Test_ReleasePthreadSemApiPause`) and corresponding tests in `GuestPthreadSem.cpp` to deterministically verify pre-mutex destruction races without relying on sleeps.
fogydes commented 2026-10-17 06:38:31 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by fogydes on 2026-10-17T06:38:31Z.


Pushed commit 501a6fa74:

  • Unmarked the internal test synchronization hooks (APS5_Test_*) from APS5_VABI in Sem.cpp and GuestPthreadSem.cpp, and defined the static cleanup callback CleanupSemaphoreWait using lambda assignment to keep the progress tracker (tools/progress.py) from counting internal test helpers as PS5 guest library exports.
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6230769505 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6740#issuecomment-6230769505). Originally posted by [fogydes](https://github.com/fogydes) on 2026-10-17T06:38:31Z. --- Pushed commit 501a6fa74: - Unmarked the internal test synchronization hooks (`APS5_Test_*`) from `APS5_VABI` in `Sem.cpp` and `GuestPthreadSem.cpp`, and defined the static cleanup callback `CleanupSemaphoreWait` using lambda assignment to keep the progress tracker (`tools/progress.py`) from counting internal test helpers as PS5 guest library exports.
adriadam10 commented 2026-10-19 08:07:03 +00:00 (Migrated from github.com)

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 NotifyOne under the lock look right. Points to fix:

  • Sem.cpp:107-108: scePthreadSemDestroy returning SCE_KERNEL_ERROR_EBUSY when 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's scePthreadSemDestroy also 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 own shared_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-244 and the APS5_Test_* exports: test-only pause hooks and counters live in the production library (PauseSemApi runs on every scePthreadSemPost). 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: resolveSem now takes the global semInitializationMutex on 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.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5568591872 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6740#pullrequestreview-5568591872). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-19T08:07:03Z. **Review:** CHANGES_REQUESTED --- Thanks for the work on the lifetime races; the shared_ptr registry and moving `NotifyOne` under the lock look right. Points to fix: - `Sem.cpp:107-108`: `scePthreadSemDestroy` returning `SCE_KERNEL_ERROR_EBUSY` when 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's `scePthreadSemDestroy` also 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 own `shared_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-244` and the `APS5_Test_*` exports: test-only pause hooks and counters live in the production library (`PauseSemApi` runs on every `scePthreadSemPost`). 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`: `resolveSem` now takes the global `semInitializationMutex` on 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.
fogydes commented 2026-10-19 08:52:04 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by fogydes on 2026-10-19T08:52:04Z.


@adriadam10 Updated and rebased on main:

  1. scePthreadSemDestroy semantics: Removed the EBUSY check; scePthreadSemDestroy succeeds with 0 even when waiters exist (memory-safe via std::shared_ptr registry and cleanup contexts). Waking waiters observe _destroyed == true and return SCE_KERNEL_ERROR_EINVAL. Added technical debt documentation under ### Unknown function info in docs/dev/debt/libkernel.md and updated the PR description accordingly.
  2. Production test hooks removed: Removed all PauseSemApi logic, pause atomic state, and APS5_Test_SetPthreadSemApiPause / APS5_Test_ReleasePthreadSemApiPause hooks from Sem.cpp and GuestPthreadSem.cpp. Verified post/destroy racing through a 50-iteration concurrent stress loop without hooks. Kept only the read-only APS5_Test_GetPthreadSemWaiterCount helper for test synchronization.
  3. Concurrent registry lookups: Changed semInitializationMutex to std::shared_mutex semRegistryMutex using std::shared_lock on resolveSem() lookups so hot synchronization paths do not contend on a global exclusive lock.
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6263413863 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6740#issuecomment-6263413863). Originally posted by [fogydes](https://github.com/fogydes) on 2026-10-19T08:52:04Z. --- @adriadam10 Updated and rebased on `main`: 1. **`scePthreadSemDestroy` semantics**: Removed the `EBUSY` check; `scePthreadSemDestroy` succeeds with 0 even when waiters exist (memory-safe via `std::shared_ptr` registry and cleanup contexts). Waking waiters observe `_destroyed == true` and return `SCE_KERNEL_ERROR_EINVAL`. Added technical debt documentation under `### Unknown function info` in `docs/dev/debt/libkernel.md` and updated the PR description accordingly. 2. **Production test hooks removed**: Removed all `PauseSemApi` logic, pause atomic state, and `APS5_Test_SetPthreadSemApiPause` / `APS5_Test_ReleasePthreadSemApiPause` hooks from `Sem.cpp` and `GuestPthreadSem.cpp`. Verified post/destroy racing through a 50-iteration concurrent stress loop without hooks. Kept only the read-only `APS5_Test_GetPthreadSemWaiterCount` helper for test synchronization. 3. **Concurrent registry lookups**: Changed `semInitializationMutex` to `std::shared_mutex semRegistryMutex` using `std::shared_lock` on `resolveSem()` lookups so hot synchronization paths do not contend on a global exclusive lock.
adriadam10 commented 2026-10-19 09:54:55 +00:00 (Migrated from github.com)

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 resolveSem all look right. Two points left:

  • GuestPthreadSem.cpp:150-164 (queuedSem loop) fails whenever scePthreadSemDestroy completes before the post thread reaches resolveSem: the slot then holds the destroyed marker, resolveSem throws std::runtime_error, the catch (...) stores -2 and Require(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:209 APS5_Test_GetPthreadSemWaiterCount is 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. poll scePthreadSemTimedwait/a flag set by the waiter before it calls scePthreadSemWait, plus a short bounded sleep loop), or keep the counter behind a test-only build definition.

Please push these and I'll re-check.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5569798934 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6740#pullrequestreview-5569798934). Originally posted by [adriadam10](https://github.com/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 `resolveSem` all look right. Two points left: - `GuestPthreadSem.cpp:150-164` (`queuedSem` loop) fails whenever `scePthreadSemDestroy` completes before the post thread reaches `resolveSem`: the slot then holds the destroyed marker, `resolveSem` throws `std::runtime_error`, the `catch (...)` stores `-2` and `Require(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:209` `APS5_Test_GetPthreadSemWaiterCount` is 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. poll `scePthreadSemTimedwait`/a flag set by the waiter before it calls `scePthreadSemWait`, plus a short bounded sleep loop), or keep the counter behind a test-only build definition. Please push these and I'll re-check.
fogydes commented 2026-10-19 10:33:25 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by fogydes on 2026-10-19T10:33:25Z.


Thanks for the re-review @adriadam10!

Addressed both points:

  • Removed test hook from production library: Deleted \APS5_Test_GetPthreadSemWaiterCount\ from \Sem.cpp. The tests in \GuestPthreadSem.cpp\ now synchronise using atomic flags set by the waiter threads prior to entering the wait, followed by bounded yields/sleeps.
  • Addressed post/destroy race in test: Set a \postStarted\ atomic flag before destroy in \GuestPthreadSem.cpp\ and accepted -2\ (
    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.
  • Rebased on current \main\ (\36f60df9ed), \ ools/check_conventions.py --base origin/main\ passed with 0 warnings, and \guest_pthread_sem\ passed 10/10 consecutive runs.
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6265201413 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6740#issuecomment-6265201413). Originally posted by [fogydes](https://github.com/fogydes) on 2026-10-19T10:33:25Z. --- Thanks for the re-review @adriadam10! Addressed both points: - **Removed test hook from production library**: Deleted \APS5_Test_GetPthreadSemWaiterCount\ from \Sem.cpp\. The tests in \GuestPthreadSem.cpp\ now synchronise using atomic flags set by the waiter threads prior to entering the wait, followed by bounded yields/sleeps. - **Addressed post/destroy race in test**: Set a \postStarted\ atomic flag before destroy in \GuestPthreadSem.cpp\ and accepted \-2\ (\ 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. - Rebased on current \main\ (\36f60df9ed\), \ ools/check_conventions.py --base origin/main\ passed with 0 warnings, and \guest_pthread_sem\ passed 10/10 consecutive runs.
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!6740
No description provided.