From f4a3fe8d4a6dff718fa6ca9d2f5d5c5dcd8d6c41 Mon Sep 17 00:00:00 2001 From: jaybeebabageyus Date: Sun, 22 Nov 2026 17:14:23 +0100 Subject: runtime: propagate LoadLibraryEx flags and reject DONT_RESOLVE_DLL_REFERENCES for bundled DLLs --- runtime/src/pe_loader.cpp | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 558ed2799..ce43936b7 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -350,8 +350,8 @@ void* bundled_find_loaded(void* ctx, const std::string& dll_lower) { return static_cast(ctx)->find_loaded_module(dll_lower); } -void* bundled_load(void* ctx, const std::string& dll_lower, bool& handled) { - return static_cast(ctx)->load_runtime_module(dll_lower, handled); +void* bundled_load(void* ctx, const std::string& dll_lower, uint32_t flags, bool& handled) { + return static_cast(ctx)->load_runtime_module(dll_lower, flags, handled); } void* bundled_get_proc(void* ctx, void* module, const std::string& sym, bool& owns_handle) { @@ -436,16 +436,32 @@ void* Loader::find_loaded_module(const std::string& dll_lower) const { return it == by_name_.end() ? nullptr : static_cast(it->second->base); } -void* Loader::load_runtime_module(const std::string& dll_lower, bool& handled) { +void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled) { handled = false; if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr; std::lock_guard lock(mutex_); - if (auto it = by_name_.find(dll_lower); it != by_name_.end()) { - handled = true; + const auto existing = by_name_.find(dll_lower); + const std::filesystem::path candidate = game_dir_ / dll_lower; + std::error_code ec; + const bool is_bundled = existing != by_name_.end() || std::filesystem::is_regular_file(candidate, ec); + if (!is_bundled) return nullptr; + + handled = true; + // Win32 DONT_RESOLVE_DLL_REFERENCES (0x1) forbids resolving dependencies or running TLS/DllMain; refuse it + // explicitly instead of silently performing a normal resolving + initialising load. + if ((flags & DONT_RESOLVE_DLL_REFERENCES) != 0) { + std::fprintf(stderr, + "[rt] loader: LoadLibraryEx(%s, DONT_RESOLVE_DLL_REFERENCES) is not supported for bundled DLLs\n", + dll_lower.c_str()); + SetLastError(ERROR_NOT_SUPPORTED); + return nullptr; + } + + if (existing != by_name_.end()) { try { initialise(); - return static_cast(it->second->base); + return static_cast(existing->second->base); } catch (const std::exception& e) { std::fprintf(stderr, "[rt] loader: run-time initialise of %s failed: %s\n", dll_lower.c_str(), e.what()); SetLastError(ERROR_DLL_INIT_FAILED); @@ -453,11 +469,6 @@ void* Loader::load_runtime_module(const std::string& dll_lower, bool& handled) { } } - const std::filesystem::path candidate = game_dir_ / dll_lower; - std::error_code ec; - if (!std::filesystem::is_regular_file(candidate, ec)) return nullptr; - - handled = true; try { Module& m = load(candidate); initialise(); -- cgit v1.2.3 From a28493ba8f7ab85749fc2c4bdefa8091bf9085cc 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/CMakeLists.txt | 14 +- runtime/src/pe_loader.cpp | 275 +++++++++++++++++++++-------- runtime/src/pe_loader.h | 10 +- runtime/test/fixtures/tiny_tls_cb_only.cpp | 42 +++++ runtime/test/loader_tls_test.cpp | 149 +++++++++++++--- 5 files changed, 388 insertions(+), 102 deletions(-) create mode 100644 runtime/test/fixtures/tiny_tls_cb_only.cpp (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 01e188e47..acfc0ce50 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -444,6 +444,18 @@ if(BUILD_TESTING) ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" ) + add_library(tiny_tls_cb_only SHARED test/fixtures/tiny_tls_cb_only.cpp) + target_compile_definitions(tiny_tls_cb_only PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_tls_cb_only PRIVATE /W4 /permissive- /utf-8 /GS-) + target_link_options(tiny_tls_cb_only PRIVATE /NODEFAULTLIB /ENTRY:DllMainCRTStartup) + target_link_libraries(tiny_tls_cb_only PRIVATE kernel32) + set_target_properties(tiny_tls_cb_only PROPERTIES + OUTPUT_NAME tiny_tls_cb_only + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ) + # pe_loader.cpp needs the shim registry for shims::find/make_unimplemented_thunk. The fixtures import only host # DLLs, so no shim tables are linked. add_executable(loader_tls_test @@ -456,7 +468,7 @@ if(BUILD_TESTING) ) target_compile_definitions(loader_tls_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(loader_tls_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - add_dependencies(loader_tls_test tiny_tls gta6rt_tls_host) + add_dependencies(loader_tls_test tiny_tls tiny_tls_cb_only gta6rt_tls_host) add_test(NAME loader_tls COMMAND loader_tls_test "$" ) diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 387051756..6d1248057 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,64 @@ 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::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 +167,81 @@ 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; + 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 +259,38 @@ 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) { + if (m.tls_slot >= kMaxMappedTlsModules) return; + const size_t slot = m.tls_slot; + ThreadTlsSlot& entry = g_thread_tls_slots[slot]; + if (entry.module == &m) return; + if (entry.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 (entry.module == g_tls_slot_owners[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; + 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 +303,22 @@ 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.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) 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 +338,28 @@ 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) { + 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 +486,13 @@ 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); + g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr); } uninstall_tls_for_thread(*m); } @@ -604,19 +715,36 @@ 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_index = index; m.tls_template = raw ? m.base + raw_rva : nullptr; m.tls_raw_size = static_cast(raw); @@ -631,13 +759,14 @@ void Loader::initialize_tls(Module& m) { } catch (...) { ExclusiveTlsLock lock; m.tls_index = kNoTlsIndex; - g_tls_slot_owner = nullptr; + m.tls_slot = kNoTlsIndex; + 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) { + m.tls_block = g_thread_tls_slots[slot].block; + m.tls_saved_block = g_thread_tls_slots[slot].saved; } } diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index 1303cdff9..f550cc9e3 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -45,12 +45,12 @@ struct Module { // Static TLS (IMAGE_DIRECTORY_ENTRY_TLS). load() installs tls_block in the calling thread and writes tls_index to // the image's _tls_index. tls_index names TEB->ThreadLocalStoragePointer[tls_index], the array - // __declspec(thread) reads; it is not a TlsAlloc slot. The loader reserves the index by loading - // gta6rt_tls_host.dll, so only one manually mapped TLS module can be live at a time; a second one is rejected - // rather than sharing (and corrupting) the slot. Every thread started after load() gets its own copy through the - // helper's DLL_THREAD_ATTACH, and gives it back at DLL_THREAD_DETACH; install_tls_for_thread() is for threads - // that already existed. + // __declspec(thread) reads; it is not a TlsAlloc slot. The loader reserves distinct indices by loading + // gta6rt_tls_host.dll (and cloning it on demand for additional simultaneous TLS modules, up to 16 at a time). + // Every thread started after load() gets its own copy through the helper's DLL_THREAD_ATTACH, and gives it back + // at DLL_THREAD_DETACH; install_tls_for_thread() is for threads that already existed. uint32_t tls_index = kNoTlsIndex; + uint32_t tls_slot = kNoTlsIndex; // index into the loader's reserved TLS-host slot pool void* tls_block = nullptr; // calling thread's copy of the image's template void* tls_saved_block = nullptr; // helper DLL block replaced in that thread, restored by ~Loader uint32_t tls_block_size = 0; // raw template + zero fill diff --git a/runtime/test/fixtures/tiny_tls_cb_only.cpp b/runtime/test/fixtures/tiny_tls_cb_only.cpp new file mode 100644 index 000000000..d8062c073 --- /dev/null +++ b/runtime/test/fixtures/tiny_tls_cb_only.cpp @@ -0,0 +1,42 @@ +// Callback-only static TLS fixture DLL: defines _tls_used with StartAddressOfRawData == EndAddressOfRawData == 0 +// and SizeOfZeroFill == 0 while providing a TLS callback (no CRT .tls section). Ordinary test code, not game data. +#include + +namespace { + +ULONG g_tls_index = 0; +int g_attach_count = 0; +int g_detach_count = 0; +volatile DWORD g_watched_thread = 0; +int g_thread_attach_count = 0; +int g_thread_detach_count = 0; + +void NTAPI tls_callback(PVOID, DWORD reason, PVOID) { + if (reason == DLL_PROCESS_ATTACH) ++g_attach_count; + if (reason == DLL_PROCESS_DETACH) ++g_detach_count; + if (GetCurrentThreadId() == g_watched_thread) { + if (reason == DLL_THREAD_ATTACH) ++g_thread_attach_count; + if (reason == DLL_THREAD_DETACH) ++g_thread_detach_count; + } +} + +PIMAGE_TLS_CALLBACK g_callbacks[] = {tls_callback, nullptr}; + +} // namespace + +extern "C" const IMAGE_TLS_DIRECTORY64 _tls_used = { + 0, // StartAddressOfRawData + 0, // EndAddressOfRawData + reinterpret_cast(&g_tls_index), // AddressOfIndex + reinterpret_cast(g_callbacks), // AddressOfCallBacks + 0, // SizeOfZeroFill + 0, // Characteristics +}; + +extern "C" __declspec(dllexport) void __cdecl tiny_tls_cb_watch_thread(DWORD id) { g_watched_thread = id; } +extern "C" __declspec(dllexport) int __cdecl tiny_tls_cb_attach_count() { return g_attach_count; } +extern "C" __declspec(dllexport) int __cdecl tiny_tls_cb_detach_count() { return g_detach_count; } +extern "C" __declspec(dllexport) int __cdecl tiny_tls_cb_thread_attach_count() { return g_thread_attach_count; } +extern "C" __declspec(dllexport) int __cdecl tiny_tls_cb_thread_detach_count() { return g_thread_detach_count; } + +extern "C" BOOL WINAPI DllMainCRTStartup(HINSTANCE, DWORD, LPVOID) { return TRUE; } diff --git a/runtime/test/loader_tls_test.cpp b/runtime/test/loader_tls_test.cpp index e3360fca7..8b7b7b179 100644 --- a/runtime/test/loader_tls_test.cpp +++ b/runtime/test/loader_tls_test.cpp @@ -307,36 +307,139 @@ void test_thread_outlives_loader(const fs::path& dll) { "its copy is freed when it ends after the Loader, with no callback into the unmapped image"); } -void test_second_tls_module_rejected(const fs::path& dll, const fs::path& temp) { - std::printf("\n-- one mapped TLS module at a time --\n"); - const fs::path copy = temp / "tiny_tls_second.dll"; +void test_multiple_tls_modules(const fs::path& dll, const fs::path& temp) { + std::printf("\n-- multiple simultaneous mapped TLS modules --\n"); + const fs::path copy2 = temp / "tiny_tls_second.dll"; + const fs::path copy3 = temp / "tiny_tls_third.dll"; // CopyFileW, not fs::copy_file: MSVC's copy_file calls CopyFile2, which Wine 9 doesn't implement. - check(CopyFileW(dll.c_str(), copy.c_str(), FALSE) != 0, "copied the TLS fixture under a second name"); + check(CopyFileW(dll.c_str(), copy2.c_str(), FALSE) != 0, "copied the TLS fixture under a second name"); + check(CopyFileW(dll.c_str(), copy3.c_str(), FALSE) != 0, "copied the TLS fixture under a third name"); { rt::Loader loader(dll.parent_path()); rt::Module& first = loader.load(dll); - check(first.tls_index != rt::kNoTlsIndex, "the first TLS module is initialized"); - - bool rejected = false; - std::string message; - try { - loader.load(copy); - } catch (const std::runtime_error& e) { - rejected = true; - message = e.what(); - } - check(rejected, "a second mapped module with TLS is rejected instead of sharing a slot"); - check(message.find("only one manually mapped module") != std::string::npos, - "the rejection explains the one-module TLS limit"); + rt::Module& second = loader.load(copy2); + rt::Module& third = loader.load(copy3); + loader.initialise(); + + check(first.tls_index != rt::kNoTlsIndex && second.tls_index != rt::kNoTlsIndex && + third.tls_index != rt::kNoTlsIndex, + "all three simultaneous TLS modules receive reserved module TLS indices"); + check(first.tls_index != second.tls_index && first.tls_index != third.tls_index && + second.tls_index != third.tls_index, + "each simultaneous TLS module gets a distinct OS module TLS index"); + + auto get1 = find_export(first, "tiny_tls_get"); + auto set1 = find_export(first, "tiny_tls_set"); + auto get2 = find_export(second, "tiny_tls_get"); + auto set2 = find_export(second, "tiny_tls_set"); + auto get3 = find_export(third, "tiny_tls_get"); + auto set3 = find_export(third, "tiny_tls_set"); + auto watch1 = find_export(first, "tiny_tls_watch_thread"); + auto watch2 = find_export(second, "tiny_tls_watch_thread"); + auto watch3 = find_export(third, "tiny_tls_watch_thread"); + auto pa1 = find_export(first, "tiny_tls_attach_count"); + auto pa2 = find_export(second, "tiny_tls_attach_count"); + auto pa3 = find_export(third, "tiny_tls_attach_count"); + auto ta1 = find_export(first, "tiny_tls_thread_attach_count"); + auto ta2 = find_export(second, "tiny_tls_thread_attach_count"); + auto ta3 = find_export(third, "tiny_tls_thread_attach_count"); + auto td1 = find_export(first, "tiny_tls_thread_detach_count"); + auto td2 = find_export(second, "tiny_tls_thread_detach_count"); + auto td3 = find_export(third, "tiny_tls_thread_detach_count"); + + check(get1() == 7 && get2() == 7 && get3() == 7, "all three modules start from their template value 7"); + set1(101); + set2(202); + set3(303); + check(get1() == 101 && get2() == 202 && get3() == 303, + "writes to each module's TLS slot stay isolated on the main thread"); + + // A worker thread started after load() must get its own fresh template copies for all three modules and run + // DLL_THREAD_ATTACH / DLL_THREAD_DETACH callbacks on all three. + struct WorkerCtx { + int(__cdecl* get1)(); + void(__cdecl* set1)(int); + int(__cdecl* get2)(); + void(__cdecl* set2)(int); + int(__cdecl* get3)(); + void(__cdecl* set3)(int); + int init1 = 0, init2 = 0, init3 = 0; + int after1 = 0, after2 = 0, after3 = 0; + }; + WorkerCtx ctx{get1, set1, get2, set2, get3, set3}; + HANDLE thread = CreateThread( + nullptr, 0, + [](void* p) -> DWORD { + auto* c = static_cast(p); + c->init1 = c->get1(); + c->init2 = c->get2(); + c->init3 = c->get3(); + c->set1(1111); + c->set2(2222); + c->set3(3333); + c->after1 = c->get1(); + c->after2 = c->get2(); + c->after3 = c->get3(); + return 0; + }, + &ctx, CREATE_SUSPENDED, nullptr); + const DWORD tid = GetThreadId(thread); + watch1(tid); + watch2(tid); + watch3(tid); + ResumeThread(thread); + WaitForSingleObject(thread, INFINITE); + CloseHandle(thread); + + check(ctx.init1 == 7 && ctx.init2 == 7 && ctx.init3 == 7, + "worker thread receives fresh template copies for all three modules"); + check(ctx.after1 == 1111 && ctx.after2 == 2222 && ctx.after3 == 3333, + "worker thread writes stay isolated across all three modules"); + check(get1() == 101 && get2() == 202 && get3() == 303, + "main thread TLS values are untouched by the worker thread"); + check(pa1() == 1 && pa2() == 1 && pa3() == 1, + "each of the three modules received DLL_PROCESS_ATTACH once"); + check(ta1() == 1 && ta2() == 1 && ta3() == 1, + "each of the three modules received DLL_THREAD_ATTACH once for the worker"); + check(td1() == 1 && td2() == 1 && td3() == 1, + "each of the three modules received DLL_THREAD_DETACH once for the worker"); + } + + // Callback-only TLS module (tls_raw_size + tls_zero_fill == 0): must still receive DLL_THREAD_ATTACH and + // DLL_THREAD_DETACH on worker threads. + const fs::path cb_only_dll = dll.parent_path() / "tiny_tls_cb_only.dll"; + if (fs::exists(cb_only_dll)) { + rt::Loader loader(cb_only_dll.parent_path()); + rt::Module& m = loader.load(cb_only_dll); + loader.initialise(); + + auto watch = find_export(m, "tiny_tls_cb_watch_thread"); + auto pa = find_export(m, "tiny_tls_cb_attach_count"); + auto ta = find_export(m, "tiny_tls_cb_thread_attach_count"); + auto td = find_export(m, "tiny_tls_cb_thread_detach_count"); + + check(m.tls_raw_size == 0 && m.tls_zero_fill == 0 && m.tls_block == nullptr, + "callback-only TLS fixture has no TLS data block"); + check(m.tls_slot != rt::kNoTlsIndex, "callback-only TLS fixture is assigned a TLS slot"); + + HANDLE thread = CreateThread(nullptr, 0, [](void*) -> DWORD { return 0; }, nullptr, CREATE_SUSPENDED, nullptr); + watch(GetThreadId(thread)); + ResumeThread(thread); + WaitForSingleObject(thread, INFINITE); + CloseHandle(thread); + + check(pa() == 1, "callback-only TLS module received DLL_PROCESS_ATTACH once"); + check(ta() == 1, "callback-only TLS module received DLL_THREAD_ATTACH once"); + check(td() == 1, "callback-only TLS module received DLL_THREAD_DETACH once"); } - // After the first loader restores its slot, the copy loads normally. + // After the loader is destroyed, all slots are released and reusable. { - rt::Loader loader(copy.parent_path()); - rt::Module& m = loader.load(copy); - check(m.tls_index != rt::kNoTlsIndex, "the copied TLS module loads after the first loader is destroyed"); - check(find_export(m, "tiny_tls_get")() == 7, "the copied module reads its template value"); + rt::Loader loader(copy2.parent_path()); + rt::Module& m = loader.load(copy2); + check(m.tls_index != rt::kNoTlsIndex, "slots are reusable after the first loader is destroyed"); + check(find_export(m, "tiny_tls_get")() == 7, "the reloaded module reads its template value"); } } @@ -370,7 +473,7 @@ int main(int argc, char** argv) { test_tls(tls_dll); test_thread_events(tls_dll); test_thread_outlives_loader(tls_dll); - test_second_tls_module_rejected(tls_dll, temp.path); + test_multiple_tls_modules(tls_dll, temp.path); } catch (const std::exception& e) { ++g_checks; ++g_failures; -- cgit v1.2.3