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:
authorkotorvr <332716892+kotorvr@users.noreply.github.com>2026-11-22 20:40:54 +0000
committerkotorvr <332716892+kotorvr@users.noreply.github.com>2026-11-22 20:40:54 +0000
commitb418319ae9ff68177adcd92b1e55e12972858188 (patch)
treed10b32e80ee719391313dbce8f81f062001c9cdb /runtime/src/pe_loader.cpp
parentf847748cc76bd3777f9c070c4034eb2fc1c04e64 (diff)
loader: static TLS for threads that were running before load()
load() installed the image's TLS block on its caller, and the helper DLL's DLL_THREAD_ATTACH covers threads started later. A thread that was already running kept the helper's one-byte block in the reserved slot, so mapped __declspec(thread) code on it read and wrote past it. The process thread pool's workers are such threads, and the task queue runs a title's callbacks on them. load() now gives every other running thread its own copy of the template through that thread's TEB, as Windows does for a DLL it loads itself: a block, no DLL_THREAD_ATTACH. The block comes out in the thread's own DLL_THREAD_DETACH (after the module's TLS callbacks) or in ~Loader. loader_tls_test: a thread and a pool worker that exist before load(), across two mappings of the fixture. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src/pe_loader.cpp')
-rw-r--r--runtime/src/pe_loader.cpp229
1 files changed, 229 insertions, 0 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index f2c62ec91..f29c64a7a 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -2,6 +2,7 @@
2 2
3#include <windows.h> 3#include <windows.h>
4#include <intrin.h> 4#include <intrin.h>
5#include <tlhelp32.h>
5 6
6#include <algorithm> 7#include <algorithm>
7#include <array> 8#include <array>
@@ -274,11 +275,50 @@ void release_thread_slot(size_t slot) {
274 entry = ThreadTlsSlot{}; 275 entry = ThreadTlsSlot{};
275} 276}
276 277
278// A block load() put into a thread that was already running (install_on_existing_threads). Such a thread has no
279// g_thread_tls_slots record of it: the record is here, keyed by thread id, and the thread's own DLL_THREAD_DETACH or
280// the module's ~Loader takes the block out again.
281struct ExistingThreadBlock {
282 DWORD thread = 0;
283 size_t slot = 0;
284 Module* module = nullptr;
285 uint32_t index = kNoTlsIndex;
286 void*** vector = nullptr; // that thread's TEB->ThreadLocalStoragePointer field; the array itself can be replaced
287 void* saved = nullptr; // what the block replaced
288 void* block = nullptr;
289};
290
291// Immortal, like the thread events that use them. `ended` holds the ids of threads whose DLL_THREAD_DETACH has run:
292// Windows frees such a thread's TLS array next, so nothing may be put into it any more.
293struct ExistingThreads {
294 SRWLOCK lock = SRWLOCK_INIT; // a leaf: nothing is called while it is held but VirtualFree and thread queries
295 std::vector<ExistingThreadBlock> blocks;
296 std::vector<DWORD> ended;
297};
298ExistingThreads& existing_threads() {
299 static auto* state = new ExistingThreads;
300 return *state;
301}
302struct ExistingThreadsLock {
303 ExistingThreadsLock() { AcquireSRWLockExclusive(&existing_threads().lock); }
304 ~ExistingThreadsLock() { ReleaseSRWLockExclusive(&existing_threads().lock); }
305 ExistingThreadsLock(const ExistingThreadsLock&) = delete;
306 ExistingThreadsLock& operator=(const ExistingThreadsLock&) = delete;
307};
308
309bool has_existing_thread_block(DWORD thread, const Module& m) {
310 ExistingThreadsLock lock;
311 for (const auto& b : existing_threads().blocks)
312 if (b.thread == thread && b.module == &m) return true;
313 return false;
314}
315
277void install_thread_block(Module& m) { 316void install_thread_block(Module& m) {
278 if (m.tls_slot >= kMaxMappedTlsModules) return; 317 if (m.tls_slot >= kMaxMappedTlsModules) return;
279 const size_t slot = m.tls_slot; 318 const size_t slot = m.tls_slot;
280 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 319 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
281 if (entry.module == &m) return; 320 if (entry.module == &m) return;
321 if (has_existing_thread_block(GetCurrentThreadId(), m)) return; // load() already gave this thread its copy
282 if (entry.module) { 322 if (entry.module) {
283 // A copy left by a module whose Loader is gone is released; a live module's is a conflict. 323 // A copy left by a module whose Loader is gone is released; a live module's is a conflict.
284 if (entry.module == g_tls_slot_owners[slot].load()) 324 if (entry.module == g_tls_slot_owners[slot].load())
@@ -345,6 +385,189 @@ void run_callbacks(Module& m, uint32_t reason, bool trace = false) {
345 } 385 }
346} 386}
347 387
388// ---- Threads that existed before load() ---------------------------------------------------------------------------
389//
390// When Windows loads a DLL with static TLS itself, every running thread gets a block for it (and no DLL_THREAD_ATTACH).
391// The helper DLL gets exactly that, so in a thread that was already running the reserved slot holds the helper's
392// one-byte block, and mapped __declspec(thread) code there would read and write past it. Such threads are not rare:
393// the workers of the process thread pool predate most loads, and the task queue runs a title's callbacks on them.
394// load() therefore gives each of them a copy of the template too, through the thread's TEB, which is ordinary memory
395// of this process.
396//
397// What makes that safe:
398// - The slot is the helper's, and nothing reads the helper's variable, so swapping the pointer under a running
399// thread disturbs nothing; the thread cannot be in mapped code of a module whose load() has not returned.
400// - The swap is made with g_tls_lock held exclusively, so no thread is inside its attach or detach event meanwhile.
401// - A thread whose detach event has run is skipped (`ended`), and so is one with no TLS array or no helper block:
402// Windows is about to free, or never built, what the block would go into.
403// - The block comes out again in that thread's own detach event, before Windows frees the array, or in ~Loader.
404// What is left: a thread that ran its detach event before the helper DLL was ever loaded and has not left the
405// process yet is not in `ended`; if Windows leaves a stale array pointer in its TEB for those last instructions,
406// the write goes to freed heap memory. And if another thread makes Windows replace a thread's TLS array (by loading
407// a DLL with static TLS) during the swap, that thread can keep the helper's block.
408using QueryThreadFn = LONG(NTAPI*)(HANDLE, int, void*, ULONG, ULONG*);
409struct ThreadBasicInfo { // THREAD_BASIC_INFORMATION (winternl.h keeps it opaque), x64
410 LONG exit_status;
411 void* teb;
412 void* process_id;
413 void* thread_id;
414 ULONG_PTR affinity;
415 LONG priority;
416 LONG base_priority;
417};
418static_assert(sizeof(ThreadBasicInfo) == 48);
419
420QueryThreadFn query_thread_fn() {
421 static const auto fn = reinterpret_cast<QueryThreadFn>(
422 reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread")));
423 return fn;
424}
425
426// The TEB's ThreadLocalStoragePointer field of a thread that is still running; null otherwise.
427void*** running_thread_tls_vector(HANDLE thread) {
428 ThreadBasicInfo info{};
429 const QueryThreadFn query = query_thread_fn();
430 if (!query || query(thread, 0 /* ThreadBasicInformation */, &info, sizeof info, nullptr) < 0) return nullptr;
431 if (info.exit_status != STILL_ACTIVE || !info.teb) return nullptr;
432 return reinterpret_cast<void***>(static_cast<uint8_t*>(info.teb) + 0x58);
433}
434
435// Takes a block out of its slot and frees it. The existing-threads lock is held; b.vector is null when the thread
436// is gone.
437void remove_existing_block(const ExistingThreadBlock& b) {
438 if (b.vector) {
439 void** slots = *b.vector;
440 if (slots && b.index < kMaxModuleTlsSlots && slots[b.index] == b.block) slots[b.index] = b.saved;
441 }
442 VirtualFree(b.block, 0, MEM_RELEASE);
443}
444
445// load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done.
446void install_on_existing_threads(Module& m) {
447 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill;
448 if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kMaxMappedTlsModules) return;
449 if (!query_thread_fn()) return;
450
451 // Outside the TLS lock: none of this may wait for a thread that is inside its attach event.
452 struct Candidate {
453 DWORD id;
454 HANDLE handle;
455 };
456 std::vector<Candidate> candidates;
457 const HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
458 if (snapshot == INVALID_HANDLE_VALUE) return;
459 THREADENTRY32 entry{};
460 entry.dwSize = sizeof entry;
461 const DWORD process = GetCurrentProcessId(), self = GetCurrentThreadId();
462 for (BOOL more = Thread32First(snapshot, &entry); more; more = Thread32Next(snapshot, &entry)) {
463 if (entry.th32OwnerProcessID != process || entry.th32ThreadID == self) continue;
464 if (HANDLE h = OpenThread(THREAD_QUERY_INFORMATION, FALSE, entry.th32ThreadID))
465 candidates.push_back({entry.th32ThreadID, h});
466 }
467 CloseHandle(snapshot);
468
469 {
470 ExclusiveTlsLock tls_lock;
471 ExistingThreadsLock lock;
472 ExistingThreads& state = existing_threads();
473 for (const Candidate& c : candidates) {
474 if (std::find(state.ended.begin(), state.ended.end(), c.id) != state.ended.end()) continue;
475 void*** vector = running_thread_tls_vector(c.handle);
476 void** slots = vector ? *vector : nullptr;
477 if (!slots || !slots[m.tls_index]) continue;
478 // A copy an earlier module left in this slot of this thread goes first; what it replaced is kept.
479 void* saved = slots[m.tls_index];
480 bool present = false;
481 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
482 if (it->thread != c.id || it->slot != m.tls_slot) {
483 ++it;
484 } else if (it->module == &m) {
485 present = true;
486 break;
487 } else {
488 if (slots[it->index] == it->block) saved = it->saved;
489 it->vector = vector;
490 remove_existing_block(*it);
491 it = state.blocks.erase(it);
492 }
493 }
494 if (present) continue;
495 void* block = VirtualAlloc(nullptr, static_cast<SIZE_T>(total), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
496 if (!block) continue;
497 if (m.tls_raw_size) std::memcpy(block, m.tls_template, m.tls_raw_size);
498 state.blocks.push_back({c.id, m.tls_slot, &m, m.tls_index, vector, saved, block});
499 slots[m.tls_index] = block;
500 }
501 }
502 for (const Candidate& c : candidates) CloseHandle(c.handle);
503}
504
505// ~Loader, with g_tls_lock held exclusively: the blocks load() put into other threads come out. A thread that has
506// ended without a detach event (TerminateThread) has no TEB to restore.
507void remove_from_existing_threads(Module& m) {
508 ExistingThreadsLock lock;
509 ExistingThreads& state = existing_threads();
510 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
511 if (it->module != &m) {
512 ++it;
513 continue;
514 }
515 ExistingThreadBlock b = *it;
516 it = state.blocks.erase(it);
517 const HANDLE h = OpenThread(THREAD_QUERY_INFORMATION, FALSE, b.thread);
518 if (!h || running_thread_tls_vector(h) != b.vector) b.vector = nullptr;
519 if (h) CloseHandle(h);
520 remove_existing_block(b);
521 }
522}
523
524// DLL_THREAD_ATTACH: a record under this thread's id is from a thread that ended without a detach event.
525void forget_ended_thread_id() {
526 const DWORD self = GetCurrentThreadId();
527 ExistingThreadsLock lock;
528 ExistingThreads& state = existing_threads();
529 state.ended.erase(std::remove(state.ended.begin(), state.ended.end(), self), state.ended.end());
530 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
531 if (it->thread != self) {
532 ++it;
533 continue;
534 }
535 VirtualFree(it->block, 0, MEM_RELEASE);
536 it = state.blocks.erase(it);
537 }
538}
539
540// DLL_THREAD_DETACH, before this thread's own records are released: the blocks load() gave it come out, newest first,
541// after the module's TLS callbacks have seen the event (Windows sends DLL_THREAD_DETACH to a DLL for a thread that
542// was running before it was loaded, too).
543void release_existing_blocks_of_this_thread() {
544 const DWORD self = GetCurrentThreadId();
545 std::vector<ExistingThreadBlock> mine;
546 {
547 ExistingThreadsLock lock;
548 for (const auto& b : existing_threads().blocks)
549 if (b.thread == self) mine.push_back(b);
550 }
551 for (auto it = mine.rbegin(); it != mine.rend(); ++it) {
552 Module* m = it->module;
553 if (g_tls_slot_owners[it->slot].load() != m || !m->initialised) continue;
554 try {
555 run_callbacks(*m, DLL_THREAD_DETACH);
556 } catch (const std::exception& e) {
557 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what());
558 }
559 }
560 ExistingThreadsLock lock;
561 ExistingThreads& state = existing_threads();
562 for (auto it = state.blocks.end(); it != state.blocks.begin();) {
563 --it;
564 if (it->thread != self) continue;
565 remove_existing_block(*it);
566 it = state.blocks.erase(it);
567 }
568 state.ended.push_back(self);
569}
570
348// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under 571// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under
349// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an 572// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an
350// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events 573// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events
@@ -353,6 +576,7 @@ void __cdecl on_host_thread_event(DWORD reason) {
353 SharedTlsLock lock; 576 SharedTlsLock lock;
354 try { 577 try {
355 if (reason == DLL_THREAD_ATTACH) { 578 if (reason == DLL_THREAD_ATTACH) {
579 forget_ended_thread_id();
356 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { 580 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) {
357 Module* m = g_tls_slot_owners[slot].load(); 581 Module* m = g_tls_slot_owners[slot].load();
358 if (!m) continue; 582 if (!m) continue;
@@ -360,6 +584,7 @@ void __cdecl on_host_thread_event(DWORD reason) {
360 if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); 584 if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH);
361 } 585 }
362 } else if (reason == DLL_THREAD_DETACH) { 586 } else if (reason == DLL_THREAD_DETACH) {
587 release_existing_blocks_of_this_thread();
363 for (size_t i = kMaxMappedTlsModules; i-- > 0;) { 588 for (size_t i = kMaxMappedTlsModules; i-- > 0;) {
364 Module* m = g_tls_slot_owners[i].load(); 589 Module* m = g_tls_slot_owners[i].load();
365 if (m && g_thread_tls_slots[i].module == m) { 590 if (m && g_thread_tls_slots[i].module == m) {
@@ -526,6 +751,7 @@ Loader::~Loader() {
526 ExclusiveTlsLock lock; 751 ExclusiveTlsLock lock;
527 Module* owner = m; 752 Module* owner = m;
528 g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr); 753 g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr);
754 remove_from_existing_threads(*m);
529 } 755 }
530 uninstall_tls_for_thread(*m); 756 uninstall_tls_for_thread(*m);
531 } 757 }
@@ -903,6 +1129,9 @@ void Loader::initialize_tls(Module& m) {
903 m.tls_block = g_thread_tls_slots[slot].block; 1129 m.tls_block = g_thread_tls_slots[slot].block;
904 m.tls_saved_block = g_thread_tls_slots[slot].saved; 1130 m.tls_saved_block = g_thread_tls_slots[slot].saved;
905 } 1131 }
1132 // Threads started from here on get their copy from the helper DLL's DLL_THREAD_ATTACH; the ones already running
1133 // get it now.
1134 install_on_existing_threads(m);
906} 1135}
907 1136
908void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); } 1137void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); }