From 16e759141996df21526249ad2ae8b744c9bc54fc Mon Sep 17 00:00:00 2001 From: SHAURYASANYAL3 Date: Sun, 22 Nov 2026 11:55:36 +0530 Subject: runtime: thunk deduplication, XGameRuntime shims, PE loader long paths, and drive-root packaging --- runtime/src/pe_loader.cpp | 17 ++++++++++++++--- 1 file changed, 14 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 ef6fab7a8..d865e4179 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -77,9 +77,20 @@ struct TlsHostModule { TlsHostModule load_tls_host() { TlsHostModule host; - wchar_t exe[MAX_PATH] = {}; - if (!GetModuleFileNameW(nullptr, exe, MAX_PATH)) return host; - const std::filesystem::path path = std::filesystem::path(exe).parent_path() / L"gta6rt_tls_host.dll"; + // Dynamic buffer loop for paths that exceed MAX_PATH + std::wstring exe_path; + DWORD size = MAX_PATH; + while (true) { + exe_path.resize(size); + DWORD len = GetModuleFileNameW(nullptr, exe_path.data(), size); + if (len == 0) return host; + if (len < size - 1) { + exe_path.resize(len); + break; + } + size *= 2; + } + const std::filesystem::path path = std::filesystem::path(exe_path).parent_path() / L"gta6rt_tls_host.dll"; // The helper is linked with the static CRT (/MT), so it needs only system DLLs. Restricting the dependency search // to System32 keeps a game-supplied vcruntime next to the executable from being picked up. host.module = LoadLibraryExW(path.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); -- cgit v1.2.3 From 236b0acec3891b773ead57d3113b2f469d0e4a9f Mon Sep 17 00:00:00 2001 From: quackottu <224479491+quackottu@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:48:35 +0530 Subject: pe_loader: honour NumberOfRvaAndSizes, and refuse a forwarder ordinal past 65535 Data directories past NumberOfRvaAndSizes were read anyway (only the exception directory checked the count), so stale bytes there were parsed as import, delay-import, export or relocation tables. And resolve_forwarder range-checked the ordinal before adding each digit, so '#65537' passed and was cast to ordinal 1. The hand-built test images now declare their 16 directories. --- runtime/src/pe_loader.cpp | 21 +++++---- runtime/test/loader_test.cpp | 1 + runtime/test/test_pe_loader_bounds.cpp | 68 ++++++++++++++++++++++++++++++ runtime/test/unimplemented_policy_test.cpp | 1 + 4 files changed, 83 insertions(+), 8 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index ef6fab7a8..e82cee3ed 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -47,6 +47,11 @@ std::string read_string(const std::string& name, uint8_t* base, uint32_t image_s return {s, end}; } +// PE/COFF: NumberOfRvaAndSizes counts the data directories; entries past it are not directories, whatever they hold. +IMAGE_DATA_DIRECTORY directory(const IMAGE_NT_HEADERS64* nt, unsigned index) { + return index < nt->OptionalHeader.NumberOfRvaAndSizes ? nt->OptionalHeader.DataDirectory[index] : IMAGE_DATA_DIRECTORY{}; +} + // The TLS directory holds virtual addresses, which relocations have already moved to this mapping. uint64_t rva_in(const Module& m, uint64_t va, const char* what) { const uint64_t base = reinterpret_cast(m.base); @@ -190,8 +195,7 @@ Module& Loader::load(const std::filesystem::path& image) { // allowed. No entry in that set uses the indirect form (UnwindData bit 0). void Loader::register_unwind(Module& m) { auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); - if (nt->OptionalHeader.NumberOfRvaAndSizes <= IMAGE_DIRECTORY_ENTRY_EXCEPTION) return; - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION]; + const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXCEPTION); // Like the system loader, a trailing partial entry is ignored. const uint32_t count = dir.Size / sizeof(RUNTIME_FUNCTION); if (!count) return; @@ -276,7 +280,7 @@ Module& Loader::map_image(const std::filesystem::path& path) { m->base = static_cast( VirtualAlloc(reinterpret_cast(oh.ImageBase), oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); if (!m->base) { - auto& relocs = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; + const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); if (!relocs.Size) throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations"); m->base = static_cast(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); @@ -297,7 +301,7 @@ Module& Loader::map_image(const std::filesystem::path& path) { int64_t delta = reinterpret_cast(m->base) - static_cast(oh.ImageBase); if (delta) { m->relocated = true; - auto& dir = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; + const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); if (!dir.Size) throw std::runtime_error(m->name + ": the image has no relocations and isn't at its base"); require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); auto* block = at(m->base, dir.VirtualAddress); @@ -455,7 +459,7 @@ void Loader::run_tls_callbacks(Module& m, uint32_t reason) { void Loader::parse_exports(Module& m) { auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; + const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXPORT); if (!dir.Size) return; require_range(m.name, dir.VirtualAddress, sizeof(IMAGE_EXPORT_DIRECTORY), m.size, "the export directory"); auto* ed = at(m.base, dir.VirtualAddress); @@ -509,8 +513,9 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d uint32_t ordinal = 0; if (by_ordinal) { for (size_t i = 1; i < symbol.size(); ++i) { - if (symbol[i] < '0' || symbol[i] > '9' || ordinal > 0xFFFF) return nullptr; + if (symbol[i] < '0' || symbol[i] > '9') return nullptr; ordinal = ordinal * 10 + static_cast(symbol[i] - '0'); + if (ordinal > 0xFFFF) return nullptr; // checked after the digit, so "#65537" can't truncate to 1 } } @@ -595,7 +600,7 @@ void Loader::bind_imports(Module& m) { } }; - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; + const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_IMPORT); if (dir.Size) { for (uint64_t i = 0;; ++i) { uint64_t rva = dir.VirtualAddress + i * sizeof(IMAGE_IMPORT_DESCRIPTOR); @@ -608,7 +613,7 @@ void Loader::bind_imports(Module& m) { } } // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. - auto& ddir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT]; + const auto ddir = directory(nt, IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT); if (ddir.Size) { for (uint64_t i = 0;; ++i) { uint64_t rva = ddir.VirtualAddress + i * sizeof(IMAGE_DELAYLOAD_DESCRIPTOR); diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 5ee203e28..84ade94b0 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -61,6 +61,7 @@ std::vector make_image() { nt->OptionalHeader.SizeOfHeaders = 0x200; nt->OptionalHeader.SizeOfImage = 0x2000; nt->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI; + nt->OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES; auto* sec = IMAGE_FIRST_SECTION(nt); std::memcpy(sec->Name, ".text", 6); sec->VirtualAddress = 0x1000; diff --git a/runtime/test/test_pe_loader_bounds.cpp b/runtime/test/test_pe_loader_bounds.cpp index 3275000e0..e510f9ad4 100644 --- a/runtime/test/test_pe_loader_bounds.cpp +++ b/runtime/test/test_pe_loader_bounds.cpp @@ -717,6 +717,72 @@ void test_highlow_relocations() { if (hold) VirtualFree(hold, 0, MEM_RELEASE); } +// PE/COFF spec, optional header: NumberOfRvaAndSizes is "the number of data-directory entries in the remainder of +// the optional header". Entries past it are not directories, whatever bytes they hold. +void test_directory_count() { + std::printf("\n--- NumberOfRvaAndSizes bounds the data directories ---\n"); + auto img = make_base_image(0x2000, 0x400); + auto* nt = nt_header_of(img); + nt->OptionalHeader.NumberOfRvaAndSizes = IMAGE_DIRECTORY_ENTRY_IMPORT; // only the export entry is a directory + nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] = {0xFFFFF000u, sizeof(IMAGE_IMPORT_DESCRIPTOR)}; + nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT] = {0xFFFFF000u, 0x20}; + expect_loader_success("Stale entries past NumberOfRvaAndSizes are not read as directories", img); +} + +// A forwarder "kernel32.#65537" names an ordinal no export table can hold (ordinals are 16 bits). It must not be +// truncated to ordinal 1 and bound to whatever kernel32 exports there. +void test_forwarder_ordinal_range() { + std::printf("\n--- Forwarder ordinal range ---\n"); + 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.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT] = {0x1000, 0x100}; + auto* ed = reinterpret_cast(dll.data() + 0x200); // RVA 0x1000 + ed->Base = 1; + ed->NumberOfFunctions = 1; + ed->NumberOfNames = 1; + ed->AddressOfFunctions = 0x1040; + ed->AddressOfNames = 0x1050; + ed->AddressOfNameOrdinals = 0x1060; + const uint32_t forwarder_rva = 0x1080, name_rva = 0x10C0; + std::memcpy(dll.data() + 0x240, &forwarder_rva, 4); + std::memcpy(dll.data() + 0x250, &name_rva, 4); + std::memcpy(dll.data() + 0x280, "kernel32.#65537", 16); + std::memcpy(dll.data() + 0x2C0, "F", 2); + { + std::ofstream out(g_temp_dir / "fwd_ord.dll", std::ios::binary); + out.write(reinterpret_cast(dll.data()), static_cast(dll.size())); + } + + auto exe = make_base_image(0x2000, 0x400); + std::fill(exe.begin() + 0x200, exe.end(), uint8_t{0}); + auto* ent = nt_header_of(exe); + ent->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] = {0x1000, 2 * sizeof(IMAGE_IMPORT_DESCRIPTOR)}; + auto* d = reinterpret_cast(exe.data() + 0x200); + d->OriginalFirstThunk = 0x1040; + d->Name = 0x1080; + d->FirstThunk = 0x1060; + const uint64_t hint_name = 0x1090; + std::memcpy(exe.data() + 0x240, &hint_name, 8); + std::memcpy(exe.data() + 0x260, &hint_name, 8); + std::memcpy(exe.data() + 0x280, "fwd_ord.dll", 12); + std::memcpy(exe.data() + 0x292, "F", 2); // after the 2-byte hint + + auto path = write_temp_image(exe); + try { + rt::Loader loader(g_temp_dir); + rt::Module& m = loader.load(path); + const bool one = m.imports.size() == 1; + check_condition(one && m.imports[0].binding == rt::Binding::Unimplemented, + "Forwarder to ordinal 65537 is not truncated to a host ordinal", + one ? "bound as " + std::to_string(static_cast(m.imports[0].binding)) + : std::to_string(m.imports.size()) + " imports"); + } catch (const std::exception& e) { + fail("Forwarder to ordinal 65537 is not truncated to a host ordinal", e.what()); + } +} + } // namespace int main() { @@ -735,6 +801,8 @@ int main() { test_virtual_address_range_wrapping(); test_boundary_exact_fits(); test_highlow_relocations(); + test_directory_count(); + test_forwarder_ordinal_range(); } catch (const std::exception& e) { std::printf("FATAL: Unhandled exception during test execution: %s\n", e.what()); ++g_failures; diff --git a/runtime/test/unimplemented_policy_test.cpp b/runtime/test/unimplemented_policy_test.cpp index ec21dd6b7..c09a3b88b 100644 --- a/runtime/test/unimplemented_policy_test.cpp +++ b/runtime/test/unimplemented_policy_test.cpp @@ -78,6 +78,7 @@ std::vector make_image() { nt->OptionalHeader.SizeOfHeaders = 0x200; nt->OptionalHeader.SizeOfImage = 0x2000; nt->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI; + nt->OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES; auto* sec = IMAGE_FIRST_SECTION(nt); std::memcpy(sec->Name, ".text", 6); sec->VirtualAddress = kTextRva; -- cgit v1.2.3 From cc7651422956d1f362bdf32f900e543b357056eb Mon Sep 17 00:00:00 2001 From: farhat Date: Sun, 22 Nov 2026 14:56:45 +0700 Subject: fix(runtime): detach initialised PE modules before unmapping them Deliver TLS and DllMain process-detach notifications in reverse dependency order while every mapped image and TLS block is still live. This lets mapped DLLs unregister FLS callbacks before their code is freed. Cover failed attach, map-only loads, partial initialisation, teardown ordering and malformed TLS tables with synthetic PE tests. --- runtime/README.md | 5 +- runtime/src/pe_loader.cpp | 20 ++++ runtime/src/pe_loader.h | 11 +- runtime/test/loader_test.cpp | 243 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 273 insertions(+), 6 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/README.md b/runtime/README.md index 796bf897d..5d2495dfd 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -41,7 +41,10 @@ code from the mapped images runs. TLS reserves its module index through the runt `gta6rt --init ` runs the same mapping and then `Loader::initialise()`: each module's TLS callbacks and each DLL's `DllMain(DLL_PROCESS_ATTACH)`, dependencies first. An EXE's entry point is not -run. +run. When the loader is destroyed, initialised modules receive TLS callbacks and DLL entry-point calls with +`DLL_PROCESS_DETACH`, in reverse initialisation order. All mapped images, unwind tables and static TLS stay +available until these notifications finish, so DLLs can release resources such as FLS callbacks safely. The reserved +argument is null (explicit unload). A map-only load receives no detach notifications. `--dry-run`, `--init` and `--run` are separate modes: give exactly one. Two together (`--dry-run --run`) print the usage and exit 2 before anything is mapped. diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index d865e4179..e1ebfe01f 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -161,6 +161,26 @@ Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) } Loader::~Loader() { + // Importers must release their resources before their dependencies. Keep every mapping, unwind table and TLS + // block alive throughout the notifications: a detach handler can still call an imported function or free an + // FLS slot whose destructor lives in another mapped image. + for (auto it = init_order_.rbegin(); it != init_order_.rend(); ++it) { + Module& m = **it; + if (!m.initialised) continue; // a map-only load never opts in to running image code + m.initialised = false; + try { + run_tls_callbacks(m, DLL_PROCESS_DETACH); + } catch (const std::exception& e) { + // A module may have changed its callback table since attach. A destructor cannot propagate the validation + // error; report it and still let DllMain release resources before the image is freed. + std::fprintf(stderr, "[rt] TLS process detach failed for %s: %s\n", m.name.c_str(), e.what()); + } + auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); + if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { + auto entry = reinterpret_cast(m.base + m.entry_rva); + entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored + } + } shims::remove_module_lookup(this); for (auto* m : order_) { // TLS state must go away before the image and its TLS block are unmapped. diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index ebcf411ec..6d6c94751 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -1,8 +1,8 @@ // Native PE mapper for Xbox Series (x86-64) images. // Maps an image, applies relocations, binds every import through the shim registry, registers its unwind table and // installs static TLS for the calling thread. -// Mapping never runs code from the image. Loader::initialise() is the one call that does: it sets up the module's TLS -// (slot, template and callbacks) and calls a DLL's entry point as DllMain. +// Mapping never runs code from the image. Loader::initialise() delivers process attach to TLS callbacks and DllMain; +// ~Loader() delivers process detach before unmapping initialised modules. The TLS slot and template are set up by load(). // gta6rt_tls_host.dll must sit next to the executable; the loader reuses the module TLS index the OS assigns it. #pragma once #include @@ -65,8 +65,9 @@ public: explicit Loader(std::filesystem::path game_dir); Loader(const Loader&) = delete; Loader& operator=(const Loader&) = delete; - // Restores the TLS slot for the calling thread. Destroy the Loader on the thread - // that called load() while any mapped TLS module is still live. + // Delivers process detach to initialised modules in reverse dependency order before freeing any mappings or TLS. + // Restores the TLS slot for the calling thread. Destroy the Loader on the thread that called load() while any + // mapped TLS module is still live; all other threads executing mapped code must have finished first. ~Loader(); // Loads an image and (recursively) the bundled modules it imports. Throws std::runtime_error on failure. @@ -86,7 +87,7 @@ public: void initialise(); // Calls the image's IMAGE_TLS_DIRECTORY64 callbacks in order with (base, reason, nullptr). This is opt-in: - // load() never runs image code, and initialise() is the only call inside the Loader that uses it. No-op for + // load() never runs image code; initialise() and ~Loader() use it for process attach/detach. No-op for // images without TLS callbacks. The loader does not deliver thread attach/detach events: install the thread's // TLS first, then call this with DLL_THREAD_ATTACH/DETACH, and uninstall after the detach callbacks. void run_tls_callbacks(Module& m, uint32_t reason); diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 5ee203e28..f946b9ae5 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -543,6 +543,245 @@ void test_initialise_rejects() { } } +// The images below jump to host observers so notifications remain observable after the mappings are freed. +// The FLS destructor itself starts in mapped code: leaving it registered would call unmapped memory at exit. +void emit_jump_stub(std::vector& img, size_t off, uint64_t target) { + img[off++] = 0x48; + img[off++] = 0xB8; // movabs rax, target; jmp rax (preserves the notification arguments) + std::memcpy(img.data() + off, &target, sizeof(target)); + off += sizeof(target); + img[off++] = 0xFF; + img[off] = 0xE0; +} + +struct Notification { + void* base; + DWORD reason; + bool tls; + bool operator==(const Notification&) const = default; +}; +std::vector g_notifications; +struct LiveImage { + void* base; + uint32_t tls_index; + void* tls_block; +}; +std::vector g_live_modules; +bool g_detach_state_live = true; +bool g_fail_attach = false; +bool g_use_fls = false; +DWORD g_fls_index = FLS_OUT_OF_INDEXES; +int g_fls_callbacks = 0; + +void observe_notification(void* base, DWORD reason, void* reserved, bool tls) { + g_notifications.push_back({base, reason, tls}); + if (reserved) g_detach_state_live = false; + if (reason != DLL_PROCESS_DETACH) return; + for (const auto& m : g_live_modules) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(m.base, &info, sizeof(info)) || info.State != MEM_COMMIT) + g_detach_state_live = false; + if (m.tls_index != rt::kNoTlsIndex && m.tls_block) { + auto** slots = reinterpret_cast(__readgsqword(0x58)); + if (slots[m.tls_index] != m.tls_block || + !VirtualQuery(m.tls_block, &info, sizeof(info)) || info.State != MEM_COMMIT || + std::memcmp(m.tls_block, "TLS!", 4) != 0) + g_detach_state_live = false; + } + } +} + +void NTAPI observe_tls(void* base, DWORD reason, void* reserved) { + observe_notification(base, reason, reserved, true); +} + +void NTAPI observe_fls(void* value) { + if (value == reinterpret_cast(1)) ++g_fls_callbacks; +} + +BOOL NTAPI observe_dllmain(void* base, DWORD reason, void* reserved) { + observe_notification(base, reason, reserved, false); + if (g_use_fls) { + if (reason == DLL_PROCESS_ATTACH) { + g_fls_index = FlsAlloc(reinterpret_cast(static_cast(base) + 0x1100)); + if (g_fls_index == FLS_OUT_OF_INDEXES || !FlsSetValue(g_fls_index, reinterpret_cast(1))) + return FALSE; + } else if (reason == DLL_PROCESS_DETACH && g_fls_index != FLS_OUT_OF_INDEXES) { + if (!FlsFree(g_fls_index)) g_detach_state_live = false; + g_fls_index = FLS_OUT_OF_INDEXES; + } + } + return !(reason == DLL_PROCESS_ATTACH && g_fail_attach); +} + +void reset_notifications() { + g_notifications.clear(); + g_live_modules.clear(); + g_detach_state_live = true; + g_fail_attach = false; + g_use_fls = false; + g_fls_callbacks = 0; +} + +void expect_notifications(const char* what, const std::vector& expected) { + if (g_notifications == expected) pass(what); + else failed(what, "unexpected TLS/DllMain notification count or order"); +} + +std::vector make_lifecycle_image() { + auto img = make_init_image(); + emit_jump_stub(img, 0x200, reinterpret_cast(&observe_tls)); + emit_jump_stub(img, 0x240, reinterpret_cast(&observe_dllmain)); + emit_jump_stub(img, 0x300, reinterpret_cast(&observe_fls)); + return img; +} + +void test_process_detach() { + // A map-only load must remain free of image-code execution, including at destruction. + reset_notifications(); + { + rt::Loader loader(g_dir); + loader.load(write_image(make_lifecycle_image())); + } + expect_notifications("a never-initialised image receives no detach notifications", {}); + + for (bool fail_attach : {false, true}) { + reset_notifications(); + g_fail_attach = fail_attach; + g_use_fls = true; + void* base = nullptr; + bool rejected = false; + { + rt::Loader loader(g_dir); + auto& m = loader.load(write_image(make_lifecycle_image())); + base = m.base; + g_live_modules = {{m.base, m.tls_index, m.tls_block}}; + try { + loader.initialise(); + loader.initialise(); // successful attach is delivered once + } catch (const std::runtime_error&) { + rejected = true; + } + } + if (rejected == fail_attach) pass("attach success/failure is preserved"); + else failed("attach success/failure is preserved", "unexpected initialise result"); + expect_notifications(fail_attach ? "a FALSE attach is detached once" : "TLS and DllMain detach once after attach", + {{base, DLL_PROCESS_ATTACH, true}, {base, DLL_PROCESS_ATTACH, false}, + {base, DLL_PROCESS_DETACH, true}, {base, DLL_PROCESS_DETACH, false}}); + if (g_detach_state_live && g_fls_callbacks == 1 && g_fls_index == FLS_OUT_OF_INDEXES) + pass("detach frees FLS while the callback image and static TLS are live"); + else + failed("detach frees FLS while the callback image and static TLS are live", "FLS cleanup missing or state freed early"); + // Keep a failing negative-control run from crashing during process exit after reporting the regression. + if (g_fls_index != FLS_OUT_OF_INDEXES) { + FlsSetValue(g_fls_index, nullptr); + FlsFree(g_fls_index); + g_fls_index = FLS_OUT_OF_INDEXES; + } + } + g_live_modules.clear(); + g_use_fls = false; +} + +void test_process_detach_invalid_tls() { + reset_notifications(); + g_use_fls = true; + void* base = nullptr; + { + rt::Loader loader(g_dir); + auto& m = loader.load(write_image(make_lifecycle_image())); + base = m.base; + loader.initialise(); + // The callback table is writable in a normal PE, but this synthetic image keeps it in executable .text. + DWORD old_protection = 0; + if (!VirtualProtect(m.base + 0x1090, sizeof(uint64_t), PAGE_EXECUTE_READWRITE, &old_protection)) + throw std::runtime_error("cannot make the synthetic TLS callback table writable"); + *reinterpret_cast(m.base + 0x1090) = reinterpret_cast(m.base) + m.size; + DWORD ignored = 0; + if (!VirtualProtect(m.base + 0x1090, sizeof(uint64_t), old_protection, &ignored)) + throw std::runtime_error("cannot restore the synthetic TLS callback table protection"); + } + expect_notifications("invalid TLS detach still calls DllMain for cleanup", + {{base, DLL_PROCESS_ATTACH, true}, {base, DLL_PROCESS_ATTACH, false}, + {base, DLL_PROCESS_DETACH, false}}); + if (g_fls_callbacks == 1 && g_fls_index == FLS_OUT_OF_INDEXES) + pass("invalid TLS detach still frees the mapped FLS callback"); + else + failed("invalid TLS detach still frees the mapped FLS callback", "FLS cleanup missing"); + reset_notifications(); +} + +void test_process_detach_without_entry() { + for (bool is_dll : {false, true}) { + reset_notifications(); + auto img = make_lifecycle_image(); + if (is_dll) nt_of(img)->OptionalHeader.AddressOfEntryPoint = 0; + else nt_of(img)->FileHeader.Characteristics &= ~IMAGE_FILE_DLL; + void* base = nullptr; + { + rt::Loader loader(g_dir); + auto& m = loader.load(write_image(img)); + base = m.base; + loader.initialise(); + } + expect_notifications(is_dll ? "a DLL without an entry point still detaches TLS" : "an EXE detaches TLS without calling its entry point", + {{base, DLL_PROCESS_ATTACH, true}, {base, DLL_PROCESS_DETACH, true}}); + } + reset_notifications(); + auto first = make_lifecycle_image(); + auto second = make_image(); + nt_of(second)->OptionalHeader.ImageBase = 0x180000000; + nt_of(second)->FileHeader.Characteristics |= IMAGE_FILE_DLL; + emit_jump_stub(second, 0x200, reinterpret_cast(&observe_dllmain)); + void* first_base = nullptr; + { + rt::Loader loader(g_dir); + first_base = loader.load(write_image(first)).base; + loader.load(write_image(second)); + g_fail_attach = true; + try { + loader.initialise(); + failed("partial initialisation rejects the first DLL", "attach succeeded"); + } catch (const std::runtime_error&) { + pass("partial initialisation rejects the first DLL"); + } + } + expect_notifications("partial initialisation does not detach an untouched later DLL", + {{first_base, DLL_PROCESS_ATTACH, true}, {first_base, DLL_PROCESS_ATTACH, false}, + {first_base, DLL_PROCESS_DETACH, true}, {first_base, DLL_PROCESS_DETACH, false}}); + reset_notifications(); +} + +void test_process_detach_dependencies() { + reset_notifications(); + auto dep = make_forwarder_image("KERNEL32.GetCurrentProcessId", 0x180000000); + auto parent = make_import_image("detach_dep.dll", "fwd"); + for (auto* img : {&dep, &parent}) { + nt_of(*img)->FileHeader.Characteristics |= IMAGE_FILE_DLL; + nt_of(*img)->OptionalHeader.AddressOfEntryPoint = 0x11C0; + emit_jump_stub(*img, 0x3C0, reinterpret_cast(&observe_dllmain)); + } + write_image_as(dep, "detach_dep.dll"); + void* parent_base = nullptr; + void* dep_base = nullptr; + { + rt::Loader loader(g_dir); + auto& m = loader.load(write_image_as(parent, "detach_parent.dll")); + parent_base = m.base; + for (const auto* mod : loader.modules()) + g_live_modules.push_back({mod->base, mod->tls_index, mod->tls_block}); + dep_base = loader.initialisation_order().front()->base; + loader.initialise(); + loader.initialise(); + } + expect_notifications("dependencies attach first and detach last", + {{dep_base, DLL_PROCESS_ATTACH, false}, {parent_base, DLL_PROCESS_ATTACH, false}, + {parent_base, DLL_PROCESS_DETACH, false}, {dep_base, DLL_PROCESS_DETACH, false}}); + if (g_detach_state_live) pass("all dependency mappings remain live until notifications finish"); + else failed("all dependency mappings remain live until notifications finish", "a dependency was unmapped early"); + g_live_modules.clear(); +} + void test_forwarded_exports() { { const char* what = "a forwarded export binds to its target instead of into the string"; @@ -820,6 +1059,10 @@ int main() { test_delay_imports(); test_initialise(); test_initialise_rejects(); + test_process_detach(); + test_process_detach_invalid_tls(); + test_process_detach_without_entry(); + test_process_detach_dependencies(); test_delay_descriptor_fields(); test_forwarded_exports(); test_unwind_registration(); -- cgit v1.2.3