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.cpp179
1 files changed, 136 insertions, 43 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index a59f9d0b1..f4ecc0de2 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -65,7 +65,8 @@ uint64_t rva_in(const Module& m, uint64_t va, const char* what) {
65 65
66IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) { 66IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) {
67 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 67 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
68 const auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS]; 68 // Through directory(), as every other directory: an entry past NumberOfRvaAndSizes is not a TLS directory.
69 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS);
69 if (!dir.Size || !dir.VirtualAddress) return nullptr; 70 if (!dir.Size || !dir.VirtualAddress) return nullptr;
70 require_range(m.name, dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64), m.size, "the TLS directory"); 71 require_range(m.name, dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64), m.size, "the TLS directory");
71 return at<IMAGE_TLS_DIRECTORY64>(m.base, dir.VirtualAddress); 72 return at<IMAGE_TLS_DIRECTORY64>(m.base, dir.VirtualAddress);
@@ -120,9 +121,14 @@ struct TlsCloneRecord {
120std::mutex g_tls_alloc_mutex; 121std::mutex g_tls_alloc_mutex;
121std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{}; 122std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{};
122std::array<std::atomic<Module*>, kMaxMappedTlsModules> g_tls_slot_owners{}; 123std::array<std::atomic<Module*>, kMaxMappedTlsModules> g_tls_slot_owners{};
124std::array<std::atomic<uint64_t>, kMaxMappedTlsModules> g_tls_slot_generations{};
125std::atomic<uint64_t> g_next_tls_generation{1};
123std::vector<TlsCloneRecord> g_tls_clones; 126std::vector<TlsCloneRecord> g_tls_clones;
124 127
125void cleanup_tls_clones_at_exit() { 128// Frees every TLS helper clone this process loaded and deletes its files. load() registers the wrapper with atexit;
129// the --run path in main() must also call this directly before ExitProcess, which skips the atexit table. Call it
130// only when no mapped code can run again: it unmaps the helper images.
131void cleanup_tls_clones_internal() {
126 for (const auto& rec : g_tls_clones) { 132 for (const auto& rec : g_tls_clones) {
127 if (rec.module) FreeLibrary(rec.module); 133 if (rec.module) FreeLibrary(rec.module);
128 if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); 134 if (!rec.path.empty()) DeleteFileW(rec.path.c_str());
@@ -130,16 +136,54 @@ void cleanup_tls_clones_at_exit() {
130 g_tls_clones.clear(); 136 g_tls_clones.clear();
131} 137}
132 138
139void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); }
140
141// The owner process named by "leonida_tls_host_<pid>_<slot>.dll"; 0 when the name does not carry one.
142DWORD clone_owner_pid(const wchar_t* name) {
143 constexpr wchar_t prefix[] = L"leonida_tls_host_";
144 const wchar_t* p = name;
145 for (size_t i = 0; i < sizeof(prefix) / sizeof(wchar_t) - 1; ++i)
146 if (*p++ != prefix[i]) return 0;
147 if (*p < L'0' || *p > L'9') return 0;
148 unsigned long pid = 0;
149 while (*p >= L'0' && *p <= L'9') {
150 pid = pid * 10 + (*p - L'0');
151 if (pid > 0xFFFFFFFFul) return 0;
152 ++p;
153 }
154 return static_cast<DWORD>(pid);
155}
156
157bool process_alive(DWORD pid) {
158 // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the
159 // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID.
160 HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
161 if (!p) return false;
162 CloseHandle(p);
163 return true;
164}
165
166// Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a
167// clone of a live process is either still open by its copy step's handle or mapped as an image, so it is skipped
168// (or DeleteFileW fails harmlessly), and a concurrent process between CopyFileW and LoadLibraryExW keeps its file.
133void sweep_stale_tls_clones(const std::filesystem::path& dir) { 169void sweep_stale_tls_clones(const std::filesystem::path& dir) {
134 WIN32_FIND_DATAW fd{}; 170 WIN32_FIND_DATAW fd{};
135 const std::filesystem::path pattern = dir / L"leonida_tls_host_*.dll"; 171 const std::filesystem::path pattern = dir / L"leonida_tls_host_*.dll";
136 HANDLE h = FindFirstFileW(pattern.c_str(), &fd); 172 HANDLE h = FindFirstFileW(pattern.c_str(), &fd);
137 if (h == INVALID_HANDLE_VALUE) return; 173 if (h == INVALID_HANDLE_VALUE) return;
138 do { 174 do {
139 if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) { 175 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
140 // Fails harmlessly for clones still mapped in live processes; deletes orphaned ones from exited processes. 176 const std::filesystem::path path = dir / fd.cFileName;
141 DeleteFileW((dir / fd.cFileName).c_str()); 177 const DWORD owner = clone_owner_pid(fd.cFileName);
142 } 178 if (owner && owner != GetCurrentProcessId() && process_alive(owner)) continue;
179 // An exclusive open (no sharing) conflicts with any handle another process holds on the file, so a failure
180 // means the copy->load sequence or a mapped image still owns it. Only unowned files reach DeleteFileW, and
181 // that stays harmless for a mapped image.
182 HANDLE probe =
183 CreateFileW(path.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
184 if (probe == INVALID_HANDLE_VALUE) continue;
185 CloseHandle(probe);
186 DeleteFileW(path.c_str());
143 } while (FindNextFileW(h, &fd)); 187 } while (FindNextFileW(h, &fd));
144 FindClose(h); 188 FindClose(h);
145} 189}
@@ -207,13 +251,27 @@ TlsHostModule ensure_tls_host(size_t slot) {
207 const std::wstring name = 251 const std::wstring name =
208 L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll"; 252 L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll";
209 const std::filesystem::path clone_path = dir / name; 253 const std::filesystem::path clone_path = dir / name;
210 if (!CopyFileW(primary.c_str(), clone_path.c_str(), FALSE)) return {}; 254 // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll.
211 255 const std::filesystem::path staging = clone_path.wstring() + L".new";
212 // Hold a read-only-shared handle across LoadLibraryExW so another process cannot overwrite the clone in between. 256 if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) return {};
213 HANDLE guard = CreateFileW(clone_path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, 257
258 // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename
259 // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone
260 // while the handle is open (an exclusive open conflicts with it) or once the image is mapped. Copying straight
261 // to the final name would leave a window where a concurrent sweep sees an unowned file.
262 HANDLE guard = CreateFileW(staging.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr,
214 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); 263 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
264 if (guard == INVALID_HANDLE_VALUE) {
265 DeleteFileW(staging.c_str());
266 return {};
267 }
268 if (!MoveFileExW(staging.c_str(), clone_path.c_str(), MOVEFILE_REPLACE_EXISTING)) {
269 CloseHandle(guard);
270 DeleteFileW(staging.c_str());
271 return {};
272 }
215 TlsHostModule loaded = load_tls_host_image(clone_path, false); 273 TlsHostModule loaded = load_tls_host_image(clone_path, false);
216 if (guard != INVALID_HANDLE_VALUE) CloseHandle(guard); 274 CloseHandle(guard);
217 275
218 if (loaded.index == TLS_OUT_OF_INDEXES) { 276 if (loaded.index == TLS_OUT_OF_INDEXES) {
219 DeleteFileW(clone_path.c_str()); 277 DeleteFileW(clone_path.c_str());
@@ -233,6 +291,7 @@ TlsHostModule ensure_tls_host(size_t slot) {
233 291
234struct ThreadTlsSlot { 292struct ThreadTlsSlot {
235 Module* module = nullptr; 293 Module* module = nullptr;
294 uint64_t generation = 0;
236 void* saved = nullptr; 295 void* saved = nullptr;
237 void* block = nullptr; 296 void* block = nullptr;
238 uint32_t index = kNoTlsIndex; 297 uint32_t index = kNoTlsIndex;
@@ -277,11 +336,13 @@ void install_thread_block(Module& m) {
277 if (m.tls_slot >= kMaxMappedTlsModules) return; 336 if (m.tls_slot >= kMaxMappedTlsModules) return;
278 const size_t slot = m.tls_slot; 337 const size_t slot = m.tls_slot;
279 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 338 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
280 if (entry.module == &m) return; 339 if (entry.module == &m && entry.generation == m.tls_generation) return;
281 if (entry.module) { 340 if (entry.module) {
282 // A copy left by a module whose Loader is gone is released; a live module's is a conflict. 341 // A copy left by a module whose Loader is gone (or from an earlier generation) is released; a live owner's is a conflict.
283 if (entry.module == g_tls_slot_owners[slot].load()) 342 if (entry.module == g_tls_slot_owners[slot].load() &&
343 entry.generation == g_tls_slot_generations[slot].load()) {
284 throw std::runtime_error("another manually mapped module's TLS is already installed in this thread slot"); 344 throw std::runtime_error("another manually mapped module's TLS is already installed in this thread slot");
345 }
285 release_thread_slot(slot); 346 release_thread_slot(slot);
286 } 347 }
287 348
@@ -289,6 +350,7 @@ void install_thread_block(Module& m) {
289 if (!total) { 350 if (!total) {
290 // Callback-only TLS module (no data block): still record attachment in this slot so DLL_THREAD_DETACH runs. 351 // Callback-only TLS module (no data block): still record attachment in this slot so DLL_THREAD_DETACH runs.
291 entry.module = &m; 352 entry.module = &m;
353 entry.generation = m.tls_generation;
292 return; 354 return;
293 } 355 }
294 if (m.tls_index == kNoTlsIndex) return; 356 if (m.tls_index == kNoTlsIndex) return;
@@ -305,6 +367,7 @@ void install_thread_block(Module& m) {
305 void* saved = slots[m.tls_index]; 367 void* saved = slots[m.tls_index];
306 slots[m.tls_index] = block; 368 slots[m.tls_index] = block;
307 entry.module = &m; 369 entry.module = &m;
370 entry.generation = m.tls_generation;
308 entry.saved = saved; 371 entry.saved = saved;
309 entry.block = block; 372 entry.block = block;
310 entry.index = m.tls_index; 373 entry.index = m.tls_index;
@@ -314,7 +377,7 @@ void uninstall_thread_block(Module& m) {
314 if (m.tls_slot >= kMaxMappedTlsModules) return; 377 if (m.tls_slot >= kMaxMappedTlsModules) return;
315 const size_t slot = m.tls_slot; 378 const size_t slot = m.tls_slot;
316 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 379 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
317 if (entry.module != &m) return; 380 if (entry.module != &m || entry.generation != m.tls_generation) return;
318 if (m.tls_block == entry.block) { 381 if (m.tls_block == entry.block) {
319 m.tls_block = nullptr; 382 m.tls_block = nullptr;
320 m.tls_saved_block = nullptr; 383 m.tls_saved_block = nullptr;
@@ -350,29 +413,39 @@ void run_callbacks(Module& m, uint32_t reason, bool trace = false) {
350// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. 413// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them.
351void __cdecl on_host_thread_event(DWORD reason) { 414void __cdecl on_host_thread_event(DWORD reason) {
352 SharedTlsLock lock; 415 SharedTlsLock lock;
353 try { 416 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events
354 if (reason == DLL_THREAD_ATTACH) { 417 // away from the other slots. Nothing may leave DllMain.
355 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { 418 if (reason == DLL_THREAD_ATTACH) {
356 Module* m = g_tls_slot_owners[slot].load(); 419 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) {
357 if (!m) continue; 420 Module* m = g_tls_slot_owners[slot].load();
421 if (!m) continue;
422 try {
358 install_thread_block(*m); 423 install_thread_block(*m);
359 if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); 424 if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH);
425 } catch (const std::exception& e) {
426 // The thread runs on without this module's TLS; later slots still get theirs.
427 std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(),
428 e.what());
360 } 429 }
361 } else if (reason == DLL_THREAD_DETACH) { 430 }
362 for (size_t i = kMaxMappedTlsModules; i-- > 0;) { 431 } else if (reason == DLL_THREAD_DETACH) {
363 Module* m = g_tls_slot_owners[i].load(); 432 for (size_t i = kMaxMappedTlsModules; i-- > 0;) {
364 if (m && g_thread_tls_slots[i].module == m) { 433 Module* m = g_tls_slot_owners[i].load();
434 if (m && g_thread_tls_slots[i].module == m &&
435 g_thread_tls_slots[i].generation == m->tls_generation) {
436 try {
365 if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH); 437 if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH);
366 uninstall_thread_block(*m); 438 } catch (const std::exception& e) {
367 } else { 439 std::fprintf(stderr, "[rt] loader: thread detach, slot %zu (%s): %s\n", i, m->name.c_str(),
368 release_thread_slot(i); // installed by a module whose Loader is gone (or nothing to do) 440 e.what());
369 } 441 }
442 // Released even when the callbacks threw: a leaked block would be handed to the OS loader as the
443 // helper's own TLS block and freed with it at thread exit.
444 uninstall_thread_block(*m);
445 } else {
446 release_thread_slot(i); // installed by a module whose Loader is gone (or nothing to do)
370 } 447 }
371 } 448 }
372 } catch (const std::exception& e) {
373 // Nothing may leave DllMain. The thread runs on without the module's TLS (attach) or keeps the copy (detach).
374 std::fprintf(stderr, "[rt] loader: thread %s: %s\n", reason == DLL_THREAD_ATTACH ? "attach" : "detach",
375 e.what());
376 } 449 }
377} 450}
378 451
@@ -451,6 +524,9 @@ void redirect_pc_to_file_header_at(const void* resolved) {
451 524
452} // namespace 525} // namespace
453 526
527// Declared in pe_loader.h; the body needs the internal clone registry above.
528void cleanup_tls_clones() { cleanup_tls_clones_internal(); }
529
454namespace { 530namespace {
455bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { 531bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) {
456 for (const Module* m : static_cast<Loader*>(ctx)->modules()) { 532 for (const Module* m : static_cast<Loader*>(ctx)->modules()) {
@@ -524,7 +600,8 @@ Loader::~Loader() {
524 { 600 {
525 ExclusiveTlsLock lock; 601 ExclusiveTlsLock lock;
526 Module* owner = m; 602 Module* owner = m;
527 g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr); 603 if (g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr))
604 g_tls_slot_generations[m->tls_slot].store(0);
528 } 605 }
529 uninstall_tls_for_thread(*m); 606 uninstall_tls_for_thread(*m);
530 } 607 }
@@ -540,10 +617,19 @@ Module& Loader::load(const std::filesystem::path& image) {
540 std::lock_guard lock(mutex_); 617 std::lock_guard lock(mutex_);
541 std::string key = lower(image.filename().string()); 618 std::string key = lower(image.filename().string());
542 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; 619 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second;
543 Module& m = map_image(image); 620 Module* mapped = nullptr;
544 bind_imports(m); // loads every bundled module m imports first, so they land in init_order_ before m 621 try {
545 protect_sections(m); 622 mapped = &map_image(image);
546 register_unwind(m); 623 bind_imports(*mapped); // loads every bundled module m imports first, so they land in init_order_ before m
624 protect_sections(*mapped);
625 register_unwind(*mapped);
626 } catch (...) {
627 // A failed load, nested ones (a dependency of a run-time load) included, must not stay findable by name:
628 // a later lookup would get a half-mapped image with unbound imports. ~Loader still frees it through order_.
629 by_name_.erase(key);
630 throw;
631 }
632 Module& m = *mapped;
547 init_order_.push_back(&m); 633 init_order_.push_back(&m);
548 if (startup_trace::enabled()) 634 if (startup_trace::enabled())
549 startup_trace::event("map", "\"module\":" + startup_trace::quote(m.name) + 635 startup_trace::event("map", "\"module\":" + startup_trace::quote(m.name) +
@@ -598,8 +684,8 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags,
598 std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str()); 684 std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str());
599 return static_cast<void*>(m.base); 685 return static_cast<void*>(m.base);
600 } catch (const std::exception& e) { 686 } catch (const std::exception& e) {
601 // Do not leave a failed run-time load indexed by name so later GetModuleHandle/LoadLibrary calls do not 687 // load() drops a module that failed to map or bind (dependencies included); this also drops one whose
602 // observe a half-initialised module. ~Loader still frees any VirtualAlloc'd mapping in order_. 688 // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via order_.
603 by_name_.erase(dll_lower); 689 by_name_.erase(dll_lower);
604 std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what()); 690 std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what());
605 SetLastError(ERROR_DLL_INIT_FAILED); 691 SetLastError(ERROR_DLL_INIT_FAILED);
@@ -696,7 +782,6 @@ void Loader::initialise(Module& m) {
696 // Only a DLL gets DllMain. An EXE's entry point has a different signature and is the caller's to run. 782 // Only a DLL gets DllMain. An EXE's entry point has a different signature and is the caller's to run.
697 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 783 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
698 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { 784 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) {
699 if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image");
700 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); 785 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva);
701 const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, nullptr); 786 const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, nullptr);
702 if (startup_trace::enabled()) 787 if (startup_trace::enabled())
@@ -741,6 +826,8 @@ Module& Loader::map_image(const std::filesystem::path& path) {
741 if (!oh.SizeOfImage || oh.SizeOfHeaders < headers_end || oh.SizeOfHeaders > oh.SizeOfImage || 826 if (!oh.SizeOfImage || oh.SizeOfHeaders < headers_end || oh.SizeOfHeaders > oh.SizeOfImage ||
742 oh.SizeOfHeaders > file.size()) 827 oh.SizeOfHeaders > file.size())
743 throw std::runtime_error(name + ": SizeOfHeaders and SizeOfImage don't fit the headers and file"); 828 throw std::runtime_error(name + ": SizeOfHeaders and SizeOfImage don't fit the headers and file");
829 if (oh.AddressOfEntryPoint && oh.AddressOfEntryPoint >= oh.SizeOfImage)
830 throw std::runtime_error(name + ": the entry point is outside the image");
744 831
745 auto* m = new Module; 832 auto* m = new Module;
746 m->name = name; 833 m->name = name;
@@ -825,8 +912,9 @@ Module& Loader::map_image(const std::filesystem::path& path) {
825// zero-fill size; it has no field naming the TLS block. The Windows loader allocates a block per module per thread and 912// zero-fill size; it has no field naming the TLS block. The Windows loader allocates a block per module per thread and
826// puts it in TEB->ThreadLocalStoragePointer[module index], which is what __declspec(thread) code reads via _tls_index. 913// puts it in TEB->ThreadLocalStoragePointer[module index], which is what __declspec(thread) code reads via _tls_index.
827// Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to 914// Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to
828// gta6rt_tls_host.dll. That makes one manually mapped TLS module work; a second one is rejected rather than silently 915// gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone
829// sharing (and corrupting) the same slot. 916// getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than
917// silently sharing (and corrupting) a slot.
830void Loader::initialize_tls(Module& m) { 918void Loader::initialize_tls(Module& m) {
831 auto* tls = tls_directory(m); 919 auto* tls = tls_directory(m);
832 if (!tls) return; 920 if (!tls) return;
@@ -878,6 +966,8 @@ void Loader::initialize_tls(Module& m) {
878 throw std::runtime_error(m.name + ": static TLS slot was claimed concurrently"); 966 throw std::runtime_error(m.name + ": static TLS slot was claimed concurrently");
879 967
880 m.tls_slot = static_cast<uint32_t>(slot); 968 m.tls_slot = static_cast<uint32_t>(slot);
969 m.tls_generation = g_next_tls_generation.fetch_add(1, std::memory_order_relaxed);
970 g_tls_slot_generations[slot].store(m.tls_generation);
881 m.tls_index = index; 971 m.tls_index = index;
882 m.tls_template = raw ? m.base + raw_rva : nullptr; 972 m.tls_template = raw ? m.base + raw_rva : nullptr;
883 m.tls_raw_size = static_cast<uint32_t>(raw); 973 m.tls_raw_size = static_cast<uint32_t>(raw);
@@ -893,11 +983,13 @@ void Loader::initialize_tls(Module& m) {
893 ExclusiveTlsLock lock; 983 ExclusiveTlsLock lock;
894 m.tls_index = kNoTlsIndex; 984 m.tls_index = kNoTlsIndex;
895 m.tls_slot = kNoTlsIndex; 985 m.tls_slot = kNoTlsIndex;
986 m.tls_generation = 0;
987 g_tls_slot_generations[slot].store(0);
896 g_tls_slot_owners[slot].store(nullptr); 988 g_tls_slot_owners[slot].store(nullptr);
897 throw; 989 throw;
898 } 990 }
899 // The loading thread's copy is the one the Module records (and ~Loader frees on that thread). 991 // The loading thread's copy is the one the Module records (and ~Loader frees on that thread).
900 if (g_thread_tls_slots[slot].module == &m) { 992 if (g_thread_tls_slots[slot].module == &m && g_thread_tls_slots[slot].generation == m.tls_generation) {
901 m.tls_block = g_thread_tls_slots[slot].block; 993 m.tls_block = g_thread_tls_slots[slot].block;
902 m.tls_saved_block = g_thread_tls_slots[slot].saved; 994 m.tls_saved_block = g_thread_tls_slots[slot].saved;
903 } 995 }
@@ -929,6 +1021,7 @@ void Loader::parse_exports(Module& m) {
929 // into the string, so forwarders are kept apart and followed when an import asks for one. 1021 // into the string, so forwarders are kept apart and followed when an import asks for one.
930 const uint64_t dir_begin = dir.VirtualAddress, dir_end = dir_begin + dir.Size; 1022 const uint64_t dir_begin = dir.VirtualAddress, dir_end = dir_begin + dir.Size;
931 auto add_export = [&](const std::string& key, uint32_t rva) { 1023 auto add_export = [&](const std::string& key, uint32_t rva) {
1024 if (!rva) return; // An unused address-table slot is absent even when a name refers to it.
932 if (rva >= dir_begin && rva < dir_end) 1025 if (rva >= dir_begin && rva < dir_end)
933 m.forwarders[key] = read_string(m.name, m.base, m.size, rva, "a forwarded export"); 1026 m.forwarders[key] = read_string(m.name, m.base, m.size, rva, "a forwarded export");
934 else if (rva >= m.size) // base + rva would point past the mapping, and a caller would jump there 1027 else if (rva >= m.size) // base + rva would point past the mapping, and a caller would jump there
@@ -1051,8 +1144,8 @@ void Loader::bind_imports(Module& m) {
1051 uint16_t ord = by_ord ? (uint16_t)IMAGE_ORDINAL64(lookup->u1.Ordinal) : 0; 1144 uint16_t ord = by_ord ? (uint16_t)IMAGE_ORDINAL64(lookup->u1.Ordinal) : 0;
1052 std::string name; 1145 std::string name;
1053 if (!by_ord) { 1146 if (!by_ord) {
1147 require_range(m.name, lookup->u1.AddressOfData, sizeof(uint16_t), m.size, "an import name");
1054 uint32_t hint = static_cast<uint32_t>(lookup->u1.AddressOfData); 1148 uint32_t hint = static_cast<uint32_t>(lookup->u1.AddressOfData);
1055 require_range(m.name, hint, sizeof(uint16_t), m.size, "an import name");
1056 name = read_string(m.name, m.base, m.size, hint + sizeof(uint16_t), "an import name"); 1149 name = read_string(m.name, m.base, m.size, hint + sizeof(uint16_t), "an import name");
1057 } 1150 }
1058 at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function = 1151 at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function =