Skip to content

feat(artifacts): inspect and extract Intel HEX and S-record firmware - #7368

Closed
Ayinkx wants to merge 1 commit into
morluto:mainfrom
Ayinkx:fix/7129-intel-hex-srecord-readers
Closed

Ayinkx wants to merge 1 commit into
morluto:mainfrom
Ayinkx:fix/7129-intel-hex-srecord-readers

Conversation

@Ayinkx

@Ayinkx Ayinkx commented Oct 27, 2026

Copy link
Copy Markdown

Summary

Refs #7129. This implements the first of the three requested firmware container readers: Intel HEX (I8HEX/I16HEX/I32HEX) and Motorola S-record (S19/S28/S37).

Before this change, open_binary rejected these text formats, so inspect_artifact and extract_artifact could not be reached. They now inventory and extract address-contiguous decoded regions without external tools, conversion, or execution.

Note: #7136 proposes the same first slice. This branch was developed independently before that PR was found; maintainers can choose the implementation they prefer.

Problem and expected behavior

An analyst with a vendor .hex, .ihx, .s19, .s28, .s37, .mot, or .srec file needs to know which bytes load at which addresses and which start address the file declares.

Expected and implemented:

  • Address-contiguous bytes become extractable entries named by inclusive range, e.g. 0x08000000-0x08000003.bin.
  • Gaps are preserved as gaps and are never zero-filled.
  • Root format_metadata records the variant, start address and its source record, record counts, EOF/termination state, and the S0 header for S-records.
  • Declared start addresses are reported as source facts, not proven entry points.
  • Malformed files fail closed with the source line.
Situation Outcome
Sparse or out-of-order records Sorted and merged into address-contiguous regions
Identical overlapping bytes Accepted
Conflicting overlapping bytes format failure naming both lines and the address
Bad checksum, non-hex content, count mismatch, unknown record type, reserved S4 format failure naming the line
Intel 02 and 04 address modes mixed format failure
Conflicting start-address records format failure
Missing Intel 01 or S-record S7/S8/S9 Regions returned; coverage unknown
Data after EOF/termination, duplicate S0, duplicate count record format failure

Change and scope

  • Pure parsers in src/domain/firmwareText.ts: strict line/record parsing, checksums, address-mode validation, overlap comparison, region merging, and bounded expansion.
  • FirmwareTextArtifactReader provides bounded, cancellable inventory and extraction with a carrier-identity check on open().
  • Wiring follows the existing artifact reader factory:
    • content/suffix recognition in BinaryTargetResolver and classifyArtifactBytes;
    • container role and reader selection for inventory and extraction;
    • target, Evidence, snapshot, and live-target format enums;
    • additive format_metadata schemas.
  • Limits: decoded bytes use the existing artifact expansion budget, regions are capped at 100,000, and source lines are capped at 4,096 bytes.
  • Docs: docs/firmware-analysis.md.

Not included, and tracked separately in #7129:

Contribution scope: format inspection and ordinary extraction. No execution, injection, mutation, new provider, or protection recovery.

Contract and boundary impact

  • Semantic owner and earliest changed stage: src/domain/firmwareText.ts owns record interpretation; the reader translates typed parser failures into ArtifactReaderFailure.
  • Contribution scope fit and linked maintainer decision: existing format-inspection boundary; not applicable.
  • CLI and MCP/tool-catalog contract: no new tools. Additive target/artifact format values intel-hex and srec, and additive format_metadata variants. Tool descriptions mention the new formats.
  • Provider, bridge, target-format, or platform compatibility: pure TypeScript; no host-specific dependency.
  • Evidence, artifact, provenance, or reconstruction contract: regions carry byteOffset: null because decoded bytes have no single source range. Declared addresses and record counts remain source facts. Failures name the line.
  • Target selection, authority, upstream behavior, and cleanup details: content-based recognition at the target boundary; no target execution. Reader cleanup follows the existing artifact reader ownership model.
  • Generated metadata, package, or installation impact: none committed.

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:

  • src/domain/firmwareText.test.ts: 12 tests covering I8/I16/I32, S19/S28/S37, sparse regions, identical and conflicting overlaps, checksum/count/unknown-type failures, conflicting address modes and start addresses, and missing termination coverage.
  • tests/boundary/filesystem/firmwareTextArtifact.test.ts: 5 tests covering target classification, inventory facts and hashes, byte-exact extraction, S0 facts, unknown coverage, fail-closed line reporting, and an ELF named .hex staying on the executable route.
  • tests/acceptance/firmwareTextCli.test.ts: 2 compiled-CLI tests covering inspection, extraction, and malformed S-record line reporting.
  • tests/boundary/mcp/firmwareTextMcp.test.ts: 2 stdio-MCP tests (full and compact profiles) covering open_binary, summary inspection, extraction, and malformed input.

Representative output from the compiled CLI for an I32 fixture with two regions:

{
  "root_format": "intel-hex",
  "coverage": { "scope": "container-entries", "status": "complete" },
  "root_metadata": {
    "kind": "intel-hex",
    "variant": "i32",
    "start_address": 134217728,
    "start_address_source": "record-05",
    "eof_terminated": true
  },
  "regions": [
    "0x08000000-0x08000003.bin",
    "0x08000010-0x08000011.bin"
  ]
}

Remaining proof gaps:

  • Synthetic fixtures with computed checksums only; no GNU objcopy, srec_cat, or real vendor files were tested.
  • No real device programming files were used.

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

Host: Windows x64, Node 24.22.1.

  • npm run compile — exit 0.
  • vitest run on the four new test files — 21 passed.
  • Related existing artifact/binary-target tests — 44 passed and 76 passed (10 skipped).
  • TypeScript typecheck against tsconfig.json — exit 0. The repository's native compiler hit host memory limits, so the same config was run with TypeScript 5.9.3 and a 7 GiB heap.
  • npm run format:check — all matched files formatted.
  • npm run verify:test-discovery — all 2,639 test files discovered exactly once.
  • node scripts/verify-module-boundaries.mjs — clean across 3,213 source files.

Compatibility, safety, and release

  • Breaking changes or migration steps: none. Previously refused text files are recognized only when the first record is structurally valid or the suffix is known and the prefix is textual.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: no execution or mutation. Decoded bytes are bounded by the existing artifact expansion budget, region count is capped, generated paths cannot traverse, and the reader is cancellable.

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.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

Recognize Intel HEX (I8/I16/I32) and Motorola S-record (S19/S28/S37) text containers from record-shaped content or a supported suffix. Parse checksummed records into address-contiguous extractable regions, preserve declared start addresses and record counts in root format metadata, and fail closed with source lines for malformed records, conflicting overlaps, and count mismatches. Missing EOF or termination records leave coverage unknown and gaps are never zero-filled.
@greptile-apps

greptile-apps Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 2/5 Tier: plus

[Medium impact] The change reaches the existing artifact inspection and extraction workflows.

Fix CRLF rejection and quadratic region copying before merging.

Findings

  1. P1 Windows line endings fail ▶
  2. P1 Security Adjacent records stall the server ▶
  3. P2 Completed lines skip the limit ▶
  4. P2 Malformed control addresses are ignored ▶
  5. P2 Start records get wrong variants ▶
  6. P2 Overlap errors omit a source ▶
Fix with agent prompt
### Issue 1
src/domain/firmwareText.ts:200-204
`#sourceLines` removes only `\n`, so CRLF records reach `decodeLineText` with a trailing `\r`. The ASCII check rejects it before `.trim()` runs. This breaks inspection and extraction of ordinary Windows-style Intel HEX and S-record files.

Remove the trailing carriage return when splitting CRLF, while still rejecting embedded control bytes. Add a filesystem-boundary test: the unit helper currently strips CRLF before calling the parser and hides this failure.

### Issue 2
src/domain/firmwareText.ts:298-301
`buildRegions` copies the entire accumulated region twice for every adjacent record. A valid image with many short records therefore causes quadratic copying, even when it produces one region and stays below the decoded-byte budget. A focused check with 4,096 adjacent 32-byte records produced 128 KiB but copied over 256 MiB through `Buffer.from` alone, before counting `Buffer.concat`.

Larger firmware can stall the MCP process in this synchronous loop, where cancellation cannot run. Allocate each completed region once and copy records into it, with cancellation checkpoints during large builds.

**How this was verified:** Both firmware parsers pass supplied records into this synchronous copying loop, while the limits count decoded bytes and completed regions rather than repeated copying.

### Issue 3
src/artifacts/FirmwareTextArtifactReader.ts:228-234
The `MAX_LINE_BYTES` check runs only on the unfinished remainder of a chunk. A newline-terminated line inside a 64 KiB chunk bypasses it entirely. For example, 5,000 spaces followed by a valid record are yielded unchecked and accepted after trimming, despite exceeding the advertised 4,096-byte limit.

Check each completed line's total length before concatenating or yielding it. Test both completed lines and lines split across chunks so the limit does not depend on where a chunk ends.

### Issue 4
src/domain/firmwareText.ts:440-446
Intel HEX control records `02`, `03`, `04`, and `05` accept a nonzero address field and silently discard it. For example, `:020001040800F1` is accepted as an extended linear address record despite its nonzero fixed address. Analysts get normal-looking metadata instead of a source-line failure.

Validate the required zero address alongside each control record's byte count, and add malformed-input tests.

### Issue 5
src/domain/firmwareText.ts:488
`variant` considers only extended-address records. A file with a `05` start-linear record but no `04` record is reported as `i8`; the equivalent `03`-without-`02` case is also reported as `i8`. Small images can use wider start records without needing an extended data base.

Include start-record types when deriving `i16` and `i32`, so the reported variant agrees with the records present.

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 6
src/domain/firmwareText.ts:290-293
Conflicting overlaps report only `record.line`, not the source line that supplied the existing byte. This misses the promised two-line diagnostic and leaves users searching for the other record. Because records are sorted by address before merging, that record may be on a distant source line.

Preserve source lines for retained byte spans and report both owners when an overlap conflicts.

---

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

Summary

Adds Intel HEX and Motorola S-record classification, metadata, inventory, and extraction of contiguous decoded regions.

  • Intel HEX and S-record files become address-based byte regions.
  • Artifact tools can inspect and extract both firmware text formats.

Ayinkx acknowledges that #7136 covers the same slice and leaves the implementation choice to maintainers. Its current status could not be verified because GitHub access was unavailable. Ayinkx also explicitly reports synthetic fixtures only; missing real-vendor validation was not treated as a separate finding.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Selected firmware file] --> B[Content and suffix classification]
  B --> C[FirmwareTextArtifactReader]
  C --> D[Split source lines]
  D --> E[Check records and decode bytes]
  E --> F[Sort records and build regions]
  F --> G[Inventory with addresses and metadata]
  G --> H[Extract contiguous region files]
Loading

Reviews (1) · Last reviewed commit: "feat(artifacts): inspect and extract Int..." · Reviewed by Greptile

Comment on lines +200 to +204
for (const byte of bytes)
if (byte !== 0x09 && (byte < 0x20 || byte > 0x7e))
throw formatError(
line.number,
`non-ASCII byte ${displayByte(byte)} in a text firmware container`,

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 Windows line endings fail

#sourceLines removes only \n, so CRLF records reach decodeLineText with a trailing \r. The ASCII check rejects it before .trim() runs. This breaks inspection and extraction of ordinary Windows-style Intel HEX and S-record files.

Remove the trailing carriage return when splitting CRLF, while still rejecting embedded control bytes. Add a filesystem-boundary test: the unit helper currently strips CRLF before calling the parser and hides this failure.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/firmwareText.ts
Line: 200-204

Comment:
**Windows line endings fail**

`#sourceLines` removes only `\n`, so CRLF records reach `decodeLineText` with a trailing `\r`. The ASCII check rejects it before `.trim()` runs. This breaks inspection and extraction of ordinary Windows-style Intel HEX and S-record files.

Remove the trailing carriage return when splitting CRLF, while still rejecting embedded control bytes. Add a filesystem-boundary test: the unit helper currently strips CRLF before calling the parser and hides this failure.

---

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

Comment on lines +298 to +301
const merged = Buffer.concat([
Buffer.from(previous.bytes),
Buffer.from(record.bytes.subarray(tailStart)),
]);

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 Adjacent records stall the server

buildRegions copies the entire accumulated region twice for every adjacent record. A valid image with many short records therefore causes quadratic copying, even when it produces one region and stays below the decoded-byte budget. A focused check with 4,096 adjacent 32-byte records produced 128 KiB but copied over 256 MiB through Buffer.from alone, before counting Buffer.concat.

Larger firmware can stall the MCP process in this synchronous loop, where cancellation cannot run. Allocate each completed region once and copy records into it, with cancellation checkpoints during large builds.

How this was verified: Both firmware parsers pass supplied records into this synchronous copying loop, while the limits count decoded bytes and completed regions rather than repeated copying.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/firmwareText.ts
Line: 298-301

Comment:
**Adjacent records stall the server**

`buildRegions` copies the entire accumulated region twice for every adjacent record. A valid image with many short records therefore causes quadratic copying, even when it produces one region and stays below the decoded-byte budget. A focused check with 4,096 adjacent 32-byte records produced 128 KiB but copied over 256 MiB through `Buffer.from` alone, before counting `Buffer.concat`.

Larger firmware can stall the MCP process in this synchronous loop, where cancellation cannot run. Allocate each completed region once and copy records into it, with cancellation checkpoints during large builds.

**How this was verified:** Both firmware parsers pass supplied records into this synchronous copying loop, while the limits count decoded bytes and completed regions rather than repeated copying.

---

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

Comment on lines +228 to +234
const bytes =
carry.length === 0
? chunk.subarray(start, index)
: Buffer.concat([carry, chunk.subarray(start, index)]);
carry = Buffer.alloc(0);
lineNumber += 1;
yield { number: lineNumber, bytes };

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 Completed lines skip the limit

The MAX_LINE_BYTES check runs only on the unfinished remainder of a chunk. A newline-terminated line inside a 64 KiB chunk bypasses it entirely. For example, 5,000 spaces followed by a valid record are yielded unchecked and accepted after trimming, despite exceeding the advertised 4,096-byte limit.

Check each completed line's total length before concatenating or yielding it. Test both completed lines and lines split across chunks so the limit does not depend on where a chunk ends.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/artifacts/FirmwareTextArtifactReader.ts
Line: 228-234

Comment:
**Completed lines skip the limit**

The `MAX_LINE_BYTES` check runs only on the unfinished remainder of a chunk. A newline-terminated line inside a 64 KiB chunk bypasses it entirely. For example, 5,000 spaces followed by a valid record are yielded unchecked and accepted after trimming, despite exceeding the advertised 4,096-byte limit.

Check each completed line's total length before concatenating or yielding it. Test both completed lines and lines split across chunks so the limit does not depend on where a chunk ends.

---

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

Comment on lines +440 to +446
if (count !== 2)
throw formatError(
line.number,
"extended linear address record must contain 2 bytes",
);
sawLinear = true;
extendedLinear = ((data[0] ?? 0) << 8) | (data[1] ?? 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.

P2 Malformed control addresses are ignored

Intel HEX control records 02, 03, 04, and 05 accept a nonzero address field and silently discard it. For example, :020001040800F1 is accepted as an extended linear address record despite its nonzero fixed address. Analysts get normal-looking metadata instead of a source-line failure.

Validate the required zero address alongside each control record's byte count, and add malformed-input tests.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/firmwareText.ts
Line: 440-446

Comment:
**Malformed control addresses are ignored**

Intel HEX control records `02`, `03`, `04`, and `05` accept a nonzero address field and silently discard it. For example, `:020001040800F1` is accepted as an extended linear address record despite its nonzero fixed address. Analysts get normal-looking metadata instead of a source-line failure.

Validate the required zero address alongside each control record's byte count, and add malformed-input tests.

---

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

format: "intel-hex",
metadata: {
kind: "intel-hex",
variant: sawLinear ? "i32" : sawSegment ? "i16" : "i8",

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 Start records get wrong variants

variant considers only extended-address records. A file with a 05 start-linear record but no 04 record is reported as i8; the equivalent 03-without-02 case is also reported as i8. Small images can use wider start records without needing an extended data base.

Include start-record types when deriving i16 and i32, so the reported variant agrees with the records present.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/firmwareText.ts
Line: 488

Comment:
**Start records get wrong variants**

`variant` considers only extended-address records. A file with a `05` start-linear record but no `04` record is reported as `i8`; the equivalent `03`-without-`02` case is also reported as `i8`. Small images can use wider start records without needing an extended data base.

Include start-record types when deriving `i16` and `i32`, so the reported variant agrees with the records present.

---

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!

Comment on lines +290 to +293
if (previousByte !== recordByte)
throw formatError(
record.line,
`conflicting overlap at address ${displayAddress(address)}: existing ${displayByte(previousByte ?? 0)}, record ${displayByte(recordByte ?? 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.

P2 Overlap errors omit a source

Conflicting overlaps report only record.line, not the source line that supplied the existing byte. This misses the promised two-line diagnostic and leaves users searching for the other record. Because records are sorted by address before merging, that record may be on a distant source line.

Preserve source lines for retained byte spans and report both owners when an overlap conflicts.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/firmwareText.ts
Line: 290-293

Comment:
**Overlap errors omit a source**

Conflicting overlaps report only `record.line`, not the source line that supplied the existing byte. This misses the promised two-line diagnostic and leaves users searching for the other record. Because records are sorted by address before merging, that record may be on a distant source line.

Preserve source lines for retained byte spans and report both owners when an overlap conflicts.

---

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

@Ayinkx
Ayinkx marked this pull request as ready for review October 27, 2026 20:05
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-27T20:05:14.292833Z
We couldn’t complete this review. Comment @codex review to try again.
2c0527a Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@gensokyo-dev

Copy link
Copy Markdown
Collaborator

The Intel HEX/S-record slice is now integrated by #7136, including real GNU objcopy/BFD byte-for-byte verification, CLI/MCP regressions, and bounded/cancellable region streams. Closing this overlapping implementation to keep one owner for these formats. Umbrella #7129 remains open for the separate uImage/FIT work.

@morluto morluto added area: evidence Evidence, artifacts, and reconstruction enhancement New feature or request labels Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: evidence Evidence, artifacts, and reconstruction enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants