kernel: run raised signals on their target thread on Windows #2228

Open
github-bot wants to merge 5 commits from github-bot/gh-2228 into main AGit
Owner

@⁠Nawid3333 on GitHub · 2026-11-12 06:52 UTC · original
Nawid3333:fix/guest-signal-on-target-thread → main · +717 −86 · 11 files · 5 commits · open

Cause

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), SignalApcHandler started a detached std::thread that 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 sceKernelInstallExceptionHandler and sceKernelRaiseException from libkernel_unity (in PS5Util.prx). Its liveness pass stops the other threads and tags class pointers while they are stopped: MARK_OBJ sets bit 0 of an object's class pointer, in IL2CPP's libil2cpp/vm/Liveness.cpp (between StopWorld and StartWorld) 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 from 0x900000000 in 256 MB steps, so a game with more than 8 modules has code past that end. #2197's log shows 13 modules, up to 0x9c0000000, and 11 of the 31 games load a module at 0x980000000 or 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 with rip and every general register except rsp and rbp zeroed (SanitizeNonGuestSignalUcontext), its changes to the context were not applied, and on Windows it took the helper path.

Change

  • Loader::IsGuestCodeAddress covers every mapped module: [0x900000000, g_desired_base_addr), where g_desired_base_addr is 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.
  • The APC runs the handler on the target in both cases: in guest code with the interrupted context, as before, and outside guest code with the sanitized context the Linux and macOS handler already uses. The helper thread and PthreadSwapSelfForSignal are removed.
  • A thread's handler is not entered again while it runs (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 without SA_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.
  • A handler does not run while its thread holds the internal lock of a guest mutex, rwlock, condition variable, 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.
  • The APC runs a handler only on its target (PthreadSelfOrNull() == thread), as the Linux and macOS handler, which takes the signals of PthreadSelfOrNull(), and a raise from the target itself is recognized by its thread object, not by its host thread id. A reused thread object is Running before 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.
  • A raise to a thread that is exiting or already joined (state is not Running) returns ESRCH, as FreeBSD's pthread_kill does for a dead thread, also when its host thread id now belongs to the caller.
  • A sleep inside a handler waits on a timer of its own (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. db7035c32 removed the wait-slice poll that version delivered at, and since 727ccd1c0 Cancel no 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 exported sceKernelRaiseException):

  • RaisedSignalHoldsTarget: the target loops on sceKernelUsleep(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 on sceKernelUsleep(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 with ESRCH.
  • RaisedSignalRunsOnlyOnItsTarget: the target sets its own PthreadSelfOrNull() 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's PthreadMutexTrylock on that mutex, which needs the same lock, has returned EBUSY; 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 past 0x980000000, 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):

  • the tests without the kernel change: RaisedSignalHoldsTarget failed: the handler ran on another thread than its target
  • main's fixed range: GuestCodeRangeFollowsAllocation failed: a module past the first eight module addresses is not guest code
  • the bound advanced from the address asked for: GuestCodeRangeFollowsAllocation failed: code mapped past an occupied module address is not guest code
  • without the dispatch flag: RaisedSignalWaitsForItsHandler failed: a raised signal ran inside its own handler
  • without the ESRCH check: RaisedSignalSkipsExitedTarget failed: a raise to an exited thread did not fail with ESRCH (4 of 5; the fifth run failed earlier in CpuExtensionContexts, which compares RDPID with the CPU the test thread runs on)
  • without the timer change: RaisedSignalLeavesTargetSleepIntact failed: the target's sleep did not end after its handler slept (20 of 20)
  • without the target check in 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)
  • without the sync-object lock rule: RaisedSignalRunsOutsideMutexLock failed: the handler ran while its target held the mutex's lock (3 of 3)
  • without the rule in 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 passed in 100 of 100 runs. common, event_queue_lifetime, sync_on_address, kernel_thread, kernel_module_info, kernel_event_flag, audio_out_timing, avplayer_file and kernel_file_system give the same results on main and with the change; two of them fail on both (File.GetTimesReportsExactNanoseconds in common, mutex waiter made progress in kernel_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_allocation included; the macOS job was cancelled before its first step.

In a game

  • #2197, Hyperspace Neptunia: Unlimited: Shuyuyus (RX 6950 XT) ran this design before the merge of current main (5af2882): the game gets past the logo screen (comment), where the issue reports a crash on main, and a New Game plays normally into the first open-zone area (comment). Saving does not work: the game asks for the save dialog, which Kyty does not show yet, a separate problem in that thread (reply).
  • #2220, Viewfinder: no result for this design yet. The previous version (3db84943a) ran the teleporter test without a crash (comment); the issue reports a crash at about every second teleport on main.

Refs #2197
Refs #2220

#833 also changes the Windows APC path (a thread interrupted by sceKernelRaiseException is parked below its 128-byte red zone before the handler runs); both change SignalApcHandler and KernelRaiseException.

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

**@⁠Nawid3333** on GitHub · 2026-11-12 06:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2228) `Nawid3333:fix/guest-signal-on-target-thread` → `main` · +717 −86 · 11 files · 5 commits · open ## Cause 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), `SignalApcHandler` started a detached `std::thread` that 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 `sceKernelInstallExceptionHandler` and `sceKernelRaiseException` from `libkernel_unity` (in `PS5Util.prx`). Its liveness pass stops the other threads and tags class pointers while they are stopped: `MARK_OBJ` sets bit 0 of an object's class pointer, in IL2CPP's `libil2cpp/vm/Liveness.cpp` (between `StopWorld` and `StartWorld`) as in Mono's [unity-liveness.c](https://github.com/Unity-Technologies/mono/blob/unity-main/mono/metadata/unity-liveness.c#L169-L177). 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 from `0x900000000` in 256 MB steps, so a game with more than 8 modules has code past that end. #2197's log shows 13 modules, up to `0x9c0000000`, and 11 of the 31 games load a module at `0x980000000` or 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 with `rip` and every general register except `rsp` and `rbp` zeroed (`SanitizeNonGuestSignalUcontext`), its changes to the context were not applied, and on Windows it took the helper path. ## Change - `Loader::IsGuestCodeAddress` covers every mapped module: `[0x900000000, g_desired_base_addr)`, where `g_desired_base_addr` is 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. - The APC runs the handler on the target in both cases: in guest code with the interrupted context, as before, and outside guest code with the sanitized context the Linux and macOS handler already uses. The helper thread and `PthreadSwapSelfForSignal` are removed. - A thread's handler is not entered again while it runs (`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 without `SA_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. - A handler does not run while its thread holds the internal lock of a guest mutex, rwlock, condition variable, `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. - The APC runs a handler only on its target (`PthreadSelfOrNull() == thread`), as the Linux and macOS handler, which takes the signals of `PthreadSelfOrNull()`, and a raise from the target itself is recognized by its thread object, not by its host thread id. A reused thread object is `Running` before 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. - A raise to a thread that is exiting or already joined (`state` is not `Running`) returns `ESRCH`, as FreeBSD's `pthread_kill` does for a dead thread, also when its host thread id now belongs to the caller. - A sleep inside a handler waits on a timer of its own (`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. db7035c32 removed the wait-slice poll that version delivered at, and since 727ccd1c0 `Cancel` no 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 exported `sceKernelRaiseException`): - `RaisedSignalHoldsTarget`: the target loops on `sceKernelUsleep(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 on `sceKernelUsleep(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 with `ESRCH`. - `RaisedSignalRunsOnlyOnItsTarget`: the target sets its own `PthreadSelfOrNull()` 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's `PthreadMutexTrylock` on that mutex, which needs the same lock, has returned `EBUSY`; 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 past `0x980000000`, 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): - the tests without the kernel change: `RaisedSignalHoldsTarget failed: the handler ran on another thread than its target` - main's fixed range: `GuestCodeRangeFollowsAllocation failed: a module past the first eight module addresses is not guest code` - the bound advanced from the address asked for: `GuestCodeRangeFollowsAllocation failed: code mapped past an occupied module address is not guest code` - without the dispatch flag: `RaisedSignalWaitsForItsHandler failed: a raised signal ran inside its own handler` - without the `ESRCH` check: `RaisedSignalSkipsExitedTarget failed: a raise to an exited thread did not fail with ESRCH` (4 of 5; the fifth run failed earlier in `CpuExtensionContexts`, which compares `RDPID` with the CPU the test thread runs on) - without the timer change: `RaisedSignalLeavesTargetSleepIntact failed: the target's sleep did not end after its handler slept` (20 of 20) - without the target check in `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) - without the sync-object lock rule: `RaisedSignalRunsOutsideMutexLock failed: the handler ran while its target held the mutex's lock` (3 of 3) - without the rule in `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 passed` in 100 of 100 runs. `common`, `event_queue_lifetime`, `sync_on_address`, `kernel_thread`, `kernel_module_info`, `kernel_event_flag`, `audio_out_timing`, `avplayer_file` and `kernel_file_system` give the same results on main and with the change; two of them fail on both (`File.GetTimesReportsExactNanoseconds` in `common`, `mutex waiter made progress` in `kernel_file_system`). Fork CI on this commit: [run 45679101070](https://github.com/Nawid3333/KytyPS5/actions/runs/45679101070/attempts/1): the Windows job (32 of 32 tests) and the Linux job (16 of 16) pass, `virtual_memory_allocation` included; the macOS job was cancelled before its first step. ## In a game - #2197, Hyperspace Neptunia: Unlimited: Shuyuyus (RX 6950 XT) ran this design before the merge of current main (5af2882): the game gets past the logo screen ([comment](https://git.gtahub.st/github/KytyPS5--KytyPS5/issues/2197)), where the issue reports a crash on main, and a New Game plays normally into the first open-zone area ([comment](https://git.gtahub.st/github/KytyPS5--KytyPS5/issues/2197)). Saving does not work: the game asks for the save dialog, which Kyty does not show yet, a separate problem in that thread ([reply](https://git.gtahub.st/github/KytyPS5--KytyPS5/issues/2197)). - #2220, Viewfinder: no result for this design yet. The previous version (3db84943a) ran the teleporter test without a crash ([comment](https://git.gtahub.st/github/KytyPS5--KytyPS5/issues/2220)); the issue reports a crash at about every second teleport on main. Refs #2197 Refs #2220 #833 also changes the Windows APC path (a thread interrupted by `sceKernelRaiseException` is parked below its 128-byte red zone before the handler runs); both change `SignalApcHandler` and `KernelRaiseException`. 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](https://claude.com/claude-code)
Guest code was the fixed range [0x900000000, 0x980000000). Modules are
mapped from 0x900000000 in 256 MB steps, so a game with more than 8
modules has code past that end, and a signal raised on a thread in such a
module was handled as if the thread ran emulator code.

Loader::IsGuestCodeAddress now covers [0x900000000, g_desired_base_addr),
the address the next module would get. It is atomic, since signal
delivery reads it on other threads, and it advances from the address a
module was mapped at, since the allocator can place a module above the
address it was asked for.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A thread sleeps on one high-resolution waitable timer of its own. A guest
signal handler run on that thread between the timer being set and the
wait on it, and that sleeps itself, set the same timer again and took its
signal, so the interrupted sleep then waited forever. A sleep entered
while the thread's timer is in use now waits on a timer of its own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When the special user APC found the target outside guest code, it ran the
guest handler on a detached std::thread posing as the target and returned,
so the target went on running while its handler ran elsewhere. The APC
now runs the handler on the target in both cases, outside guest code with
the sanitized context the Linux and macOS handler already uses.

A signal raised while the thread's handler runs stays pending and runs
after it, also for a raise on the thread itself. A handler does not run
while its thread holds the internal lock of a guest sync object or the
static object registry: the signal stays pending until the lock is
released, and waits under such a lock are cut into 10 ms slices between
which pending handlers run with the lock released. A raise to a thread
that is exiting or already joined fails with ESRCH, as FreeBSD's
pthread_kill does for a dead thread.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A reused thread object is Running before its new host thread stores its
id, so a raise can read the id of an exited thread that the system has
given to another thread. The APC then reached that thread, and
SignalApcHandler ran the target's pending handlers there; a raise whose
stale id matched the caller's own ran them on the caller. The APC now
runs handlers only on the thread whose PthreadSelfOrNull() is its
target, as the Linux and macOS handler takes the signals of
PthreadSelfOrNull(), and a raise from the target itself is recognized
by its thread object. The signal stays pending on its target.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:17:20 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-12 06:59 UTC · original · edited 2026-11-25 18:49 UTC

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review
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: nmzik

Change: Bug fix

Merge Risk: Moderate · previous review 28dc3

The 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: Passed 4

Check name Status Explanation
Title check Passed 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 r…
Description check Passed 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 redeliv…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
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](https://github.com/KytyPS5/KytyPS5/pull/2228#issuecomment-6817040550) · edited 2026-11-25 18:49 UTC <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/2228?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg" alt="Explain Change →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- This is an auto-generated comment: review paused by coderabbit.ai --> > [!NOTE] > ## Reviews paused > > It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the `reviews.auto_review.auto_pause_after_reviewed_commits` setting. > > - Last reviewed commit: 28dc312de24214e017a99fe26f5a227f0cdab981 > - Latest commit, not reviewed: 2754e93fe49e177ef59d80c9b22316bc41096251 > > Use the following commands to manage reviews: > - `@coderabbitai resume` to resume automatic reviews. > - `@coderabbitai review` to trigger a single review. > > Use the checkboxes below for quick actions: > - [ ] <!-- {"checkboxId":"7f6cc2e2-2e4e-497a-8c31-c9e4573e93d1"} --> Resume reviews > - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> Trigger review <!-- end of auto-generated comment: review paused by coderabbit.ai --> <!-- walkthrough_start --> <details> <summary><strong>Walkthrough</strong></summary> <dl> <dd> <br> 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:** `nmzik` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> <!-- change_assessment_commit:"28dc312de24214e017a99fe26f5a227f0cdab981" --> <!-- change_assessment_priority:{"version":1,"urgency":"p2","manual":false} --> **Change:** Bug fix <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/risk-normal-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Moderate</strong> · previous review <code>28dc3</code></summary> <dl> <dd> <br> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🟡 Moderate** · up to `28dc3` --> <!-- final_review_risk_coverage:{"sourceCommitId":"28dc312de24214e017a99fe26f5a227f0cdab981","coveredCommitId":"28dc312de24214e017a99fe26f5a227f0cdab981","kind":"reviewed"} --> The 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. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4</strong></summary> <dl> <dd> <br> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | 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 r… | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | 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 redeliv… | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | <details> <summary><strong>Full details: Title check</strong></summary> <dl> <dd> <br> **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. </dd> </dl> </details> <details> <summary><strong>Full details: Description check</strong></summary> <dl> <dd> <br> **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. </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=2228)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>Share</strong></summary> <dl> <dd> <br> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </dd> </dl> </details> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-12 06:59 UTC · original · edited 2026-11-12 09:10 UTC
On src/kernel/eventFlag.cpp line 241 (outdated):

@@ -229,6 +238,7 @@ void KernelEventFlagPrivate::Cancel(uint64_t bits, int* num_waiting_threads) {
 	while (m_waiting_threads > 0) {
 		m_mutex.Unlock();
 		Common::Thread::SleepMicro(10);
+		LibKernel::KernelDispatchPendingSignalForCurrentThread();

Major · Stability & Availability · Heavy lift

Avoid dispatch while Cancel owns the canceled state.

If a pending handler calls KernelSetEventFlag, KernelClearEventFlag, or KernelCancelEventFlag on this flag, that call waits for m_status to become Set. The outer Cancel cannot restore Set until the handler returns, so the target thread deadlocks.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-12 06:59 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2228#discussion_r4547331620) · edited 2026-11-12 09:10 UTC On `src/kernel/eventFlag.cpp` line 241 (outdated): ```diff @@ -229,6 +238,7 @@ void KernelEventFlagPrivate::Cancel(uint64_t bits, int* num_waiting_threads) { while (m_waiting_threads > 0) { m_mutex.Unlock(); Common::Thread::SleepMicro(10); + LibKernel::KernelDispatchPendingSignalForCurrentThread(); ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** **Avoid dispatch while `Cancel` owns the canceled state.** If a pending handler calls `KernelSetEventFlag`, `KernelClearEventFlag`, or `KernelCancelEventFlag` on this flag, that call waits for `m_status` to become `Set`. The outer `Cancel` cannot restore `Set` until the handler returns, so the target thread deadlocks. <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:e4b5f131fecd50aa90339d4c --> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-12 06:59 UTC · original · edited 2026-11-12 07:39 UTC
On src/libs/libKernel.cpp line 1026 (outdated):

@@ -1025,32 +1023,85 @@ static NtQueueApcThreadExFunc GetNtQueueApcThreadEx() {
 static void SignalApcHandler(void* arg1, void* arg2, void* /*arg3*/, PCONTEXT context) {
 	auto*      thread = static_cast<Pthread>(arg1);
 	const auto signum = static_cast<int>(reinterpret_cast<intptr_t>(arg2));
-	if (!PthreadTakePendingSignal(thread, signum)) {
+	PthreadClearSignalApcQueued(thread);

Major · Stability & Availability · Heavy lift

Keep signal dispatch protected until its handler returns.

If another SIGUSR1 arrives while the first handler runs, clearing signal_apc_queued here 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](https://github.com/KytyPS5/KytyPS5/pull/2228#discussion_r4547331628) · edited 2026-11-12 07:39 UTC On `src/libs/libKernel.cpp` line 1026 (outdated): ```diff @@ -1025,32 +1023,85 @@ static NtQueueApcThreadExFunc GetNtQueueApcThreadEx() { static void SignalApcHandler(void* arg1, void* arg2, void* /*arg3*/, PCONTEXT context) { auto* thread = static_cast<Pthread>(arg1); const auto signum = static_cast<int>(reinterpret_cast<intptr_t>(arg2)); - if (!PthreadTakePendingSignal(thread, signum)) { + PthreadClearSignalApcQueued(thread); ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** **Keep signal dispatch protected until its handler returns.** If another SIGUSR1 arrives while the first handler runs, clearing `signal_apc_queued` here 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](https://raw.githubusercontent.com/KytyPS5/KytyPS5/4f6f18761f4c4b26258edc7d722f809daaeadddf/src/libs/libKernel.cpp)) <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:00c45646fa97447c274d5aa0 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit c4e3122
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-12 06:59 UTC · original · edited 2026-11-12 08:17 UTC
On src/libs/libKernel.cpp line 1076 (outdated):

@@ -1025,32 +1023,85 @@ static NtQueueApcThreadExFunc GetNtQueueApcThreadEx() {
 static void SignalApcHandler(void* arg1, void* arg2, void* /*arg3*/, PCONTEXT context) {
 	auto*      thread = static_cast<Pthread>(arg1);
 	const auto signum = static_cast<int>(reinterpret_cast<intptr_t>(arg2));
-	if (!PthreadTakePendingSignal(thread, signum)) {
+	PthreadClearSignalApcQueued(thread);
+	if (!Loader::IsGuestCodeAddress(context->Rip) || !PthreadTakePendingSignal(thread, signum)) {
 		return;
 	}
 
 	auto* handler = reinterpret_cast<exception_handler_func_t>(g_exception_handlers[signum]);
 	if (handler != nullptr) {
 		SignalDispatchScope scope;
-		auto                ctx           = CreateSignalUcontext(context);
-		auto                guest_context = IsGuestCodeAddress(ctx.uc_mcontext.mc_rip);
-		if (!guest_context) {
-			SanitizeNonGuestSignalUcontext(&ctx, thread);
-			std::thread([thread, signum, handler, ctx]() mutable {
-				SignalDispatchScope helper_scope;
-				auto*               previous_self = PthreadSwapSelfForSignal(thread);
-				handler(signum, &ctx);
-				PthreadSwapSelfForSignal(previous_self);
-			}).detach();
-			return;
-		}
+		auto                ctx = CreateSignalUcontext(context);
 		handler(signum, &ctx);
-		if (guest_context) {
-			ApplySignalUcontext(context, ctx);
-		}
+		ApplySignalUcontext(context, ctx);
 	}
 }
 
+static bool QueueSignalApc(Pthread thread, int signum) {
+	if (!PthreadMarkSignalApcQueued(thread)) {
+		return true;
+	}
+
+	auto*      nt_queue_apc_thread_ex = GetNtQueueApcThreadEx();
+	const auto thread_id              = static_cast<DWORD>(PthreadGetHostThreadId(thread));
+	HANDLE     target_thread =
+	    (nt_queue_apc_thread_ex != nullptr && thread_id != 0)
+	        ? OpenThread(THREAD_SET_CONTEXT | THREAD_QUERY_LIMITED_INFORMATION, FALSE, thread_id)
+	        : nullptr;
+	KytyUserApcOption option {};
+	option.UserApcFlags = KytyQueueUserApcFlagsSpecialUserApc;
+	const bool queued =
+	    target_thread != nullptr && GetProcessIdOfThread(target_thread) == GetCurrentProcessId() &&
+	    nt_queue_apc_thread_ex(target_thread, option, SignalApcHandler, thread,
+		                       reinterpret_cast<void*>(static_cast<intptr_t>(signum)),
+		                       nullptr) == 0;
+	if (target_thread != nullptr) {
+		CloseHandle(target_thread);
+	}
+	if (!queued) {
+		PthreadClearSignalApcQueued(thread);
+	}
+	return queued;
+}
+
+class SignalRedelivery {
+public:
+	static SignalRedelivery& Instance() {
+		static auto* redelivery = new SignalRedelivery;
+		return *redelivery;
+	}
+
+	void Track(Pthread thread, int signum) {
+		std::lock_guard lock(m_mutex);
+		m_targets.emplace_back(thread, signum);

Major · Performance & Scalability · Quick win

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](https://github.com/KytyPS5/KytyPS5/pull/2228#discussion_r4547331632) · edited 2026-11-12 08:17 UTC On `src/libs/libKernel.cpp` line 1076 (outdated): ```diff @@ -1025,32 +1023,85 @@ static NtQueueApcThreadExFunc GetNtQueueApcThreadEx() { static void SignalApcHandler(void* arg1, void* arg2, void* /*arg3*/, PCONTEXT context) { auto* thread = static_cast<Pthread>(arg1); const auto signum = static_cast<int>(reinterpret_cast<intptr_t>(arg2)); - if (!PthreadTakePendingSignal(thread, signum)) { + PthreadClearSignalApcQueued(thread); + if (!Loader::IsGuestCodeAddress(context->Rip) || !PthreadTakePendingSignal(thread, signum)) { return; } auto* handler = reinterpret_cast<exception_handler_func_t>(g_exception_handlers[signum]); if (handler != nullptr) { SignalDispatchScope scope; - auto ctx = CreateSignalUcontext(context); - auto guest_context = IsGuestCodeAddress(ctx.uc_mcontext.mc_rip); - if (!guest_context) { - SanitizeNonGuestSignalUcontext(&ctx, thread); - std::thread([thread, signum, handler, ctx]() mutable { - SignalDispatchScope helper_scope; - auto* previous_self = PthreadSwapSelfForSignal(thread); - handler(signum, &ctx); - PthreadSwapSelfForSignal(previous_self); - }).detach(); - return; - } + auto ctx = CreateSignalUcontext(context); handler(signum, &ctx); - if (guest_context) { - ApplySignalUcontext(context, ctx); - } + ApplySignalUcontext(context, ctx); } } +static bool QueueSignalApc(Pthread thread, int signum) { + if (!PthreadMarkSignalApcQueued(thread)) { + return true; + } + + auto* nt_queue_apc_thread_ex = GetNtQueueApcThreadEx(); + const auto thread_id = static_cast<DWORD>(PthreadGetHostThreadId(thread)); + HANDLE target_thread = + (nt_queue_apc_thread_ex != nullptr && thread_id != 0) + ? OpenThread(THREAD_SET_CONTEXT | THREAD_QUERY_LIMITED_INFORMATION, FALSE, thread_id) + : nullptr; + KytyUserApcOption option {}; + option.UserApcFlags = KytyQueueUserApcFlagsSpecialUserApc; + const bool queued = + target_thread != nullptr && GetProcessIdOfThread(target_thread) == GetCurrentProcessId() && + nt_queue_apc_thread_ex(target_thread, option, SignalApcHandler, thread, + reinterpret_cast<void*>(static_cast<intptr_t>(signum)), + nullptr) == 0; + if (target_thread != nullptr) { + CloseHandle(target_thread); + } + if (!queued) { + PthreadClearSignalApcQueued(thread); + } + return queued; +} + +class SignalRedelivery { +public: + static SignalRedelivery& Instance() { + static auto* redelivery = new SignalRedelivery; + return *redelivery; + } + + void Track(Pthread thread, int signum) { + std::lock_guard lock(m_mutex); + m_targets.emplace_back(thread, signum); ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Performance & Scalability** · **Quick win** **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](https://raw.githubusercontent.com/KytyPS5/KytyPS5/4f6f18761f4c4b26258edc7d722f809daaeadddf/src/libs/libKernel.cpp)) <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:68f7459c14c114166109c377 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 7e8a108
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-12 06:59 UTC · original · edited 2026-11-12 09:11 UTC
On src/libs/libKernel.cpp line 1095 (outdated):

@@ -1025,32 +1023,85 @@ static NtQueueApcThreadExFunc GetNtQueueApcThreadEx() {
 static void SignalApcHandler(void* arg1, void* arg2, void* /*arg3*/, PCONTEXT context) {
 	auto*      thread = static_cast<Pthread>(arg1);
 	const auto signum = static_cast<int>(reinterpret_cast<intptr_t>(arg2));
-	if (!PthreadTakePendingSignal(thread, signum)) {
+	PthreadClearSignalApcQueued(thread);
+	if (!Loader::IsGuestCodeAddress(context->Rip) || !PthreadTakePendingSignal(thread, signum)) {
 		return;
 	}
 
 	auto* handler = reinterpret_cast<exception_handler_func_t>(g_exception_handlers[signum]);
 	if (handler != nullptr) {
 		SignalDispatchScope scope;
-		auto                ctx           = CreateSignalUcontext(context);
-		auto                guest_context = IsGuestCodeAddress(ctx.uc_mcontext.mc_rip);
-		if (!guest_context) {
-			SanitizeNonGuestSignalUcontext(&ctx, thread);
-			std::thread([thread, signum, handler, ctx]() mutable {
-				SignalDispatchScope helper_scope;
-				auto*               previous_self = PthreadSwapSelfForSignal(thread);
-				handler(signum, &ctx);
-				PthreadSwapSelfForSignal(previous_self);
-			}).detach();
-			return;
-		}
+		auto                ctx = CreateSignalUcontext(context);
 		handler(signum, &ctx);
-		if (guest_context) {
-			ApplySignalUcontext(context, ctx);
-		}
+		ApplySignalUcontext(context, ctx);
 	}
 }
 
+static bool QueueSignalApc(Pthread thread, int signum) {
+	if (!PthreadMarkSignalApcQueued(thread)) {
+		return true;
+	}
+
+	auto*      nt_queue_apc_thread_ex = GetNtQueueApcThreadEx();
+	const auto thread_id              = static_cast<DWORD>(PthreadGetHostThreadId(thread));
+	HANDLE     target_thread =
+	    (nt_queue_apc_thread_ex != nullptr && thread_id != 0)
+	        ? OpenThread(THREAD_SET_CONTEXT | THREAD_QUERY_LIMITED_INFORMATION, FALSE, thread_id)
+	        : nullptr;
+	KytyUserApcOption option {};
+	option.UserApcFlags = KytyQueueUserApcFlagsSpecialUserApc;
+	const bool queued =
+	    target_thread != nullptr && GetProcessIdOfThread(target_thread) == GetCurrentProcessId() &&
+	    nt_queue_apc_thread_ex(target_thread, option, SignalApcHandler, thread,
+		                       reinterpret_cast<void*>(static_cast<intptr_t>(signum)),
+		                       nullptr) == 0;
+	if (target_thread != nullptr) {
+		CloseHandle(target_thread);
+	}
+	if (!queued) {
+		PthreadClearSignalApcQueued(thread);
+	}
+	return queued;
+}
+
+class SignalRedelivery {
+public:
+	static SignalRedelivery& Instance() {
+		static auto* redelivery = new SignalRedelivery;
+		return *redelivery;
+	}
+
+	void Track(Pthread thread, int signum) {
+		std::lock_guard lock(m_mutex);
+		m_targets.emplace_back(thread, signum);
+		if (!m_started) {
+			m_started = true;
+			std::thread([this] { Run(); }).detach();
+		}
+		m_cv.notify_one();
+	}
+
+private:
+	void Run() {
+		constexpr auto REDELIVERY_INTERVAL = std::chrono::milliseconds(1);
+
+		std::unique_lock lock(m_mutex);
+		for (;;) {
+			m_cv.wait(lock, [this] { return !m_targets.empty(); });
+			m_cv.wait_for(lock, REDELIVERY_INTERVAL);
+			std::erase_if(m_targets, [](const auto& target) {
+				return !PthreadHasPendingSignal(target.first, target.second) ||
+				       !QueueSignalApc(target.first, target.second);
+			});

Major · Performance & Scalability · Heavy lift

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)

**@⁠coderabbitai[bot]** on GitHub · 2026-11-12 06:59 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2228#discussion_r4547331638) · edited 2026-11-12 09:11 UTC On `src/libs/libKernel.cpp` line 1095 (outdated): ```diff @@ -1025,32 +1023,85 @@ static NtQueueApcThreadExFunc GetNtQueueApcThreadEx() { static void SignalApcHandler(void* arg1, void* arg2, void* /*arg3*/, PCONTEXT context) { auto* thread = static_cast<Pthread>(arg1); const auto signum = static_cast<int>(reinterpret_cast<intptr_t>(arg2)); - if (!PthreadTakePendingSignal(thread, signum)) { + PthreadClearSignalApcQueued(thread); + if (!Loader::IsGuestCodeAddress(context->Rip) || !PthreadTakePendingSignal(thread, signum)) { return; } auto* handler = reinterpret_cast<exception_handler_func_t>(g_exception_handlers[signum]); if (handler != nullptr) { SignalDispatchScope scope; - auto ctx = CreateSignalUcontext(context); - auto guest_context = IsGuestCodeAddress(ctx.uc_mcontext.mc_rip); - if (!guest_context) { - SanitizeNonGuestSignalUcontext(&ctx, thread); - std::thread([thread, signum, handler, ctx]() mutable { - SignalDispatchScope helper_scope; - auto* previous_self = PthreadSwapSelfForSignal(thread); - handler(signum, &ctx); - PthreadSwapSelfForSignal(previous_self); - }).detach(); - return; - } + auto ctx = CreateSignalUcontext(context); handler(signum, &ctx); - if (guest_context) { - ApplySignalUcontext(context, ctx); - } + ApplySignalUcontext(context, ctx); } } +static bool QueueSignalApc(Pthread thread, int signum) { + if (!PthreadMarkSignalApcQueued(thread)) { + return true; + } + + auto* nt_queue_apc_thread_ex = GetNtQueueApcThreadEx(); + const auto thread_id = static_cast<DWORD>(PthreadGetHostThreadId(thread)); + HANDLE target_thread = + (nt_queue_apc_thread_ex != nullptr && thread_id != 0) + ? OpenThread(THREAD_SET_CONTEXT | THREAD_QUERY_LIMITED_INFORMATION, FALSE, thread_id) + : nullptr; + KytyUserApcOption option {}; + option.UserApcFlags = KytyQueueUserApcFlagsSpecialUserApc; + const bool queued = + target_thread != nullptr && GetProcessIdOfThread(target_thread) == GetCurrentProcessId() && + nt_queue_apc_thread_ex(target_thread, option, SignalApcHandler, thread, + reinterpret_cast<void*>(static_cast<intptr_t>(signum)), + nullptr) == 0; + if (target_thread != nullptr) { + CloseHandle(target_thread); + } + if (!queued) { + PthreadClearSignalApcQueued(thread); + } + return queued; +} + +class SignalRedelivery { +public: + static SignalRedelivery& Instance() { + static auto* redelivery = new SignalRedelivery; + return *redelivery; + } + + void Track(Pthread thread, int signum) { + std::lock_guard lock(m_mutex); + m_targets.emplace_back(thread, signum); + if (!m_started) { + m_started = true; + std::thread([this] { Run(); }).detach(); + } + m_cv.notify_one(); + } + +private: + void Run() { + constexpr auto REDELIVERY_INTERVAL = std::chrono::milliseconds(1); + + std::unique_lock lock(m_mutex); + for (;;) { + m_cv.wait(lock, [this] { return !m_targets.empty(); }); + m_cv.wait_for(lock, REDELIVERY_INTERVAL); + std::erase_if(m_targets, [](const auto& target) { + return !PthreadHasPendingSignal(target.first, target.second) || + !QueueSignalApc(target.first, target.second); + }); ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Performance & Scalability** · **Heavy lift** **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](https://raw.githubusercontent.com/KytyPS5/KytyPS5/4f6f18761f4c4b26258edc7d722f809daaeadddf/src/libs/libKernel.cpp)) <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:c348ccff61d023869821105c --> <!-- This is an auto-generated reply by CodeRabbit -->
@ -515,2 +534,4 @@
}
bool IsGuestCodeAddress(uint64_t address) {
return address >= SYSTEM_RESERVED + CODE_BASE_OFFSET && address < g_desired_base_addr;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-12 06:59 UTC · original · edited 2026-11-12 07:40 UTC

Major · Functional Correctness · Heavy lift

Base the guest-code range on the address actually allocated.

If another mapping occupies the requested module address and enough space after it, AllocateProgramMemory can place the module beyond g_desired_base_addr. Line 1732 still advances the bound from the requested address. For example, a 512 MiB reservation at 0x900000000 can move a small module beyond 0x920000000, while the next bound is 0x910000000. IsGuestCodeAddress then rejects that module’s code. On Windows, SignalApcHandler leaves its signal pending instead of handling an interrupted guest instruction. Track the allocated module ranges, or advance the bound past program->base_vaddr + program->mapped_size. (raw.githubusercontent.com)

✅ Addressed in commit c4e3122

**@⁠coderabbitai[bot]** on GitHub · 2026-11-12 06:59 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2228#discussion_r4547331644) · edited 2026-11-12 07:40 UTC <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Heavy lift** **Base the guest-code range on the address actually allocated.** If another mapping occupies the requested module address and enough space after it, `AllocateProgramMemory` can place the module beyond `g_desired_base_addr`. Line 1732 still advances the bound from the *requested* address. For example, a 512 MiB reservation at `0x900000000` can move a small module beyond `0x920000000`, while the next bound is `0x910000000`. `IsGuestCodeAddress` then rejects that module’s code. On Windows, `SignalApcHandler` leaves its signal pending instead of handling an interrupted guest instruction. Track the allocated module ranges, or advance the bound past `program->base_vaddr + program->mapped_size`. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/4f6f18761f4c4b26258edc7d722f809daaeadddf/src/kernel/memory.cpp)) <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:d792a0faf8846ace87515915 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit c4e3122
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-12 06:59 UTC · original · reviewed

Actionable comments posted: 5

Nitpick comments: 1

tests/VirtualMemoryAllocationTests.cpp: 1

5932-5932: Trivial · Maintainability & Code Quality · Heavy lift

Exercise the guest-RIP APC path in this test.

RunSignalTarget is host code, and this test loads no guest program. Loader::IsGuestCodeAddress therefore rejects the APC’s interrupted RIP. The worker can still run HoldRaisedSignal through KernelUsleep polling, so the test passes even if guest-RIP APC dispatch fails. Add a mapped guest-code target or a separate test that holds the handler after an APC interrupts guest code. (raw.githubusercontent.com)

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between bc934ef034 and 4f6f18761f4c4b26258edc7d722f809daaeadddf.

Files selected for processing: 8

  • src/kernel/eventFlag.cpp
  • src/kernel/pthread.cpp
  • src/kernel/pthread.h
  • src/kernel/semaphore.cpp
  • src/libs/libKernel.cpp
  • src/loader/runtimeLinker.cpp
  • src/loader/runtimeLinker.h
  • tests/VirtualMemoryAllocationTests.cpp

Included 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 06:59 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2228#pullrequestreview-5870425463) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 5** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning.svg" width="16" height="16" align="absmiddle" alt=""></picture> Nitpick comments: 1</summary><blockquote> <dl> <dd> <br> <details> <summary>tests/VirtualMemoryAllocationTests.cpp: 1</summary><blockquote> <dl> <dd> <br> `5932-5932`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Maintainability & Code Quality** · **Heavy lift** **Exercise the guest-RIP APC path in this test.** `RunSignalTarget` is host code, and this test loads no guest program. `Loader::IsGuestCodeAddress` therefore rejects the APC’s interrupted RIP. The worker can still run `HoldRaisedSignal` through `KernelUsleep` polling, so the test passes even if guest-RIP APC dispatch fails. Add a mapped guest-code target or a separate test that holds the handler after an APC interrupts guest code. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/4f6f18761f4c4b26258edc7d722f809daaeadddf/tests/VirtualMemoryAllocationTests.cpp)) <!-- cr-comment:v1:86ef484c11088d17269357af --> </dd> </dl> </blockquote></details> </dd> </dl> </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/bc934ef03410b760fbf8e49db1d79485e7e5f887/.coderabbit.yaml>) - **Commit**: [bc934ef](<https://github.com/KytyPS5/KytyPS5/commit/bc934ef03410b760fbf8e49db1d79485e7e5f887>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `8c6ce2e6-29f7-4528-9529-70b85dc19434` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between bc934ef03410b760fbf8e49db1d79485e7e5f887 and 4f6f18761f4c4b26258edc7d722f809daaeadddf. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 8</summary> <dl> <dd> <br> * `src/kernel/eventFlag.cpp` * `src/kernel/pthread.cpp` * `src/kernel/pthread.h` * `src/kernel/semaphore.cpp` * `src/libs/libKernel.cpp` * `src/loader/runtimeLinker.cpp` * `src/loader/runtimeLinker.h` * `tests/VirtualMemoryAllocationTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=087b02b4-cab2-4272-a113-f316d7eb31b0 attempt=ff8c9240-ad4f-4915-8bde-27851b46a852 batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-12 07:47 UTC · original · edited 2026-11-12 08:17 UTC
On src/libs/libKernel.cpp line 529 (outdated):

@@ -497,18 +499,46 @@ using exception_handler_func_t = KYTY_SYSV_ABI void (*)(int, void*);
 static thread_local bool g_dispatching_signal_handler = false;
 
 struct SignalDispatchScope {
-	SignalDispatchScope(): previous(g_dispatching_signal_handler) {
+	explicit SignalDispatchScope(Pthread thread)
+	    : thread(thread), owned(PthreadBeginSignalDispatch(thread)),
+	      previous(g_dispatching_signal_handler) {
 		g_dispatching_signal_handler = true;
 	}
-	~SignalDispatchScope() { g_dispatching_signal_handler = previous; }
+	~SignalDispatchScope() {
+		if (owned) {
+			PthreadEndSignalDispatch(thread);
+		}
+		g_dispatching_signal_handler = previous;
+	}
 
-	bool previous;
+	Pthread thread;
+	bool    owned;
+	bool    previous;
 };
 
 bool KernelIsDispatchingSignalOnCurrentThread() {
 	return g_dispatching_signal_handler;
 }
 
+template <typename Deliver>
+static void DispatchPendingSignals(Pthread thread, Deliver deliver) {
+	SignalDispatchScope scope(thread);
+	if (!scope.owned) {
+		return;
+	}
+	for (int signum = 0; signum < static_cast<int>(std::size(g_exception_handlers));) {

Major · Stability & Availability · Heavy lift

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](https://github.com/KytyPS5/KytyPS5/pull/2228#discussion_r4547681705) · edited 2026-11-12 08:17 UTC On `src/libs/libKernel.cpp` line 529 (outdated): ```diff @@ -497,18 +499,46 @@ using exception_handler_func_t = KYTY_SYSV_ABI void (*)(int, void*); static thread_local bool g_dispatching_signal_handler = false; struct SignalDispatchScope { - SignalDispatchScope(): previous(g_dispatching_signal_handler) { + explicit SignalDispatchScope(Pthread thread) + : thread(thread), owned(PthreadBeginSignalDispatch(thread)), + previous(g_dispatching_signal_handler) { g_dispatching_signal_handler = true; } - ~SignalDispatchScope() { g_dispatching_signal_handler = previous; } + ~SignalDispatchScope() { + if (owned) { + PthreadEndSignalDispatch(thread); + } + g_dispatching_signal_handler = previous; + } - bool previous; + Pthread thread; + bool owned; + bool previous; }; bool KernelIsDispatchingSignalOnCurrentThread() { return g_dispatching_signal_handler; } +template <typename Deliver> +static void DispatchPendingSignals(Pthread thread, Deliver deliver) { + SignalDispatchScope scope(thread); + if (!scope.owned) { + return; + } + for (int signum = 0; signum < static_cast<int>(std::size(g_exception_handlers));) { ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** **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. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:70197007749dfa3f3a702ba5 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 7e8a108
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-12 07:47 UTC · original · reviewed

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Major · Keep a pending target after an APC retry fails. · libKernel.cpp:1107-1109

src/libs/libKernel.cpp:1107-1109
Major · Stability & Availability · Heavy lift

Keep a pending target after an APC retry fails.

If an APC first runs outside guest code, SignalApcHandler leaves the signal pending for this worker to retry. If a later QueueSignalApc call fails while the target remains alive, erase_if stops all retries but leaves the pending bit set. A target that does not reach a wait poll never receives the signal, although KernelRaiseException already returned OK. Retain the target for a recoverable queue failure, or define a failure transition that does not leave an undeliverable pending signal.

Nitpick comments: 2

tests/VirtualMemoryAllocationTests.cpp: 2

6078-6078: Trivial · Maintainability & Code Quality · Quick win

Check that the second handler runs on the canceller.

Two handler entries show that two deliveries occurred. They do not show that the cancellation signal ran on canceller.id; a helper-thread delivery would also satisfy this check. Compare g_raised_signal_thread with canceller.id after the second entry and before releasing the handlers.


6100-6100: Trivial · Maintainability & Code Quality · Quick win

Read maximum nesting after both handlers finish.

This read occurs before g_raised_signal_release becomes true. A second handler can enter between this read and the first handler’s decrement of g_raised_signal_depth. The test can then observe two entries but still compare the earlier value of one. Move the maximum-depth read after PthreadJoin.

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 4f6f18761f4c4b26258edc7d722f809daaeadddf and c4e3122049fa96de97e2b267255461950fa5bfbd.

Files selected for processing: 6

  • src/kernel/pthread.cpp
  • src/kernel/pthread.h
  • src/libs/libKernel.cpp
  • src/loader/runtimeLinker.cpp
  • src/loader/runtimeLinker.h
  • tests/VirtualMemoryAllocationTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-12 07:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2228#pullrequestreview-5870888483) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 1** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (1)** > > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major</strong> · Keep a pending target after an APC retry fails. · <code>libKernel.cpp:1107-1109</code></summary><blockquote> > <dl> > <dd> > <br> > > `src/libs/libKernel.cpp:1107-1109` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** > > **Keep a pending target after an APC retry fails.** > > If an APC first runs outside guest code, `SignalApcHandler` leaves the signal pending for this worker to retry. If a later `QueueSignalApc` call fails while the target remains alive, `erase_if` stops all retries but leaves the pending bit set. A target that does not reach a wait poll never receives the signal, although `KernelRaiseException` already returned `OK`. Retain the target for a recoverable queue failure, or define a failure transition that does not leave an undeliverable pending signal. > > <!-- cr-comment:v1:aedf9c0bdb1eb645b504af15 --> > > </dd> > </dl> > </blockquote></details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning.svg" width="16" height="16" align="absmiddle" alt=""></picture> Nitpick comments: 2</summary><blockquote> <dl> <dd> <br> <details> <summary>tests/VirtualMemoryAllocationTests.cpp: 2</summary><blockquote> <dl> <dd> <br> `6078-6078`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Maintainability & Code Quality** · **Quick win** **Check that the second handler runs on the canceller.** Two handler entries show that two deliveries occurred. They do not show that the cancellation signal ran on `canceller.id`; a helper-thread delivery would also satisfy this check. Compare `g_raised_signal_thread` with `canceller.id` after the second entry and before releasing the handlers. <!-- cr-comment:v1:fc04d201c212f8f54e682acd --> --- `6100-6100`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Maintainability & Code Quality** · **Quick win** **Read maximum nesting after both handlers finish.** This read occurs before `g_raised_signal_release` becomes true. A second handler can enter between this read and the first handler’s decrement of `g_raised_signal_depth`. The test can then observe two entries but still compare the earlier value of one. Move the maximum-depth read after `PthreadJoin`. <!-- cr-comment:v1:9e5a9ff2c1a0530ae086f33a --> </dd> </dl> </blockquote></details> </dd> </dl> </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/bc934ef03410b760fbf8e49db1d79485e7e5f887/.coderabbit.yaml>) - **Commit**: [bc934ef](<https://github.com/KytyPS5/KytyPS5/commit/bc934ef03410b760fbf8e49db1d79485e7e5f887>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `fcfa0c11-2734-4dfa-80ab-52a9822704a5` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 4f6f18761f4c4b26258edc7d722f809daaeadddf and c4e3122049fa96de97e2b267255461950fa5bfbd. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 6</summary> <dl> <dd> <br> * `src/kernel/pthread.cpp` * `src/kernel/pthread.h` * `src/libs/libKernel.cpp` * `src/loader/runtimeLinker.cpp` * `src/loader/runtimeLinker.h` * `tests/VirtualMemoryAllocationTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=e73bb93f-b9b2-4e9a-89b4-2d4a40468515 attempt=8b6d703f-df05-49ad-a7f2-ca3f92bb31f5 batch=1/1 -->
Author
Owner

@⁠Nawid3333 on GitHub · 2026-11-12 09:10 UTC · original
On src/kernel/eventFlag.cpp line 241 (outdated):

@@ -229,6 +238,7 @@ void KernelEventFlagPrivate::Cancel(uint64_t bits, int* num_waiting_threads) {
 	while (m_waiting_threads > 0) {
 		m_mutex.Unlock();
 		Common::Thread::SleepMicro(10);
+		LibKernel::KernelDispatchPendingSignalForCurrentThread();

The dispatch in this loop is what lets Cancel finish when Unity's liveness pass stops one of the flag's waiters. That waiter runs its handler inside Wait and stays there until the world restarts; the world restarts only after this thread has run its handler too; and Cancel waits for the waiter to leave. Without the dispatch, each waits for the other.

A test for this path is in the fourth commit now: RaisedSignalReachesCancellingThread raises a signal on a thread inside Cancel while a waiter's handler still holds. With the dispatch removed from this loop it fails with a 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 Wait checks the status only after it wakes. Both need a handler that works on the object its own thread was cancelling. The window exists because Cancel here waits for its waiters to see the cancel (the status stays Canceled until they leave). If waiters compared a cancel count instead, Cancel could 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:10 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2228#discussion_r4548422658) On `src/kernel/eventFlag.cpp` line 241 (outdated): ```diff @@ -229,6 +238,7 @@ void KernelEventFlagPrivate::Cancel(uint64_t bits, int* num_waiting_threads) { while (m_waiting_threads > 0) { m_mutex.Unlock(); Common::Thread::SleepMicro(10); + LibKernel::KernelDispatchPendingSignalForCurrentThread(); ``` The dispatch in this loop is what lets `Cancel` finish when Unity's liveness pass stops one of the flag's waiters. That waiter runs its handler inside `Wait` and stays there until the world restarts; the world restarts only after this thread has run its handler too; and `Cancel` waits for the waiter to leave. Without the dispatch, each waits for the other. A test for this path is in the fourth commit now: `RaisedSignalReachesCancellingThread` raises a signal on a thread inside `Cancel` while a waiter's handler still holds. With the dispatch removed from this loop it fails with `a 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 `Wait` checks the status only after it wakes. Both need a handler that works on the object its own thread was cancelling. The window exists because `Cancel` here waits for its waiters to see the cancel (the status stays `Canceled` until they leave). If waiters compared a cancel count instead, `Cancel` could 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.
Author
Owner

@⁠Nawid3333 on GitHub · 2026-11-12 09:11 UTC · original
On src/libs/libKernel.cpp line 1095 (outdated):

@@ -1025,32 +1023,85 @@ static NtQueueApcThreadExFunc GetNtQueueApcThreadEx() {
 static void SignalApcHandler(void* arg1, void* arg2, void* /*arg3*/, PCONTEXT context) {
 	auto*      thread = static_cast<Pthread>(arg1);
 	const auto signum = static_cast<int>(reinterpret_cast<intptr_t>(arg2));
-	if (!PthreadTakePendingSignal(thread, signum)) {
+	PthreadClearSignalApcQueued(thread);
+	if (!Loader::IsGuestCodeAddress(context->Rip) || !PthreadTakePendingSignal(thread, signum)) {
 		return;
 	}
 
 	auto* handler = reinterpret_cast<exception_handler_func_t>(g_exception_handlers[signum]);
 	if (handler != nullptr) {
 		SignalDispatchScope scope;
-		auto                ctx           = CreateSignalUcontext(context);
-		auto                guest_context = IsGuestCodeAddress(ctx.uc_mcontext.mc_rip);
-		if (!guest_context) {
-			SanitizeNonGuestSignalUcontext(&ctx, thread);
-			std::thread([thread, signum, handler, ctx]() mutable {
-				SignalDispatchScope helper_scope;
-				auto*               previous_self = PthreadSwapSelfForSignal(thread);
-				handler(signum, &ctx);
-				PthreadSwapSelfForSignal(previous_self);
-			}).detach();
-			return;
-		}
+		auto                ctx = CreateSignalUcontext(context);
 		handler(signum, &ctx);
-		if (guest_context) {
-			ApplySignalUcontext(context, ctx);
-		}
+		ApplySignalUcontext(context, ctx);
 	}
 }
 
+static bool QueueSignalApc(Pthread thread, int signum) {
+	if (!PthreadMarkSignalApcQueued(thread)) {
+		return true;
+	}
+
+	auto*      nt_queue_apc_thread_ex = GetNtQueueApcThreadEx();
+	const auto thread_id              = static_cast<DWORD>(PthreadGetHostThreadId(thread));
+	HANDLE     target_thread =
+	    (nt_queue_apc_thread_ex != nullptr && thread_id != 0)
+	        ? OpenThread(THREAD_SET_CONTEXT | THREAD_QUERY_LIMITED_INFORMATION, FALSE, thread_id)
+	        : nullptr;
+	KytyUserApcOption option {};
+	option.UserApcFlags = KytyQueueUserApcFlagsSpecialUserApc;
+	const bool queued =
+	    target_thread != nullptr && GetProcessIdOfThread(target_thread) == GetCurrentProcessId() &&
+	    nt_queue_apc_thread_ex(target_thread, option, SignalApcHandler, thread,
+		                       reinterpret_cast<void*>(static_cast<intptr_t>(signum)),
+		                       nullptr) == 0;
+	if (target_thread != nullptr) {
+		CloseHandle(target_thread);
+	}
+	if (!queued) {
+		PthreadClearSignalApcQueued(thread);
+	}
+	return queued;
+}
+
+class SignalRedelivery {
+public:
+	static SignalRedelivery& Instance() {
+		static auto* redelivery = new SignalRedelivery;
+		return *redelivery;
+	}
+
+	void Track(Pthread thread, int signum) {
+		std::lock_guard lock(m_mutex);
+		m_targets.emplace_back(thread, signum);
+		if (!m_started) {
+			m_started = true;
+			std::thread([this] { Run(); }).detach();
+		}
+		m_cv.notify_one();
+	}
+
+private:
+	void Run() {
+		constexpr auto REDELIVERY_INTERVAL = std::chrono::milliseconds(1);
+
+		std::unique_lock lock(m_mutex);
+		for (;;) {
+			m_cv.wait(lock, [this] { return !m_targets.empty(); });
+			m_cv.wait_for(lock, REDELIVERY_INTERVAL);
+			std::erase_if(m_targets, [](const auto& target) {
+				return !PthreadHasPendingSignal(target.first, target.second) ||
+				       !QueueSignalApc(target.first, target.second);
+			});

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_queued is 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.

**@⁠Nawid3333** on GitHub · 2026-11-12 09:11 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2228#discussion_r4548427169) On `src/libs/libKernel.cpp` line 1095 (outdated): ```diff @@ -1025,32 +1023,85 @@ static NtQueueApcThreadExFunc GetNtQueueApcThreadEx() { static void SignalApcHandler(void* arg1, void* arg2, void* /*arg3*/, PCONTEXT context) { auto* thread = static_cast<Pthread>(arg1); const auto signum = static_cast<int>(reinterpret_cast<intptr_t>(arg2)); - if (!PthreadTakePendingSignal(thread, signum)) { + PthreadClearSignalApcQueued(thread); + if (!Loader::IsGuestCodeAddress(context->Rip) || !PthreadTakePendingSignal(thread, signum)) { return; } auto* handler = reinterpret_cast<exception_handler_func_t>(g_exception_handlers[signum]); if (handler != nullptr) { SignalDispatchScope scope; - auto ctx = CreateSignalUcontext(context); - auto guest_context = IsGuestCodeAddress(ctx.uc_mcontext.mc_rip); - if (!guest_context) { - SanitizeNonGuestSignalUcontext(&ctx, thread); - std::thread([thread, signum, handler, ctx]() mutable { - SignalDispatchScope helper_scope; - auto* previous_self = PthreadSwapSelfForSignal(thread); - handler(signum, &ctx); - PthreadSwapSelfForSignal(previous_self); - }).detach(); - return; - } + auto ctx = CreateSignalUcontext(context); handler(signum, &ctx); - if (guest_context) { - ApplySignalUcontext(context, ctx); - } + ApplySignalUcontext(context, ctx); } } +static bool QueueSignalApc(Pthread thread, int signum) { + if (!PthreadMarkSignalApcQueued(thread)) { + return true; + } + + auto* nt_queue_apc_thread_ex = GetNtQueueApcThreadEx(); + const auto thread_id = static_cast<DWORD>(PthreadGetHostThreadId(thread)); + HANDLE target_thread = + (nt_queue_apc_thread_ex != nullptr && thread_id != 0) + ? OpenThread(THREAD_SET_CONTEXT | THREAD_QUERY_LIMITED_INFORMATION, FALSE, thread_id) + : nullptr; + KytyUserApcOption option {}; + option.UserApcFlags = KytyQueueUserApcFlagsSpecialUserApc; + const bool queued = + target_thread != nullptr && GetProcessIdOfThread(target_thread) == GetCurrentProcessId() && + nt_queue_apc_thread_ex(target_thread, option, SignalApcHandler, thread, + reinterpret_cast<void*>(static_cast<intptr_t>(signum)), + nullptr) == 0; + if (target_thread != nullptr) { + CloseHandle(target_thread); + } + if (!queued) { + PthreadClearSignalApcQueued(thread); + } + return queued; +} + +class SignalRedelivery { +public: + static SignalRedelivery& Instance() { + static auto* redelivery = new SignalRedelivery; + return *redelivery; + } + + void Track(Pthread thread, int signum) { + std::lock_guard lock(m_mutex); + m_targets.emplace_back(thread, signum); + if (!m_started) { + m_started = true; + std::thread([this] { Run(); }).detach(); + } + m_cv.notify_one(); + } + +private: + void Run() { + constexpr auto REDELIVERY_INTERVAL = std::chrono::milliseconds(1); + + std::unique_lock lock(m_mutex); + for (;;) { + m_cv.wait(lock, [this] { return !m_targets.empty(); }); + m_cv.wait_for(lock, REDELIVERY_INTERVAL); + std::erase_if(m_targets, [](const auto& target) { + return !PthreadHasPendingSignal(target.first, target.second) || + !QueueSignalApc(target.first, target.second); + }); ``` 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_queued` is 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.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-12 09:11 UTC · original
On src/kernel/eventFlag.cpp line 241 (outdated):

@@ -229,6 +238,7 @@ void KernelEventFlagPrivate::Cancel(uint64_t bits, int* num_waiting_threads) {
 	while (m_waiting_threads > 0) {
 		m_mutex.Unlock();
 		Common::Thread::SleepMicro(10);
+		LibKernel::KernelDispatchPendingSignalForCurrentThread();

@⁠Nawid3333 Thank you for explaining the liveness dependency. Removing the dispatch would risk deadlocking the Unity case. From your description, RaisedSignalReachesCancellingThread exercises 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](https://github.com/KytyPS5/KytyPS5/pull/2228#discussion_r4548427828) On `src/kernel/eventFlag.cpp` line 241 (outdated): ```diff @@ -229,6 +238,7 @@ void KernelEventFlagPrivate::Cancel(uint64_t bits, int* num_waiting_threads) { while (m_waiting_threads > 0) { m_mutex.Unlock(); Common::Thread::SleepMicro(10); + LibKernel::KernelDispatchPendingSignalForCurrentThread(); ``` <!-- coderabbit-ai-generated:v1 --> @⁠Nawid3333 Thank you for explaining the liveness dependency. Removing the dispatch would risk deadlocking the Unity case. From your description, `RaisedSignalReachesCancellingThread` exercises 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? <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-12 09:11 UTC · original
On src/libs/libKernel.cpp line 1095 (outdated):

@@ -1025,32 +1023,85 @@ static NtQueueApcThreadExFunc GetNtQueueApcThreadEx() {
 static void SignalApcHandler(void* arg1, void* arg2, void* /*arg3*/, PCONTEXT context) {
 	auto*      thread = static_cast<Pthread>(arg1);
 	const auto signum = static_cast<int>(reinterpret_cast<intptr_t>(arg2));
-	if (!PthreadTakePendingSignal(thread, signum)) {
+	PthreadClearSignalApcQueued(thread);
+	if (!Loader::IsGuestCodeAddress(context->Rip) || !PthreadTakePendingSignal(thread, signum)) {
 		return;
 	}
 
 	auto* handler = reinterpret_cast<exception_handler_func_t>(g_exception_handlers[signum]);
 	if (handler != nullptr) {
 		SignalDispatchScope scope;
-		auto                ctx           = CreateSignalUcontext(context);
-		auto                guest_context = IsGuestCodeAddress(ctx.uc_mcontext.mc_rip);
-		if (!guest_context) {
-			SanitizeNonGuestSignalUcontext(&ctx, thread);
-			std::thread([thread, signum, handler, ctx]() mutable {
-				SignalDispatchScope helper_scope;
-				auto*               previous_self = PthreadSwapSelfForSignal(thread);
-				handler(signum, &ctx);
-				PthreadSwapSelfForSignal(previous_self);
-			}).detach();
-			return;
-		}
+		auto                ctx = CreateSignalUcontext(context);
 		handler(signum, &ctx);
-		if (guest_context) {
-			ApplySignalUcontext(context, ctx);
-		}
+		ApplySignalUcontext(context, ctx);
 	}
 }
 
+static bool QueueSignalApc(Pthread thread, int signum) {
+	if (!PthreadMarkSignalApcQueued(thread)) {
+		return true;
+	}
+
+	auto*      nt_queue_apc_thread_ex = GetNtQueueApcThreadEx();
+	const auto thread_id              = static_cast<DWORD>(PthreadGetHostThreadId(thread));
+	HANDLE     target_thread =
+	    (nt_queue_apc_thread_ex != nullptr && thread_id != 0)
+	        ? OpenThread(THREAD_SET_CONTEXT | THREAD_QUERY_LIMITED_INFORMATION, FALSE, thread_id)
+	        : nullptr;
+	KytyUserApcOption option {};
+	option.UserApcFlags = KytyQueueUserApcFlagsSpecialUserApc;
+	const bool queued =
+	    target_thread != nullptr && GetProcessIdOfThread(target_thread) == GetCurrentProcessId() &&
+	    nt_queue_apc_thread_ex(target_thread, option, SignalApcHandler, thread,
+		                       reinterpret_cast<void*>(static_cast<intptr_t>(signum)),
+		                       nullptr) == 0;
+	if (target_thread != nullptr) {
+		CloseHandle(target_thread);
+	}
+	if (!queued) {
+		PthreadClearSignalApcQueued(thread);
+	}
+	return queued;
+}
+
+class SignalRedelivery {
+public:
+	static SignalRedelivery& Instance() {
+		static auto* redelivery = new SignalRedelivery;
+		return *redelivery;
+	}
+
+	void Track(Pthread thread, int signum) {
+		std::lock_guard lock(m_mutex);
+		m_targets.emplace_back(thread, signum);
+		if (!m_started) {
+			m_started = true;
+			std::thread([this] { Run(); }).detach();
+		}
+		m_cv.notify_one();
+	}
+
+private:
+	void Run() {
+		constexpr auto REDELIVERY_INTERVAL = std::chrono::milliseconds(1);
+
+		std::unique_lock lock(m_mutex);
+		for (;;) {
+			m_cv.wait(lock, [this] { return !m_targets.empty(); });
+			m_cv.wait_for(lock, REDELIVERY_INTERVAL);
+			std::erase_if(m_targets, [](const auto& target) {
+				return !PthreadHasPendingSignal(target.first, target.second) ||
+				       !QueueSignalApc(target.first, target.second);
+			});

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-12 09:11 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2228#discussion_r4548431011) On `src/libs/libKernel.cpp` line 1095 (outdated): ```diff @@ -1025,32 +1023,85 @@ static NtQueueApcThreadExFunc GetNtQueueApcThreadEx() { static void SignalApcHandler(void* arg1, void* arg2, void* /*arg3*/, PCONTEXT context) { auto* thread = static_cast<Pthread>(arg1); const auto signum = static_cast<int>(reinterpret_cast<intptr_t>(arg2)); - if (!PthreadTakePendingSignal(thread, signum)) { + PthreadClearSignalApcQueued(thread); + if (!Loader::IsGuestCodeAddress(context->Rip) || !PthreadTakePendingSignal(thread, signum)) { return; } auto* handler = reinterpret_cast<exception_handler_func_t>(g_exception_handlers[signum]); if (handler != nullptr) { SignalDispatchScope scope; - auto ctx = CreateSignalUcontext(context); - auto guest_context = IsGuestCodeAddress(ctx.uc_mcontext.mc_rip); - if (!guest_context) { - SanitizeNonGuestSignalUcontext(&ctx, thread); - std::thread([thread, signum, handler, ctx]() mutable { - SignalDispatchScope helper_scope; - auto* previous_self = PthreadSwapSelfForSignal(thread); - handler(signum, &ctx); - PthreadSwapSelfForSignal(previous_self); - }).detach(); - return; - } + auto ctx = CreateSignalUcontext(context); handler(signum, &ctx); - if (guest_context) { - ApplySignalUcontext(context, ctx); - } + ApplySignalUcontext(context, ctx); } } +static bool QueueSignalApc(Pthread thread, int signum) { + if (!PthreadMarkSignalApcQueued(thread)) { + return true; + } + + auto* nt_queue_apc_thread_ex = GetNtQueueApcThreadEx(); + const auto thread_id = static_cast<DWORD>(PthreadGetHostThreadId(thread)); + HANDLE target_thread = + (nt_queue_apc_thread_ex != nullptr && thread_id != 0) + ? OpenThread(THREAD_SET_CONTEXT | THREAD_QUERY_LIMITED_INFORMATION, FALSE, thread_id) + : nullptr; + KytyUserApcOption option {}; + option.UserApcFlags = KytyQueueUserApcFlagsSpecialUserApc; + const bool queued = + target_thread != nullptr && GetProcessIdOfThread(target_thread) == GetCurrentProcessId() && + nt_queue_apc_thread_ex(target_thread, option, SignalApcHandler, thread, + reinterpret_cast<void*>(static_cast<intptr_t>(signum)), + nullptr) == 0; + if (target_thread != nullptr) { + CloseHandle(target_thread); + } + if (!queued) { + PthreadClearSignalApcQueued(thread); + } + return queued; +} + +class SignalRedelivery { +public: + static SignalRedelivery& Instance() { + static auto* redelivery = new SignalRedelivery; + return *redelivery; + } + + void Track(Pthread thread, int signum) { + std::lock_guard lock(m_mutex); + m_targets.emplace_back(thread, signum); + if (!m_started) { + m_started = true; + std::thread([this] { Run(); }).detach(); + } + m_cv.notify_one(); + } + +private: + void Run() { + constexpr auto REDELIVERY_INTERVAL = std::chrono::milliseconds(1); + + std::unique_lock lock(m_mutex); + for (;;) { + m_cv.wait(lock, [this] { return !m_targets.empty(); }); + m_cv.wait_for(lock, REDELIVERY_INTERVAL); + std::erase_if(m_targets, [](const auto& target) { + return !PthreadHasPendingSignal(target.first, target.second) || + !QueueSignalApc(target.first, target.second); + }); ``` <!-- coderabbit-ai-generated:v1 --> @⁠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. <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠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):

  • Outside the diff, a failed APC retry: the redelivery thread now drops a target only when its signal is no longer pending, and a failed queue is tried again at the next interval. A thread that exits clears its pending signals, so it leaves the list that way.
  • The cancel test also checks that the canceller's signal ran on the canceller. The handler records its thread before it counts the entry, so after the second entry the recorded thread is the second handler's.
  • The nesting test reads the deepest nesting after PthreadJoin, when both handlers have finished.
**@⁠Nawid3333** on GitHub · 2026-11-12 09:12 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2228#issuecomment-6819544387) 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): - Outside the diff, a failed APC retry: the redelivery thread now drops a target only when its signal is no longer pending, and a failed queue is tried again at the next interval. A thread that exits clears its pending signals, so it leaves the list that way. - The cancel test also checks that the canceller's signal ran on the canceller. The handler records its thread before it counts the entry, so after the second entry the recorded thread is the second handler's. - The nesting test reads the deepest nesting after `PthreadJoin`, when both handlers have finished.
Author
Owner

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

**@⁠Nawid3333** on GitHub · 2026-11-12 20:42 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2228#issuecomment-6835415052) 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.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-18 13:56 UTC · original · edited 2026-11-18 18:32 UTC
On src/libs/libKernel.cpp line 1073 (outdated):

@@ -1022,36 +1040,88 @@ static NtQueueApcThreadExFunc GetNtQueueApcThreadEx() {
 	return nt_queue_apc_thread_ex;
 }
 
-static void SignalApcHandler(void* arg1, void* arg2, void* /*arg3*/, PCONTEXT context) {
-	auto*      thread = static_cast<Pthread>(arg1);
-	const auto signum = static_cast<int>(reinterpret_cast<intptr_t>(arg2));
-	if (!PthreadTakePendingSignal(thread, signum)) {
+static void SignalApcHandler(void* arg1, void* /*arg2*/, void* /*arg3*/, PCONTEXT context) {
+	auto* thread = static_cast<Pthread>(arg1);
+	PthreadClearSignalApcQueued(thread);
+	if (!Loader::IsGuestCodeAddress(context->Rip)) {
 		return;
 	}
+	DispatchPendingSignals(thread, [context](exception_handler_func_t handler, int signum) {
+		auto ctx = CreateSignalUcontext(context);
+		handler(signum, &ctx);
+		ApplySignalUcontext(context, ctx);
+	});
+}
+
+static bool QueueSignalApc(Pthread thread, int signum) {
+	if (PthreadIsDispatchingSignal(thread) || !PthreadMarkSignalApcQueued(thread)) {
+		return true;
+	}
+
+	auto*      nt_queue_apc_thread_ex = GetNtQueueApcThreadEx();
+	const auto thread_id              = static_cast<DWORD>(PthreadGetHostThreadId(thread));
+	HANDLE     target_thread =
+	    (nt_queue_apc_thread_ex != nullptr && thread_id != 0)
+	        ? OpenThread(THREAD_SET_CONTEXT | THREAD_QUERY_LIMITED_INFORMATION, FALSE, thread_id)
+	        : nullptr;
+	KytyUserApcOption option {};
+	option.UserApcFlags = KytyQueueUserApcFlagsSpecialUserApc;
+	const bool queued =
+	    target_thread != nullptr && GetProcessIdOfThread(target_thread) == GetCurrentProcessId() &&
+	    nt_queue_apc_thread_ex(target_thread, option, SignalApcHandler, thread,
+	                           reinterpret_cast<void*>(static_cast<intptr_t>(signum)),
+	                           nullptr) == 0;

Major · Stability & Availability · Heavy lift

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 CleanupThread clears the mask. KernelRaiseException sets the bit and calls QueueSignalApc without checking almost_done. QueueSignalApc opens the stored host_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. SignalApcHandler then calls DispatchPendingSignals on the exited Pthread. PthreadTakePendingSignal refuses that target because almost_done is set, while the pending bit remains set. The loop in DispatchPendingSignals does not exit, so the recycled thread can hang inside the APC. SignalRedelivery also 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:

  • Reject raises when almost_done is set, and clear the pending bit on that path.
  • Hold a thread handle from RunThread, release it in PthreadJoin, and queue the APC through that handle. A terminated thread then fails the queue instead of resolving the stored ID again. Detached threads freed by FreeDetachedThreads also go through PthreadJoin, so their handles are released there too.

✅ Addressed in commit 4242d02

**@⁠coderabbitai[bot]** on GitHub · 2026-11-18 13:56 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2228#discussion_r4615095064) · edited 2026-11-18 18:32 UTC On `src/libs/libKernel.cpp` line 1073 (outdated): ```diff @@ -1022,36 +1040,88 @@ static NtQueueApcThreadExFunc GetNtQueueApcThreadEx() { return nt_queue_apc_thread_ex; } -static void SignalApcHandler(void* arg1, void* arg2, void* /*arg3*/, PCONTEXT context) { - auto* thread = static_cast<Pthread>(arg1); - const auto signum = static_cast<int>(reinterpret_cast<intptr_t>(arg2)); - if (!PthreadTakePendingSignal(thread, signum)) { +static void SignalApcHandler(void* arg1, void* /*arg2*/, void* /*arg3*/, PCONTEXT context) { + auto* thread = static_cast<Pthread>(arg1); + PthreadClearSignalApcQueued(thread); + if (!Loader::IsGuestCodeAddress(context->Rip)) { return; } + DispatchPendingSignals(thread, [context](exception_handler_func_t handler, int signum) { + auto ctx = CreateSignalUcontext(context); + handler(signum, &ctx); + ApplySignalUcontext(context, ctx); + }); +} + +static bool QueueSignalApc(Pthread thread, int signum) { + if (PthreadIsDispatchingSignal(thread) || !PthreadMarkSignalApcQueued(thread)) { + return true; + } + + auto* nt_queue_apc_thread_ex = GetNtQueueApcThreadEx(); + const auto thread_id = static_cast<DWORD>(PthreadGetHostThreadId(thread)); + HANDLE target_thread = + (nt_queue_apc_thread_ex != nullptr && thread_id != 0) + ? OpenThread(THREAD_SET_CONTEXT | THREAD_QUERY_LIMITED_INFORMATION, FALSE, thread_id) + : nullptr; + KytyUserApcOption option {}; + option.UserApcFlags = KytyQueueUserApcFlagsSpecialUserApc; + const bool queued = + target_thread != nullptr && GetProcessIdOfThread(target_thread) == GetCurrentProcessId() && + nt_queue_apc_thread_ex(target_thread, option, SignalApcHandler, thread, + reinterpret_cast<void*>(static_cast<intptr_t>(signum)), + nullptr) == 0; ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** **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 `CleanupThread` clears the mask. `KernelRaiseException` sets the bit and calls `QueueSignalApc` without checking `almost_done`. `QueueSignalApc` opens the stored `host_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. `SignalApcHandler` then calls `DispatchPendingSignals` on the exited `Pthread`. `PthreadTakePendingSignal` refuses that target because `almost_done` is set, while the pending bit remains set. The loop in `DispatchPendingSignals` does not exit, so the recycled thread can hang inside the APC. `SignalRedelivery` also 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: - Reject raises when `almost_done` is set, and clear the pending bit on that path. - Hold a thread handle from `RunThread`, release it in `PthreadJoin`, and queue the APC through that handle. A terminated thread then fails the queue instead of resolving the stored ID again. Detached threads freed by `FreeDetachedThreads` also go through `PthreadJoin`, so their handles are released there too. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:b4610a3cd5a0b87b90d7b527 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit 4242d02
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-18 13:56 UTC · original · reviewed

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Minor · Stop the dispatch loop when a pass consumes no signal. · libKernel.cpp:525-542

src/libs/libKernel.cpp:525-542
Minor · Stability & Availability · Quick win

Stop the dispatch loop when a pass consumes no signal.

The do/while loop repeats while PthreadHasAnyPendingSignal(thread) is true. It does not check whether PthreadTakePendingSignal consumed anything. PthreadTakePendingSignal returns false for every signum when thread->almost_done is set, but it leaves the bit in place. In that state, the loop spins forever on the dispatching thread.

Record whether the inner pass took a signal. Exit when it took none.

Proposed fix

 	do {
 		SignalDispatchScope scope(thread);
 		if (!scope.owned) {
 			return;
 		}
+		bool took = false;
 		for (int signum = 0; signum < static_cast<int>(std::size(g_exception_handlers));) {
 			if (!PthreadTakePendingSignal(thread, signum)) {
 				signum++;
 				continue;
 			}
+			took = true;
 			auto* handler =
 			    reinterpret_cast<exception_handler_func_t>(g_exception_handlers[signum]);
 			if (handler != nullptr) {
 				deliver(handler, signum);
 			}
 			signum = 0;
 		}
-	} while (PthreadHasAnyPendingSignal(thread));
+		if (!took) {
+			return;
+		}
+	} while (PthreadHasAnyPendingSignal(thread));
Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 3db84943ab9f48f0bad6c2f7cf75aa25f0cca389 and 28dc312de2.

Files selected for processing: 5

  • src/kernel/pthread.cpp
  • src/libs/libKernel.cpp
  • src/loader/runtimeLinker.cpp
  • src/loader/runtimeLinker.h
  • tests/VirtualMemoryAllocationTests.cpp

Included 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-18 13:56 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2228#pullrequestreview-5958037432) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 1** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (1)** > > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor</strong> · Stop the dispatch loop when a pass consumes no signal. · <code>libKernel.cpp:525-542</code></summary><blockquote> > <dl> > <dd> > <br> > > `src/libs/libKernel.cpp:525-542` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** > > **Stop the dispatch loop when a pass consumes no signal.** > > The `do`/`while` loop repeats while `PthreadHasAnyPendingSignal(thread)` is true. It does not check whether `PthreadTakePendingSignal` consumed anything. `PthreadTakePendingSignal` returns false for every `signum` when `thread->almost_done` is set, but it leaves the bit in place. In that state, the loop spins forever on the dispatching thread. > > Record whether the inner pass took a signal. Exit when it took none. > > <details> > <summary>Proposed fix</summary> > <dl> > <dd> > <br> > > ```diff > do { > SignalDispatchScope scope(thread); > if (!scope.owned) { > return; > } > + bool took = false; > for (int signum = 0; signum < static_cast<int>(std::size(g_exception_handlers));) { > if (!PthreadTakePendingSignal(thread, signum)) { > signum++; > continue; > } > + took = true; > auto* handler = > reinterpret_cast<exception_handler_func_t>(g_exception_handlers[signum]); > if (handler != nullptr) { > deliver(handler, signum); > } > signum = 0; > } > - } while (PthreadHasAnyPendingSignal(thread)); > + if (!took) { > + return; > + } > + } while (PthreadHasAnyPendingSignal(thread)); > ``` > </dd> > </dl> > </details> > > <!-- cr-comment:v1:93ddd13bee432cefe2c1467e --> > > </dd> > </dl> > </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/b3295bebc698a776e3b40283fdfbc70e732e79b4/.coderabbit.yaml>) - **Commit**: [b3295be](<https://github.com/KytyPS5/KytyPS5/commit/b3295bebc698a776e3b40283fdfbc70e732e79b4>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `7388ce45-c948-42e9-9665-483d687cc68e` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 3db84943ab9f48f0bad6c2f7cf75aa25f0cca389 and 28dc312de24214e017a99fe26f5a227f0cdab981. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 5</summary> <dl> <dd> <br> * `src/kernel/pthread.cpp` * `src/libs/libKernel.cpp` * `src/loader/runtimeLinker.cpp` * `src/loader/runtimeLinker.h` * `tests/VirtualMemoryAllocationTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=d56c834e-d513-4a5c-afb1-e66b2fe277cd attempt=51a10a4c-6a4d-45de-b1f3-2fbddc468c0a batch=1/1 -->
Author
Owner

@⁠Nawid3333 on GitHub · 2026-11-18 18:32 UTC · original
On src/libs/libKernel.cpp line 1073 (outdated):

@@ -1022,36 +1040,88 @@ static NtQueueApcThreadExFunc GetNtQueueApcThreadEx() {
 	return nt_queue_apc_thread_ex;
 }
 
-static void SignalApcHandler(void* arg1, void* arg2, void* /*arg3*/, PCONTEXT context) {
-	auto*      thread = static_cast<Pthread>(arg1);
-	const auto signum = static_cast<int>(reinterpret_cast<intptr_t>(arg2));
-	if (!PthreadTakePendingSignal(thread, signum)) {
+static void SignalApcHandler(void* arg1, void* /*arg2*/, void* /*arg3*/, PCONTEXT context) {
+	auto* thread = static_cast<Pthread>(arg1);
+	PthreadClearSignalApcQueued(thread);
+	if (!Loader::IsGuestCodeAddress(context->Rip)) {
 		return;
 	}
+	DispatchPendingSignals(thread, [context](exception_handler_func_t handler, int signum) {
+		auto ctx = CreateSignalUcontext(context);
+		handler(signum, &ctx);
+		ApplySignalUcontext(context, ctx);
+	});
+}
+
+static bool QueueSignalApc(Pthread thread, int signum) {
+	if (PthreadIsDispatchingSignal(thread) || !PthreadMarkSignalApcQueued(thread)) {
+		return true;
+	}
+
+	auto*      nt_queue_apc_thread_ex = GetNtQueueApcThreadEx();
+	const auto thread_id              = static_cast<DWORD>(PthreadGetHostThreadId(thread));
+	HANDLE     target_thread =
+	    (nt_queue_apc_thread_ex != nullptr && thread_id != 0)
+	        ? OpenThread(THREAD_SET_CONTEXT | THREAD_QUERY_LIMITED_INFORMATION, FALSE, thread_id)
+	        : nullptr;
+	KytyUserApcOption option {};
+	option.UserApcFlags = KytyQueueUserApcFlagsSpecialUserApc;
+	const bool queued =
+	    target_thread != nullptr && GetProcessIdOfThread(target_thread) == GetCurrentProcessId() &&
+	    nt_queue_apc_thread_ex(target_thread, option, SignalApcHandler, thread,
+	                           reinterpret_cast<void*>(static_cast<intptr_t>(signum)),
+	                           nullptr) == 0;

Confirmed and fixed in 4242d028b. A raise to a thread past CleanupThread kept its pending bit: the new test RaisedSignalSkipsExitedTarget fails on 28dc312de with a raise to an exited thread left its signal pending and passes on 4242d028b.

  • PthreadQueuePendingSignal sets the bit, then takes it back and fails when the target is almost_done or free. KernelRaiseException then returns KERNEL_ERROR_ESRCH, the result FreeBSD's pthread_kill gives for a dead thread (lib/libthr/thread/thr_kill.c looks the target up with include_dead 0). This also holds when the dead target's host thread id now belongs to the caller: RaiseOnCurrentThread returns the failed queue.
  • CleanupThread sets almost_done before it clears the mask, so a raise racing the exit either sees almost_done or has its bit cleared by the exit. PthreadJoin no longer resets almost_done; PthreadCreate resets it when it reuses the object.
  • SignalApcHandler dispatches 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: PthreadTakePendingSignal refuses only almost_done threads, and those no longer keep a bit, so the loop ends.

Windows 11 (RX 9070 XT, clang-cl): virtual_memory_allocation passes in 5 of 5 runs, event_queue_lifetime and sync_on_address pass, kernel_file_system stops with exit code 0xc0000028 on this PC with main's sources as well. Before this commit the branch was rebased onto b3295bebc (per-thread guest TLS through gs); CleanupThread clears the pending signals before main's DeleteThreadTls() frees the TLS.

**@⁠Nawid3333** on GitHub · 2026-11-18 18:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2228#discussion_r4618934129) On `src/libs/libKernel.cpp` line 1073 (outdated): ```diff @@ -1022,36 +1040,88 @@ static NtQueueApcThreadExFunc GetNtQueueApcThreadEx() { return nt_queue_apc_thread_ex; } -static void SignalApcHandler(void* arg1, void* arg2, void* /*arg3*/, PCONTEXT context) { - auto* thread = static_cast<Pthread>(arg1); - const auto signum = static_cast<int>(reinterpret_cast<intptr_t>(arg2)); - if (!PthreadTakePendingSignal(thread, signum)) { +static void SignalApcHandler(void* arg1, void* /*arg2*/, void* /*arg3*/, PCONTEXT context) { + auto* thread = static_cast<Pthread>(arg1); + PthreadClearSignalApcQueued(thread); + if (!Loader::IsGuestCodeAddress(context->Rip)) { return; } + DispatchPendingSignals(thread, [context](exception_handler_func_t handler, int signum) { + auto ctx = CreateSignalUcontext(context); + handler(signum, &ctx); + ApplySignalUcontext(context, ctx); + }); +} + +static bool QueueSignalApc(Pthread thread, int signum) { + if (PthreadIsDispatchingSignal(thread) || !PthreadMarkSignalApcQueued(thread)) { + return true; + } + + auto* nt_queue_apc_thread_ex = GetNtQueueApcThreadEx(); + const auto thread_id = static_cast<DWORD>(PthreadGetHostThreadId(thread)); + HANDLE target_thread = + (nt_queue_apc_thread_ex != nullptr && thread_id != 0) + ? OpenThread(THREAD_SET_CONTEXT | THREAD_QUERY_LIMITED_INFORMATION, FALSE, thread_id) + : nullptr; + KytyUserApcOption option {}; + option.UserApcFlags = KytyQueueUserApcFlagsSpecialUserApc; + const bool queued = + target_thread != nullptr && GetProcessIdOfThread(target_thread) == GetCurrentProcessId() && + nt_queue_apc_thread_ex(target_thread, option, SignalApcHandler, thread, + reinterpret_cast<void*>(static_cast<intptr_t>(signum)), + nullptr) == 0; ``` Confirmed and fixed in 4242d028b. A raise to a thread past `CleanupThread` kept its pending bit: the new test `RaisedSignalSkipsExitedTarget` fails on 28dc312de with `a raise to an exited thread left its signal pending` and passes on 4242d028b. - `PthreadQueuePendingSignal` sets the bit, then takes it back and fails when the target is `almost_done` or `free`. `KernelRaiseException` then returns `KERNEL_ERROR_ESRCH`, the result FreeBSD's `pthread_kill` gives for a dead thread (`lib/libthr/thread/thr_kill.c` looks the target up with `include_dead` 0). This also holds when the dead target's host thread id now belongs to the caller: `RaiseOnCurrentThread` returns the failed queue. - `CleanupThread` sets `almost_done` before it clears the mask, so a raise racing the exit either sees `almost_done` or has its bit cleared by the exit. `PthreadJoin` no longer resets `almost_done`; `PthreadCreate` resets it when it reuses the object. - `SignalApcHandler` dispatches 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`: `PthreadTakePendingSignal` refuses only `almost_done` threads, and those no longer keep a bit, so the loop ends. Windows 11 (RX 9070 XT, clang-cl): `virtual_memory_allocation` passes in 5 of 5 runs, `event_queue_lifetime` and `sync_on_address` pass, `kernel_file_system` stops with exit code 0xc0000028 on this PC with main's sources as well. Before this commit the branch was rebased onto b3295bebc (per-thread guest TLS through `gs`); `CleanupThread` clears the pending signals before main's `DeleteThreadTls()` frees the TLS.
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/2228/head:github-bot/gh-2228'
git switch 'github-bot/gh-2228'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-2228'
git switch 'github-bot/gh-2228'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-2228'
git switch 'github-bot/gh-2228'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-2228'
git switch 'main'
git merge --squash 'github-bot/gh-2228'
git switch 'main'
git merge --ff-only 'github-bot/gh-2228'
git switch 'main'
git merge 'github-bot/gh-2228'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.