upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src/pe_loader.cpp
diff options
context:
space:
mode:
authorkotorvr <332716892+kotorvr@users.noreply.github.com>2026-11-22 21:12:56 +0000
committerkotorvr <332716892+kotorvr@users.noreply.github.com>2026-11-22 21:12:56 +0000
commit292c917822f0b475697b47e0e5ac576caf3ee2a9 (patch)
treebe6d62177e827f0a110d13ef094b243a0fe3ea53 /runtime/src/pe_loader.cpp
parentb418319ae9ff68177adcd92b1e55e12972858188 (diff)
loader: harden the TLS swap on running threads
- After writing a thread's slot, read its array pointer again and repeat on the new array if Windows replaced it; if the block is not in the current array after four attempts, take it back and log. - Read and write another thread's TEB and TLS array inside __try, right after the thread was seen running, so a TEB freed by TerminateThread is a skipped thread. - Bound the list of ended thread ids. loader_tls_test: a thread terminated while it holds a block, and a load() with a dead thread still open. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src/pe_loader.cpp')
-rw-r--r--runtime/src/pe_loader.cpp94
1 files changed, 81 insertions, 13 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index f29c64a7a..8fca00668 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -401,10 +401,20 @@ void run_callbacks(Module& m, uint32_t reason, bool trace = false) {
401// - A thread whose detach event has run is skipped (`ended`), and so is one with no TLS array or no helper block: 401// - A thread whose detach event has run is skipped (`ended`), and so is one with no TLS array or no helper block:
402// Windows is about to free, or never built, what the block would go into. 402// Windows is about to free, or never built, what the block would go into.
403// - The block comes out again in that thread's own detach event, before Windows frees the array, or in ~Loader. 403// - The block comes out again in that thread's own detach event, before Windows frees the array, or in ~Loader.
404// What is left: a thread that ran its detach event before the helper DLL was ever loaded and has not left the 404// What is left:
405// process yet is not in `ended`; if Windows leaves a stale array pointer in its TEB for those last instructions, 405// - A thread that ran its detach event before the helper DLL was ever loaded and has not left the process yet is
406// the write goes to freed heap memory. And if another thread makes Windows replace a thread's TLS array (by loading 406// not in `ended`; if Windows leaves a stale array pointer in its TEB for those last instructions, the write goes
407// a DLL with static TLS) during the swap, that thread can keep the helper's block. 407// to freed heap memory.
408// - Windows replaces a thread's TLS array (a new one, copied from the old) when some thread loads a DLL with static
409// TLS. If that happens during the swap, the write can land in the old array; the thread then still has the
410// helper's one-byte block, and the first mapped __declspec(thread) access on it writes past that block: heap
411// corruption, with nothing to show for it. The swap therefore reads the array pointer again after writing and
412// repeats on the new array (kSwapAttempts times); if the block is not in the thread's current array at the end,
413// it is taken back and the miss is logged. A replacement after that last look is not seen.
414// - TerminateThread frees a thread's TEB with no detach event. Every read and write of another thread's TEB or
415// TLS array here is made right after the thread was seen running and inside __try, so a TEB that has just gone
416// is a skipped thread, not a fault in load() or ~Loader. If the memory was already given to something else, the
417// write is not caught.
408using QueryThreadFn = LONG(NTAPI*)(HANDLE, int, void*, ULONG, ULONG*); 418using QueryThreadFn = LONG(NTAPI*)(HANDLE, int, void*, ULONG, ULONG*);
409struct ThreadBasicInfo { // THREAD_BASIC_INFORMATION (winternl.h keeps it opaque), x64 419struct ThreadBasicInfo { // THREAD_BASIC_INFORMATION (winternl.h keeps it opaque), x64
410 LONG exit_status; 420 LONG exit_status;
@@ -432,20 +442,54 @@ void*** running_thread_tls_vector(HANDLE thread) {
432 return reinterpret_cast<void***>(static_cast<uint8_t*>(info.teb) + 0x58); 442 return reinterpret_cast<void***>(static_cast<uint8_t*>(info.teb) + 0x58);
433} 443}
434 444
445// Another thread's TLS array and one entry of it, read through its TEB. False when the memory is not there any more
446// (the thread was terminated). No C++ objects in these three: they are __try frames.
447bool read_thread_slot(void*** vector, uint32_t index, void**& slots, void*& value) noexcept {
448 __try {
449 slots = *vector;
450 value = slots ? slots[index] : nullptr;
451 return true;
452 } __except (EXCEPTION_EXECUTE_HANDLER) {
453 slots = nullptr;
454 value = nullptr;
455 return false;
456 }
457}
458
459bool write_thread_slot(void** slots, uint32_t index, void* value) noexcept {
460 __try {
461 slots[index] = value;
462 return true;
463 } __except (EXCEPTION_EXECUTE_HANDLER) {
464 return false;
465 }
466}
467
468// Puts `saved` back where `block` is, if it is still there.
469void restore_thread_slot(void*** vector, uint32_t index, void* block, void* saved) noexcept {
470 __try {
471 void** slots = *vector;
472 if (slots && slots[index] == block) slots[index] = saved;
473 } __except (EXCEPTION_EXECUTE_HANDLER) {
474 }
475}
476
435// Takes a block out of its slot and frees it. The existing-threads lock is held; b.vector is null when the thread 477// Takes a block out of its slot and frees it. The existing-threads lock is held; b.vector is null when the thread
436// is gone. 478// is gone.
437void remove_existing_block(const ExistingThreadBlock& b) { 479void remove_existing_block(const ExistingThreadBlock& b) {
438 if (b.vector) { 480 if (b.vector && b.index < kMaxModuleTlsSlots) restore_thread_slot(b.vector, b.index, b.block, b.saved);
439 void** slots = *b.vector;
440 if (slots && b.index < kMaxModuleTlsSlots && slots[b.index] == b.block) slots[b.index] = b.saved;
441 }
442 VirtualFree(b.block, 0, MEM_RELEASE); 481 VirtualFree(b.block, 0, MEM_RELEASE);
443} 482}
444 483
484constexpr int kSwapAttempts = 4;
485constexpr size_t kMaxEndedThreads = 1024;
486
445// load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done. 487// load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done.
446void install_on_existing_threads(Module& m) { 488void install_on_existing_threads(Module& m) {
447 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill; 489 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill;
448 if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kMaxMappedTlsModules) return; 490 if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kMaxMappedTlsModules) return;
491 // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which
492 // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours.
449 if (!query_thread_fn()) return; 493 if (!query_thread_fn()) return;
450 494
451 // Outside the TLS lock: none of this may wait for a thread that is inside its attach event. 495 // Outside the TLS lock: none of this may wait for a thread that is inside its attach event.
@@ -473,10 +517,10 @@ void install_on_existing_threads(Module& m) {
473 for (const Candidate& c : candidates) { 517 for (const Candidate& c : candidates) {
474 if (std::find(state.ended.begin(), state.ended.end(), c.id) != state.ended.end()) continue; 518 if (std::find(state.ended.begin(), state.ended.end(), c.id) != state.ended.end()) continue;
475 void*** vector = running_thread_tls_vector(c.handle); 519 void*** vector = running_thread_tls_vector(c.handle);
476 void** slots = vector ? *vector : nullptr; 520 void** slots = nullptr;
477 if (!slots || !slots[m.tls_index]) continue; 521 void* saved = nullptr;
522 if (!vector || !read_thread_slot(vector, m.tls_index, slots, saved) || !slots || !saved) continue;
478 // A copy an earlier module left in this slot of this thread goes first; what it replaced is kept. 523 // A copy an earlier module left in this slot of this thread goes first; what it replaced is kept.
479 void* saved = slots[m.tls_index];
480 bool present = false; 524 bool present = false;
481 for (auto it = state.blocks.begin(); it != state.blocks.end();) { 525 for (auto it = state.blocks.begin(); it != state.blocks.end();) {
482 if (it->thread != c.id || it->slot != m.tls_slot) { 526 if (it->thread != c.id || it->slot != m.tls_slot) {
@@ -485,7 +529,7 @@ void install_on_existing_threads(Module& m) {
485 present = true; 529 present = true;
486 break; 530 break;
487 } else { 531 } else {
488 if (slots[it->index] == it->block) saved = it->saved; 532 if (saved == it->block) saved = it->saved;
489 it->vector = vector; 533 it->vector = vector;
490 remove_existing_block(*it); 534 remove_existing_block(*it);
491 it = state.blocks.erase(it); 535 it = state.blocks.erase(it);
@@ -495,8 +539,29 @@ void install_on_existing_threads(Module& m) {
495 void* block = VirtualAlloc(nullptr, static_cast<SIZE_T>(total), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); 539 void* block = VirtualAlloc(nullptr, static_cast<SIZE_T>(total), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
496 if (!block) continue; 540 if (!block) continue;
497 if (m.tls_raw_size) std::memcpy(block, m.tls_template, m.tls_raw_size); 541 if (m.tls_raw_size) std::memcpy(block, m.tls_template, m.tls_raw_size);
542
543 // Write, then look at the thread's array pointer again: if Windows has replaced the array meanwhile, the
544 // write went into the old one, and it is made again in the new one.
545 bool installed = false;
546 for (int attempt = 0; attempt < kSwapAttempts && !installed; ++attempt) {
547 if (!running_thread_tls_vector(c.handle) || !write_thread_slot(slots, m.tls_index, block)) break;
548 void** now = nullptr;
549 void* value = nullptr;
550 if (!read_thread_slot(vector, m.tls_index, now, value) || !now) break;
551 installed = now == slots && value == block;
552 slots = now;
553 }
554 if (!installed) {
555 restore_thread_slot(vector, m.tls_index, block, saved);
556 VirtualFree(block, 0, MEM_RELEASE);
557 static std::atomic<bool> logged{false};
558 if (!logged.exchange(true))
559 std::fprintf(stderr, "[rt] loader: %s: a running thread did not take its TLS block (it ended, or "
560 "its TLS array kept changing); mapped thread-local data is not valid on it\n",
561 m.name.c_str());
562 continue;
563 }
498 state.blocks.push_back({c.id, m.tls_slot, &m, m.tls_index, vector, saved, block}); 564 state.blocks.push_back({c.id, m.tls_slot, &m, m.tls_index, vector, saved, block});
499 slots[m.tls_index] = block;
500 } 565 }
501 } 566 }
502 for (const Candidate& c : candidates) CloseHandle(c.handle); 567 for (const Candidate& c : candidates) CloseHandle(c.handle);
@@ -565,6 +630,9 @@ void release_existing_blocks_of_this_thread() {
565 remove_existing_block(*it); 630 remove_existing_block(*it);
566 it = state.blocks.erase(it); 631 it = state.blocks.erase(it);
567 } 632 }
633 // Bounded: an id matters only until its thread has left the process, moments after this event, so the oldest
634 // can go. (An id also leaves the list when a new thread gets it.)
635 if (state.ended.size() >= kMaxEndedThreads) state.ended.erase(state.ended.begin(), state.ended.begin() + kMaxEndedThreads / 2);
568 state.ended.push_back(self); 636 state.ended.push_back(self);
569} 637}
570 638