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:
authoromardev29 <154835571+omardev29@users.noreply.github.com>2026-11-22 05:27:50 +0100
committeromardev29 <154835571+omardev29@users.noreply.github.com>2026-11-22 12:29:51 +0100
commite5d44d4b0fa912a902d59e6467fb7ddaab271fde (patch)
tree5137a226aa39866d58a80f6af19dcc0666827b1e /runtime/src/pe_loader.cpp
parenta19602633b7f0e6ff5db7725c89a1bd11c244686 (diff)
Loader: give every thread started after load() its own TLS copy
Until now only the thread that called load() had the mapped image's TLS; any other thread read gta6rt_tls_host.dll's block through _tls_index, so a thread_local on the game's own threads (gta6rt runs the entry point on a new thread) started from the wrong data: tiny_game's thread_local check fails on main with LEONIDA_RUN_TLS=1. The loader now registers for the helper's thread events. On DLL_THREAD_ATTACH the new thread gets a fresh copy of the template in the reserved slot; on DLL_THREAD_DETACH the helper's own block goes back before the Windows loader frees the array. Once initialise() has run the module, the events also run its TLS callbacks (as Windows does: thread events only after DLL_PROCESS_ATTACH), with the copy already in place. An SRW lock orders the owner's publication, its initialised flag and its retirement in ~Loader against the events, which run under the loader lock; the exclusive sections only write fields. ~Loader retires the owner before uninstalling, so a thread that outlives its Loader frees its copy from its own record without touching the freed Module. Module::tls_block stays the loading thread's copy, now set by initialize_tls only. install_tls_for_thread remains for threads that existed before load(); on a thread that already has the copy it is a no-op, which the updated worker check shows.
Diffstat (limited to 'runtime/src/pe_loader.cpp')
-rw-r--r--runtime/src/pe_loader.cpp241
1 files changed, 164 insertions, 77 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index 15a62d9b4..f4579ec27 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -75,6 +75,8 @@ IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) {
75constexpr DWORD kMaxModuleTlsSlots = 64; 75constexpr DWORD kMaxModuleTlsSlots = 64;
76void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); } 76void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); }
77 77
78void __cdecl on_host_thread_event(DWORD reason);
79
78struct TlsHostModule { 80struct TlsHostModule {
79 HMODULE module = nullptr; 81 HMODULE module = nullptr;
80 DWORD index = TLS_OUT_OF_INDEXES; 82 DWORD index = TLS_OUT_OF_INDEXES;
@@ -117,6 +119,10 @@ TlsHostModule load_tls_host() {
117 return host; 119 return host;
118 } 120 }
119 host.index = *reinterpret_cast<DWORD*>(tls->AddressOfIndex); 121 host.index = *reinterpret_cast<DWORD*>(tls->AddressOfIndex);
122 // From here on the helper's DllMain reports every thread the process starts or ends (on_host_thread_event).
123 using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD));
124 if (auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event")))
125 set(&on_host_thread_event);
120 return host; 126 return host;
121} 127}
122 128
@@ -134,6 +140,121 @@ std::atomic<Module*> g_tls_slot_owner{nullptr};
134thread_local Module* g_thread_tls_module = nullptr; 140thread_local Module* g_thread_tls_module = nullptr;
135thread_local void* g_thread_tls_saved = nullptr; 141thread_local void* g_thread_tls_saved = nullptr;
136thread_local void* g_thread_tls_block = nullptr; 142thread_local void* g_thread_tls_block = nullptr;
143thread_local uint32_t g_thread_tls_index = kNoTlsIndex;
144
145// Orders the TLS owner's publication, its `initialised` flag and its retirement against the thread events. Shared in
146// on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows
147// loader lock, which the events run under).
148SRWLOCK g_tls_lock = SRWLOCK_INIT;
149struct SharedTlsLock {
150 SharedTlsLock() { AcquireSRWLockShared(&g_tls_lock); }
151 ~SharedTlsLock() { ReleaseSRWLockShared(&g_tls_lock); }
152 SharedTlsLock(const SharedTlsLock&) = delete;
153 SharedTlsLock& operator=(const SharedTlsLock&) = delete;
154};
155struct ExclusiveTlsLock {
156 ExclusiveTlsLock() { AcquireSRWLockExclusive(&g_tls_lock); }
157 ~ExclusiveTlsLock() { ReleaseSRWLockExclusive(&g_tls_lock); }
158 ExclusiveTlsLock(const ExclusiveTlsLock&) = delete;
159 ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete;
160};
161
162// Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this
163// thread's record, so it also works after the module that installed the copy is gone.
164void release_thread_block() {
165 if (!g_thread_tls_block) return;
166 void** slots = module_tls_slots();
167 if (slots && g_thread_tls_index < kMaxModuleTlsSlots && slots[g_thread_tls_index] == g_thread_tls_block)
168 slots[g_thread_tls_index] = g_thread_tls_saved;
169 VirtualFree(g_thread_tls_block, 0, MEM_RELEASE);
170 g_thread_tls_module = nullptr;
171 g_thread_tls_saved = nullptr;
172 g_thread_tls_block = nullptr;
173 g_thread_tls_index = kNoTlsIndex;
174}
175
176void install_thread_block(Module& m) {
177 if (m.tls_index == kNoTlsIndex) return;
178 if (g_thread_tls_module == &m) return;
179 if (g_thread_tls_module) {
180 // A copy left by a module whose Loader is gone is released; a live module's is a conflict.
181 if (g_thread_tls_module == g_tls_slot_owner.load())
182 throw std::runtime_error("another manually mapped module's TLS is already installed in this thread");
183 release_thread_block();
184 }
185
186 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill;
187 if (!total) return;
188 void** slots = module_tls_slots();
189 if (!slots || m.tls_index >= kMaxModuleTlsSlots)
190 throw std::runtime_error(m.name + ": cannot install TLS in this thread");
191
192 void* block = VirtualAlloc(nullptr, static_cast<SIZE_T>(total), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
193 if (!block) throw std::runtime_error(m.name + ": TLS block allocation failed");
194 if (m.tls_raw_size) std::memcpy(block, m.tls_template, m.tls_raw_size);
195 if (m.tls_zero_fill)
196 std::memset(static_cast<uint8_t*>(block) + m.tls_raw_size, 0, m.tls_zero_fill);
197
198 void* saved = slots[m.tls_index];
199 slots[m.tls_index] = block;
200 g_thread_tls_module = &m;
201 g_thread_tls_saved = saved;
202 g_thread_tls_block = block;
203 g_thread_tls_index = m.tls_index;
204}
205
206void uninstall_thread_block(Module& m) {
207 if (g_thread_tls_module != &m) return;
208 if (m.tls_block == g_thread_tls_block) {
209 m.tls_block = nullptr;
210 m.tls_saved_block = nullptr;
211 }
212 release_thread_block();
213}
214
215void run_callbacks(Module& m, uint32_t reason) {
216 auto* tls = tls_directory(m);
217 if (!tls || !tls->AddressOfCallBacks) return;
218 const uint64_t table_rva = rva_in(m, tls->AddressOfCallBacks, "the TLS callback table");
219 // The callback table has no length field: it ends at a zero entry, so every step is checked against the image.
220 for (uint64_t i = 0;; ++i) {
221 const uint64_t entry_rva = table_rva + i * sizeof(uint64_t);
222 require_range(m.name, entry_rva, sizeof(uint64_t), m.size, "a TLS callback table entry");
223 const uint64_t fn = *at<uint64_t>(m.base, static_cast<uint32_t>(entry_rva));
224 if (!fn) break;
225 auto callback =
226 reinterpret_cast<PIMAGE_TLS_CALLBACK>(m.base + rva_in(m, fn, "a TLS callback"));
227 callback(m.base, static_cast<DWORD>(reason), nullptr);
228 }
229}
230
231// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under
232// the Windows loader lock, on that thread. A new thread gets its own copy of the TLS owner's template; an ending one
233// gives the helper's block back before the Windows loader frees it. TLS callbacks get the thread events only after
234// the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. Threads that existed before the
235// module was loaded get nothing: install_tls_for_thread is still the way to cover those.
236void __cdecl on_host_thread_event(DWORD reason) {
237 SharedTlsLock lock;
238 Module* m = g_tls_slot_owner.load();
239 try {
240 if (reason == DLL_THREAD_ATTACH) {
241 if (!m) return;
242 install_thread_block(*m);
243 if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH);
244 } else if (reason == DLL_THREAD_DETACH) {
245 if (m && g_thread_tls_module == m) {
246 if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH);
247 uninstall_thread_block(*m);
248 } else {
249 release_thread_block(); // installed by a module whose Loader is gone (or nothing to do)
250 }
251 }
252 } catch (const std::exception& e) {
253 // Nothing may leave DllMain. The thread runs on without the module's TLS (attach) or keeps the copy (detach).
254 std::fprintf(stderr, "[rt] loader: thread %s: %s\n", reason == DLL_THREAD_ATTACH ? "attach" : "detach",
255 e.what());
256 }
257}
137 258
138// The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used. 259// The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used.
139bool prefer_host_copy(const std::string& dll) { 260bool prefer_host_copy(const std::string& dll) {
@@ -172,7 +293,7 @@ Loader::~Loader() {
172 for (auto it = init_order_.rbegin(); it != init_order_.rend(); ++it) { 293 for (auto it = init_order_.rbegin(); it != init_order_.rend(); ++it) {
173 Module& m = **it; 294 Module& m = **it;
174 if (!m.initialised) continue; // a map-only load never opts in to running image code 295 if (!m.initialised) continue; // a map-only load never opts in to running image code
175 m.initialised = false; 296 set_initialised(m, false); // under the TLS lock: thread events stop running its callbacks
176 try { 297 try {
177 run_tls_callbacks(m, DLL_PROCESS_DETACH); 298 run_tls_callbacks(m, DLL_PROCESS_DETACH);
178 } catch (const std::exception& e) { 299 } catch (const std::exception& e) {
@@ -190,11 +311,14 @@ Loader::~Loader() {
190 for (auto* m : order_) { 311 for (auto* m : order_) {
191 // TLS state must go away before the image and its TLS block are unmapped. 312 // TLS state must go away before the image and its TLS block are unmapped.
192 if (m->tls_index != kNoTlsIndex) { 313 if (m->tls_index != kNoTlsIndex) {
193 // Only the loading thread has this module installed; other threads must uninstall for themselves before 314 // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a
194 // the Loader is destroyed. 315 // thread that still holds a copy frees it when it ends (on_host_thread_event).
316 {
317 ExclusiveTlsLock lock;
318 Module* owner = m;
319 g_tls_slot_owner.compare_exchange_strong(owner, nullptr);
320 }
195 uninstall_tls_for_thread(*m); 321 uninstall_tls_for_thread(*m);
196 Module* owner = m;
197 g_tls_slot_owner.compare_exchange_strong(owner, nullptr);
198 } 322 }
199 // Before the image is freed: a stale table would let a later stack walk read unmapped memory. 323 // Before the image is freed: a stale table would let a later stack walk read unmapped memory.
200 if (m->function_table) RtlDeleteFunctionTable(static_cast<PRUNTIME_FUNCTION>(m->function_table)); 324 if (m->function_table) RtlDeleteFunctionTable(static_cast<PRUNTIME_FUNCTION>(m->function_table));
@@ -270,11 +394,18 @@ void Loader::initialise(Module& m) {
270 if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image"); 394 if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image");
271 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); 395 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva);
272 if (!entry(m.base, DLL_PROCESS_ATTACH, nullptr)) { 396 if (!entry(m.base, DLL_PROCESS_ATTACH, nullptr)) {
273 m.initialised = true; // it ran: a second DLL_PROCESS_ATTACH would be wrong 397 set_initialised(m, true); // it ran: a second DLL_PROCESS_ATTACH would be wrong
274 throw std::runtime_error(m.name + ": DllMain returned FALSE"); 398 throw std::runtime_error(m.name + ": DllMain returned FALSE");
275 } 399 }
276 } 400 }
277 m.initialised = true; 401 set_initialised(m, true);
402}
403
404// Under the TLS lock, which orders it against the thread events: they run a module's TLS callbacks only while this is
405// true (from initialise() until ~Loader starts the process detach).
406void Loader::set_initialised(Module& m, bool value) {
407 ExclusiveTlsLock lock;
408 m.initialised = value;
278} 409}
279 410
280Module& Loader::map_image(const std::filesystem::path& path) { 411Module& Loader::map_image(const std::filesystem::path& path) {
@@ -407,86 +538,42 @@ void Loader::initialize_tls(Module& m) {
407 if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range"); 538 if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range");
408 if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); 539 if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array");
409 540
410 Module* expected = nullptr; 541 {
411 if (!g_tls_slot_owner.compare_exchange_strong(expected, &m)) 542 // The fields are complete before a thread event can see the owner.
412 throw std::runtime_error(m.name + ": only one manually mapped module may use static TLS at a time"); 543 ExclusiveTlsLock lock;
413 544 Module* expected = nullptr;
414 m.tls_index = index; 545 if (!g_tls_slot_owner.compare_exchange_strong(expected, &m))
415 m.tls_template = raw ? m.base + raw_rva : nullptr; 546 throw std::runtime_error(m.name + ": only one manually mapped module may use static TLS at a time");
416 m.tls_raw_size = static_cast<uint32_t>(raw); 547
417 m.tls_zero_fill = tls->SizeOfZeroFill; 548 m.tls_index = index;
418 m.tls_block_size = static_cast<uint32_t>(total); 549 m.tls_template = raw ? m.base + raw_rva : nullptr;
419 // The index lives in a writable section and protect_sections() has not run yet, so the write needs no 550 m.tls_raw_size = static_cast<uint32_t>(raw);
420 // VirtualProtect dance. 551 m.tls_zero_fill = tls->SizeOfZeroFill;
421 if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index; 552 m.tls_block_size = static_cast<uint32_t>(total);
553 // The index lives in a writable section and protect_sections() has not run yet, so the write needs no
554 // VirtualProtect dance.
555 if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index;
556 }
422 try { 557 try {
423 install_tls_for_thread(m); 558 install_thread_block(m);
424 } catch (...) { 559 } catch (...) {
560 ExclusiveTlsLock lock;
425 m.tls_index = kNoTlsIndex; 561 m.tls_index = kNoTlsIndex;
426 g_tls_slot_owner = nullptr; 562 g_tls_slot_owner = nullptr;
427 throw; 563 throw;
428 } 564 }
429} 565 // The loading thread's copy is the one the Module records (and ~Loader frees on that thread).
430 566 if (g_thread_tls_module == &m) {
431void Loader::install_tls_for_thread(Module& m) { 567 m.tls_block = g_thread_tls_block;
432 if (m.tls_index == kNoTlsIndex) return; 568 m.tls_saved_block = g_thread_tls_saved;
433 if (g_thread_tls_module == &m) return;
434 if (g_thread_tls_module)
435 throw std::runtime_error("another manually mapped module's TLS is already installed in this thread");
436
437 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill;
438 if (!total) return;
439 void** slots = module_tls_slots();
440 if (!slots || m.tls_index >= kMaxModuleTlsSlots)
441 throw std::runtime_error(m.name + ": cannot install TLS in this thread");
442
443 void* block = VirtualAlloc(nullptr, static_cast<SIZE_T>(total), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
444 if (!block) throw std::runtime_error(m.name + ": TLS block allocation failed");
445 if (m.tls_raw_size) std::memcpy(block, m.tls_template, m.tls_raw_size);
446 if (m.tls_zero_fill)
447 std::memset(static_cast<uint8_t*>(block) + m.tls_raw_size, 0, m.tls_zero_fill);
448
449 void* saved = slots[m.tls_index];
450 slots[m.tls_index] = block;
451 g_thread_tls_module = &m;
452 g_thread_tls_saved = saved;
453 g_thread_tls_block = block;
454 if (!m.tls_block) {
455 m.tls_block = block;
456 m.tls_saved_block = saved;
457 } 569 }
458} 570}
459 571
460void Loader::uninstall_tls_for_thread(Module& m) { 572void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); }
461 if (g_thread_tls_module != &m) return;
462 void** slots = module_tls_slots();
463 if (slots && m.tls_index < kMaxModuleTlsSlots && slots[m.tls_index] == g_thread_tls_block)
464 slots[m.tls_index] = g_thread_tls_saved;
465 if (m.tls_block == g_thread_tls_block) {
466 m.tls_block = nullptr;
467 m.tls_saved_block = nullptr;
468 }
469 VirtualFree(g_thread_tls_block, 0, MEM_RELEASE);
470 g_thread_tls_module = nullptr;
471 g_thread_tls_saved = nullptr;
472 g_thread_tls_block = nullptr;
473}
474 573
475void Loader::run_tls_callbacks(Module& m, uint32_t reason) { 574void Loader::uninstall_tls_for_thread(Module& m) { uninstall_thread_block(m); }
476 auto* tls = tls_directory(m); 575
477 if (!tls || !tls->AddressOfCallBacks) return; 576void Loader::run_tls_callbacks(Module& m, uint32_t reason) { run_callbacks(m, reason); }
478 const uint64_t table_rva = rva_in(m, tls->AddressOfCallBacks, "the TLS callback table");
479 // The callback table has no length field: it ends at a zero entry, so every step is checked against the image.
480 for (uint64_t i = 0;; ++i) {
481 const uint64_t entry_rva = table_rva + i * sizeof(uint64_t);
482 require_range(m.name, entry_rva, sizeof(uint64_t), m.size, "a TLS callback table entry");
483 const uint64_t fn = *at<uint64_t>(m.base, static_cast<uint32_t>(entry_rva));
484 if (!fn) break;
485 auto callback =
486 reinterpret_cast<PIMAGE_TLS_CALLBACK>(m.base + rva_in(m, fn, "a TLS callback"));
487 callback(m.base, static_cast<DWORD>(reason), nullptr);
488 }
489}
490 577
491void Loader::parse_exports(Module& m) { 578void Loader::parse_exports(Module& m) {
492 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 579 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);