fix(threads): run Windows pthread and small fiber stacks in guest VA range #7149
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/7149"
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 Pouare514 on 2026-10-17T14:00:50Z.
What
scePthreadCreatethreads now run their guest entry on aGuestArenastack:AllocateGuestStackviaDoMapAnon+Mprotectguard,FreeGuestStackon failure/exit, andCallOnGuestStackasm trampoline that swaps TEBStackBase/StackLimit/0x1478to the guest range for the entry (catch-and-rethrow) then restores host bounds.libSceFiber: small contexts (<64 KiB) now allocate fromGuestArenainstead of hostVirtualAlloc, sorsp-masking idioms resolve to mapped guest memory; large contexts unchanged.GuestPthreadStackasserts 9-digit (>= 0x100000000) guest address (GuestArena starts0x200000000, host <4 GiB).scePthreadSelf) and main threads still run on host stacks — main entry is covered by #3965.Tested
guest_pthread_stackfail-without (stash-abort: worker RSP0x2b0fbc0host) / pass-with (4/4 RunThread entries in guest range); neighbors pass:fiber,guest_memory,guest_pthread_start(4/4 on rebased tip, Release Ninja).0x1a54d81fault), 13NdJobWorkerThreadson guest stacks (0x1404xxbc80), Vulkan ready + swapchain 1472x828. Next wall is an unrelatedVideoOutbad_alloc.git diff --checkclean;python tools/check_conventions.py --base origin/main --head HEADpasses.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)Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-17T14:10:36Z.
Thanks for this, and for the TLOU coordination evidence on #3965. Review at 992ab94a8: one blocker before this can go further.
scePthreadExitand cancellation never reach the stack cleanup on Windows.StartNativeThread's restore-and-free only runs whenRunThreadreturns. On Windows,scePthreadExit(Thread.cpp, theReleaseThread(self); _endthreadex(0);branch) is called from inside the guest frames, and cancellation goes through the same path. So on every exit or cancel:FreeGuestStackisn't reached, andReleaseThreadmay deleteself, which drops the only pointer to it. The whole committed stack and its arena range stay mapped.StackBase/StackLimit/DeallocationStackstill describing the guest mapping. Windows frees a thread's own stack at exit throughDeallocationStack, so the real host stack likely leaks, and the OS may release the guest mapping behind GuestArena's back (the arena maps through placeholders, so that release could succeed and the arena would later try to replace a placeholder that's gone). This part we couldn't verify here, since our bench is Linux.Exit and cancel are common:
guest_pthread_cancel,guest_onceandguest_pthread_destructor_lifetimeall use them.Ask:
scePthreadExitleave through the same restore path: keep the host bounds where it can reach them (thread_local orPthreadPrivate) and restore them before_endthreadex.RetireGuestStack/ReapRetiredStacksdoes (keyed on the thread handle being signalled).scePthreadExitand N that are cancelled, then checks after join that each old guest stack is no longer committed (VirtualQuery), so process commit doesn't grow per thread.guest_pthread_cancel,guest_onceandguest_pthread_destructor_lifetimeon Windows; the PR lists fiber, guest_memory, guest_pthread_start and guest_pthread_stack.Non-blocking notes:
RtlCaptureStackBackTrace, debuggers) will stop or misread at that frame..seh_proc/.seh_pushreg/.seh_setframewould be cleaner._beginthreadexreservation. Fine for tens of threads; worth noting for titles with hundreds.Merge order with #6540, #7135 and #3965 is fine; the text merges cleanly and there's no semantic overlap.
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-17T14:15:31Z.
One addition to the exit/cancel ask above, from reviewing #3965 alongside this.
With #3965 the main thread also runs on a guest arena stack. If the main thread calls
scePthreadExitwhile workers are still running (the adopted main thread case), Windows goes_endthreadex->ExitThreadwith the TEB still on the guest allocation, the same class as the worker case here. Today main exits from the host stack, so this is new once #3965 lands.Since this PR owns
Thread.cpp, we'd suggest a single fix inscePthreadExit: restore the host bounds before_endthreadexwhenever the current stack is a registered guest stack (GuestStacksalready tracksRegistered/HostBounds), so it covers worker threads from this PR and the main thread from #3965. Please add a main-thread-exit case to the Windows test as well.Planned order: #6540 -> #7135 -> #7149 (with this fix) -> #3965.
Imported from boykopovar/AnyPS5. Originally posted by Pouare514 on 2026-10-18T00:51:32Z.
Fixed the blocker: Windows scePthreadExit now restores host TEB StackBase/Limit/DeallocationStack before _endthreadex and retires the guest mapping instead of freeing inline. Host bounds live in thread-local GuestThreadState (FLS), not PthreadPrivate, so they survive ReleaseThread(self) deleting self. Retire duplicates the thread HANDLE and unmaps once signalled, mirroring Linux Retire/Reap; cancellation goes through the same path. Adopted-main is covered by one check: if the frame is in a GuestStacks registered range, restore MainHostBounds (main restores only, no retire, process-lifetime; #3965 EnterGuestMainStack should call GuestStackNoteMainHostBounds before switching).
Test: GuestPthreadStack on Windows runs 4 scePthreadExit + 4 cancelled (64 KiB) + 1 adopted exit; after join VirtualQuery asserts each old guest low is no longer MEM_COMMIT.
Suites (Release Ninja, winlibs gcc15): fiber, guest_memory, guest_pthread_start (30s), guest_pthread_stack, guest_pthread_cancel, guest_once, guest_pthread_destructor_lifetime — 7/7 pass. Start first segfaulted in the trampoline (Detach retired while the worker had not read guestStack); Detach no longer retires.
SEH left out: the rsp-switch cannot be expressed, wrong directives would mislead more. Commit-upfront noted in debt. Merge order ack #6540 -> #7135 -> #7149 -> #3965; Depends on stays none (clean rebase onto
f1af6c591).Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-18T01:04:43Z.
Thanks, that resolves the blocker. scePthreadExit and cancellation now retire the guest stack, restore the host TEB bounds and then call _endthreadex, and the stack is unmapped once the thread handle is signalled. The new exit and cancel checks in GuestPthreadStack cover exactly the path that leaked before.
We're running full CI on 9c1ec7f533 now. The adopted-main check can wait for #3965, since the hook does nothing until #3965 calls GuestStackNoteMainHostBounds.
Imported from boykopovar/AnyPS5. Originally posted by Bonjourcestmatt on 2026-10-18T01:09:56Z.
Windows run of
9c1ec7f53merged ontomainf663e565f(alone, without #6540, #7135 or #3965). Two existing tests regress; both pass onmain.Setup: Windows 11, MinGW-w64 GCC 15.2.0 UCRT, full configure with submodules, Release,
cmake --build build -- -k 0,ctest -E "agc|Agc|vulkan|gpu|shader" -j6 --timeout 120.mainf663e565f(3 runs)9c1ec7f53onmainguest_kernel_stack_protect0xc0000409) in 3 of 3 runs (alone) and in the full runguest_pthread_startmainguest_pthread_stack(new)The rest of the non-GPU suite passes (744 of 746; the two failures are the ones above).
guest_kernel_stack_protect: the test printsGuestKernelStackProtect failed at line 101, which isRequire(memory.Protect == PAGE_NOACCESS && memory.RegionSize >= GuardBytes)aftermprotect_nid_postfix(guard, GuardBytes, 0)on a worker's stack. The worker now runs on aGuestArenamapping, so whatVirtualQueryreports for that range is not what the test expects from a host stack. I did not look into whether the test or the stack protection should change.guest_pthread_start: about 37 times slower (56 s against 1.5 s), which is also well past the 30 s per test the CI warns about. I did not find where the time goes.Not checked: Linux and macOS (the change is Windows-only), a title, and the combination with #6540, #7135 and #3965 that the plan above mentions. If the two tests only fail without those, that would explain it.
Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by Pouare514 on 2026-10-18T01:26:38Z.
Thanks for confirming. Standing by for the full CI results on 9c1ec7f - happy to address anything it turns up. And agreed on the adopted-main check waiting for #3965's GuestStackNoteMainHostBounds hook-up.
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-18T01:50:51Z.
Thanks @Bonjourcestmatt for the Windows run. Full CI on 9c1ec7f533 shows the same thing: Windows
guest_kernel_stack_protectaborts ("failed at line 101", 0xc0000409) and passes on current main.guest_pthread_startpassed in 28.3 s against 1.6 to 2.3 s on main. I traced both to the stacks now coming from the guest arena. There are three things to fix before this can merge.1. The guard check: the arena commits in 16 KiB pieces.
AllocateGuestStackmaps the stack withDoMapAnon. On Windows that ends inCommitArenaRange, which callsGuestArenaCommit_nid_postfix(..., PS5_PAGE_SIZE). InWindowsMappings, each 16 KiB granule replaces its own placeholder (MEM_REPLACE_PLACEHOLDER), so a 2 MiB stack is about 130 separate allocations.VirtualQuerynever reports a region across an allocation boundary. So after the test'smprotect(guard, 0x10000, PROT_NONE), every page really isPAGE_NOACCESS, butRegionSizeis 0x4000, andRegionSize >= GuardBytesfails. The protection works. The failure comes from the stack's layout. Either fix is fine:GuardBytes, requiring every region to bePAGE_NOACCESS.Please don't just drop the
RegionSizecondition. The test still needs to show that the whole 64 KiB is inaccessible.2. The pages below the reported stack can now be changed by the guest. This is the real regression, and the next asserts in the same test check it. With (1) fixed, I expect the two
mprotect(..., 3) == -1checks just belowsceKernelIsStack'sstartto fail next. On main, those pages belong to the host thread stack.DoMprotectfinds no registered allocation there and returns EINVAL. On this head, they are the 1 MiB host margin and the guard page of aDoMapAnonmapping, which is registered withGuestAllocations, so the guest'smprotectsucceeds. A title can then make the guard page writable, or change the margin the host uses below the guest frames. Linux handles this case:AllocateGuestStackrecords the mapping inguestStackMappings, andGuestThreadStackHostRangeOverlapsmakesDoMprotectreturn EACCES for anything outside [stackStart, stackEnd). On Windows, that function is compiled toreturn false. Please record the Windows stacks in the same table, and enable the overlap check on Windows too, so both platforms refuse the guard and margin.3.
guest_pthread_startis 15 to 37 times slower. That test creates and joins 10,000 threads with 1 to 2 MiB stacks. On main, each thread is one_beginthreadexreservation that commits lazily. On this head, each thread maps stackSize + 1 MiB + 16 KiB through the arena. That's roughly 130 to 195 placeholder splits and replacements on map, the same again on unmap throughGuestArenaReset, and aVirtualQuerywalk over each 16 KiB region inStartNativeThread, all under theGuestAllocationsmutation lock. I've counted the calls but not timed them, so please profile it. Committing the stack as one allocation (option 1a) should remove most of the work. Reusing retired stacks of the same size would remove the map/unmap churn entirely._beginthreadexstill reserves stackSize + 1 MiB of native stack that the guest no longer runs on. Shrinking that native stack would also help with large thread counts. The test should come back to roughly main's time. Its 60 s Windows timeout is not the bar.Not verified here: these are from reading the code (our bench is Linux, so I can't run the Windows path). The arena granule and the missing Windows overlap check are both visible in the current head. When you push, please run
guest_kernel_stack_protectandguest_pthread_starton Windows, plus the tests from before (guest_pthread_stack,guest_pthread_cancel,guest_once,guest_pthread_destructor_lifetime,fiber,guest_memory).Imported from boykopovar/AnyPS5. Originally posted by Pouare514 on 2026-10-18T09:54:54Z.
Addressed all three findings (rebased on current main, force-pushed).
(1) Single-allocation commit: DoMapAnon down through CommitArenaRange takes a commit granule (0 keeps the old 16 KiB behavior for other callers); AllocateGuestStack passes bytes, so each stack is one MEM_REPLACE_PLACEHOLDER and the 64 KiB guard mprotect spans one region — the RegionSize check is untouched and passes. Required follow-up: UnmapRegistered now releases one host allocation at a time (registry pieces split by the guard protection are accumulated per allocation); per-piece reset truncated the single allocation (
guest release truncates a host allocation).(2) Windows stacks now use the Linux mechanism exactly: RegisterGuestStackMapping/UnregisterGuestStackMapping plus guestStackMappings compiled on Windows, Register in StartNativeThread, Unregister in FreeGuestStack/ReapRetiredWinStacks, GuestThreadStackHostRangeOverlaps enabled — mprotect below the reported start fails with EACCES.
(3) Reuse plus shrink: FreeGuestStack caches up to 4 committed stacks (exit-retired stacks still unmap on signal, keeping the RequireUncommitted asserts); Allocate reuses same-size entries (verified engaged: 6765 reuses / 10100 creates). Native _beginthreadex reserve cut from stackSize+1 MiB to 256 KiB (entry/exit and SEH only; no test reads the host reserve). guest_pthread_start: 14.5s before, 1.5-1.8s after (3 runs), vs main's 1.6-2.3s.
Linux unverified here: Windows Release Ninja (winlibs gcc15) only — guest_kernel_stack_protect, guest_pthread_start, guest_pthread_stack, guest_pthread_cancel, guest_once, guest_pthread_destructor_lifetime, fiber, guest_memory all green; git diff --check and check_conventions.py clean.
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-18T10:21:59Z.
Thanks, the single allocation, the Windows overlap check and the reuse cache all read right. Two things before CI:
Linux doesn't compile.
DirectMemory.cpp:740passescommitGranuleto the systemmmapon Linux ("too many arguments to functionmmap(void*, size_t, int, int, int, __off_t)"), and the newUnmapRegisteredlambda callsKernelArena::Get().Contains(...)(:901), butKernelArenaonly exists under_WIN32. Main's file compiles with the same command.A partial unmap of a Windows mapping outside the arena now frees the whole allocation. On main,
UnmapRegisteredcallsmunmap_release(allocation)only whenlastis set (nothing of the allocation remains), and otherwise decommits just the piece. The newflushPendingcallsmunmap_releasefor every non-arena run, including the flush after the loop. So unmapping part of aMAP_FIXEDmapping outside the arena releases the rest while it's still registered, and unmapping the rest later throws "VirtualFree release failed". Keepinglastwith the pending run (release only when the run ends the allocation, otherwisemunmapthe run), or not merging non-arena pieces, would keep main's behaviour.Minor: when
ReuseWinStack's commit check fails, the cache entry is dropped without unmapping it, so that mapping leaks.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-19T21:39:35Z.
I checked the current head
2456bc05a2against the earlier Linux and partial-unmap findings. They still appear present:DirectMemory.cpp,MapPlacedcallsmmap(..., commitGranule)at line 740 on Linux, where POSIXmmaptakes six arguments. A localg++ -fsyntax-onlyrun with the Linux libkernel flags fails there with “too many arguments”.UnmapRegisteredcallsKernelArena::Get()at line 901 without a platform guard, butKernelArenais declared only in the Windows section. The same Linux compile fails with “KernelArena has not been declared”.flushPendingcallsmunmap_release(pendingAllocation)for every non-arena run. The final flush runs even when the callback’slastflag is false, so a partial unmap of a host allocation still releases the full allocation while its remainder is registered. The pending run needs to retain whether the allocation is fully unmapped and decommit only the partial range.These findings are on the current head; the PR’s latest Linux/Windows app jobs are skipped, so they were not caught by hosted checks.
Imported from boykopovar/AnyPS5. Originally posted by milescoviello on 2026-10-19T22:59:18Z.
@Pouare514 a finding for your rebase, from @frankea's Windows runs on #7700 (comment). RTX 4090, Windows 11, on current
main:guest_kernel_stack_protectfails at line 109 withmain+ this PR alone, 3 of 3. That's the errno check for when a fixedmmapover a worker's stack is refused. It passes onmainf29546ac4. This is separate from the Linux build break MarcZX10 listed above.For context, #7700 (NHL 26's Heartbeat walking an ended thread's stack) now has its Windows fix planned on top of this PR. frankea has a local follow-up that moves #7838's spare-stack list out of the
__linux__block, so this PR's WindowsFreeGuestStackand its retired-stack reap collect into it instead of unmapping. They'll open it once this PR lands.AI-assisted: yes (Claude Code)
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-19T23:04:13Z.
A separate Windows regression surfaced in the RTX 4090 run documented in #7700:
guest_kernel_stack_protectfails at its fixed-mmap-over-worker-stack errno assertion (3/3) with current main + this PR, while current main passes. The report identifies this independently of the Linux build issue already noted here. Could you check the Windows fixed-map rejection path and keep this test green on the rebased PR? This is useful because the mapping must be refused without changing the live stack, and callers also rely on the expected errno.Imported from boykopovar/AnyPS5. Originally posted by Queuse on 2026-10-21T23:36:27Z.
Rebased branch,
5fc50bdbe9, maina6dcea9279; original authorship preserved.Corrects Linux mmap/platform guards, split arena unmaps, partial host-allocation release and fixed-map rejection across host-only stack margins. Baseline and candidate pass all 8 focused Windows cases (Windows 11 26200, GCC 15.2.0-r7). Earlier independent unmap controls fail when the defects are restored. Original-head Linux syntax fails; integrated syntax passes with current headers under WSL GCC 15.2.
#4563 and #9272 address separate stack-lifetime concerns. No full Linux build or title run. AI-assisted: yes.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T13:34:07Z.
I checked the exact open heads for #7149 and dependent follow-up #9582 with
git merge-tree; they have a content conflict inlibkernel/Pthread/src/Thread.cpp. #9582 carries the#8890timed-join helper change, while this PR has its Windows guest-stack adjustments. Please coordinate a merge/rebase order with the #9582 author and preserve both behaviors in the integration. I am recording the conflict so the test/fix can be carried through whichever order is easiest; no maintainer action is being requested.Imported from boykopovar/AnyPS5. Originally posted by CnRJay on 2026-11-01T19:52:36Z.
Review: COMMENTED
Correction (2026-11-01): the title-ID/log demand below is not a CONTRIBUTING requirement;
Unblocks: noneis allowed. The technical points below are unaffected.Points on 7149:
Comments in code.
Thread.cpp("The native stack only runs thread entry/exit (plus SEH dispatch)...", "Freed stacks stay committed so a later thread with the same size reuses them...") andDirectMemory.cpp("Registry ranges split on protection changes...") add comment blocks. The rule is no comments except#endifand namespace ends.Committed stack cache. "Freed stacks stay committed so a later thread with the same size reuses them" is an unbounded pool of committed memory on Windows: a title that spawns many threads of varied sizes pins all of them. What caps the pool, and are stacks of different sizes ever released?
Evidence. The description does not show a title ID with a log line proving a guest thread on main fails because its stack is outside the guest VA range. Please add that.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-23T02:49:14Z.
Review: COMMENTED
Reviewed — no blocking findings
Nothing blocks this change; the optional point below is about Windows cache cleanup when a cached stack fails validation.
What I ran
Reviewed head
2456bc05a2e885120c5b282ecc0f46eb0a8b4fe2using the prepared diff andrepo_read.py. No tests or builds were run.Results
Findings
Blocking
None.
Non-blocking
ReuseWinStack, a cached mapping is removed from the cache beforeVirtualQueryvalidates the whole range. If validation fails, the function returns without releasing the mapping, leaving it allocated and unreachable from the cache (core/libs/prx/libkernel/Pthread/src/Thread.cpp:387). Consider unmapping the candidate on this failure path.Not verified
No tests, builds, Windows runtime checks, or physical-console checks were run. The author-reported results were not independently verified. The changed files read were
core/libs/prx/libSceFiber/Export.cpp,core/libs/prx/libc/src/GuestStacks.cpp,core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp,core/libs/prx/libkernel/Pthread/src/Thread.cpp, andcore/libs/tests/GuestPthreadStack.cpp. The other changed files listed in the manifest were not read:core/libs/prx/libc/include/GuestStacks.hpp,core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp,core/libs/prx/libkernel/Pthread/include/Pthread.hpp,docs/dev/debt/libSceFiber.md, anddocs/dev/debt/libkernel.md.To get this to a good state
Nothing is required. Optional: release a cached stack if its
VirtualQueryvalidation fails.Pull request closed