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:
authorkotorvr <332716892+kotorvr@users.noreply.github.com>2026-11-22 22:19:40 +0000
committerkotorvr <332716892+kotorvr@users.noreply.github.com>2026-11-22 22:19:40 +0000
commit2fb013cd9b6ac1062625fbdb556cd1535db008f1 (patch)
tree207e9a3f233bf1abc5e61711d5c59c32b2acb07d /runtime/src/pe_loader.cpp
parent77bb72741959a2b02921697755a51548e802770e (diff)
parent4c52ce27a6cf4af2bbf07a343ede39c5f1572b8d (diff)
Merge origin/main into tls-existing-threads
Conflicts with #2070's later round (TLS generations, per-slot thread-event errors, clone purge) in pe_loader.cpp/.h and loader_tls_test.cpp: - install_thread_block keeps main's generation check and this branch's existing-thread check. - on_host_thread_event keeps main's per-slot try/catch and calls this branch's existing-thread hooks first, each in its own try/catch. - ~Loader resets the slot generation and removes the existing-thread blocks. - The existing-thread records carry the module's TLS generation too. - Both sides' tests stay. test_orphan_slot_generation_reuse now expects one DLL_THREAD_DETACH, not none: the worker was running when the second Loader mapped the module, so it gets that module's copy and its detach, as Windows does; a second detach would mean the orphaned record was taken for the new module's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src/pe_loader.cpp')
-rw-r--r--runtime/src/pe_loader.cpp196
1 files changed, 150 insertions, 46 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index f6b6673be..a55733e40 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -122,9 +122,14 @@ struct TlsCloneRecord {
122std::mutex g_tls_alloc_mutex; 122std::mutex g_tls_alloc_mutex;
123std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{}; 123std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{};
124std::array<std::atomic<Module*>, kMaxMappedTlsModules> g_tls_slot_owners{}; 124std::array<std::atomic<Module*>, kMaxMappedTlsModules> g_tls_slot_owners{};
125std::array<std::atomic<uint64_t>, kMaxMappedTlsModules> g_tls_slot_generations{};
126std::atomic<uint64_t> g_next_tls_generation{1};
125std::vector<TlsCloneRecord> g_tls_clones; 127std::vector<TlsCloneRecord> g_tls_clones;
126 128
127void cleanup_tls_clones_at_exit() { 129// Frees every TLS helper clone this process loaded and deletes its files. load() registers the wrapper with atexit;
130// the --run path in main() must also call this directly before ExitProcess, which skips the atexit table. Call it
131// only when no mapped code can run again: it unmaps the helper images.
132void cleanup_tls_clones_internal() {
128 for (const auto& rec : g_tls_clones) { 133 for (const auto& rec : g_tls_clones) {
129 if (rec.module) FreeLibrary(rec.module); 134 if (rec.module) FreeLibrary(rec.module);
130 if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); 135 if (!rec.path.empty()) DeleteFileW(rec.path.c_str());
@@ -132,16 +137,54 @@ void cleanup_tls_clones_at_exit() {
132 g_tls_clones.clear(); 137 g_tls_clones.clear();
133} 138}
134 139
140void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); }
141
142// The owner process named by "leonida_tls_host_<pid>_<slot>.dll"; 0 when the name does not carry one.
143DWORD clone_owner_pid(const wchar_t* name) {
144 constexpr wchar_t prefix[] = L"leonida_tls_host_";
145 const wchar_t* p = name;
146 for (size_t i = 0; i < sizeof(prefix) / sizeof(wchar_t) - 1; ++i)
147 if (*p++ != prefix[i]) return 0;
148 if (*p < L'0' || *p > L'9') return 0;
149 unsigned long pid = 0;
150 while (*p >= L'0' && *p <= L'9') {
151 pid = pid * 10 + (*p - L'0');
152 if (pid > 0xFFFFFFFFul) return 0;
153 ++p;
154 }
155 return static_cast<DWORD>(pid);
156}
157
158bool process_alive(DWORD pid) {
159 // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the
160 // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID.
161 HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
162 if (!p) return false;
163 CloseHandle(p);
164 return true;
165}
166
167// Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a
168// clone of a live process is either still open by its copy step's handle or mapped as an image, so it is skipped
169// (or DeleteFileW fails harmlessly), and a concurrent process between CopyFileW and LoadLibraryExW keeps its file.
135void sweep_stale_tls_clones(const std::filesystem::path& dir) { 170void sweep_stale_tls_clones(const std::filesystem::path& dir) {
136 WIN32_FIND_DATAW fd{}; 171 WIN32_FIND_DATAW fd{};
137 const std::filesystem::path pattern = dir / L"leonida_tls_host_*.dll"; 172 const std::filesystem::path pattern = dir / L"leonida_tls_host_*.dll";
138 HANDLE h = FindFirstFileW(pattern.c_str(), &fd); 173 HANDLE h = FindFirstFileW(pattern.c_str(), &fd);
139 if (h == INVALID_HANDLE_VALUE) return; 174 if (h == INVALID_HANDLE_VALUE) return;
140 do { 175 do {
141 if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) { 176 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
142 // Fails harmlessly for clones still mapped in live processes; deletes orphaned ones from exited processes. 177 const std::filesystem::path path = dir / fd.cFileName;
143 DeleteFileW((dir / fd.cFileName).c_str()); 178 const DWORD owner = clone_owner_pid(fd.cFileName);
144 } 179 if (owner && owner != GetCurrentProcessId() && process_alive(owner)) continue;
180 // An exclusive open (no sharing) conflicts with any handle another process holds on the file, so a failure
181 // means the copy->load sequence or a mapped image still owns it. Only unowned files reach DeleteFileW, and
182 // that stays harmless for a mapped image.
183 HANDLE probe =
184 CreateFileW(path.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
185 if (probe == INVALID_HANDLE_VALUE) continue;
186 CloseHandle(probe);
187 DeleteFileW(path.c_str());
145 } while (FindNextFileW(h, &fd)); 188 } while (FindNextFileW(h, &fd));
146 FindClose(h); 189 FindClose(h);
147} 190}
@@ -209,13 +252,27 @@ TlsHostModule ensure_tls_host(size_t slot) {
209 const std::wstring name = 252 const std::wstring name =
210 L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll"; 253 L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll";
211 const std::filesystem::path clone_path = dir / name; 254 const std::filesystem::path clone_path = dir / name;
212 if (!CopyFileW(primary.c_str(), clone_path.c_str(), FALSE)) return {}; 255 // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll.
213 256 const std::filesystem::path staging = clone_path.wstring() + L".new";
214 // Hold a read-only-shared handle across LoadLibraryExW so another process cannot overwrite the clone in between. 257 if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) return {};
215 HANDLE guard = CreateFileW(clone_path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, 258
259 // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename
260 // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone
261 // while the handle is open (an exclusive open conflicts with it) or once the image is mapped. Copying straight
262 // to the final name would leave a window where a concurrent sweep sees an unowned file.
263 HANDLE guard = CreateFileW(staging.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr,
216 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); 264 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
265 if (guard == INVALID_HANDLE_VALUE) {
266 DeleteFileW(staging.c_str());
267 return {};
268 }
269 if (!MoveFileExW(staging.c_str(), clone_path.c_str(), MOVEFILE_REPLACE_EXISTING)) {
270 CloseHandle(guard);
271 DeleteFileW(staging.c_str());
272 return {};
273 }
217 TlsHostModule loaded = load_tls_host_image(clone_path, false); 274 TlsHostModule loaded = load_tls_host_image(clone_path, false);
218 if (guard != INVALID_HANDLE_VALUE) CloseHandle(guard); 275 CloseHandle(guard);
219 276
220 if (loaded.index == TLS_OUT_OF_INDEXES) { 277 if (loaded.index == TLS_OUT_OF_INDEXES) {
221 DeleteFileW(clone_path.c_str()); 278 DeleteFileW(clone_path.c_str());
@@ -235,6 +292,7 @@ TlsHostModule ensure_tls_host(size_t slot) {
235 292
236struct ThreadTlsSlot { 293struct ThreadTlsSlot {
237 Module* module = nullptr; 294 Module* module = nullptr;
295 uint64_t generation = 0;
238 void* saved = nullptr; 296 void* saved = nullptr;
239 void* block = nullptr; 297 void* block = nullptr;
240 uint32_t index = kNoTlsIndex; 298 uint32_t index = kNoTlsIndex;
@@ -282,6 +340,7 @@ struct ExistingThreadBlock {
282 DWORD thread = 0; 340 DWORD thread = 0;
283 size_t slot = 0; 341 size_t slot = 0;
284 Module* module = nullptr; 342 Module* module = nullptr;
343 uint64_t generation = 0; // the module's tls_generation: with the pointer, what identifies the module
285 uint32_t index = kNoTlsIndex; 344 uint32_t index = kNoTlsIndex;
286 void*** vector = nullptr; // that thread's TEB->ThreadLocalStoragePointer field; the array itself can be replaced 345 void*** vector = nullptr; // that thread's TEB->ThreadLocalStoragePointer field; the array itself can be replaced
287 void* saved = nullptr; // what the block replaced 346 void* saved = nullptr; // what the block replaced
@@ -309,7 +368,7 @@ struct ExistingThreadsLock {
309bool has_existing_thread_block(DWORD thread, const Module& m) { 368bool has_existing_thread_block(DWORD thread, const Module& m) {
310 ExistingThreadsLock lock; 369 ExistingThreadsLock lock;
311 for (const auto& b : existing_threads().blocks) 370 for (const auto& b : existing_threads().blocks)
312 if (b.thread == thread && b.module == &m) return true; 371 if (b.thread == thread && b.module == &m && b.generation == m.tls_generation) return true;
313 return false; 372 return false;
314} 373}
315 374
@@ -317,12 +376,14 @@ void install_thread_block(Module& m) {
317 if (m.tls_slot >= kMaxMappedTlsModules) return; 376 if (m.tls_slot >= kMaxMappedTlsModules) return;
318 const size_t slot = m.tls_slot; 377 const size_t slot = m.tls_slot;
319 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 378 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
320 if (entry.module == &m) return; 379 if (entry.module == &m && entry.generation == m.tls_generation) return;
321 if (has_existing_thread_block(GetCurrentThreadId(), m)) return; // load() already gave this thread its copy 380 if (has_existing_thread_block(GetCurrentThreadId(), m)) return; // load() already gave this thread its copy
322 if (entry.module) { 381 if (entry.module) {
323 // A copy left by a module whose Loader is gone is released; a live module's is a conflict. 382 // A copy left by a module whose Loader is gone (or from an earlier generation) is released; a live owner's is a conflict.
324 if (entry.module == g_tls_slot_owners[slot].load()) 383 if (entry.module == g_tls_slot_owners[slot].load() &&
384 entry.generation == g_tls_slot_generations[slot].load()) {
325 throw std::runtime_error("another manually mapped module's TLS is already installed in this thread slot"); 385 throw std::runtime_error("another manually mapped module's TLS is already installed in this thread slot");
386 }
326 release_thread_slot(slot); 387 release_thread_slot(slot);
327 } 388 }
328 389
@@ -330,6 +391,7 @@ void install_thread_block(Module& m) {
330 if (!total) { 391 if (!total) {
331 // Callback-only TLS module (no data block): still record attachment in this slot so DLL_THREAD_DETACH runs. 392 // Callback-only TLS module (no data block): still record attachment in this slot so DLL_THREAD_DETACH runs.
332 entry.module = &m; 393 entry.module = &m;
394 entry.generation = m.tls_generation;
333 return; 395 return;
334 } 396 }
335 if (m.tls_index == kNoTlsIndex) return; 397 if (m.tls_index == kNoTlsIndex) return;
@@ -346,6 +408,7 @@ void install_thread_block(Module& m) {
346 void* saved = slots[m.tls_index]; 408 void* saved = slots[m.tls_index];
347 slots[m.tls_index] = block; 409 slots[m.tls_index] = block;
348 entry.module = &m; 410 entry.module = &m;
411 entry.generation = m.tls_generation;
349 entry.saved = saved; 412 entry.saved = saved;
350 entry.block = block; 413 entry.block = block;
351 entry.index = m.tls_index; 414 entry.index = m.tls_index;
@@ -355,7 +418,7 @@ void uninstall_thread_block(Module& m) {
355 if (m.tls_slot >= kMaxMappedTlsModules) return; 418 if (m.tls_slot >= kMaxMappedTlsModules) return;
356 const size_t slot = m.tls_slot; 419 const size_t slot = m.tls_slot;
357 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 420 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
358 if (entry.module != &m) return; 421 if (entry.module != &m || entry.generation != m.tls_generation) return;
359 if (m.tls_block == entry.block) { 422 if (m.tls_block == entry.block) {
360 m.tls_block = nullptr; 423 m.tls_block = nullptr;
361 m.tls_saved_block = nullptr; 424 m.tls_saved_block = nullptr;
@@ -536,7 +599,7 @@ void install_on_existing_threads(Module& m) {
536 for (auto it = state.blocks.begin(); it != state.blocks.end();) { 599 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
537 if (it->thread != c.id || it->slot != m.tls_slot) { 600 if (it->thread != c.id || it->slot != m.tls_slot) {
538 ++it; 601 ++it;
539 } else if (it->module == &m) { 602 } else if (it->module == &m && it->generation == m.tls_generation) {
540 present = true; 603 present = true;
541 break; 604 break;
542 } else { 605 } else {
@@ -572,7 +635,7 @@ void install_on_existing_threads(Module& m) {
572 m.name.c_str()); 635 m.name.c_str());
573 continue; 636 continue;
574 } 637 }
575 state.blocks.push_back({c.id, m.tls_slot, &m, m.tls_index, vector, saved, block}); 638 state.blocks.push_back({c.id, m.tls_slot, &m, m.tls_generation, m.tls_index, vector, saved, block});
576 } 639 }
577 } 640 }
578} 641}
@@ -583,7 +646,7 @@ void remove_from_existing_threads(Module& m) {
583 ExistingThreadsLock lock; 646 ExistingThreadsLock lock;
584 ExistingThreads& state = existing_threads(); 647 ExistingThreads& state = existing_threads();
585 for (auto it = state.blocks.begin(); it != state.blocks.end();) { 648 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
586 if (it->module != &m) { 649 if (it->module != &m || it->generation != m.tls_generation) {
587 ++it; 650 ++it;
588 continue; 651 continue;
589 } 652 }
@@ -625,7 +688,9 @@ void release_existing_blocks_of_this_thread() {
625 } 688 }
626 for (auto it = mine.rbegin(); it != mine.rend(); ++it) { 689 for (auto it = mine.rbegin(); it != mine.rend(); ++it) {
627 Module* m = it->module; 690 Module* m = it->module;
628 if (g_tls_slot_owners[it->slot].load() != m || !m->initialised) continue; 691 if (g_tls_slot_owners[it->slot].load() != m || g_tls_slot_generations[it->slot].load() != it->generation ||
692 !m->initialised)
693 continue;
629 try { 694 try {
630 run_callbacks(*m, DLL_THREAD_DETACH); 695 run_callbacks(*m, DLL_THREAD_DETACH);
631 } catch (const std::exception& e) { 696 } catch (const std::exception& e) {
@@ -652,31 +717,51 @@ void release_existing_blocks_of_this_thread() {
652// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. 717// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them.
653void __cdecl on_host_thread_event(DWORD reason) { 718void __cdecl on_host_thread_event(DWORD reason) {
654 SharedTlsLock lock; 719 SharedTlsLock lock;
655 try { 720 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events
656 if (reason == DLL_THREAD_ATTACH) { 721 // away from the other slots. Nothing may leave DllMain.
722 if (reason == DLL_THREAD_ATTACH) {
723 try {
657 forget_ended_thread_id(); 724 forget_ended_thread_id();
658 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { 725 } catch (const std::exception& e) {
659 Module* m = g_tls_slot_owners[slot].load(); 726 std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what());
660 if (!m) continue; 727 }
728 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) {
729 Module* m = g_tls_slot_owners[slot].load();
730 if (!m) continue;
731 try {
661 install_thread_block(*m); 732 install_thread_block(*m);
662 if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); 733 if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH);
734 } catch (const std::exception& e) {
735 // The thread runs on without this module's TLS; later slots still get theirs.
736 std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(),
737 e.what());
663 } 738 }
664 } else if (reason == DLL_THREAD_DETACH) { 739 }
740 } else if (reason == DLL_THREAD_DETACH) {
741 // The blocks load() gave this thread while it was already running come out first (they can sit on top of
742 // an older module's block in the same slot).
743 try {
665 release_existing_blocks_of_this_thread(); 744 release_existing_blocks_of_this_thread();
666 for (size_t i = kMaxMappedTlsModules; i-- > 0;) { 745 } catch (const std::exception& e) {
667 Module* m = g_tls_slot_owners[i].load(); 746 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what());
668 if (m && g_thread_tls_slots[i].module == m) { 747 }
748 for (size_t i = kMaxMappedTlsModules; i-- > 0;) {
749 Module* m = g_tls_slot_owners[i].load();
750 if (m && g_thread_tls_slots[i].module == m &&
751 g_thread_tls_slots[i].generation == m->tls_generation) {
752 try {
669 if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH); 753 if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH);
670 uninstall_thread_block(*m); 754 } catch (const std::exception& e) {
671 } else { 755 std::fprintf(stderr, "[rt] loader: thread detach, slot %zu (%s): %s\n", i, m->name.c_str(),
672 release_thread_slot(i); // installed by a module whose Loader is gone (or nothing to do) 756 e.what());
673 } 757 }
758 // Released even when the callbacks threw: a leaked block would be handed to the OS loader as the
759 // helper's own TLS block and freed with it at thread exit.
760 uninstall_thread_block(*m);
761 } else {
762 release_thread_slot(i); // installed by a module whose Loader is gone (or nothing to do)
674 } 763 }
675 } 764 }
676 } catch (const std::exception& e) {
677 // Nothing may leave DllMain. The thread runs on without the module's TLS (attach) or keeps the copy (detach).
678 std::fprintf(stderr, "[rt] loader: thread %s: %s\n", reason == DLL_THREAD_ATTACH ? "attach" : "detach",
679 e.what());
680 } 765 }
681} 766}
682 767
@@ -755,6 +840,9 @@ void redirect_pc_to_file_header_at(const void* resolved) {
755 840
756} // namespace 841} // namespace
757 842
843// Declared in pe_loader.h; the body needs the internal clone registry above.
844void cleanup_tls_clones() { cleanup_tls_clones_internal(); }
845
758namespace { 846namespace {
759bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { 847bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) {
760 for (const Module* m : static_cast<Loader*>(ctx)->modules()) { 848 for (const Module* m : static_cast<Loader*>(ctx)->modules()) {
@@ -828,7 +916,8 @@ Loader::~Loader() {
828 { 916 {
829 ExclusiveTlsLock lock; 917 ExclusiveTlsLock lock;
830 Module* owner = m; 918 Module* owner = m;
831 g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr); 919 if (g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr))
920 g_tls_slot_generations[m->tls_slot].store(0);
832 remove_from_existing_threads(*m); 921 remove_from_existing_threads(*m);
833 } 922 }
834 uninstall_tls_for_thread(*m); 923 uninstall_tls_for_thread(*m);
@@ -845,10 +934,19 @@ Module& Loader::load(const std::filesystem::path& image) {
845 std::lock_guard lock(mutex_); 934 std::lock_guard lock(mutex_);
846 std::string key = lower(image.filename().string()); 935 std::string key = lower(image.filename().string());
847 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; 936 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second;
848 Module& m = map_image(image); 937 Module* mapped = nullptr;
849 bind_imports(m); // loads every bundled module m imports first, so they land in init_order_ before m 938 try {
850 protect_sections(m); 939 mapped = &map_image(image);
851 register_unwind(m); 940 bind_imports(*mapped); // loads every bundled module m imports first, so they land in init_order_ before m
941 protect_sections(*mapped);
942 register_unwind(*mapped);
943 } catch (...) {
944 // A failed load, nested ones (a dependency of a run-time load) included, must not stay findable by name:
945 // a later lookup would get a half-mapped image with unbound imports. ~Loader still frees it through order_.
946 by_name_.erase(key);
947 throw;
948 }
949 Module& m = *mapped;
852 init_order_.push_back(&m); 950 init_order_.push_back(&m);
853 if (startup_trace::enabled()) 951 if (startup_trace::enabled())
854 startup_trace::event("map", "\"module\":" + startup_trace::quote(m.name) + 952 startup_trace::event("map", "\"module\":" + startup_trace::quote(m.name) +
@@ -903,8 +1001,8 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags,
903 std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str()); 1001 std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str());
904 return static_cast<void*>(m.base); 1002 return static_cast<void*>(m.base);
905 } catch (const std::exception& e) { 1003 } catch (const std::exception& e) {
906 // Do not leave a failed run-time load indexed by name so later GetModuleHandle/LoadLibrary calls do not 1004 // load() drops a module that failed to map or bind (dependencies included); this also drops one whose
907 // observe a half-initialised module. ~Loader still frees any VirtualAlloc'd mapping in order_. 1005 // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via order_.
908 by_name_.erase(dll_lower); 1006 by_name_.erase(dll_lower);
909 std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what()); 1007 std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what());
910 SetLastError(ERROR_DLL_INIT_FAILED); 1008 SetLastError(ERROR_DLL_INIT_FAILED);
@@ -1131,8 +1229,9 @@ Module& Loader::map_image(const std::filesystem::path& path) {
1131// zero-fill size; it has no field naming the TLS block. The Windows loader allocates a block per module per thread and 1229// zero-fill size; it has no field naming the TLS block. The Windows loader allocates a block per module per thread and
1132// puts it in TEB->ThreadLocalStoragePointer[module index], which is what __declspec(thread) code reads via _tls_index. 1230// puts it in TEB->ThreadLocalStoragePointer[module index], which is what __declspec(thread) code reads via _tls_index.
1133// Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to 1231// Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to
1134// gta6rt_tls_host.dll. That makes one manually mapped TLS module work; a second one is rejected rather than silently 1232// gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone
1135// sharing (and corrupting) the same slot. 1233// getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than
1234// silently sharing (and corrupting) a slot.
1136void Loader::initialize_tls(Module& m) { 1235void Loader::initialize_tls(Module& m) {
1137 auto* tls = tls_directory(m); 1236 auto* tls = tls_directory(m);
1138 if (!tls) return; 1237 if (!tls) return;
@@ -1184,6 +1283,8 @@ void Loader::initialize_tls(Module& m) {
1184 throw std::runtime_error(m.name + ": static TLS slot was claimed concurrently"); 1283 throw std::runtime_error(m.name + ": static TLS slot was claimed concurrently");
1185 1284
1186 m.tls_slot = static_cast<uint32_t>(slot); 1285 m.tls_slot = static_cast<uint32_t>(slot);
1286 m.tls_generation = g_next_tls_generation.fetch_add(1, std::memory_order_relaxed);
1287 g_tls_slot_generations[slot].store(m.tls_generation);
1187 m.tls_index = index; 1288 m.tls_index = index;
1188 m.tls_template = raw ? m.base + raw_rva : nullptr; 1289 m.tls_template = raw ? m.base + raw_rva : nullptr;
1189 m.tls_raw_size = static_cast<uint32_t>(raw); 1290 m.tls_raw_size = static_cast<uint32_t>(raw);
@@ -1199,11 +1300,13 @@ void Loader::initialize_tls(Module& m) {
1199 ExclusiveTlsLock lock; 1300 ExclusiveTlsLock lock;
1200 m.tls_index = kNoTlsIndex; 1301 m.tls_index = kNoTlsIndex;
1201 m.tls_slot = kNoTlsIndex; 1302 m.tls_slot = kNoTlsIndex;
1303 m.tls_generation = 0;
1304 g_tls_slot_generations[slot].store(0);
1202 g_tls_slot_owners[slot].store(nullptr); 1305 g_tls_slot_owners[slot].store(nullptr);
1203 throw; 1306 throw;
1204 } 1307 }
1205 // The loading thread's copy is the one the Module records (and ~Loader frees on that thread). 1308 // The loading thread's copy is the one the Module records (and ~Loader frees on that thread).
1206 if (g_thread_tls_slots[slot].module == &m) { 1309 if (g_thread_tls_slots[slot].module == &m && g_thread_tls_slots[slot].generation == m.tls_generation) {
1207 m.tls_block = g_thread_tls_slots[slot].block; 1310 m.tls_block = g_thread_tls_slots[slot].block;
1208 m.tls_saved_block = g_thread_tls_slots[slot].saved; 1311 m.tls_saved_block = g_thread_tls_slots[slot].saved;
1209 } 1312 }
@@ -1238,6 +1341,7 @@ void Loader::parse_exports(Module& m) {
1238 // into the string, so forwarders are kept apart and followed when an import asks for one. 1341 // into the string, so forwarders are kept apart and followed when an import asks for one.
1239 const uint64_t dir_begin = dir.VirtualAddress, dir_end = dir_begin + dir.Size; 1342 const uint64_t dir_begin = dir.VirtualAddress, dir_end = dir_begin + dir.Size;
1240 auto add_export = [&](const std::string& key, uint32_t rva) { 1343 auto add_export = [&](const std::string& key, uint32_t rva) {
1344 if (!rva) return; // An unused address-table slot is absent even when a name refers to it.
1241 if (rva >= dir_begin && rva < dir_end) 1345 if (rva >= dir_begin && rva < dir_end)
1242 m.forwarders[key] = read_string(m.name, m.base, m.size, rva, "a forwarded export"); 1346 m.forwarders[key] = read_string(m.name, m.base, m.size, rva, "a forwarded export");
1243 else if (rva >= m.size) // base + rva would point past the mapping, and a caller would jump there 1347 else if (rva >= m.size) // base + rva would point past the mapping, and a caller would jump there
@@ -1360,8 +1464,8 @@ void Loader::bind_imports(Module& m) {
1360 uint16_t ord = by_ord ? (uint16_t)IMAGE_ORDINAL64(lookup->u1.Ordinal) : 0; 1464 uint16_t ord = by_ord ? (uint16_t)IMAGE_ORDINAL64(lookup->u1.Ordinal) : 0;
1361 std::string name; 1465 std::string name;
1362 if (!by_ord) { 1466 if (!by_ord) {
1467 require_range(m.name, lookup->u1.AddressOfData, sizeof(uint16_t), m.size, "an import name");
1363 uint32_t hint = static_cast<uint32_t>(lookup->u1.AddressOfData); 1468 uint32_t hint = static_cast<uint32_t>(lookup->u1.AddressOfData);
1364 require_range(m.name, hint, sizeof(uint16_t), m.size, "an import name");
1365 name = read_string(m.name, m.base, m.size, hint + sizeof(uint16_t), "an import name"); 1469 name = read_string(m.name, m.base, m.size, hint + sizeof(uint16_t), "an import name");
1366 } 1470 }
1367 at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function = 1471 at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function =