kernel: run raised signals on their target thread on Windows #2228
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
GPU
GUI
help wanted
question
Shaders
Video
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/KytyPS5--KytyPS5!2228
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-2228"
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?
@Nawid3333 on GitHub · 2026-11-12 06:52 UTC · original
Nawid3333:fix/guest-signal-on-target-thread→main· +717 −86 · 11 files · 5 commits · openCause
On Windows,
sceKernelRaiseException(thread, 30)marks the signal pending and queues a special user APC to the target. When the APC found the target outside guest code (in an HLE call or a wait),SignalApcHandlerstarted a detachedstd::threadthat ran the guest handler while posing as the target, and returned. The target itself kept running and could go back to guest code while its handler was still running elsewhere. On Linux and macOS the handler runs on the target itself.Unity's PS5 builds import
sceKernelInstallExceptionHandlerandsceKernelRaiseExceptionfromlibkernel_unity(inPS5Util.prx). Its liveness pass stops the other threads and tags class pointers while they are stopped:MARK_OBJsets bit 0 of an object's class pointer, in IL2CPP'slibil2cpp/vm/Liveness.cpp(betweenStopWorldandStartWorld) as in Mono's unity-liveness.c. In #2197 (Hyperspace Neptunia: Unlimited, an IL2CPP build, Windows), NekoPrism found the game crashing on exactly such a pointer (0x21085FAD1) on a background worker thread. The logs attached to issues here show the same import pair in 31 games, all IL2CPP builds.Guest code was also a fixed range,
[0x900000000, 0x980000000). Modules are mapped from0x900000000in 256 MB steps, so a game with more than 8 modules has code past that end. #2197's log shows 13 modules, up to0x9c0000000, and 11 of the 31 games load a module at0x980000000or above (#2220 Viewfinder:CommonDialog.prx,SaveData.prx,libfmod.prx,libfmodstudio.prx). A thread in those modules counted as emulator code: its handler got a context withripand every general register exceptrspandrbpzeroed (SanitizeNonGuestSignalUcontext), its changes to the context were not applied, and on Windows it took the helper path.Change
Loader::IsGuestCodeAddresscovers every mapped module:[0x900000000, g_desired_base_addr), whereg_desired_base_addris the address the next module is asked for, the first 256 MB step above the end of the last mapped module. It is atomic, since signal delivery reads it on other threads, and it advances from the address a module was mapped at (ClaimGuestCode), since the allocator can place a module above the address it was asked for.PthreadSwapSelfForSignalare removed.DispatchPendingSignals, a thread-local flag). A signal raised meanwhile by another thread stays pending and runs after the handler returns, as on Linux and macOS, where the handler is installed withoutSA_NODEFER; on Windows a raise by the handler on its own thread also waits until it returns. After the flag is released the thread checks once more, so a signal raised after its last scan is not left pending.pthread_once, kernel or POSIX semaphore, event flag or wait-on-address object, or the static object registry (GuestSignalBlock, set before the lock is taken). The signal stays pending, and the thread runs it right after it releases the lock. A wait under such a lock is cut into 10 ms slices; between two slices the thread releases the lock, runs its pending handlers, takes the lock again and checks its condition again.PthreadSelfOrNull() == thread), as the Linux and macOS handler, which takes the signals ofPthreadSelfOrNull(), and a raise from the target itself is recognized by its thread object, not by its host thread id. A reused thread object isRunningbefore its new host thread stores its id, so an id read then can belong to another thread; the APC that reaches that thread runs nothing, and the signal stays pending on its target.stateis notRunning) returnsESRCH, as FreeBSD'spthread_killdoes for a dead thread, also when its host thread id now belongs to the caller.SleepHighResolution100ns). A thread sleeps on one high-resolution waitable timer. The handler can now run on that thread between the timer being set and the wait on it; a handler that slept set the same timer again and took its signal, and the interrupted sleep never ended.Since the previous version of this PR: it is rebuilt on current main.
db7035c32removed the wait-slice poll that version delivered at, and since727ccd1c0Cancelno longer waits for its waiters, so delivery at that poll, the redelivery thread and that version's event-flag and semaphore changes are gone; event flags and semaphores now only follow the lock rule above. The handler now runs on the target also outside guest code, as on Linux (#215, the safe-point approach, was closed with "Should be good on Linux"). As on Linux and macOS, a handler can therefore run while its thread is inside emulator code. The lock rule above covers the guest sync objects, where a test here found a deadlock: a handler that landed while its thread held a guest mutex's internal lock waited for a thread that needed the same lock. Other host locks are not covered, as on Linux and macOS.Test
In
virtual_memory_allocation_tests(signal 30; all but the last two tests raise it through the exportedsceKernelRaiseException):RaisedSignalHoldsTarget: the target loops onsceKernelUsleep(100), the handler holds until released. The handler must run on the target, and the target must make no progress while it holds.RaisedSignalInterruptsGuestCode: the same with a target that spins in a few bytes of guest code mapped like a module.RaisedSignalLeavesTargetSleepIntact: 50 rounds of a raise on a target that loops onsceKernelUsleep(100), a handler that sleeps until released, and a check that the target runs again.RaisedSignalWaitsForItsHandler: a second raise while the handler sleeps must run after it, not inside it.RaisedSignalSkipsExitedTarget: a raise to a thread that has returned but is not joined yet must fail withESRCH.RaisedSignalRunsOnlyOnItsTarget: the target sets its ownPthreadSelfOrNull()to null (a test-only hook), as a thread that got an APC meant for another thread; a raise from the target itself and one from the main thread must run no handler meanwhile, and after the target has its thread object back, the signal must run once on it.RaisedSignalRunsOutsideMutexLock: the target waits for a mutex the main thread holds, and the signal is raised while the target holds the mutex's internal lock (a test-only hook in the wait loop). The handler holds until the main thread'sPthreadMutexTrylockon that mutex, which needs the same lock, has returnedEBUSY; a handler that ran under the lock would block it, and a watchdog then fails the test.RaisedSignalRunsOutsideStaticObjectRegistry: a signal is queued on the thread itself and pending while it deletes a program's static objects, as at a module unload. The handler has a second thread take the registry lock and waits for it, so it must not run while its own thread holds that lock.GuestCodeRangeFollowsAllocation: modules are mapped until one lies past0x980000000, then one above an occupied module address; both must count as guest code.Each fails when its part of the change is taken out (Windows 11, clang-cl; 5 runs each unless noted; measured on this branch before the merge of current main, except the target-check row):
RaisedSignalHoldsTarget failed: the handler ran on another thread than its targetGuestCodeRangeFollowsAllocation failed: a module past the first eight module addresses is not guest codeGuestCodeRangeFollowsAllocation failed: code mapped past an occupied module address is not guest codeRaisedSignalWaitsForItsHandler failed: a raised signal ran inside its own handlerESRCHcheck:RaisedSignalSkipsExitedTarget failed: a raise to an exited thread did not fail with ESRCH(4 of 5; the fifth run failed earlier inCpuExtensionContexts, which comparesRDPIDwith the CPU the test thread runs on)RaisedSignalLeavesTargetSleepIntact failed: the target's sleep did not end after its handler slept(20 of 20)SignalApcHandler, or with the own-thread test by host thread id instead of the thread object:RaisedSignalRunsOnlyOnItsTarget failed: a raised signal ran on a thread that is not its target(on this head, 5 of 5 each)RaisedSignalRunsOutsideMutexLock failed: the handler ran while its target held the mutex's lock(3 of 3)DeleteObjects:RaisedSignalRunsOutsideStaticObjectRegistry failed: the handler ran while the static object registry was locked(3 of 3)On this head (based on main
93cce6656):VirtualMemoryAllocationTests: all cases passedin 100 of 100 runs.common,event_queue_lifetime,sync_on_address,kernel_thread,kernel_module_info,kernel_event_flag,audio_out_timing,avplayer_fileandkernel_file_systemgive the same results on main and with the change; two of them fail on both (File.GetTimesReportsExactNanosecondsincommon,mutex waiter made progressinkernel_file_system).Fork CI on this commit: run 45679101070: the Windows job (32 of 32 tests) and the Linux job (16 of 16) pass,
virtual_memory_allocationincluded; the macOS job was cancelled before its first step.In a game
Refs #2197
Refs #2220
#833 also changes the Windows APC path (a thread interrupted by
sceKernelRaiseExceptionis parked below its 128-byte red zone before the handler runs); both changeSignalApcHandlerandKernelRaiseException.Written with Claude Code (AI): Claude Code wrote the change and the tests and ran them; Codex and DeepSeek reviewed the diff.
🤖 Generated with Claude Code
@coderabbitai[bot] on GitHub · 2026-11-12 06:59 UTC · original · edited 2026-11-25 18:49 UTC
Walkthrough
Signal delivery now uses per-thread dispatch state and a shared dispatcher to process pending signals. On Windows, the code queues APCs and retries delivery while signals remain pending. The loader tracks guest-code allocation bounds and exposes a guest-code address check. Event-flag and semaphore polling loops dispatch pending signals after sleeping. Tests cover handler thread affinity, guest-code interruption, deferred repeated delivery, and signal handling during event-flag cancellation.
Suggested reviewers:
nmzikChange: Bug fix
Merge Risk:
Moderate · previous review
28dc3The change makes raised signals run on their target thread on Windows, and the reported game tests are positive. A signal raised at a thread that has just exited can still land on an unrelated thread or spin in the dispatcher. Handlers that re-enter the event flag being cancelled can still deadlock. Fix the exited-thread raise path before merging.
Pre-merge checks:
4
Full details: Title check
Explanation
The title "kernel: run raised signals on their target thread on Windows" matches the main change. The PR stops the Windows APC path from running guest signal handlers on a detached helper thread and runs them on the target thread instead. The title is specific, short, and states the primary behavior change.
Full details: Description check
Explanation
The description explains the cause (the Windows APC path ran handlers on a detached std::thread while the target resumed), the code changes (IsGuestCodeAddress, atomic g_desired_base_addr, APC redelivery, dispatch flag, removal of PthreadSwapSelfForSignal), and the tests added. It is directly related to the changeset.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Share
@coderabbitai[bot] on GitHub · 2026-11-12 06:59 UTC · original · edited 2026-11-12 09:10 UTC
On
src/kernel/eventFlag.cppline 241 (outdated):Avoid dispatch while
Cancelowns the canceled state.If a pending handler calls
KernelSetEventFlag,KernelClearEventFlag, orKernelCancelEventFlagon this flag, that call waits form_statusto becomeSet. The outerCancelcannot restoreSetuntil the handler returns, so the target thread deadlocks.@coderabbitai[bot] on GitHub · 2026-11-12 06:59 UTC · original · edited 2026-11-12 07:39 UTC
On
src/libs/libKernel.cppline 1026 (outdated):Keep signal dispatch protected until its handler returns.
If another SIGUSR1 arrives while the first handler runs, clearing
signal_apc_queuedhere lets the raiser queue a second special APC. Windows permits a special APC to interrupt a thread that is already executing a special APC. The second invocation can enter the same guest handler before the first invocation finishes. A handler that takes a non-recursive lock can then deadlock its target. Keep an in-progress dispatch state until the handler returns, and deliver the later pending signal afterward. (raw.githubusercontent.com)✅ Addressed in commit c4e3122
@coderabbitai[bot] on GitHub · 2026-11-12 06:59 UTC · original · edited 2026-11-12 08:17 UTC
On
src/libs/libKernel.cppline 1076 (outdated):Track each pending thread and signal once.
If callers repeatedly raise SIGUSR1 while a target is in a non-alertable wait, each call appends the same pair. The pending bit cannot represent more than one such signal, but the vector grows without a bound and the worker scans every duplicate each millisecond. Deduplicate the pair under
m_mutex. A special APC does not interrupt a non-alertable wait, so this state can persist until that wait ends. (raw.githubusercontent.com)✅ Addressed in commit 7e8a108
@coderabbitai[bot] on GitHub · 2026-11-12 06:59 UTC · original · edited 2026-11-12 09:11 UTC
On
src/libs/libKernel.cppline 1095 (outdated):Back off redelivery while the target remains in host code.
If a target continues to execute host user-mode code, each special APC returns at Line 1027 without consuming the signal. This loop can then queue another APC every millisecond for that target. Special APCs interrupt user-mode code immediately, so sustained host work can incur roughly 1,000 interruptions per second per pending target. Use bounded backoff or a guest-boundary delivery mechanism instead of a fixed-rate retry. (raw.githubusercontent.com)
@ -515,2 +534,4 @@}bool IsGuestCodeAddress(uint64_t address) {return address >= SYSTEM_RESERVED + CODE_BASE_OFFSET && address < g_desired_base_addr;@coderabbitai[bot] on GitHub · 2026-11-12 06:59 UTC · original · edited 2026-11-12 07:40 UTC
Base the guest-code range on the address actually allocated.
If another mapping occupies the requested module address and enough space after it,
AllocateProgramMemorycan place the module beyondg_desired_base_addr. Line 1732 still advances the bound from the requested address. For example, a 512 MiB reservation at0x900000000can move a small module beyond0x920000000, while the next bound is0x910000000.IsGuestCodeAddressthen rejects that module’s code. On Windows,SignalApcHandlerleaves its signal pending instead of handling an interrupted guest instruction. Track the allocated module ranges, or advance the bound pastprogram->base_vaddr + program->mapped_size. (raw.githubusercontent.com)✅ Addressed in commit c4e3122
@coderabbitai[bot] on GitHub · 2026-11-12 06:59 UTC · original · reviewed
Actionable comments posted: 5
8c6ce2e6-29f7-4528-9529-70b85dc19434Reviewing files that changed from the base of the PR and between
bc934ef034and 4f6f18761f4c4b26258edc7d722f809daaeadddf.src/kernel/eventFlag.cppsrc/kernel/pthread.cppsrc/kernel/pthread.hsrc/kernel/semaphore.cppsrc/libs/libKernel.cppsrc/loader/runtimeLinker.cppsrc/loader/runtimeLinker.htests/VirtualMemoryAllocationTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
@coderabbitai[bot] on GitHub · 2026-11-12 07:47 UTC · original · edited 2026-11-12 08:17 UTC
On
src/libs/libKernel.cppline 529 (outdated):Recheck pending signals after releasing the dispatch claim.
On Linux or macOS, a thread can raise a signal on itself and enter this dispatcher without entering the host signal handler. If another thread raises signal 30 after the scan passes 30 but before the claim is released, the nested host signal handler cannot claim dispatch and returns. The original scan then finishes. The bit remains pending while a target spinning in guest code has no reason to poll again. Recheck after releasing the claim, or arrange another host delivery for a failed claim.
✅ Addressed in commit 7e8a108
@coderabbitai[bot] on GitHub · 2026-11-12 07:47 UTC · original · reviewed
Actionable comments posted: 1
fcfa0c11-2734-4dfa-80ab-52a9822704a5Reviewing files that changed from the base of the PR and between 4f6f18761f4c4b26258edc7d722f809daaeadddf and c4e3122049fa96de97e2b267255461950fa5bfbd.
src/kernel/pthread.cppsrc/kernel/pthread.hsrc/libs/libKernel.cppsrc/loader/runtimeLinker.cppsrc/loader/runtimeLinker.htests/VirtualMemoryAllocationTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.
@Nawid3333 on GitHub · 2026-11-12 09:10 UTC · original
On
src/kernel/eventFlag.cppline 241 (outdated):The dispatch in this loop is what lets
Cancelfinish when Unity's liveness pass stops one of the flag's waiters. That waiter runs its handler insideWaitand stays there until the world restarts; the world restarts only after this thread has run its handler too; andCancelwaits for the waiter to leave. Without the dispatch, each waits for the other.A test for this path is in the fourth commit now:
RaisedSignalReachesCancellingThreadraises a signal on a thread insideCancelwhile a waiter's handler still holds. With the dispatch removed from this loop it fails witha thread cancelling an event flag did not run its handler while it waited for the waiters.A handler that sets, clears or cancels the same flag its thread is cancelling would spin, as you describe, and on a flag that allows several waiters, an untimed wait on it for bits the cancel pattern does not set would block, since
Waitchecks the status only after it wakes. Both need a handler that works on the object its own thread was cancelling. The window exists becauseCancelhere waits for its waiters to see the cancel (the status staysCanceleduntil they leave). If waiters compared a cancel count instead,Cancelcould return at once and both waits would go, but that changes the event-flag code itself, so I'd rather do it separately than in this PR.@Nawid3333 on GitHub · 2026-11-12 09:11 UTC · original
On
src/libs/libKernel.cppline 1095 (outdated):A target stays on the list only while its signal is pending, and a thread has at most one queued APC at a time (
signal_apc_queuedis set when one is queued and cleared when it runs or fails to queue), so a thread blocked in a non-alertable wait holds one queued APC, not one per millisecond. In guest code the first APC delivers the signal, Kyty's own waits deliver it through the wait poll, and since c4e312204 nothing is queued while the thread runs a handler.What is left is a thread running host code without waiting. There each retry is one special APC that returns at once, and the delivery decides when Unity's liveness pass can go on, so a backoff would add its delay to every stop of the world. I'd keep the fixed interval; the retries end when the thread reaches guest code or a wait.
@coderabbitai[bot] on GitHub · 2026-11-12 09:11 UTC · original
On
src/kernel/eventFlag.cppline 241 (outdated):@Nawid3333 Thank you for explaining the liveness dependency. Removing the dispatch would risk deadlocking the Unity case. From your description,
RaisedSignalReachesCancellingThreadexercises that case.The same-flag reentrancy risk remains, so I won’t mark the finding as addressed. I understand you prefer to handle it separately. Would you like me to open a follow-up issue for the same-flag operations and untimed wait cases?
You are interacting with an AI system.
@coderabbitai[bot] on GitHub · 2026-11-12 09:11 UTC · original
On
src/libs/libKernel.cppline 1095 (outdated):@Nawid3333 Thanks for explaining the latency tradeoff. I accept the decision to keep the fixed interval.
The queued-APC guard prevents a backlog. Active host code can still receive repeated APCs, but I have no measurements that establish a significant performance impact. I’m not marking the finding as addressed.
You are interacting with an AI system.
@Nawid3333 on GitHub · 2026-11-12 09:12 UTC · original
On the nitpick about the test only reaching the handler through the wait poll:
RaisedSignalInterruptsGuestCode(c4e312204) maps a few bytes of guest code, a counting loop, through the same path as a module, and runs the target in it. Only the APC on a guest RIP can deliver the signal there. The test checks that the handler runs on the target and that the loop stops while the handler holds. With the APC handler returning before it dispatches, it fails with "the handler did not run".On the second review (fixed in 3db84943a):
PthreadJoin, when both handlers have finished.@Nawid3333 on GitHub · 2026-11-12 20:42 UTC · original
Both testers have now run the current head (3db84943a): Hyperspace Neptunia: Unlimited boots (#2197), and Viewfinder's teleporters no longer crash (#2220). The description has the details and links.
@coderabbitai[bot] on GitHub · 2026-11-18 13:56 UTC · original · edited 2026-11-18 18:32 UTC
On
src/libs/libKernel.cppline 1073 (outdated):Stop queuing signals to exited targets; a recycled thread ID can receive the APC and spin.
A guest raise to a pthread that has already exited can set its pending bit after
CleanupThreadclears the mask.KernelRaiseExceptionsets the bit and callsQueueSignalApcwithout checkingalmost_done.QueueSignalApcopens the storedhost_thread_id, which Windows can reuse after the original thread ends. If the ID now belongs to another thread in this process, the APC runs there.SignalApcHandlerthen callsDispatchPendingSignalson the exitedPthread.PthreadTakePendingSignalrefuses that target becausealmost_doneis set, while the pending bit remains set. The loop inDispatchPendingSignalsdoes not exit, so the recycled thread can hang inside the APC.SignalRedeliveryalso keeps requeuing the target every millisecond while the bit stays set.Required behavior: a signal must not reach an OS thread other than its target, and an exited target must not keep a pending bit that blocks another thread. Choose a fix that enforces both. Options include:
almost_doneis set, and clear the pending bit on that path.RunThread, release it inPthreadJoin, and queue the APC through that handle. A terminated thread then fails the queue instead of resolving the stored ID again. Detached threads freed byFreeDetachedThreadsalso go throughPthreadJoin, so their handles are released there too.✅ Addressed in commit
4242d02@coderabbitai[bot] on GitHub · 2026-11-18 13:56 UTC · original · reviewed
Actionable comments posted: 1
7388ce45-c948-42e9-9665-483d687cc68eReviewing files that changed from the base of the PR and between 3db84943ab9f48f0bad6c2f7cf75aa25f0cca389 and
28dc312de2.src/kernel/pthread.cppsrc/libs/libKernel.cppsrc/loader/runtimeLinker.cppsrc/loader/runtimeLinker.htests/VirtualMemoryAllocationTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
@Nawid3333 on GitHub · 2026-11-18 18:32 UTC · original
On
src/libs/libKernel.cppline 1073 (outdated):Confirmed and fixed in
4242d028b. A raise to a thread pastCleanupThreadkept its pending bit: the new testRaisedSignalSkipsExitedTargetfails on28dc312dewitha raise to an exited thread left its signal pendingand passes on4242d028b.PthreadQueuePendingSignalsets the bit, then takes it back and fails when the target isalmost_doneorfree.KernelRaiseExceptionthen returnsKERNEL_ERROR_ESRCH, the result FreeBSD'spthread_killgives for a dead thread (lib/libthr/thread/thr_kill.clooks the target up withinclude_dead0). This also holds when the dead target's host thread id now belongs to the caller:RaiseOnCurrentThreadreturns the failed queue.CleanupThreadsetsalmost_donebefore it clears the mask, so a raise racing the exit either seesalmost_doneor has its bit cleared by the exit.PthreadJoinno longer resetsalmost_done;PthreadCreateresets it when it reuses the object.SignalApcHandlerdispatches only on its target thread (PthreadSelfOrNull() == thread), so an APC that reaches another thread through a reused host thread id runs no handler.This also answers the outside-diff comment on
DispatchPendingSignals:PthreadTakePendingSignalrefuses onlyalmost_donethreads, and those no longer keep a bit, so the loop ends.Windows 11 (RX 9070 XT, clang-cl):
virtual_memory_allocationpasses in 5 of 5 runs,event_queue_lifetimeandsync_on_addresspass,kernel_file_systemstops with exit code 0xc0000028 on this PC with main's sources as well. Before this commit the branch was rebased ontob3295bebc(per-thread guest TLS throughgs);CleanupThreadclears the pending signals before main'sDeleteThreadTls()frees the TLS.View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.