Skip to content

Loader: the mapped game executable owns module TLS index 0 (RT-259) - #4313

Open
mariuslozo-boop wants to merge 4 commits into
ItsNotRexed:mainfrom
mariuslozo-boop:rt/exe-tls-slot0
Open

mariuslozo-boop wants to merge 4 commits into
ItsNotRexed:mainfrom
mariuslozo-boop:rt/exe-tls-slot0

Conversation

@mariuslozo-boop

Copy link
Copy Markdown

Claimed in the coordination issue as: RT-259 (claim).

What and why

Code built with MSVC /GA (optimised for an executable) reads its thread-local storage as gs:[58h] → [0], without loading _tls_index. That is correct on Windows, because the process executable always gets module TLS index 0. Under gta6rt, though, index 0 belongs to gta6rt.exe itself, and the mapped game executable got a helper index. /GA code in the game then read and wrote gta6rt's own block.

Reproduced with a 20-line /GA program that sets a thread_local to 42:

  • native: tls_index=0 value=42;
  • under gta6rt --run on main: tls_index=6 value=0, exit code 1;
  • with this PR: tls_index=0 value=42, exit code 0.

The change (runtime/src/pe_loader.cpp, main.cpp, tls_host.cpp):

  • rt::reserve_tls_index0() runs once, from a .CRT$XCT initializer in main.cpp. That is before any of gta6rt's own static initializers and threads; checked against the map file and the disassembly.
  • It loads a "home" clone of gta6rt_tls_host.dll. The clone's TLS directory points at a 16 KiB export, gta6rt_tls_home_template, filled with a copy of gta6rt.exe's TLS template.
  • It then swaps slot 0 and the home slot on the main thread, and rewrites gta6rt.exe's _tls_index to the home index.
  • From then on, every new thread gets a full, correctly sized copy of gta6rt's TLS at the home index from ntdll. Slot 0 is free for the mapped executable (kMainImageSlot), through the existing install, thread-event and ~Loader paths.
  • On thread attach, every module's copy is installed first, then the TLS callbacks run, DLLs first and the executable last (Windows' order).
  • An executable with TLS that does not get index 0 is refused under --run and --init with the reason, and --dry-run prints a note. Before, such a /GA executable silently corrupted gta6rt's own block.
  • A primary helper without the gta6rt_tls_host_set_thread_event export is refused.
  • Helper clone files are deleted at exit again. The next run's sweep now also removes files of processes that ended while another process still held a handle to them.

Measured facts this relies on are in the comments and in runtime/README.md:

  • ntdll copies only the raw TLS template and ignores SizeOfZeroFill, hence the 16 KiB array instead of a zero-fill;
  • a mapped DLL's file cannot be deleted at exit;
  • DLL DllMain runs before the executable's TLS callbacks.

Known limits (in the README):

  • Only one executable holds index 0.
  • Other programs that use Loader must call reserve_tls_index0() at process start.
  • The home clone file stays in %TEMP% until the next run's sweep.
  • Not run under Wine here: the Wine CI job runs run_tiny_game, whose image has TLS.

Tested

Windows 11 (build 26300), RTX 5070 Ti (driver 616.92), MSVC 19.44, Vulkan SDK 1.4.363.0, RelWithDebInfo, on main 03b09a08.

  • Full ctest: 142/142 passed, both serial and -j 8. The skips are the usual ones that need game data, SDL3 or GPU tools.
  • -R "loader_tls|run_tiny" --repeat until-fail:30: all 30 rounds passed.
  • New tests:
    • loader_tls_index0: a real /GA /MD fixture, tiny_tls_ga.dll, checked from its machine code. It reads 42 at slot 0 on the loading thread, an older thread and new threads. It also checks that the EXE's own block moved by pointer identity, and the home template's size and content.
    • loader_tls_index0_threads: a reservation while another thread keeps creating threads, a thread with no TLS array yet, and code that runs before the helper's thread attach (tiny_thread_hook.dll).
    • loader_tls_index0_noreserve: a map without the reservation gets a helper index.
    • run_tiny_tls_ga: --run and --init on the fixture, and the refusal path (TMP and TEMP naming a missing folder).
    • run_tiny_tls_clone_cleanup: no clone files are left after --dry-run and --init, and the next run sweeps the home clone.
  • Against main: the new index-0 test fails 14 of 39 checks with main's loader. The cleanup test fails with the old cleanup.
  • Python: every tests/test_*.py that CI runs passed, except 5 that fail identically on clean main on this machine (Wine, llvm-mc, the game-data scan, saves and the progress dashboard).

Reviewed twice by an independent reviewer before this PR.

  • The first review found a TLS slot address that MSVC keeps across DLL calls in zlib_inflate, which made the original lazy move unsafe. That led to the startup reservation.
  • The second review found the exit-cleanup regression, now fixed and tested.

Checklist

  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (Not applicable: no translator change.)

AI-assisted (Claude Code). No game files.

🤖 Generated with Claude Code

mariuslozo-boop and others added 3 commits November 23, 2026 01:38
Windows gives the process executable module TLS index 0, and MSVC code built
with /GA reads TEB->ThreadLocalStoragePointer[0] without loading _tls_index.
The loader gave a mapped EXE a gta6rt_tls_host.dll clone's index instead, so a
thread_local int v = 42 EXE built /O2 /GA /MD printed tls_index=6 value=0
under gta6rt --run (natively tls_index=0 value=42).

Index 0 belongs to gta6rt.exe itself (and to each test EXE that links
pe_loader.cpp): measured through _tls_index == 0 before any mapping and the
new tls_index0 trace event. All of its own TLS reads go through _tls_index,
so the first time an executable is mapped the loader loads one more helper
clone (leonida_tls_host_<pid>_home.dll), stops the other threads, swaps
slots 0 and the clone's index on every thread and writes that index into the
owner's _tls_index. Threads started later swap their own slots first thing
in the helper's DLL_THREAD_ATTACH. Both pointers are OS-allocated blocks of
that thread and the OS frees every slot at thread exit, so the swap is
permanent and nothing is restored. The executable then takes slot 0
(kMainImageSlot) through the existing per-thread install, thread events and
~Loader paths; DLLs keep the helper indices. A second executable mapped
while one is live, or a move that cannot be made (a thread kept running in
the owner's code for 250 ms), gets a helper index and a stderr note.

Measured on Windows 11 26300 to make the swap safe: a new thread publishes
its TLS array in the TEB only once it is filled (LdrpAllocateTls), an ending
one clears it before freeing the blocks (LdrpFreeTls), LoadLibrary of a TLS
DLL updates other threads in one NtSetInformationProcess call, and an EXE's
TLS callbacks run after every DllMain for thread attach and detach.

Tests: loader_tls_index0 maps tiny_tls_ga.exe (built /GA, code shape
checked) next to tiny_tls.dll: 42 on the loading thread, a pre-existing
thread and new threads, this EXE's own TLS intact on all of them, two runs
in a row, a second executable at once, and a busy thread holding the move
off. run_tiny_tls_ga runs it under gta6rt --run and --init and checks the
trace names gta6rt.exe.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s the EXE's

Fixes from the review of the index-0 change:

- The lazy move at the first executable map stopped other threads and swapped
  their slots, guarded by a "thread is inside gta6rt.exe" check. That is not
  enough: MSVC keeps &ThreadLocalStoragePointer[_tls_index] across calls
  (zlib_inflate saves it at [rbp-80h] across memset, push_back and
  inflate_codes, then reads _Init_thread_epoch through it), so a thread
  stopped in the heap or memset still reads the wrong slot afterwards. The
  move is now rt::reserve_tls_index0(), done once at process start: gta6rt
  calls it from a .CRT$XCT initializer, before its own static initializers
  and before any of its threads; the CRT startup frames above it hold no TLS
  slot address (checked in the disassembly). It swaps slots 0 and home on the
  calling thread only; no thread enumeration, suspension, TEB writes or
  TlsAlloc mark are left.
- The home clone's block was the helper's 514 bytes, smaller than
  gta6rt.exe's 1398-byte TLS. The home clone is now written from
  gta6rt_tls_host.dll with its TLS directory pointed at a new 16 KiB export,
  gta6rt_tls_home_template, filled with a copy of the EXE's template and its
  alignment (LdrpAllocateTls copies End - Start and ignores SizeOfZeroFill,
  so the zero fill is part of the range). Every new thread then has a fresh
  copy of gta6rt.exe's TLS at the home index from its first instruction, so
  no adoption step or window before the helper's DLL_THREAD_ATTACH is left.
  The mapped template is checked against the EXE's after the load.
- The owner is GetModuleHandleW(nullptr) with _tls_index 0, not any module
  whose index reads 0.
- A primary helper without gta6rt_tls_host_set_thread_event is refused.
- An executable that does not get index 0 (no reservation, or another
  executable holds it) is refused by --run and --init with an error; its /GA
  code would read and write another module's TLS through slot 0. The README
  no longer says it "reads the first one's slot 0".
- Thread attach installs every module's copy before any TLS callback runs,
  as Windows allocates all blocks before the first DllMain.
- Tests: loader_tls_index0 (runs) checks this EXE's block moving from slot 0
  to the home index by identity, the home template's size and content, and
  that the getter reads slot 0 with its _tls_index pointing elsewhere (fails
  for a non-/GA build of the fixture); loader_tls_index0_threads reserves
  while threads are being created, with one suspended thread that has no TLS
  array yet and tiny_thread_hook.dll running test code before the helper's
  DLL_THREAD_ATTACH; loader_tls_index0_noreserve maps without the
  reservation. The tiny_tls_ga.cpp comment names the real test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ils cleanly

From the second review of 89cec3b8:

- The first load_tls_host_clone call is now the home clone, from .CRT$XCT,
  and it registered cleanup_tls_clones_at_exit with atexit before
  g_tls_clones was dynamically initialized in .CRT$XCU. The vector's
  destructor then ran first and the cleanup walked a destroyed vector, so
  --dry-run, --init and every return-1 path left the slot clones'
  leonida_tls_host_<pid>_<slot>.dll files in %TEMP%. g_tls_clones is now
  allocated with the first record and never destroyed, and the atexit
  handler is registered there. The home clone cannot be deleted while it is
  mapped (DeleteFileW and a POSIX-semantics delete both fail with
  ERROR_ACCESS_DENIED), so it is left for the next run's sweep, as the
  README says.
- process_alive() took an ended process as alive while another process
  still held a handle to it (CMake's execute_process does), so the next
  run's sweep skipped its files; it now reads the exit code.
- reserve_tls_index0 catches what reserve_index0 throws (for example
  std::filesystem::temp_directory_path) and stores it as the reason, so the
  reservation fails before main with a message instead of ending gta6rt.
  The owner's file name is taken before the move, so nothing can throw
  between the move and recording it.
- Tests: run_tiny_tls_clone_cleanup runs gta6rt --dry-run, --init and
  --dry-run on tiny_tls_clones.exe (three TLS modules, so one slot clone)
  and checks that each run's PID leaves no clone file but its home clone and
  that the next run deletes that one; it fails with the old cleanup.
  run_tiny_tls_ga also runs with TMP and TEMP naming a missing folder: the
  reservation fails, --run and --init refuse the image with the reason and
  run none of it, --dry-run maps it with the note.

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

Copy link
Copy Markdown
Contributor

Independent code read + build/hygiene check at 9366e54f on Linux (WSL2, Python 3.13.5, no Windows/MSVC host, no game files): pass (Windows MSVC build & live loader TLS CTest execution still needed).

  • Code read (runtime/src/tls_host.cpp, runtime/src/pe_loader.cpp, runtime/README.md, runtime/shims/startup_trace.h):
    • Sound design for MSVC /GA executables that bypass _tls_index and read TEB->ThreadLocalStoragePointer[0] directly: moves gta6rt.exe's own TLS off index 0 into a dedicated leonida_tls_host_<pid>_home.dll clone (backed by the 16 KiB gta6rt_tls_home_template export) via an early CRT initializer before static initializers or worker threads cache slot addresses, leaving slot 0 free for the mapped executable (kMainImageSlot).
    • Fail-closed guarantees are well-scoped: refuses moving if the host EXE's TLS exceeds 16 KiB, refuses --run/--init with exit 1 if index 0 was not reserved or is already held by another mapped executable, and records the move via the new tls_index0 startup-trace event.
  • Hygiene (clean worktree on 03b09a08): git diff --check, test_ctest_registration.py (4/4), test_docs_links.py (6/6), test_docs_repo_paths.py (2/2), test_text_write_line_endings.py (3/3), test_text_encoding.py (2/2) all pass.
  • Not run here: Windows MSVC build and CTest execution (loader_tls_index0_test, check_tls_index0.cmake, check_tls_clone_cleanup.cmake).

AI-assisted review.

@Kam471 Kam471 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.

Built the new fixtures and ran the TLS suite at 9366e54f on Windows 11, RTX 5070 Ti:

  • loader_tls_index0 -> passed; loader_tls_index0_threads -> passed; loader_tls_index0_noreserve -> passed.
  • run_tiny_game_tls -> passed (after building the tiny_game fixture); run_tiny_tls_ga -> passed; run_tiny_tls_clone_cleanup -> passed.
  • ctest -R tls -> 7/7 passed, 0.80 s total.
  • loader_tls_index0_test.exe needs its fixture arguments, as documented; the CTest entries supply them.

No blocking issue.

@Hanioe2

Hanioe2 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Native Windows/MSVC verification at 9366e54f on Windows 11 build 26200, MSVC 19.44.35227, SDK 10.0.26100.0, Visual Studio 17 2022 generator, RelWithDebInfo.

All eight focused CTests passed: loader_tls, loader_tls_index0, loader_tls_index0_threads, loader_tls_index0_noreserve, run_tiny_game, run_tiny_game_tls, run_tiny_tls_ga, and run_tiny_tls_clone_cleanup.

I then repeated the thread-index, /GA guest, and clone cleanup CTests 20 times each in a fresh test temp folder. All 60 repeated runs passed. Synthetic CPU fixtures only.

AI-assisted.

@2-CD

2-CD commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Windows + GPU check (complements the Linux code-read above; this is the Windows/MSVC + GPU dimension). NVIDIA GeForce RTX 5080 (driver 621.01) + AMD Radeon 610M iGPU (driver 32.0.13018.6), Windows 11, MSVC (VS BuildTools 18) + Ninja, RelWithDebInfo, Vulkan SDK headers fetched. Tested head 9366e54f (base 03b09a08).

Build: clean (a transient LNK1163 invalid selection for COMDAT section on one link cleared on a Ninja retry; no source error).

Targeted, --repeat until-fail:3:

  • loader_tls_index0, loader_tls_index0_threads, loader_tls_index0_noreserve, run_tiny_tls_ga, run_tiny_tls_clone_cleanup: all pass x3.
  • Existing loader_tls, loader, pe_loader, pe_loader_bounds: pass x3 (no regression in the PE loader / TLS path this PR rewrites).

Full suite (ctest -C RelWithDebInfo -j 6, excluding the 4 window-showing tests dxgi_swapchain|d3d12_present|vk_presenter_sync|xbox_present):

  • NVIDIA RTX 5080: 155/155 passed, 0 failed.
  • AMD Radeon 610M iGPU (LEONIDA_VK_DEVICE=Radeon): 155/155 passed, 0 failed.

The PR's unstable CI state did not reproduce locally.

Synthetic fixtures only, no game files. AI-assisted (opencode); runs on my machine.

@Exopus-0x65f7ad0

Copy link
Copy Markdown

Tested 9366e54f on Windows 11 (26300), RTX 5060 Ti / 621.14, MSVC 14.51 (VS 2026), Vulkan SDK 1.4.363.0, RelWithDebInfo, built from an empty folder with -DLEONIDA_LLVM_MC.

  • -R "loader|tls|run_tiny" --repeat until-fail:30 (serial): passes, 20/20 each round.

  • Full ctest -j4 (with LEONIDA_VK_VALIDATION=1): loader_tls fails, and it does so deterministically under -j: ctest -R "loader|tls|run_tiny" -j4 --repeat until-fail:10 failed 3 runs out of 3 on this branch, always at

    FAIL the purge skipped the clone whose owner process is still alive

    The same command on main passed 3 out of 3.

Cause: the test's "live" owner isn't alive. It's cmd.exe /c timeout /t 30 /nobreak > nul, and timeout.exe exits at once when its input is redirected ("Error: input redirection is not supported, exiting the process immediately", 40 ms, exit 1, checked here with a redirected-stdin Process.Start), which is what ctest's children get under -j. On main, process_alive only needed OpenProcess to succeed, and the test holds the child's handle, so the dead "live" child still counted as alive. This PR's exit-code check is right and exposes it.

Fix in the test (not in the purge): create the live child suspended, so it's alive until the destructor terminates it, whatever its input:

diff --git a/runtime/test/loader_tls_test.cpp b/runtime/test/loader_tls_test.cpp
index 6d5a06dd..4fcedf98 100644
--- a/runtime/test/loader_tls_test.cpp
+++ b/runtime/test/loader_tls_test.cpp
@@ -492,17 +492,20 @@ void test_orphan_slot_generation_reuse(const fs::path& dll) {
     check(td() == 0, "orphaned worker exit does not dispatch DLL_THREAD_DETACH to the new generation's module");
 }
 
-// Spawns cmd.exe to obtain one guaranteed-dead PID and one guaranteed-live one for the purge-ownership checks.
+// Spawns cmd.exe to obtain one guaranteed-dead PID and one guaranteed-live one for the purge-ownership checks. The
+// live one is created suspended: it stays alive until the destructor ends it, whatever its standard input is. (A
+// `timeout /t 30` child is not: timeout.exe exits at once, "input redirection is not supported", when ctest runs the
+// test with redirected input, as it does under -j, so the "live" owner was already dead.)
 struct ChildProcess {
     HANDLE process = nullptr;
     DWORD pid = 0;
-    explicit ChildProcess(const wchar_t* args) {
+    explicit ChildProcess(const wchar_t* args, bool suspended = false) {
         STARTUPINFOW si{};
         si.cb = sizeof(si);
         PROCESS_INFORMATION pi{};
         std::wstring cmd = std::wstring(L"cmd.exe ") + args;
-        if (!CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si,
-                            &pi))
+        if (!CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE,
+                            CREATE_NO_WINDOW | (suspended ? CREATE_SUSPENDED : 0), nullptr, nullptr, &si, &pi))
             throw std::runtime_error("CreateProcessW for cmd.exe failed");
         CloseHandle(pi.hThread);
         process = pi.hProcess;
@@ -546,7 +549,7 @@ void test_purge_ownership_scoping(const fs::path& dll, const fs::path& temp) {
     std::printf("\n-- startup purge deletes only ownerless clones --\n");
     ChildProcess dead(L"/c exit 0");
     dead.wait_exit();
-    ChildProcess live(L"/c timeout /t 30 /nobreak > nul");
+    ChildProcess live(L"/c exit 0", true);  // suspended: alive until the end of the test
 
     const fs::path clone_root = fs::temp_directory_path();
     // An own-PID name stands in for a leftover of a dead run whose PID this process reused: the sweep runs before

With it, -R "loader|tls|run_tiny" -j4 --repeat until-fail:10: 3 runs out of 3 pass (20/20). I haven't pushed anything to your branch; take it if you agree.

Everything else in the full run passed (the usual skips: shader_library_corpus, bink_*, gameinput, d3d12_rgb9e5_rtv, d3d12_first_light), 0 VUIDs.

AI-assisted (Claude Code).

@Hanioe2

Hanioe2 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

I checked whether the existing TEST-899 fixture fix (#4091) also works with RT-259 on native Windows 11 (26200), MSVC 19.44.35227, and the VS 2022 generator (RelWithDebInfo).

This confirms that the already-open #4091 fixture change is compatible with the process-liveness check in RT-259 on this MSVC setup. Native Windows and synthetic fixtures only.

AI-assisted.

@FZNull

FZNull commented Nov 23, 2026

Copy link
Copy Markdown

Tested 9366e54f on NVIDIA GeForce RTX 4060, Windows 11 build 26300 (loader-only change, no GPU path): pass.

Clean worktree at 9366e54f on main 03b09a08. MSVC 19.50.35726 + CMake/Ninja, RelWithDebInfo; cmake --build runtime/build --parallel 6 -> rc 0, 791.8 s.

  • ctest --test-dir runtime/build --no-tests=error --output-on-failure: 100% tests passed out of 160, 0 failed (161 registered: 8 environment skips and 1 disabled gameinput), 346.4 s, exit 0. loader_tls_index0, loader_tls_index0_threads, loader_tls_index0_noreserve, run_tiny_tls_ga and run_tiny_tls_clone_cleanup pass, as does every run_tiny_* test.
  • ctest ... -R "loader_tls|run_tiny" --repeat until-fail:30: 100% of 17 tests, 30/30 rounds, 77.0 s, exit 0.
  • Parallel ctest -j 8: 160/160 passed, 88.5 s, exit 0. An earlier -j 8 run had xbox_present fail transiently with VK_ERROR_FORMAT_NOT_SUPPORTED while other GPU/swapchain tests ran concurrently; it passes serially and the rerun is clean, so it is unrelated to this change.
  • The standard-library Python loop from .github/workflows/ci.yml: 295 of 297 files pass; tests/test_check_no_game_data.py (PermissionError WinError 5 removing a temp .git object) and tests/test_saves.py (os.readlink returns the \\?\ prefix) fail identically on clean main 03b09a08.

The PR's negative control (the new test failing against main's loader) was not reproduced here because that needs a main-loader build of the test binary; the new tests pass on this one. No game data is involved; the fixtures are the checked-in synthetic tiny_* ones.

AI-assisted.

@mariuslozo-boop

Copy link
Copy Markdown
Author

Thanks for the test reports.

AI-assisted (Claude Code).

@Ayinaki

Ayinaki commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested 28ea6b9 on Windows 10.0.26200, MSVC 14.52 (Visual Studio 18 2026, x64, RelWithDebInfo): pass. No GPU path in these targets.

Built loader_tls_index0_test, tiny_tls_ga, tiny_tls, tiny_thread_hook, gta6rt_tls_host and gta6rt from this head, then ran ctest -R "loader_tls_index0|run_tiny_tls":

1/5 loader_tls_index0 ............ Passed
2/5 loader_tls_index0_threads .... Passed
3/5 loader_tls_index0_noreserve .. Passed
4/5 run_tiny_tls_ga .............. Passed
5/5 run_tiny_tls_clone_cleanup ... Passed
100% tests passed, 0 tests failed out of 5

That is 5/5 on three consecutive runs of the same set (the reservation is once per process, so the runs/threads/noreserve scenarios are separate processes as intended).

@abilliontokens

Copy link
Copy Markdown
Contributor

Tested 28ea6b971ba229e8caeb7bf4a50f263224b448fb on NVIDIA GeForce RTX 5060 Ti (621.24, Windows 11): pass.

Worktree at the PR head, runtime built with scripts/build_runtime.ps1 (MSVC 14.44, RelWithDebInfo). This is a loader/TLS change with no GPU path; the affected CTest subset is the loader and tiny-game set, run on Windows (the RTX 5060 Ti was pinned for the session but these tests do not touch Vulkan).

Commands and results:

ctest --test-dir runtime/build -R 'loader_tls|run_tiny' --output-on-failure
  -> 19/19 passed (incl. run_tiny_tls_ga, run_tiny_tls_clone_cleanup, run_tiny_game_tls)
ctest --test-dir runtime/build -R 'loader_tls_index0' --output-on-failure
  -> 3/3 passed (loader_tls_index0, loader_tls_index0_threads, loader_tls_index0_noreserve)

python -I -m compileall -q make_game.py tools tests is clean. Synthetic fixtures only, no game files.

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.

9 participants