From 2dca597bd9f143992032010037f2d5c3b970d312 Mon Sep 17 00:00:00 2001 From: Leonardo Guimaraes Date: Sun, 22 Nov 2026 01:24:50 -0300 Subject: Runtime: opt-in startup trace (gta6rt --trace FILE) Writes one JSON object per line, flushed per event: module maps, TLS callbacks, DllMain results, the first call of each unimplemented import with its caller as module+RVA, OutputDebugString text, exceptions with module+RVA and a short unwind, and the exit code. A vectored handler records and returns EXCEPTION_CONTINUE_SEARCH, so behaviour is unchanged. Off by default. startup_trace_test builds a synthetic DLL image (no game data) and checks each event kind. --- runtime/src/pe_loader.cpp | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 387051756..f153acdb1 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -14,6 +14,7 @@ #include #include "../shims/shims.h" +#include "../shims/startup_trace.h" #include "base_reservation.h" namespace rt { @@ -214,7 +215,9 @@ void uninstall_thread_block(Module& m) { release_thread_block(); } -void run_callbacks(Module& m, uint32_t reason) { +// `trace`: record each callback in the startup trace. Only the Loader's own calls (process attach and detach) pass +// true; the thread events run under the Windows loader lock and stay out of the trace. +void run_callbacks(Module& m, uint32_t reason, bool trace = false) { auto* tls = tls_directory(m); if (!tls || !tls->AddressOfCallBacks) return; const uint64_t table_rva = rva_in(m, tls->AddressOfCallBacks, "the TLS callback table"); @@ -226,6 +229,10 @@ void run_callbacks(Module& m, uint32_t reason) { if (!fn) break; auto callback = reinterpret_cast(m.base + rva_in(m, fn, "a TLS callback")); + if (trace && startup_trace::enabled()) + startup_trace::event("tls_callback", "\"module\":" + startup_trace::quote(m.name) + ",\"at\":" + + startup_trace::quote(startup_trace::where(reinterpret_cast(callback))) + + ",\"reason\":" + std::to_string(reason)); callback(m.base, static_cast(reason), nullptr); } } @@ -401,6 +408,11 @@ Module& Loader::load(const std::filesystem::path& image) { protect_sections(m); register_unwind(m); init_order_.push_back(&m); + if (startup_trace::enabled()) + startup_trace::event("map", "\"module\":" + startup_trace::quote(m.name) + + ",\"base\":" + startup_trace::quote(startup_trace::hex(reinterpret_cast(m.base))) + + ",\"size\":" + startup_trace::quote(startup_trace::hex(m.size)) + + ",\"relocated\":" + (m.relocated ? "true" : "false")); return m; } @@ -458,7 +470,11 @@ void Loader::initialise(Module& m) { if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image"); auto entry = reinterpret_cast(m.base + m.entry_rva); - if (!entry(m.base, DLL_PROCESS_ATTACH, nullptr)) { + const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, nullptr); + if (startup_trace::enabled()) + startup_trace::event("dllmain", "\"module\":" + startup_trace::quote(m.name) + + ",\"result\":" + std::to_string(ok)); + if (!ok) { set_initialised(m, true); // it ran: a second DLL_PROCESS_ATTACH would be wrong throw std::runtime_error(m.name + ": DllMain returned FALSE"); } @@ -645,7 +661,7 @@ void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); } void Loader::uninstall_tls_for_thread(Module& m) { uninstall_thread_block(m); } -void Loader::run_tls_callbacks(Module& m, uint32_t reason) { run_callbacks(m, reason); } +void Loader::run_tls_callbacks(Module& m, uint32_t reason) { run_callbacks(m, reason, /*trace=*/true); } void Loader::parse_exports(Module& m) { auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); -- cgit v1.2.3 From 47f4cdc643f3fca3f87a34d9a4718f250d7cd905 Mon Sep 17 00:00:00 2001 From: jaybeebabageyus Date: Sun, 22 Nov 2026 16:21:16 +0100 Subject: runtime: route LoadLibrary/GetProcAddress of bundled package DLLs through rt::Loader --- docs/runtime_imports.md | 9 ++- runtime/CMakeLists.txt | 30 ++++++++ runtime/shims/library_loader.cpp | 104 +++++++++++++++++++++------ runtime/shims/registry.cpp | 79 +++++++++++++++++++++ runtime/shims/shims.h | 16 +++++ runtime/src/pe_loader.cpp | 106 ++++++++++++++++++++++++++++ runtime/src/pe_loader.h | 8 +++ runtime/test/check_loaded_bundled.cmake | 14 ++++ runtime/test/fixtures/tiny_bundled_dll.cpp | 39 ++++++++++ runtime/test/fixtures/tiny_bundled_dll.def | 5 ++ runtime/test/fixtures/tiny_bundled_load.cpp | 83 ++++++++++++++++++++++ runtime/test/fixtures/xmem_stub.cpp | 9 +++ runtime/test/fixtures/xmem_stub.def | 3 + 13 files changed, 482 insertions(+), 23 deletions(-) create mode 100644 runtime/test/check_loaded_bundled.cmake create mode 100644 runtime/test/fixtures/tiny_bundled_dll.cpp create mode 100644 runtime/test/fixtures/tiny_bundled_dll.def create mode 100644 runtime/test/fixtures/tiny_bundled_load.cpp create mode 100644 runtime/test/fixtures/xmem_stub.cpp create mode 100644 runtime/test/fixtures/xmem_stub.def (limited to 'runtime/src/pe_loader.cpp') diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index c3860caf1..dd7902594 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -159,9 +159,12 @@ So `XCurl.dll` needs threading, error reporting and networking from the runtime, `libHttpClient.GDK.dll` date the GDK the package was built with: newer than the first `IXUserImpl5`, older than `IXUserImpl6`. The executable's own set is still unmeasured. `QueryApiImpl`'s log gives it on the first boot. -What this does not cover: a title that `LoadLibrary`s one of the package's bundled DLLs (`Bink2Scarlett.dll`, -`XboxBvhBuilder.dll`, the FidelityFX DLLs) still gets the host loader, which loads the Xbox build without the -registry's bindings for its own console imports (`xmem.dll`, `d3d12_xs.dll`). +A title that calls `LoadLibrary*`, `GetModuleHandle*`, `GetProcAddress` or `FreeLibrary` on one of the package's +bundled DLLs (`Bink2Scarlett.dll`, `XboxBvhBuilder.dll`, the FidelityFX DLLs) is routed through `rt::Loader` instead of +the host Windows loader (excluding data-file loads and host-preferred CRTs). The loader maps the DLL from `--game-dir`, +binds its console imports (`xmem.dll`, `d3d12_xs.dll`) through the shim registry, runs its `DllMain` and TLS callbacks, +and resolves direct, ordinal and forwarded exports from the mapped image. `run_tiny_bundled_load` exercises this path +end to end with a synthetic bundled DLL importing `xmem.dll!XMemAlloc` and `XMemFree`. ## What this proves and what it does not diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 2fb2c2fd4..222635bea 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -387,6 +387,33 @@ if(BUILD_TESTING) set_target_properties(tiny_gdk_load PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" ) + # Run-time LoadLibrary of a bundled Xbox DLL (importing xmem.dll) through rt::Loader. + add_library(xmem_stub SHARED test/fixtures/xmem_stub.cpp test/fixtures/xmem_stub.def) + target_compile_definitions(xmem_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(xmem_stub PRIVATE /W4 /permissive- /utf-8) + set_target_properties(xmem_stub PROPERTIES + OUTPUT_NAME xmem + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" + ) + add_library(tiny_bundled_dll SHARED test/fixtures/tiny_bundled_dll.cpp test/fixtures/tiny_bundled_dll.def) + target_link_libraries(tiny_bundled_dll PRIVATE xmem_stub) + target_compile_definitions(tiny_bundled_dll PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_bundled_dll PRIVATE /W4 /permissive- /utf-8) + set_target_properties(tiny_bundled_dll PROPERTIES + OUTPUT_NAME tiny_bundled_dll + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" + ) + add_executable(tiny_bundled_load test/fixtures/tiny_bundled_load.cpp) + target_compile_definitions(tiny_bundled_load PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_bundled_load PRIVATE /W4 /permissive- /utf-8) + add_dependencies(tiny_bundled_load tiny_bundled_dll) + set_target_properties(tiny_bundled_load PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) add_executable(tiny_game test/fixtures/tiny_game.cpp) target_link_libraries(tiny_game PRIVATE xgameruntime_stub) target_compile_definitions(tiny_game PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) # plain fopen, as games use @@ -607,6 +634,9 @@ if(BUILD_TESTING) add_test(NAME run_tiny_gdk_load COMMAND ${CMAKE_COMMAND} "-DLOADER=$" "-DGUEST=$" "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_gdk.cmake") + add_test(NAME run_tiny_bundled_load COMMAND ${CMAKE_COMMAND} + "-DLOADER=$" "-DGUEST=$" + "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_bundled.cmake") add_test(NAME run_tiny_game COMMAND gta6rt --run $ -- hello 42) add_test(NAME run_tiny_game_exit_code COMMAND tiny_game_exit_code_test "$" "$") diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp index 585c6a299..b67a38660 100644 --- a/runtime/shims/library_loader.cpp +++ b/runtime/shims/library_loader.cpp @@ -92,60 +92,124 @@ const Pseudo* pseudo(HMODULE h) { namespace { +constexpr DWORD kDataFileLoadFlags = + LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE; + +HMODULE load_shim_or_bundled(const std::string& path, bool& handled) { + handled = false; + if (HMODULE h = owned_handle(path)) { + handled = true; + return h; + } + const std::string dll = module_name(path); + if (!dll.empty()) { + if (void* h = load_bundled_module(dll, handled); handled) return reinterpret_cast(h); + } + return nullptr; +} + HMODULE WINAPI load_library_a(LPCSTR name) { - if (HMODULE h = name ? owned_handle(name) : nullptr) return h; + if (name) { + bool handled = false; + HMODULE h = load_shim_or_bundled(name, handled); + if (handled) return h; + } return LoadLibraryA(name); } HMODULE WINAPI load_library_w(LPCWSTR name) { - if (HMODULE h = name ? owned_handle(narrow(name)) : nullptr) return h; + if (name) { + bool handled = false; + HMODULE h = load_shim_or_bundled(narrow(name), handled); + if (handled) return h; + } return LoadLibraryW(name); } HMODULE WINAPI load_library_ex_a(LPCSTR name, HANDLE file, DWORD flags) { - if (HMODULE h = name ? owned_handle(name) : nullptr) return h; + if (name && (flags & kDataFileLoadFlags) == 0) { + bool handled = false; + HMODULE h = load_shim_or_bundled(name, handled); + if (handled) return h; + } return LoadLibraryExA(name, file, flags); } HMODULE WINAPI load_library_ex_w(LPCWSTR name, HANDLE file, DWORD flags) { - if (HMODULE h = name ? owned_handle(narrow(name)) : nullptr) return h; + if (name && (flags & kDataFileLoadFlags) == 0) { + bool handled = false; + HMODULE h = load_shim_or_bundled(narrow(name), handled); + if (handled) return h; + } return LoadLibraryExW(name, file, flags); } -// GetModuleHandle answers for an owned module as if it were loaded: the GDK may probe before it loads. +// GetModuleHandle answers for an owned module as if it were loaded (the GDK may probe before it loads), and for any +// bundled package module already mapped by the native loader. HMODULE WINAPI get_module_handle_a(LPCSTR name) { - if (HMODULE h = name ? owned_handle(name) : nullptr) return h; + if (name) { + if (HMODULE h = owned_handle(name)) return h; + const std::string dll = module_name(name); + if (!dll.empty()) + if (void* h = find_loaded_bundled_module(dll)) return reinterpret_cast(h); + } return GetModuleHandleA(name); } HMODULE WINAPI get_module_handle_w(LPCWSTR name) { - if (HMODULE h = name ? owned_handle(narrow(name)) : nullptr) return h; + if (name) { + const std::string path = narrow(name); + if (HMODULE h = owned_handle(path)) return h; + const std::string dll = module_name(path); + if (!dll.empty()) + if (void* h = find_loaded_bundled_module(dll)) return reinterpret_cast(h); + } return GetModuleHandleW(name); } FARPROC WINAPI get_proc_address(HMODULE module, LPCSTR name) { - const Pseudo* p = pseudo(module); - if (!p) return GetProcAddress(module, name); - if (!name) { + if (const Pseudo* p = pseudo(module)) { + if (!name) { + SetLastError(ERROR_PROC_NOT_FOUND); + return nullptr; + } + // A value below 0x10000 is an ordinal (IS_INTRESOURCE), as in the real GetProcAddress. + const std::string what = + IS_INTRESOURCE(name) ? "#" + std::to_string(reinterpret_cast(name)) : name; + if (void* fn = find(p->dll, what)) return reinterpret_cast(fn); + { + static auto* m = new std::mutex; + static auto* seen = new std::set; + std::lock_guard lock(*m); + if (seen->insert(p->dll + "!" + what).second) + std::fprintf(stderr, "[rt] loader: GetProcAddress(%s, %s): not served\n", p->dll.c_str(), what.c_str()); + } SetLastError(ERROR_PROC_NOT_FOUND); return nullptr; } - // A value below 0x10000 is an ordinal (IS_INTRESOURCE), as in the real GetProcAddress. + + if (!name) { + if (owns_bundled_module_handle(module)) { + SetLastError(ERROR_PROC_NOT_FOUND); + return nullptr; + } + return GetProcAddress(module, name); + } + const std::string what = IS_INTRESOURCE(name) ? "#" + std::to_string(reinterpret_cast(name)) : name; - if (void* fn = find(p->dll, what)) return reinterpret_cast(fn); - { - static auto* m = new std::mutex; - static auto* seen = new std::set; - std::lock_guard lock(*m); - if (seen->insert(p->dll + "!" + what).second) - std::fprintf(stderr, "[rt] loader: GetProcAddress(%s, %s): not served\n", p->dll.c_str(), what.c_str()); + bool owns_handle = false; + void* fn = get_bundled_proc_address(module, what, owns_handle); + if (owns_handle) { + if (fn) return reinterpret_cast(fn); + SetLastError(ERROR_PROC_NOT_FOUND); + return nullptr; } - SetLastError(ERROR_PROC_NOT_FOUND); - return nullptr; + return GetProcAddress(module, name); } BOOL WINAPI free_library(HMODULE module) { if (pseudo(module)) return TRUE; // owned modules are never unloaded + if (owns_bundled_module_handle(module)) return TRUE; // mapped modules stay live until ~Loader detaches them return FreeLibrary(module); } diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp index 4c6a0d60b..27d8d8ec6 100644 --- a/runtime/shims/registry.cpp +++ b/runtime/shims/registry.cpp @@ -323,6 +323,85 @@ void remove_module_lookup(void* ctx) { } } +namespace { + +struct BundledLoaderEntry { + void* ctx; + const BundledModuleOps* ops; +}; + +// Immortal: late mapped-DLL detach or atexit handlers may call GetProcAddress/FreeLibrary during process teardown. +std::mutex& bundled_loader_mutex() { + static auto* m = new std::mutex; + return *m; +} + +std::vector& bundled_loaders() { + static auto* v = new std::vector; + return *v; +} + +std::vector snapshot_bundled_loaders() { + std::lock_guard lock(bundled_loader_mutex()); + return bundled_loaders(); +} + +} // namespace + +void add_bundled_loader(void* ctx, const BundledModuleOps* ops) { + if (!ctx || !ops) return; + std::lock_guard lock(bundled_loader_mutex()); + bundled_loaders().push_back({ctx, ops}); +} + +void remove_bundled_loader(void* ctx) { + std::lock_guard lock(bundled_loader_mutex()); + auto& list = bundled_loaders(); + for (auto it = list.begin(); it != list.end(); ++it) + if (it->ctx == ctx) { + list.erase(it); + break; + } +} + +void* find_loaded_bundled_module(const std::string& dll_lower) { + for (const auto& entry : snapshot_bundled_loaders()) + if (void* h = entry.ops->find_loaded(entry.ctx, dll_lower)) return h; + return nullptr; +} + +void* load_bundled_module(const std::string& dll_lower, bool& handled) { + handled = false; + for (const auto& entry : snapshot_bundled_loaders()) { + bool loader_handled = false; + void* h = entry.ops->load_bundled(entry.ctx, dll_lower, loader_handled); + if (loader_handled) { + handled = true; + return h; + } + } + return nullptr; +} + +void* get_bundled_proc_address(void* module, const std::string& sym, bool& owns_handle) { + owns_handle = false; + for (const auto& entry : snapshot_bundled_loaders()) { + bool loader_owns = false; + void* fn = entry.ops->get_proc(entry.ctx, module, sym, loader_owns); + if (loader_owns) { + owns_handle = true; + return fn; + } + } + return nullptr; +} + +bool owns_bundled_module_handle(void* module) { + for (const auto& entry : snapshot_bundled_loaders()) + if (entry.ops->owns_handle(entry.ctx, module)) return true; + return false; +} + Table::Table(const Entry* entries, size_t count) { for (size_t i = 0; i < count; ++i) table()[lower_ascii(entries[i].dll) + "!" + entries[i].name] = entries[i].fn; } diff --git a/runtime/shims/shims.h b/runtime/shims/shims.h index 6b9cf39d3..c20fdecf1 100644 --- a/runtime/shims/shims.h +++ b/runtime/shims/shims.h @@ -55,6 +55,22 @@ void remove_module_lookup(void* ctx); // The base of the mapped module holding `address`, through the same lookups. False if no live Loader maps it. bool mapped_image_base(uint64_t address, uint64_t& base); +// Run-time LoadLibrary / GetModuleHandle / GetProcAddress / FreeLibrary for bundled package DLLs managed by a live +// Loader. Registered in Loader::Loader and removed in Loader::~Loader. +struct BundledModuleOps { + void* (*find_loaded)(void* ctx, const std::string& dll_lower); + void* (*load_bundled)(void* ctx, const std::string& dll_lower, bool& handled); + void* (*get_proc)(void* ctx, void* module, const std::string& sym, bool& owns_handle); + bool (*owns_handle)(void* ctx, void* module); +}; +void add_bundled_loader(void* ctx, const BundledModuleOps* ops); +void remove_bundled_loader(void* ctx); + +void* find_loaded_bundled_module(const std::string& dll_lower); +void* load_bundled_module(const std::string& dll_lower, bool& handled); +void* get_bundled_proc_address(void* module, const std::string& sym, bool& owns_handle); +bool owns_bundled_module_handle(void* module); + // Test seam: called at the top of every unimplemented-import call with the address of rt_unimplemented's return // address slot (so a test can check stack alignment) and from inside the call (so it can walk the stack). using TestHook = void (*)(const void* return_address_slot); diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 387051756..558ed2799 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -345,10 +345,34 @@ bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t } return false; } + +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_get_proc(void* ctx, void* module, const std::string& sym, bool& owns_handle) { + return static_cast(ctx)->resolve_module_export(module, sym, owns_handle); +} + +bool bundled_owns_handle(void* ctx, void* module) { + return static_cast(ctx)->owns_module_handle(module); +} + +const shims::BundledModuleOps kBundledOps{ + &bundled_find_loaded, + &bundled_load, + &bundled_get_proc, + &bundled_owns_handle, +}; } // namespace Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { shims::add_module_lookup(this, &lookup_in_loader); + shims::add_bundled_loader(this, &kBundledOps); } Loader::~Loader() { @@ -372,6 +396,7 @@ Loader::~Loader() { entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored } } + shims::remove_bundled_loader(this); shims::remove_module_lookup(this); for (auto* m : order_) { // TLS state must go away before the image and its TLS block are unmapped. @@ -394,6 +419,7 @@ Loader::~Loader() { } 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); @@ -404,6 +430,86 @@ Module& Loader::load(const std::filesystem::path& image) { return m; } +void* Loader::find_loaded_module(const std::string& dll_lower) const { + std::lock_guard lock(mutex_); + auto it = by_name_.find(dll_lower); + return it == by_name_.end() ? nullptr : static_cast(it->second->base); +} + +void* Loader::load_runtime_module(const std::string& dll_lower, 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; + try { + initialise(); + return static_cast(it->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); + return nullptr; + } + } + + 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(); + 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_. + 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); + return nullptr; + } +} + +void* Loader::resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle) { + owns_handle = false; + if (!module_handle) return nullptr; + std::lock_guard lock(mutex_); + Module* target = nullptr; + for (Module* m : order_) { + if (m->base == module_handle) { + target = m; + break; + } + } + if (!target) return nullptr; + owns_handle = true; + if (auto it = target->exports.find(sym); it != target->exports.end()) return it->second; + if (auto it = target->forwarders.find(sym); it != target->forwarders.end()) { + try { + Binding binding = Binding::Unimplemented; + void* fn = resolve_forwarder(it->second, binding, 0); + if (binding == Binding::Module) initialise(); + return fn; + } catch (const std::exception& e) { + std::fprintf(stderr, "[rt] loader: forwarder %s from %s failed: %s\n", it->second.c_str(), + target->name.c_str(), e.what()); + return nullptr; + } + } + return nullptr; +} + +bool Loader::owns_module_handle(void* module_handle) const { + if (!module_handle) return false; + std::lock_guard lock(mutex_); + for (const Module* m : order_) + if (m->base == module_handle) return true; + return false; +} + // x64 has no frame-pointer chain to fall back on: without its .pdata registered, an exception raised in (or passing // through) a mapped image can't be dispatched past that frame, and the process dies. Images the system loader maps // are found through its own module list; ours are VirtualAlloc'd, so they are registered as dynamic function tables. diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index 1303cdff9..d9f89f542 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -103,6 +104,12 @@ public: void install_tls_for_thread(Module& m); void uninstall_tls_for_thread(Module& m); + // Run-time module lookup/loading used by the library_loader shim for bundled package DLLs. + void* find_loaded_module(const std::string& dll_lower) const; + void* load_runtime_module(const std::string& dll_lower, bool& handled); + void* resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle); + bool owns_module_handle(void* module_handle) const; + private: void initialise(Module& m); static void set_initialised(Module& m, bool value); @@ -115,6 +122,7 @@ private: void protect_sections(Module& m); void register_unwind(Module& m); + mutable std::recursive_mutex mutex_; std::filesystem::path game_dir_; std::map by_name_; // lower-case file name std::vector order_; // mapping order; owns the modules diff --git a/runtime/test/check_loaded_bundled.cmake b/runtime/test/check_loaded_bundled.cmake new file mode 100644 index 000000000..397e59c2f --- /dev/null +++ b/runtime/test/check_loaded_bundled.cmake @@ -0,0 +1,14 @@ +# Run the run-time bundled-DLL load fixture (tiny_bundled_load) under the loader and check its verdict from outside, +# as check_loaded_gdk.cmake does. +get_filename_component(guest_dir "${GUEST}" DIRECTORY) +get_filename_component(guest_name "${GUEST}" NAME) +execute_process( + COMMAND ${RUNNER} "${LOADER}" --run "${guest_name}" + WORKING_DIRECTORY "${guest_dir}" + TIMEOUT 90 + RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE output) +string(REPLACE "\r\n" "\n" output "${output}") +if(NOT code STREQUAL "0" OR NOT output MATCHES "(^|\n)tiny_bundled_load: PASS(\n|$)" + OR NOT output MATCHES "(^|\n)game exited with code 0(\n|$)") + message(FATAL_ERROR "Loaded bundled-DLL run-time fixture returned ${code}\n${output}") +endif() diff --git a/runtime/test/fixtures/tiny_bundled_dll.cpp b/runtime/test/fixtures/tiny_bundled_dll.cpp new file mode 100644 index 000000000..ef0fbe63b --- /dev/null +++ b/runtime/test/fixtures/tiny_bundled_dll.cpp @@ -0,0 +1,39 @@ +// A stand-in bundled Xbox DLL (like Bink2Scarlett.dll or amd_fidelityfx_upscaler_xbox.dll) that imports console +// memory functions from xmem.dll and is loaded at run time through LoadLibraryW by tiny_bundled_load.exe. +// Test code, not game content. +#include + +#include +#include + +extern "C" { +__declspec(dllimport) void* __stdcall XMemAlloc(size_t size, uint64_t attributes); +__declspec(dllimport) void __stdcall XMemFree(void* ptr, uint64_t attributes); +} + +namespace { +int g_attach_count = 0; +} + +BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) { + if (reason == DLL_PROCESS_ATTACH) ++g_attach_count; + return TRUE; +} + +extern "C" __declspec(dllexport) int __stdcall bundled_attach_count() { return g_attach_count; } + +extern "C" __declspec(dllexport) uint32_t __stdcall bundled_alloc_sum() { + auto* buf = static_cast(XMemAlloc(16 * sizeof(uint32_t), 0x5e50000)); + if (!buf) return 0; + if ((reinterpret_cast(buf) & 63u) != 0) { + XMemFree(buf, 0x5e50000); + return 0; + } + uint32_t sum = 0; + for (uint32_t i = 0; i < 16; ++i) { + buf[i] = i + 1; + sum += buf[i]; + } + XMemFree(buf, 0x5e50000); + return sum; +} diff --git a/runtime/test/fixtures/tiny_bundled_dll.def b/runtime/test/fixtures/tiny_bundled_dll.def new file mode 100644 index 000000000..9771777bb --- /dev/null +++ b/runtime/test/fixtures/tiny_bundled_dll.def @@ -0,0 +1,5 @@ +EXPORTS + bundled_attach_count @1 + bundled_alloc_sum @2 + bundled_fwd_alloc=xmem.XMemAlloc @3 + bundled_fwd_free=xmem.XMemFree @4 diff --git a/runtime/test/fixtures/tiny_bundled_load.cpp b/runtime/test/fixtures/tiny_bundled_load.cpp new file mode 100644 index 000000000..51fbaac72 --- /dev/null +++ b/runtime/test/fixtures/tiny_bundled_load.cpp @@ -0,0 +1,83 @@ +// A mapped program that loads a bundled Xbox DLL (tiny_bundled_dll.dll, which imports xmem.dll) at run time via +// LoadLibraryW, GetModuleHandle, GetProcAddress and FreeLibrary — the pattern used by titles that dynamically load +// Bink2Scarlett.dll, XboxBvhBuilder.dll or the FidelityFX DLLs. Under `gta6rt --run`, library_loader.cpp routes the +// load to rt::Loader so the DLL's xmem.dll imports bind to the shim registry instead of failing under the host loader. +// Ordinary test code; no game data. +#include + +#include +#include +#include + +namespace { + +using AttachCountFn = int(__stdcall*)(); +using AllocSumFn = uint32_t(__stdcall*)(); +using XMemAllocFn = void*(__stdcall*)(size_t, uint64_t); +using XMemFreeFn = void(__stdcall*)(void*, uint64_t); + +int fail(const char* stage, unsigned long value) { + std::printf("tiny_bundled_load: FAIL %s (0x%08lx)\n", stage, value); + return 1; +} + +} // namespace + +int main() { + if (GetModuleHandleW(L"tiny_bundled_dll.dll") != nullptr) + return fail("GetModuleHandleW before LoadLibrary should be NULL", 0); + + HMODULE mod = LoadLibraryW(L"tiny_bundled_dll.dll"); + if (!mod) return fail("LoadLibraryW(tiny_bundled_dll.dll)", GetLastError()); + + // Must be mapped by rt::Loader, not by the host Windows loader. + HMODULE host_view = nullptr; + if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, L"tiny_bundled_dll.dll", &host_view) && + host_view == mod) { + return fail("tiny_bundled_dll.dll came from the host loader, not rt::Loader", 0); + } + + if (GetModuleHandleW(L"tiny_bundled_dll.dll") != mod) + return fail("GetModuleHandleW after LoadLibrary returns the same handle", 0); + if (GetModuleHandleA("TINY_BUNDLED_DLL") != mod) + return fail("GetModuleHandleA case-insensitive without .dll returns the same handle", 0); + if (LoadLibraryExA("C:\\Fake\\Path\\tiny_bundled_dll.dll", nullptr, 0) != mod) + return fail("LoadLibraryExA with full path returns the same already-mapped handle", GetLastError()); + + auto attach_count = reinterpret_cast(GetProcAddress(mod, "bundled_attach_count")); + if (!attach_count) return fail("GetProcAddress(bundled_attach_count)", GetLastError()); + const int count = attach_count(); + if (count != 1) return fail("DllMain(DLL_PROCESS_ATTACH) ran once", static_cast(count)); + + auto alloc_sum = reinterpret_cast(GetProcAddress(mod, "bundled_alloc_sum")); + if (!alloc_sum) return fail("GetProcAddress(bundled_alloc_sum)", GetLastError()); + if (reinterpret_cast(GetProcAddress(mod, MAKEINTRESOURCEA(2))) != reinterpret_cast(alloc_sum)) + return fail("GetProcAddress by ordinal #2 matches bundled_alloc_sum", GetLastError()); + const uint32_t sum = alloc_sum(); + if (sum != 136u) return fail("bundled_alloc_sum via xmem shim returned 136", sum); + + auto fwd_alloc = reinterpret_cast(GetProcAddress(mod, "bundled_fwd_alloc")); + auto fwd_free = reinterpret_cast(GetProcAddress(mod, "bundled_fwd_free")); + if (!fwd_alloc || !fwd_free) return fail("GetProcAddress follows forwarders to xmem shim", GetLastError()); + void* block = fwd_alloc(128, 0); + if (!block || (reinterpret_cast(block) & 63u) != 0) + return fail("forwarded xmem.XMemAlloc returned aligned block", 0); + fwd_free(block, 0); + + SetLastError(0); + if (GetProcAddress(mod, "NoSuchExport") != nullptr || GetLastError() != ERROR_PROC_NOT_FOUND) + return fail("missing export returns NULL with ERROR_PROC_NOT_FOUND", GetLastError()); + SetLastError(0); + if (GetProcAddress(mod, nullptr) != nullptr || GetLastError() != ERROR_PROC_NOT_FOUND) + return fail("null export name returns NULL with ERROR_PROC_NOT_FOUND", GetLastError()); + + if (!FreeLibrary(mod)) return fail("FreeLibrary(tiny_bundled_dll.dll)", GetLastError()); + + // Host modules still resolve through the host loader. + HMODULE k32 = LoadLibraryW(L"kernel32.dll"); + if (!k32 || GetProcAddress(k32, "GetTickCount") != GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetTickCount")) + return fail("kernel32.dll still comes from the host", GetLastError()); + + std::puts("tiny_bundled_load: PASS"); + return 0; +} diff --git a/runtime/test/fixtures/xmem_stub.cpp b/runtime/test/fixtures/xmem_stub.cpp new file mode 100644 index 000000000..75754408e --- /dev/null +++ b/runtime/test/fixtures/xmem_stub.cpp @@ -0,0 +1,9 @@ +// Link-time stand-in for the console's xmem.dll, so tiny_bundled_dll.dll gets real imports of XMemAlloc and +// XMemFree (the same imports Bink2Scarlett.dll and amd_fidelityfx_upscaler_xbox.dll carry). Under `gta6rt --run` the +// shim registry answers them instead; if the host loader ever loaded this stub directly, XMemAlloc returns nullptr +// so the test fails loudly. Test code, not game content. +#include +#include + +extern "C" __declspec(dllexport) void* __stdcall XMemAlloc(size_t, uint64_t) { return nullptr; } +extern "C" __declspec(dllexport) void __stdcall XMemFree(void*, uint64_t) {} diff --git a/runtime/test/fixtures/xmem_stub.def b/runtime/test/fixtures/xmem_stub.def new file mode 100644 index 000000000..60c6ed789 --- /dev/null +++ b/runtime/test/fixtures/xmem_stub.def @@ -0,0 +1,3 @@ +EXPORTS + XMemAlloc + XMemFree -- cgit v1.2.3 From b805f191da65088ca3831fd5f4360e603670aef8 Mon Sep 17 00:00:00 2001 From: Dominik <55330408+Dom-in@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:19:53 +0000 Subject: pe_loader: refuse an export whose address is outside the image parse_exports range-checks the export directory, its three tables and every name, but stored each code export as base + rva without checking rva. An address-table entry at or past SizeOfImage (and outside the export directory, so not a forwarder) became a pointer past the mapping, which an import or GetProcAddress through the shims would hand out and a caller would jump to. The load now fails with the export's name, like every other RVA the loader follows. loader_test: an export at SizeOfImage is rejected (it loaded before this change); one at the image's last byte still loads. Co-Authored-By: Claude Opus 5.5 --- runtime/src/pe_loader.cpp | 2 ++ runtime/test/loader_test.cpp | 14 ++++++++++++++ 2 files changed, 16 insertions(+) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 387051756..a291e03d8 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -669,6 +669,8 @@ void Loader::parse_exports(Module& m) { auto add_export = [&](const std::string& key, uint32_t rva) { 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 + throw std::runtime_error(m.name + ": export " + key + " points outside the image"); else m.exports[key] = m.base + rva; }; diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index fd38434c6..2e4a32aa8 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -977,6 +977,19 @@ void test_unwind_registration() { expect_rejects("unwind data past the image", make_unwind_image({{0x1000, 0x1010, 0x1FFE}})); } +// An export whose address-table entry is past SizeOfImage (not a forwarder: outside the export directory) is +// refused instead of being stored as base + rva, a pointer outside the mapping. +void test_export_bounds() { + auto outside = make_forwarder_image("KERNEL32.GetCurrentProcessId", 0x180000000); + nt_of(outside)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size = sizeof(IMAGE_EXPORT_DIRECTORY); + *reinterpret_cast(outside.data() + 0x300) = 0x2000; // funcs[0] == SizeOfImage + expect_rejects("an export whose address is past the image", outside); + auto last = make_forwarder_image("KERNEL32.GetCurrentProcessId", 0x180000000); + nt_of(last)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size = sizeof(IMAGE_EXPORT_DIRECTORY); + *reinterpret_cast(last.data() + 0x300) = 0x1FFF; // the image's last byte: still inside + expect_loads("an export at the image's last byte still loads", last); +} + // The folder the images go to: leonida_loader_test\ in LEONIDA_TEST_DIR when that is set, otherwise in // the temporary directory. A folder per run, because security software can hold the previous run's images for a // while after they are written (so they can be neither deleted nor overwritten); the fixed parent name is what an @@ -1066,6 +1079,7 @@ int main() { test_process_detach_dependencies(); test_delay_descriptor_fields(); test_forwarded_exports(); + test_export_bounds(); test_unwind_registration(); } catch (const std::exception& e) { // A write that fails (write_image throws) ends the run with the reason, instead of terminating the process. -- cgit v1.2.3 From 56fd84b2740f92a04154da8b1d8b90f10920b3ff Mon Sep 17 00:00:00 2001 From: Dominik <55330408+Dom-in@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:59:38 +0000 Subject: pe_loader: a forwarded CRT export binds the host copy, as a direct import does resolve_forwarder checked prefer_host_copy() on the bare forwarder module name, but forwarder strings normally leave out ".dll" ("MSVCP140.?foo") and the host-copy list is named with it. So a bundled module forwarding to one of the CRT DLLs the package ships (vcruntime140, msvcp140, concrt140, ...) mapped the Xbox build of that DLL from the game folder instead of the host's, unlike a direct import of the same symbol. It now uses shim_key, the name with ".dll" the function already builds for the shim lookup. loader_test: a fake bundled vcruntime140.dll plus a provider forwarding "vcruntime140.memset" binds to the host memset and never maps the fake (fails before the change: the import ends unimplemented). Co-Authored-By: Claude Opus 5.5 --- runtime/src/pe_loader.cpp | 4 +++- runtime/test/loader_test.cpp | 29 +++++++++++++++++++++++++++++ 2 files changed, 32 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 387051756..c55520571 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -709,10 +709,12 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d } } + // shim_key, not the bare module name: forwarder strings usually leave out ".dll" ("MSVCP140.?foo"), and the host + // CRT copies are named with it, so a forwarded CRT symbol must skip the bundled Xbox build as a direct import does. const std::filesystem::path candidates[] = {game_dir_ / module, game_dir_ / (module + ".dll")}; for (const auto& candidate : candidates) { std::error_code ec; - if (prefer_host_copy(lower(module)) || !std::filesystem::exists(candidate, ec)) continue; + if (prefer_host_copy(shim_key) || !std::filesystem::exists(candidate, ec)) continue; Module& dep = load(candidate); if (auto it = dep.exports.find(symbol); it != dep.exports.end()) { binding = Binding::Module; diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index fd38434c6..f16ba5589 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -843,6 +843,35 @@ void test_forwarded_exports() { failed(what, e.what()); } } + { + // Forwarder strings name the module without ".dll". The package ships Xbox builds of the CRT + // (vcruntime140.dll, msvcp140.dll, ...) that the loader replaces with the host's for a direct import; a + // forwarded one must get the host copy too, not map the bundled file. + const char* what = "a forwarder to a CRT module without \".dll\" binds the host copy, not the bundled one"; + write_image_as(make_forwarder_image("KERNEL32.GetCurrentProcessId", 0x1a0000000), "vcruntime140.dll"); + write_image_as(make_forwarder_image("vcruntime140.memset", 0x180000000), "prov_crt.dll"); + auto importer = write_image_as(make_import_image("prov_crt.dll", "fwd"), "importer_crt.exe"); + HMODULE host_crt = LoadLibraryExA("vcruntime140.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + void* expected = host_crt ? reinterpret_cast(GetProcAddress(host_crt, "memset")) : nullptr; + if (!expected) { + std::printf("SKIP %s: no vcruntime140.dll in System32\n", what); + } else { + try { + rt::Loader loader(g_dir); + rt::Module& m = loader.load(importer); + if (m.imports.size() != 1 || m.imports[0].binding != rt::Binding::Host) + return failed(what, "the forwarded CRT import did not bind to the host"); + if (*reinterpret_cast(m.base + 0x1180) != expected) + return failed(what, "the address table does not hold the host's memset"); + for (auto* mod : loader.modules()) + if (rt::lower(mod->name) == "vcruntime140.dll") + return failed(what, "the bundled vcruntime140.dll was mapped"); + pass(what); + } catch (const std::exception& e) { + failed(what, e.what()); + } + } + } { const char* what = "a forwarder to a shimmed module binds to the shim"; write_image_as(make_forwarder_image("testshim.F", 0x180000000), "prov_shim.dll"); -- cgit v1.2.3 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/shims/library_loader.cpp | 13 ++++++------ runtime/shims/registry.cpp | 4 ++-- runtime/shims/shims.h | 4 ++-- runtime/src/pe_loader.cpp | 33 +++++++++++++++++++---------- runtime/src/pe_loader.h | 2 +- runtime/test/fixtures/tiny_bundled_load.cpp | 9 ++++++++ 6 files changed, 43 insertions(+), 22 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp index b67a38660..0093e6050 100644 --- a/runtime/shims/library_loader.cpp +++ b/runtime/shims/library_loader.cpp @@ -95,7 +95,7 @@ namespace { constexpr DWORD kDataFileLoadFlags = LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE; -HMODULE load_shim_or_bundled(const std::string& path, bool& handled) { +HMODULE load_shim_or_bundled(const std::string& path, DWORD flags, bool& handled) { handled = false; if (HMODULE h = owned_handle(path)) { handled = true; @@ -103,7 +103,8 @@ HMODULE load_shim_or_bundled(const std::string& path, bool& handled) { } const std::string dll = module_name(path); if (!dll.empty()) { - if (void* h = load_bundled_module(dll, handled); handled) return reinterpret_cast(h); + if (void* h = load_bundled_module(dll, static_cast(flags), handled); handled) + return reinterpret_cast(h); } return nullptr; } @@ -111,7 +112,7 @@ HMODULE load_shim_or_bundled(const std::string& path, bool& handled) { HMODULE WINAPI load_library_a(LPCSTR name) { if (name) { bool handled = false; - HMODULE h = load_shim_or_bundled(name, handled); + HMODULE h = load_shim_or_bundled(name, 0, handled); if (handled) return h; } return LoadLibraryA(name); @@ -120,7 +121,7 @@ HMODULE WINAPI load_library_a(LPCSTR name) { HMODULE WINAPI load_library_w(LPCWSTR name) { if (name) { bool handled = false; - HMODULE h = load_shim_or_bundled(narrow(name), handled); + HMODULE h = load_shim_or_bundled(narrow(name), 0, handled); if (handled) return h; } return LoadLibraryW(name); @@ -129,7 +130,7 @@ HMODULE WINAPI load_library_w(LPCWSTR name) { HMODULE WINAPI load_library_ex_a(LPCSTR name, HANDLE file, DWORD flags) { if (name && (flags & kDataFileLoadFlags) == 0) { bool handled = false; - HMODULE h = load_shim_or_bundled(name, handled); + HMODULE h = load_shim_or_bundled(name, flags, handled); if (handled) return h; } return LoadLibraryExA(name, file, flags); @@ -138,7 +139,7 @@ HMODULE WINAPI load_library_ex_a(LPCSTR name, HANDLE file, DWORD flags) { HMODULE WINAPI load_library_ex_w(LPCWSTR name, HANDLE file, DWORD flags) { if (name && (flags & kDataFileLoadFlags) == 0) { bool handled = false; - HMODULE h = load_shim_or_bundled(narrow(name), handled); + HMODULE h = load_shim_or_bundled(narrow(name), flags, handled); if (handled) return h; } return LoadLibraryExW(name, file, flags); diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp index 27d8d8ec6..f6eb8487c 100644 --- a/runtime/shims/registry.cpp +++ b/runtime/shims/registry.cpp @@ -370,11 +370,11 @@ void* find_loaded_bundled_module(const std::string& dll_lower) { return nullptr; } -void* load_bundled_module(const std::string& dll_lower, bool& handled) { +void* load_bundled_module(const std::string& dll_lower, uint32_t flags, bool& handled) { handled = false; for (const auto& entry : snapshot_bundled_loaders()) { bool loader_handled = false; - void* h = entry.ops->load_bundled(entry.ctx, dll_lower, loader_handled); + void* h = entry.ops->load_bundled(entry.ctx, dll_lower, flags, loader_handled); if (loader_handled) { handled = true; return h; diff --git a/runtime/shims/shims.h b/runtime/shims/shims.h index c20fdecf1..1dbf3a5bf 100644 --- a/runtime/shims/shims.h +++ b/runtime/shims/shims.h @@ -59,7 +59,7 @@ bool mapped_image_base(uint64_t address, uint64_t& base); // Loader. Registered in Loader::Loader and removed in Loader::~Loader. struct BundledModuleOps { void* (*find_loaded)(void* ctx, const std::string& dll_lower); - void* (*load_bundled)(void* ctx, const std::string& dll_lower, bool& handled); + void* (*load_bundled)(void* ctx, const std::string& dll_lower, uint32_t flags, bool& handled); void* (*get_proc)(void* ctx, void* module, const std::string& sym, bool& owns_handle); bool (*owns_handle)(void* ctx, void* module); }; @@ -67,7 +67,7 @@ void add_bundled_loader(void* ctx, const BundledModuleOps* ops); void remove_bundled_loader(void* ctx); void* find_loaded_bundled_module(const std::string& dll_lower); -void* load_bundled_module(const std::string& dll_lower, bool& handled); +void* load_bundled_module(const std::string& dll_lower, uint32_t flags, bool& handled); void* get_bundled_proc_address(void* module, const std::string& sym, bool& owns_handle); bool owns_bundled_module_handle(void* module); 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(); diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index d9f89f542..d8801bc38 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -106,7 +106,7 @@ public: // Run-time module lookup/loading used by the library_loader shim for bundled package DLLs. void* find_loaded_module(const std::string& dll_lower) const; - void* load_runtime_module(const std::string& dll_lower, bool& handled); + void* load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled); void* resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle); bool owns_module_handle(void* module_handle) const; diff --git a/runtime/test/fixtures/tiny_bundled_load.cpp b/runtime/test/fixtures/tiny_bundled_load.cpp index 51fbaac72..f2a3b7f36 100644 --- a/runtime/test/fixtures/tiny_bundled_load.cpp +++ b/runtime/test/fixtures/tiny_bundled_load.cpp @@ -27,6 +27,15 @@ int main() { if (GetModuleHandleW(L"tiny_bundled_dll.dll") != nullptr) return fail("GetModuleHandleW before LoadLibrary should be NULL", 0); + // DONT_RESOLVE_DLL_REFERENCES must fail explicitly rather than silently resolving imports and running DllMain. + SetLastError(0); + if (LoadLibraryExW(L"tiny_bundled_dll.dll", nullptr, DONT_RESOLVE_DLL_REFERENCES) != nullptr || + GetLastError() != ERROR_NOT_SUPPORTED) { + return fail("LoadLibraryExW(DONT_RESOLVE_DLL_REFERENCES) fails with ERROR_NOT_SUPPORTED", GetLastError()); + } + if (GetModuleHandleW(L"tiny_bundled_dll.dll") != nullptr) + return fail("DONT_RESOLVE_DLL_REFERENCES must not map or register the bundled DLL", 0); + HMODULE mod = LoadLibraryW(L"tiny_bundled_dll.dll"); if (!mod) return fail("LoadLibraryW(tiny_bundled_dll.dll)", GetLastError()); -- 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