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.cpp578
1 files changed, 559 insertions, 19 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index f3323e4c0..d85c1fe5f 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -2,6 +2,7 @@
2 2
3#include <windows.h> 3#include <windows.h>
4#include <intrin.h> 4#include <intrin.h>
5#include <tlhelp32.h>
5 6
6#include <algorithm> 7#include <algorithm>
7#include <array> 8#include <array>
@@ -12,6 +13,7 @@
12#include <fstream> 13#include <fstream>
13#include <mutex> 14#include <mutex>
14#include <stdexcept> 15#include <stdexcept>
16#include <system_error>
15#include <vector> 17#include <vector>
16 18
17#include "../shims/shims.h" 19#include "../shims/shims.h"
@@ -27,9 +29,54 @@ std::string lower(std::string s) {
27 29
28namespace { 30namespace {
29 31
32std::filesystem::path::string_type module_key(const std::filesystem::path& path) {
33 // Keep identity in the platform's native path representation. Only the existing ASCII case folding is
34 // applied here; representable names also retain their old narrow-byte alias below.
35 auto key = path.filename().native();
36 for (auto& c : key)
37 if (c >= 'A' && c <= 'Z') c = static_cast<std::filesystem::path::value_type>(c + ('a' - 'A'));
38 return key;
39}
40
41std::string narrow_module_key(const std::filesystem::path& path) {
42 const auto filename = path.filename();
43 try {
44 const auto narrow = filename.string();
45 // A lossy/default-character alias must not collapse two distinct Unicode basenames.
46 if (std::filesystem::path(narrow).native() == filename.native()) return lower(narrow);
47 } catch (const std::system_error&) {
48 // Some Windows standard libraries throw when a basename is outside the current narrow code page.
49 // It still has a native identity; it simply has no alias in the existing narrow lookup API.
50 }
51 return {};
52}
53
54// Windows matches module names case-insensitively with its own upcase table (RtlEqualUnicodeString); the
55// ordinal ignore-case compare is that table.
56bool same_module_name(const wchar_t* a, const wchar_t* b) {
57 return CompareStringOrdinal(a, -1, b, -1, TRUE) == CSTR_EQUAL;
58}
59
60// A narrow (ANSI code page) module name widened for a case-insensitive compare; empty when it is not valid in the
61// code page.
62std::wstring acp_to_wide(const std::string& narrow) {
63 if (narrow.empty()) return {};
64 const int n = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, narrow.data(), static_cast<int>(narrow.size()),
65 nullptr, 0);
66 if (n <= 0) return {};
67 std::wstring wide(static_cast<size_t>(n), L'\0');
68 MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, narrow.data(), static_cast<int>(narrow.size()), wide.data(), n);
69 return wide;
70}
71
72std::string path_utf8(const std::filesystem::path& path) {
73 const auto bytes = path.u8string();
74 return {reinterpret_cast<const char*>(bytes.data()), bytes.size()};
75}
76
30std::vector<uint8_t> read_file(const std::filesystem::path& p) { 77std::vector<uint8_t> read_file(const std::filesystem::path& p) {
31 std::ifstream f(p, std::ios::binary); 78 std::ifstream f(p, std::ios::binary);
32 if (!f) throw std::runtime_error("cannot open " + p.string()); 79 if (!f) throw std::runtime_error("cannot open " + path_utf8(p));
33 return {std::istreambuf_iterator<char>(f), {}}; 80 return {std::istreambuf_iterator<char>(f), {}};
34} 81}
35 82
@@ -295,6 +342,8 @@ struct ThreadTlsSlot {
295 void* saved = nullptr; 342 void* saved = nullptr;
296 void* block = nullptr; 343 void* block = nullptr;
297 uint32_t index = kNoTlsIndex; 344 uint32_t index = kNoTlsIndex;
345 void** ga_view = nullptr; // the thread's slot-0 view for a /GA EXE (Module::tls_ga_slot)
346 uint32_t ga_slot = kNoTlsIndex;
298}; 347};
299 348
300// Per-thread installation state for each reserved TLS slot. 349// Per-thread installation state for each reserved TLS slot.
@@ -323,6 +372,10 @@ void release_thread_slot(size_t slot) {
323 if (slot >= kMaxMappedTlsModules) return; 372 if (slot >= kMaxMappedTlsModules) return;
324 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 373 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
325 if (!entry.module && !entry.block) return; 374 if (!entry.module && !entry.block) return;
375 if (entry.ga_view) {
376 if (TlsGetValue(entry.ga_slot) == entry.ga_view) TlsSetValue(entry.ga_slot, nullptr);
377 VirtualFree(entry.ga_view, 0, MEM_RELEASE);
378 }
326 if (entry.block) { 379 if (entry.block) {
327 void** slots = module_tls_slots(); 380 void** slots = module_tls_slots();
328 if (slots && entry.index < kMaxModuleTlsSlots && slots[entry.index] == entry.block) 381 if (slots && entry.index < kMaxModuleTlsSlots && slots[entry.index] == entry.block)
@@ -332,11 +385,51 @@ void release_thread_slot(size_t slot) {
332 entry = ThreadTlsSlot{}; 385 entry = ThreadTlsSlot{};
333} 386}
334 387
388// A block load() put into a thread that was already running (install_on_existing_threads). Such a thread has no
389// g_thread_tls_slots record of it: the record is here, keyed by thread id, and the thread's own DLL_THREAD_DETACH or
390// the module's ~Loader takes the block out again.
391struct ExistingThreadBlock {
392 DWORD thread = 0;
393 size_t slot = 0;
394 Module* module = nullptr;
395 uint64_t generation = 0; // the module's tls_generation: with the pointer, what identifies the module
396 uint32_t index = kNoTlsIndex;
397 void*** vector = nullptr; // that thread's TEB->ThreadLocalStoragePointer field; the array itself can be replaced
398 void* saved = nullptr; // what the block replaced
399 void* block = nullptr;
400};
401
402// Immortal, like the thread events that use them. `ended` holds the ids of threads whose DLL_THREAD_DETACH has run:
403// Windows frees such a thread's TLS array next, so nothing may be put into it any more.
404struct ExistingThreads {
405 SRWLOCK lock = SRWLOCK_INIT; // a leaf: nothing is called while it is held but VirtualFree and thread queries
406 std::vector<ExistingThreadBlock> blocks;
407 std::vector<DWORD> ended;
408};
409ExistingThreads& existing_threads() {
410 static auto* state = new ExistingThreads;
411 return *state;
412}
413struct ExistingThreadsLock {
414 ExistingThreadsLock() { AcquireSRWLockExclusive(&existing_threads().lock); }
415 ~ExistingThreadsLock() { ReleaseSRWLockExclusive(&existing_threads().lock); }
416 ExistingThreadsLock(const ExistingThreadsLock&) = delete;
417 ExistingThreadsLock& operator=(const ExistingThreadsLock&) = delete;
418};
419
420bool has_existing_thread_block(DWORD thread, const Module& m) {
421 ExistingThreadsLock lock;
422 for (const auto& b : existing_threads().blocks)
423 if (b.thread == thread && b.module == &m && b.generation == m.tls_generation) return true;
424 return false;
425}
426
335void install_thread_block(Module& m) { 427void install_thread_block(Module& m) {
336 if (m.tls_slot >= kMaxMappedTlsModules) return; 428 if (m.tls_slot >= kMaxMappedTlsModules) return;
337 const size_t slot = m.tls_slot; 429 const size_t slot = m.tls_slot;
338 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 430 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
339 if (entry.module == &m && entry.generation == m.tls_generation) return; 431 if (entry.module == &m && entry.generation == m.tls_generation) return;
432 if (has_existing_thread_block(GetCurrentThreadId(), m)) return; // load() already gave this thread its copy
340 if (entry.module) { 433 if (entry.module) {
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. 434 // A copy left by a module whose Loader is gone (or from an earlier generation) is released; a live owner's is a conflict.
342 if (entry.module == g_tls_slot_owners[slot].load() && 435 if (entry.module == g_tls_slot_owners[slot].load() &&
@@ -364,6 +457,20 @@ void install_thread_block(Module& m) {
364 if (m.tls_zero_fill) 457 if (m.tls_zero_fill)
365 std::memset(static_cast<uint8_t*>(block) + m.tls_raw_size, 0, m.tls_zero_fill); 458 std::memset(static_cast<uint8_t*>(block) + m.tls_raw_size, 0, m.tls_zero_fill);
366 459
460 void** view = nullptr;
461 if (m.tls_ga_slot != kNoTlsIndex) {
462 // The /GA view: [0] and [tls_index] are this thread's block, the rest stays null (the image reads no other).
463 view = static_cast<void**>(
464 VirtualAlloc(nullptr, kMaxModuleTlsSlots * sizeof(void*), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
465 if (!view) {
466 VirtualFree(block, 0, MEM_RELEASE);
467 throw std::runtime_error(m.name + ": TLS view allocation failed");
468 }
469 view[0] = block;
470 view[m.tls_index] = block;
471 TlsSetValue(m.tls_ga_slot, view);
472 }
473
367 void* saved = slots[m.tls_index]; 474 void* saved = slots[m.tls_index];
368 slots[m.tls_index] = block; 475 slots[m.tls_index] = block;
369 entry.module = &m; 476 entry.module = &m;
@@ -371,6 +478,45 @@ void install_thread_block(Module& m) {
371 entry.saved = saved; 478 entry.saved = saved;
372 entry.block = block; 479 entry.block = block;
373 entry.index = m.tls_index; 480 entry.index = m.tls_index;
481 entry.ga_view = view;
482 entry.ga_slot = m.tls_ga_slot;
483}
484
485// Rewrites a /GA EXE's slot-0 TLS reads (Module::tls_ga_slot): every `mov r64, gs:[58h]` (65 REX.W 8B /r with
486// mod=00, r/m=100, SIB=25, disp32=58h; REX 48 or 4C for r8-r15) in an executable section becomes the same
487// instruction with disp32 = 1480h + 8 * slot, TEB->TlsSlots[slot]. Same length, so nothing else moves. The 9-byte
488// form, with its segment prefix, SIB 25 and that displacement, is not something code or tables produce by accident.
489// Must run before protect_sections() and before any of the image's code (its TLS callbacks included).
490size_t patch_ga_tls_reads(Module& m, uint32_t slot) {
491 const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(m.base);
492 const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(m.base + dos->e_lfanew);
493 const IMAGE_SECTION_HEADER* sec = IMAGE_FIRST_SECTION(nt);
494 const uint32_t disp = 0x1480u + 8u * slot;
495 size_t sites = 0;
496 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) {
497 if (!(sec->Characteristics & IMAGE_SCN_MEM_EXECUTE)) continue;
498 const uint32_t size = (std::min)(sec->Misc.VirtualSize, sec->SizeOfRawData);
499 if (sec->VirtualAddress > m.size || size > m.size - sec->VirtualAddress || size < 9) continue;
500 uint8_t* p = m.base + sec->VirtualAddress;
501 for (uint32_t k = 0; k + 9 <= size; ++k) {
502 if (p[k] != 0x65 || (p[k + 1] != 0x48 && p[k + 1] != 0x4C) || p[k + 2] != 0x8B) continue;
503 const uint8_t modrm = p[k + 3];
504 if ((modrm & 0xC7) != 0x04 || p[k + 4] != 0x25) continue;
505 uint32_t d;
506 std::memcpy(&d, p + k + 5, 4);
507 if (d != 0x58) continue;
508 std::memcpy(p + k + 5, &disp, 4);
509 ++sites;
510 k += 8;
511 }
512 }
513 return sites;
514}
515
516bool ga_tls_patch_enabled() {
517 char v[8] = {};
518 size_t n = 0;
519 return !(getenv_s(&n, v, "LEONIDA_TLS_GA_PATCH") == 0 && n == 2 && v[0] == '0');
374} 520}
375 521
376void uninstall_thread_block(Module& m) { 522void uninstall_thread_block(Module& m) {
@@ -407,6 +553,269 @@ void run_callbacks(Module& m, uint32_t reason, bool trace = false) {
407 } 553 }
408} 554}
409 555
556// ---- Threads that existed before load() ---------------------------------------------------------------------------
557//
558// When Windows loads a DLL with static TLS itself, every running thread gets a block for it (and no DLL_THREAD_ATTACH).
559// The helper DLL gets exactly that, so in a thread that was already running the reserved slot holds the helper's
560// one-byte block, and mapped __declspec(thread) code there would read and write past it. Such threads are not rare:
561// the workers of the process thread pool predate most loads, and the task queue runs a title's callbacks on them.
562// load() therefore gives each of them a copy of the template too, through the thread's TEB, which is ordinary memory
563// of this process.
564//
565// What makes that safe:
566// - The slot is the helper's, and nothing reads the helper's variable, so swapping the pointer under a running
567// thread disturbs nothing; the thread cannot be in mapped code of a module whose load() has not returned.
568// - The swap is made with g_tls_lock held exclusively, so no thread is inside its attach or detach event meanwhile.
569// - A thread whose detach event has run is skipped (`ended`), and so is one with no TLS array or no helper block:
570// Windows is about to free, or never built, what the block would go into.
571// - The block comes out again in that thread's own detach event, before Windows frees the array, or in ~Loader.
572// What is left:
573// - A thread that ran its detach event before the helper DLL was ever loaded and has not left the process yet is
574// not in `ended`; if Windows leaves a stale array pointer in its TEB for those last instructions, the write goes
575// to freed heap memory.
576// - Windows replaces a thread's TLS array (a new one, copied from the old) when some thread loads a DLL with static
577// TLS. If that happens during the swap, the write can land in the old array; the thread then still has the
578// helper's one-byte block, and the first mapped __declspec(thread) access on it writes past that block: heap
579// corruption, with nothing to show for it. The swap therefore reads the array pointer again after writing and
580// repeats on the new array (kSwapAttempts times); if the block is not in the thread's current array at the end,
581// it is taken back and the miss is logged. A replacement after that last look is not seen.
582// - TerminateThread frees a thread's TEB with no detach event. Every read and write of another thread's TEB or
583// TLS array here is made right after the thread was seen running and inside __try, so a TEB that has just gone
584// is a skipped thread, not a fault in load() or ~Loader. If the memory was already given to something else, the
585// write is not caught.
586using QueryThreadFn = LONG(NTAPI*)(HANDLE, int, void*, ULONG, ULONG*);
587struct ThreadBasicInfo { // THREAD_BASIC_INFORMATION (winternl.h keeps it opaque), x64
588 LONG exit_status;
589 void* teb;
590 void* process_id;
591 void* thread_id;
592 ULONG_PTR affinity;
593 LONG priority;
594 LONG base_priority;
595};
596static_assert(sizeof(ThreadBasicInfo) == 48);
597
598QueryThreadFn query_thread_fn() {
599 static const auto fn = reinterpret_cast<QueryThreadFn>(
600 reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread")));
601 return fn;
602}
603
604// The TEB's ThreadLocalStoragePointer field of a thread that is still running; null otherwise.
605void*** running_thread_tls_vector(HANDLE thread) {
606 ThreadBasicInfo info{};
607 const QueryThreadFn query = query_thread_fn();
608 if (!query || query(thread, 0 /* ThreadBasicInformation */, &info, sizeof info, nullptr) < 0) return nullptr;
609 if (info.exit_status != STILL_ACTIVE || !info.teb) return nullptr;
610 return reinterpret_cast<void***>(static_cast<uint8_t*>(info.teb) + 0x58);
611}
612
613// Another thread's TLS array and one entry of it, read through its TEB. False when the memory is not there any more
614// (the thread was terminated). No C++ objects in these three: they are __try frames.
615bool read_thread_slot(void*** vector, uint32_t index, void**& slots, void*& value) noexcept {
616 __try {
617 slots = *vector;
618 value = slots ? slots[index] : nullptr;
619 return true;
620 } __except (EXCEPTION_EXECUTE_HANDLER) {
621 slots = nullptr;
622 value = nullptr;
623 return false;
624 }
625}
626
627bool write_thread_slot(void** slots, uint32_t index, void* value) noexcept {
628 __try {
629 slots[index] = value;
630 return true;
631 } __except (EXCEPTION_EXECUTE_HANDLER) {
632 return false;
633 }
634}
635
636// Puts `saved` back where `block` is, if it is still there.
637void restore_thread_slot(void*** vector, uint32_t index, void* block, void* saved) noexcept {
638 __try {
639 void** slots = *vector;
640 if (slots && slots[index] == block) slots[index] = saved;
641 } __except (EXCEPTION_EXECUTE_HANDLER) {
642 }
643}
644
645// Takes a block out of its slot and frees it. The existing-threads lock is held; b.vector is null when the thread
646// is gone.
647void remove_existing_block(const ExistingThreadBlock& b) {
648 if (b.vector && b.index < kMaxModuleTlsSlots) restore_thread_slot(b.vector, b.index, b.block, b.saved);
649 VirtualFree(b.block, 0, MEM_RELEASE);
650}
651
652constexpr int kSwapAttempts = 4;
653constexpr size_t kMaxEndedThreads = 1024;
654
655// load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done.
656void install_on_existing_threads(Module& m) {
657 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill;
658 if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kMaxMappedTlsModules) return;
659 // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which
660 // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours.
661 if (!query_thread_fn()) return;
662
663 // Outside the TLS lock: none of this may wait for a thread that is inside its attach event.
664 // The handles are closed on every way out, also when a vector below cannot grow.
665 struct Candidate {
666 DWORD id = 0;
667 HANDLE handle = nullptr;
668 };
669 struct Candidates {
670 std::vector<Candidate> list;
671 HANDLE snapshot = INVALID_HANDLE_VALUE;
672 ~Candidates() {
673 if (snapshot != INVALID_HANDLE_VALUE) CloseHandle(snapshot);
674 for (const Candidate& c : list)
675 if (c.handle) CloseHandle(c.handle);
676 }
677 } found;
678 std::vector<Candidate>& candidates = found.list;
679 // TH32CS_SNAPTHREAD lists the threads of every process; the loop keeps this one's.
680 found.snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
681 if (found.snapshot == INVALID_HANDLE_VALUE) return;
682 THREADENTRY32 entry{};
683 entry.dwSize = sizeof entry;
684 const DWORD process = GetCurrentProcessId(), self = GetCurrentThreadId();
685 for (BOOL more = Thread32First(found.snapshot, &entry); more; more = Thread32Next(found.snapshot, &entry)) {
686 if (entry.th32OwnerProcessID != process || entry.th32ThreadID == self) continue;
687 candidates.push_back({entry.th32ThreadID, nullptr}); // the slot first, so the handle always has an owner
688 candidates.back().handle = OpenThread(THREAD_QUERY_INFORMATION, FALSE, entry.th32ThreadID);
689 }
690
691 {
692 ExclusiveTlsLock tls_lock;
693 ExistingThreadsLock lock;
694 ExistingThreads& state = existing_threads();
695 for (const Candidate& c : candidates) {
696 if (!c.handle) continue;
697 if (std::find(state.ended.begin(), state.ended.end(), c.id) != state.ended.end()) continue;
698 void*** vector = running_thread_tls_vector(c.handle);
699 void** slots = nullptr;
700 void* saved = nullptr;
701 if (!vector || !read_thread_slot(vector, m.tls_index, slots, saved) || !slots || !saved) continue;
702 // A copy an earlier module left in this slot of this thread goes first; what it replaced is kept.
703 bool present = false;
704 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
705 if (it->thread != c.id || it->slot != m.tls_slot) {
706 ++it;
707 } else if (it->module == &m && it->generation == m.tls_generation) {
708 present = true;
709 break;
710 } else {
711 if (saved == it->block) saved = it->saved;
712 it->vector = vector;
713 remove_existing_block(*it);
714 it = state.blocks.erase(it);
715 }
716 }
717 if (present) continue;
718 void* block = VirtualAlloc(nullptr, static_cast<SIZE_T>(total), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
719 if (!block) continue;
720 if (m.tls_raw_size) std::memcpy(block, m.tls_template, m.tls_raw_size);
721
722 // Write, then look at the thread's array pointer again: if Windows has replaced the array meanwhile, the
723 // write went into the old one, and it is made again in the new one.
724 bool installed = false;
725 for (int attempt = 0; attempt < kSwapAttempts && !installed; ++attempt) {
726 if (!running_thread_tls_vector(c.handle) || !write_thread_slot(slots, m.tls_index, block)) break;
727 void** now = nullptr;
728 void* value = nullptr;
729 if (!read_thread_slot(vector, m.tls_index, now, value) || !now) break;
730 installed = now == slots && value == block;
731 slots = now;
732 }
733 if (!installed) {
734 restore_thread_slot(vector, m.tls_index, block, saved);
735 VirtualFree(block, 0, MEM_RELEASE);
736 static std::atomic<bool> logged{false};
737 if (!logged.exchange(true))
738 std::fprintf(stderr, "[rt] loader: %s: a running thread did not take its TLS block (it ended, or "
739 "its TLS array kept changing); mapped thread-local data is not valid on it\n",
740 m.name.c_str());
741 continue;
742 }
743 state.blocks.push_back({c.id, m.tls_slot, &m, m.tls_generation, m.tls_index, vector, saved, block});
744 }
745 }
746}
747
748// ~Loader, with g_tls_lock held exclusively: the blocks load() put into other threads come out. A thread that has
749// ended without a detach event (TerminateThread) has no TEB to restore.
750void remove_from_existing_threads(Module& m) {
751 ExistingThreadsLock lock;
752 ExistingThreads& state = existing_threads();
753 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
754 if (it->module != &m || it->generation != m.tls_generation) {
755 ++it;
756 continue;
757 }
758 ExistingThreadBlock b = *it;
759 it = state.blocks.erase(it);
760 const HANDLE h = OpenThread(THREAD_QUERY_INFORMATION, FALSE, b.thread);
761 if (!h || running_thread_tls_vector(h) != b.vector) b.vector = nullptr;
762 if (h) CloseHandle(h);
763 remove_existing_block(b);
764 }
765}
766
767// DLL_THREAD_ATTACH: a record under this thread's id is from a thread that ended without a detach event.
768void forget_ended_thread_id() {
769 const DWORD self = GetCurrentThreadId();
770 ExistingThreadsLock lock;
771 ExistingThreads& state = existing_threads();
772 state.ended.erase(std::remove(state.ended.begin(), state.ended.end(), self), state.ended.end());
773 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
774 if (it->thread != self) {
775 ++it;
776 continue;
777 }
778 VirtualFree(it->block, 0, MEM_RELEASE);
779 it = state.blocks.erase(it);
780 }
781}
782
783// DLL_THREAD_DETACH, before this thread's own records are released: the blocks load() gave it come out, newest first,
784// after the module's TLS callbacks have seen the event (Windows sends DLL_THREAD_DETACH to a DLL for a thread that
785// was running before it was loaded, too).
786void release_existing_blocks_of_this_thread() {
787 const DWORD self = GetCurrentThreadId();
788 std::vector<ExistingThreadBlock> mine;
789 {
790 ExistingThreadsLock lock;
791 for (const auto& b : existing_threads().blocks)
792 if (b.thread == self) mine.push_back(b);
793 }
794 for (auto it = mine.rbegin(); it != mine.rend(); ++it) {
795 Module* m = it->module;
796 if (g_tls_slot_owners[it->slot].load() != m || g_tls_slot_generations[it->slot].load() != it->generation ||
797 !m->initialised)
798 continue;
799 try {
800 run_callbacks(*m, DLL_THREAD_DETACH);
801 } catch (const std::exception& e) {
802 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what());
803 }
804 }
805 ExistingThreadsLock lock;
806 ExistingThreads& state = existing_threads();
807 for (auto it = state.blocks.end(); it != state.blocks.begin();) {
808 --it;
809 if (it->thread != self) continue;
810 remove_existing_block(*it);
811 it = state.blocks.erase(it);
812 }
813 // Bounded: an id matters only until its thread has left the process, moments after this event, so the oldest
814 // can go. (An id also leaves the list when a new thread gets it.)
815 if (state.ended.size() >= kMaxEndedThreads) state.ended.erase(state.ended.begin(), state.ended.begin() + kMaxEndedThreads / 2);
816 state.ended.push_back(self);
817}
818
410// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under 819// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under
411// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an 820// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an
412// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events 821// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events
@@ -416,6 +825,11 @@ void __cdecl on_host_thread_event(DWORD reason) {
416 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events 825 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events
417 // away from the other slots. Nothing may leave DllMain. 826 // away from the other slots. Nothing may leave DllMain.
418 if (reason == DLL_THREAD_ATTACH) { 827 if (reason == DLL_THREAD_ATTACH) {
828 try {
829 forget_ended_thread_id();
830 } catch (const std::exception& e) {
831 std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what());
832 }
419 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { 833 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) {
420 Module* m = g_tls_slot_owners[slot].load(); 834 Module* m = g_tls_slot_owners[slot].load();
421 if (!m) continue; 835 if (!m) continue;
@@ -429,6 +843,13 @@ void __cdecl on_host_thread_event(DWORD reason) {
429 } 843 }
430 } 844 }
431 } else if (reason == DLL_THREAD_DETACH) { 845 } else if (reason == DLL_THREAD_DETACH) {
846 // The blocks load() gave this thread while it was already running come out first (they can sit on top of
847 // an older module's block in the same slot).
848 try {
849 release_existing_blocks_of_this_thread();
850 } catch (const std::exception& e) {
851 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what());
852 }
432 for (size_t i = kMaxMappedTlsModules; i-- > 0;) { 853 for (size_t i = kMaxMappedTlsModules; i-- > 0;) {
433 Module* m = g_tls_slot_owners[i].load(); 854 Module* m = g_tls_slot_owners[i].load();
434 if (m && g_thread_tls_slots[i].module == m && 855 if (m && g_thread_tls_slots[i].module == m &&
@@ -451,9 +872,15 @@ void __cdecl on_host_thread_event(DWORD reason) {
451 872
452// The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used. 873// The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used.
453bool prefer_host_copy(const std::string& dll) { 874bool prefer_host_copy(const std::string& dll) {
875 // The second row is the Debug builds of the same DLLs. A Debug build of a stand-in image (tiny_game) links them,
876 // and without them here its C++ exceptions were not redirected below: a throw caught inside the image ended the
877 // run with 0xE06D7363 (run_tiny_game_eh in a Debug build).
454 static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll", 878 static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll",
455 "msvcp140_2.dll", "msvcp140_atomic_wait.dll", "msvcp140_codecvt_ids.dll", 879 "msvcp140_2.dll", "msvcp140_atomic_wait.dll", "msvcp140_codecvt_ids.dll",
456 "concrt140.dll", "vccorlib140.dll", "vcomp140.dll"}; 880 "concrt140.dll", "vccorlib140.dll", "vcomp140.dll",
881 "vcruntime140d.dll", "vcruntime140_1d.dll", "msvcp140d.dll", "msvcp140_1d.dll",
882 "msvcp140_2d.dll", "msvcp140d_atomic_wait.dll", "msvcp140d_codecvt_ids.dll",
883 "concrt140d.dll", "vccorlib140d.dll", "vcomp140d.dll"};
457 for (auto* n : names) 884 for (auto* n : names)
458 if (dll == n) return true; 885 if (dll == n) return true;
459 return false; 886 return false;
@@ -548,11 +975,30 @@ bool bundled_owns_handle(void* ctx, void* module) {
548 return static_cast<Loader*>(ctx)->owns_module_handle(module); 975 return static_cast<Loader*>(ctx)->owns_module_handle(module);
549} 976}
550 977
978void* bundled_find_loaded_w(void* ctx, const std::wstring& basename) {
979 return static_cast<Loader*>(ctx)->find_loaded_module_w(basename);
980}
981
982void* bundled_load_w(void* ctx, const std::wstring& basename, uint32_t flags, bool& handled) {
983 return static_cast<Loader*>(ctx)->load_runtime_module_w(basename, flags, handled);
984}
985
551const shims::BundledModuleOps kBundledOps{ 986const shims::BundledModuleOps kBundledOps{
552 &bundled_find_loaded, 987 &bundled_find_loaded,
553 &bundled_load, 988 &bundled_load,
554 &bundled_get_proc, 989 &bundled_get_proc,
555 &bundled_owns_handle, 990 &bundled_owns_handle,
991 &bundled_find_loaded_w,
992 &bundled_load_w,
993};
994
995// Marks what a run-time load maps as a dynamic load for as long as it is in scope (the caller holds the mutex).
996struct RuntimeLoadScope {
997 explicit RuntimeLoadScope(int& depth) : depth_(depth) { ++depth_; }
998 ~RuntimeLoadScope() { --depth_; }
999 RuntimeLoadScope(const RuntimeLoadScope&) = delete;
1000 RuntimeLoadScope& operator=(const RuntimeLoadScope&) = delete;
1001 int& depth_;
556}; 1002};
557} // namespace 1003} // namespace
558 1004
@@ -594,6 +1040,7 @@ Loader::~Loader() {
594 Module* owner = m; 1040 Module* owner = m;
595 if (g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr)) 1041 if (g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr))
596 g_tls_slot_generations[m->tls_slot].store(0); 1042 g_tls_slot_generations[m->tls_slot].store(0);
1043 remove_from_existing_threads(*m);
597 } 1044 }
598 uninstall_tls_for_thread(*m); 1045 uninstall_tls_for_thread(*m);
599 } 1046 }
@@ -607,11 +1054,14 @@ Loader::~Loader() {
607 1054
608Module& Loader::load(const std::filesystem::path& image) { 1055Module& Loader::load(const std::filesystem::path& image) {
609 std::lock_guard lock(mutex_); 1056 std::lock_guard lock(mutex_);
610 std::string key = lower(image.filename().string()); 1057 const auto key = module_key(image);
611 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; 1058 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second;
1059 const auto narrow_key = narrow_module_key(image);
1060 if (Module* existing = find_narrow_module(narrow_key)) return *existing;
612 Module* mapped = nullptr; 1061 Module* mapped = nullptr;
613 try { 1062 try {
614 mapped = &map_image(image); 1063 mapped = &map_image(image, narrow_key);
1064 mapped->dynamic_load = runtime_loads_ > 0; // before bind_imports: its dependencies are marked the same way
615 bind_imports(*mapped); // loads every bundled module m imports first, so they land in init_order_ before m 1065 bind_imports(*mapped); // loads every bundled module m imports first, so they land in init_order_ before m
616 protect_sections(*mapped); 1066 protect_sections(*mapped);
617 register_unwind(*mapped); 1067 register_unwind(*mapped);
@@ -631,10 +1081,41 @@ Module& Loader::load(const std::filesystem::path& image) {
631 return m; 1081 return m;
632} 1082}
633 1083
1084Module* Loader::find_narrow_module(const std::string& dll_lower) const {
1085 if (dll_lower.empty()) return nullptr;
1086 // library_loader and PE import names keep their existing narrow-byte contract: the exact compare below is
1087 // bytewise, and the key is never reinterpreted as UTF-8.
1088 for (const auto& entry : by_name_)
1089 if (entry.second->narrow_key == dll_lower) return entry.second;
1090 // The key is ASCII case-folded only. A name with letters outside ASCII (Cyrillic in code page 1251, say)
1091 // compares case-insensitively through the code page, as GetModuleHandleA does: GUEST_ДА.EXE finds guest_да.exe.
1092 // Widening the folded key is safe here: rt::lower() folds ASCII letters only, and no ANSI code page's multibyte
1093 // sequences contain ASCII letter bytes, so both sides widen to the same characters they were spelt with.
1094 if (const std::wstring wide = acp_to_wide(dll_lower); !wide.empty())
1095 for (const auto& entry : by_name_)
1096 if (!entry.second->narrow_key.empty() &&
1097 same_module_name(acp_to_wide(entry.second->narrow_key).c_str(), wide.c_str()))
1098 return entry.second;
1099 return nullptr;
1100}
1101
1102Module* Loader::find_wide_module(const std::wstring& basename) const {
1103 if (basename.empty()) return nullptr;
1104 for (const auto& entry : by_name_)
1105 if (same_module_name(entry.first.c_str(), basename.c_str())) return entry.second;
1106 return nullptr;
1107}
1108
1109void* Loader::find_loaded_module_w(const std::wstring& basename) const {
1110 std::lock_guard lock(mutex_);
1111 Module* m = find_wide_module(basename);
1112 return m ? static_cast<void*>(m->base) : nullptr;
1113}
1114
634void* Loader::find_loaded_module(const std::string& dll_lower) const { 1115void* Loader::find_loaded_module(const std::string& dll_lower) const {
635 std::lock_guard lock(mutex_); 1116 std::lock_guard lock(mutex_);
636 auto it = by_name_.find(dll_lower); 1117 Module* m = find_narrow_module(dll_lower);
637 return it == by_name_.end() ? nullptr : static_cast<void*>(it->second->base); 1118 return m ? static_cast<void*>(m->base) : nullptr;
638} 1119}
639 1120
640void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled) { 1121void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled) {
@@ -642,44 +1123,69 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags,
642 if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr; 1123 if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr;
643 1124
644 std::lock_guard lock(mutex_); 1125 std::lock_guard lock(mutex_);
645 const auto existing = by_name_.find(dll_lower); 1126 const RuntimeLoadScope dynamic(runtime_loads_);
1127 Module* existing = find_narrow_module(dll_lower);
646 const std::filesystem::path candidate = game_dir_ / dll_lower; 1128 const std::filesystem::path candidate = game_dir_ / dll_lower;
647 std::error_code ec; 1129 std::error_code ec;
648 const bool is_bundled = existing != by_name_.end() || std::filesystem::is_regular_file(candidate, ec); 1130 const bool is_bundled = existing || std::filesystem::is_regular_file(candidate, ec);
649 if (!is_bundled) return nullptr; 1131 if (!is_bundled) return nullptr;
650 1132
651 handled = true; 1133 handled = true;
1134 return load_runtime_candidate(existing, candidate, flags, dll_lower);
1135}
1136
1137void* Loader::load_runtime_module_w(const std::wstring& basename, uint32_t flags, bool& handled) {
1138 handled = false;
1139 if (basename.empty()) return nullptr;
1140 // A name the code page can spell takes the narrow path's host-copy rule as well.
1141 if (const std::string narrow = narrow_module_key(std::filesystem::path(basename)); !narrow.empty())
1142 if (prefer_host_copy(narrow)) return nullptr;
1143
1144 std::lock_guard lock(mutex_);
1145 Module* existing = find_wide_module(basename);
1146 const std::filesystem::path candidate = game_dir_ / basename;
1147 std::error_code ec;
1148 if (!existing && !std::filesystem::is_regular_file(candidate, ec)) return nullptr;
1149
1150 handled = true;
1151 return load_runtime_candidate(existing, candidate, flags, path_utf8(basename));
1152}
1153
1154void* Loader::load_runtime_candidate(Module* existing, const std::filesystem::path& candidate, uint32_t flags,
1155 const std::string& display) {
652 // Win32 DONT_RESOLVE_DLL_REFERENCES (0x1) forbids resolving dependencies or running TLS/DllMain; refuse it 1156 // Win32 DONT_RESOLVE_DLL_REFERENCES (0x1) forbids resolving dependencies or running TLS/DllMain; refuse it
653 // explicitly instead of silently performing a normal resolving + initialising load. 1157 // explicitly instead of silently performing a normal resolving + initialising load.
654 if ((flags & DONT_RESOLVE_DLL_REFERENCES) != 0) { 1158 if ((flags & DONT_RESOLVE_DLL_REFERENCES) != 0) {
655 std::fprintf(stderr, 1159 std::fprintf(stderr,
656 "[rt] loader: LoadLibraryEx(%s, DONT_RESOLVE_DLL_REFERENCES) is not supported for bundled DLLs\n", 1160 "[rt] loader: LoadLibraryEx(%s, DONT_RESOLVE_DLL_REFERENCES) is not supported for bundled DLLs\n",
657 dll_lower.c_str()); 1161 display.c_str());
658 SetLastError(ERROR_NOT_SUPPORTED); 1162 SetLastError(ERROR_NOT_SUPPORTED);
659 return nullptr; 1163 return nullptr;
660 } 1164 }
661 1165
662 if (existing != by_name_.end()) { 1166 if (existing) {
663 try { 1167 try {
664 initialise(); 1168 initialise();
665 return static_cast<void*>(existing->second->base); 1169 return static_cast<void*>(existing->base);
666 } catch (const std::exception& e) { 1170 } catch (const std::exception& e) {
667 std::fprintf(stderr, "[rt] loader: run-time initialise of %s failed: %s\n", dll_lower.c_str(), e.what()); 1171 std::fprintf(stderr, "[rt] loader: run-time initialise of %s failed: %s\n", display.c_str(), e.what());
668 SetLastError(ERROR_DLL_INIT_FAILED); 1172 SetLastError(ERROR_DLL_INIT_FAILED);
669 return nullptr; 1173 return nullptr;
670 } 1174 }
671 } 1175 }
672 1176
1177 Module* mapped = nullptr;
673 try { 1178 try {
674 Module& m = load(candidate); 1179 Module& m = load(candidate);
1180 mapped = &m;
675 initialise(); 1181 initialise();
676 std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str()); 1182 std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str());
677 return static_cast<void*>(m.base); 1183 return static_cast<void*>(m.base);
678 } catch (const std::exception& e) { 1184 } catch (const std::exception& e) {
679 // load() drops a module that failed to map or bind (dependencies included); this also drops one whose 1185 // load() drops a module that failed to map or bind (dependencies included); this also drops one whose
680 // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via order_. 1186 // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via order_.
681 by_name_.erase(dll_lower); 1187 by_name_.erase(module_key(mapped ? mapped->path : candidate));
682 std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what()); 1188 std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", display.c_str(), e.what());
683 SetLastError(ERROR_DLL_INIT_FAILED); 1189 SetLastError(ERROR_DLL_INIT_FAILED);
684 return nullptr; 1190 return nullptr;
685 } 1191 }
@@ -701,6 +1207,7 @@ void* Loader::resolve_module_export(void* module_handle, const std::string& sym,
701 if (auto it = target->exports.find(sym); it != target->exports.end()) return it->second; 1207 if (auto it = target->exports.find(sym); it != target->exports.end()) return it->second;
702 if (auto it = target->forwarders.find(sym); it != target->forwarders.end()) { 1208 if (auto it = target->forwarders.find(sym); it != target->forwarders.end()) {
703 try { 1209 try {
1210 const RuntimeLoadScope dynamic(runtime_loads_);
704 Binding binding = Binding::Unimplemented; 1211 Binding binding = Binding::Unimplemented;
705 void* fn = resolve_forwarder(it->second, binding, 0); 1212 void* fn = resolve_forwarder(it->second, binding, 0);
706 if (binding == Binding::Module) initialise(); 1213 if (binding == Binding::Module) initialise();
@@ -787,7 +1294,11 @@ void Loader::initialise(Module& m) {
787 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 1294 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
788 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { 1295 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) {
789 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); 1296 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva);
790 const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, nullptr); 1297 // lpvReserved "is NULL for dynamic loads and non-NULL for static loads" (DllMain docs). What Windows points
1298 // it at is its own; a static load gets a CONTEXT captured here, so a DLL that reads through it reads memory.
1299 CONTEXT context{};
1300 if (!m.dynamic_load) RtlCaptureContext(&context);
1301 const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, m.dynamic_load ? nullptr : &context);
791 if (startup_trace::enabled()) 1302 if (startup_trace::enabled())
792 startup_trace::event("dllmain", "\"module\":" + startup_trace::quote(m.name) + 1303 startup_trace::event("dllmain", "\"module\":" + startup_trace::quote(m.name) +
793 ",\"result\":" + std::to_string(ok)); 1304 ",\"result\":" + std::to_string(ok));
@@ -806,12 +1317,12 @@ void Loader::set_initialised(Module& m, bool value) {
806 m.initialised = value; 1317 m.initialised = value;
807} 1318}
808 1319
809Module& Loader::map_image(const std::filesystem::path& path) { 1320Module& Loader::map_image(const std::filesystem::path& path, const std::string& narrow_key) {
810 auto file = read_file(path); 1321 auto file = read_file(path);
811 const std::string name = path.filename().string(); 1322 const std::string name = path_utf8(path.filename());
812 auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(file.data()); 1323 auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(file.data());
813 if (file.size() < sizeof(IMAGE_DOS_HEADER) || dos->e_magic != IMAGE_DOS_SIGNATURE) 1324 if (file.size() < sizeof(IMAGE_DOS_HEADER) || dos->e_magic != IMAGE_DOS_SIGNATURE)
814 throw std::runtime_error(path.string() + ": not an MZ image"); 1325 throw std::runtime_error(path_utf8(path) + ": not an MZ image");
815 if (dos->e_lfanew < 0 || static_cast<uint64_t>(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size()) 1326 if (dos->e_lfanew < 0 || static_cast<uint64_t>(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size())
816 throw std::runtime_error(name + ": the NT headers are outside the file"); 1327 throw std::runtime_error(name + ": the NT headers are outside the file");
817 auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew); 1328 auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew);
@@ -835,11 +1346,12 @@ Module& Loader::map_image(const std::filesystem::path& path) {
835 1346
836 auto* m = new Module; 1347 auto* m = new Module;
837 m->name = name; 1348 m->name = name;
1349 m->narrow_key = narrow_key;
838 m->path = path; 1350 m->path = path;
839 m->preferred_base = oh.ImageBase; 1351 m->preferred_base = oh.ImageBase;
840 m->size = oh.SizeOfImage; 1352 m->size = oh.SizeOfImage;
841 m->entry_rva = oh.AddressOfEntryPoint; 1353 m->entry_rva = oh.AddressOfEntryPoint;
842 by_name_[lower(m->name)] = m; 1354 by_name_[module_key(path)] = m;
843 order_.push_back(m); 1355 order_.push_back(m);
844 1356
845 // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual. 1357 // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual.
@@ -864,6 +1376,8 @@ Module& Loader::map_image(const std::filesystem::path& path) {
864 std::memcpy(m->base, file.data(), oh.SizeOfHeaders); 1376 std::memcpy(m->base, file.data(), oh.SizeOfHeaders);
865 auto* sec = IMAGE_FIRST_SECTION(nt); 1377 auto* sec = IMAGE_FIRST_SECTION(nt);
866 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { 1378 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) {
1379 if (sec->VirtualAddress < oh.SizeOfHeaders)
1380 throw std::runtime_error(m->name + ": section " + std::to_string(i) + " overlaps the headers");
867 uint32_t n = std::min(sec->SizeOfRawData, sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData); 1381 uint32_t n = std::min(sec->SizeOfRawData, sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData);
868 if (!n) continue; 1382 if (!n) continue;
869 if (sec->PointerToRawData > file.size() || n > file.size() - sec->PointerToRawData) 1383 if (sec->PointerToRawData > file.size() || n > file.size() - sec->PointerToRawData)
@@ -889,6 +1403,9 @@ Module& Loader::map_image(const std::filesystem::path& path) {
889 size_t count = (block->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2; 1403 size_t count = (block->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2;
890 for (size_t i = 0; i < count; ++i) { 1404 for (size_t i = 0; i < count; ++i) {
891 uint16_t type = entries[i] >> 12, off = entries[i] & 0xFFF; 1405 uint16_t type = entries[i] >> 12, off = entries[i] & 0xFFF;
1406 if (type != IMAGE_REL_BASED_ABSOLUTE &&
1407 static_cast<uint64_t>(block->VirtualAddress) + off < oh.SizeOfHeaders)
1408 throw std::runtime_error(m->name + ": a relocation lands in the headers");
892 if (type == IMAGE_REL_BASED_DIR64) { 1409 if (type == IMAGE_REL_BASED_DIR64) {
893 require_range(m->name, static_cast<uint64_t>(block->VirtualAddress) + off, sizeof(uint64_t), m->size, 1410 require_range(m->name, static_cast<uint64_t>(block->VirtualAddress) + off, sizeof(uint64_t), m->size,
894 "a relocation"); 1411 "a relocation");
@@ -987,6 +1504,26 @@ void Loader::initialize_tls(Module& m) {
987 // VirtualProtect dance. 1504 // VirtualProtect dance.
988 if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index; 1505 if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index;
989 } 1506 }
1507 {
1508 // An EXE's code may read its TLS at index 0 directly (/GA); index 0 is gta6rt.exe's here (pe_loader.h,
1509 // tls_ga_slot). Patched before any of the image's code runs, TLS callbacks included.
1510 const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(m.base);
1511 const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(m.base + dos->e_lfanew);
1512 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && total && index != 0 && ga_tls_patch_enabled()) {
1513 static const DWORD ga_slot = TlsAlloc();
1514 if (ga_slot == TLS_OUT_OF_INDEXES || ga_slot >= 64) {
1515 std::fprintf(stderr, "[rt] loader: %s: no TlsAlloc slot below 64 for its index-0 TLS reads\n",
1516 m.name.c_str());
1517 } else {
1518 m.tls_ga_sites = patch_ga_tls_reads(m, ga_slot);
1519 if (m.tls_ga_sites) m.tls_ga_slot = ga_slot;
1520 std::fprintf(stderr,
1521 "[rt] loader: %s: %zu index-0 TLS reads (gs:[58h]) now read its own TLS (TlsSlots[%lu]); "
1522 "its module TLS index is %u\n",
1523 m.name.c_str(), m.tls_ga_sites, static_cast<unsigned long>(ga_slot), index);
1524 }
1525 }
1526 }
990 try { 1527 try {
991 install_thread_block(m); 1528 install_thread_block(m);
992 } catch (...) { 1529 } catch (...) {
@@ -1003,6 +1540,9 @@ void Loader::initialize_tls(Module& m) {
1003 m.tls_block = g_thread_tls_slots[slot].block; 1540 m.tls_block = g_thread_tls_slots[slot].block;
1004 m.tls_saved_block = g_thread_tls_slots[slot].saved; 1541 m.tls_saved_block = g_thread_tls_slots[slot].saved;
1005 } 1542 }
1543 // Threads started from here on get their copy from the helper DLL's DLL_THREAD_ATTACH; the ones already running
1544 // get it now.
1545 install_on_existing_threads(m);
1006} 1546}
1007 1547
1008void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); } 1548void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); }