From 9ccb1052e4d317b18e82ff4b239bef25bc6b68c7 Mon Sep 17 00:00:00 2001 From: admin Date: Sun, 22 Nov 2026 18:25:41 +0000 Subject: Validate named import thunk RVAs before narrowing Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- runtime/test/loader_test.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) (limited to 'runtime/test/loader_test.cpp') diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 194174b00..d5248bd06 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -397,6 +397,42 @@ void test_imports() { } } +void test_import_name_rvas() { + for (bool delay : {false, true}) { + auto img = make_import_image("testshim.dll", "F"); + if (delay) { + std::fill(img.begin() + 0x200, img.begin() + 0x240, uint8_t{0}); + auto* d = reinterpret_cast(img.data() + 0x200); + d->Attributes.AllAttributes = 1; + d->DllNameRVA = 0x1060; + d->ImportNameTableRVA = 0x1100; + d->ImportAddressTableRVA = 0x1180; + auto* nt = nt_of(img); + nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] = {}; + auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT]; + dir.VirtualAddress = 0x1000; + dir.Size = 2 * sizeof(IMAGE_DELAYLOAD_DESCRIPTOR); + } + const char* valid = delay ? "a valid delay-import name RVA loads" : "a valid import name RVA loads"; + std::string error; + if (load(write_image(img), error) != 0) + failed(valid, error); + else + pass(valid); + + *reinterpret_cast(img.data() + 0x300) = (1ull << 32) | 0x1120; + const char* invalid = delay ? "a delay-import name RVA with high bits is rejected" + : "an import name RVA with high bits is rejected"; + error.clear(); + if (load(write_image(img), error) == 0) + failed(invalid, "the image loaded"); + else if (error.find("an import name runs past the image") == std::string::npos) + failed(invalid, error); + else + pass(invalid); + } +} + void test_delay_imports() { { auto img = make_image(); @@ -1099,6 +1135,7 @@ int main() { test_relocations(); test_exports(); test_imports(); + test_import_name_rvas(); test_delay_imports(); test_initialise(); test_initialise_rejects(); -- cgit v1.2.3 From 5e3ec685a3a60e3f7597b96824b7ee52ba3396af Mon Sep 17 00:00:00 2001 From: airp1ane <279825357+airp1ane@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:53:36 -0500 Subject: pe_loader: a failed load, dependencies included, is not left findable by name map_image records a module in by_name_ before mapping, binding and section protection can throw. The run-time load path erased only the DLL it was asked for, so a bundled dependency that failed while being bound stayed registered with unbound imports, and a later LoadLibrary or GetModuleHandle of it returned that half-loaded image. load() now erases its own key on any failure; ~Loader still frees the mapping through order_. loader_test: a parent imports fail_dep.dll, whose import table names a DLL outside the image. After the failed load neither name is found and a second load of either fails again (on the old code the dependency was still found). Co-Authored-By: Claude Opus 5.5 --- runtime/src/pe_loader.cpp | 21 +++++++++++++++------ runtime/test/loader_test.cpp | 21 +++++++++++++++++++++ 2 files changed, 36 insertions(+), 6 deletions(-) (limited to 'runtime/test/loader_test.cpp') diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index a59f9d0b1..6f19f5b2f 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -540,10 +540,19 @@ 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); - bind_imports(m); // loads every bundled module m imports first, so they land in init_order_ before m - protect_sections(m); - register_unwind(m); + Module* mapped = nullptr; + try { + mapped = &map_image(image); + bind_imports(*mapped); // loads every bundled module m imports first, so they land in init_order_ before m + protect_sections(*mapped); + register_unwind(*mapped); + } catch (...) { + // A failed load, nested ones (a dependency of a run-time load) included, must not stay findable by name: + // a later lookup would get a half-mapped image with unbound imports. ~Loader still frees it through order_. + by_name_.erase(key); + throw; + } + Module& m = *mapped; init_order_.push_back(&m); if (startup_trace::enabled()) startup_trace::event("map", "\"module\":" + startup_trace::quote(m.name) + @@ -598,8 +607,8 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, 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_. + // load() drops a module that failed to map or bind (dependencies included); this also drops one whose + // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via 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); diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 194174b00..c86ade637 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -783,6 +783,26 @@ void test_process_detach_dependencies() { g_live_modules.clear(); } +// A dependency whose import table is corrupt fails while the parent binds it. Neither must stay findable by name: +// a later load or GetModuleHandle would otherwise get a mapped image whose imports were never bound. +void test_failed_dependency_not_registered() { + const char* what = "a failed load leaves neither the module nor its failed dependency loaded"; + auto dep = make_import_image("kernel32.dll", "GetCurrentProcessId"); + reinterpret_cast(dep.data() + 0x200)->Name = 0x5000; // past SizeOfImage + const auto dep_path = write_image_as(dep, "fail_dep.dll"); + const auto parent_path = write_image_as(make_import_image("fail_dep.dll", "x"), "fail_parent.dll"); + rt::Loader loader(g_dir); + auto throws = [&](const std::filesystem::path& p) { + try { loader.load(p); return false; } catch (const std::exception&) { return true; } + }; + if (!throws(parent_path)) return failed(what, "the parent loaded over a corrupt dependency"); + if (loader.find_loaded_module("fail_dep.dll") || loader.find_loaded_module("fail_parent.dll")) + return failed(what, "a failed module is still found by name"); + if (!throws(dep_path)) return failed(what, "a second load of the dependency returned the half-loaded module"); + if (!throws(parent_path)) return failed(what, "a second load of the parent returned the half-loaded module"); + pass(what); +} + void test_forwarded_exports() { { const char* what = "a forwarded export binds to its target instead of into the string"; @@ -1106,6 +1126,7 @@ int main() { test_process_detach_invalid_tls(); test_process_detach_without_entry(); test_process_detach_dependencies(); + test_failed_dependency_not_registered(); test_delay_descriptor_fields(); test_forwarded_exports(); test_export_bounds(); -- cgit v1.2.3 From cc4799abdd73f4983e4e89f6586bf081083bb3e9 Mon Sep 17 00:00:00 2001 From: Ash Hopkins Date: Sun, 22 Nov 2026 19:26:59 +0000 Subject: runtime tests: synthetic fixed-base images take a base that is free under arm64 Wine loader_test, test_pe_loader_bounds and unimplemented_policy_test build relocation-less images fixed at 0x140000000..0x1a0000000. Under arm64 Wine (CrossOver on Apple Silicon) the process's own allocations sit at 0x100000000 and up and macOS maps its shared region at 0x180000000 (RT-22), so the loader rejected those images with "preferred base is taken" before the checks ran: loader stopped after 31 checks with 3 failures, pe_loader_bounds failed 13 checks and unimplemented_policy failed. New test/free_image_base.h: on Windows it returns the constants unchanged. Under Wine (ntdll exports wine_get_version) it moves the whole 0x140000000..0x200000000 span to a free window picked top-down, away from the heap, so each constant keeps its offset and images loaded together still get different bases. The init image reads its TLS callback addresses from its own ImageBase instead of a constant. AI-assisted. No game files. --- runtime/test/free_image_base.h | 34 ++++++++++++++++++++++++++++++ runtime/test/loader_test.cpp | 14 ++++++------ runtime/test/test_pe_loader_bounds.cpp | 6 ++++-- runtime/test/unimplemented_policy_test.cpp | 3 ++- 4 files changed, 47 insertions(+), 10 deletions(-) create mode 100644 runtime/test/free_image_base.h (limited to 'runtime/test/loader_test.cpp') diff --git a/runtime/test/free_image_base.h b/runtime/test/free_image_base.h new file mode 100644 index 000000000..4cc61493b --- /dev/null +++ b/runtime/test/free_image_base.h @@ -0,0 +1,34 @@ +#pragma once + +// A preferred base for a synthetic test image without relocations, so the loader can map it where it asks. +// +// The tests fix their images at bases from 0x140000000 (the usual EXE base) up to 0x1a0000000 (DLLs). On Windows +// that whole span is free, and free_image_base() returns the constants unchanged. Under arm64 Wine (CrossOver on +// Apple Silicon) the process's own allocations sit at 0x100000000 and up and macOS maps its shared region at +// 0x180000000 (RT-22), so such an image is rejected with "preferred base is taken" before a test checks what it is +// about, and the span can be free when a test starts and taken by Wine's own allocations a few tests later. Under +// Wine the span is therefore moved as a whole to a free window the system picks top-down, away from where the heap +// grows: each constant keeps its offset, so images loaded together still get different bases. +#include + +#include + +namespace leonida_test { + +inline std::uint64_t free_image_base(std::uint64_t preferred) { + constexpr std::uint64_t kFirst = 0x140000000, kEnd = 0x200000000; + if (preferred < kFirst || preferred >= kEnd) return preferred; + static const std::uint64_t window = [] { + constexpr SIZE_T size = kEnd - kFirst; + const HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); + if (!ntdll || !GetProcAddress(ntdll, "wine_get_version")) return kFirst; // Windows: the constants + if (void* p = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_TOP_DOWN, PAGE_NOACCESS)) { + VirtualFree(p, 0, MEM_RELEASE); + return reinterpret_cast(p); // 64 KiB aligned, as an image base must be + } + return kFirst; + }(); + return window + (preferred - kFirst); +} + +} // namespace leonida_test diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 194174b00..bcfb1605e 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -20,6 +20,7 @@ #include "../shims/shims.h" #include "../src/pe_loader.h" +#include "free_image_base.h" namespace { @@ -56,7 +57,7 @@ std::vector make_image() { nt->FileHeader.NumberOfSections = 1; nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64); nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC; - nt->OptionalHeader.ImageBase = 0x140000000; + nt->OptionalHeader.ImageBase = leonida_test::free_image_base(0x140000000); nt->OptionalHeader.AddressOfEntryPoint = 0x1000; nt->OptionalHeader.SizeOfHeaders = 0x200; nt->OptionalHeader.SizeOfImage = 0x2000; @@ -101,7 +102,7 @@ std::filesystem::path write_image_as(const std::vector& bytes, const st std::vector make_forwarder_image(const char* target, uint64_t image_base) { auto img = make_image(); std::fill(img.begin() + 0x200, img.begin() + 0x400, uint8_t{0}); // real tables end in a zero descriptor - nt_of(img)->OptionalHeader.ImageBase = image_base; + nt_of(img)->OptionalHeader.ImageBase = leonida_test::free_image_base(image_base); auto* ed = reinterpret_cast(img.data() + 0x200); ed->Base = 1; ed->NumberOfFunctions = 1; @@ -447,8 +448,6 @@ void emit_store_stub(std::vector& img, size_t off, uint64_t addr, uint3 img[n++] = 0xC3; } -constexpr uint64_t kInitBase = 0x140000000; - // make_image() plus a TLS directory and an entry point, both aimed at real machine code: a stub that stores a // sentinel in this process, so the test can tell a callback ran rather than only that it was parsed. std::vector make_init_image() { @@ -456,7 +455,8 @@ std::vector make_init_image() { auto* nt = nt_of(img); nt->FileHeader.Characteristics |= IMAGE_FILE_DLL; nt->OptionalHeader.AddressOfEntryPoint = 0x1040; - auto va = [](uint32_t rva) { return kInitBase + rva; }; + const uint64_t base = nt->OptionalHeader.ImageBase; // the TLS callback addresses below are absolute + auto va = [base](uint32_t rva) { return base + rva; }; constexpr size_t text = 0x200; // file offset of RVA 0x1000 emit_store_stub(img, text + 0x00, reinterpret_cast(&g_tls_ran), 1, 0); emit_store_stub(img, text + 0x40, reinterpret_cast(&g_main_ran), 2, 1); @@ -533,7 +533,7 @@ void test_initialise_rejects() { { auto img = make_init_image(); auto* callbacks = reinterpret_cast(img.data() + 0x290); // file offset of RVA 0x1090 - callbacks[0] = kInitBase + 0x9000; // well past SizeOfImage + callbacks[0] = nt_of(img)->OptionalHeader.ImageBase + 0x9000; // well past SizeOfImage expect_init_rejects("a TLS callback outside the image is rejected", img); } { @@ -731,7 +731,7 @@ void test_process_detach_without_entry() { reset_notifications(); auto first = make_lifecycle_image(); auto second = make_image(); - nt_of(second)->OptionalHeader.ImageBase = 0x180000000; + nt_of(second)->OptionalHeader.ImageBase = leonida_test::free_image_base(0x180000000); nt_of(second)->FileHeader.Characteristics |= IMAGE_FILE_DLL; emit_jump_stub(second, 0x200, reinterpret_cast(&observe_dllmain)); void* first_base = nullptr; diff --git a/runtime/test/test_pe_loader_bounds.cpp b/runtime/test/test_pe_loader_bounds.cpp index 5055df312..bc64c7f5d 100644 --- a/runtime/test/test_pe_loader_bounds.cpp +++ b/runtime/test/test_pe_loader_bounds.cpp @@ -20,6 +20,8 @@ #include "pe_loader.h" #endif +#include "free_image_base.h" + #if __has_include("../shims/shims.h") #include "../shims/shims.h" #elif __has_include("shims.h") @@ -159,7 +161,7 @@ std::vector make_base_image(uint32_t image_size = 0x2000, uint32_t file nt->FileHeader.NumberOfSections = 1; nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64); nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC; - nt->OptionalHeader.ImageBase = 0x140000000; + nt->OptionalHeader.ImageBase = leonida_test::free_image_base(0x140000000); nt->OptionalHeader.AddressOfEntryPoint = 0x1000; nt->OptionalHeader.SizeOfHeaders = 0x200; nt->OptionalHeader.SizeOfImage = image_size; @@ -736,7 +738,7 @@ void test_forwarder_ordinal_range() { auto dll = make_base_image(0x2000, 0x400); std::fill(dll.begin() + 0x200, dll.end(), uint8_t{0}); auto* dnt = nt_header_of(dll); - dnt->OptionalHeader.ImageBase = 0x150000000ull; + dnt->OptionalHeader.ImageBase = leonida_test::free_image_base(0x150000000ull); dnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT] = {0x1000, 0x100}; auto* ed = reinterpret_cast(dll.data() + 0x200); // RVA 0x1000 ed->Base = 1; diff --git a/runtime/test/unimplemented_policy_test.cpp b/runtime/test/unimplemented_policy_test.cpp index 3bacf40a0..77a6e5595 100644 --- a/runtime/test/unimplemented_policy_test.cpp +++ b/runtime/test/unimplemented_policy_test.cpp @@ -27,6 +27,7 @@ #include "../shims/shims.h" #include "../src/pe_loader.h" +#include "free_image_base.h" namespace { @@ -73,7 +74,7 @@ std::vector make_image() { nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64); nt->FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL | IMAGE_FILE_LARGE_ADDRESS_AWARE; nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC; - nt->OptionalHeader.ImageBase = 0x180000000; + nt->OptionalHeader.ImageBase = leonida_test::free_image_base(0x180000000); nt->OptionalHeader.AddressOfEntryPoint = 0; nt->OptionalHeader.SizeOfHeaders = 0x200; nt->OptionalHeader.SizeOfImage = 0x2000; -- cgit v1.2.3 From c9e08f9f1a509d4cabcdf36fa5e225d3eaefead1 Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 20:48:35 +0100 Subject: fix(loader): leave empty named exports unresolved --- runtime/src/pe_loader.cpp | 1 + runtime/test/loader_test.cpp | 51 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) (limited to 'runtime/test/loader_test.cpp') diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index a59f9d0b1..2400536d0 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -929,6 +929,7 @@ void Loader::parse_exports(Module& m) { // into the string, so forwarders are kept apart and followed when an import asks for one. const uint64_t dir_begin = dir.VirtualAddress, dir_end = dir_begin + dir.Size; auto add_export = [&](const std::string& key, uint32_t rva) { + if (!rva) return; // An unused address-table slot is absent even when a name refers to it. 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 diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 194174b00..a0d0eaa36 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -359,6 +359,56 @@ void test_exports() { } } +void test_empty_named_export() { + const char* what = "an empty named export stays unresolved without hiding valid exports"; + auto img = make_forwarder_image("KERNEL32.GetCurrentProcessId", 0x180000000); + auto* ed = reinterpret_cast(img.data() + 0x200); + ed->NumberOfFunctions = 3; + ed->NumberOfNames = 3; + nt_of(img)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size = 0x1A0; + auto* funcs = reinterpret_cast(img.data() + 0x300); + funcs[1] = 0; + funcs[2] = 0x11C0; // a code export outside the export directory + auto* names = reinterpret_cast(img.data() + 0x320); + names[0] = 0x1188; + names[1] = 0x1180; + names[2] = 0x1190; + auto* ords = reinterpret_cast(img.data() + 0x340); + ords[0] = 1; + ords[1] = 0; + ords[2] = 2; + std::memcpy(img.data() + 0x388, "empty\0", 6); + std::memcpy(img.data() + 0x390, "valid\0", 6); + auto provider = write_image_as(img, "empty_exports.dll"); + try { + rt::Loader loader(g_dir); + rt::Module& m = loader.load(provider); + for (const char* sym : {"empty", "#2"}) { + bool owns = false; + if (m.exports.count(sym) || m.forwarders.count(sym) || + loader.resolve_module_export(m.base, sym, owns) || !owns) + return failed(what, std::string(sym) + " did not remain absent from the mapped module"); + } + for (const char* sym : {"valid", "#3", "fwd", "#1"}) { + bool owns = false; + void* expected = (std::strcmp(sym, "valid") == 0 || std::strcmp(sym, "#3") == 0) + ? m.base + 0x11C0 : host_symbol("kernel32.dll", "GetCurrentProcessId"); + if (!expected || loader.resolve_module_export(m.base, sym, owns) != expected || !owns) + return failed(what, std::string(sym) + " no longer resolves to its valid target"); + } + auto importer = write_image_as(make_import_image("empty_exports.dll", "empty"), "empty_import.exe"); + rt::Module& importing = loader.load(importer); + if (importing.imports.size() != 1 || importing.imports[0].binding != rt::Binding::Unimplemented) + return failed(what, "an import of the empty slot did not bind as unimplemented"); + void* bound = *reinterpret_cast(importing.base + 0x1180); + if (!bound || bound == m.base) + return failed(what, "the empty import was not given a failure thunk"); + pass(what); + } catch (const std::exception& e) { + failed(what, e.what()); + } +} + void test_imports() { { auto img = make_image(); @@ -1098,6 +1148,7 @@ int main() { test_truncation(); test_relocations(); test_exports(); + test_empty_named_export(); test_imports(); test_delay_imports(); test_initialise(); -- cgit v1.2.3