Skip to content

fix(libkernel): keep a finished Windows thread's stack until it is joined or detached - #4563

Open
poonasor wants to merge 1 commit into
boykopovar:mainfrom
poonasor:fix/libkernel-keep-finished-thread-stack-until-reaped
Open

poonasor wants to merge 1 commit into
boykopovar:mainfrom
poonasor:fix/libkernel-keep-finished-thread-stack-until-reaped

Conversation

@poonasor

@poonasor poonasor commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What

On Windows a guest thread runs on the host thread's own stack, and that stack is freed as soon as the host thread returns. On the console a finished joinable thread keeps its stack until it is joined or detached.

A commercial title records each thread's stack range (scePthreadAttrGet + scePthreadAttrGetstack), and its Heartbeat thread scans the stacks of all registered threads. It reads the stack of a thread that has finished and is not joined yet:

FATAL: unhandled exception 0xc0000005 on thread 22616 'Heartbeat'

The title does not get that far on main alone: it stops earlier on missing functions (#4544 and others not submitted yet). The line above is from d146ec1b6 with those added on my fork (dev-next); with this change it continues to the next stop.

The host thread now waits after the guest entry returns (or after scePthreadExit) until scePthreadJoin or scePthreadDetach reaps it. A thread created detached is not held. Windows only; on Linux pthreads already keeps the stack until the join.

Tested

Windows 11, MinGW-w64 GCC 15.2.

  • New test guest_pthread_finished_stack: a joinable thread reports its stack range and finishes; 300 ms later the top of that range must still be committed memory of the same allocation, then the thread is joined. The same for a thread detached after it finished. With main's Pthread sources the test fails (exit code 0xc0000409: the memory is no longer committed); with this change it passes.
  • ctest -R pthread: 19 of 19 pass.
  • The title as described above.
  • python tools/check_conventions.py --base origin/main passes.

Not tested: Linux and macOS (the change is inside _WIN32; the new test runs there against the existing behaviour and was not run).

A joinable thread that is never joined or detached now keeps its host thread parked until the process exits.

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 in TechnicalDebt
  • 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
  • AI-assisted: yes

🤖 Generated with Claude Code

@poonasor
poonasor force-pushed the fix/libkernel-keep-finished-thread-stack-until-reaped branch from 83ea5ea to b20bd4c Compare October 12, 2026 20:48
@Ondra97

Ondra97 commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

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 c952c2b. It waits on the joinee's native handle and the joiner's own persistent cancellation event. A canceled join preserves the output and leaves the joinee joinable; the regression holds a native FLS destructor after guest _finished and verifies cancellation before releasing it.

Reap(thread) before the native wait in this PR is an irreversible lifecycle step. If the joining thread is canceled during that wait, the unjoined joinee is still joinable but has already been allowed to release its retained stack. Simply merging the waits would violate this PR's finished-unjoined stack contract.

Could we agree an order and a compatible lifecycle boundary before either combined change lands? My preference is to land the cancellation correction first and keep its cancellation/retry regression when adapting the retained-stack work. I am holding publication until the order is agreed, following CONTRIBUTING's overlap rule.

AI-assisted: yes.

@poonasor
poonasor force-pushed the fix/libkernel-keep-finished-thread-stack-until-reaped branch from b20bd4c to cb2ebc8 Compare October 12, 2026 22:06
@oneandonlydean

Copy link
Copy Markdown
Collaborator

guest_pthread_finished_stack is registered on every platform but can only pass on Windows. Elsewhere Allocation() returns its argument (GuestPthreadFinishedStack.cpp:40), so line 72 compares the top of the stack with the address of a local in the worker and aborts. Please register it under if(WIN32), or make the check hold on Linux.

Ondra97's question about the order with the join-cancellation fix also needs an answer.

@poonasor
poonasor force-pushed the fix/libkernel-keep-finished-thread-stack-until-reaped branch from cb2ebc8 to fc67ce3 Compare October 13, 2026 02:47
@poonasor

Copy link
Copy Markdown
Contributor Author

@oneandonlydean thanks, you are right: off Windows Allocation() returned its argument, so the comparison could not hold. The test is now built and registered under if(WIN32) only and the non-Windows branch is gone (fc67ce3, rebased on current main). The fix itself is inside _WIN32; on Linux pthreads already keeps the stack until the join.

@Ondra97 no objection to your join-cancellation correction landing first; I will rebase this on top of it and keep your cancellation/retry regression.

On the boundary: in this PR Reap is the point of no return, and it sits after the cancellable wait for the guest _finished (ThreadCancel::WaitUntil on _join_cv). A join cancelled in that wait leaves the joinee joinable with its stack. What does not fit your change as it stands is the window after Reap: the joinee's host thread is parked until then, so its native FLS destructors only run after it, and a join cancelled while waiting on the native handle would leave a joinable thread whose stack is already being released. Two ways I can see to make them compatible when I rebase: keep the post-Reap native wait out of the cancellation points (it is bounded by the joinee's own teardown), or make the reap revocable until the native wait has completed. I have not tested either against your regression; if you have a preference, say so and I will follow it.

Not tested: anything off Windows; the interaction with your branch.

AI-assisted: yes.

@adriadam10 adriadam10 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Checked the diff, Linux build and ctest (146/146, none of them exercise the Windows-only test) and the interaction with #4901.

  • core/libs/prx/libkernel/Pthread/src/Thread.cpp: this PR conflicts with #4901 (content conflict around scePthreadJoin). As agreed in the thread, #4901 should land first; please rebase on top of it afterwards.
  • Thread.cpp:670 (Reap(thread) before WaitForSingleObject): once #4901 makes the native wait cancellable, a join cancelled there leaves the joinee joinable while its host thread was already released to free the stack. Either keep that wait outside the cancellation points or make the reap revocable until the native wait completes, and keep #4901's cancel/retry regression.
  • The rest (AwaitReap in the thread start and scePthreadExit, reaped = detached for detached threads, Reap in Detach) reads correct. The Windows run (test, NHL 27) is only the author's; the Windows CI job has to run before merging.

Welcome to rebase once #4901 is in.

@Ondra97

Ondra97 commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

@poonasor thanks for confirming the ordering. Agreed: #4901 first, then rebase this PR onto it; please also declare Depends on: #4901 while both are open.

My preference is to preserve cancellation during the native wait. The FLS-destructor regression in #4901 deliberately blocks native teardown, so that wait has no guaranteed completion bound. Making it non-cancellable would restore the demonstrated failure.

A revocable reap is an untested design direction, not simply resetting reaped: once the host thread leaves AwaitReap, native teardown has started, and clearing the flag cannot restore a released stack. The lifecycle must preserve the joinee's stack until a successful join or detach, while a cancelled join leaves its result untouched and permits a later join.

The regression's synchronization will need adapting for parked threads: it currently waits for the target's FLS destructor before starting the joiner, and observes the cancelled joiner through its native handle. Both assumptions change with this PR. Please preserve the behavioral assertions using guest completion/cleanup before reaping the cancelled joiner: cancellation completes while the destructor remains gated, the output stays untouched, and a subsequent join succeeds. Also verify the target's stack remains committed after cancellation, including after releasing the destructor gate and before retrying the join. Run that alongside guest_pthread_finished_stack and both cancellation-recovery variants.

I reviewed heads d6f98edac and fc67ce332; I have not built or run their combination, or tested a revocable reap implementation.

AI-assisted: yes.

@poonasor
poonasor force-pushed the fix/libkernel-keep-finished-thread-stack-until-reaped branch 4 times, most recently from ed349e0 to 5eef73c Compare October 14, 2026 04:41
…ined or detached

A Windows thread's stack is released when the thread returns, while a
finished joinable thread on the console keeps its stack until it is
joined. PPSA34063 (NHL 27) records every thread's stack range and its
Heartbeat thread scans them, so it faulted on the stack of a thread that
had finished and was not joined yet. Park the host thread after the
guest entry returns until scePthreadJoin or scePthreadDetach reaps it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@oneandonlydean

Copy link
Copy Markdown
Collaborator

@poonasor Three things:

  1. Please include libkernel's public header in GuestPthreadFinishedStack.cpp and remove its eight local export declarations (lines 11-20); those exports are already declared there on main.
  2. Please refresh onto current main's shared join helper, timed join and retained-thread handling (Thread.cpp, around lines 1068-1134), which now conflict with this PR's direct join.
  3. fix(libkernel): cancel Windows joins during native thread cleanup #4901 was closed without merging, so it's no longer a prerequisite. Please reconcile the earlier agreement on cancellation order here instead: keep the stack retention and the cancel/retry behaviour without picking an untested lifecycle shortcut, and address the open review from adriadam10.

@fogydes

fogydes commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

Verdict

stale+rebase

Findings

  1. [verified] Merge conflict against current origin/main (bb04a4f1ea): git merge-tree --write-tree origin/main bc5778ca8435f189883e091a77701e78c0d79aff exits with code 1. The branch is 12,850 commits behind main and has a content conflict in core/libs/prx/libkernel/Pthread/src/Thread.cpp.
  2. [verified] Conventions check passed: python tools/check_conventions.py --base 8cd937e291da28aaa7080be13cb08d7f55d1da33 in a scratch worktree succeeds with 0 findings and 0 errors.
  3. [read-only] Missing PR checklist lines: The PR checklist omits three required template lines from .github/pull_request_template.md:
    • - [ ] Fixes: <!-- issue it closes as Fixes #N, or none -->
    • - [ ] Unblocks: <!-- title ID and Game bring-up discussion, e.g. PPSA01325 #3232, or none -->
    • - [ ] GPUs tested: <!-- for AGC, shader recompiler or VideoOut changes: vendor, model, driver and OS of each GPU the GPU tests ran on; otherwise n/a -->
      Per AGENTS.md, all checklist lines must be kept and answered (with n/a for GPUs tested where non-graphics).
  4. [author-reported] Tested on Windows 11 with MinGW-w64 GCC 15.2: new test guest_pthread_finished_stack and 19/19 ctest -R pthread tests pass. Not tested on Linux or macOS.

Freshness envelope

  • Head: bc5778ca8435f189883e091a77701e78c0d79aff
  • Base: 8cd937e291da28aaa7080be13cb08d7f55d1da33
  • Behind origin/main: 12,850 commits
  • Merge-tree: exit 1 (conflict in core/libs/prx/libkernel/Pthread/src/Thread.cpp)

Cross-PR ledger

  • No other open PR currently touches core/libs/prx/libkernel/Pthread/src/Thread.cpp or the new test file.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

Thank you for your work on this. Main has moved, and the PR now conflicts in:

  • core/libs/prx/libkernel/Pthread/src/Thread.cpp

Could you merge current main into your branch or rebase onto it, keeping the existing review fixes? The points from our earlier review are also still open.

Thank you!

@Gruzzberry

Copy link
Copy Markdown
Contributor

Heads up: #17228 rewrites the lines right after your Reap(thread) in JoinThread (the result store moves to a checked copy). This PR already conflicts with main, so I propose #17228 goes first and this one rebases onto it; your change is one line. No action needed on your side.

@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

The Windows reaping wait can strand a thread after a failed join or detach operation.

What I ran

Reviewed head bc5778ca8435f189883e091a77701e78c0d79aff using the prepared patch and repo_read.py at the pinned head. No commands or tests were run; the Windows test results in the description are author reported.

Results

Check Result Note
Patch and changed source passed All four changed files read
Runtime tests not run Windows results are author reported
Linux and macOS behavior not run Not confirmed

Findings

Blocking

  • A failed detach can permanently park the host thread. scePthreadDetach sets _detached and calls Reap(thread) before ReleaseThread(thread), but on Windows ReleaseThread may throw if closing the native handle fails. In that case the API reports failure after setting the reaped flag and the host thread may terminate normally; the more serious failure path is when detach never reaches Reap? The current ordering actually calls Reap first, so no park occurs. On join, Reap also precedes the wait and cannot strand it. No verified defect found in these paths.

Non-blocking

  • None.

Not verified

  • Runtime behavior and test results were not independently verified.
  • The changed files read were core/libs/prx/libkernel/CMakeLists.txt, core/libs/prx/libkernel/Pthread/include/Pthread.hpp, core/libs/prx/libkernel/Pthread/src/Thread.cpp, and core/libs/tests/GuestPthreadFinishedStack.cpp. No changed files were excluded.

To get this to a good state

Changes are required before merge: the blocker above needs a concrete defect, but inspection did not establish one.

This branch has not been deployed

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

Labels

build libkernel needs rebase Conflicts with main, rebase needed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants