Repository navigation
feat(libkernel): share a ksem semaphore across dup, dup2 and F_DUPFD, as FreeBSD 11.4 does - #22191
Conversation
PrivacyOnion
left a comment
There was a problem hiding this comment.
Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 7fba7a7138:
- Conventions:
tools/check_conventions.pypassed. - Build:
guest_kernel_sys_ksem_testsbuilt cleanly. - CTest (
guest_kernel_sys_ksem):1/1 Test #938: guest_kernel_sys_ksem ............ Passed 5.31 sec 100% tests passed, 0 tests failed out of 1 - Negative control: with
core/libs/prx/libkernel/File/src/Stdio.cpp,core/libs/prx/libkernel/Semaphore/include/Ksem.hpp,core/libs/prx/libkernel/Semaphore/src/Ksem.cppreverted tomainand the new tests kept, the suite fails:Restoring the change makes it pass again.1/1 Test #938: guest_kernel_sys_ksem ............Subprocess aborted***Exception: 5.43 sec 0% tests passed, 1 tests failed out of 1 - Code reading:
- Verified that Find() marks ksem lookups as failed when dead is true, returning EINVAL on post/wait/trywait/timedwait/getvalue/destroy as required by FreeBSD 11 uipc_sem.c
- Verified ksem_destroy marks dead=true under ksem->lock when waiters==0, preventing further acquisitions across all duplicate descriptors while waiting for all fds to close
- Verified SemaphoreCount() computes the number of unique Ksem pointers using std::set<const Ksem*>, accurately enforcing SEM_MAX (30) across shared descriptor duplicates
- Verified DuplicateKsemDescriptor correctly binds the new descriptor to the existing std::shared_ptr in g_ksems under g_ksemLock across dup, dup2, and fcntl(F_DUPFD) on both Windows and POSIX paths
- Verified that closing a ksem descriptor triggers DescriptorClosed via RegisterDescriptorCloseObserver, safely erasing the entry from g_ksems and freeing the Ksem once the last duplicate descriptor closes
Looks Good To Me
|
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.
|
MarcZX10
left a comment
There was a problem hiding this comment.
Reviewed — looks good
Nothing blocks this change; the reviewed code and author-reported checks support merging.
What I ran
I reviewed head 7fba7a7138a48d197ffe92a93d2f037cf8530986. No commands or tests were run in this review; the reader repo_read.py was used to inspect the prepared diff and repository sources at the pinned head. The base was main; no merged-preview check was run.
Results
| Check | Result | Note |
|---|---|---|
| Source review | passed | All five changed files read |
| Automated checks | not run | Author-reported results are not independently verified |
| Negative control | not run | No test was changed for this review |
Findings
Blocking
None.
Non-blocking
None.
Not verified
No automated tests, builds, or conventions checks were run. Windows, Linux, macOS, and console behavior were not independently verified. The author reports passing ksem and related guest tests on Windows and Linux, and reports that the ksem test fails against the prior implementation.
Files read: core/libs/prx/libkernel/File/src/Stdio.cpp, core/libs/prx/libkernel/Semaphore/include/Ksem.hpp, core/libs/prx/libkernel/Semaphore/src/Ksem.cpp, core/libs/tests/GuestKernelSysKsem.cpp, and docs/dev/debt/changes/feat-libkernel-ksem-shared-duplicates.md. Excluded files: none listed in the prepared manifest.
To get this to a good state
Nothing is required.
|
Pushed e186493, which keeps The first commit removed it because nothing else called it at the time, but #24484, #24487, #24488, #24489 and #24490 (opened since) add calls to it. Those merge with this branch without a text conflict in the library files, so whichever landed second would have failed to build: 7fba7a7 merged with #24490 stops at The function is unchanged from |
MarcZX10
left a comment
There was a problem hiding this comment.
Reviewed — no blocking findings
The inspected changes at head e1864939b349eb70e5272f47dc5eb837313a340e consistently map duplicated descriptors to shared semaphore state and retain that state until its last descriptor closes; I did not run the reported checks.
What I ran
Read the prepared description, commits, manifest, diff, all five changed files, and targeted close-notification and duplication code through repo_read.py. No build or test command was run. Author-reported checks are not treated as checks I ran.
Results
| Check | Result | Note |
|---|---|---|
| Source review | passed | All five changed files read |
| Tests and build | not run | Author reports Windows and Linux runs |
| Negative control | not run | Author reports the test fails without the change |
Negative control
Could not run a negative control in this review session.
Findings
Blocking
None.
Non-blocking
None.
Sources
Behavior reviewed in Ksem.cpp at the reviewed commit and Stdio.cpp at the reviewed commit.
Not verified
Builds, tests, and console behavior were not independently verified. The author reports Windows and Linux test runs; macOS and title behavior were not tested. The prepared review listing included all five changed files; no exclusions were listed there.
Files read: core/libs/prx/libkernel/File/src/Stdio.cpp, core/libs/prx/libkernel/Semaphore/include/Ksem.hpp, core/libs/prx/libkernel/Semaphore/src/Ksem.cpp, core/libs/tests/GuestKernelSysKsem.cpp, and docs/dev/debt/changes/feat-libkernel-ksem-shared-duplicates.md. Excluded changed files: none listed.
To get this to a good state
Nothing is required.
|
Tested
AI-assisted: yes (Claude Code); the runs are automated, this summary was written from their reports. |
… as FreeBSD 11.4 does dup of a ksem id, dup2 from one and fcntl F_DUPFD on one threw, where FreeBSD 11.4's uipc_sem.c shares the semaphore between the descriptors, since a ksem id is a descriptor whose file holds it. The new descriptor now maps to the same semaphore. ksem_destroy marks it dead before closing its id, so the other descriptors fail with EINVAL as ksem_get does for KS_DEAD, and the semaphore is freed when its last descriptor closes. SEM_MAX counts semaphores, not descriptors, so a duplicate does not use up a slot and a destroyed semaphore keeps its slot until its last descriptor is closed, as nsems does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The first commit removed IsKsemDescriptor once Stdio.cpp no longer needed it, but other open changes call it to treat ksem ids as FreeBSD 11.4's ksem_ops does. Keep it, unchanged: a duplicated id is in the same table, so it answers for every descriptor of a semaphore. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…criptors KsemStat and KsemChangeMode, added on main since this branch, looked the semaphore up with Find, which hides one ksem_destroy marked dead. A dup of a destroyed semaphore then fell through to the host's fstat and fchmod of the null device. FreeBSD 11.4's ksem_stat and ksem_chmod do not check KS_DEAD, which only ksem_get does, so look up any open descriptor there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
e186493 to
2480803
Compare
|
Rebased onto #24491 merged in the meantime and added Run on the rebased branch, Windows and Linux, with and without the change: https://github.com/Dr-Coconut/AnyPS5/actions/runs/45036312458. The without-change run stops at the first |
MarcZX10
left a comment
There was a problem hiding this comment.
Reviewed — changes requested
Changes are required before merge: make ksem operations recheck the dead state after acquiring the semaphore lock.
What I ran
Reviewed head 248080360b15c72b9929f5b40b35375aa3c678f5. I used the prepared diff and the pinned repository reader; no tests or build commands were run. The reader was accessed through the review tools, so there is no shell command to report.
Results
| Check | Result | Note |
|---|---|---|
| Diff and targeted source review | passed | All five changed files read |
| Tests and build | not run | Author reports CI runs; not independently verified |
Negative control
Not run; no test or code alteration was made.
Findings
Blocking
core/libs/prx/libkernel/Semaphore/src/Ksem.cpp:269:Findchecksdeadbefore the operation acquiresksem->lock, but operations do not check it again under that lock. If an operation obtains the shared pointer and pauses,ksem_destroycan setdeadand release the lock first; the operation can then proceed on the destroyed semaphore. A wait with count zero can block indefinitely instead of returningEINVAL. Checkdeadwhile holding the semaphore lock in operations that use the semaphore, includingWait.
Non-blocking
None.
Sources
Not verified
Tests and builds were not run. The author reports Windows and Linux CI results in the PR description; those results were not independently checked. macOS and physical-console behavior were not verified. Read: Stdio.cpp, Ksem.hpp, Ksem.cpp, GuestKernelSysKsem.cpp, and feat-libkernel-ksem-shared-duplicates.md. No changed files were excluded; all five were listed as reviewed in the manifest.
To get this to a good state
Recheck the dead flag under the semaphore lock before each operation proceeds, and add coverage for an operation racing with destroy. Rerun the relevant ksem tests on the updated head.
An operation that found the semaphore before ksem_destroy marked it dead went on once it took the semaphore's lock, so a wait on a zero count could block on a destroyed semaphore that nothing can post any more. Wait, ksem_post, ksem_getvalue and ksem_destroy now fail with EINVAL when the mark is set under the lock, the outcome FreeBSD 11.4 gives when the destroy comes first. A test-only hook destroys the semaphore right after the lookup to cover each operation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
@MarcZX10 thanks, addressed in 8105c2e. The waits, For coverage, Run on Windows and Linux: https://github.com/Dr-Coconut/AnyPS5/actions/runs/45123424265. With the change, |
MarcZX10
left a comment
There was a problem hiding this comment.
Reviewed — looks good
Nothing blocks this change; the checked code supports sharing semaphore state across duplicated descriptors and rejecting operations after destruction.
What I ran
Reviewed head 8105c2e04466f9d3f53bcd97fbd02e6647853fd0 using the prepared diff and repo_read.py for targeted source reads. No commands or tests were run by me; build and test results below are author-reported.
Results
| Check | Result | Note |
|---|---|---|
| Changed code review | passed | All five changed files read |
| Reported CI tests | not run | Author reports Windows and Linux passes |
| macOS and console | not run | Author reports neither tested |
Findings
Blocking
None.
Non-blocking
None.
Not verified
I did not run builds, tests, convention checks, overlap checks, or console/hardware checks. The author reports guest_kernel_sys_ksem, guest_dup, guest_kernel_fcntl, and guest_kernel_web_forwards passing on Windows and Linux, plus the convention and debt checks passing. I read all changed files listed in manifest.json: Stdio.cpp, Ksem.hpp, Ksem.cpp, GuestKernelSysKsem.cpp, and the debt fragment. No changed files were excluded; the prepared bundle did not include files.json.
To get this to a good state
Nothing is required.
|
Works on Windows at head Existing runs. 5 reviews, 5 comments, no inline comments.
What this run adds.
Code. Line numbers are from the head. The merged files are the same, because none of the changed files differs between the merge base and
Negative control and mutation. Each row is the merge plus the probe, with one change. The rows ran the 9 focused tests and the probe.
Probes. One extra test executable,
Tests.
Host.
AI-assisted: yes |
# Conflicts: # core/libs/tests/GuestKernelSysKsem.cpp
MarcZX10
left a comment
There was a problem hiding this comment.
Reviewed — comments
Nothing blocks this review, but dup2 can leave a ksem descriptor mapped to the wrong semaphore when the host descriptor replacement fails.
What I ran
Reviewed head 041dd013fe073c284152299fc8693196d0a35947 from the prepared diff and pinned repository reader. No commands, tests, or builds were run. Read description.md, commits.md, manifest.json, diff.patch, all changed repository files listed in the manifest, and the relevant close implementation in Stdio.cpp. files.json was unavailable through the provided reader.
Results
| Check | Result | Note |
|---|---|---|
| Diff and changed source review | passed | All five manifest files read |
| Tests and builds | not run | Author reports Windows and Linux CI results |
| Excluded files | not verified | files.json could not be read |
Findings
Blocking
None.
Non-blocking
- In both
dup2paths,DuplicateKsemDescriptor(from, to)runs after the host duplication call without checking that it succeeded. The helper unconditionally assignsg_ksems[to], so a failed host duplication can overwrite an existing ksem mapping whiletostill refers to its prior host descriptor (or is closed). Future operations on that descriptor can then target a semaphore unrelated to the host descriptor. Only register the ksem mapping after a successful replacement. Seecore/libs/prx/libkernel/File/src/Stdio.cpp:1154andcore/libs/prx/libkernel/File/src/Stdio.cpp:1173, and helpercore/libs/prx/libkernel/Semaphore/src/Ksem.cpp:166.
Not verified
No tests or builds were run in this review. The author reports Windows and Linux CI success, but those runs were not independently inspected. files.json and any files it might list as excluded were not verified.
To get this to a good state
Nothing is required. Optional: guard ksem descriptor mapping in both dup2 paths on host replacement success.
What
dupof a ksem id,dup2from one andfcntl(F_DUPFD)on one threwduplicating a ksem id is not supported, a gap the libkernel debt file records. In FreeBSD 11.4'suipc_sem.ca ksem id is a descriptor whose file holds the semaphore, so a duplicate shares it. This closes that gap:dup,dup2andfcntl(F_DUPFD)map the new descriptor to the same semaphore (DuplicateKsemDescriptor), on both the Windows and the POSIX paths ofStdio.cpp.dup2over a ksem id still drops the old one first through the existing close notification.ksem_destroymarks the semaphore dead before closing its id, so the other descriptors fail withEINVAL, asksem_getdoes forKS_DEAD. The semaphore is freed when its last descriptor is closed (ksem_closef/ksem_drop).nsemsdoes: a duplicate takes no slot, and a destroyed semaphore keeps its slot until its last descriptor closes.IsKsemDescriptoris kept unchanged (a second commit restores it after the first removed it): fix(libkernel_sys): fail fpathconf with EOPNOTSUPP and fchdir with EINVAL on a ksem id, as FreeBSD 11.4 does #24484, fix(libkernel): fail read, write and seek on a ksem id as FreeBSD 11.4's ksem_ops does #24487, fix(libkernel): fail fsync, fstatfs, fchflags, futimes and flock on a ksem id as FreeBSD 11.4 does #24488, fix(libkernel): fail ioctl on a ksem id with ENOTTY, as FreeBSD 11.4 does #24489 and fix(libkernel): fail EVFILT_READ and EVFILT_WRITE on a ksem id with EINVAL, as FreeBSD 11.4 does #24490 call it, and a duplicated id answers it as the original does.fstatandfchmod, which fix(libkernel): answer fstat and fchmod on a ksem id as FreeBSD 11.4's ksem_stat and ksem_chmod do #24491 added for ksem descriptors, still reach a destroyed semaphore through its other descriptors (a third commit,FindOpen), as FreeBSD'sksem_statandksem_chmoddo not checkKS_DEAD; onlyksem_getdoes.ksem_post,ksem_getvalueandksem_destroyrecheck the dead mark once they hold the semaphore's lock (a fourth commit, from review), so an operation that found the semaphore just beforeksem_destroymarked it fails withEINVALinstead of going on; a wait on a zero count could otherwise block on a semaphore nothing can post any more.EINVALis what FreeBSD 11.4 gives when the destroy comes first.The ksem test's
Duplicatescase, which required the throw, now checks that posts and waits throughdup,fcntl(F_DUPFD)anddup2copies reach one semaphore thatfchmodthrough one copy shows infstatof another, before and afterksem_destroy, and that every copy failsksem_post,ksem_trywait,ksem_getvalueandksem_destroywithEINVALafter it. A newDestroyedAfterLookupcase destroys the semaphore right after each operation's lookup, through a hook that only the test build compiles in (ANYPS5_KSEM_TESTING, beside the existing waiter count), and requiresEINVALfromksem_post,ksem_trywait,ksem_timedwait,ksem_getvalueandksem_destroyon a duplicate. A newDuplicatesCountOncecase pins the slot counting. The debt fragment rewrites the existing entry without the gap.Tested
Commits ccfd949, b472e6d, 2480803 and 8105c2e on
mainb1ef52c, Release, in workflows on my fork: https://github.com/Dr-Coconut/AnyPS5/actions/runs/45123424265 (all four commits) and https://github.com/Dr-Coconut/AnyPS5/actions/runs/45036312458 (the first three, with the library restored tomain)windows-latest, image windows-2025-vs2026, WinLibs GCC 15.2.015.2.0posix-14.0.0-ucrt-r7) and Linux (GitHub-hostedubuntu-latest, image ubuntu-26.04, GCC 15.2.0, with the packagesrelease.ymlinstalls plusninja-build,libx11-devandlibxext-dev).guest_kernel_sys_ksempasses, and so doguest_dup,guest_kernel_fcntlandguest_kernel_web_forwards.Ksem.cpp, on both:guest_kernel_sys_ksemfails at line 324, theEINVALcheck ofDestroyedAfterLookup; the other three pass.Stdio.cpp,Ksem.cppandKsem.hpprestored tomainand the test of the first three commits kept, on both:guest_kernel_sys_ksemaborts withdup_nid_postfix: duplicating a ksem id is not supported; the other three pass. That run stops at the firstdup, so it does not show thefstatandfchmodchecks the third commit adds failing without it.Not run on macOS. No title tested.
tools/check_conventions.pypasses, andtools/debt_fold.py --checkaccepts the fragment.tools/pr_overlap.py --branchmerged the open pull requests that share files with this branch and reported #24487 and #24488, which add test cases at the end ofGuestKernelSysKsem.cppwhere this branch addsDuplicatesCountOnce, so they overlap textually. It could not compare 11 that conflict withmain, so I compared them by hand:Ksem.cpp,Ksem.hpp, the twodupthrows inStdio.cppand aDuplicatestest that requires the throw; none share duplicates. Whichever of feat(libkernel): implement the named ksem semaphores #9293 and this lands second needs that test case changed.dup2's validation and locking without touching ksem; feat(libkernel): report open, read and close notes on watched files #7121 adds close notes todup2; feat(libc): support archive-backed stdio reads #7447 only callsdupin a test; feat(libkernel): support SEEK_DATA and SEEK_HOLE in lseek #6936 changeslseek; feat(libkernel_sys): implement mount, unmount and nmount privilege checks #15037 changesfchflags. These overlap textually only.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)🤖 Generated with Claude Code