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:
Diffstat (limited to 'runtime/src/pe_loader.cpp')
-rw-r--r--runtime/src/pe_loader.cpp320
1 files changed, 320 insertions, 0 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index 3c7f9da08..bbb04cd6c 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>
@@ -332,11 +333,51 @@ void release_thread_slot(size_t slot) {
332 entry = ThreadTlsSlot{}; 333 entry = ThreadTlsSlot{};
333} 334}
334 335
336// A block load() put into a thread that was already running (install_on_existing_threads). Such a thread has no
337// g_thread_tls_slots record of it: the record is here, keyed by thread id, and the thread's own DLL_THREAD_DETACH or
338// the module's ~Loader takes the block out again.
339struct ExistingThreadBlock {
340 DWORD thread = 0;
341 size_t slot = 0;
342 Module* module = nullptr;
343 uint64_t generation = 0; // the module's tls_generation: with the pointer, what identifies the module
344 uint32_t index = kNoTlsIndex;
345 void*** vector = nullptr; // that thread's TEB->ThreadLocalStoragePointer field; the array itself can be replaced
346 void* saved = nullptr; // what the block replaced
347 void* block = nullptr;
348};
349
350// Immortal, like the thread events that use them. `ended` holds the ids of threads whose DLL_THREAD_DETACH has run:
351// Windows frees such a thread's TLS array next, so nothing may be put into it any more.
352struct ExistingThreads {
353 SRWLOCK lock = SRWLOCK_INIT; // a leaf: nothing is called while it is held but VirtualFree and thread queries
354 std::vector<ExistingThreadBlock> blocks;
355 std::vector<DWORD> ended;
356};
357ExistingThreads& existing_threads() {
358 static auto* state = new ExistingThreads;
359 return *state;
360}
361struct ExistingThreadsLock {
362 ExistingThreadsLock() { AcquireSRWLockExclusive(&existing_threads().lock); }
363 ~ExistingThreadsLock() { ReleaseSRWLockExclusive(&existing_threads().lock); }
364 ExistingThreadsLock(const ExistingThreadsLock&) = delete;
365 ExistingThreadsLock& operator=(const ExistingThreadsLock&) = delete;
366};
367
368bool has_existing_thread_block(DWORD thread, const Module& m) {
369 ExistingThreadsLock lock;
370 for (const auto& b : existing_threads().blocks)
371 if (b.thread == thread && b.module == &m && b.generation == m.tls_generation) return true;
372 return false;
373}
374
335void install_thread_block(Module& m) { 375void install_thread_block(Module& m) {
336 if (m.tls_slot >= kMaxMappedTlsModules) return; 376 if (m.tls_slot >= kMaxMappedTlsModules) return;
337 const size_t slot = m.tls_slot; 377 const size_t slot = m.tls_slot;
338 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 378 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
339 if (entry.module == &m && entry.generation == m.tls_generation) return; 379 if (entry.module == &m && entry.generation == m.tls_generation) return;
380 if (has_existing_thread_block(GetCurrentThreadId(), m)) return; // load() already gave this thread its copy
340 if (entry.module) { 381 if (entry.module) {
341 // A copy left by a module whose Loader is gone (or from an earlier generation) is released; a live owner's is a conflict. 382 // A copy left by a module whose Loader is gone (or from an earlier generation) is released; a live owner's is a conflict.
342 if (entry.module == g_tls_slot_owners[slot].load() && 383 if (entry.module == g_tls_slot_owners[slot].load() &&
@@ -407,6 +448,269 @@ void run_callbacks(Module& m, uint32_t reason, bool trace = false) {
407 } 448 }
408} 449}
409 450
451// ---- Threads that existed before load() ---------------------------------------------------------------------------
452//
453// When Windows loads a DLL with static TLS itself, every running thread gets a block for it (and no DLL_THREAD_ATTACH).
454// The helper DLL gets exactly that, so in a thread that was already running the reserved slot holds the helper's
455// one-byte block, and mapped __declspec(thread) code there would read and write past it. Such threads are not rare:
456// the workers of the process thread pool predate most loads, and the task queue runs a title's callbacks on them.
457// load() therefore gives each of them a copy of the template too, through the thread's TEB, which is ordinary memory
458// of this process.
459//
460// What makes that safe:
461// - The slot is the helper's, and nothing reads the helper's variable, so swapping the pointer under a running
462// thread disturbs nothing; the thread cannot be in mapped code of a module whose load() has not returned.
463// - The swap is made with g_tls_lock held exclusively, so no thread is inside its attach or detach event meanwhile.
464// - A thread whose detach event has run is skipped (`ended`), and so is one with no TLS array or no helper block:
465// Windows is about to free, or never built, what the block would go into.
466// - The block comes out again in that thread's own detach event, before Windows frees the array, or in ~Loader.
467// What is left:
468// - A thread that ran its detach event before the helper DLL was ever loaded and has not left the process yet is
469// not in `ended`; if Windows leaves a stale array pointer in its TEB for those last instructions, the write goes
470// to freed heap memory.
471// - Windows replaces a thread's TLS array (a new one, copied from the old) when some thread loads a DLL with static
472// TLS. If that happens during the swap, the write can land in the old array; the thread then still has the
473// helper's one-byte block, and the first mapped __declspec(thread) access on it writes past that block: heap
474// corruption, with nothing to show for it. The swap therefore reads the array pointer again after writing and
475// repeats on the new array (kSwapAttempts times); if the block is not in the thread's current array at the end,
476// it is taken back and the miss is logged. A replacement after that last look is not seen.
477// - TerminateThread frees a thread's TEB with no detach event. Every read and write of another thread's TEB or
478// TLS array here is made right after the thread was seen running and inside __try, so a TEB that has just gone
479// is a skipped thread, not a fault in load() or ~Loader. If the memory was already given to something else, the
480// write is not caught.
481using QueryThreadFn = LONG(NTAPI*)(HANDLE, int, void*, ULONG, ULONG*);
482struct ThreadBasicInfo { // THREAD_BASIC_INFORMATION (winternl.h keeps it opaque), x64
483 LONG exit_status;
484 void* teb;
485 void* process_id;
486 void* thread_id;
487 ULONG_PTR affinity;
488 LONG priority;
489 LONG base_priority;
490};
491static_assert(sizeof(ThreadBasicInfo) == 48);
492
493QueryThreadFn query_thread_fn() {
494 static const auto fn = reinterpret_cast<QueryThreadFn>(
495 reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread")));
496 return fn;
497}
498
499// The TEB's ThreadLocalStoragePointer field of a thread that is still running; null otherwise.
500void*** running_thread_tls_vector(HANDLE thread) {
501 ThreadBasicInfo info{};
502 const QueryThreadFn query = query_thread_fn();
503 if (!query || query(thread, 0 /* ThreadBasicInformation */, &info, sizeof info, nullptr) < 0) return nullptr;
504 if (info.exit_status != STILL_ACTIVE || !info.teb) return nullptr;
505 return reinterpret_cast<void***>(static_cast<uint8_t*>(info.teb) + 0x58);
506}
507
508// Another thread's TLS array and one entry of it, read through its TEB. False when the memory is not there any more
509// (the thread was terminated). No C++ objects in these three: they are __try frames.
510bool read_thread_slot(void*** vector, uint32_t index, void**& slots, void*& value) noexcept {
511 __try {
512 slots = *vector;
513 value = slots ? slots[index] : nullptr;
514 return true;
515 } __except (EXCEPTION_EXECUTE_HANDLER) {
516 slots = nullptr;
517 value = nullptr;
518 return false;
519 }
520}
521
522bool write_thread_slot(void** slots, uint32_t index, void* value) noexcept {
523 __try {
524 slots[index] = value;
525 return true;
526 } __except (EXCEPTION_EXECUTE_HANDLER) {
527 return false;
528 }
529}
530
531// Puts `saved` back where `block` is, if it is still there.
532void restore_thread_slot(void*** vector, uint32_t index, void* block, void* saved) noexcept {
533 __try {
534 void** slots = *vector;
535 if (slots && slots[index] == block) slots[index] = saved;
536 } __except (EXCEPTION_EXECUTE_HANDLER) {
537 }
538}
539
540// Takes a block out of its slot and frees it. The existing-threads lock is held; b.vector is null when the thread
541// is gone.
542void remove_existing_block(const ExistingThreadBlock& b) {
543 if (b.vector && b.index < kMaxModuleTlsSlots) restore_thread_slot(b.vector, b.index, b.block, b.saved);
544 VirtualFree(b.block, 0, MEM_RELEASE);
545}
546
547constexpr int kSwapAttempts = 4;
548constexpr size_t kMaxEndedThreads = 1024;
549
550// load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done.
551void install_on_existing_threads(Module& m) {
552 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill;
553 if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kMaxMappedTlsModules) return;
554 // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which
555 // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours.
556 if (!query_thread_fn()) return;
557
558 // Outside the TLS lock: none of this may wait for a thread that is inside its attach event.
559 // The handles are closed on every way out, also when a vector below cannot grow.
560 struct Candidate {
561 DWORD id = 0;
562 HANDLE handle = nullptr;
563 };
564 struct Candidates {
565 std::vector<Candidate> list;
566 HANDLE snapshot = INVALID_HANDLE_VALUE;
567 ~Candidates() {
568 if (snapshot != INVALID_HANDLE_VALUE) CloseHandle(snapshot);
569 for (const Candidate& c : list)
570 if (c.handle) CloseHandle(c.handle);
571 }
572 } found;
573 std::vector<Candidate>& candidates = found.list;
574 // TH32CS_SNAPTHREAD lists the threads of every process; the loop keeps this one's.
575 found.snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
576 if (found.snapshot == INVALID_HANDLE_VALUE) return;
577 THREADENTRY32 entry{};
578 entry.dwSize = sizeof entry;
579 const DWORD process = GetCurrentProcessId(), self = GetCurrentThreadId();
580 for (BOOL more = Thread32First(found.snapshot, &entry); more; more = Thread32Next(found.snapshot, &entry)) {
581 if (entry.th32OwnerProcessID != process || entry.th32ThreadID == self) continue;
582 candidates.push_back({entry.th32ThreadID, nullptr}); // the slot first, so the handle always has an owner
583 candidates.back().handle = OpenThread(THREAD_QUERY_INFORMATION, FALSE, entry.th32ThreadID);
584 }
585
586 {
587 ExclusiveTlsLock tls_lock;
588 ExistingThreadsLock lock;
589 ExistingThreads& state = existing_threads();
590 for (const Candidate& c : candidates) {
591 if (!c.handle) continue;
592 if (std::find(state.ended.begin(), state.ended.end(), c.id) != state.ended.end()) continue;
593 void*** vector = running_thread_tls_vector(c.handle);
594 void** slots = nullptr;
595 void* saved = nullptr;
596 if (!vector || !read_thread_slot(vector, m.tls_index, slots, saved) || !slots || !saved) continue;
597 // A copy an earlier module left in this slot of this thread goes first; what it replaced is kept.
598 bool present = false;
599 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
600 if (it->thread != c.id || it->slot != m.tls_slot) {
601 ++it;
602 } else if (it->module == &m && it->generation == m.tls_generation) {
603 present = true;
604 break;
605 } else {
606 if (saved == it->block) saved = it->saved;
607 it->vector = vector;
608 remove_existing_block(*it);
609 it = state.blocks.erase(it);
610 }
611 }
612 if (present) continue;
613 void* block = VirtualAlloc(nullptr, static_cast<SIZE_T>(total), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
614 if (!block) continue;
615 if (m.tls_raw_size) std::memcpy(block, m.tls_template, m.tls_raw_size);
616
617 // Write, then look at the thread's array pointer again: if Windows has replaced the array meanwhile, the
618 // write went into the old one, and it is made again in the new one.
619 bool installed = false;
620 for (int attempt = 0; attempt < kSwapAttempts && !installed; ++attempt) {
621 if (!running_thread_tls_vector(c.handle) || !write_thread_slot(slots, m.tls_index, block)) break;
622 void** now = nullptr;
623 void* value = nullptr;
624 if (!read_thread_slot(vector, m.tls_index, now, value) || !now) break;
625 installed = now == slots && value == block;
626 slots = now;
627 }
628 if (!installed) {
629 restore_thread_slot(vector, m.tls_index, block, saved);
630 VirtualFree(block, 0, MEM_RELEASE);
631 static std::atomic<bool> logged{false};
632 if (!logged.exchange(true))
633 std::fprintf(stderr, "[rt] loader: %s: a running thread did not take its TLS block (it ended, or "
634 "its TLS array kept changing); mapped thread-local data is not valid on it\n",
635 m.name.c_str());
636 continue;
637 }
638 state.blocks.push_back({c.id, m.tls_slot, &m, m.tls_generation, m.tls_index, vector, saved, block});
639 }
640 }
641}
642
643// ~Loader, with g_tls_lock held exclusively: the blocks load() put into other threads come out. A thread that has
644// ended without a detach event (TerminateThread) has no TEB to restore.
645void remove_from_existing_threads(Module& m) {
646 ExistingThreadsLock lock;
647 ExistingThreads& state = existing_threads();
648 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
649 if (it->module != &m || it->generation != m.tls_generation) {
650 ++it;
651 continue;
652 }
653 ExistingThreadBlock b = *it;
654 it = state.blocks.erase(it);
655 const HANDLE h = OpenThread(THREAD_QUERY_INFORMATION, FALSE, b.thread);
656 if (!h || running_thread_tls_vector(h) != b.vector) b.vector = nullptr;
657 if (h) CloseHandle(h);
658 remove_existing_block(b);
659 }
660}
661
662// DLL_THREAD_ATTACH: a record under this thread's id is from a thread that ended without a detach event.
663void forget_ended_thread_id() {
664 const DWORD self = GetCurrentThreadId();
665 ExistingThreadsLock lock;
666 ExistingThreads& state = existing_threads();
667 state.ended.erase(std::remove(state.ended.begin(), state.ended.end(), self), state.ended.end());
668 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
669 if (it->thread != self) {
670 ++it;
671 continue;
672 }
673 VirtualFree(it->block, 0, MEM_RELEASE);
674 it = state.blocks.erase(it);
675 }
676}
677
678// DLL_THREAD_DETACH, before this thread's own records are released: the blocks load() gave it come out, newest first,
679// after the module's TLS callbacks have seen the event (Windows sends DLL_THREAD_DETACH to a DLL for a thread that
680// was running before it was loaded, too).
681void release_existing_blocks_of_this_thread() {
682 const DWORD self = GetCurrentThreadId();
683 std::vector<ExistingThreadBlock> mine;
684 {
685 ExistingThreadsLock lock;
686 for (const auto& b : existing_threads().blocks)
687 if (b.thread == self) mine.push_back(b);
688 }
689 for (auto it = mine.rbegin(); it != mine.rend(); ++it) {
690 Module* m = it->module;
691 if (g_tls_slot_owners[it->slot].load() != m || g_tls_slot_generations[it->slot].load() != it->generation ||
692 !m->initialised)
693 continue;
694 try {
695 run_callbacks(*m, DLL_THREAD_DETACH);
696 } catch (const std::exception& e) {
697 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what());
698 }
699 }
700 ExistingThreadsLock lock;
701 ExistingThreads& state = existing_threads();
702 for (auto it = state.blocks.end(); it != state.blocks.begin();) {
703 --it;
704 if (it->thread != self) continue;
705 remove_existing_block(*it);
706 it = state.blocks.erase(it);
707 }
708 // Bounded: an id matters only until its thread has left the process, moments after this event, so the oldest
709 // can go. (An id also leaves the list when a new thread gets it.)
710 if (state.ended.size() >= kMaxEndedThreads) state.ended.erase(state.ended.begin(), state.ended.begin() + kMaxEndedThreads / 2);
711 state.ended.push_back(self);
712}
713
410// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under 714// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under
411// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an 715// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an
412// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events 716// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events
@@ -416,6 +720,11 @@ void __cdecl on_host_thread_event(DWORD reason) {
416 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events 720 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events
417 // away from the other slots. Nothing may leave DllMain. 721 // away from the other slots. Nothing may leave DllMain.
418 if (reason == DLL_THREAD_ATTACH) { 722 if (reason == DLL_THREAD_ATTACH) {
723 try {
724 forget_ended_thread_id();
725 } catch (const std::exception& e) {
726 std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what());
727 }
419 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { 728 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) {
420 Module* m = g_tls_slot_owners[slot].load(); 729 Module* m = g_tls_slot_owners[slot].load();
421 if (!m) continue; 730 if (!m) continue;
@@ -429,6 +738,13 @@ void __cdecl on_host_thread_event(DWORD reason) {
429 } 738 }
430 } 739 }
431 } else if (reason == DLL_THREAD_DETACH) { 740 } else if (reason == DLL_THREAD_DETACH) {
741 // The blocks load() gave this thread while it was already running come out first (they can sit on top of
742 // an older module's block in the same slot).
743 try {
744 release_existing_blocks_of_this_thread();
745 } catch (const std::exception& e) {
746 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what());
747 }
432 for (size_t i = kMaxMappedTlsModules; i-- > 0;) { 748 for (size_t i = kMaxMappedTlsModules; i-- > 0;) {
433 Module* m = g_tls_slot_owners[i].load(); 749 Module* m = g_tls_slot_owners[i].load();
434 if (m && g_thread_tls_slots[i].module == m && 750 if (m && g_thread_tls_slots[i].module == m &&
@@ -604,6 +920,7 @@ Loader::~Loader() {
604 Module* owner = m; 920 Module* owner = m;
605 if (g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr)) 921 if (g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr))
606 g_tls_slot_generations[m->tls_slot].store(0); 922 g_tls_slot_generations[m->tls_slot].store(0);
923 remove_from_existing_threads(*m);
607 } 924 }
608 uninstall_tls_for_thread(*m); 925 uninstall_tls_for_thread(*m);
609 } 926 }
@@ -1026,6 +1343,9 @@ void Loader::initialize_tls(Module& m) {
1026 m.tls_block = g_thread_tls_slots[slot].block; 1343 m.tls_block = g_thread_tls_slots[slot].block;
1027 m.tls_saved_block = g_thread_tls_slots[slot].saved; 1344 m.tls_saved_block = g_thread_tls_slots[slot].saved;
1028 } 1345 }
1346 // Threads started from here on get their copy from the helper DLL's DLL_THREAD_ATTACH; the ones already running
1347 // get it now.
1348 install_on_existing_threads(m);
1029} 1349}
1030 1350
1031void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); } 1351void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); }