Skip to content

feat(pe): share one image-layout owner and read the exception directory - #7024

Closed
NgLanNg wants to merge 6 commits into
morluto:mainfrom
NgLanNg:feat/pe-image-layout-and-exception-directory
Closed

NgLanNg wants to merge 6 commits into
morluto:mainfrom
NgLanNg:feat/pe-image-layout-and-exception-directory

Conversation

@NgLanNg

@NgLanNg NgLanNg commented Oct 24, 2026 •

Copy link
Copy Markdown

Summary

PE header, section-table and data-directory facts now have one shared owner, and a new
reader exposes the image's exception directory as measured function extents.

PeImageLayout owns header admission, the section table, data directories, virtual
extent and file-backed RVA mapping, with tagged failure reasons. PeResourceLayout
delegates its header and section facts to that owner and keeps only the
resource-specific mapping rules and their messages.

PeExceptionDirectory decodes the exception directory as RUNTIME_FUNCTION records
and reports partial coverage and tagged failures instead of silently dropping extents
that no section maps.

Problem and expected behavior

PE header and section-table facts were parsed in more than one place, so two readers
could disagree about the same image. A reader that wanted a function boundary had no
supported way to obtain one: the exception directory is the authoritative source for
x64 function extents, and nothing read it.

Expected: one owner for PE image facts, and a way to ask an image for its measured
function extents with explicit failure reasons and coverage.

Change and scope

PeImageLayout becomes the single owner for MZ/PE header admission, the section
table, data directories, virtual extent and file-backed RVA mapping. PeResourceLayout
keeps its own resource mapping semantics — an empty interval still resolves at a
section's virtual end, a zero-extent section owns no byte, and an ambiguous interval
still fails — and only its messages.

PeExceptionDirectory reads the exception directory and reports each measured extent,
the coverage it achieved, and a tagged reason when the directory is absent,
inconsistent, unmapped, not file-backed, empty or malformed.

No target execution, no injection, no memory mutation, no protection recovery. This is
static format inspection of an artifact the caller already possesses.

Contract and boundary impact

  • Semantic owner and earliest changed stage: src/native/pe/PeImageLayout.ts owns PE
    image facts; PeResourceLayout consumes it. Native artifact inspection stage.
  • Contribution scope fit and linked maintainer decision: supported — "format
    inspection", "ordinary archive and standard-compression extraction, disassembly,
    decompilation, cross-references". No new provider, no target execution, no
    protection recovery. Not applicable.
  • CLI and MCP/tool-catalog contract: no CLI command, MCP tool, input schema or tool
    catalog entry changes. This adds library capability only.
  • Provider, bridge, target-format, or platform compatibility: PE only. Reads the
    EXCEPTION data directory of an existing PE image; no new dependency, no bridge
    change, no platform-specific code.
  • Evidence, artifact, provenance, or reconstruction contract: no Evidence record,
    artifact inventory or provenance field changes. The new reader reports partial
    coverage and tagged failures rather than defaulting to "absent".
  • Target selection, authority, upstream behavior, and cleanup details (if applicable):
    not applicable; the reader takes bytes already in memory and reads no target.
  • Generated metadata (docs/public/product-catalog.json), package, or installation
    impact: the package version moves to 6.8.0 with matching package-lock.json,
    server.json, src/generatedPackageMetadata.ts, docs/installation.md and
    .release-please-manifest.json. CI regenerates and validates the ignored catalog
    and skills/; no authored skill instruction changed.

Expected effects:

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

  • Tests added or updated: src/native/PeExceptionDirectory.test.ts (new, 446 lines)
    covers record decoding, partial coverage, and each tagged failure reason.
    tests/boundary/filesystem/peResources.test.ts continues to cover resource
    mapping through the new shared owner.
  • Base reproduction or other evidence: the exception directory has no prior reader
    in this repository, so there is no base behaviour to regress. The resource reader's
    behaviour is covered by the existing boundary test, which passes unchanged.
  • User-visible CLI/MCP output (if applicable): none; this is library capability.
  • Remaining proof gaps: the exception-directory reader is not yet surfaced through a
    CLI command or MCP tool, so it is not reachable by users in this release. PE
    (32-bit and 64-bit) is covered; ELF, Mach-O and other formats are out of scope for
    this reader.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

Validation performed

All commands below were executed on this branch.

  • npm run check:fast — passed (typecheck and lint clean, 0 errors).
  • npx vitest run tests/boundary/native tests/boundary/filesystem/peResources.test.ts src/native — 15 passed.
  • npx vitest run tests/conformance/releaseConfiguration.test.ts — 5 passed.
  • npx vitest run tests/boundary/filesystem/releaseCheckpoint.test.ts — 39 passed.
  • npx vitest run tests/boundary/filesystem/releaseNotes.test.ts — 5 passed.
  • npm run metadata:check — passed.
  • npm run docs:check — passed.
  • npm run test:python — 91 passed.
  • npm run jscpd — 3.40% duplicated lines, no threshold failure.
  • npm run scan:todos — no tech-debt markers.
  • npm run knip — clean.
  • npm pack --dry-run — rea-agents-6.8.0.tgz, 2110 files, 8.1 MB; contains no vault/ path.
  • npm ci --ignore-scripts — succeeded and left package-lock.json unchanged.

Pre-existing failures, not caused by this change

Each was reproduced identically on clean origin/main in a separate worktree.

  • npm run check:pr — test:run was force-killed at the 50-minute task limit; the
    remaining suite steps (test:python, docs:check, jscpd, scan:todos) pass
    individually.
  • tests/acceptance/setup/* — 20 failed / 24 passed on origin/main for the same
    test names; on this branch 5 failed / 39 passed for the same set. Setup and
    client-configuration tests, unrelated to PE code.
  • tests/boundary/filesystem/analysisSnapshot.test.ts,
    tests/boundary/filesystem/processCliFileInput.test.ts — 5 failed / 59 passed on
    origin/main, identical on this branch. Cancellation-timing tests.
  • tests/boundary/mcp/toolSchemaValidity.test.ts — 2 failed / 13 passed on
    origin/main, identical on this branch. 30s MCP stdio handshake timeouts.
  • tests/acceptance/applications/peResources.test.ts — fails identically on
    origin/main (30s MCP stdio handshake timeout).

Compatibility, safety, and release

  • Breaking changes or migration steps: none. The release is a minor version under
    always-bump-minor. PeResourceLayout's public behaviour and messages are
    unchanged; only the internal owner of PE image facts moved.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable — no provider,
    browser or OS-specific path changed. The PE reader is exercised through the
    real-file boundary test (tests/boundary/filesystem/peResources.test.ts), which
    admits the largest measured stock Windows resource table.
  • Package or release metadata impact: version 6.8.0 across package.json,
    package-lock.json, server.json, src/generatedPackageMetadata.ts,
    docs/installation.md and .release-please-manifest.json; CHANGELOG.md has a
    6.8.0 section. npm pack --dry-run produces rea-agents-6.8.0.tgz.
  • Security, privacy, process, or containment review: the new reader inspects bytes
    the caller already supplied. It adds no target execution, no network access and no
    credential handling, and it reports partial coverage explicitly rather than
    presenting missing extents as absent.

Author readiness

Human owner:

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output. — not applicable; no CLI or MCP surface changes.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

Update: rebased onto current main

main advanced 1,160 commits during review preparation. The branch is rebased onto
origin/main at 422ca5a8f and re-verified.

Two rebase resolutions worth review:

  • PeResourceLayout.ts — main had evolved its own inline header parsing.
    Resolved in favour of the shared PeImageLayout owner, which already carries the
    three checks main added (RVA range overflows, raw bytes overlap headers,
    overlapping raw file ranges). Behaviour is preserved; the owner moved.
  • src/generatedPackageMetadata.ts — kept main's new pinnedNodeVersion field
    alongside the 6.8.0 version bump.

Integration fix found by the rebase

origin/main added PeCertificateParser, which imported readPeHeaders from
PeResourceLayout — the exact export this branch had moved into PeImageLayout. The
rebase left that import dangling, and typecheck failed with TS2305.

Fixed by exposing the header offsets the parser needs (peOffset, optionalOffset,
optionalMagic, directoriesOffset) on PeImageLayout, and reading the security
directory through directoryOffset rather than recomputing it. The certificate
parser now shares one owner for PE header facts instead of carrying a second reader.

Re-validation after the rebase

Toolchain: pinned Node 24.22.1 / npm 11.19.1 (installed for this; .nvmrc pins
24.22.1 and engines requires ^24.22.1).

  • npm ci --ignore-scripts — succeeded, lockfile unchanged.
  • npm run check:fast — passed.
  • npm run typecheck — passed (was failing TS2305 before the integration fix).
  • npm run build:cached — passed.
  • npx vitest run --project acceptance tests/acceptance/peCertificatesCli.test.ts — 5 passed. This is the suite that exercises the parser I changed.
  • npx vitest run --project boundary --project conformance --project unit — 9169 passed, 3 failed. All three reproduced as failures on origin/main or pass in isolation:
    • productCatalog.test.ts and setupSkill.test.ts — stale generated catalog after the rebase; npm run docs:generate regenerates it and both then pass (27 tests).
    • kunaProvider.test.ts — passes in isolation (31 tests); contention-flaky.
  • npm run metadata:check — passed.
  • npm run docs:check — 9 passed.
  • npm run test:python — 91 passed.
  • npm run jscpd — 3.63% duplicated lines.
  • npm run scan:todos — no tech-debt markers.
  • npm run knip — clean.

alan-bot and others added 5 commits October 24, 2026 23:56
Extract PE header, section-table and data-directory parsing from
PeResourceLayout into a shared PeImageLayout owner, then build the
exception-directory reader on that same owner.

- src/native/pe/PeImageLayout.ts: single owner for MZ/PE header
  admission, section table, data directories, virtual extent and
  file-backed RVA mapping, with tagged failure reasons.
- src/native/PeExceptionDirectory.ts: decode and inspect the
  exception directory as RUNTIME_FUNCTION records, reporting partial
  coverage and tagged failures instead of silently dropping extents
  that no section maps.
- src/native/pe/PeResourceLayout.ts: delegate header and section
  facts to the shared owner; keep only resource-specific mapping
  rules and their messages.
vault/lance-chat/session-snapshot.md is rewritten by the session harness on
every turn, so tracking it produces constant churn and merge conflicts. The
durable FM26 state lives in vault/evidences/fm26-state.md instead.

The two .err capture logs are empty and carry no evidence.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The FM26 investigation material under vault/ is local working evidence, not
a repository contribution. It holds verbatim EA Sports match-commentary
strings, and AGENTS.md already states that local planning artifacts are never
committed.

Untrack the whole directory and ignore it. The evidence stays on disk, and the
release now carries only the PE image-layout change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The session harness writes HTML session exports into the repository root.
They are untracked working artifacts and are not part of the source tree, but
oxfmt still checks them and its failure blocks the release gate.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Version bump to 6.8.0 with the PE image-layout and exception-directory
release notes. Release Please uses always-bump-minor, so the feature
introduced on this branch ships as a minor release.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@greptile-apps

greptile-apps Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 0/5 Tier: plus

[Medium impact] The changes reach bounded PE artifact inspection across several native readers.

Do not merge yet: resource and certificate inspection regress, and the earlier memory, file-lifetime, and release blockers remain.

Findings

  1. P1 Empty resources stop inspection ▶
  2. P1 Resource overlap checks change ▶
  3. P1 Readable certificates become unavailable ▶
  4. P1 Security Large directories exhaust memory ▶
  5. P1 Valid headers look truncated ▶
  6. P1 Failed closes lose results ▶
  7. P1 Release baseline advances too early ▶
  8. P2 Lookups miss retained functions ▶
  9. P2 Ambiguous sections produce trusted bounds ▶
  10. P2 Missing bytes look complete ▶
  11. P2 PE readers still duplicate facts ▶
  12. P2 Tests bypass required cleanup ▶
  13. P2 Tests discard useful errors ▶
  14. P2 File errors bypass tagged results ▶
Fix with agent prompt
### Issue 1
src/native/pe/PeResourceLayout.ts:48-51
When an empty resource sits exactly at its section's virtual end, the strict `< peVirtualExtent(section)` filter leaves no candidate. `map` then throws, losing the entire resource report. The existing test at `PeResourceParser.test.ts:377` requires this case to succeed.

Restore the endpoint fallback when no section owns the address, while keeping the file-backed check.

### Issue 2
src/native/pe/PeResourceLayout.ts:54-57
Replacing `intersectsResource` loses two existing rules:
- A section with zero extent inside a requested range now falsely counts as an overlap, rejecting the resource report.
- An empty header payload at a positive-extent section's start now misses the conflict and receives a header location.

Restore the positive-extent guard and the point check for empty resources in both overlap branches. Existing tests cover both cases.

### Issue 3
src/native/pe/PeCertificateParser.ts:57-59
`parsePeCertificates` now rejects an intact certificate table when unrelated sections overlap in the file, declare bytes outside the file, or overflow their RVA range. Unlike the old header-only reader, `readPeImageLayout` checks these declarations before the certificate table is examined.

The security directory uses a file offset, so reading it does not need these section checks. Share the decoded header facts without forcing resource mapping requirements onto certificate inspection.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

### Issue 4
src/native/PeExceptionDirectory.ts:429-433
`inspectPeExceptionDirectory` allocates the entire file-backed directory before checking its memory cost. A large or sparse PE can pass the section and file bounds and request gigabytes here. Decoding then allocates up to five more arrays sized from those records. This can exhaust the caller's memory instead of returning a tagged failure.

The repository requires accounting for representation expansion before allocation. Enforce a shared byte/record allowance before both the file read and decoding.

**How this was verified:** The inspected file's directory and section sizes determine `available`, which reaches `Buffer.alloc` and the record-sized arrays without a memory allowance.

### Issue 5
src/native/pe/PeImageLayout.ts:undefined-387
`peHeaderBytes` cannot widen the initial window when the PE header itself falls outside it. For example, a valid image with `e_lfanew = 0x1100` gets only the first `0x1000` bytes read. This check returns `undefined`, so `inspectPeExceptionDirectory` skips the wider read and reports `truncated-header`, even though parsing the full buffer works. Read the COFF header at the declared offset first, then use it to size the remaining header reads.

### Issue 6
src/native/PeExceptionDirectory.ts:435-436
A rejected `handle.close()` replaces the pending result or earlier read error, and no owner retains the handle for retry. This loses both the inspection outcome and the cleanup path. The repository requires descriptor-backed reads to have an owner before opening and to retain failed closes with earlier outcomes. Use the existing owned-file helpers rather than a bare `open`/`finally` pair.

### Issue 7
.release-please-manifest.json:undefined-2
This changes the published release baseline to `6.8.0` inside a feature PR. Merging a feature branch does not run the release-creation job, which only accepts Release Please branch names. The next checkpoint nevertheless reads this manifest as the published baseline: preparing the intended `6.8.0` fails the “must advance” check, while a later version requires a published `6.8.0` tag that this merge does not create.

Leave the version changes for the actual release PR so the baseline advances with publication.

### Issue 8
src/native/PeExceptionDirectory.ts:334-338
The decoder keeps overlapping extents, but both lookup methods assume they are disjoint. With records `[0x1000, 0x1100)` and `[0x1020, 0x1030)`, `functionAt(0x1040)` returns `undefined`, and `extentsIn(0x1040, 1)` yields nothing, despite the first retained extent covering that address. Either reject and report overlaps when decoding, or build lookups that handle every retained interval.

### Issue 9
src/native/PeExceptionDirectory.ts:155-160
Checking `sectionAt` only at the directory's start does not establish an unambiguous mapping for its full range. Two sections with separate file ranges can overlap later in RVA space. A directory starting before that overlap is accepted and decoded using the first section's bytes throughout.

The new `fileRange` method has the same gap, while the resource mapper explicitly rejects it. Put the full-interval check in the shared owner and use it from the exception reader.

### Issue 10
src/native/PeExceptionDirectory.ts:268-272
Flooring both sizes to whole records can hide an incomplete directory. If `declaredSize` is 13 and only 12 bytes are available, one valid record produces `coverage: 1` and `complete: true`, with no partial-read warning. That contradicts the range contract that fewer bytes than `declaredSize` must mean a partial read. Reject a trailing partial record as malformed, or include unread trailing bytes in the completeness decision.

### Issue 11
src/native/pe/PeImageLayout.ts:255-263
The shared-owner refactor still leaves PE headers and section facts parsed independently. `readPeImage` reads the optional header and data directories itself, and `readPeSectionDirectory` separately reads the COFF header and section table. This new loop repeats those facts again.

The repository requires consumers to use the owner's parsed facts and directly related duplicate interpretation to be removed. Share the structural decoder with those readers too, while keeping their admission and mapping policies separate. This repository requirement must be satisfied before merging.

### Issue 12
src/native/PeExceptionDirectory.test.ts:409-414
These file tests create a suite-wide temporary directory directly with `mkdtemp`. The repository requires `createTestTempDirectory` for exact-path, awaited cleanup, including failures and timeouts. Use that helper per test instead of adding another `beforeAll`/`afterAll` cleanup path. This repository requirement must be satisfied before merging.

### Issue 13
src/native/PeExceptionDirectory.test.ts:150-152
The successful `Result` tests assert `ok` and then return on failure. The testing guide explicitly requires throwing the typed error before asserting successful values; the preceding `ok` assertion adds no coverage. Apply that pattern here and throughout the new success cases so failures show the actual parser error. The same pattern appears in both file-versus-memory checks. This repository requirement must be satisfied before merging.

### Issue 14
src/native/PeExceptionDirectory.ts:413-416
A missing or unreadable path makes `inspectPeExceptionDirectory` reject at `open` instead of returning a tagged failure. File read errors take the same unhandled path. Callers therefore need a second error channel alongside the advertised `Result`.

The repository requires expected boundary failures to use the tagged error algebra. Add file-access failure cases and return them through `Result`. This repository requirement must be satisfied before merging.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds PeImageLayout for shared PE facts and PeExceptionDirectory for function extents, coverage, and tagged failures.

  • PE resource and certificate readers now share one source for image facts.
  • PE images can now report measured function extents from their Exception Directory.
  • The published package and setup examples now use version 6.8.0.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  B["PE bytes"] --> L["PeImageLayout"]
  L --> R["PeResourceLayout"]
  R --> P["Resource reader"]
  L --> C["PeCertificateParser"]
  L --> E["PeExceptionDirectory"]
  E --> F["Function extents and coverage"]
Loading

Reviews (2) · Last reviewed commit: "fix(pe): route the certificate parser th..." · Reviewed by Greptile

Comment on lines +429 to +433
const records = await readExactly(
handle,
range.value.offset,
range.value.available,
);

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.

P1 security Large directories exhaust memory

inspectPeExceptionDirectory allocates the entire file-backed directory before checking its memory cost. A large or sparse PE can pass the section and file bounds and request gigabytes here. Decoding then allocates up to five more arrays sized from those records. This can exhaust the caller's memory instead of returning a tagged failure.

The repository requires accounting for representation expansion before allocation. Enforce a shared byte/record allowance before both the file read and decoding.

How this was verified: The inspected file's directory and section sizes determine available, which reaches Buffer.alloc and the record-sized arrays without a memory allowance.

Context Used: AGENTS.md (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/PeExceptionDirectory.ts
Line: 429-433

Comment:
**Large directories exhaust memory**

`inspectPeExceptionDirectory` allocates the entire file-backed directory before checking its memory cost. A large or sparse PE can pass the section and file bounds and request gigabytes here. Decoding then allocates up to five more arrays sized from those records. This can exhaust the caller's memory instead of returning a tagged failure.

The repository requires accounting for representation expansion before allocation. Enforce a shared byte/record allowance before both the file read and decoding.

**How this was verified:** The inspected file's directory and section sizes determine `available`, which reaches `Buffer.alloc` and the record-sized arrays without a memory allowance.

**Context Used:** AGENTS.md ([source](https://github.com/morluto/rea/blob/main/AGENTS.md))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

if (bytes.readUInt16LE(0) !== MZ_SIGNATURE) return undefined;
const pe = bytes.readUInt32LE(PE_POINTER_OFFSET);
if (pe > MAX_HEADER_BYTES || pe < DOS_HEADER_BYTES) return undefined;
if (bytes.length < pe + COFF_HEADER_BYTES + 4) return undefined;

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.

P1 Valid headers look truncated

peHeaderBytes cannot widen the initial window when the PE header itself falls outside it. For example, a valid image with e_lfanew = 0x1100 gets only the first 0x1000 bytes read. This check returns undefined, so inspectPeExceptionDirectory skips the wider read and reports truncated-header, even though parsing the full buffer works. Read the COFF header at the declared offset first, then use it to size the remaining header reads.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/pe/PeImageLayout.ts
Line: 375

Comment:
**Valid headers look truncated**

`peHeaderBytes` cannot widen the initial window when the PE header itself falls outside it. For example, a valid image with `e_lfanew = 0x1100` gets only the first `0x1000` bytes read. This check returns `undefined`, so `inspectPeExceptionDirectory` skips the wider read and reports `truncated-header`, even though parsing the full buffer works. Read the COFF header at the declared offset first, then use it to size the remaining header reads.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +334 to +338
const index = lastIndexBeginningAtOrBefore(rva);
if (index < 0) return undefined;
if (rva < at(sortedEnds, index))
return { begin: at(sortedBegins, index), end: at(sortedEnds, index) };
return undefined;

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.

P2 Lookups miss retained functions

The decoder keeps overlapping extents, but both lookup methods assume they are disjoint. With records [0x1000, 0x1100) and [0x1020, 0x1030), functionAt(0x1040) returns undefined, and extentsIn(0x1040, 1) yields nothing, despite the first retained extent covering that address. Either reject and report overlaps when decoding, or build lookups that handle every retained interval.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/PeExceptionDirectory.ts
Line: 334-338

Comment:
**Lookups miss retained functions**

The decoder keeps overlapping extents, but both lookup methods assume they are disjoint. With records `[0x1000, 0x1100)` and `[0x1020, 0x1030)`, `functionAt(0x1040)` returns `undefined`, and `extentsIn(0x1040, 1)` yields nothing, despite the first retained extent covering that address. Either reject and report overlaps when decoding, or build lookups that handle every retained interval.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +155 to +160
const section = measurable.value.sectionAt(declared.rva);
if (section === null)
return failure(
"exception-directory-unmapped",
`Exception Directory RVA 0x${declared.rva.toString(16)} has no unambiguous section mapping.`,
);

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.

P2 Ambiguous sections produce trusted bounds

Checking sectionAt only at the directory's start does not establish an unambiguous mapping for its full range. Two sections with separate file ranges can overlap later in RVA space. A directory starting before that overlap is accepted and decoded using the first section's bytes throughout.

The new fileRange method has the same gap, while the resource mapper explicitly rejects it. Put the full-interval check in the shared owner and use it from the exception reader.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/PeExceptionDirectory.ts
Line: 155-160

Comment:
**Ambiguous sections produce trusted bounds**

Checking `sectionAt` only at the directory's start does not establish an unambiguous mapping for its full range. Two sections with separate file ranges can overlap later in RVA space. A directory starting before that overlap is accepted and decoded using the first section's bytes throughout.

The new `fileRange` method has the same gap, while the resource mapper explicitly rejects it. Put the full-interval check in the shared owner and use it from the exception reader.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +268 to +272
const coverage =
range.declaredCount === 0
? 1
: Math.min(readCount / range.declaredCount, 1);
const complete = readCount >= range.declaredCount;

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.

P2 Missing bytes look complete

Flooring both sizes to whole records can hide an incomplete directory. If declaredSize is 13 and only 12 bytes are available, one valid record produces coverage: 1 and complete: true, with no partial-read warning. That contradicts the range contract that fewer bytes than declaredSize must mean a partial read. Reject a trailing partial record as malformed, or include unread trailing bytes in the completeness decision.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/PeExceptionDirectory.ts
Line: 268-272

Comment:
**Missing bytes look complete**

Flooring both sizes to whole records can hide an incomplete directory. If `declaredSize` is 13 and only 12 bytes are available, one valid record produces `coverage: 1` and `complete: true`, with no partial-read warning. That contradicts the range contract that fewer bytes than `declaredSize` must mean a partial read. Reject a trailing partial record as malformed, or include unread trailing bytes in the completeness decision.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +247 to +255
const sections: PeSection[] = [];
for (let index = 0; index < sectionCount; index++) {
const at = table + index * SECTION_HEADER_BYTES;
const section: PeSection = {
name: bytes.toString("latin1", at, at + 8).replace(/\0+$/u, ""),
virtualSize: bytes.readUInt32LE(at + 8),
rva: bytes.readUInt32LE(at + 12),
size: bytes.readUInt32LE(at + 16),
offset: bytes.readUInt32LE(at + 20),

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.

P2 PE readers still duplicate facts

The shared-owner refactor still leaves PE headers and section facts parsed independently. readPeImage reads the optional header and data directories itself, and readPeSectionDirectory separately reads the COFF header and section table. This new loop repeats those facts again.

The repository requires consumers to use the owner's parsed facts and directly related duplicate interpretation to be removed. Share the structural decoder with those readers too, while keeping their admission and mapping policies separate. This repository requirement must be satisfied before merging.

Context Used: AGENTS.md (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/pe/PeImageLayout.ts
Line: 247-255

Comment:
**PE readers still duplicate facts**

The shared-owner refactor still leaves PE headers and section facts parsed independently. `readPeImage` reads the optional header and data directories itself, and `readPeSectionDirectory` separately reads the COFF header and section table. This new loop repeats those facts again.

The repository requires consumers to use the owner's parsed facts and directly related duplicate interpretation to be removed. Share the structural decoder with those readers too, while keeping their admission and mapping policies separate. This repository requirement must be satisfied before merging.

**Context Used:** AGENTS.md ([source](https://github.com/morluto/rea/blob/main/AGENTS.md))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@@ -1,3 +1,3 @@
{
".": "6.7.0"
".": "6.8.0"

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.

P1 Release baseline advances too early

This changes the published release baseline to 6.8.0 inside a feature PR. Merging a feature branch does not run the release-creation job, which only accepts Release Please branch names. The next checkpoint nevertheless reads this manifest as the published baseline: preparing the intended 6.8.0 fails the “must advance” check, while a later version requires a published 6.8.0 tag that this merge does not create.

Leave the version changes for the actual release PR so the baseline advances with publication.

Prompt To Fix With AI
This is a comment left during a code review.
Path: .release-please-manifest.json
Line: 2

Comment:
**Release baseline advances too early**

This changes the published release baseline to `6.8.0` inside a feature PR. Merging a feature branch does not run the release-creation job, which only accepts Release Please branch names. The next checkpoint nevertheless reads this manifest as the published baseline: preparing the intended `6.8.0` fails the “must advance” check, while a later version requires a published `6.8.0` tag that this merge does not create.

Leave the version changes for the actual release PR so the baseline advances with publication.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +409 to +414
beforeAll(async () => {
directory = await mkdtemp(join(tmpdir(), "rea-pdata-"));
});

afterAll(async () => {
await rm(directory, { recursive: true, force: true });

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.

P2 Tests bypass required cleanup

These file tests create a suite-wide temporary directory directly with mkdtemp. The repository requires createTestTempDirectory for exact-path, awaited cleanup, including failures and timeouts. Use that helper per test instead of adding another beforeAll/afterAll cleanup path. This repository requirement must be satisfied before merging.

Context Used: AGENTS.md (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/PeExceptionDirectory.test.ts
Line: 409-414

Comment:
**Tests bypass required cleanup**

These file tests create a suite-wide temporary directory directly with `mkdtemp`. The repository requires `createTestTempDirectory` for exact-path, awaited cleanup, including failures and timeouts. Use that helper per test instead of adding another `beforeAll`/`afterAll` cleanup path. This repository requirement must be satisfied before merging.

**Context Used:** AGENTS.md ([source](https://github.com/morluto/rea/blob/main/AGENTS.md))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +150 to +152
const result = parsePeExceptionDirectory(bytes);
expect(result.ok).toBe(true);
if (!result.ok) return;

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.

P2 Tests discard useful errors

The successful Result tests assert ok and then return on failure. The testing guide explicitly requires throwing the typed error before asserting successful values; the preceding ok assertion adds no coverage. Apply that pattern here and throughout the new success cases so failures show the actual parser error. The same pattern appears in both file-versus-memory checks. This repository requirement must be satisfied before merging.

Context Used: Documentation (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/PeExceptionDirectory.test.ts
Line: 150-152

Comment:
**Tests discard useful errors**

The successful `Result` tests assert `ok` and then return on failure. The testing guide explicitly requires throwing the typed error before asserting successful values; the preceding `ok` assertion adds no coverage. Apply that pattern here and throughout the new success cases so failures show the actual parser error. The same pattern appears in both file-versus-memory checks. This repository requirement must be satisfied before merging.

**Context Used:** Documentation ([source](https://github.com/morluto/rea/blob/main/docs))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +413 to +416
): Promise<Result<PeExceptionDirectory, PeExceptionFailure>> => {
const handle = await open(path, "r");
try {
const { size: fileSize } = await handle.stat();

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.

P2 File errors bypass tagged results

A missing or unreadable path makes inspectPeExceptionDirectory reject at open instead of returning a tagged failure. File read errors take the same unhandled path. Callers therefore need a second error channel alongside the advertised Result.

The repository requires expected boundary failures to use the tagged error algebra. Add file-access failure cases and return them through Result. This repository requirement must be satisfied before merging.

Context Used: AGENTS.md (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/PeExceptionDirectory.ts
Line: 413-416

Comment:
**File errors bypass tagged results**

A missing or unreadable path makes `inspectPeExceptionDirectory` reject at `open` instead of returning a tagged failure. File read errors take the same unhandled path. Callers therefore need a second error channel alongside the advertised `Result`.

The repository requires expected boundary failures to use the tagged error algebra. Add file-access failure cases and return them through `Result`. This repository requirement must be satisfied before merging.

**Context Used:** AGENTS.md ([source](https://github.com/morluto/rea/blob/main/AGENTS.md))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

… owner

origin/main added PeCertificateParser importing readPeHeaders from
PeResourceLayout, which this branch had already moved into PeImageLayout.
The rebase left the import dangling.

Expose the header offsets the parser actually needs (PE signature, optional
header, magic, data-directory array) on PeImageLayout, and read the security
directory through directoryOffset instead of recomputing it. The parser now
shares one owner for PE header facts rather than carrying a second reader.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@NgLanNg
NgLanNg force-pushed the feat/pe-image-layout-and-exception-directory branch from be4a039 to 9fa9aa1 Compare October 24, 2026 17:26
Comment on lines +48 to 51
const candidates = sections.filter(
(section) =>
rva >= section.rva && rva - section.rva < virtualExtent(section),
rva >= section.rva && rva - section.rva < peVirtualExtent(section),
);

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.

P1 Empty resources stop inspection

When an empty resource sits exactly at its section's virtual end, the strict < peVirtualExtent(section) filter leaves no candidate. map then throws, losing the entire resource report. The existing test at PeResourceParser.test.ts:377 requires this case to succeed.

Restore the endpoint fallback when no section owns the address, while keeping the file-backed check.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/pe/PeResourceLayout.ts
Line: 48-51

Comment:
**Empty resources stop inspection**

When an empty resource sits exactly at its section's virtual end, the strict `< peVirtualExtent(section)` filter leaves no candidate. `map` then throws, losing the entire resource report. The existing test at `PeResourceParser.test.ts:377` requires this case to succeed.

Restore the endpoint fallback when no section owns the address, while keeping the file-backed check.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +54 to +57
sections.some(
(section) =>
section.rva < rva + size &&
section.rva + peVirtualExtent(section) > rva,

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.

P1 Resource overlap checks change

Replacing intersectsResource loses two existing rules:

  • A section with zero extent inside a requested range now falsely counts as an overlap, rejecting the resource report.
  • An empty header payload at a positive-extent section's start now misses the conflict and receives a header location.

Restore the positive-extent guard and the point check for empty resources in both overlap branches. Existing tests cover both cases.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/pe/PeResourceLayout.ts
Line: 54-57

Comment:
**Resource overlap checks change**

Replacing `intersectsResource` loses two existing rules:
- A section with zero extent inside a requested range now falsely counts as an overlap, rejecting the resource report.
- An empty header payload at a positive-extent section's start now misses the conflict and receives a header location.

Restore the positive-extent guard and the point check for empty resources in both overlap branches. Existing tests cover both cases.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +57 to +59
const parsed = readPeImageLayout(bytes);
if (!parsed.ok)
throw new ArtifactReaderFailure("format", parsed.error.reason);

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.

P1 Readable certificates become unavailable

parsePeCertificates now rejects an intact certificate table when unrelated sections overlap in the file, declare bytes outside the file, or overflow their RVA range. Unlike the old header-only reader, readPeImageLayout checks these declarations before the certificate table is examined.

The security directory uses a file offset, so reading it does not need these section checks. Share the decoded header facts without forcing resource mapping requirements onto certificate inspection.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/pe/PeCertificateParser.ts
Line: 57-59

Comment:
**Readable certificates become unavailable**

`parsePeCertificates` now rejects an intact certificate table when unrelated sections overlap in the file, declare bytes outside the file, or overflow their RVA range. Unlike the old header-only reader, `readPeImageLayout` checks these declarations before the certificate table is examined.

The security directory uses a file offset, so reading it does not need these section checks. Share the decoded header facts without forcing resource mapping requirements onto certificate inspection.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@morluto

morluto commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thank you @NgLanNg for working on this! Closing as superseded: the shared PE image-layout owner has landed on main in commit f585acc748 (fix(pe)!: share one loader-equivalent PE header owner across static readers (#14253)), and the x64 exception-directory function-range reader is being carried forward in open PR #14254 (feat(pe): inspect x64 exception-directory function ranges) on top of that owner.

@morluto morluto closed this Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants