diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index c3860caf10..dd7902594a 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 2fb2c2fd4a..222635bea1 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 585c6a2995..0093e60501 100644 --- a/runtime/shims/library_loader.cpp +++ b/runtime/shims/library_loader.cpp @@ -92,60 +92,125 @@ 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, DWORD flags, 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, static_cast(flags), 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, 0, 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), 0, 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, flags, 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), flags, 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 4c6a0d60b4..f6eb8487cb 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, 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, flags, 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 6b9cf39d34..1dbf3a5bf5 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, 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); +}; +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, 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); + // 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 387051756d..ce43936b73 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, 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) { + 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,97 @@ 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, uint32_t flags, bool& handled) { + handled = false; + if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr; + + std::lock_guard lock(mutex_); + 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(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); + return nullptr; + } + } + + 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 1303cdff90..d8801bc384 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 @@ class Loader { 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, 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; + private: void initialise(Module& m); static void set_initialised(Module& m, bool value); @@ -115,6 +122,7 @@ class Loader { 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 0000000000..397e59c2f6 --- /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 0000000000..ef0fbe63b8 --- /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 0000000000..9771777bbc --- /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 0000000000..f2a3b7f36a --- /dev/null +++ b/runtime/test/fixtures/tiny_bundled_load.cpp @@ -0,0 +1,92 @@ +// 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); + + // 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()); + + // 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 0000000000..75754408ec --- /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 0000000000..60c6ed789f --- /dev/null +++ b/runtime/test/fixtures/xmem_stub.def @@ -0,0 +1,3 @@ +EXPORTS + XMemAlloc + XMemFree