upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src/pe_loader.cpp
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/src/pe_loader.cpp
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/src/pe_loader.cpp')
-rw-r--r--runtime/src/pe_loader.cpp454
1 files changed, 395 insertions, 59 deletions
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;