Skip to content

pe_loader: probe the game folder and load the host DLL once per imported DLL, not once per import (PERF-RT-IMPORT-CACHE) - #8340

Open
TG0000 wants to merge 1 commit into
ItsNotRexed:mainfrom
TG0000:perf/runtime-startup-input
Open

TG0000 wants to merge 1 commit into
ItsNotRexed:mainfrom
TG0000:perf/runtime-startup-input

Conversation

@TG0000

@TG0000 TG0000 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Item: PERF-RT-IMPORT-CACHE (claimed in #8186).

What

Loader::resolve (runtime/src/pe_loader.cpp) ran std::filesystem::exists(<game-dir>/<dll>) (a file-system call) and LoadLibraryExA for every import that the shim table does not serve, although every import of a descriptor names the same DLL. That is about 1,900 host imports at startup, according to the counts in docs/runtime_imports.md (432 in the executable, about 1,200 in the 16 package DLLs). They spread over a few dozen DLLs.

bind_imports now installs a Loader::ImportCache for the module it binds. It puts the outer cache back when it returns, since load() binds a dependency from inside resolve(). For each DLL name, resolve() keeps:

  • the lowered key and prefer_host_copy,
  • the bundled module, or none,
  • the host handle, or the failure.

Each one is worked out on the first import that needs it, through a small rt::Lazy<T> (runtime/src/lazy.h). If a step throws, the value stays unset, as it was before.

Why the behaviour is the same

  • Bundled module: load() of a module that is already mapped returns it from by_name_. The cached Module* is the one every later call would return.
  • Host DLL: LoadLibraryExA of a loaded DLL returns the same handle, so only its reference count differs. The loader never frees a host DLL.
  • redirect_pc_to_file_header(h): it already ignores a module it has seen. It is now called once, when the DLL is loaded, which is still before any mapped code runs. redirect_pc_to_file_header_at(p) still runs for each import.
  • Unchanged: ImportRecords, bound addresses, the shim-first order, a bundled module's miss falling to its host namesake, and the unimplemented thunks.
  • Not cached: shims::find, the export and forwarder lookups and GetProcAddress still run for each import.

The diff does not touch the bind_thunks signature, its call sites or the lines around nt in bind_imports. Those are what #7423 and #5677 change. git merge-tree against each open pe_loader.cpp PR (#7423, #5677, #8072, #7880, #7996, #7884, #5302) is clean. #8134 conflicts on exactly the same files with and without this commit. The header gains three private declarations next to resolve.

Tests

runtime/test/pe_loader_import_cache_test.cpp (new, registered as the CTest pe_loader_import_cache) has two parts, neither needing game files:

  1. Model of resolve(). It runs main's body and the patched body call for call, over a fake world: a shim table, files beside the game, bundled modules with exports and forwarders, host DLLs with names and ordinals, and the CRT list. It covers:

    • fixed cases: no descriptor, an empty descriptor, one import, all-shim, a CRT DLL, a missing DLL, a bundled module with forwarders and a host namesake, and two descriptors with the same DLL;
    • 2,000 random import tables (250,039 imports, a quarter of the descriptors with 0–2 imports).

    Every case gives identical IAT values, records, redirect and redirect_at effects, and order of first loads. GetProcAddress runs as often as before. Over the random tables, exists drops from 150,111 calls to 6,189 and LoadLibraryExA from 197,448 to 8,782. Exact counts are checked on the fixed tables, for example 5 → 1 of each for six kernel32 imports.

  2. Benchmark of the calls removed, made for real. It binds 725 named exports of 12 System32 DLLs and API sets against an empty temporary game folder, before and after the cache, and checks that the bound addresses are identical. Median of 41 runs:

exists LoadLibraryExA heap allocations time
before (per import) 725 725 979 17.9 ms
after (per DLL) 12 12 29 0.56 ms

That is about 32× less time (96.9%), about 24 µs saved per import on this machine. A run under load gave 31.4 ms → 1.06 ms (29.8×). The benchmark leaves out the shim lookups and the binding of bundled modules, which this PR does not change.

Also run:

  • clang++ -std=c++20 -O2 -Wall -Wextra -Werror -Wpedantic on the new test: it passes.
  • test_pe_loader_bounds: real Loader::load over synthetic images, import tables included. I built it with llvm-mingw, stubbing __try/__except (a forced-include header that only matters when a fault happens). All 54 checks pass on this branch and on main.
  • pe_loader.cpp and the loader tests that include its header, syntax-checked with clang and -Wall -Wextra: no new diagnostics. Only the existing SEH ones remain, which mingw cannot compile.
  • cmake -DLEONIDA_BUILD_WINDOWS_RUNTIME=OFF with ninja and clang 23 (llvm-mingw): builds. 66 of 67 CTests pass; vk_queue_query_sync failed once and passed on rerun, and it builds from no file this PR touches.

The MSVC build of the Windows runtime, including pe_loader_test and the new CTest under MSVC, is left to CI. No MSVC toolchain is installed here. Windows 11 Pro, no GPU needed.

AI-assisted (Claude Code, Claude Opus 5.5).

🤖 Generated with Claude Code

…ted DLL, not once per import

Loader::resolve ran std::filesystem::exists(<game>/<dll>) and LoadLibraryExA for every import that the shim
table does not serve, though every import of a descriptor names the same DLL. bind_imports now installs a cache
(Loader::ImportCache) for the module it binds; resolve() keeps, per DLL name, the lowered key, prefer_host_copy,
the bundled module (or none) and the host handle (or failure), each worked out on the first import that needs it.
A kept answer is the one asking again gives: load() of a mapped module returns it from by_name_, and
LoadLibraryExA of a loaded DLL returns the same handle (only its reference count differs; the loader never frees
a host DLL). Bindings, addresses, ImportRecords and the RtlPcToFileHeader redirects are unchanged.

runtime/test/pe_loader_import_cache_test.cpp checks resolve before and after on fixed and 2000 random import
tables (same results and side effects) and times the calls removed: 725 System32 imports in 12 descriptors bind
about 30x faster (18 ms -> 0.56 ms on this machine).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@tupacfan04 tupacfan04 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The successful path is sound — cache scoped to one bind_imports, RAII restore, DLL-name key, same shim → bundled → host → unimplemented order, per-import GetProcAddress — but failed probes are cached as final answers.

runtime/src/pe_loader.cpp:1606-1609 and :1611-1624:

Module* bundled = imported.bundled.get([&]() -> Module* {
    auto path = game_dir_ / dll;
    return !imported.host_crt && std::filesystem::exists(path) ? &load(path) : nullptr;
});
...
if (HMODULE h = imported.host.get([&] { ... return LoadLibraryExA(...); })) { ... }

rt::Lazy sets set_ = true for any returned value, including nullptr (runtime/src/lazy.h:14-22). Before this PR every import re-ran exists/LoadLibraryExA. A failed LoadLibraryExA is not necessarily permanent within the same bind_imports: a later host DLL's DllMain, a later bundled/forwarder load, or a game-folder change can make it available. The cache then returns the stored null and the later import becomes an Unimplemented thunk.

Synthetic model: A.dll fails, B.dll loads and makes A available, then A again. The old resolve_before binds the second A as Host; the cached resolve_after binds it as Unimplemented. The test bakes in “a null result is a result: it is kept” (runtime/test/pe_loader_import_cache_test.cpp:75-78), so it cannot see the difference. Fix: cache only successful results; leave a failed host Lazy unset/retryable and re-probe a missing bundled file. Add the model case.

Secondary: the new CTest is a model of resolve (it links the test + lazy.h, not pe_loader.cpp), so the real Loader::ImportCache install/restore around a nested load(), the real resolve/__try/header paths, and the real import table are untested; test_pe_loader_bounds does not count per-DLL probes, and the xcurl.dll/XCURL.DLL case does not assert a per-DLL count.

Refcount note: the success path now keeps one LoadLibraryExA reference instead of one per import. The loader never frees it, but any host-side FreeLibrary/unload would invalidate the cached HMODULE; the old extra references were a safety net, and this lifetime is untested. Synthetic analysis only; no game files. AI-assisted (OpenCode).

@lohant27-netizen

Copy link
Copy Markdown

Tested c6ec8578b on Windows 11 (10.0.26300), NVIDIA GeForce RTX 5070 (driver 32.0.16.2101, subgroup 32), MSVC with SDK 10.0.26100, Release, merged onto main 2a3b3b554 together with #8457, #8454, #8373, #8364 and #8340 (no conflicts between them): pass.

@RAINighty

Copy link
Copy Markdown

Tested c6ec8578b merged with main 867d922f0 (clean merge) on Windows 11 (10.0.26300), Intel Core i7-14650HX, MSVC 19.44.35228, RelWithDebInfo (Ninja), CPU-only tests: pass.

  • pe_loader, pe_loader_bounds and the new pe_loader_import_cache all pass (3 of 3).
  • Control: with main's runtime/src/lazy.h, pe_loader.cpp and pe_loader.h under this PR's tests, the same three tests also pass. pe_loader_import_cache is described in the CMake comment as a model of resolve() before and after the cache, so it does not fail without the loader change; it checks the model and the benchmark, not the loader itself.
  • Code not reviewed beyond running it. No GPU or game files.

AI-assisted (Claude Code).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants