diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index a1939ba461..e11b5760fa 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1462,6 +1462,27 @@ if(BUILD_TESTING) # Wine serves its builtin wsock32 for a wsock32.dll loaded by path; the test needs its own copy. Windows ignores this. set_tests_properties(library_loader_names PROPERTIES ENVIRONMENT "WINEDLLOVERRIDES=wsock32=n,b") + # GetModuleFileNameA/W and GetModuleHandleA/W(nullptr) for a mapped executable, bundled DLLs, and owned shims. + add_executable(library_loader_test + test/library_loader_test.cpp + src/pe_loader.cpp + shims/library_loader.cpp + shims/registry.cpp + shims/xmem.cpp + ) + target_include_directories(library_loader_test PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src + ${CMAKE_CURRENT_SOURCE_DIR}/shims + ) + target_compile_definitions(library_loader_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(library_loader_test PRIVATE /W4 /permissive- /utf-8 /EHsc) + target_link_options(library_loader_test PRIVATE /OPT:NOREF) + target_link_libraries(library_loader_test PRIVATE psapi) + add_dependencies(library_loader_test tiny_exe tiny_dll gta6rt_tls_host) + add_test(NAME library_loader + COMMAND library_loader_test "$" "$" + ) + # The host GameInput path (docs/gameinput.md): mapped code that imports GameInputCreate from GameInput.dll, with no # GameInput shim linked. Needs the SDK's gameinput.lib and GameInput.h to build the fixture, and a GameInput.dll on # the machine to run (the test skips with 77 only when Windows cannot load GameInput.dll). No game files. diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp index 69a9b48f0d..eb33c1ad84 100644 --- a/runtime/shims/library_loader.cpp +++ b/runtime/shims/library_loader.cpp @@ -232,40 +232,103 @@ HMODULE WINAPI load_library_ex_w(LPCWSTR name, HANDLE file, DWORD flags) { } // GetModuleHandle answers for a LEONIDA_COMPAT_DIR module as Windows would (its handle once loaded, else NULL, never -// the shim's pseudo-handle), 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. +// the shim's pseudo-handle), for an owned module as if it were loaded (the GDK may probe before it loads), for any +// bundled package module already mapped by the native loader, and for NULL when a mapped executable is active. HMODULE WINAPI get_module_handle_a(LPCSTR name) { - if (name) { - bool compat = false; - if (HMODULE h = compat_first(widen(name), false, 0, compat); compat) return h; - 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); + if (!name) { + if (void* main = main_bundled_module()) { + SetLastError(ERROR_SUCCESS); + return reinterpret_cast(main); + } + return GetModuleHandleA(nullptr); } + bool compat = false; + if (HMODULE h = compat_first(widen(name), false, 0, compat); compat) return h; + 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 (name) { - bool compat = false; - if (HMODULE h = compat_first(name, false, 0, compat); compat) return h; - if (ascii_basename(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); - } else { - // Outside ASCII: by the wide basename (narrow() would turn it into '?'), as for load_library_w. - const std::wstring dll = module_name_w(name); - if (!dll.empty()) - if (void* h = find_loaded_bundled_module_w(dll)) return reinterpret_cast(h); + if (!name) { + if (void* main = main_bundled_module()) { + SetLastError(ERROR_SUCCESS); + return reinterpret_cast(main); } + return GetModuleHandleW(nullptr); + } + bool compat = false; + if (HMODULE h = compat_first(name, false, 0, compat); compat) return h; + if (ascii_basename(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); + } else { + // Outside ASCII: by the wide basename (narrow() would turn it into '?'), as for load_library_w. + const std::wstring dll = module_name_w(name); + if (!dll.empty()) + if (void* h = find_loaded_bundled_module_w(dll)) return reinterpret_cast(h); } return GetModuleHandleW(name); } +bool resolve_module_filename(HMODULE module, std::wstring& wide) { + if (!module) return bundled_module_path(nullptr, wide); + if (const Pseudo* p = pseudo(module)) { + wide.assign(p->dll.begin(), p->dll.end()); + return true; + } + return bundled_module_path(module, wide); +} + +template +DWORD copy_module_filename(const std::basic_string& text, CharT* out, DWORD size) { + if (size == 0) { + SetLastError(ERROR_INSUFFICIENT_BUFFER); + return 0; + } + if (!out) { + SetLastError(ERROR_INVALID_PARAMETER); + return 0; + } + const size_t n = text.size(); + if (n >= static_cast(size)) { + const size_t copy = static_cast(size) - 1; + if (copy) std::memcpy(out, text.data(), copy * sizeof(CharT)); + out[copy] = 0; + SetLastError(ERROR_INSUFFICIENT_BUFFER); + return size; + } + std::memcpy(out, text.data(), (n + 1) * sizeof(CharT)); + SetLastError(ERROR_SUCCESS); + return static_cast(n); +} + +DWORD WINAPI get_module_file_name_w(HMODULE module, LPWSTR filename, DWORD size) { + std::wstring wide; + if (!resolve_module_filename(module, wide)) return GetModuleFileNameW(module, filename, size); + return copy_module_filename(wide, filename, size); +} + +DWORD WINAPI get_module_file_name_a(HMODULE module, LPSTR filename, DWORD size) { + std::wstring wide; + if (!resolve_module_filename(module, wide)) return GetModuleFileNameA(module, filename, size); + std::string ansi; + if (!wide.empty()) { + const int needed = WideCharToMultiByte(CP_ACP, 0, wide.data(), static_cast(wide.size()), nullptr, 0, + nullptr, nullptr); + if (needed <= 0) return 0; + ansi.resize(static_cast(needed)); + WideCharToMultiByte(CP_ACP, 0, wide.data(), static_cast(wide.size()), ansi.data(), needed, nullptr, + nullptr); + } + return copy_module_filename(ansi, filename, size); +} + FARPROC WINAPI get_proc_address(HMODULE module, LPCSTR name) { if (const Pseudo* p = pseudo(module)) { if (!name) { @@ -342,6 +405,8 @@ BOOL WINAPI disable_thread_calls(HMODULE module) { {dll, "LoadLibraryExW", reinterpret_cast(&rt::shims::library_loader::load_library_ex_w)}, \ {dll, "GetModuleHandleA", reinterpret_cast(&rt::shims::library_loader::get_module_handle_a)}, \ {dll, "GetModuleHandleW", reinterpret_cast(&rt::shims::library_loader::get_module_handle_w)}, \ + {dll, "GetModuleFileNameA", reinterpret_cast(&rt::shims::library_loader::get_module_file_name_a)}, \ + {dll, "GetModuleFileNameW", reinterpret_cast(&rt::shims::library_loader::get_module_file_name_w)}, \ {dll, "GetProcAddress", reinterpret_cast(&rt::shims::library_loader::get_proc_address)}, \ {dll, "FreeLibrary", reinterpret_cast(&rt::shims::library_loader::free_library)}, \ {dll, "DisableThreadLibraryCalls", reinterpret_cast(&rt::shims::library_loader::disable_thread_calls)} diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp index 5c7f39470b..25fb926286 100644 --- a/runtime/shims/registry.cpp +++ b/runtime/shims/registry.cpp @@ -548,6 +548,19 @@ bool owns_bundled_module_handle(void* module) { return false; } +bool bundled_module_path(void* module, std::wstring& path) { + for (const auto& entry : snapshot_bundled_loaders()) + if (entry.ops->module_path && entry.ops->module_path(entry.ctx, module, path)) return true; + return false; +} + +void* main_bundled_module() { + for (const auto& entry : snapshot_bundled_loaders()) + if (entry.ops->main_module) + if (void* h = entry.ops->main_module(entry.ctx)) return h; + return nullptr; +} + void add_xmem_allocation_hooks(const void* owner, const XMemAllocationHooks* hooks) { if (!owner || !hooks) return; std::lock_guard lock(xmem_hooks_mutex()); diff --git a/runtime/shims/shims.h b/runtime/shims/shims.h index e724279453..0cd7fc6982 100644 --- a/runtime/shims/shims.h +++ b/runtime/shims/shims.h @@ -77,6 +77,9 @@ struct BundledModuleOps { void* (*compat_module)(void* ctx, const std::wstring& basename, const std::wstring& name, bool load, uint32_t flags, bool& handled); bool (*owns_compat_handle)(void* ctx, void* module); + // Optional path and primary-executable queries for GetModuleFileName* and GetModuleHandle(nullptr). Either may be null. + bool (*module_path)(void* ctx, void* module, std::wstring& path); + void* (*main_module)(void* ctx); }; void add_bundled_loader(void* ctx, const BundledModuleOps* ops); void remove_bundled_loader(void* ctx); @@ -90,6 +93,8 @@ bool owns_bundled_module_handle(void* module); void* compat_module(const std::wstring& basename, const std::wstring& name, bool load, uint32_t flags, bool& handled); bool owns_compat_module_handle(void* module); +bool bundled_module_path(void* module, std::wstring& path); +void* main_bundled_module(); // Title-exported __XMemAllocationHooks__ (GDK XMEM_ALLOCATION_HOOKS): the console runtime routes internal // allocations (including D3D12 descriptor heaps) through these callbacks when the mapped image exports the struct. diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index d441605057..bd129ef94e 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1358,6 +1358,14 @@ bool bundled_owns_compat_handle(void* ctx, void* module) { return static_cast(ctx)->owns_compat_handle(module); } +bool bundled_module_path_op(void* ctx, void* module, std::wstring& path) { + return static_cast(ctx)->module_path(module, path); +} + +void* bundled_main_module_op(void* ctx) { + return static_cast(ctx)->main_module_handle(); +} + const shims::BundledModuleOps kBundledOps{ &bundled_find_loaded, &bundled_load, @@ -1367,6 +1375,8 @@ const shims::BundledModuleOps kBundledOps{ &bundled_load_w, &bundled_compat_module, &bundled_owns_compat_handle, + &bundled_module_path_op, + &bundled_main_module_op, }; // Marks what a run-time load maps as a dynamic load for as long as it is in scope (the caller holds the mutex). @@ -1635,6 +1645,24 @@ bool Loader::owns_module_handle(void* module_handle) const { return false; } +bool Loader::module_path(void* module_handle, std::wstring& out_path) const { + std::lock_guard lock(mutex_); + for (const Module* m : order_) { + if (module_handle ? (m->base == module_handle) : m->is_exe) { + out_path = m->full_path.native(); + return true; + } + } + return false; +} + +void* Loader::main_module_handle() const { + std::lock_guard lock(mutex_); + for (const Module* m : order_) + if (m->is_exe) return static_cast(m->base); + return nullptr; +} + // 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. @@ -1742,6 +1770,12 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& m->name = name; m->narrow_key = narrow_key; m->path = path; + { + std::error_code ec; + const std::filesystem::path abs = std::filesystem::absolute(path, ec); + m->full_path = ec ? path : abs.lexically_normal(); + } + m->is_exe = (nt->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0; m->preferred_base = oh.ImageBase; m->size = oh.SizeOfImage; m->entry_rva = oh.AddressOfEntryPoint; diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index 31be1a9d36..b5c65d4c77 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -30,10 +30,12 @@ struct Module { std::string name; // UTF-8 basename for diagnostics and traces, not a lookup key std::string narrow_key; // legacy lower-case narrow basename; empty when it cannot round-trip std::filesystem::path path; + std::filesystem::path full_path; // absolute path captured at map time, for GetModuleFileName* uint8_t* base = nullptr; uint64_t preferred_base = 0; uint32_t size = 0; uint32_t entry_rva = 0; + bool is_exe = false; bool relocated = false; bool initialised = false; @@ -145,6 +147,8 @@ class Loader { void* runtime_compat_module(const std::wstring& basename, const std::wstring& name, bool load, uint32_t flags, bool& handled); bool owns_compat_handle(void* module); + bool module_path(void* module_handle, std::wstring& out_path) const; + void* main_module_handle() const; private: void initialise(Module& m); diff --git a/runtime/test/library_loader_test.cpp b/runtime/test/library_loader_test.cpp new file mode 100644 index 0000000000..a403854c2a --- /dev/null +++ b/runtime/test/library_loader_test.cpp @@ -0,0 +1,176 @@ +// Checks GetModuleFileNameA/W and GetModuleHandleA/W(nullptr) through shims/library_loader.cpp against host controls. +#include + +#include +#include +#include +#include +#include + +#include "pe_loader.h" +#include "shims.h" + +namespace { + +namespace fs = std::filesystem; +int g_failures = 0; + +void check(bool ok, const char* what) { + std::printf("%s %s\n", ok ? "PASS" : "FAIL", what); + if (!ok) ++g_failures; +} + +using GetModuleHandleAFn = HMODULE(WINAPI*)(LPCSTR); +using GetModuleHandleWFn = HMODULE(WINAPI*)(LPCWSTR); +using GetModuleFileNameAFn = DWORD(WINAPI*)(HMODULE, LPSTR, DWORD); +using GetModuleFileNameWFn = DWORD(WINAPI*)(HMODULE, LPWSTR, DWORD); + +std::wstring wide_from_acp(const char* s) { + if (!s || !*s) return {}; + const int n = MultiByteToWideChar(CP_ACP, 0, s, -1, nullptr, 0); + if (n <= 1) return {}; + std::wstring out(static_cast(n), L'\0'); + MultiByteToWideChar(CP_ACP, 0, s, -1, out.data(), n); + out.pop_back(); + return out; +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 3) { + std::fprintf(stderr, "usage: library_loader_test \n"); + return 2; + } + const fs::path exe_path = fs::absolute(argv[1]).lexically_normal(); + const fs::path dll_path = fs::absolute(argv[2]).lexically_normal(); + + const auto get_handle_a = + reinterpret_cast(rt::shims::find("api-ms-win-core-libraryloader-l1-2-0.dll", "GetModuleHandleA")); + const auto get_handle_w = + reinterpret_cast(rt::shims::find("api-ms-win-core-libraryloader-l1-2-0.dll", "GetModuleHandleW")); + const auto get_name_a = + reinterpret_cast(rt::shims::find("api-ms-win-core-libraryloader-l1-2-0.dll", "GetModuleFileNameA")); + const auto get_name_w = + reinterpret_cast(rt::shims::find("api-ms-win-core-libraryloader-l1-2-0.dll", "GetModuleFileNameW")); + + check(get_handle_a && get_handle_w && get_name_a && get_name_w, + "libraryloader-l1-2-0 serves GetModuleHandleA/W and GetModuleFileNameA/W"); + if (!get_handle_a || !get_handle_w || !get_name_a || !get_name_w) return 1; + + // 1. Before any EXE is loaded, nullptr falls back to host executable (parity with native GetModuleFileNameW). + wchar_t host_w[MAX_PATH] = {}; + const DWORD host_w_len = ::GetModuleFileNameW(nullptr, host_w, MAX_PATH); + wchar_t shim_w[MAX_PATH] = {}; + const DWORD pre_w_len = get_name_w(nullptr, shim_w, MAX_PATH); + check(pre_w_len == host_w_len && std::wstring(shim_w) == host_w, + "GetModuleFileNameW(nullptr) falls back to host before an EXE is loaded"); + check(get_handle_w(nullptr) == ::GetModuleHandleW(nullptr), + "GetModuleHandleW(nullptr) falls back to host before an EXE is loaded"); + + // 2. Host truncation/error-code control check on native GetModuleFileNameW/A. + std::wstring short_host_w(5, L'x'); + ::SetLastError(0); + const DWORD host_trunc_w = ::GetModuleFileNameW(nullptr, short_host_w.data(), 5); + const DWORD host_trunc_err = ::GetLastError(); + + // 3. Load a DLL only: nullptr still falls back to host, explicit DLL HMODULE resolves to the DLL path. + try { + { + rt::Loader dll_only(dll_path.parent_path()); + rt::Module& dll_mod = dll_only.load(dll_path); + const HMODULE dll_h = reinterpret_cast(dll_mod.base); + std::wstring out_w(MAX_PATH, L'\0'); + const DWORD dll_len = get_name_w(dll_h, out_w.data(), MAX_PATH); + out_w.resize(dll_len); + check(dll_len == dll_path.wstring().size() && out_w == dll_path.wstring(), + "GetModuleFileNameW(dll_h) returns mapped bundled DLL path"); + std::wstring after_dll_null(MAX_PATH, L'\0'); + const DWORD n = get_name_w(nullptr, after_dll_null.data(), MAX_PATH); + after_dll_null.resize(n); + check(after_dll_null == host_w, "GetModuleFileNameW(nullptr) stays host when only DLLs are mapped"); + } + + // 4. Load an EXE (passed via a relative filename), then change CWD before querying GetModuleFileNameA/W. + const fs::path orig_cwd = fs::current_path(); + const fs::path temp_cwd = fs::temp_directory_path(); + fs::current_path(exe_path.parent_path()); + rt::Loader loader(exe_path.parent_path()); + rt::Module& exe_mod = loader.load(exe_path.filename()); + fs::current_path(temp_cwd); + + const HMODULE exe_h = reinterpret_cast(exe_mod.base); + check(get_handle_w(nullptr) == exe_h && get_handle_a(nullptr) == exe_h, + "GetModuleHandleA/W(nullptr) returns mapped EXE HMODULE"); + + std::wstring mapped_w(MAX_PATH, L'\0'); + ::SetLastError(ERROR_INVALID_PARAMETER); + const DWORD mapped_w_len = get_name_w(nullptr, mapped_w.data(), MAX_PATH); + const DWORD mapped_w_err = ::GetLastError(); + mapped_w.resize(mapped_w_len); + check(mapped_w == exe_path.wstring() && mapped_w_err == ERROR_SUCCESS, + "GetModuleFileNameW(nullptr) returns absolute mapped EXE path even after SetCurrentDirectory"); + + std::vector mapped_a(MAX_PATH, '\0'); + ::SetLastError(ERROR_INVALID_PARAMETER); + const DWORD mapped_a_len = get_name_a(exe_h, mapped_a.data(), MAX_PATH); + const DWORD mapped_a_err = ::GetLastError(); + check(mapped_a_err == ERROR_SUCCESS && wide_from_acp(mapped_a.data()) == exe_path.wstring() && + mapped_a_len == std::strlen(mapped_a.data()), + "GetModuleFileNameA(exe_h) returns matching ACP path"); + + // Truncation and size=0 parity against host Windows behavior. + std::wstring exact_len_buf(mapped_w_len + 1, L'Z'); + ::SetLastError(0); + const DWORD exact_len_ret = get_name_w(nullptr, exact_len_buf.data(), mapped_w_len); + check(exact_len_ret == mapped_w_len && ::GetLastError() == ERROR_INSUFFICIENT_BUFFER && + exact_len_buf[mapped_w_len - 1] == L'\0', + "GetModuleFileNameW with nSize == len truncates with NUL, returns nSize, sets ERROR_INSUFFICIENT_BUFFER"); + + std::wstring trunc_w(5, L'Z'); + ::SetLastError(0); + const DWORD trunc_ret = get_name_w(nullptr, trunc_w.data(), 5); + check(trunc_ret == host_trunc_w && ::GetLastError() == host_trunc_err && + trunc_w.substr(0, 4) == exe_path.wstring().substr(0, 4) && trunc_w[4] == L'\0', + "GetModuleFileNameW truncation matches native host semantics"); + + std::vector trunc_a(5, 'Z'); + ::SetLastError(0); + const DWORD trunc_a_ret = get_name_a(nullptr, trunc_a.data(), 5); + check(trunc_a_ret == 5 && ::GetLastError() == ERROR_INSUFFICIENT_BUFFER && trunc_a[4] == '\0', + "GetModuleFileNameA truncation sets ERROR_INSUFFICIENT_BUFFER and NUL-terminates"); + + wchar_t zero_w[4] = L"abc"; + ::SetLastError(0); + check(get_name_w(nullptr, zero_w, 0) == 0 && ::GetLastError() == ERROR_INSUFFICIENT_BUFFER, + "GetModuleFileNameW with nSize=0 returns 0 with ERROR_INSUFFICIENT_BUFFER"); + + // Bundled dependency HMODULE (tiny_dll loaded by tiny_exe). + const HMODULE dep_h = get_handle_a("tiny_dll.dll"); + check(dep_h != nullptr, "GetModuleHandleA finds loaded dependency tiny_dll.dll"); + if (dep_h) { + std::wstring dep_w(MAX_PATH, L'\0'); + const DWORD dep_len = get_name_w(dep_h, dep_w.data(), MAX_PATH); + dep_w.resize(dep_len); + check(fs::path(dep_w).filename() == dll_path.filename(), + "GetModuleFileNameW(dep_h) resolves dependency path"); + } + + // Owned shim pseudo-handle (xmem.dll). + const HMODULE shim_h = get_handle_a("xmem.dll"); + check(shim_h != nullptr, "GetModuleHandleA resolves owned shim xmem.dll"); + if (shim_h) { + std::wstring xmem_w(MAX_PATH, L'\0'); + const DWORD xmem_len = get_name_w(shim_h, xmem_w.data(), MAX_PATH); + xmem_w.resize(xmem_len); + check(xmem_w == L"xmem.dll", "GetModuleFileNameW(pseudo) returns shim DLL name"); + } + + fs::current_path(orig_cwd); + } catch (const std::exception& e) { + std::printf("FAIL exception: %s\n", e.what()); + ++g_failures; + } + std::printf("library_loader_test: %s (%d failures)\n", g_failures ? "FAILED" : "OK", g_failures); + return g_failures ? 1 : 0; +}