From 81d82bfcc4082a28279403888251adde907541f3 Mon Sep 17 00:00:00 2001 From: jaybeebabageyus Date: Sun, 22 Nov 2026 16:49:22 +0100 Subject: runtime: support multiple simultaneous manually mapped static-TLS modules --- runtime/src/pe_loader.cpp | 290 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 216 insertions(+), 74 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 387051756..113ca23ea 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -73,8 +74,11 @@ IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) { // loader-assigned per-module TLS index and is a different index space from TlsAlloc/TlsGetValue (TlsSlots). Only the OS // loader can allocate a module index, so the runtime ships a minimal DLL whose only content is a TLS anchor // (src/tls_host.cpp). Loading it makes the OS reserve an index and give every thread a block for it; the native loader -// reuses that index for the mapped image. One helper means one mapped TLS module at a time. +// reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader +// clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent +// module TLS index for each simultaneous module (up to kMaxMappedTlsModules). constexpr DWORD kMaxModuleTlsSlots = 64; +constexpr size_t kMaxMappedTlsModules = 16; void** module_tls_slots() { return reinterpret_cast(__readgsqword(0x58)); } void __cdecl on_host_thread_event(DWORD reason); @@ -84,22 +88,66 @@ struct TlsHostModule { DWORD index = TLS_OUT_OF_INDEXES; }; -TlsHostModule load_tls_host() { - TlsHostModule host; - // Dynamic buffer loop for paths that exceed MAX_PATH +std::filesystem::path tls_host_base_path() { std::wstring exe_path; DWORD size = MAX_PATH; while (true) { exe_path.resize(size); DWORD len = GetModuleFileNameW(nullptr, exe_path.data(), size); - if (len == 0) return host; + if (len == 0) return {}; if (len < size - 1) { exe_path.resize(len); break; } size *= 2; } - const std::filesystem::path path = std::filesystem::path(exe_path).parent_path() / L"gta6rt_tls_host.dll"; + return std::filesystem::path(exe_path).parent_path() / L"gta6rt_tls_host.dll"; +} + +std::filesystem::path tls_host_clone_dir() { + wchar_t buf[MAX_PATH]; + DWORD n = GetTempPathW(MAX_PATH, buf); + if (n > 0 && n < MAX_PATH) return std::filesystem::path(buf); + return std::filesystem::temp_directory_path(); +} + +struct TlsCloneRecord { + HMODULE module = nullptr; + std::filesystem::path path; +}; + +std::mutex g_tls_alloc_mutex; +std::array g_tls_hosts{}; +std::array, kMaxMappedTlsModules> g_tls_slot_owners{}; +std::array, kMaxMappedTlsModules> g_tls_slot_generations{}; +std::atomic g_next_tls_generation{1}; +std::vector g_tls_clones; + +void cleanup_tls_clones_at_exit() { + for (const auto& rec : g_tls_clones) { + if (rec.module) FreeLibrary(rec.module); + if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); + } + g_tls_clones.clear(); +} + +void sweep_stale_tls_clones(const std::filesystem::path& dir) { + WIN32_FIND_DATAW fd{}; + const std::filesystem::path pattern = dir / L"leonida_tls_host_*.dll"; + HANDLE h = FindFirstFileW(pattern.c_str(), &fd); + if (h == INVALID_HANDLE_VALUE) return; + do { + if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) { + // Fails harmlessly for clones still mapped in live processes; deletes orphaned ones from exited processes. + DeleteFileW((dir / fd.cFileName).c_str()); + } + } while (FindNextFileW(h, &fd)); + FindClose(h); +} + +TlsHostModule load_tls_host_image(const std::filesystem::path& path, bool hook_thread_events) { + TlsHostModule host; + if (path.empty()) return host; // The helper is linked with the static CRT (/MT), so it needs only system DLLs. Restricting the dependency search // to System32 keeps a game-supplied vcruntime next to the executable from being picked up. host.module = LoadLibraryExW(path.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); @@ -121,31 +169,82 @@ TlsHostModule load_tls_host() { return host; } host.index = *reinterpret_cast(tls->AddressOfIndex); - // From here on the helper's DllMain reports every thread the process starts or ends (on_host_thread_event). - using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); - if (auto set = reinterpret_cast(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"))) - set(&on_host_thread_event); + if (hook_thread_events) { + // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots. + using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); + if (auto set = reinterpret_cast(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"))) + set(&on_host_thread_event); + } return host; } -TlsHostModule& tls_host() { - // The helper stays loaded for the process lifetime: unloading it would release the reserved TLS index. Its own - // per-thread blocks are restored by uninstall_tls_for_thread, so the OS loader can free them normally. - static TlsHostModule host = load_tls_host(); - return host; +// Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock). +TlsHostModule ensure_tls_host(size_t slot) { + if (slot >= kMaxMappedTlsModules) return {}; + if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot]; + + const std::filesystem::path primary = tls_host_base_path(); + if (primary.empty()) return {}; + + if (slot == 0) { + g_tls_hosts[0] = load_tls_host_image(primary, true); + return g_tls_hosts[0]; + } + + // Ensure slot 0 is loaded first so thread attach/detach events are hooked. + if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) { + g_tls_hosts[0] = load_tls_host_image(primary, true); + if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) return {}; + } + + // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem). + const std::filesystem::path dir = tls_host_clone_dir(); + static bool swept = false; + if (!swept) { + swept = true; + sweep_stale_tls_clones(dir); + std::atexit(&cleanup_tls_clones_at_exit); + } + const std::wstring name = + L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll"; + const std::filesystem::path clone_path = dir / name; + if (!CopyFileW(primary.c_str(), clone_path.c_str(), FALSE)) return {}; + + // Hold a read-only-shared handle across LoadLibraryExW so another process cannot overwrite the clone in between. + HANDLE guard = CreateFileW(clone_path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + TlsHostModule loaded = load_tls_host_image(clone_path, false); + if (guard != INVALID_HANDLE_VALUE) CloseHandle(guard); + + if (loaded.index == TLS_OUT_OF_INDEXES) { + DeleteFileW(clone_path.c_str()); + return {}; + } + for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { + if (i != slot && g_tls_hosts[i].index == loaded.index) { + FreeLibrary(loaded.module); + DeleteFileW(clone_path.c_str()); + return {}; + } + } + g_tls_clones.push_back({loaded.module, clone_path}); + g_tls_hosts[slot] = loaded; + return g_tls_hosts[slot]; } -std::atomic g_tls_slot_owner{nullptr}; +struct ThreadTlsSlot { + Module* module = nullptr; + uint64_t generation = 0; + void* saved = nullptr; + void* block = nullptr; + uint32_t index = kNoTlsIndex; +}; -// Per-thread installation state. Only one mapped TLS module can own the reserved slot, so one entry per thread is -// enough; the saved pointer is the helper DLL's own block that the OS loader will free at thread exit. -thread_local Module* g_thread_tls_module = nullptr; -thread_local void* g_thread_tls_saved = nullptr; -thread_local void* g_thread_tls_block = nullptr; -thread_local uint32_t g_thread_tls_index = kNoTlsIndex; +// Per-thread installation state for each reserved TLS slot. +thread_local std::array g_thread_tls_slots{}; -// Orders the TLS owner's publication, its `initialised` flag and its retirement against the thread events. Shared in -// on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows +// Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared +// in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows // loader lock, which the events run under). SRWLOCK g_tls_lock = SRWLOCK_INIT; struct SharedTlsLock { @@ -163,30 +262,41 @@ struct ExclusiveTlsLock { // Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this // thread's record, so it also works after the module that installed the copy is gone. -void release_thread_block() { - if (!g_thread_tls_block) return; - void** slots = module_tls_slots(); - if (slots && g_thread_tls_index < kMaxModuleTlsSlots && slots[g_thread_tls_index] == g_thread_tls_block) - slots[g_thread_tls_index] = g_thread_tls_saved; - VirtualFree(g_thread_tls_block, 0, MEM_RELEASE); - g_thread_tls_module = nullptr; - g_thread_tls_saved = nullptr; - g_thread_tls_block = nullptr; - g_thread_tls_index = kNoTlsIndex; +void release_thread_slot(size_t slot) { + if (slot >= kMaxMappedTlsModules) return; + ThreadTlsSlot& entry = g_thread_tls_slots[slot]; + if (!entry.module && !entry.block) return; + if (entry.block) { + void** slots = module_tls_slots(); + if (slots && entry.index < kMaxModuleTlsSlots && slots[entry.index] == entry.block) + slots[entry.index] = entry.saved; + VirtualFree(entry.block, 0, MEM_RELEASE); + } + entry = ThreadTlsSlot{}; } void install_thread_block(Module& m) { - if (m.tls_index == kNoTlsIndex) return; - if (g_thread_tls_module == &m) return; - if (g_thread_tls_module) { - // A copy left by a module whose Loader is gone is released; a live module's is a conflict. - if (g_thread_tls_module == g_tls_slot_owner.load()) - throw std::runtime_error("another manually mapped module's TLS is already installed in this thread"); - release_thread_block(); + if (m.tls_slot >= kMaxMappedTlsModules) return; + const size_t slot = m.tls_slot; + ThreadTlsSlot& entry = g_thread_tls_slots[slot]; + if (entry.module == &m && entry.generation == m.tls_generation) return; + if (entry.module) { + // A copy left by a module whose Loader is gone (or from an earlier generation) is released; a live owner's is a conflict. + if (entry.module == g_tls_slot_owners[slot].load() && + entry.generation == g_tls_slot_generations[slot].load()) { + throw std::runtime_error("another manually mapped module's TLS is already installed in this thread slot"); + } + release_thread_slot(slot); } const uint64_t total = static_cast(m.tls_raw_size) + m.tls_zero_fill; - if (!total) return; + if (!total) { + // Callback-only TLS module (no data block): still record attachment in this slot so DLL_THREAD_DETACH runs. + entry.module = &m; + entry.generation = m.tls_generation; + return; + } + if (m.tls_index == kNoTlsIndex) return; void** slots = module_tls_slots(); if (!slots || m.tls_index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": cannot install TLS in this thread"); @@ -199,19 +309,23 @@ void install_thread_block(Module& m) { void* saved = slots[m.tls_index]; slots[m.tls_index] = block; - g_thread_tls_module = &m; - g_thread_tls_saved = saved; - g_thread_tls_block = block; - g_thread_tls_index = m.tls_index; + entry.module = &m; + entry.generation = m.tls_generation; + entry.saved = saved; + entry.block = block; + entry.index = m.tls_index; } void uninstall_thread_block(Module& m) { - if (g_thread_tls_module != &m) return; - if (m.tls_block == g_thread_tls_block) { + if (m.tls_slot >= kMaxMappedTlsModules) return; + const size_t slot = m.tls_slot; + ThreadTlsSlot& entry = g_thread_tls_slots[slot]; + if (entry.module != &m || entry.generation != m.tls_generation) return; + if (m.tls_block == entry.block) { m.tls_block = nullptr; m.tls_saved_block = nullptr; } - release_thread_block(); + release_thread_slot(slot); } void run_callbacks(Module& m, uint32_t reason) { @@ -231,24 +345,29 @@ void run_callbacks(Module& m, uint32_t reason) { } // Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under -// the Windows loader lock, on that thread. A new thread gets its own copy of the TLS owner's template; an ending one -// gives the helper's block back before the Windows loader frees it. TLS callbacks get the thread events only after -// the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. Threads that existed before the -// module was loaded get nothing: install_tls_for_thread is still the way to cover those. +// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an +// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events +// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. void __cdecl on_host_thread_event(DWORD reason) { SharedTlsLock lock; - Module* m = g_tls_slot_owner.load(); try { if (reason == DLL_THREAD_ATTACH) { - if (!m) return; - install_thread_block(*m); - if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); + for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { + Module* m = g_tls_slot_owners[slot].load(); + if (!m) continue; + install_thread_block(*m); + if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); + } } else if (reason == DLL_THREAD_DETACH) { - if (m && g_thread_tls_module == m) { - if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH); - uninstall_thread_block(*m); - } else { - release_thread_block(); // installed by a module whose Loader is gone (or nothing to do) + for (size_t i = kMaxMappedTlsModules; i-- > 0;) { + Module* m = g_tls_slot_owners[i].load(); + if (m && g_thread_tls_slots[i].module == m && + g_thread_tls_slots[i].generation == m->tls_generation) { + if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH); + uninstall_thread_block(*m); + } else { + release_thread_slot(i); // installed by a module whose Loader is gone (or nothing to do) + } } } } catch (const std::exception& e) { @@ -375,13 +494,14 @@ Loader::~Loader() { shims::remove_module_lookup(this); for (auto* m : order_) { // TLS state must go away before the image and its TLS block are unmapped. - if (m->tls_index != kNoTlsIndex) { + if (m->tls_index != kNoTlsIndex && m->tls_slot < kMaxMappedTlsModules) { // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a // thread that still holds a copy frees it when it ends (on_host_thread_event). { ExclusiveTlsLock lock; Module* owner = m; - g_tls_slot_owner.compare_exchange_strong(owner, nullptr); + if (g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr)) + g_tls_slot_generations[m->tls_slot].store(0); } uninstall_tls_for_thread(*m); } @@ -604,19 +724,38 @@ void Loader::initialize_tls(Module& m) { require_range(m.name, index_rva, sizeof(uint32_t), m.size, "the TLS index"); } - DWORD index = tls_host().index; - if (index == TLS_OUT_OF_INDEXES) - throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index"); - if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range"); if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); + size_t slot = kMaxMappedTlsModules; + DWORD index = TLS_OUT_OF_INDEXES; { + std::lock_guard alloc_lock(g_tls_alloc_mutex); + for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { + if (g_tls_slot_owners[i].load() == nullptr) { + slot = i; + break; + } + } + if (slot >= kMaxMappedTlsModules) + throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) + + " manually mapped static TLS slots are in use"); + + // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with + // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock). + index = ensure_tls_host(slot).index; + if (index == TLS_OUT_OF_INDEXES) + throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index"); + if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range"); + // The fields are complete before a thread event can see the owner. ExclusiveTlsLock lock; Module* expected = nullptr; - if (!g_tls_slot_owner.compare_exchange_strong(expected, &m)) - throw std::runtime_error(m.name + ": only one manually mapped module may use static TLS at a time"); + if (!g_tls_slot_owners[slot].compare_exchange_strong(expected, &m)) + throw std::runtime_error(m.name + ": static TLS slot was claimed concurrently"); + m.tls_slot = static_cast(slot); + m.tls_generation = g_next_tls_generation.fetch_add(1, std::memory_order_relaxed); + g_tls_slot_generations[slot].store(m.tls_generation); m.tls_index = index; m.tls_template = raw ? m.base + raw_rva : nullptr; m.tls_raw_size = static_cast(raw); @@ -631,13 +770,16 @@ void Loader::initialize_tls(Module& m) { } catch (...) { ExclusiveTlsLock lock; m.tls_index = kNoTlsIndex; - g_tls_slot_owner = nullptr; + m.tls_slot = kNoTlsIndex; + m.tls_generation = 0; + g_tls_slot_generations[slot].store(0); + g_tls_slot_owners[slot].store(nullptr); throw; } // The loading thread's copy is the one the Module records (and ~Loader frees on that thread). - if (g_thread_tls_module == &m) { - m.tls_block = g_thread_tls_block; - m.tls_saved_block = g_thread_tls_saved; + if (g_thread_tls_slots[slot].module == &m && g_thread_tls_slots[slot].generation == m.tls_generation) { + m.tls_block = g_thread_tls_slots[slot].block; + m.tls_saved_block = g_thread_tls_slots[slot].saved; } } -- cgit v1.2.3 From 9ccb1052e4d317b18e82ff4b239bef25bc6b68c7 Mon Sep 17 00:00:00 2001 From: admin Date: Sun, 22 Nov 2026 18:25:41 +0000 Subject: Validate named import thunk RVAs before narrowing Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- runtime/src/pe_loader.cpp | 2 +- runtime/test/loader_test.cpp | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index a59f9d0b1..c10c6ea5a 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1051,8 +1051,8 @@ void Loader::bind_imports(Module& m) { uint16_t ord = by_ord ? (uint16_t)IMAGE_ORDINAL64(lookup->u1.Ordinal) : 0; std::string name; if (!by_ord) { + require_range(m.name, lookup->u1.AddressOfData, sizeof(uint16_t), m.size, "an import name"); uint32_t hint = static_cast(lookup->u1.AddressOfData); - require_range(m.name, hint, sizeof(uint16_t), m.size, "an import name"); name = read_string(m.name, m.base, m.size, hint + sizeof(uint16_t), "an import name"); } at(m.base, static_cast(iat_rva))->u1.Function = diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 194174b00..d5248bd06 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -397,6 +397,42 @@ void test_imports() { } } +void test_import_name_rvas() { + for (bool delay : {false, true}) { + auto img = make_import_image("testshim.dll", "F"); + if (delay) { + std::fill(img.begin() + 0x200, img.begin() + 0x240, uint8_t{0}); + auto* d = reinterpret_cast(img.data() + 0x200); + d->Attributes.AllAttributes = 1; + d->DllNameRVA = 0x1060; + d->ImportNameTableRVA = 0x1100; + d->ImportAddressTableRVA = 0x1180; + auto* nt = nt_of(img); + nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] = {}; + auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT]; + dir.VirtualAddress = 0x1000; + dir.Size = 2 * sizeof(IMAGE_DELAYLOAD_DESCRIPTOR); + } + const char* valid = delay ? "a valid delay-import name RVA loads" : "a valid import name RVA loads"; + std::string error; + if (load(write_image(img), error) != 0) + failed(valid, error); + else + pass(valid); + + *reinterpret_cast(img.data() + 0x300) = (1ull << 32) | 0x1120; + const char* invalid = delay ? "a delay-import name RVA with high bits is rejected" + : "an import name RVA with high bits is rejected"; + error.clear(); + if (load(write_image(img), error) == 0) + failed(invalid, "the image loaded"); + else if (error.find("an import name runs past the image") == std::string::npos) + failed(invalid, error); + else + pass(invalid); + } +} + void test_delay_imports() { { auto img = make_image(); @@ -1099,6 +1135,7 @@ int main() { test_relocations(); test_exports(); test_imports(); + test_import_name_rvas(); test_delay_imports(); test_initialise(); test_initialise_rejects(); -- cgit v1.2.3 From 5e3ec685a3a60e3f7597b96824b7ee52ba3396af Mon Sep 17 00:00:00 2001 From: airp1ane <279825357+airp1ane@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:53:36 -0500 Subject: pe_loader: a failed load, dependencies included, is not left findable by name map_image records a module in by_name_ before mapping, binding and section protection can throw. The run-time load path erased only the DLL it was asked for, so a bundled dependency that failed while being bound stayed registered with unbound imports, and a later LoadLibrary or GetModuleHandle of it returned that half-loaded image. load() now erases its own key on any failure; ~Loader still frees the mapping through order_. loader_test: a parent imports fail_dep.dll, whose import table names a DLL outside the image. After the failed load neither name is found and a second load of either fails again (on the old code the dependency was still found). Co-Authored-By: Claude Opus 5.5 --- runtime/src/pe_loader.cpp | 21 +++++++++++++++------ runtime/test/loader_test.cpp | 21 +++++++++++++++++++++ 2 files changed, 36 insertions(+), 6 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index a59f9d0b1..6f19f5b2f 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -540,10 +540,19 @@ Module& Loader::load(const std::filesystem::path& image) { std::lock_guard lock(mutex_); std::string key = lower(image.filename().string()); if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; - Module& m = map_image(image); - bind_imports(m); // loads every bundled module m imports first, so they land in init_order_ before m - protect_sections(m); - register_unwind(m); + Module* mapped = nullptr; + try { + mapped = &map_image(image); + bind_imports(*mapped); // loads every bundled module m imports first, so they land in init_order_ before m + protect_sections(*mapped); + register_unwind(*mapped); + } catch (...) { + // A failed load, nested ones (a dependency of a run-time load) included, must not stay findable by name: + // a later lookup would get a half-mapped image with unbound imports. ~Loader still frees it through order_. + by_name_.erase(key); + throw; + } + Module& m = *mapped; init_order_.push_back(&m); if (startup_trace::enabled()) startup_trace::event("map", "\"module\":" + startup_trace::quote(m.name) + @@ -598,8 +607,8 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str()); return static_cast(m.base); } catch (const std::exception& e) { - // Do not leave a failed run-time load indexed by name so later GetModuleHandle/LoadLibrary calls do not - // observe a half-initialised module. ~Loader still frees any VirtualAlloc'd mapping in order_. + // load() drops a module that failed to map or bind (dependencies included); this also drops one whose + // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via order_. by_name_.erase(dll_lower); std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what()); SetLastError(ERROR_DLL_INIT_FAILED); diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 194174b00..c86ade637 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -783,6 +783,26 @@ void test_process_detach_dependencies() { g_live_modules.clear(); } +// A dependency whose import table is corrupt fails while the parent binds it. Neither must stay findable by name: +// a later load or GetModuleHandle would otherwise get a mapped image whose imports were never bound. +void test_failed_dependency_not_registered() { + const char* what = "a failed load leaves neither the module nor its failed dependency loaded"; + auto dep = make_import_image("kernel32.dll", "GetCurrentProcessId"); + reinterpret_cast(dep.data() + 0x200)->Name = 0x5000; // past SizeOfImage + const auto dep_path = write_image_as(dep, "fail_dep.dll"); + const auto parent_path = write_image_as(make_import_image("fail_dep.dll", "x"), "fail_parent.dll"); + rt::Loader loader(g_dir); + auto throws = [&](const std::filesystem::path& p) { + try { loader.load(p); return false; } catch (const std::exception&) { return true; } + }; + if (!throws(parent_path)) return failed(what, "the parent loaded over a corrupt dependency"); + if (loader.find_loaded_module("fail_dep.dll") || loader.find_loaded_module("fail_parent.dll")) + return failed(what, "a failed module is still found by name"); + if (!throws(dep_path)) return failed(what, "a second load of the dependency returned the half-loaded module"); + if (!throws(parent_path)) return failed(what, "a second load of the parent returned the half-loaded module"); + pass(what); +} + void test_forwarded_exports() { { const char* what = "a forwarded export binds to its target instead of into the string"; @@ -1106,6 +1126,7 @@ int main() { test_process_detach_invalid_tls(); test_process_detach_without_entry(); test_process_detach_dependencies(); + test_failed_dependency_not_registered(); test_delay_descriptor_fields(); test_forwarded_exports(); test_export_bounds(); -- cgit v1.2.3 From c9e08f9f1a509d4cabcdf36fa5e225d3eaefead1 Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 20:48:35 +0100 Subject: fix(loader): leave empty named exports unresolved --- runtime/src/pe_loader.cpp | 1 + runtime/test/loader_test.cpp | 51 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index a59f9d0b1..2400536d0 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -929,6 +929,7 @@ void Loader::parse_exports(Module& m) { // into the string, so forwarders are kept apart and followed when an import asks for one. const uint64_t dir_begin = dir.VirtualAddress, dir_end = dir_begin + dir.Size; auto add_export = [&](const std::string& key, uint32_t rva) { + if (!rva) return; // An unused address-table slot is absent even when a name refers to it. if (rva >= dir_begin && rva < dir_end) m.forwarders[key] = read_string(m.name, m.base, m.size, rva, "a forwarded export"); else if (rva >= m.size) // base + rva would point past the mapping, and a caller would jump there diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 194174b00..a0d0eaa36 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -359,6 +359,56 @@ void test_exports() { } } +void test_empty_named_export() { + const char* what = "an empty named export stays unresolved without hiding valid exports"; + auto img = make_forwarder_image("KERNEL32.GetCurrentProcessId", 0x180000000); + auto* ed = reinterpret_cast(img.data() + 0x200); + ed->NumberOfFunctions = 3; + ed->NumberOfNames = 3; + nt_of(img)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size = 0x1A0; + auto* funcs = reinterpret_cast(img.data() + 0x300); + funcs[1] = 0; + funcs[2] = 0x11C0; // a code export outside the export directory + auto* names = reinterpret_cast(img.data() + 0x320); + names[0] = 0x1188; + names[1] = 0x1180; + names[2] = 0x1190; + auto* ords = reinterpret_cast(img.data() + 0x340); + ords[0] = 1; + ords[1] = 0; + ords[2] = 2; + std::memcpy(img.data() + 0x388, "empty\0", 6); + std::memcpy(img.data() + 0x390, "valid\0", 6); + auto provider = write_image_as(img, "empty_exports.dll"); + try { + rt::Loader loader(g_dir); + rt::Module& m = loader.load(provider); + for (const char* sym : {"empty", "#2"}) { + bool owns = false; + if (m.exports.count(sym) || m.forwarders.count(sym) || + loader.resolve_module_export(m.base, sym, owns) || !owns) + return failed(what, std::string(sym) + " did not remain absent from the mapped module"); + } + for (const char* sym : {"valid", "#3", "fwd", "#1"}) { + bool owns = false; + void* expected = (std::strcmp(sym, "valid") == 0 || std::strcmp(sym, "#3") == 0) + ? m.base + 0x11C0 : host_symbol("kernel32.dll", "GetCurrentProcessId"); + if (!expected || loader.resolve_module_export(m.base, sym, owns) != expected || !owns) + return failed(what, std::string(sym) + " no longer resolves to its valid target"); + } + auto importer = write_image_as(make_import_image("empty_exports.dll", "empty"), "empty_import.exe"); + rt::Module& importing = loader.load(importer); + if (importing.imports.size() != 1 || importing.imports[0].binding != rt::Binding::Unimplemented) + return failed(what, "an import of the empty slot did not bind as unimplemented"); + void* bound = *reinterpret_cast(importing.base + 0x1180); + if (!bound || bound == m.base) + return failed(what, "the empty import was not given a failure thunk"); + pass(what); + } catch (const std::exception& e) { + failed(what, e.what()); + } +} + void test_imports() { { auto img = make_image(); @@ -1098,6 +1148,7 @@ int main() { test_truncation(); test_relocations(); test_exports(); + test_empty_named_export(); test_imports(); test_delay_imports(); test_initialise(); -- cgit v1.2.3 From 1188e6406e31870119a7e50c5972599db554a406 Mon Sep 17 00:00:00 2001 From: jaybeebabageyus Date: Sun, 22 Nov 2026 20:54:47 +0100 Subject: runtime: scope the TLS clone purge to ownerless files, clean clones before ExitProcess, per-slot thread-event errors The startup purge deleted every leonida_tls_host_*.dll in the temp directory, so it could remove the clone of a concurrent process that had copied its helper but not reached LoadLibraryExW yet. Clones are now copied to a staging name and renamed into place while the copy step's guard handle is open, so a final-name clone never exists without a handle, and the purge skips files that fail an exclusive open or whose owner process (from the file name) is still alive. std::atexit cleanup never ran on the --run path because main ends with ExitProcess; the loader now exposes cleanup_tls_clones() and main calls it before ExitProcess (atexit still covers normal exits). on_host_thread_event wrapped the whole slot loop in one try/catch, so one throwing slot killed the events for every other module. The catch is now per slot, and the detach path releases the slot even when the callbacks threw, instead of leaking the block to the OS loader. README and the initialize_tls comment no longer claim only one mapped TLS module can be live; the loader_tls_test gained purge-ownership and explicit-cleanup checks. --- runtime/README.md | 7 ++- runtime/src/main.cpp | 2 + runtime/src/pe_loader.cpp | 126 ++++++++++++++++++++++++++++++--------- runtime/src/pe_loader.h | 8 ++- runtime/test/loader_tls_test.cpp | 108 +++++++++++++++++++++++++++++++++ 5 files changed, 218 insertions(+), 33 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/README.md b/runtime/README.md index 7060f4368..f7e25831e 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -118,9 +118,10 @@ process lifetime and answers as Windows does when no `Loader` is alive. different index space from the `TlsAlloc` slots, and only the OS loader can allocate a module index. The runtime therefore ships a minimal `gta6rt_tls_host.dll`; the loader reuses the index the OS assigns it, writes that index into the image's `AddressOfIndex`, and copies the image's TLS template into the -slot. This reserves one index, so **one manually mapped TLS module can be live at a time**; a second -one is rejected with an error instead of sharing the slot. Images without a TLS directory (or with an -all-zero one) load normally. +slot. This reserves one index; every additional simultaneous TLS module gets its own by mapping a fresh +clone of the helper from `%TEMP%\leonida_tls_host__.dll`, so up to 16 modules can be live at +once and a further one is rejected with an error instead of sharing a slot. Images without a TLS +directory (or with an all-zero one) load normally. Current limits, by design: diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 560f68349..c8875d853 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -129,6 +129,8 @@ int wmain(int argc, wchar_t** argv) { std::fflush(stderr); // Not `return`: a normal host exit runs the CRT's atexit table, which the game shares with gta6rt (its // handlers would run against a game that has stopped) and whose last word decides the exit status. + // ExitProcess also skips atexit, so the TLS clone cleanup registered there is run here instead. + rt::cleanup_tls_clones(); ExitProcess(static_cast(code)); } catch (const std::exception& e) { std::fprintf(stderr, "error: %s\n", e.what()); diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 113ca23ea..ec87ab7ee 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -123,7 +123,10 @@ std::array, kMaxMappedTlsModules> g_tls_slot_generations{} std::atomic g_next_tls_generation{1}; std::vector g_tls_clones; -void cleanup_tls_clones_at_exit() { +// Frees every TLS helper clone this process loaded and deletes its files. load() registers the wrapper with atexit; +// the --run path in main() must also call this directly before ExitProcess, which skips the atexit table. Call it +// only when no mapped code can run again: it unmaps the helper images. +void cleanup_tls_clones_internal() { for (const auto& rec : g_tls_clones) { if (rec.module) FreeLibrary(rec.module); if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); @@ -131,16 +134,54 @@ void cleanup_tls_clones_at_exit() { g_tls_clones.clear(); } +void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); } + +// The owner process named by "leonida_tls_host__.dll"; 0 when the name does not carry one. +DWORD clone_owner_pid(const wchar_t* name) { + constexpr wchar_t prefix[] = L"leonida_tls_host_"; + const wchar_t* p = name; + for (size_t i = 0; i < sizeof(prefix) / sizeof(wchar_t) - 1; ++i) + if (*p++ != prefix[i]) return 0; + if (*p < L'0' || *p > L'9') return 0; + unsigned long pid = 0; + while (*p >= L'0' && *p <= L'9') { + pid = pid * 10 + (*p - L'0'); + if (pid > 0xFFFFFFFFul) return 0; + ++p; + } + return static_cast(pid); +} + +bool process_alive(DWORD pid) { + // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the + // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID. + HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); + if (!p) return false; + CloseHandle(p); + return true; +} + +// Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a +// clone of a live process is either still open by its copy step's handle or mapped as an image, so it is skipped +// (or DeleteFileW fails harmlessly), and a concurrent process between CopyFileW and LoadLibraryExW keeps its file. void sweep_stale_tls_clones(const std::filesystem::path& dir) { WIN32_FIND_DATAW fd{}; const std::filesystem::path pattern = dir / L"leonida_tls_host_*.dll"; HANDLE h = FindFirstFileW(pattern.c_str(), &fd); if (h == INVALID_HANDLE_VALUE) return; do { - if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) { - // Fails harmlessly for clones still mapped in live processes; deletes orphaned ones from exited processes. - DeleteFileW((dir / fd.cFileName).c_str()); - } + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; + const std::filesystem::path path = dir / fd.cFileName; + const DWORD owner = clone_owner_pid(fd.cFileName); + if (owner && owner != GetCurrentProcessId() && process_alive(owner)) continue; + // An exclusive open (no sharing) conflicts with any handle another process holds on the file, so a failure + // means the copy->load sequence or a mapped image still owns it. Only unowned files reach DeleteFileW, and + // that stays harmless for a mapped image. + HANDLE probe = + CreateFileW(path.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (probe == INVALID_HANDLE_VALUE) continue; + CloseHandle(probe); + DeleteFileW(path.c_str()); } while (FindNextFileW(h, &fd)); FindClose(h); } @@ -208,13 +249,27 @@ TlsHostModule ensure_tls_host(size_t slot) { const std::wstring name = L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll"; const std::filesystem::path clone_path = dir / name; - if (!CopyFileW(primary.c_str(), clone_path.c_str(), FALSE)) return {}; - - // Hold a read-only-shared handle across LoadLibraryExW so another process cannot overwrite the clone in between. - HANDLE guard = CreateFileW(clone_path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, + // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll. + const std::filesystem::path staging = clone_path.wstring() + L".new"; + if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) return {}; + + // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename + // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone + // while the handle is open (an exclusive open conflicts with it) or once the image is mapped. Copying straight + // to the final name would leave a window where a concurrent sweep sees an unowned file. + HANDLE guard = CreateFileW(staging.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (guard == INVALID_HANDLE_VALUE) { + DeleteFileW(staging.c_str()); + return {}; + } + if (!MoveFileExW(staging.c_str(), clone_path.c_str(), MOVEFILE_REPLACE_EXISTING)) { + CloseHandle(guard); + DeleteFileW(staging.c_str()); + return {}; + } TlsHostModule loaded = load_tls_host_image(clone_path, false); - if (guard != INVALID_HANDLE_VALUE) CloseHandle(guard); + CloseHandle(guard); if (loaded.index == TLS_OUT_OF_INDEXES) { DeleteFileW(clone_path.c_str()); @@ -350,30 +405,39 @@ void run_callbacks(Module& m, uint32_t reason) { // only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. void __cdecl on_host_thread_event(DWORD reason) { SharedTlsLock lock; - try { - if (reason == DLL_THREAD_ATTACH) { - for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { - Module* m = g_tls_slot_owners[slot].load(); - if (!m) continue; + // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events + // away from the other slots. Nothing may leave DllMain. + if (reason == DLL_THREAD_ATTACH) { + for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { + Module* m = g_tls_slot_owners[slot].load(); + if (!m) continue; + try { install_thread_block(*m); if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); + } catch (const std::exception& e) { + // The thread runs on without this module's TLS; later slots still get theirs. + std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), + e.what()); } - } else if (reason == DLL_THREAD_DETACH) { - for (size_t i = kMaxMappedTlsModules; i-- > 0;) { - Module* m = g_tls_slot_owners[i].load(); - if (m && g_thread_tls_slots[i].module == m && - g_thread_tls_slots[i].generation == m->tls_generation) { + } + } else if (reason == DLL_THREAD_DETACH) { + for (size_t i = kMaxMappedTlsModules; i-- > 0;) { + Module* m = g_tls_slot_owners[i].load(); + if (m && g_thread_tls_slots[i].module == m && + g_thread_tls_slots[i].generation == m->tls_generation) { + try { if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH); - uninstall_thread_block(*m); - } else { - release_thread_slot(i); // installed by a module whose Loader is gone (or nothing to do) + } catch (const std::exception& e) { + std::fprintf(stderr, "[rt] loader: thread detach, slot %zu (%s): %s\n", i, m->name.c_str(), + e.what()); } + // Released even when the callbacks threw: a leaked block would be handed to the OS loader as the + // helper's own TLS block and freed with it at thread exit. + uninstall_thread_block(*m); + } else { + release_thread_slot(i); // installed by a module whose Loader is gone (or nothing to do) } } - } catch (const std::exception& e) { - // Nothing may leave DllMain. The thread runs on without the module's TLS (attach) or keeps the copy (detach). - std::fprintf(stderr, "[rt] loader: thread %s: %s\n", reason == DLL_THREAD_ATTACH ? "attach" : "detach", - e.what()); } } @@ -452,6 +516,9 @@ void redirect_pc_to_file_header_at(const void* resolved) { } // namespace +// Declared in pe_loader.h; the body needs the internal clone registry above. +void cleanup_tls_clones() { cleanup_tls_clones_internal(); } + namespace { bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { for (const Module* m : static_cast(ctx)->modules()) { @@ -701,8 +768,9 @@ Module& Loader::map_image(const std::filesystem::path& path) { // zero-fill size; it has no field naming the TLS block. The Windows loader allocates a block per module per thread and // puts it in TEB->ThreadLocalStoragePointer[module index], which is what __declspec(thread) code reads via _tls_index. // Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to -// gta6rt_tls_host.dll. That makes one manually mapped TLS module work; a second one is rejected rather than silently -// sharing (and corrupting) the same slot. +// gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone +// getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than +// silently sharing (and corrupting) a slot. void Loader::initialize_tls(Module& m) { auto* tls = tls_directory(m); if (!tls) return; diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index 42a2719f2..0861259ab 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -99,7 +99,8 @@ public: // Installs/removes this module's template copy in the calling thread's TEB slot. load() does this for its caller // and the thread events for threads started after it; both are no-ops on a thread that already has this module's // copy. Call install on a thread that existed before load(), before mapped code runs there, and uninstall before - // that thread exits. Only one TLS module can be installed in a thread. These do not run TLS callbacks (use + // that thread exits. Each module's copy sits in its own TEB slot, so one thread can hold copies of several + // modules. These do not run TLS callbacks (use // run_tls_callbacks with DLL_THREAD_ATTACH/DETACH for that). void install_tls_for_thread(Module& m); void uninstall_tls_for_thread(Module& m); @@ -122,6 +123,11 @@ private: std::vector init_order_; // dependencies first, see initialisation_order() }; +// Frees the TLS helper clones load() created and deletes their files (Module::tls_index background). load() +// registers this with atexit; a caller that ends with ExitProcess must invoke it directly, because ExitProcess +// skips the atexit table. Call it when no mapped code can run again: it unmaps the helper images. +void cleanup_tls_clones(); + std::string lower(std::string s); } // namespace rt diff --git a/runtime/test/loader_tls_test.cpp b/runtime/test/loader_tls_test.cpp index 8b1d6d6e1..a4962d4d1 100644 --- a/runtime/test/loader_tls_test.cpp +++ b/runtime/test/loader_tls_test.cpp @@ -492,6 +492,107 @@ void test_orphan_slot_generation_reuse(const fs::path& dll) { check(td() == 0, "orphaned worker exit does not dispatch DLL_THREAD_DETACH to the new generation's module"); } +// Spawns cmd.exe to obtain one guaranteed-dead PID and one guaranteed-live one for the purge-ownership checks. +struct ChildProcess { + HANDLE process = nullptr; + DWORD pid = 0; + explicit ChildProcess(const wchar_t* args) { + STARTUPINFOW si{}; + si.cb = sizeof(si); + PROCESS_INFORMATION pi{}; + std::wstring cmd = std::wstring(L"cmd.exe ") + args; + if (!CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si, + &pi)) + throw std::runtime_error("CreateProcessW for cmd.exe failed"); + CloseHandle(pi.hThread); + process = pi.hProcess; + pid = pi.dwProcessId; + } + ChildProcess(const ChildProcess&) = delete; + ChildProcess& operator=(const ChildProcess&) = delete; + void wait_exit() { + WaitForSingleObject(process, INFINITE); + CloseHandle(process); + process = nullptr; + } + ~ChildProcess() { + if (process) { + TerminateProcess(process, 0); + WaitForSingleObject(process, INFINITE); + CloseHandle(process); + } + } +}; + +// Clone files live in the temp root (the loader's clone directory), named with this process's PID. +std::vector own_clone_files() { + const std::wstring own = L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_"; + std::vector found; + WIN32_FIND_DATAW fd{}; + HANDLE h = FindFirstFileW((fs::temp_directory_path() / (own + L"*.dll")).c_str(), &fd); + if (h == INVALID_HANDLE_VALUE) return found; + do { + if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) + found.push_back(fs::temp_directory_path() / fd.cFileName); + } while (FindNextFileW(h, &fd)); + FindClose(h); + return found; +} + +// The startup purge must delete only clones whose owning process is gone and that nothing holds open: a concurrent +// process between its CopyFileW and its LoadLibraryExW must keep its file. Runs before any other clone-creating +// test, because the sweep fires once per process. +void test_purge_ownership_scoping(const fs::path& dll, const fs::path& temp) { + std::printf("\n-- startup purge deletes only ownerless clones --\n"); + ChildProcess dead(L"/c exit 0"); + dead.wait_exit(); + ChildProcess live(L"/c timeout /t 30 /nobreak > nul"); + + const fs::path clone_root = fs::temp_directory_path(); + const fs::path dead_file = clone_root / (L"leonida_tls_host_" + std::to_wstring(dead.pid) + L"_31.dll"); + const fs::path held_file = clone_root / (L"leonida_tls_host_" + std::to_wstring(dead.pid) + L"_32.dll"); + const fs::path live_file = clone_root / (L"leonida_tls_host_" + std::to_wstring(live.pid) + L"_33.dll"); + const char bytes[8] = "purgeXX"; + write_file(dead_file, bytes, 8); + write_file(held_file, bytes, 8); + write_file(live_file, bytes, 8); + // An open handle without FILE_SHARE_DELETE stands in for another process's guard or mapped image: the purge's + // exclusive-open probe must fail against it. + HANDLE held = CreateFileW(held_file.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + check(held != INVALID_HANDLE_VALUE, "opened the held clone stand-in without FILE_SHARE_DELETE"); + + const fs::path second = temp / "tiny_tls_purge_second.dll"; + check(CopyFileW(dll.c_str(), second.c_str(), FALSE) != 0, "copied the TLS fixture for the purge test"); + { + rt::Loader loader(dll.parent_path()); + rt::Module& first = loader.load(dll); // slot 0: primary helper, no clone + rt::Module& mapped_second = loader.load(second); // slot 1: clone; the purge sweep runs here + check(first.tls_index != rt::kNoTlsIndex && mapped_second.tls_index != rt::kNoTlsIndex, + "the purge test loads two simultaneous TLS modules"); + } + const auto clone_of_this_process = own_clone_files(); + check(clone_of_this_process.size() == 1, "this process owns exactly one clone file after the two-module load"); + + const bool dead_pid_still_free = [&] { + HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, dead.pid); + if (!p) return true; + CloseHandle(p); + return false; + }(); + if (dead_pid_still_free) + check(!fs::exists(dead_file), "the purge deleted the clone whose owner process is gone"); + else + std::printf("SKIP dead-owner deletion check: the child's PID was reused meanwhile\n"); + check(fs::exists(held_file), "the purge skipped the clone another handle holds open"); + check(fs::exists(live_file), "the purge skipped the clone whose owner process is still alive"); + + CloseHandle(held); + std::error_code ec; + fs::remove(held_file, ec); + fs::remove(live_file, ec); +} + void print_result() { if (g_failures == 0) std::printf("\nloader_tls_test: OK (%d checks)\n", g_checks); @@ -519,11 +620,18 @@ int main(int argc, char** argv) { } TempDir temp; + test_purge_ownership_scoping(tls_dll, temp.path); // first: the sweep fires once per process test_tls(tls_dll); test_thread_events(tls_dll); test_thread_outlives_loader(tls_dll); test_multiple_tls_modules(tls_dll, temp.path); test_orphan_slot_generation_reuse(tls_dll); + + // The --run path calls cleanup_tls_clones() before ExitProcess because atexit never runs there. + std::printf("\n-- explicit clone cleanup (the ExitProcess path) --\n"); + check(!own_clone_files().empty(), "TLS helper clone files exist before explicit cleanup"); + rt::cleanup_tls_clones(); + check(own_clone_files().empty(), "cleanup_tls_clones deletes every clone file of this process"); } catch (const std::exception& e) { ++g_checks; ++g_failures; -- cgit v1.2.3