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:
authorVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 14:19:45 +0100
committerVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 14:19:45 +0100
commit5a8c52e009b855c49a3dbae8ea51ddb36de1ad22 (patch)
tree6110dada00ca400240cbea76573957af1e01d259 /runtime/src/pe_loader.cpp
parentf1918a31dfe79909e62e1e7cafa4ab735946c6b9 (diff)
parenta0acd33d77babe67a28e398b2936a9f735a50f5d (diff)
Merge main into test/coverage-gaps (#1299)
Conflicts: runtime/test/shaders/check.py, scripts/run_gpu_tests.py, tests/semantic/regen_fixtures.py, tests/semantic/test_value_semantics.py AI-assisted.
Diffstat (limited to 'runtime/src/pe_loader.cpp')
-rw-r--r--runtime/src/pe_loader.cpp327
1 files changed, 243 insertions, 84 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index 15a62d9b4..1ab9c7801 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -9,6 +9,7 @@
9#include <cstdlib> 9#include <cstdlib>
10#include <cstring> 10#include <cstring>
11#include <fstream> 11#include <fstream>
12#include <mutex>
12#include <stdexcept> 13#include <stdexcept>
13#include <vector> 14#include <vector>
14 15
@@ -75,6 +76,8 @@ IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) {
75constexpr DWORD kMaxModuleTlsSlots = 64; 76constexpr DWORD kMaxModuleTlsSlots = 64;
76void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); } 77void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); }
77 78
79void __cdecl on_host_thread_event(DWORD reason);
80
78struct TlsHostModule { 81struct TlsHostModule {
79 HMODULE module = nullptr; 82 HMODULE module = nullptr;
80 DWORD index = TLS_OUT_OF_INDEXES; 83 DWORD index = TLS_OUT_OF_INDEXES;
@@ -117,6 +120,10 @@ TlsHostModule load_tls_host() {
117 return host; 120 return host;
118 } 121 }
119 host.index = *reinterpret_cast<DWORD*>(tls->AddressOfIndex); 122 host.index = *reinterpret_cast<DWORD*>(tls->AddressOfIndex);
123 // From here on the helper's DllMain reports every thread the process starts or ends (on_host_thread_event).
124 using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD));
125 if (auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event")))
126 set(&on_host_thread_event);
120 return host; 127 return host;
121} 128}
122 129
@@ -134,6 +141,121 @@ std::atomic<Module*> g_tls_slot_owner{nullptr};
134thread_local Module* g_thread_tls_module = nullptr; 141thread_local Module* g_thread_tls_module = nullptr;
135thread_local void* g_thread_tls_saved = nullptr; 142thread_local void* g_thread_tls_saved = nullptr;
136thread_local void* g_thread_tls_block = nullptr; 143thread_local void* g_thread_tls_block = nullptr;
144thread_local uint32_t g_thread_tls_index = kNoTlsIndex;
145
146// Orders the TLS owner's publication, its `initialised` flag and its retirement against the thread events. Shared in
147// on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows
148// loader lock, which the events run under).
149SRWLOCK g_tls_lock = SRWLOCK_INIT;
150struct SharedTlsLock {
151 SharedTlsLock() { AcquireSRWLockShared(&g_tls_lock); }
152 ~SharedTlsLock() { ReleaseSRWLockShared(&g_tls_lock); }
153 SharedTlsLock(const SharedTlsLock&) = delete;
154 SharedTlsLock& operator=(const SharedTlsLock&) = delete;
155};
156struct ExclusiveTlsLock {
157 ExclusiveTlsLock() { AcquireSRWLockExclusive(&g_tls_lock); }
158 ~ExclusiveTlsLock() { ReleaseSRWLockExclusive(&g_tls_lock); }
159 ExclusiveTlsLock(const ExclusiveTlsLock&) = delete;
160 ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete;
161};
162
163// Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this
164// thread's record, so it also works after the module that installed the copy is gone.
165void release_thread_block() {
166 if (!g_thread_tls_block) return;
167 void** slots = module_tls_slots();
168 if (slots && g_thread_tls_index < kMaxModuleTlsSlots && slots[g_thread_tls_index] == g_thread_tls_block)
169 slots[g_thread_tls_index] = g_thread_tls_saved;
170 VirtualFree(g_thread_tls_block, 0, MEM_RELEASE);
171 g_thread_tls_module = nullptr;
172 g_thread_tls_saved = nullptr;
173 g_thread_tls_block = nullptr;
174 g_thread_tls_index = kNoTlsIndex;
175}
176
177void install_thread_block(Module& m) {
178 if (m.tls_index == kNoTlsIndex) return;
179 if (g_thread_tls_module == &m) return;
180 if (g_thread_tls_module) {
181 // A copy left by a module whose Loader is gone is released; a live module's is a conflict.
182 if (g_thread_tls_module == g_tls_slot_owner.load())
183 throw std::runtime_error("another manually mapped module's TLS is already installed in this thread");
184 release_thread_block();
185 }
186
187 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill;
188 if (!total) return;
189 void** slots = module_tls_slots();
190 if (!slots || m.tls_index >= kMaxModuleTlsSlots)
191 throw std::runtime_error(m.name + ": cannot install TLS in this thread");
192
193 void* block = VirtualAlloc(nullptr, static_cast<SIZE_T>(total), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
194 if (!block) throw std::runtime_error(m.name + ": TLS block allocation failed");
195 if (m.tls_raw_size) std::memcpy(block, m.tls_template, m.tls_raw_size);
196 if (m.tls_zero_fill)
197 std::memset(static_cast<uint8_t*>(block) + m.tls_raw_size, 0, m.tls_zero_fill);
198
199 void* saved = slots[m.tls_index];
200 slots[m.tls_index] = block;
201 g_thread_tls_module = &m;
202 g_thread_tls_saved = saved;
203 g_thread_tls_block = block;
204 g_thread_tls_index = m.tls_index;
205}
206
207void uninstall_thread_block(Module& m) {
208 if (g_thread_tls_module != &m) return;
209 if (m.tls_block == g_thread_tls_block) {
210 m.tls_block = nullptr;
211 m.tls_saved_block = nullptr;
212 }
213 release_thread_block();
214}
215
216void run_callbacks(Module& m, uint32_t reason) {
217 auto* tls = tls_directory(m);
218 if (!tls || !tls->AddressOfCallBacks) return;
219 const uint64_t table_rva = rva_in(m, tls->AddressOfCallBacks, "the TLS callback table");
220 // The callback table has no length field: it ends at a zero entry, so every step is checked against the image.
221 for (uint64_t i = 0;; ++i) {
222 const uint64_t entry_rva = table_rva + i * sizeof(uint64_t);
223 require_range(m.name, entry_rva, sizeof(uint64_t), m.size, "a TLS callback table entry");
224 const uint64_t fn = *at<uint64_t>(m.base, static_cast<uint32_t>(entry_rva));
225 if (!fn) break;
226 auto callback =
227 reinterpret_cast<PIMAGE_TLS_CALLBACK>(m.base + rva_in(m, fn, "a TLS callback"));
228 callback(m.base, static_cast<DWORD>(reason), nullptr);
229 }
230}
231
232// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under
233// the Windows loader lock, on that thread. A new thread gets its own copy of the TLS owner's template; an ending one
234// gives the helper's block back before the Windows loader frees it. TLS callbacks get the thread events only after
235// the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. Threads that existed before the
236// module was loaded get nothing: install_tls_for_thread is still the way to cover those.
237void __cdecl on_host_thread_event(DWORD reason) {
238 SharedTlsLock lock;
239 Module* m = g_tls_slot_owner.load();
240 try {
241 if (reason == DLL_THREAD_ATTACH) {
242 if (!m) return;
243 install_thread_block(*m);
244 if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH);
245 } else if (reason == DLL_THREAD_DETACH) {
246 if (m && g_thread_tls_module == m) {
247 if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH);
248 uninstall_thread_block(*m);
249 } else {
250 release_thread_block(); // installed by a module whose Loader is gone (or nothing to do)
251 }
252 }
253 } catch (const std::exception& e) {
254 // Nothing may leave DllMain. The thread runs on without the module's TLS (attach) or keeps the copy (detach).
255 std::fprintf(stderr, "[rt] loader: thread %s: %s\n", reason == DLL_THREAD_ATTACH ? "attach" : "detach",
256 e.what());
257 }
258}
137 259
138// The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used. 260// The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used.
139bool prefer_host_copy(const std::string& dll) { 261bool prefer_host_copy(const std::string& dll) {
@@ -145,6 +267,69 @@ bool prefer_host_copy(const std::string& dll) {
145 return false; 267 return false;
146} 268}
147 269
270// MSVC C++ exceptions in a mapped image. _CxxThrowException (vcruntime140.dll) puts the throwing image's base in the
271// exception record, from RtlPcToFileHeader(pThrowInfo); the frame handler adds the ThrowInfo's RVAs (catchable types,
272// copy constructor, destructor) to it. RtlPcToFileHeader only knows images the Windows loader mapped, so for ours the
273// base is 0 and the exception can't be matched to a catch. The host copies the loader binds get their import of it
274// redirected: the Windows answer first, then the modules a live Loader has mapped (shims::mapped_image_base).
275using PcToFileHeaderFn = PVOID(NTAPI*)(PVOID, PVOID*);
276std::atomic<PcToFileHeaderFn> g_host_pc_to_file_header{nullptr};
277
278PVOID NTAPI pc_to_file_header(PVOID pc, PVOID* base) {
279 if (PVOID found = g_host_pc_to_file_header.load()(pc, base)) return found;
280 uint64_t mapped = 0;
281 if (!shims::mapped_image_base(reinterpret_cast<uint64_t>(pc), mapped)) {
282 *base = nullptr;
283 return nullptr;
284 }
285 *base = reinterpret_cast<PVOID>(mapped);
286 return *base;
287}
288
289// Points every import of RtlPcToFileHeader by name in a host module at pc_to_file_header, once per module. The
290// module is a system DLL the Windows loader has already validated and bound, so its tables are read unchecked.
291// The redirect stays for the process lifetime; with no live Loader it answers exactly as Windows does.
292void redirect_pc_to_file_header(HMODULE host) {
293 static std::mutex mutex;
294 static std::vector<HMODULE> done;
295 std::lock_guard lock(mutex);
296 if (std::find(done.begin(), done.end(), host) != done.end()) return;
297 done.push_back(host);
298
299 auto* base = reinterpret_cast<uint8_t*>(host);
300 auto* nt = at<IMAGE_NT_HEADERS64>(base, reinterpret_cast<IMAGE_DOS_HEADER*>(base)->e_lfanew);
301 const auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
302 if (!dir.Size || !dir.VirtualAddress) return;
303 for (auto* d = at<IMAGE_IMPORT_DESCRIPTOR>(base, dir.VirtualAddress); d->Name; ++d) {
304 if (!d->OriginalFirstThunk) continue; // no name table to match against
305 auto* names = at<IMAGE_THUNK_DATA64>(base, d->OriginalFirstThunk);
306 auto* iat = at<IMAGE_THUNK_DATA64>(base, d->FirstThunk);
307 for (; names->u1.AddressOfData; ++names, ++iat) {
308 if (IMAGE_SNAP_BY_ORDINAL64(names->u1.Ordinal)) continue;
309 auto* by_name = at<IMAGE_IMPORT_BY_NAME>(base, static_cast<uint32_t>(names->u1.AddressOfData));
310 if (std::strcmp(reinterpret_cast<const char*>(by_name->Name), "RtlPcToFileHeader") != 0) continue;
311 auto* slot = reinterpret_cast<void**>(&iat->u1.Function);
312 if (*slot == reinterpret_cast<void*>(&pc_to_file_header)) continue;
313 PcToFileHeaderFn expected = nullptr; // the first bound address is the Windows function
314 g_host_pc_to_file_header.compare_exchange_strong(expected, reinterpret_cast<PcToFileHeaderFn>(*slot));
315 DWORD old = 0;
316 if (!VirtualProtect(slot, sizeof(void*), PAGE_READWRITE, &old)) continue;
317 *slot = reinterpret_cast<void*>(&pc_to_file_header);
318 VirtualProtect(slot, sizeof(void*), old, &old);
319 }
320 }
321}
322
323// The module a host import actually resolved into. GetProcAddress follows forwarders, so this can be another DLL
324// than the one imported (on Windows vcruntime140.dll implements _CxxThrowException itself); that module's
325// RtlPcToFileHeader import is the one the throw calls.
326void redirect_pc_to_file_header_at(const void* resolved) {
327 HMODULE owner = nullptr;
328 if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
329 static_cast<LPCWSTR>(resolved), &owner) && owner)
330 redirect_pc_to_file_header(owner);
331}
332
148} // namespace 333} // namespace
149 334
150namespace { 335namespace {
@@ -172,7 +357,7 @@ Loader::~Loader() {
172 for (auto it = init_order_.rbegin(); it != init_order_.rend(); ++it) { 357 for (auto it = init_order_.rbegin(); it != init_order_.rend(); ++it) {
173 Module& m = **it; 358 Module& m = **it;
174 if (!m.initialised) continue; // a map-only load never opts in to running image code 359 if (!m.initialised) continue; // a map-only load never opts in to running image code
175 m.initialised = false; 360 set_initialised(m, false); // under the TLS lock: thread events stop running its callbacks
176 try { 361 try {
177 run_tls_callbacks(m, DLL_PROCESS_DETACH); 362 run_tls_callbacks(m, DLL_PROCESS_DETACH);
178 } catch (const std::exception& e) { 363 } catch (const std::exception& e) {
@@ -190,11 +375,14 @@ Loader::~Loader() {
190 for (auto* m : order_) { 375 for (auto* m : order_) {
191 // TLS state must go away before the image and its TLS block are unmapped. 376 // TLS state must go away before the image and its TLS block are unmapped.
192 if (m->tls_index != kNoTlsIndex) { 377 if (m->tls_index != kNoTlsIndex) {
193 // Only the loading thread has this module installed; other threads must uninstall for themselves before 378 // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a
194 // the Loader is destroyed. 379 // thread that still holds a copy frees it when it ends (on_host_thread_event).
380 {
381 ExclusiveTlsLock lock;
382 Module* owner = m;
383 g_tls_slot_owner.compare_exchange_strong(owner, nullptr);
384 }
195 uninstall_tls_for_thread(*m); 385 uninstall_tls_for_thread(*m);
196 Module* owner = m;
197 g_tls_slot_owner.compare_exchange_strong(owner, nullptr);
198 } 386 }
199 // Before the image is freed: a stale table would let a later stack walk read unmapped memory. 387 // Before the image is freed: a stale table would let a later stack walk read unmapped memory.
200 if (m->function_table) RtlDeleteFunctionTable(static_cast<PRUNTIME_FUNCTION>(m->function_table)); 388 if (m->function_table) RtlDeleteFunctionTable(static_cast<PRUNTIME_FUNCTION>(m->function_table));
@@ -270,11 +458,18 @@ void Loader::initialise(Module& m) {
270 if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image"); 458 if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image");
271 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); 459 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva);
272 if (!entry(m.base, DLL_PROCESS_ATTACH, nullptr)) { 460 if (!entry(m.base, DLL_PROCESS_ATTACH, nullptr)) {
273 m.initialised = true; // it ran: a second DLL_PROCESS_ATTACH would be wrong 461 set_initialised(m, true); // it ran: a second DLL_PROCESS_ATTACH would be wrong
274 throw std::runtime_error(m.name + ": DllMain returned FALSE"); 462 throw std::runtime_error(m.name + ": DllMain returned FALSE");
275 } 463 }
276 } 464 }
277 m.initialised = true; 465 set_initialised(m, true);
466}
467
468// Under the TLS lock, which orders it against the thread events: they run a module's TLS callbacks only while this is
469// true (from initialise() until ~Loader starts the process detach).
470void Loader::set_initialised(Module& m, bool value) {
471 ExclusiveTlsLock lock;
472 m.initialised = value;
278} 473}
279 474
280Module& Loader::map_image(const std::filesystem::path& path) { 475Module& Loader::map_image(const std::filesystem::path& path) {
@@ -292,12 +487,15 @@ Module& Loader::map_image(const std::filesystem::path& path) {
292 nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) 487 nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC)
293 throw std::runtime_error(name + ": not a PE32+ image"); 488 throw std::runtime_error(name + ": not a PE32+ image");
294 auto& oh = nt->OptionalHeader; 489 auto& oh = nt->OptionalHeader;
295 uint64_t sections = static_cast<uint64_t>(dos->e_lfanew) + 4 + sizeof(IMAGE_FILE_HEADER) + 490 const uint64_t sections = static_cast<uint64_t>(dos->e_lfanew) + 4 + sizeof(IMAGE_FILE_HEADER) +
296 nt->FileHeader.SizeOfOptionalHeader; 491 nt->FileHeader.SizeOfOptionalHeader;
297 if (sections + static_cast<uint64_t>(nt->FileHeader.NumberOfSections) * sizeof(IMAGE_SECTION_HEADER) > file.size()) 492 const uint64_t headers_end =
493 sections + static_cast<uint64_t>(nt->FileHeader.NumberOfSections) * sizeof(IMAGE_SECTION_HEADER);
494 if (headers_end > file.size())
298 throw std::runtime_error(name + ": the section table runs past the end of the file"); 495 throw std::runtime_error(name + ": the section table runs past the end of the file");
299 if (!oh.SizeOfImage || oh.SizeOfHeaders > oh.SizeOfImage || oh.SizeOfHeaders > file.size()) 496 if (!oh.SizeOfImage || oh.SizeOfHeaders < headers_end || oh.SizeOfHeaders > oh.SizeOfImage ||
300 throw std::runtime_error(name + ": SizeOfHeaders and SizeOfImage don't fit the file"); 497 oh.SizeOfHeaders > file.size())
498 throw std::runtime_error(name + ": SizeOfHeaders and SizeOfImage don't fit the headers and file");
301 499
302 auto* m = new Module; 500 auto* m = new Module;
303 m->name = name; 501 m->name = name;
@@ -338,8 +536,9 @@ Module& Loader::map_image(const std::filesystem::path& path) {
338 auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress); 536 auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress);
339 auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size; 537 auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size;
340 while (reinterpret_cast<uint8_t*>(block) < end) { 538 while (reinterpret_cast<uint8_t*>(block) < end) {
341 if (block->SizeOfBlock < sizeof(IMAGE_BASE_RELOCATION) || 539 const size_t remaining = static_cast<size_t>(end - reinterpret_cast<uint8_t*>(block));
342 reinterpret_cast<uint8_t*>(block) + block->SizeOfBlock > end) 540 if (remaining < sizeof(IMAGE_BASE_RELOCATION) || block->SizeOfBlock < sizeof(IMAGE_BASE_RELOCATION) ||
541 block->SizeOfBlock > remaining)
343 throw std::runtime_error(m->name + ": a relocation block doesn't fit the relocation table"); 542 throw std::runtime_error(m->name + ": a relocation block doesn't fit the relocation table");
344 auto* entries = reinterpret_cast<uint16_t*>(block + 1); 543 auto* entries = reinterpret_cast<uint16_t*>(block + 1);
345 size_t count = (block->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2; 544 size_t count = (block->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2;
@@ -407,86 +606,42 @@ void Loader::initialize_tls(Module& m) {
407 if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range"); 606 if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range");
408 if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); 607 if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array");
409 608
410 Module* expected = nullptr; 609 {
411 if (!g_tls_slot_owner.compare_exchange_strong(expected, &m)) 610 // The fields are complete before a thread event can see the owner.
412 throw std::runtime_error(m.name + ": only one manually mapped module may use static TLS at a time"); 611 ExclusiveTlsLock lock;
413 612 Module* expected = nullptr;
414 m.tls_index = index; 613 if (!g_tls_slot_owner.compare_exchange_strong(expected, &m))
415 m.tls_template = raw ? m.base + raw_rva : nullptr; 614 throw std::runtime_error(m.name + ": only one manually mapped module may use static TLS at a time");
416 m.tls_raw_size = static_cast<uint32_t>(raw); 615
417 m.tls_zero_fill = tls->SizeOfZeroFill; 616 m.tls_index = index;
418 m.tls_block_size = static_cast<uint32_t>(total); 617 m.tls_template = raw ? m.base + raw_rva : nullptr;
419 // The index lives in a writable section and protect_sections() has not run yet, so the write needs no 618 m.tls_raw_size = static_cast<uint32_t>(raw);
420 // VirtualProtect dance. 619 m.tls_zero_fill = tls->SizeOfZeroFill;
421 if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index; 620 m.tls_block_size = static_cast<uint32_t>(total);
621 // The index lives in a writable section and protect_sections() has not run yet, so the write needs no
622 // VirtualProtect dance.
623 if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index;
624 }
422 try { 625 try {
423 install_tls_for_thread(m); 626 install_thread_block(m);
424 } catch (...) { 627 } catch (...) {
628 ExclusiveTlsLock lock;
425 m.tls_index = kNoTlsIndex; 629 m.tls_index = kNoTlsIndex;
426 g_tls_slot_owner = nullptr; 630 g_tls_slot_owner = nullptr;
427 throw; 631 throw;
428 } 632 }
429} 633 // The loading thread's copy is the one the Module records (and ~Loader frees on that thread).
430 634 if (g_thread_tls_module == &m) {
431void Loader::install_tls_for_thread(Module& m) { 635 m.tls_block = g_thread_tls_block;
432 if (m.tls_index == kNoTlsIndex) return; 636 m.tls_saved_block = g_thread_tls_saved;
433 if (g_thread_tls_module == &m) return;
434 if (g_thread_tls_module)
435 throw std::runtime_error("another manually mapped module's TLS is already installed in this thread");
436
437 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill;
438 if (!total) return;
439 void** slots = module_tls_slots();
440 if (!slots || m.tls_index >= kMaxModuleTlsSlots)
441 throw std::runtime_error(m.name + ": cannot install TLS in this thread");
442
443 void* block = VirtualAlloc(nullptr, static_cast<SIZE_T>(total), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
444 if (!block) throw std::runtime_error(m.name + ": TLS block allocation failed");
445 if (m.tls_raw_size) std::memcpy(block, m.tls_template, m.tls_raw_size);
446 if (m.tls_zero_fill)
447 std::memset(static_cast<uint8_t*>(block) + m.tls_raw_size, 0, m.tls_zero_fill);
448
449 void* saved = slots[m.tls_index];
450 slots[m.tls_index] = block;
451 g_thread_tls_module = &m;
452 g_thread_tls_saved = saved;
453 g_thread_tls_block = block;
454 if (!m.tls_block) {
455 m.tls_block = block;
456 m.tls_saved_block = saved;
457 } 637 }
458} 638}
459 639
460void Loader::uninstall_tls_for_thread(Module& m) { 640void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); }
461 if (g_thread_tls_module != &m) return;
462 void** slots = module_tls_slots();
463 if (slots && m.tls_index < kMaxModuleTlsSlots && slots[m.tls_index] == g_thread_tls_block)
464 slots[m.tls_index] = g_thread_tls_saved;
465 if (m.tls_block == g_thread_tls_block) {
466 m.tls_block = nullptr;
467 m.tls_saved_block = nullptr;
468 }
469 VirtualFree(g_thread_tls_block, 0, MEM_RELEASE);
470 g_thread_tls_module = nullptr;
471 g_thread_tls_saved = nullptr;
472 g_thread_tls_block = nullptr;
473}
474 641
475void Loader::run_tls_callbacks(Module& m, uint32_t reason) { 642void Loader::uninstall_tls_for_thread(Module& m) { uninstall_thread_block(m); }
476 auto* tls = tls_directory(m); 643
477 if (!tls || !tls->AddressOfCallBacks) return; 644void Loader::run_tls_callbacks(Module& m, uint32_t reason) { run_callbacks(m, reason); }
478 const uint64_t table_rva = rva_in(m, tls->AddressOfCallBacks, "the TLS callback table");
479 // The callback table has no length field: it ends at a zero entry, so every step is checked against the image.
480 for (uint64_t i = 0;; ++i) {
481 const uint64_t entry_rva = table_rva + i * sizeof(uint64_t);
482 require_range(m.name, entry_rva, sizeof(uint64_t), m.size, "a TLS callback table entry");
483 const uint64_t fn = *at<uint64_t>(m.base, static_cast<uint32_t>(entry_rva));
484 if (!fn) break;
485 auto callback =
486 reinterpret_cast<PIMAGE_TLS_CALLBACK>(m.base + rva_in(m, fn, "a TLS callback"));
487 callback(m.base, static_cast<DWORD>(reason), nullptr);
488 }
489}
490 645
491void Loader::parse_exports(Module& m) { 646void Loader::parse_exports(Module& m) {
492 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 647 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
@@ -566,8 +721,10 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d
566 721
567 HMODULE h = LoadLibraryExA(module.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); 722 HMODULE h = LoadLibraryExA(module.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
568 if (!h) return nullptr; 723 if (!h) return nullptr;
724 if (prefer_host_copy(shim_key)) redirect_pc_to_file_header(h);
569 FARPROC p = GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(static_cast<WORD>(ordinal)) : symbol.c_str()); 725 FARPROC p = GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(static_cast<WORD>(ordinal)) : symbol.c_str());
570 if (!p) return nullptr; 726 if (!p) return nullptr;
727 if (prefer_host_copy(shim_key)) redirect_pc_to_file_header_at(reinterpret_cast<const void*>(p));
571 binding = Binding::Host; 728 binding = Binding::Host;
572 return reinterpret_cast<void*>(p); 729 return reinterpret_cast<void*>(p);
573} 730}
@@ -598,8 +755,10 @@ void* Loader::resolve(Module& m, const std::string& dll, const std::string& name
598 } 755 }
599 // Host Windows: system DLLs and API sets. LOAD_LIBRARY_SEARCH_SYSTEM32 keeps the game folder out of the search. 756 // Host Windows: system DLLs and API sets. LOAD_LIBRARY_SEARCH_SYSTEM32 keeps the game folder out of the search.
600 if (HMODULE h = LoadLibraryExA(dll.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)) { 757 if (HMODULE h = LoadLibraryExA(dll.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)) {
758 if (prefer_host_copy(key)) redirect_pc_to_file_header(h); // before any mapped code can throw through it
601 FARPROC p = GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str()); 759 FARPROC p = GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str());
602 if (p) { 760 if (p) {
761 if (prefer_host_copy(key)) redirect_pc_to_file_header_at(reinterpret_cast<const void*>(p));
603 m.imports.push_back({dll, sym, Binding::Host}); 762 m.imports.push_back({dll, sym, Binding::Host});
604 return reinterpret_cast<void*>(p); 763 return reinterpret_cast<void*>(p);
605 } 764 }