Skip to content

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

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
CnRJay:fix/agc-thread-local-teardown
Oct 5, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
CnRJay:fix/agc-thread-local-teardown

Conversation

@CnRJay

@CnRJay CnRJay commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

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; fix(shader): splat the bindless table hit into a bool vector for SPIR-V 1.3 #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

On MinGW, thread_local storage is emutls: libgcc frees a thread's blocks
from a winpthread key destructor when the thread function returns, and
the CRT runs the thread_local destructors later, from the module's TLS
callback at thread detach. The destructors of the driver's non-trivial
thread_locals (the deferred label queue, packet profile, capture and
revalidation scratch vectors, build profile, memory counters, disk cache
buffers) therefore ran on freed storage. Under the debug heap the flip
test failed on every run at the queue worker's exit after the injected
flip failure; without it the use-after-free showed up as intermittent
heap corruption or a stack overflow on the Windows CI job.

ShaderRecompiler::ThreadOwned keeps such state behind a trivially
destructible thread_local pointer and deletes it from its own pthread key
destructor, which receives the objects directly instead of reading
emutls. The driver no longer registers any thread_local destructor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added build shader core/shader agc libSceAgc* labels Oct 5, 2026
@oneandonlydean

Copy link
Copy Markdown
Collaborator

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.

@oneandonlydean
oneandonlydean merged commit 60b6cfc into boykopovar:main Oct 5, 2026
3 checks passed
oneandonlydean added a commit to oneandonlydean/AnyPS5 that referenced this pull request Oct 5, 2026
Conflicts resolved:
- libSceAudioPropagation/Export.cpp: upstream's boykopovar#482 + boykopovar#489 version taken; it is
  the same no-propagation model as astrobot's stand-in, with SourceRender and the
  handle-only UnregisterMaterial already in it.
- State.cpp (boykopovar#453): astrobot's resident depth model kept; it already skips the
  tests of an absent plane (boykopovar#453's test is on astrobot since e087a4f).
- Graphics.cpp, State.hpp, ShaderResources.cpp: astrobot's DepthTarget model kept
  (exportIndex, no DepthSurface.hpp), upstream's ThreadOwned include added.
- BdaResources.cpp: astrobot's form with boykopovar#390's message.
- VulkanDevice.cpp, Context.hpp, PacketExecution.cpp: both sides kept
  (calibrated timestamps, host query reset, GDS, memory budget; pipeline stats).
- Spirv: astrobot's split-wave rules first, then boykopovar#608's wave-mask ballot and
  boykopovar#587's host subgroup lane; astrobot's function LDS sizing and boykopovar#573's LDS lock
  both kept; conditionalDepth kept in the atomic update loops; upstream's
  buffer atomics (boykopovar#321 boykopovar#332 boykopovar#594) and 64-bit LDS atomics taken.
- TechnicalDebt.md: both sides, duplicate lines dropped.


Build fixes folded in: the upstream boykopovar#453 test block duplicated next to
astrobot's adapted copy removed; a lost closing brace after the host
query reset block restored; lookupLog() is a function since boykopovar#590; the
duplicate MUTEX_TYPE_ADAPTIVE constant (astrobot's 93b2d0e equals boykopovar#156)
removed; the ops boykopovar#596 drops removed from the masked-select list and the
BDA test message updated (the gate-batch-2 integ commits 559e4fab6 and
2ec968fb5).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agc libSceAgc* build shader core/shader

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants