fix(agc): free per-thread driver state at thread exit without emutls #590

Merged
CnRJay merged 1 commit from upstream-pr/590 into main 2026-10-05 01:25:47 +00:00
CnRJay commented 2026-10-05 00:09:20 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by CnRJay on 2026-10-05T00:09:20Z.


What

agc_driver_flip fails intermittently on the Windows CI job, for example on #574 (run 37242466887): a stack overflow inside libstdc++ on the second --repeat. The cause is a use-after-free at thread exit, in every driver thread_local with a non-trivial destructor.

Root cause. With MinGW GCC, thread_local is emutls, and thread exit happens in two steps in the wrong order:

  1. When the thread function returns, winpthread runs its key destructors, including libgcc's emutls one, which frees the thread's TLS blocks.
  2. Later, at DLL_THREAD_DETACH, the CRT's tls_callback → run_dtor_list runs the C++ thread_local destructors on those already freed blocks.

So ~DeferredLabels() and the others read their vector or map pointers from freed memory and free them. Depending on what reused the memory, that is silent, heap corruption (0xc0000374), an access violation in free, or the stack overflow seen in CI.

How it was pinned down:

  • Reproduction: running 12 copies of the test in parallel locally gives an occasional 0xc0000374.
  • Deterministic under a debugger: under gdb, Windows enables the debug heap, and the flip test then fails on every run. The thread is the queue worker exiting after the injected flip failure, in testFailure.
  • Culprit: the destructor run just before the failing free was AgcDriver::DriverDetail::DeferredLabels::~DeferredLabels().
  • Freed storage: at its entry, this is filled with 0xfeeefeee, the debug heap's freed-memory pattern.

Fix. ShaderRecompiler::ThreadOwned (core/shader/recompiler/ThreadOwned.hpp):

  • It keeps the state behind a trivially destructible thread_local T*, which registers nothing with the CRT's thread-exit list.
  • It deletes the object from its own pthread key destructor, which receives the objects directly rather than reading emutls, so the order against libgcc's key no longer matters.
  • The hot path stays one TLS pointer read.

It lives in the recompiler tree because the recompiler's own disk cache needs it and the recompiler doesn't depend on libs/prx. The driver already uses recompiler headers, and ThreadOwned is added to shaderCacheReviewedNames, since it cannot change a recompile.

Converted sites:

  • Execution: the deferred label queue and its recording vector, PacketProfile, the CPU-fill block, the six capture-validation scratch vectors, and ThreadMemoryCounters. Its destructor also unregisters from the global profile, and that now happens before the storage goes away.
  • Graphics: ThreadBuildProfile, which merges into the global profile on destruction, the lookup log, the revalidation scratch vectors, and the image-mirror change mask.
  • Recompiler: the shader disk cache's read buffer and key vector.

objdump of libSceAgcDriver.prx shows no calls to __cxa_thread_atexit left; there were 25 before.

Follow-ups, not in this PR: the same hazard exists outside the driver.

  • libkernel.prx: scePthreadGetspecific/scePthreadSetspecific and sceKernelUuidCreate.
  • libSceRandom.prx: sceRandomGetRandomNumber.

Tested

Windows 11, MinGW GCC 15.2.0 r7, NVIDIA Vulkan.

  • agc_driver_flip under gdb (debug heap): 5/5 pass. Without the fix, every run stops with Critical error detected c0000374.
  • agc_driver_flip, 12 parallel ctest --repeat until-fail:100: 1200/1200 pass. Without the fix, the same load reproduced the crash.
  • Full ctest: 220/221 pass. agc_shader_memory fails without this change too; #574 fixes it.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • AI-assisted: yes

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4738636801 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/590). Originally posted by [CnRJay](https://github.com/CnRJay) on 2026-10-05T00:09:20Z. --- ### What `agc_driver_flip` fails intermittently on the Windows CI job, for example on #574 (run 37242466887): a stack overflow inside libstdc++ on the second `--repeat`. The cause is a use-after-free at thread exit, in every driver `thread_local` with a non-trivial destructor. **Root cause.** With MinGW GCC, `thread_local` is emutls, and thread exit happens in two steps in the wrong order: 1. When the thread function returns, winpthread runs its key destructors, including libgcc's emutls one, which frees the thread's TLS blocks. 2. Later, at `DLL_THREAD_DETACH`, the CRT's `tls_callback` → `run_dtor_list` runs the C++ `thread_local` destructors on those already freed blocks. So `~DeferredLabels()` and the others read their vector or map pointers from freed memory and free them. Depending on what reused the memory, that is silent, heap corruption (`0xc0000374`), an access violation in `free`, or the stack overflow seen in CI. How it was pinned down: - **Reproduction:** running 12 copies of the test in parallel locally gives an occasional `0xc0000374`. - **Deterministic under a debugger:** under gdb, Windows enables the debug heap, and the flip test then fails on every run. The thread is the queue worker exiting after the injected flip failure, in `testFailure`. - **Culprit:** the destructor run just before the failing `free` was `AgcDriver::DriverDetail::DeferredLabels::~DeferredLabels()`. - **Freed storage:** at its entry, `this` is filled with `0xfeeefeee`, the debug heap's freed-memory pattern. **Fix.** `ShaderRecompiler::ThreadOwned` (core/shader/recompiler/ThreadOwned.hpp): - It keeps the state behind a trivially destructible `thread_local T*`, which registers nothing with the CRT's thread-exit list. - It deletes the object from its own pthread key destructor, which receives the objects directly rather than reading emutls, so the order against libgcc's key no longer matters. - The hot path stays one TLS pointer read. It lives in the recompiler tree because the recompiler's own disk cache needs it and the recompiler doesn't depend on `libs/prx`. The driver already uses recompiler headers, and `ThreadOwned` is added to `shaderCacheReviewedNames`, since it cannot change a recompile. Converted sites: - **Execution:** the deferred label queue and its recording vector, `PacketProfile`, the CPU-fill block, the six capture-validation scratch vectors, and `ThreadMemoryCounters`. Its destructor also unregisters from the global profile, and that now happens before the storage goes away. - **Graphics:** `ThreadBuildProfile`, which merges into the global profile on destruction, the lookup log, the revalidation scratch vectors, and the image-mirror change mask. - **Recompiler:** the shader disk cache's read buffer and key vector. `objdump` of `libSceAgcDriver.prx` shows no calls to `__cxa_thread_atexit` left; there were 25 before. **Follow-ups, not in this PR:** the same hazard exists outside the driver. - `libkernel.prx`: `scePthreadGetspecific`/`scePthreadSetspecific` and `sceKernelUuidCreate`. - `libSceRandom.prx`: `sceRandomGetRandomNumber`. ### Tested Windows 11, MinGW GCC 15.2.0 r7, NVIDIA Vulkan. - `agc_driver_flip` under gdb (debug heap): 5/5 pass. Without the fix, every run stops with `Critical error detected c0000374`. - `agc_driver_flip`, 12 parallel `ctest --repeat until-fail:100`: 1200/1200 pass. Without the fix, the same load reproduced the crash. - Full `ctest`: 220/221 pass. `agc_shader_memory` fails without this change too; #574 fixes it. ### Checklist - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed in [TechnicalDebt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/TechnicalDebt.md#silent-stubs) - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] AI-assisted: yes 🤖 Generated with [Claude Code](https://claude.com/claude-code)
oneandonlydean commented 2026-10-05 01:18:36 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-05T01:18:36Z.


Thanks, that's a very clear diagnosis. Keeping the state behind a trivially destructible pointer and deleting it from a pthread key destructor fixes the emutls order, and the remaining thread_locals in the driver are all trivially destructible.

Two small notes, neither blocking:

  1. After the key destructor deletes an object, its thread_local slot still points at it. If anything on that thread reaches CounterFor() or deferredLabels() later in thread exit (another key's destructor, for example), it gets freed memory on Linux, where TLS is native. Clearing the slot in the destroy callback (keeping a T** in Owned) would make a late call allocate a fresh object instead, which the key destructor loop then frees again.
  2. Key destructors don't run for the main thread at exit(), where C++ thread_local destructors did. So the main thread's ThreadBuildProfile merge and report, and its ThreadMemoryCounters retirement, no longer happen at process exit. That only affects diagnostics.

There's no new test; the Windows agc_driver_flip run in CI passed, and on Linux the full ctest passes here. PPSA21564 runs on Linux, so this doesn't change anything I can observe. Ready to merge from my side.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:5986483225 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/590#issuecomment-5986483225). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-05T01:18:36Z. --- Thanks, that's a very clear diagnosis. Keeping the state behind a trivially destructible pointer and deleting it from a pthread key destructor fixes the emutls order, and the remaining `thread_local`s in the driver are all trivially destructible. Two small notes, neither blocking: 1. After the key destructor deletes an object, its `thread_local` slot still points at it. If anything on that thread reaches `CounterFor()` or `deferredLabels()` later in thread exit (another key's destructor, for example), it gets freed memory on Linux, where TLS is native. Clearing the slot in the destroy callback (keeping a `T**` in `Owned`) would make a late call allocate a fresh object instead, which the key destructor loop then frees again. 2. Key destructors don't run for the main thread at `exit()`, where C++ `thread_local` destructors did. So the main thread's `ThreadBuildProfile` merge and report, and its `ThreadMemoryCounters` retirement, no longer happen at process exit. That only affects diagnostics. There's no new test; the Windows `agc_driver_flip` run in CI passed, and on Linux the full ctest passes here. PPSA21564 runs on Linux, so this doesn't change anything I can observe. Ready to merge from my side.
Sign in to join this conversation.
No reviewers
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!590
No description provided.