From 0ddf806359d30022a3152e61c93ed077212d25aa Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Mon, 23 Nov 2026 14:36:22 -0500 Subject: pe_loader: move an image with no relocation directory, refuse only on IMAGE_FILE_RELOCS_STRIPPED The loader refused any image whose preferred base was taken when it had no relocation directory. Windows' loader decides on the file header flag instead (LdrRelocateImage, the same in Wine's perform_relocations and ReactOS's LdrRelocateImageWithBias): IMAGE_FILE_RELOCS_STRIPPED set means the image cannot move and is refused (STATUS_CONFLICTING_ADDRESSES); with the flag clear and an empty directory the image is moved with nothing to fix up, as a second copy of such a DLL is. map_image now does the same, for an EXE and a DLL alike: it refuses to move a flag-set image (also one that has a relocation table, as Windows does), moves a flag-clear image without a directory and logs one "[rt] loader: ... moved ... with no relocations" line, so a move without fix-ups shows in traces. base_reservation::needed keeps reserving the main image's range for both kinds of image without relocations, and now also for a flag-set image with a table, so the main image keeps its base wherever it did before. The retail executable and every package DLL have a relocation table and the flag clear, so neither path applies to them. loader_test covers a flag-clear image moved when its base is held (it loads elsewhere, nothing is fixed up, its DllMain runs), the same image with the flag set (refused), the flag at a free base (maps), and the flag with a relocation table (refused). test_failed_dependency_not_registered's dependency shared its parent's base and was refused for that; it now fails on its corrupt import table, which is what the test describes. Co-Authored-By: Claude Opus 5.5 --- runtime/src/pe_loader.cpp | 22 ++++++++++++++-------- 1 file changed, 14 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 c29a288a9..253a773b5 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1425,10 +1425,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& if (!m->base) m->base = static_cast(VirtualAlloc(reinterpret_cast(oh.ImageBase), oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); - if (!m->base) { - 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"); + if (!m->base) { // whether the image may move is decided at the relocation step below m->base = static_cast(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); } @@ -1453,10 +1450,19 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& } int64_t delta = reinterpret_cast(m->base) - static_cast(oh.ImageBase); - if (delta) { - m->relocated = true; - 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"); + // Windows' loader (LdrRelocateImage) refuses to move an image only when IMAGE_FILE_RELOCS_STRIPPED is set; with the + // flag clear and no relocation directory it moves it and fixes up nothing, so the image is trusted to hold no + // absolute addresses. That move is logged so it shows in traces. base_reservation::needed still keeps the main + // image's range free when it has no relocation directory, so a main image is moved this way only where the + // range could not be had. + const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); + if (delta) m->relocated = true; + if (delta && (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)) + throw std::runtime_error(m->name + ": preferred base is taken and the image's relocations are stripped"); + if (delta && !dir.Size) + std::fprintf(stderr, "[rt] loader: %s: preferred base %#llx is taken, moved to %p with no relocations\n", + m->name.c_str(), static_cast(oh.ImageBase), static_cast(m->base)); + if (delta && dir.Size) { require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); auto* block = at(m->base, dir.VirtualAddress); auto* end = reinterpret_cast(block) + dir.Size; -- cgit v1.2.3 From ca56a0d5eff2f6217a593babcfaff87d46daa15d Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Mon, 23 Nov 2026 15:12:44 -0500 Subject: pe_loader: a relocation table is applied whatever RELOCS_STRIPPED says (Windows 11 measurement) Zombins2 measured the Windows 11 (26200) loader with synthetic x64 DLLs in #8847. An image with IMAGE_FILE_RELOCS_STRIPPED set and a relocation table was moved and fixed up when its base was taken. The previous commit refused that case, while main relocated it. That is now back to main's behaviour: a moved image with a table is fixed up whatever the flag says, and the flag refuses a move only when there is no table. base_reservation::needed is back to main's test (the directory size) and no longer reserves for a flag-set image with a table. The core change stays: with the flag clear and no relocation directory, the image is moved with nothing fixed up and the move is logged. That matches the measurement. Windows also refused flag-set DLLs without a relocation directory at a free base (error 487), and it is not known why. The loader keeps main's behaviour there and maps them at their base. runtime/README.md records this as an open question, and loader_test's check for it no longer claims Windows parity. The flag-with-table check now expects a move with the DIR64 fix-up applied. Co-Authored-By: Claude Opus 5.5 --- runtime/README.md | 9 +++++++-- runtime/src/base_reservation.h | 11 +++++------ runtime/src/pe_loader.cpp | 12 ++++++------ runtime/test/loader_test.cpp | 35 ++++++++++++++++++++++++++--------- 4 files changed, 44 insertions(+), 23 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/README.md b/runtime/README.md index b91689582..abe3e841b 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -133,8 +133,13 @@ with the seed on stderr; a seed of 0 uses a fixed non-zero state. Unset, the hos ## PE loader `src/pe_loader.cpp` maps x86-64 images at their preferred base, or elsewhere (with relocations) when -that base is taken. As on Windows, only `IMAGE_FILE_RELOCS_STRIPPED` refuses the move; an image with the flag -clear and no relocation directory is moved with nothing fixed up, and the loader logs that. It copies headers and +that base is taken. An image with a relocation table is moved and fixed up whatever `IMAGE_FILE_RELOCS_STRIPPED` +says; without one, the flag refuses the move, and an image with the flag clear is moved with nothing fixed up (the +loader logs that). The Windows 11 loader does the same in these three cases, as measured by Zombins2 with +synthetic DLLs ([#8847](https://github.com/ItsNotRexed/Leonida/pull/8847#issuecomment-7112587898)). Open +question from the same measurement: Windows also refused flag-set DLLs without a relocation directory at a free +preferred base (error 487, linker-built `/FIXED` DLLs included), and why is not known; the loader still maps those +at their base, as before. It copies headers and sections, applies `IMAGE_REL_BASED_DIR64` relocations, binds imports by name or ordinal, parses the export table, sets section protections, and registers the image's x64 unwind table (`.pdata`) with `RtlAddFunctionTable`, so exceptions raised in or passing diff --git a/runtime/src/base_reservation.h b/runtime/src/base_reservation.h index 485cf5917..5ccfe1aaa 100644 --- a/runtime/src/base_reservation.h +++ b/runtime/src/base_reservation.h @@ -63,10 +63,10 @@ inline void* commit_reserved(std::uint64_t base, std::uint64_t size) { } // The preferred range of `image` when it has no relocations and that range is not free in this process; nullopt -// when the image can be mapped as it is (or is not a readable PE32+, which the loader reports itself). "No -// relocations" is either IMAGE_FILE_RELOCS_STRIPPED, which the loader refuses to move, or an empty relocation -// directory with the flag clear, which it moves with nothing fixed up (as Windows does): that is right only for an -// image with no absolute addresses in it, so its range is kept free all the same. +// when the image can be mapped as it is (or is not a readable PE32+, which the loader reports itself). Without a +// relocation directory the loader refuses to move an image that has IMAGE_FILE_RELOCS_STRIPPED, and moves one with +// the flag clear with nothing fixed up: that is right only for an image with no absolute addresses in it, so its +// range is kept free either way. An image with a relocation table is moved and fixed up whatever the flag says. inline std::optional needed(const std::filesystem::path& image) { std::ifstream file(image, std::ios::binary); IMAGE_DOS_HEADER dos{}; @@ -78,8 +78,7 @@ inline std::optional needed(const std::filesystem::path& image) { !nt.OptionalHeader.SizeOfImage) return std::nullopt; const auto& oh = nt.OptionalHeader; - if (!(nt.FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED) && - oh.NumberOfRvaAndSizes > IMAGE_DIRECTORY_ENTRY_BASERELOC && + if (oh.NumberOfRvaAndSizes > IMAGE_DIRECTORY_ENTRY_BASERELOC && oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size) return std::nullopt; // relocatable: the loader moves it if the base is taken const Range r{oh.ImageBase, (static_cast(oh.SizeOfImage) + 0xffff) & ~std::uint64_t{0xffff}}; diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 253a773b5..1c6b91b54 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1450,14 +1450,14 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& } int64_t delta = reinterpret_cast(m->base) - static_cast(oh.ImageBase); - // Windows' loader (LdrRelocateImage) refuses to move an image only when IMAGE_FILE_RELOCS_STRIPPED is set; with the - // flag clear and no relocation directory it moves it and fixes up nothing, so the image is trusted to hold no - // absolute addresses. That move is logged so it shows in traces. base_reservation::needed still keeps the main - // image's range free when it has no relocation directory, so a main image is moved this way only where the - // range could not be had. + // A moved image with a relocation table is fixed up, whatever IMAGE_FILE_RELOCS_STRIPPED says. Without a table, + // the flag refuses the move; with the flag clear the image is moved and nothing is fixed up, so it is trusted to + // hold no absolute addresses. The Windows 11 loader does all three (measured in #8847); that move is logged so + // it shows in traces. base_reservation::needed still keeps the main image's range free when it has no + // relocation directory, so a main image is moved this way only where the range could not be had. const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); if (delta) m->relocated = true; - if (delta && (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)) + if (delta && !dir.Size && (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)) throw std::runtime_error(m->name + ": preferred base is taken and the image's relocations are stripped"); if (delta && !dir.Size) std::fprintf(stderr, "[rt] loader: %s: preferred base %#llx is taken, moved to %p with no relocations\n", diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index a49a75385..926becd12 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -654,10 +654,11 @@ void test_initialise_rejects() { } } -// An image with no relocation directory whose preferred base is taken. Windows' loader (LdrRelocateImage) refuses to -// move an image only when IMAGE_FILE_RELOCS_STRIPPED is set; with the flag clear it maps it elsewhere and fixes up -// nothing, as it does for a second copy of such a DLL. The DllMain stub stores through an absolute address in this -// process, not in the image, so it runs correctly wherever the image lands. +// IMAGE_FILE_RELOCS_STRIPPED against a relocation directory, when the preferred base is taken. Measured on the +// Windows 11 (26200) loader with synthetic DLLs (#8847): with no relocation directory the flag refuses the move and +// an image with the flag clear is moved with nothing fixed up; with a relocation table the image is moved and fixed +// up whatever the flag says. The DllMain stub stores through an absolute address in this process, not in the image, +// so it runs correctly wherever the image lands. void test_moved_without_relocations() { auto img = make_image(); auto* nt = nt_of(img); @@ -704,13 +705,16 @@ void test_moved_without_relocations() { } if (held) VirtualFree(held, 0, MEM_RELEASE); { - // The flag only forbids moving: at a free base such an image maps as usual. + // At a free base such an image maps, as it did before. Not Windows parity: the Windows 11 loader refused these + // DLLs (error 487) at a free base too, for a reason not yet known (#8847); runtime/README.md keeps the question. auto stripped = img; nt_of(stripped)->FileHeader.Characteristics |= IMAGE_FILE_RELOCS_STRIPPED; - expect_loads("an image with IMAGE_FILE_RELOCS_STRIPPED maps at its free base", stripped); + expect_loads("an image with IMAGE_FILE_RELOCS_STRIPPED and no relocations maps at its free base", stripped); } { - // Windows refuses on the flag, whatever the relocation directory holds. ImageBase 0 makes the loader move it. + // With a relocation table the flag does not stop the move: the table is applied, as Windows does it. + // ImageBase 0 makes the loader move it; the one DIR64 entry points at the qword at RVA 0x1100. + const char* what = "an image with IMAGE_FILE_RELOCS_STRIPPED and a relocation table is moved and fixed up"; auto stripped = make_image(); auto* snt = nt_of(stripped); snt->FileHeader.Characteristics |= IMAGE_FILE_RELOCS_STRIPPED; @@ -719,8 +723,21 @@ void test_moved_without_relocations() { auto* block = reinterpret_cast(stripped.data() + 0x200); block->VirtualAddress = 0x1000; block->SizeOfBlock = 0x0A; - reinterpret_cast(block + 1)[0] = IMAGE_REL_BASED_DIR64 << 12; - expect_rejects("an image with IMAGE_FILE_RELOCS_STRIPPED and a relocation table is not moved", stripped); + reinterpret_cast(block + 1)[0] = (IMAGE_REL_BASED_DIR64 << 12) | 0x100; + uint64_t original; + std::memcpy(&original, stripped.data() + 0x300, sizeof original); + auto p = write_image(stripped); + try { + rt::Loader loader(g_dir); + rt::Module& m = loader.load(p); + uint64_t moved; + std::memcpy(&moved, m.base + 0x1100, sizeof moved); + if (!m.relocated) failed(what, "it was not moved"); + else if (moved != original + reinterpret_cast(m.base)) failed(what, "the pointer wasn't fixed up"); + else pass(what); + } catch (const std::exception& e) { + failed(what, e.what()); + } } } -- cgit v1.2.3 From bb256ebbf32d7493e3d867923ec737e60d3f9f9d Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Tue, 24 Nov 2026 05:00:08 -0500 Subject: pe_loader: the relocation-move notes stop citing the old pull request number The Windows 11 measurement behind this behaviour was posted in a review of pull request 8847 of the original repository, which went private on 2026-11-23, so its link and the "#8847" references in pe_loader.cpp and loader_test.cpp lead nowhere now. runtime/README.md keeps the measurement and the open question in its own words and names where it came from; the code comments point at the README. No behaviour changes. Co-Authored-By: Claude Opus 5.5 --- runtime/README.md | 9 ++++----- runtime/src/pe_loader.cpp | 2 +- runtime/test/loader_test.cpp | 10 +++++----- 3 files changed, 10 insertions(+), 11 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/README.md b/runtime/README.md index abe3e841b..268ceb45f 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -135,12 +135,11 @@ with the seed on stderr; a seed of 0 uses a fixed non-zero state. Unset, the hos `src/pe_loader.cpp` maps x86-64 images at their preferred base, or elsewhere (with relocations) when that base is taken. An image with a relocation table is moved and fixed up whatever `IMAGE_FILE_RELOCS_STRIPPED` says; without one, the flag refuses the move, and an image with the flag clear is moved with nothing fixed up (the -loader logs that). The Windows 11 loader does the same in these three cases, as measured by Zombins2 with -synthetic DLLs ([#8847](https://github.com/ItsNotRexed/Leonida/pull/8847#issuecomment-7112587898)). Open -question from the same measurement: Windows also refused flag-set DLLs without a relocation directory at a free +loader logs that). The Windows 11 (build 26200) loader does the same in these three cases, as Zombins2 measured +with synthetic DLLs in a review of old pull request 8847 of the original repository, which is no longer readable. +Open question from the same measurement: Windows also refused flag-set DLLs without a relocation directory at a free preferred base (error 487, linker-built `/FIXED` DLLs included), and why is not known; the loader still maps those -at their base, as before. It copies headers and -sections, applies `IMAGE_REL_BASED_DIR64` relocations, binds +at their base, as before. It copies headers and sections, applies `IMAGE_REL_BASED_DIR64` relocations, binds imports by name or ordinal, parses the export table, sets section protections, and registers the image's x64 unwind table (`.pdata`) with `RtlAddFunctionTable`, so exceptions raised in or passing through a mapped image are dispatched and stack walks can step over its frames. The table is validated diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 1c6b91b54..de42996f5 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1452,7 +1452,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& int64_t delta = reinterpret_cast(m->base) - static_cast(oh.ImageBase); // A moved image with a relocation table is fixed up, whatever IMAGE_FILE_RELOCS_STRIPPED says. Without a table, // the flag refuses the move; with the flag clear the image is moved and nothing is fixed up, so it is trusted to - // hold no absolute addresses. The Windows 11 loader does all three (measured in #8847); that move is logged so + // hold no absolute addresses. The Windows 11 loader does all three (runtime/README.md); that move is logged so // it shows in traces. base_reservation::needed still keeps the main image's range free when it has no // relocation directory, so a main image is moved this way only where the range could not be had. const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 926becd12..6930878a9 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -655,10 +655,10 @@ void test_initialise_rejects() { } // IMAGE_FILE_RELOCS_STRIPPED against a relocation directory, when the preferred base is taken. Measured on the -// Windows 11 (26200) loader with synthetic DLLs (#8847): with no relocation directory the flag refuses the move and -// an image with the flag clear is moved with nothing fixed up; with a relocation table the image is moved and fixed -// up whatever the flag says. The DllMain stub stores through an absolute address in this process, not in the image, -// so it runs correctly wherever the image lands. +// Windows 11 (26200) loader with synthetic DLLs (runtime/README.md): with no relocation directory the flag refuses +// the move and an image with the flag clear is moved with nothing fixed up; with a relocation table the image is +// moved and fixed up whatever the flag says. The DllMain stub stores through an absolute address in this process, +// not in the image, so it runs correctly wherever the image lands. void test_moved_without_relocations() { auto img = make_image(); auto* nt = nt_of(img); @@ -706,7 +706,7 @@ void test_moved_without_relocations() { if (held) VirtualFree(held, 0, MEM_RELEASE); { // At a free base such an image maps, as it did before. Not Windows parity: the Windows 11 loader refused these - // DLLs (error 487) at a free base too, for a reason not yet known (#8847); runtime/README.md keeps the question. + // DLLs (error 487) at a free base too, for a reason not yet known; runtime/README.md keeps the question. auto stripped = img; nt_of(stripped)->FileHeader.Characteristics |= IMAGE_FILE_RELOCS_STRIPPED; expect_loads("an image with IMAGE_FILE_RELOCS_STRIPPED and no relocations maps at its free base", stripped); -- cgit v1.2.3 From 82d6883bed1c18dfb4d409314e7805262aded79e Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Mon, 23 Nov 2026 11:41:08 -0500 Subject: pe_loader: trace delay imports bound to an unimplemented thunk; note delay-load and thread-attach order Delay imports are bound eagerly (deliberate: --dry-run shows the whole import surface). A delay-loaded DLL or function that nothing serves becomes an unimplemented thunk returning 0 at its first call, where Windows' delay-load helper raises 0xC06D007E / 0xC06D007F, which a title can catch for a fallback. The binding is unchanged; --trace now writes a delay_import_unimplemented event (module, import) for each such import at load, so the first boot names them before any image code runs. docs/runtime_imports.md gets two notes on where the loader differs from Windows: the eager delay binding above, and that DLL_THREAD_ATTACH reaches TLS callbacks in TLS slot order, which puts the executable before the DLLs it imports (Windows' order is undocumented). runtime/README.md lists the new trace event and now says the loader applies DIR64 and HIGHLOW relocations and rejects HIGH, LOW and HIGHADJ (old upstream 761). startup_trace_test gets a synthetic DLL with one ordinary and two delay imports (one missing, one bound to kernel32): exactly one delay_import_unimplemented event, naming the missing delay import. Findings by cynbun in the old upstream coordination issue (old upstream 7231). Co-Authored-By: Claude Opus 5.5 --- docs/runtime_imports.md | 16 ++++++ runtime/README.md | 4 +- runtime/shims/startup_trace.h | 9 ++-- runtime/src/pe_loader.cpp | 13 +++-- runtime/test/startup_trace_test.cpp | 100 +++++++++++++++++++++++++++++++++++- 5 files changed, 133 insertions(+), 9 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index 7b9f62d5a..79741f785 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -287,6 +287,22 @@ families are not listed. The sources are the Microsoft Learn pages for the D3D12 (`gaming/gdk/docs/reference/system//functions/`); `D3D12XboxCreateDevice` is matched by name from the measurement in `d3d12_vulkan.md`, because its page could not be found. +### Delay imports and thread events: where the loader differs from Windows + +- **Delay imports are bound eagerly.** `Loader::bind_imports` (`runtime/src/pe_loader.cpp`) binds the delay-import + table at load time, like the import table, so `--dry-run` shows the whole import surface. A delay-loaded DLL or + function that nothing serves becomes an unimplemented thunk, which follows `LEONIDA_UNIMPLEMENTED` at its first + call (return 0 by default). On Windows the delay-load helper raises `0xC06D007E` (module not found) or + `0xC06D007F` (procedure not found) at that call instead, and a title can catch it and take a fallback; that fallback + never runs here. `--trace` writes a `delay_import_unimplemented` event (`module`, `import`) for each such import + when the image is loaded. +- **Thread events reach TLS callbacks in TLS slot order.** A new thread's `DLL_THREAD_ATTACH` runs the mapped + modules' TLS callbacks in the order of their TLS slots (`DLL_THREAD_DETACH` in reverse). A module takes the lowest + free slot when it is mapped, before its imports are loaded, so the executable's callbacks run before those of the + DLLs it imports; a slot freed by an unloaded module goes to the next one. Windows does not document its order, so a + title that depends on DLL-first order would see a difference here. Mapped DLLs' `DllMain` gets no thread events + (`runtime/README.md`, PE loader). + ## Run-time loaded modules Not every console module is reached through an import table. `libHttpClient.GDK.dll` and `XCurl.dll` both use the diff --git a/runtime/README.md b/runtime/README.md index 61794a2c2..5859d4fe5 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -133,7 +133,8 @@ with the seed on stderr; a seed of 0 uses a fixed non-zero state. Unset, the hos ## PE loader `src/pe_loader.cpp` maps x86-64 images at their preferred base, or elsewhere (with relocations) when -that base is taken, copies headers and sections, applies `IMAGE_REL_BASED_DIR64` relocations, binds +that base is taken, copies headers and sections, applies `IMAGE_REL_BASED_DIR64` and `HIGHLOW` relocations +(rejecting the other types, such as `HIGH`, `LOW` and `HIGHADJ`, which no x64 MSVC image contains), binds imports by name or ordinal, parses the export table, sets section protections, and registers the image's x64 unwind table (`.pdata`) with `RtlAddFunctionTable`, so exceptions raised in or passing through a mapped image are dispatched and stack walks can step over its frames. The table is validated @@ -449,6 +450,7 @@ from the ANSI code page. | `tls_callback` | before each TLS callback the Loader runs (process attach and detach; thread events run under the Windows loader lock and are not traced) | `module`, `at` (module+RVA), `reason` | | `dllmain` | after `DllMain(DLL_PROCESS_ATTACH)` returns | `module`, `result` | | `unimplemented_call` | first call of each unimplemented import | `import` (`dll!name`), `caller` (module+RVA) | +| `delay_import_unimplemented` | at load, for each delay import that binds to an unimplemented thunk (Windows would raise `0xC06D007E`/`0xC06D007F` at its first call; [runtime_imports.md](../docs/runtime_imports.md#delay-imports-and-thread-events-where-the-loader-differs-from-windows)) | `module`, `import` (`dll!name`) | | `xmem_attributes` | the first `XMemAlloc`, `XMemFree`, `XMemAllocDefault`, `XMemFreeDefault` and `XMemVirtualAlloc` for each distinct raw attribute word (not every allocation) | `api`, `attributes`, `size` (not for the frees), `caller` (module+RVA) | | `xmem_physical_pages` | the first `XMemAllocatePhysicalPages` for each distinct attribute word | `api`, `attributes`, `pages`, `caller` | | `file_open_failed` | a guest `CreateFileW`/`CreateFile2` that fails (at most 256 events) | `api`, `path` (as the title passed it), `error` (Win32), `caller` (module+RVA) | diff --git a/runtime/shims/startup_trace.h b/runtime/shims/startup_trace.h index 7b47d993a..7fb9cdfea 100644 --- a/runtime/shims/startup_trace.h +++ b/runtime/shims/startup_trace.h @@ -6,11 +6,12 @@ // {"seq":2,"t":0.001,"kind":"map","module":"a.dll","base":"0x...","size":"0x2000","relocated":false} // {"seq":3,"t":0.002,"kind":"tls_callback","module":"a.dll","at":"a.dll+0x1200","reason":1} // {"seq":4,"t":0.002,"kind":"dllmain","module":"a.dll","result":1} -// {"seq":5,"t":0.010,"kind":"unimplemented_call","import":"x.dll!Foo","caller":"a.dll+0x3f10"} (first call only) -// {"seq":6,"t":0.011,"kind":"debug_string","text":"..."} -// {"seq":7,"t":0.020,"kind":"exception","code":"0xc0000005","at":"a.dll+0x4a00","access":"read","address":"0x0", +// {"seq":5,"t":0.002,"kind":"delay_import_unimplemented","module":"a.dll","import":"x.dll!Bar"} (at load) +// {"seq":6,"t":0.010,"kind":"unimplemented_call","import":"x.dll!Foo","caller":"a.dll+0x3f10"} (first call only) +// {"seq":7,"t":0.011,"kind":"debug_string","text":"..."} +// {"seq":8,"t":0.020,"kind":"exception","code":"0xc0000005","at":"a.dll+0x4a00","access":"read","address":"0x0", // "stack":["a.dll+0x4a00","a.dll+0x2210"]} -// {"seq":8,"t":0.030,"kind":"exit","code":0} +// {"seq":9,"t":0.030,"kind":"exit","code":0} // // The exception handler is vectored, logs and returns EXCEPTION_CONTINUE_SEARCH: it never changes what the process // does (except LEONIDA_SKIP_INT3, below). diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index c29a288a9..ebb1531bd 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1796,7 +1796,10 @@ void Loader::bind_imports(Module& m) { const uint64_t headers_end = nt->OptionalHeader.SizeOfHeaders; // Thunk tables have no length field: they end at a zero entry, so each step is checked against the image. - auto bind_thunks = [&](const std::string& dll, uint64_t lookup_rva, uint64_t iat_rva) { + // `delayed`: a delay import that binds to an unimplemented thunk is traced. Windows' delay-load helper would raise + // 0xC06D007E (module) or 0xC06D007F (procedure) at its first call, which a title can catch for a fallback; the + // thunk returns 0 instead, so the trace names each such import before any image code runs. + auto bind_thunks = [&](const std::string& dll, uint64_t lookup_rva, uint64_t iat_rva, bool delayed) { for (;; lookup_rva += sizeof(IMAGE_THUNK_DATA64), iat_rva += sizeof(IMAGE_THUNK_DATA64)) { require_range(m.name, lookup_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import lookup table"); require_range(m.name, iat_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import address table"); @@ -1814,6 +1817,10 @@ void Loader::bind_imports(Module& m) { throw std::runtime_error(m.name + ": an import address table lands in the headers"); at(m.base, static_cast(iat_rva))->u1.Function = reinterpret_cast(resolve(m, dll, name, ord, by_ord)); + if (delayed && startup_trace::enabled() && m.imports.back().binding == Binding::Unimplemented) + startup_trace::event("delay_import_unimplemented", + "\"module\":" + startup_trace::quote(m.name) + ",\"import\":" + + startup_trace::quote(dll + "!" + m.imports.back().name)); } }; @@ -1826,7 +1833,7 @@ void Loader::bind_imports(Module& m) { if (!d->Name) break; std::string dll = read_string(m.name, m.base, m.size, d->Name, "an imported DLL name"); uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk; - bind_thunks(dll, lookup, d->FirstThunk); + bind_thunks(dll, lookup, d->FirstThunk, false); } } // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. @@ -1849,7 +1856,7 @@ void Loader::bind_imports(Module& m) { // thunk addresses as name RVAs. if (!d->ImportNameTableRVA) throw std::runtime_error(m.name + ": a delay-import descriptor has no name table"); - bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA); + bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA, true); } } } diff --git a/runtime/test/startup_trace_test.cpp b/runtime/test/startup_trace_test.cpp index 336f957eb..75dcc669b 100644 --- a/runtime/test/startup_trace_test.cpp +++ b/runtime/test/startup_trace_test.cpp @@ -7,7 +7,8 @@ // 0x1220 reads address 0 (an access violation the test catches) // The loader maps it with the trace open, the test calls the three functions, closes the trace and checks the lines: // map, unimplemented_call with the caller as module+RVA, debug_string with the text, exception with the faulting -// RVA and access kind. No game data and no GPU are involved. +// RVA and access kind. A second image with delay imports checks delay_import_unimplemented (make_delay_image). +// No game data and no GPU are involved. // LEONIDA_TEST_DIR names the folder for the image and the trace, as for loader_test; the default is the temp folder. #include @@ -277,6 +278,102 @@ void test_trace(const fs::path& dir) { check(find_line(lines, "exit") == &lines.back(), "exit comes last"); } +// A DLL image with no code: one ordinary import that binds to nothing, and two delay-import descriptors, one naming a +// function nothing serves and one naming kernel32!GetTickCount (bound to the host). Delay imports are bound when the +// image is loaded, so the trace names the missing one then; the ordinary missing import and the bound delay import +// give no such event. +constexpr const char* kDelayImageName = "delay_image.bin"; + +std::vector make_delay_image() { + std::vector b(0x600, 0); + auto* dos = reinterpret_cast(b.data()); + dos->e_magic = IMAGE_DOS_SIGNATURE; + dos->e_lfanew = 0x80; + auto* nt = reinterpret_cast(b.data() + dos->e_lfanew); + nt->Signature = IMAGE_NT_SIGNATURE; + nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64; + nt->FileHeader.NumberOfSections = 1; + 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 = 0x1a0000000; + 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, ".data", 6); + sec->VirtualAddress = kTextRva; + sec->Misc.VirtualSize = 0x400; + sec->PointerToRawData = 0x200; + sec->SizeOfRawData = 0x400; + sec->Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE; + + uint8_t* data = b.data() + 0x200; + auto put_string = [&](uint32_t off, const char* s) { std::strcpy(reinterpret_cast(data + off), s); }; + // One name table entry and its terminator at `lookup_off`, the import's hint/name at `hint_off`. + auto put_thunk = [&](uint32_t lookup_off, uint32_t hint_off, const char* name) { + *reinterpret_cast(data + lookup_off) = kTextRva + hint_off; + put_string(hint_off + 2, name); + }; + put_string(0x100, "leonida_trace_probe.dll"); + put_string(0x120, "kernel32.dll"); + + auto* d = reinterpret_cast(data); + d->Name = kTextRva + 0x100; + d->OriginalFirstThunk = kTextRva + 0x140; + d->FirstThunk = kTextRva + 0x160; + put_thunk(0x140, 0x180, "NormalProbeMissing"); + + const struct { + uint32_t dll_off, int_off, iat_off, hint_off; + const char* name; + } delayed[2] = {{0x100, 0x1A0, 0x1C0, 0x1E0, "DelayProbeMissing"}, {0x120, 0x200, 0x220, 0x240, "GetTickCount"}}; + for (int i = 0; i < 2; ++i) { + auto* dd = reinterpret_cast(data + 0x40) + i; + dd->Attributes.AllAttributes = 1; // dlattrRva + dd->DllNameRVA = kTextRva + delayed[i].dll_off; + dd->ImportNameTableRVA = kTextRva + delayed[i].int_off; + dd->ImportAddressTableRVA = kTextRva + delayed[i].iat_off; + put_thunk(delayed[i].int_off, delayed[i].hint_off, delayed[i].name); + } + + auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; + dir.VirtualAddress = kTextRva; + dir.Size = 2 * sizeof(IMAGE_IMPORT_DESCRIPTOR); + auto& ddir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT]; + ddir.VirtualAddress = kTextRva + 0x40; + ddir.Size = 3 * sizeof(IMAGE_DELAYLOAD_DESCRIPTOR); + return b; +} + +void test_delay_import_trace(const fs::path& dir) { + const fs::path image = write_file(dir / kDelayImageName, make_delay_image()); + const fs::path trace = dir / "delay_trace.jsonl"; + check(rt::startup_trace::open(trace.c_str()), "open the delay-import trace file"); + { + rt::Loader loader(dir); + rt::Module& m = loader.load(image); + int unimplemented = 0, host = 0; + for (const auto& r : m.imports) { + unimplemented += r.binding == rt::Binding::Unimplemented; + host += r.binding == rt::Binding::Host; + } + check(m.imports.size() == 3 && unimplemented == 2 && host == 1, + "the delay image binds 3 imports: 2 unimplemented, 1 host"); + } + rt::startup_trace::close(); + + const auto lines = read_lines(trace); + int events = 0; + for (auto& l : lines) events += l.find("\"kind\":\"delay_import_unimplemented\"") != std::string::npos; + const std::string* e = find_line(lines, "delay_import_unimplemented"); + check(events == 1, "one delay_import_unimplemented event (got " + std::to_string(events) + ")"); + check(has(e, "\"module\":\"" + std::string(kDelayImageName) + "\"") && + has(e, "\"import\":\"leonida_trace_probe.dll!DelayProbeMissing\""), + "delay_import_unimplemented names the module and the delay import"); +} + } // namespace int wmain() { @@ -285,6 +382,7 @@ int wmain() { test_disabled_is_silent(); test_existing_file_is_kept(dir); test_trace(dir); + test_delay_import_trace(dir); std::error_code ec; fs::remove_all(dir, ec); } catch (const std::exception& e) { -- cgit v1.2.3