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:
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/pe_loader.cpp
parentd7cbc3e7cb4d031c790dddd265a83fb6a1a1a7a5 (diff)
Runtime: install static TLS for mapped images
Diffstat (limited to 'runtime/src/pe_loader.cpp')
-rw-r--r--runtime/src/pe_loader.cpp267
1 files changed, 205 insertions, 62 deletions
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];