From 24dc98d7c035bde08e679e3c62a59402a2b57cc5 Mon Sep 17 00:00:00 2001 From: popcoder565 <339285150+popcoder565@users.noreply.github.com> Date: Thu, 8 Oct 2026 09:47:25 -0400 Subject: [PATCH] fix(libkernel): give up a raise whose target stays in NtContinue or winpthreads The retry that waits for a target to leave NtContinue, NtContinueEx or libwinpthread-1.dll had no bound, so a target that stayed there made sceKernelRaiseException spin forever. It now throws after 1 s. A new guest_raise_exception phase keeps a thread inside NtContinue by continuing a context that calls NtContinue again, and checks that the raise throws and that the handler did not run. Co-Authored-By: Claude Opus 5.5 --- .../prx/libkernel/System/src/Exception.cpp | 4 ++ core/libs/tests/GuestRaiseException.cpp | 49 +++++++++++++++++++ docs/dev/TechnicalDebt.md | 2 +- 3 files changed, 54 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libkernel/System/src/Exception.cpp b/core/libs/prx/libkernel/System/src/Exception.cpp index 6405c30a6..b40e31546 100644 --- a/core/libs/prx/libkernel/System/src/Exception.cpp +++ b/core/libs/prx/libkernel/System/src/Exception.cpp @@ -5,6 +5,7 @@ #include "prx/libkernel/KernelErrors.hpp" #include "prx/libkernel/Pthread/include/Pthread.hpp" #include +#include #include #include #include @@ -101,6 +102,7 @@ GuestExceptionHandler Handler(int signum) { #ifdef _WIN32 constexpr std::size_t RedZone = 128; constexpr std::size_t HomeArea = 32; +constexpr auto RetryLimit = std::chrono::seconds(1); struct Delivery { GuestExceptionHandler handler; @@ -216,6 +218,7 @@ bool RaiseOn(Pthread thread, GuestExceptionHandler handler, int signum) { const auto native = static_cast(thread->nativeHandle); auto queued = std::make_unique(Delivery{handler, signum, {}}); alignas(16) Delivery delivery{handler, signum, {}}; + const auto retryDeadline = std::chrono::steady_clock::now() + RetryLimit; for (;;) { if (SuspendThread(native) == static_cast(-1)) { if (Exited(native)) return false; @@ -239,6 +242,7 @@ bool RaiseOn(Pthread thread, GuestExceptionHandler handler, int signum) { } if (!RestoringContext(delivery.context.Rip) && !InWinpthread(delivery.context.Rip)) break; ResumeThread(native); + if (std::chrono::steady_clock::now() >= retryDeadline) throw std::runtime_error("sceKernelRaiseException: the target thread stayed inside NtContinue or winpthreads for 1 s"); SwitchToThread(); } const DWORD64 slot = (delivery.context.Rsp - RedZone - sizeof(Delivery)) & ~static_cast(15); diff --git a/core/libs/tests/GuestRaiseException.cpp b/core/libs/tests/GuestRaiseException.cpp index e4a71a612..ceed4647a 100644 --- a/core/libs/tests/GuestRaiseException.cpp +++ b/core/libs/tests/GuestRaiseException.cpp @@ -134,6 +134,28 @@ static void* APS5_VABI Continuing(void* arg) { return nullptr; } +using NtContinueFunction = LONG(NTAPI*)(CONTEXT*, BOOLEAN); +alignas(16) static CONTEXT loopContext; +alignas(16) static CONTEXT leaveContext; +static std::atomic loopingId{0}; + +static void* APS5_VABI Looping(void* arg) { + auto& worker = *static_cast(arg); + const auto ntContinue = reinterpret_cast(reinterpret_cast(GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtContinue"))); + volatile bool left = false; + RtlCaptureContext(&leaveContext); + if (left) return nullptr; + left = true; + loopContext = leaveContext; + loopContext.Rip = reinterpret_cast(ntContinue); + loopContext.Rcx = reinterpret_cast(&loopContext); + loopContext.Rdx = 0; + loopingId.store(GetCurrentThreadId()); + worker.started.store(true); + ntContinue(&loopContext, FALSE); + return nullptr; +} + static std::atomic finishedReturned{false}; static void* APS5_VABI Finished(void*) { @@ -249,6 +271,33 @@ int main() { selfing.stop.store(true); Require(scePthreadJoin(selfingThread, nullptr) == 0); + Worker looping; + Pthread loopingThread = nullptr; + Require(scePthreadCreate(&loopingThread, nullptr, Looping, &looping, "looping") == 0); + while (!looping.started.load()) std::this_thread::yield(); + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + const int beforeLooping = calls.load(); + const auto raisedAt = std::chrono::steady_clock::now(); + bool refused = false; + try { + sceKernelRaiseException(loopingThread, SIGUSR1); + } catch (const std::runtime_error&) { + refused = true; + } + const auto retried = std::chrono::steady_clock::now() - raisedAt; + Require(refused && retried >= std::chrono::milliseconds(900) && retried < std::chrono::seconds(10)); + Require(calls.load() == beforeLooping); + const HANDLE loopingHandle = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT, FALSE, loopingId.load()); + Require(loopingHandle != nullptr); + Require(SuspendThread(loopingHandle) != static_cast(-1)); + CONTEXT stopped{}; + stopped.ContextFlags = CONTEXT_CONTROL; + Require(GetThreadContext(loopingHandle, &stopped) != 0); + loopContext = leaveContext; + Require(ResumeThread(loopingHandle) != static_cast(-1)); + CloseHandle(loopingHandle); + Require(scePthreadJoin(loopingThread, nullptr) == 0); + Pthread finishedThread = nullptr; Require(scePthreadCreate(&finishedThread, nullptr, Finished, nullptr, "finished") == 0); while (!finishedReturned.load()) std::this_thread::yield(); diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index b163ec184..05c9990bb 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -222,7 +222,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceKernelRaiseException](../../core/libs/prx/libkernel/System/src/Exception.cpp) does not consult the target thread's signal mask - [sceKernelRaiseException](../../core/libs/prx/libkernel/System/src/Exception.cpp) saves and restores only `CONTEXT_FULL | CONTEXT_SEGMENTS` on Windows, so the upper halves of the YMM registers are not preserved if the handler or the entry uses AVX - [sceKernelRaiseException](../../core/libs/prx/libkernel/System/src/Exception.cpp) reaches a thread that waits in an alertable `TimedWait` wait through an APC. A thread blocked anywhere else, including all waits under `APS5_COARSE_TIMED_WAITS` and host waits inside the emulator, is redirected and runs the handler only when that wait returns -- [sceKernelRaiseException](../../core/libs/prx/libkernel/System/src/Exception.cpp) on Windows runs the handler wherever the target thread was interrupted. It waits only while the thread is inside winpthreads or restoring a context through `NtContinue`, so a handler that calls into other host code the thread was interrupted in, such as the C runtime's heap or a lock of the emulator, can deadlock on it or reenter it +- [sceKernelRaiseException](../../core/libs/prx/libkernel/System/src/Exception.cpp) on Windows runs the handler wherever the target thread was interrupted. It waits only while the thread is inside winpthreads or restoring a context through `NtContinue`, and throws if that lasts 1 s, so a handler that calls into other host code the thread was interrupted in, such as the C runtime's heap or a lock of the emulator, can deadlock on it or reenter it - [libSceUlt queues](../../core/libs/prx/libSceUlt/Export.cpp) use preallocated host storage instead of the supplied guest work area; its existing size formula and the 512-byte object layouts remain unverified. Waiting-queue pool thread limits and waiter priority ordering are not implemented. Finalization wakes blocked queue callers with `ULT_ERROR_STATE`. - [Thread cancellation](../../core/libs/prx/libkernel/Pthread/src/Thread.cpp) (libkernel) is not modelled: `scePthreadCancel` throws, so no cancel request is ever pending and `scePthreadTestcancel` and `pthread_testcancel` return without acting; the cancel state and type set by `scePthreadSetcancelstate` and `scePthreadSetcanceltype` are stored and not used - [MIMG `tfe` and `lwe`](../../core/shader/recompiler/RdnaDecoder/src/RdnaImageOpDecoder.cpp) never write the status VGPR after the data. On hardware it is written only when a texel fetch hits an unmapped page of a partially resident texture, or, for `lwe` on sample/gather, when the LOD is below the T# `MIN_LOD_WARN`; texture memory is always resident here, and `lwe` on sample, gather and `image_get_lod` throws.