diff options
Diffstat (limited to 'runtime/src/pe_loader.cpp')
| -rw-r--r-- | runtime/src/pe_loader.cpp | 178 |
1 files changed, 177 insertions, 1 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index fd9299517..c6e62c73a 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp | |||
| @@ -424,6 +424,8 @@ struct ThreadTlsSlot { | |||
| 424 | void* saved = nullptr; | 424 | void* saved = nullptr; |
| 425 | void* block = nullptr; | 425 | void* block = nullptr; |
| 426 | uint32_t index = kNoTlsIndex; | 426 | uint32_t index = kNoTlsIndex; |
| 427 | void** ga_view = nullptr; // the thread's slot-0 view for a /GA EXE (Module::tls_ga_slot) | ||
| 428 | uint32_t ga_slot = kNoTlsIndex; | ||
| 427 | }; | 429 | }; |
| 428 | 430 | ||
| 429 | // Per-thread installation state for each reserved TLS slot. | 431 | // Per-thread installation state for each reserved TLS slot. |
| @@ -627,6 +629,10 @@ void release_thread_slot(size_t slot) { | |||
| 627 | if (slot >= kTlsSlotCount) return; | 629 | if (slot >= kTlsSlotCount) return; |
| 628 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; | 630 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; |
| 629 | if (!entry.module && !entry.block) return; | 631 | if (!entry.module && !entry.block) return; |
| 632 | if (entry.ga_view) { | ||
| 633 | if (TlsGetValue(entry.ga_slot) == entry.ga_view) TlsSetValue(entry.ga_slot, nullptr); | ||
| 634 | VirtualFree(entry.ga_view, 0, MEM_RELEASE); | ||
| 635 | } | ||
| 630 | if (entry.block) { | 636 | if (entry.block) { |
| 631 | void** slots = module_tls_slots(); | 637 | void** slots = module_tls_slots(); |
| 632 | if (slots && entry.index < kMaxModuleTlsSlots && slots[entry.index] == entry.block) | 638 | if (slots && entry.index < kMaxModuleTlsSlots && slots[entry.index] == entry.block) |
| @@ -648,6 +654,8 @@ struct ExistingThreadBlock { | |||
| 648 | void*** vector = nullptr; // that thread's TEB->ThreadLocalStoragePointer field; the array itself can be replaced | 654 | void*** vector = nullptr; // that thread's TEB->ThreadLocalStoragePointer field; the array itself can be replaced |
| 649 | void* saved = nullptr; // what the block replaced | 655 | void* saved = nullptr; // what the block replaced |
| 650 | void* block = nullptr; | 656 | void* block = nullptr; |
| 657 | void** ga_cell = nullptr; // that thread's TEB->TlsSlots[tls_ga_slot]: inline in the TEB, so it never moves | ||
| 658 | void* ga_view = nullptr; // the /GA view that cell points at (Module::tls_ga_slot) | ||
| 651 | }; | 659 | }; |
| 652 | 660 | ||
| 653 | // Immortal, like the thread events that use them. `ended` holds the ids of threads whose DLL_THREAD_DETACH has run: | 661 | // Immortal, like the thread events that use them. `ended` holds the ids of threads whose DLL_THREAD_DETACH has run: |
| @@ -675,6 +683,17 @@ bool has_existing_thread_block(DWORD thread, const Module& m) { | |||
| 675 | return false; | 683 | return false; |
| 676 | } | 684 | } |
| 677 | 685 | ||
| 686 | // The /GA view a thread's TlsSlots[Module::tls_ga_slot] points at: [0] and [tls_index] are this thread's block. | ||
| 687 | // Null when it cannot be allocated. | ||
| 688 | void** make_ga_view(const Module& m, void* block) { | ||
| 689 | auto* view = static_cast<void**>( | ||
| 690 | VirtualAlloc(nullptr, kMaxModuleTlsSlots * sizeof(void*), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | ||
| 691 | if (!view) return nullptr; | ||
| 692 | view[0] = block; | ||
| 693 | view[m.tls_index] = block; | ||
| 694 | return view; | ||
| 695 | } | ||
| 696 | |||
| 678 | void install_thread_block(Module& m) { | 697 | void install_thread_block(Module& m) { |
| 679 | if (m.tls_slot >= kTlsSlotCount) return; | 698 | if (m.tls_slot >= kTlsSlotCount) return; |
| 680 | const size_t slot = m.tls_slot; | 699 | const size_t slot = m.tls_slot; |
| @@ -708,6 +727,17 @@ void install_thread_block(Module& m) { | |||
| 708 | if (m.tls_zero_fill) | 727 | if (m.tls_zero_fill) |
| 709 | std::memset(static_cast<uint8_t*>(block) + m.tls_raw_size, 0, m.tls_zero_fill); | 728 | std::memset(static_cast<uint8_t*>(block) + m.tls_raw_size, 0, m.tls_zero_fill); |
| 710 | 729 | ||
| 730 | void** view = nullptr; | ||
| 731 | if (m.tls_ga_slot != kNoTlsIndex) { | ||
| 732 | // The /GA view: [0] and [tls_index] are this thread's block, the rest stays null (the image reads no other). | ||
| 733 | view = make_ga_view(m, block); | ||
| 734 | if (!view) { | ||
| 735 | VirtualFree(block, 0, MEM_RELEASE); | ||
| 736 | throw std::runtime_error(m.name + ": TLS view allocation failed"); | ||
| 737 | } | ||
| 738 | TlsSetValue(m.tls_ga_slot, view); | ||
| 739 | } | ||
| 740 | |||
| 711 | void* saved = slots[m.tls_index]; | 741 | void* saved = slots[m.tls_index]; |
| 712 | slots[m.tls_index] = block; | 742 | slots[m.tls_index] = block; |
| 713 | entry.module = &m; | 743 | entry.module = &m; |
| @@ -715,6 +745,45 @@ void install_thread_block(Module& m) { | |||
| 715 | entry.saved = saved; | 745 | entry.saved = saved; |
| 716 | entry.block = block; | 746 | entry.block = block; |
| 717 | entry.index = m.tls_index; | 747 | entry.index = m.tls_index; |
| 748 | entry.ga_view = view; | ||
| 749 | entry.ga_slot = m.tls_ga_slot; | ||
| 750 | } | ||
| 751 | |||
| 752 | // Rewrites a /GA EXE's slot-0 TLS reads (Module::tls_ga_slot): every `mov r64, gs:[58h]` (65 REX.W 8B /r with | ||
| 753 | // mod=00, r/m=100, SIB=25, disp32=58h; REX 48 or 4C for r8-r15) in an executable section becomes the same | ||
| 754 | // instruction with disp32 = 1480h + 8 * slot, TEB->TlsSlots[slot]. Same length, so nothing else moves. The 9-byte | ||
| 755 | // form, with its segment prefix, SIB 25 and that displacement, is not something code or tables produce by accident. | ||
| 756 | // Must run before protect_sections() and before any of the image's code (its TLS callbacks included). | ||
| 757 | size_t patch_ga_tls_reads(Module& m, uint32_t slot) { | ||
| 758 | const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(m.base); | ||
| 759 | const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(m.base + dos->e_lfanew); | ||
| 760 | const IMAGE_SECTION_HEADER* sec = IMAGE_FIRST_SECTION(nt); | ||
| 761 | const uint32_t disp = 0x1480u + 8u * slot; | ||
| 762 | size_t sites = 0; | ||
| 763 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { | ||
| 764 | if (!(sec->Characteristics & IMAGE_SCN_MEM_EXECUTE)) continue; | ||
| 765 | const uint32_t size = (std::min)(sec->Misc.VirtualSize, sec->SizeOfRawData); | ||
| 766 | if (sec->VirtualAddress > m.size || size > m.size - sec->VirtualAddress || size < 9) continue; | ||
| 767 | uint8_t* p = m.base + sec->VirtualAddress; | ||
| 768 | for (uint32_t k = 0; k + 9 <= size; ++k) { | ||
| 769 | if (p[k] != 0x65 || (p[k + 1] != 0x48 && p[k + 1] != 0x4C) || p[k + 2] != 0x8B) continue; | ||
| 770 | const uint8_t modrm = p[k + 3]; | ||
| 771 | if ((modrm & 0xC7) != 0x04 || p[k + 4] != 0x25) continue; | ||
| 772 | uint32_t d; | ||
| 773 | std::memcpy(&d, p + k + 5, 4); | ||
| 774 | if (d != 0x58) continue; | ||
| 775 | std::memcpy(p + k + 5, &disp, 4); | ||
| 776 | ++sites; | ||
| 777 | k += 8; | ||
| 778 | } | ||
| 779 | } | ||
| 780 | return sites; | ||
| 781 | } | ||
| 782 | |||
| 783 | bool ga_tls_patch_enabled() { | ||
| 784 | char v[8] = {}; | ||
| 785 | size_t n = 0; | ||
| 786 | return !(getenv_s(&n, v, "LEONIDA_TLS_GA_PATCH") == 0 && n == 2 && v[0] == '0'); | ||
| 718 | } | 787 | } |
| 719 | 788 | ||
| 720 | void uninstall_thread_block(Module& m) { | 789 | void uninstall_thread_block(Module& m) { |
| @@ -808,6 +877,16 @@ void*** running_thread_tls_vector(HANDLE thread) { | |||
| 808 | return reinterpret_cast<void***>(static_cast<uint8_t*>(info.teb) + 0x58); | 877 | return reinterpret_cast<void***>(static_cast<uint8_t*>(info.teb) + 0x58); |
| 809 | } | 878 | } |
| 810 | 879 | ||
| 880 | // That thread's TEB->TlsSlots[slot] cell (0x1480 + 8 * slot): inline in the TEB, so it cannot be replaced while the | ||
| 881 | // thread runs. Null when the thread is gone. | ||
| 882 | void** running_thread_tls_cell(HANDLE thread, uint32_t slot) { | ||
| 883 | ThreadBasicInfo info{}; | ||
| 884 | const QueryThreadFn query = query_thread_fn(); | ||
| 885 | if (!query || query(thread, 0 /* ThreadBasicInformation */, &info, sizeof info, nullptr) < 0) return nullptr; | ||
| 886 | if (info.exit_status != STILL_ACTIVE || !info.teb) return nullptr; | ||
| 887 | return reinterpret_cast<void**>(static_cast<uint8_t*>(info.teb) + 0x1480 + 8 * slot); | ||
| 888 | } | ||
| 889 | |||
| 811 | // Another thread's TLS array and one entry of it, read through its TEB. False when the memory is not there any more | 890 | // Another thread's TLS array and one entry of it, read through its TEB. False when the memory is not there any more |
| 812 | // (the thread was terminated). No C++ objects in these three: they are __try frames. | 891 | // (the thread was terminated). No C++ objects in these three: they are __try frames. |
| 813 | bool read_thread_slot(void*** vector, uint32_t index, void**& slots, void*& value) noexcept { | 892 | bool read_thread_slot(void*** vector, uint32_t index, void**& slots, void*& value) noexcept { |
| @@ -840,10 +919,32 @@ void restore_thread_slot(void*** vector, uint32_t index, void* block, void* save | |||
| 840 | } | 919 | } |
| 841 | } | 920 | } |
| 842 | 921 | ||
| 922 | // Writes one TlsSlots cell of another thread; false when the thread's TEB is gone already. | ||
| 923 | bool write_tls_cell(void** cell, void* value) noexcept { | ||
| 924 | __try { | ||
| 925 | *cell = value; | ||
| 926 | return true; | ||
| 927 | } __except (EXCEPTION_EXECUTE_HANDLER) { | ||
| 928 | return false; | ||
| 929 | } | ||
| 930 | } | ||
| 931 | |||
| 932 | // Empties a TlsSlots cell that still holds `view` (a thread that ended may hold another value). | ||
| 933 | void restore_tls_cell(void** cell, void* view) noexcept { | ||
| 934 | __try { | ||
| 935 | if (*cell == view) *cell = nullptr; | ||
| 936 | } __except (EXCEPTION_EXECUTE_HANDLER) { | ||
| 937 | } | ||
| 938 | } | ||
| 939 | |||
| 843 | // Takes a block out of its slot and frees it. The existing-threads lock is held; b.vector is null when the thread | 940 | // Takes a block out of its slot and frees it. The existing-threads lock is held; b.vector is null when the thread |
| 844 | // is gone. | 941 | // is gone. |
| 845 | void remove_existing_block(const ExistingThreadBlock& b) { | 942 | void remove_existing_block(const ExistingThreadBlock& b) { |
| 846 | if (b.vector && b.index < kMaxModuleTlsSlots) restore_thread_slot(b.vector, b.index, b.block, b.saved); | 943 | if (b.vector && b.index < kMaxModuleTlsSlots) restore_thread_slot(b.vector, b.index, b.block, b.saved); |
| 944 | if (b.ga_view) { | ||
| 945 | if (b.ga_cell) restore_tls_cell(b.ga_cell, b.ga_view); | ||
| 946 | VirtualFree(b.ga_view, 0, MEM_RELEASE); | ||
| 947 | } | ||
| 847 | VirtualFree(b.block, 0, MEM_RELEASE); | 948 | VirtualFree(b.block, 0, MEM_RELEASE); |
| 848 | } | 949 | } |
| 849 | 950 | ||
| @@ -938,7 +1039,26 @@ void install_on_existing_threads(Module& m) { | |||
| 938 | m.name.c_str()); | 1039 | m.name.c_str()); |
| 939 | continue; | 1040 | continue; |
| 940 | } | 1041 | } |
| 941 | state.blocks.push_back({c.id, m.tls_slot, &m, m.tls_generation, m.tls_index, vector, saved, block}); | 1042 | void** ga_cell = nullptr; |
| 1043 | void* ga_view = nullptr; | ||
| 1044 | if (m.tls_ga_slot != kNoTlsIndex) { | ||
| 1045 | // The /GA view this thread's rewritten index-0 TLS reads go through, as install_thread_block gives | ||
| 1046 | // a thread started after load(). Without it those reads dereference null on this thread. | ||
| 1047 | ga_cell = running_thread_tls_cell(c.handle, m.tls_ga_slot); | ||
| 1048 | if (ga_cell) ga_view = make_ga_view(m, block); | ||
| 1049 | if (!ga_view || !write_tls_cell(ga_cell, ga_view)) { | ||
| 1050 | if (ga_view) VirtualFree(ga_view, 0, MEM_RELEASE); | ||
| 1051 | ga_cell = nullptr; | ||
| 1052 | ga_view = nullptr; | ||
| 1053 | static std::atomic<bool> logged_view{false}; | ||
| 1054 | if (!logged_view.exchange(true)) | ||
| 1055 | std::fprintf(stderr, "[rt] loader: %s: a running thread did not take its /GA TLS view; " | ||
| 1056 | "index-0 TLS reads in it have no block\n", | ||
| 1057 | m.name.c_str()); | ||
| 1058 | } | ||
| 1059 | } | ||
| 1060 | state.blocks.push_back( | ||
| 1061 | {c.id, m.tls_slot, &m, m.tls_generation, m.tls_index, vector, saved, block, ga_cell, ga_view}); | ||
| 942 | } | 1062 | } |
| 943 | } | 1063 | } |
| 944 | } | 1064 | } |
| @@ -958,6 +1078,7 @@ void remove_from_existing_threads(Module& m) { | |||
| 958 | const HANDLE h = OpenThread(THREAD_QUERY_INFORMATION, FALSE, b.thread); | 1078 | const HANDLE h = OpenThread(THREAD_QUERY_INFORMATION, FALSE, b.thread); |
| 959 | if (!h || running_thread_tls_vector(h) != b.vector) b.vector = nullptr; | 1079 | if (!h || running_thread_tls_vector(h) != b.vector) b.vector = nullptr; |
| 960 | if (h) CloseHandle(h); | 1080 | if (h) CloseHandle(h); |
| 1081 | if (!b.vector) b.ga_cell = nullptr; // the TEB went with the thread | ||
| 961 | remove_existing_block(b); | 1082 | remove_existing_block(b); |
| 962 | } | 1083 | } |
| 963 | } | 1084 | } |
| @@ -974,6 +1095,7 @@ void forget_ended_thread_id() { | |||
| 974 | continue; | 1095 | continue; |
| 975 | } | 1096 | } |
| 976 | VirtualFree(it->block, 0, MEM_RELEASE); | 1097 | VirtualFree(it->block, 0, MEM_RELEASE); |
| 1098 | VirtualFree(it->ga_view, 0, MEM_RELEASE); | ||
| 977 | it = state.blocks.erase(it); | 1099 | it = state.blocks.erase(it); |
| 978 | } | 1100 | } |
| 979 | } | 1101 | } |
| @@ -1237,6 +1359,9 @@ struct RuntimeLoadScope { | |||
| 1237 | } // namespace | 1359 | } // namespace |
| 1238 | 1360 | ||
| 1239 | Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { | 1361 | Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { |
| 1362 | std::vector<wchar_t> compat(32768); | ||
| 1363 | const DWORD n = GetEnvironmentVariableW(L"LEONIDA_COMPAT_DIR", compat.data(), static_cast<DWORD>(compat.size())); | ||
| 1364 | if (n > 0 && n < compat.size()) compat_dir_ = std::filesystem::path(compat.data()); | ||
| 1240 | shims::add_module_lookup(this, &lookup_in_loader); | 1365 | shims::add_module_lookup(this, &lookup_in_loader); |
| 1241 | shims::add_bundled_loader(this, &kBundledOps); | 1366 | shims::add_bundled_loader(this, &kBundledOps); |
| 1242 | } | 1367 | } |
| @@ -1770,6 +1895,26 @@ void Loader::initialize_tls(Module& m) { | |||
| 1770 | // VirtualProtect dance. | 1895 | // VirtualProtect dance. |
| 1771 | if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index; | 1896 | if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index; |
| 1772 | } | 1897 | } |
| 1898 | { | ||
| 1899 | // An EXE's code may read its TLS at index 0 directly (/GA); index 0 is gta6rt.exe's here (pe_loader.h, | ||
| 1900 | // tls_ga_slot). Patched before any of the image's code runs, TLS callbacks included. | ||
| 1901 | const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(m.base); | ||
| 1902 | const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(m.base + dos->e_lfanew); | ||
| 1903 | if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && total && index != 0 && ga_tls_patch_enabled()) { | ||
| 1904 | static const DWORD ga_slot = TlsAlloc(); | ||
| 1905 | if (ga_slot == TLS_OUT_OF_INDEXES || ga_slot >= 64) { | ||
| 1906 | std::fprintf(stderr, "[rt] loader: %s: no TlsAlloc slot below 64 for its index-0 TLS reads\n", | ||
| 1907 | m.name.c_str()); | ||
| 1908 | } else { | ||
| 1909 | m.tls_ga_sites = patch_ga_tls_reads(m, ga_slot); | ||
| 1910 | if (m.tls_ga_sites) m.tls_ga_slot = ga_slot; | ||
| 1911 | std::fprintf(stderr, | ||
| 1912 | "[rt] loader: %s: %zu index-0 TLS reads (gs:[58h]) now read its own TLS (TlsSlots[%lu]); " | ||
| 1913 | "its module TLS index is %u\n", | ||
| 1914 | m.name.c_str(), m.tls_ga_sites, static_cast<unsigned long>(ga_slot), index); | ||
| 1915 | } | ||
| 1916 | } | ||
| 1917 | } | ||
| 1773 | try { | 1918 | try { |
| 1774 | install_thread_block(m); | 1919 | install_thread_block(m); |
| 1775 | } catch (...) { | 1920 | } catch (...) { |
| @@ -1888,10 +2033,41 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d | |||
| 1888 | return reinterpret_cast<void*>(p); | 2033 | return reinterpret_cast<void*>(p); |
| 1889 | } | 2034 | } |
| 1890 | 2035 | ||
| 2036 | bool Loader::resolve_compat(const std::string& key, const std::string& dll, const std::string& name, uint16_t ordinal, | ||
| 2037 | bool by_ordinal, void*& out) { | ||
| 2038 | out = nullptr; | ||
| 2039 | if (compat_dir_.empty() || key.empty() || key.find_first_of("/\\:") != std::string::npos) return false; | ||
| 2040 | HMODULE h = nullptr; | ||
| 2041 | if (auto it = compat_modules_.find(key); it != compat_modules_.end()) { | ||
| 2042 | h = static_cast<HMODULE>(it->second); | ||
| 2043 | } else { | ||
| 2044 | const std::filesystem::path candidate = compat_dir_ / std::filesystem::path(dll); | ||
| 2045 | std::error_code ec; | ||
| 2046 | if (!std::filesystem::is_regular_file(candidate, ec)) return false; | ||
| 2047 | // The full path, with the compat folder on the DLL's own search path for its dependencies; never the game | ||
| 2048 | // folder. Windows maps it, so its CRT, TLS and SEH work as for any host DLL. | ||
| 2049 | h = LoadLibraryExW(candidate.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); | ||
| 2050 | if (!h) | ||
| 2051 | throw std::runtime_error("LEONIDA_COMPAT_DIR: " + path_utf8(candidate) + " exists but Windows could not " + | ||
| 2052 | "load it (error " + std::to_string(GetLastError()) + ")"); | ||
| 2053 | compat_modules_.emplace(key, h); | ||
| 2054 | std::fprintf(stderr, "[rt] compat: %s -> %s\n", dll.c_str(), path_utf8(candidate).c_str()); | ||
| 2055 | } | ||
| 2056 | out = reinterpret_cast<void*>(GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str())); | ||
| 2057 | return true; | ||
| 2058 | } | ||
| 2059 | |||
| 1891 | void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) { | 2060 | void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) { |
| 1892 | std::string key = lower(dll); | 2061 | std::string key = lower(dll); |
| 1893 | std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name; | 2062 | std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name; |
| 1894 | 2063 | ||
| 2064 | // Opt-in compat modules come first: a DLL the player put in LEONIDA_COMPAT_DIR owns all of its imports, so one | ||
| 2065 | // console module is never served half by a shim and half by the drop-in (they would not share state). | ||
| 2066 | if (void* p = nullptr; resolve_compat(key, dll, name, ordinal, by_ordinal, p)) { | ||
| 2067 | m.imports.push_back({dll, sym, p ? Binding::Host : Binding::Unimplemented}); | ||
| 2068 | return p ? p : shims::make_unimplemented_thunk(dll, sym); | ||
| 2069 | } | ||
| 2070 | |||
| 1895 | if (void* p = shims::find(key, sym)) { | 2071 | if (void* p = shims::find(key, sym)) { |
| 1896 | m.imports.push_back({dll, sym, Binding::Shim}); | 2072 | m.imports.push_back({dll, sym, Binding::Shim}); |
| 1897 | return p; | 2073 | return p; |