Skip to content

feat(libkernel): share a ksem semaphore across dup, dup2 and F_DUPFD, as FreeBSD 11.4 does - #22191

Merged
oneandonlydean merged 5 commits into
boykopovar:mainfrom
Dr-Coconut:feat/libkernel-ksem-shared-duplicates
Nov 26, 2026
Merged

oneandonlydean merged 5 commits into
boykopovar:mainfrom
Dr-Coconut:feat/libkernel-ksem-shared-duplicates

Conversation

@Dr-Coconut

@Dr-Coconut Dr-Coconut commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

What

dup of a ksem id, dup2 from one and fcntl(F_DUPFD) on one threw duplicating a ksem id is not supported, a gap the libkernel debt file records. In FreeBSD 11.4's uipc_sem.c a ksem id is a descriptor whose file holds the semaphore, so a duplicate shares it. This closes that gap:

The ksem test's Duplicates case, which required the throw, now checks that posts and waits through dup, fcntl(F_DUPFD) and dup2 copies reach one semaphore that fchmod through one copy shows in fstat of another, before and after ksem_destroy, and that every copy fails ksem_post, ksem_trywait, ksem_getvalue and ksem_destroy with EINVAL after it. A new DestroyedAfterLookup case 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 requires EINVAL from ksem_post, ksem_trywait, ksem_timedwait, ksem_getvalue and ksem_destroy on a duplicate. A new DuplicatesCountOnce case pins the slot counting. The debt fragment rewrites the existing entry without the gap.

Tested

Commits ccfd949, b472e6d, 2480803 and 8105c2e on main b1ef52c, 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 to main)

  • Windows (GitHub-hosted windows-latest, image windows-2025-vs2026, WinLibs GCC 15.2.0 15.2.0posix-14.0.0-ucrt-r7) and Linux (GitHub-hosted ubuntu-latest, image ubuntu-26.04, GCC 15.2.0, with the packages release.yml installs plus ninja-build, libx11-dev and libxext-dev).
  • With the change, on both: guest_kernel_sys_ksem passes, and so do guest_dup, guest_kernel_fcntl and guest_kernel_web_forwards.
  • With only the four rechecks of the fourth commit deleted from Ksem.cpp, on both: guest_kernel_sys_ksem fails at line 324, the EINVAL check of DestroyedAfterLookup; the other three pass.
  • With Stdio.cpp, Ksem.cpp and Ksem.hpp restored to main and the test of the first three commits kept, on both: guest_kernel_sys_ksem aborts with dup_nid_postfix: duplicating a ksem id is not supported; the other three pass. That run stops at the first dup, so it does not show the fstat and fchmod checks the third commit adds failing without it.

Not run on macOS. No title tested. tools/check_conventions.py passes, and tools/debt_fold.py --check accepts the fragment. tools/pr_overlap.py --branch merged the open pull requests that share files with this branch and reported #24487 and #24488, which add test cases at the end of GuestKernelSysKsem.cpp where this branch adds DuplicatesCountOnce, so they overlap textually. It could not compare 11 that conflict with main, so I compared them by hand:

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 and the licence notice of code adapted from upstream (see AGENTS.md)
  • 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
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes

🤖 Generated with Claude Code

@PrivacyOnion PrivacyOnion left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 7fba7a7138:

  • Conventions: tools/check_conventions.py passed.
  • Build: guest_kernel_sys_ksem_tests built 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.cpp reverted to main and the new tests kept, the suite fails:
    1/1 Test #938: guest_kernel_sys_ksem ............Subprocess aborted***Exception:   5.43 sec
    0% tests passed, 1 tests failed out of 1
    
    Restoring the change makes it pass again.
  • 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

@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

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.

Pull request Shared files not compared
PR 6936 core/libs/prx/libkernel/File/src/Stdio.cpp
PR 7121 core/libs/prx/libkernel/File/src/Stdio.cpp
PR 7447 core/libs/prx/libkernel/File/src/Stdio.cpp
PR 9293 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
PR 9297 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
PR 9302 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
PR 12682 core/libs/prx/libkernel/File/src/Stdio.cpp
PR 12688 core/libs/prx/libkernel/File/src/Stdio.cpp
PR 12700 core/libs/prx/libkernel/File/src/Stdio.cpp
PR 12965 core/libs/prx/libkernel/File/src/Stdio.cpp
PR 15037 core/libs/prx/libkernel/File/src/Stdio.cpp
PR 18190 core/libs/prx/libkernel/File/src/Stdio.cpp
core/libs/prx/libkernel/Semaphore/src/Ksem.cpp
PR 25468 core/libs/prx/libkernel/File/src/Stdio.cpp

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@Dr-Coconut

Copy link
Copy Markdown
Contributor Author

Pushed e186493, which keeps IsKsemDescriptor instead of removing it.

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 Kqueue.cpp:331: 'IsKsemDescriptor' was not declared in this scope. With e186493, the library files #24484, #24489 and #24490 change compile after merging each of them into this branch (WinLibs GCC 15.2.0). #24487 and #24488 conflict with this branch only in GuestKernelSysKsem.cpp.

The function is unchanged from main. A descriptor made by dup, dup2 or F_DUPFD is in the same table, so those checks see it as a ksem id too, as FreeBSD's ksem_ops applies to every descriptor of the file.

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@ycbuzi

ycbuzi commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Tested e1864939b3 merged into main, with the whole ctest suite on each machine below. Nothing fails that does not also fail on main on the same machine.

  • Windows Server 2022 (GitHub-hosted runner), full build, WinLibs GCC 15.2.0: 99% tests passed, 2 tests failed out of 6619; 99% tests passed, 4 tests failed out of 6619. 2 of the failing tests fail on main too. run
  • Windows Server 2025 (GitHub-hosted runner), full build, WinLibs GCC 15.2.0: 100% tests passed, 0 tests failed out of 6619; 100% tests passed, 0 tests failed out of 6619. run

AI-assisted: yes (Claude Code); the runs are automated, this summary was written from their reports.

@github-actions github-actions Bot added the needs rebase Conflicts with main, rebase needed label Nov 22, 2026
Dr-Coconut and others added 3 commits November 22, 2026 19:33
… 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>
@Dr-Coconut

Copy link
Copy Markdown
Contributor Author

Rebased onto main b1ef52c and pushed a third commit, 2480803.

#24491 merged in the meantime and added KsemStat and KsemChangeMode, which look the semaphore up with Find. On this branch Find hides a semaphore that ksem_destroy marked dead, so after the rebase fstat or fchmod on a dup of a destroyed semaphore fell through to the host's null device. FreeBSD 11.4's ksem_stat and ksem_chmod do not check KS_DEAD (only ksem_get does), so the new commit has them look up any open descriptor (FindOpen). The Duplicates test now also checks fchmod through one copy against fstat of another, before and after ksem_destroy.

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 dup, so it does not exercise the new fstat and fchmod checks on their own; the description says so.

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: Find checks dead before the operation acquires ksem->lock, but operations do not check it again under that lock. If an operation obtains the shared pointer and pauses, ksem_destroy can set dead and release the lock first; the operation can then proceed on the destroyed semaphore. A wait with count zero can block indefinitely instead of returning EINVAL. Check dead while holding the semaphore lock in operations that use the semaphore, including Wait.

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>
@Dr-Coconut

Copy link
Copy Markdown
Contributor Author

@MarcZX10 thanks, addressed in 8105c2e.

The waits, ksem_post, ksem_getvalue and ksem_destroy now check dead again once they hold ksem->lock and fail with EINVAL if it is set. ksem_destroy sets the mark under that lock only when there are no waiters, so once it has, no operation proceeds on the semaphore and no wait can start on it. FreeBSD 11.4's kern_sem_wait has the same window (ksem_get checks KS_DEAD before taking sem_lock, and nothing checks it after), but EINVAL is also what it returns when the destroy comes first, so the recheck only picks the outcome that cannot block on a dead semaphore.

For coverage, DestroyedAfterLookup uses a hook that only the test build compiles in (ANYPS5_KSEM_TESTING, like KsemWaiterCountForTests): it runs once right after the lookup in Find and destroys the semaphore there, so each of ksem_post, ksem_trywait, ksem_timedwait, ksem_getvalue and ksem_destroy on a duplicate hits the race deterministically and must fail with EINVAL.

Run on Windows and Linux: https://github.com/Dr-Coconut/AnyPS5/actions/runs/45123424265. With the change, guest_kernel_sys_ksem and the three controls pass. With only the four rechecks deleted (sed in the workflow), guest_kernel_sys_ksem fails at line 324, the EINVAL check of the new case, and the controls pass.

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@Helldiverr

Copy link
Copy Markdown
Contributor

Works on Windows at head 8105c2e044. guest_kernel_sys_ksem passes in 3 of 3 runs, and with main's Stdio.cpp it aborts at the first dup. Six of the seven mutations below are caught. A probe also covers a case the tests leave out: fcntl(F_DUPFD) with a start above the next free descriptor. On Windows that call goes through the dup loop in File::DuplicateFrom, and it works here. One point to weigh, not blocking: the test's F_DUPFD call (GuestKernelSysKsem.cpp:278) uses start 0, so on Windows it never closes the lower copies. The probe shows that this path relies on the mapping in dup (mutation m7), so a test case with a higher start would pin it.

Existing runs. 5 reviews, 5 comments, no inline comments.

  • The author, Dr-Coconut:
    • PR description: commits ccfd949732, b472e6d1b1, 248080360b and 8105c2e044 on main b1ef52c45e, Release, in workflows on the author's fork. Windows (GitHub-hosted windows-latest, WinLibs GCC 15.2.0) and Linux (GitHub-hosted ubuntu-latest, GCC 15.2.0). guest_kernel_sys_ksem, guest_dup, guest_kernel_fcntl and guest_kernel_web_forwards pass. With only the four rechecks deleted, guest_kernel_sys_ksem fails at line 324. With Stdio.cpp, Ksem.cpp and Ksem.hpp restored to main, it aborts at the first dup. The description notes that this run does not show the fstat and fchmod checks failing on their own. check_conventions and debt_fold --check pass.
    • 3 comments. 11-21: e1864939b3 keeps IsKsemDescriptor, because five other open PRs call it. 11-22: rebase onto main b1ef52c45e and 248080360b, which adds FindOpen for fstat and fchmod (fork run 45036312458). 11-23: 8105c2e044 rechecks the dead mark under the semaphore lock, with the DestroyedAfterLookup hook (fork run 45123424265).
  • PrivacyOnion, 1 review, APPROVED at 7fba7a7138. Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release): guest_kernel_sys_ksem passed. Negative control: with Stdio.cpp, Ksem.hpp and Ksem.cpp reverted to main and the new tests kept, the test aborted.
  • MarcZX10, 4 reviews, none with a build or test run: APPROVED at 7fba7a7138; COMMENTED at e1864939b3, no findings; CHANGES_REQUESTED at 248080360b, asking for the dead mark to be rechecked under ksem->lock; APPROVED at 8105c2e044, no findings.
  • ycbuzi, 1 comment: an automated test report at the old head e1864939b3, full ctest on GitHub-hosted Windows Server 2022 and 2025 runners. Nothing failed that does not also fail on main.
  • github-actions, 1 pr-overlap comment: PRs 24487 and 24488 touch GuestKernelSysKsem.cpp (line 376 on main at the time). The comparison with 12 other PRs that share Stdio.cpp or the ksem files could not be completed.
  • CI at 8105c2e044: windows, eligibility, library-portability, report and pr pass. conventions and labels each have one passing run and one cancelled run. linux, relinker, relinker-asan, write-watch, edge-watch, register-context and pipe-write are skipped.
  • No local Windows run has been posted at 8105c2e044. The author's Windows runs are on GitHub-hosted runners.

What this run adds.

  • A local Windows run at head 8105c2e044, not on a GitHub-hosted runner.
  • 160 libkernel descriptor, ksem and semaphore tests, on main and 3 times on the merge.
  • A negative control and 7 mutations, one of them the same as the author's recheck check. One mutation survives.
  • A probe covering F_DUPFD with a high start, a waiter blocked through a copy, a destroy racing with operations on a copy, dup2 over a shared id, and the semaphore count afterwards.

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 main 5ae28f2373.

  • Ksem.cpp:
    • Find (line 72) hides a semaphore marked dead (line 78). FindOpen (line 87), used by KsemStat (line 174) and KsemChangeMode (line 189), does not.
    • Wait (line 118), ksem_post, ksem_getvalue and ksem_destroy check the mark again under ksem->lock (lines 122, 242, 273 and 286).
    • ksem_destroy returns EBUSY while there are waiters (line 287). Otherwise it sets the mark (line 288) and closes only the id it was given (line 290). The other copies stay open until they are closed, and DescriptorClosed (line 108) erases each one from g_ksems.
    • SemaphoreCount (line 94) counts distinct semaphores, and ksem_init uses it against SemMax (line 229).
    • DuplicateKsemDescriptor (line 163) maps the new descriptor to the same semaphore.
  • Stdio.cpp:
    • dup (line 1078) calls DuplicateKsemDescriptor at line 1089.
    • dup2 (line 1105) calls it at line 1145 on Windows and at line 1164 on POSIX. Before that, both paths call EqueueDescriptorClosed(to) (lines 1127 and 1158), which drops the old mapping of to.
    • File::DuplicateFrom (line 898) calls it only on the POSIX path (line 911). On Windows, the loop calls dup until the result is at least start (line 904), then closes the lower copies (line 906). So on Windows, F_DUPFD depends on line 1089 and on the close notification. The probe and m7 below show both.
  • On main 5ae28f2373, fcntl with F_DUPFD calls DuplicateFrom (DescriptorControl.cpp:517), and F_DUP2FD calls dup2 (DescriptorControl.cpp:523).
  • Derived, not measured: m6 survives because each operation that uses Find rechecks the mark under the lock. So the check in Find only returns early. The one caller without a recheck is the test-only KsemWaiterCountForTests_nid_no_patch (line 199).
  • Debt: the fragment feat-libkernel-ksem-shared-duplicates.md rewrites the existing entry without the gap. debt_fold --check passes.

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.

Row Change guest_kernel_sys_ksem Other 8 tests Probe
n0 Stdio.cpp restored to main aborts, dup_nid_postfix: duplicating a ksem id is not supported pass every case throws at the first dup
m1 the four rechecks under ksem->lock deleted (as in the description) fails, line 324 pass same as the merge
m2 ksem_init compares g_ksems.size() with SemMax fails, line 335 pass same as the merge
m3 KsemStat and KsemChangeMode use Find instead of FindOpen fails, line 288 pass same as the merge
m4 ksem_destroy does not set the dead mark fails, line 291 pass times out at 60 s with no output
m5 Windows dup2 without DuplicateKsemDescriptor fails, line 55 pass dup2 case: the target is no longer a semaphore
m6 Find does not check the dead mark passes pass same as the merge
m7 dup without DuplicateKsemDescriptor fails, line 276 pass F_DUPFD, waiter and dup2 cases fail with EINVAL; the race worker gets EINVAL on its first operation
  • The 8 other tests are guest_kernel_sys_dup, guest_dup, guest_kernel_fcntl, guest_kernel_fcntl_sync, guest_kernel_web_forwards, guest_kqueue, guest_kernel_semaphore_trywait_bounds and guest_semaphore.
  • m3 fails at the fchmod through a copy after ksem_destroy (line 288). The author's negative control could not reach that check.
  • m5 fails inside the Value helper (line 55), at its ksem_getvalue check.
  • m4: derived from the probe code, not traced. The race case stops its worker only on EINVAL. Without the mark, the copy stays live, so the worker never stops. The probe's output was buffered and lost when it was killed.
  • m1 shows that the race case of the probe does not hit the window the rechecks close. Only the hook in DestroyedAfterLookup does.

Probes. One extra test executable, gpu_c_ksem_probe, built with ANYPS5_KSEM_TESTING and registered in core/libs/CMakeLists.txt for this run only. The probe ran once on main and 3 times on the merge. Error values are guest errno (16 EBUSY, 22 EINVAL).

Case main 5ae28f2373 Merge, each of 3 runs
fcntl(id, F_DUPFD, id + 12), id 3 throws returns 15; 2 ksem descriptors in 0 to 30; a post through 15 is seen through 3 (value 3 to 4)
A thread blocked in ksem_wait on a dup copy throws at dup waiter count 1; ksem_destroy through the id and through the copy return EBUSY; a post through the id wakes the waiter; then destroy through the copy succeeds, ksem_post on the id gives EINVAL, and close on the id succeeds
50 rounds: a thread posts, try-waits and waits 1 ms on a copy while the main thread destroys the id, retrying on EBUSY throws at dup 50 rounds; 2269 to 2301 operations; 92,366 to 103,137 EBUSY retries in total; 0 unexpected results; after each destroy, post, trywait and timedwait on the copy all give EINVAL
b (value 7) has a copy c; dup2(a, b) with a at value 1 throws at dup b reads 1 and c reads 7. Destroy through c succeeds, and b still posts. Destroy through b succeeds, then ksem_post(a) gives EINVAL
ksem descriptors left in 0 to 4095, then how many ksem_init calls succeed 5 left, 25 created 0 left, 30 created
  • On main, each case leaks the semaphores it made before the throw, which is why 5 are left.
  • The F_DUPFD row checks the Windows loop: the lower copies are closed and their mappings dropped, so only 3 and 15 remain.
  • The race counts are totals over the 50 rounds of one run. Other builds and tests were running on the machine.

Tests.

  • Selection: ^(guest_kernel_|guest_dup|guest_kqueue|guest_semaphore|guest_posix_spawn|guest_select|guest_poll|guest_fcntl|guest_file_), 160 tests, without the probe.
  • main 5ae28f2373: 158/160. Merge: 158/160 in runs 1 and 3, and 157/160 in run 2.
    • In every run, guest_semaphore_trace and guest_kernel_batch_map_guest_pointers did not run, because my target list did not build semaphore_trace_tests and guest_kernel_batch_map_guest_pointers.
    • In merge run 2, guest_file_lock_process timed out at 20 s with no output. That run took 23.5 s in total, against 6 to 11 s for the other runs.
    • I then built those executables and ran these 3 tests 3 times on main and 3 times on the merge. All 3 passed in each of the 6 runs.
    • In every run, 6 guest_kernel_sys_paths_* symlink tests skip with Windows symbolic-link privileges unavailable.
  • The PR changes guest_kernel_sys_ksem and adds no test executable, so the count is the same on both trees.
  • No build warnings on main or on the merge.
  • tools/check_conventions.py --base 5ae28f2373: all checks passed (rc=0).
  • debt_fold --check: rc=0, no output.

Host.

  • CPU: AMD Ryzen 9 9950X3D. GPU: AMD Radeon AI PRO R9700 (not used by these tests).
  • OS: Windows 11 Pro 26300.
  • Toolchain: WinLibs GCC 15.2, Ninja, Release.
  • Commits: head 8105c2e044 merged onto main 5ae28f2373 as a9724a0b87 (tree 9125312142). The mutation runs and the extra runs used re-merges with the same tree.

AI-assisted: yes

# Conflicts:
#	core/libs/tests/GuestKernelSysKsem.cpp

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 dup2 paths, DuplicateKsemDescriptor(from, to) runs after the host duplication call without checking that it succeeded. The helper unconditionally assigns g_ksems[to], so a failed host duplication can overwrite an existing ksem mapping while to still 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. See core/libs/prx/libkernel/File/src/Stdio.cpp:1154 and core/libs/prx/libkernel/File/src/Stdio.cpp:1173, and helper core/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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants