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.cpp107
1 files changed, 102 insertions, 5 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index d85c1fe5f..5e55ac1f9 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -397,6 +397,8 @@ struct ExistingThreadBlock {
397 void*** vector = nullptr; // that thread's TEB->ThreadLocalStoragePointer field; the array itself can be replaced 397 void*** vector = nullptr; // that thread's TEB->ThreadLocalStoragePointer field; the array itself can be replaced
398 void* saved = nullptr; // what the block replaced 398 void* saved = nullptr; // what the block replaced
399 void* block = nullptr; 399 void* block = nullptr;
400 void** ga_cell = nullptr; // that thread's TEB->TlsSlots[tls_ga_slot]: inline in the TEB, so it never moves
401 void* ga_view = nullptr; // the /GA view that cell points at (Module::tls_ga_slot)
400}; 402};
401 403
402// Immortal, like the thread events that use them. `ended` holds the ids of threads whose DLL_THREAD_DETACH has run: 404// Immortal, like the thread events that use them. `ended` holds the ids of threads whose DLL_THREAD_DETACH has run:
@@ -424,6 +426,17 @@ bool has_existing_thread_block(DWORD thread, const Module& m) {
424 return false; 426 return false;
425} 427}
426 428
429// The /GA view a thread's TlsSlots[Module::tls_ga_slot] points at: [0] and [tls_index] are this thread's block.
430// Null when it cannot be allocated.
431void** make_ga_view(const Module& m, void* block) {
432 auto* view = static_cast<void**>(
433 VirtualAlloc(nullptr, kMaxModuleTlsSlots * sizeof(void*), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
434 if (!view) return nullptr;
435 view[0] = block;
436 view[m.tls_index] = block;
437 return view;
438}
439
427void install_thread_block(Module& m) { 440void install_thread_block(Module& m) {
428 if (m.tls_slot >= kMaxMappedTlsModules) return; 441 if (m.tls_slot >= kMaxMappedTlsModules) return;
429 const size_t slot = m.tls_slot; 442 const size_t slot = m.tls_slot;
@@ -460,14 +473,11 @@ void install_thread_block(Module& m) {
460 void** view = nullptr; 473 void** view = nullptr;
461 if (m.tls_ga_slot != kNoTlsIndex) { 474 if (m.tls_ga_slot != kNoTlsIndex) {
462 // The /GA view: [0] and [tls_index] are this thread's block, the rest stays null (the image reads no other). 475 // The /GA view: [0] and [tls_index] are this thread's block, the rest stays null (the image reads no other).
463 view = static_cast<void**>( 476 view = make_ga_view(m, block);
464 VirtualAlloc(nullptr, kMaxModuleTlsSlots * sizeof(void*), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
465 if (!view) { 477 if (!view) {
466 VirtualFree(block, 0, MEM_RELEASE); 478 VirtualFree(block, 0, MEM_RELEASE);
467 throw std::runtime_error(m.name + ": TLS view allocation failed"); 479 throw std::runtime_error(m.name + ": TLS view allocation failed");
468 } 480 }
469 view[0] = block;
470 view[m.tls_index] = block;
471 TlsSetValue(m.tls_ga_slot, view); 481 TlsSetValue(m.tls_ga_slot, view);
472 } 482 }
473 483
@@ -610,6 +620,16 @@ void*** running_thread_tls_vector(HANDLE thread) {
610 return reinterpret_cast<void***>(static_cast<uint8_t*>(info.teb) + 0x58); 620 return reinterpret_cast<void***>(static_cast<uint8_t*>(info.teb) + 0x58);
611} 621}
612 622
623// That thread's TEB->TlsSlots[slot] cell (0x1480 + 8 * slot): inline in the TEB, so it cannot be replaced while the
624// thread runs. Null when the thread is gone.
625void** running_thread_tls_cell(HANDLE thread, uint32_t slot) {
626 ThreadBasicInfo info{};
627 const QueryThreadFn query = query_thread_fn();
628 if (!query || query(thread, 0 /* ThreadBasicInformation */, &info, sizeof info, nullptr) < 0) return nullptr;
629 if (info.exit_status != STILL_ACTIVE || !info.teb) return nullptr;
630 return reinterpret_cast<void**>(static_cast<uint8_t*>(info.teb) + 0x1480 + 8 * slot);
631}
632
613// Another thread's TLS array and one entry of it, read through its TEB. False when the memory is not there any more 633// Another thread's TLS array and one entry of it, read through its TEB. False when the memory is not there any more
614// (the thread was terminated). No C++ objects in these three: they are __try frames. 634// (the thread was terminated). No C++ objects in these three: they are __try frames.
615bool read_thread_slot(void*** vector, uint32_t index, void**& slots, void*& value) noexcept { 635bool read_thread_slot(void*** vector, uint32_t index, void**& slots, void*& value) noexcept {
@@ -642,10 +662,32 @@ void restore_thread_slot(void*** vector, uint32_t index, void* block, void* save
642 } 662 }
643} 663}
644 664
665// Writes one TlsSlots cell of another thread; false when the thread's TEB is gone already.
666bool write_tls_cell(void** cell, void* value) noexcept {
667 __try {
668 *cell = value;
669 return true;
670 } __except (EXCEPTION_EXECUTE_HANDLER) {
671 return false;
672 }
673}
674
675// Empties a TlsSlots cell that still holds `view` (a thread that ended may hold another value).
676void restore_tls_cell(void** cell, void* view) noexcept {
677 __try {
678 if (*cell == view) *cell = nullptr;
679 } __except (EXCEPTION_EXECUTE_HANDLER) {
680 }
681}
682
645// Takes a block out of its slot and frees it. The existing-threads lock is held; b.vector is null when the thread 683// Takes a block out of its slot and frees it. The existing-threads lock is held; b.vector is null when the thread
646// is gone. 684// is gone.
647void remove_existing_block(const ExistingThreadBlock& b) { 685void remove_existing_block(const ExistingThreadBlock& b) {
648 if (b.vector && b.index < kMaxModuleTlsSlots) restore_thread_slot(b.vector, b.index, b.block, b.saved); 686 if (b.vector && b.index < kMaxModuleTlsSlots) restore_thread_slot(b.vector, b.index, b.block, b.saved);
687 if (b.ga_view) {
688 if (b.ga_cell) restore_tls_cell(b.ga_cell, b.ga_view);
689 VirtualFree(b.ga_view, 0, MEM_RELEASE);
690 }
649 VirtualFree(b.block, 0, MEM_RELEASE); 691 VirtualFree(b.block, 0, MEM_RELEASE);
650} 692}
651 693
@@ -740,7 +782,26 @@ void install_on_existing_threads(Module& m) {
740 m.name.c_str()); 782 m.name.c_str());
741 continue; 783 continue;
742 } 784 }
743 state.blocks.push_back({c.id, m.tls_slot, &m, m.tls_generation, m.tls_index, vector, saved, block}); 785 void** ga_cell = nullptr;
786 void* ga_view = nullptr;
787 if (m.tls_ga_slot != kNoTlsIndex) {
788 // The /GA view this thread's rewritten index-0 TLS reads go through, as install_thread_block gives
789 // a thread started after load(). Without it those reads dereference null on this thread.
790 ga_cell = running_thread_tls_cell(c.handle, m.tls_ga_slot);
791 if (ga_cell) ga_view = make_ga_view(m, block);
792 if (!ga_view || !write_tls_cell(ga_cell, ga_view)) {
793 if (ga_view) VirtualFree(ga_view, 0, MEM_RELEASE);
794 ga_cell = nullptr;
795 ga_view = nullptr;
796 static std::atomic<bool> logged_view{false};
797 if (!logged_view.exchange(true))
798 std::fprintf(stderr, "[rt] loader: %s: a running thread did not take its /GA TLS view; "
799 "index-0 TLS reads in it have no block\n",
800 m.name.c_str());
801 }
802 }
803 state.blocks.push_back(
804 {c.id, m.tls_slot, &m, m.tls_generation, m.tls_index, vector, saved, block, ga_cell, ga_view});
744 } 805 }
745 } 806 }
746} 807}
@@ -760,6 +821,7 @@ void remove_from_existing_threads(Module& m) {
760 const HANDLE h = OpenThread(THREAD_QUERY_INFORMATION, FALSE, b.thread); 821 const HANDLE h = OpenThread(THREAD_QUERY_INFORMATION, FALSE, b.thread);
761 if (!h || running_thread_tls_vector(h) != b.vector) b.vector = nullptr; 822 if (!h || running_thread_tls_vector(h) != b.vector) b.vector = nullptr;
762 if (h) CloseHandle(h); 823 if (h) CloseHandle(h);
824 if (!b.vector) b.ga_cell = nullptr; // the TEB went with the thread
763 remove_existing_block(b); 825 remove_existing_block(b);
764 } 826 }
765} 827}
@@ -776,6 +838,7 @@ void forget_ended_thread_id() {
776 continue; 838 continue;
777 } 839 }
778 VirtualFree(it->block, 0, MEM_RELEASE); 840 VirtualFree(it->block, 0, MEM_RELEASE);
841 VirtualFree(it->ga_view, 0, MEM_RELEASE);
779 it = state.blocks.erase(it); 842 it = state.blocks.erase(it);
780 } 843 }
781} 844}
@@ -1003,6 +1066,9 @@ struct RuntimeLoadScope {
1003} // namespace 1066} // namespace
1004 1067
1005Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { 1068Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) {
1069 std::vector<wchar_t> compat(32768);
1070 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());
1006 shims::add_module_lookup(this, &lookup_in_loader); 1072 shims::add_module_lookup(this, &lookup_in_loader);
1007 shims::add_bundled_loader(this, &kBundledOps); 1073 shims::add_bundled_loader(this, &kBundledOps);
1008} 1074}
@@ -1642,10 +1708,41 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d
1642 return reinterpret_cast<void*>(p); 1708 return reinterpret_cast<void*>(p);
1643} 1709}
1644 1710
1711bool Loader::resolve_compat(const std::string& key, const std::string& dll, const std::string& name, uint16_t ordinal,
1712 bool by_ordinal, void*& out) {
1713 out = nullptr;
1714 if (compat_dir_.empty() || key.empty() || key.find_first_of("/\\:") != std::string::npos) return false;
1715 HMODULE h = nullptr;
1716 if (auto it = compat_modules_.find(key); it != compat_modules_.end()) {
1717 h = static_cast<HMODULE>(it->second);
1718 } else {
1719 const std::filesystem::path candidate = compat_dir_ / std::filesystem::path(dll);
1720 std::error_code ec;
1721 if (!std::filesystem::is_regular_file(candidate, ec)) return false;
1722 // The full path, with the compat folder on the DLL's own search path for its dependencies; never the game
1723 // folder. Windows maps it, so its CRT, TLS and SEH work as for any host DLL.
1724 h = LoadLibraryExW(candidate.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);
1725 if (!h)
1726 throw std::runtime_error("LEONIDA_COMPAT_DIR: " + path_utf8(candidate) + " exists but Windows could not " +
1727 "load it (error " + std::to_string(GetLastError()) + ")");
1728 compat_modules_.emplace(key, h);
1729 std::fprintf(stderr, "[rt] compat: %s -> %s\n", dll.c_str(), path_utf8(candidate).c_str());
1730 }
1731 out = reinterpret_cast<void*>(GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str()));
1732 return true;
1733}
1734
1645void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) { 1735void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) {
1646 std::string key = lower(dll); 1736 std::string key = lower(dll);
1647 std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name; 1737 std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name;
1648 1738
1739 // Opt-in compat modules come first: a DLL the player put in LEONIDA_COMPAT_DIR owns all of its imports, so one
1740 // console module is never served half by a shim and half by the drop-in (they would not share state).
1741 if (void* p = nullptr; resolve_compat(key, dll, name, ordinal, by_ordinal, p)) {
1742 m.imports.push_back({dll, sym, p ? Binding::Host : Binding::Unimplemented});
1743 return p ? p : shims::make_unimplemented_thunk(dll, sym);
1744 }
1745
1649 if (void* p = shims::find(key, sym)) { 1746 if (void* p = shims::find(key, sym)) {
1650 m.imports.push_back({dll, sym, Binding::Shim}); 1747 m.imports.push_back({dll, sym, Binding::Shim});
1651 return p; 1748 return p;