fix(libkernel): redirect a raise only once the target leaves host code #7652
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/7652"
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 billythemenace2 on 2026-10-18T20:25:19Z.
Requested by billy
What
On Windows,
sceKernelRaiseExceptionsuspends the target thread and redirects it to the guest handler wherever it stopped. The only exceptions are NtContinue and winpthreads. A target stopped inside host code, such as a C runtime call or a host library, can be holding a host lock there. If the handler then waits, as a collector's thread-stop handler does, the lock stays held, and every host thread that needs it stops too.SONIC SUPERSTARS (PPSA06888) froze at frame 65 on current
mainbecause of this. Its IL2CPP "UDS" thread was redirected in the middle of libSceNpTrophy2's[trophy] ...stderr write (the log line breaks off mid-word) and parked insceKernelWaitEventFlag. gdb showed it as theOwningThreadof the ucrt stderr critical section, with recursion 2. The driver'sShaderDiskCachereport andAsyncLogthreads were blocked inRtlEnterCriticalSectionon that lock.InHostModule: the address is in a loaded module other than the executable or a*.guest.prx.BlockedInWait: the address is in an ntdll wait stub (NtWaitForSingleObject,NtWaitForMultipleObjects,NtWaitForAlertByThreadId,NtDelayExecution, the I/O completion and keyed-event waits) or in win32u'sNtUserMsgWaitForMultipleObjectsEx. A thread blocked there is still redirected, as before, whichguest_raise_exception's host-blocked and lock-blocked cases rely on.Tested
guest_raise_in_host_codetest has a scePthread writing 1 MiB blocks to atmpfile()through ucrt while the main thread raises 20 times. The handler waits until the main thread has written to the same file. It times out onmain(the main thread blocks on the stream lock the redirected writer still holds) and passes with this change.guest_raise_exception,guest_raise_nested_sleepandguest_mutex_raise_exceptionpass.guest_raise_exceptiontakes 18.8 s here, against 15.8 s onmain.mainf03a2da5e, RX 5700 XT: without the change it stops presenting at frame 65 with no error. With it, it runs past frame 4000 at 60 FPS and then reaches the knownnative multisample depth metadata fill transition is not implementedstop (#6297, #6300).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
Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-18T20:48:11Z.
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)docs/dev/debt/libkernel.mdL148Some 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/CMakeLists.txtcore/libs/prx/libkernel/CMakeLists.txtcore/libs/prx/libkernel/System/src/Exception.cppdocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/CMakeLists.txtdocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/CMakeLists.txtcore/libs/prx/libkernel/CMakeLists.txtdocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/CMakeLists.txtdocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/System/src/Exception.cppcore/libs/prx/libkernel/CMakeLists.txtcore/libs/prx/libkernel/CMakeLists.txtdocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/CMakeLists.txtcore/libs/prx/libkernel/System/src/Exception.cppcore/libs/prx/libkernel/CMakeLists.txtcore/libs/prx/libkernel/System/src/Exception.cppdocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/CMakeLists.txtdocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mdImported from boykopovar/AnyPS5. Originally posted by wachi35676 on 2026-10-19T00:12:54Z.
Tested at
2e363d375on Windows 11 (GCC 15.2),main8a456334f. The four raise tests pass. As a negative control,guest_raise_in_host_codewithmain'sException.cppfailed 7 of 10 runs (timeout), and 0 of 10 with this branch. So it catches the bug, but not on every run.I measured the cost of waiting for guest code with a target thread looping
LoadLibraryW(L"dbghelp.dll")/FreeLibraryplusGetModuleFileNameW:maindelivers 300 raises in 0.01 s (median 0.04 ms).scePthreadYield, sleeping insceKernelUsleepor calling ucrtsnprintfshows no change (under 1 ms).InHostModulecounts libkernel.prx, libc.prx and the other HLE modules as host modules. So a thread inside a long HLE or driver call now waits up to 1 s per raise, and after that it is still redirected inside host code. Coulddocs/dev/debt/libkernel.mdget a Windows entry covering both points?AI-assisted: yes (Claude Code); results above were run on this machine.
Imported from boykopovar/AnyPS5. Originally posted by whamre on 2026-10-19T11:54:11Z.
This also unblocks LEGO Builder's Journey (PPSA05496). We hit the same deadlock independently: IL2CPP's GC raises SIGUSR1 to stop the world, the main thread was redirected into the suspend handler inside host code, and the title stopped presenting after two frames. A local change with the same idea (redirect only once the target is back in title code) gets it past the logo into the first scene. Tested on Windows 11 (26300), GCC 15.2, RTX 2080 SUPER.
One problem we ran into while writing ours, which this version has too:
InHostModulecallsGetModuleHandleExWandGetModuleFileNameWwhile the target is suspended, and both take loader locks. If the target was suspended while holding one (insideLoadLibrary,FreeLibraryor a DLL notification, as in thedbghelp.dllloop in the measurement above), the raising thread blocks on that lock while it keeps the target suspended, and neither thread continues. Thestaticinitializer ofBlockedInWait(GetModuleHandleW,GetProcAddress) has the same issue on the first raise, as do the existing ones inRestoringContextandInWinpthread.What we did instead:
VirtualQuery(rip)is called, and itsAllocationBaseis looked up in a small lock-free cache of image bases → guest/host. AMEM_IMAGEbase that isn't cached yet is classified withGetModuleFileNameWafterResumeThread, and the target is sampled again.statics are run once before the firstSuspendThread.For the cost raised in the review, we also queue an APC as soon as the target is found in host code and keep sampling. Whichever happens first runs the handler: the APC at the thread's next alertable
TimedWaitwait (which already drains APCs), or the redirect once the thread is sampled in title code. An atomic claim makes sure it runs once. This helps a thread that leaves an HLE call into a wait. It doesn't help one that stays in host code without waiting, like theLoadLibraryWloop, which still waits up to 1 s.If it's useful, I can send the cache, the warm-up and the APC part as a follow-up PR once this one is merged, together with the Windows entry for
docs/dev/debt/libkernel.mdrequested above.AI-assisted: yes (Claude). The LEGO results are from my machine.
Imported from boykopovar/AnyPS5. Originally posted by billythemenace2 on 2026-10-19T16:23:21Z.
@whamre thank you, the loader-lock deadlock is a real bug in this version, and good to hear it unblocks LEGO Builder's Journey too. @wachi35676 thank you for the negative control and the cost measurements.
Updated at
d2657b975:VirtualQuery(rip)runs then, and itsAllocationBaseis looked up in a lock-free table of image bases marked guest or host (the executable and*.guest.prxare guest). An image not yet in the table is classified withGetModuleFileNameWafterResumeThread, and the target is sampled again. A full table counts unknown images as host. Nothing is allocated while the target is suspended.RestoringContext,InWinpthread,BlockedInWait, the executable base and the table are initialized before the firstSuspendThread.docs/dev/debt/libkernel.mdhas a Windows entry forsceKernelRaiseException. It says the HLE modules count as host code, that a target staying in host code costs the raiser up to 1 s per raise and is then redirected there anyway, and that the APC fast path is not implemented.guest_raise_in_host_codenow raises 100 times. Withmain'sException.cppit timed out on 6 of 6 runs, and it passes on every run with this branch.On the RX 5700 XT the four raise tests pass,
guest_raise_exception11 of 12 runs at 18.6-22.4 s. The first run after the rebuild timed out at 62 s once and I couldn't reproduce it in 11 reruns or a direct run, so I'm noting it in case it shows up for anyone else.@whamre yes please, the APC part as a follow-up would be welcome. It addresses exactly the cost @wachi35676 measured for a thread that leaves an HLE call into a wait. I left it out here so this stays the minimal fix.
AI-assisted (Claude Code).
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-20T11:17:59Z.
Checked the diff against the review thread:
VirtualQueryand the lock-free image table run while the target is suspended; unknown images are classified afterResumeThread, and a full table counts as host.SuspendThread; the NtContinue/winpthreads 1 s throw is unchanged.guest_raise_in_host_codeis registered underWIN32, and the debt entry covers the up-to-1 s cost per raise and the missing APC path.Merged.
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-20T12:06:58Z.
Since this merged,
guest_raise_exceptionon the Windows CI runners has gone from 14.7-14.9 s (4 runs on the previous main) to 17-29 s, with 6 of 10 runs hitting the 30 s timeout. The runs were on unrelated pull requests, all on maind50ec76da0. This PR is the only merge in that range that touches the raise path, and it matches the 15.8 → 18.8 s you measured locally.The cause is the new retry: a target running host code is resumed and re-suspended until it is sampled in guest code, for up to the 1 s
RetryLimitper raise. Several cases inguest_raise_exceptionraise against threads that loop outside guest code:RaiseException(kernelbase/ntdll dispatch),scePthreadSelfandsceKernelSyncOnAddressWake(our libraries are built as.prx, so they count as host code), andstd::this_thread::yield. That's about 220 raises, and each can now wait up to 1 s, more often on a loaded 4-core runner. The same cap applies at run time: a collector that stops every thread with a raise can wait up to 1 s for each thread in host code or in a syscall not on the wait list.Could you give host code its own short limit, separate from the 1 s limit that still guards NtContinue and winpthreads? For example, a host deadline of around 50 ms after which the target is redirected where it is, as before. Your
guest_raise_in_host_codewriter spins in guest code between every 1 MiB write, so it should still pass, and so should the original stderr case. Logging the longest wait per raise in both tests would show what value is safe. TreatingNtYieldExecutionlike the listed waits might also be worth considering.Before it merges we'll check:
guest_raise_exceptionback near 15 s on Windows CI (three runs, no timeout),guest_raise_in_host_code,guest_raise_nested_sleepandguest_mutex_raise_exceptionpassing, and your title run still getting past the freeze.Imported from boykopovar/AnyPS5. Originally posted by whamre on 2026-10-20T14:43:58Z.
Numbers for the host-code limit, from a local build of
main30fda0a03with the limit read from an environment variable (not a PR). Windows 11 (26300), i5-10500 (6 cores, 12 threads), WinLibs GCC 15.2.0, Release:guest_raise_in_host_codeguest_raise_exceptionguest_raise_nested_sleepandguest_mutex_raise_exceptionpass at every limit. The longest wait for one raise inguest_raise_exception, at the 1000 ms limit, was 21.5 ms. So on this 6-core machine the host-code freeze needs somewhere between 10 and 50 ms. 50 ms passes here but is about 2.3 times the longest wait measured, which may be tight on a loaded 4-core runner. Logging the longest wait per raise on CI, as suggested above, would show how much margin it has there. I can run LEGO Builder's Journey (PPSA05496), the title that froze without this, against a candidate once its shader cache is warm.AI-assisted: yes.
Imported from boykopovar/AnyPS5. Originally posted by whamre on 2026-10-20T15:31:59Z.
Follow-up with LEGO Builder's Journey (PPSA05496), the title the host-code retry was first needed for: on
main30fda0a03, 2 runs each with the host-code limit at 0, 50 and 1000 ms all get past the point where it froze, to the next unrelated stop. None of the 77 GC raises per run met a target in host code, so this title doesn't constrain the limit; theguest_raise_in_host_codenumbers above are what bound it.AI-assisted: yes.
Imported from boykopovar/AnyPS5. Originally posted by billythemenace2 on 2026-10-20T15:40:53Z.
@oneandonlydean @whamre thank you both, and for the numbers. The follow-up is https://github.com/boykopovar/AnyPS5/pull/8539. Host code now has its own 100 ms limit, NtContinue and winpthreads keep 1 s, and
NtYieldExecutioncounts as a wait. A failedGetThreadContextis retried instead of thrown, which Sonic hit once.guest_raise_in_host_codeprints the longest raise. I picked 100 ms over 50 ms because the longest raise in that test reached 45 ms here. Hereguest_raise_exceptionis back to 12.7-14.0 s.AI-assisted (Claude Code).