feat(libkernel): implement the named ksem semaphores #9293

Closed
DavidSamir wants to merge 13 commits from upstream-pr/9293 into main
DavidSamir commented 2026-10-21 17:30:58 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by DavidSamir on 2026-10-21T17:30:58Z.


What

Builds on #9284 and adds the named ksem_* exports to libkernel/Semaphore/src/Ksem.cpp, following FreeBSD 11 sys/kern/uipc_sem.c. Until #9284 merges, this PR's diff also shows #9284's commits.

Moved to libkernel so libkernel imports reach it on Windows, as #9284 now is. The PS5 3.20 lists export ksem_* from libkernel too, and a Windows libkernel import never searches libkernel_sys. The libkernel_sys stubs for ksem_open, ksem_close and ksem_unlink are removed.

Export Behaviour
ksem_open(semid_t* idp, const char* name, int oflag, mode_t mode, u_int value) see the rules below
ksem_close(semid_t) EINVAL on an unnamed id, which needs ksem_destroy
ksem_unlink(const char* name) removes the name, ENOENT if it is absent; ids already open keep working, and a later O_CREAT open makes a new semaphore

ksem_open's rules, in the order of sys_ksem_open and ksem_create:

  1. EINVAL for oflag bits other than O_CREAT | O_EXCL, then for value > SEM_VALUE_MAX.
  2. The descriptor is allocated (EMFILE or ENFILE when none is left), and the id is written to *idp (EFAULT for a NULL idp) before the name is checked, as FreeBSD's early copyout does.
  3. EFAULT for a NULL name, ENAMETOOLONG for 1024 bytes or more, and EINVAL for a name that doesn't start with /.
  4. ENOENT for a missing name without O_CREAT, and EEXIST for an existing name with O_CREAT | O_EXCL.
  5. ENFILE when a new name would exceed the 30 semaphores (SEM_MAX).

Each successful open returns a new descriptor id that shares the semaphore.

The limit counts semaphore objects, as FreeBSD's nsems does. Two opens of one name are one semaphore, and a name still linked counts until ksem_unlink, even with no open id. Unnamed ksem_init gives ENOSPC past the limit, as in #9284. (Points from @pipe1os's review on #9284.)

ksem_destroy now gives EINVAL on a named id, which needs ksem_close, as FreeBSD's KS_ANONYMOUS check does. A debt line in libkernel.md records that named semaphores are kept per process, which fits a single guest process: mode is accepted, and the owner and permission checks are not modelled.

Tested

Windows 11 Pro 26200, WinLibs GCC 15.2.0 r7, Release. These are CPU-side exports, so no GPU is involved.

  • guest_kernel_sys_ksem gains Named():
    • every error rule above;
    • two ids opened on one name share the count (a post through one is seen through the other);
    • ksem_destroy on a named id and ksem_close on an unnamed id give EINVAL;
    • after ksem_unlink the name is gone (ENOENT), but the open ids still work; ksem_close invalidates its id, and the other id is unaffected;
    • a new O_CREAT open after the unlink starts from its own value.
  • New NamedLimit():
    • a NULL name gives EFAULT with the id already written but dead;
    • two opens of one name plus 29 unnamed semaphores make 30, and the named one still counts after both ids are closed: unnamed ksem_init gives ENOSPC and a new name gives ENFILE;
    • after ksem_unlink, there's room again.
    • Negative control: with the named limit check removed, the test fails at line 232.
  • With #9284's code, where the named forms are still stubs, the test aborts with ksem_open_nid_postfix not implemented. On this branch it passes, 5 of 5 runs. tools/check_conventions.py passes, including the duplicate-export rule (all ten ksem_* are now exported by libkernel only).
  • Overlap: tools/pr_overlap.py crashes on this machine's partial clone, so it was replaced by a check against an index of every open PR's diff plus git merge-tree. This branch merges cleanly with main and with #9160, #9195, #9162, #9161, #9156, #9171, #9273, #9242, #9019, #9008, #9097, #9141, #9103, #8987 and #7121.

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: #9284
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4955697611 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9293). Originally posted by [DavidSamir](https://github.com/DavidSamir) on 2026-10-21T17:30:58Z. --- ### What Builds on #9284 and adds the named `ksem_*` exports to `libkernel/Semaphore/src/Ksem.cpp`, following FreeBSD 11 `sys/kern/uipc_sem.c`. **Until #9284 merges, this PR's diff also shows #9284's commits.** **Moved to libkernel so libkernel imports reach it on Windows**, as #9284 now is. The PS5 3.20 lists export `ksem_*` from libkernel too, and a Windows libkernel import never searches libkernel_sys. The libkernel_sys stubs for `ksem_open`, `ksem_close` and `ksem_unlink` are removed. | Export | Behaviour | |---|---| | `ksem_open(semid_t* idp, const char* name, int oflag, mode_t mode, u_int value)` | see the rules below | | `ksem_close(semid_t)` | `EINVAL` on an unnamed id, which needs `ksem_destroy` | | `ksem_unlink(const char* name)` | removes the name, `ENOENT` if it is absent; ids already open keep working, and a later `O_CREAT` open makes a new semaphore | `ksem_open`'s rules, in the order of `sys_ksem_open` and `ksem_create`: 1. `EINVAL` for `oflag` bits other than `O_CREAT | O_EXCL`, then for `value > SEM_VALUE_MAX`. 2. The descriptor is allocated (`EMFILE` or `ENFILE` when none is left), and the id is written to `*idp` (`EFAULT` for a NULL `idp`) **before** the name is checked, as FreeBSD's early copyout does. 3. `EFAULT` for a NULL name, `ENAMETOOLONG` for 1024 bytes or more, and `EINVAL` for a name that doesn't start with `/`. 4. `ENOENT` for a missing name without `O_CREAT`, and `EEXIST` for an existing name with `O_CREAT | O_EXCL`. 5. `ENFILE` when a new name would exceed the 30 semaphores (`SEM_MAX`). Each successful open returns a new descriptor id that shares the semaphore. **The limit counts semaphore objects, as FreeBSD's `nsems` does.** Two opens of one name are one semaphore, and a name still linked counts until `ksem_unlink`, even with no open id. Unnamed `ksem_init` gives `ENOSPC` past the limit, as in #9284. (Points from @pipe1os's review on #9284.) `ksem_destroy` now gives `EINVAL` on a named id, which needs `ksem_close`, as FreeBSD's `KS_ANONYMOUS` check does. A debt line in `libkernel.md` records that named semaphores are kept per process, which fits a single guest process: `mode` is accepted, and the owner and permission checks are not modelled. ### Tested Windows 11 Pro 26200, WinLibs GCC 15.2.0 r7, Release. These are CPU-side exports, so no GPU is involved. - `guest_kernel_sys_ksem` gains `Named()`: - every error rule above; - two ids opened on one name share the count (a post through one is seen through the other); - `ksem_destroy` on a named id and `ksem_close` on an unnamed id give `EINVAL`; - after `ksem_unlink` the name is gone (`ENOENT`), but the open ids still work; `ksem_close` invalidates its id, and the other id is unaffected; - a new `O_CREAT` open after the unlink starts from its own value. - New `NamedLimit()`: - a NULL name gives `EFAULT` with the id already written but dead; - two opens of one name plus 29 unnamed semaphores make 30, and the named one still counts after both ids are closed: unnamed `ksem_init` gives `ENOSPC` and a new name gives `ENFILE`; - after `ksem_unlink`, there's room again. - Negative control: with the named limit check removed, the test fails at line 232. - With #9284's code, where the named forms are still stubs, the test aborts with `ksem_open_nid_postfix not implemented`. On this branch it passes, 5 of 5 runs. `tools/check_conventions.py` passes, including the duplicate-export rule (all ten `ksem_*` are now exported by libkernel only). - Overlap: `tools/pr_overlap.py` crashes on this machine's partial clone, so it was replaced by a check against an index of every open PR's diff plus `git merge-tree`. This branch merges cleanly with `main` and with #9160, #9195, #9162, #9161, #9156, #9171, #9273, #9242, #9019, #9008, #9097, #9141, #9103, #8987 and #7121. ### 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: #9284 - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes
github-actions[bot] commented 2026-10-21 17:31:56 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-21T17:31:56Z.


Progress report (0c6a5bd → b208fd6)

📈 System libraries: 42.19% (+0.09%, +10 implemented, -10 removed functions)

✅ 10 implemented
Library Name
libkernel ksem_close_nid_postfix
libkernel ksem_destroy_nid_postfix
libkernel ksem_getvalue_nid_postfix
libkernel ksem_init_nid_postfix
libkernel ksem_open_nid_postfix
libkernel ksem_post_nid_postfix
libkernel ksem_timedwait_nid_postfix
libkernel ksem_trywait_nid_postfix
libkernel ksem_unlink_nid_postfix
libkernel ksem_wait_nid_postfix
🗑️ 10 removed
Library Name
libkernel_sys ksem_close_nid_postfix
libkernel_sys ksem_destroy_nid_postfix
libkernel_sys ksem_getvalue_nid_postfix
libkernel_sys ksem_init_nid_postfix
libkernel_sys ksem_open_nid_postfix
libkernel_sys ksem_post_nid_postfix
libkernel_sys ksem_timedwait_nid_postfix
libkernel_sys ksem_trywait_nid_postfix
libkernel_sys ksem_unlink_nid_postfix
libkernel_sys ksem_wait_nid_postfix
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6322355045 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9293#issuecomment-6322355045). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-21T17:31:56Z. --- <!-- progress-report --> ### Progress report (0c6a5bd → b208fd6) 📈 **System libraries**: 42.19% (+0.09%, +10 implemented, -10 removed functions) <details> <summary>✅ 10 implemented</summary> | Library | Name | | - | - | | libkernel | `ksem_close_nid_postfix` | | libkernel | `ksem_destroy_nid_postfix` | | libkernel | `ksem_getvalue_nid_postfix` | | libkernel | `ksem_init_nid_postfix` | | libkernel | `ksem_open_nid_postfix` | | libkernel | `ksem_post_nid_postfix` | | libkernel | `ksem_timedwait_nid_postfix` | | libkernel | `ksem_trywait_nid_postfix` | | libkernel | `ksem_unlink_nid_postfix` | | libkernel | `ksem_wait_nid_postfix` | </details> <details> <summary>🗑️ 10 removed</summary> | Library | Name | | - | - | | libkernel_sys | `ksem_close_nid_postfix` | | libkernel_sys | `ksem_destroy_nid_postfix` | | libkernel_sys | `ksem_getvalue_nid_postfix` | | libkernel_sys | `ksem_init_nid_postfix` | | libkernel_sys | `ksem_open_nid_postfix` | | libkernel_sys | `ksem_post_nid_postfix` | | libkernel_sys | `ksem_timedwait_nid_postfix` | | libkernel_sys | `ksem_trywait_nid_postfix` | | libkernel_sys | `ksem_unlink_nid_postfix` | | libkernel_sys | `ksem_wait_nid_postfix` | </details>
DavidSamir commented 2026-10-22 02:06:20 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by DavidSamir on 2026-10-22T02:06:20Z.


Linux: Ubuntu 24.04.1 LTS (WSL2), GCC 13.3.0, Release; head b208fd6b2 merged onto main 8c26eac3c.

  • guest_kernel_sys_ksem passes 3/3.
  • Negative control: with the named limit check removed (if (Objects() >= SemMax) replaced by if (false)), it fails at line 232, as listed.

Run from the PC (Windows host, Linux in WSL2), not from the PR author's machine.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6330942813 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9293#issuecomment-6330942813). Originally posted by [DavidSamir](https://github.com/DavidSamir) on 2026-10-22T02:06:20Z. --- Linux: Ubuntu 24.04.1 LTS (WSL2), GCC 13.3.0, Release; head `b208fd6b2` merged onto `main` `8c26eac3c`. - `guest_kernel_sys_ksem` passes 3/3. - Negative control: with the named limit check removed (`if (Objects() >= SemMax)` replaced by `if (false)`), it fails at line 232, as listed. Run from the PC (Windows host, Linux in WSL2), not from the PR author's machine.
harisibrar1 commented 2026-10-24 13:37:55 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by harisibrar1 on 2026-10-24T13:37:55Z.

Review: COMMENTED


Checked against main 522e32e3b6 and FreeBSD release/11.4.0 sys/kern/uipc_sem.c / lib/libc/gen/sem_new.c:

  • ksem_open with a NULL name: in 11.4, sys_ksem_open passes uap->name straight to ksem_create, and name == NULL is its anonymous branch (uipc_sem.c:494-500). It allocates a KS_ANONYMOUS semaphore and returns 0, and gives ENOSPC if falloc fails (L477-478). Ksem.cpp:208 returns EFAULT instead, and GuestKernelSysKsem.cpp:157/:220 pin that. Could this follow FreeBSD (an unnamed semaphore that ksem_destroy accepts and ksem_close rejects with EINVAL), or throw if you'd rather not assume the PS5 matches?
  • The rest of the order matches 11.4 as far as I can see: oflag, value, falloc, early copyout, copyinstr/ENAMETOOLONG, leading /, ENOENT/EEXIST/ENFILE. So do the nsems-style counting (a linked name counts until unlink), the KS_ANONYMOUS checks in ksem_close/ksem_destroy, and ksem_unlink (no / check, ENOENT).
  • A 3-way git merge-tree of this head with current main now conflicts in core/libs/prx/libkernel_sys/Export.Discovery.cpp, because main dropped the neighbouring ktimer_* stubs, so it needs a rebase (along with #9284, which is still open).
  • Side note: 11.4's libc sem_open (sem_new.c) is file-backed and never calls ksem_open, so it doesn't bear on these rules either way.

Reviewed with AI assistance (Claude Code); the checks above were run locally on my machine.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5638438040 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9293#pullrequestreview-5638438040). Originally posted by [harisibrar1](https://github.com/harisibrar1) on 2026-10-24T13:37:55Z. **Review:** COMMENTED --- Checked against main 522e32e3b6 and FreeBSD release/11.4.0 `sys/kern/uipc_sem.c` / `lib/libc/gen/sem_new.c`: - `ksem_open` with a NULL name: in 11.4, `sys_ksem_open` passes `uap->name` straight to `ksem_create`, and `name == NULL` is its anonymous branch (uipc_sem.c:494-500). It allocates a `KS_ANONYMOUS` semaphore and returns 0, and gives `ENOSPC` if falloc fails (L477-478). `Ksem.cpp:208` returns `EFAULT` instead, and `GuestKernelSysKsem.cpp:157`/`:220` pin that. Could this follow FreeBSD (an unnamed semaphore that `ksem_destroy` accepts and `ksem_close` rejects with EINVAL), or throw if you'd rather not assume the PS5 matches? - The rest of the order matches 11.4 as far as I can see: oflag, value, falloc, early copyout, copyinstr/ENAMETOOLONG, leading `/`, ENOENT/EEXIST/ENFILE. So do the `nsems`-style counting (a linked name counts until unlink), the KS_ANONYMOUS checks in `ksem_close`/`ksem_destroy`, and `ksem_unlink` (no `/` check, ENOENT). - A 3-way `git merge-tree` of this head with current main now conflicts in `core/libs/prx/libkernel_sys/Export.Discovery.cpp`, because main dropped the neighbouring `ktimer_*` stubs, so it needs a rebase (along with #9284, which is still open). - Side note: 11.4's libc `sem_open` (`sem_new.c`) is file-backed and never calls `ksem_open`, so it doesn't bear on these rules either way. Reviewed with AI assistance (Claude Code); the checks above were run locally on my machine.
CnRJay commented 2026-11-01 20:04:55 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by CnRJay on 2026-11-01T20:04:55Z.

Review: COMMENTED


Withdrawn. This review applied a title-ID/log requirement that is not in CONTRIBUTING (Unblocks: none is allowed), and it contained no code review.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5729973400 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9293#pullrequestreview-5729973400). Originally posted by [CnRJay](https://github.com/CnRJay) on 2026-11-01T20:04:55Z. **Review:** COMMENTED --- Withdrawn. This review applied a title-ID/log requirement that is not in CONTRIBUTING (`Unblocks: none` is allowed), and it contained no code review.
MarcZX10 commented 2026-11-23 02:22:12 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-23T02:22:12Z.

Review: CHANGES_REQUESTED


Reviewed — changes requested

Changes are required before merge: handle an empty semaphore name before indexing its first character.

What I ran

Reviewed head b208fd6b210d26e58b969d2341404b4cf085f5b0. I did not run tests or build commands. I read the prepared description, commits, diff, manifest, and all changed file paths; the file listing showed all nine changed files included. The review bundle did not provide files.json.

Results

Check Result Note
Code review failed Empty name can trigger undefined behavior
Build and tests not run No commands run

Findings

Blocking

  • core/libs/prx/libkernel/Semaphore/src/Ksem.cpp:211: An empty string is a valid non-null name, but after constructing an empty path, this line reads path[0]. That is out-of-bounds access and can cause undefined behavior instead of returning EINVAL. Check path.empty() before indexing.

Non-blocking

None.

Not verified

Build and test results were not independently verified. I reviewed all changed paths listed by the reader; the listing showed no excluded changed files.

To get this to a good state

Check for an empty path before reading path[0], then rerun the build and ksem tests on the updated head.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6015892881 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9293#pullrequestreview-6015892881). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-23T02:22:12Z. **Review:** CHANGES_REQUESTED --- # Reviewed — changes requested Changes are required before merge: handle an empty semaphore name before indexing its first character. ## What I ran Reviewed head `b208fd6b210d26e58b969d2341404b4cf085f5b0`. I did not run tests or build commands. I read the prepared description, commits, diff, manifest, and all changed file paths; the file listing showed all nine changed files included. The review bundle did not provide `files.json`. ## Results | Check | Result | Note | |---|---|---| | Code review | failed | Empty name can trigger undefined behavior | | Build and tests | not run | No commands run | ## Findings ### Blocking - `core/libs/prx/libkernel/Semaphore/src/Ksem.cpp:211`: An empty string is a valid non-null `name`, but after constructing an empty `path`, this line reads `path[0]`. That is out-of-bounds access and can cause undefined behavior instead of returning `EINVAL`. Check `path.empty()` before indexing. ### Non-blocking None. ## Not verified Build and test results were not independently verified. I reviewed all changed paths listed by the reader; the listing showed no excluded changed files. ## To get this to a good state Check for an empty path before reading `path[0]`, then rerun the build and ksem tests on the updated head.

Pull request closed

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!9293
No description provided.