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 <noreply@anthropic.com>
This commit is contained in:
popcoder565
2026-10-08 00:53:58 -04:00
parent c3f3cc849a
commit 175846186a
@@ -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<ULONG_PTR>(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();