upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
authormariuslozo-boop <254631011+mariuslozo-boop@users.noreply.github.com>2026-11-23 00:12:40 +0100
committermariuslozo-boop <254631011+mariuslozo-boop@users.noreply.github.com>2026-11-23 01:38:19 +0100
commit66a7dbc1cd49cc29b34ceeab3020d42ca85f03d2 (patch)
tree27a5f9dd2ba27a5f230e126e1a954aa8bd16edee /runtime
parent03b09a086592a197db64d91655c6e65c30764d96 (diff)
Loader: a mapped executable owns module TLS index 0
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>
Diffstat (limited to 'runtime')
-rw-r--r--runtime/CMakeLists.txt31
-rw-r--r--runtime/README.md31
-rw-r--r--runtime/shims/startup_trace.h15
-rw-r--r--runtime/src/pe_loader.cpp454
-rw-r--r--runtime/src/pe_loader.h5
-rw-r--r--runtime/src/tls_host.cpp5
-rw-r--r--runtime/test/check_tls_index0.cmake27
-rw-r--r--runtime/test/fixtures/tiny_tls_ga.cpp35
-rw-r--r--runtime/test/loader_tls_index0_test.cpp358
9 files changed, 893 insertions, 68 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index ed946d115..95a844ab2 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -536,6 +536,32 @@ if(BUILD_TESTING)
536 COMMAND loader_tls_test "$<TARGET_FILE:tiny_tls>" 536 COMMAND loader_tls_test "$<TARGET_FILE:tiny_tls>"
537 ) 537 )
538 538
539 # Module TLS index 0 fixture: an EXE built /GA, so its thread_local reads go straight to
540 # ThreadLocalStoragePointer[0] as a game executable's can. The loader must give a mapped executable index 0;
541 # loader_tls_index0_test maps it next to tiny_tls.dll and run_tiny_tls_ga runs it under gta6rt. Ordinary test
542 # code, no game data. The test checks the /GA code shape only where the compiler is MSVC, which implements /GA.
543 add_executable(tiny_tls_ga test/fixtures/tiny_tls_ga.cpp)
544 target_compile_options(tiny_tls_ga PRIVATE /W4 /permissive- /utf-8 /EHsc /GA)
545 set_target_properties(tiny_tls_ga PROPERTIES
546 RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}"
547 ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}"
548 )
549 add_executable(loader_tls_index0_test
550 test/loader_tls_index0_test.cpp
551 src/pe_loader.cpp
552 shims/registry.cpp
553 )
554 target_include_directories(loader_tls_index0_test PRIVATE
555 ${CMAKE_CURRENT_SOURCE_DIR}/src
556 )
557 target_compile_definitions(loader_tls_index0_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
558 $<$<CXX_COMPILER_ID:MSVC>:LEONIDA_GA_FIXTURE_IS_GA=1>)
559 target_compile_options(loader_tls_index0_test PRIVATE /W4 /permissive- /utf-8 /EHsc)
560 add_dependencies(loader_tls_index0_test tiny_tls_ga tiny_tls gta6rt_tls_host)
561 add_test(NAME loader_tls_index0
562 COMMAND loader_tls_index0_test "$<TARGET_FILE:tiny_tls_ga>" "$<TARGET_FILE:tiny_tls>"
563 )
564
539 # DisableThreadLibraryCalls from a mapped DllMain (shims/library_loader.cpp). The fixture is built without the CRT, so 565 # DisableThreadLibraryCalls from a mapped DllMain (shims/library_loader.cpp). The fixture is built without the CRT, so
540 # DllMain's only work is that one call. No game files. 566 # DllMain's only work is that one call. No game files.
541 add_library(dll_thread_calls SHARED test/fixtures/dll_thread_calls.cpp) 567 add_library(dll_thread_calls SHARED test/fixtures/dll_thread_calls.cpp)
@@ -787,6 +813,11 @@ if(BUILD_TESTING)
787 # The opt-in checks, one test each: thread_local on the game's threads, a C++ exception caught inside the image. 813 # The opt-in checks, one test each: thread_local on the game's threads, a C++ exception caught inside the image.
788 add_test(NAME run_tiny_game_tls COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42 tls) 814 add_test(NAME run_tiny_game_tls COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42 tls)
789 add_test(NAME run_tiny_game_eh COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42 eh) 815 add_test(NAME run_tiny_game_eh COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42 eh)
816 # A /GA executable under --run and --init reads its TLS from slot 0, and the trace names gta6rt.exe as the image
817 # whose index 0 moved.
818 add_test(NAME run_tiny_tls_ga COMMAND ${CMAKE_COMMAND}
819 "-DLOADER=$<TARGET_FILE:gta6rt>" "-DGUEST=$<TARGET_FILE:tiny_tls_ga>" "-DTRACE_DIR=${CMAKE_CURRENT_BINARY_DIR}"
820 "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_tls_index0.cmake")
790 # GAME: is the game folder, absolute, when gta6rt is given a bare image name or `--game-dir .`. 821 # GAME: is the game folder, absolute, when gta6rt is given a bare image name or `--game-dir .`.
791 add_test(NAME run_tiny_game_dir COMMAND ${CMAKE_COMMAND} 822 add_test(NAME run_tiny_game_dir COMMAND ${CMAKE_COMMAND}
792 "-DLOADER=$<TARGET_FILE:gta6rt>" "-DGUEST=$<TARGET_FILE:tiny_game>" 823 "-DLOADER=$<TARGET_FILE:gta6rt>" "-DGUEST=$<TARGET_FILE:tiny_game>"
diff --git a/runtime/README.md b/runtime/README.md
index 23eb2fb97..c739a370c 100644
--- a/runtime/README.md
+++ b/runtime/README.md
@@ -123,6 +123,23 @@ clone of the helper from `%TEMP%\leonida_tls_host_<pid>_<slot>.dll`, so up to 16
123once and a further one is rejected with an error instead of sharing a slot. Images without a TLS 123once and a further one is rejected with an error instead of sharing a slot. Images without a TLS
124directory (or with an all-zero one) load normally. 124directory (or with an all-zero one) load normally.
125 125
126An executable (an image without `IMAGE_FILE_DLL`, the game's EXE under `--run`, `--init` and `--dry-run`) gets
127module TLS index 0 instead, as Windows gives the process EXE. MSVC code built with `/GA` relies on that: it reads
128`ThreadLocalStoragePointer[0]` directly and never loads `_tls_index`. A `thread_local int v = 42;` EXE built
129`/O2 /GA /MD` printed `tls_index=0 value=42` natively but `tls_index=6 value=0` under `gta6rt --run` when it got a
130helper's index. Index 0 belongs to `gta6rt.exe` itself (measured: Windows gives it to the process EXE, the trace event below names
131it, and `gta6rt.exe` has a TLS block, 1350 bytes when measured, and no TLS callbacks), and all of its own TLS reads
132go through `_tls_index`.
133So the first time an executable is mapped, the loader moves `gta6rt.exe`'s block: it loads one more clone
134(`leonida_tls_host_<pid>_home.dll`), stops the other threads, swaps slots 0 and that clone's index on every thread
135and writes the clone's index into `gta6rt.exe`'s `_tls_index`. A thread started later swaps its own two slots in the
136helper's `DLL_THREAD_ATTACH` before anything else runs there. Slot 0 then holds a spare helper block, which the
137executable's template copy replaces on the loading thread, on threads started later, and through
138`install_tls_for_thread()` on older ones, exactly as a DLL's copy replaces a helper's. Both swapped pointers are
139blocks the OS allocated for that thread, and it frees every slot at thread exit, so nothing is swapped back; the move
140stays for the process lifetime and every later executable gets index 0 directly. The startup trace records it once
141(`tls_index0`). DLLs keep the helper indices and work next to the executable as before.
142
126Current limits, by design: 143Current limits, by design:
127 144
128- `load()` runs no image code. Static TLS is data, not code. The TLS index helper is the runtime's own 145- `load()` runs no image code. Static TLS is data, not code. The TLS index helper is the runtime's own
@@ -137,7 +154,18 @@ Current limits, by design:
137 existed before `load()` gets nothing: 154 existed before `load()` gets nothing:
138 call `install_tls_for_thread()` before mapped code runs on it and `uninstall_tls_for_thread()` before it 155 call `install_tls_for_thread()` before mapped code runs on it and `uninstall_tls_for_thread()` before it
139 exits. Mapped DLLs' `DllMain` is not called with thread events. Destroy the `Loader` on the thread that 156 exits. Mapped DLLs' `DllMain` is not called with thread events. Destroy the `Loader` on the thread that
140 called `load()`. 157 called `load()`. The executable's thread events come after the DLLs' ones, for attach and for detach, as
158 Windows orders an EXE's TLS callbacks.
159- One executable holds index 0 at a time. A second one mapped while the first is live gets a helper index and a
160 `[rt] loader: ... does not get module TLS index 0` line on stderr: its `_tls_index` code works, its `/GA` code
161 reads the first one's slot 0. The same happens when the move cannot be made: when no single module holds index
162 0, or when another thread keeps running `gta6rt.exe`'s own code for the 250 ms the move waits (a thread stopped
163 there could be between its load of `_tls_index` and its read of the slot). The next executable tries again.
164- The home clone stays loaded until the process ends (freeing it would free `gta6rt.exe`'s blocks), so its file
165 stays in `%TEMP%` until the next run's clean-up of dead processes' clones deletes it. Runtime code that runs on a
166 new thread before the helper's `DLL_THREAD_ATTACH` (a vectored exception handler during an earlier DLL's thread
167 attach) would read the clone's block in place of `gta6rt.exe`'s; a thread created to skip DLL thread attach never
168 swaps its slots.
141- The TOC of the game's RPF archives is encrypted and is not read here. The loader works on the PE 169- The TOC of the game's RPF archives is encrypted and is not read here. The loader works on the PE
142 files and on any images the caller passes it. 170 files and on any images the caller passes it.
143 171
@@ -290,6 +318,7 @@ from the ANSI code page.
290| `kind` | When | Fields | 318| `kind` | When | Fields |
291|---|---|---| 319|---|---|---|
292| `trace_open` | first line | `pid` | 320| `trace_open` | first line | `pid` |
321| `tls_index0` | the first executable is mapped and module TLS index 0 moves to it (once per process) | `owner` (the image that held index 0, `gta6rt.exe`), `moved_to` (the index its block moved to) |
293| `map` | a module is mapped, bound and protected | `module`, `base`, `size`, `relocated` | 322| `map` | a module is mapped, bound and protected | `module`, `base`, `size`, `relocated` |
294| `tls_callback` | before each TLS callback the Loader runs (process attach and detach; thread events run under the Windows loader lock and are not traced) | `module`, `at` (module+RVA), `reason` | 323| `tls_callback` | before each TLS callback the Loader runs (process attach and detach; thread events run under the Windows loader lock and are not traced) | `module`, `at` (module+RVA), `reason` |
295| `dllmain` | after `DllMain(DLL_PROCESS_ATTACH)` returns | `module`, `result` | 324| `dllmain` | after `DllMain(DLL_PROCESS_ATTACH)` returns | `module`, `result` |
diff --git a/runtime/shims/startup_trace.h b/runtime/shims/startup_trace.h
index 5203837d8..dd0b62c95 100644
--- a/runtime/shims/startup_trace.h
+++ b/runtime/shims/startup_trace.h
@@ -3,14 +3,15 @@
3// One JSON object per line, flushed per event so the file survives a crash. Off by default; every entry point is a 3// One JSON object per line, flushed per event so the file survives a crash. Off by default; every entry point is a
4// single relaxed load when it is off. Events: 4// single relaxed load when it is off. Events:
5// {"seq":1,"t":0.000,"kind":"trace_open"} 5// {"seq":1,"t":0.000,"kind":"trace_open"}
6// {"seq":2,"t":0.001,"kind":"map","module":"a.dll","base":"0x...","size":"0x2000","relocated":false} 6// {"seq":2,"t":0.001,"kind":"tls_index0","owner":"gta6rt.exe","moved_to":4} (first executable mapped, once)
7// {"seq":3,"t":0.002,"kind":"tls_callback","module":"a.dll","at":"a.dll+0x1200","reason":1} 7// {"seq":3,"t":0.001,"kind":"map","module":"a.dll","base":"0x...","size":"0x2000","relocated":false}
8// {"seq":4,"t":0.002,"kind":"dllmain","module":"a.dll","result":1} 8// {"seq":4,"t":0.002,"kind":"tls_callback","module":"a.dll","at":"a.dll+0x1200","reason":1}
9// {"seq":5,"t":0.010,"kind":"unimplemented_call","import":"x.dll!Foo","caller":"a.dll+0x3f10"} (first call only) 9// {"seq":5,"t":0.002,"kind":"dllmain","module":"a.dll","result":1}
10// {"seq":6,"t":0.011,"kind":"debug_string","text":"..."} 10// {"seq":6,"t":0.010,"kind":"unimplemented_call","import":"x.dll!Foo","caller":"a.dll+0x3f10"} (first call only)
11// {"seq":7,"t":0.020,"kind":"exception","code":"0xc0000005","at":"a.dll+0x4a00","access":"read","address":"0x0", 11// {"seq":7,"t":0.011,"kind":"debug_string","text":"..."}
12// {"seq":8,"t":0.020,"kind":"exception","code":"0xc0000005","at":"a.dll+0x4a00","access":"read","address":"0x0",
12// "stack":["a.dll+0x4a00","a.dll+0x2210"]} 13// "stack":["a.dll+0x4a00","a.dll+0x2210"]}
13// {"seq":8,"t":0.030,"kind":"exit","code":0} 14// {"seq":9,"t":0.030,"kind":"exit","code":0}
14// 15//
15// The exception handler is vectored, logs and returns EXCEPTION_CONTINUE_SEARCH: it never changes what the process 16// The exception handler is vectored, logs and returns EXCEPTION_CONTINUE_SEARCH: it never changes what the process
16// does. OutputDebugStringA/W raise DBG_PRINTEXCEPTION_C / DBG_PRINTEXCEPTION_WIDE_C when no debugger is attached, so 17// does. OutputDebugStringA/W raise DBG_PRINTEXCEPTION_C / DBG_PRINTEXCEPTION_WIDE_C when no debugger is attached, so
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index f4ecc0de2..821fc1595 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -2,6 +2,8 @@
2 2
3#include <windows.h> 3#include <windows.h>
4#include <intrin.h> 4#include <intrin.h>
5#include <psapi.h>
6#include <tlhelp32.h>
5 7
6#include <algorithm> 8#include <algorithm>
7#include <array> 9#include <array>
@@ -79,8 +81,25 @@ IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) {
79// reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader 81// reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader
80// clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent 82// clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent
81// module TLS index for each simultaneous module (up to kMaxMappedTlsModules). 83// module TLS index for each simultaneous module (up to kMaxMappedTlsModules).
84//
85// A mapped executable is different: MSVC code built with /GA (an EXE-only optimisation) skips _tls_index and reads
86// TEB->ThreadLocalStoragePointer[0] directly (mov rax, gs:[58h]; mov rax, [rax]), because Windows always gives the
87// process executable module TLS index 0. Measured with a `thread_local int v = 42;` EXE built /O2 /GA /MD: natively
88// tls_index=0 value=42; mapped with a helper index (6) the code still read slot 0 and printed value=0. Index 0 belongs to
89// the runtime's own EXE (gta6rt.exe has a TLS block, 1350 bytes when measured, and no TLS callbacks; each test EXE
90// that links this file has one too), and every TLS read in its disassembly goes through _tls_index (the only direct gs:[58h] read is
91// module_tls_slots below, which wants the array itself). So index 0 is freed by moving the owner:
92// move_index0_owner swaps slots 0 and H of every thread, H being the index of a further helper clone that exists for
93// this, and writes H into the owner's _tls_index. The owner then finds its block through H, and slot 0 holds the
94// helper's spare block, which the mapped executable's copy replaces (kMainImageSlot) exactly as a DLL's copy replaces
95// a helper's. The swap is permanent: both pointers are blocks the OS allocated for this thread, and at thread exit it
96// frees every slot by index whatever block each holds, so nothing has to be swapped back.
82constexpr DWORD kMaxModuleTlsSlots = 64; 97constexpr DWORD kMaxModuleTlsSlots = 64;
83constexpr size_t kMaxMappedTlsModules = 16; 98constexpr size_t kMaxMappedTlsModules = 16;
99// The slot for a mapped executable, which reads module TLS index 0 (see above). Only one at a time; a second
100// executable mapped while one is live gets an ordinary helper slot. kTlsSlotCount sizes the per-slot tables.
101constexpr size_t kMainImageSlot = kMaxMappedTlsModules;
102constexpr size_t kTlsSlotCount = kMaxMappedTlsModules + 1;
84void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); } 103void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); }
85 104
86void __cdecl on_host_thread_event(DWORD reason); 105void __cdecl on_host_thread_event(DWORD reason);
@@ -120,11 +139,21 @@ struct TlsCloneRecord {
120 139
121std::mutex g_tls_alloc_mutex; 140std::mutex g_tls_alloc_mutex;
122std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{}; 141std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{};
123std::array<std::atomic<Module*>, kMaxMappedTlsModules> g_tls_slot_owners{}; 142std::array<std::atomic<Module*>, kTlsSlotCount> g_tls_slot_owners{};
124std::array<std::atomic<uint64_t>, kMaxMappedTlsModules> g_tls_slot_generations{}; 143std::array<std::atomic<uint64_t>, kTlsSlotCount> g_tls_slot_generations{};
125std::atomic<uint64_t> g_next_tls_generation{1}; 144std::atomic<uint64_t> g_next_tls_generation{1};
126std::vector<TlsCloneRecord> g_tls_clones; 145std::vector<TlsCloneRecord> g_tls_clones;
127 146
147// The move of module TLS index 0 (see kMainImageSlot), done at most once per process. `moved` is written under both
148// g_tls_alloc_mutex and an exclusive g_tls_lock, so thread events read it under the shared lock; the other fields are
149// set before it and never change after.
150struct Index0Move {
151 bool moved = false;
152 TlsHostModule home; // the clone whose index now holds the owner's block; never freed
153 DWORD mark = TLS_OUT_OF_INDEXES; // TlsAlloc slot, non-zero on a thread whose slots 0 and home are swapped
154};
155Index0Move g_index0;
156
128// Frees every TLS helper clone this process loaded and deletes its files. load() registers the wrapper with atexit; 157// Frees every TLS helper clone this process loaded and deletes its files. load() registers the wrapper with atexit;
129// the --run path in main() must also call this directly before ExitProcess, which skips the atexit table. Call it 158// the --run path in main() must also call this directly before ExitProcess, which skips the atexit table. Call it
130// only when no mapped code can run again: it unmaps the helper images. 159// only when no mapped code can run again: it unmaps the helper images.
@@ -221,25 +250,23 @@ TlsHostModule load_tls_host_image(const std::filesystem::path& path, bool hook_t
221 return host; 250 return host;
222} 251}
223 252
224// Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock). 253// The primary helper: slot 0's index, and the only helper whose DllMain reports thread events (on_host_thread_event
225TlsHostModule ensure_tls_host(size_t slot) { 254// covers every slot). Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the
226 if (slot >= kMaxMappedTlsModules) return {}; 255// Windows loader lock).
227 if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot]; 256bool ensure_primary_tls_host() {
257 if (g_tls_hosts[0].index != TLS_OUT_OF_INDEXES) return true;
258 const std::filesystem::path primary = tls_host_base_path();
259 if (primary.empty()) return false;
260 g_tls_hosts[0] = load_tls_host_image(primary, true);
261 return g_tls_hosts[0].index != TLS_OUT_OF_INDEXES;
262}
228 263
264// Copies gta6rt_tls_host.dll to "leonida_tls_host_<pid>_<tag>.dll" in the clone directory and loads it, so the OS
265// gives the copy an index of its own. On failure the file is gone again and the result has no index. The caller
266// records the clone (g_tls_clones) if it is to be freed at exit. Same locking rule as ensure_primary_tls_host.
267TlsHostModule load_tls_host_clone(const std::wstring& tag, std::filesystem::path& clone_path) {
229 const std::filesystem::path primary = tls_host_base_path(); 268 const std::filesystem::path primary = tls_host_base_path();
230 if (primary.empty()) return {}; 269 if (primary.empty()) return {};
231
232 if (slot == 0) {
233 g_tls_hosts[0] = load_tls_host_image(primary, true);
234 return g_tls_hosts[0];
235 }
236
237 // Ensure slot 0 is loaded first so thread attach/detach events are hooked.
238 if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) {
239 g_tls_hosts[0] = load_tls_host_image(primary, true);
240 if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) return {};
241 }
242
243 // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem). 270 // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem).
244 const std::filesystem::path dir = tls_host_clone_dir(); 271 const std::filesystem::path dir = tls_host_clone_dir();
245 static bool swept = false; 272 static bool swept = false;
@@ -248,9 +275,8 @@ TlsHostModule ensure_tls_host(size_t slot) {
248 sweep_stale_tls_clones(dir); 275 sweep_stale_tls_clones(dir);
249 std::atexit(&cleanup_tls_clones_at_exit); 276 std::atexit(&cleanup_tls_clones_at_exit);
250 } 277 }
251 const std::wstring name = 278 const std::wstring name = L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + tag + L".dll";
252 L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll"; 279 clone_path = dir / name;
253 const std::filesystem::path clone_path = dir / name;
254 // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll. 280 // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll.
255 const std::filesystem::path staging = clone_path.wstring() + L".new"; 281 const std::filesystem::path staging = clone_path.wstring() + L".new";
256 if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) return {}; 282 if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) return {};
@@ -273,17 +299,29 @@ TlsHostModule ensure_tls_host(size_t slot) {
273 TlsHostModule loaded = load_tls_host_image(clone_path, false); 299 TlsHostModule loaded = load_tls_host_image(clone_path, false);
274 CloseHandle(guard); 300 CloseHandle(guard);
275 301
276 if (loaded.index == TLS_OUT_OF_INDEXES) { 302 if (loaded.index == TLS_OUT_OF_INDEXES) DeleteFileW(clone_path.c_str());
303 return loaded;
304}
305
306// Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock).
307TlsHostModule ensure_tls_host(size_t slot) {
308 if (slot >= kMaxMappedTlsModules) return {};
309 if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot];
310 // Slot 0 is the primary helper; it is loaded first in any case so thread attach/detach events are hooked.
311 if (!ensure_primary_tls_host()) return {};
312 if (slot == 0) return g_tls_hosts[0];
313
314 std::filesystem::path clone_path;
315 TlsHostModule loaded = load_tls_host_clone(std::to_wstring(slot), clone_path);
316 if (loaded.index == TLS_OUT_OF_INDEXES) return {};
317 // Index 0 is the runtime EXE's, and after the move the home clone's index holds that EXE's block.
318 bool taken = loaded.index == 0 || loaded.index == g_index0.home.index;
319 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) taken |= i != slot && g_tls_hosts[i].index == loaded.index;
320 if (taken) {
321 FreeLibrary(loaded.module);
277 DeleteFileW(clone_path.c_str()); 322 DeleteFileW(clone_path.c_str());
278 return {}; 323 return {};
279 } 324 }
280 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) {
281 if (i != slot && g_tls_hosts[i].index == loaded.index) {
282 FreeLibrary(loaded.module);
283 DeleteFileW(clone_path.c_str());
284 return {};
285 }
286 }
287 g_tls_clones.push_back({loaded.module, clone_path}); 325 g_tls_clones.push_back({loaded.module, clone_path});
288 g_tls_hosts[slot] = loaded; 326 g_tls_hosts[slot] = loaded;
289 return g_tls_hosts[slot]; 327 return g_tls_hosts[slot];
@@ -298,11 +336,12 @@ struct ThreadTlsSlot {
298}; 336};
299 337
300// Per-thread installation state for each reserved TLS slot. 338// Per-thread installation state for each reserved TLS slot.
301thread_local std::array<ThreadTlsSlot, kMaxMappedTlsModules> g_thread_tls_slots{}; 339thread_local std::array<ThreadTlsSlot, kTlsSlotCount> g_thread_tls_slots{};
302 340
303// Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared 341// Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared
304// in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows 342// in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows
305// loader lock, which the events run under). 343// loader lock, which the events run under) and for the one-time index-0 move, which lists and stops threads under it
344// with the loader lock already held.
306SRWLOCK g_tls_lock = SRWLOCK_INIT; 345SRWLOCK g_tls_lock = SRWLOCK_INIT;
307struct SharedTlsLock { 346struct SharedTlsLock {
308 SharedTlsLock() { AcquireSRWLockShared(&g_tls_lock); } 347 SharedTlsLock() { AcquireSRWLockShared(&g_tls_lock); }
@@ -317,10 +356,275 @@ struct ExclusiveTlsLock {
317 ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete; 356 ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete;
318}; 357};
319 358
359// x64 TEB fields the move reads and writes on other threads (the same offsets on Wine): ThreadLocalStoragePointer,
360// and TlsSlots[64], the array TlsGetValue reads for an index below 64.
361constexpr size_t kTebTlsPointer = 0x58;
362constexpr size_t kTebTlsSlots = 0x1480;
363
364// The image that owns module TLS index 0: the one whose TLS directory's AddressOfIndex holds 0. Only images the
365// Windows loader mapped are listed, so their headers are read unchecked.
366struct Index0Owner {
367 const uint8_t* base = nullptr;
368 size_t size = 0;
369 DWORD* index = nullptr; // the owner's _tls_index
370 std::string name; // UTF-8 file name, for the trace and messages
371};
372
373std::string module_file_name(HMODULE module) {
374 wchar_t path[MAX_PATH];
375 const DWORD n = GetModuleFileNameW(module, path, MAX_PATH);
376 if (!n || n >= MAX_PATH) return "?";
377 const wchar_t* name = path;
378 for (const wchar_t* p = path; *p; ++p)
379 if (*p == L'\\' || *p == L'/') name = p + 1;
380 const int bytes = WideCharToMultiByte(CP_UTF8, 0, name, -1, nullptr, 0, nullptr, nullptr);
381 if (bytes <= 1) return "?";
382 std::string out(static_cast<size_t>(bytes - 1), '\0');
383 WideCharToMultiByte(CP_UTF8, 0, name, -1, out.data(), bytes, nullptr, nullptr);
384 return out;
385}
386
387// Empty on success, else why index 0 has no single movable owner.
388std::string find_index0_owner(Index0Owner& owner) {
389 std::vector<HMODULE> modules(256);
390 DWORD needed = 0;
391 for (;;) {
392 const DWORD bytes = static_cast<DWORD>(modules.size() * sizeof(HMODULE));
393 if (!EnumProcessModules(GetCurrentProcess(), modules.data(), bytes, &needed))
394 return "the process's modules cannot be listed";
395 if (needed <= bytes) break;
396 modules.resize(needed / sizeof(HMODULE) + 16); // a DLL loaded in between needs room too
397 }
398 modules.resize(needed / sizeof(HMODULE));
399 int found = 0;
400 HMODULE owner_module = nullptr;
401 for (HMODULE module : modules) {
402 auto* base = reinterpret_cast<uint8_t*>(module);
403 auto* nt = at<IMAGE_NT_HEADERS64>(base, reinterpret_cast<IMAGE_DOS_HEADER*>(base)->e_lfanew);
404 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS);
405 if (!dir.Size || !dir.VirtualAddress) continue;
406 auto* tls = at<IMAGE_TLS_DIRECTORY64>(base, dir.VirtualAddress);
407 if (!tls->AddressOfIndex || *reinterpret_cast<DWORD*>(tls->AddressOfIndex) != 0) continue;
408 ++found;
409 owner_module = module;
410 owner.base = base;
411 owner.size = nt->OptionalHeader.SizeOfImage;
412 owner.index = reinterpret_cast<DWORD*>(tls->AddressOfIndex);
413 }
414 if (found == 0) return "no module holds it";
415 if (found > 1) return "more than one module reports it";
416 owner.name = module_file_name(owner_module);
417 // The helpers are loaded after the EXE, so one of them holds index 0 only in a process whose EXE has no TLS; DLL
418 // slot 0 then already maps DLLs there.
419 for (const auto& host : g_tls_hosts)
420 if (host.module == owner_module) return "it belongs to gta6rt_tls_host.dll";
421 return {};
422}
423
424using NtQueryInformationThreadFn = LONG(NTAPI*)(HANDLE, int, PVOID, ULONG, PULONG);
425using LdrLockLoaderLockFn = LONG(NTAPI*)(ULONG, ULONG*, ULONG_PTR*);
426using LdrUnlockLoaderLockFn = LONG(NTAPI*)(ULONG, ULONG_PTR);
427
428struct ThreadBasicInformation { // THREAD_BASIC_INFORMATION (NtQueryInformationThread class 0)
429 LONG exit_status;
430 PVOID teb;
431 PVOID process_id;
432 PVOID thread_id;
433 ULONG_PTR affinity;
434 LONG priority;
435 LONG base_priority;
436};
437
438struct OtherThread {
439 HANDLE handle = nullptr;
440 uint8_t* teb = nullptr;
441 bool suspended = false;
442};
443
444enum class SwapResult { Done, Busy, Failed };
445
446// One attempt at the swap, with every other thread of the process stopped. The exclusive g_tls_lock keeps every
447// thread event out, and with it the adoption on threads that start meanwhile. Busy: a thread was stopped inside the
448// owner's code, perhaps between its load of _tls_index and its read of the slot, so the caller resumes everything and
449// tries again. Measured in ntdll (Windows 11 26300): a starting thread fills its whole TLS array before it stores it in
450// its TEB (LdrpAllocateTls), an ending one clears that TEB field before it frees the blocks (LdrpFreeTls), and
451// LoadLibrary of a DLL with TLS has the kernel update every thread's array in one system call (NtSetInformationProcess,
452// class 0x23), which GetThreadContext below waits out on the calling thread. So an array seen here is complete and
453// still owned; a thread with none yet gets one with the owner's block at 0 and adopts the swap in DLL_THREAD_ATTACH.
454// Wine builds a starting thread's array and grows every thread's array for LoadLibrary in user mode, both under its
455// loader lock, so the Windows loader lock is held as well; it comes before g_tls_lock, the order the thread events
456// (run under it) take them in.
457SwapResult swap_index0_on_all_threads(const Index0Owner& owner, DWORD home, DWORD mark, std::string& error) {
458 static const HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
459 static const auto query =
460 reinterpret_cast<NtQueryInformationThreadFn>(GetProcAddress(ntdll, "NtQueryInformationThread"));
461 static const auto lock_loader = reinterpret_cast<LdrLockLoaderLockFn>(GetProcAddress(ntdll, "LdrLockLoaderLock"));
462 static const auto unlock_loader =
463 reinterpret_cast<LdrUnlockLoaderLockFn>(GetProcAddress(ntdll, "LdrUnlockLoaderLock"));
464 if (!query || !lock_loader || !unlock_loader) {
465 error = "ntdll lacks NtQueryInformationThread or the loader lock calls";
466 return SwapResult::Failed;
467 }
468 ULONG disposition = 0;
469 ULONG_PTR cookie = 0;
470 if (lock_loader(0, &disposition, &cookie) < 0) {
471 error = "the Windows loader lock cannot be taken";
472 return SwapResult::Failed;
473 }
474 struct LoaderUnlock {
475 ULONG_PTR cookie;
476 ~LoaderUnlock() { unlock_loader(0, cookie); }
477 } loader_unlock{cookie};
478 ExclusiveTlsLock lock;
479
480 // Listed under the lock: a thread that starts later runs its DLL_THREAD_ATTACH after the swap and adopts it there
481 // (adopt_index0_move_on_this_thread).
482 std::vector<OtherThread> threads;
483 {
484 HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
485 if (snapshot == INVALID_HANDLE_VALUE) {
486 error = "the process's threads cannot be listed";
487 return SwapResult::Failed;
488 }
489 THREADENTRY32 entry{};
490 entry.dwSize = sizeof(entry);
491 const DWORD pid = GetCurrentProcessId(), self = GetCurrentThreadId();
492 for (BOOL more = Thread32First(snapshot, &entry); more; more = Thread32Next(snapshot, &entry)) {
493 if (entry.th32OwnerProcessID != pid || entry.th32ThreadID == self) continue;
494 HANDLE h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION | SYNCHRONIZE,
495 FALSE, entry.th32ThreadID);
496 if (!h) continue; // ended since the snapshot
497 ThreadBasicInformation info{};
498 if (query(h, 0, &info, sizeof(info), nullptr) < 0 || !info.teb) {
499 CloseHandle(h);
500 continue;
501 }
502 threads.push_back({h, static_cast<uint8_t*>(info.teb)});
503 }
504 CloseHandle(snapshot);
505 }
506
507 // From the first SuspendThread to the last ResumeThread nothing below allocates or takes a lock: a stopped thread
508 // can hold the heap lock.
509 bool busy = false;
510 for (auto& t : threads) {
511 if (SuspendThread(t.handle) == static_cast<DWORD>(-1)) {
512 if (WaitForSingleObject(t.handle, 0) == WAIT_OBJECT_0) continue; // it ended; its TEB is gone
513 busy = true; // a live thread left unswapped would read the helper's block for the owner's
514 break;
515 }
516 t.suspended = true;
517 // SuspendThread only asks; GetThreadContext returns once the thread has stopped.
518 CONTEXT context{};
519 context.ContextFlags = CONTEXT_CONTROL;
520 if (!GetThreadContext(t.handle, &context)) {
521 if (WaitForSingleObject(t.handle, 0) == WAIT_OBJECT_0) continue; // it ended; its TEB is gone
522 busy = true;
523 break;
524 }
525 if (context.Rip - reinterpret_cast<uint64_t>(owner.base) < owner.size) {
526 busy = true;
527 break;
528 }
529 }
530 if (!busy) {
531 for (auto& t : threads) {
532 if (!t.suspended || WaitForSingleObject(t.handle, 0) == WAIT_OBJECT_0) continue;
533 // No array yet: the thread is still starting, and its DLL_THREAD_ATTACH adopts the swap.
534 auto** slots = *reinterpret_cast<void***>(t.teb + kTebTlsPointer);
535 if (!slots) continue;
536 std::swap(slots[0], slots[home]);
537 reinterpret_cast<void**>(t.teb + kTebTlsSlots)[mark] = reinterpret_cast<void*>(1);
538 }
539 // The owner's code reads the new index from here on, this thread's included.
540 void** own = module_tls_slots();
541 std::swap(own[0], own[home]);
542 TlsSetValue(mark, reinterpret_cast<void*>(1));
543 *owner.index = home;
544 g_index0.moved = true;
545 }
546 for (auto& t : threads) {
547 if (t.suspended) ResumeThread(t.handle);
548 CloseHandle(t.handle);
549 }
550 return busy ? SwapResult::Busy : SwapResult::Done;
551}
552
553// Frees module TLS index 0 for a mapped executable (see kMainImageSlot): loads the home clone, then swaps slots 0
554// and home on every thread and writes home into the owner's _tls_index. Empty on success (also when it was done
555// before), else why not; nothing has changed then. Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock
556// held. Never inlined, so the caller reads its own thread_local data through the new index once this returns.
557__declspec(noinline) std::string move_index0_owner() {
558 if (g_index0.moved) return {};
559 if (!ensure_primary_tls_host()) return "gta6rt_tls_host.dll is missing or has no module TLS index";
560 Index0Owner owner;
561 if (std::string why = find_index0_owner(owner); !why.empty()) return "module TLS index 0: " + why;
562 if (g_index0.home.index == TLS_OUT_OF_INDEXES) {
563 // Kept loaded for the process lifetime: FreeLibrary would make the OS free every thread's slot at its index,
564 // which holds the owner's block from now on. Not in g_tls_clones for that reason; the sweep of a later run
565 // deletes the file once this process has ended.
566 std::filesystem::path path;
567 TlsHostModule home = load_tls_host_clone(L"home", path);
568 if (home.index == TLS_OUT_OF_INDEXES) return "the TLS helper clone for index 0 cannot be loaded";
569 bool taken = home.index == 0 || home.index >= kMaxModuleTlsSlots;
570 for (const auto& host : g_tls_hosts) taken |= host.index == home.index;
571 if (taken) {
572 FreeLibrary(home.module);
573 DeleteFileW(path.c_str());
574 return "the TLS helper clone for index 0 got an unusable index";
575 }
576 g_index0.home = home;
577 }
578 if (g_index0.mark == TLS_OUT_OF_INDEXES) {
579 const DWORD mark = TlsAlloc();
580 if (mark == TLS_OUT_OF_INDEXES) return "no TlsAlloc slot is free";
581 if (mark >= 64) { // another thread's TlsSlots can only be written for the first 64
582 TlsFree(mark);
583 return "no TlsAlloc slot below 64 is free";
584 }
585 g_index0.mark = mark;
586 }
587 // _tls_index sits in .data; made writable first in case a linker merged it into a read-only section.
588 DWORD old_protect = 0;
589 if (!VirtualProtect(owner.index, sizeof(DWORD), PAGE_READWRITE, &old_protect))
590 return "the owner's _tls_index cannot be written";
591 // A thread caught in the owner's code usually leaves it within microseconds; one that keeps computing there for
592 // the whole budget makes the move give up (the executable then maps with a helper index), and a later executable
593 // tries again.
594 std::string error;
595 SwapResult result = SwapResult::Busy;
596 const ULONGLONG give_up = GetTickCount64() + 250;
597 for (bool first = true; result == SwapResult::Busy && (first || GetTickCount64() < give_up); first = false) {
598 if (!first) Sleep(1);
599 result = swap_index0_on_all_threads(owner, g_index0.home.index, g_index0.mark, error);
600 }
601 VirtualProtect(owner.index, sizeof(DWORD), old_protect, &old_protect);
602 if (result == SwapResult::Busy) return "a thread kept running inside " + owner.name;
603 if (result == SwapResult::Failed) return error;
604 if (startup_trace::enabled())
605 startup_trace::event("tls_index0", "\"owner\":" + startup_trace::quote(owner.name) +
606 ",\"moved_to\":" + std::to_string(g_index0.home.index));
607 return {};
608}
609
610// Puts a thread started after the move in the same state as the threads the move swapped. Called first in this
611// thread's DLL_THREAD_ATTACH, under the shared lock, before anything reads the runtime's own thread_local data: the
612// OS built this thread's array with the owner's block at 0 and the home clone's at home. DLLs loaded before the
613// helper get their DLL_THREAD_ATTACH earlier, and the EXE's TLS callbacks run later (measured on Windows 11 26300:
614// DllMain of every DLL, then the EXE's callbacks, for attach and for detach), so only runtime code a vectored
615// exception handler runs in that window would read the home clone's block in place of its own.
616void adopt_index0_move_on_this_thread() {
617 if (!g_index0.moved || TlsGetValue(g_index0.mark)) return;
618 void** slots = module_tls_slots();
619 if (!slots) return;
620 std::swap(slots[0], slots[g_index0.home.index]);
621 TlsSetValue(g_index0.mark, reinterpret_cast<void*>(1));
622}
623
320// Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this 624// Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this
321// thread's record, so it also works after the module that installed the copy is gone. 625// thread's record, so it also works after the module that installed the copy is gone.
322void release_thread_slot(size_t slot) { 626void release_thread_slot(size_t slot) {
323 if (slot >= kMaxMappedTlsModules) return; 627 if (slot >= kTlsSlotCount) return;
324 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 628 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
325 if (!entry.module && !entry.block) return; 629 if (!entry.module && !entry.block) return;
326 if (entry.block) { 630 if (entry.block) {
@@ -333,7 +637,7 @@ void release_thread_slot(size_t slot) {
333} 637}
334 638
335void install_thread_block(Module& m) { 639void install_thread_block(Module& m) {
336 if (m.tls_slot >= kMaxMappedTlsModules) return; 640 if (m.tls_slot >= kTlsSlotCount) return;
337 const size_t slot = m.tls_slot; 641 const size_t slot = m.tls_slot;
338 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 642 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
339 if (entry.module == &m && entry.generation == m.tls_generation) return; 643 if (entry.module == &m && entry.generation == m.tls_generation) return;
@@ -374,7 +678,7 @@ void install_thread_block(Module& m) {
374} 678}
375 679
376void uninstall_thread_block(Module& m) { 680void uninstall_thread_block(Module& m) {
377 if (m.tls_slot >= kMaxMappedTlsModules) return; 681 if (m.tls_slot >= kTlsSlotCount) return;
378 const size_t slot = m.tls_slot; 682 const size_t slot = m.tls_slot;
379 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 683 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
380 if (entry.module != &m || entry.generation != m.tls_generation) return; 684 if (entry.module != &m || entry.generation != m.tls_generation) return;
@@ -407,16 +711,17 @@ void run_callbacks(Module& m, uint32_t reason, bool trace = false) {
407 } 711 }
408} 712}
409 713
410// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under 714// The body of on_host_thread_event, called with the shared lock held. A new thread gets its own copy of each active
411// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an 715// TLS owner's template; an ending one gives each helper's block back before the Windows loader frees it. TLS callbacks
412// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events 716// get the thread events only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them.
413// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. 717// The mapped executable comes last both ways, as Windows runs an EXE's TLS callbacks after every DllMain for attach
414void __cdecl on_host_thread_event(DWORD reason) { 718// and for detach (measured on Windows 11 26300); kMainImageSlot is the highest slot, so attach runs in slot order and
415 SharedTlsLock lock; 719// detach runs the DLL slots in reverse and that slot after them.
720__declspec(noinline) void deliver_thread_event(DWORD reason) {
416 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events 721 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events
417 // away from the other slots. Nothing may leave DllMain. 722 // away from the other slots. Nothing may leave DllMain.
418 if (reason == DLL_THREAD_ATTACH) { 723 if (reason == DLL_THREAD_ATTACH) {
419 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { 724 for (size_t slot = 0; slot < kTlsSlotCount; ++slot) {
420 Module* m = g_tls_slot_owners[slot].load(); 725 Module* m = g_tls_slot_owners[slot].load();
421 if (!m) continue; 726 if (!m) continue;
422 try { 727 try {
@@ -429,7 +734,8 @@ void __cdecl on_host_thread_event(DWORD reason) {
429 } 734 }
430 } 735 }
431 } else if (reason == DLL_THREAD_DETACH) { 736 } else if (reason == DLL_THREAD_DETACH) {
432 for (size_t i = kMaxMappedTlsModules; i-- > 0;) { 737 for (size_t step = 0; step < kTlsSlotCount; ++step) {
738 const size_t i = step < kMaxMappedTlsModules ? kMaxMappedTlsModules - 1 - step : kMainImageSlot;
433 Module* m = g_tls_slot_owners[i].load(); 739 Module* m = g_tls_slot_owners[i].load();
434 if (m && g_thread_tls_slots[i].module == m && 740 if (m && g_thread_tls_slots[i].module == m &&
435 g_thread_tls_slots[i].generation == m->tls_generation) { 741 g_thread_tls_slots[i].generation == m->tls_generation) {
@@ -449,6 +755,15 @@ void __cdecl on_host_thread_event(DWORD reason) {
449 } 755 }
450} 756}
451 757
758// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under
759// the Windows loader lock, on that thread. It reads no thread_local data itself: on a new thread the index-0 move has
760// to be adopted before the runtime's own TLS is where its _tls_index says (deliver_thread_event is not inlined).
761void __cdecl on_host_thread_event(DWORD reason) {
762 SharedTlsLock lock;
763 if (reason == DLL_THREAD_ATTACH) adopt_index0_move_on_this_thread();
764 deliver_thread_event(reason);
765}
766
452// The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used. 767// The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used.
453bool prefer_host_copy(const std::string& dll) { 768bool prefer_host_copy(const std::string& dll) {
454 static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll", 769 static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll",
@@ -594,7 +909,7 @@ Loader::~Loader() {
594 shims::remove_module_lookup(this); 909 shims::remove_module_lookup(this);
595 for (auto* m : order_) { 910 for (auto* m : order_) {
596 // TLS state must go away before the image and its TLS block are unmapped. 911 // TLS state must go away before the image and its TLS block are unmapped.
597 if (m->tls_index != kNoTlsIndex && m->tls_slot < kMaxMappedTlsModules) { 912 if (m->tls_index != kNoTlsIndex && m->tls_slot < kTlsSlotCount) {
598 // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a 913 // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a
599 // thread that still holds a copy frees it when it ends (on_host_thread_event). 914 // thread that still holds a copy frees it when it ends (on_host_thread_event).
600 { 915 {
@@ -914,7 +1229,7 @@ Module& Loader::map_image(const std::filesystem::path& path) {
914// Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to 1229// Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to
915// gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone 1230// gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone
916// getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than 1231// getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than
917// silently sharing (and corrupting) a slot. 1232// silently sharing (and corrupting) a slot. An executable takes index 0 instead (kMainImageSlot), as on Windows.
918void Loader::initialize_tls(Module& m) { 1233void Loader::initialize_tls(Module& m) {
919 auto* tls = tls_directory(m); 1234 auto* tls = tls_directory(m);
920 if (!tls) return; 1235 if (!tls) return;
@@ -938,26 +1253,47 @@ void Loader::initialize_tls(Module& m) {
938 1253
939 if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); 1254 if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array");
940 1255
941 size_t slot = kMaxMappedTlsModules; 1256 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
1257 const bool executable = (nt->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0;
1258
1259 size_t slot = kTlsSlotCount;
942 DWORD index = TLS_OUT_OF_INDEXES; 1260 DWORD index = TLS_OUT_OF_INDEXES;
943 { 1261 {
944 std::lock_guard alloc_lock(g_tls_alloc_mutex); 1262 std::lock_guard alloc_lock(g_tls_alloc_mutex);
945 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { 1263 if (executable) {
946 if (g_tls_slot_owners[i].load() == nullptr) { 1264 // Load/clone OUTSIDE ExclusiveTlsLock, as below; the move takes that lock itself.
947 slot = i; 1265 std::string why = move_index0_owner();
948 break; 1266 if (why.empty() && g_tls_slot_owners[kMainImageSlot].load() == nullptr) {
1267 slot = kMainImageSlot;
1268 index = 0;
1269 } else {
1270 // Mapped on as a DLL is: code that reads _tls_index works, /GA code reads another image's slot 0.
1271 if (why.empty()) why = "another mapped executable holds it";
1272 std::fprintf(stderr,
1273 "[rt] loader: %s does not get module TLS index 0 (%s); its code built with /GA will not "
1274 "find its TLS\n",
1275 m.name.c_str(), why.c_str());
1276 }
1277 }
1278 if (slot == kTlsSlotCount) {
1279 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) {
1280 if (g_tls_slot_owners[i].load() == nullptr) {
1281 slot = i;
1282 break;
1283 }
949 } 1284 }
1285 if (slot >= kMaxMappedTlsModules)
1286 throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) +
1287 " manually mapped static TLS slots are in use");
1288
1289 // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with
1290 // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock).
1291 index = ensure_tls_host(slot).index;
1292 if (index == TLS_OUT_OF_INDEXES)
1293 throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index");
1294 if (index >= kMaxModuleTlsSlots)
1295 throw std::runtime_error(m.name + ": reserved TLS index is out of range");
950 } 1296 }
951 if (slot >= kMaxMappedTlsModules)
952 throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) +
953 " manually mapped static TLS slots are in use");
954
955 // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with
956 // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock).
957 index = ensure_tls_host(slot).index;
958 if (index == TLS_OUT_OF_INDEXES)
959 throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index");
960 if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range");
961 1297
962 // The fields are complete before a thread event can see the owner. 1298 // The fields are complete before a thread event can see the owner.
963 ExclusiveTlsLock lock; 1299 ExclusiveTlsLock lock;
diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h
index 8fb24349f..7b4e76b37 100644
--- a/runtime/src/pe_loader.h
+++ b/runtime/src/pe_loader.h
@@ -48,10 +48,13 @@ struct Module {
48 // the image's _tls_index. tls_index names TEB->ThreadLocalStoragePointer[tls_index], the array 48 // the image's _tls_index. tls_index names TEB->ThreadLocalStoragePointer[tls_index], the array
49 // __declspec(thread) reads; it is not a TlsAlloc slot. The loader reserves distinct indices by loading 49 // __declspec(thread) reads; it is not a TlsAlloc slot. The loader reserves distinct indices by loading
50 // gta6rt_tls_host.dll (and cloning it on demand for additional simultaneous TLS modules, up to 16 at a time). 50 // gta6rt_tls_host.dll (and cloning it on demand for additional simultaneous TLS modules, up to 16 at a time).
51 // An executable gets index 0, as Windows gives the process EXE, because code built with /GA reads slot 0 without
52 // _tls_index: the first time one is mapped, the runtime's own EXE moves its block to a helper clone's index on
53 // every thread. Only one executable holds index 0 at a time; another one mapped meanwhile gets a helper index.
51 // Every thread started after load() gets its own copy through the helper's DLL_THREAD_ATTACH, and gives it back 54 // Every thread started after load() gets its own copy through the helper's DLL_THREAD_ATTACH, and gives it back
52 // at DLL_THREAD_DETACH; install_tls_for_thread() is for threads that already existed. 55 // at DLL_THREAD_DETACH; install_tls_for_thread() is for threads that already existed.
53 uint32_t tls_index = kNoTlsIndex; 56 uint32_t tls_index = kNoTlsIndex;
54 uint32_t tls_slot = kNoTlsIndex; // index into the loader's reserved TLS-host slot pool 57 uint32_t tls_slot = kNoTlsIndex; // index into the loader's reserved TLS-host slot pool ; 16 is index 0, an executable's
55 uint64_t tls_generation = 0; // unique token per TLS initialisation, distinguishing reused slots/addresses 58 uint64_t tls_generation = 0; // unique token per TLS initialisation, distinguishing reused slots/addresses
56 void* tls_block = nullptr; // calling thread's copy of the image's template 59 void* tls_block = nullptr; // calling thread's copy of the image's template
57 void* tls_saved_block = nullptr; // helper DLL block replaced in that thread, restored by ~Loader 60 void* tls_saved_block = nullptr; // helper DLL block replaced in that thread, restored by ~Loader
diff --git a/runtime/src/tls_host.cpp b/runtime/src/tls_host.cpp
index ab234cbd9..a55941873 100644
--- a/runtime/src/tls_host.cpp
+++ b/runtime/src/tls_host.cpp
@@ -5,6 +5,11 @@
5// __declspec(thread) access in mapped code reads a valid TEB slot. The anchor itself is never used; the loader saves 5// __declspec(thread) access in mapped code reads a valid TEB slot. The anchor itself is never used; the loader saves
6// and restores the helper's own block, so the helper's CRT TLS state is not disturbed. 6// and restores the helper's own block, so the helper's CRT TLS state is not disturbed.
7// 7//
8// One more clone, leonida_tls_host_<pid>_home.dll, is loaded the first time an executable is mapped: the runtime's
9// own EXE, which Windows gave module TLS index 0, moves its block to that clone's index on every thread so the mapped
10// executable can take index 0. That clone stays loaded until the process ends, and its slot then holds the runtime's
11// live TLS, so nothing in this DLL may read or write its own TLS (gta6rt_tls_host_keep is never called).
12//
8// The Windows loader also calls this DLL's DllMain with DLL_THREAD_ATTACH on every new thread (after it has built that 13// The Windows loader also calls this DLL's DllMain with DLL_THREAD_ATTACH on every new thread (after it has built that
9// thread's TLS array) and with DLL_THREAD_DETACH when a thread exits (before it frees the array). The loader registers 14// thread's TLS array) and with DLL_THREAD_DETACH when a thread exits (before it frees the array). The loader registers
10// a callback here so it can give each new thread its own copy of the mapped image's TLS, and put this DLL's block back 15// a callback here so it can give each new thread its own copy of the mapped image's TLS, and put this DLL's block back
diff --git a/runtime/test/check_tls_index0.cmake b/runtime/test/check_tls_index0.cmake
new file mode 100644
index 000000000..f5df18999
--- /dev/null
+++ b/runtime/test/check_tls_index0.cmake
@@ -0,0 +1,27 @@
1# gta6rt --run and --init with tiny_tls_ga.exe, an executable built /GA whose thread_local reads go straight to
2# ThreadLocalStoragePointer[0]. --run: the game thread and a second thread both read the template value 42 and
3# _tls_index is 0. Both modes: the startup trace names gta6rt.exe as the image that held module TLS index 0 and the
4# index its block moved to.
5foreach(mode run init)
6 set(trace "${TRACE_DIR}/tls_index0_${mode}.jsonl")
7 file(REMOVE "${trace}") # --trace only creates a new file
8 execute_process(
9 COMMAND ${RUNNER} "${LOADER}" --${mode} "${GUEST}" --trace "${trace}"
10 TIMEOUT 90
11 RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE error)
12 if(NOT code STREQUAL "0")
13 message(FATAL_ERROR "--${mode} returned ${code}\n${output}\n${error}")
14 endif()
15 if(mode STREQUAL "run" AND (NOT output MATCHES "tiny_tls_ga: tls_index=0 main=42 thread=42 OK"
16 OR NOT output MATCHES "game exited with code 0"))
17 message(FATAL_ERROR "--run did not read the TLS from slot 0\n${output}\n${error}")
18 endif()
19 if(error MATCHES "does not get module TLS index 0")
20 message(FATAL_ERROR "--${mode}: the executable was not given index 0\n${error}")
21 endif()
22 file(READ "${trace}" lines)
23 if(NOT lines MATCHES "\"kind\":\"tls_index0\",\"owner\":\"gta6rt.exe\",\"moved_to\":[1-9][0-9]*}")
24 message(FATAL_ERROR "--${mode}: no tls_index0 event naming gta6rt.exe in the trace\n${lines}")
25 endif()
26 file(REMOVE "${trace}")
27endforeach()
diff --git a/runtime/test/fixtures/tiny_tls_ga.cpp b/runtime/test/fixtures/tiny_tls_ga.cpp
new file mode 100644
index 000000000..1fd460c99
--- /dev/null
+++ b/runtime/test/fixtures/tiny_tls_ga.cpp
@@ -0,0 +1,35 @@
1// Tiny fixture EXE for module TLS index 0. It is ordinary test code, not game content.
2//
3// Built /GA (CMakeLists.txt), the EXE-only option that lets the compiler assume the image is the process executable
4// and so has module TLS index 0: every thread_local access below reads TEB->ThreadLocalStoragePointer[0] directly
5// (mov rax, gs:[58h]; mov rax, [rax]) and never loads _tls_index. Mapped with any other index, the getter reads
6// whatever block sits in slot 0. loader_main_tls_test calls the exports on threads of its own; under
7// `gta6rt --run` (run_tiny_tls_ga) main() checks the value on the game thread and on a second thread and returns 0
8// only when both read the template value 42.
9#include <cstdio>
10#include <thread>
11
12extern "C" unsigned long _tls_index;
13
14namespace {
15thread_local int t_value = 42;
16}
17
18extern "C" __declspec(dllexport) __declspec(noinline) int __cdecl tiny_ga_get() { return t_value; }
19extern "C" __declspec(dllexport) __declspec(noinline) void __cdecl tiny_ga_set(int value) { t_value = value; }
20// Where this thread's t_value is, so the test can find its offset inside the slot-0 block.
21extern "C" __declspec(dllexport) __declspec(noinline) int* __cdecl tiny_ga_address() { return &t_value; }
22extern "C" __declspec(dllexport) unsigned long __cdecl tiny_ga_tls_index() { return _tls_index; }
23extern "C" __declspec(dllexport) unsigned long* __cdecl tiny_ga_tls_index_address() { return &_tls_index; }
24
25int main() {
26 const int on_main = tiny_ga_get();
27 tiny_ga_set(7);
28 int on_thread = -1;
29 std::thread worker([&] { on_thread = tiny_ga_get(); });
30 worker.join();
31 const bool ok = on_main == 42 && on_thread == 42 && tiny_ga_get() == 7;
32 std::printf("tiny_tls_ga: tls_index=%lu main=%d thread=%d %s\n", _tls_index, on_main, on_thread,
33 ok ? "OK" : "FAILED");
34 return ok ? 0 : 1;
35}
diff --git a/runtime/test/loader_tls_index0_test.cpp b/runtime/test/loader_tls_index0_test.cpp
new file mode 100644
index 000000000..d113c4303
--- /dev/null
+++ b/runtime/test/loader_tls_index0_test.cpp
@@ -0,0 +1,358 @@
1// End-to-end checks for module TLS index 0 and a mapped executable, against locally built fixtures.
2//
3// Windows gives the process executable module TLS index 0, and MSVC code built with /GA relies on it: it reads
4// TEB->ThreadLocalStoragePointer[0] without loading _tls_index. tiny_tls_ga.exe is such an image (a thread_local int
5// with the initializer 42, built /GA). The loader frees index 0 by moving this test EXE's own block (index 0 before
6// the first executable is mapped) to a helper clone's index on every thread. The checks: the executable reads 42 on
7// the loading thread, on a thread that existed before the move, and on threads started later; this EXE's own
8// thread_local data stays its own on all of them; tiny_tls.dll keeps a helper index alongside; two runs one after the
9// other both get index 0, and a second executable mapped meanwhile gets a helper index.
10//
11// gta6rt_tls_host.dll must sit next to this EXE, as for loader_tls_test. No game files are needed.
12#include <windows.h>
13#include <intrin.h>
14
15#include <atomic>
16#include <cstdint>
17#include <cstdio>
18#include <cstring>
19#include <filesystem>
20#include <stdexcept>
21#include <string>
22#include <thread>
23
24#include "pe_loader.h"
25
26extern "C" unsigned long _tls_index; // this EXE's module TLS index, read through its TLS directory's AddressOfIndex
27
28namespace {
29
30namespace fs = std::filesystem;
31
32int g_checks = 0;
33int g_failures = 0;
34
35void check(bool condition, const char* what) {
36 ++g_checks;
37 std::printf("%s %s\n", condition ? "PASS" : "FAIL", what);
38 if (!condition) ++g_failures;
39}
40
41// This EXE's own TLS: thread_local reads here go through _tls_index, so they follow the move.
42thread_local int t_host = 1234;
43
44__declspec(noinline) int host_value() { return t_host; }
45__declspec(noinline) void set_host_value(int value) { t_host = value; }
46__declspec(noinline) const void* host_address() { return &t_host; }
47
48void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); }
49
50// Whether t_host lies in the block this thread's slot _tls_index holds (the block is larger than this file's TLS).
51bool host_tls_in_own_slot() {
52 const auto* block = static_cast<const uint8_t*>(module_tls_slots()[_tls_index]);
53 const auto* p = static_cast<const uint8_t*>(host_address());
54 return block && p >= block && p < block + 0x10000;
55}
56
57template <class Fn>
58Fn find_export(const rt::Module& m, const char* name) {
59 const auto it = m.exports.find(name);
60 if (it == m.exports.end()) throw std::runtime_error(std::string("missing export ") + name);
61 return reinterpret_cast<Fn>(it->second);
62}
63
64struct Ga {
65 int(__cdecl* get)();
66 void(__cdecl* set)(int);
67 int*(__cdecl* address)();
68 unsigned long(__cdecl* tls_index)();
69 unsigned long*(__cdecl* tls_index_address)();
70};
71
72Ga ga_exports(const rt::Module& m) {
73 return {find_export<int(__cdecl*)()>(m, "tiny_ga_get"), find_export<void(__cdecl*)(int)>(m, "tiny_ga_set"),
74 find_export<int*(__cdecl*)()>(m, "tiny_ga_address"),
75 find_export<unsigned long(__cdecl*)()>(m, "tiny_ga_tls_index"),
76 find_export<unsigned long*(__cdecl*)()>(m, "tiny_ga_tls_index_address")};
77}
78
79// Code bytes of a function, past an incremental-linking jump stub (Debug builds export the stub).
80const uint8_t* code_of(const void* fn) {
81 const auto* p = static_cast<const uint8_t*>(fn);
82 if (p[0] == 0xE9) {
83 int32_t rel;
84 std::memcpy(&rel, p + 1, 4);
85 p += 5 + rel;
86 }
87 return p;
88}
89
90// The /GA shape of the getter, up to its ret: a load of gs:[58h] (65 REX.W 8B /r with a SIB of disp32 0x58) and no
91// rip-relative operand that lands on the image's _tls_index.
92bool reads_slot0_without_index(const void* fn, const void* tls_index) {
93 const uint8_t* p = code_of(fn);
94 bool gs58 = false, index = false;
95 for (size_t i = 0; i < 64 && p[i] != 0xC3; ++i) {
96 if (p[i] == 0x65 && (p[i + 1] & 0xF8) == 0x48 && p[i + 2] == 0x8B && (p[i + 3] & 0xC7) == 0x04 &&
97 p[i + 4] == 0x25 && p[i + 5] == 0x58 && !p[i + 6] && !p[i + 7] && !p[i + 8])
98 gs58 = true;
99 int32_t disp;
100 std::memcpy(&disp, p + i, 4);
101 for (int tail = 4; tail <= 5; ++tail) // the displacement ends the instruction or is followed by an imm8
102 index |= p + i + tail + disp == tls_index;
103 }
104 return gs58 && !index;
105}
106
107// What a thread started after load() sees, without any install call.
108struct NewThreadView {
109 int ga = -1, ga_after_set = -1, host = -1;
110 bool host_in_own_slot = false;
111 void* slot0 = nullptr;
112 int dll = -1;
113};
114
115// ga may be null: then only this EXE's own TLS is looked at.
116NewThreadView run_new_thread(const Ga* ga, int(__cdecl* dll_get)() = nullptr) {
117 NewThreadView v;
118 std::thread t([&] {
119 v.slot0 = module_tls_slots()[0];
120 if (ga) {
121 v.ga = ga->get();
122 ga->set(9);
123 v.ga_after_set = ga->get();
124 }
125 v.host = host_value();
126 set_host_value(4321);
127 v.host_in_own_slot = host_tls_in_own_slot();
128 if (dll_get) v.dll = dll_get();
129 });
130 t.join();
131 return v;
132}
133
134// A thread that exists before any executable is mapped. It holds its own value in t_host across the move, then
135// installs the executable's copy itself (install_tls_for_thread, as for any module and a thread older than load()).
136struct EarlyThread {
137 HANDLE ready = CreateEventW(nullptr, TRUE, FALSE, nullptr);
138 HANDLE go = CreateEventW(nullptr, TRUE, FALSE, nullptr);
139 HANDLE done = CreateEventW(nullptr, TRUE, FALSE, nullptr);
140 HANDLE quit = CreateEventW(nullptr, TRUE, FALSE, nullptr);
141 rt::Loader* loader = nullptr;
142 rt::Module* module = nullptr;
143 Ga ga{};
144 int host_after_move = -1, ga_installed = -1, ga_after_set = -1;
145 bool host_in_own_slot = false, block_in_slot0 = false, slot0_restored = false;
146 std::thread thread;
147
148 EarlyThread() {
149 thread = std::thread([this] {
150 set_host_value(777);
151 SetEvent(ready);
152 WaitForSingleObject(go, INFINITE);
153 if (!loader) return; // the test stopped before it got this far
154 host_after_move = host_value();
155 host_in_own_slot = host_tls_in_own_slot();
156 void* before = module_tls_slots()[0];
157 loader->install_tls_for_thread(*module);
158 block_in_slot0 = module_tls_slots()[0] != before;
159 ga_installed = ga.get();
160 ga.set(5);
161 ga_after_set = ga.get();
162 loader->uninstall_tls_for_thread(*module);
163 slot0_restored = module_tls_slots()[0] == before;
164 SetEvent(done);
165 WaitForSingleObject(quit, INFINITE); // ends after both Loaders are gone
166 });
167 WaitForSingleObject(ready, INFINITE);
168 }
169 ~EarlyThread() {
170 SetEvent(go);
171 SetEvent(quit);
172 if (thread.joinable()) thread.join();
173 for (HANDLE h : {ready, go, done, quit}) CloseHandle(h);
174 }
175};
176
177// A thread that keeps running inside this EXE's code could be stopped between its load of _tls_index and its read
178// of the slot, so the move waits for it and gives up after its time budget: nothing changes, the executable maps with
179// a helper index, and the move is tried again for the next executable.
180void test_busy_thread_refuses(const fs::path& exe) {
181 std::printf("\n-- a thread busy in this EXE's code holds the move off --\n");
182 std::atomic<bool> stop{false}, wrong{false};
183 std::atomic<long> spins{0};
184 std::thread spinner([&] {
185 set_host_value(31337);
186 while (!stop.load(std::memory_order_relaxed)) {
187 if (host_value() != 31337) wrong = true;
188 spins.fetch_add(1, std::memory_order_relaxed);
189 }
190 });
191 while (spins.load() == 0) Sleep(0);
192 {
193 rt::Loader loader(exe.parent_path());
194 rt::Module& m = loader.load(exe);
195 check(m.tls_index != 0 && m.tls_index != rt::kNoTlsIndex,
196 "while a thread runs inside this EXE's code the executable gets a helper index");
197 check(_tls_index == 0 && host_value() == 555, "this EXE keeps index 0 and its value then");
198 }
199 stop = true;
200 spinner.join();
201 check(!wrong, "the busy thread read its own TLS value on every one of its spins");
202}
203
204void test_first_run(const fs::path& exe, const fs::path& dll, EarlyThread& early, unsigned long& moved_to) {
205 std::printf("\n-- first run: %s --\n", exe.string().c_str());
206 void* block = nullptr;
207 void* saved = nullptr;
208 {
209 rt::Loader loader(exe.parent_path());
210 rt::Module& m = loader.load(exe);
211 const Ga ga = ga_exports(m);
212 moved_to = _tls_index;
213 std::printf(" this EXE's _tls_index is now %lu; the executable's block=%p\n", moved_to, m.tls_block);
214
215 check(m.tls_index == 0, "the mapped executable gets module TLS index 0");
216 check(ga.tls_index() == 0, "its AddressOfIndex (_tls_index) holds 0");
217 check(m.tls_block && module_tls_slots()[0] == m.tls_block, "slot 0 of this thread holds its template copy");
218 check(ga.get() == 42, "its /GA getter reads the template value 42 on the loading thread");
219 check(moved_to != 0 && moved_to != rt::kNoTlsIndex, "this EXE's own _tls_index moved off 0");
220 check(host_value() == 555, "this EXE's thread_local value survives the move on the loading thread");
221 check(host_tls_in_own_slot(), "this EXE's TLS is in the slot its new _tls_index names");
222 check(m.tls_saved_block && m.tls_saved_block != module_tls_slots()[moved_to],
223 "the block saved from slot 0 is the helper clone's, not this EXE's");
224
225 // The getter follows slot 0, whatever _tls_index says: a stand-in block there changes what it reads.
226 const auto offset = reinterpret_cast<const uint8_t*>(ga.address()) - static_cast<const uint8_t*>(m.tls_block);
227 alignas(64) static uint8_t stand_in[4096];
228 bool offset_ok = offset >= 0 && static_cast<uint64_t>(offset) + sizeof(int) <= m.tls_block_size;
229 check(offset_ok, "the executable's thread_local lies inside its slot-0 block");
230 if (offset_ok && static_cast<size_t>(offset) + sizeof(int) <= sizeof(stand_in)) {
231 const int marker = 77;
232 std::memcpy(stand_in + offset, &marker, sizeof(marker));
233 void* real = module_tls_slots()[0];
234 module_tls_slots()[0] = stand_in;
235 const int seen = ga.get();
236 module_tls_slots()[0] = real;
237 check(seen == 77, "the executable's getter reads slot 0 directly");
238 }
239#if LEONIDA_GA_FIXTURE_IS_GA
240 check(reads_slot0_without_index(reinterpret_cast<const void*>(ga.get), ga.tls_index_address()),
241 "the fixture's getter is /GA code: gs:[58h] and no load of _tls_index");
242#else
243 std::printf("SKIP the fixture's /GA code shape (this compiler may ignore /GA)\n");
244#endif
245
246 ga.set(43);
247 const NewThreadView fresh = run_new_thread(&ga);
248 check(fresh.ga == 42, "a thread started after load() reads 42 without an install call");
249 check(fresh.ga_after_set == 9 && ga.get() == 43, "its write stays in its own copy");
250 check(fresh.slot0 != m.tls_block, "its slot 0 is its own block, not the loading thread's");
251 check(fresh.host == 1234 && fresh.host_in_own_slot,
252 "this EXE's thread_local starts at its initializer there, in the moved slot");
253 check(host_value() == 555, "this EXE's value on the loading thread is unchanged");
254
255 early.loader = &loader;
256 early.module = &m;
257 early.ga = ga;
258 SetEvent(early.go);
259 WaitForSingleObject(early.done, INFINITE);
260 check(early.host_after_move == 777 && early.host_in_own_slot,
261 "a thread that existed before the move keeps this EXE's TLS value (777)");
262 check(early.block_in_slot0 && early.ga_installed == 42 && early.ga_after_set == 5,
263 "install_tls_for_thread gives that thread its own copy in slot 0");
264 check(early.slot0_restored, "uninstall_tls_for_thread puts that thread's slot 0 back");
265
266 loader.initialise();
267 check(m.initialised, "initialise() runs the executable's TLS callbacks (it has none)");
268 check(run_new_thread(&ga).ga == 42, "after initialise() a new thread still reads 42");
269
270 // A DLL with TLS keeps a helper index next to the executable's 0.
271 rt::Module& d = loader.load(dll);
272 const auto dll_get = find_export<int(__cdecl*)()>(d, "tiny_tls_get");
273 check(d.tls_index != rt::kNoTlsIndex && d.tls_index != 0 && d.tls_index != moved_to,
274 "tiny_tls.dll gets a helper index, neither 0 nor this EXE's");
275 check(dll_get() == 7 && ga.get() == 43 && host_value() == 555,
276 "the DLL, the executable and this EXE each read their own value on the loading thread");
277 const NewThreadView both = run_new_thread(&ga, dll_get);
278 check(both.dll == 7 && both.ga == 42 && both.host == 1234,
279 "a new thread reads the DLL's 7, the executable's 42 and this EXE's 1234");
280
281 block = m.tls_block;
282 saved = m.tls_saved_block;
283 }
284 check(module_tls_slots()[0] == saved, "~Loader puts the helper clone's block back in slot 0");
285 MEMORY_BASIC_INFORMATION info{};
286 check(VirtualQuery(block, &info, sizeof(info)) == 0 || info.State == MEM_FREE, "~Loader frees the copy");
287 check(_tls_index == moved_to && host_value() == 555, "this EXE keeps its moved index and value after the run");
288}
289
290void test_second_run(const fs::path& exe, unsigned long moved_to) {
291 std::printf("\n-- second run, and a second executable at once --\n");
292 wchar_t temp[MAX_PATH];
293 GetTempPathW(MAX_PATH, temp);
294 const fs::path copy = fs::path(temp) / ("leonida_tls_index0_copy_" + std::to_string(GetCurrentProcessId()) + ".exe");
295 // CopyFileW, not fs::copy_file: MSVC's copy_file calls CopyFile2, which Wine 9 doesn't implement.
296 check(CopyFileW(exe.c_str(), copy.c_str(), FALSE) != 0, "copied the executable under a second name");
297 {
298 rt::Loader loader(exe.parent_path());
299 rt::Module& m = loader.load(exe);
300 const Ga ga = ga_exports(m);
301 loader.initialise();
302 check(m.tls_index == 0 && ga.get() == 42, "a second Loader maps the executable at index 0 again, value 42");
303 check(_tls_index == moved_to, "the move is done once: this EXE's index stays where the first run put it");
304 check(run_new_thread(&ga).ga == 42 && host_value() == 555, "new threads and this EXE's value still check out");
305
306 rt::Module& other = loader.load(copy);
307 const Ga other_ga = ga_exports(other);
308 check(other.tls_index != 0 && other.tls_index != rt::kNoTlsIndex && other_ga.tls_index() == other.tls_index,
309 "a second executable mapped meanwhile gets a helper index in its _tls_index");
310 check(m.tls_index == 0 && ga.get() == 42, "the first keeps index 0 and its value");
311 // The documented limit: /GA code of the second one reads slot 0, the first one's block.
312 check(other_ga.address() == ga.address(), "the second executable's /GA code reads the first one's slot 0");
313 }
314 std::error_code ec;
315 fs::remove(copy, ec);
316}
317
318void print_result() {
319 if (g_failures == 0)
320 std::printf("\nloader_tls_index0_test: OK (%d checks)\n", g_checks);
321 else
322 std::printf("\nloader_tls_index0_test: FAILED (%d checks, %d failure%s)\n", g_checks, g_failures,
323 g_failures == 1 ? "" : "s");
324}
325
326} // namespace
327
328int main(int argc, char** argv) {
329 std::setvbuf(stdout, nullptr, _IONBF, 0);
330 std::printf("loader_tls_index0_test: module TLS index 0 for a mapped executable\n");
331 if (argc != 3) {
332 std::fprintf(stderr, "usage: loader_tls_index0_test <tiny_tls_ga.exe> <tiny_tls.dll>\n");
333 return 2;
334 }
335 const fs::path exe = argv[1], dll = argv[2];
336 try {
337 check(fs::exists(exe) && fs::exists(dll), "the fixtures exist");
338 // Measured, not assumed: before anything is mapped, index 0 is this EXE's (Windows gives it to the process
339 // executable when that has TLS, as every EXE linking pe_loader.cpp does).
340 check(_tls_index == 0, "before any executable is mapped, this test EXE holds module TLS index 0");
341 set_host_value(555);
342 unsigned long moved_to = 0;
343 {
344 EarlyThread early;
345 test_busy_thread_refuses(exe);
346 test_first_run(exe, dll, early, moved_to);
347 test_second_run(exe, moved_to);
348 } // the early thread ends here, after both Loaders
349 check(run_new_thread(nullptr).host == 1234,
350 "a thread started after both runs still gets this EXE's TLS at its moved index");
351 } catch (const std::exception& e) {
352 ++g_checks;
353 ++g_failures;
354 std::printf("FAIL unexpected exception: %s\n", e.what());
355 }
356 print_result();
357 return g_failures ? 1 : 0;
358}