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