Skip to content

feat(firmware): decode ARM M-profile and RISC-V mtvec interrupt vector tables - #14421

Merged
morluto merged 15 commits into
morluto:mainfrom
liziye627-design:feat/firmware-interrupt-vector-table
Nov 28, 2026
Merged

morluto merged 15 commits into
morluto:mainfrom
liziye627-design:feat/firmware-interrupt-vector-table

Conversation

@liziye627-design

@liziye627-design liziye627-design commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Advances #7955 and #3615 by adding inspect_firmware_vector_table (rea inspect-firmware-vector-table), a read-only, session-free static interrupt and trap vector-table disassembly operation for ARM M-profile (armv6-m, armv7-m, armv8-m) and RISC-V mtvec firmware images, with optional CMSIS-SVD <interrupt> peripheral binding.

Problem and expected behavior

Embedded and MCU firmware reverse engineering typically begins from hardware reset, exception, and external peripheral IRQ handlers rather than main(). Previously, REA validated only the Reset vector when opening raw ARM M-profile images and had no standalone static decoder to inventory system exceptions, external IRQ handler addresses, Thumb bit-0 violations, shared dummy/default handler loops, or RISC-V mtvec Direct/Vectored jump stubs.

With inspect_firmware_vector_table:

  • ARM M-profile (armv6-m, armv7-m, armv8-m): decodes 32-bit little-endian vector entries at caller-selected base_address + 128-byte VTOR-aligned vector_table_offset, reporting Initial MSP (word 0), profile-specific architectural system exceptions 1..15 (Reset, NMI, HardFault, SVCall, PendSV, SysTick; MemManage, BusFault, UsageFault, and DebugMonitor on armv7-m/armv8-m; SecureFault on armv8-m; slots 4, 5, 6, and 12 architecturally reserved on armv6-m) with name_basis: "architecture_manual", Thumb bit-0 validation, non-zero reserved-slot diagnostics, external IRQ 0..N entries, and shared_handler_groups for default infinite-loop stubs.
  • RISC-V mtvec (riscv): decodes 4-byte aligned trap-vector slots (JAL, AUIPC+JALR with bit-0 clearing, and compressed C.J), reporting slot 0's synchronous trap target in trap_entry_address while keeping reset_code_address: null, distinguishing vectored_jumps vs single_entry_or_inline table shape, labeling architectural standard slots (1, 3, 5, 7, 9, 11) with name_basis: "architecture_manual", and preserving unmapped local interrupt slots (>= 16) with name: null (name_basis: "observed_slot").
  • Optional CMSIS-SVD <interrupt> binding (svd_xml): parses <peripheral><interrupt><name>/<value> declarations within caller-adjustable max_svd_xml_nodes and max_svd_expanded_chars budgets (parseXmlDocumentWithinNodeLimit + Set-backed linear deduplication and pre-allocation expansion accounting) to label matching external IRQ numbers with name_basis: "explicit_profile", reporting duplicate IRQ declarations as explicit ambiguities rather than silently picking one.

Change and scope

Follow the contribution scope.
Read-only static byte and optional caller-supplied SVD XML inspection (not applicable for target execution, injection, mutation, or protection recovery). Does not guess base_address or fabricate vendor IRQ names when svd_xml is omitted.

Contract and boundary impact

  • Semantic owner and earliest changed stage: src/domain/firmware/firmwareVectorTable.ts, src/domain/firmware/firmwareSvdInterrupts.ts, src/domain/firmware/firmwareRiscvTrapVector.ts, and src/domain/firmware/firmwareVectorTableParser.ts own vector-slot decoding, profile-specific architectural exception tables, RISC-V branch-stub decoding (readUint16At/readUint32At from src/domain/binaryContainer.ts), and bounded SVD <interrupt> extraction (parseXmlDocumentWithinNodeLimit from src/domain/xmlDocument.ts).
  • Contribution scope fit and linked maintainer decision: Portable read-only static firmware diagnostic advancing [Roadmap] Embedded firmware: make REA work on the devices around us #7955 and [Feature] Hardware and Embedded Reverse Engineering: ESP32 firmware extraction, NVS decoding, raw flash mapping, and bus capture analysis #3615.
  • CLI and MCP/tool-catalog contract: Adds inspect_firmware_vector_table (rea inspect-firmware-vector-table <path> --architecture <arch> --base-address <hex> [--vector-table-offset N] [--max-entries N] [--svd-xml <xml>] [--max-svd-xml-nodes N] [--max-svd-expanded-chars N] [--max-file-bytes N]).
  • Provider, bridge, target-format, or platform compatibility: Portable Node.js provider (FIRMWARE_VECTOR_TABLE_PROVIDER in src/firmware/vectorTable/FirmwareVectorTableProvider.ts).
  • Evidence, artifact, provenance, or reconstruction contract: Emits SHA-256-bound Evidence with file-offset-range table span, omitting defaulted controls via callerAnalysisParameters(rawInput) and preserving name_basis ("architecture_manual" | "explicit_profile" | "observed_slot") and thumb_bit_set per entry.
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): Uses ArtifactResourceScope, withStableArtifactHandle, and readAdmittedRange so whole-file SHA-256 is streamed while retaining only the bounded vector-table slice; max_file_bytes, max_svd_xml_nodes, and max_svd_expanded_chars limits report typed details.limit (control_kind: "parameter").
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact: Authored guide added at docs/guides/firmware/firmware-vector-tables.md, advertised schema summary updated at scripts/verify/advertised-schemas/tools/inspect_firmware_vector_table.json, and skill guidance updated in .agents/skills/reverse-engineer-anything/references/native-and-artifacts.md (synced to .cursor-plugin/). Ignored generated outputs remain uncommitted.

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/domain/firmware/firmwareVectorTable.test.ts (executed): ARMv6-M reserved-slot enforcement (slots 4, 5, 6, 12), ARMv7-M and ARMv8-M (SecureFault) exception decoding, even-address Thumb bit-0 violation detection, shared default-handler grouping, CMSIS-SVD <interrupt> linear Set deduplication and expansion bounds, and RISC-V mtvec JAL / C.J / odd-immediate AUIPC+JALR trap decoding with trap_entry_address and reset_code_address: null.
    • src/application/binaryDiagnostics/FirmwareVectorTableService.test.ts (executed): digest-bound Evidence locations, omitted-default parameter preservation, late-cancellation Evidence retention, and typed control_kind: "parameter" limit recovery.
    • src/firmware/vectorTable/FirmwareVectorTableProvider.test.ts (executed): withStableArtifactHandle streaming SHA-256 + bounded positional slice read, max_file_bytes / max_svd_xml_nodes / max_svd_expanded_chars budget refusals, AbortSignal cancellation cause preservation, and read-coverage integrity handling.
    • tests/boundary/mcp/firmwareVectorTableMcpCli.test.ts (executed): end-to-end advertised MCP and public CLI parity, registered in providerCapabilityCases.ts and providerLifecycleCoverage.ts.
  • Base reproduction or other evidence: Prior to this change, REA had no static vector-table inventory or SVD IRQ mapper for raw MCU images.
  • Remaining proof gaps: RISC-V mtvec mode bit (DIRECT vs VECTORED) is configured by runtime csrw mtvec code rather than the table bytes themselves, so table-only inspection reports structural jump-slot evidence and notes that runtime mtvec.MODE remains unverified until code inspection.

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

  • node scripts/run-typescript.mjs --noEmit && node scripts/run-typescript.mjs --noEmit -p tsconfig.scripts.json — passed
  • npx oxlint -c .oxlintrc.json --quiet ... && npx oxfmt --check ... && node scripts/verify/architecture-guards.mjs && node scripts/verify-module-boundaries.mjs && node scripts/verify/fixed-ceilings.mjs && node scripts/verify/rea-numeric-limits.mjs — passed
  • node scripts/run-typescript.mjs && node scripts/verify-advertised-schemas.mjs --package-root=. --update-summary — passed
  • npx vitest run src/domain/firmware/firmwareVectorTable.test.ts src/application/binaryDiagnostics/FirmwareVectorTableService.test.ts src/firmware/vectorTable/FirmwareVectorTableProvider.test.ts tests/boundary/mcp/firmwareVectorTableMcpCli.test.ts tests/conformance/providerCapabilityConformance.test.ts tests/evaluation/providerLifecycleCoverage.test.ts tests/evaluation/fixedCeilingGuard.test.ts tests/evaluation/moduleReExportGuard.test.ts tests/boundary/cli/cliContractCommandParity.test.ts tests/boundary/mcp/enhancedTools.01-lists-the-complete-target-open.test.ts — passed

Compatibility, safety, and release

  • Breaking changes or migration steps: None; additive CLI/MCP inspection operation.
  • Real Hopper/Ghidra, browser, or OS coverage: Exercised on Windows x64; portable Node implementation.
  • Package or release metadata impact: Updated advertised schema summary and .cursor-plugin skill mirror.
  • Security, privacy, process, or containment review: Streaming whole-file SHA-256 with bounded table-slice reads (withStableArtifactHandle), Saxes node-counted XML parsing disallowing DOCTYPE (parseXmlDocumentWithinNodeLimit), pre-allocation SVD expansion bounds, and ArtifactResourceScope handle cleanup.

Author readiness

Human owner: @liziye627-design

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

@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-25T05:49:19.044339Z
We couldn’t complete this review. Comment @codex review to try again.
703e7f3 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 25, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The PR appears safe to merge; no new blocking issue was established.RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[Medium impact] The PR appears safe to merge; no new blocking issue was established.

Summary

Adds read-only firmware vector inspection through CLI and MCP.

  • ARM and RISC-V firmware tables now show their exception and trap targets.
  • Caller-supplied CMSIS-SVD data can name matching firmware interrupts.
  • CLI and MCP callers can run the table inspection and retrieve its saved results.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[CLI or MCP request] --> B[Check caller inputs]
  B --> C[Parse optional SVD within budgets]
  C --> D[Stream file digest and retain bounded table bytes]
  D --> E{Architecture}
  E --> F[Decode ARM vectors]
  E --> G[Decode RISC-V jump slots]
  F --> H[Build counts, coverage and diagnostics]
  G --> H
  H --> I[Check file stability and close handle]
  I --> J[Create digest-bound Evidence]
  J --> K[Complete result]
  J --> L[Retained summary]
  L --> M[Paged analysis views]
Loading

Reviews (13) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." · Reviewed by Greptile

@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
@liziye627-design
liziye627-design force-pushed the feat/firmware-interrupt-vector-table branch 2 times, most recently from 3ac2264 to ebd570b Compare November 26, 2026 20:44
@liziye627-design
liziye627-design force-pushed the feat/firmware-interrupt-vector-table branch from ebd570b to ae48a8b Compare November 27, 2026 16:25
…t unbound SVD interrupts

The architecture field now takes the ARM M-profile variant names REA uses
for raw images (armv6-m through armv8.1-m.main) plus riscv. ARMv8-M
Baseline gets ARMv6-M's exceptions; only Mainline names MemManage,
BusFault, UsageFault, SecureFault and DebugMonitor. The old armv8-m value
named Mainline faults on Cortex-M23 tables.

vtor_aligned checks the 128-byte ARMv7-M/ARMv8-M minimum and is null on
ARMv6-M, whose VTOR is optional and implementation-defined. Slots past the
end of the 32-bit address space are no longer decoded with wrapped
addresses, and an initial stack pointer that is not word-aligned is
flagged.

CMSIS-SVD interrupts without a name or with a non-integer value are
reported as anomalies instead of skipped silently, and the expanded-name
budget is charged once while parsing instead of twice with two formulas.
likely_default_stub is removed: every shared-handler group set it to true.
RISC-V limitations now cover vectored exceptions on slot 0, CLIC address
tables and the mcause numbering assumed for SVD bindings.
@morluto

morluto commented Nov 27, 2026

Copy link
Copy Markdown
Owner

Maintainer review of the vector-table decoder, checked against CMSIS-Core, the CMSIS-SVD schema and the RISC-V Privileged spec. Fixes are in commit 27728d8 on this branch. Please pull before rebasing so the commit isn't dropped.

Defects fixed

  1. Wrong exception names on ARMv8-M Baseline. armv8-m named MemManage, BusFault, UsageFault, SecureFault and DebugMonitor on every ARMv8-M table. ARMv8-M Baseline (Cortex-M23) has only ARMv6-M's exceptions; CMSIS IRQn_Type confirms that for Cortex-M23 versus Cortex-M33.
    • New values: architecture now takes the M-profile variant names REA already uses for raw images (architectureVariant.ts: armv6-m, armv7-m, armv7e-m, armv8-m.base, armv8-m.main, armv8.1-m.main) plus riscv.
    • Breaking for callers of this PR: armv8-m is no longer accepted.
  2. VTOR alignment.
    • ARMv6-M: VTOR is optional (absent on Cortex-M0), and CMSIS puts TBLOFF at bit 8 on Cortex-M0+, so vtor_aligned is now null there.
    • ARMv7-M and ARMv8-M: it checks the architectural 128-byte minimum. A limitation notes the additional power-of-two requirement: alignment to the next power of two of the implemented exception count, which the image does not record.
  3. Address wrap. With a base near the top of the 32-bit space, slot addresses wrapped to low memory. Decoding now stops at the end of the address space, and coverage is partial.
  4. Initial SP. A value that isn't word-aligned is now flagged. SP_main bits [1:0] are RAZ/WI, so the processor would start with a different stack pointer.
  5. Silent SVD skips. Interrupts without a name, or with a value that isn't a non-negative integer, were skipped silently, and so were the interrupts of a nameless peripheral. They are now listed in anomalies.
    • The schema declares <value> as xs:integer, so decimal with an optional + is accepted.
    • 0x and 0X hexadecimal are also accepted, because vendor files use them.
  6. RISC-V assumptions are now stated as limitations:
    • in vectored mode slot 0 also receives every synchronous exception;
    • a CLIC (mtvt) table holds addresses rather than jumps, so its slots decode as unrecognized;
    • SVD values are bound as mcause codes 16 and up.

Brittleness fixed

  • Duplicated budget accounting. The SVD name budget was charged twice: once while parsing, and again while decoding slots, with a different formula in each of two files. A slot can never emit more text than its declaration, so it is now charged once, at parse time. expandedChars and the two svdEntryChars copies are removed.
  • Tautological field. likely_default_stub was always true, because only groups of two or more slots are emitted. It is removed; groups are still sorted most-shared first.
  • Named constants. Exception and VTOR tables moved to firmwareArmExceptions.ts, keyed by variant, so a new variant fails to compile until it is classified. Constants are named after their source (ARM_EXTERNAL_IRQ_BASE and others).
  • One formatter. hex32 was duplicated and is now one export.

Left as is

decodeArmVectorEntries keeps five parameters, which the lint flags. The ESP and RISC-V decoders aren't touched beyond the above.

Tests

There are six new regressions: Baseline versus Mainline naming, ARMv6-M VTOR unknown, the address-space end, a misaligned SP, unbound SVD interrupts, and the RISC-V limitations. These pass:

  • test:local on the domain, provider and service tests;
  • test:focused on firmwareVectorTableMcpCli.test.ts;
  • check:fast, docs:check, and the advertised-schema check (regenerated).

Sources

  • ARM-software/CMSIS_5 CMSIS-Core:
    • core_cm0plus.h, core_cm3.h/cm4/cm7, core_cm23.h and core_cm33.h: SCB_VTOR_TBLOFF_Pos.
    • The device IRQn_Type enums, via DeepWiki.
  • CMSIS/Utilities/CMSIS-SVD.xsd: interruptType/value is xs:integer.
  • The Armv6-M, Armv7-M and Armv8-M Architecture Reference Manuals: exception numbers, VTOR and SP_main.
  • The RISC-V Privileged Architecture: mcause interrupt codes, mtvec MODE and alignment.
  • The RISC-V CLIC specification: mtvt.

… RISC-V tables

Duplicate interrupt declarations were found by rebuilding a key that
repeats the full peripheral name for every <interrupt>, so a long name
repeated across many declarations cost name length times declaration
count. Bound names are now indexed per peripheral name, looked up once
per <peripheral>.

The 8-byte minimum held for every architecture, but only an ARM table
must start with InitialSP and Reset; a RISC-V Direct-mode table can be
one instruction. max_entries and max_file_bytes now admit one slot.
@morluto
morluto enabled auto-merge (squash) November 27, 2026 18:27
auto-merge was automatically disabled November 27, 2026 19:14

Head branch was pushed to by a user without write access

Comment thread src/cli/binaryDiagnosticsCommands.ts Resolved
…ir owners

Recovery assertions compare the delivered action with the shared refusal
formatter applied to the reported limit, instead of pinning sentences.
The summary-delivery test set REA_AGENT_RESULT_MAX_BYTES, which nothing
reads, and used a result large enough to exceed the default budget too;
it now sets REA_AGENT_RESULT_BUDGET_BYTES, asserts the reported budget,
and uses a result between the minimum and default budgets, checking that
the default delivers it complete.

The view counts active ARM entries and recognized RISC-V slots with a loop
instead of filtered copies.
The analysis view recounted active ARM entries and recognized RISC-V slots
on every summary and page request. The producer already collects exactly
those slots as handler targets, so the report now stores
active_arm_entry_count and recognized_riscv_slot_count from them, and the
view reads the stored fields. The service checks the stored counts against
the slots once when it validates the provider's report.
@morluto
morluto enabled auto-merge (squash) November 27, 2026 22:21
@morluto
morluto disabled auto-merge November 27, 2026 22:30
@morluto
morluto enabled auto-merge (squash) November 27, 2026 22:34
@morluto
morluto disabled auto-merge November 27, 2026 22:36
@morluto
morluto enabled auto-merge (squash) November 27, 2026 22:37
@morluto
morluto disabled auto-merge November 27, 2026 22:38
@morluto
morluto enabled auto-merge (squash) November 27, 2026 22:42
@morluto
morluto disabled auto-merge November 27, 2026 22:45
@morluto
morluto enabled auto-merge (squash) November 27, 2026 22:47
@morluto
morluto disabled auto-merge November 27, 2026 22:51
@morluto
morluto enabled auto-merge (squash) November 27, 2026 23:04
@morluto
morluto disabled auto-merge November 27, 2026 23:06
@morluto
morluto enabled auto-merge (squash) November 27, 2026 23:14
@morluto
morluto disabled auto-merge November 27, 2026 23:17
@morluto
morluto enabled auto-merge (squash) November 27, 2026 23:29
@morluto
morluto disabled auto-merge November 27, 2026 23:31
@morluto
morluto enabled auto-merge (squash) November 27, 2026 23:34
@morluto
morluto disabled auto-merge November 27, 2026 23:36
@morluto
morluto enabled auto-merge (squash) November 28, 2026 00:07
auto-merge was automatically disabled November 28, 2026 00:48

Head branch was pushed to by a user without write access

# Conflicts:
#	src/domain/analysisView/analysisView.ts
#	src/domain/analysisView/analysisViewRequest.ts
#	src/domain/analysisView/analysisViewResult.ts
#	src/server/toolResult.ts
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