diff options
| author | TreXito <81475944+TreXito@users.noreply.github.com> | 2026-11-23 16:09:44 +0000 |
|---|---|---|
| committer | TreXito <81475944+TreXito@users.noreply.github.com> | 2026-11-23 16:09:44 +0000 |
| commit | 4a92a119d6acb5675178650f362590ffd3c8e54c (patch) | |
| tree | 8e875f4b60bc8fc2c22772c528e1c78101031a3c /runtime/src/pe_loader.cpp | |
| parent | 64ed15f2559497d61d6d0454baec83bc99806de1 (diff) | |
| parent | 8575d36edc479218972497a7bded8651a42856c0 (diff) | |
Merge origin/main into fix/ldexp-f16-mode-rtz
Conflict in docs/design.md: kept main's wording for the three rows and re-added the v_ldexp_f16 sentence to the MODE.FP_ROUND row.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src/pe_loader.cpp')
| -rw-r--r-- | runtime/src/pe_loader.cpp | 403 |
1 files changed, 388 insertions, 15 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index f3323e4c0..bfeab4c7f 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> |
| @@ -12,6 +13,7 @@ | |||
| 12 | #include <fstream> | 13 | #include <fstream> |
| 13 | #include <mutex> | 14 | #include <mutex> |
| 14 | #include <stdexcept> | 15 | #include <stdexcept> |
| 16 | #include <system_error> | ||
| 15 | #include <vector> | 17 | #include <vector> |
| 16 | 18 | ||
| 17 | #include "../shims/shims.h" | 19 | #include "../shims/shims.h" |
| @@ -27,9 +29,36 @@ std::string lower(std::string s) { | |||
| 27 | 29 | ||
| 28 | namespace { | 30 | namespace { |
| 29 | 31 | ||
| 32 | std::filesystem::path::string_type module_key(const std::filesystem::path& path) { | ||
| 33 | // Keep identity in the platform's native path representation. Only the existing ASCII case folding is | ||
| 34 | // applied here; representable names also retain their old narrow-byte alias below. | ||
| 35 | auto key = path.filename().native(); | ||
| 36 | for (auto& c : key) | ||
| 37 | if (c >= 'A' && c <= 'Z') c = static_cast<std::filesystem::path::value_type>(c + ('a' - 'A')); | ||
| 38 | return key; | ||
| 39 | } | ||
| 40 | |||
| 41 | std::string narrow_module_key(const std::filesystem::path& path) { | ||
| 42 | const auto filename = path.filename(); | ||
| 43 | try { | ||
| 44 | const auto narrow = filename.string(); | ||
| 45 | // A lossy/default-character alias must not collapse two distinct Unicode basenames. | ||
| 46 | if (std::filesystem::path(narrow).native() == filename.native()) return lower(narrow); | ||
| 47 | } catch (const std::system_error&) { | ||
| 48 | // Some Windows standard libraries throw when a basename is outside the current narrow code page. | ||
| 49 | // It still has a native identity; it simply has no alias in the existing narrow lookup API. | ||
| 50 | } | ||
| 51 | return {}; | ||
| 52 | } | ||
| 53 | |||
| 54 | std::string path_utf8(const std::filesystem::path& path) { | ||
| 55 | const auto bytes = path.u8string(); | ||
| 56 | return {reinterpret_cast<const char*>(bytes.data()), bytes.size()}; | ||
| 57 | } | ||
| 58 | |||
| 30 | std::vector<uint8_t> read_file(const std::filesystem::path& p) { | 59 | std::vector<uint8_t> read_file(const std::filesystem::path& p) { |
| 31 | std::ifstream f(p, std::ios::binary); | 60 | std::ifstream f(p, std::ios::binary); |
| 32 | if (!f) throw std::runtime_error("cannot open " + p.string()); | 61 | if (!f) throw std::runtime_error("cannot open " + path_utf8(p)); |
| 33 | return {std::istreambuf_iterator<char>(f), {}}; | 62 | return {std::istreambuf_iterator<char>(f), {}}; |
| 34 | } | 63 | } |
| 35 | 64 | ||
| @@ -332,11 +361,51 @@ void release_thread_slot(size_t slot) { | |||
| 332 | entry = ThreadTlsSlot{}; | 361 | entry = ThreadTlsSlot{}; |
| 333 | } | 362 | } |
| 334 | 363 | ||
| 364 | // A block load() put into a thread that was already running (install_on_existing_threads). Such a thread has no | ||
| 365 | // g_thread_tls_slots record of it: the record is here, keyed by thread id, and the thread's own DLL_THREAD_DETACH or | ||
| 366 | // the module's ~Loader takes the block out again. | ||
| 367 | struct ExistingThreadBlock { | ||
| 368 | DWORD thread = 0; | ||
| 369 | size_t slot = 0; | ||
| 370 | Module* module = nullptr; | ||
| 371 | uint64_t generation = 0; // the module's tls_generation: with the pointer, what identifies the module | ||
| 372 | uint32_t index = kNoTlsIndex; | ||
| 373 | void*** vector = nullptr; // that thread's TEB->ThreadLocalStoragePointer field; the array itself can be replaced | ||
| 374 | void* saved = nullptr; // what the block replaced | ||
| 375 | void* block = nullptr; | ||
| 376 | }; | ||
| 377 | |||
| 378 | // Immortal, like the thread events that use them. `ended` holds the ids of threads whose DLL_THREAD_DETACH has run: | ||
| 379 | // Windows frees such a thread's TLS array next, so nothing may be put into it any more. | ||
| 380 | struct ExistingThreads { | ||
| 381 | SRWLOCK lock = SRWLOCK_INIT; // a leaf: nothing is called while it is held but VirtualFree and thread queries | ||
| 382 | std::vector<ExistingThreadBlock> blocks; | ||
| 383 | std::vector<DWORD> ended; | ||
| 384 | }; | ||
| 385 | ExistingThreads& existing_threads() { | ||
| 386 | static auto* state = new ExistingThreads; | ||
| 387 | return *state; | ||
| 388 | } | ||
| 389 | struct ExistingThreadsLock { | ||
| 390 | ExistingThreadsLock() { AcquireSRWLockExclusive(&existing_threads().lock); } | ||
| 391 | ~ExistingThreadsLock() { ReleaseSRWLockExclusive(&existing_threads().lock); } | ||
| 392 | ExistingThreadsLock(const ExistingThreadsLock&) = delete; | ||
| 393 | ExistingThreadsLock& operator=(const ExistingThreadsLock&) = delete; | ||
| 394 | }; | ||
| 395 | |||
| 396 | bool has_existing_thread_block(DWORD thread, const Module& m) { | ||
| 397 | ExistingThreadsLock lock; | ||
| 398 | for (const auto& b : existing_threads().blocks) | ||
| 399 | if (b.thread == thread && b.module == &m && b.generation == m.tls_generation) return true; | ||
| 400 | return false; | ||
| 401 | } | ||
| 402 | |||
| 335 | void install_thread_block(Module& m) { | 403 | void install_thread_block(Module& m) { |
| 336 | if (m.tls_slot >= kMaxMappedTlsModules) return; | 404 | if (m.tls_slot >= kMaxMappedTlsModules) return; |
| 337 | const size_t slot = m.tls_slot; | 405 | const size_t slot = m.tls_slot; |
| 338 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; | 406 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; |
| 339 | if (entry.module == &m && entry.generation == m.tls_generation) return; | 407 | if (entry.module == &m && entry.generation == m.tls_generation) return; |
| 408 | if (has_existing_thread_block(GetCurrentThreadId(), m)) return; // load() already gave this thread its copy | ||
| 340 | if (entry.module) { | 409 | 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. | 410 | // 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() && | 411 | if (entry.module == g_tls_slot_owners[slot].load() && |
| @@ -407,6 +476,269 @@ void run_callbacks(Module& m, uint32_t reason, bool trace = false) { | |||
| 407 | } | 476 | } |
| 408 | } | 477 | } |
| 409 | 478 | ||
| 479 | // ---- Threads that existed before load() --------------------------------------------------------------------------- | ||
| 480 | // | ||
| 481 | // When Windows loads a DLL with static TLS itself, every running thread gets a block for it (and no DLL_THREAD_ATTACH). | ||
| 482 | // The helper DLL gets exactly that, so in a thread that was already running the reserved slot holds the helper's | ||
| 483 | // one-byte block, and mapped __declspec(thread) code there would read and write past it. Such threads are not rare: | ||
| 484 | // the workers of the process thread pool predate most loads, and the task queue runs a title's callbacks on them. | ||
| 485 | // load() therefore gives each of them a copy of the template too, through the thread's TEB, which is ordinary memory | ||
| 486 | // of this process. | ||
| 487 | // | ||
| 488 | // What makes that safe: | ||
| 489 | // - The slot is the helper's, and nothing reads the helper's variable, so swapping the pointer under a running | ||
| 490 | // thread disturbs nothing; the thread cannot be in mapped code of a module whose load() has not returned. | ||
| 491 | // - The swap is made with g_tls_lock held exclusively, so no thread is inside its attach or detach event meanwhile. | ||
| 492 | // - A thread whose detach event has run is skipped (`ended`), and so is one with no TLS array or no helper block: | ||
| 493 | // Windows is about to free, or never built, what the block would go into. | ||
| 494 | // - The block comes out again in that thread's own detach event, before Windows frees the array, or in ~Loader. | ||
| 495 | // What is left: | ||
| 496 | // - A thread that ran its detach event before the helper DLL was ever loaded and has not left the process yet is | ||
| 497 | // not in `ended`; if Windows leaves a stale array pointer in its TEB for those last instructions, the write goes | ||
| 498 | // to freed heap memory. | ||
| 499 | // - Windows replaces a thread's TLS array (a new one, copied from the old) when some thread loads a DLL with static | ||
| 500 | // TLS. If that happens during the swap, the write can land in the old array; the thread then still has the | ||
| 501 | // helper's one-byte block, and the first mapped __declspec(thread) access on it writes past that block: heap | ||
| 502 | // corruption, with nothing to show for it. The swap therefore reads the array pointer again after writing and | ||
| 503 | // repeats on the new array (kSwapAttempts times); if the block is not in the thread's current array at the end, | ||
| 504 | // it is taken back and the miss is logged. A replacement after that last look is not seen. | ||
| 505 | // - TerminateThread frees a thread's TEB with no detach event. Every read and write of another thread's TEB or | ||
| 506 | // TLS array here is made right after the thread was seen running and inside __try, so a TEB that has just gone | ||
| 507 | // is a skipped thread, not a fault in load() or ~Loader. If the memory was already given to something else, the | ||
| 508 | // write is not caught. | ||
| 509 | using QueryThreadFn = LONG(NTAPI*)(HANDLE, int, void*, ULONG, ULONG*); | ||
| 510 | struct ThreadBasicInfo { // THREAD_BASIC_INFORMATION (winternl.h keeps it opaque), x64 | ||
| 511 | LONG exit_status; | ||
| 512 | void* teb; | ||
| 513 | void* process_id; | ||
| 514 | void* thread_id; | ||
| 515 | ULONG_PTR affinity; | ||
| 516 | LONG priority; | ||
| 517 | LONG base_priority; | ||
| 518 | }; | ||
| 519 | static_assert(sizeof(ThreadBasicInfo) == 48); | ||
| 520 | |||
| 521 | QueryThreadFn query_thread_fn() { | ||
| 522 | static const auto fn = reinterpret_cast<QueryThreadFn>( | ||
| 523 | reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread"))); | ||
| 524 | return fn; | ||
| 525 | } | ||
| 526 | |||
| 527 | // The TEB's ThreadLocalStoragePointer field of a thread that is still running; null otherwise. | ||
| 528 | void*** running_thread_tls_vector(HANDLE thread) { | ||
| 529 | ThreadBasicInfo info{}; | ||
| 530 | const QueryThreadFn query = query_thread_fn(); | ||
| 531 | if (!query || query(thread, 0 /* ThreadBasicInformation */, &info, sizeof info, nullptr) < 0) return nullptr; | ||
| 532 | if (info.exit_status != STILL_ACTIVE || !info.teb) return nullptr; | ||
| 533 | return reinterpret_cast<void***>(static_cast<uint8_t*>(info.teb) + 0x58); | ||
| 534 | } | ||
| 535 | |||
| 536 | // Another thread's TLS array and one entry of it, read through its TEB. False when the memory is not there any more | ||
| 537 | // (the thread was terminated). No C++ objects in these three: they are __try frames. | ||
| 538 | bool read_thread_slot(void*** vector, uint32_t index, void**& slots, void*& value) noexcept { | ||
| 539 | __try { | ||
| 540 | slots = *vector; | ||
| 541 | value = slots ? slots[index] : nullptr; | ||
| 542 | return true; | ||
| 543 | } __except (EXCEPTION_EXECUTE_HANDLER) { | ||
| 544 | slots = nullptr; | ||
| 545 | value = nullptr; | ||
| 546 | return false; | ||
| 547 | } | ||
| 548 | } | ||
| 549 | |||
| 550 | bool write_thread_slot(void** slots, uint32_t index, void* value) noexcept { | ||
| 551 | __try { | ||
| 552 | slots[index] = value; | ||
| 553 | return true; | ||
| 554 | } __except (EXCEPTION_EXECUTE_HANDLER) { | ||
| 555 | return false; | ||
| 556 | } | ||
| 557 | } | ||
| 558 | |||
| 559 | // Puts `saved` back where `block` is, if it is still there. | ||
| 560 | void restore_thread_slot(void*** vector, uint32_t index, void* block, void* saved) noexcept { | ||
| 561 | __try { | ||
| 562 | void** slots = *vector; | ||
| 563 | if (slots && slots[index] == block) slots[index] = saved; | ||
| 564 | } __except (EXCEPTION_EXECUTE_HANDLER) { | ||
| 565 | } | ||
| 566 | } | ||
| 567 | |||
| 568 | // Takes a block out of its slot and frees it. The existing-threads lock is held; b.vector is null when the thread | ||
| 569 | // is gone. | ||
| 570 | void remove_existing_block(const ExistingThreadBlock& b) { | ||
| 571 | if (b.vector && b.index < kMaxModuleTlsSlots) restore_thread_slot(b.vector, b.index, b.block, b.saved); | ||
| 572 | VirtualFree(b.block, 0, MEM_RELEASE); | ||
| 573 | } | ||
| 574 | |||
| 575 | constexpr int kSwapAttempts = 4; | ||
| 576 | constexpr size_t kMaxEndedThreads = 1024; | ||
| 577 | |||
| 578 | // load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done. | ||
| 579 | void install_on_existing_threads(Module& m) { | ||
| 580 | const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill; | ||
| 581 | if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kMaxMappedTlsModules) return; | ||
| 582 | // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which | ||
| 583 | // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours. | ||
| 584 | if (!query_thread_fn()) return; | ||
| 585 | |||
| 586 | // Outside the TLS lock: none of this may wait for a thread that is inside its attach event. | ||
| 587 | // The handles are closed on every way out, also when a vector below cannot grow. | ||
| 588 | struct Candidate { | ||
| 589 | DWORD id = 0; | ||
| 590 | HANDLE handle = nullptr; | ||
| 591 | }; | ||
| 592 | struct Candidates { | ||
| 593 | std::vector<Candidate> list; | ||
| 594 | HANDLE snapshot = INVALID_HANDLE_VALUE; | ||
| 595 | ~Candidates() { | ||
| 596 | if (snapshot != INVALID_HANDLE_VALUE) CloseHandle(snapshot); | ||
| 597 | for (const Candidate& c : list) | ||
| 598 | if (c.handle) CloseHandle(c.handle); | ||
| 599 | } | ||
| 600 | } found; | ||
| 601 | std::vector<Candidate>& candidates = found.list; | ||
| 602 | // TH32CS_SNAPTHREAD lists the threads of every process; the loop keeps this one's. | ||
| 603 | found.snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); | ||
| 604 | if (found.snapshot == INVALID_HANDLE_VALUE) return; | ||
| 605 | THREADENTRY32 entry{}; | ||
| 606 | entry.dwSize = sizeof entry; | ||
| 607 | const DWORD process = GetCurrentProcessId(), self = GetCurrentThreadId(); | ||
| 608 | for (BOOL more = Thread32First(found.snapshot, &entry); more; more = Thread32Next(found.snapshot, &entry)) { | ||
| 609 | if (entry.th32OwnerProcessID != process || entry.th32ThreadID == self) continue; | ||
| 610 | candidates.push_back({entry.th32ThreadID, nullptr}); // the slot first, so the handle always has an owner | ||
| 611 | candidates.back().handle = OpenThread(THREAD_QUERY_INFORMATION, FALSE, entry.th32ThreadID); | ||
| 612 | } | ||
| 613 | |||
| 614 | { | ||
| 615 | ExclusiveTlsLock tls_lock; | ||
| 616 | ExistingThreadsLock lock; | ||
| 617 | ExistingThreads& state = existing_threads(); | ||
| 618 | for (const Candidate& c : candidates) { | ||
| 619 | if (!c.handle) continue; | ||
| 620 | if (std::find(state.ended.begin(), state.ended.end(), c.id) != state.ended.end()) continue; | ||
| 621 | void*** vector = running_thread_tls_vector(c.handle); | ||
| 622 | void** slots = nullptr; | ||
| 623 | void* saved = nullptr; | ||
| 624 | if (!vector || !read_thread_slot(vector, m.tls_index, slots, saved) || !slots || !saved) continue; | ||
| 625 | // A copy an earlier module left in this slot of this thread goes first; what it replaced is kept. | ||
| 626 | bool present = false; | ||
| 627 | for (auto it = state.blocks.begin(); it != state.blocks.end();) { | ||
| 628 | if (it->thread != c.id || it->slot != m.tls_slot) { | ||
| 629 | ++it; | ||
| 630 | } else if (it->module == &m && it->generation == m.tls_generation) { | ||
| 631 | present = true; | ||
| 632 | break; | ||
| 633 | } else { | ||
| 634 | if (saved == it->block) saved = it->saved; | ||
| 635 | it->vector = vector; | ||
| 636 | remove_existing_block(*it); | ||
| 637 | it = state.blocks.erase(it); | ||
| 638 | } | ||
| 639 | } | ||
| 640 | if (present) continue; | ||
| 641 | void* block = VirtualAlloc(nullptr, static_cast<SIZE_T>(total), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); | ||
| 642 | if (!block) continue; | ||
| 643 | if (m.tls_raw_size) std::memcpy(block, m.tls_template, m.tls_raw_size); | ||
| 644 | |||
| 645 | // Write, then look at the thread's array pointer again: if Windows has replaced the array meanwhile, the | ||
| 646 | // write went into the old one, and it is made again in the new one. | ||
| 647 | bool installed = false; | ||
| 648 | for (int attempt = 0; attempt < kSwapAttempts && !installed; ++attempt) { | ||
| 649 | if (!running_thread_tls_vector(c.handle) || !write_thread_slot(slots, m.tls_index, block)) break; | ||
| 650 | void** now = nullptr; | ||
| 651 | void* value = nullptr; | ||
| 652 | if (!read_thread_slot(vector, m.tls_index, now, value) || !now) break; | ||
| 653 | installed = now == slots && value == block; | ||
| 654 | slots = now; | ||
| 655 | } | ||
| 656 | if (!installed) { | ||
| 657 | restore_thread_slot(vector, m.tls_index, block, saved); | ||
| 658 | VirtualFree(block, 0, MEM_RELEASE); | ||
| 659 | static std::atomic<bool> logged{false}; | ||
| 660 | if (!logged.exchange(true)) | ||
| 661 | std::fprintf(stderr, "[rt] loader: %s: a running thread did not take its TLS block (it ended, or " | ||
| 662 | "its TLS array kept changing); mapped thread-local data is not valid on it\n", | ||
| 663 | m.name.c_str()); | ||
| 664 | continue; | ||
| 665 | } | ||
| 666 | state.blocks.push_back({c.id, m.tls_slot, &m, m.tls_generation, m.tls_index, vector, saved, block}); | ||
| 667 | } | ||
| 668 | } | ||
| 669 | } | ||
| 670 | |||
| 671 | // ~Loader, with g_tls_lock held exclusively: the blocks load() put into other threads come out. A thread that has | ||
| 672 | // ended without a detach event (TerminateThread) has no TEB to restore. | ||
| 673 | void remove_from_existing_threads(Module& m) { | ||
| 674 | ExistingThreadsLock lock; | ||
| 675 | ExistingThreads& state = existing_threads(); | ||
| 676 | for (auto it = state.blocks.begin(); it != state.blocks.end();) { | ||
| 677 | if (it->module != &m || it->generation != m.tls_generation) { | ||
| 678 | ++it; | ||
| 679 | continue; | ||
| 680 | } | ||
| 681 | ExistingThreadBlock b = *it; | ||
| 682 | it = state.blocks.erase(it); | ||
| 683 | const HANDLE h = OpenThread(THREAD_QUERY_INFORMATION, FALSE, b.thread); | ||
| 684 | if (!h || running_thread_tls_vector(h) != b.vector) b.vector = nullptr; | ||
| 685 | if (h) CloseHandle(h); | ||
| 686 | remove_existing_block(b); | ||
| 687 | } | ||
| 688 | } | ||
| 689 | |||
| 690 | // DLL_THREAD_ATTACH: a record under this thread's id is from a thread that ended without a detach event. | ||
| 691 | void forget_ended_thread_id() { | ||
| 692 | const DWORD self = GetCurrentThreadId(); | ||
| 693 | ExistingThreadsLock lock; | ||
| 694 | ExistingThreads& state = existing_threads(); | ||
| 695 | state.ended.erase(std::remove(state.ended.begin(), state.ended.end(), self), state.ended.end()); | ||
| 696 | for (auto it = state.blocks.begin(); it != state.blocks.end();) { | ||
| 697 | if (it->thread != self) { | ||
| 698 | ++it; | ||
| 699 | continue; | ||
| 700 | } | ||
| 701 | VirtualFree(it->block, 0, MEM_RELEASE); | ||
| 702 | it = state.blocks.erase(it); | ||
| 703 | } | ||
| 704 | } | ||
| 705 | |||
| 706 | // DLL_THREAD_DETACH, before this thread's own records are released: the blocks load() gave it come out, newest first, | ||
| 707 | // after the module's TLS callbacks have seen the event (Windows sends DLL_THREAD_DETACH to a DLL for a thread that | ||
| 708 | // was running before it was loaded, too). | ||
| 709 | void release_existing_blocks_of_this_thread() { | ||
| 710 | const DWORD self = GetCurrentThreadId(); | ||
| 711 | std::vector<ExistingThreadBlock> mine; | ||
| 712 | { | ||
| 713 | ExistingThreadsLock lock; | ||
| 714 | for (const auto& b : existing_threads().blocks) | ||
| 715 | if (b.thread == self) mine.push_back(b); | ||
| 716 | } | ||
| 717 | for (auto it = mine.rbegin(); it != mine.rend(); ++it) { | ||
| 718 | Module* m = it->module; | ||
| 719 | if (g_tls_slot_owners[it->slot].load() != m || g_tls_slot_generations[it->slot].load() != it->generation || | ||
| 720 | !m->initialised) | ||
| 721 | continue; | ||
| 722 | try { | ||
| 723 | run_callbacks(*m, DLL_THREAD_DETACH); | ||
| 724 | } catch (const std::exception& e) { | ||
| 725 | std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what()); | ||
| 726 | } | ||
| 727 | } | ||
| 728 | ExistingThreadsLock lock; | ||
| 729 | ExistingThreads& state = existing_threads(); | ||
| 730 | for (auto it = state.blocks.end(); it != state.blocks.begin();) { | ||
| 731 | --it; | ||
| 732 | if (it->thread != self) continue; | ||
| 733 | remove_existing_block(*it); | ||
| 734 | it = state.blocks.erase(it); | ||
| 735 | } | ||
| 736 | // Bounded: an id matters only until its thread has left the process, moments after this event, so the oldest | ||
| 737 | // can go. (An id also leaves the list when a new thread gets it.) | ||
| 738 | if (state.ended.size() >= kMaxEndedThreads) state.ended.erase(state.ended.begin(), state.ended.begin() + kMaxEndedThreads / 2); | ||
| 739 | state.ended.push_back(self); | ||
| 740 | } | ||
| 741 | |||
| 410 | // Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under | 742 | // 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 | 743 | // 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 | 744 | // ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events |
| @@ -416,6 +748,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 | 748 | // 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. | 749 | // away from the other slots. Nothing may leave DllMain. |
| 418 | if (reason == DLL_THREAD_ATTACH) { | 750 | if (reason == DLL_THREAD_ATTACH) { |
| 751 | try { | ||
| 752 | forget_ended_thread_id(); | ||
| 753 | } catch (const std::exception& e) { | ||
| 754 | std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what()); | ||
| 755 | } | ||
| 419 | for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { | 756 | for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { |
| 420 | Module* m = g_tls_slot_owners[slot].load(); | 757 | Module* m = g_tls_slot_owners[slot].load(); |
| 421 | if (!m) continue; | 758 | if (!m) continue; |
| @@ -429,6 +766,13 @@ void __cdecl on_host_thread_event(DWORD reason) { | |||
| 429 | } | 766 | } |
| 430 | } | 767 | } |
| 431 | } else if (reason == DLL_THREAD_DETACH) { | 768 | } else if (reason == DLL_THREAD_DETACH) { |
| 769 | // The blocks load() gave this thread while it was already running come out first (they can sit on top of | ||
| 770 | // an older module's block in the same slot). | ||
| 771 | try { | ||
| 772 | release_existing_blocks_of_this_thread(); | ||
| 773 | } catch (const std::exception& e) { | ||
| 774 | std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what()); | ||
| 775 | } | ||
| 432 | for (size_t i = kMaxMappedTlsModules; i-- > 0;) { | 776 | for (size_t i = kMaxMappedTlsModules; i-- > 0;) { |
| 433 | Module* m = g_tls_slot_owners[i].load(); | 777 | Module* m = g_tls_slot_owners[i].load(); |
| 434 | if (m && g_thread_tls_slots[i].module == m && | 778 | if (m && g_thread_tls_slots[i].module == m && |
| @@ -451,9 +795,15 @@ void __cdecl on_host_thread_event(DWORD reason) { | |||
| 451 | 795 | ||
| 452 | // The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used. | 796 | // The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used. |
| 453 | bool prefer_host_copy(const std::string& dll) { | 797 | bool prefer_host_copy(const std::string& dll) { |
| 798 | // The second row is the Debug builds of the same DLLs. A Debug build of a stand-in image (tiny_game) links them, | ||
| 799 | // and without them here its C++ exceptions were not redirected below: a throw caught inside the image ended the | ||
| 800 | // run with 0xE06D7363 (run_tiny_game_eh in a Debug build). | ||
| 454 | static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll", | 801 | static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll", |
| 455 | "msvcp140_2.dll", "msvcp140_atomic_wait.dll", "msvcp140_codecvt_ids.dll", | 802 | "msvcp140_2.dll", "msvcp140_atomic_wait.dll", "msvcp140_codecvt_ids.dll", |
| 456 | "concrt140.dll", "vccorlib140.dll", "vcomp140.dll"}; | 803 | "concrt140.dll", "vccorlib140.dll", "vcomp140.dll", |
| 804 | "vcruntime140d.dll", "vcruntime140_1d.dll", "msvcp140d.dll", "msvcp140_1d.dll", | ||
| 805 | "msvcp140_2d.dll", "msvcp140d_atomic_wait.dll", "msvcp140d_codecvt_ids.dll", | ||
| 806 | "concrt140d.dll", "vccorlib140d.dll", "vcomp140d.dll"}; | ||
| 457 | for (auto* n : names) | 807 | for (auto* n : names) |
| 458 | if (dll == n) return true; | 808 | if (dll == n) return true; |
| 459 | return false; | 809 | return false; |
| @@ -594,6 +944,7 @@ Loader::~Loader() { | |||
| 594 | Module* owner = m; | 944 | Module* owner = m; |
| 595 | if (g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr)) | 945 | if (g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr)) |
| 596 | g_tls_slot_generations[m->tls_slot].store(0); | 946 | g_tls_slot_generations[m->tls_slot].store(0); |
| 947 | remove_from_existing_threads(*m); | ||
| 597 | } | 948 | } |
| 598 | uninstall_tls_for_thread(*m); | 949 | uninstall_tls_for_thread(*m); |
| 599 | } | 950 | } |
| @@ -607,11 +958,13 @@ Loader::~Loader() { | |||
| 607 | 958 | ||
| 608 | Module& Loader::load(const std::filesystem::path& image) { | 959 | Module& Loader::load(const std::filesystem::path& image) { |
| 609 | std::lock_guard lock(mutex_); | 960 | std::lock_guard lock(mutex_); |
| 610 | std::string key = lower(image.filename().string()); | 961 | const auto key = module_key(image); |
| 611 | if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; | 962 | if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; |
| 963 | const auto narrow_key = narrow_module_key(image); | ||
| 964 | if (Module* existing = find_narrow_module(narrow_key)) return *existing; | ||
| 612 | Module* mapped = nullptr; | 965 | Module* mapped = nullptr; |
| 613 | try { | 966 | try { |
| 614 | mapped = &map_image(image); | 967 | mapped = &map_image(image, narrow_key); |
| 615 | bind_imports(*mapped); // loads every bundled module m imports first, so they land in init_order_ before m | 968 | bind_imports(*mapped); // loads every bundled module m imports first, so they land in init_order_ before m |
| 616 | protect_sections(*mapped); | 969 | protect_sections(*mapped); |
| 617 | register_unwind(*mapped); | 970 | register_unwind(*mapped); |
| @@ -631,10 +984,19 @@ Module& Loader::load(const std::filesystem::path& image) { | |||
| 631 | return m; | 984 | return m; |
| 632 | } | 985 | } |
| 633 | 986 | ||
| 987 | Module* Loader::find_narrow_module(const std::string& dll_lower) const { | ||
| 988 | if (dll_lower.empty()) return nullptr; | ||
| 989 | // library_loader and PE import names keep their existing narrow-byte contract. Do not reinterpret them | ||
| 990 | // as UTF-8 or widen already-folded bytes (which could be part of a multibyte code-page character). | ||
| 991 | for (const auto& entry : by_name_) | ||
| 992 | if (entry.second->narrow_key == dll_lower) return entry.second; | ||
| 993 | return nullptr; | ||
| 994 | } | ||
| 995 | |||
| 634 | void* Loader::find_loaded_module(const std::string& dll_lower) const { | 996 | void* Loader::find_loaded_module(const std::string& dll_lower) const { |
| 635 | std::lock_guard lock(mutex_); | 997 | std::lock_guard lock(mutex_); |
| 636 | auto it = by_name_.find(dll_lower); | 998 | Module* m = find_narrow_module(dll_lower); |
| 637 | return it == by_name_.end() ? nullptr : static_cast<void*>(it->second->base); | 999 | return m ? static_cast<void*>(m->base) : nullptr; |
| 638 | } | 1000 | } |
| 639 | 1001 | ||
| 640 | void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled) { | 1002 | void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled) { |
| @@ -642,10 +1004,10 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, | |||
| 642 | if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr; | 1004 | if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr; |
| 643 | 1005 | ||
| 644 | std::lock_guard lock(mutex_); | 1006 | std::lock_guard lock(mutex_); |
| 645 | const auto existing = by_name_.find(dll_lower); | 1007 | Module* existing = find_narrow_module(dll_lower); |
| 646 | const std::filesystem::path candidate = game_dir_ / dll_lower; | 1008 | const std::filesystem::path candidate = game_dir_ / dll_lower; |
| 647 | std::error_code ec; | 1009 | std::error_code ec; |
| 648 | const bool is_bundled = existing != by_name_.end() || std::filesystem::is_regular_file(candidate, ec); | 1010 | const bool is_bundled = existing || std::filesystem::is_regular_file(candidate, ec); |
| 649 | if (!is_bundled) return nullptr; | 1011 | if (!is_bundled) return nullptr; |
| 650 | 1012 | ||
| 651 | handled = true; | 1013 | handled = true; |
| @@ -659,10 +1021,10 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, | |||
| 659 | return nullptr; | 1021 | return nullptr; |
| 660 | } | 1022 | } |
| 661 | 1023 | ||
| 662 | if (existing != by_name_.end()) { | 1024 | if (existing) { |
| 663 | try { | 1025 | try { |
| 664 | initialise(); | 1026 | initialise(); |
| 665 | return static_cast<void*>(existing->second->base); | 1027 | return static_cast<void*>(existing->base); |
| 666 | } catch (const std::exception& e) { | 1028 | } catch (const std::exception& e) { |
| 667 | std::fprintf(stderr, "[rt] loader: run-time initialise of %s failed: %s\n", dll_lower.c_str(), e.what()); | 1029 | std::fprintf(stderr, "[rt] loader: run-time initialise of %s failed: %s\n", dll_lower.c_str(), e.what()); |
| 668 | SetLastError(ERROR_DLL_INIT_FAILED); | 1030 | SetLastError(ERROR_DLL_INIT_FAILED); |
| @@ -670,15 +1032,17 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, | |||
| 670 | } | 1032 | } |
| 671 | } | 1033 | } |
| 672 | 1034 | ||
| 1035 | Module* mapped = nullptr; | ||
| 673 | try { | 1036 | try { |
| 674 | Module& m = load(candidate); | 1037 | Module& m = load(candidate); |
| 1038 | mapped = &m; | ||
| 675 | initialise(); | 1039 | initialise(); |
| 676 | std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str()); | 1040 | std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str()); |
| 677 | return static_cast<void*>(m.base); | 1041 | return static_cast<void*>(m.base); |
| 678 | } catch (const std::exception& e) { | 1042 | } catch (const std::exception& e) { |
| 679 | // load() drops a module that failed to map or bind (dependencies included); this also drops one whose | 1043 | // load() drops a module that failed to map or bind (dependencies included); this also drops one whose |
| 680 | // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via order_. | 1044 | // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via order_. |
| 681 | by_name_.erase(dll_lower); | 1045 | by_name_.erase(module_key(mapped ? mapped->path : candidate)); |
| 682 | std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what()); | 1046 | std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what()); |
| 683 | SetLastError(ERROR_DLL_INIT_FAILED); | 1047 | SetLastError(ERROR_DLL_INIT_FAILED); |
| 684 | return nullptr; | 1048 | return nullptr; |
| @@ -806,12 +1170,12 @@ void Loader::set_initialised(Module& m, bool value) { | |||
| 806 | m.initialised = value; | 1170 | m.initialised = value; |
| 807 | } | 1171 | } |
| 808 | 1172 | ||
| 809 | Module& Loader::map_image(const std::filesystem::path& path) { | 1173 | Module& Loader::map_image(const std::filesystem::path& path, const std::string& narrow_key) { |
| 810 | auto file = read_file(path); | 1174 | auto file = read_file(path); |
| 811 | const std::string name = path.filename().string(); | 1175 | const std::string name = path_utf8(path.filename()); |
| 812 | auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(file.data()); | 1176 | auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(file.data()); |
| 813 | if (file.size() < sizeof(IMAGE_DOS_HEADER) || dos->e_magic != IMAGE_DOS_SIGNATURE) | 1177 | if (file.size() < sizeof(IMAGE_DOS_HEADER) || dos->e_magic != IMAGE_DOS_SIGNATURE) |
| 814 | throw std::runtime_error(path.string() + ": not an MZ image"); | 1178 | throw std::runtime_error(path_utf8(path) + ": not an MZ image"); |
| 815 | if (dos->e_lfanew < 0 || static_cast<uint64_t>(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size()) | 1179 | if (dos->e_lfanew < 0 || static_cast<uint64_t>(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size()) |
| 816 | throw std::runtime_error(name + ": the NT headers are outside the file"); | 1180 | throw std::runtime_error(name + ": the NT headers are outside the file"); |
| 817 | auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew); | 1181 | auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew); |
| @@ -835,11 +1199,12 @@ Module& Loader::map_image(const std::filesystem::path& path) { | |||
| 835 | 1199 | ||
| 836 | auto* m = new Module; | 1200 | auto* m = new Module; |
| 837 | m->name = name; | 1201 | m->name = name; |
| 1202 | m->narrow_key = narrow_key; | ||
| 838 | m->path = path; | 1203 | m->path = path; |
| 839 | m->preferred_base = oh.ImageBase; | 1204 | m->preferred_base = oh.ImageBase; |
| 840 | m->size = oh.SizeOfImage; | 1205 | m->size = oh.SizeOfImage; |
| 841 | m->entry_rva = oh.AddressOfEntryPoint; | 1206 | m->entry_rva = oh.AddressOfEntryPoint; |
| 842 | by_name_[lower(m->name)] = m; | 1207 | by_name_[module_key(path)] = m; |
| 843 | order_.push_back(m); | 1208 | order_.push_back(m); |
| 844 | 1209 | ||
| 845 | // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual. | 1210 | // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual. |
| @@ -864,6 +1229,8 @@ Module& Loader::map_image(const std::filesystem::path& path) { | |||
| 864 | std::memcpy(m->base, file.data(), oh.SizeOfHeaders); | 1229 | std::memcpy(m->base, file.data(), oh.SizeOfHeaders); |
| 865 | auto* sec = IMAGE_FIRST_SECTION(nt); | 1230 | auto* sec = IMAGE_FIRST_SECTION(nt); |
| 866 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { | 1231 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { |
| 1232 | if (sec->VirtualAddress < oh.SizeOfHeaders) | ||
| 1233 | throw std::runtime_error(m->name + ": section " + std::to_string(i) + " overlaps the headers"); | ||
| 867 | uint32_t n = std::min(sec->SizeOfRawData, sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData); | 1234 | uint32_t n = std::min(sec->SizeOfRawData, sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData); |
| 868 | if (!n) continue; | 1235 | if (!n) continue; |
| 869 | if (sec->PointerToRawData > file.size() || n > file.size() - sec->PointerToRawData) | 1236 | if (sec->PointerToRawData > file.size() || n > file.size() - sec->PointerToRawData) |
| @@ -889,6 +1256,9 @@ Module& Loader::map_image(const std::filesystem::path& path) { | |||
| 889 | size_t count = (block->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2; | 1256 | size_t count = (block->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2; |
| 890 | for (size_t i = 0; i < count; ++i) { | 1257 | for (size_t i = 0; i < count; ++i) { |
| 891 | uint16_t type = entries[i] >> 12, off = entries[i] & 0xFFF; | 1258 | uint16_t type = entries[i] >> 12, off = entries[i] & 0xFFF; |
| 1259 | if (type != IMAGE_REL_BASED_ABSOLUTE && | ||
| 1260 | static_cast<uint64_t>(block->VirtualAddress) + off < oh.SizeOfHeaders) | ||
| 1261 | throw std::runtime_error(m->name + ": a relocation lands in the headers"); | ||
| 892 | if (type == IMAGE_REL_BASED_DIR64) { | 1262 | if (type == IMAGE_REL_BASED_DIR64) { |
| 893 | require_range(m->name, static_cast<uint64_t>(block->VirtualAddress) + off, sizeof(uint64_t), m->size, | 1263 | require_range(m->name, static_cast<uint64_t>(block->VirtualAddress) + off, sizeof(uint64_t), m->size, |
| 894 | "a relocation"); | 1264 | "a relocation"); |
| @@ -1003,6 +1373,9 @@ void Loader::initialize_tls(Module& m) { | |||
| 1003 | m.tls_block = g_thread_tls_slots[slot].block; | 1373 | m.tls_block = g_thread_tls_slots[slot].block; |
| 1004 | m.tls_saved_block = g_thread_tls_slots[slot].saved; | 1374 | m.tls_saved_block = g_thread_tls_slots[slot].saved; |
| 1005 | } | 1375 | } |
| 1376 | // Threads started from here on get their copy from the helper DLL's DLL_THREAD_ATTACH; the ones already running | ||
| 1377 | // get it now. | ||
| 1378 | install_on_existing_threads(m); | ||
| 1006 | } | 1379 | } |
| 1007 | 1380 | ||
| 1008 | void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); } | 1381 | void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); } |