upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src
diff options
context:
space:
mode:
authorKam471 <kam471@users.noreply.github.com>2026-11-21 22:19:03 +0000
committerKam471 <kam471@users.noreply.github.com>2026-11-21 23:29:24 +0000
commit993a2cbf72a9509ca730e509ea38e455d35f5a74 (patch)
treea3d6dc8481bfeabb7e5a94840ef4474504add23d /runtime/src
parentd7cbc3e7cb4d031c790dddd265a83fb6a1a1a7a5 (diff)
Runtime: install static TLS for mapped images
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/main.cpp10
-rw-r--r--runtime/src/pe_loader.cpp267
-rw-r--r--runtime/src/pe_loader.h49
-rw-r--r--runtime/src/tls_host.cpp15
4 files changed, 266 insertions, 75 deletions
diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp
index d79ff97dc..07b9086f9 100644
--- a/runtime/src/main.cpp
+++ b/runtime/src/main.cpp
@@ -1,8 +1,10 @@
1// gta6rt: native runtime for the Xbox Series build. 1// gta6rt: native runtime for the Xbox Series build.
2// 2//
3// gta6rt --dry-run <image> [--game-dir DIR] 3// gta6rt --dry-run <image> [--game-dir DIR]
4// Maps the image and its bundled modules, applies relocations, binds every import and prints a report. 4// Maps the image and its bundled modules, applies relocations, binds every import, installs static TLS for
5// No code from the image runs. 5// this thread and prints a report. No code from the mapped images
6// runs. TLS needs the runtime's own gta6rt_tls_host.dll, which reserves the module TLS index; system DLLs are
7// loaded to resolve host imports, as before.
6// 8//
7// gta6rt --init <image> [--game-dir DIR] 9// gta6rt --init <image> [--game-dir DIR]
8// The same mapping, then each loaded DLL's TLS callbacks and DllMain(DLL_PROCESS_ATTACH) are run. 10// The same mapping, then each loaded DLL's TLS callbacks and DllMain(DLL_PROCESS_ATTACH) are run.
@@ -66,9 +68,9 @@ int wmain(int argc, wchar_t** argv) {
66 68
67 try { 69 try {
68 rt::Loader loader(game_dir); 70 rt::Loader loader(game_dir);
69 rt::Module& main_module = loader.load(image); 71 rt::Module& main_module = loader.load(image); // maps, binds and installs TLS; runs no image code
70 if (init || run) { 72 if (init || run) {
71 loader.initialise(); 73 loader.initialise(); // TLS callbacks, then DllMain(DLL_PROCESS_ATTACH) for DLLs
72 std::printf("%zu module(s) initialised\n", loader.modules().size()); 74 std::printf("%zu module(s) initialised\n", loader.modules().size());
73 } 75 }
74 int unimplemented = 0; 76 int unimplemented = 0;
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index 82357c859..ca12273b2 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -1,11 +1,16 @@
1#include "pe_loader.h" 1#include "pe_loader.h"
2 2
3#include <windows.h> 3#include <windows.h>
4#include <intrin.h>
4 5
5#include <algorithm> 6#include <algorithm>
7#include <atomic>
8#include <cstdio>
9#include <cstdlib>
6#include <cstring> 10#include <cstring>
7#include <fstream> 11#include <fstream>
8#include <stdexcept> 12#include <stdexcept>
13#include <vector>
9 14
10#include "../shims/shims.h" 15#include "../shims/shims.h"
11 16
@@ -42,6 +47,78 @@ std::string read_string(const std::string& name, uint8_t* base, uint32_t image_s
42 return {s, end}; 47 return {s, end};
43} 48}
44 49
50// The TLS directory holds virtual addresses, which relocations have already moved to this mapping.
51uint64_t rva_in(const Module& m, uint64_t va, const char* what) {
52 const uint64_t base = reinterpret_cast<uint64_t>(m.base);
53 if (va < base || va - base >= m.size) throw std::runtime_error(m.name + ": " + what + " is outside the image");
54 return va - base;
55}
56
57IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) {
58 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
59 const auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS];
60 if (!dir.Size || !dir.VirtualAddress) return nullptr;
61 require_range(m.name, dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64), m.size, "the TLS directory");
62 return at<IMAGE_TLS_DIRECTORY64>(m.base, dir.VirtualAddress);
63}
64
65// __declspec(thread) reads TEB->ThreadLocalStoragePointer[_tls_index] at gs:[58h]. That array is indexed by the
66// loader-assigned per-module TLS index and is a different index space from TlsAlloc/TlsGetValue (TlsSlots). Only the OS
67// loader can allocate a module index, so the runtime ships a minimal DLL whose only content is a TLS anchor
68// (src/tls_host.cpp). Loading it makes the OS reserve an index and give every thread a block for it; the native loader
69// reuses that index for the mapped image. One helper means one mapped TLS module at a time.
70constexpr DWORD kMaxModuleTlsSlots = 64;
71void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); }
72
73struct TlsHostModule {
74 HMODULE module = nullptr;
75 DWORD index = TLS_OUT_OF_INDEXES;
76};
77
78TlsHostModule load_tls_host() {
79 TlsHostModule host;
80 wchar_t exe[MAX_PATH] = {};
81 if (!GetModuleFileNameW(nullptr, exe, MAX_PATH)) return host;
82 const std::filesystem::path path = std::filesystem::path(exe).parent_path() / L"gta6rt_tls_host.dll";
83 // The helper is linked with the static CRT (/MT), so it needs only system DLLs. Restricting the dependency search
84 // to System32 keeps a game-supplied vcruntime next to the executable from being picked up.
85 host.module = LoadLibraryExW(path.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
86 if (!host.module) return host;
87
88 auto* base = reinterpret_cast<uint8_t*>(host.module);
89 auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(base);
90 auto* nt = at<IMAGE_NT_HEADERS64>(base, dos->e_lfanew);
91 const auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS];
92 if (!dir.Size || !dir.VirtualAddress) {
93 FreeLibrary(host.module);
94 host.module = nullptr;
95 return host;
96 }
97 auto* tls = at<IMAGE_TLS_DIRECTORY64>(base, dir.VirtualAddress);
98 if (!tls->AddressOfIndex) {
99 FreeLibrary(host.module);
100 host.module = nullptr;
101 return host;
102 }
103 host.index = *reinterpret_cast<DWORD*>(tls->AddressOfIndex);
104 return host;
105}
106
107TlsHostModule& tls_host() {
108 // The helper stays loaded for the process lifetime: unloading it would release the reserved TLS index. Its own
109 // per-thread blocks are restored by uninstall_tls_for_thread, so the OS loader can free them normally.
110 static TlsHostModule host = load_tls_host();
111 return host;
112}
113
114std::atomic<Module*> g_tls_slot_owner{nullptr};
115
116// Per-thread installation state. Only one mapped TLS module can own the reserved slot, so one entry per thread is
117// enough; the saved pointer is the helper DLL's own block that the OS loader will free at thread exit.
118thread_local Module* g_thread_tls_module = nullptr;
119thread_local void* g_thread_tls_saved = nullptr;
120thread_local void* g_thread_tls_block = nullptr;
121
45// The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used. 122// The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used.
46bool prefer_host_copy(const std::string& dll) { 123bool prefer_host_copy(const std::string& dll) {
47 static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll", 124 static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll",
@@ -56,10 +133,17 @@ bool prefer_host_copy(const std::string& dll) {
56 133
57Loader::~Loader() { 134Loader::~Loader() {
58 for (auto* m : order_) { 135 for (auto* m : order_) {
136 // TLS state must go away before the image and its TLS block are unmapped.
137 if (m->tls_index != kNoTlsIndex) {
138 // Only the loading thread has this module installed; other threads must uninstall for themselves before
139 // the Loader is destroyed.
140 uninstall_tls_for_thread(*m);
141 Module* owner = m;
142 g_tls_slot_owner.compare_exchange_strong(owner, nullptr);
143 }
59 // Before the image is freed: a stale table would let a later stack walk read unmapped memory. 144 // Before the image is freed: a stale table would let a later stack walk read unmapped memory.
60 if (m->function_table) RtlDeleteFunctionTable(static_cast<PRUNTIME_FUNCTION>(m->function_table)); 145 if (m->function_table) RtlDeleteFunctionTable(static_cast<PRUNTIME_FUNCTION>(m->function_table));
61 if (m->tls_block) VirtualFree(m->tls_block, 0, MEM_RELEASE); 146 if (m->tls_block) VirtualFree(m->tls_block, 0, MEM_RELEASE);
62 if (m->has_tls_slot) TlsFree(m->tls_slot);
63 if (m->base) VirtualFree(m->base, 0, MEM_RELEASE); 147 if (m->base) VirtualFree(m->base, 0, MEM_RELEASE);
64 delete m; 148 delete m;
65 } 149 }
@@ -122,70 +206,12 @@ void Loader::initialise() {
122 206
123void Loader::initialise(Module& m) { 207void Loader::initialise(Module& m) {
124 if (m.initialised) return; 208 if (m.initialised) return;
125 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
126 const uint64_t base = reinterpret_cast<uint64_t>(m.base);
127
128 // The TLS directory holds virtual addresses, which relocations have already moved to this mapping.
129 auto rva_of = [&](uint64_t va, const char* what) {
130 if (va < base || va - base >= m.size)
131 throw std::runtime_error(m.name + ": " + what + " is outside the image");
132 return va - base;
133 };
134
135 auto& tls_dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS];
136 if (tls_dir.Size) {
137 require_range(m.name, tls_dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64), m.size, "the TLS directory");
138 auto* tls = at<IMAGE_TLS_DIRECTORY64>(m.base, tls_dir.VirtualAddress);
139
140 uint64_t start = 0, template_size = 0;
141 if (tls->StartAddressOfRawData || tls->EndAddressOfRawData) {
142 start = rva_of(tls->StartAddressOfRawData, "the TLS template");
143 uint64_t end = rva_of(tls->EndAddressOfRawData, "the end of the TLS template");
144 if (end < start) throw std::runtime_error(m.name + ": the TLS template ends before it starts");
145 template_size = end - start;
146 require_range(m.name, start, template_size, m.size, "the TLS template");
147 }
148 m.tls_block_size = template_size + tls->SizeOfZeroFill;
149 if (m.tls_block_size > (1u << 20)) throw std::runtime_error(m.name + ": the TLS block is larger than 1 MiB");
150 if (m.tls_block_size) {
151 m.tls_block = VirtualAlloc(nullptr, static_cast<SIZE_T>(m.tls_block_size), MEM_RESERVE | MEM_COMMIT,
152 PAGE_READWRITE);
153 if (!m.tls_block) throw std::runtime_error(m.name + ": cannot allocate the TLS block");
154 if (template_size) std::memcpy(m.tls_block, m.base + start, static_cast<size_t>(template_size));
155 }
156
157 if (tls->AddressOfIndex) {
158 uint64_t index_rva = rva_of(tls->AddressOfIndex, "the TLS index");
159 require_range(m.name, index_rva, sizeof(uint32_t), m.size, "the TLS index");
160 DWORD slot = TlsAlloc();
161 if (slot == TLS_OUT_OF_INDEXES) throw std::runtime_error(m.name + ": no TLS slot is free");
162 m.tls_slot = slot;
163 m.has_tls_slot = true;
164 if (m.tls_block) TlsSetValue(slot, m.tls_block);
165 // The index lives in a writable section, but protect_sections already ran, so lift it for the write.
166 auto* index = m.base + index_rva;
167 auto* page = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(index) & ~uintptr_t(0xFFF));
168 DWORD old = 0, ignored = 0;
169 if (!VirtualProtect(page, 0x1000, PAGE_READWRITE, &old))
170 throw std::runtime_error(m.name + ": the TLS index can't be written");
171 *reinterpret_cast<uint32_t*>(index) = slot;
172 VirtualProtect(page, 0x1000, old, &ignored);
173 }
174 209
175 if (tls->AddressOfCallBacks) { 210 // TLS was installed by load(); initialise() only delivers the events, so no slot is allocated or written twice.
176 uint64_t table_rva = rva_of(tls->AddressOfCallBacks, "the TLS callback table"); 211 run_tls_callbacks(m, DLL_PROCESS_ATTACH);
177 for (uint64_t i = 0;; ++i) {
178 uint64_t entry_rva = table_rva + i * sizeof(uint64_t);
179 require_range(m.name, entry_rva, sizeof(uint64_t), m.size, "a TLS callback table entry");
180 uint64_t fn = *at<uint64_t>(m.base, static_cast<uint32_t>(entry_rva));
181 if (!fn) break;
182 auto callback = reinterpret_cast<void(NTAPI*)(void*, DWORD, void*)>(m.base + rva_of(fn, "a TLS callback"));
183 callback(m.base, DLL_PROCESS_ATTACH, nullptr);
184 }
185 }
186 }
187 212
188 // Only a DLL gets DllMain. An EXE's entry point has a different signature and is the caller's to run. 213 // Only a DLL gets DllMain. An EXE's entry point has a different signature and is the caller's to run.
214 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
189 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { 215 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) {
190 if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image"); 216 if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image");
191 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); 217 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva);
@@ -276,10 +302,127 @@ Module& Loader::map_image(const std::filesystem::path& path) {
276 block = reinterpret_cast<IMAGE_BASE_RELOCATION*>(reinterpret_cast<uint8_t*>(block) + block->SizeOfBlock); 302 block = reinterpret_cast<IMAGE_BASE_RELOCATION*>(reinterpret_cast<uint8_t*>(block) + block->SizeOfBlock);
277 } 303 }
278 } 304 }
305 // The TLS directory and the exception directory hold virtual addresses, so both are read after relocation. TLS is
306 // installed here, before bind_imports can return control to the caller and before any image code can run.
307 initialize_tls(*m);
279 parse_exports(*m); 308 parse_exports(*m);
280 return *m; 309 return *m;
281} 310}
282 311
312// Static TLS for the thread that calls load(). The PE TLS directory only carries the template (Start..End) and the
313// zero-fill size; it has no field naming the TLS block. The Windows loader allocates a block per module per thread and
314// puts it in TEB->ThreadLocalStoragePointer[module index], which is what __declspec(thread) code reads via _tls_index.
315// Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to
316// gta6rt_tls_host.dll. That makes one manually mapped TLS module work; a second one is rejected rather than silently
317// sharing (and corrupting) the same slot.
318void Loader::initialize_tls(Module& m) {
319 auto* tls = tls_directory(m);
320 if (!tls) return;
321 // A present but all-zero directory is treated like an absent one.
322 if (!tls->StartAddressOfRawData && !tls->EndAddressOfRawData && !tls->AddressOfIndex && !tls->AddressOfCallBacks &&
323 !tls->SizeOfZeroFill)
324 return;
325 if (tls->EndAddressOfRawData < tls->StartAddressOfRawData)
326 throw std::runtime_error(m.name + ": TLS template end precedes its start");
327 uint64_t raw = tls->EndAddressOfRawData - tls->StartAddressOfRawData;
328 uint64_t total = raw + tls->SizeOfZeroFill;
329 if (total > 0xFFFFFFFFull) throw std::runtime_error(m.name + ": TLS block is too large");
330 const uint32_t raw_rva =
331 raw ? static_cast<uint32_t>(rva_in(m, tls->StartAddressOfRawData, "the TLS template")) : 0;
332 if (raw) require_range(m.name, raw_rva, raw, m.size, "the TLS template");
333 uint64_t index_rva = 0;
334 if (tls->AddressOfIndex) {
335 index_rva = rva_in(m, tls->AddressOfIndex, "the TLS index");
336 require_range(m.name, index_rva, sizeof(uint32_t), m.size, "the TLS index");
337 }
338
339 DWORD index = tls_host().index;
340 if (index == TLS_OUT_OF_INDEXES)
341 throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index");
342 if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range");
343 if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array");
344
345 Module* expected = nullptr;
346 if (!g_tls_slot_owner.compare_exchange_strong(expected, &m))
347 throw std::runtime_error(m.name + ": only one manually mapped module may use static TLS at a time");
348
349 m.tls_index = index;
350 m.tls_template = raw ? m.base + raw_rva : nullptr;
351 m.tls_raw_size = static_cast<uint32_t>(raw);
352 m.tls_zero_fill = tls->SizeOfZeroFill;
353 m.tls_block_size = static_cast<uint32_t>(total);
354 // The index lives in a writable section and protect_sections() has not run yet, so the write needs no
355 // VirtualProtect dance.
356 if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index;
357 try {
358 install_tls_for_thread(m);
359 } catch (...) {
360 m.tls_index = kNoTlsIndex;
361 g_tls_slot_owner = nullptr;
362 throw;
363 }
364}
365
366void Loader::install_tls_for_thread(Module& m) {
367 if (m.tls_index == kNoTlsIndex) return;
368 if (g_thread_tls_module == &m) return;
369 if (g_thread_tls_module)
370 throw std::runtime_error("another manually mapped module's TLS is already installed in this thread");
371
372 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill;
373 if (!total) return;
374 void** slots = module_tls_slots();
375 if (!slots || m.tls_index >= kMaxModuleTlsSlots)
376 throw std::runtime_error(m.name + ": cannot install TLS in this thread");
377
378 void* block = VirtualAlloc(nullptr, static_cast<SIZE_T>(total), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
379 if (!block) throw std::runtime_error(m.name + ": TLS block allocation failed");
380 if (m.tls_raw_size) std::memcpy(block, m.tls_template, m.tls_raw_size);
381 if (m.tls_zero_fill)
382 std::memset(static_cast<uint8_t*>(block) + m.tls_raw_size, 0, m.tls_zero_fill);
383
384 void* saved = slots[m.tls_index];
385 slots[m.tls_index] = block;
386 g_thread_tls_module = &m;
387 g_thread_tls_saved = saved;
388 g_thread_tls_block = block;
389 if (!m.tls_block) {
390 m.tls_block = block;
391 m.tls_saved_block = saved;
392 }
393}
394
395void Loader::uninstall_tls_for_thread(Module& m) {
396 if (g_thread_tls_module != &m) return;
397 void** slots = module_tls_slots();
398 if (slots && m.tls_index < kMaxModuleTlsSlots && slots[m.tls_index] == g_thread_tls_block)
399 slots[m.tls_index] = g_thread_tls_saved;
400 if (m.tls_block == g_thread_tls_block) {
401 m.tls_block = nullptr;
402 m.tls_saved_block = nullptr;
403 }
404 VirtualFree(g_thread_tls_block, 0, MEM_RELEASE);
405 g_thread_tls_module = nullptr;
406 g_thread_tls_saved = nullptr;
407 g_thread_tls_block = nullptr;
408}
409
410void Loader::run_tls_callbacks(Module& m, uint32_t reason) {
411 auto* tls = tls_directory(m);
412 if (!tls || !tls->AddressOfCallBacks) return;
413 const uint64_t table_rva = rva_in(m, tls->AddressOfCallBacks, "the TLS callback table");
414 // The callback table has no length field: it ends at a zero entry, so every step is checked against the image.
415 for (uint64_t i = 0;; ++i) {
416 const uint64_t entry_rva = table_rva + i * sizeof(uint64_t);
417 require_range(m.name, entry_rva, sizeof(uint64_t), m.size, "a TLS callback table entry");
418 const uint64_t fn = *at<uint64_t>(m.base, static_cast<uint32_t>(entry_rva));
419 if (!fn) break;
420 auto callback =
421 reinterpret_cast<PIMAGE_TLS_CALLBACK>(m.base + rva_in(m, fn, "a TLS callback"));
422 callback(m.base, static_cast<DWORD>(reason), nullptr);
423 }
424}
425
283void Loader::parse_exports(Module& m) { 426void Loader::parse_exports(Module& m) {
284 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 427 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
285 auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; 428 auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h
index 5f6d1b7a5..6946f1cc0 100644
--- a/runtime/src/pe_loader.h
+++ b/runtime/src/pe_loader.h
@@ -1,7 +1,9 @@
1// Native PE mapper for Xbox Series (x86-64) images. 1// Native PE mapper for Xbox Series (x86-64) images.
2// Maps an image, applies relocations, binds every import through the shim registry and registers its unwind table. 2// Maps an image, applies relocations, binds every import through the shim registry, registers its unwind table and
3// Mapping never runs code from the image. Loader::initialise() is the one call that does: it sets up the 3// installs static TLS for the calling thread.
4// module's TLS (slot, template and callbacks) and calls a DLL's entry point as DllMain. 4// Mapping never runs code from the image. Loader::initialise() is the one call that does: it sets up the module's TLS
5// (slot, template and callbacks) and calls a DLL's entry point as DllMain.
6// gta6rt_tls_host.dll must sit next to the executable; the loader reuses the module TLS index the OS assigns it.
5#pragma once 7#pragma once
6#include <cstdint> 8#include <cstdint>
7#include <filesystem> 9#include <filesystem>
@@ -13,6 +15,9 @@ namespace rt {
13 15
14enum class Binding { Shim, Host, Module, Unimplemented }; 16enum class Binding { Shim, Host, Module, Unimplemented };
15 17
18// No module TLS index has been assigned (matches TLS_OUT_OF_INDEXES without pulling <windows.h> into this header).
19inline constexpr uint32_t kNoTlsIndex = 0xFFFFFFFFu;
20
16struct ImportRecord { 21struct ImportRecord {
17 std::string dll; 22 std::string dll;
18 std::string name; // "#123" for ordinals 23 std::string name; // "#123" for ordinals
@@ -27,12 +32,6 @@ struct Module {
27 uint32_t size = 0; 32 uint32_t size = 0;
28 uint32_t entry_rva = 0; 33 uint32_t entry_rva = 0;
29 bool relocated = false; 34 bool relocated = false;
30
31 // Filled in by initialise(). The TLS slot and block are owned by the loader and released with it.
32 void* tls_block = nullptr;
33 uint64_t tls_block_size = 0;
34 unsigned tls_slot = 0;
35 bool has_tls_slot = false;
36 bool initialised = false; 35 bool initialised = false;
37 36
38 // The image's exception directory (.pdata), registered with RtlAddFunctionTable by load() so that exception 37 // The image's exception directory (.pdata), registered with RtlAddFunctionTable by load() so that exception
@@ -43,14 +42,31 @@ struct Module {
43 std::vector<ImportRecord> imports; 42 std::vector<ImportRecord> imports;
44 std::map<std::string, void*> exports; // by name, plus "#ordinal" 43 std::map<std::string, void*> exports; // by name, plus "#ordinal"
45 std::map<std::string, std::string> forwarders; // same keys, holding "module.symbol" for re-exports 44 std::map<std::string, std::string> forwarders; // same keys, holding "module.symbol" for re-exports
45
46 // Static TLS (IMAGE_DIRECTORY_ENTRY_TLS). load() installs tls_block in the calling thread and writes tls_index to
47 // the image's _tls_index. tls_index names TEB->ThreadLocalStoragePointer[tls_index], the array
48 // __declspec(thread) reads; it is not a TlsAlloc slot. The loader reserves the index by loading
49 // gta6rt_tls_host.dll, so only one manually mapped TLS module can be live at a time; a second one is rejected
50 // rather than sharing (and corrupting) the slot. install_tls_for_thread() must be called for every other thread
51 // the runtime creates.
52 uint32_t tls_index = kNoTlsIndex;
53 void* tls_block = nullptr; // calling thread's copy of the image's template
54 void* tls_saved_block = nullptr; // helper DLL block replaced in that thread, restored by ~Loader
55 uint32_t tls_block_size = 0; // raw template + zero fill
56 const uint8_t* tls_template = nullptr; // raw template in the mapped image
57 uint32_t tls_raw_size = 0;
58 uint32_t tls_zero_fill = 0;
46}; 59};
47 60
48class Loader { 61class Loader {
49public: 62public:
50 explicit Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) {} 63 explicit Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) {}
64 // Restores the TLS slot for the calling thread. Destroy the Loader on the thread
65 // that called load() while any mapped TLS module is still live.
51 ~Loader(); 66 ~Loader();
52 67
53 // Loads an image and (recursively) the bundled modules it imports. Throws std::runtime_error on failure. 68 // Loads an image and (recursively) the bundled modules it imports. Throws std::runtime_error on failure.
69 // Static TLS is installed here, before any image code can run; initialise() does not install it again.
54 Module& load(const std::filesystem::path& image); 70 Module& load(const std::filesystem::path& image);
55 71
56 const std::vector<Module*>& modules() const { return order_; } 72 const std::vector<Module*>& modules() const { return order_; }
@@ -62,11 +78,26 @@ public:
62 // Runs each loaded module's TLS callbacks and then its DllMain(DLL_PROCESS_ATTACH), dependencies first. 78 // Runs each loaded module's TLS callbacks and then its DllMain(DLL_PROCESS_ATTACH), dependencies first.
63 // Only DLLs get DllMain called: an EXE's entry point is the caller's to run. Throws on a corrupt TLS 79 // Only DLLs get DllMain called: an EXE's entry point is the caller's to run. Throws on a corrupt TLS
64 // directory, a TLS callback outside its image, or a DllMain that returns FALSE. 80 // directory, a TLS callback outside its image, or a DllMain that returns FALSE.
81 // TLS was already installed by load(), so this is safe to call on the loading thread without a second install.
65 void initialise(); 82 void initialise();
66 83
84 // Calls the image's IMAGE_TLS_DIRECTORY64 callbacks in order with (base, reason, nullptr). This is opt-in:
85 // load() never runs image code, and initialise() is the only call inside the Loader that uses it. No-op for
86 // images without TLS callbacks. The loader does not deliver thread attach/detach events: install the thread's
87 // TLS first, then call this with DLL_THREAD_ATTACH/DETACH, and uninstall after the detach callbacks.
88 void run_tls_callbacks(Module& m, uint32_t reason);
89
90 // Installs/removes this module's template copy in the calling thread's TEB slot. load() does this for its caller;
91 // the runtime must call install before mapped code runs on any other thread and uninstall before that thread
92 // exits. Only one TLS module can be installed in a thread. These do not run TLS callbacks (use run_tls_callbacks
93 // with DLL_THREAD_ATTACH/DETACH for that).
94 void install_tls_for_thread(Module& m);
95 void uninstall_tls_for_thread(Module& m);
96
67private: 97private:
68 void initialise(Module& m); 98 void initialise(Module& m);
69 Module& map_image(const std::filesystem::path& path); 99 Module& map_image(const std::filesystem::path& path);
100 void initialize_tls(Module& m);
70 void bind_imports(Module& m); 101 void bind_imports(Module& m);
71 void* resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal); 102 void* resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal);
72 void* resolve_forwarder(const std::string& spec, Binding& binding, int depth); 103 void* resolve_forwarder(const std::string& spec, Binding& binding, int depth);
diff --git a/runtime/src/tls_host.cpp b/runtime/src/tls_host.cpp
new file mode 100644
index 000000000..54322be4f
--- /dev/null
+++ b/runtime/src/tls_host.cpp
@@ -0,0 +1,15 @@
1// Minimal TLS anchor DLL for the native loader.
2//
3// Loading this image makes the Windows loader assign it a per-module TLS index and allocate a block for that index in
4// every thread's TEB. Loader::initialize_tls reuses that reserved index for the manually mapped image, so
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.
7#include <windows.h>
8
9__declspec(thread) unsigned char g_tls_host_anchor = 0;
10
11// Never called. The export keeps the TLS variable (and therefore the image's TLS directory) from being dropped by
12// the linker without making DllMain touch TLS during thread attach/detach.
13extern "C" __declspec(dllexport) void gta6rt_tls_host_keep() { g_tls_host_anchor = 1; }
14
15BOOL WINAPI DllMain(HINSTANCE, DWORD, LPVOID) { return TRUE; }