diff options
| author | Vonsek <45567075+Vonsek@users.noreply.github.com> | 2026-11-22 09:43:07 +0100 |
|---|---|---|
| committer | Vonsek <45567075+Vonsek@users.noreply.github.com> | 2026-11-22 09:43:07 +0100 |
| commit | 8ccf429a56bf62ae231d0aa06e043c17bb8a83e2 (patch) | |
| tree | 8a0d75f90344444a356ac7021acb451852621eb5 /runtime/src/pe_loader.cpp | |
| parent | e444c83335ea6f3cabf68539c2f6d63d39d0a868 (diff) | |
| parent | c603b8f8ff9090fbf5bcc0297990f40cd1cb6638 (diff) | |
Merge main into the S#/T# mip test (#319)
Conflicts in docs/d3d12_vulkan.md, runtime/CMakeLists.txt, check.py,
run_gpu_tests.py and test_shader_checks.py: main's versions with
vk_sampler_test, ps_ssharp and its checks added back (ps_ssharp is drawn
with vs_ids through DRAWN_WITH now).
AI-assisted (Claude Code).
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.cpp | 405 |
1 files changed, 334 insertions, 71 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index a0198c033..15a62d9b4 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp | |||
| @@ -1,11 +1,16 @@ | |||
| 1 | #include "pe_loader.h" | 1 | #include "pe_loader.h" |
| 2 | 2 | ||
| 3 | #include <windows.h> | 3 | #include <windows.h> |
| 4 | #include <intrin.h> | ||
| 4 | 5 | ||
| 5 | #include <algorithm> | 6 | #include <algorithm> |
| 7 | #include <atomic> | ||
| 8 | #include <cstdio> | ||
| 9 | #include <cstdlib> | ||
| 6 | #include <cstring> | 10 | #include <cstring> |
| 7 | #include <fstream> | 11 | #include <fstream> |
| 8 | #include <stdexcept> | 12 | #include <stdexcept> |
| 13 | #include <vector> | ||
| 9 | 14 | ||
| 10 | #include "../shims/shims.h" | 15 | #include "../shims/shims.h" |
| 11 | 16 | ||
| @@ -42,6 +47,94 @@ std::string read_string(const std::string& name, uint8_t* base, uint32_t image_s | |||
| 42 | return {s, end}; | 47 | return {s, end}; |
| 43 | } | 48 | } |
| 44 | 49 | ||
| 50 | // PE/COFF: NumberOfRvaAndSizes counts the data directories; entries past it are not directories, whatever they hold. | ||
| 51 | IMAGE_DATA_DIRECTORY directory(const IMAGE_NT_HEADERS64* nt, unsigned index) { | ||
| 52 | return index < nt->OptionalHeader.NumberOfRvaAndSizes ? nt->OptionalHeader.DataDirectory[index] : IMAGE_DATA_DIRECTORY{}; | ||
| 53 | } | ||
| 54 | |||
| 55 | // The TLS directory holds virtual addresses, which relocations have already moved to this mapping. | ||
| 56 | uint64_t rva_in(const Module& m, uint64_t va, const char* what) { | ||
| 57 | const uint64_t base = reinterpret_cast<uint64_t>(m.base); | ||
| 58 | if (va < base || va - base >= m.size) throw std::runtime_error(m.name + ": " + what + " is outside the image"); | ||
| 59 | return va - base; | ||
| 60 | } | ||
| 61 | |||
| 62 | IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) { | ||
| 63 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); | ||
| 64 | const auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS]; | ||
| 65 | if (!dir.Size || !dir.VirtualAddress) return nullptr; | ||
| 66 | require_range(m.name, dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64), m.size, "the TLS directory"); | ||
| 67 | return at<IMAGE_TLS_DIRECTORY64>(m.base, dir.VirtualAddress); | ||
| 68 | } | ||
| 69 | |||
| 70 | // __declspec(thread) reads TEB->ThreadLocalStoragePointer[_tls_index] at gs:[58h]. That array is indexed by the | ||
| 71 | // loader-assigned per-module TLS index and is a different index space from TlsAlloc/TlsGetValue (TlsSlots). Only the OS | ||
| 72 | // loader can allocate a module index, so the runtime ships a minimal DLL whose only content is a TLS anchor | ||
| 73 | // (src/tls_host.cpp). Loading it makes the OS reserve an index and give every thread a block for it; the native loader | ||
| 74 | // reuses that index for the mapped image. One helper means one mapped TLS module at a time. | ||
| 75 | constexpr DWORD kMaxModuleTlsSlots = 64; | ||
| 76 | void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); } | ||
| 77 | |||
| 78 | struct TlsHostModule { | ||
| 79 | HMODULE module = nullptr; | ||
| 80 | DWORD index = TLS_OUT_OF_INDEXES; | ||
| 81 | }; | ||
| 82 | |||
| 83 | TlsHostModule load_tls_host() { | ||
| 84 | TlsHostModule host; | ||
| 85 | // Dynamic buffer loop for paths that exceed MAX_PATH | ||
| 86 | std::wstring exe_path; | ||
| 87 | DWORD size = MAX_PATH; | ||
| 88 | while (true) { | ||
| 89 | exe_path.resize(size); | ||
| 90 | DWORD len = GetModuleFileNameW(nullptr, exe_path.data(), size); | ||
| 91 | if (len == 0) return host; | ||
| 92 | if (len < size - 1) { | ||
| 93 | exe_path.resize(len); | ||
| 94 | break; | ||
| 95 | } | ||
| 96 | size *= 2; | ||
| 97 | } | ||
| 98 | const std::filesystem::path path = std::filesystem::path(exe_path).parent_path() / L"gta6rt_tls_host.dll"; | ||
| 99 | // The helper is linked with the static CRT (/MT), so it needs only system DLLs. Restricting the dependency search | ||
| 100 | // to System32 keeps a game-supplied vcruntime next to the executable from being picked up. | ||
| 101 | host.module = LoadLibraryExW(path.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); | ||
| 102 | if (!host.module) return host; | ||
| 103 | |||
| 104 | auto* base = reinterpret_cast<uint8_t*>(host.module); | ||
| 105 | auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(base); | ||
| 106 | auto* nt = at<IMAGE_NT_HEADERS64>(base, dos->e_lfanew); | ||
| 107 | const auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS]; | ||
| 108 | if (!dir.Size || !dir.VirtualAddress) { | ||
| 109 | FreeLibrary(host.module); | ||
| 110 | host.module = nullptr; | ||
| 111 | return host; | ||
| 112 | } | ||
| 113 | auto* tls = at<IMAGE_TLS_DIRECTORY64>(base, dir.VirtualAddress); | ||
| 114 | if (!tls->AddressOfIndex) { | ||
| 115 | FreeLibrary(host.module); | ||
| 116 | host.module = nullptr; | ||
| 117 | return host; | ||
| 118 | } | ||
| 119 | host.index = *reinterpret_cast<DWORD*>(tls->AddressOfIndex); | ||
| 120 | return host; | ||
| 121 | } | ||
| 122 | |||
| 123 | TlsHostModule& tls_host() { | ||
| 124 | // The helper stays loaded for the process lifetime: unloading it would release the reserved TLS index. Its own | ||
| 125 | // per-thread blocks are restored by uninstall_tls_for_thread, so the OS loader can free them normally. | ||
| 126 | static TlsHostModule host = load_tls_host(); | ||
| 127 | return host; | ||
| 128 | } | ||
| 129 | |||
| 130 | std::atomic<Module*> g_tls_slot_owner{nullptr}; | ||
| 131 | |||
| 132 | // Per-thread installation state. Only one mapped TLS module can own the reserved slot, so one entry per thread is | ||
| 133 | // enough; the saved pointer is the helper DLL's own block that the OS loader will free at thread exit. | ||
| 134 | thread_local Module* g_thread_tls_module = nullptr; | ||
| 135 | thread_local void* g_thread_tls_saved = nullptr; | ||
| 136 | thread_local void* g_thread_tls_block = nullptr; | ||
| 137 | |||
| 45 | // The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used. | 138 | // The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used. |
| 46 | bool prefer_host_copy(const std::string& dll) { | 139 | bool prefer_host_copy(const std::string& dll) { |
| 47 | static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll", | 140 | static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll", |
| @@ -54,10 +147,58 @@ bool prefer_host_copy(const std::string& dll) { | |||
| 54 | 147 | ||
| 55 | } // namespace | 148 | } // namespace |
| 56 | 149 | ||
| 150 | namespace { | ||
| 151 | bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { | ||
| 152 | for (const Module* m : static_cast<Loader*>(ctx)->modules()) { | ||
| 153 | const auto base = reinterpret_cast<uint64_t>(m->base); | ||
| 154 | if (m->base && address >= base && address - base < m->size) { | ||
| 155 | module = m->name; | ||
| 156 | rva = static_cast<uint32_t>(address - base); | ||
| 157 | return true; | ||
| 158 | } | ||
| 159 | } | ||
| 160 | return false; | ||
| 161 | } | ||
| 162 | } // namespace | ||
| 163 | |||
| 164 | Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { | ||
| 165 | shims::add_module_lookup(this, &lookup_in_loader); | ||
| 166 | } | ||
| 167 | |||
| 57 | Loader::~Loader() { | 168 | Loader::~Loader() { |
| 169 | // Importers must release their resources before their dependencies. Keep every mapping, unwind table and TLS | ||
| 170 | // block alive throughout the notifications: a detach handler can still call an imported function or free an | ||
| 171 | // FLS slot whose destructor lives in another mapped image. | ||
| 172 | for (auto it = init_order_.rbegin(); it != init_order_.rend(); ++it) { | ||
| 173 | Module& m = **it; | ||
| 174 | if (!m.initialised) continue; // a map-only load never opts in to running image code | ||
| 175 | m.initialised = false; | ||
| 176 | try { | ||
| 177 | run_tls_callbacks(m, DLL_PROCESS_DETACH); | ||
| 178 | } catch (const std::exception& e) { | ||
| 179 | // A module may have changed its callback table since attach. A destructor cannot propagate the validation | ||
| 180 | // error; report it and still let DllMain release resources before the image is freed. | ||
| 181 | std::fprintf(stderr, "[rt] TLS process detach failed for %s: %s\n", m.name.c_str(), e.what()); | ||
| 182 | } | ||
| 183 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); | ||
| 184 | if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { | ||
| 185 | auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); | ||
| 186 | entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored | ||
| 187 | } | ||
| 188 | } | ||
| 189 | shims::remove_module_lookup(this); | ||
| 58 | for (auto* m : order_) { | 190 | for (auto* m : order_) { |
| 191 | // TLS state must go away before the image and its TLS block are unmapped. | ||
| 192 | if (m->tls_index != kNoTlsIndex) { | ||
| 193 | // Only the loading thread has this module installed; other threads must uninstall for themselves before | ||
| 194 | // the Loader is destroyed. | ||
| 195 | uninstall_tls_for_thread(*m); | ||
| 196 | Module* owner = m; | ||
| 197 | g_tls_slot_owner.compare_exchange_strong(owner, nullptr); | ||
| 198 | } | ||
| 199 | // Before the image is freed: a stale table would let a later stack walk read unmapped memory. | ||
| 200 | if (m->function_table) RtlDeleteFunctionTable(static_cast<PRUNTIME_FUNCTION>(m->function_table)); | ||
| 59 | if (m->tls_block) VirtualFree(m->tls_block, 0, MEM_RELEASE); | 201 | if (m->tls_block) VirtualFree(m->tls_block, 0, MEM_RELEASE); |
| 60 | if (m->has_tls_slot) TlsFree(m->tls_slot); | ||
| 61 | if (m->base) VirtualFree(m->base, 0, MEM_RELEASE); | 202 | if (m->base) VirtualFree(m->base, 0, MEM_RELEASE); |
| 62 | delete m; | 203 | delete m; |
| 63 | } | 204 | } |
| @@ -69,10 +210,48 @@ Module& Loader::load(const std::filesystem::path& image) { | |||
| 69 | Module& m = map_image(image); | 210 | Module& m = map_image(image); |
| 70 | bind_imports(m); // loads every bundled module m imports first, so they land in init_order_ before m | 211 | bind_imports(m); // loads every bundled module m imports first, so they land in init_order_ before m |
| 71 | protect_sections(m); | 212 | protect_sections(m); |
| 213 | register_unwind(m); | ||
| 72 | init_order_.push_back(&m); | 214 | init_order_.push_back(&m); |
| 73 | return m; | 215 | return m; |
| 74 | } | 216 | } |
| 75 | 217 | ||
| 218 | // x64 has no frame-pointer chain to fall back on: without its .pdata registered, an exception raised in (or passing | ||
| 219 | // through) a mapped image can't be dispatched past that frame, and the process dies. Images the system loader maps | ||
| 220 | // are found through its own module list; ours are VirtualAlloc'd, so they are registered as dynamic function tables. | ||
| 221 | // | ||
| 222 | // The table is checked before it is handed over, because RtlLookupFunctionEntry trusts it: it binary-searches the | ||
| 223 | // entries by BeginAddress and follows UnwindData without bounds checks. Measured over 3,780 x64 images in | ||
| 224 | // System32 (5,023,071 entries) and the package's FidelityFX DLLs: every table is sorted and non-overlapping and in | ||
| 225 | // bounds, and one shipped image (symcryptk.dll) has a zero-length entry (BeginAddress == EndAddress), so that is | ||
| 226 | // allowed. No entry in that set uses the indirect form (UnwindData bit 0). | ||
| 227 | void Loader::register_unwind(Module& m) { | ||
| 228 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); | ||
| 229 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXCEPTION); | ||
| 230 | // Like the system loader, a trailing partial entry is ignored. | ||
| 231 | const uint32_t count = dir.Size / sizeof(RUNTIME_FUNCTION); | ||
| 232 | if (!count) return; | ||
| 233 | require_range(m.name, dir.VirtualAddress, static_cast<uint64_t>(count) * sizeof(RUNTIME_FUNCTION), m.size, | ||
| 234 | "the exception directory"); | ||
| 235 | auto* table = at<RUNTIME_FUNCTION>(m.base, dir.VirtualAddress); | ||
| 236 | auto reject = [&](uint32_t i, const char* why) { | ||
| 237 | throw std::runtime_error(m.name + ": unwind entry " + std::to_string(i) + " " + why); | ||
| 238 | }; | ||
| 239 | uint32_t previous_end = 0; | ||
| 240 | for (uint32_t i = 0; i < count; ++i) { | ||
| 241 | const RUNTIME_FUNCTION& f = table[i]; | ||
| 242 | if (f.EndAddress < f.BeginAddress || f.EndAddress > m.size) reject(i, "covers code outside the image"); | ||
| 243 | if (f.BeginAddress < previous_end) reject(i, "is out of order or overlaps the one before it"); | ||
| 244 | // UNWIND_INFO starts with a 4-byte header; its codes and handler data are the unwinder's to read. | ||
| 245 | const uint32_t info = f.UnwindData & ~1u; | ||
| 246 | if (info > m.size || m.size - info < 4) reject(i, "has unwind data outside the image"); | ||
| 247 | previous_end = f.EndAddress; | ||
| 248 | } | ||
| 249 | if (!RtlAddFunctionTable(table, count, reinterpret_cast<DWORD64>(m.base))) | ||
| 250 | throw std::runtime_error(m.name + ": RtlAddFunctionTable failed"); | ||
| 251 | m.function_table = table; | ||
| 252 | m.function_count = count; | ||
| 253 | } | ||
| 254 | |||
| 76 | void Loader::initialise() { | 255 | void Loader::initialise() { |
| 77 | // Not order_: map_image pushes a module there before bind_imports maps its dependencies, so order_ lists an | 256 | // Not order_: map_image pushes a module there before bind_imports maps its dependencies, so order_ lists an |
| 78 | // importer ahead of the DLLs it imports. init_order_ is filled once a module's imports are all loaded. | 257 | // importer ahead of the DLLs it imports. init_order_ is filled once a module's imports are all loaded. |
| @@ -81,70 +260,12 @@ void Loader::initialise() { | |||
| 81 | 260 | ||
| 82 | void Loader::initialise(Module& m) { | 261 | void Loader::initialise(Module& m) { |
| 83 | if (m.initialised) return; | 262 | if (m.initialised) return; |
| 84 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); | ||
| 85 | const uint64_t base = reinterpret_cast<uint64_t>(m.base); | ||
| 86 | 263 | ||
| 87 | // The TLS directory holds virtual addresses, which relocations have already moved to this mapping. | 264 | // TLS was installed by load(); initialise() only delivers the events, so no slot is allocated or written twice. |
| 88 | auto rva_of = [&](uint64_t va, const char* what) { | 265 | run_tls_callbacks(m, DLL_PROCESS_ATTACH); |
| 89 | if (va < base || va - base >= m.size) | ||
| 90 | throw std::runtime_error(m.name + ": " + what + " is outside the image"); | ||
| 91 | return va - base; | ||
| 92 | }; | ||
| 93 | |||
| 94 | auto& tls_dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS]; | ||
| 95 | if (tls_dir.Size) { | ||
| 96 | require_range(m.name, tls_dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64), m.size, "the TLS directory"); | ||
| 97 | auto* tls = at<IMAGE_TLS_DIRECTORY64>(m.base, tls_dir.VirtualAddress); | ||
| 98 | |||
| 99 | uint64_t start = 0, template_size = 0; | ||
| 100 | if (tls->StartAddressOfRawData || tls->EndAddressOfRawData) { | ||
| 101 | start = rva_of(tls->StartAddressOfRawData, "the TLS template"); | ||
| 102 | uint64_t end = rva_of(tls->EndAddressOfRawData, "the end of the TLS template"); | ||
| 103 | if (end < start) throw std::runtime_error(m.name + ": the TLS template ends before it starts"); | ||
| 104 | template_size = end - start; | ||
| 105 | require_range(m.name, start, template_size, m.size, "the TLS template"); | ||
| 106 | } | ||
| 107 | m.tls_block_size = template_size + tls->SizeOfZeroFill; | ||
| 108 | if (m.tls_block_size > (1u << 20)) throw std::runtime_error(m.name + ": the TLS block is larger than 1 MiB"); | ||
| 109 | if (m.tls_block_size) { | ||
| 110 | m.tls_block = VirtualAlloc(nullptr, static_cast<SIZE_T>(m.tls_block_size), MEM_RESERVE | MEM_COMMIT, | ||
| 111 | PAGE_READWRITE); | ||
| 112 | if (!m.tls_block) throw std::runtime_error(m.name + ": cannot allocate the TLS block"); | ||
| 113 | if (template_size) std::memcpy(m.tls_block, m.base + start, static_cast<size_t>(template_size)); | ||
| 114 | } | ||
| 115 | |||
| 116 | if (tls->AddressOfIndex) { | ||
| 117 | uint64_t index_rva = rva_of(tls->AddressOfIndex, "the TLS index"); | ||
| 118 | require_range(m.name, index_rva, sizeof(uint32_t), m.size, "the TLS index"); | ||
| 119 | DWORD slot = TlsAlloc(); | ||
| 120 | if (slot == TLS_OUT_OF_INDEXES) throw std::runtime_error(m.name + ": no TLS slot is free"); | ||
| 121 | m.tls_slot = slot; | ||
| 122 | m.has_tls_slot = true; | ||
| 123 | if (m.tls_block) TlsSetValue(slot, m.tls_block); | ||
| 124 | // The index lives in a writable section, but protect_sections already ran, so lift it for the write. | ||
| 125 | auto* index = m.base + index_rva; | ||
| 126 | auto* page = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(index) & ~uintptr_t(0xFFF)); | ||
| 127 | DWORD old = 0, ignored = 0; | ||
| 128 | if (!VirtualProtect(page, 0x1000, PAGE_READWRITE, &old)) | ||
| 129 | throw std::runtime_error(m.name + ": the TLS index can't be written"); | ||
| 130 | *reinterpret_cast<uint32_t*>(index) = slot; | ||
| 131 | VirtualProtect(page, 0x1000, old, &ignored); | ||
| 132 | } | ||
| 133 | |||
| 134 | if (tls->AddressOfCallBacks) { | ||
| 135 | uint64_t table_rva = rva_of(tls->AddressOfCallBacks, "the TLS callback table"); | ||
| 136 | for (uint64_t i = 0;; ++i) { | ||
| 137 | uint64_t entry_rva = table_rva + i * sizeof(uint64_t); | ||
| 138 | require_range(m.name, entry_rva, sizeof(uint64_t), m.size, "a TLS callback table entry"); | ||
| 139 | uint64_t fn = *at<uint64_t>(m.base, static_cast<uint32_t>(entry_rva)); | ||
| 140 | if (!fn) break; | ||
| 141 | auto callback = reinterpret_cast<void(NTAPI*)(void*, DWORD, void*)>(m.base + rva_of(fn, "a TLS callback")); | ||
| 142 | callback(m.base, DLL_PROCESS_ATTACH, nullptr); | ||
| 143 | } | ||
| 144 | } | ||
| 145 | } | ||
| 146 | 266 | ||
| 147 | // Only a DLL gets DllMain. An EXE's entry point has a different signature and is the caller's to run. | 267 | // Only a DLL gets DllMain. An EXE's entry point has a different signature and is the caller's to run. |
| 268 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); | ||
| 148 | if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { | 269 | if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { |
| 149 | if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image"); | 270 | if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image"); |
| 150 | auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); | 271 | auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); |
| @@ -190,7 +311,7 @@ Module& Loader::map_image(const std::filesystem::path& path) { | |||
| 190 | m->base = static_cast<uint8_t*>( | 311 | m->base = static_cast<uint8_t*>( |
| 191 | VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | 312 | VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); |
| 192 | if (!m->base) { | 313 | if (!m->base) { |
| 193 | auto& relocs = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; | 314 | const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); |
| 194 | if (!relocs.Size) | 315 | if (!relocs.Size) |
| 195 | throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations"); | 316 | throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations"); |
| 196 | m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | 317 | m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); |
| @@ -211,7 +332,7 @@ Module& Loader::map_image(const std::filesystem::path& path) { | |||
| 211 | int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase); | 332 | int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase); |
| 212 | if (delta) { | 333 | if (delta) { |
| 213 | m->relocated = true; | 334 | m->relocated = true; |
| 214 | auto& dir = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; | 335 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); |
| 215 | if (!dir.Size) throw std::runtime_error(m->name + ": the image has no relocations and isn't at its base"); | 336 | if (!dir.Size) throw std::runtime_error(m->name + ": the image has no relocations and isn't at its base"); |
| 216 | require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); | 337 | require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); |
| 217 | auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress); | 338 | auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress); |
| @@ -228,6 +349,17 @@ Module& Loader::map_image(const std::filesystem::path& path) { | |||
| 228 | require_range(m->name, static_cast<uint64_t>(block->VirtualAddress) + off, sizeof(uint64_t), m->size, | 349 | require_range(m->name, static_cast<uint64_t>(block->VirtualAddress) + off, sizeof(uint64_t), m->size, |
| 229 | "a relocation"); | 350 | "a relocation"); |
| 230 | *at<uint64_t>(m->base, block->VirtualAddress + off) += delta; | 351 | *at<uint64_t>(m->base, block->VirtualAddress + off) += delta; |
| 352 | } else if (type == IMAGE_REL_BASED_HIGHLOW) { | ||
| 353 | // A 32-bit absolute address (code built /LARGEADDRESSAWARE:NO), which the x64 Windows loader | ||
| 354 | // also applies. Where the new address no longer fits in 32 bits, Windows would truncate it; the | ||
| 355 | // image would then jump or read through a wrong pointer, so the load is refused instead. | ||
| 356 | require_range(m->name, static_cast<uint64_t>(block->VirtualAddress) + off, sizeof(uint32_t), | ||
| 357 | m->size, "a relocation"); | ||
| 358 | auto* slot = at<uint32_t>(m->base, block->VirtualAddress + off); | ||
| 359 | const int64_t moved = static_cast<int64_t>(*slot) + delta; | ||
| 360 | if (moved < 0 || moved > 0xFFFFFFFFll) | ||
| 361 | throw std::runtime_error(m->name + ": a 32-bit (HIGHLOW) relocation does not fit at this base"); | ||
| 362 | *slot = static_cast<uint32_t>(moved); | ||
| 231 | } else if (type != IMAGE_REL_BASED_ABSOLUTE) { | 363 | } else if (type != IMAGE_REL_BASED_ABSOLUTE) { |
| 232 | throw std::runtime_error(m->name + ": unsupported relocation type " + std::to_string(type)); | 364 | throw std::runtime_error(m->name + ": unsupported relocation type " + std::to_string(type)); |
| 233 | } | 365 | } |
| @@ -235,13 +367,130 @@ Module& Loader::map_image(const std::filesystem::path& path) { | |||
| 235 | block = reinterpret_cast<IMAGE_BASE_RELOCATION*>(reinterpret_cast<uint8_t*>(block) + block->SizeOfBlock); | 367 | block = reinterpret_cast<IMAGE_BASE_RELOCATION*>(reinterpret_cast<uint8_t*>(block) + block->SizeOfBlock); |
| 236 | } | 368 | } |
| 237 | } | 369 | } |
| 370 | // The TLS directory and the exception directory hold virtual addresses, so both are read after relocation. TLS is | ||
| 371 | // installed here, before bind_imports can return control to the caller and before any image code can run. | ||
| 372 | initialize_tls(*m); | ||
| 238 | parse_exports(*m); | 373 | parse_exports(*m); |
| 239 | return *m; | 374 | return *m; |
| 240 | } | 375 | } |
| 241 | 376 | ||
| 377 | // Static TLS for the thread that calls load(). The PE TLS directory only carries the template (Start..End) and the | ||
| 378 | // zero-fill size; it has no field naming the TLS block. The Windows loader allocates a block per module per thread and | ||
| 379 | // puts it in TEB->ThreadLocalStoragePointer[module index], which is what __declspec(thread) code reads via _tls_index. | ||
| 380 | // Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to | ||
| 381 | // gta6rt_tls_host.dll. That makes one manually mapped TLS module work; a second one is rejected rather than silently | ||
| 382 | // sharing (and corrupting) the same slot. | ||
| 383 | void Loader::initialize_tls(Module& m) { | ||
| 384 | auto* tls = tls_directory(m); | ||
| 385 | if (!tls) return; | ||
| 386 | // A present but all-zero directory is treated like an absent one. | ||
| 387 | if (!tls->StartAddressOfRawData && !tls->EndAddressOfRawData && !tls->AddressOfIndex && !tls->AddressOfCallBacks && | ||
| 388 | !tls->SizeOfZeroFill) | ||
| 389 | return; | ||
| 390 | if (tls->EndAddressOfRawData < tls->StartAddressOfRawData) | ||
| 391 | throw std::runtime_error(m.name + ": TLS template end precedes its start"); | ||
| 392 | uint64_t raw = tls->EndAddressOfRawData - tls->StartAddressOfRawData; | ||
| 393 | uint64_t total = raw + tls->SizeOfZeroFill; | ||
| 394 | if (total > 0xFFFFFFFFull) throw std::runtime_error(m.name + ": TLS block is too large"); | ||
| 395 | const uint32_t raw_rva = | ||
| 396 | raw ? static_cast<uint32_t>(rva_in(m, tls->StartAddressOfRawData, "the TLS template")) : 0; | ||
| 397 | if (raw) require_range(m.name, raw_rva, raw, m.size, "the TLS template"); | ||
| 398 | uint64_t index_rva = 0; | ||
| 399 | if (tls->AddressOfIndex) { | ||
| 400 | index_rva = rva_in(m, tls->AddressOfIndex, "the TLS index"); | ||
| 401 | require_range(m.name, index_rva, sizeof(uint32_t), m.size, "the TLS index"); | ||
| 402 | } | ||
| 403 | |||
| 404 | DWORD index = tls_host().index; | ||
| 405 | if (index == TLS_OUT_OF_INDEXES) | ||
| 406 | throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index"); | ||
| 407 | if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range"); | ||
| 408 | if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); | ||
| 409 | |||
| 410 | Module* expected = nullptr; | ||
| 411 | if (!g_tls_slot_owner.compare_exchange_strong(expected, &m)) | ||
| 412 | throw std::runtime_error(m.name + ": only one manually mapped module may use static TLS at a time"); | ||
| 413 | |||
| 414 | m.tls_index = index; | ||
| 415 | m.tls_template = raw ? m.base + raw_rva : nullptr; | ||
| 416 | m.tls_raw_size = static_cast<uint32_t>(raw); | ||
| 417 | m.tls_zero_fill = tls->SizeOfZeroFill; | ||
| 418 | m.tls_block_size = static_cast<uint32_t>(total); | ||
| 419 | // The index lives in a writable section and protect_sections() has not run yet, so the write needs no | ||
| 420 | // VirtualProtect dance. | ||
| 421 | if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index; | ||
| 422 | try { | ||
| 423 | install_tls_for_thread(m); | ||
| 424 | } catch (...) { | ||
| 425 | m.tls_index = kNoTlsIndex; | ||
| 426 | g_tls_slot_owner = nullptr; | ||
| 427 | throw; | ||
| 428 | } | ||
| 429 | } | ||
| 430 | |||
| 431 | void Loader::install_tls_for_thread(Module& m) { | ||
| 432 | if (m.tls_index == kNoTlsIndex) return; | ||
| 433 | if (g_thread_tls_module == &m) return; | ||
| 434 | if (g_thread_tls_module) | ||
| 435 | throw std::runtime_error("another manually mapped module's TLS is already installed in this thread"); | ||
| 436 | |||
| 437 | const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill; | ||
| 438 | if (!total) return; | ||
| 439 | void** slots = module_tls_slots(); | ||
| 440 | if (!slots || m.tls_index >= kMaxModuleTlsSlots) | ||
| 441 | throw std::runtime_error(m.name + ": cannot install TLS in this thread"); | ||
| 442 | |||
| 443 | void* block = VirtualAlloc(nullptr, static_cast<SIZE_T>(total), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); | ||
| 444 | if (!block) throw std::runtime_error(m.name + ": TLS block allocation failed"); | ||
| 445 | if (m.tls_raw_size) std::memcpy(block, m.tls_template, m.tls_raw_size); | ||
| 446 | if (m.tls_zero_fill) | ||
| 447 | std::memset(static_cast<uint8_t*>(block) + m.tls_raw_size, 0, m.tls_zero_fill); | ||
| 448 | |||
| 449 | void* saved = slots[m.tls_index]; | ||
| 450 | slots[m.tls_index] = block; | ||
| 451 | g_thread_tls_module = &m; | ||
| 452 | g_thread_tls_saved = saved; | ||
| 453 | g_thread_tls_block = block; | ||
| 454 | if (!m.tls_block) { | ||
| 455 | m.tls_block = block; | ||
| 456 | m.tls_saved_block = saved; | ||
| 457 | } | ||
| 458 | } | ||
| 459 | |||
| 460 | void Loader::uninstall_tls_for_thread(Module& m) { | ||
| 461 | if (g_thread_tls_module != &m) return; | ||
| 462 | void** slots = module_tls_slots(); | ||
| 463 | if (slots && m.tls_index < kMaxModuleTlsSlots && slots[m.tls_index] == g_thread_tls_block) | ||
| 464 | slots[m.tls_index] = g_thread_tls_saved; | ||
| 465 | if (m.tls_block == g_thread_tls_block) { | ||
| 466 | m.tls_block = nullptr; | ||
| 467 | m.tls_saved_block = nullptr; | ||
| 468 | } | ||
| 469 | VirtualFree(g_thread_tls_block, 0, MEM_RELEASE); | ||
| 470 | g_thread_tls_module = nullptr; | ||
| 471 | g_thread_tls_saved = nullptr; | ||
| 472 | g_thread_tls_block = nullptr; | ||
| 473 | } | ||
| 474 | |||
| 475 | void Loader::run_tls_callbacks(Module& m, uint32_t reason) { | ||
| 476 | auto* tls = tls_directory(m); | ||
| 477 | if (!tls || !tls->AddressOfCallBacks) return; | ||
| 478 | const uint64_t table_rva = rva_in(m, tls->AddressOfCallBacks, "the TLS callback table"); | ||
| 479 | // The callback table has no length field: it ends at a zero entry, so every step is checked against the image. | ||
| 480 | for (uint64_t i = 0;; ++i) { | ||
| 481 | const uint64_t entry_rva = table_rva + i * sizeof(uint64_t); | ||
| 482 | require_range(m.name, entry_rva, sizeof(uint64_t), m.size, "a TLS callback table entry"); | ||
| 483 | const uint64_t fn = *at<uint64_t>(m.base, static_cast<uint32_t>(entry_rva)); | ||
| 484 | if (!fn) break; | ||
| 485 | auto callback = | ||
| 486 | reinterpret_cast<PIMAGE_TLS_CALLBACK>(m.base + rva_in(m, fn, "a TLS callback")); | ||
| 487 | callback(m.base, static_cast<DWORD>(reason), nullptr); | ||
| 488 | } | ||
| 489 | } | ||
| 490 | |||
| 242 | void Loader::parse_exports(Module& m) { | 491 | void Loader::parse_exports(Module& m) { |
| 243 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); | 492 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); |
| 244 | auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; | 493 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXPORT); |
| 245 | if (!dir.Size) return; | 494 | if (!dir.Size) return; |
| 246 | require_range(m.name, dir.VirtualAddress, sizeof(IMAGE_EXPORT_DIRECTORY), m.size, "the export directory"); | 495 | require_range(m.name, dir.VirtualAddress, sizeof(IMAGE_EXPORT_DIRECTORY), m.size, "the export directory"); |
| 247 | auto* ed = at<IMAGE_EXPORT_DIRECTORY>(m.base, dir.VirtualAddress); | 496 | auto* ed = at<IMAGE_EXPORT_DIRECTORY>(m.base, dir.VirtualAddress); |
| @@ -281,12 +530,23 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d | |||
| 281 | auto dot = spec.rfind('.'); | 530 | auto dot = spec.rfind('.'); |
| 282 | if (dot == std::string::npos || dot == 0 || dot + 1 >= spec.size()) return nullptr; | 531 | if (dot == std::string::npos || dot == 0 || dot + 1 >= spec.size()) return nullptr; |
| 283 | const std::string module = spec.substr(0, dot), symbol = spec.substr(dot + 1); | 532 | const std::string module = spec.substr(0, dot), symbol = spec.substr(dot + 1); |
| 533 | |||
| 534 | // A forwarder can name a module the loader shims. Shims take precedence over a bundled or host copy, exactly as | ||
| 535 | // they do for a direct import in resolve(); without this, a forwarded xmem or d3d12_xs call becomes a failure thunk. | ||
| 536 | std::string shim_key = lower(module); | ||
| 537 | if (shim_key.size() < 4 || shim_key.compare(shim_key.size() - 4, 4, ".dll") != 0) shim_key += ".dll"; | ||
| 538 | if (void* p = shims::find(shim_key, symbol)) { | ||
| 539 | binding = Binding::Shim; | ||
| 540 | return p; | ||
| 541 | } | ||
| 542 | |||
| 284 | const bool by_ordinal = symbol.size() > 1 && symbol[0] == '#'; | 543 | const bool by_ordinal = symbol.size() > 1 && symbol[0] == '#'; |
| 285 | uint32_t ordinal = 0; | 544 | uint32_t ordinal = 0; |
| 286 | if (by_ordinal) { | 545 | if (by_ordinal) { |
| 287 | for (size_t i = 1; i < symbol.size(); ++i) { | 546 | for (size_t i = 1; i < symbol.size(); ++i) { |
| 288 | if (symbol[i] < '0' || symbol[i] > '9' || ordinal > 0xFFFF) return nullptr; | 547 | if (symbol[i] < '0' || symbol[i] > '9') return nullptr; |
| 289 | ordinal = ordinal * 10 + static_cast<uint32_t>(symbol[i] - '0'); | 548 | ordinal = ordinal * 10 + static_cast<uint32_t>(symbol[i] - '0'); |
| 549 | if (ordinal > 0xFFFF) return nullptr; // checked after the digit, so "#65537" can't truncate to 1 | ||
| 290 | } | 550 | } |
| 291 | } | 551 | } |
| 292 | 552 | ||
| @@ -371,7 +631,7 @@ void Loader::bind_imports(Module& m) { | |||
| 371 | } | 631 | } |
| 372 | }; | 632 | }; |
| 373 | 633 | ||
| 374 | auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; | 634 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_IMPORT); |
| 375 | if (dir.Size) { | 635 | if (dir.Size) { |
| 376 | for (uint64_t i = 0;; ++i) { | 636 | for (uint64_t i = 0;; ++i) { |
| 377 | uint64_t rva = dir.VirtualAddress + i * sizeof(IMAGE_IMPORT_DESCRIPTOR); | 637 | uint64_t rva = dir.VirtualAddress + i * sizeof(IMAGE_IMPORT_DESCRIPTOR); |
| @@ -384,7 +644,7 @@ void Loader::bind_imports(Module& m) { | |||
| 384 | } | 644 | } |
| 385 | } | 645 | } |
| 386 | // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. | 646 | // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. |
| 387 | auto& ddir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT]; | 647 | const auto ddir = directory(nt, IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT); |
| 388 | if (ddir.Size) { | 648 | if (ddir.Size) { |
| 389 | for (uint64_t i = 0;; ++i) { | 649 | for (uint64_t i = 0;; ++i) { |
| 390 | uint64_t rva = ddir.VirtualAddress + i * sizeof(IMAGE_DELAYLOAD_DESCRIPTOR); | 650 | uint64_t rva = ddir.VirtualAddress + i * sizeof(IMAGE_DELAYLOAD_DESCRIPTOR); |
| @@ -398,9 +658,12 @@ void Loader::bind_imports(Module& m) { | |||
| 398 | if (!d->ImportAddressTableRVA) | 658 | if (!d->ImportAddressTableRVA) |
| 399 | throw std::runtime_error(m.name + ": a delay-import descriptor has no address table"); | 659 | throw std::runtime_error(m.name + ": a delay-import descriptor has no address table"); |
| 400 | std::string dll = read_string(m.name, m.base, m.size, d->DllNameRVA, "a delay-imported DLL name"); | 660 | std::string dll = read_string(m.name, m.base, m.size, d->DllNameRVA, "a delay-imported DLL name"); |
| 401 | // The name table is optional: without it, entries are read back through the address table itself. | 661 | // Without a name table the IAT still holds delay thunks, not import names, so there is no symbol to bind |
| 402 | bind_thunks(dll, d->ImportNameTableRVA ? d->ImportNameTableRVA : d->ImportAddressTableRVA, | 662 | // eagerly. Every MSVC delay descriptor and every System32 DLL has one; reject the form instead of reading |
| 403 | d->ImportAddressTableRVA); | 663 | // thunk addresses as name RVAs. |
| 664 | if (!d->ImportNameTableRVA) | ||
| 665 | throw std::runtime_error(m.name + ": a delay-import descriptor has no name table"); | ||
| 666 | bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA); | ||
| 404 | } | 667 | } |
| 405 | } | 668 | } |
| 406 | } | 669 | } |