Skip to content

PE/loader tests: hermetic synthetic images for ImageInfo, ImportLibrary and prepare - #287

Closed
SkippySteve wants to merge 56 commits into
Marvisak:mainfrom
SkippySteve:SkippySteve/victory-pr-own-next15
Closed

SkippySteve wants to merge 56 commits into
Marvisak:mainfrom
SkippySteve:SkippySteve/victory-pr-own-next15

Conversation

@SkippySteve

@SkippySteve SkippySteve commented Nov 24, 2026 •

Copy link
Copy Markdown

Several victory-pe and victory-loader unit tests parse the test binary itself. That binary is a PE image only on Windows, so on Linux they fail with Unknown 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 in prepare). It has one commit for each, plus three that widen the ImageInfo tests, one that widens the ImportLibrary tests and four that widen the prepare tests. #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.dll import 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, and FORCE_INTEGRITY set. They check that:

  • info describes the original image correctly: it is not a DLL, and the entry point, import IAT slots and TLS callbacks match.
  • The patched copy:
    • has IMAGE_FILE_DLL set, entry point 0 and checksum 0;
    • has FORCE_INTEGRITY cleared, with the other DLL flags unchanged;
    • points the import directory at the empty terminator with size 20;
    • zeroes the bound-import directory and the TLS callbacks pointer.
  • Only the relocation for the TLS callbacks pointer becomes IMAGE_REL_BASED_ABSOLUTE.
  • No other bytes change. The whole file is compared byte by byte.
  • An import directory whose size excludes the terminator gives the same result. This ports keeps_iat_slots_when_import_size_excludes_the_terminator.
  • With three import descriptors (one a differently cased kernel32.dll with 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.
  • An image without imports or TLS changes only in its headers.
  • file_name() is a stable victory-image-<16 hex of BLAKE3>.dll.
  • Empty, truncated and non-AMD64 input returns an error and doesn't panic.
  • After a simulated rebase (applying every DIR64 relocation with a delta, as Wine does for DYNAMIC_BASE images), 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 leave delta there.
  • The callbacks pointer's relocation is found in a later block; a HIGHLOW entry for the same RVA and the other DIR64 entries are left alone.
  • With no relocation directory, a size of 0, a directory outside the file, a block shorter than its header or longer than the directory, prepare still clears the callbacks pointer and rewrites no relocation entry.
  • TLS without callbacks leaves the relocations alone.
  • Preparing a prepared image changes no bytes, and a title that is already a DLL keeps its other file flags.
  • With a shorter optional header (10 directories, the section table right after them), the bound-import slot that would overlap the section header is not written, and the rest of the patch still happens.
  • Two DIR64 entries for the TLS callbacks pointer (as merged relocation tables can leave) both become no-ops, so a rebase still leaves the pointer at 0.
  • An import directory of only a terminator, recorded with a larger size, is pointed at itself with size 20.
  • With the relocations in a .reloc section 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.
  • An import directory with a size but no RVA is left as it is, and the rest of the patch still happens.
  • A relocation of a type x64 loaders do not define (5 to 9, 11 to 15) on the callbacks pointer, or four bytes before it, is taken as pointer-wide and becomes a no-op; one eight bytes before or past the pointer is left alone. Narrowing that assumed width to 2 bytes fails the test.
  • Every truncation of the image, and every byte set to 0x00 and to 0xFF in 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.dll import by name (with a hint) and by ordinal, and two TLS callbacks. They check:

  • Headers and sections: machine, DLL flag, timestamp, image base, entry point, subsystem and stack sizes.
  • Imports and their IAT slot RVAs.
  • TLS callbacks are read in order up to the null terminator. A callback below the image base is reported as malformed.
  • rva_to_file_offset:
    • section data maps correctly;
    • headers and the section end don't map;
    • raw padding past the virtual size isn't treated as section data;
    • an offset near 4 GiB doesn't wrap.
  • An IAT that runs past SizeOfImage, including at the 4 GiB limit, is Malformed.
  • A non-AMD64 machine is Unsupported, and truncated input returns an error without panicking.
  • A PE32 (32-bit) optional header is Unsupported.
  • ImportSymbol displays as its name or #<ordinal>.
  • The TLS callback walk stops at 1024 entries when an array of 1100 has no terminator.
  • With a second section (.data, virtual size 0), rva_to_file_offset maps 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.
  • When OriginalFirstThunk is 0, as old linkers leave it, import names are read from the IAT, with the same slots.
  • TLS edge cases:
    • a directory with no callback array is still reported, with no callbacks; an RVA of 0, or a header with too few directory slots, means no TLS;
    • a callback array in the last 8 bytes of the section, with no terminator after it, gives one callback;
    • a directory past the section or too close to its end, a callback array past the section or below the image base, and a callback 4 GiB or more above the base are all Malformed.

Each of these tests adds one optional directory to the same image, and only that test uses it:

  • Delay imports: USER32.dll!MessageBoxW is 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 past SizeOfImage, including at the 4 GiB limit, is Malformed.
  • Exports: a local export plus forwarders by name (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.
  • CodeView: an RSDS record gives the PDB path, GUID and age, and 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 whose SizeOfData is too short for the signature, GUID or age is malformed, while a short non-CodeView entry pointing past the file is never read.
  • Directory flags: has_relocations, has_exception_table and has_load_config follow their directory entries. RELOCS_STRIPPED overrides a leftover relocation entry, and an entry with size 0 counts as absent.
  • Subsystem names and the DLL flag: each named subsystem, plus other.
  • Fields that are never read: setting the other TLS directory fields (raw data VAs below the image base, an AddressOfIndex of u64::MAX), a delay descriptor's module handle, bound IAT, unload IAT and timestamp (all RVAs past SizeOfImage), the export directory's characteristics, timestamp and version, and the CodeView debug entry's characteristics, timestamp and version to garbage changes nothing ImageInfo reports. The same holds for the DOS header bytes between the magic and e_lfanew, a COFF symbol table pointer past the file with a huge symbol count, the optional-header fields ImageInfo doesn'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 .text with 0xEE changes nothing either, and parsing the same bytes twice (or cloning the result) gives the same ImageInfo.
  • layout helpers: the file header, optional header and data directory offsets match the image. An index at or past NumberOfRvaAndSizes, a truncated DOS header and an e_lfanew of u32::MAX all return None.

victory-pe: crates/victory-pe/src/implib.rs (4 unit tests)

implib.rs (the reader behind victory lib-exports) had no tests. The new tests build an in-memory !<arch> archive of short-format import objects. They check:

  • reads_short_imports_sorted_and_deduplicated:
    • Each name type is read correctly: by name, no-prefix (_Prefixed → Prefixed), undecorated (_Stdcall@8 → Stdcall) and by ordinal.
    • Each export keeps its code/data/const kind.
    • The output is sorted.
    • An export repeated under a different hint becomes one entry.
    • A member that isn't a short import object is counted in other_members.
  • rejects_what_is_not_an_archive: input that isn't an archive returns an error, and an empty archive has no imports.
  • reads_msvc_layout_with_linker_and_long_name_members: the layout lib.exe writes, 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 in other_members.
  • damaged_archives_and_members_do_not_panic:
    • Every truncation of an archive returns a result without panicking.
    • A member whose size runs past the end of the file, and a long name that points past the names table, return an error.
    • In an otherwise intact archive, an import object whose SizeOfData runs past the member, or one cut short inside its header, is counted in other_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 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. 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 --check on the three touched files: clean.
  • cargo test -p victory-loader --lib: the 2 new relocation tests pass; the 3 existing prepare::tests that parse the test binary still fail on Linux, as on main (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 .reloc test, 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 of NumberOfRvaAndSizes fails the short-header test, and stopping after the first callback relocation fails the duplicate-relocation test) and in image.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) and ImageInfo::rva_to_file_offset (which maps it by its raw size) find the TLS directory in different places. prepare then cleared 8 bytes of the headers, left the real callback pointer set, and returned Ok: the OS would have run the callbacks before any import was bound. prepare now re-parses the patched copy and returns PrepareError::Patch if the callback pointer is still set (a_section_table_that_hides_the_tls_directory_is_an_error; without the fix the copy keeps 0x140001140).

Data in a second section. In the other tests, all import, TLS and export data sits in .text. New tests add a .data section whose file offset is not the .text shift, and fill the file with 0xEE where 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 .data first in the section table changes only the order of sections. object reads 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 .text for any of them is Malformed, even though the same bytes are there. Only the IAT may be in another section. If rva_to_file_offset checks only the first section, 4 tests fail, including the new import and table-order tests.

Import library names. New implib tests cover IMPORT_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_PREFIX drops a single ?, @ or _, and UNDECORATE also drops everything from the next @).

On Linux, main still has 7 failing tests: 4 in image::tests and 3 in prepare::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.

SkippySteve added 3 commits November 23, 2026 21:26
…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.
@SkippySteve
SkippySteve force-pushed the SkippySteve/victory-pr-own-next15 branch from 82477e2 to b1ba679 Compare November 24, 2026 02:27
@SkippySteve SkippySteve changed the title Loader tests: prepare a synthetic image so patching is covered on every host PE/loader tests: hermetic synthetic images for ImageInfo, ImportLibrary and prepare Nov 24, 2026
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.
muhammed-aksoy pushed a commit to muhammed-aksoy/VIctory that referenced this pull request Nov 24, 2026
SkippySteve added 3 commits November 23, 2026 21:40
…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.
muhammed-aksoy pushed a commit to muhammed-aksoy/VIctory that referenced this pull request Nov 24, 2026
SkippySteve added 5 commits November 23, 2026 21:56
…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.
edsuuu referenced this pull request in edsuuu/VI-BR-PORT Nov 24, 2026
…fo, ImportLibrary and prepare

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SkippySteve added 5 commits November 23, 2026 22:35
…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
@jeremygold02

jeremygold02 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Tested the current open PR at head d6f7fd2616fd8bf592c876b61d6851ae12323abc (head and discussion refreshed before this edit).

  • cargo test --locked -p victory-loader --lib relocation — passed 4 tests: a_relocation_overlaps_the_bytes_it_writes, relocation_entries_know_each_width_and_the_highadj_parameter, relocation_entries_walk_blocks_and_skip_padding, and relocation_entries_drop_targets_past_the_top_of_the_address_space.
  • cargo test --locked -p victory-loader --test synthetic_prepare — passed 28 tests, including HIGHADJ, 32-bit callback-field relocations, and refusal of relocation/TLS RVAs outside valid headers/sections.
  • cargo test --locked -p victory-pe --test synthetic_image — passed 41 tests.

The branch advanced from b95118f43883654db068e028a35e1ae3fbabe6a1 after the earlier 22/37 synthetic test pass; the results above are a fresh run on the current head. The earlier dir64_entries_ filters (in victory-pe, then in victory-loader) each matched zero tests after the helper was renamed to relocation_entries; the loader relocation tests above provide the actual coverage. These tests use synthetic PE data only.

Code: prepare.rs, synthetic_prepare.rs, synthetic_image.rs.

SkippySteve added 4 commits November 23, 2026 23:18
…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
SkippySteve added 4 commits November 24, 2026 00:30
…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
SkippySteve added 10 commits November 24, 2026 00:50
…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 catminou4 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.

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.rs 43 passed, tests/synthetic_image.rs 100 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.

SkippySteve added 12 commits November 24, 2026 02:34
…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
… short records are malformed, and unread DOS, COFF symbol, optional-header, section and import-descriptor fields
…aring a name table and IAT, and delay descriptors without a name table
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