sceKernelRaiseException on Windows can stop a thread inside emulator code that holds a host lock #1488
Loading…
Reference in a new issue
No description provided.
Delete branch "%!s()"
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 awake-devel on 2026-10-08T09:04:37Z.
On Windows,
sceKernelRaiseExceptionredirects any target thread that is not in an alertableTimedWaitwait (RaiseOnincore/libs/prx/libkernel/System/src/Exception.cpp), wherever itsRipis. If the thread is inside emulator code at that moment, for examplesceKernelSyncOnAddressWakeholdingg_waitersLock(SyncOnAddress.cpp), the guest handler runs while that host lock is held:On the console these calls are system calls, which a signal cannot interrupt halfway, so the guest never sees this. TechnicalDebt already says a thread blocked in a host wait runs the handler when that wait returns, but not that it can run while host locks are held.
Possible directions (each needs testing on Windows):
Ripis in guest code; otherwise resume and retry. Simple, but a thread blocked in a non-alertable host wait would make the raise spin until that wait ends, and it needs a reliable guest/host address map (executable andapp0modules vs.libs/*.prxand system DLLs).Ripis in host code, unwind (RtlVirtualUnwind) to the first return address in guest code and replace it with a stub that delivers the signal there (the return-address hijacking .NET uses to suspend threads in native code). Raises stay asynchronous, but pending hijacks must be tracked per thread and C++ exceptions must not unwind through a hijacked frame.A reproducer phase for
guest_raise_exception(a thread loops onsceKernelSyncOnAddressWake, the handler waits like a GC handler, and the main thread callssceKernelSyncOnAddressWakeon another address while the handler runs) is ready to share (a script that adds it toGuestRaiseException.cpp); it reports which module the thread was stopped in and fails if the wake blocks for 2 s. I can post it here or open it as a draft PR if that helps someone test. It has never been run.Related: #1421 and #1431 change the same delivery code; neither addresses this case on Windows. #1431 documents the same limitation for Linux in TechnicalDebt.
Imported from boykopovar/AnyPS5. Originally posted by LeandroLP23 on 2026-10-08T09:47:27Z.
Confirmed on Windows 11, MinGW-w64 GCC 15.2.0, Release,
main3e32797c.I wrote a reproducer from your description (not your script, which isn't posted): a
wakerguest thread loops onsceKernelSyncOnAddressWake(&a, 1); the SIGUSR1 handler records the interruptedrip(ucontext + 0xe0), then spins until released, like a GC handler; for each round the main thread raises SIGUSR1 on the waker, waits for the handler, and callssceKernelSyncOnAddressWake(&b, 1)from another thread, counting it as blocked if it has not returned after 2 s.300 rounds, 148 blocked:
libwinpthread-1.dll(the mutexstd::mutexuses)libkernel.prxsceKernelSyncOnAddressWake+0x160ntdll.dll,KERNELBASE.dll, the test itselfEvery blocked round had the waker stopped in host code taking or holding
g_waitersLock; none blocked when it was stopped elsewhere. The wake returned as soon as the handler did.Reproducer (
core/libs/tests/GuestRaiseExceptionHostLock.cpp, built likeguest_raise_exception_tests)Imported from boykopovar/AnyPS5. Originally posted by popcoder565 on 2026-10-08T10:51:03Z.
I measured how much of this #1421 covers, using LeandroLP23's reproducer (300 rounds per run). Setup: Windows 10 (19045), Intel Core i7-12700H, MinGW-w64 GCC 15.2.0 (WinLibs r7), Release.
main4b2413fblibwinpthread-1.dll256,libkernel.prx32, the test 12main+ #1421, run 1libkernel.prx194, the test 102,ntdll.dll4main+ #1421, run 2libkernel.prx206, the test 94#1421 resumes and re-suspends a target that is inside
libwinpthread-1.dll, so the stops inside the mutex go away. The thread is then caught a little later in libkernel, withg_waitersLockstill held. With #1421, every blocked round had the worker in one of two places:sceKernelSyncOnAddressWake, between +0x38 and +0x167;pthread_mutex_unlockimport thunk, just before the unlock.So #1421 halves this but doesn't fix it. The remaining cases need one of the directions above: a host-code check that also covers the libraries, or the return-address hijack.
Tested with AI assistance (Claude Code).
Imported from boykopovar/AnyPS5. Originally posted by klosixgaming-arch on 2026-10-08T11:50:50Z.
This issue is related to several recent PRs I've reviewed that touch the exception handling code:
sceKernelRaiseExceptionhandlers that sleepThe concern raised here - that a thread inside emulator code holding a host lock could be interrupted by an exception handler - is valid and worth investigating. The proposed directions (redirect only when Rip is in guest code, or unwind to first guest return address) are both reasonable approaches.
Based on my review of the related PRs, I'd suggest:
The issue correctly notes that this hasn't been reproduced yet, so testing on Windows would be valuable before attempting a fix.
Imported from boykopovar/AnyPS5. Originally posted by awake-devel on 2026-10-08T18:24:52Z.
Thanks @LeandroLP23 for the reproducer and the Windows run, and @popcoder565 for measuring #1421 with it. I've removed "unconfirmed" from the title.
Summary so far, with LeandroLP23's reproducer (300 rounds):
main: about half the rounds block (148 and 142). Every blocked round had the worker stopped in host code while taking or holdingg_waitersLock.main+ #1421: 62 and 76 blocked. The stops insidelibwinpthread-1.dllare gone. The rest are insidesceKernelSyncOnAddressWake(+0x38 to +0x167), or at libkernel'spthread_mutex_unlockthunk, with the lock still held.So the cases that remain need direction 1 or 2 from the issue. The smallest step looks like widening #1421's "resume and retry" check from the system libraries to all host code, including the emulator's own
libs/*.prxmodules. The cost is the one already noted: a raise can spin while the target sits in a non-alertable host wait.@popcoder565, since this builds directly on #1421, would you rather extend #1421 or take it as a follow-up PR? I can't test on Windows, so I'd rather not open a competing change. LeandroLP23's reproducer would make a good regression test for either.
Imported from boykopovar/AnyPS5. Originally posted by popcoder565 on 2026-10-09T02:56:29Z.
@awake-devel I'll take it as a follow-up PR on top of #1421. #1802 already builds on #1421 at
24dc98d7, so I'd rather not change it while it's under review.One catch with widening the synchronous retry: it breaks the host-blocked phase of
guest_raise_exception. There the main thread holds astd::mutex, raises at a worker blocked on it, and unlocks only after the raise returns. If the raise retries while the worker is in host code, it waits on itself until the 1 s bound and throws. A game thread in a long non-alertable host wait would hit the same throw, for example acondition_variablewait in an HLE library during a cold shader compile. That's worse than today's late delivery.So I'll try deferring instead. When the target is stopped in host code, the raise goes to a delivery thread and
sceKernelRaiseExceptionreturns 0 at once, likekill(). The delivery thread re-checks the target until it's back in guest code (the main executable or a*.guest.prxmodule) or in an alertable wait, and delivers there. I'll measure it with LeandroLP23's reproducer and the existing phases, and post the numbers here.🤖 Addressed by Claude Code
Imported from boykopovar/AnyPS5. Originally posted by popcoder565 on 2026-10-09T03:47:33Z.
Here are the numbers for deferring raises, as promised. Setup: Windows 10 (19045), GCC 15.2.0 (WinLibs r7), Release,
mainf1451396+ #1421. I'm not opening a PR for this yet.What I tried: when the target is stopped outside guest code, the raise goes to a delivery thread and returns 0. The delivery thread re-checks the target until it's stopped in the main executable or a
*.guest.prxmodule (or in an alertable wait), then redirects it there.sceKernelSyncOnAddressWake. The delivery thread only catches it in guest code by chance: about 75 checks per delivery (median), up to 330. One 300-round run took 120 s. Another failed in round 0 because the handler didn't run within the reproducer's 5 s.guest_raise_exceptionpassed 5/5 (about 10 s). Two phases needed changes, though. The host-blocked worker exits right after its last round, so a raise deferred until it returns to guest code is never delivered. The NtContinue phase now gets a delayed delivery instead of the 1 s throw.So deferring by sampling fixes the lock problem, but delivery to a thread that stays in host code can take arbitrarily long. A GC waiting for its handlers would stall for just as long. It would need a deterministic way to deliver when the thread returns to guest code. I'll leave it here for now rather than open something that can stall a GC.
🤖 Addressed by Claude Code
Imported from boykopovar/AnyPS5. Originally posted by gunerky on 2026-10-09T15:25:22Z.
Windows measurements and an obstacle to direction 2
I tested the host-lock scenario and the Windows unwind prerequisite for the proposed normal-return delivery approach. This is an investigation report, not a fix: no return address was modified and no deferred delivery was implemented.
Windows 11 x64 (build 26300), WinLibs MinGW-w64 GCC 15.2.0 r7 UCRT/POSIX/SEH, Release,
BUILD_TESTING=ON. All three comparisons used based70b89989473ba1f6ae13e44e079e67f1f8a44b0, with the PR heads locally integrated separately.24dc98d7c035bde08e679e3c62a59402a2b57cc5)076102124b98906ce5b3dc31c18f2cde020705fa)Each comparison was three 100-round repeats, in ten-round child processes with a 25 s process deadline. There were no missing deliveries or child timeouts in these 900 rounds; all workers recovered after releasing the handler. The 150 ms observation window differs from the 2 s window in earlier comments. These are bounded loss-of-progress observations, not permanent-deadlock claims or directly comparable failure rates. The PR code remains its authors' work; it was not changed for these comparisons.
The additional finding concerns direction 2:
RtlLookupFunctionEntry/RtlVirtualUnwindprobe used an explicitly registered guest assembly interval, not the entire test executable. In 100 live samples per build it found zero verified host-to-guest returns: main had 89 missing-metadata samples and 11 already in guest code; #1421 had 92/8; #1562 had 93/7. The host chain stopped inlibkernel.prx. Missing metadata was not treated as a leaf frame.-fasynchronous-unwind-tableson the unmodifiedSyncOnAddress.cppfails assembly with.seh_handlerdata used outside of .seh_proc block. An independently written throwing System V ABI fixture fails the same way. A nonthrowing System V fixture compiles, but still lacks Windows function entries.WindowsExceptions.cpp, linked to the existing project libc with its normal section rename, passes with the existing setting. Compiling that test with asynchronous tables enabled aborts atTrackedError(0xc0000409). The simple project-linked native exception fixture also aborts with that setting. These results were confirmed outside the sandbox. Thus a general flag change would both leave System V gaps and break existing exception behavior.The existing project's DWARF
.ehframdata and Windows function entries are distinct prerequisites here. The GCC patch discussion describes the same System V assembly inconsistency; no compiler patch or replacement toolchain was used. This does not prove that every possible boundary design is blocked, but it prevents presenting this Windows-API-based experiment as a working general mechanism.Current relevant CTests: 13 passed, longest 8.75 s, including Windows exceptions, guest raise, address synchronization, thread lifecycle and the optional read-only probe. Conventions, test registration and whitespace checks passed. Long research runs were kept outside CTest; no repository timeout was increased. Pending-delivery ownership, thread-exit cancellation, nested callbacks, exception unwinding through an armed return and trampoline register/return restoration remain unimplemented and untested. Linux, PS5 hardware and games: Not tested.
The sources below were independently written from the issue's scenario, with LeandroLP23's report and popcoder565's deferred-delivery results as context, not copied reproducer code. Newly authored research sources are offered under this repository's GPLv2 license. No Sony SDK, firmware or game files were used. AI-assisted: yes, OpenAI Codex.
Reproduction commands and standalone research sources (GPLv2)
Reproducing the investigation
Save the seven source files below together in a directory outside the repository. Use Windows x64, Python 3 and the repository-supported WinLibs MinGW-w64 GCC 15.2.0 r7 toolchain.
reproduce.pychecks the compiler version, prepends its directory to PATH and writes only to the supplied output directory. It does not fetch, merge, commit, patch repository sources or change Windows security policies.Use an existing Release build of the pinned source. For each measured main/PR integration, pass the corresponding directory containing matching NID-patched
libkernel.prxandlibc.prx. Do not mix libraries from different builds. The runner compiles the repository's existingNidCompute.cppandSha1.cppfrom--source; those files remain covered by the project license and are not republished here.The following paths are examples to replace, not prerequisites tied to the author's machine. PowerShell commands:
Repeat with the matching #1421 and #1562 build directories. The source identities for the reported results are listed above; the script does not make those integrations. The independent harness sends SIGUSR1 while a guest thread repeatedly calls address wake, holds the handler using atomic coordination, observes an independent wake, releases the handler, then joins. It records the actual NID calls, native thread identities and interrupted addresses. A ten-round child is terminated after 25 s if stuck. A 15-minute total budget leaves incomplete work incomplete; subprocess failure or timeout is not counted as success. Controls are available as
--mode empty,guest,long_waitandfinished. The long-wait control schedules release at 150 ms. Start with the default single ten-round batch if a shorter check is preferred.For the metadata/exception comparison, use the same build's unpatched libc and import library:
The runner builds the independent ABI fixtures, the scoped native helper, the unmodified
SyncOnAddress.cppand the unmodifiedWindowsExceptions.cppinto isolated outputs. Each executable has the matching unpatched libc beside it. It applies the repository's.eh_frameto.ehframrename. Expected failures are logged as failures: System V throwing/table-on assembly,SyncOnAddress/table-on assembly, and native project-linked/table-on exception executions. Native and System V table-off controls and the scoped-helper case should pass. The nonthrowing System V table-on case should return correct values but report missing metadata. The script finishing does not mean these experiments are all green or that #1488 is fixed; inspect the exit codes and JSON rows.All commands, return codes and deadlines are in
commands.jsonl; measurement observations are inresults.json; fixture results are infixtures.json. The added standalone driver was checked with a ten-round measurement smoke run and the fixture matrix; the original 900-round counts above are the earlier frozen measurements, not new counts from packaging validation. No whole-executable guest classification, missing-frame guessing or stack mutation is used. Normal integer/double fixture return checks do not test redirect restoration. The read-only analyzer's conservative accepted unwind records are version 1 without handler or chain flags.This is standalone research material, not a proposed repository test registration or production patch. Source attribution and AI assistance are disclosed above. The included newly authored sources use the project's GPLv2 license; retain that attribution if redistributing them.
reproduce.pyMeasure.cppWindowsHostBoundaryProbe.hppWindowsHostBoundaryProbe.cppAbiFixture.cppInspectFixture.cppScopedFixture.cppImported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-10T06:25:40Z.
#1562 changed the Windows mutex, rwlock and timed waits so delivery can run while a thread waits. Could you rerun the 300 rounds on current main?
Imported from boykopovar/AnyPS5. Originally posted by LeandroLP23 on 2026-10-10T07:18:14Z.
Reran it on current
main04d06f0d(with #1562), same reproducer, Windows 11, WinLibs GCC 15.2.0 r7, Release: 300 rounds, 35 blocked (148 on3e32797c). In all 35 the worker was stopped insidesceKernelSyncOnAddressWakeitself (libkernel.prx+0x198c0 ×18, +0x197a8 ×11, three other offsets ×6), which takesg_waitersLockatSyncOnAddress.cpp:115; none inlibwinpthreadany more (282 of the stops before). So the waits are covered now, and what's left is a raise that lands while the worker is insideWake.