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:
authorVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 20:27:12 +0100
committerVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 20:27:12 +0100
commit3eb80d77e384a8c51bb58076dc881d7d291f8001 (patch)
treeeb76604305dca9a75845c36bdbbe8fe066051fe1 /runtime/src/pe_loader.cpp
parentb87dc1e9af21b11375c29dfa1046232eccbed2db (diff)
parent162821017ea3c286c8bec860f3ff94f037912061 (diff)
Merge main into cov-d16fmt (#2039)
Conflicts: scripts/run_gpu_tests.py tests/semantic/regen_fixtures.py tests/test_shader_checks.py AI-assisted.
Diffstat (limited to 'runtime/src/pe_loader.cpp')
-rw-r--r--runtime/src/pe_loader.cpp420
1 files changed, 343 insertions, 77 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index 387051756..a59f9d0b1 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -4,6 +4,7 @@
4#include <intrin.h> 4#include <intrin.h>
5 5
6#include <algorithm> 6#include <algorithm>
7#include <array>
7#include <atomic> 8#include <atomic>
8#include <cstdio> 9#include <cstdio>
9#include <cstdlib> 10#include <cstdlib>
@@ -14,6 +15,7 @@
14#include <vector> 15#include <vector>
15 16
16#include "../shims/shims.h" 17#include "../shims/shims.h"
18#include "../shims/startup_trace.h"
17#include "base_reservation.h" 19#include "base_reservation.h"
18 20
19namespace rt { 21namespace rt {
@@ -73,8 +75,11 @@ IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) {
73// loader-assigned per-module TLS index and is a different index space from TlsAlloc/TlsGetValue (TlsSlots). Only the OS 75// loader-assigned per-module TLS index and is a different index space from TlsAlloc/TlsGetValue (TlsSlots). Only the OS
74// loader can allocate a module index, so the runtime ships a minimal DLL whose only content is a TLS anchor 76// loader can allocate a module index, so the runtime ships a minimal DLL whose only content is a TLS anchor
75// (src/tls_host.cpp). Loading it makes the OS reserve an index and give every thread a block for it; the native loader 77// (src/tls_host.cpp). Loading it makes the OS reserve an index and give every thread a block for it; the native loader
76// reuses that index for the mapped image. One helper means one mapped TLS module at a time. 78// reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader
79// clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent
80// module TLS index for each simultaneous module (up to kMaxMappedTlsModules).
77constexpr DWORD kMaxModuleTlsSlots = 64; 81constexpr DWORD kMaxModuleTlsSlots = 64;
82constexpr size_t kMaxMappedTlsModules = 16;
78void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); } 83void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); }
79 84
80void __cdecl on_host_thread_event(DWORD reason); 85void __cdecl on_host_thread_event(DWORD reason);
@@ -84,22 +89,64 @@ struct TlsHostModule {
84 DWORD index = TLS_OUT_OF_INDEXES; 89 DWORD index = TLS_OUT_OF_INDEXES;
85}; 90};
86 91
87TlsHostModule load_tls_host() { 92std::filesystem::path tls_host_base_path() {
88 TlsHostModule host;
89 // Dynamic buffer loop for paths that exceed MAX_PATH
90 std::wstring exe_path; 93 std::wstring exe_path;
91 DWORD size = MAX_PATH; 94 DWORD size = MAX_PATH;
92 while (true) { 95 while (true) {
93 exe_path.resize(size); 96 exe_path.resize(size);
94 DWORD len = GetModuleFileNameW(nullptr, exe_path.data(), size); 97 DWORD len = GetModuleFileNameW(nullptr, exe_path.data(), size);
95 if (len == 0) return host; 98 if (len == 0) return {};
96 if (len < size - 1) { 99 if (len < size - 1) {
97 exe_path.resize(len); 100 exe_path.resize(len);
98 break; 101 break;
99 } 102 }
100 size *= 2; 103 size *= 2;
101 } 104 }
102 const std::filesystem::path path = std::filesystem::path(exe_path).parent_path() / L"gta6rt_tls_host.dll"; 105 return std::filesystem::path(exe_path).parent_path() / L"gta6rt_tls_host.dll";
106}
107
108std::filesystem::path tls_host_clone_dir() {
109 wchar_t buf[MAX_PATH];
110 DWORD n = GetTempPathW(MAX_PATH, buf);
111 if (n > 0 && n < MAX_PATH) return std::filesystem::path(buf);
112 return std::filesystem::temp_directory_path();
113}
114
115struct TlsCloneRecord {
116 HMODULE module = nullptr;
117 std::filesystem::path path;
118};
119
120std::mutex g_tls_alloc_mutex;
121std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{};
122std::array<std::atomic<Module*>, kMaxMappedTlsModules> g_tls_slot_owners{};
123std::vector<TlsCloneRecord> g_tls_clones;
124
125void cleanup_tls_clones_at_exit() {
126 for (const auto& rec : g_tls_clones) {
127 if (rec.module) FreeLibrary(rec.module);
128 if (!rec.path.empty()) DeleteFileW(rec.path.c_str());
129 }
130 g_tls_clones.clear();
131}
132
133void sweep_stale_tls_clones(const std::filesystem::path& dir) {
134 WIN32_FIND_DATAW fd{};
135 const std::filesystem::path pattern = dir / L"leonida_tls_host_*.dll";
136 HANDLE h = FindFirstFileW(pattern.c_str(), &fd);
137 if (h == INVALID_HANDLE_VALUE) return;
138 do {
139 if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
140 // Fails harmlessly for clones still mapped in live processes; deletes orphaned ones from exited processes.
141 DeleteFileW((dir / fd.cFileName).c_str());
142 }
143 } while (FindNextFileW(h, &fd));
144 FindClose(h);
145}
146
147TlsHostModule load_tls_host_image(const std::filesystem::path& path, bool hook_thread_events) {
148 TlsHostModule host;
149 if (path.empty()) return host;
103 // The helper is linked with the static CRT (/MT), so it needs only system DLLs. Restricting the dependency search 150 // The helper is linked with the static CRT (/MT), so it needs only system DLLs. Restricting the dependency search
104 // to System32 keeps a game-supplied vcruntime next to the executable from being picked up. 151 // to System32 keeps a game-supplied vcruntime next to the executable from being picked up.
105 host.module = LoadLibraryExW(path.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); 152 host.module = LoadLibraryExW(path.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
@@ -121,31 +168,81 @@ TlsHostModule load_tls_host() {
121 return host; 168 return host;
122 } 169 }
123 host.index = *reinterpret_cast<DWORD*>(tls->AddressOfIndex); 170 host.index = *reinterpret_cast<DWORD*>(tls->AddressOfIndex);
124 // From here on the helper's DllMain reports every thread the process starts or ends (on_host_thread_event). 171 if (hook_thread_events) {
125 using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); 172 // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots.
126 if (auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"))) 173 using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD));
127 set(&on_host_thread_event); 174 if (auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event")))
175 set(&on_host_thread_event);
176 }
128 return host; 177 return host;
129} 178}
130 179
131TlsHostModule& tls_host() { 180// Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock).
132 // The helper stays loaded for the process lifetime: unloading it would release the reserved TLS index. Its own 181TlsHostModule ensure_tls_host(size_t slot) {
133 // per-thread blocks are restored by uninstall_tls_for_thread, so the OS loader can free them normally. 182 if (slot >= kMaxMappedTlsModules) return {};
134 static TlsHostModule host = load_tls_host(); 183 if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot];
135 return host; 184
185 const std::filesystem::path primary = tls_host_base_path();
186 if (primary.empty()) return {};
187
188 if (slot == 0) {
189 g_tls_hosts[0] = load_tls_host_image(primary, true);
190 return g_tls_hosts[0];
191 }
192
193 // Ensure slot 0 is loaded first so thread attach/detach events are hooked.
194 if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) {
195 g_tls_hosts[0] = load_tls_host_image(primary, true);
196 if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) return {};
197 }
198
199 // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem).
200 const std::filesystem::path dir = tls_host_clone_dir();
201 static bool swept = false;
202 if (!swept) {
203 swept = true;
204 sweep_stale_tls_clones(dir);
205 std::atexit(&cleanup_tls_clones_at_exit);
206 }
207 const std::wstring name =
208 L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll";
209 const std::filesystem::path clone_path = dir / name;
210 if (!CopyFileW(primary.c_str(), clone_path.c_str(), FALSE)) return {};
211
212 // Hold a read-only-shared handle across LoadLibraryExW so another process cannot overwrite the clone in between.
213 HANDLE guard = CreateFileW(clone_path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr,
214 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
215 TlsHostModule loaded = load_tls_host_image(clone_path, false);
216 if (guard != INVALID_HANDLE_VALUE) CloseHandle(guard);
217
218 if (loaded.index == TLS_OUT_OF_INDEXES) {
219 DeleteFileW(clone_path.c_str());
220 return {};
221 }
222 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) {
223 if (i != slot && g_tls_hosts[i].index == loaded.index) {
224 FreeLibrary(loaded.module);
225 DeleteFileW(clone_path.c_str());
226 return {};
227 }
228 }
229 g_tls_clones.push_back({loaded.module, clone_path});
230 g_tls_hosts[slot] = loaded;
231 return g_tls_hosts[slot];
136} 232}
137 233
138std::atomic<Module*> g_tls_slot_owner{nullptr}; 234struct ThreadTlsSlot {
235 Module* module = nullptr;
236 void* saved = nullptr;
237 void* block = nullptr;
238 uint32_t index = kNoTlsIndex;
239};
139 240
140// Per-thread installation state. Only one mapped TLS module can own the reserved slot, so one entry per thread is 241// Per-thread installation state for each reserved TLS slot.
141// enough; the saved pointer is the helper DLL's own block that the OS loader will free at thread exit. 242thread_local std::array<ThreadTlsSlot, kMaxMappedTlsModules> g_thread_tls_slots{};
142thread_local Module* g_thread_tls_module = nullptr;
143thread_local void* g_thread_tls_saved = nullptr;
144thread_local void* g_thread_tls_block = nullptr;
145thread_local uint32_t g_thread_tls_index = kNoTlsIndex;
146 243
147// Orders the TLS owner's publication, its `initialised` flag and its retirement against the thread events. Shared in 244// Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared
148// on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows 245// in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows
149// loader lock, which the events run under). 246// loader lock, which the events run under).
150SRWLOCK g_tls_lock = SRWLOCK_INIT; 247SRWLOCK g_tls_lock = SRWLOCK_INIT;
151struct SharedTlsLock { 248struct SharedTlsLock {
@@ -163,30 +260,38 @@ struct ExclusiveTlsLock {
163 260
164// Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this 261// Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this
165// thread's record, so it also works after the module that installed the copy is gone. 262// thread's record, so it also works after the module that installed the copy is gone.
166void release_thread_block() { 263void release_thread_slot(size_t slot) {
167 if (!g_thread_tls_block) return; 264 if (slot >= kMaxMappedTlsModules) return;
168 void** slots = module_tls_slots(); 265 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
169 if (slots && g_thread_tls_index < kMaxModuleTlsSlots && slots[g_thread_tls_index] == g_thread_tls_block) 266 if (!entry.module && !entry.block) return;
170 slots[g_thread_tls_index] = g_thread_tls_saved; 267 if (entry.block) {
171 VirtualFree(g_thread_tls_block, 0, MEM_RELEASE); 268 void** slots = module_tls_slots();
172 g_thread_tls_module = nullptr; 269 if (slots && entry.index < kMaxModuleTlsSlots && slots[entry.index] == entry.block)
173 g_thread_tls_saved = nullptr; 270 slots[entry.index] = entry.saved;
174 g_thread_tls_block = nullptr; 271 VirtualFree(entry.block, 0, MEM_RELEASE);
175 g_thread_tls_index = kNoTlsIndex; 272 }
273 entry = ThreadTlsSlot{};
176} 274}
177 275
178void install_thread_block(Module& m) { 276void install_thread_block(Module& m) {
179 if (m.tls_index == kNoTlsIndex) return; 277 if (m.tls_slot >= kMaxMappedTlsModules) return;
180 if (g_thread_tls_module == &m) return; 278 const size_t slot = m.tls_slot;
181 if (g_thread_tls_module) { 279 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
280 if (entry.module == &m) return;
281 if (entry.module) {
182 // A copy left by a module whose Loader is gone is released; a live module's is a conflict. 282 // A copy left by a module whose Loader is gone is released; a live module's is a conflict.
183 if (g_thread_tls_module == g_tls_slot_owner.load()) 283 if (entry.module == g_tls_slot_owners[slot].load())
184 throw std::runtime_error("another manually mapped module's TLS is already installed in this thread"); 284 throw std::runtime_error("another manually mapped module's TLS is already installed in this thread slot");
185 release_thread_block(); 285 release_thread_slot(slot);
186 } 286 }
187 287
188 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill; 288 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill;
189 if (!total) return; 289 if (!total) {
290 // Callback-only TLS module (no data block): still record attachment in this slot so DLL_THREAD_DETACH runs.
291 entry.module = &m;
292 return;
293 }
294 if (m.tls_index == kNoTlsIndex) return;
190 void** slots = module_tls_slots(); 295 void** slots = module_tls_slots();
191 if (!slots || m.tls_index >= kMaxModuleTlsSlots) 296 if (!slots || m.tls_index >= kMaxModuleTlsSlots)
192 throw std::runtime_error(m.name + ": cannot install TLS in this thread"); 297 throw std::runtime_error(m.name + ": cannot install TLS in this thread");
@@ -199,22 +304,27 @@ void install_thread_block(Module& m) {
199 304
200 void* saved = slots[m.tls_index]; 305 void* saved = slots[m.tls_index];
201 slots[m.tls_index] = block; 306 slots[m.tls_index] = block;
202 g_thread_tls_module = &m; 307 entry.module = &m;
203 g_thread_tls_saved = saved; 308 entry.saved = saved;
204 g_thread_tls_block = block; 309 entry.block = block;
205 g_thread_tls_index = m.tls_index; 310 entry.index = m.tls_index;
206} 311}
207 312
208void uninstall_thread_block(Module& m) { 313void uninstall_thread_block(Module& m) {
209 if (g_thread_tls_module != &m) return; 314 if (m.tls_slot >= kMaxMappedTlsModules) return;
210 if (m.tls_block == g_thread_tls_block) { 315 const size_t slot = m.tls_slot;
316 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
317 if (entry.module != &m) return;
318 if (m.tls_block == entry.block) {
211 m.tls_block = nullptr; 319 m.tls_block = nullptr;
212 m.tls_saved_block = nullptr; 320 m.tls_saved_block = nullptr;
213 } 321 }
214 release_thread_block(); 322 release_thread_slot(slot);
215} 323}
216 324
217void run_callbacks(Module& m, uint32_t reason) { 325// `trace`: record each callback in the startup trace. Only the Loader's own calls (process attach and detach) pass
326// true; the thread events run under the Windows loader lock and stay out of the trace.
327void run_callbacks(Module& m, uint32_t reason, bool trace = false) {
218 auto* tls = tls_directory(m); 328 auto* tls = tls_directory(m);
219 if (!tls || !tls->AddressOfCallBacks) return; 329 if (!tls || !tls->AddressOfCallBacks) return;
220 const uint64_t table_rva = rva_in(m, tls->AddressOfCallBacks, "the TLS callback table"); 330 const uint64_t table_rva = rva_in(m, tls->AddressOfCallBacks, "the TLS callback table");
@@ -226,29 +336,37 @@ void run_callbacks(Module& m, uint32_t reason) {
226 if (!fn) break; 336 if (!fn) break;
227 auto callback = 337 auto callback =
228 reinterpret_cast<PIMAGE_TLS_CALLBACK>(m.base + rva_in(m, fn, "a TLS callback")); 338 reinterpret_cast<PIMAGE_TLS_CALLBACK>(m.base + rva_in(m, fn, "a TLS callback"));
339 if (trace && startup_trace::enabled())
340 startup_trace::event("tls_callback", "\"module\":" + startup_trace::quote(m.name) + ",\"at\":" +
341 startup_trace::quote(startup_trace::where(reinterpret_cast<uint64_t>(callback))) +
342 ",\"reason\":" + std::to_string(reason));
229 callback(m.base, static_cast<DWORD>(reason), nullptr); 343 callback(m.base, static_cast<DWORD>(reason), nullptr);
230 } 344 }
231} 345}
232 346
233// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under 347// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under
234// the Windows loader lock, on that thread. A new thread gets its own copy of the TLS owner's template; an ending one 348// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an
235// gives the helper's block back before the Windows loader frees it. TLS callbacks get the thread events only after 349// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events
236// the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. Threads that existed before the 350// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them.
237// module was loaded get nothing: install_tls_for_thread is still the way to cover those.
238void __cdecl on_host_thread_event(DWORD reason) { 351void __cdecl on_host_thread_event(DWORD reason) {
239 SharedTlsLock lock; 352 SharedTlsLock lock;
240 Module* m = g_tls_slot_owner.load();
241 try { 353 try {
242 if (reason == DLL_THREAD_ATTACH) { 354 if (reason == DLL_THREAD_ATTACH) {
243 if (!m) return; 355 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) {
244 install_thread_block(*m); 356 Module* m = g_tls_slot_owners[slot].load();
245 if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); 357 if (!m) continue;
358 install_thread_block(*m);
359 if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH);
360 }
246 } else if (reason == DLL_THREAD_DETACH) { 361 } else if (reason == DLL_THREAD_DETACH) {
247 if (m && g_thread_tls_module == m) { 362 for (size_t i = kMaxMappedTlsModules; i-- > 0;) {
248 if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH); 363 Module* m = g_tls_slot_owners[i].load();
249 uninstall_thread_block(*m); 364 if (m && g_thread_tls_slots[i].module == m) {
250 } else { 365 if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH);
251 release_thread_block(); // installed by a module whose Loader is gone (or nothing to do) 366 uninstall_thread_block(*m);
367 } else {
368 release_thread_slot(i); // installed by a module whose Loader is gone (or nothing to do)
369 }
252 } 370 }
253 } 371 }
254 } catch (const std::exception& e) { 372 } catch (const std::exception& e) {
@@ -345,10 +463,34 @@ bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t
345 } 463 }
346 return false; 464 return false;
347} 465}
466
467void* bundled_find_loaded(void* ctx, const std::string& dll_lower) {
468 return static_cast<Loader*>(ctx)->find_loaded_module(dll_lower);
469}
470
471void* bundled_load(void* ctx, const std::string& dll_lower, uint32_t flags, bool& handled) {
472 return static_cast<Loader*>(ctx)->load_runtime_module(dll_lower, flags, handled);
473}
474
475void* bundled_get_proc(void* ctx, void* module, const std::string& sym, bool& owns_handle) {
476 return static_cast<Loader*>(ctx)->resolve_module_export(module, sym, owns_handle);
477}
478
479bool bundled_owns_handle(void* ctx, void* module) {
480 return static_cast<Loader*>(ctx)->owns_module_handle(module);
481}
482
483const shims::BundledModuleOps kBundledOps{
484 &bundled_find_loaded,
485 &bundled_load,
486 &bundled_get_proc,
487 &bundled_owns_handle,
488};
348} // namespace 489} // namespace
349 490
350Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { 491Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) {
351 shims::add_module_lookup(this, &lookup_in_loader); 492 shims::add_module_lookup(this, &lookup_in_loader);
493 shims::add_bundled_loader(this, &kBundledOps);
352} 494}
353 495
354Loader::~Loader() { 496Loader::~Loader() {
@@ -372,16 +514,17 @@ Loader::~Loader() {
372 entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored 514 entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored
373 } 515 }
374 } 516 }
517 shims::remove_bundled_loader(this);
375 shims::remove_module_lookup(this); 518 shims::remove_module_lookup(this);
376 for (auto* m : order_) { 519 for (auto* m : order_) {
377 // TLS state must go away before the image and its TLS block are unmapped. 520 // TLS state must go away before the image and its TLS block are unmapped.
378 if (m->tls_index != kNoTlsIndex) { 521 if (m->tls_index != kNoTlsIndex && m->tls_slot < kMaxMappedTlsModules) {
379 // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a 522 // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a
380 // thread that still holds a copy frees it when it ends (on_host_thread_event). 523 // thread that still holds a copy frees it when it ends (on_host_thread_event).
381 { 524 {
382 ExclusiveTlsLock lock; 525 ExclusiveTlsLock lock;
383 Module* owner = m; 526 Module* owner = m;
384 g_tls_slot_owner.compare_exchange_strong(owner, nullptr); 527 g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr);
385 } 528 }
386 uninstall_tls_for_thread(*m); 529 uninstall_tls_for_thread(*m);
387 } 530 }
@@ -394,6 +537,7 @@ Loader::~Loader() {
394} 537}
395 538
396Module& Loader::load(const std::filesystem::path& image) { 539Module& Loader::load(const std::filesystem::path& image) {
540 std::lock_guard lock(mutex_);
397 std::string key = lower(image.filename().string()); 541 std::string key = lower(image.filename().string());
398 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; 542 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second;
399 Module& m = map_image(image); 543 Module& m = map_image(image);
@@ -401,9 +545,105 @@ Module& Loader::load(const std::filesystem::path& image) {
401 protect_sections(m); 545 protect_sections(m);
402 register_unwind(m); 546 register_unwind(m);
403 init_order_.push_back(&m); 547 init_order_.push_back(&m);
548 if (startup_trace::enabled())
549 startup_trace::event("map", "\"module\":" + startup_trace::quote(m.name) +
550 ",\"base\":" + startup_trace::quote(startup_trace::hex(reinterpret_cast<uint64_t>(m.base))) +
551 ",\"size\":" + startup_trace::quote(startup_trace::hex(m.size)) +
552 ",\"relocated\":" + (m.relocated ? "true" : "false"));
404 return m; 553 return m;
405} 554}
406 555
556void* Loader::find_loaded_module(const std::string& dll_lower) const {
557 std::lock_guard lock(mutex_);
558 auto it = by_name_.find(dll_lower);
559 return it == by_name_.end() ? nullptr : static_cast<void*>(it->second->base);
560}
561
562void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled) {
563 handled = false;
564 if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr;
565
566 std::lock_guard lock(mutex_);
567 const auto existing = by_name_.find(dll_lower);
568 const std::filesystem::path candidate = game_dir_ / dll_lower;
569 std::error_code ec;
570 const bool is_bundled = existing != by_name_.end() || std::filesystem::is_regular_file(candidate, ec);
571 if (!is_bundled) return nullptr;
572
573 handled = true;
574 // Win32 DONT_RESOLVE_DLL_REFERENCES (0x1) forbids resolving dependencies or running TLS/DllMain; refuse it
575 // explicitly instead of silently performing a normal resolving + initialising load.
576 if ((flags & DONT_RESOLVE_DLL_REFERENCES) != 0) {
577 std::fprintf(stderr,
578 "[rt] loader: LoadLibraryEx(%s, DONT_RESOLVE_DLL_REFERENCES) is not supported for bundled DLLs\n",
579 dll_lower.c_str());
580 SetLastError(ERROR_NOT_SUPPORTED);
581 return nullptr;
582 }
583
584 if (existing != by_name_.end()) {
585 try {
586 initialise();
587 return static_cast<void*>(existing->second->base);
588 } catch (const std::exception& e) {
589 std::fprintf(stderr, "[rt] loader: run-time initialise of %s failed: %s\n", dll_lower.c_str(), e.what());
590 SetLastError(ERROR_DLL_INIT_FAILED);
591 return nullptr;
592 }
593 }
594
595 try {
596 Module& m = load(candidate);
597 initialise();
598 std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str());
599 return static_cast<void*>(m.base);
600 } catch (const std::exception& e) {
601 // Do not leave a failed run-time load indexed by name so later GetModuleHandle/LoadLibrary calls do not
602 // observe a half-initialised module. ~Loader still frees any VirtualAlloc'd mapping in order_.
603 by_name_.erase(dll_lower);
604 std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what());
605 SetLastError(ERROR_DLL_INIT_FAILED);
606 return nullptr;
607 }
608}
609
610void* Loader::resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle) {
611 owns_handle = false;
612 if (!module_handle) return nullptr;
613 std::lock_guard lock(mutex_);
614 Module* target = nullptr;
615 for (Module* m : order_) {
616 if (m->base == module_handle) {
617 target = m;
618 break;
619 }
620 }
621 if (!target) return nullptr;
622 owns_handle = true;
623 if (auto it = target->exports.find(sym); it != target->exports.end()) return it->second;
624 if (auto it = target->forwarders.find(sym); it != target->forwarders.end()) {
625 try {
626 Binding binding = Binding::Unimplemented;
627 void* fn = resolve_forwarder(it->second, binding, 0);
628 if (binding == Binding::Module) initialise();
629 return fn;
630 } catch (const std::exception& e) {
631 std::fprintf(stderr, "[rt] loader: forwarder %s from %s failed: %s\n", it->second.c_str(),
632 target->name.c_str(), e.what());
633 return nullptr;
634 }
635 }
636 return nullptr;
637}
638
639bool Loader::owns_module_handle(void* module_handle) const {
640 if (!module_handle) return false;
641 std::lock_guard lock(mutex_);
642 for (const Module* m : order_)
643 if (m->base == module_handle) return true;
644 return false;
645}
646
407// x64 has no frame-pointer chain to fall back on: without its .pdata registered, an exception raised in (or passing 647// x64 has no frame-pointer chain to fall back on: without its .pdata registered, an exception raised in (or passing
408// through) a mapped image can't be dispatched past that frame, and the process dies. Images the system loader maps 648// through) a mapped image can't be dispatched past that frame, and the process dies. Images the system loader maps
409// are found through its own module list; ours are VirtualAlloc'd, so they are registered as dynamic function tables. 649// are found through its own module list; ours are VirtualAlloc'd, so they are registered as dynamic function tables.
@@ -458,7 +698,11 @@ void Loader::initialise(Module& m) {
458 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { 698 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) {
459 if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image"); 699 if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image");
460 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); 700 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva);
461 if (!entry(m.base, DLL_PROCESS_ATTACH, nullptr)) { 701 const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, nullptr);
702 if (startup_trace::enabled())
703 startup_trace::event("dllmain", "\"module\":" + startup_trace::quote(m.name) +
704 ",\"result\":" + std::to_string(ok));
705 if (!ok) {
462 set_initialised(m, true); // it ran: a second DLL_PROCESS_ATTACH would be wrong 706 set_initialised(m, true); // it ran: a second DLL_PROCESS_ATTACH would be wrong
463 throw std::runtime_error(m.name + ": DllMain returned FALSE"); 707 throw std::runtime_error(m.name + ": DllMain returned FALSE");
464 } 708 }
@@ -604,19 +848,36 @@ void Loader::initialize_tls(Module& m) {
604 require_range(m.name, index_rva, sizeof(uint32_t), m.size, "the TLS index"); 848 require_range(m.name, index_rva, sizeof(uint32_t), m.size, "the TLS index");
605 } 849 }
606 850
607 DWORD index = tls_host().index;
608 if (index == TLS_OUT_OF_INDEXES)
609 throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index");
610 if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range");
611 if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); 851 if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array");
612 852
853 size_t slot = kMaxMappedTlsModules;
854 DWORD index = TLS_OUT_OF_INDEXES;
613 { 855 {
856 std::lock_guard alloc_lock(g_tls_alloc_mutex);
857 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) {
858 if (g_tls_slot_owners[i].load() == nullptr) {
859 slot = i;
860 break;
861 }
862 }
863 if (slot >= kMaxMappedTlsModules)
864 throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) +
865 " manually mapped static TLS slots are in use");
866
867 // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with
868 // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock).
869 index = ensure_tls_host(slot).index;
870 if (index == TLS_OUT_OF_INDEXES)
871 throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index");
872 if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range");
873
614 // The fields are complete before a thread event can see the owner. 874 // The fields are complete before a thread event can see the owner.
615 ExclusiveTlsLock lock; 875 ExclusiveTlsLock lock;
616 Module* expected = nullptr; 876 Module* expected = nullptr;
617 if (!g_tls_slot_owner.compare_exchange_strong(expected, &m)) 877 if (!g_tls_slot_owners[slot].compare_exchange_strong(expected, &m))
618 throw std::runtime_error(m.name + ": only one manually mapped module may use static TLS at a time"); 878 throw std::runtime_error(m.name + ": static TLS slot was claimed concurrently");
619 879
880 m.tls_slot = static_cast<uint32_t>(slot);
620 m.tls_index = index; 881 m.tls_index = index;
621 m.tls_template = raw ? m.base + raw_rva : nullptr; 882 m.tls_template = raw ? m.base + raw_rva : nullptr;
622 m.tls_raw_size = static_cast<uint32_t>(raw); 883 m.tls_raw_size = static_cast<uint32_t>(raw);
@@ -631,13 +892,14 @@ void Loader::initialize_tls(Module& m) {
631 } catch (...) { 892 } catch (...) {
632 ExclusiveTlsLock lock; 893 ExclusiveTlsLock lock;
633 m.tls_index = kNoTlsIndex; 894 m.tls_index = kNoTlsIndex;
634 g_tls_slot_owner = nullptr; 895 m.tls_slot = kNoTlsIndex;
896 g_tls_slot_owners[slot].store(nullptr);
635 throw; 897 throw;
636 } 898 }
637 // The loading thread's copy is the one the Module records (and ~Loader frees on that thread). 899 // The loading thread's copy is the one the Module records (and ~Loader frees on that thread).
638 if (g_thread_tls_module == &m) { 900 if (g_thread_tls_slots[slot].module == &m) {
639 m.tls_block = g_thread_tls_block; 901 m.tls_block = g_thread_tls_slots[slot].block;
640 m.tls_saved_block = g_thread_tls_saved; 902 m.tls_saved_block = g_thread_tls_slots[slot].saved;
641 } 903 }
642} 904}
643 905
@@ -645,7 +907,7 @@ void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); }
645 907
646void Loader::uninstall_tls_for_thread(Module& m) { uninstall_thread_block(m); } 908void Loader::uninstall_tls_for_thread(Module& m) { uninstall_thread_block(m); }
647 909
648void Loader::run_tls_callbacks(Module& m, uint32_t reason) { run_callbacks(m, reason); } 910void Loader::run_tls_callbacks(Module& m, uint32_t reason) { run_callbacks(m, reason, /*trace=*/true); }
649 911
650void Loader::parse_exports(Module& m) { 912void Loader::parse_exports(Module& m) {
651 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 913 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
@@ -669,6 +931,8 @@ void Loader::parse_exports(Module& m) {
669 auto add_export = [&](const std::string& key, uint32_t rva) { 931 auto add_export = [&](const std::string& key, uint32_t rva) {
670 if (rva >= dir_begin && rva < dir_end) 932 if (rva >= dir_begin && rva < dir_end)
671 m.forwarders[key] = read_string(m.name, m.base, m.size, rva, "a forwarded export"); 933 m.forwarders[key] = read_string(m.name, m.base, m.size, rva, "a forwarded export");
934 else if (rva >= m.size) // base + rva would point past the mapping, and a caller would jump there
935 throw std::runtime_error(m.name + ": export " + key + " points outside the image");
672 else 936 else
673 m.exports[key] = m.base + rva; 937 m.exports[key] = m.base + rva;
674 }; 938 };
@@ -709,10 +973,12 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d
709 } 973 }
710 } 974 }
711 975
976 // shim_key, not the bare module name: forwarder strings usually leave out ".dll" ("MSVCP140.?foo"), and the host
977 // CRT copies are named with it, so a forwarded CRT symbol must skip the bundled Xbox build as a direct import does.
712 const std::filesystem::path candidates[] = {game_dir_ / module, game_dir_ / (module + ".dll")}; 978 const std::filesystem::path candidates[] = {game_dir_ / module, game_dir_ / (module + ".dll")};
713 for (const auto& candidate : candidates) { 979 for (const auto& candidate : candidates) {
714 std::error_code ec; 980 std::error_code ec;
715 if (prefer_host_copy(lower(module)) || !std::filesystem::exists(candidate, ec)) continue; 981 if (prefer_host_copy(shim_key) || !std::filesystem::exists(candidate, ec)) continue;
716 Module& dep = load(candidate); 982 Module& dep = load(candidate);
717 if (auto it = dep.exports.find(symbol); it != dep.exports.end()) { 983 if (auto it = dep.exports.find(symbol); it != dep.exports.end()) {
718 binding = Binding::Module; 984 binding = Binding::Module;