fix(libkernel): return ESRCH for deleted semaphore handles #10558
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/10558"
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 ZSWolt on 2026-10-24T09:49:37Z.
What
sceKernelDeleteSemafreed the semaphore object, which is also the handle the title holds. Every later call through that handle read freed memory:sceKernelPollSema,sceKernelSignalSema,sceKernelWaitSema,sceKernelCancelSemaand a secondsceKernelDeleteSema. A delete on one thread while another thread was still inside a call could also free the object under that call.The console returns
0x80020003(ESRCH) for a poll, a signal and a second delete of a deleted semaphore. This was measured in prosper's console oracle and is already cited indocs/dev/debt/libkernel.md.Live semaphores are now kept in a table of
shared_ptrs keyed by their handle:sceKernelCreateSemaadds the new semaphore under a handle taken from a counter that starts at 1 and is never reused, not under the object's address, so a stale handle can't reach a later semaphore.sceKernelDeleteSemaremoves it before waking the waiters.The existing behavior for waiters that are woken by a delete (
EACCES) is unchanged.APS5_TRACE_SYNClines now print the handle insignalandwaittoo, ascreatealready did, so they still match.SemaphoreTrace.cppused to read the object's fields through the handle; it now gets the object fromKernelSemaObjectForTests_nid_no_patch, which follows the*ForTests_nid_no_patchhelper naming already used in libSceNet and is not exported as a NID.The debt entry now records what is still different:
Tested
BUILD_TESTING=ON.guest_semaphore:Semaphore.cppthe test fails: it hangs until ctest's timeout after the first use of a deleted handle. With this change it passes.guest_semaphoreandguest_semaphore_tracepassed 30 consecutive runs.ctest: 2028/2029. The one failure,agc_driver_multisample_retirement("MSAA storage promotion did not retain its source image"), fails the same way with main'sSemaphore.cpp. It's a WSL environment issue: there's no/dev/udmabuf, so the shared direct memory path is copied.tools/check_conventions.py: all checks passed.Semaphore.cpp,Semaphore.hppand the libkernel debt file, and its patch touches the opening lines ofsceKernelSignalSema,sceKernelWaitSemaandsceKernelCancelSema. Whichever lands second will need a small textual rebase: this PR adds the handle lookup at the top of each call, and #9491 changes their bodies. #6044 only movesGuestSemaphore.cpp.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-24T10:29:16Z.
Review: CHANGES_REQUESTED
The old-handle reuse case in the debt entry is a correctness gap for the behavior this PR is fixing.
liveSemasis keyed byKernelSemaPrivate*, andsceKernelCreateSemareturnscreated.get(). After A is deleted and freed, the allocator may reuse that address for B; a call using stale handle A then finds B and can poll/signal/delete the wrong semaphore instead of returning ESRCH. This is possible with the current ownership model, not just an unknown console edge case. Please use a non-reused public handle (for example, a monotonic opaque token mapped to the shared object) and add a regression that deletes A, creates B, then verifies all operations through A still return ESRCH while B remains usable. The current debt note accurately describes the mismatch but does not prevent it.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-24T11:04:49Z.
Review: APPROVED
Thanks for addressing the stale-handle reuse case. I reviewed exact head
6597963c94e74f3862cd24d4f0653acf49a7b35c: handles now come from a monotonic counter and map to shared semaphore objects; all API operations acquire a shared reference through the lookup, while delete removes the mapping before marking the object deleted and waking waiters. The 64-round create/delete/recreate regression exercises every operation through the stale handle and verifies the new semaphore remains usable; the race test covers concurrent poll/signal and deletion. The latest hosted conventions, eligibility, labels, and report checks pass, but product build jobs are skipped. I could not run the focused C++ test locally because this checkout lacks the SDL2 development package required by full-project CMake configuration; the contributor reports the focused tests and repeated runs passing. The remaining limitations are documented in the PR.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-24T11:29:02Z.
Review: CHANGES_REQUESTED
The stale-handle fix and regression coverage address the prior correctness issue, and the existing approval reflects that code review. I am reopening the merge-coordination item from the overlap report: #9491 is still open and changes the bodies of
sceKernelSignalSema,sceKernelWaitSema, andsceKernelCancelSema, which this PR also changes to add handle lookup and shared ownership. The PR description acknowledges that whichever lands second needs a rebase, but the checklist still saysDepends on: none; please agree on integration order with #9491’s author and declare any dependency or explicit coordination. #6044 also renamesGuestSemaphore.cpptocore/libs/tests/threads/GuestSemaphore.cpp, so coordinate that test-file move as well. I checked #8725’s debt patch: it concerns SyncOnAddress text and does not overlap the semaphore entry’s behavior. The author reports repeated focused tests and a full suite with one unrelated WSL Vulkan failure; hosted product builds are skipped.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-24T11:54:12Z.
Review: CHANGES_REQUESTED
The stale-handle implementation and regression remain approved on their merits, and #9491 has now agreed to merge this PR first and list it as a dependency. One merge-coordination item remains: #6044 moves GuestSemaphore.cpp to core/libs/tests/threads/GuestSemaphore.cpp. Please confirm the proposed order with #6044’s author (or arrange for the move to carry these assertions) and keep the rebase/integration expectation explicit. This request is limited to preserving the test edit across that rename.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-24T16:33:34Z.
Review: APPROVED
Re-reviewed exact head
6597963c94. The remaining integration item is resolved: #6044 is closed without merging, and the #9491 author explicitly agreed that this PR lands first and #9491 rebases on it; the checklist records that order. The implementation and regression coverage are unchanged from my prior approval, including stale-handle rejection across poll, signal, wait, cancel and delete, address-reuse rounds, and the concurrent delete race. Hosted conventions, eligibility, labels and report pass; product/platform jobs are skipped by path selection. Restoring approval for this exact head.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-01T14:26:52Z.
Review: COMMENTED
Reviewed — no blocking findings
Handing out a monotonic handle and keeping the semaphore alive in a shared table lets a delete wait for in-flight waiters without freeing memory they still use, and the new test pins the ESRCH answers for deleted handles that the PR describes; the console's answers themselves are not checkable here.
What I ran
1aec488dda13e72898fd5fa25515b4f0fd2f0788, baseb415263451(the precheck base)./usr/bin/python33.11.2, no build.python3 tools/pr_precheck.py --repo boykopovar/AnyPS5 --pr 10558 --output-dir /dev/shm/reviewer-run/precheck/10558python3 tools/pr_abi_audit.py --repo /marc/AnyPS5 --base b415263451 --head 1aec488dda13e72898fd5fa25515b4f0fd2f0788 --json(exit 0;passed; 0 findings; 6 symbols).core/libs/tests/GuestSemaphore.cppfrom a head extract: one literal-path registration heuristic.Semaphore.cpp(the handle table,FindSema,sceKernelCreateSema,sceKernelDeleteSema, and the wait path that holds ashared_ptrcopy) and the test'sRequireDeletedHandlesandRequireInvalidArguments(lines 26-67).Results
Precheck report, checks table, unedited (
/dev/shm/reviewer-run/precheck/10558/report.md):The precheck deliberately does not configure, build, or compile AnyPS5.git diff --check b41526345185943c53af0c6eee97863df4389c9e...1aec488dda13e72898fd5fa25515b4f0fd2f0788/usr/bin/python3 tools/check_conventions.py --base b41526345185943c53af0c6eee97863df4389c9e --head 1aec488dda13e72898fd5fa25515b4f0fd2f0788 --title fix(libkernel): return ESRCH for deleted semaphore handles --body /dev/shm/reviewer-run/precheck/10558/pr-body.md/usr/bin/python3 tools/pr_abi_audit.py --base b41526345185943c53af0c6eee97863df4389c9e --head 1aec488dda13e72898fd5fa25515b4f0fd2f0788 --jsonNo changed Python implementation files.No changed tools/ module has an existing sibling tools/tests/test_<module>.py suite.No changed test_*.py files./usr/bin/python3 /marc/AnyPS5/tools/pr_stack_check.py 10558 --repo boykopovar/AnyPS5 --output-dir /dev/shm/reviewer-run/precheck/10558/stackNot run: C++ tests need exact-head binaries, which require a build; the precheck does not build./usr/bin/python3 /dev/shm/reviewer-run/precheck/10558/head-1aec488dda13-5061b18b/tools/pr_test_quality.py --root /dev/shm/reviewer-run/precheck/10558/head-1aec488dda13-5061b18b --json core/libs/prx/libkernel/Semaphore/include/Semaphore.hpp core/libs/prx/libkernel/Semaphore/src/Semaphore.cpp core/libs/tests/GuestSemaphore.cpp core/libs/tests/SemaphoreTrace.cpp docs/dev/debt/libkernel.mdNo changed Python test module in tools/ can be run as a no-build base-source control.Negative control
Not run here. The PR's test is C++ and needs a build; the handle-table change is the code under test.
Findings
Blocking: none.
Non-blocking:
KernelSemaObjectForTests_nid_no_patchis declared in the publicSemaphore.hppinsideextern "C", so it becomes part of the library's exported surface. If the repository keeps test hooks out of exports, it should move to a test-only translation unit.Sources
github.com/boykopovar/AnyPS5@1aec488dda/core/libs/prx/libkernel/Semaphore/src/Semaphore.cppgithub.com/boykopovar/AnyPS5@1aec488dda/core/libs/tests/GuestSemaphore.cpp (L26-L67)Not verified
guest_semaphorewas not built or run here.windows,conventions,eligibility,labels,library-portabilityandreportsucceeded;linux,register-context,relinker,relinker-asanandwrite-watchwere skipped.Imported from boykopovar/AnyPS5. Originally posted by ahmadmuj on 2026-11-06T06:57:28Z.
Review: APPROVED
Checked head
16fbff468227a648d732ab19f92fadd8750c1773, PR base9f9e4207099c61409f4f9df27f90823eb9aabc22. The three focused semaphore tests pass on this head and current mainbbd85f7ebfd41433598b4573eaae53df19dc059aon Linux.I also ran an isolated probe linked to the actual libkernel/libc modules: 32 FIFO and 32 priority rounds, each with four guest waiters with distinct priorities and token needs. Each round confirms the complete queue under its mutex before deletion, then drops the test pointer. Delete returns 0; all waiters return EACCES. After joining, stale poll/signal/delete return ESRCH, and a distinct replacement handle retains exactly its initial tokens.
The probe and focused tests also pass with ASan+UBSan, with no sanitizer errors. Waits are finite and the probe has a 25-second external timeout. The shared ownership and waiter cleanup look good to me.
This checks the implementation's deletion contract, not new console measurements. It does not replace the requested NVIDIA run.
Imported from boykopovar/AnyPS5. Originally posted by ahmadmuj on 2026-11-06T09:17:45Z.
Review: COMMENTED
Tested head
16fbff468227a648d732ab19f92fadd8750c1773against maine509b292479c383dabd18bf5c323eff1afe9d2f3on native Windows, RTX 4080, NVIDIA 617.42, Vulkan 1.4.351. These are separate exact snapshots, not a merge build.Both Release builds pass the same six Vulkan execution tests:
agc_driver_pattern_buffer_fill,agc_driver_stream_copy,agc_driver_buffer_integer_atomics,agc_driver_f16_to_f32_unpack,agc_driver_image_store_sint, andagc_driver_zero_position_vertex. All 12 runs pass without skips. Their exact readback assertions and printed result values match; half conversion covers all 65,536 patterns with both decodes.Each process confirms the NVIDIA device and loaded Khronos validation DLL (1.4.367).
ANYPS5_REQUIRE_VULKAN=1andANYPS5_NO_SHADER_CACHE=1are set. Both sides report zero VUIDs and no validation errors. The same implicit OBS/NVIDIA layers are present on both sides.This adds a bounded NVIDIA compatibility check to my earlier semaphore review. It does not cover the full GPU suite, games, console behavior, or a main/head integration build. I leave the broader NVIDIA gate to the maintainers.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-16T12:48:35Z.
Review: CHANGES_REQUESTED
Reviewed — changes requested
Changes are required before merge: make the semaphore test accessor retain the semaphore while its fields are inspected, so concurrent deletion cannot invalidate the returned pointer.
What I ran
Reviewed head
05c9e9c513633d8aa9ec68c80e76dbb77e0258c6. No build, test, or other programmatic check was run in this review.Results
Findings
Blocking
core/libs/prx/libkernel/Semaphore/src/Semaphore.cpp:39-40:FindSema(handle)returns a temporaryshared_ptr, and.get()leaves the caller with a raw pointer after that owner is destroyed. If a concurrent delete removes the registry entry, the object can be freed while the tests read its mutex and fields. This affects the new accessor callers inGuestSemaphoreHandoff.cppandSemaphoreTrace.cpp. Return ashared_ptrto the test callers, or provide a helper that reads the required state while retaining ownership.Non-blocking
None.
Not verified
No commands or tests were run. The PR description reports
guest_semaphoreandguest_semaphore_tracepassed 30 consecutive runs, and fullctestpassed 2028/2029 with one reported environment-related failure; these results were not independently verified. All six changed files listed in the manifest were read. No changed files were excluded by the manifest.To get this to a good state
Change the test accessor to preserve shared ownership during inspection, then rerun the semaphore tests and relevant checks on the new head.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-17T10:27:49Z.
Review: CHANGES_REQUESTED
Reviewed — changes requested
Changes are required before merge:
WaiterCountincore/libs/tests/GuestSemaphore.cppstill dereferences the semaphore handle as a pointer, and the handle is no longer a pointer.What I ran
3781f83c28150911fa3c3bd39daa5d3f442835f5(basemain). Read the changed hunks in the diff for all six changed files.core/libs/tests/GuestSemaphore.cpplines 141–180 with the repository reader.guest_semaphore,guest_semaphore_traceorctest.Results
*ForTests_nid_no_patchnamingctestFindings
Blocking
core/libs/tests/GuestSemaphore.cpp:141(unchanged by this diff, reached by changed behaviour).WaiterCountlockssem->mutexand readssem->waiterCount, so it treatsKernelSemaas aKernelSemaPrivate*. This PR makes the handle a counter value:core/libs/prx/libkernel/Semaphore/src/Semaphore.cpp:65setshandle = reinterpret_cast<KernelSema>(++lastSemaHandle). The first semaphore gets handle1, soWaiterCountdereferences a small integer.RequireZeroTimeoutcalls it at lines 156, 166, 167 and 170, andmaincallsRequireZeroTimeoutlast. By reading, that is a crash inguest_semaphoreon the first call. The PR saysguest_semaphorepassed 30 consecutive runs. I have not run it, so the author needs to reconcile that claim with this code.Non-blocking
core/libs/prx/libkernel/Semaphore/src/Semaphore.cpp:12:<memory>is now included twice, at lines 10 and 12. Remove the second one.Sources
*ForTests_nid_no_patchnaming matches the existing helpers: SetResolverLookupForTests_nid_no_patch and KsemWaiterCountForTests_nid_no_patch.WaiterCount: GuestSemaphore.cpp lines 141–143.Not verified
guest_semaphore,guest_semaphore_trace, the 30 reported runs, the 50-round race test and the fullctestrun. Only the author reported these.WaiterCountcrash is from reading the code. I did not execute it.KernelSema: the search found only handle pass-throughs in the tests and in libSceNpCommon. I did not read every call site.core/libs/prx/libkernel/Semaphore/include/Semaphore.hpp,core/libs/prx/libkernel/Semaphore/src/Semaphore.cpp,core/libs/tests/GuestSemaphore.cpp,core/libs/tests/GuestSemaphoreHandoff.cpp,core/libs/tests/SemaphoreTrace.cpp,docs/dev/debt/libkernel.md). The head text was read only forcore/libs/tests/GuestSemaphore.cpplines 141–180. Nothing was excluded.To get this to a good state
WaiterCountincore/libs/tests/GuestSemaphore.cppwith the handle-to-object lookup above.guest_semaphore,guest_semaphore_traceandcteston the new head, and post the output.<memory>include (optional).Imported from boykopovar/AnyPS5. Originally posted by lgqdaxia on 2026-11-28T18:05:47Z.
Review: COMMENTED
I checked the test callers at
3781f83c2815and agree with MarcZX10's two findings.WaiterCounttreats a guest semaphore handle as an object address. The handoff and trace helpers look it up in the registry, but drop the owningshared_ptrbefore their last read. A concurrent deletion can leave that read using a stale pointer.We opened a test-only patch against your
fix/libkernel-deleted-sema-esrchbranch. The helpers now look up the opaque handle and hold the registry'sshared_ptruntil they finish reading under the object's mutex. On Windows x64 with MinGW,guest_semaphore,guest_semaphore_handoffandguest_semaphore_traceall passed atb6833166a1e5. ZSWolt/AnyPS5#1Imported from boykopovar/AnyPS5. Originally posted by ligmaSec on 2026-12-03T13:25:16Z.
Review: COMMENTED
Built the focused checks against the existing Linux runtime. The semaphore handoff and tracing fixtures passed. The larger semaphore fixture aborted in this standalone setup. A trial merge against integration main reports a conflict in
Semaphore.cpp.AI-assisted: yes.
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.