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:
authorRoberto0953 <Roberto0953@users.noreply.github.com>2026-11-23 17:46:05 +0100
committerRoberto0953 <Roberto0953@users.noreply.github.com>2026-11-23 17:46:05 +0100
commit3dbde4295e33bd6cc10a8804e1327da90f37307e (patch)
tree4409499cb7637acf2733baaf6c7af15f76a0dbb1 /runtime/src/pe_loader.cpp
parent28ea6b971ba229e8caeb7bf4a50f263224b448fb (diff)
parent042c5f37836dc2c8d5913c2fc5a88e99bdee083b (diff)
Merge remote-tracking branch 'upstream/main' into rebase/4313-on-042c5f378
# Conflicts: # runtime/CMakeLists.txt # runtime/README.md # runtime/src/pe_loader.cpp
Diffstat (limited to 'runtime/src/pe_loader.cpp')
-rw-r--r--runtime/src/pe_loader.cpp421
1 files changed, 405 insertions, 16 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index a4c56cb5d..ecf44a221 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,36 @@ 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
54std::string path_utf8(const std::filesystem::path& path) {
55 const auto bytes = path.u8string();
56 return {reinterpret_cast<const char*>(bytes.data()), bytes.size()};
57}
58
30std::vector<uint8_t> read_file(const std::filesystem::path& p) { 59std::vector<uint8_t> read_file(const std::filesystem::path& p) {
31 std::ifstream f(p, std::ios::binary); 60 std::ifstream f(p, std::ios::binary);
32 if (!f) throw std::runtime_error("cannot open " + p.string()); 61 if (!f) throw std::runtime_error("cannot open " + path_utf8(p));
33 return {std::istreambuf_iterator<char>(f), {}}; 62 return {std::istreambuf_iterator<char>(f), {}};
34} 63}
35 64
@@ -589,11 +618,51 @@ void release_thread_slot(size_t slot) {
589 entry = ThreadTlsSlot{}; 618 entry = ThreadTlsSlot{};
590} 619}
591 620
621// A block load() put into a thread that was already running (install_on_existing_threads). Such a thread has no
622// g_thread_tls_slots record of it: the record is here, keyed by thread id, and the thread's own DLL_THREAD_DETACH or
623// the module's ~Loader takes the block out again.
624struct ExistingThreadBlock {
625 DWORD thread = 0;
626 size_t slot = 0;
627 Module* module = nullptr;
628 uint64_t generation = 0; // the module's tls_generation: with the pointer, what identifies the module
629 uint32_t index = kNoTlsIndex;
630 void*** vector = nullptr; // that thread's TEB->ThreadLocalStoragePointer field; the array itself can be replaced
631 void* saved = nullptr; // what the block replaced
632 void* block = nullptr;
633};
634
635// Immortal, like the thread events that use them. `ended` holds the ids of threads whose DLL_THREAD_DETACH has run:
636// Windows frees such a thread's TLS array next, so nothing may be put into it any more.
637struct ExistingThreads {
638 SRWLOCK lock = SRWLOCK_INIT; // a leaf: nothing is called while it is held but VirtualFree and thread queries
639 std::vector<ExistingThreadBlock> blocks;
640 std::vector<DWORD> ended;
641};
642ExistingThreads& existing_threads() {
643 static auto* state = new ExistingThreads;
644 return *state;
645}
646struct ExistingThreadsLock {
647 ExistingThreadsLock() { AcquireSRWLockExclusive(&existing_threads().lock); }
648 ~ExistingThreadsLock() { ReleaseSRWLockExclusive(&existing_threads().lock); }
649 ExistingThreadsLock(const ExistingThreadsLock&) = delete;
650 ExistingThreadsLock& operator=(const ExistingThreadsLock&) = delete;
651};
652
653bool has_existing_thread_block(DWORD thread, const Module& m) {
654 ExistingThreadsLock lock;
655 for (const auto& b : existing_threads().blocks)
656 if (b.thread == thread && b.module == &m && b.generation == m.tls_generation) return true;
657 return false;
658}
659
592void install_thread_block(Module& m) { 660void install_thread_block(Module& m) {
593 if (m.tls_slot >= kTlsSlotCount) return; 661 if (m.tls_slot >= kTlsSlotCount) return;
594 const size_t slot = m.tls_slot; 662 const size_t slot = m.tls_slot;
595 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 663 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
596 if (entry.module == &m && entry.generation == m.tls_generation) return; 664 if (entry.module == &m && entry.generation == m.tls_generation) return;
665 if (has_existing_thread_block(GetCurrentThreadId(), m)) return; // load() already gave this thread its copy
597 if (entry.module) { 666 if (entry.module) {
598 // A copy left by a module whose Loader is gone (or from an earlier generation) is released; a live owner's is a conflict. 667 // A copy left by a module whose Loader is gone (or from an earlier generation) is released; a live owner's is a conflict.
599 if (entry.module == g_tls_slot_owners[slot].load() && 668 if (entry.module == g_tls_slot_owners[slot].load() &&
@@ -664,6 +733,269 @@ void run_callbacks(Module& m, uint32_t reason, bool trace = false) {
664 } 733 }
665} 734}
666 735
736// ---- Threads that existed before load() ---------------------------------------------------------------------------
737//
738// When Windows loads a DLL with static TLS itself, every running thread gets a block for it (and no DLL_THREAD_ATTACH).
739// The helper DLL gets exactly that, so in a thread that was already running the reserved slot holds the helper's
740// one-byte block, and mapped __declspec(thread) code there would read and write past it. Such threads are not rare:
741// the workers of the process thread pool predate most loads, and the task queue runs a title's callbacks on them.
742// load() therefore gives each of them a copy of the template too, through the thread's TEB, which is ordinary memory
743// of this process.
744//
745// What makes that safe:
746// - The slot is the helper's, and nothing reads the helper's variable, so swapping the pointer under a running
747// thread disturbs nothing; the thread cannot be in mapped code of a module whose load() has not returned.
748// - The swap is made with g_tls_lock held exclusively, so no thread is inside its attach or detach event meanwhile.
749// - A thread whose detach event has run is skipped (`ended`), and so is one with no TLS array or no helper block:
750// Windows is about to free, or never built, what the block would go into.
751// - The block comes out again in that thread's own detach event, before Windows frees the array, or in ~Loader.
752// What is left:
753// - A thread that ran its detach event before the helper DLL was ever loaded and has not left the process yet is
754// not in `ended`; if Windows leaves a stale array pointer in its TEB for those last instructions, the write goes
755// to freed heap memory.
756// - Windows replaces a thread's TLS array (a new one, copied from the old) when some thread loads a DLL with static
757// TLS. If that happens during the swap, the write can land in the old array; the thread then still has the
758// helper's one-byte block, and the first mapped __declspec(thread) access on it writes past that block: heap
759// corruption, with nothing to show for it. The swap therefore reads the array pointer again after writing and
760// repeats on the new array (kSwapAttempts times); if the block is not in the thread's current array at the end,
761// it is taken back and the miss is logged. A replacement after that last look is not seen.
762// - TerminateThread frees a thread's TEB with no detach event. Every read and write of another thread's TEB or
763// TLS array here is made right after the thread was seen running and inside __try, so a TEB that has just gone
764// is a skipped thread, not a fault in load() or ~Loader. If the memory was already given to something else, the
765// write is not caught.
766using QueryThreadFn = LONG(NTAPI*)(HANDLE, int, void*, ULONG, ULONG*);
767struct ThreadBasicInfo { // THREAD_BASIC_INFORMATION (winternl.h keeps it opaque), x64
768 LONG exit_status;
769 void* teb;
770 void* process_id;
771 void* thread_id;
772 ULONG_PTR affinity;
773 LONG priority;
774 LONG base_priority;
775};
776static_assert(sizeof(ThreadBasicInfo) == 48);
777
778QueryThreadFn query_thread_fn() {
779 static const auto fn = reinterpret_cast<QueryThreadFn>(
780 reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread")));
781 return fn;
782}
783
784// The TEB's ThreadLocalStoragePointer field of a thread that is still running; null otherwise.
785void*** running_thread_tls_vector(HANDLE thread) {
786 ThreadBasicInfo info{};
787 const QueryThreadFn query = query_thread_fn();
788 if (!query || query(thread, 0 /* ThreadBasicInformation */, &info, sizeof info, nullptr) < 0) return nullptr;
789 if (info.exit_status != STILL_ACTIVE || !info.teb) return nullptr;
790 return reinterpret_cast<void***>(static_cast<uint8_t*>(info.teb) + 0x58);
791}
792
793// Another thread's TLS array and one entry of it, read through its TEB. False when the memory is not there any more
794// (the thread was terminated). No C++ objects in these three: they are __try frames.
795bool read_thread_slot(void*** vector, uint32_t index, void**& slots, void*& value) noexcept {
796 __try {
797 slots = *vector;
798 value = slots ? slots[index] : nullptr;
799 return true;
800 } __except (EXCEPTION_EXECUTE_HANDLER) {
801 slots = nullptr;
802 value = nullptr;
803 return false;
804 }
805}
806
807bool write_thread_slot(void** slots, uint32_t index, void* value) noexcept {
808 __try {
809 slots[index] = value;
810 return true;
811 } __except (EXCEPTION_EXECUTE_HANDLER) {
812 return false;
813 }
814}
815
816// Puts `saved` back where `block` is, if it is still there.
817void restore_thread_slot(void*** vector, uint32_t index, void* block, void* saved) noexcept {
818 __try {
819 void** slots = *vector;
820 if (slots && slots[index] == block) slots[index] = saved;
821 } __except (EXCEPTION_EXECUTE_HANDLER) {
822 }
823}
824
825// Takes a block out of its slot and frees it. The existing-threads lock is held; b.vector is null when the thread
826// is gone.
827void remove_existing_block(const ExistingThreadBlock& b) {
828 if (b.vector && b.index < kMaxModuleTlsSlots) restore_thread_slot(b.vector, b.index, b.block, b.saved);
829 VirtualFree(b.block, 0, MEM_RELEASE);
830}
831
832constexpr int kSwapAttempts = 4;
833constexpr size_t kMaxEndedThreads = 1024;
834
835// load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done.
836void install_on_existing_threads(Module& m) {
837 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill;
838 if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kMaxMappedTlsModules) return;
839 // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which
840 // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours.
841 if (!query_thread_fn()) return;
842
843 // Outside the TLS lock: none of this may wait for a thread that is inside its attach event.
844 // The handles are closed on every way out, also when a vector below cannot grow.
845 struct Candidate {
846 DWORD id = 0;
847 HANDLE handle = nullptr;
848 };
849 struct Candidates {
850 std::vector<Candidate> list;
851 HANDLE snapshot = INVALID_HANDLE_VALUE;
852 ~Candidates() {
853 if (snapshot != INVALID_HANDLE_VALUE) CloseHandle(snapshot);
854 for (const Candidate& c : list)
855 if (c.handle) CloseHandle(c.handle);
856 }
857 } found;
858 std::vector<Candidate>& candidates = found.list;
859 // TH32CS_SNAPTHREAD lists the threads of every process; the loop keeps this one's.
860 found.snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
861 if (found.snapshot == INVALID_HANDLE_VALUE) return;
862 THREADENTRY32 entry{};
863 entry.dwSize = sizeof entry;
864 const DWORD process = GetCurrentProcessId(), self = GetCurrentThreadId();
865 for (BOOL more = Thread32First(found.snapshot, &entry); more; more = Thread32Next(found.snapshot, &entry)) {
866 if (entry.th32OwnerProcessID != process || entry.th32ThreadID == self) continue;
867 candidates.push_back({entry.th32ThreadID, nullptr}); // the slot first, so the handle always has an owner
868 candidates.back().handle = OpenThread(THREAD_QUERY_INFORMATION, FALSE, entry.th32ThreadID);
869 }
870
871 {
872 ExclusiveTlsLock tls_lock;
873 ExistingThreadsLock lock;
874 ExistingThreads& state = existing_threads();
875 for (const Candidate& c : candidates) {
876 if (!c.handle) continue;
877 if (std::find(state.ended.begin(), state.ended.end(), c.id) != state.ended.end()) continue;
878 void*** vector = running_thread_tls_vector(c.handle);
879 void** slots = nullptr;
880 void* saved = nullptr;
881 if (!vector || !read_thread_slot(vector, m.tls_index, slots, saved) || !slots || !saved) continue;
882 // A copy an earlier module left in this slot of this thread goes first; what it replaced is kept.
883 bool present = false;
884 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
885 if (it->thread != c.id || it->slot != m.tls_slot) {
886 ++it;
887 } else if (it->module == &m && it->generation == m.tls_generation) {
888 present = true;
889 break;
890 } else {
891 if (saved == it->block) saved = it->saved;
892 it->vector = vector;
893 remove_existing_block(*it);
894 it = state.blocks.erase(it);
895 }
896 }
897 if (present) continue;
898 void* block = VirtualAlloc(nullptr, static_cast<SIZE_T>(total), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
899 if (!block) continue;
900 if (m.tls_raw_size) std::memcpy(block, m.tls_template, m.tls_raw_size);
901
902 // Write, then look at the thread's array pointer again: if Windows has replaced the array meanwhile, the
903 // write went into the old one, and it is made again in the new one.
904 bool installed = false;
905 for (int attempt = 0; attempt < kSwapAttempts && !installed; ++attempt) {
906 if (!running_thread_tls_vector(c.handle) || !write_thread_slot(slots, m.tls_index, block)) break;
907 void** now = nullptr;
908 void* value = nullptr;
909 if (!read_thread_slot(vector, m.tls_index, now, value) || !now) break;
910 installed = now == slots && value == block;
911 slots = now;
912 }
913 if (!installed) {
914 restore_thread_slot(vector, m.tls_index, block, saved);
915 VirtualFree(block, 0, MEM_RELEASE);
916 static std::atomic<bool> logged{false};
917 if (!logged.exchange(true))
918 std::fprintf(stderr, "[rt] loader: %s: a running thread did not take its TLS block (it ended, or "
919 "its TLS array kept changing); mapped thread-local data is not valid on it\n",
920 m.name.c_str());
921 continue;
922 }
923 state.blocks.push_back({c.id, m.tls_slot, &m, m.tls_generation, m.tls_index, vector, saved, block});
924 }
925 }
926}
927
928// ~Loader, with g_tls_lock held exclusively: the blocks load() put into other threads come out. A thread that has
929// ended without a detach event (TerminateThread) has no TEB to restore.
930void remove_from_existing_threads(Module& m) {
931 ExistingThreadsLock lock;
932 ExistingThreads& state = existing_threads();
933 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
934 if (it->module != &m || it->generation != m.tls_generation) {
935 ++it;
936 continue;
937 }
938 ExistingThreadBlock b = *it;
939 it = state.blocks.erase(it);
940 const HANDLE h = OpenThread(THREAD_QUERY_INFORMATION, FALSE, b.thread);
941 if (!h || running_thread_tls_vector(h) != b.vector) b.vector = nullptr;
942 if (h) CloseHandle(h);
943 remove_existing_block(b);
944 }
945}
946
947// DLL_THREAD_ATTACH: a record under this thread's id is from a thread that ended without a detach event.
948void forget_ended_thread_id() {
949 const DWORD self = GetCurrentThreadId();
950 ExistingThreadsLock lock;
951 ExistingThreads& state = existing_threads();
952 state.ended.erase(std::remove(state.ended.begin(), state.ended.end(), self), state.ended.end());
953 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
954 if (it->thread != self) {
955 ++it;
956 continue;
957 }
958 VirtualFree(it->block, 0, MEM_RELEASE);
959 it = state.blocks.erase(it);
960 }
961}
962
963// DLL_THREAD_DETACH, before this thread's own records are released: the blocks load() gave it come out, newest first,
964// after the module's TLS callbacks have seen the event (Windows sends DLL_THREAD_DETACH to a DLL for a thread that
965// was running before it was loaded, too).
966void release_existing_blocks_of_this_thread() {
967 const DWORD self = GetCurrentThreadId();
968 std::vector<ExistingThreadBlock> mine;
969 {
970 ExistingThreadsLock lock;
971 for (const auto& b : existing_threads().blocks)
972 if (b.thread == self) mine.push_back(b);
973 }
974 for (auto it = mine.rbegin(); it != mine.rend(); ++it) {
975 Module* m = it->module;
976 if (g_tls_slot_owners[it->slot].load() != m || g_tls_slot_generations[it->slot].load() != it->generation ||
977 !m->initialised)
978 continue;
979 try {
980 run_callbacks(*m, DLL_THREAD_DETACH);
981 } catch (const std::exception& e) {
982 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what());
983 }
984 }
985 ExistingThreadsLock lock;
986 ExistingThreads& state = existing_threads();
987 for (auto it = state.blocks.end(); it != state.blocks.begin();) {
988 --it;
989 if (it->thread != self) continue;
990 remove_existing_block(*it);
991 it = state.blocks.erase(it);
992 }
993 // Bounded: an id matters only until its thread has left the process, moments after this event, so the oldest
994 // can go. (An id also leaves the list when a new thread gets it.)
995 if (state.ended.size() >= kMaxEndedThreads) state.ended.erase(state.ended.begin(), state.ended.begin() + kMaxEndedThreads / 2);
996 state.ended.push_back(self);
997}
998
667// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under 999// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under
668// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an 1000// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an
669// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events 1001// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events
@@ -677,6 +1009,11 @@ void __cdecl on_host_thread_event(DWORD reason) {
677 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events 1009 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events
678 // away from the other slots. Nothing may leave DllMain. 1010 // away from the other slots. Nothing may leave DllMain.
679 if (reason == DLL_THREAD_ATTACH) { 1011 if (reason == DLL_THREAD_ATTACH) {
1012 try {
1013 forget_ended_thread_id();
1014 } catch (const std::exception& e) {
1015 std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what());
1016 }
680 std::array<Module*, kTlsSlotCount> installed{}; 1017 std::array<Module*, kTlsSlotCount> installed{};
681 for (size_t slot = 0; slot < kTlsSlotCount; ++slot) { 1018 for (size_t slot = 0; slot < kTlsSlotCount; ++slot) {
682 Module* m = g_tls_slot_owners[slot].load(); 1019 Module* m = g_tls_slot_owners[slot].load();
@@ -701,6 +1038,13 @@ void __cdecl on_host_thread_event(DWORD reason) {
701 } 1038 }
702 } 1039 }
703 } else if (reason == DLL_THREAD_DETACH) { 1040 } else if (reason == DLL_THREAD_DETACH) {
1041 // The blocks load() gave this thread while it was already running come out first (they can sit on top of
1042 // an older module's block in the same slot).
1043 try {
1044 release_existing_blocks_of_this_thread();
1045 } catch (const std::exception& e) {
1046 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what());
1047 }
704 for (size_t step = 0; step < kTlsSlotCount; ++step) { 1048 for (size_t step = 0; step < kTlsSlotCount; ++step) {
705 const size_t i = step < kMaxMappedTlsModules ? kMaxMappedTlsModules - 1 - step : kMainImageSlot; 1049 const size_t i = step < kMaxMappedTlsModules ? kMaxMappedTlsModules - 1 - step : kMainImageSlot;
706 Module* m = g_tls_slot_owners[i].load(); 1050 Module* m = g_tls_slot_owners[i].load();
@@ -724,9 +1068,15 @@ void __cdecl on_host_thread_event(DWORD reason) {
724 1068
725// The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used. 1069// The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used.
726bool prefer_host_copy(const std::string& dll) { 1070bool prefer_host_copy(const std::string& dll) {
1071 // The second row is the Debug builds of the same DLLs. A Debug build of a stand-in image (tiny_game) links them,
1072 // and without them here its C++ exceptions were not redirected below: a throw caught inside the image ended the
1073 // run with 0xE06D7363 (run_tiny_game_eh in a Debug build).
727 static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll", 1074 static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll",
728 "msvcp140_2.dll", "msvcp140_atomic_wait.dll", "msvcp140_codecvt_ids.dll", 1075 "msvcp140_2.dll", "msvcp140_atomic_wait.dll", "msvcp140_codecvt_ids.dll",
729 "concrt140.dll", "vccorlib140.dll", "vcomp140.dll"}; 1076 "concrt140.dll", "vccorlib140.dll", "vcomp140.dll",
1077 "vcruntime140d.dll", "vcruntime140_1d.dll", "msvcp140d.dll", "msvcp140_1d.dll",
1078 "msvcp140_2d.dll", "msvcp140d_atomic_wait.dll", "msvcp140d_codecvt_ids.dll",
1079 "concrt140d.dll", "vccorlib140d.dll", "vcomp140d.dll"};
730 for (auto* n : names) 1080 for (auto* n : names)
731 if (dll == n) return true; 1081 if (dll == n) return true;
732 return false; 1082 return false;
@@ -847,6 +1197,15 @@ const shims::BundledModuleOps kBundledOps{
847 &bundled_get_proc, 1197 &bundled_get_proc,
848 &bundled_owns_handle, 1198 &bundled_owns_handle,
849}; 1199};
1200
1201// Marks what a run-time load maps as a dynamic load for as long as it is in scope (the caller holds the mutex).
1202struct RuntimeLoadScope {
1203 explicit RuntimeLoadScope(int& depth) : depth_(depth) { ++depth_; }
1204 ~RuntimeLoadScope() { --depth_; }
1205 RuntimeLoadScope(const RuntimeLoadScope&) = delete;
1206 RuntimeLoadScope& operator=(const RuntimeLoadScope&) = delete;
1207 int& depth_;
1208};
850} // namespace 1209} // namespace
851 1210
852Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { 1211Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) {
@@ -887,6 +1246,7 @@ Loader::~Loader() {
887 Module* owner = m; 1246 Module* owner = m;
888 if (g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr)) 1247 if (g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr))
889 g_tls_slot_generations[m->tls_slot].store(0); 1248 g_tls_slot_generations[m->tls_slot].store(0);
1249 remove_from_existing_threads(*m);
890 } 1250 }
891 uninstall_tls_for_thread(*m); 1251 uninstall_tls_for_thread(*m);
892 } 1252 }
@@ -900,11 +1260,14 @@ Loader::~Loader() {
900 1260
901Module& Loader::load(const std::filesystem::path& image) { 1261Module& Loader::load(const std::filesystem::path& image) {
902 std::lock_guard lock(mutex_); 1262 std::lock_guard lock(mutex_);
903 std::string key = lower(image.filename().string()); 1263 const auto key = module_key(image);
904 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; 1264 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second;
1265 const auto narrow_key = narrow_module_key(image);
1266 if (Module* existing = find_narrow_module(narrow_key)) return *existing;
905 Module* mapped = nullptr; 1267 Module* mapped = nullptr;
906 try { 1268 try {
907 mapped = &map_image(image); 1269 mapped = &map_image(image, narrow_key);
1270 mapped->dynamic_load = runtime_loads_ > 0; // before bind_imports: its dependencies are marked the same way
908 bind_imports(*mapped); // loads every bundled module m imports first, so they land in init_order_ before m 1271 bind_imports(*mapped); // loads every bundled module m imports first, so they land in init_order_ before m
909 protect_sections(*mapped); 1272 protect_sections(*mapped);
910 register_unwind(*mapped); 1273 register_unwind(*mapped);
@@ -924,10 +1287,19 @@ Module& Loader::load(const std::filesystem::path& image) {
924 return m; 1287 return m;
925} 1288}
926 1289
1290Module* Loader::find_narrow_module(const std::string& dll_lower) const {
1291 if (dll_lower.empty()) return nullptr;
1292 // library_loader and PE import names keep their existing narrow-byte contract. Do not reinterpret them
1293 // as UTF-8 or widen already-folded bytes (which could be part of a multibyte code-page character).
1294 for (const auto& entry : by_name_)
1295 if (entry.second->narrow_key == dll_lower) return entry.second;
1296 return nullptr;
1297}
1298
927void* Loader::find_loaded_module(const std::string& dll_lower) const { 1299void* Loader::find_loaded_module(const std::string& dll_lower) const {
928 std::lock_guard lock(mutex_); 1300 std::lock_guard lock(mutex_);
929 auto it = by_name_.find(dll_lower); 1301 Module* m = find_narrow_module(dll_lower);
930 return it == by_name_.end() ? nullptr : static_cast<void*>(it->second->base); 1302 return m ? static_cast<void*>(m->base) : nullptr;
931} 1303}
932 1304
933void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled) { 1305void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled) {
@@ -935,10 +1307,11 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags,
935 if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr; 1307 if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr;
936 1308
937 std::lock_guard lock(mutex_); 1309 std::lock_guard lock(mutex_);
938 const auto existing = by_name_.find(dll_lower); 1310 const RuntimeLoadScope dynamic(runtime_loads_);
1311 Module* existing = find_narrow_module(dll_lower);
939 const std::filesystem::path candidate = game_dir_ / dll_lower; 1312 const std::filesystem::path candidate = game_dir_ / dll_lower;
940 std::error_code ec; 1313 std::error_code ec;
941 const bool is_bundled = existing != by_name_.end() || std::filesystem::is_regular_file(candidate, ec); 1314 const bool is_bundled = existing || std::filesystem::is_regular_file(candidate, ec);
942 if (!is_bundled) return nullptr; 1315 if (!is_bundled) return nullptr;
943 1316
944 handled = true; 1317 handled = true;
@@ -952,10 +1325,10 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags,
952 return nullptr; 1325 return nullptr;
953 } 1326 }
954 1327
955 if (existing != by_name_.end()) { 1328 if (existing) {
956 try { 1329 try {
957 initialise(); 1330 initialise();
958 return static_cast<void*>(existing->second->base); 1331 return static_cast<void*>(existing->base);
959 } catch (const std::exception& e) { 1332 } catch (const std::exception& e) {
960 std::fprintf(stderr, "[rt] loader: run-time initialise of %s failed: %s\n", dll_lower.c_str(), e.what()); 1333 std::fprintf(stderr, "[rt] loader: run-time initialise of %s failed: %s\n", dll_lower.c_str(), e.what());
961 SetLastError(ERROR_DLL_INIT_FAILED); 1334 SetLastError(ERROR_DLL_INIT_FAILED);
@@ -963,15 +1336,17 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags,
963 } 1336 }
964 } 1337 }
965 1338
1339 Module* mapped = nullptr;
966 try { 1340 try {
967 Module& m = load(candidate); 1341 Module& m = load(candidate);
1342 mapped = &m;
968 initialise(); 1343 initialise();
969 std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str()); 1344 std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str());
970 return static_cast<void*>(m.base); 1345 return static_cast<void*>(m.base);
971 } catch (const std::exception& e) { 1346 } catch (const std::exception& e) {
972 // load() drops a module that failed to map or bind (dependencies included); this also drops one whose 1347 // load() drops a module that failed to map or bind (dependencies included); this also drops one whose
973 // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via order_. 1348 // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via order_.
974 by_name_.erase(dll_lower); 1349 by_name_.erase(module_key(mapped ? mapped->path : candidate));
975 std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what()); 1350 std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what());
976 SetLastError(ERROR_DLL_INIT_FAILED); 1351 SetLastError(ERROR_DLL_INIT_FAILED);
977 return nullptr; 1352 return nullptr;
@@ -994,6 +1369,7 @@ void* Loader::resolve_module_export(void* module_handle, const std::string& sym,
994 if (auto it = target->exports.find(sym); it != target->exports.end()) return it->second; 1369 if (auto it = target->exports.find(sym); it != target->exports.end()) return it->second;
995 if (auto it = target->forwarders.find(sym); it != target->forwarders.end()) { 1370 if (auto it = target->forwarders.find(sym); it != target->forwarders.end()) {
996 try { 1371 try {
1372 const RuntimeLoadScope dynamic(runtime_loads_);
997 Binding binding = Binding::Unimplemented; 1373 Binding binding = Binding::Unimplemented;
998 void* fn = resolve_forwarder(it->second, binding, 0); 1374 void* fn = resolve_forwarder(it->second, binding, 0);
999 if (binding == Binding::Module) initialise(); 1375 if (binding == Binding::Module) initialise();
@@ -1080,7 +1456,11 @@ void Loader::initialise(Module& m) {
1080 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 1456 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
1081 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { 1457 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) {
1082 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); 1458 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva);
1083 const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, nullptr); 1459 // lpvReserved "is NULL for dynamic loads and non-NULL for static loads" (DllMain docs). What Windows points
1460 // it at is its own; a static load gets a CONTEXT captured here, so a DLL that reads through it reads memory.
1461 CONTEXT context{};
1462 if (!m.dynamic_load) RtlCaptureContext(&context);
1463 const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, m.dynamic_load ? nullptr : &context);
1084 if (startup_trace::enabled()) 1464 if (startup_trace::enabled())
1085 startup_trace::event("dllmain", "\"module\":" + startup_trace::quote(m.name) + 1465 startup_trace::event("dllmain", "\"module\":" + startup_trace::quote(m.name) +
1086 ",\"result\":" + std::to_string(ok)); 1466 ",\"result\":" + std::to_string(ok));
@@ -1099,12 +1479,12 @@ void Loader::set_initialised(Module& m, bool value) {
1099 m.initialised = value; 1479 m.initialised = value;
1100} 1480}
1101 1481
1102Module& Loader::map_image(const std::filesystem::path& path) { 1482Module& Loader::map_image(const std::filesystem::path& path, const std::string& narrow_key) {
1103 auto file = read_file(path); 1483 auto file = read_file(path);
1104 const std::string name = path.filename().string(); 1484 const std::string name = path_utf8(path.filename());
1105 auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(file.data()); 1485 auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(file.data());
1106 if (file.size() < sizeof(IMAGE_DOS_HEADER) || dos->e_magic != IMAGE_DOS_SIGNATURE) 1486 if (file.size() < sizeof(IMAGE_DOS_HEADER) || dos->e_magic != IMAGE_DOS_SIGNATURE)
1107 throw std::runtime_error(path.string() + ": not an MZ image"); 1487 throw std::runtime_error(path_utf8(path) + ": not an MZ image");
1108 if (dos->e_lfanew < 0 || static_cast<uint64_t>(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size()) 1488 if (dos->e_lfanew < 0 || static_cast<uint64_t>(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size())
1109 throw std::runtime_error(name + ": the NT headers are outside the file"); 1489 throw std::runtime_error(name + ": the NT headers are outside the file");
1110 auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew); 1490 auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew);
@@ -1128,11 +1508,12 @@ Module& Loader::map_image(const std::filesystem::path& path) {
1128 1508
1129 auto* m = new Module; 1509 auto* m = new Module;
1130 m->name = name; 1510 m->name = name;
1511 m->narrow_key = narrow_key;
1131 m->path = path; 1512 m->path = path;
1132 m->preferred_base = oh.ImageBase; 1513 m->preferred_base = oh.ImageBase;
1133 m->size = oh.SizeOfImage; 1514 m->size = oh.SizeOfImage;
1134 m->entry_rva = oh.AddressOfEntryPoint; 1515 m->entry_rva = oh.AddressOfEntryPoint;
1135 by_name_[lower(m->name)] = m; 1516 by_name_[module_key(path)] = m;
1136 order_.push_back(m); 1517 order_.push_back(m);
1137 1518
1138 // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual. 1519 // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual.
@@ -1157,6 +1538,8 @@ Module& Loader::map_image(const std::filesystem::path& path) {
1157 std::memcpy(m->base, file.data(), oh.SizeOfHeaders); 1538 std::memcpy(m->base, file.data(), oh.SizeOfHeaders);
1158 auto* sec = IMAGE_FIRST_SECTION(nt); 1539 auto* sec = IMAGE_FIRST_SECTION(nt);
1159 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { 1540 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) {
1541 if (sec->VirtualAddress < oh.SizeOfHeaders)
1542 throw std::runtime_error(m->name + ": section " + std::to_string(i) + " overlaps the headers");
1160 uint32_t n = std::min(sec->SizeOfRawData, sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData); 1543 uint32_t n = std::min(sec->SizeOfRawData, sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData);
1161 if (!n) continue; 1544 if (!n) continue;
1162 if (sec->PointerToRawData > file.size() || n > file.size() - sec->PointerToRawData) 1545 if (sec->PointerToRawData > file.size() || n > file.size() - sec->PointerToRawData)
@@ -1182,6 +1565,9 @@ Module& Loader::map_image(const std::filesystem::path& path) {
1182 size_t count = (block->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2; 1565 size_t count = (block->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2;
1183 for (size_t i = 0; i < count; ++i) { 1566 for (size_t i = 0; i < count; ++i) {
1184 uint16_t type = entries[i] >> 12, off = entries[i] & 0xFFF; 1567 uint16_t type = entries[i] >> 12, off = entries[i] & 0xFFF;
1568 if (type != IMAGE_REL_BASED_ABSOLUTE &&
1569 static_cast<uint64_t>(block->VirtualAddress) + off < oh.SizeOfHeaders)
1570 throw std::runtime_error(m->name + ": a relocation lands in the headers");
1185 if (type == IMAGE_REL_BASED_DIR64) { 1571 if (type == IMAGE_REL_BASED_DIR64) {
1186 require_range(m->name, static_cast<uint64_t>(block->VirtualAddress) + off, sizeof(uint64_t), m->size, 1572 require_range(m->name, static_cast<uint64_t>(block->VirtualAddress) + off, sizeof(uint64_t), m->size,
1187 "a relocation"); 1573 "a relocation");
@@ -1321,6 +1707,9 @@ void Loader::initialize_tls(Module& m) {
1321 m.tls_block = g_thread_tls_slots[slot].block; 1707 m.tls_block = g_thread_tls_slots[slot].block;
1322 m.tls_saved_block = g_thread_tls_slots[slot].saved; 1708 m.tls_saved_block = g_thread_tls_slots[slot].saved;
1323 } 1709 }
1710 // Threads started from here on get their copy from the helper DLL's DLL_THREAD_ATTACH; the ones already running
1711 // get it now.
1712 install_on_existing_threads(m);
1324} 1713}
1325 1714
1326void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); } 1715void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); }