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:
authorkirigayakazima <46666711+kirigayakazima@users.noreply.github.com>2026-11-29 11:02:12 +0800
committerkirigayakazima <46666711+kirigayakazima@users.noreply.github.com>2026-11-29 11:02:12 +0800
commit85b87608fa3bc7aef8606a0debbd794b7e760f9f (patch)
tree17f969b3144832a832e5017152d196938aef64c2 /runtime/src/pe_loader.cpp
parentbb27da204adb88f5d3c1178583f460dd7483c632 (diff)
parentc8bf0e7b6568f471b42540010e335ca6413d4c58 (diff)
Merge current main and reconcile glb_writer coverage
Diffstat (limited to 'runtime/src/pe_loader.cpp')
-rw-r--r--runtime/src/pe_loader.cpp771
1 files changed, 647 insertions, 124 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index c29a288a9..303469b06 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 <share.h>
5#include <tlhelp32.h> 6#include <tlhelp32.h>
6 7
7#include <algorithm> 8#include <algorithm>
@@ -10,7 +11,7 @@
10#include <cstdio> 11#include <cstdio>
11#include <cstdlib> 12#include <cstdlib>
12#include <cstring> 13#include <cstring>
13#include <fstream> 14#include <memory>
14#include <mutex> 15#include <mutex>
15#include <stdexcept> 16#include <stdexcept>
16#include <system_error> 17#include <system_error>
@@ -19,6 +20,10 @@
19#include "../shims/shims.h" 20#include "../shims/shims.h"
20#include "../shims/startup_trace.h" 21#include "../shims/startup_trace.h"
21#include "base_reservation.h" 22#include "base_reservation.h"
23#include "bmi_emulation.h"
24#include "clzero_patch.h"
25#include "cpu_emulation.h"
26#include "isa_jit_patch.h"
22 27
23namespace rt { 28namespace rt {
24 29
@@ -75,9 +80,16 @@ std::string path_utf8(const std::filesystem::path& path) {
75} 80}
76 81
77std::vector<uint8_t> read_file(const std::filesystem::path& p) { 82std::vector<uint8_t> read_file(const std::filesystem::path& p) {
78 std::ifstream f(p, std::ios::binary); 83 std::unique_ptr<std::FILE, decltype(&std::fclose)> file(
79 if (!f) throw std::runtime_error("cannot open " + path_utf8(p)); 84 _wfsopen(p.c_str(), L"rb", _SH_DENYNO), std::fclose);
80 return {std::istreambuf_iterator<char>(f), {}}; 85 if (!file) throw std::runtime_error("cannot open " + path_utf8(p));
86
87 std::vector<uint8_t> bytes;
88 std::array<uint8_t, 64 * 1024> block;
89 while (const auto count = std::fread(block.data(), 1, block.size(), file.get()))
90 bytes.insert(bytes.end(), block.data(), block.data() + count);
91 if (std::ferror(file.get())) throw std::runtime_error("cannot read " + path_utf8(p));
92 return bytes;
81} 93}
82 94
83template <class T> 95template <class T>
@@ -126,8 +138,29 @@ IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) {
126// reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader 138// reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader
127// clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent 139// clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent
128// module TLS index for each simultaneous module (up to kMaxMappedTlsModules). 140// module TLS index for each simultaneous module (up to kMaxMappedTlsModules).
141//
142// A mapped executable is different: MSVC code built with /GA (an EXE-only optimisation) skips _tls_index and reads
143// TEB->ThreadLocalStoragePointer[0] directly (mov rax, gs:[58h]; mov rax, [rax]), because Windows always gives the
144// process executable module TLS index 0. Measured with a `thread_local int v = 42;` EXE built /O2 /GA /MD: natively
145// tls_index=0 value=42; mapped with a helper index (6) the code still read slot 0 and printed value=0. Index 0
146// belongs to the runtime's own EXE (gta6rt.exe: a 1398-byte template when measured, no TLS callbacks; so does each
147// test EXE that links this file), and every TLS read in its disassembly goes through _tls_index (the only direct
148// gs:[58h] read is module_tls_slots below, which wants the array itself). reserve_tls_index0 therefore moves the owner
149// off index 0, once, at process start: it loads the home clone (make_home_clone_image), whose TLS template is a copy of
150// the owner's, and on the calling thread swaps slots 0 and home and writes home into the owner's _tls_index. From then on every thread the OS
151// starts has a fresh copy of the owner's template at home, which is where the owner looks, from its first instruction:
152// nothing has to run on a new thread first. Slot 0 holds a block nobody reads, which the mapped executable's copy
153// replaces (kMainImageSlot) exactly as a DLL's copy replaces a helper's, and the OS frees both slots at thread exit.
154// It has to happen before any other thread has run the owner's code: MSVC keeps &ThreadLocalStoragePointer[_tls_index]
155// across calls (zlib_inflate in shader_library.h saves it at [rbp-80h] across memset, push_back and inflate_codes, then
156// reads _Init_thread_epoch through it), so a running thread cannot be moved safely, wherever it is stopped. Such a
157// thread's TLS would also stay where it was, at index 0.
129constexpr DWORD kMaxModuleTlsSlots = 64; 158constexpr DWORD kMaxModuleTlsSlots = 64;
130constexpr size_t kMaxMappedTlsModules = 16; 159constexpr size_t kMaxMappedTlsModules = 16;
160// The slot for a mapped executable, which reads module TLS index 0 (see above). Only one at a time; a second
161// executable mapped while one is live gets an ordinary helper slot. kTlsSlotCount sizes the per-slot tables.
162constexpr size_t kMainImageSlot = kMaxMappedTlsModules;
163constexpr size_t kTlsSlotCount = kMaxMappedTlsModules + 1;
131void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); } 164void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); }
132 165
133void __cdecl on_host_thread_event(DWORD reason); 166void __cdecl on_host_thread_event(DWORD reason);
@@ -135,6 +168,7 @@ void __cdecl on_host_thread_event(DWORD reason);
135struct TlsHostModule { 168struct TlsHostModule {
136 HMODULE module = nullptr; 169 HMODULE module = nullptr;
137 DWORD index = TLS_OUT_OF_INDEXES; 170 DWORD index = TLS_OUT_OF_INDEXES;
171 bool hooked = false; // its DllMain reports thread events to on_host_thread_event
138}; 172};
139 173
140std::filesystem::path tls_host_base_path() { 174std::filesystem::path tls_host_base_path() {
@@ -167,20 +201,39 @@ struct TlsCloneRecord {
167 201
168std::mutex g_tls_alloc_mutex; 202std::mutex g_tls_alloc_mutex;
169std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{}; 203std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{};
170std::array<std::atomic<Module*>, kMaxMappedTlsModules> g_tls_slot_owners{}; 204std::array<std::atomic<Module*>, kTlsSlotCount> g_tls_slot_owners{};
171std::array<std::atomic<uint64_t>, kMaxMappedTlsModules> g_tls_slot_generations{}; 205std::array<std::atomic<uint64_t>, kTlsSlotCount> g_tls_slot_generations{};
172std::atomic<uint64_t> g_next_tls_generation{1}; 206std::atomic<uint64_t> g_next_tls_generation{1};
173std::vector<TlsCloneRecord> g_tls_clones; 207// Allocated with the first clone and never destroyed: cleanup_tls_clones_at_exit runs from the atexit table, and a
208// static vector's destructor (registered when its dynamic initializer ran) could run before it. Under
209// g_tls_alloc_mutex, as are its records.
210std::vector<TlsCloneRecord>* g_tls_clones = nullptr;
211
212// The move of module TLS index 0 (see kMainImageSlot): done at most once, by reserve_tls_index0 under
213// g_tls_alloc_mutex. `why` is the reason it was not done, for the executable that then maps with a helper index.
214// Constant-initialized only (no std::string): gta6rt reserves from a CRT initializer that runs before the dynamic
215// initializers of this file, which would otherwise reset what it wrote.
216struct Index0Move {
217 bool moved = false;
218 bool traced = false; // the startup trace opens after the move; the first executable map reports it
219 TlsHostModule home; // the clone whose index holds the owner's TLS from now on; never freed
220 char owner[260] = {}; // UTF-8 file name of the image that held index 0
221 char why[160] = "reserve_tls_index0 was not called at process start";
222};
223Index0Move g_index0;
174 224
175// Frees every TLS helper clone this process loaded and deletes its files. load() registers the wrapper with atexit; 225// Frees every TLS helper clone recorded for a mapped DLL's slot and deletes its files. ensure_tls_host registers the
176// the --run path in main() must also call this directly before ExitProcess, which skips the atexit table. Call it 226// wrapper with atexit when it records the first clone; the --run path in main() must also call this directly before
177// only when no mapped code can run again: it unmaps the helper images. 227// ExitProcess, which skips the atexit table. Call it only when no mapped code can run again: it unmaps the helper
228// images. The home clone is not recorded (reserve_index0): it stays loaded, so its file outlives the process and the
229// next run's sweep deletes it.
178void cleanup_tls_clones_internal() { 230void cleanup_tls_clones_internal() {
179 for (const auto& rec : g_tls_clones) { 231 if (!g_tls_clones) return;
232 for (const auto& rec : *g_tls_clones) {
180 if (rec.module) FreeLibrary(rec.module); 233 if (rec.module) FreeLibrary(rec.module);
181 if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); 234 if (!rec.path.empty()) DeleteFileW(rec.path.c_str());
182 } 235 }
183 g_tls_clones.clear(); 236 g_tls_clones->clear();
184} 237}
185 238
186void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); } 239void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); }
@@ -204,10 +257,14 @@ DWORD clone_owner_pid(const wchar_t* name) {
204bool process_alive(DWORD pid) { 257bool process_alive(DWORD pid) {
205 // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the 258 // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the
206 // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID. 259 // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID.
260 // OpenProcess also succeeds on a process that has ended while another process still holds a handle to it (a
261 // parent waiting on its exit code, as CMake's execute_process does), so the exit code decides.
207 HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); 262 HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
208 if (!p) return false; 263 if (!p) return false;
264 DWORD code = 0;
265 const bool alive = !GetExitCodeProcess(p, &code) || code == STILL_ACTIVE;
209 CloseHandle(p); 266 CloseHandle(p);
210 return true; 267 return alive;
211} 268}
212 269
213// Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a 270// Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a
@@ -262,45 +319,66 @@ TlsHostModule load_tls_host_image(const std::filesystem::path& path, bool hook_t
262 if (hook_thread_events) { 319 if (hook_thread_events) {
263 // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots. 320 // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots.
264 using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); 321 using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD));
265 if (auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"))) 322 auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"));
323 if (set) {
266 set(&on_host_thread_event); 324 set(&on_host_thread_event);
325 host.hooked = true;
326 }
267 } 327 }
268 return host; 328 return host;
269} 329}
270 330
271// Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock). 331// The primary helper: slot 0's index, and the only helper whose DllMain reports thread events (on_host_thread_event
272TlsHostModule ensure_tls_host(size_t slot) { 332// covers every slot). Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the
273 if (slot >= kMaxMappedTlsModules) return {}; 333// Windows loader lock).
274 if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot]; 334// A helper without the thread-event export is refused: no thread started later would get its copies.
275 335bool ensure_primary_tls_host() {
336 if (g_tls_hosts[0].index != TLS_OUT_OF_INDEXES) return true;
276 const std::filesystem::path primary = tls_host_base_path(); 337 const std::filesystem::path primary = tls_host_base_path();
277 if (primary.empty()) return {}; 338 if (primary.empty()) return false;
278 339 TlsHostModule host = load_tls_host_image(primary, true);
279 if (slot == 0) { 340 if (host.index != TLS_OUT_OF_INDEXES && !host.hooked) {
280 g_tls_hosts[0] = load_tls_host_image(primary, true); 341 FreeLibrary(host.module);
281 return g_tls_hosts[0]; 342 return false;
282 }
283
284 // Ensure slot 0 is loaded first so thread attach/detach events are hooked.
285 if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) {
286 g_tls_hosts[0] = load_tls_host_image(primary, true);
287 if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) return {};
288 } 343 }
344 g_tls_hosts[0] = host;
345 return host.index != TLS_OUT_OF_INDEXES;
346}
289 347
348// Copies gta6rt_tls_host.dll (or writes `image`, a changed copy of it) to "leonida_tls_host_<pid>_<tag>.dll" in the
349// clone directory and loads it, so the OS gives the copy an index of its own. On failure the file is gone again and
350// the result has no index. The caller records the clone (g_tls_clones) if it is to be freed at exit. Same locking rule
351// as ensure_primary_tls_host.
352TlsHostModule load_tls_host_clone(const std::wstring& tag, std::filesystem::path& clone_path,
353 const std::vector<uint8_t>* image = nullptr) {
354 const std::filesystem::path primary = tls_host_base_path();
355 if (primary.empty()) return {};
290 // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem). 356 // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem).
291 const std::filesystem::path dir = tls_host_clone_dir(); 357 const std::filesystem::path dir = tls_host_clone_dir();
292 static bool swept = false; 358 static bool swept = false;
293 if (!swept) { 359 if (!swept) {
294 swept = true; 360 swept = true;
295 sweep_stale_tls_clones(dir); 361 sweep_stale_tls_clones(dir);
296 std::atexit(&cleanup_tls_clones_at_exit);
297 } 362 }
298 const std::wstring name = 363 const std::wstring name = L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + tag + L".dll";
299 L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll"; 364 clone_path = dir / name;
300 const std::filesystem::path clone_path = dir / name;
301 // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll. 365 // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll.
302 const std::filesystem::path staging = clone_path.wstring() + L".new"; 366 const std::filesystem::path staging = clone_path.wstring() + L".new";
303 if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) return {}; 367 if (image) {
368 HANDLE out =
369 CreateFileW(staging.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
370 if (out == INVALID_HANDLE_VALUE) return {};
371 DWORD written = 0;
372 const bool ok = WriteFile(out, image->data(), static_cast<DWORD>(image->size()), &written, nullptr) &&
373 written == image->size();
374 CloseHandle(out);
375 if (!ok) {
376 DeleteFileW(staging.c_str());
377 return {};
378 }
379 } else if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) {
380 return {};
381 }
304 382
305 // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename 383 // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename
306 // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone 384 // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone
@@ -320,18 +398,34 @@ TlsHostModule ensure_tls_host(size_t slot) {
320 TlsHostModule loaded = load_tls_host_image(clone_path, false); 398 TlsHostModule loaded = load_tls_host_image(clone_path, false);
321 CloseHandle(guard); 399 CloseHandle(guard);
322 400
323 if (loaded.index == TLS_OUT_OF_INDEXES) { 401 if (loaded.index == TLS_OUT_OF_INDEXES) DeleteFileW(clone_path.c_str());
402 return loaded;
403}
404
405// Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock).
406TlsHostModule ensure_tls_host(size_t slot) {
407 if (slot >= kMaxMappedTlsModules) return {};
408 if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot];
409 // Slot 0 is the primary helper; it is loaded first in any case so thread attach/detach events are hooked.
410 if (!ensure_primary_tls_host()) return {};
411 if (slot == 0) return g_tls_hosts[0];
412
413 std::filesystem::path clone_path;
414 TlsHostModule loaded = load_tls_host_clone(std::to_wstring(slot), clone_path);
415 if (loaded.index == TLS_OUT_OF_INDEXES) return {};
416 // Index 0 is the runtime EXE's, and after the move the home clone's index holds that EXE's TLS.
417 bool taken = loaded.index == 0 || loaded.index == g_index0.home.index;
418 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) taken |= i != slot && g_tls_hosts[i].index == loaded.index;
419 if (taken) {
420 FreeLibrary(loaded.module);
324 DeleteFileW(clone_path.c_str()); 421 DeleteFileW(clone_path.c_str());
325 return {}; 422 return {};
326 } 423 }
327 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { 424 if (!g_tls_clones) {
328 if (i != slot && g_tls_hosts[i].index == loaded.index) { 425 g_tls_clones = new std::vector<TlsCloneRecord>;
329 FreeLibrary(loaded.module); 426 std::atexit(&cleanup_tls_clones_at_exit);
330 DeleteFileW(clone_path.c_str());
331 return {};
332 }
333 } 427 }
334 g_tls_clones.push_back({loaded.module, clone_path}); 428 g_tls_clones->push_back({loaded.module, clone_path});
335 g_tls_hosts[slot] = loaded; 429 g_tls_hosts[slot] = loaded;
336 return g_tls_hosts[slot]; 430 return g_tls_hosts[slot];
337} 431}
@@ -347,7 +441,7 @@ struct ThreadTlsSlot {
347}; 441};
348 442
349// Per-thread installation state for each reserved TLS slot. 443// Per-thread installation state for each reserved TLS slot.
350thread_local std::array<ThreadTlsSlot, kMaxMappedTlsModules> g_thread_tls_slots{}; 444thread_local std::array<ThreadTlsSlot, kTlsSlotCount> g_thread_tls_slots{};
351 445
352// Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared 446// Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared
353// in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows 447// in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows
@@ -366,10 +460,185 @@ struct ExclusiveTlsLock {
366 ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete; 460 ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete;
367}; 461};
368 462
463// gta6rt_tls_host.dll's exports that the home clone's TLS directory is pointed at (tls_host.cpp): a zero array in its
464// .rdata and that array's size.
465constexpr char kHomeTemplateExport[] = "gta6rt_tls_home_template";
466constexpr char kHomeTemplateSizeExport[] = "gta6rt_tls_home_template_size";
467
468// File offset of `len` bytes at `rva` in an image file held in memory, or SIZE_MAX when they are not all inside one
469// section's raw data.
470size_t file_offset(const std::vector<uint8_t>& file, const IMAGE_NT_HEADERS64* nt, uint64_t rva, uint64_t len) {
471 const auto* sec = IMAGE_FIRST_SECTION(nt);
472 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) {
473 if (reinterpret_cast<const uint8_t*>(sec + 1) > file.data() + file.size()) break;
474 if (rva < sec->VirtualAddress || rva + len > static_cast<uint64_t>(sec->VirtualAddress) + sec->SizeOfRawData)
475 continue;
476 const uint64_t off = sec->PointerToRawData + (rva - sec->VirtualAddress);
477 return off + len <= file.size() ? static_cast<size_t>(off) : SIZE_MAX;
478 }
479 return SIZE_MAX;
480}
481
482// The RVA of a named export in an image file held in memory, 0 when it has none.
483uint32_t file_export(const std::vector<uint8_t>& file, const IMAGE_NT_HEADERS64* nt, const char* wanted) {
484 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXPORT);
485 const size_t ed_off = file_offset(file, nt, dir.VirtualAddress, sizeof(IMAGE_EXPORT_DIRECTORY));
486 if (!dir.Size || ed_off == SIZE_MAX) return 0;
487 const auto* ed = reinterpret_cast<const IMAGE_EXPORT_DIRECTORY*>(file.data() + ed_off);
488 const size_t names = file_offset(file, nt, ed->AddressOfNames, uint64_t{4} * ed->NumberOfNames);
489 const size_t ords = file_offset(file, nt, ed->AddressOfNameOrdinals, uint64_t{2} * ed->NumberOfNames);
490 const size_t funcs = file_offset(file, nt, ed->AddressOfFunctions, uint64_t{4} * ed->NumberOfFunctions);
491 if (names == SIZE_MAX || ords == SIZE_MAX || funcs == SIZE_MAX) return 0;
492 const size_t wanted_len = std::strlen(wanted) + 1;
493 for (uint32_t i = 0; i < ed->NumberOfNames; ++i) {
494 uint32_t name_rva, func_rva;
495 uint16_t ord;
496 std::memcpy(&name_rva, file.data() + names + 4 * i, 4);
497 std::memcpy(&ord, file.data() + ords + 2 * i, 2);
498 const size_t name = file_offset(file, nt, name_rva, wanted_len);
499 if (name == SIZE_MAX || std::memcmp(file.data() + name, wanted, wanted_len) != 0) continue;
500 if (ord >= ed->NumberOfFunctions) return 0;
501 std::memcpy(&func_rva, file.data() + funcs + 4 * ord, 4);
502 return func_rva;
503 }
504 return 0;
505}
506
507// Turns gta6rt_tls_host.dll's bytes into the home clone: its TLS directory now covers gta6rt_tls_home_template, which
508// starts with a copy of the owner's template (taken from the mapped owner, so its pointers are already relocated; the
509// array itself has no relocations), and takes the owner's alignment. The OS then gives every thread, at the home
510// index, a block that is a fresh copy of the owner's TLS. The zero fill goes into the covered range too:
511// LdrpAllocateTls allocates and copies End - Start only (Windows 11 26300) and ignores SizeOfZeroFill. The directory's
512// Start and End have base relocations, so they follow the clone wherever it loads. Empty on success, else why not.
513std::string make_home_clone_image(std::vector<uint8_t>& file, const IMAGE_TLS_DIRECTORY64& owner) {
514 if (file.size() < sizeof(IMAGE_DOS_HEADER)) return "gta6rt_tls_host.dll is truncated";
515 const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(file.data());
516 if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew < 0 ||
517 static_cast<size_t>(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size())
518 return "gta6rt_tls_host.dll has no PE header";
519 auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew);
520 if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC)
521 return "gta6rt_tls_host.dll is not a 64-bit image";
522 const uint32_t array_rva = file_export(file, nt, kHomeTemplateExport);
523 const uint32_t size_rva = file_export(file, nt, kHomeTemplateSizeExport);
524 const size_t size_off = file_offset(file, nt, size_rva, sizeof(uint32_t));
525 if (!array_rva || !size_rva || size_off == SIZE_MAX)
526 return "gta6rt_tls_host.dll has no gta6rt_tls_home_template";
527 uint32_t capacity;
528 std::memcpy(&capacity, file.data() + size_off, sizeof(capacity));
529 const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData;
530 const uint64_t total = raw + owner.SizeOfZeroFill;
531 if (owner.EndAddressOfRawData < owner.StartAddressOfRawData || total > capacity)
532 return "the owner's TLS (" + std::to_string(total) + " bytes) does not fit gta6rt_tls_home_template (" +
533 std::to_string(capacity) + " bytes)";
534 const size_t array_off = file_offset(file, nt, array_rva, capacity);
535 const auto tls_dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS);
536 const size_t tls_off = file_offset(file, nt, tls_dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64));
537 if (array_off == SIZE_MAX || !tls_dir.Size || tls_off == SIZE_MAX)
538 return "gta6rt_tls_host.dll's TLS directory or home template lies outside its file";
539 std::memcpy(file.data() + array_off, reinterpret_cast<const void*>(owner.StartAddressOfRawData), raw);
540 std::memset(file.data() + array_off + raw, 0, capacity - raw);
541 auto* tls = reinterpret_cast<IMAGE_TLS_DIRECTORY64*>(file.data() + tls_off);
542 tls->StartAddressOfRawData = nt->OptionalHeader.ImageBase + array_rva;
543 tls->EndAddressOfRawData = tls->StartAddressOfRawData + total;
544 tls->SizeOfZeroFill = 0;
545 tls->Characteristics =
546 (tls->Characteristics & ~IMAGE_SCN_ALIGN_MASK) | (owner.Characteristics & IMAGE_SCN_ALIGN_MASK);
547 return {};
548}
549
550std::string module_file_name(HMODULE module) {
551 wchar_t path[MAX_PATH];
552 const DWORD n = GetModuleFileNameW(module, path, MAX_PATH);
553 if (!n || n >= MAX_PATH) return "?";
554 const wchar_t* name = path;
555 for (const wchar_t* p = path; *p; ++p)
556 if (*p == L'\\' || *p == L'/') name = p + 1;
557 const int bytes = WideCharToMultiByte(CP_UTF8, 0, name, -1, nullptr, 0, nullptr, nullptr);
558 if (bytes <= 1) return "?";
559 std::string out(static_cast<size_t>(bytes - 1), '\0');
560 WideCharToMultiByte(CP_UTF8, 0, name, -1, out.data(), bytes, nullptr, nullptr);
561 return out;
562}
563
564// The move on the calling thread, kept apart so that no frame of reserve_index0 holds a slot address across it. After
565// it the owner's live block is at `home` and slot 0 holds the home clone's fresh copy, which nothing reads.
566__declspec(noinline) void move_index0_on_this_thread(DWORD* owner_index, DWORD home) {
567 void** slots = module_tls_slots();
568 std::swap(slots[0], slots[home]);
569 *owner_index = home;
570}
571
572// See reserve_tls_index0. Empty on success, else why not; nothing has changed then. g_tls_alloc_mutex held. It reads
573// no thread_local data and runs no code that does, before or after the move.
574std::string reserve_index0() {
575 // Windows gives index 0 to the process executable when it has TLS; a DLL can only hold it in a process whose EXE
576 // has none, and a DLL that is still loading or was loaded without its references resolved shows 0 too.
577 const HMODULE exe = GetModuleHandleW(nullptr);
578 auto* base = reinterpret_cast<uint8_t*>(exe);
579 auto* nt = at<IMAGE_NT_HEADERS64>(base, reinterpret_cast<IMAGE_DOS_HEADER*>(base)->e_lfanew);
580 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS);
581 if (!dir.Size || !dir.VirtualAddress) return "the process executable has no TLS, so index 0 is not its";
582 const IMAGE_TLS_DIRECTORY64 owner = *at<IMAGE_TLS_DIRECTORY64>(base, dir.VirtualAddress);
583 auto* owner_index = reinterpret_cast<DWORD*>(owner.AddressOfIndex);
584 if (!owner_index) return "the process executable's TLS directory has no index";
585 if (*owner_index != 0) return "the process executable's _tls_index is " + std::to_string(*owner_index) + ", not 0";
586 if (!module_tls_slots()) return "this thread has no TLS array";
587 if (!ensure_primary_tls_host())
588 return "gta6rt_tls_host.dll is missing, has no module TLS index or lacks gta6rt_tls_host_set_thread_event";
589
590 std::vector<uint8_t> image;
591 try {
592 image = read_file(tls_host_base_path());
593 } catch (const std::exception& e) {
594 return e.what();
595 }
596 if (std::string why = make_home_clone_image(image, owner); !why.empty()) return why;
597 std::filesystem::path path;
598 const TlsHostModule home = load_tls_host_clone(L"home", path, &image);
599 if (home.index == TLS_OUT_OF_INDEXES) return "the home clone of gta6rt_tls_host.dll cannot be loaded";
600 auto drop = [&](std::string why) {
601 FreeLibrary(home.module); // safe until the move below: nothing lives at its index yet
602 DeleteFileW(path.c_str());
603 return why;
604 };
605 bool taken = home.index == 0 || home.index >= kMaxModuleTlsSlots;
606 for (const auto& host : g_tls_hosts) taken |= host.index == home.index;
607 if (taken) return drop("the home clone got an unusable module TLS index");
608 // The OS must have taken the changed directory: the mapped clone's template is the owner's, at full size.
609 auto* home_base = reinterpret_cast<uint8_t*>(home.module);
610 auto* home_nt = at<IMAGE_NT_HEADERS64>(home_base, reinterpret_cast<IMAGE_DOS_HEADER*>(home_base)->e_lfanew);
611 const auto* home_tls =
612 at<IMAGE_TLS_DIRECTORY64>(home_base, directory(home_nt, IMAGE_DIRECTORY_ENTRY_TLS).VirtualAddress);
613 const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData;
614 if (home_tls->EndAddressOfRawData - home_tls->StartAddressOfRawData != raw + owner.SizeOfZeroFill ||
615 std::memcmp(reinterpret_cast<const void*>(home_tls->StartAddressOfRawData),
616 reinterpret_cast<const void*>(owner.StartAddressOfRawData), raw) != 0)
617 return drop("the home clone's mapped TLS template is not the owner's");
618
619 // Everything that can throw comes first: past the move this records the result and nothing more.
620 const std::string name = module_file_name(exe);
621 // _tls_index sits in .data; made writable first in case a linker merged it into a read-only section.
622 DWORD old_protect = 0;
623 if (!VirtualProtect(owner_index, sizeof(DWORD), PAGE_READWRITE, &old_protect))
624 return drop("the owner's _tls_index cannot be written");
625 move_index0_on_this_thread(owner_index, home.index);
626 VirtualProtect(owner_index, sizeof(DWORD), old_protect, &old_protect);
627
628 // Kept loaded for the process lifetime: FreeLibrary would make the OS free every thread's block at its index, the
629 // owner's from now on. Not in g_tls_clones for that reason. Its file cannot be deleted while it is mapped
630 // (DeleteFileW and a POSIX-semantics delete both fail with ERROR_ACCESS_DENIED on Windows 11), so it stays until
631 // a later run's sweep.
632 g_index0.home = home;
633 std::snprintf(g_index0.owner, sizeof(g_index0.owner), "%s", name.c_str());
634 g_index0.moved = true;
635 return {};
636}
637
369// Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this 638// Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this
370// thread's record, so it also works after the module that installed the copy is gone. 639// thread's record, so it also works after the module that installed the copy is gone.
371void release_thread_slot(size_t slot) { 640void release_thread_slot(size_t slot) {
372 if (slot >= kMaxMappedTlsModules) return; 641 if (slot >= kTlsSlotCount) return;
373 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 642 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
374 if (!entry.module && !entry.block) return; 643 if (!entry.module && !entry.block) return;
375 if (entry.ga_view) { 644 if (entry.ga_view) {
@@ -438,7 +707,7 @@ void** make_ga_view(const Module& m, void* block) {
438} 707}
439 708
440void install_thread_block(Module& m) { 709void install_thread_block(Module& m) {
441 if (m.tls_slot >= kMaxMappedTlsModules) return; 710 if (m.tls_slot >= kTlsSlotCount) return;
442 const size_t slot = m.tls_slot; 711 const size_t slot = m.tls_slot;
443 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 712 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
444 if (entry.module == &m && entry.generation == m.tls_generation) return; 713 if (entry.module == &m && entry.generation == m.tls_generation) return;
@@ -530,7 +799,7 @@ bool ga_tls_patch_enabled() {
530} 799}
531 800
532void uninstall_thread_block(Module& m) { 801void uninstall_thread_block(Module& m) {
533 if (m.tls_slot >= kMaxMappedTlsModules) return; 802 if (m.tls_slot >= kTlsSlotCount) return;
534 const size_t slot = m.tls_slot; 803 const size_t slot = m.tls_slot;
535 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 804 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
536 if (entry.module != &m || entry.generation != m.tls_generation) return; 805 if (entry.module != &m || entry.generation != m.tls_generation) return;
@@ -697,7 +966,7 @@ constexpr size_t kMaxEndedThreads = 1024;
697// load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done. 966// load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done.
698void install_on_existing_threads(Module& m) { 967void install_on_existing_threads(Module& m) {
699 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill; 968 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill;
700 if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kMaxMappedTlsModules) return; 969 if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kTlsSlotCount) return;
701 // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which 970 // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which
702 // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours. 971 // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours.
703 if (!query_thread_fn()) return; 972 if (!query_thread_fn()) return;
@@ -882,7 +1151,11 @@ void release_existing_blocks_of_this_thread() {
882// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under 1151// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under
883// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an 1152// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an
884// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events 1153// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events
885// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. 1154// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. Windows allocates
1155// every module's block before the first DllMain of a new thread, and runs an EXE's TLS callbacks after every DllMain,
1156// for attach and for detach (measured on Windows 11 26300). So attach installs all copies first and then runs the
1157// callbacks, the DLL slots in order and the executable's last; detach runs the DLL slots in reverse and then the
1158// executable's slot, each releasing its copy after its callbacks.
886void __cdecl on_host_thread_event(DWORD reason) { 1159void __cdecl on_host_thread_event(DWORD reason) {
887 SharedTlsLock lock; 1160 SharedTlsLock lock;
888 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events 1161 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events
@@ -893,14 +1166,25 @@ void __cdecl on_host_thread_event(DWORD reason) {
893 } catch (const std::exception& e) { 1166 } catch (const std::exception& e) {
894 std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what()); 1167 std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what());
895 } 1168 }
896 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { 1169 std::array<Module*, kTlsSlotCount> installed{};
1170 for (size_t slot = 0; slot < kTlsSlotCount; ++slot) {
897 Module* m = g_tls_slot_owners[slot].load(); 1171 Module* m = g_tls_slot_owners[slot].load();
898 if (!m) continue; 1172 if (!m) continue;
899 try { 1173 try {
900 install_thread_block(*m); 1174 install_thread_block(*m);
901 if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); 1175 installed[slot] = m;
1176 } catch (const std::exception& e) {
1177 // The thread runs on without this module's TLS (and its callbacks); later slots still get theirs.
1178 std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(),
1179 e.what());
1180 }
1181 }
1182 for (size_t slot = 0; slot < kTlsSlotCount; ++slot) {
1183 Module* m = installed[slot];
1184 if (!m || !m->initialised) continue;
1185 try {
1186 run_callbacks(*m, DLL_THREAD_ATTACH);
902 } catch (const std::exception& e) { 1187 } catch (const std::exception& e) {
903 // The thread runs on without this module's TLS; later slots still get theirs.
904 std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), 1188 std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(),
905 e.what()); 1189 e.what());
906 } 1190 }
@@ -913,7 +1197,8 @@ void __cdecl on_host_thread_event(DWORD reason) {
913 } catch (const std::exception& e) { 1197 } catch (const std::exception& e) {
914 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what()); 1198 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what());
915 } 1199 }
916 for (size_t i = kMaxMappedTlsModules; i-- > 0;) { 1200 for (size_t step = 0; step < kTlsSlotCount; ++step) {
1201 const size_t i = step < kMaxMappedTlsModules ? kMaxMappedTlsModules - 1 - step : kMainImageSlot;
917 Module* m = g_tls_slot_owners[i].load(); 1202 Module* m = g_tls_slot_owners[i].load();
918 if (m && g_thread_tls_slots[i].module == m && 1203 if (m && g_thread_tls_slots[i].module == m &&
919 g_thread_tls_slots[i].generation == m->tls_generation) { 1204 g_thread_tls_slots[i].generation == m->tls_generation) {
@@ -1017,6 +1302,26 @@ void redirect_pc_to_file_header_at(const void* resolved) {
1017// Declared in pe_loader.h; the body needs the internal clone registry above. 1302// Declared in pe_loader.h; the body needs the internal clone registry above.
1018void cleanup_tls_clones() { cleanup_tls_clones_internal(); } 1303void cleanup_tls_clones() { cleanup_tls_clones_internal(); }
1019 1304
1305bool reserve_tls_index0(std::string* why) {
1306 std::lock_guard alloc_lock(g_tls_alloc_mutex);
1307 static bool attempted = false; // once: a later attempt could meet threads that already run this EXE's code
1308 if (!attempted) {
1309 attempted = true;
1310 // A throw (std::filesystem::temp_directory_path when GetTempPathW fails, an allocation) is a failed
1311 // reservation like any other: gta6rt calls this before main, where an exception would end it with no message.
1312 try {
1313 const std::string reason = reserve_index0();
1314 std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", reason.c_str());
1315 } catch (const std::exception& e) {
1316 std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", e.what());
1317 } catch (...) {
1318 std::snprintf(g_index0.why, sizeof(g_index0.why), "an unknown error while reserving it");
1319 }
1320 }
1321 if (why) *why = g_index0.moved ? std::string() : std::string(g_index0.why);
1322 return g_index0.moved;
1323}
1324
1020namespace { 1325namespace {
1021bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { 1326bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) {
1022 return static_cast<Loader*>(ctx)->find_address(address, module, rva); 1327 return static_cast<Loader*>(ctx)->find_address(address, module, rva);
@@ -1046,6 +1351,15 @@ void* bundled_load_w(void* ctx, const std::wstring& basename, uint32_t flags, bo
1046 return static_cast<Loader*>(ctx)->load_runtime_module_w(basename, flags, handled); 1351 return static_cast<Loader*>(ctx)->load_runtime_module_w(basename, flags, handled);
1047} 1352}
1048 1353
1354void* bundled_compat_module(void* ctx, const std::wstring& basename, const std::wstring& name, bool load,
1355 uint32_t flags, bool& handled) {
1356 return static_cast<Loader*>(ctx)->runtime_compat_module(basename, name, load, flags, handled);
1357}
1358
1359bool bundled_owns_compat_handle(void* ctx, void* module) {
1360 return static_cast<Loader*>(ctx)->owns_compat_handle(module);
1361}
1362
1049const shims::BundledModuleOps kBundledOps{ 1363const shims::BundledModuleOps kBundledOps{
1050 &bundled_find_loaded, 1364 &bundled_find_loaded,
1051 &bundled_load, 1365 &bundled_load,
@@ -1053,6 +1367,8 @@ const shims::BundledModuleOps kBundledOps{
1053 &bundled_owns_handle, 1367 &bundled_owns_handle,
1054 &bundled_find_loaded_w, 1368 &bundled_find_loaded_w,
1055 &bundled_load_w, 1369 &bundled_load_w,
1370 &bundled_compat_module,
1371 &bundled_owns_compat_handle,
1056}; 1372};
1057 1373
1058// Marks what a run-time load maps as a dynamic load for as long as it is in scope (the caller holds the mutex). 1374// Marks what a run-time load maps as a dynamic load for as long as it is in scope (the caller holds the mutex).
@@ -1068,7 +1384,18 @@ struct RuntimeLoadScope {
1068Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { 1384Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) {
1069 std::vector<wchar_t> compat(32768); 1385 std::vector<wchar_t> compat(32768);
1070 const DWORD n = GetEnvironmentVariableW(L"LEONIDA_COMPAT_DIR", compat.data(), static_cast<DWORD>(compat.size())); 1386 const DWORD n = GetEnvironmentVariableW(L"LEONIDA_COMPAT_DIR", compat.data(), static_cast<DWORD>(compat.size()));
1071 if (n > 0 && n < compat.size()) compat_dir_ = std::filesystem::path(compat.data()); 1387 if (n > 0 && n < compat.size()) {
1388 // Absolute, with backslashes and no trailing separator: LoadLibraryExW with LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
1389 // needs a full path, and owns_compat_handle() compares it with a module's own folder.
1390 std::error_code ec;
1391 compat_dir_ = std::filesystem::absolute(std::filesystem::path(compat.data()), ec).lexically_normal();
1392 compat_dir_.make_preferred();
1393 if (!compat_dir_.has_filename()) compat_dir_ = compat_dir_.parent_path();
1394 for (std::filesystem::directory_iterator it(compat_dir_, ec), end; !ec && it != end; it.increment(ec)) {
1395 std::error_code file_ec;
1396 if (it->is_regular_file(file_ec)) compat_files_.push_back(it->path().filename());
1397 }
1398 }
1072 shims::add_module_lookup(this, &lookup_in_loader); 1399 shims::add_module_lookup(this, &lookup_in_loader);
1073 shims::add_bundled_loader(this, &kBundledOps); 1400 shims::add_bundled_loader(this, &kBundledOps);
1074} 1401}
@@ -1094,11 +1421,12 @@ Loader::~Loader() {
1094 entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored 1421 entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored
1095 } 1422 }
1096 } 1423 }
1424 shims::remove_xmem_allocation_hooks(this);
1097 shims::remove_bundled_loader(this); 1425 shims::remove_bundled_loader(this);
1098 shims::remove_module_lookup(this); 1426 shims::remove_module_lookup(this);
1099 for (auto* m : order_) { 1427 for (auto* m : order_) {
1100 // TLS state must go away before the image and its TLS block are unmapped. 1428 // TLS state must go away before the image and its TLS block are unmapped.
1101 if (m->tls_index != kNoTlsIndex && m->tls_slot < kMaxMappedTlsModules) { 1429 if (m->tls_index != kNoTlsIndex && m->tls_slot < kTlsSlotCount) {
1102 // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a 1430 // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a
1103 // thread that still holds a copy frees it when it ends (on_host_thread_event). 1431 // thread that still holds a copy frees it when it ends (on_host_thread_event).
1104 { 1432 {
@@ -1208,6 +1536,8 @@ void* Loader::load_runtime_module_w(const std::wstring& basename, uint32_t flags
1208 if (prefer_host_copy(narrow)) return nullptr; 1536 if (prefer_host_copy(narrow)) return nullptr;
1209 1537
1210 std::lock_guard lock(mutex_); 1538 std::lock_guard lock(mutex_);
1539 // As load_runtime_module: a run-time load, so DllMain gets a null lpvReserved.
1540 const RuntimeLoadScope dynamic(runtime_loads_);
1211 Module* existing = find_wide_module(basename); 1541 Module* existing = find_wide_module(basename);
1212 const std::filesystem::path candidate = game_dir_ / basename; 1542 const std::filesystem::path candidate = game_dir_ / basename;
1213 std::error_code ec; 1543 std::error_code ec;
@@ -1425,10 +1755,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
1425 if (!m->base) 1755 if (!m->base)
1426 m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, 1756 m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage,
1427 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); 1757 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
1428 if (!m->base) { 1758 if (!m->base) { // whether the image may move is decided at the relocation step below
1429 const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC);
1430 if (!relocs.Size)
1431 throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations");
1432 m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); 1759 m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
1433 if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); 1760 if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed");
1434 } 1761 }
@@ -1453,10 +1780,19 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
1453 } 1780 }
1454 1781
1455 int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase); 1782 int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase);
1456 if (delta) { 1783 // A moved image with a relocation table is fixed up, whatever IMAGE_FILE_RELOCS_STRIPPED says. Without a table,
1457 m->relocated = true; 1784 // the flag refuses the move; with the flag clear the image is moved and nothing is fixed up, so it is trusted to
1458 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); 1785 // hold no absolute addresses. The Windows 11 loader does all three (runtime/README.md); that move is logged so
1459 if (!dir.Size) throw std::runtime_error(m->name + ": the image has no relocations and isn't at its base"); 1786 // it shows in traces. base_reservation::needed still keeps the main image's range free when it has no
1787 // relocation directory, so a main image is moved this way only where the range could not be had.
1788 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC);
1789 if (delta) m->relocated = true;
1790 if (delta && !dir.Size && (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED))
1791 throw std::runtime_error(m->name + ": preferred base is taken and the image's relocations are stripped");
1792 if (delta && !dir.Size)
1793 std::fprintf(stderr, "[rt] loader: %s: preferred base %#llx is taken, moved to %p with no relocations\n",
1794 m->name.c_str(), static_cast<unsigned long long>(oh.ImageBase), static_cast<void*>(m->base));
1795 if (delta && dir.Size) {
1460 require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); 1796 require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table");
1461 auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress); 1797 auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress);
1462 auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size; 1798 auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size;
@@ -1498,6 +1834,12 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
1498 // installed here, before bind_imports can return control to the caller and before any image code can run. 1834 // installed here, before bind_imports can return control to the caller and before any image code can run.
1499 initialize_tls(*m); 1835 initialize_tls(*m);
1500 parse_exports(*m); 1836 parse_exports(*m);
1837 if (auto it = m->exports.find("__XMemAllocationHooks__"); it != m->exports.end()) {
1838 const auto offset = static_cast<uint64_t>(static_cast<uint8_t*>(it->second) - m->base);
1839 if (offset <= m->size && m->size - offset >= sizeof(shims::XMemAllocationHooks)) {
1840 shims::add_xmem_allocation_hooks(this, static_cast<const shims::XMemAllocationHooks*>(it->second));
1841 }
1842 }
1501 return *m; 1843 return *m;
1502} 1844}
1503 1845
@@ -1507,7 +1849,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
1507// Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to 1849// Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to
1508// gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone 1850// gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone
1509// getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than 1851// getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than
1510// silently sharing (and corrupting) a slot. 1852// silently sharing (and corrupting) a slot. An executable takes index 0 instead (kMainImageSlot), as on Windows.
1511void Loader::initialize_tls(Module& m) { 1853void Loader::initialize_tls(Module& m) {
1512 auto* tls = tls_directory(m); 1854 auto* tls = tls_directory(m);
1513 if (!tls) return; 1855 if (!tls) return;
@@ -1536,26 +1878,70 @@ void Loader::initialize_tls(Module& m) {
1536 1878
1537 if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); 1879 if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array");
1538 1880
1539 size_t slot = kMaxMappedTlsModules; 1881 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
1882 const bool executable = (nt->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0;
1883
1884 size_t slot = kTlsSlotCount;
1540 DWORD index = TLS_OUT_OF_INDEXES; 1885 DWORD index = TLS_OUT_OF_INDEXES;
1541 { 1886 {
1542 std::lock_guard alloc_lock(g_tls_alloc_mutex); 1887 std::lock_guard alloc_lock(g_tls_alloc_mutex);
1543 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { 1888 if (executable) {
1544 if (g_tls_slot_owners[i].load() == nullptr) { 1889 if (g_index0.moved && g_tls_slot_owners[kMainImageSlot].load() == nullptr) {
1545 slot = i; 1890 slot = kMainImageSlot;
1546 break; 1891 index = 0;
1892 if (!g_index0.traced && startup_trace::enabled()) {
1893 g_index0.traced = true;
1894 startup_trace::event("tls_index0", "\"owner\":" + startup_trace::quote(g_index0.owner) +
1895 ",\"moved_to\":" + std::to_string(g_index0.home.index));
1896 }
1897 } else {
1898 // Mapped on as a DLL is: its code that reads _tls_index works, but its /GA code would read and write
1899 // the block in slot 0, which is the runtime's own TLS or the other executable's. gta6rt refuses to
1900 // run such an image (main.cpp); a Loader user must not run its code either.
1901 std::fprintf(stderr,
1902 "[rt] loader: %s does not get module TLS index 0 (%s); its code built with /GA would use "
1903 "another module's TLS\n",
1904 m.name.c_str(), g_index0.moved ? "another mapped executable holds it" : g_index0.why);
1905 }
1906 }
1907 if (slot == kTlsSlotCount) {
1908 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) {
1909 if (g_tls_slot_owners[i].load() == nullptr) {
1910 slot = i;
1911 break;
1912 }
1547 } 1913 }
1914 if (slot >= kMaxMappedTlsModules)
1915 throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) +
1916 " manually mapped static TLS slots are in use");
1917
1918 // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with
1919 // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock).
1920 index = ensure_tls_host(slot).index;
1921 if (index == TLS_OUT_OF_INDEXES)
1922 throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index");
1923 if (index >= kMaxModuleTlsSlots)
1924 throw std::runtime_error(m.name + ": reserved TLS index is out of range");
1548 } 1925 }
1549 if (slot >= kMaxMappedTlsModules)
1550 throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) +
1551 " manually mapped static TLS slots are in use");
1552 1926
1553 // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with 1927 // An EXE's code may read its TLS at index 0 directly (/GA); index 0 is gta6rt.exe's here (pe_loader.h,
1554 // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock). 1928 // tls_ga_slot). Patched before any of the image's code runs, TLS callbacks included, and before the owner is
1555 index = ensure_tls_host(slot).index; 1929 // published below: from then on a thread event (install_thread_block) reads m.tls_ga_slot
1556 if (index == TLS_OUT_OF_INDEXES) 1930 // (RT-LOADER-RUNTIME-SCOPE-AND-TLS-SLOT).
1557 throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index"); 1931 if (executable && total && index != 0 && ga_tls_patch_enabled()) {
1558 if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range"); 1932 static const DWORD ga_slot = TlsAlloc();
1933 if (ga_slot == TLS_OUT_OF_INDEXES || ga_slot >= 64) {
1934 std::fprintf(stderr, "[rt] loader: %s: no TlsAlloc slot below 64 for its index-0 TLS reads\n",
1935 m.name.c_str());
1936 } else {
1937 m.tls_ga_sites = patch_ga_tls_reads(m, ga_slot);
1938 if (m.tls_ga_sites) m.tls_ga_slot = ga_slot;
1939 std::fprintf(stderr,
1940 "[rt] loader: %s: %zu index-0 TLS reads (gs:[58h]) now read its own TLS (TlsSlots[%lu]); "
1941 "its module TLS index is %u\n",
1942 m.name.c_str(), m.tls_ga_sites, static_cast<unsigned long>(ga_slot), index);
1943 }
1944 }
1559 1945
1560 // The fields are complete before a thread event can see the owner. 1946 // The fields are complete before a thread event can see the owner.
1561 ExclusiveTlsLock lock; 1947 ExclusiveTlsLock lock;
@@ -1575,26 +1961,6 @@ void Loader::initialize_tls(Module& m) {
1575 // VirtualProtect dance. 1961 // VirtualProtect dance.
1576 if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index; 1962 if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index;
1577 } 1963 }
1578 {
1579 // An EXE's code may read its TLS at index 0 directly (/GA); index 0 is gta6rt.exe's here (pe_loader.h,
1580 // tls_ga_slot). Patched before any of the image's code runs, TLS callbacks included.
1581 const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(m.base);
1582 const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(m.base + dos->e_lfanew);
1583 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && total && index != 0 && ga_tls_patch_enabled()) {
1584 static const DWORD ga_slot = TlsAlloc();
1585 if (ga_slot == TLS_OUT_OF_INDEXES || ga_slot >= 64) {
1586 std::fprintf(stderr, "[rt] loader: %s: no TlsAlloc slot below 64 for its index-0 TLS reads\n",
1587 m.name.c_str());
1588 } else {
1589 m.tls_ga_sites = patch_ga_tls_reads(m, ga_slot);
1590 if (m.tls_ga_sites) m.tls_ga_slot = ga_slot;
1591 std::fprintf(stderr,
1592 "[rt] loader: %s: %zu index-0 TLS reads (gs:[58h]) now read its own TLS (TlsSlots[%lu]); "
1593 "its module TLS index is %u\n",
1594 m.name.c_str(), m.tls_ga_sites, static_cast<unsigned long>(ga_slot), index);
1595 }
1596 }
1597 }
1598 try { 1964 try {
1599 install_thread_block(m); 1965 install_thread_block(m);
1600 } catch (...) { 1966 } catch (...) {
@@ -1713,37 +2079,128 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d
1713 return reinterpret_cast<void*>(p); 2079 return reinterpret_cast<void*>(p);
1714} 2080}
1715 2081
2082const std::filesystem::path* Loader::compat_file(const std::wstring& basename) const {
2083 if (basename.empty()) return nullptr;
2084 for (const auto& file : compat_files_)
2085 if (same_module_name(file.c_str(), basename.c_str())) return &file;
2086 return nullptr;
2087}
2088
2089void* Loader::compat_handle(const std::filesystem::path& file, bool load, uint32_t& error) {
2090 error = ERROR_SUCCESS;
2091 const std::string key = lower(path_utf8(file));
2092 if (auto it = compat_modules_.find(key); it != compat_modules_.end()) return it->second;
2093 const std::filesystem::path candidate = compat_dir_ / file;
2094 // Already live without a lookup through here: Windows loaded it from the folder as another compat DLL's
2095 // dependency (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR), or something loaded it by its path. That is the module a
2096 // static import or a run-time load must share. The reference taken here is kept, as for the DLLs loaded below.
2097 if (HMODULE live = nullptr; GetModuleHandleExW(0, candidate.c_str(), &live) && live) {
2098 compat_modules_.emplace(key, live);
2099 std::fprintf(stderr, "[rt] compat: %s -> %s (already loaded)\n", path_utf8(file).c_str(),
2100 path_utf8(candidate).c_str());
2101 return live;
2102 }
2103 if (!load) return nullptr;
2104 // The full path, with the compat folder on the DLL's own search path for its dependencies; never the game
2105 // folder. Windows maps it, so its CRT, TLS and SEH work as for any host DLL.
2106 // A file Windows cannot map (truncated, wrong machine, not a PE image) otherwise raises a modal "Bad Image"
2107 // box and LoadLibraryExW does not return until someone clicks it: a headless run would hang on a failure
2108 // that the caller reports anyway. The mode is this thread's, and goes back as it was.
2109 DWORD previous_mode = 0;
2110 const bool mode_set = SetThreadErrorMode(GetThreadErrorMode() | SEM_FAILCRITICALERRORS, &previous_mode) != 0;
2111 HMODULE h = LoadLibraryExW(candidate.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);
2112 error = h ? ERROR_SUCCESS : GetLastError();
2113 if (mode_set) SetThreadErrorMode(previous_mode, nullptr);
2114 if (!h) return nullptr;
2115 compat_modules_.emplace(key, h);
2116 std::fprintf(stderr, "[rt] compat: %s -> %s\n", path_utf8(file).c_str(), path_utf8(candidate).c_str());
2117 return h;
2118}
2119
1716bool Loader::resolve_compat(const std::string& key, const std::string& dll, const std::string& name, uint16_t ordinal, 2120bool Loader::resolve_compat(const std::string& key, const std::string& dll, const std::string& name, uint16_t ordinal,
1717 bool by_ordinal, void*& out) { 2121 bool by_ordinal, void*& out) {
1718 out = nullptr; 2122 out = nullptr;
1719 if (compat_dir_.empty() || key.empty() || key.find_first_of("/\\:") != std::string::npos) return false; 2123 if (compat_dir_.empty() || key.empty() || key.find_first_of("/\\:") != std::string::npos) return false;
1720 HMODULE h = nullptr; 2124 const std::filesystem::path* file = compat_file(acp_to_wide(dll));
1721 if (auto it = compat_modules_.find(key); it != compat_modules_.end()) { 2125 if (!file) return false;
1722 h = static_cast<HMODULE>(it->second); 2126 uint32_t error = ERROR_SUCCESS;
1723 } else { 2127 HMODULE h = static_cast<HMODULE>(compat_handle(*file, true, error));
1724 const std::filesystem::path candidate = compat_dir_ / std::filesystem::path(dll); 2128 if (!h)
1725 std::error_code ec; 2129 throw std::runtime_error("LEONIDA_COMPAT_DIR: " + path_utf8(compat_dir_ / *file) +
1726 if (!std::filesystem::is_regular_file(candidate, ec)) return false; 2130 " exists but Windows could not load it (error " + std::to_string(error) + ")");
1727 // The full path, with the compat folder on the DLL's own search path for its dependencies; never the game
1728 // folder. Windows maps it, so its CRT, TLS and SEH work as for any host DLL.
1729 // A file Windows cannot map (truncated, wrong machine, not a PE image) otherwise raises a modal "Bad Image"
1730 // box and LoadLibraryExW does not return until someone clicks it: a headless run would hang on a failure
1731 // that is reported right below anyway. The mode is this thread's, and goes back as it was.
1732 DWORD previous_mode = 0;
1733 const bool mode_set = SetThreadErrorMode(GetThreadErrorMode() | SEM_FAILCRITICALERRORS, &previous_mode) != 0;
1734 h = LoadLibraryExW(candidate.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);
1735 const DWORD load_error = h ? ERROR_SUCCESS : GetLastError();
1736 if (mode_set) SetThreadErrorMode(previous_mode, nullptr);
1737 if (!h)
1738 throw std::runtime_error("LEONIDA_COMPAT_DIR: " + path_utf8(candidate) + " exists but Windows could not " +
1739 "load it (error " + std::to_string(load_error) + ")");
1740 compat_modules_.emplace(key, h);
1741 std::fprintf(stderr, "[rt] compat: %s -> %s\n", dll.c_str(), path_utf8(candidate).c_str());
1742 }
1743 out = reinterpret_cast<void*>(GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str())); 2131 out = reinterpret_cast<void*>(GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str()));
1744 return true; 2132 return true;
1745} 2133}
1746 2134
2135void* Loader::runtime_compat_module(const std::wstring& basename, const std::wstring& name, bool load,
2136 uint32_t flags, bool& handled) {
2137 handled = false;
2138 if (compat_dir_.empty()) return nullptr;
2139 std::lock_guard lock(mutex_);
2140 const std::filesystem::path* file = compat_file(basename);
2141 if (!file) return nullptr;
2142 const std::filesystem::path compat_path = compat_dir_ / *file;
2143 // A name with a directory names one file, which Windows would load even when another of the same name is in use:
2144 // the compat DLL answers it only when it is that file (".dll" added as LoadLibrary adds it). Any other path goes
2145 // on as without the folder.
2146 if (name.find_first_of(L"\\/:") != std::wstring::npos) {
2147 std::filesystem::path given(name);
2148 given.replace_filename(basename);
2149 std::error_code ec;
2150 if (!std::filesystem::equivalent(given, compat_path, ec)) return nullptr;
2151 }
2152 handled = true;
2153 // DONT_RESOLVE_DLL_REFERENCES maps a DLL without its dependencies, TLS or DllMain. The compat DLL is shared with
2154 // static imports, initialised, so refuse it before loading or returning a handle, as for bundled DLLs
2155 // (load_runtime_candidate).
2156 if (load && (flags & DONT_RESOLVE_DLL_REFERENCES) != 0) {
2157 std::fprintf(stderr, "[rt] compat: LoadLibraryEx(%s, DONT_RESOLVE_DLL_REFERENCES) is not supported\n",
2158 path_utf8(compat_path).c_str());
2159 SetLastError(ERROR_NOT_SUPPORTED);
2160 return nullptr;
2161 }
2162 uint32_t error = ERROR_SUCCESS;
2163 void* h = compat_handle(*file, load, error);
2164 if (!h && load) {
2165 // As a LoadLibrary of a file Windows refuses: null and its error, never the shim (the player put the DLL
2166 // there to own the module).
2167 std::fprintf(stderr, "[rt] compat: %s exists but Windows could not load it (error %u, run-time load)\n",
2168 path_utf8(compat_path).c_str(), error);
2169 SetLastError(error);
2170 } else if (!h) {
2171 SetLastError(ERROR_MOD_NOT_FOUND); // GetModuleHandle of a module nothing has loaded yet
2172 }
2173 return h;
2174}
2175
2176bool Loader::owns_compat_handle(void* module) {
2177 if (!module || compat_dir_.empty()) return false;
2178 {
2179 std::lock_guard lock(mutex_);
2180 for (const auto& [key, h] : compat_modules_)
2181 if (h == module) return true;
2182 }
2183 // A DLL from the folder that no lookup has seen yet (Windows loaded it as another compat DLL's dependency): its
2184 // exports are its own too. Recorded, with a kept reference, through compat_handle(). GetModuleFileNameW can take
2185 // the Windows loader lock, so the path is read without mutex_ held; compat_dir_ and compat_files_ do not change
2186 // after construction.
2187 std::vector<wchar_t> path(MAX_PATH);
2188 DWORD length = 0;
2189 for (;;) {
2190 length = GetModuleFileNameW(static_cast<HMODULE>(module), path.data(), static_cast<DWORD>(path.size()));
2191 if (!length || length < path.size() || path.size() >= 32768) break;
2192 path.resize(path.size() * 2);
2193 }
2194 if (!length || length >= path.size()) return false;
2195 const std::filesystem::path file(std::wstring(path.data(), length));
2196 if (!same_module_name(file.parent_path().c_str(), compat_dir_.c_str())) return false;
2197 const std::filesystem::path* entry = compat_file(file.filename().native());
2198 if (!entry) return false;
2199 std::lock_guard lock(mutex_);
2200 uint32_t error = ERROR_SUCCESS;
2201 return compat_handle(*entry, false, error) == module;
2202}
2203
1747void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) { 2204void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) {
1748 std::string key = lower(dll); 2205 std::string key = lower(dll);
1749 std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name; 2206 std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name;
@@ -1796,7 +2253,10 @@ void Loader::bind_imports(Module& m) {
1796 const uint64_t headers_end = nt->OptionalHeader.SizeOfHeaders; 2253 const uint64_t headers_end = nt->OptionalHeader.SizeOfHeaders;
1797 2254
1798 // Thunk tables have no length field: they end at a zero entry, so each step is checked against the image. 2255 // Thunk tables have no length field: they end at a zero entry, so each step is checked against the image.
1799 auto bind_thunks = [&](const std::string& dll, uint64_t lookup_rva, uint64_t iat_rva) { 2256 // `delayed`: a delay import that binds to an unimplemented thunk is traced. Windows' delay-load helper would raise
2257 // 0xC06D007E (module) or 0xC06D007F (procedure) at its first call, which a title can catch for a fallback; the
2258 // thunk returns 0 instead, so the trace names each such import before any image code runs.
2259 auto bind_thunks = [&](const std::string& dll, uint64_t lookup_rva, uint64_t iat_rva, bool delayed) {
1800 for (;; lookup_rva += sizeof(IMAGE_THUNK_DATA64), iat_rva += sizeof(IMAGE_THUNK_DATA64)) { 2260 for (;; lookup_rva += sizeof(IMAGE_THUNK_DATA64), iat_rva += sizeof(IMAGE_THUNK_DATA64)) {
1801 require_range(m.name, lookup_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import lookup table"); 2261 require_range(m.name, lookup_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import lookup table");
1802 require_range(m.name, iat_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import address table"); 2262 require_range(m.name, iat_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import address table");
@@ -1814,6 +2274,10 @@ void Loader::bind_imports(Module& m) {
1814 throw std::runtime_error(m.name + ": an import address table lands in the headers"); 2274 throw std::runtime_error(m.name + ": an import address table lands in the headers");
1815 at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function = 2275 at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function =
1816 reinterpret_cast<uint64_t>(resolve(m, dll, name, ord, by_ord)); 2276 reinterpret_cast<uint64_t>(resolve(m, dll, name, ord, by_ord));
2277 if (delayed && startup_trace::enabled() && m.imports.back().binding == Binding::Unimplemented)
2278 startup_trace::event("delay_import_unimplemented",
2279 "\"module\":" + startup_trace::quote(m.name) + ",\"import\":" +
2280 startup_trace::quote(dll + "!" + m.imports.back().name));
1817 } 2281 }
1818 }; 2282 };
1819 2283
@@ -1826,7 +2290,7 @@ void Loader::bind_imports(Module& m) {
1826 if (!d->Name) break; 2290 if (!d->Name) break;
1827 std::string dll = read_string(m.name, m.base, m.size, d->Name, "an imported DLL name"); 2291 std::string dll = read_string(m.name, m.base, m.size, d->Name, "an imported DLL name");
1828 uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk; 2292 uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk;
1829 bind_thunks(dll, lookup, d->FirstThunk); 2293 bind_thunks(dll, lookup, d->FirstThunk, false);
1830 } 2294 }
1831 } 2295 }
1832 // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. 2296 // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run.
@@ -1849,7 +2313,7 @@ void Loader::bind_imports(Module& m) {
1849 // thunk addresses as name RVAs. 2313 // thunk addresses as name RVAs.
1850 if (!d->ImportNameTableRVA) 2314 if (!d->ImportNameTableRVA)
1851 throw std::runtime_error(m.name + ": a delay-import descriptor has no name table"); 2315 throw std::runtime_error(m.name + ": a delay-import descriptor has no name table");
1852 bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA); 2316 bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA, true);
1853 } 2317 }
1854 } 2318 }
1855} 2319}
@@ -1857,6 +2321,65 @@ void Loader::bind_imports(Module& m) {
1857void Loader::protect_sections(Module& m) { 2321void Loader::protect_sections(Module& m) {
1858 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 2322 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
1859 DWORD old; 2323 DWORD old;
2324 // On a CPU without CLZERO, the image's CLZERO loops run from stubs instead of taking a #UD per cache line
2325 // (clzero_patch.h). The sections are still writable here, and none of the image's code has run.
2326 static const bool clzero_missing = !rt::cpu_emulation::detect_host().clzero;
2327 if (clzero_missing && rt::clzero_patch::enabled()) {
2328 std::vector<std::pair<uint8_t*, size_t>> code;
2329 const IMAGE_SECTION_HEADER* cs = IMAGE_FIRST_SECTION(nt);
2330 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++cs) {
2331 if (!(cs->Characteristics & IMAGE_SCN_MEM_EXECUTE) || cs->VirtualAddress >= m.size) continue;
2332 const uint64_t size = std::min<uint64_t>(std::min(cs->Misc.VirtualSize, cs->SizeOfRawData),
2333 m.size - cs->VirtualAddress);
2334 if (size) code.push_back({m.base + cs->VirtualAddress, static_cast<size_t>(size)});
2335 }
2336 const auto patched = rt::clzero_patch::patch(code, uint64_t(m.base), uint64_t(m.base) + m.size);
2337 if (patched.sites)
2338 std::fprintf(stderr,
2339 "[rt] loader: %s: %zu CLZERO loops run from stubs at %p (%zu bytes), not as a #UD per line\n",
2340 m.name.c_str(), patched.sites, static_cast<void*>(patched.stubs), patched.stub_bytes);
2341 }
2342 {
2343 const auto isa = rt::isa_jit_patch::patch_image(m.base, m.size);
2344 if (isa.stubs && isa.stub_bytes) {
2345 std::unique_lock lock(ranges_mutex_);
2346 ranges_.push_back({reinterpret_cast<uint64_t>(isa.stubs),
2347 static_cast<uint32_t>(isa.stub_bytes), m.name + "[isa-stubs]"});
2348 }
2349 if (isa.inplace_sites || isa.bmi_stubs || isa.avx2_stubs || isa.fma3_stubs) {
2350 std::fprintf(stderr,
2351 "[rt] loader: %s: native AVX1/x64 acceleration: %zu in-place, %zu BMI, %zu AVX2 (%zu fused 4B), "
2352 "%zu FMA3 stubs at %p (%zu KiB)\n",
2353 m.name.c_str(), isa.inplace_sites, isa.bmi_stubs, isa.avx2_stubs, isa.avx2_fused_4b,
2354 isa.fma3_stubs, static_cast<void*>(isa.stubs), (isa.stub_bytes + 1023u) / 1024u);
2355 }
2356 }
2357 static const auto bmi_host = rt::bmi_emulation::detect_host();
2358 if ((!bmi_host.bmi1 || !bmi_host.lzcnt) && rt::bmi_emulation::lzcnt_patch_enabled()) {
2359 std::vector<std::pair<uint32_t, uint32_t>> exec_ranges;
2360 const IMAGE_SECTION_HEADER* cs = IMAGE_FIRST_SECTION(nt);
2361 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++cs) {
2362 if (!(cs->Characteristics & IMAGE_SCN_MEM_EXECUTE) || cs->VirtualAddress >= m.size) continue;
2363 const uint64_t size = std::min<uint64_t>(std::min(cs->Misc.VirtualSize, cs->SizeOfRawData),
2364 m.size - cs->VirtualAddress);
2365 if (size) exec_ranges.push_back({cs->VirtualAddress, static_cast<uint32_t>(size)});
2366 }
2367 const auto exc = directory(nt, IMAGE_DIRECTORY_ENTRY_EXCEPTION);
2368 const RUNTIME_FUNCTION* pdata = nullptr;
2369 uint32_t pdata_count = 0;
2370 if (exc.VirtualAddress && exc.Size >= sizeof(RUNTIME_FUNCTION) && exc.VirtualAddress < m.size) {
2371 const uint64_t max_bytes = std::min<uint64_t>(exc.Size, m.size - exc.VirtualAddress);
2372 pdata_count = static_cast<uint32_t>(max_bytes / sizeof(RUNTIME_FUNCTION));
2373 pdata = at<RUNTIME_FUNCTION>(m.base, exc.VirtualAddress);
2374 }
2375 const auto patched = rt::bmi_emulation::patch_image(
2376 m.base, m.size, exec_ranges, pdata, pdata_count, !bmi_host.bmi1, !bmi_host.lzcnt);
2377 if (patched.tzcnt_sites || patched.lzcnt_sites)
2378 std::fprintf(stderr,
2379 "[rt] loader: %s: patched %zu TZCNT and %zu LZCNT sites (%zu stubs at %p, %zu #UD)\n",
2380 m.name.c_str(), patched.tzcnt_sites, patched.lzcnt_sites, patched.stub_sites,
2381 static_cast<void*>(patched.stubs), patched.ud2_sites);
2382 }
1860 VirtualProtect(m.base, nt->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &old); 2383 VirtualProtect(m.base, nt->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &old);
1861 auto* sec = IMAGE_FIRST_SECTION(nt); 2384 auto* sec = IMAGE_FIRST_SECTION(nt);
1862 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { 2385 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) {