diff options
| author | ItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com> | 2026-11-22 23:08:12 -0500 |
|---|---|---|
| committer | ItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com> | 2026-11-22 23:08:12 -0500 |
| commit | 44d705ce4b34002c61cb65786c4faaffde08d1f2 (patch) | |
| tree | f9657f02bd83bd151ab999640b7d9a32b448e925 /runtime | |
| parent | 210813af2a1e628f7bcba57a69cf486abe81962b (diff) | |
| parent | 2fb013cd9b6ac1062625fbdb556cd1535db008f1 (diff) | |
Merge pull request #3671 from kotorvr
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime')
| -rw-r--r-- | runtime/README.md | 7 | ||||
| -rw-r--r-- | runtime/src/pe_loader.cpp | 320 | ||||
| -rw-r--r-- | runtime/src/pe_loader.h | 13 | ||||
| -rw-r--r-- | runtime/test/loader_tls_test.cpp | 174 |
4 files changed, 504 insertions, 10 deletions
diff --git a/runtime/README.md b/runtime/README.md index aace038d9..160843870 100644 --- a/runtime/README.md +++ b/runtime/README.md | |||
| @@ -134,9 +134,10 @@ Current limits, by design: | |||
| 134 | `gta6rt_tls_host.dll`'s `DLL_THREAD_ATTACH`, and gives it back at `DLL_THREAD_DETACH`, also when the | 134 | `gta6rt_tls_host.dll`'s `DLL_THREAD_ATTACH`, and gives it back at `DLL_THREAD_DETACH`, also when the |
| 135 | thread outlives its `Loader`. From `initialise()` until `~Loader` starts the process detach, those | 135 | thread outlives its `Loader`. From `initialise()` until `~Loader` starts the process detach, those |
| 136 | events also run the module's TLS callbacks, with the thread's copy already in place. A thread that | 136 | events also run the module's TLS callbacks, with the thread's copy already in place. A thread that |
| 137 | existed before `load()` gets nothing: | 137 | was already running when `load()` ran, such as a worker of the process thread pool that the task queue later runs a |
| 138 | call `install_tls_for_thread()` before mapped code runs on it and `uninstall_tls_for_thread()` before it | 138 | title's callback on, gets its copy from `load()` itself, the way Windows gives one to running threads for a DLL it |
| 139 | exits. Mapped DLLs' `DllMain` is not called with thread events. Destroy the `Loader` on the thread that | 139 | loads: a block, no `DLL_THREAD_ATTACH`, `DLL_THREAD_DETACH` when it ends, and `~Loader` takes the block back. |
| 140 | `install_tls_for_thread()` and `uninstall_tls_for_thread()` are no-ops on such a thread. Mapped DLLs' `DllMain` is not called with thread events. Destroy the `Loader` on the thread that | ||
| 140 | called `load()`. | 141 | called `load()`. |
| 141 | - The TOC of the game's RPF archives is encrypted and is not read here. The loader works on the PE | 142 | - The TOC of the game's RPF archives is encrypted and is not read here. The loader works on the PE |
| 142 | files and on any images the caller passes it. | 143 | files and on any images the caller passes it. |
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. | ||
| 339 | struct 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. | ||
| 352 | struct 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 | }; | ||
| 357 | ExistingThreads& existing_threads() { | ||
| 358 | static auto* state = new ExistingThreads; | ||
| 359 | return *state; | ||
| 360 | } | ||
| 361 | struct 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 | |||
| 368 | bool 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 | |||
| 335 | void install_thread_block(Module& m) { | 375 | void 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. | ||
| 481 | using QueryThreadFn = LONG(NTAPI*)(HANDLE, int, void*, ULONG, ULONG*); | ||
| 482 | struct 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 | }; | ||
| 491 | static_assert(sizeof(ThreadBasicInfo) == 48); | ||
| 492 | |||
| 493 | QueryThreadFn 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. | ||
| 500 | void*** 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. | ||
| 510 | bool 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 | |||
| 522 | bool 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. | ||
| 532 | void 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. | ||
| 542 | void 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 | |||
| 547 | constexpr int kSwapAttempts = 4; | ||
| 548 | constexpr 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. | ||
| 551 | void 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. | ||
| 645 | void 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. | ||
| 663 | void 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). | ||
| 681 | void 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 | ||
| 1031 | void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); } | 1351 | void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); } |
diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index d7e5be91c..57962c9b4 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h | |||
| @@ -50,7 +50,8 @@ struct Module { | |||
| 50 | // __declspec(thread) reads; it is not a TlsAlloc slot. The loader reserves distinct indices by loading | 50 | // __declspec(thread) reads; it is not a TlsAlloc slot. The loader reserves distinct indices by loading |
| 51 | // gta6rt_tls_host.dll (and cloning it on demand for additional simultaneous TLS modules, up to 16 at a time). | 51 | // gta6rt_tls_host.dll (and cloning it on demand for additional simultaneous TLS modules, up to 16 at a time). |
| 52 | // Every thread started after load() gets its own copy through the helper's DLL_THREAD_ATTACH, and gives it back | 52 | // Every thread started after load() gets its own copy through the helper's DLL_THREAD_ATTACH, and gives it back |
| 53 | // at DLL_THREAD_DETACH; install_tls_for_thread() is for threads that already existed. | 53 | // at DLL_THREAD_DETACH. A thread that was already running gets its copy from load() itself, as it would from |
| 54 | // Windows for a DLL Windows loads: a block, no DLL_THREAD_ATTACH, and DLL_THREAD_DETACH when it ends. | ||
| 54 | uint32_t tls_index = kNoTlsIndex; | 55 | uint32_t tls_index = kNoTlsIndex; |
| 55 | uint32_t tls_slot = kNoTlsIndex; // index into the loader's reserved TLS-host slot pool | 56 | uint32_t tls_slot = kNoTlsIndex; // index into the loader's reserved TLS-host slot pool |
| 56 | uint64_t tls_generation = 0; // unique token per TLS initialisation, distinguishing reused slots/addresses | 57 | uint64_t tls_generation = 0; // unique token per TLS initialisation, distinguishing reused slots/addresses |
| @@ -104,11 +105,11 @@ public: | |||
| 104 | void run_tls_callbacks(Module& m, uint32_t reason); | 105 | void run_tls_callbacks(Module& m, uint32_t reason); |
| 105 | 106 | ||
| 106 | // Installs/removes this module's template copy in the calling thread's TEB slot. load() does this for its caller | 107 | // Installs/removes this module's template copy in the calling thread's TEB slot. load() does this for its caller |
| 107 | // and the thread events for threads started after it; both are no-ops on a thread that already has this module's | 108 | // and for every other thread running at the time, and the thread events for threads started after it, so on any |
| 108 | // copy. Call install on a thread that existed before load(), before mapped code runs there, and uninstall before | 109 | // of those both are no-ops. They remain for a thread load() could not reach (pe_loader.cpp, "Threads that |
| 109 | // that thread exits. Each module's copy sits in its own TEB slot, so one thread can hold copies of several | 110 | // existed before load()", lists the cases): install before mapped code runs there, uninstall before the thread |
| 110 | // modules. These do not run TLS callbacks (use | 111 | // exits. Each module's copy sits in its own TEB slot, so one thread can hold copies of several modules. These do |
| 111 | // run_tls_callbacks with DLL_THREAD_ATTACH/DETACH for that). | 112 | // not run TLS callbacks (use run_tls_callbacks with DLL_THREAD_ATTACH/DETACH for that). |
| 112 | void install_tls_for_thread(Module& m); | 113 | void install_tls_for_thread(Module& m); |
| 113 | void uninstall_tls_for_thread(Module& m); | 114 | void uninstall_tls_for_thread(Module& m); |
| 114 | 115 | ||
diff --git a/runtime/test/loader_tls_test.cpp b/runtime/test/loader_tls_test.cpp index 6d5a06dd3..f7cc4514b 100644 --- a/runtime/test/loader_tls_test.cpp +++ b/runtime/test/loader_tls_test.cpp | |||
| @@ -443,6 +443,172 @@ void test_multiple_tls_modules(const fs::path& dll, const fs::path& temp) { | |||
| 443 | } | 443 | } |
| 444 | } | 444 | } |
| 445 | 445 | ||
| 446 | // Threads that already exist when load() runs: a thread of the caller's and a worker of the process thread pool, | ||
| 447 | // which is where the task queue (third_party/xtaskqueue, ThreadPool_win32.cpp) runs a title's callbacks. Windows | ||
| 448 | // gives such threads the new module's TLS block when it loads a DLL itself, and no DLL_THREAD_ATTACH; load() has to | ||
| 449 | // do the same, or mapped code on them reads the helper DLL's one-byte block. | ||
| 450 | struct PoolProbe { | ||
| 451 | int(__cdecl* get)() = nullptr; | ||
| 452 | void(__cdecl* set)(int) = nullptr; | ||
| 453 | HANDLE done = nullptr; | ||
| 454 | LONG value = -1; | ||
| 455 | DWORD thread = 0; | ||
| 456 | }; | ||
| 457 | |||
| 458 | void CALLBACK pool_probe(PTP_CALLBACK_INSTANCE, void* context) { | ||
| 459 | auto* probe = static_cast<PoolProbe*>(context); | ||
| 460 | probe->thread = GetCurrentThreadId(); | ||
| 461 | if (probe->get) { | ||
| 462 | probe->value = probe->get(); | ||
| 463 | probe->set(4000); | ||
| 464 | } | ||
| 465 | SetEvent(probe->done); | ||
| 466 | } | ||
| 467 | |||
| 468 | struct ParkedThread { | ||
| 469 | HANDLE up = CreateEventW(nullptr, FALSE, FALSE, nullptr); | ||
| 470 | HANDLE never = CreateEventW(nullptr, FALSE, FALSE, nullptr); | ||
| 471 | }; | ||
| 472 | |||
| 473 | DWORD WINAPI park(void* context) { | ||
| 474 | auto* parked = static_cast<ParkedThread*>(context); | ||
| 475 | SetEvent(parked->up); | ||
| 476 | WaitForSingleObject(parked->never, INFINITE); | ||
| 477 | return 0; | ||
| 478 | } | ||
| 479 | |||
| 480 | // TerminateThread ends a thread with no DLL_THREAD_DETACH and frees its TEB. A thread that load() gave a block and | ||
| 481 | // that is then terminated must not be touched by ~Loader, and a thread that is already dead must be passed by. | ||
| 482 | void test_terminated_thread(const fs::path& dll) { | ||
| 483 | ParkedThread parked; | ||
| 484 | const HANDLE victim = CreateThread(nullptr, 0, &park, &parked, 0, nullptr); | ||
| 485 | check(victim != nullptr && WaitForSingleObject(parked.up, 10000) == WAIT_OBJECT_0, "a parked thread is running"); | ||
| 486 | if (!victim) return; | ||
| 487 | { | ||
| 488 | rt::Loader loader(dll.parent_path()); | ||
| 489 | rt::Module& m = loader.load(dll); | ||
| 490 | check(find_export<int(__cdecl*)()>(m, "tiny_tls_get")() == 7, "load() with a parked thread running"); | ||
| 491 | TerminateThread(victim, 0); | ||
| 492 | WaitForSingleObject(victim, INFINITE); | ||
| 493 | } | ||
| 494 | check(true, "~Loader passes by a thread that was terminated while it held a block"); | ||
| 495 | { | ||
| 496 | // The dead thread is still a kernel object (its handle is open) while this load() looks at the threads. | ||
| 497 | rt::Loader loader(dll.parent_path()); | ||
| 498 | rt::Module& m = loader.load(dll); | ||
| 499 | check(find_export<int(__cdecl*)()>(m, "tiny_tls_get")() == 7, "load() passes by a thread that has ended"); | ||
| 500 | } | ||
| 501 | CloseHandle(victim); | ||
| 502 | CloseHandle(parked.up); | ||
| 503 | CloseHandle(parked.never); | ||
| 504 | } | ||
| 505 | |||
| 506 | void test_existing_threads(const fs::path& dll) { | ||
| 507 | // A pool worker exists from here on: the callback has run on one, and the pool keeps its workers for a while. | ||
| 508 | PoolProbe warm; | ||
| 509 | warm.done = CreateEventW(nullptr, FALSE, FALSE, nullptr); | ||
| 510 | check(TrySubmitThreadpoolCallback(&pool_probe, &warm, nullptr) != 0 && | ||
| 511 | WaitForSingleObject(warm.done, 10000) == WAIT_OBJECT_0, | ||
| 512 | "a thread-pool worker exists before load()"); | ||
| 513 | |||
| 514 | struct Step { | ||
| 515 | HANDLE go = CreateEventW(nullptr, FALSE, FALSE, nullptr); | ||
| 516 | HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr); | ||
| 517 | }; | ||
| 518 | Step first, second, last; | ||
| 519 | HANDLE started = CreateEventW(nullptr, FALSE, FALSE, nullptr); | ||
| 520 | int(__cdecl* get)() = nullptr; | ||
| 521 | void(__cdecl* set)(int) = nullptr; | ||
| 522 | int seen_first = -1, seen_after_write = -1, seen_second = -1; | ||
| 523 | void* block_first = nullptr; | ||
| 524 | DWORD early_id = 0; | ||
| 525 | uint32_t index = rt::kNoTlsIndex; | ||
| 526 | std::thread early([&] { | ||
| 527 | early_id = GetCurrentThreadId(); | ||
| 528 | SetEvent(started); | ||
| 529 | WaitForSingleObject(first.go, INFINITE); // the first Loader has mapped the fixture | ||
| 530 | block_first = module_tls_slots()[index]; | ||
| 531 | seen_first = get(); | ||
| 532 | set(55); | ||
| 533 | seen_after_write = get(); | ||
| 534 | SetEvent(first.done); | ||
| 535 | WaitForSingleObject(second.go, INFINITE); // that Loader is gone and a second one has mapped it again | ||
| 536 | seen_second = get(); | ||
| 537 | SetEvent(second.done); | ||
| 538 | WaitForSingleObject(last.go, INFINITE); // ends while the second module is initialised | ||
| 539 | }); | ||
| 540 | WaitForSingleObject(started, INFINITE); | ||
| 541 | |||
| 542 | MEMORY_BASIC_INFORMATION info{}; | ||
| 543 | { | ||
| 544 | rt::Loader loader(dll.parent_path()); | ||
| 545 | rt::Module& m = loader.load(dll); | ||
| 546 | index = m.tls_index; | ||
| 547 | get = find_export<int(__cdecl*)()>(m, "tiny_tls_get"); | ||
| 548 | set = find_export<void(__cdecl*)(int)>(m, "tiny_tls_set"); | ||
| 549 | set(42); | ||
| 550 | |||
| 551 | SetEvent(first.go); | ||
| 552 | WaitForSingleObject(first.done, INFINITE); | ||
| 553 | check(seen_first == 7, "a thread that existed before load() reads the template value 7"); | ||
| 554 | check(seen_after_write == 55 && get() == 42, "its write stays in its own block"); | ||
| 555 | check(block_first != nullptr && block_first != m.tls_block && block_first != m.tls_saved_block, | ||
| 556 | "it has a block of its own, not the loading thread's or the helper DLL's"); | ||
| 557 | void* seen_block = nullptr; | ||
| 558 | std::thread([&] { seen_block = module_tls_slots()[index]; }).join(); | ||
| 559 | check(seen_block != block_first, "a thread started after load() still gets its own block"); | ||
| 560 | |||
| 561 | // Every callback sees the template value, or the 4000 an earlier callback left on the same worker. | ||
| 562 | bool pool_ok = true, on_warm_worker = false; | ||
| 563 | for (int i = 0; i < 16; ++i) { | ||
| 564 | PoolProbe probe; | ||
| 565 | probe.get = get; | ||
| 566 | probe.set = set; | ||
| 567 | probe.done = warm.done; | ||
| 568 | if (!TrySubmitThreadpoolCallback(&pool_probe, &probe, nullptr) || | ||
| 569 | WaitForSingleObject(probe.done, 10000) != WAIT_OBJECT_0) { | ||
| 570 | pool_ok = false; | ||
| 571 | break; | ||
| 572 | } | ||
| 573 | pool_ok = pool_ok && (probe.value == 7 || probe.value == 4000); | ||
| 574 | on_warm_worker = on_warm_worker || probe.thread == warm.thread; | ||
| 575 | } | ||
| 576 | check(pool_ok, "thread-pool callbacks read the template value on workers that predate load()"); | ||
| 577 | std::puts(on_warm_worker ? " (one of them ran on the worker that existed before load())" | ||
| 578 | : " (the pool did not reuse the earlier worker this time)"); | ||
| 579 | check(VirtualQuery(block_first, &info, sizeof(info)) != 0 && info.State == MEM_COMMIT, | ||
| 580 | "the block is live while the Loader is"); | ||
| 581 | } | ||
| 582 | check(module_tls_slots()[index] != nullptr, "the loading thread has the helper DLL's block back"); | ||
| 583 | check(VirtualQuery(block_first, &info, sizeof(info)) == 0 || info.State == MEM_FREE, | ||
| 584 | "~Loader frees the block it gave the earlier thread, which is still running"); | ||
| 585 | |||
| 586 | { | ||
| 587 | // The same thread, a second mapping: a fresh copy of the template, not the 55 it wrote into the first. | ||
| 588 | rt::Loader loader(dll.parent_path()); | ||
| 589 | rt::Module& m = loader.load(dll); | ||
| 590 | index = m.tls_index; | ||
| 591 | get = find_export<int(__cdecl*)()>(m, "tiny_tls_get"); | ||
| 592 | set = find_export<void(__cdecl*)(int)>(m, "tiny_tls_set"); | ||
| 593 | auto watch = find_export<void(__cdecl*)(DWORD)>(m, "tiny_tls_watch_thread"); | ||
| 594 | auto thread_attach = find_export<int(__cdecl*)()>(m, "tiny_tls_thread_attach_count"); | ||
| 595 | auto thread_detach = find_export<int(__cdecl*)()>(m, "tiny_tls_thread_detach_count"); | ||
| 596 | watch(early_id); | ||
| 597 | loader.initialise(); | ||
| 598 | SetEvent(second.go); | ||
| 599 | WaitForSingleObject(second.done, INFINITE); | ||
| 600 | check(seen_second == 7, "the same thread reads the template value again after a second load()"); | ||
| 601 | SetEvent(last.go); | ||
| 602 | early.join(); | ||
| 603 | // As for a DLL Windows loads itself: no DLL_THREAD_ATTACH for a thread that was already running, and | ||
| 604 | // DLL_THREAD_DETACH when it ends. | ||
| 605 | check(thread_attach() == 0, "a thread that existed before load() gets no DLL_THREAD_ATTACH"); | ||
| 606 | check(thread_detach() == 1, "it gets DLL_THREAD_DETACH once when it ends"); | ||
| 607 | } | ||
| 608 | for (HANDLE h : {first.go, first.done, second.go, second.done, last.go, last.done, started, warm.done}) | ||
| 609 | CloseHandle(h); | ||
| 610 | } | ||
| 611 | |||
| 446 | // A worker thread that outlives Loader #1 keeps an orphaned g_thread_tls_slots[slot] record until it exits. | 612 | // A worker thread that outlives Loader #1 keeps an orphaned g_thread_tls_slots[slot] record until it exits. |
| 447 | // Even if Loader #2 reuses the same TLS slot (and even the same Module* address), the generation token must | 613 | // Even if Loader #2 reuses the same TLS slot (and even the same Module* address), the generation token must |
| 448 | // prevent Loader #2 from mistaking the orphaned entry for its own on install_tls_for_thread or DLL_THREAD_DETACH. | 614 | // prevent Loader #2 from mistaking the orphaned entry for its own on install_tls_for_thread or DLL_THREAD_DETACH. |
| @@ -489,7 +655,11 @@ void test_orphan_slot_generation_reuse(const fs::path& dll) { | |||
| 489 | CloseHandle(go); | 655 | CloseHandle(go); |
| 490 | CloseHandle(ready); | 656 | CloseHandle(ready); |
| 491 | 657 | ||
| 492 | check(td() == 0, "orphaned worker exit does not dispatch DLL_THREAD_DETACH to the new generation's module"); | 658 | // The worker was running when loader2 mapped the module, so load() gave it its own copy and, as Windows does for a |
| 659 | // DLL loaded while a thread runs, the module gets DLL_THREAD_DETACH once when that thread ends | ||
| 660 | // (test_existing_threads). A second one would mean the orphaned loader1 record was taken for loader2's. | ||
| 661 | check(td() == 1, "orphaned worker exit dispatches DLL_THREAD_DETACH to the new generation's module once, for " | ||
| 662 | "its own copy, not again for the orphaned record"); | ||
| 493 | } | 663 | } |
| 494 | 664 | ||
| 495 | // Spawns cmd.exe to obtain one guaranteed-dead PID and one guaranteed-live one for the purge-ownership checks. | 665 | // Spawns cmd.exe to obtain one guaranteed-dead PID and one guaranteed-live one for the purge-ownership checks. |
| @@ -614,6 +784,8 @@ int main(int argc, char** argv) { | |||
| 614 | 784 | ||
| 615 | TempDir temp; | 785 | TempDir temp; |
| 616 | test_purge_ownership_scoping(tls_dll, temp.path); // first: the sweep fires once per process | 786 | test_purge_ownership_scoping(tls_dll, temp.path); // first: the sweep fires once per process |
| 787 | test_existing_threads(tls_dll); | ||
| 788 | test_terminated_thread(tls_dll); | ||
| 617 | test_tls(tls_dll); | 789 | test_tls(tls_dll); |
| 618 | test_thread_events(tls_dll); | 790 | test_thread_events(tls_dll); |
| 619 | test_thread_outlives_loader(tls_dll); | 791 | test_thread_outlives_loader(tls_dll); |