Skip to content

runtime: support multiple simultaneous manually mapped static-TLS modules - #2070

Merged
ItsNotRexed merged 18 commits into
ItsNotRexed:mainfrom
jaybeebabageyus:rt-multi-module-tls
Nov 22, 2026
Merged

ItsNotRexed merged 18 commits into
ItsNotRexed:mainfrom
jaybeebabageyus:rt-multi-module-tls

Conversation

@jaybeebabageyus

@jaybeebabageyus jaybeebabageyus commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Removes the single-module static TLS limit in rt::Loader ("only one manually mapped module may use static TLS at a time"). When the game executable (game_scarlett_master.exe) and one or more bundled Xbox DLLs both carry static TLS directories (__declspec(thread) / thread_local), the loader previously rejected the second module at load time.

How it works

  • On-demand TLS slot pool (kMaxMappedTlsModules = 16):
    • Slot 0 continues to load gta6rt_tls_host.dll directly next to the executable with zero temporary files (identical to existing behavior for 0–1 TLS modules) and hooks on_host_thread_event.
    • Additional simultaneous static-TLS modules (slot 1..15) lazily clone gta6rt_tls_host.dll to a per-process path in %TEMP% (or LEONIDA_TEST_DIR) via CopyFileW (Wine 9 compatible, avoiding CopyFile2) and load it with LoadLibraryExW(..., LOAD_LIBRARY_SEARCH_SYSTEM32), causing the OS loader to allocate an independent module TLS index in TEB->ThreadLocalStoragePointer[].
    • Cloning/loading happens under g_tls_alloc_mutex outside g_tls_lock, so LoadLibraryExW (which takes the Windows loader lock) can never deadlock with on_host_thread_event (which runs under the loader lock and acquires SharedTlsLock).
  • Per-slot tracking & thread events:
    • Replaced single-owner g_tls_slot_owner and single-entry thread_local pointers with std::array<..., kMaxMappedTlsModules> indexed by Module::tls_slot.
    • on_host_thread_event installs/runs DLL_THREAD_ATTACH across all active TLS slots in order, and runs DLL_THREAD_DETACH / restores helper blocks in reverse order on thread exit (still freeing orphaned blocks if a thread outlives its Loader).
  • Tests (runtime/test/loader_tls_test.cpp):
    • Replaced test_second_tls_module_rejected with test_multiple_tls_modules, verifying 3 simultaneous manually mapped static-TLS modules receive distinct OS module TLS indices, maintain isolated __declspec(thread) state across main and worker threads, receive DLL_PROCESS_ATTACH / DLL_THREAD_ATTACH / DLL_THREAD_DETACH callbacks on all 3 modules, and release their slots for reuse after ~Loader().

Verification

  • AI-assisted: Yes (implemented and verified with an AI coding assistant).
  • Environment: Windows 11 x64, MSVC 19.44.35230.0 (VS 2022 Build Tools), Windows SDK 10.0.26100.0, CMake 4.4.4 (RelWithDebInfo).
  • Tests run (all passed, 0 failures, no game data used):
    • ctest -C Release -R "^(loader_tls|loader|pe_loader)$" --output-on-failure — 3/3 passed (loader: 64/64 checks, pe_loader: 74/74 checks, loader_tls: 69/69 checks, including purge-ownership scoping, explicit pre-ExitProcess cleanup and per-slot thread-event isolation).

@Jadiac5

Jadiac5 commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Tested ba912772 on Windows 11, MSVC 19.44.35222 (VS 2022 Build Tools, Ninja, RelWithDebInfo): pass, with two
things to look at.

  • Ran: cmake --build runtime/build, ctest --test-dir runtime/build -C RelWithDebInfo --output-on-failure, then
    ctest -R "^loader_tls$" four more times (once with LEONIDA_TEST_DIR set).
  • ctest: 42/42 passed, same as main at 4eb6155d. loader_tls: OK, 51 checks (main: 45). loader 64 and
    pe_loader 74, unchanged.
  • Leftover files: every run leaves leonida_tls_host_<pid>_1.dll and _2.dll in %TEMP% (or in
    LEONIDA_TEST_DIR); after five runs there were ten. ensure_tls_host in runtime/src/pe_loader.cpp copies them
    and nothing deletes them, and they cannot be deleted while loaded. A game process with several TLS modules would
    leave some on every start.
  • Loading a DLL from a writable folder: the clone is written to %TEMP% under a predictable name and then
    LoadLibraryExW'd. Another process of the same user could replace it between CopyFileW and the load. Copying
    next to the executable, or opening the copy without write sharing before loading it, would close that.
  • The runtime reads LEONIDA_TEST_DIR (tls_host_clone_dir), a variable that so far only tests use.
  • The first loader_tls run after the build took 12.4 s (0.04 s on main); the four reruns took 0.08–0.13 s. I
    assume antivirus scanning the fresh copies, but did not confirm it.
  • The new callback check is cb >= 3 for each module, which would also pass if a module received another module's
    thread events twice.
  • Note: the branch is based on 6a6704df, not current main; I tested the branch as it is, not a merge.
  • Not tested: Wine, and more than three TLS modules at once.

AI-assisted (Claude Code).

@Flyander Flyander left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A valid TLS directory may contain callbacks while tls_raw_size + tls_zero_fill is zero. install_thread_block returns before registering such a module in g_thread_tls_slots, but the attach path still invokes its callbacks and the detach path only invokes callbacks for registered slots. That silently drops DLL_THREAD_DETACH for callback-only TLS modules. Please track callback delivery separately from whether a TLS data block exists, and cover a callback-only fixture.

@Ingenioeren

Copy link
Copy Markdown

I tested #2070 at ba912772 together with #2021 at f4a3fe8 on main at 4eb6155d, with #2030 for Windows SDK 10.0.26100.0 (D3D12_SDK_VERSION=612). Windows 11 x64, MSVC 19.43, RelWithDebInfo. All 21 focused headless loader and runtime CTests passed with #2021 alone and with both PRs applied.

I also extended tiny_bundled_load and tiny_bundled_dll locally with one initialized __declspec(thread) value each. The mapped EXE loads the DLL with LoadLibraryW, sets both values, then creates a thread that sees and mutates its own copies. The entry thread checks that its values are unchanged.

Synthetic inputs only. AI-assisted testing.

@jaybeebabageyus

Copy link
Copy Markdown
Contributor Author

Rebased onto \main\ (\4eb6155d) and addressed all review feedback in \�28493ba:

  • Callback-only TLS modules (@Flyander): \install_thread_block\ now records \entry.module = &m\ in \g_thread_tls_slots[slot]\ even when \ ls_raw_size + tls_zero_fill == 0, and
    elease_thread_slot\ clears the slot entry even when \entry.block == nullptr. Added a \ iny_tls_cb_only.dll\ fixture (/NODEFAULTLIB, \ ls_raw_size == 0 && tls_zero_fill == 0, .CRT\ callback) in \loader_tls_test.cpp\ verifying \DLL_PROCESS_ATTACH, \DLL_THREAD_ATTACH, and \DLL_THREAD_DETACH\ all fire once.
  • Clone cleanup & write-guard (@Jadiac5): Removed \LEONIDA_TEST_DIR\ from \ ls_host_clone_dir, added an \�texit\ cleanup that unloads and deletes this process's clones, sweeps orphaned \leonida_tls_host_*.dll\ files from dead processes on startup, and holds a read-only-shared handle across \LoadLibraryExW\ so another process cannot overwrite the clone between \CopyFileW\ and load.
  • Exact callback assertions: \ est_multiple_tls_modules\ now uses \ iny_tls_watch_thread\ on a suspended worker thread and asserts == 1\ for \DLL_PROCESS_ATTACH, \DLL_THREAD_ATTACH, and \DLL_THREAD_DETACH\ on each of the 3 modules.

Re-tested on Windows 11 x64 (MSVC 19.44, RelWithDebInfo): \loader\ (64/64), \pe_loader\ (74/74), \loader_tls\ (58/58) all pass.

@Ingenioeren

Copy link
Copy Markdown

Retested a28493ba on Windows 11 with MSVC 19.43, using the same #2021 and SDK patches as my previous check. Both runs used separate empty TEMP and TMP directories.

  • loader_tls passed all 58 checks, including the callback-only fixture, with zero helper DLLs left after the test process exited.
  • gta6rt --run with the bundled-DLL TLS fixture also passed and exited 0. It left one helper DLL after exit.

The launcher’s successful --run path ends in Win32 ExitProcess, so it bypasses the host CRT std::atexit callback that performs this cleanup. An end-to-end test can count the temporary helper files after the launcher has exited. Synthetic inputs only. AI-assisted testing.

@Flyander Flyander left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The callback-only TLS fix and its fixture are now present. I found a separate lifecycle issue in the per-thread slot tracking:

A worker can outlive a Loader; its g_thread_tls_slots[slot].module entry is intentionally kept so the old block can be freed when that worker exits. Loader::~Loader clears the owner and frees the old Module, allowing a later loader to reuse both the TLS slot and (through normal allocator reuse) the same Module address. install_thread_block then treats the stale entry as current at entry.module == &m and returns without installing the new template. On thread exit, on_host_thread_event can likewise mistake the stale entry for the new owner and send the new module DLL_THREAD_DETACH without a corresponding DLL_THREAD_ATTACH.

Pointer identity cannot distinguish these module lifetimes. Please include a generation/token in the module and per-thread slot record, and release mismatched stale entries before install or callback dispatch. This matters for the orphan cleanup case the implementation explicitly supports. I reviewed this statically and did not run tests.

@jaybeebabageyus

Copy link
Copy Markdown
Contributor Author

Fixed in $(git -C C:\Users\jayde.gemini\antigravity\scratch\Leonida rev-parse --short HEAD):

  • Added a monotonic 64-bit \ ls_generation\ token on \Module\ and \ThreadTlsSlot\ (plus \g_tls_slot_generations) so \install_thread_block, \uninstall_thread_block, and \on_host_thread_event(DLL_THREAD_DETACH)\ never mistake an orphaned entry from an earlier \Loader\ for a new module reusing the same slot or \Module*\ address. Mismatched stale entries are released without dispatching callbacks to the new generation's module.
  • Added \ est_orphan_slot_generation_reuse\ in
    untime/test/loader_tls_test.cpp, verifying that a worker thread outliving \Loader Add pytest regression tests for the RDNA2 -> SPIR-V translator, plus a Linux CI job #1\ does not trigger \DLL_THREAD_DETACH\ on \Loader Vulkan tools: fix builds on Linux #2\ when the slot is reused.

Re-tested on Windows 11 x64 (MSVC 19.44, RelWithDebInfo): \loader\ (64/64), \pe_loader\ (74/74), \loader_tls\ (60/60) all pass.

@Flyander Flyander left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pointer-reuse finding from my prior review is fixed by the generation check. Two separate lifecycle issues remain at this head:

  • The startup purge deletes every leonida_tls_host_*.dll without checking ownership or whether another process is using that path. A concurrent process can have copied its TLS clone but not reached LoadLibraryExW yet; this purge can remove its file and make its load fail. The protection handle is opened only after the copy and allows delete sharing.
  • The std::atexit cleanup does not run on the normal --run exit path because main calls ExitProcess directly. TLS clones therefore remain on disk until a later purge.

Please scope deletion to files owned by this process (or protect the create/load sequence across processes) and run cleanup before the ExitProcess path.

@dcastell1

Copy link
Copy Markdown
Contributor

Tested 81d82bf on Windows 11 x64 (MSVC 19.44, Ninja, CPU-only tests): pass. Built the runtime from this tree and ran ctest -R "loader|pe_loader": 4/4 passed (loader 9.0 s, pe_loader 0.3 s, pe_loader_bounds 0.4 s, loader_tls 0.3 s).

That covers the regression risk of sharing the loader state across two simultaneous manuals: the bounds and TLS tests still pass with the per-manual bookkeeping in place.

@jaybeebabageyus

Copy link
Copy Markdown
Contributor Author

Thanks — loader state shared across two simultaneous manual mappings is exactly the regression risk here, good to see bounds and TLS green on the current head. AI-assisted.

@poke900310-lgtm

Copy link
Copy Markdown

One more thing at 81d82bf, separate from what's been raised so far.

In on_host_thread_event (pe_loader.cpp:351-377), the try/catch wraps the whole slot loop, so a throw for one slot ends the event for every other slot. install_thread_block can throw on a failed VirtualAlloc. run_callbacks throws when a callback table entry no longer validates, which is the case ~Loader already catches for process detach.

  • On DLL_THREAD_ATTACH, every later slot gets no block and no callback, so that module's __declspec(thread) reads the clone helper's own small block.
  • On DLL_THREAD_DETACH (reverse order), every lower slot skips its release. The helper's pointer is never put back, so the OS loader frees our VirtualAlloc block as its own at thread exit.

With a single module this only hurt the module that failed; now one bad module breaks all of them. Moving the try/catch inside the loop, and always releasing the slot on detach even if the callback threw, should be enough.

Minor: runtime/README.md (around line 121) and the comment above initialize_tls (pe_loader.cpp:700-705) still say only one mapped TLS module can be live at a time.

AI-assisted review (Claude Code), read-only; I didn't build or run it.

…-mods

rdna2spirv: bitwise abs/neg in v_cmp(x)_class_f32 to preserve sNaNs (SHADER-457)
…d-textures

restofworld_index: identify embedded 0x980 textures and companion TTPF pools (ASSET-148)
…d-format-facts

docs: record the 6stars format facts that reproduce
docs: document the low-disk run-only build and hint it in preflight
…efore ExitProcess, per-slot thread-event errors

The startup purge deleted every leonida_tls_host_*.dll in the temp directory, so it could remove the
clone of a concurrent process that had copied its helper but not reached LoadLibraryExW yet. Clones
are now copied to a staging name and renamed into place while the copy step's guard handle is open, so
a final-name clone never exists without a handle, and the purge skips files that fail an exclusive
open or whose owner process (from the file name) is still alive.

std::atexit cleanup never ran on the --run path because main ends with ExitProcess; the loader now
exposes cleanup_tls_clones() and main calls it before ExitProcess (atexit still covers normal exits).

on_host_thread_event wrapped the whole slot loop in one try/catch, so one throwing slot killed the
events for every other module. The catch is now per slot, and the detach path releases the slot even
when the callbacks threw, instead of leaking the block to the OS loader.

README and the initialize_tls comment no longer claim only one mapped TLS module can be live; the
loader_tls_test gained purge-ownership and explicit-cleanup checks.
# Conflicts:
#	runtime/src/pe_loader.cpp
#	runtime/src/pe_loader.h
#	runtime/test/loader_tls_test.cpp
The dead-owner case relied on the spawned child's PID staying free until the
sweep ran, which is not guaranteed on a busy machine; a reused PID turned the
check into a SKIP. The deletable stand-in now uses this process's own PID
instead: the sweep runs before this process has created any clone, so a file
named with the current PID is always a leftover of a dead run there, and the
live-PID and handle-held skip cases keep their own deterministic stand-ins.
@jaybeebabageyus

Copy link
Copy Markdown
Contributor Author

All three points addressed in 1188e64 and 4edfb24, on top of a merge of upstream/main (50e9dd3) that clears the conflict against the current base.

Purge ownership (round 3, item 1). Clones are no longer created directly under their final name: ensure_tls_host copies to a staging path (...dll.new, which the sweep pattern does not match), opens the guard handle on the staging file, and only then MoveFileExWs it into place, so a final-name clone never exists without that handle open. sweep_stale_tls_clones now skips any file it cannot open exclusively (a no-sharing CreateFileW conflicts with any open handle, so the guard or a mapped image blocks it) and any file whose owner PID, parsed from the file name, belongs to a live process. Deletion of a still-mapped image keeps failing harmlessly. A concurrent process between its copy and its LoadLibraryExW therefore keeps its clone, and this process only deletes files no live process owns. test_purge_ownership_scoping covers the three cases: ownerless (deleted), handle-held (skipped), live owner (skipped).

Cleanup on the --run path (round 3, item 2). cleanup_tls_clones() is now public (declared in pe_loader.h); main calls it right before ExitProcess on the --run path, and the std::atexit registration stays for normal exits. loader_tls_test verifies the clone files are gone after an explicit call.

Per-slot event handling (round 4). The try/catch in on_host_thread_event moved inside the loop: a throwing install_thread_block or callback reports and skips only its own slot, so the other modules still get their blocks and callbacks on attach and their releases on detach. The detach path now releases the slot even when the callback threw, instead of leaking the block to the OS loader as the helper's own TLS. The single-module wording in runtime/README.md (~L121), above Loader::initialize_tls, and the per-thread install comment in pe_loader.h now describe the clone-per-module scheme.

Tests: ctest -C Release -R "^(loader_tls|loader|pe_loader)$" — 3/3 passed; loader_tls 69/69 checks (MSVC 19.44 / SDK 10.0.26100, Win 11 26200, RTX 3060).

@ItsNotRexed
ItsNotRexed merged commit 00f9ebd into ItsNotRexed:main Nov 22, 2026
2 of 4 checks passed
kotorvr added a commit to kotorvr/Leonida that referenced this pull request Nov 22, 2026
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>
Sc4ros added a commit to Sc4ros/Leonida that referenced this pull request Nov 23, 2026
on_host_thread_event only ran the TLS callbacks of modules that own a TLS slot,
so a DLL without a TLS directory never heard about a thread, and no module's
DllMain did. It now announces every thread to every initialised module, in
initialisation order (reverse for detach): the module's TLS callbacks, then
its DllMain, after the thread's TLS copies are in place. A thread is detached
only from the modules whose attach it saw.

- DisableThreadLibraryCalls from a mapped DllMain (ItsNotRexed#2383) is recorded through a
  new optional BundledModuleOps entry and switches the DllMain events off,
  except for a module with a TLS directory: Windows answers TRUE there and keeps
  sending them, and so does the loader.
- A module that has a DllMain or a TLS directory makes sure the thread-event
  hook (the primary gta6rt_tls_host.dll) is loaded when it is initialised.
- thread_events_test loads four CRT-free fixture DLLs with both the Windows
  loader and rt::Loader and requires identical event logs, so the order is
  measured rather than assumed.

Depends on ItsNotRexed#2070 (the thread-event slot code) and ItsNotRexed#2383.

Co-Authored-By: Claude Sonnet 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.