Skip to content

feat(firmware): inspect uClinux bFLT flat executables offline - #14663

Merged
morluto merged 6 commits into
morluto:mainfrom
mvanhorn:fix/bflt-executable-inventory
Nov 26, 2026
Merged

morluto merged 6 commits into
morluto:mainfrom
mvanhorn:fix/bflt-executable-inventory

Conversation

@mvanhorn

@mvanhorn mvanhorn commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

uClinux flat executables (bFLT) are the program format on no-MMU embedded Linux systems such as Cortex-M, ColdFire, Blackfin and RISC-V nommu boards, and they appear inside firmware root filesystems. REA does not recognize the format today, so a bFLT file comes back as an unknown blob. To see where text and data begin, where the program starts, how many relocations it carries, or to get at a gzip-compressed body, an analyst has to decode the 64-byte header by hand or with a separate tool and loses per-segment Evidence.

This adds an offline bflt artifact format. inspect-artifact and extract-artifact (and the MCP inspect_artifact / extract_artifact tools) recognize the bFLT magic regardless of filename, report the big-endian header as facts, and serve text (header included), data and the relocation table as extractable segments. gzip and gzdata bodies are inflated in memory under the existing artifact_limits.expanded_bytes budget. Relocations are listed, not applied, and nothing is executed. No issue exists for this; it is a format-inspection and ordinary-extraction addition within the supported contribution scope.

Problem and expected behavior

Use case: given a busybox bFLT pulled out of a firmware root filesystem, see its revision, flags, entry offset, segment boundaries, stack size and relocation table, inflate a compressed body, then extract text.bin and open it as a raw binary with an architecture taken from the firmware or kernel configuration.

Observable outcome:

  • A file starting with bFLT is recognized as bflt. The root is an archive whose architecture is null, because the flat header does not name a CPU.
  • The root format_metadata (kind: "bflt") reports revision, entry, data_start, data_end, bss_end, the derived text_size, data_size and bss_size, stack_size, reloc_start, reloc_count, flags with flag_names and unknown_flags, build_date (revision 4), compression, inflated_bytes, the first 64 relocations with relocations_truncated, and out_of_range_relocation_count.
  • Members are text.bin ([0, data_start), header included, so entry is an offset into it), data.bin and relocations.bin, each with kind: "bflt-segment" metadata. Stored segments keep their file range as source_location; segments that exist only after inflation have no file range and carry image_offset.
  • With gzip, everything after the header is one gzip stream; with gzdata, text is stored and the stream starts at data_start. Revision 2 loaders ignore these flags, so a revision 2 body is read as stored.
  • When the stream exceeds artifact_limits.expanded_bytes or cannot be inflated, the header facts are still reported, coverage is unknown, a limitation names the cause, and the stored bytes are served as compressed-body.gz (plus text.bin for gzdata).
  • Only a missing magic or a header shorter than 64 bytes refuses the file. An unknown revision, revision 2 relocation semantics, inconsistent segment offsets, an entry outside text, bss_end before data_end, a relocation table past the image, and more than 64 relocations become limitations beside the facts that still hold. Files over 128 MiB are rejected.
  • inspect-artifact adds one open_binary next probe: extract text.bin, open it as raw-binary with a caller-chosen architecture, and set the entry to a chosen load base plus the header entry.

Change and scope

  • src/domain/bfltExecutable.ts owns parsing: magic and header decoding, flag names, segment ranges, bounded gzip and gzdata inflation, relocation listing and range checks, and limitations. src/domain/bfltExecutable.fixture.ts builds synthetic files for the tests.
  • src/artifacts/BfltArtifactReader.ts maps the decoded executable onto the existing DecodedRegionArtifactReader, passing artifact_limits.expanded_bytes through, as the Intel HEX, S-record, UF2 and DfuSe readers already use that base.
  • Wiring: recognition in artifactFormatRecognition.ts, registration in artifactFormats.ts, bflt and bflt-segment metadata in artifactFormatMetadata.ts and formatMetadata/firmwareMetadata.ts, the inventory view, artifact graph, targetFormats.ts (archive), the reader format union, and the open_binary next probe in artifactInspection.ts.
  • Fixed limits in the diff and why they are not REA_ settings:
    • BFLT_MAX_FILE_BYTES = 128 MiB: a whole-file admission ceiling, the same fixed ceiling the DfuSe and Intel HEX readers use, because the decoder holds the file once in memory.
    • BFLT_LISTED_RELOCATIONS = 64: a delivery budget for the inline relocations list in header metadata, not an admission limit. Every entry is still range-checked and counted, and relocations.bin holds the complete table.
    • BFLT_HEADER_SIZE = 64: the size of the format's header as defined by flat.h, not a tunable budget.
    • Inflation has no new limit: it is charged to the existing caller-selected artifact_limits.expanded_bytes, with that parameter's existing default.
  • Docs: new docs/bflt-executables.md with the docs index and sidebar, a CLI example in docs/getting-started/cli.md, a section in docs/guides/firmware/firmware-analysis.md, bFLT gzip decompression in the expanded_bytes reader list in docs/reference/limits-and-recovery.md, and a bFLT entry in the skill references under .agents/skills/reverse-engineer-anything/ and its .cursor-plugin/ mirror.

Not included: applying relocations, resolving shared-library references, guessing the CPU, decoding revision 2 relocation words (their bit order and base segment depend on the target CPU), and any execution or loading.

Follow the contribution scope.
Unresolved scope, authority, side effects, or required verification block
integration. Link the required maintainer scope decision for new providers or
capabilities involving target execution, injection, mutation, or protection
recovery; ordinary fixes within existing boundaries may state "not applicable".
Draft PRs may leave the scope decision pending and the Author readiness and
Author checklist unchecked. Maintainers can help resolve open questions.

Contract and boundary impact

  • Semantic owner and earliest changed stage: bfltExecutable.ts produces the header facts, segment ranges, inflated image and limitations; the reader, inventory graph, inventory view and inspection next probes consume them without reparsing raw bytes.
  • Contribution scope fit and linked maintainer decision: format inspection and ordinary extraction of a local file; not applicable (no target execution, injection, mutation, or protection recovery).
  • CLI and MCP/tool-catalog contract: no new tools or parameters. Existing artifact tools recognize one more format value, bflt, and artifact_limits.expanded_bytes now also bounds bFLT inflation.
  • Provider, bridge, target-format, or platform compatibility: new target format bflt, classified as an archive target; existing formats unchanged. Recognition requires the 4-byte bFLT magic at offset 0.
  • Evidence, artifact, provenance, or reconstruction contract: new bflt and bflt-segment metadata shapes; stored segments carry source ranges, inflated segments carry image_offset, and every segment carries its SHA-256.
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): not applicable.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact (CI generates and validates ignored catalogs and skills/; edit authored instructions in .agents/skills/reverse-engineer-anything/ and never commit build outputs): none committed; authored skill references updated under .agents/skills/reverse-engineer-anything/ and .cursor-plugin/.

Expected effects (check known effects; use documentation-only on its own).
Unchecked items do not establish absence; leave uncertainties visible.

  • 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/domain/bfltExecutable.test.ts (revision 4 header facts and segment boundaries, gzip body inflation served by image offset only, gzdata text kept at its file offset with data inflated, an over-budget gzip body reported as a limitation with the stored bytes, revision 2 with its stored-entry caveat, a revision 2 body read as stored when gzip flag bits are set, build_date only for revision 4, revision 2 relocation words listed without range checks, a short or unmarked header refused, unknown revisions, unknown flags and out-of-range offsets, revision 4 relocations measured from the byte after the header through the end of bss, relocations past the inline budget, a relocation table past the file), src/artifacts/BfltArtifactReader.test.ts (inventory by magic with header facts and segment ranges, extraction of inflated gzip segments), tests/boundary/providers/native/artifactProvider.standaloneFormats.test.ts (the open_binary next probe for text.bin), and src/application/binary/TargetFormatVocabularies.test.ts.
  • Base reproduction or other evidence: source-derived. The base revision has no bflt format value or reader, so a bFLT file is not recognized there. The CLI output below is executed against this branch.
  • User-visible CLI/MCP output (if applicable): executed, node scripts/rea.mjs inspect-artifact plain.bflt --json on a file generated by bfltFile() (256 bytes of text, 8 bytes of data, 3 relocations, ram flag). Excerpt of the inventory substep's root format_metadata:
{
  "kind": "bflt",
  "revision": 4,
  "entry": 64,
  "data_start": 320,
  "data_end": 328,
  "bss_end": 344,
  "stack_size": 4096,
  "reloc_start": 328,
  "reloc_count": 3,
  "flags": 1,
  "flag_names": ["ram"],
  "unknown_flags": 0,
  "build_date": 1764115200,
  "build_date_iso": "2025-11-26T00:00:00.000Z",
  "compression": "none",
  "text_size": 320,
  "data_size": 8,
  "bss_size": 16,
  "inflated_bytes": null,
  "relocations": [16, 32, 260],
  "relocations_truncated": false,
  "out_of_range_relocation_count": 0
}

Coverage was {"scope":"container-entries","status":"complete"} and the members were text.bin (320 bytes, source_location {"offset":0,"length":320}), data.bin (8 bytes at offset 320) and relocations.bin (12 bytes at offset 328). The next probe was open_binary with the rationale "Extract text.bin with extract_artifact, then open it with format raw-binary, a caller-chosen architecture (the bFLT header names none) and entry_point set to a chosen load base. The program entry is that base plus 0x40; relocations are not applied."

gzip example: gzip.bflt (flags ram and gzip, 64 KiB of text and 4 KiB of data compressed into a 178-byte file) reported "compression": "gzip", "inflated_bytes": 69640, "data_start": 65600, "relocations": [16, 32] and complete coverage. The inflated data.bin occurrence was:

{"logical_path":"data.bin","declared_size":4096,"source_location":null,"format_metadata":{"kind":"bflt-segment","segment":"data","image_offset":65600,"length":4096},"hash_status":"verified"}

node scripts/rea.mjs extract-artifact gzip.bflt --output-root "$PWD/xout" --json wrote text.bin (65600 bytes), data.bin (4096 bytes) and relocations.bin (8 bytes) with containment_verified: true. The SHA-256 of text.bin (abd9b1e0...cdc389) and data.bin (267e5d2b...c6899d) matched both shasum -a 256 on the written files and an independent gzip.decompress of the stored body. A gzdata copy kept text.bin at its file range and inflated data.bin ("inflated_bytes": 4100).

Limitation examples:

  • The same gzip.bflt with --artifact-limits '{"expanded_bytes":4096}' exited 0 with coverage unknown, inflated_bytes null, one member compressed-body.gz (114 bytes at offset 64), and the limitation "The gzip body inflates past the 4096-byte artifact_limits.expanded_bytes budget; only the stored compressed bytes are exposed. Raise artifact_limits.expanded_bytes to inflate it."
  • A file whose header declares 1000 relocations with only one stored exited 0 with coverage unknown, text.bin and data.bin listed, no relocations.bin, out_of_range_relocation_count null, and the limitation "The relocation table [0x144, 0x10e4) runs past the 328-byte file; relocations are not listed."
  • A file with the gzip flag and a corrupt stream exited 0 with coverage unknown, compressed-body.gz (50 bytes) served and extractable, and the limitation "The gzip body is not a readable gzip stream; only the stored compressed bytes are exposed."

Refusal example: a 32-byte file starting with bFLT exited 1 with "code":"unsupported_target", "failure_kind":"malformed" and the reason "bFLT is malformed: bFLT header is truncated: 32 bytes, expected 64".

  • Remaining proof gaps: tested against synthetic files built from the flat.h header layout. No toolchain-built bFLT (for example from elf2flt) was used. The 128 MiB rejection is not exercised by a CLI run. The MCP tools were not exercised directly; they share the inventory and extraction path the CLI uses.

For boundary fixes, identify the applicable boundary regressions
and lifecycle regressions
covered by the evidence above, and explain relevant gaps.

Not a boundary fix. The new reader's tests cover a truncated header, a missing magic, segment and relocation ranges past the file, an over-budget compressed body, and an unreadable gzip stream. Cancellation is not separately tested for this format.

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.

Demo

Rendered walkthrough of the CLI inspect output above (simulated terminal, values taken from a real run on generated fixtures).

demo

rea-bflt-demo.mp4

Validation performed

  • npx vitest run src/application/binary/TargetFormatVocabularies.test.ts src/artifacts/BfltArtifactReader.test.ts src/domain/bfltExecutable.test.ts tests/boundary/providers/native/artifactProvider.standaloneFormats.test.ts: 77 tests passed, 0 failed
  • npm run check:fast (typecheck, lint, architecture guards): passed, "Architecture guards passed across 3135 source files."
  • npm run docs:check: passed, including tests/conformance/readmeConsistency.test.ts (8 tests)
  • npm run format:check: "All matched files use the correct format."
  • npm run verify:advertised-schemas: passed, 262 distinct schemas and 38 patterns accepted by V8, Go RE2 and Python re; the C++ RE2 and Rust engines were not installed locally and were not verified
  • npm run compile, then node scripts/rea.mjs inspect-artifact and extract-artifact on generated files: output as shown above

Compatibility, safety, and release

  • Breaking changes or migration steps: none.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable; offline parsing only, run on macOS. The open_binary next probe was not followed with a real provider in this run.
  • Package or release metadata impact: one new format value, bflt.
  • Security, privacy, process, or containment review: reads a local file only and extracts through the existing contained extraction path. Header offsets are target-derived and untrusted; every range is checked against the file or the inflated image before it is served, and a range that does not fit is reported, not clipped. Inflation is bounded by artifact_limits.expanded_bytes, and the whole file is bounded by the fixed 128 MiB ceiling.

AI was used for assistance.

Author readiness

Human owner: @mvanhorn

  • 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.

Author checklist (completed by the PR author before requesting review)

  • 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.
  • I ran every test, build, or measurement needed to validate this change, reported a browser, GPU, or environment gap only when that runtime or hardware is unavailable, and reported the checks I ran and their results without presenting inferred correctness or speedups as measured.
  • Comments explain constraints or non-obvious decisions; task history and conversations stay out of code and docs.
  • Documentation is concise and factual, without punchy slogans or promotional language.
  • This change fixes the root cause and follows the engineering rules in AGENTS.md.
  • Formatted input is interpreted once at the owning boundary, and consumers use the owner's parsed facts. See Interpret boundary facts once.
  • Combined failures preserve partial observations, remaining resources, and cleanup facts. See Own the lifecycle.
  • A hardcoded limit is an REA_ runtime setting with a default, floor, and maximum, unless a fixed ceiling has a stated reason. See Adding a runtime setting.

The reader matches the bFLT magic on any filename, records the 64-byte
big-endian header, and extracts text.bin (header included), data.bin,
and relocations.bin while listing relocations as stored words. gzip and
gzdata bodies inflate under artifact_limits.expanded_bytes; revision 2
is always stored, and its relocation words stay unchecked because their
layout depends on a CPU the header never names. A missing magic or a
header shorter than 64 bytes is the only refusal, other inconsistencies
are limitations beside the remaining facts, files above 128 MiB are
rejected, and the follow-up probe opens the text image as a raw binary
with a caller-chosen architecture and entry.
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

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

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-26T05:26:06.923976Z
We couldn’t complete this review. Comment @codex review to try again.
6396728 PR opened
ℹ️ 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.

@greptile-apps

greptile-apps Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The PR appears safe to merge; both previous findings are addressed, and no new actionable issue was established.RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[Medium impact] The PR appears safe to merge; both previous findings are addressed, and no new actionable issue was established.

Summary

Adds offline bFLT inspection and extraction, including header facts, stored and inflated segments, relocation listings, and follow-up guidance.

  • REA turns bFLT files into header facts and extractable segments.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[bFLT magic] --> B[Decode header]
  B --> C{Compressed body?}
  C -->|No| D[Stored image]
  C -->|Yes| E[Inflate under caller budget and fixed ceiling]
  E -->|Success| F[Inflated image]
  E -->|Failure or limit| G[Header facts and compressed fallback]
  D --> H[Text, data and relocation segments]
  F --> H
  H --> I[Inventory and contained extraction]
  G --> I
Loading

Reviews (4) · Last reviewed commit: "fix(firmware): cap bFLT in-memory gzip i..." · Reviewed by Greptile

Comment thread src/domain/bfltExecutable.ts Resolved
Comment thread src/domain/artifactInspection.ts Resolved
@morluto morluto added area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior enhancement New feature or request labels Nov 26, 2026
@morluto
morluto enabled auto-merge (squash) November 26, 2026 18:13
@morluto
morluto merged commit 04cb70c into morluto:main Nov 26, 2026
54 checks passed
@mvanhorn

Copy link
Copy Markdown
Contributor Author

@morluto thanks again for merging the bFLT support. Being able to inspect and extract uClinux flat executables offline beats decoding the 64-byte header by hand.

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