fix(libkernel): answer a second scePthreadJoin with ESRCH #4481
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/4481"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from boykopovar/AnyPS5. Originally posted by Roojool on 2026-10-12T13:12:33Z.
What
A second
scePthreadJoinon the same thread now returnsESRCH(0x80020003) instead of reading freed memory.On a PS5 (firmware 13.60)
scePthreadJoinanswersESRCHfor a thread that was already joined — measured by #4160's author and recorded in its TechnicalDebt entry: "here a joined thread is released, so a second join reads freed memory". #4160 deliberately left that follow-up: keeping the thread for the second answer needs the thread lifetime to change. This is that change:ESRCH.scePthreadCreatepublishes over the same guest handle storage, so a create/join loop over one storage holds one object;libSceJobManagerandlibSceUltjoin patterns are covered.scePthreadDetachon a joined thread answersEINVAL, as FreeBSD does on a thread that is not joinable; the console answer for a detach after a join is unverified. It is required so the retained object is not released twice. Recorded in TechnicalDebt.PosixThread::ToErrnoalready maps0x80020003to3, FreeBSD'sESRCHfor a deadpthread_t; the test pins it.EDEADLK, join-after-detach/detach-twiceEINVAL, the zeroed attribute — all already correct since #4160.Tested
guest_pthread_second_join: create -> join 0 (retval read) -> second join0x80020003with*retvaluntouched -> detach0x80020016-> posixpthread_join3 -> 64 create/join/second-join rounds over the same storage (recycle path) -> join-after-detach and detach-twiceEINVAL.main(9aa5fd290): the test fails 3/3 on Windows (abort0xc0000409, freednativeHandle) and 2/2 on WSL Linux (SIGSEGV) — the use-after-free.Thread.cppwith this PR's test) crashes 4/4 runs — SIGSEGV, exit 139, backtrace intoscePthreadJoin— and the head passes 5/5; the 42 neighbouring thread tests pass at the head.guest_pthread_join_self, pthread/thread/cond/sem/ult/ampr/libc/signals/cpumask suites); WSL2 Linux (g++ 15.2.0, Release, -j4) 17/17 including the new test.python tools/check_conventions.py --base 9aa5fd290passes.Checklist
main; no other open PR implements the same functions.mdfiles or images added to the repositoryConsole semantics are #4160's author's measurements on PS5 firmware 13.60; no console was run for this change. Residuals (a guest that joins into a fresh storage location every time retains those objects; joining a detached handle after it ended; a handle value copied to a second storage and joined there after a recycle) are recorded in TechnicalDebt.
Imported from boykopovar/AnyPS5. Originally posted by copilot-pull-request-reviewer[bot] on 2026-10-12T13:12:40Z.
Review: COMMENTED
Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.
Imported from boykopovar/AnyPS5. Originally posted by Dextroid17 on 2026-10-12T16:00:47Z.
Review: COMMENTED
The control crashes, and the backtrace localises it — a second join dereferences the released object rather than merely failing. Head
dc30882e1, parent33ae282e4, in a worktree:That turns the debt entry from a description into a measured crash, and it is the strongest single line available to the body. Isolation check: the neighbouring thread targets are clean at the head —
ctest -R 'guest_(pthread|thread|cond|sem|semaphore|posix_sem|libc_threads|ult|ampr_threads)'is 100% tests passed out of 42.Smaller points:
docs/dev/TechnicalDebt.md:487comes from #4160 (0b7e4ddf9) and says a second join returnsESRCH(0x80020003) on a PS5 (firmware 13.60). The clause this PR replaces — "here a joined thread is released, so a second join reads freed memory" — is the parent revision's line 487, so the debt change reads best as a rewrite of that one sentence, which is what it does.EINVAL: the accurate version is the hedge the debt line already uses. FreeBSD'spthread_detachreturns it for a thread that is not joinable —THR_FLAGS_DETACHEDset orpthread->joiner != NULL(lib/libthr/thread/thr_detach.c:55-59) — and a completedpthread_joinitself setsTHR_FLAGS_DETACHEDand collects the thread (thr_join.c:141-143), whilepthread->joinercovers only an in-flight joiner (a concurrent second joiner getsENOTSUP,thr_join.c:96-98). Reading the citation as "FreeBSD's answer for a joined thread" puts the weight on the clause that does not apply to a finished join._joinedis astd::atomic<bool>, probed withload(acquire)atThread.cpp:653and taken withexchange(true, acq_rel)at:660, both loser paths returningSCE_KERNEL_ERROR_ESRCHbefore the retval store at:664/:668— and the test pins that (GuestPthreadSecondJoin.cpp:41-42, again at:45and:62).joinedThreadsas keyed by the address of the guest handle slot (_handleStorage, withusing Pthread = PthreadPrivate*), released only byRecycleJoinedThreadcalled fromscePthreadCreate— which matches what you and the debt line describe, so the open item is the third residual rather than the first. The body says all three residuals are recorded in TechnicalDebt, but only two are: on this head,grep -in "second storage\|handle value copied" docs/dev/TechnicalDebt.mdfinds nothing for "a handle value copied to a second storage and joined there after a recycle". It has a consequence worth recording: joining a copied handle retains the object under the original storage key (Thread.cpp:423), so a laterscePthreadCreateover that original storage callsReleaseThreadon an object the copy still points at — the same freed-memory read this PR removes, reachable through the copy. Either a debt line or aRequireinGuestPthreadSecondJoin.cppwould close it.Nit:
core/libs/tests/GuestPthreadSecondJoin.cpphas no trailing newline (\ No newline at end of file);tools/check_conventions.pydoes not flag it, but it stands out in a new file.Written with AI assistance.
Hermes Agent 🤖 at your service
Imported from boykopovar/AnyPS5. Originally posted by copilot-pull-request-reviewer[bot] on 2026-10-12T16:32:26Z.
Review: COMMENTED
Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.
Imported from boykopovar/AnyPS5. Originally posted by Roojool on 2026-10-12T16:40:05Z.
Thank you for the control run — quoting the measured crash into the PR body now.
Follow-ups pushed (head
57105ebfb):scePthreadCreateover that original storage releases an object the copy still points at, and the copy reads freed memory.GuestPthreadSecondJoin.cppends with a newline.EINVALwording in the PR body follows the debt line's hedge: FreeBSD'spthread_detachanswersEINVALfor a thread that is not joinable (THR_FLAGS_DETACHEDset or a joiner in flight); the console answer for a detach after a join is unverified.AI-assisted: yes.
Imported from boykopovar/AnyPS5. Originally posted by Dextroid17 on 2026-10-12T17:46:13Z.
All three follow-ups are in the head. Read at
57105ebfb— read, not rebuilt here.docs/dev/TechnicalDebt.md:487now ends: "a later scePthreadCreate over that original storage releases an object the copy still points at, and the copy reads freed memory". That is the clause whose absence I found on the previous head, and it is the one that closes the residual rather than describing it.EINVALwording is the hedged form the debt line already used: "as FreeBSD does on a thread that is not joinable; the console answer for a detach after a join is unverified."core/libs/tests/GuestPthreadSecondJoin.cppends with a newline now.Nothing else from me. The measured crash is the line I would keep at the top of the body — it is reproduceable from the parent's
Thread.cppplus this test alone, which is what makes the debt entry evidence rather than description.Written with AI assistance.
Imported from boykopovar/AnyPS5. Originally posted by copilot-pull-request-reviewer[bot] on 2026-10-12T19:13:18Z.
Review: COMMENTED
Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.
Imported from boykopovar/AnyPS5. Originally posted by Ondra97 on 2026-10-12T21:15:20Z.
Tested change: 20e5499ac. Full Release Windows build (MinGW GCC 15.2) exits 0 and 11/11 thread/TLS tests pass, including repeated native/adopted cancellation, event cleanup and handle-count checks. No game or console run.
I have a tested Windows native-join cancellation fix on main
c952c2b0e. It waits on the joinee's native handle and the joiner's own persistent cancellation event, preserving the return-value output and allowing the joinee to be joined later. The regression holds a native FLS destructor after guest _finished, requests cancellation only once the native wait is reached, and passes with the fix; the original code completes normally and overwrites the output.This overlaps the _joined.exchange(true) before the native wait in this PR: cancellation in that phase would leave the joinee permanently claimed and a retry would return ESRCH. The lifecycle needs a temporary join claim that rolls back on cancellation, or the final claim after the cancellable wait with appropriate concurrency handling. #4533 inherits this lifecycle.
Could we agree to land the cancellation correction first, then preserve its cancellation/retry regression while adapting this lifecycle work? Alternatively, please propose a sequence that keeps the canceled joinee joinable. I am holding publication until the order is agreed, following CONTRIBUTING's overlap rule.
AI-assisted: yes.
Imported from boykopovar/AnyPS5. Originally posted by Roojool on 2026-10-12T21:46:17Z.
Thank you for checking the interaction. I read your 20e5499ac change and agree that our _joined claim before the native wait needs to account for cancellation. Let's land your cancellation correction first. Once your PR is published, I will declare it as a dependency of #4481 and adapt the join lifecycle while preserving your canceled-join/retry regression. #4533 will then be restacked on the updated #4481. I have not tested the combined changes yet; the combined lifecycle will need Windows and Linux tests and an independent review before pushing.
AI-assisted: yes.
Imported from boykopovar/AnyPS5. Originally posted by Ondra97 on 2026-10-12T21:53:58Z.
Thanks for confirming the order. We are still waiting for the author's response on #4563, which also overlaps the native join lifecycle. Once the ordering is agreed there as well, we will publish our cancellation PR.
AI-assisted: yes.
Imported from boykopovar/AnyPS5. Originally posted by muhzain05 on 2026-10-12T23:17:54Z.
Hi @Roojool — I independently investigated the pthread handle-lifetime issue before seeing #4481, and I won't open a competing PR.
I found two additional cases that may be useful when adapting the join lifecycle after Ondra97's change:
scePthreadJoin(T)and another thread detaches T, Detach can release the ownership reference while J still waits on T's join condition variable. Source analysis indicates a possible use-after-free. FreeBSD libthr rejects this Detach withEINVAL, but I haven't verified the PS5 behavior.sceKernelRaiseExceptioncan fail to suspend a target that exits between validation andSuspendThread. I observed this in local stress testing. Detached targets also expose a separate lifetime issue.I have Windows-only regression tests and concurrency probes covering these scenarios, as well as concurrent joins and cancellation during Join. Happy to share the relevant tests if helpful.
No PS5 or Linux validation was performed.
AI-assisted: yes.
Imported from boykopovar/AnyPS5. Originally posted by Roojool on 2026-10-13T06:52:59Z.
Thank you for flagging both cases and for avoiding a competing PR. Please share the regression tests and concurrency probes, the exact base commit, and the Windows build/run commands with results or logs. The detach-during-join and cancellation/retry cases would be useful when adapting the lifecycle.
We have agreed to land Ondra97's cancellation correction first; publication is currently waiting for the overlapping #4563 ordering discussion. We have not validated your additional cases ourselves, and the PS5 detach-during-join behavior remains unverified. Please include the raise-during-exit probe too so that it can be assessed separately.
AI-assisted: yes.
Imported from boykopovar/AnyPS5. Originally posted by muhzain05 on 2026-10-13T08:03:23Z.
Thanks @Roojool! I’ll prepare the regression tests, concurrency probes, exact base SHA, and Windows build/run logs.
Would you prefer that I open a small PR against your branch with the tests, or share them as a standalone patch/gist?
I’m happy to contribute the tests directly if that makes integration easier, especially given the coordination with Ondra97 and #4563.
AI-assisted: yes.
Imported from boykopovar/AnyPS5. Originally posted by Roojool on 2026-10-13T09:22:19Z.
A patch or gist works best for now: this branch will be reworked once #4901's cancellation correction lands (ordering agreed upstream), so tests targeting today's head would need adaptation anyway. Share them standalone with your base SHA and run logs, and we will integrate them with your authorship preserved when the lifecycle update goes in. If a PR is easier for you, one against this branch is also fine — whichever you prefer.
Imported from boykopovar/AnyPS5. Originally posted by muhzain05 on 2026-10-13T11:31:15Z.
Thanks @Roojool! I've prepared the standalone regression tests and concurrency probes as requested.
Evidence package: https://gist.github.com/muhzain05/93cde195edd88b6e6f720f47f7de7dc2
The gist includes a
git ampatch (0001-…patch, with authorship preserved), standalone probes, Windows build/run commands, and logs.Base commit:
c13dc7e6b(also the base of #4901).Regression tests
guest_pthread_join_detachEINVAL, matching FreeBSD'sthr_detach.c:55-59.guest_pthread_join_cancel_retryPTHREAD_CANCELED, leaves its output untouched, and keeps the target joinable.Additional probes
--release-blockedis only safe with #4481's retention fix.Windows results
Environment: Windows 11, WinLibs GCC 15.2.0, Release.
a2dfbfd34).d6f98edac).ESRCH._finishedwas set, bypassing the export's earlier check."cannot suspend the target thread"occurred approximately once per 60,000–66,000 rounds.Correction to my earlier comment: The original exception I observed came from my local build with detached targets. On unmodified code with joinable targets, the failure is considerably rarer, as reported above.
Limitations
These tests are intended to complement the ongoing #4901 cancellation work and the subsequent #4481 lifecycle changes, rather than introduce a competing implementation.
Happy to help adapt the tests once the lifecycle changes land.
AI-assisted: yes.
Imported from boykopovar/AnyPS5. Originally posted by Roojool on 2026-10-14T05:19:15Z.
Thank you — the package is exactly what we asked for, and the
git ampatch with authorship preserved is the easiest form to integrate.Plan: the branch reworks when #4901's cancellation correction lands (ordering agreed upstream), and your regression tests for detach-during-join and cancellation/retry target that same rework — so we will fold your patch in there, on top of the integrated lifecycle, and credit you as author of those tests. The raise-during-exit probe will be assessed separately at the same time, as discussed.
The
needs rebaselabel is also being handled now: the branch is being rebased onto currentmainas a base-carry step, ahead of the #4901 integration.Imported from boykopovar/AnyPS5. Originally posted by copilot-pull-request-reviewer[bot] on 2026-10-14T05:29:38Z.
Review: COMMENTED
Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.
Imported from boykopovar/AnyPS5. Originally posted by Ondra97 on 2026-10-14T09:17:26Z.
Hi @Roojool — a heads-up regarding the plan to wait for #4901: our PR was closed without merging. The maintainer's closing comment asks us to hold PRs without a known affected title while the queue is high, and to reopen with a title ID and a log line showing the issue on current main.
The agreed sequence therefore needs revisiting: #4901 is currently closed, so there is no pending merge for #4481 to wait on. Could we align the next step with the maintainer before continuing on that assumption? The lifecycle adaptation still needs to preserve cancellation/retry behavior, including cancellation during native cleanup; compatibility of the combined changes has not been validated.
AI-assisted: yes — Codex.
Imported from boykopovar/AnyPS5. Originally posted by Roojool on 2026-10-14T10:45:08Z.
Thanks for the heads-up. With #4901 closed, the integration plan is shelved: this branch is rebased onto current main and stands on its own evidence — the console-measured second-join
ESRCHrecorded in TechnicalDebt, and the independently validated use-after-free (the review's control run: SIGSEGV 4/4 on the parent revision with this PR's test, 5/5 at the head).The cancellation interplay you designed remains recorded in the thread for whenever a lifecycle rework is wanted; muhzain05's regression tests for detach-during-join and cancellation/retry are likewise held for that moment.
Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-15T12:06:28Z.
Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.
main)core/libs/prx/libkernel/Pthread/include/Pthread.hppL142core/libs/prx/libkernel/Pthread/src/Thread.cppL792-793, L811-812docs/dev/debt/libkernel.mdL146Some 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.
core/libs/prx/libkernel/Pthread/src/Thread.cppcore/libs/prx/libkernel/CMakeLists.txtcore/libs/prx/libkernel/CMakeLists.txtcore/libs/prx/libkernel/Pthread/include/Pthread.hppcore/libs/prx/libkernel/Pthread/src/Thread.cppdocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/CMakeLists.txtdocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/CMakeLists.txtdocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/CMakeLists.txtcore/libs/prx/libkernel/CMakeLists.txtcore/libs/prx/libkernel/Pthread/include/Pthread.hppcore/libs/prx/libkernel/Pthread/src/Thread.cppdocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/CMakeLists.txtdocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/Pthread/src/Thread.cpp