Skip to content

feat(libkernel): deliver sceKernelRaiseException on Windows - #760

Merged
adriadam10 merged 9 commits into
boykopovar:mainfrom
merwie:feat/kernel-raise-exception-windows
Oct 7, 2026
Merged

adriadam10 merged 9 commits into
boykopovar:mainfrom
merwie:feat/kernel-raise-exception-windows

Conversation

@merwie

@merwie merwie commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What

sceKernelRaiseException(thread, signum) threw. On Windows it now runs the handler recorded by sceKernelInstallExceptionHandler (#724) on the target thread, with a PS5 ucontext of the interrupted state (16-byte uc_sigmask, 48 bytes, FreeBSD amd64 mcontext at 0x40, mc_rsp at 0xf8; checked with static_assert), as proposed in #727:

  • Calling thread: the handler runs directly with the captured context.
  • Thread in a libkernel wait: the TimedWait waits (Condition signal waits, timer waits, sleeps) are alertable and count themselves in a per-thread wait state (PthreadPrivate::waitState). If the suspended target is in such a wait, the delivery is queued with QueueUserAPC; the handler runs on the target inside its wait, with a context captured there, and the wait continues afterwards (an APC returns WAIT_IO_COMPLETION, which the waits retry).
  • Running thread: SuspendThread + GetThreadContext, copy the delivery onto the target's own stack below its 128-byte red zone, with the entry's 32-byte home area below that copy (refused if those pages are not committed), and redirect rip to an entry that builds the ucontext, calls the handler, writes back the possibly modified registers and returns with RtlRestoreContext.

Only SIGUSR1 (30) can be raised, as in shadPS4; other signals return SCE_KERNEL_ERROR_EINVAL, a null thread SCE_KERNEL_ERROR_ESRCH, and raising without an installed handler throws. Linux still throws (the host signal choice is open in #727). Known limits, also in #727: a thread blocked in a host wait outside TimedWait (or with APS5_COARSE_TIMED_WAITS) does not run the handler until it returns to guest code or enters such a wait; signal masks are not consulted.

  • New Windows test guest_raise_exception, which checks:
    • raising an unsupported signal, and raising without a handler;
    • raising on the calling thread;
    • 100 raises on a busy worker and 100 on a worker blocked in sceKernelWaitSema. Each checks that the handler ran on that worker, that mc_rsp is set and lies above the handler's frame, and that the worker continues (the blocked one returns from its wait once the semaphore is signaled).
    • HostBlocked, 20 rounds: a worker blocked on a host std::mutex, a non-alertable wait in a system call. That wait takes the redirect path, so the handler runs only once the wait returns to guest code. The thread then resumes through sysret, which overwrites rcx/r11. Each round raises while the worker is blocked, releases the mutex, and expects exactly one delivery on that worker. This pins that the redirect entry takes the delivery from rsp and the live registers (the wait gets its real result in rax), not from rcx or the stale snapshot.
    • Raising on a thread that has returned but is not yet joined returns ESRCH.

Tested

Windows 11, WinLibs GCC 15.2.0 r7, Ryzen 7 9800X3D, Radeon RX 9070 XT.

  • ctest: 317/319 passed, including guest_raise_exception (also 10 consecutive runs, 2000 deliveries). agc_driver_lds_atomics64 and agc_driver_vopc_compare_table fail on this machine on main as well (Vulkan device tests).
  • PPSA12544 (Hollow Knight: Silksong, Unity IL2CPP): its GC stop-the-world (PS5Util, see Hollow Knight: Silksong (PPSA12544) #726) raises SIGUSR1 on threads blocked in libkernel waits; the handlers run and return, the collector proceeds, and the title goes on to load level0.

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: feat(libkernel): record exception handlers #724 (its commit is included here)
  • AI-assisted: yes

🤖 Generated with Claude Code

merwie and others added 2 commits October 5, 2026 22:50
sceKernelInstallExceptionHandler and sceKernelRemoveExceptionHandler threw.
They now keep one handler per allowed signal (SIGHUP, SIGILL, SIGFPE,
SIGBUS, SIGSEGV, SIGUSR1, as in shadPS4): another signal or a null handler
returns EINVAL, a second handler for a signal returns EAGAIN, and removing
clears it. Delivery is not implemented and is recorded in the technical
debt; sceKernelRaiseException still throws.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Run the SIGUSR1 handler recorded by sceKernelInstallExceptionHandler on the
target thread with a PS5 ucontext (uc_mcontext at 0x40, FreeBSD amd64
layout) of its interrupted state:

- on the calling thread, directly;
- on a thread in a libkernel wait, from an APC: the TimedWait waits are
  alertable and count themselves in a per-thread wait state, so the
  handler runs inside the wait, which then continues;
- on a running thread, by suspending it and redirecting it to an entry
  that calls the handler and restores the possibly modified context.

Other signals return EINVAL, as in shadPS4; raising without a handler
throws. Linux still throws.

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

Copy link
Copy Markdown
Collaborator

Thanks for this. One thing in the redirect path for a running thread:

RedirectedEntry is an ordinary MinGW function, so it uses the Windows x64 convention, where the callee owns the 32-byte home area above its return address. With Rsp = ((Rsp - 128) & ~15) - 8, that home area is [new Rsp + 8, new Rsp + 40), and it starts at or just below old Rsp - 128. So the top of it falls inside the guest's 128-byte red zone, which the description says the entry stays below. GCC can spill rcx (the Delivery*) there, which would overwrite live guest data. Reserving another 32 bytes, for example ((Rsp - 128 - 32) & ~15) - 8, keeps it clear.

Related, and smaller: RedirectedEntry frees the Delivery with delete on the interrupted thread. If that thread was suspended inside the heap (the heap lock is recursive for its owner), the free runs on a heap that is half updated. Copying the Delivery onto the target's stack below that gap before SetThreadContext, and passing its address in rcx, avoids the heap on that thread entirely.

The rest looks right to me: the ucontext offsets match the static_asserts, waits retry after an APC, and Linux behaviour is unchanged apart from the new EINVAL/ESRCH returns ahead of the throw.

@github-actions github-actions Bot added the needs rebase Conflicts with main, rebase needed label Oct 5, 2026
merwie and others added 2 commits October 6, 2026 09:59
…/kernel-raise-exception-windows

# Conflicts:
#	core/libs/prx/libkernel/Pthread/src/Thread.cpp
#	docs/dev/TechnicalDebt.md
The redirect entry's Windows x64 home area started inside the guest's
128-byte red zone, and the interrupted thread freed the delivery on the
heap, which it may have been suspended inside. The delivery is now copied
onto the target stack below the red zone, with the home area below it, and
the copy is refused when those pages are not committed.

AI-assisted: yes

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

merwie commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, both fixed in b550545. The delivery is now copied onto the target stack at (rsp - 128 - sizeof(Delivery)) & ~15, and the entry starts at slot - 32 - 8, so its home area is [slot - 32, slot), below the copy and below the red zone. rcx points at the copy, and nothing on the interrupted thread touches the heap. Before writing, VirtualQuery checks that the pages from the home area up to rsp - 128 are committed, read-write and not a guard page. Otherwise the raise throws, because writing a guard page from the raising thread would break the target's stack growth. Also merged main (the TechnicalDebt line next to #796's, and #761's SetStackFromHost next to waitState in Thread.cpp). Non-GPU tests pass, and guest_raise_exception passed 5 repeated runs.

@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Oct 6, 2026
…sters

A thread suspended inside a system call returns through sysret, which
overwrites rcx and r11, so the delivery address passed in rcx was
garbage when the redirected thread resumed. PPSA12544 crashed that way
on its SaveDataProcessQueue thread, blocked in a host wait when Unity's
GC raised SIGUSR1. The redirected rip is now an entry stub that takes
the delivery from its fixed place above rsp. It also stores the live
general registers into the delivery's context first: the snapshot taken
while the thread was in the system call still holds the call number in
rax instead of its result, which the restore would have handed back to
the wait.

The guest test raises at a thread blocked on a host mutex in 20 rounds
and expects each delivery once the wait returns; it fails without this
change.

AI-assisted: yes

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

merwie commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Found and fixed a real bug in the redirect path while testing PPSA12544 past its intro (3cd2ff9). A thread suspended inside a Windows system call (here Unity's SaveDataProcessQueue, blocked in a host wait) resumes through sysret, which overwrites rcx and r11. So the Delivery* passed in rcx was garbage, and the handler call faulted (call *%r9 with instruction bytes as the pointer). The snapshot from GetThreadContext also still had the system call number in rax, not its result, so restoring it after the handler would have handed the wait a bogus status.

The redirected rip is now a small Aps5RedirectedEntryStub. It stores the live general registers into the delivery's context (static_asserts pin the offsets), takes the delivery from its fixed place 40 bytes above rsp, and jumps to the C++ entry. For a thread interrupted in user mode the live registers equal the snapshot, since rcx is no longer modified. GuestRaiseException gains a case that raises at a thread blocked on a host mutex, in 20 rounds, and expects each delivery once the wait returns. It fails without the change. Non-GPU tests pass.

@github-actions github-actions Bot added the needs rebase Conflicts with main, rebase needed label Oct 6, 2026
@oneandonlydean

Copy link
Copy Markdown
Collaborator

Thanks. #724 (exception handler recording) is merged now, and this branch conflicts with main in core/libs/prx/libkernel/CMakeLists.txt and System/src/Exception.cpp. Could you merge or rebase onto main, keeping your delivery code on top of #724's handler recording?

…/kernel-raise-exception-windows

# Conflicts:
#	core/libs/prx/libkernel/CMakeLists.txt
#	core/libs/prx/libkernel/System/src/Exception.cpp
@merwie

merwie commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

Merged main (as a merge, so the review history stays). main's Exception.cpp was identical to the #724 commit this branch already built on, so the delivery code sits unchanged on top of #724's handler recording. In CMakeLists.txt I kept the guest_raise_exception registration next to #724's guest_exception_handler. Non-GPU tests pass (232), including both exception tests.

@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Oct 7, 2026

@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.

Thanks, the redirect path and the asm stub look right to me (field offsets of Delivery/CONTEXT match the static_asserts, entry stack is 8 mod 16). A few things before this can go in:

  • Exception.cpp:198: new Delivery runs while the target is suspended. If the target holds the allocator/CRT lock when suspended, the raising thread deadlocks. Allocate before SuspendThread (and don't allocate in any path between suspend and resume, including the throw sites, which should resume first, as the others do).
  • Exception.cpp:197, Thread.cpp:177/411: waitState points into the target's thread_local. Raising on a thread that has already exited but isn't joined (or an adopted thread that exited) reads freed TLS. Please clear the pointer at thread exit (or keep the state in PthreadPrivate) and say what happens when the target already finished (ESRCH?).
  • Exception.cpp:208: only CONTEXT_FULL | CONTEXT_FLOATING_POINT is saved, so the upper halves of YMM are not preserved if the handler or the entry uses AVX. Either capture the XState or document it as a known limit.
  • The limits listed in the description (waits outside TimedWait and APS5_COARSE_TIMED_WAITS, signal masks not consulted, ucontext layout taken from FreeBSD, Linux still throwing) need lines in docs/dev/TechnicalDebt.md (criterion: every unverified choice gets a line, under the right ### section and not at the end of it).
  • The description doesn't mention the third test case (HostBlocked, 20 rounds with a host mutex); please describe what it pins, since it relies on the handler running only after the thread returns to guest code.

Windows runtime behaviour can't be run on our side; the Windows CI job is green, so these are code-review points.

@ps54all ps54all mentioned this pull request Oct 7, 2026
9 tasks done
…wait count

The APC delivery was allocated after SuspendThread, so a target holding
the allocator lock deadlocked the raising thread; it is now allocated
before the suspend. The wait count a raise checks lived in the target's
thread_local storage and dangled once the thread exited; it is now a
member of PthreadPrivate, which TimedWait counts into through a
thread-local pointer bound when the thread starts, and a raise on a
thread that already finished returns ESRCH. TechnicalDebt gets one line
per unverified choice: Windows only, the FreeBSD ucontext layout, the
signal mask, the YMM upper halves, and delivery to threads outside
TimedWait.

AI-assisted: yes

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

merwie commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, all addressed in 51b6079:

  • Allocation while suspended: the APC Delivery is now allocated before SuspendThread (released to the APC only once queued). The redirect path keeps its copy on our stack. Every throw after the suspend resumes the thread first.
  • waitState into freed TLS: the counter is now a member of PthreadPrivate (waitCount), which outlives the thread. TimedWait counts into it through a thread-local pointer bound when the thread starts (adopted threads too), and falls back to a thread-local counter on threads without one. A raise on a thread that has already finished returns ESRCH. The test raises on a returned, not-yet-joined thread and expects that.
  • YMM upper halves: documented as a known limit rather than capturing the XState.
  • TechnicalDebt: one line each, in Functional, next to feat(libkernel): record exception handlers #724's (which now says only raised signals are delivered): Windows only (Linux throws); FreeBSD ucontext layout; signal mask not consulted; YMM upper halves; threads outside an alertable TimedWait wait (including APS5_COARSE_TIMED_WAITS and host waits) run the handler only when the wait returns.
  • Description: now covers the HostBlocked case and what it pins.

The exception tests pass 3 runs in a row, and the non-GPU tests pass (232).

…/kernel-raise-exception-windows

# Conflicts:
#	docs/dev/TechnicalDebt.md
@tv7

tv7 commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Data point: PPSA03306 (Silt, Unity) needs this too. On main (cea1ef13) with #1141 and #1196, and its Unity modules relinked to Media/Modules (#716/#717), the title aborts with sceKernelRaiseException not implemented, called from Il2CppUserAssemblies.prx. With this PR merged locally, it gets past that point and loads unity default resources and mscorlib.dll-resources.dat. It later stops at a ud2 in its own libc.prx, right after sceKernelDebugRaiseException(0xa0020008), which looks unrelated to this change. Windows 11, GCC 15.2.0, RTX 3070.

@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.

Thanks, everything from the last round is addressed (allocation before suspend, waitCount in PthreadPrivate, ESRCH on a finished thread, the TechnicalDebt lines). Build and ctest are green on our side against current main, and the Windows job runs guest_raise_exception 3/3. Two new things in the wait path, plus a minor one:

  • TimedWait.cpp:26-31 (AlertableWait, same in AlertableSleep): there is a window after WaitForMultipleObjectsEx returns and before fetch_sub. If RaiseOn suspends the target there, it sees waitCount > 0 and queues an APC (Exception.cpp:199). The thread then leaves the wait and returns to guest code, so the APC only runs at its next alertable TimedWait wait, which may never come. A stop-the-world collector waiting for that handler would hang. One way to close it: after the decrement, drain pending APCs before returning (SleepEx(0, TRUE), or NtTestAlert if yielding is a concern). A raise that suspends the thread after the decrement takes the redirect path anyway.
  • TimedWait.cpp:172: Condition::waitSignalUntil calls EventSet(waiter->event, 0) while holding queueLock, and EventSet is now alertable. A pending APC would run the guest handler with the condition's queueLock held. If the handler notifies that condition, it deadlocks on the non-recursive mutex. That poll is 0 ms anyway, so a non-alertable wait there avoids the problem.
  • Minor, Exception.cpp:276/198: a target that exits between the _finished check and SuspendThread/GetThreadContext/QueueUserAPC makes the raise throw instead of returning ESRCH. Checking WaitForSingleObject(native, 0) == WAIT_OBJECT_0 after the suspend (then resume and return ESRCH) would cover it.

A raise that suspends the thread after its wait returned but before the
wait count drops queued an APC that only ran at the next alertable wait.
Pending APCs are now run right after the count drops. The 0 ms poll in
Condition::waitSignalUntil runs under queueLock and is no longer
alertable, and a target that exits during the raise returns ESRCH.

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

merwie commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. All three are addressed in 2654e3a:

  • Window after the wait: AlertableWait and AlertableSleep now run pending APCs right after the count drops (NtTestAlert, with SleepEx(0, TRUE) as a fallback if it can't be resolved). A raise that suspends the thread after the decrement takes the redirect path, as you said. The new Leaving part of guest_raise_exception signals a semaphore and raises at staggered delays while the target leaves its wait, then spins without waiting again (200 rounds). Without the drain it hung 5 of 5 runs; with it, it passes 5 of 5.
  • waitSignalUntil: the 0 ms poll under queueLock is a plain WaitForSingleObject now, so no APC can run with the lock held.
  • Exit during the raise: after SuspendThread, a signalled thread handle resumes and returns ESRCH. A failed suspend on an exited thread also returns ESRCH.

Merged main before this too (TechnicalDebt conflict). Non-GPU tests pass (235).

@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.

Thanks, all three points are addressed in 2654e3a (APC drain after the count drops, with the Leaving test; non-alertable 0 ms poll under queueLock; ESRCH when the target exits after the suspend). Build and ctest green against current main; the Windows job covers guest_raise_exception. Merging once CI is green.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants