fix(libkernel): prevent use-after-free on event flag deletion and multi-waiter race #6737
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/6737"
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:36:52Z.
What
This change addresses two synchronization defects in
EventFlag.cpp:Pre-Mutex Lifetime Protection and Drain in
sceKernelDeleteEventFlag:Previously, if
_waiters != 0,sceKernelDeleteEventFlagflaggedef->_deleted = true, calledef->_changed.NotifyAll(), and immediately returnedSCE_OKwithout waiting. The last waking waiter decremented_waitersto 0, unlocked_mutex, and calleddelete ef;. Furthermore, callers queued to acquire_mutexin other APIs had no lifetime protection, leading to use-after-free upon deletion.Event flags are now tracked in
eventFlagRegistryusingstd::shared_ptr<KernelEventFlagPrivate>guarded bystd::shared_mutex eventFlagRegistryMutex. Every API entry point acquires an owningkeepAlivereference before attempting to acquire the object's_mutex.sceKernelDeleteEventFlagmarks_deleted = true, notifies all waiters, waits for_waiters == 0, and retires the handle from the registry. Waiting threads decrement_waitersand notify the deleter via RAIIWaiterGuard, returningSCE_KERNEL_ERROR_EACCES. Callers holdkeepAlivethroughout execution, guaranteeing no memory corruption or use-after-free occurs.Multi-Waiter In-Order Evaluation Semantics (
sceKernelSetEventFlag):When multiple threads wait on an
EVF_ATTR_MULTIevent flag, waiters are queued in registration order via an intrusive FIFO list.Following fpPS4 (
kernel/ps4_event_flag.pas,_sceKernelSetEventFlag),sceKernelSetEventFlagevaluates 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 indocs/dev/debt/libkernel.mdunder "Unknown function info".Tested
GuestKernelErrors.cpp:SCE_OK).SCE_KERNEL_ERROR_EACCES.python tools/check_conventions.py --base origin/main: passed with 0 warnings.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 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 beforeSetEventFlag/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.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-16T09:12:35Z.
I also have a lifetime question about the delete drain.
_waiterscounts only calls that entered the blocking wait path. IfsceKernelSetEventFlag/PollEventFlagis already blocked acquiring_mutexwhile the deleter is waiting, the last waiter can drop_waitersto zero; the deleter can then reacquire the mutex, observe zero, unlock and deleteefwhile 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.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.
docs/dev/debt/libkernel.mdcore/libs/tests/GuestKernelErrors.cppdocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mdImported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-16T09:46:11Z.
Review: COMMENTED
Native Linux run on exact head
f4db9065b3024b8d3be62c951acf8ac173e247ab, 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.The test does not compile. A full build with
BUILD_TESTING=ONstops at:The test file defines its own error constants (lines 45-54) and EACCES is not one of them. The
build-relinkerrun in the description does not buildguest_kernel_error_tests, so this would not show up there. For the runs below I addedstatic constexpr int SCE_KERNEL_ERROR_EACCES = static_cast<int>(0x8002000D);next to the others.With that line added:
ctest -E "^agc|gpu|vulkan|video_out"): 648/650, same asmain. The twofile_writer_*failures also happen onmainon this machine.guest_kernel_errors: 100/100 normal, 50/50 withtaskset -c 0. ASan: 50/50, and 20/20 withtaskset -c 0, no reports.Test against
main'sEventFlag.cpp(same test, only the production file replaced), each run with a 5 s timeout:taskset -c 0With
APS5_TRACE_SYNC=1, a hanging run stops inmulti_raceafterset ... |=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 onmainin 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.
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 insceKernelWaitEventFlag) but not threads executing other API functions (sceKernelSetEventFlag,sceKernelClearEventFlag,sceKernelCancelEventFlag,sceKernelPollEventFlag). This created a race condition where:_deleted = trueand waits for_waiters == 0sceKernelSetEventFlag)_waiters == 0, deletion thread deletes the objectSolution
I implemented a comprehensive lifetime tracking mechanism:
_activecounter: Addedint _active = 0;toKernelEventFlagPrivateto track all API function entrantssceKernelSetEventFlag: Increment_activeafter_deletedcheck, decrement before returnsceKernelClearEventFlag: Increment_activeafter_deletedcheck, decrement before returnsceKernelCancelEventFlag: Increment_activeafter_deletedcheck, decrement before returnsceKernelPollEventFlag: Increment_activeafter validation, decrement on all return pathssceKernelWaitEventFlag:_activeafter_deletedcheck and before waiter setup_activeon all return paths (early satisfaction, _deleted/_cancelGeneration/timedOut checks, normal completion)WaiterGuarddestructor to also decrement_active[&] { return ef->_waiters == 0; }to[&] { return ef->_waiters == 0 && ef->_active == 0; }How This Fixes the Race Condition
_waiters == 0, ignoring other API users_waiters == 0AND_active == 0_waiters == 0)_active == 0)_activeon entry and decrement on exit, guaranteeing safe deletionVerification
Co-Authored-By: Claude Code [email protected]
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-16T11:08:49Z.
The latest commit says
_activeaccounts for every API entrant, but callers waiting to acquire_mutexstill are not counted.sceKernelDeleteEventFlagacquires that same mutex, sets_deleted, and waits for_waiters == 0 && _active == 0; aSetEventFlag,PollEventFlag, orWaitEventFlagcaller already queued on the mutex has not incremented either count. The delete wait can therefore finish and freeefbefore the queued caller gets the mutex. The increments inside Set/Clear/Cancel/Poll happen only after theirlock_guardacquires it, and Wait does not increment_activeat 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
_activeleak insceKernelPollEventFlag: the single-waiterSCE_KERNEL_ERROR_EPERMbranch returns after++ef->_activewithout decrementing it. A subsequent delete can wait forever on_active != 0.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:
SCE_KERNEL_ERROR_EACCES(0x8002000D) incore/libs/tests/GuestKernelErrors.cppto resolve the scope error reported by @jotitadev._activecounter approach with an explicit registry storingstd::shared_ptr<KernelEventFlagPrivate>(eventFlagRegistryundereventFlagRegistryMutex). Every API entry point resolves the handle into astd::shared_ptr keepAlivebefore attempting to acquire the object's_mutex. This guarantees that even ifsceKernelDeleteEventFlagexecutes and retires the handle, any callers currently queued on or waiting for_mutexhold an owning reference so the object is never freed prematurely._activeLeaks: Removing_activein favor ofshared_ptrlifetime tracking inherently eliminates the leak onPollEventFlag'sSCE_KERNEL_ERROR_EPERMpath.APS5_Test_SetEventFlagApiPauseandWaitForEventFlagWaiters) inGuestKernelErrors.cppto deterministically test multi-waiter wakeups and pre-mutex delete races.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 headd914118dfa43a0f247138025b3b953a27745ac43merged onmain452494439. ASan: separateRelWithDebInfobuild with-DANYPS5_ENABLE_ASAN=ON,ASAN_OPTIONS=detect_leaks=0:halt_on_error=1, onlyguest_kernel_error_tests.guest_kernel_error_testsbuilds; no local patch needed.ctest -E "^agc|gpu|vulkan|video_out"): same 3 failures asmainon this machine (file_writer_binary,file_writer_text, andguest_host_standard_error, which times out under-j8onmaintoo and passes alone).guest_kernel_errors:--repeat until-fail:300pass,taskset -c 0100/100, 300 runs with 12 in parallel 0 failures. ASan: 100/100 and 30/30 withtaskset -c 0, no reports.Checks that the new cases cover the fixes (production file changed, test unchanged):
EventFlag.cppsceKernelSetEventFlag/PollEventFlagcheck the registry but do not keep theshared_ptrheap-use-after-freeinsceKernelSetEventFlag, from theapi_delete_racecase. Release 0/30 (no crash without ASan).main's logic (Set only ORs bits; waiters recheck the live pattern andConsumeafter waking)multi_racehangs 13/30, 3/30 withtaskset -c 0So 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.
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:
GuestKernelErrors.cpp(multi_race), updatedt1to wait withEVF_WAITMODE_AND | EVF_WAITMODE_CLEAR_PAT(matchingt2). Since both waiters now clear the pattern upon satisfaction, the missed wake on unpatchedmaintriggers deterministically without relying on scheduler wake order.APS5_Test_*) fromAPS5_VABIinEventFlag.cppandGuestKernelErrors.cppso the project progress tracker does not count internal test synchronization helpers as guest firmware exports.Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-19T08:06:57Z.
Review: CHANGES_REQUESTED
Thanks, the lifetime part (registry +
shared_ptrkeep-alive, delete draining_waiters) looks right and matches how KytyPS5 drains waiters on delete. Two things before this can merge: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'sResultPatto 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 returnSCE_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.APS5_Test_*exports and thePauseEventFlagApiatomics inEventFlag.cpp:91-95,175,230add 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 onAPS5_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.
Imported from boykopovar/AnyPS5. Originally posted by fogydes on 2026-10-19T09:03:16Z.
@adriadam10 Updated and rebased on
main:sceKernelSetEventFlagwith 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_patternbefore evaluating subsequent waiters. If a clearing waiter breaks a later waiter's condition, that later waiter remains asleep. Documented indocs/dev/debt/libkernel.mdunder### Unknown function info. Updated unit tests inGuestKernelErrors.cppto verify both orderings:SCE_OK.PauseEventFlagApilogic, pause atomic state, andAPS5_Test_SetEventFlagApiPause/APS5_Test_ReleaseEventFlagApiPausefrom production code. Replaced the pause-hook race tests with 50-iteration concurrent Set/Poll racing Delete stress loops without hooks, keeping only the read-onlyAPS5_Test_GetEventFlagWaiterCounthelper for test synchronization.eventFlagRegistryMutexwithstd::shared_mutexusingstd::shared_lockonResolveEventFlaglookups so hot paths do not serialize on an exclusive lock.Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-19T11:06:08Z.
Re-checked against the new head:
GuestKernelErrors.cpp, and the unverified-on-console part is under "Unknown function info".shared_ptrkeep-alive and the delete drain look right.Checked the interdiff, tests and TechnicalDebt placement; merged.