Skip to content

PE inspection: audit the package dependency graph before first boot - #6242

Open
ODanielAtaide wants to merge 4 commits into
ItsNotRexed:mainfrom
ODanielAtaide:boot/pe-package-import-graph
Open

ODanielAtaide wants to merge 4 commits into
ItsNotRexed:mainfrom
ODanielAtaide:boot/pe-package-import-graph

Conversation

@ODanielAtaide

Copy link
Copy Markdown

What this adds

First-boot PE inspection currently lists only the executable’s direct imports. Add an opt-in --dependencies pass and enable it in scripts/first_look.ps1. It follows normal and delay imports through local package DLLs, lists each image once even in a cycle, and records the shortest chain to each image. The Markdown report points to absent or unreadable DLLs, machine mismatches, ambiguous file names, and names or ordinals absent from the local export table.

This is a read-only inventory of the package, independent of the runtime build. A forwarded export counts as a declaration. Windows and shim binding behavior can be measured with the existing --dry-run. This complements #5732, which classifies shim coverage for explicitly supplied images.

Claim: #6089 (comment)

Validation

  • Windows CPU, Python 3.14: test_pe_inspect.py, 63 passed, 1 existing symlink test skipped. The four new tests cover transitive normal and delay imports, a cycle, a forwarded export declaration, named and ordinal lookup, unreadable and mismatched DLLs, and report path protection.
  • The first_look.ps1 integration test exercises the real inspector and checks the transition from missing to unreadable when a DLL appears. It fails on unmodified main because the graph is absent. The exit-code integration test also passes.
  • With the independent test-harness fix tests: stub gdk_runtime_calls, find_hash_lookup and exe_checklist in test_first_look_rebuild #6133 applied in a separate checkout, all six first-look tests pass. The four existing rebuild assertions fail on unchanged main because the harness omits three tool stubs.
  • Parsed two stock Windows executables with a local copy of their first shared dependency. Also passed py_compile, PowerShell syntax validation, and git diff --check.

No game files or GPU execution. AI-assisted.

Follow normal and delay imports through package images and report the dependency chain for missing files, unreadable images, architecture mismatches and missing exports.

AI-assisted.
@shdann

shdann commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

The new dependency graph retains a quadratic number of module references for a linear DLL chain at 5094af7c. Each module stores a fresh copy of its parent's full chain plus its own name. Each DLL is inspected once, but the JSON repeats every prefix.

Modules Import edges Names stored across chain lists Graph JSON bytes (json.dumps)
32 31 528 12,580
64 63 2,080 37,572
128 127 8,256 124,420
256 255 32,896 445,572

Every import resolved in this synthetic test. One predecessor per module preserves the shortest path chosen by breadth-first traversal. Reconstruct full chains for diagnostics when needed. If the JSON must include every full chain, its output size has the same quadratic lower bound.

Reproduce from the repository root with py -3.14 -I -. The files come from the PR's own fixture builder.

import json, runpy, tempfile
from pathlib import Path
t = runpy.run_path("tests/test_pe_inspect.py")
for n in (32, 64, 128, 256):
    with tempfile.TemporaryDirectory() as d:
        root = Path(d)
        names = ["test.exe"] + [f"m{i:03}.dll" for i in range(1,n)]
        for i,name in enumerate(names):
            refs = [(names[i+1], ["Start"])] if i+1 < n else []
            (root/name).write_bytes(t["package_image"](refs,exports=t["with_exports"]([0x1000],{0:"Start"})))
        graph = t["pe_inspect"].inspect(str(root/names[0]),str(root),dependencies=True)["dependency_graph"]
        assert all(e["status"] == "declared" for e in graph["imports"])
        print(n,len(graph["imports"]),sum(len(m["chain"]) for m in graph["modules"]),len(json.dumps(graph).encode()))

On Windows, 63 PE inspector tests passed and one skipped. The first-look report integration test passed. The new cycle test fails against 561b65a8, which lacks the dependency graph.

AI-assisted.

@Kev-Ball

Kev-Ball commented Nov 23, 2026 •

Copy link
Copy Markdown

Ran the --dependencies CLI at 5094af7c on CachyOS with 17 package PE roots: 16 DLLs and one PE-format catalog. The catalog was the root with zero static import edges. I originally called that root the executable; the title executable was absent from this run. See the retest below for the verified title executable.

Across the DLL roots I counted 325 distinct (source, imported DLL, import kind) edges, all normal imports. Of these, 30 resolved locally with every requested export declared. The other 295 were classified not_in_package on this Linux host. That status describes package contents and does not establish whether an import would bind on Windows.

I recomputed reachability and shortest distances from the individual direct-import reports and case-insensitive directory membership. Both matched the new graph for all 17 roots. One DLL root reached depth two, 13 reached depth one and two had no local dependencies. All visited local modules parsed successfully. The long-chain and delay-import cases remain covered by synthetic fixtures. AI-assisted, CPU only.

Keep a single predecessor per image and reconstruct paths only for Markdown findings. Collect all inspected DLLs before writing a batch of reports. Regression tests cover a deep chain and a file another report would overwrite.

AI-assisted.
@Kev-Ball

Kev-Ball commented Nov 23, 2026 •

Copy link
Copy Markdown

Retested the predecessor change at af7ba1b2 with the same 16 DLLs and one PE-format catalog passed to a single --dependencies invocation. It produced all 17 JSON/Markdown pairs. Reconstructing the chains from the new parent links reproduced every old chain across the 48 module entries. After substituting those reconstructed chains, all 17 parsed JSON reports matched the earlier revision in full. All 17 Markdown reports also remained byte-identical, including the rendered diagnostic paths.

This covers the batch CLI and the externally visible diagnostics on the same Xbox 1.0.2.1 package as the earlier check. CachyOS x86-64, CPU only, AI-assisted.

Retested the ordinal-matching change at d1b88de78 against its direct parent 6c2ef3c50 with the SHA-256-verified Xbox 1.0.2.1 title executable as the root and the package folder as --game-dir. The executable directly imports 587 functions across 68 normal import descriptors, including 24 ordinal imports. The dependency walk visited 8 local images and reported 195 edges. The full JSON and Markdown reports were byte-identical between revisions. This adds the title root to the preceding catalog/DLL checks. The synthetic regression still supplies the name-versus-ordinal collision case. AI-assisted.

@ODanielAtaide

Copy link
Copy Markdown
Author

Thanks for the reproducer. Updated in af7ba1b2: each module stores one parent from the breadth-first walk. Markdown reconstructs the full path only for a finding. On the same 32/64/128/256/512-module synthetic chains the updated graph sizes are 6,590 / 13,310 / 26,750 / 53,630 / 107,390 bytes. The old 512-module graph was 1,677,700 bytes.

I also reproduced a batch-output collision: the first entry's report could overwrite a DLL imported only by a later entry. The CLI now collects all inspected inputs before writing. The regression test verifies the would-be output survives and the later report can still resolve its export.

Windows CPU: 65 PE inspector tests passed, one symlink test skipped. The first-look report and exit-code integrations passed. AI-assisted.

@daemosofchaos

Copy link
Copy Markdown
Contributor

Independent Windows 11 / Python 3.12 review of af7ba1b2 (CPU only, synthetic PE fixtures):

  • test_pe_inspect.py: 66 tests passed. The first-look dependency-report integration and exit-code integration each passed.
  • An additional diamond-and-cycle graph check confirmed that the leaf keeps the first shortest BFS parent and that a missing delay import appears on the reconstructed path.
  • A separate batch-output test used a real NTFS hard link: the first report's Markdown path aliased a dependency only reached from the second input. This head refused the first report, preserved the dependency bytes and still classified the second input's dependency as declared. The same test against previous revision 5094af7c failed because it overwrote the synthetic dependency through the hard link.

Environment note: the first-look exit test initially failed on both revisions in my PowerShell 7-launched session because its inherited PowerShell module path interfered with Windows PowerShell's Get-FileHash. Limiting PSModulePath to Windows PowerShell's module directory in the parent process made the test pass; no system settings changed. That is a pre-existing test-environment issue, not a demonstrated regression in this PR.

These checks establish the tested synthetic behavior, not actual package bindings or boot success. No game files or GPU were used. AI-assisted review.

— LocalFirst-AI

@Kam471

Kam471 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Head af7ba1b27 (2 commits, 5 files, +344/−32): tools/pe_inspect.py, scripts/first_look.ps1, docs/boot.md, and two test files. No runtime C++ and no boot-path change. git diff --check clean.

Windows 11, Python 3.13: python -I -m pytest tests/test_pe_inspect.py tests/test_first_look_shim_report.py -q → 66 passed, 1 skipped, 616 subtests passed.

End-to-end on a real package member (amd_fidelityfx_upscaler_xbox.dll, --game-dir the package): exits 0, reports "4 image(s) ... 87 import descriptor(s)", and correctly flags d3d12_xs.dll and xmem.dll as not in the package with the exports they need. Read-only; nothing is loaded.

Verdict: good pre-boot audit tool and docs, works as described, and the failure paths (absent, unreadable, machine mismatch, ambiguous name, missing export) are covered by tests. It is diagnostic only: it cannot change the first frame. Applies cleanly to exe-day-merge and current main; runtime regression risk is zero.

Keep the first-look hash lookup and dependency graph assertions and stage their report path helper in the test fixture.
@ODanielAtaide

ODanielAtaide commented Nov 23, 2026 •

Copy link
Copy Markdown
Author

@ItsNotRexed Could you approve the fork workflows for 6c2ef3c5 and review #6242?

I merged upstream main at 511e3826 and resolved the conflict in the first-look test. The fixture checks both the dependency graph and the hash lookup report, with their shared report-path helper staged.

On Windows 11 with CPython 3.14, the PE inspector suite passed 65 tests with one skip. All six first-look integration tests passed. A separate read-only parser check on a local x64 executable produced 68 import records. The sample's build version remains unverified.

The No Game Data and whitespace checks passed. AI-assisted (Codex).

Additional Windows check with the same executable and a separate local DLL directory. The read-only dependency walk visited 8 PE images and recorded 195 imports. Of those, 18 had a declaration in a local DLL, 167 were host candidates, and 10 remained unresolved across 7 distinct library names. Version alignment and loader binding remain unverified.

@kapitche

Copy link
Copy Markdown
Contributor

Tested 6c2ef3c merged with main 1ce6eb5 on Linux/Python 3.12.16 and Windows/Python 3.13.1: pass

Merge was clean on both (tools/pe_inspect.py, scripts/first_look.ps1, tests/test_pe_inspect.py, tests/test_first_look_shim_report.py, docs/boot.md).

Linux, 3.12.16:

  • python -I tests/test_pe_inspect.py: Ran 66 tests, OK (skipped=1).
  • Negative control (tools/pe_inspect.py restored from upstream/main, tests from the PR): Ran 66 tests, FAILED (failures=3, errors=3, skipped=1). PR version restored afterwards.

Windows, 3.13.1 (worktree of main with the PR merged):

  • tests\test_pe_inspect.py: Ran 66 tests, OK. tests\test_first_look_shim_report.py: Ran 1 test, OK. tests\test_first_look_exit.py: Ran 1 test, OK.
  • On main alone (same worktree checked out at main), test_first_look_shim_report.py FAILS (test_retry_with_last_missing_dll_supplied) and test_first_look_exit.py is OK, so this PR's change to that test and to first_look.ps1 is what makes it pass here.

Diff read: --dependencies follows normal and delay imports breadth-first through the chosen folder with strict parsing, reports each edge as declared, missing exports, not in the package, host candidate, ambiguous (several files differing only by case) or invalid name, and never joins an image-supplied name to a path before rejecting separators. I did not run it on a real package.

Overlap: #7084 (open) rewrites classify_dll and the import/report code in the same tool, so the two PRs are likely to conflict.

Keep name and ordinal identities distinct in dependency matching and preserve the report format.
@ODanielAtaide

Copy link
Copy Markdown
Author

hey @ItsNotRexed, could you take a look at #6242 when you get a chance? the windows tests passed on d1b88de. just waiting on approval to run the checks, thanks!

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.

6 participants