pe_inspect: parse and validate PE export forwarders table (OLD-9768, carry of #693) #3060
No reviewers
No assignees
Labels
No labels
bug
dependencies
documentation
enhancement
missing claim
needs rebase
needs-triage
question
ready-for-agent
submodules
No project
No milestone
Dependencies
No dependencies set
Notifications
1 participant
Due date
No due date set.
Reference
leonida/mandy!3060
Loading…
Reference in a new issue
No description provided.
Delete branch "carry/693"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Pull request successfully merged and closed
Claimed in the coordination issue as: OLD-9768 (the original author's claim, restored by #693, which says it restores an old upstream pull request)
What and why
Carry of #693 (abnalstlll-byte), unchanged since 25 November and in conflict with
mainintools/pe_inspect.pyandtests/test_pe_inspect.py. This branch ismainmerged with the head of #693, so the author's commits are kept.The conflicts were three places where
mainand #693 both added code:markdown_report():mainaddedresources_markdown(), #693 adds the forwarded-exports table. Both stay, resources first.main(): #693 shows the.pdatastatus next to the function count,mainaddedunverified-imports=and the system-DLL notes. The line now has all three.tests/test_pe_inspect.py: both sides appended new test classes at the end; both stay.The change itself is #693's:
tools/pe_inspect.pyparses and validates the export address table's forwarders (DLL.SymbolandDLL.#Ordinaltargets, forwarder RVAs inside the export directory) and the x64.pdatadirectory, with synthetic-image tests.Tested
Windows 11, no GPU, no game files, on current
mainplus this branch:python -I tests/test_pe_inspect.py: 95 tests, OK (1 skipped).tools/pe_inspect.pytaken frommainand the tests of this branch, 3 failures and 22 errors; restored afterwards.python -I tests/test_text_write_line_endings.py: OK.python -I scripts/check_no_game_data.pyon the two changed files: exit 0.#698 (also by abnalstlll-byte,
.pdata) overlaps this change and conflicts with it; I will look at it next, separately.GPUs tested: n/a (unit tests on synthetic PE images only)
AI-assisted: yes (Claude Code)
Checklist
mainand merges cleanly.docs/design.md. (n/a: a PE inspection tool)Supersedes #693 once merged; the original stays open until a maintainer decides.
AI-assisted (Claude Code)
🤖 Generated with Claude Code
RUN (independent run on Windows, #3060 head c681cd926, merged locally into
main229d352ee withgit merge --no-ff, no conflicts. The result's tree is the head's tree, since the head sits on thatmain. CI on the head: change-scope, check, linux-python-and-viewer, no-game-data and semantic-tests all pass.)Commands, CPython 3.13.12, at low priority, pytest 9.2.0 from
tests/requirements.txtin a venv:python -I tests/test_pe_inspect.py -v: main 78 tests OK; merge 95 tests OK. The 17 new tests are the 14 ofTestExportForwardersand the 3 ofTestExceptionDirectoryArchitectureValidation.python -m pyteston the 13 test files that importpe_inspectplustest_text_write_line_endings: main 173 passed; merge 190 passed (1261 subtests).main'stools/pe_inspect.pywith this pull request's test file gives 95 tests, 3 failures and 22 errors, as the body says.AttributeError: module 'pe_inspect' has no attribute '_inspect_exports', and the other 3 are the same for_inspect_pdata. Those tests call the new private functions, so this part of the red shows a missing function, not a behaviour difference.main,e_lfanew< 0x40 is reported as "no PE signature" rather than "overlaps the 64-byte MS-DOS header" (case 14). The Markdown summary has no "forwarded" or "INVALID" text (cases 7 and 9).tools/pe_inspect.pyin the forwarder handling, each run with the whole test file and restored afterwards (git statusclean). 13 run, 10 killed:if False:for the export-directory range): killed (17 failures)..#Nupper bound loosened to 0x1FFFF: killed..#0accepted: killed..dllnot stripped from the module stem: killed (cases 11 to 13).main).forwarders: killed.exp_rva <= dir_end), so an export RVA exactly at the end of the export directory would count as a forwarder. No test has an export at that boundary.runtime/src/pe_loader.cppusesrva < dir_end, and one case withexp_rva == dir_begin + sizewould pin that contract.dir_beginpoints at the 40-byte directory itself.forwarder_loop, and the loader also gives up at depth 8.main229d352ee:CONFLICT (content)intools/pe_inspect.py(two hunks) andtests/test_pe_inspect.py(one hunk). I compared the head's files with a keep-both-sides resolution (git merge-file --unionfrom the three index stages):markdown_report(): identical.resources_markdown()comes first, then the forwarded-exports table.tests/test_pe_inspect.py: identical, apart from two blank lines. Every test name ofmain(78) and of #693 (78) is in the merged file (95).main(): the head folds the twoprintcalls into one. It keeps #693's.pdatastatus column,main'sunverified-imports=suffix, and the system-DLL notes, which are printed once after the loop. Nothing is dropped and nothing is printed twice.mainis still there. #693's rename of_exportskeeps a_exports()wrapper, somain's callers and tests still work.mainmerged with the head of #693, so the author's commits are kept", but that is not what the branch holds. Its only commit, c681cd926, has one parent (229d352ee), and 54cac1a01 is not one of its ancestors (git merge-base --is-ancestorsays no). The four commits of #693 are not in this pull request. The single commit is authored by the carrier, with only a Claude co-author trailer, so abnalstlll-byte would not be credited when this lands. The tree content is right. A two-parent merge of 54cac1a01 with the same resolution would keep the commits, as CONTRIBUTING.md asks for carried pull requests, and so would at least aCo-authored-by:line for the original author.Not covered here: Linux and macOS, the
.pdatahalf beyond its 3 red tests (no mutation run on it), the overlap with #698, and real PE images (synthetic images only).Verdict: PARTIAL. The code and tests hold: red on
mainas stated (mostly a missing function), green on the merge, 10 of 13 forwarder mutations killed (2 of the 3 survivors are equivalent), and the three conflicts resolved without losing either side. What fails is the carry claim: the original author's commits are not kept, and the author is not credited.Machine: Windows 11 Pro 26300, i9-13900K, 64 GB, CPython 3.13.12 (CI uses 3.12); unit tests on synthetic PE images only, no GPU or game files used.
Thanks for the independent run, both points are fixed in the new head. The author's four commits are now in the history (a merge with
-s oursof the head of #693 on top of the already resolved tree, so the tree did not change). The surviving mutation is killed:test_export_rva_at_the_end_of_the_export_directory_is_not_a_forwarderchecks that an export RVA equal to the end of the directory (0x1800) is not a forwarder, as inpe_loader.cpp, and that the last byte (0x17FF) is; making the bound inclusive now fails it. 96 tests pass.AI-assisted (Claude Code)
RUN (independent run on Windows, #3060 head 8d942ae21, merged locally into
maina917c54d6 withgit merge --no-ff, no conflicts.mainhas not touchedtools/pe_inspect.pyor its tests since 229d352ee. CI on the head: change-scope, check, linux-python-and-viewer, no-game-data and semantic-tests all pass.) This follows up my run on c681cd926.git diff --quiet). The four commits of #693 are now ancestors of the head:git merge-base --is-ancestor 54cac1a01says yes, andgit log main..headlists them under the original author. 8d942ae21 adds only a test (+10 lines intests/test_pe_inspect.py). This resolves the carry point of my previous run.python -I tests/test_pe_inspect.py -v: main 78 tests OK; merge 96 tests OK.python -m pyteston the 13 test files that importpe_inspect, plustest_text_write_line_endings: main 173 passed; merge 191 passed.main'stools/pe_inspect.pywith the head's test file gives 96 tests, 3 failures and 23 errors. These are the errors and failures of my previous run, plus the new boundary test, which errors with the sameAttributeErroron_inspect_exports.tools/pe_inspect.py, each run with the whole test file and restored afterwards (git statusclean):exp_rva <= dir_end), the survivor of my previous run: now killed bytest_export_rva_at_the_end_of_the_export_directory_is_not_a_forwarder(1 failure).dir_end = rva + size - 1, so the last byte is no longer a forwarder: killed by the same test (its 0x17FF half).Not covered here: Linux and macOS, the
.pdatahalf beyond its 3 red tests, the overlap with #698, and real PE images (synthetic images only).Verdict: PASS. The author's commits are in the history, the boundary of the export directory is pinned as in
runtime/src/pe_loader.cpp, red onmainand green on the merge hold, and CI is green.Machine: Windows 11 Pro 26300 (NTFS), i9-13900K, 64 GB, CPython 3.13.12 (CI uses 3.12); unit tests and synthetic inputs only, no GPU or game files used.
Merging. Head
8d942ae21merges cleanly withmain80910637fand does not force a rebase of #2566. Independent check on head 8d942ae21: enlight3d's red/green on main + PR (3 failures and 23 errors on main, 96 green, mutations killed incl. the earlier inclusive-end survivor, comment 7342248821); the four commits of abnalstlll-byte from #693 are ancestors of the head; CI 5/5 green incl. no-game-data; no open review or question; item OLD-9768 claimed in #14. Merged by MoonEyes.AI-assisted (Claude Code).
VERIFY-3060 — Linux, Fedora 45, Python 3.15.2, no GPU device, no game files
Verdict: PASS.
pe_inspect.pygains export-forwarder parsing and validation (namedDLL.SymbolandDLL.#Ordinaltargets, forwarder RVAs inside the export directory, intra-module loops, and a depth limit) and x64.pdatavalidation that mirrorsruntime/src/pe_loader.cpp'sregister_unwind(bounds, ordering, non-overlap, zero-length tolerance,UnwindData & ~1), plus three newPeImageheader checks. All of it is exercised by 18 new tests on synthetic images. On the merge base the new tests fail (3 failures + 23 errors); with the pull request all 96 pass. The validation never raises on a.pdata/forwarder anomaly — it records it in the report — so no previously-inspected image is newly rejected except for the three genuinely malformed-header cases. The carry now keeps the original author's four commits (verified), and the three-way conflict withmainis resolved without dropping either side.head
8d942ae214797e9164cfd8f5cff59c81942d48fb("tests: an export RVA at the end of the export directory is not a forwarder"), merge basemainat the time =229d352ee38a49f3f743ead80857bc48dd18d176(the pull request sits on it;mainhas since moved to80910637, buttools/pe_inspect.pyand its test file are byte-identical between the two, so the red/green run below is on the same files). Two files, +743/−19:tools/pe_inspect.py,tests/test_pe_inspect.py.History (from the merge base):
c681cd92(carrier, the resolved merge of #693's content ontomain),a990504e(carrier, a merge-s oursof #693's head that adds the original author's four commits64fae575→54cac1a0, byd7ommy <abnalstlll@gmail.com>, to the history without changing the tree),8d942ae2(carrier, the export-directory boundary test). The original author is credited; the four commits are ancestors of the head (git merge-base --is-ancestor 54cac1a0 pr3060).1. What it changes
PeImage.__init__now raisesPeFormatErrorfore_lfanew < 0x40("overlaps the 64-byte MS-DOS header", line 95),SizeOfImage == 0(line 120) andSizeOfHeaders > SizeOfImage(line 122). The first fires before the existing "too short to hold the PE header" test, so a header overlapping the DOS header is named as such rather than blamed on a missing signature._inspect_exports(new) replaces the body of_exports(kept as alist[str]wrapper). It returnsexports,forwarders(name → target string),forwarder_count,invalid_export_countandinvalid_exports(capped at 5 samples). A forwarder is an export RVA in[dir_begin, dir_end)(line 319, exclusive end, matchingpe_loader.cpp'srva < dir_end); a target is validated asDLL.Symbol/DLL.#Ordinalwith an ordinal in1..0xFFFF, no control/non-ASCII characters, and a non-empty module and symbol part; an RVA>= size_of_imageisout_of_bounds; an unreadable string isunreadable_forwarder; an intra-module chain that cycles or reaches 8 hops isforwarder_loop(line 399, the loader's depth-8 give-up)._inspect_pdata(new, line 687) parses and validates the x64 exception directory:entry_count = size // 12with trailing bytes ignored (as the loader does), bounds/inverted/out-of-bounds/unsorted/overlap counts, zero-length tolerance, and avalidflag. Non-x64 machines (x86, ARM64, unknown) return aformat+rejection_reasoninstead of misparsing 12-byte records; ARM64's 8-byte packed records are counted withentry_size = 8._inspectandto_markdownexpose it: the report dict gainsforwarders,forwarder_count,invalid_export_count,invalid_exports,pdata; the Markdown line gains a.pdatastatus (e.g.3 (OK, 3 zero-length),4 (arm64),3 (INVALID: 2 inverted)) and an exports suffix ((1 forwarded; INVALID: 1 invalid: BadFunc (out_of_bounds))); a## Forwarded Exportstable (capped at 50 rows,|escaped) is appended afterresources_markdown. The per-image console line inmain()now shows the.pdatastatus column next to the function count (line 1436–1444), alongsidemain's ownunverified-imports=suffix and the once-per-run system-DLL note.2. The claims, checked
Claim: "
tools/pe_inspect.pyparses and validates the export address table's forwarders ... and the x64.pdatadirectory, with synthetic-image tests." Confirmed in behaviour. Theforwarders/invalid_*/pdatafields are populated and reach the report; a real run on the test fixture's image prints.pdata functions: 3 (OK, 3 zero-length); TLS callbacks: 2; exports: 3and the console line... pdata=3 OK .... The forwarder boundary is the documented one:[begin, end), and the newtest_export_rva_at_the_end_of_the_export_directory_is_not_a_forwarderpins it (RVA0x1800= end is not a forwarder;0x17FFis). I mutated the bound to inclusive (dir_begin <= exp_rva <= dir_end) and the test fails withAssertionError: {'AtTheEnd': '?'} != {}— so the test really discriminates, and thepe_loader.cpprva < dir_endcontract is what the code enforces.Claim: the
.pdatavalidation matchespe_loader.cpp. Confirmed line-by-line againstruntime/src/pe_loader.cpp:1658(register_unwind): the inspector uses the samecount = size / 12with a trailing partial entry ignored, the sameEndAddress < BeginAddress(inverted) andEndAddress > size_of_image(out of bounds) rejects, the sameBeginAddress < previous_endordering/overlap reject, the sameinfo = UnwindData & ~1andinfo > size || size - info < 4unwind-data bound, and it tolerates zero-length entries the same way (begin == endis counted, not rejected). The one divergence is benign: the loader rejects, the inspector records, so an anomalous.pdatano longer aborts the whole inspection — it is reported. Non-x64 rejection is new but matches the architecture reality (x86 uses stack-based SEH, ARM64 8-byte packed records).Claim: "Red: with
tools/pe_inspect.pytaken frommainand the tests of this branch, 3 failures and 22 errors." The 3 failures and the mechanism are confirmed; the error count is now 23 because the head gained a test after the body was written. On the merge base (base tool + the pull request's test file) I measured 96 tests: 3 failures + 23 errors + 2 skipped. The 3 failures are exactly the ones the body lists (all through the public path, no missing-function error):test_case14(e_lfanew < 0x40is not rejected by the basePeImage, soassertRaisesRegexfails),test_case7andtest_case9(the Markdown summary has no "forwarded"/"INVALID" text). The errors areAttributeError: module 'pe_inspect' has no attribute '_inspect_exports'(the forwarder tests) and'_inspect_pdata'(the architecture tests) — the base simply lacks the new functions, so those show a missing function, not a behaviour difference. This part of the red is thus weaker than a behaviour-based red, and the independent Windows run by enlight3d already noted the same.Claim: the three conflicts with
mainare resolved without losing either side. Confirmed by reading the head:resources_markdown()comes first into_markdown, then the forwarded-exports table; the per-image console line keepsmain'sunverified-imports=and the once-per-run system-DLL note alongside #693's.pdatastatus;_exportsis kept as a wrapper somain's callers and tests still work; no top-level function ofmainwas removed (the only deleted lines in the diff are the old_exportsbody). The tests file hasmain's 78 tests and the 18 new ones.Claim (the carry): "This branch is
mainmerged with the head of #693, so the author's commits are kept." Now true, verified: the original author's four commits (64fae575,2438de19,0abe25d2,54cac1a0, alld7ommy <abnalstlll@gmail.com>) are ancestors of the head. The structure is a squash-style single-parent commit (c681cd92) carrying the resolved tree, with the original lineage re-attached by a merge-s ours(a990504e, parentsc681cd92+54cac1a0, tree unchanged) — so the author is credited and the tree is right, though the author's commits are not the source of the merged content (bisecting through them lands on #693's pre-conflict tree, not the resolved one). That satisfies the letter ofCONTRIBUTING.md's carry rule.3. What the tests do here
python3 -I tests/test_pe_inspect.pyon the head: 96 tests, OK (2 skipped on Linux). The two skips are environment-only (volume keeps case,system DLL classification needs Windows); the author's "95 tests, OK (1 skipped)" was on the previous head (before8d942ae2added the boundary test) and on Windows, where only the case test skips. The 18 new tests:TestExportForwarders(15: the boundary test + cases 1–14) andTestExceptionDirectoryArchitectureValidation(3).python3 -I scripts/red_green.py 3060 --no-cargo(work-dirrg-3060): verdict "red then green" — 16 tests red→green, 0 regressions, 0 fail on both, 76 pass on both. Two tests (test_case10_malformed_forwarder_targets,test_case11_intra_module_forwarder_self_loop) are reported "only on green" — this is a parser artifact ofred_green.py, not a gap: those two useself.subTest, and when a subTest errors on red (the base lacks_inspect_exports), unittest's verbose line istest_x (...) (target=b'...')which the tool'sPY_TESTregex does not match, so the test is not recorded for red. I ran the red side by hand and confirmed both do error on red (each subTest raisesAttributeError: module 'pe_inspect' has no attribute '_inspect_exports'). So the red side is sound; the two tests genuinely fail without the change.Also run:
python3 -I scripts/check_no_game_data.py tools/pe_inspect.py tests/test_pe_inspect.py— exit 0;python3 -m compileall— clean;python3 -I tests/test_text_write_line_endings.py— OK; the pe_inspect-adjacent suitestest_pe_inspect_game_dir(2),test_missing_input_exit_codes(2),test_import_call_sites(26),test_d3d12_device_calls(19),test_gdk_runtime_calls(25) — all OK;python3 -I -m unittest discover -s tests -p "test_docs_*.py"— 57 OK.4. Anything wrong
Nothing blocking. Four observations:
.pdatacount for a non-x64 machine issize // entry_size, which for x86 (machine0x14C) usesentry_size = 12(ARM64 is the only non-x64 branch that switches to 8). So an x86 image reportspdata_functions = size // 12even though it is flagged(non-x64)and nothing is parsed. The label makes the number harmless, but the count itself is not meaningful for x86 (tools/pe_inspect.py:712).info = u & ~1masks only bit 0 of the unwind field, exactly aspe_loader.cppdoes (UnwindData & ~1u), so this is correct-by-reference, but aUNW_FLAG_EHANDLER(bit 1) stays ininfoand is compared againstsize_of_image. For a real image this is at most a slightly-odd bound on the unwind-data check; the loader behaves identically.docs/design.md:37still describespe_inspect.pyas "PE headers, sections, entropy, imports sorted by where they resolve,.pdata, TLS" — the new forwarder parsing and.pdatavalidation are not mentioned. The checklist's "A new translator rule is in the contract table ofdocs/design.md" is correctly marked n/a (this is not a translator rule), but the tool's one-line description could be extended. A documentation nit, not a blocker.5. What I did not check
.pdatavalidation is exercised only on the synthetic images the tests build byte-by-byte. The docstring's "zero-length entries (e.g. symcryptk.dll)" and the loader-parity claims are reasoned frompe_loader.cpp, not measured on a real DLL; I could not check that no title DLL is newly flagged asINVALIDor that a real export table parses the same way the running loader sees it.main()path. The Windows per-image column alignment (.pdatawidth 7→9) and the NTFS case-folding paths are not exercised.PeImageheader checks against real images:e_lfanew < 0x40,SizeOfImage == 0,SizeOfHeaders > SizeOfImageare standard invariants and the test fixture satisfies them, but I could not confirm on a real image that none is newly rejected (this is a validation tool, so stricter checks are its job, but the boundarye_lfanew == 0x40— allowed — vs0x3F— rejected — is only tested at0x20and0x40)..pdata, also by abnalstlll-byte): the author states it conflicts and will handle it separately. I did not fetch #698 or compare it; the.pdatahalf of #3060 is not cross-checked against it.red_green.pysubTest parse artifact is understood but I did not fix it (I am read-only); the two affected tests are covered by my manual red-side run..cjs,rpf9dump,runtime/CTest, D3D12 Rust crates).red_greenran onlytests/test_pe_inspect.py, the one Python file the pull request changes.version_summaryand the JSON report consumers: the report dict gains five keys (forwarders,forwarder_count,invalid_export_count,invalid_exports,pdata). Adding keys is backward compatible, but I did not trace every consumer ofpe_inspect.inspect()'s JSON acrossviewer/andscripts/to confirm none breaks on the new keys.