feat(libkernel): deliver sceKernelRaiseException on Windows #760
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/760"
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 merwie on 2026-10-05T21:33:58Z.
What
sceKernelRaiseException(thread, signum)threw. On Windows it now runs the handler recorded bysceKernelInstallExceptionHandler(#724) on the target thread, with a PS5ucontextof the interrupted state (16-byteuc_sigmask, 48 bytes, FreeBSD amd64mcontextat 0x40,mc_rspat 0xf8; checked withstatic_assert), as proposed in #727:TimedWaitwaits (Conditionsignal 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 withQueueUserAPC; the handler runs on the target inside its wait, with a context captured there, and the wait continues afterwards (an APC returnsWAIT_IO_COMPLETION, which the waits retry).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 redirectripto an entry that builds theucontext, calls the handler, writes back the possibly modified registers and returns withRtlRestoreContext.Only SIGUSR1 (30) can be raised, as in shadPS4; other signals return
SCE_KERNEL_ERROR_EINVAL, a null threadSCE_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 outsideTimedWait(or withAPS5_COARSE_TIMED_WAITS) does not run the handler until it returns to guest code or enters such a wait; signal masks are not consulted.guest_raise_exception, which checks:sceKernelWaitSema. Each checks that the handler ran on that worker, thatmc_rspis 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 hoststd::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 throughsysret, which overwritesrcx/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 fromrspand the live registers (the wait gets its real result inrax), not fromrcxor the stale snapshot.ESRCH.Tested
Windows 11, WinLibs GCC 15.2.0 r7, Ryzen 7 9800X3D, Radeon RX 9070 XT.
ctest: 317/319 passed, includingguest_raise_exception(also 10 consecutive runs, 2000 deliveries).agc_driver_lds_atomics64andagc_driver_vopc_compare_tablefail on this machine onmainas well (Vulkan device tests).level0.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt.mdfiles or images added to the repository (attach them to this PR)🤖 Generated with Claude Code
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-05T22:56:51Z.
Thanks for this. One thing in the redirect path for a running thread:
RedirectedEntryis an ordinary MinGW function, so it uses the Windows x64 convention, where the callee owns the 32-byte home area above its return address. WithRsp = ((Rsp - 128) & ~15) - 8, that home area is[new Rsp + 8, new Rsp + 40), and it starts at or just belowold 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 spillrcx(theDelivery*) there, which would overwrite live guest data. Reserving another 32 bytes, for example((Rsp - 128 - 32) & ~15) - 8, keeps it clear.Related, and smaller:
RedirectedEntryfrees theDeliverywithdeleteon 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 theDeliveryonto the target's stack below that gap beforeSetThreadContext, and passing its address inrcx, avoids the heap on that thread entirely.The rest looks right to me: the
ucontextoffsets match thestatic_asserts, waits retry after an APC, and Linux behaviour is unchanged apart from the newEINVAL/ESRCHreturns ahead of the throw.Imported from boykopovar/AnyPS5. Originally posted by merwie on 2026-10-06T07:59:41Z.
Thanks, both fixed in
b550545b. The delivery is now copied onto the target stack at(rsp - 128 - sizeof(Delivery)) & ~15, and the entry starts atslot - 32 - 8, so its home area is[slot - 32, slot), below the copy and below the red zone.rcxpoints at the copy, and nothing on the interrupted thread touches the heap. Before writing,VirtualQuerychecks that the pages from the home area up torsp - 128are 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 mergedmain(the TechnicalDebt line next to #796's, and #761'sSetStackFromHostnext towaitStateinThread.cpp). Non-GPU tests pass, andguest_raise_exceptionpassed 5 repeated runs.Imported from boykopovar/AnyPS5. Originally posted by merwie on 2026-10-06T13:41:32Z.
Found and fixed a real bug in the redirect path while testing PPSA12544 past its intro (
3cd2ff91). A thread suspended inside a Windows system call (here Unity'sSaveDataProcessQueue, blocked in a host wait) resumes throughsysret, which overwritesrcxandr11. So theDelivery*passed inrcxwas garbage, and the handler call faulted (call *%r9with instruction bytes as the pointer). The snapshot fromGetThreadContextalso still had the system call number inrax, not its result, so restoring it after the handler would have handed the wait a bogus status.The redirected
ripis now a smallAps5RedirectedEntryStub. 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 aboversp, and jumps to the C++ entry. For a thread interrupted in user mode the live registers equal the snapshot, sincercxis no longer modified.GuestRaiseExceptiongains 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.Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-06T22:02:45Z.
Thanks. #724 (exception handler recording) is merged now, and this branch conflicts with main in
core/libs/prx/libkernel/CMakeLists.txtandSystem/src/Exception.cpp. Could you merge or rebase onto main, keeping your delivery code on top of #724's handler recording?Imported from boykopovar/AnyPS5. Originally posted by merwie on 2026-10-07T05:45:53Z.
Merged
main(as a merge, so the review history stays).main'sException.cppwas identical to the #724 commit this branch already built on, so the delivery code sits unchanged on top of #724's handler recording. InCMakeLists.txtI kept theguest_raise_exceptionregistration next to #724'sguest_exception_handler. Non-GPU tests pass (232), including both exception tests.Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-07T15:55:20Z.
Review: CHANGES_REQUESTED
Thanks, the redirect path and the asm stub look right to me (field offsets of
Delivery/CONTEXTmatch thestatic_asserts, entry stack is 8 mod 16). A few things before this can go in:Exception.cpp:198:new Deliveryruns while the target is suspended. If the target holds the allocator/CRT lock when suspended, the raising thread deadlocks. Allocate beforeSuspendThread(and don't allocate in any path between suspend and resume, including thethrowsites, which should resume first, as the others do).Exception.cpp:197,Thread.cpp:177/411:waitStatepoints into the target'sthread_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 inPthreadPrivate) and say what happens when the target already finished (ESRCH?).Exception.cpp:208: onlyCONTEXT_FULL | CONTEXT_FLOATING_POINTis 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.TimedWaitandAPS5_COARSE_TIMED_WAITS, signal masks not consulted,ucontextlayout taken from FreeBSD, Linux still throwing) need lines indocs/dev/TechnicalDebt.md(criterion: every unverified choice gets a line, under the right###section and not at the end of it).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.
Imported from boykopovar/AnyPS5. Originally posted by merwie on 2026-10-07T19:11:00Z.
Thanks, all addressed in
51b6079b:Deliveryis now allocated beforeSuspendThread(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.waitStateinto freed TLS: the counter is now a member ofPthreadPrivate(waitCount), which outlives the thread.TimedWaitcounts 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 returnsESRCH. The test raises on a returned, not-yet-joined thread and expects that.ucontextlayout; signal mask not consulted; YMM upper halves; threads outside an alertableTimedWaitwait (includingAPS5_COARSE_TIMED_WAITSand host waits) run the handler only when the wait returns.HostBlockedcase and what it pins.The exception tests pass 3 runs in a row, and the non-GPU tests pass (232).
Imported from boykopovar/AnyPS5. Originally posted by tv7 on 2026-10-07T19:25:24Z.
Data point: PPSA03306 (Silt, Unity) needs this too. On
main(cea1ef13) with #1141 and #1196, and its Unity modules relinked toMedia/Modules(#716/#717), the title aborts withsceKernelRaiseException not implemented, called fromIl2CppUserAssemblies.prx. With this PR merged locally, it gets past that point and loadsunity default resourcesandmscorlib.dll-resources.dat. It later stops at aud2in its ownlibc.prx, right aftersceKernelDebugRaiseException(0xa0020008), which looks unrelated to this change. Windows 11, GCC 15.2.0, RTX 3070.Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-07T20:02:52Z.
Review: CHANGES_REQUESTED
Thanks, everything from the last round is addressed (allocation before suspend,
waitCountinPthreadPrivate,ESRCHon a finished thread, the TechnicalDebt lines). Build and ctest are green on our side against currentmain, and the Windows job runsguest_raise_exception3/3. Two new things in the wait path, plus a minor one:TimedWait.cpp:26-31(AlertableWait, same inAlertableSleep): there is a window afterWaitForMultipleObjectsExreturns and beforefetch_sub. IfRaiseOnsuspends the target there, it seeswaitCount > 0and 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 alertableTimedWaitwait, 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), orNtTestAlertif yielding is a concern). A raise that suspends the thread after the decrement takes the redirect path anyway.TimedWait.cpp:172:Condition::waitSignalUntilcallsEventSet(waiter->event, 0)while holdingqueueLock, andEventSetis now alertable. A pending APC would run the guest handler with the condition'squeueLockheld. 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.Exception.cpp:276/198: a target that exits between the_finishedcheck andSuspendThread/GetThreadContext/QueueUserAPCmakes the raise throw instead of returningESRCH. CheckingWaitForSingleObject(native, 0) == WAIT_OBJECT_0after the suspend (then resume and returnESRCH) would cover it.Imported from boykopovar/AnyPS5. Originally posted by merwie on 2026-10-07T20:11:44Z.
Thanks. All three are addressed in
2654e3a4:AlertableWaitandAlertableSleepnow run pending APCs right after the count drops (NtTestAlert, withSleepEx(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 newLeavingpart ofguest_raise_exceptionsignals 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 underqueueLockis a plainWaitForSingleObjectnow, so no APC can run with the lock held.SuspendThread, a signalled thread handle resumes and returnsESRCH. A failed suspend on an exited thread also returnsESRCH.Merged
mainbefore this too (TechnicalDebt conflict). Non-GPU tests pass (235).Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-07T20:27:37Z.
Review: APPROVED
Thanks, all three points are addressed in
2654e3a4(APC drain after the count drops, with theLeavingtest; non-alertable 0 ms poll underqueueLock;ESRCHwhen the target exits after the suspend). Build and ctest green against currentmain; the Windows job coversguest_raise_exception. Merging once CI is green.