Repository navigation
PE/loader tests: hermetic synthetic images for ImageInfo, ImportLibrary and prepare - #287
SkippySteve wants to merge 56 commits into
Conversation
…ry host The prepare unit tests patch the test binary itself, which is a PE image only on Windows. This builds a small PE32+ executable in the test (one import module, one TLS callback, DIR64 relocations, a bound-import entry) and checks what prepare writes and that nothing else changes.
The ImageInfo unit tests that read imports, TLS and section mapping parse the test binary itself, which is a PE only on Windows. Add an integration test that builds a small PE32+ executable in memory (one section, a KERNEL32.dll import by name and by ordinal, two TLS callbacks) and checks headers, sections, imports and their IAT slots, TLS callback order, rva_to_file_offset (padding past the virtual size, the 4 GiB limit), an IAT running outside the image, other machines and truncated input. No game data or files on disk.
implib.rs, the reader behind `victory lib-exports`, had no tests. Two are added, built from an in-memory `!<arch>` archive of short-format import objects (no SDK .lib, no game data), so they run on every host: - every name type maps to the export the linker would bind (by name, no-prefix, undecorated, by ordinal), with its code/data/const kind; - the result is sorted, and a repeat of an export under another hint is one entry (the hint is not part of the key); - a member that is not a short import object is counted in other_members rather than dropped; - a file that is not an archive is an error, an empty archive has no imports.
82477e2 to
b1ba679
Compare
prepare() walks the base relocations to find the one that patches the TLS callback field. It added each DIR64 entry's page offset to the block's page RVA unchecked: a damaged block near u32::MAX panicked with an overflow in debug builds and, in release, wrapped to a low RVA that could match the field and zero an unrelated relocation entry. Targets that do not fit in an RVA are now left out, the TLS field's own RVA is computed with checked_add, and the block walk is split into dir64_entries over plain bytes so it is covered by tests on every host.
…s on every host Extend the synthetic image with optional delay-import, export and debug directories, each added only by the test that needs it, and check: delay-import IAT slots and their bounds, export forwarders by name and by ordinal, the RSDS record and its symbol-server key (non-RSDS is ignored), the relocation/exception/load-config flags including RELOCS_STRIPPED, subsystem names, and the raw layout offset helpers.
…ion on every host Adds five hermetic tests to synthetic_image.rs: names read from the IAT when OriginalFirstThunk is 0, a TLS directory with no callbacks or no RVA, a callback array that runs to the end of its section, TLS data outside the sections or past 4 GiB, and a PE32 header being Unsupported.
Adds two ImportLibrary unit tests. One builds the layout lib.exe writes (two `/` linker members, a `//` long-names member, imports under `/<n>` names) and checks that the bookkeeping members are neither imports nor other members. The other checks that a truncated archive, an oversized member and a long name past the names table return an error without a panic, and that a cut-short or overlong import object inside an intact archive is counted in other_members.
…tions A simulated rebase shows the cleared TLS callback pointer stays 0 while the other pointers move, and that it would not without the no-op entry. Also covers a callback relocation in a later block next to a HIGHLOW entry for the same RVA, missing or damaged relocation tables, TLS with no callbacks, re-preparing a prepared image, and a title that is already a DLL.
The synthetic image had one import descriptor, so a terminator placed a fixed 20 bytes in passed every test. Build three, one a differently cased duplicate of KERNEL32.dll without a name table, and check the terminator lands 60 bytes in while the descriptors and IATs stay as the title left them.
…tions and damaged images safe prepare() must not write directory slots past NumberOfRvaAndSizes (there a shorter optional header's section table begins), must neutralise every DIR64 relocation of the TLS callbacks pointer, must give an import directory of only a terminator the size of one descriptor, and must return a result for every truncation and single-byte corruption of the synthetic image.
… and a second section ImportSymbol's Display, the 1024-callback walk limit, an export reached only by ordinal, a delay import by ordinal, and rva_to_file_offset across two sections (one with a virtual size of 0) had no test that runs off Windows. Each is built into the same synthetic image.
… byte-level corruption sweeps
…fo, ImportLibrary and prepare Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ort directory without an RVA
…e virtual size, and implib names that differ only by DLL or kind
A damaged section table (a section with no virtual size, listed first, over the same RVAs as the real one) makes object and rva_to_file_offset find the TLS directory in different places. prepare cleared a header field instead and returned a copy whose callbacks the OS would still run. Re-parse the patched copy and fail if its callback pointer is still set.
…ssy section names, ordinal implib entries, and relocations beside the TLS callback field
|
Tested the current open PR at head
The branch advanced from |
…t ordinal bases and unused slots, and ignore directories with no RVA
…lback field A HIGHLOW, HIGH, LOW or HIGHADJ entry on the AddressOfCallBacks field, or a DIR64 entry a few bytes before it, rewrites part of the cleared pointer on a rebase just as the field's own DIR64 entry would, and the reparse check runs before any rebase so it cannot catch that. Walk every relocation type with its width (HIGHADJ's parameter slot skipped, unknown types taken as pointer-wide) and clear each entry whose bytes overlap the field. Synthetic regressions rebase prepared images with each fixup kind and fail without the change.
The Windows and Wine loaders find the relocation table through the directory RVA in the mapped image, and the headers are mapped at the RVA equal to their file offset. prepare only looked through the section table, so a table in the header slack went unread and the DIR64 entry for the TLS callback field stayed armed: a rebase would turn the cleared pointer into the load delta. Read such a table up to SizeOfHeaders. Also cover the layout offset helpers: e_lfanew, short files, directory counts and bounded little-endian reads.
…ers, skip /SYM64/, and refuse an unterminated DLL name
…d, TLS VAs follow the header's image base, a callback at the base is RVA 0, and a section-less image parses
…ta, an empty DLL name is kept, EXPORTAS names are taken as written, and kinds sort code, data, const regardless of timestamp
… the last dot and a bad one fails the parse, an ordinal with two names is listed once, a delay IAT may end at SizeOfImage, and delay attributes are not checked
…file offset, a debug directory must hold whole entries, archives and COFF objects are unsupported, and repeated DLL descriptors stay separate
…without a terminator inside the section are malformed, the import directory size does not limit descriptors, and an export past the raw data keeps its RVA
…a DLL name and a thunk table, an IAT at RVA 0 is taken as written, export ordinals must fit 16 bits and name ordinals the address table, export tables outside the sections are malformed, and the export DLL name is not read
…values are not checked against each other, and data appended after the last section is not mapped
… and builds differing only in their checksum prepare to the same bytes under different names
…e directory entry alone, and relocations need both a directory and no stripped flag
…section table follows the declared optional header size, and stack sizes are read as 64-bit values
…ITY, carries an overlay over unchanged, clears the callback relocation even when relocations are marked stripped, clears a pointer to an empty callback array, and reports parse and patch errors apart
…e of the callback field, a block running past the relocation directory is not read, and prepare's info is the original parsed on its own
… DOS stub, directories set through layout are reported, the checksum, bound-import and IAT directories change nothing read, and DLL characteristic flags are distinct bits
catminou4
left a comment
There was a problem hiding this comment.
Verified locally on macOS 26 arm64, rustc 1.98.1 (aarch64-apple-darwin) at head 08d0483, cargo test -p victory-pe -p victory-loader --locked --no-fail-fast:
- New synthetic tests all pass on macOS:
tests/synthetic_prepare.rs43 passed,tests/synthetic_image.rs100 passed — the hermetic-image approach works outside Windows. - The following failures are pre-existing on main and unrelated to this PR (the tests parse the test binary itself as a PE image, which only works on Windows; #523 gates them off non-Windows): loader lib 3 failed (
patches_own_test_binary,keeps_iat_slots_when_import_size_excludes_the_terminator,file_name_is_stable_per_build), pe lib 4 failed — identical set to main.
Approving.
…tions map through the first in the table, RVAs below a section do not wrap, subsystem names need exact values, and the DLL bit alone decides is_dll
… ways stays in each table, and import symbols compare on the hint but display without it
…read through layout is the one reported, and forwarders by ordinal span the 16-bit range
…bles and TLS data there are not in the file
… at its own file offset, names only from the directory's section, whatever the table order
…at its file offset, forwarders only inside the directory's range, export names only from its section
…port names, unaligned IATs, TLS data in the headers, and an IAT crossing SizeOfImage
…hout a NUL before the section end are malformed
…nused section bytes, and repeat parses
… short records are malformed, and unread DOS, COFF symbol, optional-header, section and import-descriptor fields
…al size, and export name tables at RVA 0
…aring a name table and IAT, and delay descriptors without a name table
Several
victory-peandvictory-loaderunit tests parse the test binary itself. That binary is a PE image only on Windows, so on Linux they fail withUnknown file magic, and #235 limits them to Windows. This PR adds hermetic tests that run on every host. Each one builds its PE image or import library byte by byte in memory, with no game data, fixtures or files on disk. It changes no library code and doesn't touch the existing tests.This PR combines four earlier PRs: #287 (loader
prepare), #257 (ImageInfo), #268 (ImportLibrary) and #344 (a relocation fix inprepare). It has one commit for each, plus three that widen theImageInfotests, one that widens theImportLibrarytests and four that widen thepreparetests. #344 is the only library change.victory-loader:crates/victory-loader/tests/synthetic_prepare.rs(43 tests)The tests build a PE32+ executable in memory. It has one section, a
KERNEL32.dllimport by name and by ordinal, a TLS directory with one callback, DIR64 base relocations for the TLS pointers, a bound-import directory entry, a checksum, andFORCE_INTEGRITYset. They check that:infodescribes the original image correctly: it is not a DLL, and the entry point, import IAT slots and TLS callbacks match.IMAGE_FILE_DLLset, entry point 0 and checksum 0;FORCE_INTEGRITYcleared, with the other DLL flags unchanged;IMAGE_REL_BASED_ABSOLUTE.keeps_iat_slots_when_import_size_excludes_the_terminator.kernel32.dllwith no name table), each is read as its own module with its IAT slots, and the import directory points at the terminator 60 bytes in, not a fixed 20.file_name()is a stablevictory-image-<16 hex of BLAKE3>.dll.DYNAMIC_BASEimages), the cleared TLS callbacks pointer stays 0 while the TLS index pointer and the callback array move. Without the no-op relocation the same rebase would leavedeltathere.HIGHLOWentry for the same RVA and the other DIR64 entries are left alone.preparestill clears the callbacks pointer and rewrites no relocation entry..relocsection of their own (a different file offset from.data), the callbacks pointer's entry is found through the section table; a block for another page with an entry at the same page offset is left alone, as is a stale copy of the old block in.data, and a rebase keeps the pointer at 0.0x00and to0xFFin turn, returns a result without panicking; a patched copy keeps the original's length and hash.victory-pe:crates/victory-pe/tests/synthetic_image.rs(144 tests)The tests build a PE32+ executable in memory with one section, a
KERNEL32.dllimport by name (with a hint) and by ordinal, and two TLS callbacks. They check:rva_to_file_offset:SizeOfImage, including at the 4 GiB limit, isMalformed.Unsupported, and truncated input returns an error without panicking.Unsupported.ImportSymboldisplays as its name or#<ordinal>..data, virtual size 0),rva_to_file_offsetmaps each RVA through the section that holds it, uses the raw size as the size in memory, and maps neither the gap between the sections nor the end of.data.OriginalFirstThunkis 0, as old linkers leave it, import names are read from the IAT, with the same slots.Malformed.Each of these tests adds one optional directory to the same image, and only that test uses it:
USER32.dll!MessageBoxWis read with its hint and IAT slot, separately from the ordinary imports, and by ordinal (#9) when its name-table entry is an ordinal. A delay IAT that runs pastSizeOfImage, including at the 4 GiB limit, isMalformed.NTDLL.RtlFoo) and by ordinal (NTDLL.#7). Forwarders have no RVA. With one name fewer, the local export is read by ordinal only, with no name.symbol_key()gives the symbol-server key (the first three GUID fields are little-endian; the age is unpadded hex). A record that isn't RSDS (NB10) is ignored, and an RSDS record in a later debug entry is still found. With two RSDS records the first is reported. A record whoseSizeOfDatais too short for the signature, GUID or age is malformed, while a short non-CodeView entry pointing past the file is never read.has_relocations,has_exception_tableandhas_load_configfollow their directory entries.RELOCS_STRIPPEDoverrides a leftover relocation entry, and an entry with size 0 counts as absent.other.AddressOfIndexofu64::MAX), a delay descriptor's module handle, bound IAT, unload IAT and timestamp (all RVAs pastSizeOfImage), the export directory's characteristics, timestamp and version, and the CodeView debug entry's characteristics, timestamp and version to garbage changes nothingImageInforeports. The same holds for the DOS header bytes between the magic ande_lfanew, a COFF symbol table pointer past the file with a huge symbol count, the optional-header fieldsImageInfodoesn't keep (linker, OS, image and subsystem versions, code and data sizes, base of code,Win32VersionValue, checksum, heap sizes, loader flags), a section's relocation and line-number fields, and an import descriptor's timestamp and forwarder chain. Filling the unused bytes of.textwith0xEEchanges nothing either, and parsing the same bytes twice (or cloning the result) gives the sameImageInfo.layouthelpers: the file header, optional header and data directory offsets match the image. An index at or pastNumberOfRvaAndSizes, a truncated DOS header and ane_lfanewofu32::MAXall returnNone.victory-pe:crates/victory-pe/src/implib.rs(4 unit tests)implib.rs(the reader behindvictory lib-exports) had no tests. The new tests build an in-memory!<arch>archive of short-format import objects. They check:_Prefixed→Prefixed), undecorated (_Stdcall@8→Stdcall) and by ordinal.other_members.lib.exewrites, with two/linker members, a//long-names member and imports under/<n>names. The imports are read, and the linker and long-names members aren't counted as imports or inother_members.SizeOfDataruns past the member, or one cut short inside its header, is counted inother_members.victory-loader: a relocation past the top of the address space is not wrapped (was #344)prepare()walks the base relocations to find the one that patches the TLS callback field. It added each DIR64 entry's page offset to the block's page RVA unchecked: a damaged block nearu32::MAXpanicked with an overflow in debug builds and, in release, wrapped to a low RVA that could match the field and zero an unrelated relocation entry.Targets that do not fit in an RVA are now left out, the TLS field's own RVA is computed with
checked_add, and the block walk is split intodir64_entriesover plain bytes. Two new unit tests (dir64_entries_walk_blocks_and_skip_other_types,dir64_entries_drop_targets_past_the_top_of_the_address_space) build relocation blocks in memory and pass on Linux.Testing
I ran these on Arch Linux (x86_64-unknown-linux-gnu), on top of current
main:cargo test -p victory-loader --test synthetic_prepare: 43 passed.cargo test -p victory-pe --test synthetic_image: 135 passed.cargo test -p victory-pe --lib implib: 34 passed.cargo clippy -p victory-pe -p victory-loader --all-targets -- -D warnings: clean.rustfmt --checkon the three touched files: clean.cargo test -p victory-loader --lib: the 2 new relocation tests pass; the 3 existingprepare::teststhat parse the test binary still fail on Linux, as onmain(Build: gate Windows-only paths so the workspace builds and tests on Linux #235).cargo xtask policy: ok.To check that the tests catch regressions, I broke checks in
prepare.rs(12 ways; matching relocations by page offset alone or reading the relocation directory as if it were in the first section fails only the.reloctest, writing the import slot when its RVA is 0 fails the no-RVA test; dropping the relocation no-op fails 3 tests, including the rebase one, placing the import terminator a fixed 20 bytes in fails only the three-descriptor test, writing the bound-import slot regardless ofNumberOfRvaAndSizesfails the short-header test, and stopping after the first callback relocation fails the duplicate-relocation test) and inimage.rs(13 ways), one at a time. Each change made a test fail.TLS callbacks behind a damaged section table. A section with no virtual size, listed before the real one and over the same RVAs, makes
object(which skips it) andImageInfo::rva_to_file_offset(which maps it by its raw size) find the TLS directory in different places.preparethen cleared 8 bytes of the headers, left the real callback pointer set, and returnedOk: the OS would have run the callbacks before any import was bound.preparenow re-parses the patched copy and returnsPrepareError::Patchif the callback pointer is still set (a_section_table_that_hides_the_tls_directory_is_an_error; without the fix the copy keeps0x140001140).Data in a second section. In the other tests, all import, TLS and export data sits in
.text. New tests add a.datasection whose file offset is not the.textshift, and fill the file with0xEEwhere that shift would point. Imports, delay imports and TLS are read at.data's own file offset. A TLS directory in one section can point at a callback array in the other, and reading the array stops at the end of.data's raw data. Listing.datafirst in the section table changes only the order ofsections.objectreads DLL names, name tables and hint/name entries only from the section that holds the import (or delay-import) directory: a descriptor that points into.textfor any of them isMalformed, even though the same bytes are there. Only the IAT may be in another section. Ifrva_to_file_offsetchecks only the first section, 4 tests fail, including the new import and table-order tests.Import library names. New
implibtests coverIMPORT_OBJECT_NAME_EXPORTAS(the third string is the export name; a member without it is counted as another member), undefined import type 3 and name types 5 to 7 (counted, with the members around them still read), and prefix stripping (NO_PREFIXdrops a single?,@or_, andUNDECORATEalso drops everything from the next@).On Linux,
mainstill has 7 failing tests: 4 inimage::testsand 3 inprepare::tests, all of which parse the test binary itself. #235 handles those. I haven't run the new tests on Windows. They use only the public API and don't depend on the host.