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:
authorRafael <rafaelalvesp2005@gmail.com>2026-11-23 15:35:19 -0300
committerRafael <rafaelalvesp2005@gmail.com>2026-11-23 15:35:34 -0300
commit721341dc53c54a68ed08587e1bb5ab9583e48458 (patch)
tree995fb34aff79b0c51ba7b94f45bc354a3d2a7f05 /runtime/src/pe_loader.cpp
parentc8f263917100f66e600f68a494e5cfe90c5cba17 (diff)
parent6dda0630bd6fc0514baadb94fb98e36bd7d64c0b (diff)
Merge main into fix/walk-bvh_index
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.cpp499
1 files changed, 480 insertions, 19 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index f3323e4c0..e5becb472 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
@@ -332,11 +379,51 @@ void release_thread_slot(size_t slot) {
332 entry = ThreadTlsSlot{}; 379 entry = ThreadTlsSlot{};
333} 380}
334 381
382// A block load() put into a thread that was already running (install_on_existing_threads). Such a thread has no
383// g_thread_tls_slots record of it: the record is here, keyed by thread id, and the thread's own DLL_THREAD_DETACH or
384// the module's ~Loader takes the block out again.
385struct ExistingThreadBlock {
386 DWORD thread = 0;
387 size_t slot = 0;
388 Module* module = nullptr;
389 uint64_t generation = 0; // the module's tls_generation: with the pointer, what identifies the module
390 uint32_t index = kNoTlsIndex;
391 void*** vector = nullptr; // that thread's TEB->ThreadLocalStoragePointer field; the array itself can be replaced
392 void* saved = nullptr; // what the block replaced
393 void* block = nullptr;
394};
395
396// Immortal, like the thread events that use them. `ended` holds the ids of threads whose DLL_THREAD_DETACH has run:
397// Windows frees such a thread's TLS array next, so nothing may be put into it any more.
398struct ExistingThreads {
399 SRWLOCK lock = SRWLOCK_INIT; // a leaf: nothing is called while it is held but VirtualFree and thread queries
400 std::vector<ExistingThreadBlock> blocks;
401 std::vector<DWORD> ended;
402};
403ExistingThreads& existing_threads() {
404 static auto* state = new ExistingThreads;
405 return *state;
406}
407struct ExistingThreadsLock {
408 ExistingThreadsLock() { AcquireSRWLockExclusive(&existing_threads().lock); }
409 ~ExistingThreadsLock() { ReleaseSRWLockExclusive(&existing_threads().lock); }
410 ExistingThreadsLock(const ExistingThreadsLock&) = delete;
411 ExistingThreadsLock& operator=(const ExistingThreadsLock&) = delete;
412};
413
414bool has_existing_thread_block(DWORD thread, const Module& m) {
415 ExistingThreadsLock lock;
416 for (const auto& b : existing_threads().blocks)
417 if (b.thread == thread && b.module == &m && b.generation == m.tls_generation) return true;
418 return false;
419}
420
335void install_thread_block(Module& m) { 421void install_thread_block(Module& m) {
336 if (m.tls_slot >= kMaxMappedTlsModules) return; 422 if (m.tls_slot >= kMaxMappedTlsModules) return;
337 const size_t slot = m.tls_slot; 423 const size_t slot = m.tls_slot;
338 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 424 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
339 if (entry.module == &m && entry.generation == m.tls_generation) return; 425 if (entry.module == &m && entry.generation == m.tls_generation) return;
426 if (has_existing_thread_block(GetCurrentThreadId(), m)) return; // load() already gave this thread its copy
340 if (entry.module) { 427 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. 428 // 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() && 429 if (entry.module == g_tls_slot_owners[slot].load() &&
@@ -407,6 +494,269 @@ void run_callbacks(Module& m, uint32_t reason, bool trace = false) {
407 } 494 }
408} 495}
409 496
497// ---- Threads that existed before load() ---------------------------------------------------------------------------
498//
499// When Windows loads a DLL with static TLS itself, every running thread gets a block for it (and no DLL_THREAD_ATTACH).
500// The helper DLL gets exactly that, so in a thread that was already running the reserved slot holds the helper's
501// one-byte block, and mapped __declspec(thread) code there would read and write past it. Such threads are not rare:
502// the workers of the process thread pool predate most loads, and the task queue runs a title's callbacks on them.
503// load() therefore gives each of them a copy of the template too, through the thread's TEB, which is ordinary memory
504// of this process.
505//
506// What makes that safe:
507// - The slot is the helper's, and nothing reads the helper's variable, so swapping the pointer under a running
508// thread disturbs nothing; the thread cannot be in mapped code of a module whose load() has not returned.
509// - The swap is made with g_tls_lock held exclusively, so no thread is inside its attach or detach event meanwhile.
510// - A thread whose detach event has run is skipped (`ended`), and so is one with no TLS array or no helper block:
511// Windows is about to free, or never built, what the block would go into.
512// - The block comes out again in that thread's own detach event, before Windows frees the array, or in ~Loader.
513// What is left:
514// - A thread that ran its detach event before the helper DLL was ever loaded and has not left the process yet is
515// not in `ended`; if Windows leaves a stale array pointer in its TEB for those last instructions, the write goes
516// to freed heap memory.
517// - Windows replaces a thread's TLS array (a new one, copied from the old) when some thread loads a DLL with static
518// TLS. If that happens during the swap, the write can land in the old array; the thread then still has the
519// helper's one-byte block, and the first mapped __declspec(thread) access on it writes past that block: heap
520// corruption, with nothing to show for it. The swap therefore reads the array pointer again after writing and
521// repeats on the new array (kSwapAttempts times); if the block is not in the thread's current array at the end,
522// it is taken back and the miss is logged. A replacement after that last look is not seen.
523// - TerminateThread frees a thread's TEB with no detach event. Every read and write of another thread's TEB or
524// TLS array here is made right after the thread was seen running and inside __try, so a TEB that has just gone
525// is a skipped thread, not a fault in load() or ~Loader. If the memory was already given to something else, the
526// write is not caught.
527using QueryThreadFn = LONG(NTAPI*)(HANDLE, int, void*, ULONG, ULONG*);
528struct ThreadBasicInfo { // THREAD_BASIC_INFORMATION (winternl.h keeps it opaque), x64
529 LONG exit_status;
530 void* teb;
531 void* process_id;
532 void* thread_id;
533 ULONG_PTR affinity;
534 LONG priority;
535 LONG base_priority;
536};
537static_assert(sizeof(ThreadBasicInfo) == 48);
538
539QueryThreadFn query_thread_fn() {
540 static const auto fn = reinterpret_cast<QueryThreadFn>(
541 reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread")));
542 return fn;
543}
544
545// The TEB's ThreadLocalStoragePointer field of a thread that is still running; null otherwise.
546void*** running_thread_tls_vector(HANDLE thread) {
547 ThreadBasicInfo info{};
548 const QueryThreadFn query = query_thread_fn();
549 if (!query || query(thread, 0 /* ThreadBasicInformation */, &info, sizeof info, nullptr) < 0) return nullptr;
550 if (info.exit_status != STILL_ACTIVE || !info.teb) return nullptr;
551 return reinterpret_cast<void***>(static_cast<uint8_t*>(info.teb) + 0x58);
552}
553
554// Another thread's TLS array and one entry of it, read through its TEB. False when the memory is not there any more
555// (the thread was terminated). No C++ objects in these three: they are __try frames.
556bool read_thread_slot(void*** vector, uint32_t index, void**& slots, void*& value) noexcept {
557 __try {
558 slots = *vector;
559 value = slots ? slots[index] : nullptr;
560 return true;
561 } __except (EXCEPTION_EXECUTE_HANDLER) {
562 slots = nullptr;
563 value = nullptr;
564 return false;
565 }
566}
567
568bool write_thread_slot(void** slots, uint32_t index, void* value) noexcept {
569 __try {
570 slots[index] = value;
571 return true;
572 } __except (EXCEPTION_EXECUTE_HANDLER) {
573 return false;
574 }
575}
576
577// Puts `saved` back where `block` is, if it is still there.
578void restore_thread_slot(void*** vector, uint32_t index, void* block, void* saved) noexcept {
579 __try {
580 void** slots = *vector;
581 if (slots && slots[index] == block) slots[index] = saved;
582 } __except (EXCEPTION_EXECUTE_HANDLER) {
583 }
584}
585
586// Takes a block out of its slot and frees it. The existing-threads lock is held; b.vector is null when the thread
587// is gone.
588void remove_existing_block(const ExistingThreadBlock& b) {
589 if (b.vector && b.index < kMaxModuleTlsSlots) restore_thread_slot(b.vector, b.index, b.block, b.saved);
590 VirtualFree(b.block, 0, MEM_RELEASE);
591}
592
593constexpr int kSwapAttempts = 4;
594constexpr size_t kMaxEndedThreads = 1024;
595
596// load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done.
597void install_on_existing_threads(Module& m) {
598 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill;
599 if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kMaxMappedTlsModules) return;
600 // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which
601 // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours.
602 if (!query_thread_fn()) return;
603
604 // Outside the TLS lock: none of this may wait for a thread that is inside its attach event.
605 // The handles are closed on every way out, also when a vector below cannot grow.
606 struct Candidate {
607 DWORD id = 0;
608 HANDLE handle = nullptr;
609 };
610 struct Candidates {
611 std::vector<Candidate> list;
612 HANDLE snapshot = INVALID_HANDLE_VALUE;
613 ~Candidates() {
614 if (snapshot != INVALID_HANDLE_VALUE) CloseHandle(snapshot);
615 for (const Candidate& c : list)
616 if (c.handle) CloseHandle(c.handle);
617 }
618 } found;
619 std::vector<Candidate>& candidates = found.list;
620 // TH32CS_SNAPTHREAD lists the threads of every process; the loop keeps this one's.
621 found.snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
622 if (found.snapshot == INVALID_HANDLE_VALUE) return;
623 THREADENTRY32 entry{};
624 entry.dwSize = sizeof entry;
625 const DWORD process = GetCurrentProcessId(), self = GetCurrentThreadId();
626 for (BOOL more = Thread32First(found.snapshot, &entry); more; more = Thread32Next(found.snapshot, &entry)) {
627 if (entry.th32OwnerProcessID != process || entry.th32ThreadID == self) continue;
628 candidates.push_back({entry.th32ThreadID, nullptr}); // the slot first, so the handle always has an owner
629 candidates.back().handle = OpenThread(THREAD_QUERY_INFORMATION, FALSE, entry.th32ThreadID);
630 }
631
632 {
633 ExclusiveTlsLock tls_lock;
634 ExistingThreadsLock lock;
635 ExistingThreads& state = existing_threads();
636 for (const Candidate& c : candidates) {
637 if (!c.handle) continue;
638 if (std::find(state.ended.begin(), state.ended.end(), c.id) != state.ended.end()) continue;
639 void*** vector = running_thread_tls_vector(c.handle);
640 void** slots = nullptr;
641 void* saved = nullptr;
642 if (!vector || !read_thread_slot(vector, m.tls_index, slots, saved) || !slots || !saved) continue;
643 // A copy an earlier module left in this slot of this thread goes first; what it replaced is kept.
644 bool present = false;
645 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
646 if (it->thread != c.id || it->slot != m.tls_slot) {
647 ++it;
648 } else if (it->module == &m && it->generation == m.tls_generation) {
649 present = true;
650 break;
651 } else {
652 if (saved == it->block) saved = it->saved;
653 it->vector = vector;
654 remove_existing_block(*it);
655 it = state.blocks.erase(it);
656 }
657 }
658 if (present) continue;
659 void* block = VirtualAlloc(nullptr, static_cast<SIZE_T>(total), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
660 if (!block) continue;
661 if (m.tls_raw_size) std::memcpy(block, m.tls_template, m.tls_raw_size);
662
663 // Write, then look at the thread's array pointer again: if Windows has replaced the array meanwhile, the
664 // write went into the old one, and it is made again in the new one.
665 bool installed = false;
666 for (int attempt = 0; attempt < kSwapAttempts && !installed; ++attempt) {
667 if (!running_thread_tls_vector(c.handle) || !write_thread_slot(slots, m.tls_index, block)) break;
668 void** now = nullptr;
669 void* value = nullptr;
670 if (!read_thread_slot(vector, m.tls_index, now, value) || !now) break;
671 installed = now == slots && value == block;
672 slots = now;
673 }
674 if (!installed) {
675 restore_thread_slot(vector, m.tls_index, block, saved);
676 VirtualFree(block, 0, MEM_RELEASE);
677 static std::atomic<bool> logged{false};
678 if (!logged.exchange(true))
679 std::fprintf(stderr, "[rt] loader: %s: a running thread did not take its TLS block (it ended, or "
680 "its TLS array kept changing); mapped thread-local data is not valid on it\n",
681 m.name.c_str());
682 continue;
683 }
684 state.blocks.push_back({c.id, m.tls_slot, &m, m.tls_generation, m.tls_index, vector, saved, block});
685 }
686 }
687}
688
689// ~Loader, with g_tls_lock held exclusively: the blocks load() put into other threads come out. A thread that has
690// ended without a detach event (TerminateThread) has no TEB to restore.
691void remove_from_existing_threads(Module& m) {
692 ExistingThreadsLock lock;
693 ExistingThreads& state = existing_threads();
694 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
695 if (it->module != &m || it->generation != m.tls_generation) {
696 ++it;
697 continue;
698 }
699 ExistingThreadBlock b = *it;
700 it = state.blocks.erase(it);
701 const HANDLE h = OpenThread(THREAD_QUERY_INFORMATION, FALSE, b.thread);
702 if (!h || running_thread_tls_vector(h) != b.vector) b.vector = nullptr;
703 if (h) CloseHandle(h);
704 remove_existing_block(b);
705 }
706}
707
708// DLL_THREAD_ATTACH: a record under this thread's id is from a thread that ended without a detach event.
709void forget_ended_thread_id() {
710 const DWORD self = GetCurrentThreadId();
711 ExistingThreadsLock lock;
712 ExistingThreads& state = existing_threads();
713 state.ended.erase(std::remove(state.ended.begin(), state.ended.end(), self), state.ended.end());
714 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
715 if (it->thread != self) {
716 ++it;
717 continue;
718 }
719 VirtualFree(it->block, 0, MEM_RELEASE);
720 it = state.blocks.erase(it);
721 }
722}
723
724// DLL_THREAD_DETACH, before this thread's own records are released: the blocks load() gave it come out, newest first,
725// after the module's TLS callbacks have seen the event (Windows sends DLL_THREAD_DETACH to a DLL for a thread that
726// was running before it was loaded, too).
727void release_existing_blocks_of_this_thread() {
728 const DWORD self = GetCurrentThreadId();
729 std::vector<ExistingThreadBlock> mine;
730 {
731 ExistingThreadsLock lock;
732 for (const auto& b : existing_threads().blocks)
733 if (b.thread == self) mine.push_back(b);
734 }
735 for (auto it = mine.rbegin(); it != mine.rend(); ++it) {
736 Module* m = it->module;
737 if (g_tls_slot_owners[it->slot].load() != m || g_tls_slot_generations[it->slot].load() != it->generation ||
738 !m->initialised)
739 continue;
740 try {
741 run_callbacks(*m, DLL_THREAD_DETACH);
742 } catch (const std::exception& e) {
743 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what());
744 }
745 }
746 ExistingThreadsLock lock;
747 ExistingThreads& state = existing_threads();
748 for (auto it = state.blocks.end(); it != state.blocks.begin();) {
749 --it;
750 if (it->thread != self) continue;
751 remove_existing_block(*it);
752 it = state.blocks.erase(it);
753 }
754 // Bounded: an id matters only until its thread has left the process, moments after this event, so the oldest
755 // can go. (An id also leaves the list when a new thread gets it.)
756 if (state.ended.size() >= kMaxEndedThreads) state.ended.erase(state.ended.begin(), state.ended.begin() + kMaxEndedThreads / 2);
757 state.ended.push_back(self);
758}
759
410// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under 760// 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 761// 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 762// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events
@@ -416,6 +766,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 766 // 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. 767 // away from the other slots. Nothing may leave DllMain.
418 if (reason == DLL_THREAD_ATTACH) { 768 if (reason == DLL_THREAD_ATTACH) {
769 try {
770 forget_ended_thread_id();
771 } catch (const std::exception& e) {
772 std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what());
773 }
419 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { 774 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) {
420 Module* m = g_tls_slot_owners[slot].load(); 775 Module* m = g_tls_slot_owners[slot].load();
421 if (!m) continue; 776 if (!m) continue;
@@ -429,6 +784,13 @@ void __cdecl on_host_thread_event(DWORD reason) {
429 } 784 }
430 } 785 }
431 } else if (reason == DLL_THREAD_DETACH) { 786 } else if (reason == DLL_THREAD_DETACH) {
787 // The blocks load() gave this thread while it was already running come out first (they can sit on top of
788 // an older module's block in the same slot).
789 try {
790 release_existing_blocks_of_this_thread();
791 } catch (const std::exception& e) {
792 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what());
793 }
432 for (size_t i = kMaxMappedTlsModules; i-- > 0;) { 794 for (size_t i = kMaxMappedTlsModules; i-- > 0;) {
433 Module* m = g_tls_slot_owners[i].load(); 795 Module* m = g_tls_slot_owners[i].load();
434 if (m && g_thread_tls_slots[i].module == m && 796 if (m && g_thread_tls_slots[i].module == m &&
@@ -451,9 +813,15 @@ void __cdecl on_host_thread_event(DWORD reason) {
451 813
452// The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used. 814// 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) { 815bool prefer_host_copy(const std::string& dll) {
816 // The second row is the Debug builds of the same DLLs. A Debug build of a stand-in image (tiny_game) links them,
817 // and without them here its C++ exceptions were not redirected below: a throw caught inside the image ended the
818 // 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", 819 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", 820 "msvcp140_2.dll", "msvcp140_atomic_wait.dll", "msvcp140_codecvt_ids.dll",
456 "concrt140.dll", "vccorlib140.dll", "vcomp140.dll"}; 821 "concrt140.dll", "vccorlib140.dll", "vcomp140.dll",
822 "vcruntime140d.dll", "vcruntime140_1d.dll", "msvcp140d.dll", "msvcp140_1d.dll",
823 "msvcp140_2d.dll", "msvcp140d_atomic_wait.dll", "msvcp140d_codecvt_ids.dll",
824 "concrt140d.dll", "vccorlib140d.dll", "vcomp140d.dll"};
457 for (auto* n : names) 825 for (auto* n : names)
458 if (dll == n) return true; 826 if (dll == n) return true;
459 return false; 827 return false;
@@ -548,11 +916,30 @@ bool bundled_owns_handle(void* ctx, void* module) {
548 return static_cast<Loader*>(ctx)->owns_module_handle(module); 916 return static_cast<Loader*>(ctx)->owns_module_handle(module);
549} 917}
550 918
919void* bundled_find_loaded_w(void* ctx, const std::wstring& basename) {
920 return static_cast<Loader*>(ctx)->find_loaded_module_w(basename);
921}
922
923void* bundled_load_w(void* ctx, const std::wstring& basename, uint32_t flags, bool& handled) {
924 return static_cast<Loader*>(ctx)->load_runtime_module_w(basename, flags, handled);
925}
926
551const shims::BundledModuleOps kBundledOps{ 927const shims::BundledModuleOps kBundledOps{
552 &bundled_find_loaded, 928 &bundled_find_loaded,
553 &bundled_load, 929 &bundled_load,
554 &bundled_get_proc, 930 &bundled_get_proc,
555 &bundled_owns_handle, 931 &bundled_owns_handle,
932 &bundled_find_loaded_w,
933 &bundled_load_w,
934};
935
936// Marks what a run-time load maps as a dynamic load for as long as it is in scope (the caller holds the mutex).
937struct RuntimeLoadScope {
938 explicit RuntimeLoadScope(int& depth) : depth_(depth) { ++depth_; }
939 ~RuntimeLoadScope() { --depth_; }
940 RuntimeLoadScope(const RuntimeLoadScope&) = delete;
941 RuntimeLoadScope& operator=(const RuntimeLoadScope&) = delete;
942 int& depth_;
556}; 943};
557} // namespace 944} // namespace
558 945
@@ -594,6 +981,7 @@ Loader::~Loader() {
594 Module* owner = m; 981 Module* owner = m;
595 if (g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr)) 982 if (g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr))
596 g_tls_slot_generations[m->tls_slot].store(0); 983 g_tls_slot_generations[m->tls_slot].store(0);
984 remove_from_existing_threads(*m);
597 } 985 }
598 uninstall_tls_for_thread(*m); 986 uninstall_tls_for_thread(*m);
599 } 987 }
@@ -607,11 +995,14 @@ Loader::~Loader() {
607 995
608Module& Loader::load(const std::filesystem::path& image) { 996Module& Loader::load(const std::filesystem::path& image) {
609 std::lock_guard lock(mutex_); 997 std::lock_guard lock(mutex_);
610 std::string key = lower(image.filename().string()); 998 const auto key = module_key(image);
611 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; 999 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second;
1000 const auto narrow_key = narrow_module_key(image);
1001 if (Module* existing = find_narrow_module(narrow_key)) return *existing;
612 Module* mapped = nullptr; 1002 Module* mapped = nullptr;
613 try { 1003 try {
614 mapped = &map_image(image); 1004 mapped = &map_image(image, narrow_key);
1005 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 1006 bind_imports(*mapped); // loads every bundled module m imports first, so they land in init_order_ before m
616 protect_sections(*mapped); 1007 protect_sections(*mapped);
617 register_unwind(*mapped); 1008 register_unwind(*mapped);
@@ -631,10 +1022,41 @@ Module& Loader::load(const std::filesystem::path& image) {
631 return m; 1022 return m;
632} 1023}
633 1024
1025Module* Loader::find_narrow_module(const std::string& dll_lower) const {
1026 if (dll_lower.empty()) return nullptr;
1027 // library_loader and PE import names keep their existing narrow-byte contract: the exact compare below is
1028 // bytewise, and the key is never reinterpreted as UTF-8.
1029 for (const auto& entry : by_name_)
1030 if (entry.second->narrow_key == dll_lower) return entry.second;
1031 // The key is ASCII case-folded only. A name with letters outside ASCII (Cyrillic in code page 1251, say)
1032 // compares case-insensitively through the code page, as GetModuleHandleA does: GUEST_ДА.EXE finds guest_да.exe.
1033 // Widening the folded key is safe here: rt::lower() folds ASCII letters only, and no ANSI code page's multibyte
1034 // sequences contain ASCII letter bytes, so both sides widen to the same characters they were spelt with.
1035 if (const std::wstring wide = acp_to_wide(dll_lower); !wide.empty())
1036 for (const auto& entry : by_name_)
1037 if (!entry.second->narrow_key.empty() &&
1038 same_module_name(acp_to_wide(entry.second->narrow_key).c_str(), wide.c_str()))
1039 return entry.second;
1040 return nullptr;
1041}
1042
1043Module* Loader::find_wide_module(const std::wstring& basename) const {
1044 if (basename.empty()) return nullptr;
1045 for (const auto& entry : by_name_)
1046 if (same_module_name(entry.first.c_str(), basename.c_str())) return entry.second;
1047 return nullptr;
1048}
1049
1050void* Loader::find_loaded_module_w(const std::wstring& basename) const {
1051 std::lock_guard lock(mutex_);
1052 Module* m = find_wide_module(basename);
1053 return m ? static_cast<void*>(m->base) : nullptr;
1054}
1055
634void* Loader::find_loaded_module(const std::string& dll_lower) const { 1056void* Loader::find_loaded_module(const std::string& dll_lower) const {
635 std::lock_guard lock(mutex_); 1057 std::lock_guard lock(mutex_);
636 auto it = by_name_.find(dll_lower); 1058 Module* m = find_narrow_module(dll_lower);
637 return it == by_name_.end() ? nullptr : static_cast<void*>(it->second->base); 1059 return m ? static_cast<void*>(m->base) : nullptr;
638} 1060}
639 1061
640void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled) { 1062void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled) {
@@ -642,44 +1064,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; 1064 if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr;
643 1065
644 std::lock_guard lock(mutex_); 1066 std::lock_guard lock(mutex_);
645 const auto existing = by_name_.find(dll_lower); 1067 const RuntimeLoadScope dynamic(runtime_loads_);
1068 Module* existing = find_narrow_module(dll_lower);
646 const std::filesystem::path candidate = game_dir_ / dll_lower; 1069 const std::filesystem::path candidate = game_dir_ / dll_lower;
647 std::error_code ec; 1070 std::error_code ec;
648 const bool is_bundled = existing != by_name_.end() || std::filesystem::is_regular_file(candidate, ec); 1071 const bool is_bundled = existing || std::filesystem::is_regular_file(candidate, ec);
649 if (!is_bundled) return nullptr; 1072 if (!is_bundled) return nullptr;
650 1073
651 handled = true; 1074 handled = true;
1075 return load_runtime_candidate(existing, candidate, flags, dll_lower);
1076}
1077
1078void* Loader::load_runtime_module_w(const std::wstring& basename, uint32_t flags, bool& handled) {
1079 handled = false;
1080 if (basename.empty()) return nullptr;
1081 // A name the code page can spell takes the narrow path's host-copy rule as well.
1082 if (const std::string narrow = narrow_module_key(std::filesystem::path(basename)); !narrow.empty())
1083 if (prefer_host_copy(narrow)) return nullptr;
1084
1085 std::lock_guard lock(mutex_);
1086 Module* existing = find_wide_module(basename);
1087 const std::filesystem::path candidate = game_dir_ / basename;
1088 std::error_code ec;
1089 if (!existing && !std::filesystem::is_regular_file(candidate, ec)) return nullptr;
1090
1091 handled = true;
1092 return load_runtime_candidate(existing, candidate, flags, path_utf8(basename));
1093}
1094
1095void* Loader::load_runtime_candidate(Module* existing, const std::filesystem::path& candidate, uint32_t flags,
1096 const std::string& display) {
652 // Win32 DONT_RESOLVE_DLL_REFERENCES (0x1) forbids resolving dependencies or running TLS/DllMain; refuse it 1097 // 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. 1098 // explicitly instead of silently performing a normal resolving + initialising load.
654 if ((flags & DONT_RESOLVE_DLL_REFERENCES) != 0) { 1099 if ((flags & DONT_RESOLVE_DLL_REFERENCES) != 0) {
655 std::fprintf(stderr, 1100 std::fprintf(stderr,
656 "[rt] loader: LoadLibraryEx(%s, DONT_RESOLVE_DLL_REFERENCES) is not supported for bundled DLLs\n", 1101 "[rt] loader: LoadLibraryEx(%s, DONT_RESOLVE_DLL_REFERENCES) is not supported for bundled DLLs\n",
657 dll_lower.c_str()); 1102 display.c_str());
658 SetLastError(ERROR_NOT_SUPPORTED); 1103 SetLastError(ERROR_NOT_SUPPORTED);
659 return nullptr; 1104 return nullptr;
660 } 1105 }
661 1106
662 if (existing != by_name_.end()) { 1107 if (existing) {
663 try { 1108 try {
664 initialise(); 1109 initialise();
665 return static_cast<void*>(existing->second->base); 1110 return static_cast<void*>(existing->base);
666 } catch (const std::exception& e) { 1111 } 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()); 1112 std::fprintf(stderr, "[rt] loader: run-time initialise of %s failed: %s\n", display.c_str(), e.what());
668 SetLastError(ERROR_DLL_INIT_FAILED); 1113 SetLastError(ERROR_DLL_INIT_FAILED);
669 return nullptr; 1114 return nullptr;
670 } 1115 }
671 } 1116 }
672 1117
1118 Module* mapped = nullptr;
673 try { 1119 try {
674 Module& m = load(candidate); 1120 Module& m = load(candidate);
1121 mapped = &m;
675 initialise(); 1122 initialise();
676 std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str()); 1123 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); 1124 return static_cast<void*>(m.base);
678 } catch (const std::exception& e) { 1125 } catch (const std::exception& e) {
679 // load() drops a module that failed to map or bind (dependencies included); this also drops one whose 1126 // 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_. 1127 // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via order_.
681 by_name_.erase(dll_lower); 1128 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()); 1129 std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", display.c_str(), e.what());
683 SetLastError(ERROR_DLL_INIT_FAILED); 1130 SetLastError(ERROR_DLL_INIT_FAILED);
684 return nullptr; 1131 return nullptr;
685 } 1132 }
@@ -701,6 +1148,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; 1148 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()) { 1149 if (auto it = target->forwarders.find(sym); it != target->forwarders.end()) {
703 try { 1150 try {
1151 const RuntimeLoadScope dynamic(runtime_loads_);
704 Binding binding = Binding::Unimplemented; 1152 Binding binding = Binding::Unimplemented;
705 void* fn = resolve_forwarder(it->second, binding, 0); 1153 void* fn = resolve_forwarder(it->second, binding, 0);
706 if (binding == Binding::Module) initialise(); 1154 if (binding == Binding::Module) initialise();
@@ -787,7 +1235,11 @@ void Loader::initialise(Module& m) {
787 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 1235 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) { 1236 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); 1237 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); 1238 // lpvReserved "is NULL for dynamic loads and non-NULL for static loads" (DllMain docs). What Windows points
1239 // it at is its own; a static load gets a CONTEXT captured here, so a DLL that reads through it reads memory.
1240 CONTEXT context{};
1241 if (!m.dynamic_load) RtlCaptureContext(&context);
1242 const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, m.dynamic_load ? nullptr : &context);
791 if (startup_trace::enabled()) 1243 if (startup_trace::enabled())
792 startup_trace::event("dllmain", "\"module\":" + startup_trace::quote(m.name) + 1244 startup_trace::event("dllmain", "\"module\":" + startup_trace::quote(m.name) +
793 ",\"result\":" + std::to_string(ok)); 1245 ",\"result\":" + std::to_string(ok));
@@ -806,12 +1258,12 @@ void Loader::set_initialised(Module& m, bool value) {
806 m.initialised = value; 1258 m.initialised = value;
807} 1259}
808 1260
809Module& Loader::map_image(const std::filesystem::path& path) { 1261Module& Loader::map_image(const std::filesystem::path& path, const std::string& narrow_key) {
810 auto file = read_file(path); 1262 auto file = read_file(path);
811 const std::string name = path.filename().string(); 1263 const std::string name = path_utf8(path.filename());
812 auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(file.data()); 1264 auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(file.data());
813 if (file.size() < sizeof(IMAGE_DOS_HEADER) || dos->e_magic != IMAGE_DOS_SIGNATURE) 1265 if (file.size() < sizeof(IMAGE_DOS_HEADER) || dos->e_magic != IMAGE_DOS_SIGNATURE)
814 throw std::runtime_error(path.string() + ": not an MZ image"); 1266 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()) 1267 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"); 1268 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); 1269 auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew);
@@ -835,11 +1287,12 @@ Module& Loader::map_image(const std::filesystem::path& path) {
835 1287
836 auto* m = new Module; 1288 auto* m = new Module;
837 m->name = name; 1289 m->name = name;
1290 m->narrow_key = narrow_key;
838 m->path = path; 1291 m->path = path;
839 m->preferred_base = oh.ImageBase; 1292 m->preferred_base = oh.ImageBase;
840 m->size = oh.SizeOfImage; 1293 m->size = oh.SizeOfImage;
841 m->entry_rva = oh.AddressOfEntryPoint; 1294 m->entry_rva = oh.AddressOfEntryPoint;
842 by_name_[lower(m->name)] = m; 1295 by_name_[module_key(path)] = m;
843 order_.push_back(m); 1296 order_.push_back(m);
844 1297
845 // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual. 1298 // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual.
@@ -864,6 +1317,8 @@ Module& Loader::map_image(const std::filesystem::path& path) {
864 std::memcpy(m->base, file.data(), oh.SizeOfHeaders); 1317 std::memcpy(m->base, file.data(), oh.SizeOfHeaders);
865 auto* sec = IMAGE_FIRST_SECTION(nt); 1318 auto* sec = IMAGE_FIRST_SECTION(nt);
866 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { 1319 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) {
1320 if (sec->VirtualAddress < oh.SizeOfHeaders)
1321 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); 1322 uint32_t n = std::min(sec->SizeOfRawData, sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData);
868 if (!n) continue; 1323 if (!n) continue;
869 if (sec->PointerToRawData > file.size() || n > file.size() - sec->PointerToRawData) 1324 if (sec->PointerToRawData > file.size() || n > file.size() - sec->PointerToRawData)
@@ -889,6 +1344,9 @@ Module& Loader::map_image(const std::filesystem::path& path) {
889 size_t count = (block->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2; 1344 size_t count = (block->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2;
890 for (size_t i = 0; i < count; ++i) { 1345 for (size_t i = 0; i < count; ++i) {
891 uint16_t type = entries[i] >> 12, off = entries[i] & 0xFFF; 1346 uint16_t type = entries[i] >> 12, off = entries[i] & 0xFFF;
1347 if (type != IMAGE_REL_BASED_ABSOLUTE &&
1348 static_cast<uint64_t>(block->VirtualAddress) + off < oh.SizeOfHeaders)
1349 throw std::runtime_error(m->name + ": a relocation lands in the headers");
892 if (type == IMAGE_REL_BASED_DIR64) { 1350 if (type == IMAGE_REL_BASED_DIR64) {
893 require_range(m->name, static_cast<uint64_t>(block->VirtualAddress) + off, sizeof(uint64_t), m->size, 1351 require_range(m->name, static_cast<uint64_t>(block->VirtualAddress) + off, sizeof(uint64_t), m->size,
894 "a relocation"); 1352 "a relocation");
@@ -1003,6 +1461,9 @@ void Loader::initialize_tls(Module& m) {
1003 m.tls_block = g_thread_tls_slots[slot].block; 1461 m.tls_block = g_thread_tls_slots[slot].block;
1004 m.tls_saved_block = g_thread_tls_slots[slot].saved; 1462 m.tls_saved_block = g_thread_tls_slots[slot].saved;
1005 } 1463 }
1464 // Threads started from here on get their copy from the helper DLL's DLL_THREAD_ATTACH; the ones already running
1465 // get it now.
1466 install_on_existing_threads(m);
1006} 1467}
1007 1468
1008void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); } 1469void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); }