sceKernelRaiseException on Windows can stop a thread inside emulator code that holds a host lock #1488

Closed
opened 2026-10-08 09:04:37 +00:00 by awake-devel · 9 comments
awake-devel commented 2026-10-08 09:04:37 +00:00 (Migrated from github.com)
Contributor

Imported from boykopovar/AnyPS5. Originally posted by awake-devel on 2026-10-08T09:04:37Z.


⚠️ Unconfirmed, needs testing on Windows. This comes from reading the code; it has not been reproduced. I have no Windows machine, so I can't check it myself. A Windows tester running the reproducer below would settle whether it is real.

This issue was investigated and written by Claude Code (AI), and posted by me after review.

On Windows, sceKernelRaiseException redirects any target thread that is not in an alertable TimedWait wait (RaiseOn in core/libs/prx/libkernel/System/src/Exception.cpp), wherever its Rip is. If the thread is inside emulator code at that moment, for example sceKernelSyncOnAddressWake holding g_waitersLock (SyncOnAddress.cpp), the guest handler runs while that host lock is held:

  • if the handler (or anything it calls) takes the same lock, the thread deadlocks on itself;
  • a GC-style handler that waits until the world restarts keeps the lock held, so the raising thread deadlocks as soon as it needs that lock.

On the console these calls are system calls, which a signal cannot interrupt halfway, so the guest never sees this. TechnicalDebt already says a thread blocked in a host wait runs the handler when that wait returns, but not that it can run while host locks are held.

Possible directions (each needs testing on Windows):

  1. Redirect only when Rip is in guest code; otherwise resume and retry. Simple, but a thread blocked in a non-alertable host wait would make the raise spin until that wait ends, and it needs a reliable guest/host address map (executable and app0 modules vs. libs/*.prx and system DLLs).
  2. When Rip is in host code, unwind (RtlVirtualUnwind) to the first return address in guest code and replace it with a stub that delivers the signal there (the return-address hijacking .NET uses to suspend threads in native code). Raises stay asynchronous, but pending hijacks must be tracked per thread and C++ exceptions must not unwind through a hijacked frame.

A reproducer phase for guest_raise_exception (a thread loops on sceKernelSyncOnAddressWake, the handler waits like a GC handler, and the main thread calls sceKernelSyncOnAddressWake on another address while the handler runs) is ready to share (a script that adds it to GuestRaiseException.cpp); it reports which module the thread was stopped in and fails if the wake blocks for 2 s. I can post it here or open it as a draft PR if that helps someone test. It has never been run.

Related: #1421 and #1431 change the same delivery code; neither addresses this case on Windows. #1431 documents the same limitation for Linux in TechnicalDebt.

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5759000995 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/issues/1488). Originally posted by [awake-devel](https://github.com/awake-devel) on 2026-10-08T09:04:37Z. --- > ⚠️ **Unconfirmed, needs testing on Windows.** This comes from reading the code; it has not been reproduced. I have no Windows machine, so I can't check it myself. A Windows tester running the reproducer below would settle whether it is real. > > This issue was investigated and written by Claude Code (AI), and posted by me after review. On Windows, `sceKernelRaiseException` redirects any target thread that is not in an alertable `TimedWait` wait (`RaiseOn` in `core/libs/prx/libkernel/System/src/Exception.cpp`), wherever its `Rip` is. If the thread is inside emulator code at that moment, for example `sceKernelSyncOnAddressWake` holding `g_waitersLock` (`SyncOnAddress.cpp`), the guest handler runs while that host lock is held: - if the handler (or anything it calls) takes the same lock, the thread deadlocks on itself; - a GC-style handler that waits until the world restarts keeps the lock held, so the raising thread deadlocks as soon as it needs that lock. On the console these calls are system calls, which a signal cannot interrupt halfway, so the guest never sees this. TechnicalDebt already says a thread blocked in a host wait runs the handler when that wait returns, but not that it can run while host locks are held. Possible directions (each needs testing on Windows): 1. Redirect only when `Rip` is in guest code; otherwise resume and retry. Simple, but a thread blocked in a non-alertable host wait would make the raise spin until that wait ends, and it needs a reliable guest/host address map (executable and `app0` modules vs. `libs/*.prx` and system DLLs). 2. When `Rip` is in host code, unwind (`RtlVirtualUnwind`) to the first return address in guest code and replace it with a stub that delivers the signal there (the return-address hijacking .NET uses to suspend threads in native code). Raises stay asynchronous, but pending hijacks must be tracked per thread and C++ exceptions must not unwind through a hijacked frame. A reproducer phase for `guest_raise_exception` (a thread loops on `sceKernelSyncOnAddressWake`, the handler waits like a GC handler, and the main thread calls `sceKernelSyncOnAddressWake` on another address while the handler runs) is ready to share (a script that adds it to `GuestRaiseException.cpp`); it reports which module the thread was stopped in and fails if the wake blocks for 2 s. I can post it here or open it as a draft PR if that helps someone test. It has never been run. Related: #1421 and #1431 change the same delivery code; neither addresses this case on Windows. #1431 documents the same limitation for Linux in TechnicalDebt.
LeandroLP23 commented 2026-10-08 09:47:27 +00:00 (Migrated from github.com)
Author
Contributor

Imported from boykopovar/AnyPS5. Originally posted by LeandroLP23 on 2026-10-08T09:47:27Z.


Confirmed on Windows 11, MinGW-w64 GCC 15.2.0, Release, main 3e32797c.

I wrote a reproducer from your description (not your script, which isn't posted): a waker guest thread loops on sceKernelSyncOnAddressWake(&a, 1); the SIGUSR1 handler records the interrupted rip (ucontext + 0xe0), then spins until released, like a GC handler; for each round the main thread raises SIGUSR1 on the waker, waits for the handler, and calls sceKernelSyncOnAddressWake(&b, 1) from another thread, counting it as blocked if it has not returned after 2 s.

300 rounds, 148 blocked:

Waker stopped in Rounds Blocked
libwinpthread-1.dll (the mutex std::mutex uses) 282 146
libkernel.prx 13 2, both at sceKernelSyncOnAddressWake+0x160
ntdll.dll, KERNELBASE.dll, the test itself 5 0

Every blocked round had the waker stopped in host code taking or holding g_waitersLock; none blocked when it was stopped elsewhere. The wake returned as soon as the handler did.

Reproducer (core/libs/tests/GuestRaiseExceptionHostLock.cpp, built like guest_raise_exception_tests)
#include "SceTypes.hpp"
#include <windows.h>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <map>
#include <string>
#include <thread>

extern "C" {
int APS5_VABI sceKernelInstallExceptionHandler(int signum, void* handler);
int APS5_VABI sceKernelRemoveExceptionHandler(int signum);
int APS5_VABI sceKernelRaiseException(Pthread thread, int signum);
int APS5_VABI scePthreadCreate(Pthread* thread, const PthreadAttr* attr, PthreadEntry entry, void* arg, const char* name);
int APS5_VABI scePthreadJoin(Pthread thread, void** retval);
int APS5_VABI sceKernelSyncOnAddressWake(void* address, std::int32_t count);
}

static constexpr int SIGUSR1 = 30;
static constexpr int Rounds = 300;

static std::atomic<int> entered{0};
static std::atomic<bool> resume{false};
static std::atomic<bool> stop{false};
static std::atomic<std::uint64_t> stoppedRip{0};
static std::uint32_t addressA = 0;
static std::uint32_t addressB = 0;

static void APS5_VABI Handler(int, void* context) {
    std::uint64_t rip = 0;
    std::memcpy(&rip, static_cast<unsigned char*>(context) + 0xe0, sizeof(rip));
    stoppedRip.store(rip);
    entered.fetch_add(1);
    while (!resume.load()) std::this_thread::yield();
}

static void* APS5_VABI Waker(void*) {
    while (!stop.load()) sceKernelSyncOnAddressWake(&addressA, 1);
    return nullptr;
}

static std::string ModuleOf(std::uint64_t address) {
    HMODULE module = nullptr;
    if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
            reinterpret_cast<LPCSTR>(address), &module)) return "?";
    char path[MAX_PATH]{};
    GetModuleFileNameA(module, path, MAX_PATH);
    const char* name = std::strrchr(path, '\\');
    return name ? name + 1 : path;
}

int main() {
    std::setvbuf(stdout, nullptr, _IONBF, 0);
    if (sceKernelInstallExceptionHandler(SIGUSR1, reinterpret_cast<void*>(&Handler)) != 0) return 2;
    Pthread worker = nullptr;
    if (scePthreadCreate(&worker, nullptr, Waker, nullptr, "waker") != 0) return 2;
    std::this_thread::sleep_for(std::chrono::milliseconds(50));
    std::map<std::string, int> stoppedIn;
    int blocked = 0;
    for (int round = 0; round < Rounds; ++round) {
        resume.store(false);
        const int before = entered.load();
        if (sceKernelRaiseException(worker, SIGUSR1) != 0) return 2;
        const auto raised = std::chrono::steady_clock::now();
        while (entered.load() == before) {
            if (std::chrono::steady_clock::now() - raised > std::chrono::seconds(5)) {
                std::printf("round %d: the handler did not run within 5 s\n", round);
                return 3;
            }
            std::this_thread::yield();
        }
        const auto module = ModuleOf(stoppedRip.load());
        ++stoppedIn[module];
        std::atomic<bool> done{false};
        std::thread main([&] {
            sceKernelSyncOnAddressWake(&addressB, 1);
            done.store(true);
        });
        const auto start = std::chrono::steady_clock::now();
        while (!done.load() && std::chrono::steady_clock::now() - start < std::chrono::seconds(2)) std::this_thread::sleep_for(std::chrono::milliseconds(1));
        if (!done.load()) {
            ++blocked;
            std::printf("round %d: sceKernelSyncOnAddressWake blocked for 2 s while the handler ran; worker stopped at %s+0x%llx\n", round,
                module.c_str(), static_cast<unsigned long long>(stoppedRip.load() - reinterpret_cast<std::uint64_t>(GetModuleHandleA(module.c_str()))));
        }
        resume.store(true);
        main.join();
    }
    stop.store(true);
    scePthreadJoin(worker, nullptr);
    sceKernelRemoveExceptionHandler(SIGUSR1);
    std::printf("rounds %d, blocked %d; worker stopped in:", Rounds, blocked);
    for (const auto& [module, count] : stoppedIn) std::printf(" %s=%d", module.c_str(), count);
    std::printf("\n");
    return blocked ? 1 : 0;
}
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6057190528 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/issues/1488#issuecomment-6057190528). Originally posted by [LeandroLP23](https://github.com/LeandroLP23) on 2026-10-08T09:47:27Z. --- Confirmed on Windows 11, MinGW-w64 GCC 15.2.0, Release, `main` 3e32797c. I wrote a reproducer from your description (not your script, which isn't posted): a `waker` guest thread loops on `sceKernelSyncOnAddressWake(&a, 1)`; the SIGUSR1 handler records the interrupted `rip` (ucontext + 0xe0), then spins until released, like a GC handler; for each round the main thread raises SIGUSR1 on the waker, waits for the handler, and calls `sceKernelSyncOnAddressWake(&b, 1)` from another thread, counting it as blocked if it has not returned after 2 s. 300 rounds, 148 blocked: | Waker stopped in | Rounds | Blocked | |---|---|---| | `libwinpthread-1.dll` (the mutex `std::mutex` uses) | 282 | 146 | | `libkernel.prx` | 13 | 2, both at `sceKernelSyncOnAddressWake`+0x160 | | `ntdll.dll`, `KERNELBASE.dll`, the test itself | 5 | 0 | Every blocked round had the waker stopped in host code taking or holding `g_waitersLock`; none blocked when it was stopped elsewhere. The wake returned as soon as the handler did. <details> <summary>Reproducer (<code>core/libs/tests/GuestRaiseExceptionHostLock.cpp</code>, built like <code>guest_raise_exception_tests</code>)</summary> ```cpp #include "SceTypes.hpp" #include <windows.h> #include <atomic> #include <chrono> #include <cstdint> #include <cstdio> #include <cstring> #include <map> #include <string> #include <thread> extern "C" { int APS5_VABI sceKernelInstallExceptionHandler(int signum, void* handler); int APS5_VABI sceKernelRemoveExceptionHandler(int signum); int APS5_VABI sceKernelRaiseException(Pthread thread, int signum); int APS5_VABI scePthreadCreate(Pthread* thread, const PthreadAttr* attr, PthreadEntry entry, void* arg, const char* name); int APS5_VABI scePthreadJoin(Pthread thread, void** retval); int APS5_VABI sceKernelSyncOnAddressWake(void* address, std::int32_t count); } static constexpr int SIGUSR1 = 30; static constexpr int Rounds = 300; static std::atomic<int> entered{0}; static std::atomic<bool> resume{false}; static std::atomic<bool> stop{false}; static std::atomic<std::uint64_t> stoppedRip{0}; static std::uint32_t addressA = 0; static std::uint32_t addressB = 0; static void APS5_VABI Handler(int, void* context) { std::uint64_t rip = 0; std::memcpy(&rip, static_cast<unsigned char*>(context) + 0xe0, sizeof(rip)); stoppedRip.store(rip); entered.fetch_add(1); while (!resume.load()) std::this_thread::yield(); } static void* APS5_VABI Waker(void*) { while (!stop.load()) sceKernelSyncOnAddressWake(&addressA, 1); return nullptr; } static std::string ModuleOf(std::uint64_t address) { HMODULE module = nullptr; if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, reinterpret_cast<LPCSTR>(address), &module)) return "?"; char path[MAX_PATH]{}; GetModuleFileNameA(module, path, MAX_PATH); const char* name = std::strrchr(path, '\\'); return name ? name + 1 : path; } int main() { std::setvbuf(stdout, nullptr, _IONBF, 0); if (sceKernelInstallExceptionHandler(SIGUSR1, reinterpret_cast<void*>(&Handler)) != 0) return 2; Pthread worker = nullptr; if (scePthreadCreate(&worker, nullptr, Waker, nullptr, "waker") != 0) return 2; std::this_thread::sleep_for(std::chrono::milliseconds(50)); std::map<std::string, int> stoppedIn; int blocked = 0; for (int round = 0; round < Rounds; ++round) { resume.store(false); const int before = entered.load(); if (sceKernelRaiseException(worker, SIGUSR1) != 0) return 2; const auto raised = std::chrono::steady_clock::now(); while (entered.load() == before) { if (std::chrono::steady_clock::now() - raised > std::chrono::seconds(5)) { std::printf("round %d: the handler did not run within 5 s\n", round); return 3; } std::this_thread::yield(); } const auto module = ModuleOf(stoppedRip.load()); ++stoppedIn[module]; std::atomic<bool> done{false}; std::thread main([&] { sceKernelSyncOnAddressWake(&addressB, 1); done.store(true); }); const auto start = std::chrono::steady_clock::now(); while (!done.load() && std::chrono::steady_clock::now() - start < std::chrono::seconds(2)) std::this_thread::sleep_for(std::chrono::milliseconds(1)); if (!done.load()) { ++blocked; std::printf("round %d: sceKernelSyncOnAddressWake blocked for 2 s while the handler ran; worker stopped at %s+0x%llx\n", round, module.c_str(), static_cast<unsigned long long>(stoppedRip.load() - reinterpret_cast<std::uint64_t>(GetModuleHandleA(module.c_str())))); } resume.store(true); main.join(); } stop.store(true); scePthreadJoin(worker, nullptr); sceKernelRemoveExceptionHandler(SIGUSR1); std::printf("rounds %d, blocked %d; worker stopped in:", Rounds, blocked); for (const auto& [module, count] : stoppedIn) std::printf(" %s=%d", module.c_str(), count); std::printf("\n"); return blocked ? 1 : 0; } ``` </details>
popcoder565 commented 2026-10-08 10:51:03 +00:00 (Migrated from github.com)
Author
Contributor

Imported from boykopovar/AnyPS5. Originally posted by popcoder565 on 2026-10-08T10:51:03Z.


I measured how much of this #1421 covers, using LeandroLP23's reproducer (300 rounds per run). Setup: Windows 10 (19045), Intel Core i7-12700H, MinGW-w64 GCC 15.2.0 (WinLibs r7), Release.

Build Blocked rounds Worker stopped in
main 4b2413fb 142 libwinpthread-1.dll 256, libkernel.prx 32, the test 12
main + #1421, run 1 62 libkernel.prx 194, the test 102, ntdll.dll 4
main + #1421, run 2 76 libkernel.prx 206, the test 94

#1421 resumes and re-suspends a target that is inside libwinpthread-1.dll, so the stops inside the mutex go away. The thread is then caught a little later in libkernel, with g_waitersLock still held. With #1421, every blocked round had the worker in one of two places:

  • inside sceKernelSyncOnAddressWake, between +0x38 and +0x167;
  • at libkernel's pthread_mutex_unlock import thunk, just before the unlock.

So #1421 halves this but doesn't fix it. The remaining cases need one of the directions above: a host-code check that also covers the libraries, or the return-address hijack.

Tested with AI assistance (Claude Code).

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6058243901 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/issues/1488#issuecomment-6058243901). Originally posted by [popcoder565](https://github.com/popcoder565) on 2026-10-08T10:51:03Z. --- I measured how much of this #1421 covers, using LeandroLP23's reproducer (300 rounds per run). Setup: Windows 10 (19045), Intel Core i7-12700H, MinGW-w64 GCC 15.2.0 (WinLibs r7), Release. | Build | Blocked rounds | Worker stopped in | |---|---|---| | `main` 4b2413fb | 142 | `libwinpthread-1.dll` 256, `libkernel.prx` 32, the test 12 | | `main` + #1421, run 1 | 62 | `libkernel.prx` 194, the test 102, `ntdll.dll` 4 | | `main` + #1421, run 2 | 76 | `libkernel.prx` 206, the test 94 | #1421 resumes and re-suspends a target that is inside `libwinpthread-1.dll`, so the stops inside the mutex go away. The thread is then caught a little later in libkernel, with `g_waitersLock` still held. With #1421, every blocked round had the worker in one of two places: - inside `sceKernelSyncOnAddressWake`, between +0x38 and +0x167; - at libkernel's `pthread_mutex_unlock` import thunk, just before the unlock. So #1421 halves this but doesn't fix it. The remaining cases need one of the directions above: a host-code check that also covers the libraries, or the return-address hijack. Tested with AI assistance (Claude Code).
klosixgaming-arch commented 2026-10-08 11:50:50 +00:00 (Migrated from github.com)
Author
Contributor

Imported from boykopovar/AnyPS5. Originally posted by klosixgaming-arch on 2026-10-08T11:50:50Z.


This issue is related to several recent PRs I've reviewed that touch the exception handling code:

  • PR #1520 ("fix(libkernel): give a sleep nested in an APC its own timer on Windows") addresses a similar Windows-specific timing issue with sceKernelRaiseException handlers that sleep
  • PR #1476 (mentioned in the issue) fixes the same timer reuse for Condition waiters

The concern raised here - that a thread inside emulator code holding a host lock could be interrupted by an exception handler - is valid and worth investigating. The proposed directions (redirect only when Rip is in guest code, or unwind to first guest return address) are both reasonable approaches.

Based on my review of the related PRs, I'd suggest:

  1. Testing the reproducer phase mentioned in the issue on Windows to confirm whether this is actually happening
  2. If confirmed, direction #1 (redirect only when Rip is in guest code) seems simpler and less risky than unwinding
  3. This should be coordinated with any changes from PRs #1421 and #1431 which also modify the same delivery code

The issue correctly notes that this hasn't been reproduced yet, so testing on Windows would be valuable before attempting a fix.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6059230586 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/issues/1488#issuecomment-6059230586). Originally posted by [klosixgaming-arch](https://github.com/klosixgaming-arch) on 2026-10-08T11:50:50Z. --- This issue is related to several recent PRs I've reviewed that touch the exception handling code: - PR #1520 ("fix(libkernel): give a sleep nested in an APC its own timer on Windows") addresses a similar Windows-specific timing issue with `sceKernelRaiseException` handlers that sleep - PR #1476 (mentioned in the issue) fixes the same timer reuse for Condition waiters The concern raised here - that a thread inside emulator code holding a host lock could be interrupted by an exception handler - is valid and worth investigating. The proposed directions (redirect only when Rip is in guest code, or unwind to first guest return address) are both reasonable approaches. Based on my review of the related PRs, I'd suggest: 1. Testing the reproducer phase mentioned in the issue on Windows to confirm whether this is actually happening 2. If confirmed, direction #1 (redirect only when Rip is in guest code) seems simpler and less risky than unwinding 3. This should be coordinated with any changes from PRs #1421 and #1431 which also modify the same delivery code The issue correctly notes that this hasn't been reproduced yet, so testing on Windows would be valuable before attempting a fix.
awake-devel commented 2026-10-08 18:24:52 +00:00 (Migrated from github.com)
Author
Contributor

Imported from boykopovar/AnyPS5. Originally posted by awake-devel on 2026-10-08T18:24:52Z.


Investigated and written by Claude Code (AI), and posted by me after review.

Thanks @LeandroLP23 for the reproducer and the Windows run, and @popcoder565 for measuring #1421 with it. I've removed "unconfirmed" from the title.

Summary so far, with LeandroLP23's reproducer (300 rounds):

  • main: about half the rounds block (148 and 142). Every blocked round had the worker stopped in host code while taking or holding g_waitersLock.
  • main + #1421: 62 and 76 blocked. The stops inside libwinpthread-1.dll are gone. The rest are inside sceKernelSyncOnAddressWake (+0x38 to +0x167), or at libkernel's pthread_mutex_unlock thunk, with the lock still held.

So the cases that remain need direction 1 or 2 from the issue. The smallest step looks like widening #1421's "resume and retry" check from the system libraries to all host code, including the emulator's own libs/*.prx modules. The cost is the one already noted: a raise can spin while the target sits in a non-alertable host wait.

@popcoder565, since this builds directly on #1421, would you rather extend #1421 or take it as a follow-up PR? I can't test on Windows, so I'd rather not open a competing change. LeandroLP23's reproducer would make a good regression test for either.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6066377995 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/issues/1488#issuecomment-6066377995). Originally posted by [awake-devel](https://github.com/awake-devel) on 2026-10-08T18:24:52Z. --- > Investigated and written by Claude Code (AI), and posted by me after review. Thanks @LeandroLP23 for the reproducer and the Windows run, and @popcoder565 for measuring #1421 with it. I've removed "unconfirmed" from the title. Summary so far, with LeandroLP23's reproducer (300 rounds): - **`main`:** about half the rounds block (148 and 142). Every blocked round had the worker stopped in host code while taking or holding `g_waitersLock`. - **`main` + #1421:** 62 and 76 blocked. The stops inside `libwinpthread-1.dll` are gone. The rest are inside `sceKernelSyncOnAddressWake` (+0x38 to +0x167), or at libkernel's `pthread_mutex_unlock` thunk, with the lock still held. So the cases that remain need direction 1 or 2 from the issue. The smallest step looks like widening #1421's "resume and retry" check from the system libraries to all host code, including the emulator's own `libs/*.prx` modules. The cost is the one already noted: a raise can spin while the target sits in a non-alertable host wait. @popcoder565, since this builds directly on #1421, would you rather extend #1421 or take it as a follow-up PR? I can't test on Windows, so I'd rather not open a competing change. LeandroLP23's reproducer would make a good regression test for either.
popcoder565 commented 2026-10-09 02:56:29 +00:00 (Migrated from github.com)
Author
Contributor

Imported from boykopovar/AnyPS5. Originally posted by popcoder565 on 2026-10-09T02:56:29Z.


@awake-devel I'll take it as a follow-up PR on top of #1421. #1802 already builds on #1421 at 24dc98d7, so I'd rather not change it while it's under review.

One catch with widening the synchronous retry: it breaks the host-blocked phase of guest_raise_exception. There the main thread holds a std::mutex, raises at a worker blocked on it, and unlocks only after the raise returns. If the raise retries while the worker is in host code, it waits on itself until the 1 s bound and throws. A game thread in a long non-alertable host wait would hit the same throw, for example a condition_variable wait in an HLE library during a cold shader compile. That's worse than today's late delivery.

So I'll try deferring instead. When the target is stopped in host code, the raise goes to a delivery thread and sceKernelRaiseException returns 0 at once, like kill(). The delivery thread re-checks the target until it's back in guest code (the main executable or a *.guest.prx module) or in an alertable wait, and delivers there. I'll measure it with LeandroLP23's reproducer and the existing phases, and post the numbers here.

🤖 Addressed by Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6073313262 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/issues/1488#issuecomment-6073313262). Originally posted by [popcoder565](https://github.com/popcoder565) on 2026-10-09T02:56:29Z. --- @awake-devel I'll take it as a follow-up PR on top of #1421. #1802 already builds on #1421 at `24dc98d7`, so I'd rather not change it while it's under review. One catch with widening the synchronous retry: it breaks the host-blocked phase of `guest_raise_exception`. There the main thread holds a `std::mutex`, raises at a worker blocked on it, and unlocks only after the raise returns. If the raise retries while the worker is in host code, it waits on itself until the 1 s bound and throws. A game thread in a long non-alertable host wait would hit the same throw, for example a `condition_variable` wait in an HLE library during a cold shader compile. That's worse than today's late delivery. So I'll try deferring instead. When the target is stopped in host code, the raise goes to a delivery thread and `sceKernelRaiseException` returns 0 at once, like `kill()`. The delivery thread re-checks the target until it's back in guest code (the main executable or a `*.guest.prx` module) or in an alertable wait, and delivers there. I'll measure it with LeandroLP23's reproducer and the existing phases, and post the numbers here. _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_
popcoder565 commented 2026-10-09 03:47:33 +00:00 (Migrated from github.com)
Author
Contributor

Imported from boykopovar/AnyPS5. Originally posted by popcoder565 on 2026-10-09T03:47:33Z.


Here are the numbers for deferring raises, as promised. Setup: Windows 10 (19045), GCC 15.2.0 (WinLibs r7), Release, main f1451396 + #1421. I'm not opening a PR for this yet.

What I tried: when the target is stopped outside guest code, the raise goes to a delivery thread and returns 0. The delivery thread re-checks the target until it's stopped in the main executable or a *.guest.prx module (or in an alertable wait), then redirects it there.

  • Blocked rounds: LeandroLP23's reproducer had 0 blocked rounds in 300, against 62 and 76 with #1421 alone. Every delivery landed in the test executable.
  • Latency: this is the problem. The reproducer's worker spends nearly all its time inside sceKernelSyncOnAddressWake. The delivery thread only catches it in guest code by chance: about 75 checks per delivery (median), up to 330. One 300-round run took 120 s. Another failed in round 0 because the handler didn't run within the reproducer's 5 s.
  • Existing phases: guest_raise_exception passed 5/5 (about 10 s). Two phases needed changes, though. The host-blocked worker exits right after its last round, so a raise deferred until it returns to guest code is never delivered. The NtContinue phase now gets a delayed delivery instead of the 1 s throw.

So deferring by sampling fixes the lock problem, but delivery to a thread that stays in host code can take arbitrarily long. A GC waiting for its handlers would stall for just as long. It would need a deterministic way to deliver when the thread returns to guest code. I'll leave it here for now rather than open something that can stall a GC.

🤖 Addressed by Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6073861195 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/issues/1488#issuecomment-6073861195). Originally posted by [popcoder565](https://github.com/popcoder565) on 2026-10-09T03:47:33Z. --- Here are the numbers for deferring raises, as promised. Setup: Windows 10 (19045), GCC 15.2.0 (WinLibs r7), Release, `main` f1451396 + #1421. I'm not opening a PR for this yet. What I tried: when the target is stopped outside guest code, the raise goes to a delivery thread and returns 0. The delivery thread re-checks the target until it's stopped in the main executable or a `*.guest.prx` module (or in an alertable wait), then redirects it there. - **Blocked rounds:** LeandroLP23's reproducer had 0 blocked rounds in 300, against 62 and 76 with #1421 alone. Every delivery landed in the test executable. - **Latency:** this is the problem. The reproducer's worker spends nearly all its time inside `sceKernelSyncOnAddressWake`. The delivery thread only catches it in guest code by chance: about 75 checks per delivery (median), up to 330. One 300-round run took 120 s. Another failed in round 0 because the handler didn't run within the reproducer's 5 s. - **Existing phases:** `guest_raise_exception` passed 5/5 (about 10 s). Two phases needed changes, though. The host-blocked worker exits right after its last round, so a raise deferred until it returns to guest code is never delivered. The NtContinue phase now gets a delayed delivery instead of the 1 s throw. So deferring by sampling fixes the lock problem, but delivery to a thread that stays in host code can take arbitrarily long. A GC waiting for its handlers would stall for just as long. It would need a deterministic way to deliver when the thread returns to guest code. I'll leave it here for now rather than open something that can stall a GC. _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_
gunerky commented 2026-10-09 15:25:22 +00:00 (Migrated from github.com)
Author
Contributor

Imported from boykopovar/AnyPS5. Originally posted by gunerky on 2026-10-09T15:25:22Z.


Windows measurements and an obstacle to direction 2

I tested the host-lock scenario and the Windows unwind prerequisite for the proposed normal-return delivery approach. This is an investigation report, not a fix: no return address was modified and no deferred delivery was implemented.

Windows 11 x64 (build 26300), WinLibs MinGW-w64 GCC 15.2.0 r7 UCRT/POSIX/SEH, Release, BUILD_TESTING=ON. All three comparisons used base d70b89989473ba1f6ae13e44e079e67f1f8a44b0, with the PR heads locally integrated separately.

Build Rounds completed Independent wake did not return within 150 ms while the handler was held
Main 300/300 161
Main + #1421 (24dc98d7c035bde08e679e3c62a59402a2b57cc5) 300/300 53
Main + #1562 (076102124b98906ce5b3dc31c18f2cde020705fa) 300/300 140

Each comparison was three 100-round repeats, in ten-round child processes with a 25 s process deadline. There were no missing deliveries or child timeouts in these 900 rounds; all workers recovered after releasing the handler. The 150 ms observation window differs from the 2 s window in earlier comments. These are bounded loss-of-progress observations, not permanent-deadlock claims or directly comparable failure rates. The PR code remains its authors' work; it was not changed for these comparisons.

The additional finding concerns direction 2:

  • A read-only RtlLookupFunctionEntry/RtlVirtualUnwind probe used an explicitly registered guest assembly interval, not the entire test executable. In 100 live samples per build it found zero verified host-to-guest returns: main had 89 missing-metadata samples and 11 already in guest code; #1421 had 92/8; #1562 had 93/7. The host chain stopped in libkernel.prx. Missing metadata was not treated as a leaf frame.
  • With the supported compiler, enabling -fasynchronous-unwind-tables on the unmodified SyncOnAddress.cpp fails assembly with .seh_handlerdata used outside of .seh_proc block. An independently written throwing System V ABI fixture fails the same way. A nonthrowing System V fixture compiles, but still lacks Windows function entries.
  • A native helper can retain Windows and DWARF metadata together when the option is scoped to that function. Its integer/floating-point results and typed exception cleanup pass, but unwinding still stops at the surrounding System V ABI host wrapper.
  • The unmodified WindowsExceptions.cpp, linked to the existing project libc with its normal section rename, passes with the existing setting. Compiling that test with asynchronous tables enabled aborts at TrackedError (0xc0000409). The simple project-linked native exception fixture also aborts with that setting. These results were confirmed outside the sandbox. Thus a general flag change would both leave System V gaps and break existing exception behavior.

The existing project's DWARF .ehfram data and Windows function entries are distinct prerequisites here. The GCC patch discussion describes the same System V assembly inconsistency; no compiler patch or replacement toolchain was used. This does not prove that every possible boundary design is blocked, but it prevents presenting this Windows-API-based experiment as a working general mechanism.

Current relevant CTests: 13 passed, longest 8.75 s, including Windows exceptions, guest raise, address synchronization, thread lifecycle and the optional read-only probe. Conventions, test registration and whitespace checks passed. Long research runs were kept outside CTest; no repository timeout was increased. Pending-delivery ownership, thread-exit cancellation, nested callbacks, exception unwinding through an armed return and trampoline register/return restoration remain unimplemented and untested. Linux, PS5 hardware and games: Not tested.

The sources below were independently written from the issue's scenario, with LeandroLP23's report and popcoder565's deferred-delivery results as context, not copied reproducer code. Newly authored research sources are offered under this repository's GPLv2 license. No Sony SDK, firmware or game files were used. AI-assisted: yes, OpenAI Codex.

Reproduction commands and standalone research sources (GPLv2)

Reproducing the investigation

Save the seven source files below together in a directory outside the repository. Use Windows x64, Python 3 and the repository-supported WinLibs MinGW-w64 GCC 15.2.0 r7 toolchain. reproduce.py checks the compiler version, prepends its directory to PATH and writes only to the supplied output directory. It does not fetch, merge, commit, patch repository sources or change Windows security policies.

Use an existing Release build of the pinned source. For each measured main/PR integration, pass the corresponding directory containing matching NID-patched libkernel.prx and libc.prx. Do not mix libraries from different builds. The runner compiles the repository's existing NidCompute.cpp and Sha1.cpp from --source; those files remain covered by the project license and are not republished here.

The following paths are examples to replace, not prerequisites tied to the author's machine. PowerShell commands:

python reproduce.py measure --source C:/src/AnyPS5 --compiler C:/tools/mingw64/bin/g++.exe --libs C:/build/AnyPS5/core/libs/libs --out C:/research/1488-main-lock --mode lock --repeats 3 --batches 10
python reproduce.py measure --source C:/src/AnyPS5 --compiler C:/tools/mingw64/bin/g++.exe --libs C:/build/AnyPS5/core/libs/libs --out C:/research/1488-main-probe --mode probe --repeats 1 --batches 10

Repeat with the matching #1421 and #1562 build directories. The source identities for the reported results are listed above; the script does not make those integrations. The independent harness sends SIGUSR1 while a guest thread repeatedly calls address wake, holds the handler using atomic coordination, observes an independent wake, releases the handler, then joins. It records the actual NID calls, native thread identities and interrupted addresses. A ten-round child is terminated after 25 s if stuck. A 15-minute total budget leaves incomplete work incomplete; subprocess failure or timeout is not counted as success. Controls are available as --mode empty, guest, long_wait and finished. The long-wait control schedules release at 150 ms. Start with the default single ten-round batch if a shorter check is preferred.

For the metadata/exception comparison, use the same build's unpatched libc and import library:

python reproduce.py fixtures --source C:/src/AnyPS5 --compiler C:/tools/mingw64/bin/g++.exe --libc C:/build/AnyPS5/core/libs/libs/unpatched/libc.prx --libc-import C:/build/AnyPS5/core/libs/libs/implib/liblibc.dll.a --out C:/research/1488-metadata

The runner builds the independent ABI fixtures, the scoped native helper, the unmodified SyncOnAddress.cpp and the unmodified WindowsExceptions.cpp into isolated outputs. Each executable has the matching unpatched libc beside it. It applies the repository's .eh_frame to .ehfram rename. Expected failures are logged as failures: System V throwing/table-on assembly, SyncOnAddress/table-on assembly, and native project-linked/table-on exception executions. Native and System V table-off controls and the scoped-helper case should pass. The nonthrowing System V table-on case should return correct values but report missing metadata. The script finishing does not mean these experiments are all green or that #1488 is fixed; inspect the exit codes and JSON rows.

All commands, return codes and deadlines are in commands.jsonl; measurement observations are in results.json; fixture results are in fixtures.json. The added standalone driver was checked with a ten-round measurement smoke run and the fixture matrix; the original 900-round counts above are the earlier frozen measurements, not new counts from packaging validation. No whole-executable guest classification, missing-frame guessing or stack mutation is used. Normal integer/double fixture return checks do not test redirect restoration. The read-only analyzer's conservative accepted unwind records are version 1 without handler or chain flags.

This is standalone research material, not a proposed repository test registration or production patch. Source attribution and AI assistance are disclosed above. The included newly authored sources use the project's GPLv2 license; retain that attribution if redistributing them.

reproduce.py

import argparse
import ctypes
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import time

parser = argparse.ArgumentParser()
parser.add_argument('phase', choices=['measure', 'fixtures'])
parser.add_argument('--source', type=Path, required=True)
parser.add_argument('--compiler', default='g++')
parser.add_argument('--out', type=Path, required=True)
parser.add_argument('--libs', type=Path)
parser.add_argument('--libc', type=Path)
parser.add_argument('--libc-import', type=Path)
parser.add_argument('--mode', choices=['lock', 'empty', 'guest', 'probe', 'long_wait', 'finished'], default='lock')
parser.add_argument('--repeats', type=int, default=1)
parser.add_argument('--batches', type=int, default=1)
args = parser.parse_args()
if sys.platform != 'win32':
    parser.error('This research runner requires Windows x64 and MinGW GCC 15.2.0.')
if args.repeats < 1 or args.batches < 1:
    parser.error('Repeat and batch counts must be positive.')
ctypes.windll.kernel32.SetErrorMode(0x8003)
source = args.source.resolve()
out = args.out.resolve()
files = Path(__file__).resolve().parent
if out == source or out == files or source in out.parents:
    parser.error('Use an output directory outside the source checkout and reproducer directory.')
out.mkdir(parents=True, exist_ok=True)
resolved = shutil.which(args.compiler)
compiler = Path(resolved or args.compiler).resolve()
env = os.environ.copy()
for key in list(env):
    if key.startswith(('APS5_', 'ANYPS5_', 'VK_')):
        del env[key]
env['PATH'] = str(compiler.parent) + os.pathsep + env['PATH']
version = subprocess.check_output([str(compiler), '-dumpfullversion'], env=env, text=True).strip()
if version != '15.2.0':
    parser.error('The recorded investigation uses GCC 15.2.0; do not silently substitute another compiler.')
temporary = out / 'tmp'
temporary.mkdir(exist_ok=True)
env['TEMP'] = str(temporary)
env['TMP'] = str(temporary)


def run(name, command, timeout=90):
    command = [str(item) for item in command]
    started = time.monotonic()
    log = out / (name + '.log')
    with log.open('w', encoding='utf-8') as stream:
        stream.write(subprocess.list2cmdline(command) + '\n')
        stream.flush()
        try:
            process = subprocess.run(command, cwd=out, env=env, stdout=stream, stderr=subprocess.STDOUT, timeout=timeout)
            code, timed_out = process.returncode, False
        except subprocess.TimeoutExpired:
            code, timed_out = -1, True
    record = {'name': name, 'command': command, 'exit_code': code, 'timed_out': timed_out, 'seconds': round(time.monotonic() - started, 6)}
    with (out / 'commands.jsonl').open('a', encoding='utf-8') as stream:
        stream.write(json.dumps(record) + '\n')
    print(f'{name}: exit={code}, timed_out={timed_out}', flush=True)
    return record


def require(record):
    if record['exit_code'] or record['timed_out']:
        raise RuntimeError('See ' + str(out / (record['name'] + '.log')))


def rows(name):
    values = []
    for line in (out / (name + '.log')).read_text(encoding='utf-8', errors='replace').splitlines():
        if line.startswith('{'):
            values.append(json.loads(line))
    return values


includes = ['-I', source / 'core/libs', '-I', source / 'core/libs/nid/include', '-I', files]
common = ['-O3', '-DNDEBUG', '-std=c++20', *includes]

if args.phase == 'measure':
    if not args.libs:
        parser.error('measure requires --libs pointing to matching NID-patched libkernel.prx and libc.prx.')
    library = args.libs.resolve() / 'libkernel.prx'
    if not library.is_file() or not (library.parent / 'libc.prx').is_file():
        parser.error('The matching patched library pair is missing.')
    exe = out / 'measure.exe'
    require(run('compile-measure', [compiler, *common, '-D_WIN32_WINNT=0x0A00', '-fasynchronous-unwind-tables', files / 'Measure.cpp', files / 'WindowsHostBoundaryProbe.cpp', source / 'core/libs/nid/src/NidCompute.cpp', source / 'core/libs/nid/src/Sha1.cpp', '-o', exe, '-static-libstdc++', '-static-libgcc']))
    records = []
    started = time.monotonic()
    for repetition in range(args.repeats):
        for batch in range(args.batches):
            if time.monotonic() - started >= 900:
                break
            name = f'{args.mode}-{repetition}-{batch}'
            process = run(name, [exe, library, (repetition * args.batches + batch) * 10, args.mode, 'nid'], timeout=25)
            records.append({'process': process, 'rows': rows(name)})
    (out / 'results.json').write_text(json.dumps({'mode': args.mode, 'requested_rounds': args.repeats * args.batches * 10, 'batches': records}, indent=2), encoding='utf-8')
    if any(item['process']['exit_code'] or item['process']['timed_out'] for item in records) or len(records) != args.repeats * args.batches:
        raise SystemExit(1)
else:
    if not args.libc or not args.libc_import:
        parser.error('fixtures requires --libc (unpatched libc.prx) and --libc-import (its import library).')
    libc = args.libc.resolve()
    imports = args.libc_import.resolve()
    if not libc.is_file() or not imports.is_file():
        parser.error('The unpatched libc pair is missing.')
    objcopy = compiler.parent / 'objcopy.exe'
    if not objcopy.is_file():
        parser.error('objcopy.exe must be next to the selected compiler.')
    configs = [
        ('native-off-project', [], '-fno-asynchronous-unwind-tables', 'AbiFixture.cpp'),
        ('sysv-off-project', ['-DRESEARCH_SYSV'], '-fno-asynchronous-unwind-tables', 'AbiFixture.cpp'),
        ('native-on-project', [], '-fasynchronous-unwind-tables', 'AbiFixture.cpp'),
        ('sysv-on-project', ['-DRESEARCH_SYSV'], '-fasynchronous-unwind-tables', 'AbiFixture.cpp'),
        ('sysv-on-nonthrow', ['-DRESEARCH_SYSV', '-DRESEARCH_NO_THROW', '-fno-exceptions'], '-fasynchronous-unwind-tables', 'AbiFixture.cpp'),
        ('scoped-helper', ['-DRESEARCH_SYSV', '-DRESEARCH_SCOPED_OBSERVER'], '-fno-asynchronous-unwind-tables', 'ScopedFixture.cpp'),
    ]
    records = []
    for name, extra, tables, file in configs:
        directory = out / name
        directory.mkdir(exist_ok=True)
        shutil.copy2(libc, directory / 'libc.prx')
        obj = directory / 'fixture.o'
        exe = directory / 'fixture.exe'
        flags = [*common, tables, *extra]
        compiled = run(name + '-compile', [compiler, *flags, '-c', files / file, '-o', obj])
        tested = None
        if compiled['exit_code'] == 0:
            linked = run(name + '-link', [compiler, *flags, files / 'InspectFixture.cpp', obj, imports, '-o', exe])
            if linked['exit_code'] == 0:
                require(run(name + '-rename', [objcopy, '--rename-section', '.eh_frame=.ehfram', exe]))
                tested = run(name + '-run', [exe], timeout=10)
        records.append({'name': name, 'compile': compiled, 'run': tested})
    for tables in ['off', 'on']:
        flag = '-fno-asynchronous-unwind-tables' if tables == 'off' else '-fasynchronous-unwind-tables'
        run('SyncOnAddress-' + tables, [compiler, '-O3', '-DNDEBUG', '-std=gnu++20', *includes, flag, '-DAPS5_ENABLE_TIMING_LOG=0', '-D_WIN32_WINNT=0x0602', '-Dlibkernel_EXPORTS', '-c', source / 'core/libs/prx/libkernel/SyncOnAddress/src/SyncOnAddress.cpp', '-o', out / ('SyncOnAddress-' + tables + '.o')])
        directory = out / ('windows-exceptions-' + tables)
        directory.mkdir(exist_ok=True)
        shutil.copy2(libc, directory / 'libc.prx')
        exe = directory / 'windows-exceptions.exe'
        compiled = run('WindowsExceptions-' + tables + '-compile', [compiler, *common, flag, source / 'core/libs/tests/WindowsExceptions.cpp', imports, '-o', exe])
        if compiled['exit_code'] == 0:
            require(run('WindowsExceptions-' + tables + '-rename', [objcopy, '--rename-section', '.eh_frame=.ehfram', exe]))
            run('WindowsExceptions-' + tables + '-run', [exe], timeout=10)
    (out / 'fixtures.json').write_text(json.dumps(records, indent=2), encoding='utf-8')
    print('Experimental failure exit codes are recorded; compare them with the controls, not with an all-green suite.', flush=True)

Measure.cpp

#include "SceTypes.hpp"
#include <nid/NidCompute.hpp>
#include "WindowsHostBoundaryProbe.hpp"
#include <windows.h>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <stdexcept>
#include <string>
#include <thread>

using Clock = std::chrono::steady_clock;
using Wake = int (APS5_VABI *)(void*, std::int32_t);
using Create = int (APS5_VABI *)(Pthread*, const PthreadAttr*, PthreadEntry, void*, const char*);
using Join = int (APS5_VABI *)(Pthread, void**);
using Install = int (APS5_VABI *)(int, void*);
using Remove = int (APS5_VABI *)(int);
using Raise = int (APS5_VABI *)(Pthread, int);

struct Worker {
    std::atomic<std::uint32_t> stop{0};
    std::uint32_t address = 0;
    Wake wake = nullptr;
    std::atomic<std::uint64_t> loops{0};
    std::atomic<DWORD> id{0};
    std::atomic<std::uintptr_t> low{0};
    std::atomic<std::uintptr_t> high{0};
    std::uint32_t guestOnly = 0;
    HANDLE gate = nullptr;
    std::atomic<bool> waiting{false};
};

static_assert(offsetof(Worker, address) == 4 && offsetof(Worker, wake) == 8 && offsetof(Worker, loops) == 16);
static_assert(std::atomic<std::uint64_t>::is_always_lock_free && std::atomic<DWORD>::is_always_lock_free);
static std::atomic<bool> entered{false};
static std::atomic<bool> released{false};
static std::atomic<bool> left{false};
static std::atomic<DWORD> handlerId{0};
static std::atomic<std::uint64_t> interruptedRip{0};
static std::atomic<std::uint64_t> interruptedRsp{0};
static std::atomic<int> deliveredSignal{0};

static void APS5_VABI Handler(int signal, void* context) {
    std::uint64_t rip = 0;
    std::uint64_t rsp = 0;
    std::memcpy(&rip, static_cast<unsigned char*>(context) + 0xe0, sizeof(rip));
    std::memcpy(&rsp, static_cast<unsigned char*>(context) + 0xf8, sizeof(rsp));
    interruptedRip.store(rip, std::memory_order_relaxed);
    interruptedRsp.store(rsp, std::memory_order_relaxed);
    handlerId.store(GetCurrentThreadId(), std::memory_order_relaxed);
    deliveredSignal.store(signal, std::memory_order_relaxed);
    entered.store(true, std::memory_order_release);
    while (!released.load(std::memory_order_acquire)) {}
    left.store(true, std::memory_order_release);
}

extern "C" void APS5_VABI ResearchReady_nid_no_patch(Worker* worker) {
    ULONG_PTR low = 0;
    ULONG_PTR high = 0;
    GetCurrentThreadStackLimits(&low, &high);
    worker->low.store(low);
    worker->high.store(high);
    worker->id.store(GetCurrentThreadId(), std::memory_order_release);
}

extern "C" void APS5_VABI ResearchWait_nid_no_patch(Worker* worker) {
    worker->waiting.store(true, std::memory_order_release);
    WaitForSingleObject(worker->gate, INFINITE);
}

extern "C" void* APS5_VABI ResearchGuestBegin_nid_no_patch(void*);
extern "C" void ResearchGuestEnd_nid_no_patch();
asm(".text\n"
    ".globl ResearchGuestBegin_nid_no_patch\n"
    "ResearchGuestBegin_nid_no_patch:\n"
    "pushq %rbx\n"
    "movq %rdi, %rbx\n"
    "call ResearchReady_nid_no_patch\n"
    "1:\n"
    "cmpl $0, (%rbx)\n"
    "jne 2f\n"
    "cmpl $2, 48(%rbx)\n"
    "jne 4f\n"
    "movq %rbx, %rdi\n"
    "call ResearchWait_nid_no_patch\n"
    "jmp 3f\n"
    "4:\n"
    "cmpl $0, 48(%rbx)\n"
    "jne 3f\n"
    "leaq 4(%rbx), %rdi\n"
    "movl $1, %esi\n"
    "call *8(%rbx)\n"
    "3:\n"
    "lock incq 16(%rbx)\n"
    "jmp 1b\n"
    "2:\n"
    "xorl %eax, %eax\n"
    "popq %rbx\n"
    "ret\n"
    ".globl ResearchGuestEnd_nid_no_patch\n"
    "ResearchGuestEnd_nid_no_patch:\n");
static_assert(offsetof(Worker, guestOnly) == 48);

template<class T> static T Symbol(HMODULE module, const char* name, bool patched) {
    const auto symbol = patched ? Nid::ComputeNid(name, "libkernel") : std::string(name);
    const auto address = GetProcAddress(module, symbol.c_str());
    if (!address) throw std::runtime_error("Missing export: " + symbol);
    return reinterpret_cast<T>(address);
}

static bool Observe(const std::atomic<bool>& flag, std::chrono::milliseconds duration) {
    const auto end = Clock::now() + duration;
    while (!flag.load(std::memory_order_acquire)) {
        if (Clock::now() >= end) return false;
        std::this_thread::yield();
    }
    return true;
}

static double Milliseconds(Clock::time_point begin, Clock::time_point end) {
    return std::chrono::duration<double, std::milli>(end - begin).count();
}

static std::string Location(std::uintptr_t pc, std::uintptr_t* offset) {
    MEMORY_BASIC_INFORMATION info{};
    if (!VirtualQuery(reinterpret_cast<void*>(pc), &info, sizeof(info))) return "unknown";
    char name[MAX_PATH]{};
    const DWORD size = GetModuleFileNameA(static_cast<HMODULE>(info.AllocationBase), name, MAX_PATH);
    *offset = pc - reinterpret_cast<std::uintptr_t>(info.AllocationBase);
    if (!size) return "anonymous";
    const std::string path(name, size);
    return path.substr(path.find_last_of("/\\") + 1);
}

static void Probe(HANDLE thread, const Worker& worker, int round) {
    using namespace WindowsHostBoundary;
    CONTEXT context{};
    context.ContextFlags = CONTEXT_FULL | CONTEXT_FLOATING_POINT;
    if (SuspendThread(thread) == DWORD(-1)) throw std::runtime_error("Probe suspend failed");
    const bool captured = GetThreadContext(thread, &context);
    Analysis result;
    const char* outcome = "capture_failed";
    if (captured) {
        const std::array<GuestRange, 1> ranges{{{reinterpret_cast<DWORD64>(&ResearchGuestBegin_nid_no_patch), reinterpret_cast<DWORD64>(&ResearchGuestEnd_nid_no_patch)}}};
        result = Analyze_nid_no_patch(context, worker.low.load(), worker.high.load(), ranges);
        outcome = StatusName_nid_no_patch(result.status);
    }
    const DWORD resume = ResumeThread(thread);
    std::printf("{\"event\":\"probe\",\"round\":%d,\"outcome\":\"%s\",\"stack_written\":false,\"resumed\":%s,\"frames\":[", round, outcome, resume == DWORD(-1) ? "false" : "true");
    for (std::size_t index = 0; index < result.count; ++index) {
        std::uintptr_t offset = 0;
        const auto module = Location(result.frames[index].rip, &offset);
        std::printf("%s{\"rip\":\"0x%llx\",\"rsp\":\"0x%llx\",\"module\":\"%s\",\"offset\":\"0x%llx\",\"metadata\":%s}", index ? "," : "", static_cast<unsigned long long>(result.frames[index].rip), static_cast<unsigned long long>(result.frames[index].rsp), module.c_str(), static_cast<unsigned long long>(offset), result.frames[index].metadata ? "true" : "false");
    }
    std::puts("]}");
    std::fflush(stdout);
}

int main(int argc, char** argv) {
    SetErrorMode(0x8003);
    if (argc != 5) return 2;
    const std::string path(argv[1]);
    const std::string mode(argv[3]);
    const bool patched = std::string(argv[4]) == "nid";
    const auto slash = path.find_last_of("/\\");
    SetDllDirectoryA(path.substr(0, slash).c_str());
    const auto module = LoadLibraryA(path.c_str());
    if (!module) { std::printf("{\"event\":\"load_failed\",\"error\":%lu}\n", GetLastError()); return 3; }
    try {
        const auto create = Symbol<Create>(module, "scePthreadCreate", patched);
        const auto join = Symbol<Join>(module, "scePthreadJoin", patched);
        const auto install = Symbol<Install>(module, "sceKernelInstallExceptionHandler", patched);
        const auto remove = Symbol<Remove>(module, "sceKernelRemoveExceptionHandler", patched);
        const auto raise = Symbol<Raise>(module, "sceKernelRaiseException", patched);
        const auto wake = Symbol<Wake>(module, "sceKernelSyncOnAddressWake", patched);
        DWORD shadowPolicy = 0;
        const bool shadowRead = GetProcessMitigationPolicy(GetCurrentProcess(), ProcessUserShadowStackPolicy, &shadowPolicy, sizeof(shadowPolicy));
        std::printf("{\"event\":\"environment\",\"shadow_policy_read\":%s,\"shadow_policy_flags\":%lu,\"guest_low\":\"0x%llx\",\"guest_high\":\"0x%llx\",\"handler_clock\":\"controller_observation_upper_bound\"}\n", shadowRead ? "true" : "false", shadowPolicy, static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(&ResearchGuestBegin_nid_no_patch)), static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(&ResearchGuestEnd_nid_no_patch)));
        if (install(30, reinterpret_cast<void*>(&Handler)) != 0) throw std::runtime_error("Install failed");
        const int first = std::stoi(argv[2]);
        for (int round = first; round < first + 10; ++round) {
            entered.store(false); released.store(mode == "empty"); left.store(false); handlerId.store(0); interruptedRip.store(0); interruptedRsp.store(0); deliveredSignal.store(0);
            Worker worker;
            worker.wake = wake;
            worker.guestOnly = mode == "guest";
            if (mode == "long_wait") {
                worker.guestOnly = 2;
                worker.gate = CreateEventW(nullptr, TRUE, FALSE, nullptr);
                if (!worker.gate) throw std::runtime_error("CreateEvent failed");
            }
            Pthread target = nullptr;
            if (create(&target, nullptr, ResearchGuestBegin_nid_no_patch, &worker, "boundary measurement") != 0) throw std::runtime_error("Create failed");
            const auto readyDeadline = Clock::now() + std::chrono::seconds(2);
            while (!worker.id.load(std::memory_order_acquire) || (mode == "long_wait" ? !worker.waiting.load(std::memory_order_acquire) : worker.loops.load() < 100)) {
                if (Clock::now() > readyDeadline) throw std::runtime_error("Worker readiness timeout");
                std::this_thread::yield();
            }
            HANDLE native = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION | SYNCHRONIZE, FALSE, worker.id.load());
            if (!native) throw std::runtime_error("OpenThread failed");
            if (mode == "probe") {
                Probe(native, worker, round);
                worker.stop.store(1);
                const int joined = join(target, nullptr);
                CloseHandle(native);
                std::printf("{\"event\":\"probe_cleanup\",\"round\":%d,\"join_result\":%d}\n", round, joined);
                std::fflush(stdout);
                continue;
            }
            if (mode == "finished") {
                worker.stop.store(1);
                const bool exited = WaitForSingleObject(native, 1000) == WAIT_OBJECT_0;
                const int raised = raise(target, 30);
                const int joined = join(target, nullptr);
                CloseHandle(native);
                std::printf("{\"event\":\"exit_control\",\"round\":%d,\"exited\":%s,\"raise_result\":%d,\"handler_called\":%s,\"join_result\":%d}\n", round, exited ? "true" : "false", raised, entered.load() ? "true" : "false", joined);
                std::fflush(stdout);
                continue;
            }
            std::thread waitRelease;
            if (mode == "long_wait") {
                waitRelease = std::thread([&] { std::this_thread::sleep_for(std::chrono::milliseconds(150)); SetEvent(worker.gate); });
            }
            const auto sent = Clock::now();
            const int raised = raise(target, 30);
            const auto raiseReturned = Clock::now();
            const bool delivered = Observe(entered, std::chrono::milliseconds(1000));
            const auto handlerObserved = Clock::now();
            std::atomic<bool> wakeStarted{false};
            std::atomic<bool> wakeDone{false};
            int wakeResult = -1;
            std::uint32_t independent = 0;
            Clock::time_point wakeBegin;
            Clock::time_point wakeEnd;
            std::thread independentThread([&] {
                wakeBegin = Clock::now();
                wakeStarted.store(true, std::memory_order_release);
                wakeResult = wake(&independent, 1);
                wakeEnd = Clock::now();
                wakeDone.store(true, std::memory_order_release);
            });
            Observe(wakeStarted, std::chrono::milliseconds(1000));
            const bool progressedWhileHeld = Observe(wakeDone, std::chrono::milliseconds(150));
            const auto beforeRelease = Clock::now();
            std::uintptr_t offset = 0;
            const auto interruptedModule = Location(interruptedRip.load(), &offset);
            const char* outcome = !delivered ? "missing_delivery" : !progressedWhileHeld ? "wake_blocked_while_handler_held" : Milliseconds(sent, handlerObserved) > 100 ? "delayed_delivery" : "delivered_wake_progressed";
            std::printf("{\"event\":\"observation\",\"round\":%d,\"outcome\":\"%s\",\"raise_result\":%d,\"raise_ms\":%.6f,\"delivery_observed_ms\":%.6f,\"wake_progressed_while_held\":%s,\"hold_observed_ms\":%.6f,\"worker_id\":%lu,\"handler_id\":%lu,\"signal\":%d,\"interrupted_rip\":\"0x%llx\",\"interrupted_rsp\":\"0x%llx\",\"interrupted_module\":\"%s\",\"module_offset\":\"0x%llx\"}\n", round, outcome, raised, Milliseconds(sent, raiseReturned), Milliseconds(sent, handlerObserved), progressedWhileHeld ? "true" : "false", Milliseconds(handlerObserved, beforeRelease), worker.id.load(), handlerId.load(), deliveredSignal.load(), static_cast<unsigned long long>(interruptedRip.load()), static_cast<unsigned long long>(interruptedRsp.load()), interruptedModule.c_str(), static_cast<unsigned long long>(offset));
            std::fflush(stdout);
            released.store(true, std::memory_order_release);
            const bool handlerRecovered = Observe(left, std::chrono::milliseconds(1000));
            worker.stop.store(1);
            independentThread.join();
            const int joined = join(target, nullptr);
            if (waitRelease.joinable()) waitRelease.join();
            if (worker.gate) CloseHandle(worker.gate);
            CloseHandle(native);
            std::printf("{\"event\":\"completion\",\"round\":%d,\"handler_recovered\":%s,\"wake_result\":%d,\"wake_ms\":%.6f,\"join_result\":%d,\"same_thread\":%s,\"loops\":%llu}\n", round, handlerRecovered ? "true" : "false", wakeResult, Milliseconds(wakeBegin, wakeEnd), joined, handlerId.load() == worker.id.load() ? "true" : "false", static_cast<unsigned long long>(worker.loops.load()));
            std::fflush(stdout);
        }
        if (remove(30) != 0) throw std::runtime_error("Remove failed");
    } catch (const std::exception& error) {
        std::printf("{\"event\":\"error\",\"message\":\"%s\"}\n", error.what());
        std::fflush(stdout);
        return 4;
    }
    return 0;
}

WindowsHostBoundaryProbe.hpp

#ifndef CORE_LIBS_PRX_LIBKERNEL_WINDOWS_HOST_BOUNDARY_PROBE_HPP
#define CORE_LIBS_PRX_LIBKERNEL_WINDOWS_HOST_BOUNDARY_PROBE_HPP

#include <windows.h>
#include <array>
#include <cstddef>
#include <span>

namespace WindowsHostBoundary {

struct GuestRange {
    DWORD64 low;
    DWORD64 high;
};

enum class Status {
    RegisteredGuest,
    NormalReturnCandidate,
    InvalidGuestRange,
    UnsupportedContext,
    StackBounds,
    UnreadableStack,
    MissingUnwindMetadata,
    UnsupportedUnwindHandler,
    InvalidMetadata,
    InvalidUnwindProgress,
    InvalidReturnSlot,
    FrameLimit
};

struct Frame {
    DWORD64 rip = 0;
    DWORD64 rsp = 0;
    bool metadata = false;
};

struct Analysis {
    Status status = Status::UnsupportedContext;
    std::array<Frame, 32> frames{};
    std::size_t count = 0;
    DWORD64 returnSlot = 0;
    DWORD64 guestReturn = 0;
};

Analysis Analyze_nid_no_patch(const CONTEXT& context, DWORD64 stackLow, DWORD64 stackHigh, std::span<const GuestRange> guestRanges);
const char* StatusName_nid_no_patch(Status status);

}

#endif

WindowsHostBoundaryProbe.cpp

#include "WindowsHostBoundaryProbe.hpp"
#include <cstdint>
#include <limits>

namespace WindowsHostBoundary {
namespace {

bool Readable(DWORD64 low, DWORD64 high) {
    if (low >= high) return false;
    while (low < high) {
        MEMORY_BASIC_INFORMATION info{};
        if (VirtualQuery(reinterpret_cast<void*>(low), &info, sizeof(info)) != sizeof(info)) return false;
        if (info.State != MEM_COMMIT || (info.Protect & (PAGE_GUARD | PAGE_NOACCESS))) return false;
        if (!(info.Protect & (PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY))) return false;
        const auto base = reinterpret_cast<DWORD64>(info.BaseAddress);
        if (info.RegionSize > std::numeric_limits<DWORD64>::max() - base) return false;
        const auto end = base + info.RegionSize;
        if (end <= low) return false;
        low = end;
    }
    return true;
}

bool Executable(DWORD64 low, DWORD64 high) {
    if (low >= high) return false;
    while (low < high) {
        MEMORY_BASIC_INFORMATION info{};
        if (VirtualQuery(reinterpret_cast<void*>(low), &info, sizeof(info)) != sizeof(info)) return false;
        if (info.State != MEM_COMMIT || (info.Protect & (PAGE_GUARD | PAGE_NOACCESS))) return false;
        if (!(info.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY))) return false;
        const auto base = reinterpret_cast<DWORD64>(info.BaseAddress);
        if (info.RegionSize > std::numeric_limits<DWORD64>::max() - base) return false;
        const auto end = base + info.RegionSize;
        if (end <= low) return false;
        low = end;
    }
    return true;
}

bool Guest(DWORD64 pc, std::span<const GuestRange> ranges) {
    for (const auto& range : ranges)
        if (pc >= range.low && pc < range.high) return true;
    return false;
}

bool Read(DWORD64 address, void* output, SIZE_T size) {
    SIZE_T copied = 0;
    return ReadProcessMemory(GetCurrentProcess(), reinterpret_cast<void*>(address), output, size, &copied) && copied == size;
}

}

Analysis Analyze_nid_no_patch(const CONTEXT& input, DWORD64 stackLow, DWORD64 stackHigh, std::span<const GuestRange> guestRanges) {
    Analysis result;
    if (guestRanges.empty()) {
        result.status = Status::InvalidGuestRange;
        return result;
    }
    for (const auto& range : guestRanges) {
        if (!Executable(range.low, range.high)) {
            result.status = Status::InvalidGuestRange;
            return result;
        }
    }
    if ((input.ContextFlags & CONTEXT_CONTROL) != CONTEXT_CONTROL || (input.ContextFlags & CONTEXT_INTEGER) != CONTEXT_INTEGER) return result;
    if (stackLow >= stackHigh || stackHigh - stackLow < 8 || input.Rsp < stackLow || input.Rsp > stackHigh - 8) {
        result.status = Status::StackBounds;
        return result;
    }
    if (!Readable(input.Rsp, stackHigh)) {
        result.status = Status::UnreadableStack;
        return result;
    }
    CONTEXT context = input;
    result.status = Status::FrameLimit;
    DWORD64 slot = 0;
    for (std::size_t index = 0; index < result.frames.size(); ++index) {
        result.frames[index] = {context.Rip, context.Rsp, false};
        ++result.count;
        if (Guest(context.Rip, guestRanges)) {
            result.status = index == 0 ? Status::RegisteredGuest : Status::NormalReturnCandidate;
            result.returnSlot = slot;
            result.guestReturn = context.Rip;
            return result;
        }
        DWORD64 base = 0;
        const auto entry = RtlLookupFunctionEntry(context.Rip, &base, nullptr);
        if (!entry) {
            result.status = Status::MissingUnwindMetadata;
            return result;
        }
        result.frames[index].metadata = true;
        RUNTIME_FUNCTION function{};
        if (!Read(reinterpret_cast<DWORD64>(entry), &function, sizeof(function)) || function.BeginAddress >= function.EndAddress || base > std::numeric_limits<DWORD64>::max() - function.EndAddress || context.Rip < base + function.BeginAddress || context.Rip >= base + function.EndAddress || base > std::numeric_limits<DWORD64>::max() - function.UnwindData) {
            result.status = Status::InvalidMetadata;
            return result;
        }
        std::uint8_t header = 0;
        if (!Read(base + function.UnwindData, &header, sizeof(header)) || (header & 7) != 1 || (header >> 3) != 0) {
            result.status = Status::UnsupportedUnwindHandler;
            return result;
        }
        const auto oldRsp = context.Rsp;
        void* data = nullptr;
        DWORD64 establisher = 0;
        RtlVirtualUnwind(UNW_FLAG_NHANDLER, base, context.Rip, entry, &context, &data, &establisher, nullptr);
        if (context.Rsp <= oldRsp || context.Rsp > stackHigh || establisher < stackLow || establisher >= stackHigh) {
            result.status = Status::InvalidUnwindProgress;
            return result;
        }
        slot = context.Rsp - 8;
        DWORD64 stored = 0;
        if (slot < oldRsp || !Read(slot, &stored, sizeof(stored)) || stored != context.Rip || !Executable(context.Rip, context.Rip + 1)) {
            result.status = Status::InvalidReturnSlot;
            return result;
        }
    }
    return result;
}

const char* StatusName_nid_no_patch(Status status) {
    switch (status) {
        case Status::RegisteredGuest: return "registered_guest";
        case Status::NormalReturnCandidate: return "normal_return_candidate";
        case Status::InvalidGuestRange: return "invalid_guest_range";
        case Status::UnsupportedContext: return "unsupported_context";
        case Status::StackBounds: return "stack_bounds";
        case Status::UnreadableStack: return "unreadable_stack";
        case Status::MissingUnwindMetadata: return "missing_unwind_metadata";
        case Status::UnsupportedUnwindHandler: return "unsupported_unwind_handler";
        case Status::InvalidMetadata: return "invalid_metadata";
        case Status::InvalidUnwindProgress: return "invalid_unwind_progress";
        case Status::InvalidReturnSlot: return "invalid_return_slot";
        case Status::FrameLimit: return "frame_limit";
    }
    return "unknown_status";
}

}

AbiFixture.cpp

#include "prx/libc/include/general/VabiMacros.hpp"
#include <cstdint>
#include <stdexcept>

#ifdef RESEARCH_SYSV
#define RESEARCH_ABI APS5_VABI
#else
#define RESEARCH_ABI
#endif

using Observer = void (*)(std::uint64_t);

extern "C" __attribute__((noinline)) std::uint64_t RESEARCH_ABI ResearchInteger_nid_no_patch(std::uint64_t value, Observer observer) {
    volatile std::uint64_t storage[17]{};
    storage[0] = value;
    storage[16] = value ^ 0x123456789abcdef0ULL;
    observer(storage[16]);
    return storage[0] + storage[16];
}

extern "C" __attribute__((noinline)) double RESEARCH_ABI ResearchFloating_nid_no_patch(double value, Observer observer) {
    volatile double storage[17]{};
    storage[0] = value;
    storage[16] = value * 1.5;
    observer(static_cast<std::uint64_t>(storage[16]));
    return storage[0] + storage[16];
}

#ifndef RESEARCH_NO_THROW
extern "C" __attribute__((noinline)) void RESEARCH_ABI ResearchThrow_nid_no_patch(int* destroyed) {
    struct Guard {
        int* destroyed;
        ~Guard() { ++*destroyed; }
    } guard{destroyed};
    throw std::runtime_error("metadata fixture exception");
}
#endif

InspectFixture.cpp

#include "prx/libc/include/general/VabiMacros.hpp"
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <stdexcept>

#ifdef RESEARCH_SYSV
#define RESEARCH_ABI APS5_VABI
#else
#define RESEARCH_ABI
#endif

using Observer = void (*)(std::uint64_t);
extern "C" std::uint64_t RESEARCH_ABI ResearchInteger_nid_no_patch(std::uint64_t, Observer);
extern "C" double RESEARCH_ABI ResearchFloating_nid_no_patch(double, Observer);
#ifndef RESEARCH_NO_THROW
extern "C" void RESEARCH_ABI ResearchThrow_nid_no_patch(int*);
#endif

#ifdef RESEARCH_SCOPED_OBSERVER
extern "C" std::uint64_t ResearchNativeHelper_nid_no_patch(std::uint64_t, Observer);
__attribute__((noinline, optimize("asynchronous-unwind-tables")))
#endif
static void Observe(std::uint64_t value) {
    CONTEXT context{};
    RtlCaptureContext(&context);
    for (unsigned depth = 0; depth < 4; ++depth) {
        DWORD64 base = 0;
        const auto entry = RtlLookupFunctionEntry(context.Rip, &base, nullptr);
        std::printf("{\"event\":\"active_frame\",\"depth\":%u,\"metadata\":%s,\"rip\":\"0x%llx\",\"value\":%llu}\n", depth, entry ? "true" : "false", static_cast<unsigned long long>(context.Rip), static_cast<unsigned long long>(value));
        if (!entry) break;
        void* data = nullptr;
        DWORD64 establisher = 0;
        RtlVirtualUnwind(UNW_FLAG_NHANDLER, base, context.Rip, entry, &context, &data, &establisher, nullptr);
    }
}

int main() {
    SetErrorMode(0x8003);
    DWORD64 base = 0;
    const DWORD64 addresses[]{reinterpret_cast<DWORD64>(&ResearchInteger_nid_no_patch), reinterpret_cast<DWORD64>(&ResearchFloating_nid_no_patch)
#ifdef RESEARCH_SCOPED_OBSERVER
        , reinterpret_cast<DWORD64>(&ResearchNativeHelper_nid_no_patch)
#endif
#ifndef RESEARCH_NO_THROW
        , reinterpret_cast<DWORD64>(&ResearchThrow_nid_no_patch)
#endif
    };
    for (const auto address : addresses) {
        const auto entry = RtlLookupFunctionEntry(address, &base, nullptr);
        std::printf("{\"event\":\"lookup\",\"address\":\"0x%llx\",\"metadata\":%s}\n", static_cast<unsigned long long>(address), entry ? "true" : "false");
    }
    const auto integer = ResearchInteger_nid_no_patch(19, Observe);
    const auto floating = ResearchFloating_nid_no_patch(2.25, Observe);
#ifndef RESEARCH_NO_THROW
    int destroyed = 0;
    bool caught = false;
    try {
        ResearchThrow_nid_no_patch(&destroyed);
    } catch (const std::runtime_error& error) {
        caught = std::strcmp(error.what(), "metadata fixture exception") == 0;
    }
    const bool correct = integer == 19 + (19 ^ 0x123456789abcdef0ULL) && floating == 5.625 && caught && destroyed == 1;
    std::printf("{\"event\":\"returns_and_exception\",\"correct\":%s,\"destroyed\":%d,\"caught\":%s}\n", correct ? "true" : "false", destroyed, caught ? "true" : "false");
#else
    const bool correct = integer == 19 + (19 ^ 0x123456789abcdef0ULL) && floating == 5.625;
    std::printf("{\"event\":\"returns_only\",\"correct\":%s}\n", correct ? "true" : "false");
#endif
    return correct ? 0 : 1;
}

ScopedFixture.cpp

#include "prx/libc/include/general/VabiMacros.hpp"
#include <cstdint>
#include <stdexcept>

using Observer = void (*)(std::uint64_t);

extern "C" __attribute__((noinline, optimize("asynchronous-unwind-tables"))) std::uint64_t ResearchNativeHelper_nid_no_patch(std::uint64_t value, Observer observer) {
    volatile std::uint64_t storage[17]{};
    storage[0] = value;
    storage[16] = value ^ 0x123456789abcdef0ULL;
    observer(storage[16]);
    return storage[0] + storage[16];
}

extern "C" __attribute__((noinline)) std::uint64_t APS5_VABI ResearchInteger_nid_no_patch(std::uint64_t value, Observer observer) {
    return ResearchNativeHelper_nid_no_patch(value, observer);
}

extern "C" __attribute__((noinline)) double APS5_VABI ResearchFloating_nid_no_patch(double value, Observer observer) {
    volatile double storage[17]{};
    storage[0] = value;
    storage[16] = value * 1.5;
    observer(static_cast<std::uint64_t>(storage[16]));
    return storage[0] + storage[16];
}

extern "C" __attribute__((noinline)) void APS5_VABI ResearchThrow_nid_no_patch(int* destroyed) {
    struct Guard {
        int* destroyed;
        ~Guard() { ++*destroyed; }
    } guard{destroyed};
    throw std::runtime_error("metadata fixture exception");
}
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6083922076 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/issues/1488#issuecomment-6083922076). Originally posted by [gunerky](https://github.com/gunerky) on 2026-10-09T15:25:22Z. --- ### Windows measurements and an obstacle to direction 2 I tested the host-lock scenario and the Windows unwind prerequisite for the proposed normal-return delivery approach. This is an investigation report, not a fix: no return address was modified and no deferred delivery was implemented. Windows 11 x64 (build 26300), WinLibs MinGW-w64 GCC 15.2.0 r7 UCRT/POSIX/SEH, Release, `BUILD_TESTING=ON`. All three comparisons used base `d70b89989473ba1f6ae13e44e079e67f1f8a44b0`, with the PR heads locally integrated separately. | Build | Rounds completed | Independent wake did not return within 150 ms while the handler was held | | --- | ---: | ---: | | Main | 300/300 | 161 | | Main + #1421 (`24dc98d7c035bde08e679e3c62a59402a2b57cc5`) | 300/300 | 53 | | Main + #1562 (`076102124b98906ce5b3dc31c18f2cde020705fa`) | 300/300 | 140 | Each comparison was three 100-round repeats, in ten-round child processes with a 25 s process deadline. There were no missing deliveries or child timeouts in these 900 rounds; all workers recovered after releasing the handler. The 150 ms observation window differs from the 2 s window in earlier comments. These are bounded loss-of-progress observations, not permanent-deadlock claims or directly comparable failure rates. The PR code remains its authors' work; it was not changed for these comparisons. The additional finding concerns direction 2: - A read-only `RtlLookupFunctionEntry`/`RtlVirtualUnwind` probe used an explicitly registered guest assembly interval, not the entire test executable. In 100 live samples per build it found **zero verified host-to-guest returns**: main had 89 missing-metadata samples and 11 already in guest code; #1421 had 92/8; #1562 had 93/7. The host chain stopped in `libkernel.prx`. Missing metadata was not treated as a leaf frame. - With the supported compiler, enabling `-fasynchronous-unwind-tables` on the unmodified `SyncOnAddress.cpp` fails assembly with `.seh_handlerdata used outside of .seh_proc block`. An independently written throwing System V ABI fixture fails the same way. A nonthrowing System V fixture compiles, but still lacks Windows function entries. - A native helper can retain Windows and DWARF metadata together when the option is scoped to that function. Its integer/floating-point results and typed exception cleanup pass, but unwinding still stops at the surrounding System V ABI host wrapper. - The unmodified `WindowsExceptions.cpp`, linked to the existing project libc with its normal section rename, passes with the existing setting. Compiling that test with asynchronous tables enabled aborts at `TrackedError` (`0xc0000409`). The simple project-linked native exception fixture also aborts with that setting. These results were confirmed outside the sandbox. Thus a general flag change would both leave System V gaps and break existing exception behavior. The existing project's DWARF `.ehfram` data and Windows function entries are distinct prerequisites here. The [GCC patch discussion](https://gcc.gnu.org/pipermail/gcc-patches/2026-May/716290.html) describes the same System V assembly inconsistency; no compiler patch or replacement toolchain was used. This does not prove that every possible boundary design is blocked, but it prevents presenting this Windows-API-based experiment as a working general mechanism. Current relevant CTests: **13 passed**, longest 8.75 s, including Windows exceptions, guest raise, address synchronization, thread lifecycle and the optional read-only probe. Conventions, test registration and whitespace checks passed. Long research runs were kept outside CTest; no repository timeout was increased. Pending-delivery ownership, thread-exit cancellation, nested callbacks, exception unwinding through an armed return and trampoline register/return restoration remain unimplemented and untested. Linux, PS5 hardware and games: **Not tested**. The sources below were independently written from the issue's scenario, with [LeandroLP23's report](https://github.com/boykopovar/AnyPS5/issues/1488#issuecomment-6057190528) and [popcoder565's deferred-delivery results](https://github.com/boykopovar/AnyPS5/issues/1488#issuecomment-6073861195) as context, not copied reproducer code. Newly authored research sources are offered under this repository's [GPLv2 license](https://github.com/boykopovar/AnyPS5/blob/d70b89989473ba1f6ae13e44e079e67f1f8a44b0/LICENSE). No Sony SDK, firmware or game files were used. **AI-assisted: yes, OpenAI Codex.** <details> <summary>Reproduction commands and standalone research sources (GPLv2)</summary> # Reproducing the investigation Save the seven source files below together in a directory outside the repository. Use Windows x64, Python 3 and the repository-supported WinLibs MinGW-w64 GCC 15.2.0 r7 toolchain. `reproduce.py` checks the compiler version, prepends its directory to PATH and writes only to the supplied output directory. It does not fetch, merge, commit, patch repository sources or change Windows security policies. Use an existing Release build of the pinned source. For each measured main/PR integration, pass the corresponding directory containing matching NID-patched `libkernel.prx` and `libc.prx`. Do not mix libraries from different builds. The runner compiles the repository's existing `NidCompute.cpp` and `Sha1.cpp` from `--source`; those files remain covered by the project license and are not republished here. The following paths are examples to replace, not prerequisites tied to the author's machine. PowerShell commands: ```powershell python reproduce.py measure --source C:/src/AnyPS5 --compiler C:/tools/mingw64/bin/g++.exe --libs C:/build/AnyPS5/core/libs/libs --out C:/research/1488-main-lock --mode lock --repeats 3 --batches 10 python reproduce.py measure --source C:/src/AnyPS5 --compiler C:/tools/mingw64/bin/g++.exe --libs C:/build/AnyPS5/core/libs/libs --out C:/research/1488-main-probe --mode probe --repeats 1 --batches 10 ``` Repeat with the matching #1421 and #1562 build directories. The source identities for the reported results are listed above; the script does not make those integrations. The independent harness sends SIGUSR1 while a guest thread repeatedly calls address wake, holds the handler using atomic coordination, observes an independent wake, releases the handler, then joins. It records the actual NID calls, native thread identities and interrupted addresses. A ten-round child is terminated after 25 s if stuck. A 15-minute total budget leaves incomplete work incomplete; subprocess failure or timeout is not counted as success. Controls are available as `--mode empty`, `guest`, `long_wait` and `finished`. The long-wait control schedules release at 150 ms. Start with the default single ten-round batch if a shorter check is preferred. For the metadata/exception comparison, use the same build's **unpatched** libc and import library: ```powershell python reproduce.py fixtures --source C:/src/AnyPS5 --compiler C:/tools/mingw64/bin/g++.exe --libc C:/build/AnyPS5/core/libs/libs/unpatched/libc.prx --libc-import C:/build/AnyPS5/core/libs/libs/implib/liblibc.dll.a --out C:/research/1488-metadata ``` The runner builds the independent ABI fixtures, the scoped native helper, the unmodified `SyncOnAddress.cpp` and the unmodified `WindowsExceptions.cpp` into isolated outputs. Each executable has the matching unpatched libc beside it. It applies the repository's `.eh_frame` to `.ehfram` rename. Expected failures are logged as failures: System V throwing/table-on assembly, `SyncOnAddress`/table-on assembly, and native project-linked/table-on exception executions. Native and System V table-off controls and the scoped-helper case should pass. The nonthrowing System V table-on case should return correct values but report missing metadata. The script finishing does not mean these experiments are all green or that #1488 is fixed; inspect the exit codes and JSON rows. All commands, return codes and deadlines are in `commands.jsonl`; measurement observations are in `results.json`; fixture results are in `fixtures.json`. The added standalone driver was checked with a ten-round measurement smoke run and the fixture matrix; the original 900-round counts above are the earlier frozen measurements, not new counts from packaging validation. No whole-executable guest classification, missing-frame guessing or stack mutation is used. Normal integer/double fixture return checks do not test redirect restoration. The read-only analyzer's conservative accepted unwind records are version 1 without handler or chain flags. This is standalone research material, not a proposed repository test registration or production patch. Source attribution and AI assistance are disclosed above. The included newly authored sources use the project's GPLv2 license; retain that attribution if redistributing them. ### `reproduce.py` ```python import argparse import ctypes import json import os from pathlib import Path import shutil import subprocess import sys import time parser = argparse.ArgumentParser() parser.add_argument('phase', choices=['measure', 'fixtures']) parser.add_argument('--source', type=Path, required=True) parser.add_argument('--compiler', default='g++') parser.add_argument('--out', type=Path, required=True) parser.add_argument('--libs', type=Path) parser.add_argument('--libc', type=Path) parser.add_argument('--libc-import', type=Path) parser.add_argument('--mode', choices=['lock', 'empty', 'guest', 'probe', 'long_wait', 'finished'], default='lock') parser.add_argument('--repeats', type=int, default=1) parser.add_argument('--batches', type=int, default=1) args = parser.parse_args() if sys.platform != 'win32': parser.error('This research runner requires Windows x64 and MinGW GCC 15.2.0.') if args.repeats < 1 or args.batches < 1: parser.error('Repeat and batch counts must be positive.') ctypes.windll.kernel32.SetErrorMode(0x8003) source = args.source.resolve() out = args.out.resolve() files = Path(__file__).resolve().parent if out == source or out == files or source in out.parents: parser.error('Use an output directory outside the source checkout and reproducer directory.') out.mkdir(parents=True, exist_ok=True) resolved = shutil.which(args.compiler) compiler = Path(resolved or args.compiler).resolve() env = os.environ.copy() for key in list(env): if key.startswith(('APS5_', 'ANYPS5_', 'VK_')): del env[key] env['PATH'] = str(compiler.parent) + os.pathsep + env['PATH'] version = subprocess.check_output([str(compiler), '-dumpfullversion'], env=env, text=True).strip() if version != '15.2.0': parser.error('The recorded investigation uses GCC 15.2.0; do not silently substitute another compiler.') temporary = out / 'tmp' temporary.mkdir(exist_ok=True) env['TEMP'] = str(temporary) env['TMP'] = str(temporary) def run(name, command, timeout=90): command = [str(item) for item in command] started = time.monotonic() log = out / (name + '.log') with log.open('w', encoding='utf-8') as stream: stream.write(subprocess.list2cmdline(command) + '\n') stream.flush() try: process = subprocess.run(command, cwd=out, env=env, stdout=stream, stderr=subprocess.STDOUT, timeout=timeout) code, timed_out = process.returncode, False except subprocess.TimeoutExpired: code, timed_out = -1, True record = {'name': name, 'command': command, 'exit_code': code, 'timed_out': timed_out, 'seconds': round(time.monotonic() - started, 6)} with (out / 'commands.jsonl').open('a', encoding='utf-8') as stream: stream.write(json.dumps(record) + '\n') print(f'{name}: exit={code}, timed_out={timed_out}', flush=True) return record def require(record): if record['exit_code'] or record['timed_out']: raise RuntimeError('See ' + str(out / (record['name'] + '.log'))) def rows(name): values = [] for line in (out / (name + '.log')).read_text(encoding='utf-8', errors='replace').splitlines(): if line.startswith('{'): values.append(json.loads(line)) return values includes = ['-I', source / 'core/libs', '-I', source / 'core/libs/nid/include', '-I', files] common = ['-O3', '-DNDEBUG', '-std=c++20', *includes] if args.phase == 'measure': if not args.libs: parser.error('measure requires --libs pointing to matching NID-patched libkernel.prx and libc.prx.') library = args.libs.resolve() / 'libkernel.prx' if not library.is_file() or not (library.parent / 'libc.prx').is_file(): parser.error('The matching patched library pair is missing.') exe = out / 'measure.exe' require(run('compile-measure', [compiler, *common, '-D_WIN32_WINNT=0x0A00', '-fasynchronous-unwind-tables', files / 'Measure.cpp', files / 'WindowsHostBoundaryProbe.cpp', source / 'core/libs/nid/src/NidCompute.cpp', source / 'core/libs/nid/src/Sha1.cpp', '-o', exe, '-static-libstdc++', '-static-libgcc'])) records = [] started = time.monotonic() for repetition in range(args.repeats): for batch in range(args.batches): if time.monotonic() - started >= 900: break name = f'{args.mode}-{repetition}-{batch}' process = run(name, [exe, library, (repetition * args.batches + batch) * 10, args.mode, 'nid'], timeout=25) records.append({'process': process, 'rows': rows(name)}) (out / 'results.json').write_text(json.dumps({'mode': args.mode, 'requested_rounds': args.repeats * args.batches * 10, 'batches': records}, indent=2), encoding='utf-8') if any(item['process']['exit_code'] or item['process']['timed_out'] for item in records) or len(records) != args.repeats * args.batches: raise SystemExit(1) else: if not args.libc or not args.libc_import: parser.error('fixtures requires --libc (unpatched libc.prx) and --libc-import (its import library).') libc = args.libc.resolve() imports = args.libc_import.resolve() if not libc.is_file() or not imports.is_file(): parser.error('The unpatched libc pair is missing.') objcopy = compiler.parent / 'objcopy.exe' if not objcopy.is_file(): parser.error('objcopy.exe must be next to the selected compiler.') configs = [ ('native-off-project', [], '-fno-asynchronous-unwind-tables', 'AbiFixture.cpp'), ('sysv-off-project', ['-DRESEARCH_SYSV'], '-fno-asynchronous-unwind-tables', 'AbiFixture.cpp'), ('native-on-project', [], '-fasynchronous-unwind-tables', 'AbiFixture.cpp'), ('sysv-on-project', ['-DRESEARCH_SYSV'], '-fasynchronous-unwind-tables', 'AbiFixture.cpp'), ('sysv-on-nonthrow', ['-DRESEARCH_SYSV', '-DRESEARCH_NO_THROW', '-fno-exceptions'], '-fasynchronous-unwind-tables', 'AbiFixture.cpp'), ('scoped-helper', ['-DRESEARCH_SYSV', '-DRESEARCH_SCOPED_OBSERVER'], '-fno-asynchronous-unwind-tables', 'ScopedFixture.cpp'), ] records = [] for name, extra, tables, file in configs: directory = out / name directory.mkdir(exist_ok=True) shutil.copy2(libc, directory / 'libc.prx') obj = directory / 'fixture.o' exe = directory / 'fixture.exe' flags = [*common, tables, *extra] compiled = run(name + '-compile', [compiler, *flags, '-c', files / file, '-o', obj]) tested = None if compiled['exit_code'] == 0: linked = run(name + '-link', [compiler, *flags, files / 'InspectFixture.cpp', obj, imports, '-o', exe]) if linked['exit_code'] == 0: require(run(name + '-rename', [objcopy, '--rename-section', '.eh_frame=.ehfram', exe])) tested = run(name + '-run', [exe], timeout=10) records.append({'name': name, 'compile': compiled, 'run': tested}) for tables in ['off', 'on']: flag = '-fno-asynchronous-unwind-tables' if tables == 'off' else '-fasynchronous-unwind-tables' run('SyncOnAddress-' + tables, [compiler, '-O3', '-DNDEBUG', '-std=gnu++20', *includes, flag, '-DAPS5_ENABLE_TIMING_LOG=0', '-D_WIN32_WINNT=0x0602', '-Dlibkernel_EXPORTS', '-c', source / 'core/libs/prx/libkernel/SyncOnAddress/src/SyncOnAddress.cpp', '-o', out / ('SyncOnAddress-' + tables + '.o')]) directory = out / ('windows-exceptions-' + tables) directory.mkdir(exist_ok=True) shutil.copy2(libc, directory / 'libc.prx') exe = directory / 'windows-exceptions.exe' compiled = run('WindowsExceptions-' + tables + '-compile', [compiler, *common, flag, source / 'core/libs/tests/WindowsExceptions.cpp', imports, '-o', exe]) if compiled['exit_code'] == 0: require(run('WindowsExceptions-' + tables + '-rename', [objcopy, '--rename-section', '.eh_frame=.ehfram', exe])) run('WindowsExceptions-' + tables + '-run', [exe], timeout=10) (out / 'fixtures.json').write_text(json.dumps(records, indent=2), encoding='utf-8') print('Experimental failure exit codes are recorded; compare them with the controls, not with an all-green suite.', flush=True) ``` ### `Measure.cpp` ```cpp #include "SceTypes.hpp" #include <nid/NidCompute.hpp> #include "WindowsHostBoundaryProbe.hpp" #include <windows.h> #include <atomic> #include <chrono> #include <cstddef> #include <cstdint> #include <cstdio> #include <cstring> #include <stdexcept> #include <string> #include <thread> using Clock = std::chrono::steady_clock; using Wake = int (APS5_VABI *)(void*, std::int32_t); using Create = int (APS5_VABI *)(Pthread*, const PthreadAttr*, PthreadEntry, void*, const char*); using Join = int (APS5_VABI *)(Pthread, void**); using Install = int (APS5_VABI *)(int, void*); using Remove = int (APS5_VABI *)(int); using Raise = int (APS5_VABI *)(Pthread, int); struct Worker { std::atomic<std::uint32_t> stop{0}; std::uint32_t address = 0; Wake wake = nullptr; std::atomic<std::uint64_t> loops{0}; std::atomic<DWORD> id{0}; std::atomic<std::uintptr_t> low{0}; std::atomic<std::uintptr_t> high{0}; std::uint32_t guestOnly = 0; HANDLE gate = nullptr; std::atomic<bool> waiting{false}; }; static_assert(offsetof(Worker, address) == 4 && offsetof(Worker, wake) == 8 && offsetof(Worker, loops) == 16); static_assert(std::atomic<std::uint64_t>::is_always_lock_free && std::atomic<DWORD>::is_always_lock_free); static std::atomic<bool> entered{false}; static std::atomic<bool> released{false}; static std::atomic<bool> left{false}; static std::atomic<DWORD> handlerId{0}; static std::atomic<std::uint64_t> interruptedRip{0}; static std::atomic<std::uint64_t> interruptedRsp{0}; static std::atomic<int> deliveredSignal{0}; static void APS5_VABI Handler(int signal, void* context) { std::uint64_t rip = 0; std::uint64_t rsp = 0; std::memcpy(&rip, static_cast<unsigned char*>(context) + 0xe0, sizeof(rip)); std::memcpy(&rsp, static_cast<unsigned char*>(context) + 0xf8, sizeof(rsp)); interruptedRip.store(rip, std::memory_order_relaxed); interruptedRsp.store(rsp, std::memory_order_relaxed); handlerId.store(GetCurrentThreadId(), std::memory_order_relaxed); deliveredSignal.store(signal, std::memory_order_relaxed); entered.store(true, std::memory_order_release); while (!released.load(std::memory_order_acquire)) {} left.store(true, std::memory_order_release); } extern "C" void APS5_VABI ResearchReady_nid_no_patch(Worker* worker) { ULONG_PTR low = 0; ULONG_PTR high = 0; GetCurrentThreadStackLimits(&low, &high); worker->low.store(low); worker->high.store(high); worker->id.store(GetCurrentThreadId(), std::memory_order_release); } extern "C" void APS5_VABI ResearchWait_nid_no_patch(Worker* worker) { worker->waiting.store(true, std::memory_order_release); WaitForSingleObject(worker->gate, INFINITE); } extern "C" void* APS5_VABI ResearchGuestBegin_nid_no_patch(void*); extern "C" void ResearchGuestEnd_nid_no_patch(); asm(".text\n" ".globl ResearchGuestBegin_nid_no_patch\n" "ResearchGuestBegin_nid_no_patch:\n" "pushq %rbx\n" "movq %rdi, %rbx\n" "call ResearchReady_nid_no_patch\n" "1:\n" "cmpl $0, (%rbx)\n" "jne 2f\n" "cmpl $2, 48(%rbx)\n" "jne 4f\n" "movq %rbx, %rdi\n" "call ResearchWait_nid_no_patch\n" "jmp 3f\n" "4:\n" "cmpl $0, 48(%rbx)\n" "jne 3f\n" "leaq 4(%rbx), %rdi\n" "movl $1, %esi\n" "call *8(%rbx)\n" "3:\n" "lock incq 16(%rbx)\n" "jmp 1b\n" "2:\n" "xorl %eax, %eax\n" "popq %rbx\n" "ret\n" ".globl ResearchGuestEnd_nid_no_patch\n" "ResearchGuestEnd_nid_no_patch:\n"); static_assert(offsetof(Worker, guestOnly) == 48); template<class T> static T Symbol(HMODULE module, const char* name, bool patched) { const auto symbol = patched ? Nid::ComputeNid(name, "libkernel") : std::string(name); const auto address = GetProcAddress(module, symbol.c_str()); if (!address) throw std::runtime_error("Missing export: " + symbol); return reinterpret_cast<T>(address); } static bool Observe(const std::atomic<bool>& flag, std::chrono::milliseconds duration) { const auto end = Clock::now() + duration; while (!flag.load(std::memory_order_acquire)) { if (Clock::now() >= end) return false; std::this_thread::yield(); } return true; } static double Milliseconds(Clock::time_point begin, Clock::time_point end) { return std::chrono::duration<double, std::milli>(end - begin).count(); } static std::string Location(std::uintptr_t pc, std::uintptr_t* offset) { MEMORY_BASIC_INFORMATION info{}; if (!VirtualQuery(reinterpret_cast<void*>(pc), &info, sizeof(info))) return "unknown"; char name[MAX_PATH]{}; const DWORD size = GetModuleFileNameA(static_cast<HMODULE>(info.AllocationBase), name, MAX_PATH); *offset = pc - reinterpret_cast<std::uintptr_t>(info.AllocationBase); if (!size) return "anonymous"; const std::string path(name, size); return path.substr(path.find_last_of("/\\") + 1); } static void Probe(HANDLE thread, const Worker& worker, int round) { using namespace WindowsHostBoundary; CONTEXT context{}; context.ContextFlags = CONTEXT_FULL | CONTEXT_FLOATING_POINT; if (SuspendThread(thread) == DWORD(-1)) throw std::runtime_error("Probe suspend failed"); const bool captured = GetThreadContext(thread, &context); Analysis result; const char* outcome = "capture_failed"; if (captured) { const std::array<GuestRange, 1> ranges{{{reinterpret_cast<DWORD64>(&ResearchGuestBegin_nid_no_patch), reinterpret_cast<DWORD64>(&ResearchGuestEnd_nid_no_patch)}}}; result = Analyze_nid_no_patch(context, worker.low.load(), worker.high.load(), ranges); outcome = StatusName_nid_no_patch(result.status); } const DWORD resume = ResumeThread(thread); std::printf("{\"event\":\"probe\",\"round\":%d,\"outcome\":\"%s\",\"stack_written\":false,\"resumed\":%s,\"frames\":[", round, outcome, resume == DWORD(-1) ? "false" : "true"); for (std::size_t index = 0; index < result.count; ++index) { std::uintptr_t offset = 0; const auto module = Location(result.frames[index].rip, &offset); std::printf("%s{\"rip\":\"0x%llx\",\"rsp\":\"0x%llx\",\"module\":\"%s\",\"offset\":\"0x%llx\",\"metadata\":%s}", index ? "," : "", static_cast<unsigned long long>(result.frames[index].rip), static_cast<unsigned long long>(result.frames[index].rsp), module.c_str(), static_cast<unsigned long long>(offset), result.frames[index].metadata ? "true" : "false"); } std::puts("]}"); std::fflush(stdout); } int main(int argc, char** argv) { SetErrorMode(0x8003); if (argc != 5) return 2; const std::string path(argv[1]); const std::string mode(argv[3]); const bool patched = std::string(argv[4]) == "nid"; const auto slash = path.find_last_of("/\\"); SetDllDirectoryA(path.substr(0, slash).c_str()); const auto module = LoadLibraryA(path.c_str()); if (!module) { std::printf("{\"event\":\"load_failed\",\"error\":%lu}\n", GetLastError()); return 3; } try { const auto create = Symbol<Create>(module, "scePthreadCreate", patched); const auto join = Symbol<Join>(module, "scePthreadJoin", patched); const auto install = Symbol<Install>(module, "sceKernelInstallExceptionHandler", patched); const auto remove = Symbol<Remove>(module, "sceKernelRemoveExceptionHandler", patched); const auto raise = Symbol<Raise>(module, "sceKernelRaiseException", patched); const auto wake = Symbol<Wake>(module, "sceKernelSyncOnAddressWake", patched); DWORD shadowPolicy = 0; const bool shadowRead = GetProcessMitigationPolicy(GetCurrentProcess(), ProcessUserShadowStackPolicy, &shadowPolicy, sizeof(shadowPolicy)); std::printf("{\"event\":\"environment\",\"shadow_policy_read\":%s,\"shadow_policy_flags\":%lu,\"guest_low\":\"0x%llx\",\"guest_high\":\"0x%llx\",\"handler_clock\":\"controller_observation_upper_bound\"}\n", shadowRead ? "true" : "false", shadowPolicy, static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(&ResearchGuestBegin_nid_no_patch)), static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(&ResearchGuestEnd_nid_no_patch))); if (install(30, reinterpret_cast<void*>(&Handler)) != 0) throw std::runtime_error("Install failed"); const int first = std::stoi(argv[2]); for (int round = first; round < first + 10; ++round) { entered.store(false); released.store(mode == "empty"); left.store(false); handlerId.store(0); interruptedRip.store(0); interruptedRsp.store(0); deliveredSignal.store(0); Worker worker; worker.wake = wake; worker.guestOnly = mode == "guest"; if (mode == "long_wait") { worker.guestOnly = 2; worker.gate = CreateEventW(nullptr, TRUE, FALSE, nullptr); if (!worker.gate) throw std::runtime_error("CreateEvent failed"); } Pthread target = nullptr; if (create(&target, nullptr, ResearchGuestBegin_nid_no_patch, &worker, "boundary measurement") != 0) throw std::runtime_error("Create failed"); const auto readyDeadline = Clock::now() + std::chrono::seconds(2); while (!worker.id.load(std::memory_order_acquire) || (mode == "long_wait" ? !worker.waiting.load(std::memory_order_acquire) : worker.loops.load() < 100)) { if (Clock::now() > readyDeadline) throw std::runtime_error("Worker readiness timeout"); std::this_thread::yield(); } HANDLE native = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION | SYNCHRONIZE, FALSE, worker.id.load()); if (!native) throw std::runtime_error("OpenThread failed"); if (mode == "probe") { Probe(native, worker, round); worker.stop.store(1); const int joined = join(target, nullptr); CloseHandle(native); std::printf("{\"event\":\"probe_cleanup\",\"round\":%d,\"join_result\":%d}\n", round, joined); std::fflush(stdout); continue; } if (mode == "finished") { worker.stop.store(1); const bool exited = WaitForSingleObject(native, 1000) == WAIT_OBJECT_0; const int raised = raise(target, 30); const int joined = join(target, nullptr); CloseHandle(native); std::printf("{\"event\":\"exit_control\",\"round\":%d,\"exited\":%s,\"raise_result\":%d,\"handler_called\":%s,\"join_result\":%d}\n", round, exited ? "true" : "false", raised, entered.load() ? "true" : "false", joined); std::fflush(stdout); continue; } std::thread waitRelease; if (mode == "long_wait") { waitRelease = std::thread([&] { std::this_thread::sleep_for(std::chrono::milliseconds(150)); SetEvent(worker.gate); }); } const auto sent = Clock::now(); const int raised = raise(target, 30); const auto raiseReturned = Clock::now(); const bool delivered = Observe(entered, std::chrono::milliseconds(1000)); const auto handlerObserved = Clock::now(); std::atomic<bool> wakeStarted{false}; std::atomic<bool> wakeDone{false}; int wakeResult = -1; std::uint32_t independent = 0; Clock::time_point wakeBegin; Clock::time_point wakeEnd; std::thread independentThread([&] { wakeBegin = Clock::now(); wakeStarted.store(true, std::memory_order_release); wakeResult = wake(&independent, 1); wakeEnd = Clock::now(); wakeDone.store(true, std::memory_order_release); }); Observe(wakeStarted, std::chrono::milliseconds(1000)); const bool progressedWhileHeld = Observe(wakeDone, std::chrono::milliseconds(150)); const auto beforeRelease = Clock::now(); std::uintptr_t offset = 0; const auto interruptedModule = Location(interruptedRip.load(), &offset); const char* outcome = !delivered ? "missing_delivery" : !progressedWhileHeld ? "wake_blocked_while_handler_held" : Milliseconds(sent, handlerObserved) > 100 ? "delayed_delivery" : "delivered_wake_progressed"; std::printf("{\"event\":\"observation\",\"round\":%d,\"outcome\":\"%s\",\"raise_result\":%d,\"raise_ms\":%.6f,\"delivery_observed_ms\":%.6f,\"wake_progressed_while_held\":%s,\"hold_observed_ms\":%.6f,\"worker_id\":%lu,\"handler_id\":%lu,\"signal\":%d,\"interrupted_rip\":\"0x%llx\",\"interrupted_rsp\":\"0x%llx\",\"interrupted_module\":\"%s\",\"module_offset\":\"0x%llx\"}\n", round, outcome, raised, Milliseconds(sent, raiseReturned), Milliseconds(sent, handlerObserved), progressedWhileHeld ? "true" : "false", Milliseconds(handlerObserved, beforeRelease), worker.id.load(), handlerId.load(), deliveredSignal.load(), static_cast<unsigned long long>(interruptedRip.load()), static_cast<unsigned long long>(interruptedRsp.load()), interruptedModule.c_str(), static_cast<unsigned long long>(offset)); std::fflush(stdout); released.store(true, std::memory_order_release); const bool handlerRecovered = Observe(left, std::chrono::milliseconds(1000)); worker.stop.store(1); independentThread.join(); const int joined = join(target, nullptr); if (waitRelease.joinable()) waitRelease.join(); if (worker.gate) CloseHandle(worker.gate); CloseHandle(native); std::printf("{\"event\":\"completion\",\"round\":%d,\"handler_recovered\":%s,\"wake_result\":%d,\"wake_ms\":%.6f,\"join_result\":%d,\"same_thread\":%s,\"loops\":%llu}\n", round, handlerRecovered ? "true" : "false", wakeResult, Milliseconds(wakeBegin, wakeEnd), joined, handlerId.load() == worker.id.load() ? "true" : "false", static_cast<unsigned long long>(worker.loops.load())); std::fflush(stdout); } if (remove(30) != 0) throw std::runtime_error("Remove failed"); } catch (const std::exception& error) { std::printf("{\"event\":\"error\",\"message\":\"%s\"}\n", error.what()); std::fflush(stdout); return 4; } return 0; } ``` ### `WindowsHostBoundaryProbe.hpp` ```cpp #ifndef CORE_LIBS_PRX_LIBKERNEL_WINDOWS_HOST_BOUNDARY_PROBE_HPP #define CORE_LIBS_PRX_LIBKERNEL_WINDOWS_HOST_BOUNDARY_PROBE_HPP #include <windows.h> #include <array> #include <cstddef> #include <span> namespace WindowsHostBoundary { struct GuestRange { DWORD64 low; DWORD64 high; }; enum class Status { RegisteredGuest, NormalReturnCandidate, InvalidGuestRange, UnsupportedContext, StackBounds, UnreadableStack, MissingUnwindMetadata, UnsupportedUnwindHandler, InvalidMetadata, InvalidUnwindProgress, InvalidReturnSlot, FrameLimit }; struct Frame { DWORD64 rip = 0; DWORD64 rsp = 0; bool metadata = false; }; struct Analysis { Status status = Status::UnsupportedContext; std::array<Frame, 32> frames{}; std::size_t count = 0; DWORD64 returnSlot = 0; DWORD64 guestReturn = 0; }; Analysis Analyze_nid_no_patch(const CONTEXT& context, DWORD64 stackLow, DWORD64 stackHigh, std::span<const GuestRange> guestRanges); const char* StatusName_nid_no_patch(Status status); } #endif ``` ### `WindowsHostBoundaryProbe.cpp` ```cpp #include "WindowsHostBoundaryProbe.hpp" #include <cstdint> #include <limits> namespace WindowsHostBoundary { namespace { bool Readable(DWORD64 low, DWORD64 high) { if (low >= high) return false; while (low < high) { MEMORY_BASIC_INFORMATION info{}; if (VirtualQuery(reinterpret_cast<void*>(low), &info, sizeof(info)) != sizeof(info)) return false; if (info.State != MEM_COMMIT || (info.Protect & (PAGE_GUARD | PAGE_NOACCESS))) return false; if (!(info.Protect & (PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY))) return false; const auto base = reinterpret_cast<DWORD64>(info.BaseAddress); if (info.RegionSize > std::numeric_limits<DWORD64>::max() - base) return false; const auto end = base + info.RegionSize; if (end <= low) return false; low = end; } return true; } bool Executable(DWORD64 low, DWORD64 high) { if (low >= high) return false; while (low < high) { MEMORY_BASIC_INFORMATION info{}; if (VirtualQuery(reinterpret_cast<void*>(low), &info, sizeof(info)) != sizeof(info)) return false; if (info.State != MEM_COMMIT || (info.Protect & (PAGE_GUARD | PAGE_NOACCESS))) return false; if (!(info.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY))) return false; const auto base = reinterpret_cast<DWORD64>(info.BaseAddress); if (info.RegionSize > std::numeric_limits<DWORD64>::max() - base) return false; const auto end = base + info.RegionSize; if (end <= low) return false; low = end; } return true; } bool Guest(DWORD64 pc, std::span<const GuestRange> ranges) { for (const auto& range : ranges) if (pc >= range.low && pc < range.high) return true; return false; } bool Read(DWORD64 address, void* output, SIZE_T size) { SIZE_T copied = 0; return ReadProcessMemory(GetCurrentProcess(), reinterpret_cast<void*>(address), output, size, &copied) && copied == size; } } Analysis Analyze_nid_no_patch(const CONTEXT& input, DWORD64 stackLow, DWORD64 stackHigh, std::span<const GuestRange> guestRanges) { Analysis result; if (guestRanges.empty()) { result.status = Status::InvalidGuestRange; return result; } for (const auto& range : guestRanges) { if (!Executable(range.low, range.high)) { result.status = Status::InvalidGuestRange; return result; } } if ((input.ContextFlags & CONTEXT_CONTROL) != CONTEXT_CONTROL || (input.ContextFlags & CONTEXT_INTEGER) != CONTEXT_INTEGER) return result; if (stackLow >= stackHigh || stackHigh - stackLow < 8 || input.Rsp < stackLow || input.Rsp > stackHigh - 8) { result.status = Status::StackBounds; return result; } if (!Readable(input.Rsp, stackHigh)) { result.status = Status::UnreadableStack; return result; } CONTEXT context = input; result.status = Status::FrameLimit; DWORD64 slot = 0; for (std::size_t index = 0; index < result.frames.size(); ++index) { result.frames[index] = {context.Rip, context.Rsp, false}; ++result.count; if (Guest(context.Rip, guestRanges)) { result.status = index == 0 ? Status::RegisteredGuest : Status::NormalReturnCandidate; result.returnSlot = slot; result.guestReturn = context.Rip; return result; } DWORD64 base = 0; const auto entry = RtlLookupFunctionEntry(context.Rip, &base, nullptr); if (!entry) { result.status = Status::MissingUnwindMetadata; return result; } result.frames[index].metadata = true; RUNTIME_FUNCTION function{}; if (!Read(reinterpret_cast<DWORD64>(entry), &function, sizeof(function)) || function.BeginAddress >= function.EndAddress || base > std::numeric_limits<DWORD64>::max() - function.EndAddress || context.Rip < base + function.BeginAddress || context.Rip >= base + function.EndAddress || base > std::numeric_limits<DWORD64>::max() - function.UnwindData) { result.status = Status::InvalidMetadata; return result; } std::uint8_t header = 0; if (!Read(base + function.UnwindData, &header, sizeof(header)) || (header & 7) != 1 || (header >> 3) != 0) { result.status = Status::UnsupportedUnwindHandler; return result; } const auto oldRsp = context.Rsp; void* data = nullptr; DWORD64 establisher = 0; RtlVirtualUnwind(UNW_FLAG_NHANDLER, base, context.Rip, entry, &context, &data, &establisher, nullptr); if (context.Rsp <= oldRsp || context.Rsp > stackHigh || establisher < stackLow || establisher >= stackHigh) { result.status = Status::InvalidUnwindProgress; return result; } slot = context.Rsp - 8; DWORD64 stored = 0; if (slot < oldRsp || !Read(slot, &stored, sizeof(stored)) || stored != context.Rip || !Executable(context.Rip, context.Rip + 1)) { result.status = Status::InvalidReturnSlot; return result; } } return result; } const char* StatusName_nid_no_patch(Status status) { switch (status) { case Status::RegisteredGuest: return "registered_guest"; case Status::NormalReturnCandidate: return "normal_return_candidate"; case Status::InvalidGuestRange: return "invalid_guest_range"; case Status::UnsupportedContext: return "unsupported_context"; case Status::StackBounds: return "stack_bounds"; case Status::UnreadableStack: return "unreadable_stack"; case Status::MissingUnwindMetadata: return "missing_unwind_metadata"; case Status::UnsupportedUnwindHandler: return "unsupported_unwind_handler"; case Status::InvalidMetadata: return "invalid_metadata"; case Status::InvalidUnwindProgress: return "invalid_unwind_progress"; case Status::InvalidReturnSlot: return "invalid_return_slot"; case Status::FrameLimit: return "frame_limit"; } return "unknown_status"; } } ``` ### `AbiFixture.cpp` ```cpp #include "prx/libc/include/general/VabiMacros.hpp" #include <cstdint> #include <stdexcept> #ifdef RESEARCH_SYSV #define RESEARCH_ABI APS5_VABI #else #define RESEARCH_ABI #endif using Observer = void (*)(std::uint64_t); extern "C" __attribute__((noinline)) std::uint64_t RESEARCH_ABI ResearchInteger_nid_no_patch(std::uint64_t value, Observer observer) { volatile std::uint64_t storage[17]{}; storage[0] = value; storage[16] = value ^ 0x123456789abcdef0ULL; observer(storage[16]); return storage[0] + storage[16]; } extern "C" __attribute__((noinline)) double RESEARCH_ABI ResearchFloating_nid_no_patch(double value, Observer observer) { volatile double storage[17]{}; storage[0] = value; storage[16] = value * 1.5; observer(static_cast<std::uint64_t>(storage[16])); return storage[0] + storage[16]; } #ifndef RESEARCH_NO_THROW extern "C" __attribute__((noinline)) void RESEARCH_ABI ResearchThrow_nid_no_patch(int* destroyed) { struct Guard { int* destroyed; ~Guard() { ++*destroyed; } } guard{destroyed}; throw std::runtime_error("metadata fixture exception"); } #endif ``` ### `InspectFixture.cpp` ```cpp #include "prx/libc/include/general/VabiMacros.hpp" #include <windows.h> #include <cstdint> #include <cstdio> #include <cstring> #include <stdexcept> #ifdef RESEARCH_SYSV #define RESEARCH_ABI APS5_VABI #else #define RESEARCH_ABI #endif using Observer = void (*)(std::uint64_t); extern "C" std::uint64_t RESEARCH_ABI ResearchInteger_nid_no_patch(std::uint64_t, Observer); extern "C" double RESEARCH_ABI ResearchFloating_nid_no_patch(double, Observer); #ifndef RESEARCH_NO_THROW extern "C" void RESEARCH_ABI ResearchThrow_nid_no_patch(int*); #endif #ifdef RESEARCH_SCOPED_OBSERVER extern "C" std::uint64_t ResearchNativeHelper_nid_no_patch(std::uint64_t, Observer); __attribute__((noinline, optimize("asynchronous-unwind-tables"))) #endif static void Observe(std::uint64_t value) { CONTEXT context{}; RtlCaptureContext(&context); for (unsigned depth = 0; depth < 4; ++depth) { DWORD64 base = 0; const auto entry = RtlLookupFunctionEntry(context.Rip, &base, nullptr); std::printf("{\"event\":\"active_frame\",\"depth\":%u,\"metadata\":%s,\"rip\":\"0x%llx\",\"value\":%llu}\n", depth, entry ? "true" : "false", static_cast<unsigned long long>(context.Rip), static_cast<unsigned long long>(value)); if (!entry) break; void* data = nullptr; DWORD64 establisher = 0; RtlVirtualUnwind(UNW_FLAG_NHANDLER, base, context.Rip, entry, &context, &data, &establisher, nullptr); } } int main() { SetErrorMode(0x8003); DWORD64 base = 0; const DWORD64 addresses[]{reinterpret_cast<DWORD64>(&ResearchInteger_nid_no_patch), reinterpret_cast<DWORD64>(&ResearchFloating_nid_no_patch) #ifdef RESEARCH_SCOPED_OBSERVER , reinterpret_cast<DWORD64>(&ResearchNativeHelper_nid_no_patch) #endif #ifndef RESEARCH_NO_THROW , reinterpret_cast<DWORD64>(&ResearchThrow_nid_no_patch) #endif }; for (const auto address : addresses) { const auto entry = RtlLookupFunctionEntry(address, &base, nullptr); std::printf("{\"event\":\"lookup\",\"address\":\"0x%llx\",\"metadata\":%s}\n", static_cast<unsigned long long>(address), entry ? "true" : "false"); } const auto integer = ResearchInteger_nid_no_patch(19, Observe); const auto floating = ResearchFloating_nid_no_patch(2.25, Observe); #ifndef RESEARCH_NO_THROW int destroyed = 0; bool caught = false; try { ResearchThrow_nid_no_patch(&destroyed); } catch (const std::runtime_error& error) { caught = std::strcmp(error.what(), "metadata fixture exception") == 0; } const bool correct = integer == 19 + (19 ^ 0x123456789abcdef0ULL) && floating == 5.625 && caught && destroyed == 1; std::printf("{\"event\":\"returns_and_exception\",\"correct\":%s,\"destroyed\":%d,\"caught\":%s}\n", correct ? "true" : "false", destroyed, caught ? "true" : "false"); #else const bool correct = integer == 19 + (19 ^ 0x123456789abcdef0ULL) && floating == 5.625; std::printf("{\"event\":\"returns_only\",\"correct\":%s}\n", correct ? "true" : "false"); #endif return correct ? 0 : 1; } ``` ### `ScopedFixture.cpp` ```cpp #include "prx/libc/include/general/VabiMacros.hpp" #include <cstdint> #include <stdexcept> using Observer = void (*)(std::uint64_t); extern "C" __attribute__((noinline, optimize("asynchronous-unwind-tables"))) std::uint64_t ResearchNativeHelper_nid_no_patch(std::uint64_t value, Observer observer) { volatile std::uint64_t storage[17]{}; storage[0] = value; storage[16] = value ^ 0x123456789abcdef0ULL; observer(storage[16]); return storage[0] + storage[16]; } extern "C" __attribute__((noinline)) std::uint64_t APS5_VABI ResearchInteger_nid_no_patch(std::uint64_t value, Observer observer) { return ResearchNativeHelper_nid_no_patch(value, observer); } extern "C" __attribute__((noinline)) double APS5_VABI ResearchFloating_nid_no_patch(double value, Observer observer) { volatile double storage[17]{}; storage[0] = value; storage[16] = value * 1.5; observer(static_cast<std::uint64_t>(storage[16])); return storage[0] + storage[16]; } extern "C" __attribute__((noinline)) void APS5_VABI ResearchThrow_nid_no_patch(int* destroyed) { struct Guard { int* destroyed; ~Guard() { ++*destroyed; } } guard{destroyed}; throw std::runtime_error("metadata fixture exception"); } ``` </details>
oneandonlydean commented 2026-10-10 06:25:40 +00:00 (Migrated from github.com)
Author
Contributor

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-10T06:25:40Z.


#1562 changed the Windows mutex, rwlock and timed waits so delivery can run while a thread waits. Could you rerun the 300 rounds on current main?

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6094634294 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/issues/1488#issuecomment-6094634294). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-10T06:25:40Z. --- #1562 changed the Windows mutex, rwlock and timed waits so delivery can run while a thread waits. Could you rerun the 300 rounds on current main?
LeandroLP23 commented 2026-10-10 07:18:14 +00:00 (Migrated from github.com)
Author
Contributor

Imported from boykopovar/AnyPS5. Originally posted by LeandroLP23 on 2026-10-10T07:18:14Z.


Reran it on current main 04d06f0d (with #1562), same reproducer, Windows 11, WinLibs GCC 15.2.0 r7, Release: 300 rounds, 35 blocked (148 on 3e32797c). In all 35 the worker was stopped inside sceKernelSyncOnAddressWake itself (libkernel.prx +0x198c0 ×18, +0x197a8 ×11, three other offsets ×6), which takes g_waitersLock at SyncOnAddress.cpp:115; none in libwinpthread any more (282 of the stops before). So the waits are covered now, and what's left is a raise that lands while the worker is inside Wake.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6095044608 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/issues/1488#issuecomment-6095044608). Originally posted by [LeandroLP23](https://github.com/LeandroLP23) on 2026-10-10T07:18:14Z. --- Reran it on current `main` 04d06f0d (with #1562), same reproducer, Windows 11, WinLibs GCC 15.2.0 r7, Release: 300 rounds, **35 blocked** (148 on 3e32797c). In all 35 the worker was stopped inside `sceKernelSyncOnAddressWake` itself (`libkernel.prx` +0x198c0 ×18, +0x197a8 ×11, three other offsets ×6), which takes `g_waitersLock` at `SyncOnAddress.cpp:115`; none in `libwinpthread` any more (282 of the stops before). So the waits are covered now, and what's left is a raise that lands while the worker is inside `Wake`.
Sign in to join this conversation.
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5#1488
No description provided.