fix(libkernel): return ESRCH for deleted semaphore handles #10558

Open
ZSWolt wants to merge 12 commits from upstream-pr/10558 into main
ZSWolt commented 2026-10-24 09:49:37 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ZSWolt on 2026-10-24T09:49:37Z.


What

sceKernelDeleteSema freed the semaphore object, which is also the handle the title holds. Every later call through that handle read freed memory: sceKernelPollSema, sceKernelSignalSema, sceKernelWaitSema, sceKernelCancelSema and a second sceKernelDeleteSema. 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 in docs/dev/debt/libkernel.md.

Live semaphores are now kept in a table of shared_ptrs keyed by their handle:

  • sceKernelCreateSema adds 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.
  • sceKernelDeleteSema removes it before waking the waiters.
  • Every call looks the handle up first and returns ESRCH when the handle is missing (deleted, never created, or null).
  • The reference a call holds keeps the object alive until it returns, so a concurrent delete no longer frees it under that call.

The existing behavior for waiters that are woken by a delete (EACCES) is unchanged.

APS5_TRACE_SYNC lines now print the handle in signal and wait too, as create already did, so they still match. SemaphoreTrace.cpp used to read the object's fields through the handle; it now gets the object from KernelSemaObjectForTests_nid_no_patch, which follows the *ForTests_nid_no_patch helper naming already used in libSceNet and is not exported as a NID.

The debt entry now records what is still different:

  • Handles are counter values, not the console's IDs.
  • The ESRCH from a wait or a cancel of a deleted semaphore was not measured.

Tested

  • Windows 11 with WSL2, Ubuntu 26.04.1, GCC 15.2.0, Release, BUILD_TESTING=ON.
  • New checks in guest_semaphore:
    • After a delete, poll, signal, a second delete, a timed wait and a cancel return ESRCH, and the wait's timeout and the cancel's thread count are left untouched.
    • A live semaphore still works afterwards.
    • An address that was never a semaphore returns ESRCH.
    • 64 rounds of create A, delete A, create B: B's handle differs from A's, every call through A returns ESRCH with its outputs untouched, and B keeps working. With an address-keyed table this aborts, because the allocator hands A's address to B.
    • 50 rounds of a delete racing a thread that polls and signals the same semaphore.
  • On main's Semaphore.cpp the test fails: it hangs until ctest's timeout after the first use of a deleted handle. With this change it passes. guest_semaphore and guest_semaphore_trace passed 30 consecutive runs.
  • Full 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's Semaphore.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.
  • Overlap: #9491 (queued-waiter handoff) also edits Semaphore.cpp, Semaphore.hpp and the libkernel debt file, and its patch touches the opening lines of sceKernelSignalSema, sceKernelWaitSema and sceKernelCancelSema. 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 moves GuestSemaphore.cpp.

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 (#9491 lands after this one, agreed in #9491; #6044 was closed without merging)
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4994365888 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10558). Originally posted by [ZSWolt](https://github.com/ZSWolt) on 2026-10-24T09:49:37Z. --- ### What `sceKernelDeleteSema` freed the semaphore object, which is also the handle the title holds. Every later call through that handle read freed memory: `sceKernelPollSema`, `sceKernelSignalSema`, `sceKernelWaitSema`, `sceKernelCancelSema` and a second `sceKernelDeleteSema`. 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](https://github.com/mattias800/prosper/blob/3ea5cb9a846b6dcd00f5073360462bbda4f72288/prosper/tests/data/console_oracle/kernel.golden.tsv#L17-L19) and is already cited in `docs/dev/debt/libkernel.md`. Live semaphores are now kept in a table of `shared_ptr`s keyed by their handle: - `sceKernelCreateSema` adds 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. - `sceKernelDeleteSema` removes it before waking the waiters. - Every call looks the handle up first and returns ESRCH when the handle is missing (deleted, never created, or null). - The reference a call holds keeps the object alive until it returns, so a concurrent delete no longer frees it under that call. The existing behavior for waiters that are woken by a delete (`EACCES`) is unchanged. `APS5_TRACE_SYNC` lines now print the handle in `signal` and `wait` too, as `create` already did, so they still match. `SemaphoreTrace.cpp` used to read the object's fields through the handle; it now gets the object from `KernelSemaObjectForTests_nid_no_patch`, which follows the `*ForTests_nid_no_patch` helper naming already used in libSceNet and is not exported as a NID. The debt entry now records what is still different: - Handles are counter values, not the console's IDs. - The ESRCH from a wait or a cancel of a deleted semaphore was not measured. ### Tested - Windows 11 with WSL2, Ubuntu 26.04.1, GCC 15.2.0, Release, `BUILD_TESTING=ON`. - New checks in `guest_semaphore`: - After a delete, poll, signal, a second delete, a timed wait and a cancel return ESRCH, and the wait's timeout and the cancel's thread count are left untouched. - A live semaphore still works afterwards. - An address that was never a semaphore returns ESRCH. - 64 rounds of create A, delete A, create B: B's handle differs from A's, every call through A returns ESRCH with its outputs untouched, and B keeps working. With an address-keyed table this aborts, because the allocator hands A's address to B. - 50 rounds of a delete racing a thread that polls and signals the same semaphore. - On main's `Semaphore.cpp` the test fails: it hangs until ctest's timeout after the first use of a deleted handle. With this change it passes. `guest_semaphore` and `guest_semaphore_trace` passed 30 consecutive runs. - Full `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's `Semaphore.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. - Overlap: #9491 (queued-waiter handoff) also edits `Semaphore.cpp`, `Semaphore.hpp` and the libkernel debt file, and its patch touches the opening lines of `sceKernelSignalSema`, `sceKernelWaitSema` and `sceKernelCancelSema`. 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 moves `GuestSemaphore.cpp`. ### 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 (#9491 lands after this one, [agreed in #9491](https://github.com/boykopovar/AnyPS5/pull/9491#issuecomment-6383848916); #6044 was closed without merging) - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes
MarcZX10 commented 2026-10-24 10:29:16 +00:00 (Migrated from github.com)

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. liveSemas is keyed by KernelSemaPrivate*, and sceKernelCreateSema returns created.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.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5637930190 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10558#pullrequestreview-5637930190). Originally posted by [MarcZX10](https://github.com/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. `liveSemas` is keyed by `KernelSemaPrivate*`, and `sceKernelCreateSema` returns `created.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.
MarcZX10 commented 2026-10-24 11:04:49 +00:00 (Migrated from github.com)

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.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5638016787 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10558#pullrequestreview-5638016787). Originally posted by [MarcZX10](https://github.com/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.
MarcZX10 commented 2026-10-24 11:29:02 +00:00 (Migrated from github.com)

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, and sceKernelCancelSema, 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 says Depends on: none; please agree on integration order with #9491’s author and declare any dependency or explicit coordination. #6044 also renames GuestSemaphore.cpp to core/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.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5638080756 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10558#pullrequestreview-5638080756). Originally posted by [MarcZX10](https://github.com/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`, and `sceKernelCancelSema`, 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 says `Depends on: none`; please agree on integration order with #9491’s author and declare any dependency or explicit coordination. #6044 also renames `GuestSemaphore.cpp` to `core/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.
MarcZX10 commented 2026-10-24 11:54:12 +00:00 (Migrated from github.com)

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.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5638146771 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10558#pullrequestreview-5638146771). Originally posted by [MarcZX10](https://github.com/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.
MarcZX10 commented 2026-10-24 16:33:34 +00:00 (Migrated from github.com)

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.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5638973552 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10558#pullrequestreview-5638973552). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-24T16:33:34Z. **Review:** APPROVED --- Re-reviewed exact head 6597963c94e74f3862cd24d4f0653acf49a7b35c. 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.
MarcZX10 commented 2026-11-01 14:26:52 +00:00 (Migrated from github.com)

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

  • Exact head 1aec488dda13e72898fd5fa25515b4f0fd2f0788, base b415263451 (the precheck base).
  • Environment: Linux, /usr/bin/python3 3.11.2, no build.
  • Precheck: python3 tools/pr_precheck.py --repo boykopovar/AnyPS5 --pr 10558 --output-dir /dev/shm/reviewer-run/precheck/10558
  • ABI audit by hand (helper absent from the head tree): python3 tools/pr_abi_audit.py --repo /marc/AnyPS5 --base b415263451 --head 1aec488dda13e72898fd5fa25515b4f0fd2f0788 --json (exit 0; passed; 0 findings; 6 symbols).
  • Test-quality helper on core/libs/tests/GuestSemaphore.cpp from a head extract: one literal-path registration heuristic.
  • Source read at head: Semaphore.cpp (the handle table, FindSema, sceKernelCreateSema, sceKernelDeleteSema, and the wait path that holds a shared_ptr copy) and the test's RequireDeletedHandles and RequireInvalidArguments (lines 26-67).

Results

Precheck report, checks table, unedited (/dev/shm/reviewer-run/precheck/10558/report.md):

Check Status Command / reason
build_and_compile not_applicable The precheck deliberately does not configure, build, or compile AnyPS5.
diff_check passed git diff --check b41526345185943c53af0c6eee97863df4389c9e...1aec488dda13e72898fd5fa25515b4f0fd2f0788
conventions_and_pr_template passed /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
changed_export_abi_audit failed /usr/bin/python3 tools/pr_abi_audit.py --base b41526345185943c53af0c6eee97863df4389c9e --head 1aec488dda13e72898fd5fa25515b4f0fd2f0788 --json
python_syntax not_applicable No changed Python implementation files.
related_python_unit_tests not_applicable No changed tools/ module has an existing sibling tools/tests/test_<module>.py suite.
python_test_registration not_applicable No changed test_*.py files.
live_dependency_and_mergeability_check passed /usr/bin/python3 /marc/AnyPS5/tools/pr_stack_check.py 10558 --repo boykopovar/AnyPS5 --output-dir /dev/shm/reviewer-run/precheck/10558/stack
build_dependent_cpp_tests not_applicable Not run: C++ tests need exact-head binaries, which require a build; the precheck does not build.
test_quality_heuristics failed /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.md
negative_controls not_applicable No 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_patch is declared in the public Semaphore.hpp inside extern "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.
  • The console's ESRCH answers for poll, signal and a second delete are the author's report; the PR's debt entry should cite the measurement.

Sources

Not verified

  • The C++ test guest_semaphore was not built or run here.
  • The console's ESRCH behaviour was not verified.
  • Hosted: at this head windows, conventions, eligibility, labels, library-portability and report succeeded; linux, register-context, relinker, relinker-asan and write-watch were skipped.
<!-- greyfinch-sync:boykopovar/AnyPS5:review:5728594183 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10558#pullrequestreview-5728594183). Originally posted by [MarcZX10](https://github.com/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 - Exact head `1aec488dda13e72898fd5fa25515b4f0fd2f0788`, base `b415263451` (the precheck base). - Environment: Linux, `/usr/bin/python3` 3.11.2, no build. - Precheck: `python3 tools/pr_precheck.py --repo boykopovar/AnyPS5 --pr 10558 --output-dir /dev/shm/reviewer-run/precheck/10558` - ABI audit by hand (helper absent from the head tree): `python3 tools/pr_abi_audit.py --repo /marc/AnyPS5 --base b415263451 --head 1aec488dda13e72898fd5fa25515b4f0fd2f0788 --json` (exit 0; `passed`; 0 findings; 6 symbols). - Test-quality helper on `core/libs/tests/GuestSemaphore.cpp` from a head extract: one literal-path registration heuristic. - Source read at head: `Semaphore.cpp` (the handle table, `FindSema`, `sceKernelCreateSema`, `sceKernelDeleteSema`, and the wait path that holds a `shared_ptr` copy) and the test's `RequireDeletedHandles` and `RequireInvalidArguments` (lines 26-67). ## Results Precheck report, checks table, unedited (`/dev/shm/reviewer-run/precheck/10558/report.md`): | Check | Status | Command / reason | |---|---|---| | build_and_compile | not_applicable | `The precheck deliberately does not configure, build, or compile AnyPS5.` | | diff_check | passed | `git diff --check b41526345185943c53af0c6eee97863df4389c9e...1aec488dda13e72898fd5fa25515b4f0fd2f0788` | | conventions_and_pr_template | passed | `/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` | | changed_export_abi_audit | failed | `/usr/bin/python3 tools/pr_abi_audit.py --base b41526345185943c53af0c6eee97863df4389c9e --head 1aec488dda13e72898fd5fa25515b4f0fd2f0788 --json` | | python_syntax | not_applicable | `No changed Python implementation files.` | | related_python_unit_tests | not_applicable | `No changed tools/ module has an existing sibling tools/tests/test_<module>.py suite.` | | python_test_registration | not_applicable | `No changed test_*.py files.` | | live_dependency_and_mergeability_check | passed | `/usr/bin/python3 /marc/AnyPS5/tools/pr_stack_check.py 10558 --repo boykopovar/AnyPS5 --output-dir /dev/shm/reviewer-run/precheck/10558/stack` | | build_dependent_cpp_tests | not_applicable | `Not run: C++ tests need exact-head binaries, which require a build; the precheck does not build.` | | test_quality_heuristics | failed | `/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.md` | | negative_controls | not_applicable | `No 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_patch` is declared in the public `Semaphore.hpp` inside `extern "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. - The console's ESRCH answers for poll, signal and a second delete are the author's report; the PR's debt entry should cite the measurement. ## Sources - Handle table, delete and wait at head: https://github.com/boykopovar/AnyPS5/blob/1aec488dda13e72898fd5fa25515b4f0fd2f0788/core/libs/prx/libkernel/Semaphore/src/Semaphore.cpp - Test at head: https://github.com/boykopovar/AnyPS5/blob/1aec488dda13e72898fd5fa25515b4f0fd2f0788/core/libs/tests/GuestSemaphore.cpp#L26-L67 ## Not verified - The C++ test `guest_semaphore` was not built or run here. - The console's ESRCH behaviour was not verified. - Hosted: at this head `windows`, `conventions`, `eligibility`, `labels`, `library-portability` and `report` succeeded; `linux`, `register-context`, `relinker`, `relinker-asan` and `write-watch` were skipped.
ahmadmuj commented 2026-11-06 06:57:28 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ahmadmuj on 2026-11-06T06:57:28Z.

Review: APPROVED


Checked head 16fbff468227a648d732ab19f92fadd8750c1773, PR base 9f9e4207099c61409f4f9df27f90823eb9aabc22. The three focused semaphore tests pass on this head and current main bbd85f7ebfd41433598b4573eaae53df19dc059a on 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.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5796788941 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10558#pullrequestreview-5796788941). Originally posted by [ahmadmuj](https://github.com/ahmadmuj) on 2026-11-06T06:57:28Z. **Review:** APPROVED --- Checked head `16fbff468227a648d732ab19f92fadd8750c1773`, PR base `9f9e4207099c61409f4f9df27f90823eb9aabc22`. The three focused semaphore tests pass on this head and current main `bbd85f7ebfd41433598b4573eaae53df19dc059a` on 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.
ahmadmuj commented 2026-11-06 09:17:45 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ahmadmuj on 2026-11-06T09:17:45Z.

Review: COMMENTED


Tested head 16fbff468227a648d732ab19f92fadd8750c1773 against main e509b292479c383dabd18bf5c323eff1afe9d2f3 on 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, and agc_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=1 and ANYPS5_NO_SHADER_CACHE=1 are 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.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5798093594 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10558#pullrequestreview-5798093594). Originally posted by [ahmadmuj](https://github.com/ahmadmuj) on 2026-11-06T09:17:45Z. **Review:** COMMENTED --- Tested head `16fbff468227a648d732ab19f92fadd8750c1773` against main `e509b292479c383dabd18bf5c323eff1afe9d2f3` on 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`, and `agc_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=1` and `ANYPS5_NO_SHADER_CACHE=1` are 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.
MarcZX10 commented 2026-11-16 12:48:35 +00:00 (Migrated from github.com)

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

Check Result Note
Source review failed Test accessor returns an unowned pointer
Build and tests not run Author reports test results in the PR description

Findings

Blocking

  • core/libs/prx/libkernel/Semaphore/src/Semaphore.cpp:39-40: FindSema(handle) returns a temporary shared_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 in GuestSemaphoreHandoff.cpp and SemaphoreTrace.cpp. Return a shared_ptr to 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_semaphore and guest_semaphore_trace passed 30 consecutive runs, and full ctest passed 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.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5920208540 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10558#pullrequestreview-5920208540). Originally posted by [MarcZX10](https://github.com/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 | Check | Result | Note | |---|---|---| | Source review | failed | Test accessor returns an unowned pointer | | Build and tests | not run | Author reports test results in the PR description | ## Findings ### Blocking - `core/libs/prx/libkernel/Semaphore/src/Semaphore.cpp:39-40`: `FindSema(handle)` returns a temporary `shared_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 in `GuestSemaphoreHandoff.cpp` and `SemaphoreTrace.cpp`. Return a `shared_ptr` to 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_semaphore` and `guest_semaphore_trace` passed 30 consecutive runs, and full `ctest` passed 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.
MarcZX10 commented 2026-11-17 10:27:49 +00:00 (Migrated from github.com)

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: WaiterCount in core/libs/tests/GuestSemaphore.cpp still dereferences the semaphore handle as a pointer, and the handle is no longer a pointer.

What I ran

  • Head: 3781f83c28150911fa3c3bd39daa5d3f442835f5 (base main). Read the changed hunks in the diff for all six changed files.
  • Read the head text of core/libs/tests/GuestSemaphore.cpp lines 141–180 with the repository reader.
  • Commands, from the repository reader:
python3 repo_read.py search KernelSema core
python3 repo_read.py search ForTests_nid_no_patch core
python3 repo_read.py cat core/libs/prx/libSceNpCommon/Runtime.cpp 655 680
  • I did not build the project and did not run guest_semaphore, guest_semaphore_trace or ctest.

Results

Check Result Note
Handle type change read failed By reading, not executed
*ForTests_nid_no_patch naming passed Matches the existing helpers in libSceNet and Ksem
libSceNpCommon wrappers passed Forward the handle only
Build and ctest not run
Negative control not run

Findings

Blocking

  • core/libs/tests/GuestSemaphore.cpp:141 (unchanged by this diff, reached by changed behaviour). WaiterCount locks sem->mutex and reads sem->waiterCount, so it treats KernelSema as a KernelSemaPrivate*. This PR makes the handle a counter value: core/libs/prx/libkernel/Semaphore/src/Semaphore.cpp:65 sets handle = reinterpret_cast<KernelSema>(++lastSemaHandle). The first semaphore gets handle 1, so WaiterCount dereferences a small integer. RequireZeroTimeout calls it at lines 156, 166, 167 and 170, and main calls RequireZeroTimeout last. By reading, that is a crash in guest_semaphore on the first call. The PR says guest_semaphore passed 30 consecutive runs. I have not run it, so the author needs to reconcile that claim with this code.

    static int WaiterCount(KernelSema sem) {
        KernelSemaPrivate* object = KernelSemaObjectForTests_nid_no_patch(sem);
        Require(object != nullptr);
        std::lock_guard<std::mutex> lock(object->mutex);
        return object->waiterCount;
    }
    

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

Not verified

  • The build, guest_semaphore, guest_semaphore_trace, the 30 reported runs, the 50-round race test and the full ctest run. Only the author reported these.
  • The WaiterCount crash is from reading the code. I did not execute it.
  • The external links to prosper and shadPS4 in the debt file. I did not open them.
  • Other users of KernelSema: the search found only handle pass-throughs in the tests and in libSceNpCommon. I did not read every call site.
  • Files read: the diff of all six changed files (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 for core/libs/tests/GuestSemaphore.cpp lines 141–180. Nothing was excluded.

To get this to a good state

  • Replace WaiterCount in core/libs/tests/GuestSemaphore.cpp with the handle-to-object lookup above.
  • Rerun guest_semaphore, guest_semaphore_trace and ctest on the new head, and post the output.
  • Remove the duplicate <memory> include (optional).
<!-- greyfinch-sync:boykopovar/AnyPS5:review:5936762414 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10558#pullrequestreview-5936762414). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-17T10:27:49Z. **Review:** CHANGES_REQUESTED --- # Reviewed — changes requested Changes are required before merge: `WaiterCount` in `core/libs/tests/GuestSemaphore.cpp` still dereferences the semaphore handle as a pointer, and the handle is no longer a pointer. ## What I ran - Head: `3781f83c28150911fa3c3bd39daa5d3f442835f5` (base `main`). Read the changed hunks in the diff for all six changed files. - Read the head text of `core/libs/tests/GuestSemaphore.cpp` lines 141–180 with the repository reader. - Commands, from the repository reader: ``` python3 repo_read.py search KernelSema core python3 repo_read.py search ForTests_nid_no_patch core python3 repo_read.py cat core/libs/prx/libSceNpCommon/Runtime.cpp 655 680 ``` - I did not build the project and did not run `guest_semaphore`, `guest_semaphore_trace` or `ctest`. ## Results | Check | Result | Note | |---|---|---| | Handle type change read | failed | By reading, not executed | | `*ForTests_nid_no_patch` naming | passed | Matches the existing helpers in libSceNet and Ksem | | libSceNpCommon wrappers | passed | Forward the handle only | | Build and `ctest` | not run | | | Negative control | not run | | ## Findings ### Blocking - **`core/libs/tests/GuestSemaphore.cpp:141`** (unchanged by this diff, reached by changed behaviour). `WaiterCount` locks `sem->mutex` and reads `sem->waiterCount`, so it treats `KernelSema` as a `KernelSemaPrivate*`. This PR makes the handle a counter value: `core/libs/prx/libkernel/Semaphore/src/Semaphore.cpp:65` sets `handle = reinterpret_cast<KernelSema>(++lastSemaHandle)`. The first semaphore gets handle `1`, so `WaiterCount` dereferences a small integer. `RequireZeroTimeout` calls it at lines 156, 166, 167 and 170, and `main` calls `RequireZeroTimeout` last. By reading, that is a crash in `guest_semaphore` on the first call. The PR says `guest_semaphore` passed 30 consecutive runs. I have not run it, so the author needs to reconcile that claim with this code. ```suggestion static int WaiterCount(KernelSema sem) { KernelSemaPrivate* object = KernelSemaObjectForTests_nid_no_patch(sem); Require(object != nullptr); std::lock_guard<std::mutex> lock(object->mutex); return object->waiterCount; } ``` ### 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 - The `*ForTests_nid_no_patch` naming matches the existing helpers: [SetResolverLookupForTests_nid_no_patch](https://github.com/boykopovar/AnyPS5/blob/3781f83c28150911fa3c3bd39daa5d3f442835f5/core/libs/prx/libSceNet/Export.cpp#L965) and [KsemWaiterCountForTests_nid_no_patch](https://github.com/boykopovar/AnyPS5/blob/3781f83c28150911fa3c3bd39daa5d3f442835f5/core/libs/prx/libkernel/Semaphore/src/Ksem.cpp#L120). - `WaiterCount`: [GuestSemaphore.cpp lines 141–143](https://github.com/boykopovar/AnyPS5/blob/3781f83c28150911fa3c3bd39daa5d3f442835f5/core/libs/tests/GuestSemaphore.cpp#L141-L143). ## Not verified - The build, `guest_semaphore`, `guest_semaphore_trace`, the 30 reported runs, the 50-round race test and the full `ctest` run. Only the author reported these. - The `WaiterCount` crash is from reading the code. I did not execute it. - The external links to prosper and shadPS4 in the debt file. I did not open them. - Other users of `KernelSema`: the search found only handle pass-throughs in the tests and in libSceNpCommon. I did not read every call site. - Files read: the diff of all six changed files (`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 for `core/libs/tests/GuestSemaphore.cpp` lines 141–180. Nothing was excluded. ## To get this to a good state - Replace `WaiterCount` in `core/libs/tests/GuestSemaphore.cpp` with the handle-to-object lookup above. - Rerun `guest_semaphore`, `guest_semaphore_trace` and `ctest` on the new head, and post the output. - Remove the duplicate `<memory>` include (optional).
lgqdaxia commented 2026-11-28 18:05:47 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by lgqdaxia on 2026-11-28T18:05:47Z.

Review: COMMENTED


I checked the test callers at 3781f83c2815 and agree with MarcZX10's two findings. WaiterCount treats a guest semaphore handle as an object address. The handoff and trace helpers look it up in the registry, but drop the owning shared_ptr before 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-esrch branch. The helpers now look up the opaque handle and hold the registry's shared_ptr until they finish reading under the object's mutex. On Windows x64 with MinGW, guest_semaphore, guest_semaphore_handoff and guest_semaphore_trace all passed at b6833166a1e5. ZSWolt/AnyPS5#1

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6099475902 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10558#pullrequestreview-6099475902). Originally posted by [lgqdaxia](https://github.com/lgqdaxia) on 2026-11-28T18:05:47Z. **Review:** COMMENTED --- I checked the test callers at `3781f83c2815` and agree with MarcZX10's two findings. `WaiterCount` treats a guest semaphore handle as an object address. The handoff and trace helpers look it up in the registry, but drop the owning `shared_ptr` before 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-esrch` branch. The helpers now look up the opaque handle and hold the registry's `shared_ptr` until they finish reading under the object's mutex. On Windows x64 with MinGW, `guest_semaphore`, `guest_semaphore_handoff` and `guest_semaphore_trace` all passed at `b6833166a1e5`. [ZSWolt/AnyPS5#1](https://github.com/ZSWolt/AnyPS5/pull/1)
ligmaSec commented 2026-12-03 13:25:16 +00:00 (Migrated from github.com)

Imported 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.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6170655334 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10558#pullrequestreview-6170655334). Originally posted by [ligmaSec](https://github.com/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.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/10558:upstream-pr/10558'
git switch 'upstream-pr/10558'

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.

git switch 'main'
git merge --no-ff 'upstream-pr/10558'
git switch 'upstream-pr/10558'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/10558'
git switch 'upstream-pr/10558'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/10558'
git switch 'main'
git merge --squash 'upstream-pr/10558'
git switch 'main'
git merge --ff-only 'upstream-pr/10558'
git switch 'main'
git merge 'upstream-pr/10558'
git push origin 'main'
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!10558
No description provided.