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:
Diffstat (limited to 'runtime/src/pe_loader.cpp')
-rw-r--r--runtime/src/pe_loader.cpp450
1 files changed, 384 insertions, 66 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index cc4ae88aa..57822d1ec 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -126,8 +126,29 @@ IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) {
126// reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader 126// reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader
127// clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent 127// clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent
128// module TLS index for each simultaneous module (up to kMaxMappedTlsModules). 128// module TLS index for each simultaneous module (up to kMaxMappedTlsModules).
129//
130// A mapped executable is different: MSVC code built with /GA (an EXE-only optimisation) skips _tls_index and reads
131// TEB->ThreadLocalStoragePointer[0] directly (mov rax, gs:[58h]; mov rax, [rax]), because Windows always gives the
132// process executable module TLS index 0. Measured with a `thread_local int v = 42;` EXE built /O2 /GA /MD: natively
133// tls_index=0 value=42; mapped with a helper index (6) the code still read slot 0 and printed value=0. Index 0
134// belongs to the runtime's own EXE (gta6rt.exe: a 1398-byte template when measured, no TLS callbacks; so does each
135// test EXE that links this file), and every TLS read in its disassembly goes through _tls_index (the only direct
136// gs:[58h] read is module_tls_slots below, which wants the array itself). reserve_tls_index0 therefore moves the owner
137// off index 0, once, at process start: it loads the home clone (make_home_clone_image), whose TLS template is a copy of
138// the owner's, and on the calling thread swaps slots 0 and home and writes home into the owner's _tls_index. From then on every thread the OS
139// starts has a fresh copy of the owner's template at home, which is where the owner looks, from its first instruction:
140// nothing has to run on a new thread first. Slot 0 holds a block nobody reads, which the mapped executable's copy
141// replaces (kMainImageSlot) exactly as a DLL's copy replaces a helper's, and the OS frees both slots at thread exit.
142// It has to happen before any other thread has run the owner's code: MSVC keeps &ThreadLocalStoragePointer[_tls_index]
143// across calls (zlib_inflate in shader_library.h saves it at [rbp-80h] across memset, push_back and inflate_codes, then
144// reads _Init_thread_epoch through it), so a running thread cannot be moved safely, wherever it is stopped. Such a
145// thread's TLS would also stay where it was, at index 0.
129constexpr DWORD kMaxModuleTlsSlots = 64; 146constexpr DWORD kMaxModuleTlsSlots = 64;
130constexpr size_t kMaxMappedTlsModules = 16; 147constexpr size_t kMaxMappedTlsModules = 16;
148// The slot for a mapped executable, which reads module TLS index 0 (see above). Only one at a time; a second
149// executable mapped while one is live gets an ordinary helper slot. kTlsSlotCount sizes the per-slot tables.
150constexpr size_t kMainImageSlot = kMaxMappedTlsModules;
151constexpr size_t kTlsSlotCount = kMaxMappedTlsModules + 1;
131void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); } 152void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); }
132 153
133void __cdecl on_host_thread_event(DWORD reason); 154void __cdecl on_host_thread_event(DWORD reason);
@@ -135,6 +156,7 @@ void __cdecl on_host_thread_event(DWORD reason);
135struct TlsHostModule { 156struct TlsHostModule {
136 HMODULE module = nullptr; 157 HMODULE module = nullptr;
137 DWORD index = TLS_OUT_OF_INDEXES; 158 DWORD index = TLS_OUT_OF_INDEXES;
159 bool hooked = false; // its DllMain reports thread events to on_host_thread_event
138}; 160};
139 161
140std::filesystem::path tls_host_base_path() { 162std::filesystem::path tls_host_base_path() {
@@ -167,20 +189,39 @@ struct TlsCloneRecord {
167 189
168std::mutex g_tls_alloc_mutex; 190std::mutex g_tls_alloc_mutex;
169std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{}; 191std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{};
170std::array<std::atomic<Module*>, kMaxMappedTlsModules> g_tls_slot_owners{}; 192std::array<std::atomic<Module*>, kTlsSlotCount> g_tls_slot_owners{};
171std::array<std::atomic<uint64_t>, kMaxMappedTlsModules> g_tls_slot_generations{}; 193std::array<std::atomic<uint64_t>, kTlsSlotCount> g_tls_slot_generations{};
172std::atomic<uint64_t> g_next_tls_generation{1}; 194std::atomic<uint64_t> g_next_tls_generation{1};
173std::vector<TlsCloneRecord> g_tls_clones; 195// Allocated with the first clone and never destroyed: cleanup_tls_clones_at_exit runs from the atexit table, and a
196// static vector's destructor (registered when its dynamic initializer ran) could run before it. Under
197// g_tls_alloc_mutex, as are its records.
198std::vector<TlsCloneRecord>* g_tls_clones = nullptr;
199
200// The move of module TLS index 0 (see kMainImageSlot): done at most once, by reserve_tls_index0 under
201// g_tls_alloc_mutex. `why` is the reason it was not done, for the executable that then maps with a helper index.
202// Constant-initialized only (no std::string): gta6rt reserves from a CRT initializer that runs before the dynamic
203// initializers of this file, which would otherwise reset what it wrote.
204struct Index0Move {
205 bool moved = false;
206 bool traced = false; // the startup trace opens after the move; the first executable map reports it
207 TlsHostModule home; // the clone whose index holds the owner's TLS from now on; never freed
208 char owner[260] = {}; // UTF-8 file name of the image that held index 0
209 char why[160] = "reserve_tls_index0 was not called at process start";
210};
211Index0Move g_index0;
174 212
175// Frees every TLS helper clone this process loaded and deletes its files. load() registers the wrapper with atexit; 213// Frees every TLS helper clone recorded for a mapped DLL's slot and deletes its files. ensure_tls_host registers the
176// the --run path in main() must also call this directly before ExitProcess, which skips the atexit table. Call it 214// wrapper with atexit when it records the first clone; the --run path in main() must also call this directly before
177// only when no mapped code can run again: it unmaps the helper images. 215// ExitProcess, which skips the atexit table. Call it only when no mapped code can run again: it unmaps the helper
216// images. The home clone is not recorded (reserve_index0): it stays loaded, so its file outlives the process and the
217// next run's sweep deletes it.
178void cleanup_tls_clones_internal() { 218void cleanup_tls_clones_internal() {
179 for (const auto& rec : g_tls_clones) { 219 if (!g_tls_clones) return;
220 for (const auto& rec : *g_tls_clones) {
180 if (rec.module) FreeLibrary(rec.module); 221 if (rec.module) FreeLibrary(rec.module);
181 if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); 222 if (!rec.path.empty()) DeleteFileW(rec.path.c_str());
182 } 223 }
183 g_tls_clones.clear(); 224 g_tls_clones->clear();
184} 225}
185 226
186void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); } 227void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); }
@@ -204,10 +245,14 @@ DWORD clone_owner_pid(const wchar_t* name) {
204bool process_alive(DWORD pid) { 245bool process_alive(DWORD pid) {
205 // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the 246 // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the
206 // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID. 247 // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID.
248 // OpenProcess also succeeds on a process that has ended while another process still holds a handle to it (a
249 // parent waiting on its exit code, as CMake's execute_process does), so the exit code decides.
207 HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); 250 HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
208 if (!p) return false; 251 if (!p) return false;
252 DWORD code = 0;
253 const bool alive = !GetExitCodeProcess(p, &code) || code == STILL_ACTIVE;
209 CloseHandle(p); 254 CloseHandle(p);
210 return true; 255 return alive;
211} 256}
212 257
213// Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a 258// Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a
@@ -262,45 +307,66 @@ TlsHostModule load_tls_host_image(const std::filesystem::path& path, bool hook_t
262 if (hook_thread_events) { 307 if (hook_thread_events) {
263 // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots. 308 // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots.
264 using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); 309 using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD));
265 if (auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"))) 310 auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"));
311 if (set) {
266 set(&on_host_thread_event); 312 set(&on_host_thread_event);
313 host.hooked = true;
314 }
267 } 315 }
268 return host; 316 return host;
269} 317}
270 318
271// Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock). 319// The primary helper: slot 0's index, and the only helper whose DllMain reports thread events (on_host_thread_event
272TlsHostModule ensure_tls_host(size_t slot) { 320// covers every slot). Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the
273 if (slot >= kMaxMappedTlsModules) return {}; 321// Windows loader lock).
274 if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot]; 322// A helper without the thread-event export is refused: no thread started later would get its copies.
275 323bool ensure_primary_tls_host() {
324 if (g_tls_hosts[0].index != TLS_OUT_OF_INDEXES) return true;
276 const std::filesystem::path primary = tls_host_base_path(); 325 const std::filesystem::path primary = tls_host_base_path();
277 if (primary.empty()) return {}; 326 if (primary.empty()) return false;
278 327 TlsHostModule host = load_tls_host_image(primary, true);
279 if (slot == 0) { 328 if (host.index != TLS_OUT_OF_INDEXES && !host.hooked) {
280 g_tls_hosts[0] = load_tls_host_image(primary, true); 329 FreeLibrary(host.module);
281 return g_tls_hosts[0]; 330 return false;
282 }
283
284 // Ensure slot 0 is loaded first so thread attach/detach events are hooked.
285 if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) {
286 g_tls_hosts[0] = load_tls_host_image(primary, true);
287 if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) return {};
288 } 331 }
332 g_tls_hosts[0] = host;
333 return host.index != TLS_OUT_OF_INDEXES;
334}
289 335
336// Copies gta6rt_tls_host.dll (or writes `image`, a changed copy of it) to "leonida_tls_host_<pid>_<tag>.dll" in the
337// clone directory and loads it, so the OS gives the copy an index of its own. On failure the file is gone again and
338// the result has no index. The caller records the clone (g_tls_clones) if it is to be freed at exit. Same locking rule
339// as ensure_primary_tls_host.
340TlsHostModule load_tls_host_clone(const std::wstring& tag, std::filesystem::path& clone_path,
341 const std::vector<uint8_t>* image = nullptr) {
342 const std::filesystem::path primary = tls_host_base_path();
343 if (primary.empty()) return {};
290 // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem). 344 // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem).
291 const std::filesystem::path dir = tls_host_clone_dir(); 345 const std::filesystem::path dir = tls_host_clone_dir();
292 static bool swept = false; 346 static bool swept = false;
293 if (!swept) { 347 if (!swept) {
294 swept = true; 348 swept = true;
295 sweep_stale_tls_clones(dir); 349 sweep_stale_tls_clones(dir);
296 std::atexit(&cleanup_tls_clones_at_exit);
297 } 350 }
298 const std::wstring name = 351 const std::wstring name = L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + tag + L".dll";
299 L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll"; 352 clone_path = dir / name;
300 const std::filesystem::path clone_path = dir / name;
301 // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll. 353 // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll.
302 const std::filesystem::path staging = clone_path.wstring() + L".new"; 354 const std::filesystem::path staging = clone_path.wstring() + L".new";
303 if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) return {}; 355 if (image) {
356 HANDLE out =
357 CreateFileW(staging.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
358 if (out == INVALID_HANDLE_VALUE) return {};
359 DWORD written = 0;
360 const bool ok = WriteFile(out, image->data(), static_cast<DWORD>(image->size()), &written, nullptr) &&
361 written == image->size();
362 CloseHandle(out);
363 if (!ok) {
364 DeleteFileW(staging.c_str());
365 return {};
366 }
367 } else if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) {
368 return {};
369 }
304 370
305 // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename 371 // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename
306 // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone 372 // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone
@@ -320,18 +386,34 @@ TlsHostModule ensure_tls_host(size_t slot) {
320 TlsHostModule loaded = load_tls_host_image(clone_path, false); 386 TlsHostModule loaded = load_tls_host_image(clone_path, false);
321 CloseHandle(guard); 387 CloseHandle(guard);
322 388
323 if (loaded.index == TLS_OUT_OF_INDEXES) { 389 if (loaded.index == TLS_OUT_OF_INDEXES) DeleteFileW(clone_path.c_str());
390 return loaded;
391}
392
393// Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock).
394TlsHostModule ensure_tls_host(size_t slot) {
395 if (slot >= kMaxMappedTlsModules) return {};
396 if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot];
397 // Slot 0 is the primary helper; it is loaded first in any case so thread attach/detach events are hooked.
398 if (!ensure_primary_tls_host()) return {};
399 if (slot == 0) return g_tls_hosts[0];
400
401 std::filesystem::path clone_path;
402 TlsHostModule loaded = load_tls_host_clone(std::to_wstring(slot), clone_path);
403 if (loaded.index == TLS_OUT_OF_INDEXES) return {};
404 // Index 0 is the runtime EXE's, and after the move the home clone's index holds that EXE's TLS.
405 bool taken = loaded.index == 0 || loaded.index == g_index0.home.index;
406 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) taken |= i != slot && g_tls_hosts[i].index == loaded.index;
407 if (taken) {
408 FreeLibrary(loaded.module);
324 DeleteFileW(clone_path.c_str()); 409 DeleteFileW(clone_path.c_str());
325 return {}; 410 return {};
326 } 411 }
327 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { 412 if (!g_tls_clones) {
328 if (i != slot && g_tls_hosts[i].index == loaded.index) { 413 g_tls_clones = new std::vector<TlsCloneRecord>;
329 FreeLibrary(loaded.module); 414 std::atexit(&cleanup_tls_clones_at_exit);
330 DeleteFileW(clone_path.c_str());
331 return {};
332 }
333 } 415 }
334 g_tls_clones.push_back({loaded.module, clone_path}); 416 g_tls_clones->push_back({loaded.module, clone_path});
335 g_tls_hosts[slot] = loaded; 417 g_tls_hosts[slot] = loaded;
336 return g_tls_hosts[slot]; 418 return g_tls_hosts[slot];
337} 419}
@@ -347,7 +429,7 @@ struct ThreadTlsSlot {
347}; 429};
348 430
349// Per-thread installation state for each reserved TLS slot. 431// Per-thread installation state for each reserved TLS slot.
350thread_local std::array<ThreadTlsSlot, kMaxMappedTlsModules> g_thread_tls_slots{}; 432thread_local std::array<ThreadTlsSlot, kTlsSlotCount> g_thread_tls_slots{};
351 433
352// Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared 434// Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared
353// in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows 435// in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows
@@ -366,10 +448,185 @@ struct ExclusiveTlsLock {
366 ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete; 448 ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete;
367}; 449};
368 450
451// gta6rt_tls_host.dll's exports that the home clone's TLS directory is pointed at (tls_host.cpp): a zero array in its
452// .rdata and that array's size.
453constexpr char kHomeTemplateExport[] = "gta6rt_tls_home_template";
454constexpr char kHomeTemplateSizeExport[] = "gta6rt_tls_home_template_size";
455
456// File offset of `len` bytes at `rva` in an image file held in memory, or SIZE_MAX when they are not all inside one
457// section's raw data.
458size_t file_offset(const std::vector<uint8_t>& file, const IMAGE_NT_HEADERS64* nt, uint64_t rva, uint64_t len) {
459 const auto* sec = IMAGE_FIRST_SECTION(nt);
460 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) {
461 if (reinterpret_cast<const uint8_t*>(sec + 1) > file.data() + file.size()) break;
462 if (rva < sec->VirtualAddress || rva + len > static_cast<uint64_t>(sec->VirtualAddress) + sec->SizeOfRawData)
463 continue;
464 const uint64_t off = sec->PointerToRawData + (rva - sec->VirtualAddress);
465 return off + len <= file.size() ? static_cast<size_t>(off) : SIZE_MAX;
466 }
467 return SIZE_MAX;
468}
469
470// The RVA of a named export in an image file held in memory, 0 when it has none.
471uint32_t file_export(const std::vector<uint8_t>& file, const IMAGE_NT_HEADERS64* nt, const char* wanted) {
472 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXPORT);
473 const size_t ed_off = file_offset(file, nt, dir.VirtualAddress, sizeof(IMAGE_EXPORT_DIRECTORY));
474 if (!dir.Size || ed_off == SIZE_MAX) return 0;
475 const auto* ed = reinterpret_cast<const IMAGE_EXPORT_DIRECTORY*>(file.data() + ed_off);
476 const size_t names = file_offset(file, nt, ed->AddressOfNames, uint64_t{4} * ed->NumberOfNames);
477 const size_t ords = file_offset(file, nt, ed->AddressOfNameOrdinals, uint64_t{2} * ed->NumberOfNames);
478 const size_t funcs = file_offset(file, nt, ed->AddressOfFunctions, uint64_t{4} * ed->NumberOfFunctions);
479 if (names == SIZE_MAX || ords == SIZE_MAX || funcs == SIZE_MAX) return 0;
480 const size_t wanted_len = std::strlen(wanted) + 1;
481 for (uint32_t i = 0; i < ed->NumberOfNames; ++i) {
482 uint32_t name_rva, func_rva;
483 uint16_t ord;
484 std::memcpy(&name_rva, file.data() + names + 4 * i, 4);
485 std::memcpy(&ord, file.data() + ords + 2 * i, 2);
486 const size_t name = file_offset(file, nt, name_rva, wanted_len);
487 if (name == SIZE_MAX || std::memcmp(file.data() + name, wanted, wanted_len) != 0) continue;
488 if (ord >= ed->NumberOfFunctions) return 0;
489 std::memcpy(&func_rva, file.data() + funcs + 4 * ord, 4);
490 return func_rva;
491 }
492 return 0;
493}
494
495// Turns gta6rt_tls_host.dll's bytes into the home clone: its TLS directory now covers gta6rt_tls_home_template, which
496// starts with a copy of the owner's template (taken from the mapped owner, so its pointers are already relocated; the
497// array itself has no relocations), and takes the owner's alignment. The OS then gives every thread, at the home
498// index, a block that is a fresh copy of the owner's TLS. The zero fill goes into the covered range too:
499// LdrpAllocateTls allocates and copies End - Start only (Windows 11 26300) and ignores SizeOfZeroFill. The directory's
500// Start and End have base relocations, so they follow the clone wherever it loads. Empty on success, else why not.
501std::string make_home_clone_image(std::vector<uint8_t>& file, const IMAGE_TLS_DIRECTORY64& owner) {
502 if (file.size() < sizeof(IMAGE_DOS_HEADER)) return "gta6rt_tls_host.dll is truncated";
503 const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(file.data());
504 if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew < 0 ||
505 static_cast<size_t>(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size())
506 return "gta6rt_tls_host.dll has no PE header";
507 auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew);
508 if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC)
509 return "gta6rt_tls_host.dll is not a 64-bit image";
510 const uint32_t array_rva = file_export(file, nt, kHomeTemplateExport);
511 const uint32_t size_rva = file_export(file, nt, kHomeTemplateSizeExport);
512 const size_t size_off = file_offset(file, nt, size_rva, sizeof(uint32_t));
513 if (!array_rva || !size_rva || size_off == SIZE_MAX)
514 return "gta6rt_tls_host.dll has no gta6rt_tls_home_template";
515 uint32_t capacity;
516 std::memcpy(&capacity, file.data() + size_off, sizeof(capacity));
517 const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData;
518 const uint64_t total = raw + owner.SizeOfZeroFill;
519 if (owner.EndAddressOfRawData < owner.StartAddressOfRawData || total > capacity)
520 return "the owner's TLS (" + std::to_string(total) + " bytes) does not fit gta6rt_tls_home_template (" +
521 std::to_string(capacity) + " bytes)";
522 const size_t array_off = file_offset(file, nt, array_rva, capacity);
523 const auto tls_dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS);
524 const size_t tls_off = file_offset(file, nt, tls_dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64));
525 if (array_off == SIZE_MAX || !tls_dir.Size || tls_off == SIZE_MAX)
526 return "gta6rt_tls_host.dll's TLS directory or home template lies outside its file";
527 std::memcpy(file.data() + array_off, reinterpret_cast<const void*>(owner.StartAddressOfRawData), raw);
528 std::memset(file.data() + array_off + raw, 0, capacity - raw);
529 auto* tls = reinterpret_cast<IMAGE_TLS_DIRECTORY64*>(file.data() + tls_off);
530 tls->StartAddressOfRawData = nt->OptionalHeader.ImageBase + array_rva;
531 tls->EndAddressOfRawData = tls->StartAddressOfRawData + total;
532 tls->SizeOfZeroFill = 0;
533 tls->Characteristics =
534 (tls->Characteristics & ~IMAGE_SCN_ALIGN_MASK) | (owner.Characteristics & IMAGE_SCN_ALIGN_MASK);
535 return {};
536}
537
538std::string module_file_name(HMODULE module) {
539 wchar_t path[MAX_PATH];
540 const DWORD n = GetModuleFileNameW(module, path, MAX_PATH);
541 if (!n || n >= MAX_PATH) return "?";
542 const wchar_t* name = path;
543 for (const wchar_t* p = path; *p; ++p)
544 if (*p == L'\\' || *p == L'/') name = p + 1;
545 const int bytes = WideCharToMultiByte(CP_UTF8, 0, name, -1, nullptr, 0, nullptr, nullptr);
546 if (bytes <= 1) return "?";
547 std::string out(static_cast<size_t>(bytes - 1), '\0');
548 WideCharToMultiByte(CP_UTF8, 0, name, -1, out.data(), bytes, nullptr, nullptr);
549 return out;
550}
551
552// The move on the calling thread, kept apart so that no frame of reserve_index0 holds a slot address across it. After
553// it the owner's live block is at `home` and slot 0 holds the home clone's fresh copy, which nothing reads.
554__declspec(noinline) void move_index0_on_this_thread(DWORD* owner_index, DWORD home) {
555 void** slots = module_tls_slots();
556 std::swap(slots[0], slots[home]);
557 *owner_index = home;
558}
559
560// See reserve_tls_index0. Empty on success, else why not; nothing has changed then. g_tls_alloc_mutex held. It reads
561// no thread_local data and runs no code that does, before or after the move.
562std::string reserve_index0() {
563 // Windows gives index 0 to the process executable when it has TLS; a DLL can only hold it in a process whose EXE
564 // has none, and a DLL that is still loading or was loaded without its references resolved shows 0 too.
565 const HMODULE exe = GetModuleHandleW(nullptr);
566 auto* base = reinterpret_cast<uint8_t*>(exe);
567 auto* nt = at<IMAGE_NT_HEADERS64>(base, reinterpret_cast<IMAGE_DOS_HEADER*>(base)->e_lfanew);
568 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS);
569 if (!dir.Size || !dir.VirtualAddress) return "the process executable has no TLS, so index 0 is not its";
570 const IMAGE_TLS_DIRECTORY64 owner = *at<IMAGE_TLS_DIRECTORY64>(base, dir.VirtualAddress);
571 auto* owner_index = reinterpret_cast<DWORD*>(owner.AddressOfIndex);
572 if (!owner_index) return "the process executable's TLS directory has no index";
573 if (*owner_index != 0) return "the process executable's _tls_index is " + std::to_string(*owner_index) + ", not 0";
574 if (!module_tls_slots()) return "this thread has no TLS array";
575 if (!ensure_primary_tls_host())
576 return "gta6rt_tls_host.dll is missing, has no module TLS index or lacks gta6rt_tls_host_set_thread_event";
577
578 std::vector<uint8_t> image;
579 try {
580 image = read_file(tls_host_base_path());
581 } catch (const std::exception& e) {
582 return e.what();
583 }
584 if (std::string why = make_home_clone_image(image, owner); !why.empty()) return why;
585 std::filesystem::path path;
586 const TlsHostModule home = load_tls_host_clone(L"home", path, &image);
587 if (home.index == TLS_OUT_OF_INDEXES) return "the home clone of gta6rt_tls_host.dll cannot be loaded";
588 auto drop = [&](std::string why) {
589 FreeLibrary(home.module); // safe until the move below: nothing lives at its index yet
590 DeleteFileW(path.c_str());
591 return why;
592 };
593 bool taken = home.index == 0 || home.index >= kMaxModuleTlsSlots;
594 for (const auto& host : g_tls_hosts) taken |= host.index == home.index;
595 if (taken) return drop("the home clone got an unusable module TLS index");
596 // The OS must have taken the changed directory: the mapped clone's template is the owner's, at full size.
597 auto* home_base = reinterpret_cast<uint8_t*>(home.module);
598 auto* home_nt = at<IMAGE_NT_HEADERS64>(home_base, reinterpret_cast<IMAGE_DOS_HEADER*>(home_base)->e_lfanew);
599 const auto* home_tls =
600 at<IMAGE_TLS_DIRECTORY64>(home_base, directory(home_nt, IMAGE_DIRECTORY_ENTRY_TLS).VirtualAddress);
601 const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData;
602 if (home_tls->EndAddressOfRawData - home_tls->StartAddressOfRawData != raw + owner.SizeOfZeroFill ||
603 std::memcmp(reinterpret_cast<const void*>(home_tls->StartAddressOfRawData),
604 reinterpret_cast<const void*>(owner.StartAddressOfRawData), raw) != 0)
605 return drop("the home clone's mapped TLS template is not the owner's");
606
607 // Everything that can throw comes first: past the move this records the result and nothing more.
608 const std::string name = module_file_name(exe);
609 // _tls_index sits in .data; made writable first in case a linker merged it into a read-only section.
610 DWORD old_protect = 0;
611 if (!VirtualProtect(owner_index, sizeof(DWORD), PAGE_READWRITE, &old_protect))
612 return drop("the owner's _tls_index cannot be written");
613 move_index0_on_this_thread(owner_index, home.index);
614 VirtualProtect(owner_index, sizeof(DWORD), old_protect, &old_protect);
615
616 // Kept loaded for the process lifetime: FreeLibrary would make the OS free every thread's block at its index, the
617 // owner's from now on. Not in g_tls_clones for that reason. Its file cannot be deleted while it is mapped
618 // (DeleteFileW and a POSIX-semantics delete both fail with ERROR_ACCESS_DENIED on Windows 11), so it stays until
619 // a later run's sweep.
620 g_index0.home = home;
621 std::snprintf(g_index0.owner, sizeof(g_index0.owner), "%s", name.c_str());
622 g_index0.moved = true;
623 return {};
624}
625
369// Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this 626// Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this
370// thread's record, so it also works after the module that installed the copy is gone. 627// thread's record, so it also works after the module that installed the copy is gone.
371void release_thread_slot(size_t slot) { 628void release_thread_slot(size_t slot) {
372 if (slot >= kMaxMappedTlsModules) return; 629 if (slot >= kTlsSlotCount) return;
373 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 630 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
374 if (!entry.module && !entry.block) return; 631 if (!entry.module && !entry.block) return;
375 if (entry.ga_view) { 632 if (entry.ga_view) {
@@ -438,7 +695,7 @@ void** make_ga_view(const Module& m, void* block) {
438} 695}
439 696
440void install_thread_block(Module& m) { 697void install_thread_block(Module& m) {
441 if (m.tls_slot >= kMaxMappedTlsModules) return; 698 if (m.tls_slot >= kTlsSlotCount) return;
442 const size_t slot = m.tls_slot; 699 const size_t slot = m.tls_slot;
443 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 700 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
444 if (entry.module == &m && entry.generation == m.tls_generation) return; 701 if (entry.module == &m && entry.generation == m.tls_generation) return;
@@ -530,7 +787,7 @@ bool ga_tls_patch_enabled() {
530} 787}
531 788
532void uninstall_thread_block(Module& m) { 789void uninstall_thread_block(Module& m) {
533 if (m.tls_slot >= kMaxMappedTlsModules) return; 790 if (m.tls_slot >= kTlsSlotCount) return;
534 const size_t slot = m.tls_slot; 791 const size_t slot = m.tls_slot;
535 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 792 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
536 if (entry.module != &m || entry.generation != m.tls_generation) return; 793 if (entry.module != &m || entry.generation != m.tls_generation) return;
@@ -697,7 +954,7 @@ constexpr size_t kMaxEndedThreads = 1024;
697// load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done. 954// load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done.
698void install_on_existing_threads(Module& m) { 955void install_on_existing_threads(Module& m) {
699 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill; 956 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill;
700 if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kMaxMappedTlsModules) return; 957 if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kTlsSlotCount) return;
701 // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which 958 // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which
702 // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours. 959 // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours.
703 if (!query_thread_fn()) return; 960 if (!query_thread_fn()) return;
@@ -882,7 +1139,11 @@ void release_existing_blocks_of_this_thread() {
882// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under 1139// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under
883// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an 1140// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an
884// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events 1141// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events
885// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. 1142// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. Windows allocates
1143// every module's block before the first DllMain of a new thread, and runs an EXE's TLS callbacks after every DllMain,
1144// for attach and for detach (measured on Windows 11 26300). So attach installs all copies first and then runs the
1145// callbacks, the DLL slots in order and the executable's last; detach runs the DLL slots in reverse and then the
1146// executable's slot, each releasing its copy after its callbacks.
886void __cdecl on_host_thread_event(DWORD reason) { 1147void __cdecl on_host_thread_event(DWORD reason) {
887 SharedTlsLock lock; 1148 SharedTlsLock lock;
888 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events 1149 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events
@@ -893,14 +1154,25 @@ void __cdecl on_host_thread_event(DWORD reason) {
893 } catch (const std::exception& e) { 1154 } catch (const std::exception& e) {
894 std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what()); 1155 std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what());
895 } 1156 }
896 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { 1157 std::array<Module*, kTlsSlotCount> installed{};
1158 for (size_t slot = 0; slot < kTlsSlotCount; ++slot) {
897 Module* m = g_tls_slot_owners[slot].load(); 1159 Module* m = g_tls_slot_owners[slot].load();
898 if (!m) continue; 1160 if (!m) continue;
899 try { 1161 try {
900 install_thread_block(*m); 1162 install_thread_block(*m);
901 if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); 1163 installed[slot] = m;
1164 } catch (const std::exception& e) {
1165 // The thread runs on without this module's TLS (and its callbacks); later slots still get theirs.
1166 std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(),
1167 e.what());
1168 }
1169 }
1170 for (size_t slot = 0; slot < kTlsSlotCount; ++slot) {
1171 Module* m = installed[slot];
1172 if (!m || !m->initialised) continue;
1173 try {
1174 run_callbacks(*m, DLL_THREAD_ATTACH);
902 } catch (const std::exception& e) { 1175 } catch (const std::exception& e) {
903 // The thread runs on without this module's TLS; later slots still get theirs.
904 std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), 1176 std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(),
905 e.what()); 1177 e.what());
906 } 1178 }
@@ -913,7 +1185,8 @@ void __cdecl on_host_thread_event(DWORD reason) {
913 } catch (const std::exception& e) { 1185 } catch (const std::exception& e) {
914 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what()); 1186 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what());
915 } 1187 }
916 for (size_t i = kMaxMappedTlsModules; i-- > 0;) { 1188 for (size_t step = 0; step < kTlsSlotCount; ++step) {
1189 const size_t i = step < kMaxMappedTlsModules ? kMaxMappedTlsModules - 1 - step : kMainImageSlot;
917 Module* m = g_tls_slot_owners[i].load(); 1190 Module* m = g_tls_slot_owners[i].load();
918 if (m && g_thread_tls_slots[i].module == m && 1191 if (m && g_thread_tls_slots[i].module == m &&
919 g_thread_tls_slots[i].generation == m->tls_generation) { 1192 g_thread_tls_slots[i].generation == m->tls_generation) {
@@ -1017,6 +1290,26 @@ void redirect_pc_to_file_header_at(const void* resolved) {
1017// Declared in pe_loader.h; the body needs the internal clone registry above. 1290// Declared in pe_loader.h; the body needs the internal clone registry above.
1018void cleanup_tls_clones() { cleanup_tls_clones_internal(); } 1291void cleanup_tls_clones() { cleanup_tls_clones_internal(); }
1019 1292
1293bool reserve_tls_index0(std::string* why) {
1294 std::lock_guard alloc_lock(g_tls_alloc_mutex);
1295 static bool attempted = false; // once: a later attempt could meet threads that already run this EXE's code
1296 if (!attempted) {
1297 attempted = true;
1298 // A throw (std::filesystem::temp_directory_path when GetTempPathW fails, an allocation) is a failed
1299 // reservation like any other: gta6rt calls this before main, where an exception would end it with no message.
1300 try {
1301 const std::string reason = reserve_index0();
1302 std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", reason.c_str());
1303 } catch (const std::exception& e) {
1304 std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", e.what());
1305 } catch (...) {
1306 std::snprintf(g_index0.why, sizeof(g_index0.why), "an unknown error while reserving it");
1307 }
1308 }
1309 if (why) *why = g_index0.moved ? std::string() : std::string(g_index0.why);
1310 return g_index0.moved;
1311}
1312
1020namespace { 1313namespace {
1021bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { 1314bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) {
1022 return static_cast<Loader*>(ctx)->find_address(address, module, rva); 1315 return static_cast<Loader*>(ctx)->find_address(address, module, rva);
@@ -1099,7 +1392,7 @@ Loader::~Loader() {
1099 shims::remove_module_lookup(this); 1392 shims::remove_module_lookup(this);
1100 for (auto* m : order_) { 1393 for (auto* m : order_) {
1101 // TLS state must go away before the image and its TLS block are unmapped. 1394 // TLS state must go away before the image and its TLS block are unmapped.
1102 if (m->tls_index != kNoTlsIndex && m->tls_slot < kMaxMappedTlsModules) { 1395 if (m->tls_index != kNoTlsIndex && m->tls_slot < kTlsSlotCount) {
1103 // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a 1396 // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a
1104 // thread that still holds a copy frees it when it ends (on_host_thread_event). 1397 // thread that still holds a copy frees it when it ends (on_host_thread_event).
1105 { 1398 {
@@ -1514,7 +1807,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
1514// Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to 1807// Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to
1515// gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone 1808// gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone
1516// getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than 1809// getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than
1517// silently sharing (and corrupting) a slot. 1810// silently sharing (and corrupting) a slot. An executable takes index 0 instead (kMainImageSlot), as on Windows.
1518void Loader::initialize_tls(Module& m) { 1811void Loader::initialize_tls(Module& m) {
1519 auto* tls = tls_directory(m); 1812 auto* tls = tls_directory(m);
1520 if (!tls) return; 1813 if (!tls) return;
@@ -1543,26 +1836,51 @@ void Loader::initialize_tls(Module& m) {
1543 1836
1544 if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); 1837 if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array");
1545 1838
1546 size_t slot = kMaxMappedTlsModules; 1839 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
1840 const bool executable = (nt->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0;
1841
1842 size_t slot = kTlsSlotCount;
1547 DWORD index = TLS_OUT_OF_INDEXES; 1843 DWORD index = TLS_OUT_OF_INDEXES;
1548 { 1844 {
1549 std::lock_guard alloc_lock(g_tls_alloc_mutex); 1845 std::lock_guard alloc_lock(g_tls_alloc_mutex);
1550 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { 1846 if (executable) {
1551 if (g_tls_slot_owners[i].load() == nullptr) { 1847 if (g_index0.moved && g_tls_slot_owners[kMainImageSlot].load() == nullptr) {
1552 slot = i; 1848 slot = kMainImageSlot;
1553 break; 1849 index = 0;
1850 if (!g_index0.traced && startup_trace::enabled()) {
1851 g_index0.traced = true;
1852 startup_trace::event("tls_index0", "\"owner\":" + startup_trace::quote(g_index0.owner) +
1853 ",\"moved_to\":" + std::to_string(g_index0.home.index));
1854 }
1855 } else {
1856 // Mapped on as a DLL is: its code that reads _tls_index works, but its /GA code would read and write
1857 // the block in slot 0, which is the runtime's own TLS or the other executable's. gta6rt refuses to
1858 // run such an image (main.cpp); a Loader user must not run its code either.
1859 std::fprintf(stderr,
1860 "[rt] loader: %s does not get module TLS index 0 (%s); its code built with /GA would use "
1861 "another module's TLS\n",
1862 m.name.c_str(), g_index0.moved ? "another mapped executable holds it" : g_index0.why);
1863 }
1864 }
1865 if (slot == kTlsSlotCount) {
1866 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) {
1867 if (g_tls_slot_owners[i].load() == nullptr) {
1868 slot = i;
1869 break;
1870 }
1554 } 1871 }
1872 if (slot >= kMaxMappedTlsModules)
1873 throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) +
1874 " manually mapped static TLS slots are in use");
1875
1876 // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with
1877 // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock).
1878 index = ensure_tls_host(slot).index;
1879 if (index == TLS_OUT_OF_INDEXES)
1880 throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index");
1881 if (index >= kMaxModuleTlsSlots)
1882 throw std::runtime_error(m.name + ": reserved TLS index is out of range");
1555 } 1883 }
1556 if (slot >= kMaxMappedTlsModules)
1557 throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) +
1558 " manually mapped static TLS slots are in use");
1559
1560 // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with
1561 // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock).
1562 index = ensure_tls_host(slot).index;
1563 if (index == TLS_OUT_OF_INDEXES)
1564 throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index");
1565 if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range");
1566 1884
1567 // The fields are complete before a thread event can see the owner. 1885 // The fields are complete before a thread event can see the owner.
1568 ExclusiveTlsLock lock; 1886 ExclusiveTlsLock lock;