From 175846186a0946ae99e591c930be5847faca83cd Mon Sep 17 00:00:00 2001 From: popcoder565 <339285150+popcoder565@users.noreply.github.com> Date: Thu, 8 Oct 2026 00:53:58 -0400 Subject: [PATCH] fix(libkernel): read the raise target's context before choosing APC delivery SuspendThread returns before the thread has stopped, and GetThreadContext waits until it has. waitCount was read right after SuspendThread, so a thread that was leaving its wait could still decrement it and drain its APCs with NtTestAlert before QueueUserAPC queued the delivery, which then waited for an alertable wait that never came. The context is now read first, so waitCount is read from a stopped thread. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libkernel/System/src/Exception.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/core/libs/prx/libkernel/System/src/Exception.cpp b/core/libs/prx/libkernel/System/src/Exception.cpp index 71bc22c90..36f165762 100644 --- a/core/libs/prx/libkernel/System/src/Exception.cpp +++ b/core/libs/prx/libkernel/System/src/Exception.cpp @@ -219,6 +219,11 @@ bool RaiseOn(Pthread thread, GuestExceptionHandler handler, int signum) { ResumeThread(native); return false; } + delivery.context.ContextFlags = CONTEXT_FULL | CONTEXT_SEGMENTS; + if (!GetThreadContext(native, &delivery.context)) { + ResumeThread(native); + throw std::runtime_error("sceKernelRaiseException: cannot read the target thread context"); + } if (thread->waitCount.load(std::memory_order_seq_cst) > 0) { const bool accepted = QueueUserAPC(WaitingEntry, native, reinterpret_cast(queued.get())) != 0; ResumeThread(native); @@ -226,11 +231,6 @@ bool RaiseOn(Pthread thread, GuestExceptionHandler handler, int signum) { queued.release(); return true; } - delivery.context.ContextFlags = CONTEXT_FULL | CONTEXT_SEGMENTS; - if (!GetThreadContext(native, &delivery.context)) { - ResumeThread(native); - throw std::runtime_error("sceKernelRaiseException: cannot read the target thread context"); - } if (!RestoringContext(delivery.context.Rip)) break; ResumeThread(native); SwitchToThread();