Skip to content

loader: static TLS for threads that were running before load() - #3671

Merged
ItsNotRexed merged 4 commits into
ItsNotRexed:mainfrom
MrCheese5:tls-existing-threads
Nov 23, 2026
Merged

ItsNotRexed merged 4 commits into
ItsNotRexed:mainfrom
MrCheese5:tls-existing-threads

Conversation

@MrCheese5

Copy link
Copy Markdown
Contributor

Claim: #3232 (comment) (RT-225)

What and why

load() installed a mapped image's static TLS block on the calling thread, and the helper DLL's DLL_THREAD_ATTACH covers threads started later. A thread that was already running kept the helper's one-byte block in the reserved slot, so __declspec(thread) code on it read past that block and wrote into the heap. runtime/README.md listed it as a limit for callers of the C++ API, but game code reaches it: third_party/xtaskqueue/Source/Task/ThreadPool_win32.cpp uses the process thread pool, whose workers usually predate the load, and a run-time LoadLibrary of a bundled TLS DLL happens with the title's threads running.

On f847748c, with the repo's tiny_tls.dll (template value 7), the new test's thread created before load() and a pool callback on a worker that existed before it both read something else (5 of the 14 new checks fail).

The change (runtime/src/pe_loader.cpp)

When Windows loads a DLL with static TLS itself, every running thread gets a block for it and no DLL_THREAD_ATTACH. load() now does the same for a mapped image:

  • install_on_existing_threads: after the caller's own block, every other running thread of the process (a toolhelp snapshot, then NtQueryInformationThread for each thread's TEB) gets its own copy of the template in the reserved slot of its ThreadLocalStoragePointer array. The swap is made with the TLS lock held exclusively, so no thread is inside its attach or detach event meanwhile.
  • The record of such a block is kept by thread id (the thread's own thread_local record cannot be written from outside). It comes out in that thread's DLL_THREAD_DETACH, after the module's TLS callbacks have seen the event and before Windows frees the array, or in ~Loader, which restores the helper's block in threads that are still running.
  • Skipped: a thread whose detach event has already run, one with no TLS array or no helper block in the slot, and one that has ended. A thread id reused after a TerminateThread drops the stale record at its attach.
  • install_tls_for_thread() on such a thread is now a no-op, as it already was on a thread started after load().

What is left, all written down above the code:

  • A TLS array replaced during the swap. When some thread loads a DLL with static TLS, Windows gives every thread a new TLS array copied from the old one. If that happens while load() writes a thread's slot, the write can land in the old array; the thread then still has the helper's one-byte block, and the first mapped __declspec(thread) access on it writes past that block: silent heap corruption. The swap therefore reads the thread's array pointer again after writing and repeats on the new array, four times at most; if the block is not in the current array at the end it is taken back and the miss is logged once. A replacement after that last look is not seen. And the first write of an attempt can still land in an array Windows has already replaced and freed: reading the pointer again detects that afterwards, it does not prevent it.
  • TerminateThread. It frees a thread's TEB with no detach event. Every read and write of another thread's TEB or TLS array is made right after the thread was seen running and inside __try, so a TEB that has just gone is a skipped thread, not a fault in load() or ~Loader. If the memory was already reused, the write is not caught.
  • A thread past its detach event from before the helper DLL was first loaded that has not left the process yet is not known as ended; if Windows leaves a stale array pointer in its TEB for those last instructions, the write goes to freed memory.

Modules with TLS callbacks and no data get no record on such threads, so no DLL_THREAD_DETACH there. The list of ended thread ids is capped at 1024 (the oldest half goes); it is scanned linearly under the lock once per thread at load().

No TEB layout is new here: the offset of ThreadLocalStoragePointer is the one the loader already reads through gs:[58h].

Tested

Windows 11 26200, MSVC 19.44, Ninja, RelWithDebInfo, NVIDIA GeForce RTX 4090, driver 621.14, base f847748c. No GPU is needed for the change itself.

  • loader_tls_test: 74 checks, all pass; on f847748c 5 of the first 14 new ones fail. New: a thread and a warm pool worker created before load(); the thread reads 7, writes 55 and keeps it, has a block of its own; 16 pool callbacks read 7 (the run prints whether one landed on the worker that existed before the load: it did in the runs I looked at); ~Loader frees that thread's block while it is still running; after a second load() the same thread reads 7 again, gets no DLL_THREAD_ATTACH and one DLL_THREAD_DETACH; a thread terminated with TerminateThread while it holds a block is passed by in ~Loader, and a dead thread whose handle is still open is passed by in load().
  • The test 40 times in a row on the final head (and 60 on the first commit): all pass. These runs exercise the normal path only: neither the array-replacement race nor a TEB freed mid-access occurs in them, so they are no evidence for the handling of those two.
  • Full ctest -j 4 on the final head, Visual Studio 2022's CMake 3.31.6 and its Ninja (what scripts/build_runtime.ps1 uses): 141 tests, 133 passed, 8 skipped (the five package tests, vk_sync_validation, d3d12_rgb9e5_rtv, d3d12_first_light), 0 failed. The first commit also passed with CMake 4.4.3.
  • Not run under Wine.

AI-assisted (Claude Code).

🤖 Generated with Claude Code

MrCheese5 and others added 2 commits November 22, 2026 20:40
load() installed the image's TLS block on its caller, and the helper DLL's
DLL_THREAD_ATTACH covers threads started later. A thread that was already
running kept the helper's one-byte block in the reserved slot, so mapped
__declspec(thread) code on it read and wrote past it. The process thread
pool's workers are such threads, and the task queue runs a title's
callbacks on them.

load() now gives every other running thread its own copy of the template
through that thread's TEB, as Windows does for a DLL it loads itself: a
block, no DLL_THREAD_ATTACH. The block comes out in the thread's own
DLL_THREAD_DETACH (after the module's TLS callbacks) or in ~Loader.

loader_tls_test: a thread and a pool worker that exist before load(),
across two mappings of the fixture.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
- After writing a thread's slot, read its array pointer again and repeat on
  the new array if Windows replaced it; if the block is not in the current
  array after four attempts, take it back and log.
- Read and write another thread's TEB and TLS array inside __try, right
  after the thread was seen running, so a TEB freed by TerminateThread is a
  skipped thread.
- Bound the list of ended thread ids.

loader_tls_test: a thread terminated while it holds a block, and a load()
with a dead thread still open.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@shdann

shdann commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Review note about cost and scale. An AI tool helped me to read the diff. I did not build or run the change.

1. The thread snapshot includes all threads on the system

CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) ignores the process ID. The snapshot contains each thread of each process. install_on_existing_threads runs one time for each module that has static TLS. A desktop system can have thousands of threads. Then each such module load makes a full snapshot and examines each entry.

Suggestions:

  • Make one snapshot for each load() call. Use it for all modules of that call.
  • Or keep a list of thread IDs in the runtime. The helper DLL gets each DLL_THREAD_ATTACH and DLL_THREAD_DETACH event.

2. The records use linear searches while the locks are held

  • state.ended is a vector of a maximum of 1024 IDs. The code searches it with std::find for each candidate thread.
  • state.blocks is one vector. has_existing_thread_block searches it by thread and module. The install loop searches it by thread and slot. The three remove functions search it by thread or by module.

With T threads and M modules, the vector holds T x M entries. One install costs O(T x T x M). The process does this M times.

Suggestion: use a map from thread ID to the blocks of that thread. Use a set for ended. The counts are small now. But other threads wait on g_tls_lock during this work.

3. Each block uses one VirtualAlloc call

Each call commits a minimum of 4 KiB and reserves 64 KiB of address space. A TLS template is frequently much smaller. Suggestion: make one allocation for each module that holds the copies for all threads. Or use a heap allocation with the correct alignment.

4. Handle leak on an error path

candidates.push_back or state.blocks.push_back can throw. Then the code does not close the thread handles in candidates. The CloseHandle loop is after the locked block. Suggestion: use a small RAII object for each handle.

@CharlyRien

Copy link
Copy Markdown

Code review of 292c917 (AI-assisted), with a synthetic probe in a private copy on Windows 11 23H2 (MSVC). Nothing was pushed. @shdann's note covers snapshot cost; these are correctness issues in the window where a thread is being created while load() runs. The PR's own loader_tls test passes.

Probe: rv_sleeper.dll, loaded before the helper DLL, holds a chosen thread T inside its own DLL_THREAD_ATTACH, so T's TLS array exists but the helper's attach hasn't run yet. Then load() runs on the repo's tiny_tls.dll, and T is released after a chosen delay.

  1. Thread exit crashes: a block still in the slot gets freed (proved). install_on_existing_threads (~L488) gives a block to every thread that has a TLS array, including one whose helper DLL_THREAD_ATTACH is still pending: just created, queued behind earlier DLLs' attaches or waiting on the loader lock.
    • When that attach runs, forget_ended_thread_id (~L590) treats every record under its id as belonging to a dead thread. It VirtualFrees the block without restoring the slot.
    • install_thread_block then saves that freed pointer as saved. At thread exit, release_thread_slot writes it back, and Windows' TLS cleanup frees it from the heap. The helper's own block is also leaked.
    T in an earlier DLL's attach: vector=000001F6A4A6EC90 slot=000001F6A4A82CE0
    load() took 32 ms; T slot after load=000001F6A4BA0000 (COMMIT)
    T read 7; ...
    letting T exit while the Loader is alive...
    exit=0xC0000005
    
    It crashed the same way 2 of 2 times with a 100 ms delay. The trigger is any thread the title creates while load() runs, whose attach for earlier DLLs (CRT, d3d12, the driver) is still in progress.
  2. Two blocks per thread and DLL_THREAD_DETACH twice (proved). The window runs from publishing the owner (~L1173) to install_on_existing_threads taking the exclusive lock, with the toolhelp snapshot inside it. A thread whose helper attach lands in that window gets a block from the attach, then a second one on top, with the first recorded as saved. At exit, release_existing_blocks_of_this_thread runs the TLS callbacks, and the loop in on_host_thread_event (~L656) runs them again:
    spin 0 us     -> DLL_THREAD_DETACH count for T = 1
    spin 1000 us  -> count for T = 2
    spin 10000 us -> count for T = 2
    spin 30000 us -> count for T = 2
    
    A looped run gave a double detach in 430 of 500 iterations. A title callback that frees per-thread resources frees them twice.
  3. The thread is never checked against this process (reasoned). running_thread_tls_vector reads a struct that has process_id but never compares it. Between the snapshot and OpenThread, a thread of this process can exit and its id can be reused in another process. NtQueryInformationThread then returns that other process's TEB address, and the code reads and writes teb+0x58 at that address in its own address space. __try only catches an access violation. If the address happens to fall on one of this process's own TEBs, that thread gets a block recorded under the wrong id.
  4. Failures don't fail load() (reasoned). If VirtualAlloc fails or the array keeps changing, the thread is skipped and only the first miss is logged. load() still succeeds, and that thread keeps the helper's 1-byte block, so mapped __declspec(thread) code on it writes past it. Also, as the PR text says, modules with TLS callbacks but no TLS data get no DLL_THREAD_DETACH on pre-existing threads, where Windows would send one.

Checked and found correct:

  • No suspend/resume, so no deadlock with a suspended thread holding the heap or loader lock.
  • GetProcAddress resolved before the TLS lock; snapshot and OpenThread outside it.
  • Snapshot entries filtered by owner pid.
  • Page-aligned, zero-filled blocks cover SizeOfZeroFill.
  • Restores re-read *vector, so a TLS array Windows replaced later is handled.
  • ~Loader and thread detach serialised by the exclusive and shared locks.
  • Reload into the same slot.
  • No DLL_THREAD_ATTACH for pre-existing threads, as on Windows.

ctest here also fails d3d12_shader_cache, d3d12_vulkan_device and d3d12_typeless_rtv. Those fail on main on this machine (the first is fixed in #2167), and none of them links pe_loader.cpp.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@MrCheese5

Copy link
Copy Markdown
Contributor Author

Thanks, all four points are fair. What I did and did not do:

  1. Handle leak: fixed, 77bb7274. The snapshot handle and the thread handles now belong to a small holder that closes them on every way out, and a candidate's slot is pushed before its handle is opened.

  2. System-wide snapshot: measured, left as is, noted in the code. You are right that TH32CS_SNAPTHREAD lists every thread on the system. On this machine (6,312 threads at the time) the snapshot plus the walk took a median of 37 ms over 20 runs, measured from Python with ctypes, so an upper bound for the C++ loop. That is paid once per mapped image that has static TLS data, not per module: of the package's 16 DLLs the CRT ones are host copies and are not mapped, so it is the executable and a few bundled DLLs. I would rather not add the runtime's own thread list here: the helper DLL only sees threads from the moment it is loaded, so the list would still need a snapshot for the ones before it, and it is one more structure to keep right under the loader lock. Reusing one snapshot across the modules of a single load() call is a clean follow-up if this turns out to matter at boot; say so and I will do it here instead.

  3. Linear bookkeeping: left as is. The counts are threads that existed at a load times modules with TLS data, tens of entries, and the ended-id list is capped at 1,024. I agree the shape is quadratic on paper and that it runs with g_tls_lock held; a map keyed by thread id is the fix if the numbers grow. I kept flat vectors because every one of these paths also runs inside a thread event under the Windows loader lock, where I wanted as little allocation and as little code as possible.

  4. One VirtualAlloc per block: left as is, on purpose. It is what the existing paths do for the loading thread and for threads started after load() (install_thread_block), and the tests check that a block is released by asking VirtualQuery for it. A different allocator for these blocks only would make the two kinds of block differ in how they are freed, in code that restores other threads' slots.

Tested for the new commit: loader_tls_test 20 runs, 74 checks each, and loader_test; not the full suite again (the full run in the description is from the commit before). AI-assisted (Claude Code).

Conflicts with ItsNotRexed#2070's later round (TLS generations, per-slot thread-event
errors, clone purge) in pe_loader.cpp/.h and loader_tls_test.cpp:
- install_thread_block keeps main's generation check and this branch's
  existing-thread check.
- on_host_thread_event keeps main's per-slot try/catch and calls this
  branch's existing-thread hooks first, each in its own try/catch.
- ~Loader resets the slot generation and removes the existing-thread blocks.
- The existing-thread records carry the module's TLS generation too.
- Both sides' tests stay. test_orphan_slot_generation_reuse now expects
  one DLL_THREAD_DETACH, not none: the worker was running when the second
  Loader mapped the module, so it gets that module's copy and its detach,
  as Windows does; a second detach would mean the orphaned record was taken
  for the new module's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@MrCheese5

Copy link
Copy Markdown
Contributor Author

Merged current main into this branch (2fb013cd, a merge, nothing rewritten). The conflicts were with #2070's later round (TLS generations, per-slot thread-event errors, the clone purge):

  • install_thread_block keeps main's generation check and this branch's existing-thread check; on_host_thread_event keeps main's per-slot try/catch and calls this branch's two existing-thread hooks first, each in its own try/catch; ~Loader resets the slot generation and removes the existing-thread blocks.
  • The existing-thread records now carry the module's TLS generation as well as its pointer, so they follow main's rule for a reused slot or address.
  • Both sides' tests stay. One assertion of main's test_orphan_slot_generation_reuse changes, from no DLL_THREAD_DETACH to exactly one. Its worker thread is still running when the second Loader maps the module, so with this PR load() gives that thread the module's copy, and the module gets DLL_THREAD_DETACH once when the thread ends, as Windows does for a DLL loaded while a thread runs (this PR's own test_existing_threads checks the same). A second detach would still mean the orphaned first-Loader record was taken for the new module's. @jaybeebabageyus, it is your test: say so if you read its intent differently. One limit I found while checking: on this machine the second Module never landed at the first one's address (5 of 5 runs printed different addresses), so the count was 1 with the generation check disabled too. The test as written does not reach the reused-address case here, before or after this change.

Tested on 2fb013cd, Visual Studio 2022's CMake 3.31.6, RTX 4090 621.14: full ctest -j 4 154 tests, 145 passed, 9 skipped, 0 failed; loader_tls_test 85 checks.

Repeat runs, asked for because another session saw loader_tls fail intermittently on main. 50 runs of loader_tls_test alone, then 50 rounds of ctest -j 4 over loader_tls, xgameruntime, file_system and d3d12_vulkan_device:

build alone under ctest -j 4
main aa2988cc 0 of 50 failed 0 of 50 failed
this PR 2fb013cd 0 of 50 failed 0 of 50 failed

So I could not reproduce that failure on this machine at all, and these numbers say nothing for or against this PR on it. AI-assisted (Claude Code).

@evilclanker9000

Copy link
Copy Markdown
Contributor

Tested 2fb013c on Windows 11 (MSVC RelWithDebInfo): full runtime build, then ctest for the shim/loader tests (loader, pe_loader, loader_tls, dll_thread_calls, unimplemented_policy, startup_trace, xmem, process_cmdline, file_system, winhttp_offline, xgameruntime, run_tiny_*, allocator_proxy) — 27 of 27 passed. AI-assisted.

@ItsNotRexed
ItsNotRexed merged commit 44d705c into ItsNotRexed:main Nov 23, 2026
3 of 10 checks passed
Raxstreams pushed a commit to Raxstreams/Leonida that referenced this pull request Nov 23, 2026
Raxstreams pushed a commit to Raxstreams/Leonida that referenced this pull request Nov 23, 2026
…block too

After ItsNotRexed#3671 a thread that was already running when load() ran gets each module's TLS block from load()
itself, and install_tls_for_thread is a no-op there. install_on_existing_threads stopped at
kMaxMappedTlsModules, so the executable in kMainImageSlot (ItsNotRexed#4313) was skipped: such a thread, a thread-pool
worker for instance, kept slot 0 as it was and /GA code on it read the wrong block. The check now covers
kTlsSlotCount. loader_tls_index0's early thread checks the new contract; without the change it fails
(reads no 42 in slot 0 before any install call).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants