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 e5becb472..5e55ac1f9 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp | |||
| @@ -342,6 +342,8 @@ struct ThreadTlsSlot { | |||
| 342 | void* saved = nullptr; | 342 | void* saved = nullptr; |
| 343 | void* block = nullptr; | 343 | void* block = nullptr; |
| 344 | uint32_t index = kNoTlsIndex; | 344 | uint32_t index = kNoTlsIndex; |
| 345 | void** ga_view = nullptr; // the thread's slot-0 view for a /GA EXE (Module::tls_ga_slot) | ||
| 346 | uint32_t ga_slot = kNoTlsIndex; | ||
| 345 | }; | 347 | }; |
| 346 | 348 | ||
| 347 | // Per-thread installation state for each reserved TLS slot. | 349 | // Per-thread installation state for each reserved TLS slot. |
| @@ -370,6 +372,10 @@ void release_thread_slot(size_t slot) { | |||
| 370 | if (slot >= kMaxMappedTlsModules) return; | 372 | if (slot >= kMaxMappedTlsModules) return; |
| 371 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; | 373 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; |
| 372 | if (!entry.module && !entry.block) return; | 374 | if (!entry.module && !entry.block) return; |
| 375 | if (entry.ga_view) { | ||
| 376 | if (TlsGetValue(entry.ga_slot) == entry.ga_view) TlsSetValue(entry.ga_slot, nullptr); | ||
| 377 | VirtualFree(entry.ga_view, 0, MEM_RELEASE); | ||
| 378 | } | ||
| 373 | if (entry.block) { | 379 | if (entry.block) { |
| 374 | void** slots = module_tls_slots(); | 380 | void** slots = module_tls_slots(); |
| 375 | if (slots && entry.index < kMaxModuleTlsSlots && slots[entry.index] == entry.block) | 381 | if (slots && entry.index < kMaxModuleTlsSlots && slots[entry.index] == entry.block) |
| @@ -391,6 +397,8 @@ struct ExistingThreadBlock { | |||
| 391 | 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 |
| 392 | void* saved = nullptr; // what the block replaced | 398 | void* saved = nullptr; // what the block replaced |
| 393 | 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) | ||
| 394 | }; | 402 | }; |
| 395 | 403 | ||
| 396 | // 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: |
| @@ -418,6 +426,17 @@ bool has_existing_thread_block(DWORD thread, const Module& m) { | |||
| 418 | return false; | 426 | return false; |
| 419 | } | 427 | } |
| 420 | 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. | ||
| 431 | void** 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 | |||
| 421 | void install_thread_block(Module& m) { | 440 | void install_thread_block(Module& m) { |
| 422 | if (m.tls_slot >= kMaxMappedTlsModules) return; | 441 | if (m.tls_slot >= kMaxMappedTlsModules) return; |
| 423 | const size_t slot = m.tls_slot; | 442 | const size_t slot = m.tls_slot; |
| @@ -451,6 +470,17 @@ void install_thread_block(Module& m) { | |||
| 451 | if (m.tls_zero_fill) | 470 | if (m.tls_zero_fill) |
| 452 | std::memset(static_cast<uint8_t*>(block) + m.tls_raw_size, 0, m.tls_zero_fill); | 471 | std::memset(static_cast<uint8_t*>(block) + m.tls_raw_size, 0, m.tls_zero_fill); |
| 453 | 472 | ||
| 473 | void** view = nullptr; | ||
| 474 | if (m.tls_ga_slot != kNoTlsIndex) { | ||
| 475 | // The /GA view: [0] and [tls_index] are this thread's block, the rest stays null (the image reads no other). | ||
| 476 | view = make_ga_view(m, block); | ||
| 477 | if (!view) { | ||
| 478 | VirtualFree(block, 0, MEM_RELEASE); | ||
| 479 | throw std::runtime_error(m.name + ": TLS view allocation failed"); | ||
| 480 | } | ||
| 481 | TlsSetValue(m.tls_ga_slot, view); | ||
| 482 | } | ||
| 483 | |||
| 454 | void* saved = slots[m.tls_index]; | 484 | void* saved = slots[m.tls_index]; |
| 455 | slots[m.tls_index] = block; | 485 | slots[m.tls_index] = block; |
| 456 | entry.module = &m; | 486 | entry.module = &m; |
| @@ -458,6 +488,45 @@ void install_thread_block(Module& m) { | |||
| 458 | entry.saved = saved; | 488 | entry.saved = saved; |
| 459 | entry.block = block; | 489 | entry.block = block; |
| 460 | entry.index = m.tls_index; | 490 | entry.index = m.tls_index; |
| 491 | entry.ga_view = view; | ||
| 492 | entry.ga_slot = m.tls_ga_slot; | ||
| 493 | } | ||
| 494 | |||
| 495 | // Rewrites a /GA EXE's slot-0 TLS reads (Module::tls_ga_slot): every `mov r64, gs:[58h]` (65 REX.W 8B /r with | ||
| 496 | // mod=00, r/m=100, SIB=25, disp32=58h; REX 48 or 4C for r8-r15) in an executable section becomes the same | ||
| 497 | // instruction with disp32 = 1480h + 8 * slot, TEB->TlsSlots[slot]. Same length, so nothing else moves. The 9-byte | ||
| 498 | // form, with its segment prefix, SIB 25 and that displacement, is not something code or tables produce by accident. | ||
| 499 | // Must run before protect_sections() and before any of the image's code (its TLS callbacks included). | ||
| 500 | size_t patch_ga_tls_reads(Module& m, uint32_t slot) { | ||
| 501 | const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(m.base); | ||
| 502 | const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(m.base + dos->e_lfanew); | ||
| 503 | const IMAGE_SECTION_HEADER* sec = IMAGE_FIRST_SECTION(nt); | ||
| 504 | const uint32_t disp = 0x1480u + 8u * slot; | ||
| 505 | size_t sites = 0; | ||
| 506 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { | ||
| 507 | if (!(sec->Characteristics & IMAGE_SCN_MEM_EXECUTE)) continue; | ||
| 508 | const uint32_t size = (std::min)(sec->Misc.VirtualSize, sec->SizeOfRawData); | ||
| 509 | if (sec->VirtualAddress > m.size || size > m.size - sec->VirtualAddress || size < 9) continue; | ||
| 510 | uint8_t* p = m.base + sec->VirtualAddress; | ||
| 511 | for (uint32_t k = 0; k + 9 <= size; ++k) { | ||
| 512 | if (p[k] != 0x65 || (p[k + 1] != 0x48 && p[k + 1] != 0x4C) || p[k + 2] != 0x8B) continue; | ||
| 513 | const uint8_t modrm = p[k + 3]; | ||
| 514 | if ((modrm & 0xC7) != 0x04 || p[k + 4] != 0x25) continue; | ||
| 515 | uint32_t d; | ||
| 516 | std::memcpy(&d, p + k + 5, 4); | ||
| 517 | if (d != 0x58) continue; | ||
| 518 | std::memcpy(p + k + 5, &disp, 4); | ||
| 519 | ++sites; | ||
| 520 | k += 8; | ||
| 521 | } | ||
| 522 | } | ||
| 523 | return sites; | ||
| 524 | } | ||
| 525 | |||
| 526 | bool ga_tls_patch_enabled() { | ||
| 527 | char v[8] = {}; | ||
| 528 | size_t n = 0; | ||
| 529 | return !(getenv_s(&n, v, "LEONIDA_TLS_GA_PATCH") == 0 && n == 2 && v[0] == '0'); | ||
| 461 | } | 530 | } |
| 462 | 531 | ||
| 463 | void uninstall_thread_block(Module& m) { | 532 | void uninstall_thread_block(Module& m) { |
| @@ -551,6 +620,16 @@ void*** running_thread_tls_vector(HANDLE thread) { | |||
| 551 | return reinterpret_cast<void***>(static_cast<uint8_t*>(info.teb) + 0x58); | 620 | return reinterpret_cast<void***>(static_cast<uint8_t*>(info.teb) + 0x58); |
| 552 | } | 621 | } |
| 553 | 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. | ||
| 625 | void** 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 | |||
| 554 | // 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 |
| 555 | // (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. |
| 556 | bool read_thread_slot(void*** vector, uint32_t index, void**& slots, void*& value) noexcept { | 635 | bool read_thread_slot(void*** vector, uint32_t index, void**& slots, void*& value) noexcept { |
| @@ -583,10 +662,32 @@ void restore_thread_slot(void*** vector, uint32_t index, void* block, void* save | |||
| 583 | } | 662 | } |
| 584 | } | 663 | } |
| 585 | 664 | ||
| 665 | // Writes one TlsSlots cell of another thread; false when the thread's TEB is gone already. | ||
| 666 | bool 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). | ||
| 676 | void restore_tls_cell(void** cell, void* view) noexcept { | ||
| 677 | __try { | ||
| 678 | if (*cell == view) *cell = nullptr; | ||
| 679 | } __except (EXCEPTION_EXECUTE_HANDLER) { | ||
| 680 | } | ||
| 681 | } | ||
| 682 | |||
| 586 | // 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 |
| 587 | // is gone. | 684 | // is gone. |
| 588 | void remove_existing_block(const ExistingThreadBlock& b) { | 685 | void remove_existing_block(const ExistingThreadBlock& b) { |
| 589 | 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 | } | ||
| 590 | VirtualFree(b.block, 0, MEM_RELEASE); | 691 | VirtualFree(b.block, 0, MEM_RELEASE); |
| 591 | } | 692 | } |
| 592 | 693 | ||
| @@ -681,7 +782,26 @@ void install_on_existing_threads(Module& m) { | |||
| 681 | m.name.c_str()); | 782 | m.name.c_str()); |
| 682 | continue; | 783 | continue; |
| 683 | } | 784 | } |
| 684 | 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}); | ||
| 685 | } | 805 | } |
| 686 | } | 806 | } |
| 687 | } | 807 | } |
| @@ -701,6 +821,7 @@ void remove_from_existing_threads(Module& m) { | |||
| 701 | const HANDLE h = OpenThread(THREAD_QUERY_INFORMATION, FALSE, b.thread); | 821 | const HANDLE h = OpenThread(THREAD_QUERY_INFORMATION, FALSE, b.thread); |
| 702 | 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; |
| 703 | if (h) CloseHandle(h); | 823 | if (h) CloseHandle(h); |
| 824 | if (!b.vector) b.ga_cell = nullptr; // the TEB went with the thread | ||
| 704 | remove_existing_block(b); | 825 | remove_existing_block(b); |
| 705 | } | 826 | } |
| 706 | } | 827 | } |
| @@ -717,6 +838,7 @@ void forget_ended_thread_id() { | |||
| 717 | continue; | 838 | continue; |
| 718 | } | 839 | } |
| 719 | VirtualFree(it->block, 0, MEM_RELEASE); | 840 | VirtualFree(it->block, 0, MEM_RELEASE); |
| 841 | VirtualFree(it->ga_view, 0, MEM_RELEASE); | ||
| 720 | it = state.blocks.erase(it); | 842 | it = state.blocks.erase(it); |
| 721 | } | 843 | } |
| 722 | } | 844 | } |
| @@ -944,6 +1066,9 @@ struct RuntimeLoadScope { | |||
| 944 | } // namespace | 1066 | } // namespace |
| 945 | 1067 | ||
| 946 | Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { | 1068 | Loader::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()); | ||
| 947 | shims::add_module_lookup(this, &lookup_in_loader); | 1072 | shims::add_module_lookup(this, &lookup_in_loader); |
| 948 | shims::add_bundled_loader(this, &kBundledOps); | 1073 | shims::add_bundled_loader(this, &kBundledOps); |
| 949 | } | 1074 | } |
| @@ -1445,6 +1570,26 @@ void Loader::initialize_tls(Module& m) { | |||
| 1445 | // VirtualProtect dance. | 1570 | // VirtualProtect dance. |
| 1446 | if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index; | 1571 | if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index; |
| 1447 | } | 1572 | } |
| 1573 | { | ||
| 1574 | // An EXE's code may read its TLS at index 0 directly (/GA); index 0 is gta6rt.exe's here (pe_loader.h, | ||
| 1575 | // tls_ga_slot). Patched before any of the image's code runs, TLS callbacks included. | ||
| 1576 | const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(m.base); | ||
| 1577 | const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(m.base + dos->e_lfanew); | ||
| 1578 | if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && total && index != 0 && ga_tls_patch_enabled()) { | ||
| 1579 | static const DWORD ga_slot = TlsAlloc(); | ||
| 1580 | if (ga_slot == TLS_OUT_OF_INDEXES || ga_slot >= 64) { | ||
| 1581 | std::fprintf(stderr, "[rt] loader: %s: no TlsAlloc slot below 64 for its index-0 TLS reads\n", | ||
| 1582 | m.name.c_str()); | ||
| 1583 | } else { | ||
| 1584 | m.tls_ga_sites = patch_ga_tls_reads(m, ga_slot); | ||
| 1585 | if (m.tls_ga_sites) m.tls_ga_slot = ga_slot; | ||
| 1586 | std::fprintf(stderr, | ||
| 1587 | "[rt] loader: %s: %zu index-0 TLS reads (gs:[58h]) now read its own TLS (TlsSlots[%lu]); " | ||
| 1588 | "its module TLS index is %u\n", | ||
| 1589 | m.name.c_str(), m.tls_ga_sites, static_cast<unsigned long>(ga_slot), index); | ||
| 1590 | } | ||
| 1591 | } | ||
| 1592 | } | ||
| 1448 | try { | 1593 | try { |
| 1449 | install_thread_block(m); | 1594 | install_thread_block(m); |
| 1450 | } catch (...) { | 1595 | } catch (...) { |
| @@ -1563,10 +1708,41 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d | |||
| 1563 | return reinterpret_cast<void*>(p); | 1708 | return reinterpret_cast<void*>(p); |
| 1564 | } | 1709 | } |
| 1565 | 1710 | ||
| 1711 | bool 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 | |||
| 1566 | void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) { | 1735 | void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) { |
| 1567 | std::string key = lower(dll); | 1736 | std::string key = lower(dll); |
| 1568 | std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name; | 1737 | std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name; |
| 1569 | 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 | |||
| 1570 | if (void* p = shims::find(key, sym)) { | 1746 | if (void* p = shims::find(key, sym)) { |
| 1571 | m.imports.push_back({dll, sym, Binding::Shim}); | 1747 | m.imports.push_back({dll, sym, Binding::Shim}); |
| 1572 | return p; | 1748 | return p; |