Loader::initialise(Module&) called every DllMain(DLL_PROCESS_ATTACH) with
lpvReserved NULL. Microsoft's DllMain reference: "If fdwReason is
DLL_PROCESS_ATTACH, lpvReserved is NULL for dynamic loads and non-NULL for
static loads." The executable gta6rt maps and the DLLs it imports are the
static case; a run-time LoadLibrary (load_runtime_module) and a
GetProcAddress forwarder (resolve_module_export) are dynamic.
Each Module now records whether it was mapped inside a run-time load, and a
static module's DllMain gets a pointer to a CONTEXT captured for the call.
TLS callbacks and the process detach in ~Loader (an unload: NULL) are
unchanged.
loader_test: a host load() + initialise() must give a non-NULL lpvReserved
(fails on main), the same image through load_runtime_module NULL. The
lifecycle observer checks lpvReserved on detach only.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
With it, d3d12_xs reads list slot 48 as the console's IASetVertexBuffers, so the PC-shaped fixture list's
ClearRenderTargetView never runs and Close fails. The branch also changes runtime/src/pe_loader.cpp and carried
committed conflict markers in docs/fssm_crosscheck.md. Its docs rows go with it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pe_loader: resolve() and resolve_forwarder() key the DLL name with
dll_key() — lower-case, trailing '.' dropped, ".dll" added when there
is no extension — the file-name rule LoadLibrary applies. Without it an
import naming "GameInput" or "gameinput.dll." missed the shim and
owns_dll lookups while LoadLibraryExA still bound a host namesake.
registry: xaudio2_9.dll ordinals 8-10 classify as hresult (host table
measured: XAudio2CreateV2_9 / WithVersionInfo / WithSharedContexts);
the redist's ordinal table is unconfirmed and stays other.
import_inventory: classify parity for the #1 ordinals; the delay-import
directory (entry 13) is read with the loader's checks; the descriptor
table stops at Name == 0 and unreadable names fail like read_string;
host-bound imports report as host instead of unimplemented thunk
(owns_dll ported); thunk tables deduplicate by RVA under a global cap.
Generated with [Devin](https://devin.ai)
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
lookup_in_loader walked Loader::modules() with no lock while map_image
appends to it under Loader::mutex_. The lookup runs on any thread: behind
the RtlPcToFileHeader redirect on every C++ throw from a mapped image, and
for trace and stop lines. A throw during another thread's run-time load
read a vector that was being reallocated.
find_address reads a table of (base, size, name) under a leaf lock;
map_image adds an entry once the image's memory exists.
loader_test: lookups from one thread while another loads 300 images. With
the old code it crashes under AddressSanitizer at the vector read.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
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.
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 <noreply@anthropic.com>
Every data directory the loader reads goes through directory(), which
returns an empty entry past OptionalHeader.NumberOfRvaAndSizes (PE/COFF: those
slots are not directories, whatever bytes they hold) - except the TLS one,
which read DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS] directly. An image
declaring fewer than 10 directories with leftover bytes in slot 9 then failed
to load ("the TLS directory runs past the image") or, with plausible bytes,
had a TLS directory the Windows loader would ignore.
loader_test: with NumberOfRvaAndSizes = 9 and junk in the TLS slot the image
loads (it was rejected before); with all 16 the same slot is still checked
and refused.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
resolve_forwarder checked prefer_host_copy() on the bare forwarder module
name, but forwarder strings normally leave out ".dll" ("MSVCP140.?foo")
and the host-copy list is named with it. So a bundled module forwarding to
one of the CRT DLLs the package ships (vcruntime140, msvcp140, concrt140,
...) mapped the Xbox build of that DLL from the game folder instead of the
host's, unlike a direct import of the same symbol. It now uses shim_key,
the name with ".dll" the function already builds for the shim lookup.
loader_test: a fake bundled vcruntime140.dll plus a provider forwarding
"vcruntime140.memset" binds to the host memset and never maps the fake
(fails before the change: the import ends unimplemented).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
parse_exports range-checks the export directory, its three tables and every
name, but stored each code export as base + rva without checking rva. An
address-table entry at or past SizeOfImage (and outside the export
directory, so not a forwarder) became a pointer past the mapping, which an
import or GetProcAddress through the shims would hand out and a caller would
jump to. The load now fails with the export's name, like every other RVA the
loader follows.
loader_test: an export at SizeOfImage is rejected (it loaded before this
change); one at the image's last byte still loads.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.
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.
loader_test: the probe for security software that holds newly written
images also stops when writing and reading one back averages over
25 ms. Under Wine there is no such software and its file I/O alone took
38-40 ms in the wine job, so there only the refusals and contents are
checked.
The host comparisons move from d3d12_vulkan_device_test's
create_host_device to copycmp::create_host, so the copy comparisons are
skipped under Wine too (with them, winevulkan asserted in
vkBindBufferMemory).
An IAT without an INT still holds delay thunks, not name RVAs, so eager binding has no symbol to resolve. Reject the form with a clear error. A scan of the installed x64 System32 tree found 4,620 DLLs and 17,558 delay descriptors, none with a missing INT or without dlattrRva. The test now expects the rejection.
On Windows with Trend Micro Maximum Security (Defender and Smart App Control
off), images the test writes to %TEMP% can be written but not opened for a
while: each takes 50-800 ms, the first case failed, the truncation case
stalled for about ten minutes, and an uncaught write error then ended the
process with 0xc0000409. Held images from one run also made the next fail.
- Each run writes to leonida_loader_test\<process id>, so the previous run's
held images cannot collide; LEONIDA_TEST_DIR picks the parent folder.
- A start-up check writes and reads back 8 images and stops with the reason
and the folder to exclude if one is refused or they average over 25 ms.
- A failed write ends the run as one FAIL instead of std::terminate.
- A run folder that cannot be removed is reported as a note.
The loader and its 48 checks are unchanged. ctest 15/15 on Windows 11 with
the antivirus active. AI-assisted (Claude Code).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Images the loader maps by hand are unknown to the system unwinder, so an exception raised in or passing through one couldn't be dispatched and killed the process. load() now validates the exception directory (entries in bounds, sorted, non-overlapping; zero-length entries allowed, as in System32's symcryptk.dll) and registers it; the loader removes it before freeing the image. Rules measured over 3,780 x64 System32 images (5,023,071 entries) and the 16 package DLLs.
Tests: loader_test covers registration, removal and six corrupt tables on hand-built images; pe_loader_test checks a fixture SEH fault is caught by the image's own handler (fails without registration) and, with LEONIDA_GAME_DIR, every package DLL's table.
AI-assisted.
A forwarder target is resolved through game_dir and System32, but not through shims::find, so a forwarder to xmem or d3d12_xs became an unimplemented thunk. Check the normalized module name against the shim registry first, as a direct import already does. A synthetic shim table and a forwarder-to-shim test cover it.
parse_exports stored base + RVA for every export, but an export whose RVA lands inside the export
directory is a forwarder string ("KERNEL32.Sleep"), not code, so an import of one received a pointer
into the string. Forwarders are now recorded separately and followed when an import asks for one:
bundled modules first, then LoadLibraryEx/GetProcAddress for system DLLs, with a depth cap so two
modules re-exporting each other stop instead of recursing. An unresolvable forwarder records the
import as unimplemented.
The delay-import walk also assumed every descriptor is RVA-based and has a name table. A descriptor
without dlattrRva stores 32-bit virtual addresses, which cannot address an x64 image base, so it is
rejected with a message instead of being misread. A missing address table is rejected, and a missing
name table now reads its entries back through the address table.
Mapping an image never ran anything. TLS callbacks and DllMain were documented as the caller's, and
nothing called them, so a module that needs either could not be brought up at all.
Loader::initialise() now allocates the module's TLS slot, copies the template and SizeOfZeroFill into
it, writes the slot index into the image, runs the TLS callbacks with DLL_PROCESS_ATTACH, then calls
the entry point of a DLL as DllMain. Every address it follows is bounded like the rest of the loader:
the directory, the template, the index, the callback table and each callback, with a 1 MiB ceiling on
the block. Only DLLs get DllMain; an EXE's entry point has a different signature and stays the
caller's to run, and --dry-run still runs nothing.
The tests build an image whose TLS callback and DllMain are real machine-code stubs that store a
sentinel, so they check the code actually executed rather than merely being parsed.
The loader trusted the image it was handed: e_lfanew was dereferenced without
checking it against the file size, section copies were bounded by the file but
not by SizeOfImage, and the relocation, export and import walks put no limit on
where an image's own RVAs sent them. A truncated or corrupt image could read or
write outside the mapping the loader had just allocated, and a PE32 image was
read through a PE32+ header instead of being rejected.
Every RVA is now checked first, and a bad one fails with the file's name and
what did not fit. loader_test builds its own images, so ctest covers the good
and the corrupt cases without needing any game files.