fix(libkernel): prevent use-after-free on event flag deletion and multi-waiter race #6737

Merged
fogydes merged 1 commit from upstream-pr/6737 into main 2026-10-19 11:05:18 +00:00
fogydes commented 2026-10-16 08:36:52 +00:00 (Migrated from github.com)

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


What

This change addresses two synchronization defects in EventFlag.cpp:

  1. Pre-Mutex Lifetime Protection and Drain in sceKernelDeleteEventFlag:
    Previously, if _waiters != 0, sceKernelDeleteEventFlag flagged ef->_deleted = true, called ef->_changed.NotifyAll(), and immediately returned SCE_OK without waiting. The last waking waiter decremented _waiters to 0, unlocked _mutex, and called delete ef;. Furthermore, callers queued to acquire _mutex in other APIs had no lifetime protection, leading to use-after-free upon deletion.
    Event flags are now tracked in eventFlagRegistry using std::shared_ptr<KernelEventFlagPrivate> guarded by std::shared_mutex eventFlagRegistryMutex. Every API entry point acquires an owning keepAlive reference before attempting to acquire the object's _mutex. sceKernelDeleteEventFlag marks _deleted = true, notifies all waiters, waits for _waiters == 0, and retires the handle from the registry. Waiting threads decrement _waiters and notify the deleter via RAII WaiterGuard, returning SCE_KERNEL_ERROR_EACCES. Callers hold keepAlive throughout execution, guaranteeing no memory corruption or use-after-free occurs.

  2. Multi-Waiter In-Order Evaluation Semantics (sceKernelSetEventFlag):
    When multiple threads wait on an EVF_ATTR_MULTI event flag, waiters are queued in registration order via an intrusive FIFO list.
    Following fpPS4 (kernel/ps4_event_flag.pas, _sceKernelSetEventFlag), sceKernelSetEventFlag evaluates registered waiters in FIFO order. Each satisfied waiter records its result pattern and has its clear mode applied immediately to _pattern (_change_by_mode) before subsequent waiters are evaluated. If a preceding waiter clears bits, any later waiter whose condition is no longer met remains asleep. This behavior is documented in docs/dev/debt/libkernel.md under "Unknown function info".

Tested

  • Windows 11 x86-64, MinGW-w64 GCC 15.2.0, C++20.
  • Unit tests in GuestKernelErrors.cpp:
    • Multi-waiter FIFO evaluation: non-clearing waiter registered first and clearing waiter registered second (both wake with SCE_OK).
    • Multi-waiter FIFO evaluation: clearing waiter registered first and non-clearing waiter registered second (first wakes and clears; second stays asleep until next set).
    • Deletion with active waiters returning SCE_KERNEL_ERROR_EACCES.
    • Concurrent pre-mutex Set/Poll stress loops (50 iterations each) racing deletion without leaks or crashes.
  • python tools/check_conventions.py --base origin/main: passed with 0 warnings.

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:4885715175 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6737). Originally posted by [fogydes](https://github.com/fogydes) on 2026-10-16T08:36:52Z. --- ### What This change addresses two synchronization defects in `EventFlag.cpp`: 1. **Pre-Mutex Lifetime Protection and Drain in `sceKernelDeleteEventFlag`:** Previously, if `_waiters != 0`, `sceKernelDeleteEventFlag` flagged `ef->_deleted = true`, called `ef->_changed.NotifyAll()`, and immediately returned `SCE_OK` without waiting. The last waking waiter decremented `_waiters` to 0, unlocked `_mutex`, and called `delete ef;`. Furthermore, callers queued to acquire `_mutex` in other APIs had no lifetime protection, leading to use-after-free upon deletion. Event flags are now tracked in `eventFlagRegistry` using `std::shared_ptr<KernelEventFlagPrivate>` guarded by `std::shared_mutex eventFlagRegistryMutex`. Every API entry point acquires an owning `keepAlive` reference before attempting to acquire the object's `_mutex`. `sceKernelDeleteEventFlag` marks `_deleted = true`, notifies all waiters, waits for `_waiters == 0`, and retires the handle from the registry. Waiting threads decrement `_waiters` and notify the deleter via RAII `WaiterGuard`, returning `SCE_KERNEL_ERROR_EACCES`. Callers hold `keepAlive` throughout execution, guaranteeing no memory corruption or use-after-free occurs. 2. **Multi-Waiter In-Order Evaluation Semantics (`sceKernelSetEventFlag`):** When multiple threads wait on an `EVF_ATTR_MULTI` event flag, waiters are queued in registration order via an intrusive FIFO list. Following fpPS4 (`kernel/ps4_event_flag.pas`, `_sceKernelSetEventFlag`), `sceKernelSetEventFlag` evaluates registered waiters in FIFO order. Each satisfied waiter records its result pattern and has its clear mode applied immediately to `_pattern` (`_change_by_mode`) before subsequent waiters are evaluated. If a preceding waiter clears bits, any later waiter whose condition is no longer met remains asleep. This behavior is documented in `docs/dev/debt/libkernel.md` under "Unknown function info". ### Tested - Windows 11 x86-64, MinGW-w64 GCC 15.2.0, C++20. - Unit tests in `GuestKernelErrors.cpp`: - Multi-waiter FIFO evaluation: non-clearing waiter registered first and clearing waiter registered second (both wake with `SCE_OK`). - Multi-waiter FIFO evaluation: clearing waiter registered first and non-clearing waiter registered second (first wakes and clears; second stays asleep until next set). - Deletion with active waiters returning `SCE_KERNEL_ERROR_EACCES`. - Concurrent pre-mutex Set/Poll stress loops (50 iterations each) racing deletion without leaks or crashes. - `python tools/check_conventions.py --base origin/main`: passed with 0 warnings. ### 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
MarcZX10 commented 2026-10-16 08:53:37 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-16T08:53:37Z.


One test reliability concern: both concurrent regressions signal “started” before entering sceKernelWaitEventFlag, then rely on a 5 ms sleep before SetEventFlag/delete. The main thread can still run first (or a waiter can be descheduled after setting its flag), so the new multi-waiter case can take the immediate-satisfaction path and the deletion case can run before either waiter is registered. In that schedule the tests pass without exercising the two races this PR fixes. Could the tests synchronize on actual waiter registration (or expose a test-only barrier) instead of using the sleep? I have not reproduced a miss; this is about ensuring the regression tests force the intended interleaving.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6211838719 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6737#issuecomment-6211838719). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-16T08:53:37Z. --- One test reliability concern: both concurrent regressions signal “started” before entering `sceKernelWaitEventFlag`, then rely on a 5 ms sleep before `SetEventFlag`/delete. The main thread can still run first (or a waiter can be descheduled after setting its flag), so the new multi-waiter case can take the immediate-satisfaction path and the deletion case can run before either waiter is registered. In that schedule the tests pass without exercising the two races this PR fixes. Could the tests synchronize on actual waiter registration (or expose a test-only barrier) instead of using the sleep? I have not reproduced a miss; this is about ensuring the regression tests force the intended interleaving.
MarcZX10 commented 2026-10-16 09:12:35 +00:00 (Migrated from github.com)

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


I also have a lifetime question about the delete drain. _waiters counts only calls that entered the blocking wait path. If sceKernelSetEventFlag/PollEventFlag is already blocked acquiring _mutex while the deleter is waiting, the last waiter can drop _waiters to zero; the deleter can then reacquire the mutex, observe zero, unlock and delete ef while that non-waiter API call is still queued on the mutex. That would leave the same destroyed-mutex race described in the PR body. Is concurrent Set/Poll during deletion forbidden by the guest API contract? If the fix intends to cover those callers, could the object lifetime also account for active API entrants (and add a stress case for a setter/poller racing deletion)? This is a code-path concern; I have not reproduced it.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6212152723 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6737#issuecomment-6212152723). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-16T09:12:35Z. --- I also have a lifetime question about the delete drain. `_waiters` counts only calls that entered the blocking wait path. If `sceKernelSetEventFlag`/`PollEventFlag` is already blocked acquiring `_mutex` while the deleter is waiting, the last waiter can drop `_waiters` to zero; the deleter can then reacquire the mutex, observe zero, unlock and delete `ef` while that non-waiter API call is still queued on the mutex. That would leave the same destroyed-mutex race described in the PR body. Is concurrent Set/Poll during deletion forbidden by the guest API contract? If the fix intends to cover those callers, could the object lifetime also account for active API entrants (and add a stress case for a setter/poller racing deletion)? This is a code-path concern; I have not reproduced it.
github-actions[bot] commented 2026-10-16 09:34:03 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-16T09:34:03Z.


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 5021 docs/dev/debt/libkernel.md
PR 6044 core/libs/tests/GuestKernelErrors.cpp
PR 6149 docs/dev/debt/libkernel.md
PR 6446 docs/dev/debt/libkernel.md
PR 6469 docs/dev/debt/libkernel.md
PR 6519 docs/dev/debt/libkernel.md
PR 6836 docs/dev/debt/libkernel.md
PR 6908 docs/dev/debt/libkernel.md
PR 6936 docs/dev/debt/libkernel.md
PR 6977 docs/dev/debt/libkernel.md
PR 7039 docs/dev/debt/libkernel.md
PR 7049 docs/dev/debt/libkernel.md
PR 7075 docs/dev/debt/libkernel.md
PR 7088 docs/dev/debt/libkernel.md
PR 7105 docs/dev/debt/libkernel.md
PR 7121 docs/dev/debt/libkernel.md
PR 7129 docs/dev/debt/libkernel.md
PR 7149 docs/dev/debt/libkernel.md
PR 7192 docs/dev/debt/libkernel.md
PR 7299 docs/dev/debt/libkernel.md
PR 7332 docs/dev/debt/libkernel.md
PR 7509 docs/dev/debt/libkernel.md
PR 7543 docs/dev/debt/libkernel.md
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6212559595 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6737#issuecomment-6212559595). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-16T09:34:03Z. --- <!-- pr-overlap --> 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 5021](https://www.github.com/boykopovar/AnyPS5/pull/5021) | `docs/dev/debt/libkernel.md` | | [PR 6044](https://www.github.com/boykopovar/AnyPS5/pull/6044) | `core/libs/tests/GuestKernelErrors.cpp` | | [PR 6149](https://www.github.com/boykopovar/AnyPS5/pull/6149) | `docs/dev/debt/libkernel.md` | | [PR 6446](https://www.github.com/boykopovar/AnyPS5/pull/6446) | `docs/dev/debt/libkernel.md` | | [PR 6469](https://www.github.com/boykopovar/AnyPS5/pull/6469) | `docs/dev/debt/libkernel.md` | | [PR 6519](https://www.github.com/boykopovar/AnyPS5/pull/6519) | `docs/dev/debt/libkernel.md` | | [PR 6836](https://www.github.com/boykopovar/AnyPS5/pull/6836) | `docs/dev/debt/libkernel.md` | | [PR 6908](https://www.github.com/boykopovar/AnyPS5/pull/6908) | `docs/dev/debt/libkernel.md` | | [PR 6936](https://www.github.com/boykopovar/AnyPS5/pull/6936) | `docs/dev/debt/libkernel.md` | | [PR 6977](https://www.github.com/boykopovar/AnyPS5/pull/6977) | `docs/dev/debt/libkernel.md` | | [PR 7039](https://www.github.com/boykopovar/AnyPS5/pull/7039) | `docs/dev/debt/libkernel.md` | | [PR 7049](https://www.github.com/boykopovar/AnyPS5/pull/7049) | `docs/dev/debt/libkernel.md` | | [PR 7075](https://www.github.com/boykopovar/AnyPS5/pull/7075) | `docs/dev/debt/libkernel.md` | | [PR 7088](https://www.github.com/boykopovar/AnyPS5/pull/7088) | `docs/dev/debt/libkernel.md` | | [PR 7105](https://www.github.com/boykopovar/AnyPS5/pull/7105) | `docs/dev/debt/libkernel.md` | | [PR 7121](https://www.github.com/boykopovar/AnyPS5/pull/7121) | `docs/dev/debt/libkernel.md` | | [PR 7129](https://www.github.com/boykopovar/AnyPS5/pull/7129) | `docs/dev/debt/libkernel.md` | | [PR 7149](https://www.github.com/boykopovar/AnyPS5/pull/7149) | `docs/dev/debt/libkernel.md` | | [PR 7192](https://www.github.com/boykopovar/AnyPS5/pull/7192) | `docs/dev/debt/libkernel.md` | | [PR 7299](https://www.github.com/boykopovar/AnyPS5/pull/7299) | `docs/dev/debt/libkernel.md` | | [PR 7332](https://www.github.com/boykopovar/AnyPS5/pull/7332) | `docs/dev/debt/libkernel.md` | | [PR 7509](https://www.github.com/boykopovar/AnyPS5/pull/7509) | `docs/dev/debt/libkernel.md` | | [PR 7543](https://www.github.com/boykopovar/AnyPS5/pull/7543) | `docs/dev/debt/libkernel.md` |
jotitadev commented 2026-10-16 09:46:11 +00:00 (Migrated from github.com)

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

Review: COMMENTED


Native Linux run on exact head f4db9065b3024b8d3be62c951acf8ac173e247ab, 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.

The test does not compile. A full build with BUILD_TESTING=ON stops at:

core/libs/tests/GuestKernelErrors.cpp:295:24: error: 'SCE_KERNEL_ERROR_EACCES' was not declared in this scope

The test file defines its own error constants (lines 45-54) and EACCES is not one of them. The build-relinker run in the description does not build guest_kernel_error_tests, so this would not show up there. For the runs below I added static constexpr int SCE_KERNEL_ERROR_EACCES = static_cast<int>(0x8002000D); next to the others.

With that line added:

  • 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_kernel_errors: 100/100 normal, 50/50 with taskset -c 0. ASan: 50/50, and 20/20 with taskset -c 0, no reports.

Test against main's EventFlag.cpp (same test, only the production file replaced), each run with a 5 s timeout:

Run Failures
12 threads 6/30, all hangs
taskset -c 0 0/30
ASan, 12 threads 5/20, all hangs, no ASan report

With APS5_TRACE_SYNC=1, a hanging run stops in multi_race after set ... |=0x1, with both waiters registered: the missed wakeup this PR fixes. So on this machine the multi-waiter case catches the missed wakeup about 1 run in 5, and never on one CPU. This matches @MarcZX100's point about the 5 ms sleep. The deletion case passed on main in every run that got past the multi-waiter case, ASan included, so it does not detect the old delete path.

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

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5545931470 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6737#pullrequestreview-5545931470). Originally posted by [jotitadev](https://github.com/jotitadev) on 2026-10-16T09:46:11Z. **Review:** COMMENTED --- Native Linux run on exact head `f4db9065b3024b8d3be62c951acf8ac173e247ab`, 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`. **The test does not compile.** A full build with `BUILD_TESTING=ON` stops at: ``` core/libs/tests/GuestKernelErrors.cpp:295:24: error: 'SCE_KERNEL_ERROR_EACCES' was not declared in this scope ``` The test file defines its own error constants (lines 45-54) and EACCES is not one of them. The `build-relinker` run in the description does not build `guest_kernel_error_tests`, so this would not show up there. For the runs below I added `static constexpr int SCE_KERNEL_ERROR_EACCES = static_cast<int>(0x8002000D);` next to the others. With that line added: - 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_kernel_errors`: 100/100 normal, 50/50 with `taskset -c 0`. ASan: 50/50, and 20/20 with `taskset -c 0`, no reports. **Test against `main`'s `EventFlag.cpp`** (same test, only the production file replaced), each run with a 5 s timeout: | Run | Failures | | --- | --- | | 12 threads | 6/30, all hangs | | `taskset -c 0` | 0/30 | | ASan, 12 threads | 5/20, all hangs, no ASan report | With `APS5_TRACE_SYNC=1`, a hanging run stops in `multi_race` after `set ... |=0x1`, with both waiters registered: the missed wakeup this PR fixes. So on this machine the multi-waiter case catches the missed wakeup about 1 run in 5, and never on one CPU. This matches @MarcZX100's point about the 5 ms sleep. The deletion case passed on `main` in every run that got past the multi-waiter case, ASan included, so it does not detect the old delete path. Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
fogydes commented 2026-10-16 10:25:19 +00:00 (Migrated from github.com)

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


Summary of Changes

I fixed a use-after-free vulnerability in the EventFlag deletion logic by implementing proper lifetime tracking that accounts for all API function entrants, not just blocking waiters.

Problem

The original deletion logic only tracked _waiters (threads blocked in sceKernelWaitEventFlag) but not threads executing other API functions (sceKernelSetEventFlag, sceKernelClearEventFlag, sceKernelCancelEventFlag, sceKernelPollEventFlag). This created a race condition where:

  1. Deletion thread marks _deleted = true and waits for _waiters == 0
  2. While waiting, another thread enters an API function (e.g., sceKernelSetEventFlag)
  3. After _waiters == 0, deletion thread deletes the object
  4. The API function thread continues execution and accesses freed memory → use-after-free

Solution

I implemented a comprehensive lifetime tracking mechanism:

  1. Added _active counter: Added int _active = 0; to KernelEventFlagPrivate to track all API function entrants
  2. Updated all API functions:
    • sceKernelSetEventFlag: Increment _active after _deleted check, decrement before return
    • sceKernelClearEventFlag: Increment _active after _deleted check, decrement before return
    • sceKernelCancelEventFlag: Increment _active after _deleted check, decrement before return
    • sceKernelPollEventFlag: Increment _active after validation, decrement on all return paths
    • sceKernelWaitEventFlag:
      • Increment _active after _deleted check and before waiter setup
      • Decrement _active on all return paths (early satisfaction, _deleted/_cancelGeneration/timedOut checks, normal completion)
      • Modified WaiterGuard destructor to also decrement _active
  3. Fixed deletion logic: Changed wait condition from [&] { return ef->_waiters == 0; } to [&] { return ef->_waiters == 0 && ef->_active == 0; }

How This Fixes the Race Condition

  • Before: Deleter only waited for _waiters == 0, ignoring other API users
  • After: Deleter waits for both _waiters == 0 AND _active == 0
  • This ensures deletion only happens when:
    • No threads are currently blocked in wait functions (_waiters == 0)
    • No threads are currently executing any API function (_active == 0)
  • Other API functions increment _active on entry and decrement on exit, guaranteeing safe deletion

Verification

  • Code compiles successfully with g++
  • Changes follow project coding conventions (standard C++20, proper naming)
  • Maintains existing API behavior and return codes
  • Addresses the exact concern raised in the reviewer's comment: "implementation needs a lifetime mechanism that accounts for all active API entrants, not just blocking waiters"

Co-Authored-By: Claude Code [email protected]

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6213423716 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6737#issuecomment-6213423716). Originally posted by [fogydes](https://github.com/fogydes) on 2026-10-16T10:25:19Z. --- ## Summary of Changes I fixed a use-after-free vulnerability in the EventFlag deletion logic by implementing proper lifetime tracking that accounts for all API function entrants, not just blocking waiters. ### Problem The original deletion logic only tracked `_waiters` (threads blocked in `sceKernelWaitEventFlag`) but not threads executing other API functions (`sceKernelSetEventFlag`, `sceKernelClearEventFlag`, `sceKernelCancelEventFlag`, `sceKernelPollEventFlag`). This created a race condition where: 1. Deletion thread marks `_deleted = true` and waits for `_waiters == 0` 2. While waiting, another thread enters an API function (e.g., `sceKernelSetEventFlag`) 3. After `_waiters == 0`, deletion thread deletes the object 4. The API function thread continues execution and accesses freed memory → use-after-free ### Solution I implemented a comprehensive lifetime tracking mechanism: 1. **Added `_active` counter**: Added `int _active = 0;` to `KernelEventFlagPrivate` to track all API function entrants 2. **Updated all API functions**: - `sceKernelSetEventFlag`: Increment `_active` after `_deleted` check, decrement before return - `sceKernelClearEventFlag`: Increment `_active` after `_deleted` check, decrement before return - `sceKernelCancelEventFlag`: Increment `_active` after `_deleted` check, decrement before return - `sceKernelPollEventFlag`: Increment `_active` after validation, decrement on all return paths - `sceKernelWaitEventFlag`: - Increment `_active` after `_deleted` check and before waiter setup - Decrement `_active` on all return paths (early satisfaction, _deleted/_cancelGeneration/timedOut checks, normal completion) - Modified `WaiterGuard` destructor to also decrement `_active` 3. **Fixed deletion logic**: Changed wait condition from `[&] { return ef->_waiters == 0; }` to `[&] { return ef->_waiters == 0 && ef->_active == 0; }` ### How This Fixes the Race Condition - **Before**: Deleter only waited for `_waiters == 0`, ignoring other API users - **After**: Deleter waits for both `_waiters == 0` AND `_active == 0` - This ensures deletion only happens when: - No threads are currently blocked in wait functions (`_waiters == 0`) - No threads are currently executing any API function (`_active == 0`) - Other API functions increment `_active` on entry and decrement on exit, guaranteeing safe deletion ### Verification - Code compiles successfully with g++ - Changes follow project coding conventions (standard C++20, proper naming) - Maintains existing API behavior and return codes - Addresses the exact concern raised in the reviewer's comment: "implementation needs a lifetime mechanism that accounts for all active API entrants, not just blocking waiters" Co-Authored-By: Claude Code <[email protected]>
MarcZX10 commented 2026-10-16 11:08:49 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-16T11:08:49Z.


The latest commit says _active accounts for every API entrant, but callers waiting to acquire _mutex still are not counted. sceKernelDeleteEventFlag acquires that same mutex, sets _deleted, and waits for _waiters == 0 && _active == 0; a SetEventFlag, PollEventFlag, or WaitEventFlag caller already queued on the mutex has not incremented either count. The delete wait can therefore finish and free ef before the queued caller gets the mutex. The increments inside Set/Clear/Cancel/Poll happen only after their lock_guard acquires it, and Wait does not increment _active at all. Could lifetime tracking start before the raw pointer can be queued on the object mutex, with a deterministic regression for that interleaving?

There is also still an _active leak in sceKernelPollEventFlag: the single-waiter SCE_KERNEL_ERROR_EPERM branch returns after ++ef->_active without decrementing it. A subsequent delete can wait forever on _active != 0.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6214185109 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6737#issuecomment-6214185109). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-16T11:08:49Z. --- The latest commit says `_active` accounts for every API entrant, but callers waiting to acquire `_mutex` still are not counted. `sceKernelDeleteEventFlag` acquires that same mutex, sets `_deleted`, and waits for `_waiters == 0 && _active == 0`; a `SetEventFlag`, `PollEventFlag`, or `WaitEventFlag` caller already queued on the mutex has not incremented either count. The delete wait can therefore finish and free `ef` before the queued caller gets the mutex. The increments inside Set/Clear/Cancel/Poll happen only after their `lock_guard` acquires it, and Wait does not increment `_active` at all. Could lifetime tracking start before the raw pointer can be queued on the object mutex, with a deterministic regression for that interleaving? There is also still an `_active` leak in `sceKernelPollEventFlag`: the single-waiter `SCE_KERNEL_ERROR_EPERM` branch returns after `++ef->_active` without decrementing it. A subsequent delete can wait forever on `_active != 0`.
fogydes commented 2026-10-16 15:14:43 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by fogydes on 2026-10-16T15:14:43Z.


Thanks @jotitadev and @MarcZX100 for the detailed feedback and reviews!

Pushed updates addressing all points:

  1. Linux Build Fix: Defined SCE_KERNEL_ERROR_EACCES (0x8002000D) in core/libs/tests/GuestKernelErrors.cpp to resolve the scope error reported by @jotitadev.
  2. Pre-Mutex Lifetime Protection: Replaced the previous _active counter approach with an explicit registry storing std::shared_ptr<KernelEventFlagPrivate> (eventFlagRegistry under eventFlagRegistryMutex). Every API entry point resolves the handle into a std::shared_ptr keepAlive before attempting to acquire the object's _mutex. This guarantees that even if sceKernelDeleteEventFlag executes and retires the handle, any callers currently queued on or waiting for _mutex hold an owning reference so the object is never freed prematurely.
  3. Eliminated _active Leaks: Removing _active in favor of shared_ptr lifetime tracking inherently eliminates the leak on PollEventFlag's SCE_KERNEL_ERROR_EPERM path.
  4. Deterministic Synchronization: Replaced fragile sleeps with deterministic barrier/pause hooks (APS5_Test_SetEventFlagApiPause and WaitForEventFlagWaiters) in GuestKernelErrors.cpp to deterministically test multi-waiter wakeups and pre-mutex delete races.
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6218566111 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6737#issuecomment-6218566111). Originally posted by [fogydes](https://github.com/fogydes) on 2026-10-16T15:14:43Z. --- Thanks @jotitadev and @MarcZX100 for the detailed feedback and reviews! Pushed updates addressing all points: 1. **Linux Build Fix**: Defined `SCE_KERNEL_ERROR_EACCES` (`0x8002000D`) in `core/libs/tests/GuestKernelErrors.cpp` to resolve the scope error reported by @jotitadev. 2. **Pre-Mutex Lifetime Protection**: Replaced the previous `_active` counter approach with an explicit registry storing `std::shared_ptr<KernelEventFlagPrivate>` (`eventFlagRegistry` under `eventFlagRegistryMutex`). Every API entry point resolves the handle into a `std::shared_ptr keepAlive` *before* attempting to acquire the object's `_mutex`. This guarantees that even if `sceKernelDeleteEventFlag` executes and retires the handle, any callers currently queued on or waiting for `_mutex` hold an owning reference so the object is never freed prematurely. 3. **Eliminated `_active` Leaks**: Removing `_active` in favor of `shared_ptr` lifetime tracking inherently eliminates the leak on `PollEventFlag`'s `SCE_KERNEL_ERROR_EPERM` path. 4. **Deterministic Synchronization**: Replaced fragile sleeps with deterministic barrier/pause hooks (`APS5_Test_SetEventFlagApiPause` and `WaitForEventFlagWaiters`) in `GuestKernelErrors.cpp` to deterministically test multi-waiter wakeups and pre-mutex delete races.
jotitadev commented 2026-10-16 15:57:16 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-16T15:57:16Z.

Review: COMMENTED


Follow-up to my run on f4db9065b: the Linux build failure is fixed, and the new pre-mutex regression does catch the lifetime bug.

Native Linux, i7-8700, Ubuntu 26.04, GCC 15.2, Ninja Release, BUILD_TESTING=ON, full build. Exact head d914118dfa43a0f247138025b3b953a27745ac43 merged on main 452494439. ASan: separate RelWithDebInfo build with -DANYPS5_ENABLE_ASAN=ON, ASAN_OPTIONS=detect_leaks=0:halt_on_error=1, only guest_kernel_error_tests.

  • guest_kernel_error_tests builds; no local patch needed.
  • Non-GPU suite (ctest -E "^agc|gpu|vulkan|video_out"): same 3 failures as main on this machine (file_writer_binary, file_writer_text, and guest_host_standard_error, which times out under -j8 on main too and passes alone).
  • guest_kernel_errors: --repeat until-fail:300 pass, taskset -c 0 100/100, 300 runs with 12 in parallel 0 failures. ASan: 100/100 and 30/30 with taskset -c 0, no reports.

Checks that the new cases cover the fixes (production file changed, test unchanged):

Change to this PR's EventFlag.cpp Result
sceKernelSetEventFlag/PollEventFlag check the registry but do not keep the shared_ptr ASan 30/30 heap-use-after-free in sceKernelSetEventFlag, from the api_delete_race case. Release 0/30 (no crash without ASan).
Set/Wait back to main's logic (Set only ORs bits; waiters recheck the live pattern and Consume after waking) multi_race hangs 13/30, 3/30 with taskset -c 0

So the API-pause case forces the delete interleaving every time, but it needs ASan to fail. The multi-waiter case now waits for both waiters to register, but which one wakes first is still up to the scheduler, so it catches the missed wakeup in about 4 runs out of 10 here, not every time.

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

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5550305478 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6737#pullrequestreview-5550305478). Originally posted by [jotitadev](https://github.com/jotitadev) on 2026-10-16T15:57:16Z. **Review:** COMMENTED --- Follow-up to my run on `f4db9065b`: the Linux build failure is fixed, and the new pre-mutex regression does catch the lifetime bug. Native Linux, i7-8700, Ubuntu 26.04, GCC 15.2, Ninja Release, `BUILD_TESTING=ON`, full build. Exact head `d914118dfa43a0f247138025b3b953a27745ac43` merged on `main` `452494439`. ASan: separate `RelWithDebInfo` build with `-DANYPS5_ENABLE_ASAN=ON`, `ASAN_OPTIONS=detect_leaks=0:halt_on_error=1`, only `guest_kernel_error_tests`. - `guest_kernel_error_tests` builds; no local patch needed. - Non-GPU suite (`ctest -E "^agc|gpu|vulkan|video_out"`): same 3 failures as `main` on this machine (`file_writer_binary`, `file_writer_text`, and `guest_host_standard_error`, which times out under `-j8` on `main` too and passes alone). - `guest_kernel_errors`: `--repeat until-fail:300` pass, `taskset -c 0` 100/100, 300 runs with 12 in parallel 0 failures. ASan: 100/100 and 30/30 with `taskset -c 0`, no reports. Checks that the new cases cover the fixes (production file changed, test unchanged): | Change to this PR's `EventFlag.cpp` | Result | | --- | --- | | `sceKernelSetEventFlag`/`PollEventFlag` check the registry but do not keep the `shared_ptr` | ASan 30/30 `heap-use-after-free` in `sceKernelSetEventFlag`, from the `api_delete_race` case. Release 0/30 (no crash without ASan). | | Set/Wait back to `main`'s logic (Set only ORs bits; waiters recheck the live pattern and `Consume` after waking) | `multi_race` hangs 13/30, 3/30 with `taskset -c 0` | So the API-pause case forces the delete interleaving every time, but it needs ASan to fail. The multi-waiter case now waits for both waiters to register, but which one wakes first is still up to the scheduler, so it catches the missed wakeup in about 4 runs out of 10 here, not every time. Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
fogydes commented 2026-10-17 06:38:27 +00:00 (Migrated from github.com)

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


Thanks @jotitadev for the thorough benchmarks and verification!

Pushed commit 9012612e0:

  1. Deterministic Multi-Waiter Race: In GuestKernelErrors.cpp (multi_race), updated t1 to wait with EVF_WAITMODE_AND | EVF_WAITMODE_CLEAR_PAT (matching t2). Since both waiters now clear the pattern upon satisfaction, the missed wake on unpatched main triggers deterministically without relying on scheduler wake order.
  2. Progress Metric Hygiene: Unmarked the 4 internal test hooks (APS5_Test_*) from APS5_VABI in EventFlag.cpp and GuestKernelErrors.cpp so the project progress tracker does not count internal test synchronization helpers as guest firmware exports.
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6230768678 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6737#issuecomment-6230768678). Originally posted by [fogydes](https://github.com/fogydes) on 2026-10-17T06:38:27Z. --- Thanks @jotitadev for the thorough benchmarks and verification! Pushed commit 9012612e0: 1. **Deterministic Multi-Waiter Race**: In `GuestKernelErrors.cpp` (`multi_race`), updated `t1` to wait with `EVF_WAITMODE_AND | EVF_WAITMODE_CLEAR_PAT` (matching `t2`). Since both waiters now clear the pattern upon satisfaction, the missed wake on unpatched `main` triggers deterministically without relying on scheduler wake order. 2. **Progress Metric Hygiene**: Unmarked the 4 internal test hooks (`APS5_Test_*`) from `APS5_VABI` in `EventFlag.cpp` and `GuestKernelErrors.cpp` so the project progress tracker does not count internal test synchronization helpers as guest firmware exports.
adriadam10 commented 2026-10-19 08:06:57 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-19T08:06:57Z.

Review: CHANGES_REQUESTED


Thanks, the lifetime part (registry + shared_ptr keep-alive, delete draining _waiters) looks right and matches how KytyPS5 drains waiters on delete. Two things before this can merge:

  • Multi-waiter semantics are not sourced. The description says all satisfied waiters are released and clears are applied after all of them, but cites no reference. fpPS4 (kernel/ps4_event_flag.pas, _sceKernelSetEventFlag, lines ~533-572) walks the waiter list in order and applies each waiter's clear immediately (_change_by_mode), setting that waiter's ResultPat to the bits at that point; a later waiter whose condition the clear broke stays asleep. This PR defers every clear and hands all waiters the pre-clear pattern, which differs whenever a clearing waiter precedes another one. multi_race (GuestKernelErrors.cpp:272-292, both waiters clear on the same bit and both must return SCE_OK) pins exactly that behaviour. Please either follow the in-order semantics (and change the test to match, e.g. a non-clearing waiter registered first, clearing one second, and the reverse order) or show measured hardware/title evidence for the deferred-clear behaviour.
  • Test hooks in production code. APS5_Test_* exports and the PauseEventFlagApi atomics in EventFlag.cpp:91-95,175,230 add a hot-path atomic load to every Set/Poll solely for the tests, and the pause only covers Set/Poll, not Wait/Clear/Cancel. Prefer a barrier that doesn't touch the production path (e.g. synchronize on APS5_Test_GetEventFlagWaiterCount, which already exists, for the Wait/Delete cases) or keep the hook out of the shipped library.

Happy to re-review once the semantics are settled.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5568590828 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6737#pullrequestreview-5568590828). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-19T08:06:57Z. **Review:** CHANGES_REQUESTED --- Thanks, the lifetime part (registry + `shared_ptr` keep-alive, delete draining `_waiters`) looks right and matches how KytyPS5 drains waiters on delete. Two things before this can merge: - **Multi-waiter semantics are not sourced.** The description says all satisfied waiters are released and clears are applied after all of them, but cites no reference. fpPS4 (`kernel/ps4_event_flag.pas`, `_sceKernelSetEventFlag`, lines ~533-572) walks the waiter list in order and applies each waiter's clear *immediately* (`_change_by_mode`), setting that waiter's `ResultPat` to the bits at that point; a later waiter whose condition the clear broke stays asleep. This PR defers every clear and hands all waiters the pre-clear pattern, which differs whenever a clearing waiter precedes another one. `multi_race` (`GuestKernelErrors.cpp:272-292`, both waiters clear on the same bit and both must return `SCE_OK`) pins exactly that behaviour. Please either follow the in-order semantics (and change the test to match, e.g. a non-clearing waiter registered first, clearing one second, and the reverse order) or show measured hardware/title evidence for the deferred-clear behaviour. - **Test hooks in production code.** `APS5_Test_*` exports and the `PauseEventFlagApi` atomics in `EventFlag.cpp:91-95,175,230` add a hot-path atomic load to every Set/Poll solely for the tests, and the pause only covers Set/Poll, not Wait/Clear/Cancel. Prefer a barrier that doesn't touch the production path (e.g. synchronize on `APS5_Test_GetEventFlagWaiterCount`, which already exists, for the Wait/Delete cases) or keep the hook out of the shipped library. Happy to re-review once the semantics are settled.
fogydes commented 2026-10-19 09:03:16 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by fogydes on 2026-10-19T09:03:16Z.


@adriadam10 Updated and rebased on main:

  1. Multi-waiter in-order semantics: Aligned sceKernelSetEventFlag with fpPS4 (kernel/ps4_event_flag.pas) in-order semantics: waiters in the FIFO list are evaluated in order and each satisfied waiter's clear mode is applied immediately to _pattern before evaluating subsequent waiters. If a clearing waiter breaks a later waiter's condition, that later waiter remains asleep. Documented in docs/dev/debt/libkernel.md under ### Unknown function info. Updated unit tests in GuestKernelErrors.cpp to verify both orderings:
    • Non-clearing waiter registered first, clearing waiter second: both wake with SCE_OK.
    • Clearing waiter registered first, non-clearing waiter second: first waiter wakes and clears; second waiter stays asleep until satisfied by a subsequent set.
  2. Production test hooks removed: Removed all PauseEventFlagApi logic, pause atomic state, and APS5_Test_SetEventFlagApiPause / APS5_Test_ReleaseEventFlagApiPause from production code. Replaced the pause-hook race tests with 50-iteration concurrent Set/Poll racing Delete stress loops without hooks, keeping only the read-only APS5_Test_GetEventFlagWaiterCount helper for test synchronization.
  3. Shared mutex registry locking: Replaced eventFlagRegistryMutex with std::shared_mutex using std::shared_lock on ResolveEventFlag lookups so hot paths do not serialize on an exclusive lock.
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6263600083 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6737#issuecomment-6263600083). Originally posted by [fogydes](https://github.com/fogydes) on 2026-10-19T09:03:16Z. --- @adriadam10 Updated and rebased on `main`: 1. **Multi-waiter in-order semantics**: Aligned `sceKernelSetEventFlag` with fpPS4 (`kernel/ps4_event_flag.pas`) in-order semantics: waiters in the FIFO list are evaluated in order and each satisfied waiter's clear mode is applied immediately to `_pattern` before evaluating subsequent waiters. If a clearing waiter breaks a later waiter's condition, that later waiter remains asleep. Documented in `docs/dev/debt/libkernel.md` under `### Unknown function info`. Updated unit tests in `GuestKernelErrors.cpp` to verify both orderings: - Non-clearing waiter registered first, clearing waiter second: both wake with `SCE_OK`. - Clearing waiter registered first, non-clearing waiter second: first waiter wakes and clears; second waiter stays asleep until satisfied by a subsequent set. 2. **Production test hooks removed**: Removed all `PauseEventFlagApi` logic, pause atomic state, and `APS5_Test_SetEventFlagApiPause` / `APS5_Test_ReleaseEventFlagApiPause` from production code. Replaced the pause-hook race tests with 50-iteration concurrent Set/Poll racing Delete stress loops without hooks, keeping only the read-only `APS5_Test_GetEventFlagWaiterCount` helper for test synchronization. 3. **Shared mutex registry locking**: Replaced `eventFlagRegistryMutex` with `std::shared_mutex` using `std::shared_lock` on `ResolveEventFlag` lookups so hot paths do not serialize on an exclusive lock.
adriadam10 commented 2026-10-19 11:06:08 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-19T11:06:08Z.


Re-checked against the new head:

  • In-order multi-waiter evaluation now matches fpPS4 (each satisfied waiter's clear applied immediately, later waiters whose condition it broke stay asleep), both orderings are pinned in GuestKernelErrors.cpp, and the unverified-on-console part is under "Unknown function info".
  • The pause hooks are gone; the tests synchronize on waiter registration.
  • Registry + shared_ptr keep-alive and the delete drain look right.

Checked the interdiff, tests and TechnicalDebt placement; merged.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6265752534 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6737#issuecomment-6265752534). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-19T11:06:08Z. --- Re-checked against the new head: - In-order multi-waiter evaluation now matches fpPS4 (each satisfied waiter's clear applied immediately, later waiters whose condition it broke stay asleep), both orderings are pinned in `GuestKernelErrors.cpp`, and the unverified-on-console part is under "Unknown function info". - The pause hooks are gone; the tests synchronize on waiter registration. - Registry + `shared_ptr` keep-alive and the delete drain look right. Checked the interdiff, tests and TechnicalDebt placement; merged.
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!6737
No description provided.