Repository navigation
Conversation
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.
[Medium impact] The change reaches the existing artifact inspection and extraction workflows. Fix CRLF rejection and quadratic region copying before merging. Findings
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.SummaryAdds Intel HEX and Motorola S-record classification, metadata, inventory, and extraction of contiguous decoded regions.
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]
Reviews (1) · Last reviewed commit: "feat(artifacts): inspect and extract Int..." · Reviewed by Greptile |
| 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`, |
There was a problem hiding this comment.
#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.| const merged = Buffer.concat([ | ||
| Buffer.from(previous.bytes), | ||
| Buffer.from(record.bytes.subarray(tailStart)), | ||
| ]); |
There was a problem hiding this 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.
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.| 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 }; |
There was a problem hiding this 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.
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.| 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); |
There was a problem hiding this 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.
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", |
There was a problem hiding this 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.
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!
| if (previousByte !== recordByte) | ||
| throw formatError( | ||
| record.line, | ||
| `conflicting overlap at address ${displayAddress(address)}: existing ${displayByte(previousByte ?? 0)}, record ${displayByte(recordByte ?? 0)}`, |
There was a problem hiding this comment.
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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
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. |
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_binaryrejected these text formats, soinspect_artifactandextract_artifactcould 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.srecfile needs to know which bytes load at which addresses and which start address the file declares.Expected and implemented:
0x08000000-0x08000003.bin.format_metadatarecords the variant, start address and its source record, record counts, EOF/termination state, and the S0 header for S-records.formatfailure naming both lines and the addressS4formatfailure naming the line02and04address modes mixedformatfailureformatfailure01or S-recordS7/S8/S9unknownS0, duplicate count recordformatfailureChange and scope
src/domain/firmwareText.ts: strict line/record parsing, checksums, address-mode validation, overlap comparison, region merging, and bounded expansion.FirmwareTextArtifactReaderprovides bounded, cancellable inventory and extraction with a carrier-identity check onopen().BinaryTargetResolverandclassifyArtifactBytes;format_metadataschemas.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
src/domain/firmwareText.tsowns record interpretation; the reader translates typed parser failures intoArtifactReaderFailure.intel-hexandsrec, and additiveformat_metadatavariants. Tool descriptions mention the new formats.byteOffset: nullbecause decoded bytes have no single source range. Declared addresses and record counts remain source facts. Failures name the line.Expected effects:
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.hexstaying 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) coveringopen_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:
For evidence-bearing changes:
Validation performed
Host: Windows x64, Node 24.22.1.
npm run compile— exit 0.vitest runon the four new test files — 21 passed.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
Author readiness
Human owner:
Before merge
type(scope): outcome.