Files
reverse-engineering-anything/src/cli/binaryDiagnosticsCommands.ts
T
0af842ad26 feat(firmware): disassemble RISC-V, MIPS32, PowerPC, and ARM64 split-immediate MMIO accesses (#15413)
* feat(firmware): disassemble RISC-V, MIPS32, PowerPC, and ARM64 split-immediate MMIO accesses

* fix(firmware): tighten SVD interval inheritance and split-immediate register tracking

* fix(firmware): bound inherited SVD block expansion and decode exact destination GPRs

* fix(firmware): clear Rs across acquire-ordered ARM64 CAS and CASP variants

* chore(mcp): sync advertised schema summary and budget projection with main

* fix(firmware): bound CMSIS-SVD numeric widths before BigInt and index expansion

* fix(firmware): keep rejected SVD addressBlocks distinct from omitted spans

* fix(firmware): bound MMIO representation growth and preserve SVD ambiguity

* perf(firmware): memoize SVD address lookups and pre-rank peripheral names

* fix(firmware): scan a whole application image by default for MMIO syntheses

On the 1.36 MB IROM segment of the MicroPython 1.24.1 ESP32-C3 image, a
default call scanned 256 KiB and kept 512 of 713 matching accesses. The
omitted rows were not in the retained Evidence, so the agent had to repeat
the call with larger controls or page by scan_offset. Defaults now scan
4 MiB and keep up to 32,768 syntheses within a 16 MiB representation
allowance, matching the literal-pool tool. Retained summary delivery still
sizes what reaches the agent. The image completes in about 1 s with 4,073
syntheses.

Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* refactor(firmware): use MMIO synthesis maximums as their defaults directly

The default scan, synthesis and representation constants only repeated
their maximums, which Knip reports as duplicate exports. The budgets and
the parser fallback now name the maximums.

Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* fix(firmware): bound SVD match cache weight, exclude RISC-V flash, and report scan-limit stops

---------

Co-authored-by: gensokyo-dev <gensokyo-dev@users.noreply.github.com>
Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
2026-12-03 17:22:49 +08:00

832 lines
25 KiB
TypeScript

import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import {
withEvidenceCallerInputPath,
type Evidence,
} from "../domain/evidence.js";
import { BYTE_ENTROPY_PROVIDER } from "../domain/investigationProviders.js";
import { ok } from "../domain/result.js";
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "../contracts/native/binaryDiagnosticsToolContracts.js";
import { deliverCliAnalysisEvidence } from "./analysisEvidenceDelivery.js";
import { cliPublicationInvocation } from "./cliEvidencePublication.js";
import { contractNamed } from "./contractCliDescription.js";
import {
callerTargetPath,
registerContractCommand,
} from "./contractCommand.js";
import {
deliverWithService,
inspectWithService,
} from "./contractCommandRunners.js";
import { PRODUCER_LIMITS_HELP } from "./producerLimitsOption.js";
import { UNIVERSAL_SLICE_ARCHITECTURE_HELP } from "./universalSliceOption.js";
type BinaryDiagnosticsOperation =
(typeof BINARY_DIAGNOSTICS_TOOL_CONTRACTS)[number]["name"];
const contract = <Name extends BinaryDiagnosticsOperation>(name: Name) =>
contractNamed(BINARY_DIAGNOSTICS_TOOL_CONTRACTS, name);
const singleCallerPath = {
positionals: ["path"],
callerPaths: ["path"],
} as const;
/** Inspect operator-selected files through the same shared workflow as MCP. */
export const registerBinaryDiagnosticsCommands = (
cli: CliInstance,
logger: Logger,
environment: Readonly<NodeJS.ProcessEnv>,
): void => {
registerContractCommand(
cli,
logger,
contract("inspect_elf_notes"),
{
description:
"Inspect ELF PT_NOTE and SHT_NOTE identities without executing the image",
...singleCallerPath,
fields: { path: { description: "Local ELF32/ELF64 image" } },
},
inspectWithService(
async () =>
(
await import("../composition/binaryDiagnostics/elfNotes.js")
).createElfNotesService(),
"rea-elf-notes",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_dwarf_units"),
{
description: "Inspect DWARF compile units without executing the image",
...singleCallerPath,
fields: {
path: {
description:
"Local ELF, Mach-O, or PE image, or a DWARF file inside a .dSYM bundle",
},
architecture: {
description: UNIVERSAL_SLICE_ARCHITECTURE_HELP,
},
},
},
inspectWithService(
async () =>
(
await import("../composition/binaryDiagnostics/dwarfUnits.js")
).createDwarfUnitsService(),
"rea-dwarf-units",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_elf_debug_link"),
{
description:
"Inspect ELF separate debug-file linkage without executing the image",
positionals: ["path"],
callerPaths: ["path", "candidate_path"],
fields: {
path: { description: "Local ELF32/ELF64 image" },
candidate_path: {
description: "One caller-selected debug file to verify",
},
},
},
inspectWithService(
async () =>
(
await import("../composition/binaryDiagnostics/elfDebugLink.js")
).createElfDebugLinkService(),
"rea-elf-debug-link",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_native_initializers"),
{
description:
"List ELF and Mach-O initializer and finalizer functions without executing the image",
...singleCallerPath,
fields: {
path: {
description:
"Local ELF32/ELF64, thin Mach-O or universal Mach-O image",
},
architecture: {
description: UNIVERSAL_SLICE_ARCHITECTURE_HELP,
},
},
},
inspectWithService(
async () =>
(
await import("../composition/binaryDiagnostics/nativeInitializers.js")
).createNativeInitializersService(),
"rea-native-initializers",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_elf_unwind_ranges"),
{
description:
"Inspect ELF unwind function ranges without executing the image",
...singleCallerPath,
fields: { path: { description: "Local ELF32/ELF64 image" } },
},
inspectWithService(
async () =>
(
await import("../composition/binaryDiagnostics/elfUnwindRanges.js")
).createElfUnwindRangesService(),
"rea-elf-unwind-ranges",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_pe_unwind_ranges"),
{
description:
"Inspect x64 PE exception-directory function ranges without executing the image",
...singleCallerPath,
fields: { path: { description: "Local PE32+ image" } },
},
inspectWithService(
async () =>
(
await import("../composition/binaryDiagnostics/peUnwindRanges.js")
).createPeUnwindRangesService(),
"rea-pe-unwind-ranges",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_macho_function_starts"),
{
description:
"List Mach-O function starts and data-in-code entries without executing the image",
...singleCallerPath,
fields: {
path: {
description: "Local thin Mach-O or universal Mach-O image",
},
architecture: {
description: UNIVERSAL_SLICE_ARCHITECTURE_HELP,
},
},
},
inspectWithService(
async () =>
(
await import("../composition/binaryDiagnostics/machoFunctionStarts.js")
).createMachoFunctionStartsService(),
"rea-macho-function-starts",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_apple_ips"),
{
description:
"Inspect an Apple .ips crash report without executing a target",
positionals: ["path"],
callerPaths: ["path", "join_path"],
fields: {
path: { description: "Local Apple .ips crash report" },
join_path: {
description:
"Optional local Mach-O executable or dSYM whose slice LC_UUID matches report images",
},
},
},
inspectWithService(
async () =>
(
await import("../composition/binaryDiagnostics/appleIps.js")
).createAppleIpsService(),
"rea-apple-ips",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_kernel_module"),
{
description:
"Inspect Linux kernel module metadata without executing the module",
...singleCallerPath,
fields: {
path: {
description:
"Local ELF32/ELF64 kernel module or compressed .ko container",
},
},
},
inspectWithService(
async () =>
(
await import("../composition/binaryDiagnostics/kernelModule.js")
).createKernelModuleService(),
"rea-kernel-module",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_kernel_build_config"),
{
description:
"Inspect a Linux kernel image's version banner and embedded build config without executing it",
...singleCallerPath,
fields: {
path: {
description:
"Local vmlinux ELF, raw Image, x86 bzImage/zImage, or configs.ko",
},
},
},
inspectWithService(
async () =>
(
await import("../composition/binaryDiagnostics/kernelBuildConfig.js")
).createKernelBuildConfigService(),
"rea-kernel-build-config",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_pe_load_config"),
{
description:
"Inspect PE TLS callbacks and load configuration without executing the image",
...singleCallerPath,
fields: { path: { description: "Local PE32/PE32+ image" } },
},
inspectWithService(
async () =>
(
await import("../composition/binaryDiagnostics/peLoadConfig.js")
).createPeLoadConfigService(),
"rea-pe-load-config",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_pe_overlay"),
{
description:
"Report bytes appended after a PE image, including a certificate-table split",
...singleCallerPath,
fields: { path: { description: "Local PE32/PE32+ image" } },
},
inspectWithService(
async () =>
(
await import("../composition/binaryDiagnostics/peOverlay.js")
).createPeOverlayService(),
"rea-pe-overlay",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_binary_hardening"),
{
description:
"Inspect ELF, PE, and Mach-O hardening without executing the image",
...singleCallerPath,
fields: { path: { description: "Local ELF, PE, or Mach-O image" } },
},
inspectWithService(
async () =>
(
await import("../composition/binaryDiagnostics/binaryHardening.js")
).createBinaryHardeningService(),
"rea-binary-hardening",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_byte_entropy"),
{
description:
"Inspect file-wide and block byte entropy without executing the file",
...singleCallerPath,
evidenceDelivery: true,
fields: {
path: { description: "Local file" },
block_size: {
description: "Power-of-two block size from 256 to 65536 bytes",
},
offset: { description: "Window start as a decimal file byte offset" },
length: {
description: "Window length in bytes; omit to extend through EOF",
},
},
},
deliverWithService(
async () =>
(
await import("../composition/binaryDiagnostics/byteEntropy.js")
).createByteEntropyService(),
BYTE_ENTROPY_PROVIDER.id,
),
);
registerContractCommand(
cli,
logger,
contract("inspect_pe_certificates"),
{
description:
"Inspect PE Authenticode certificate table identities without verifying signatures",
...singleCallerPath,
fields: { path: { description: "Local PE32/PE32+ image" } },
},
inspectWithService(
async () =>
(
await import("../composition/binaryDiagnostics/peCertificates.js")
).createPeCertificatesService(),
"rea-pe-certificates",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_pe_imports"),
{
description:
"Inspect PE import and delay-load table identities without executing the image",
...singleCallerPath,
evidenceDelivery: true,
fields: { path: { description: "Local PE32/PE32+ image" } },
},
deliverWithService(
async () =>
(
await import("../composition/binaryDiagnostics/peImports.js")
).createPeImportsService(),
"rea-pe-imports",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_windows_shortcut"),
{
description:
"Inspect a Windows Shell Link (.lnk) without resolving or executing the target",
...singleCallerPath,
fields: {
path: { description: "Local Windows Shell Link (.lnk) file" },
},
},
inspectWithService(
async () =>
(
await import("../composition/binaryDiagnostics/windowsShortcut.js")
).createWindowsShortcutService(),
"rea-windows-shortcut",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_pe_resources"),
{
description:
"Inspect PE resource identities, payload ranges, hashes and icon-group relationships",
...singleCallerPath,
evidenceDelivery: true,
fields: { path: { description: "Local PE32/PE32+ image" } },
},
deliverWithService(
async () =>
(
await import("../composition/binaryDiagnostics/peResources.js")
).createPeResourcesService(),
"rea-pe-resources",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_devicetree"),
{
description: "Inspect a flattened devicetree blob without executing it",
...singleCallerPath,
evidenceDelivery: true,
fields: {
path: { description: "Local flattened devicetree image" },
max_file_bytes: { description: "Maximum FDT file size in bytes" },
max_nodes: { description: "Maximum number of device-tree nodes" },
max_properties: {
description: "Maximum number of device-tree properties",
},
max_depth: { description: "Maximum device-tree nesting depth" },
max_decoded_bytes: {
description:
"Maximum estimated bytes of the decoded report, charged before allocation",
},
},
},
deliverWithService(
async () =>
(
await import("../composition/binaryDiagnostics/devicetree.js")
).createDevicetreeService(),
"rea-devicetree",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_native_exports"),
{
description:
"Inspect PE or ELF image's export table without executing it",
...singleCallerPath,
evidenceDelivery: true,
fields: { path: { description: "Local PE or ELF image" } },
},
deliverWithService(
async () =>
(
await import("../composition/binaryDiagnostics/nativeExports.js")
).createNativeExportsService(),
"rea-native-exports",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_elf_dependencies"),
{
description:
"Inspect ELF needed libraries and required symbol versions without executing the image",
...singleCallerPath,
evidenceDelivery: true,
fields: {
path: { description: "Local ELF32/ELF64 ET_EXEC or ET_DYN image" },
},
},
deliverWithService(
async () =>
(
await import("../composition/binaryDiagnostics/elfDependencies.js")
).createElfDependenciesService(),
"rea-elf-dependencies",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_binary_layout"),
{
description:
"Inspect ELF file/linked layout without executing the selected object; Linux x64 with caller-supplied pwntools only",
...singleCallerPath,
jsonText: ["producer_limits"],
fields: {
path: { description: "Local ELF binary or relocatable object" },
producer_limits: { description: PRODUCER_LIMITS_HELP },
},
omit: {
detail:
"One-shot output is complete Evidence; this command has no summary delivery",
},
},
async (input, context) => {
const { createBinaryLayoutService } =
await import("../composition/binaryDiagnostics/binaryLayout.js");
const result = await createBinaryLayoutService(
environment,
).inspectAndClose(input, {
signal: context.signal,
});
return result.ok
? withEvidenceCallerInputPath(result.value, callerTargetPath(context))
: projectAnalysisError(result.error);
},
);
registerContractCommand(
cli,
logger,
contract("inspect_recorded_crash"),
{
description:
"Inspect supplied core registers/signals and optional debugger mapping evidence",
...singleCallerPath,
jsonText: ["producer_limits"],
fields: {
path: {
description: "Local Linux ELF64 amd64 or AArch64 little-endian core",
},
producer_limits: { description: PRODUCER_LIMITS_HELP },
include_debugger_context: {
name: "debuggerContext",
description: "Add BYO core-only GDB/pwndbg mapping candidates",
},
},
},
async (input, context) => {
const { createRecordedCrashService } =
await import("../composition/binaryDiagnostics/recordedCrash.js");
const result = await createRecordedCrashService(
environment,
).inspectAndClose(input, {
signal: context.signal,
});
return result.ok
? withEvidenceCallerInputPath(result.value, callerTargetPath(context))
: projectAnalysisError(result.error);
},
);
registerContractCommand(
cli,
logger,
contract("inspect_esp_nvs"),
{
description:
"Decode an ESP-IDF v1/v2 Non-Volatile Storage (NVS) partition or flash slice without executing it",
...singleCallerPath,
evidenceDelivery: true,
fields: {
path: { description: "Local NVS partition image or ESP flash dump" },
partition_offset: {
description: "4096-byte aligned NVS start offset inside path",
},
partition_bytes: {
description: "Optional 4096-byte multiple NVS slice length",
},
max_entries: {
description:
"Optional inline cap on decoded NVS entries; complete entries remain in --evidence_output",
},
max_file_bytes: { description: "Maximum input file size in bytes" },
max_decoded_bytes: {
description:
"Maximum estimated decoded NVS representation size in bytes",
},
},
},
async (input, context) => {
const { createEspNvsService } =
await import("../composition/binaryDiagnostics/espNvs.js");
const service = createEspNvsService();
const retainedSources: Evidence[] = [];
const retention =
context.delivery?.evidenceOutput !== undefined ||
(context.delivery?.detail === undefined &&
cliPublicationInvocation().retention !== undefined)
? {
recordEvidence: (evidence: Evidence) => {
retainedSources.push(evidence);
return ok("added" as const);
},
evidenceById: (id: string) =>
retainedSources.find((record) => record.evidence_id === id),
}
: undefined;
return deliverCliAnalysisEvidence({
callerInputPath: callerTargetPath(context),
run: async () => {
const result = await service.inspect(
input,
{ signal: context.signal },
retention,
);
// Summary delivery returns no inline entries; project the summary and
// publish its bundle from the uncapped parent Evidence.
if (
result.ok &&
context.delivery?.detail === "summary" &&
retainedSources.length > 0
) {
return ok(retainedSources.pop()!);
}
return result;
},
service,
providerId: "rea-esp-nvs",
operation: context.operation,
signal: context.signal,
detail: context.delivery?.detail,
evidenceOutput: context.delivery?.evidenceOutput,
...(context.delivery?.view === undefined
? {}
: { view: context.delivery.view }),
sourceEvidence: retainedSources,
});
},
);
registerContractCommand(
cli,
logger,
contract("inspect_firmware_architecture_candidates"),
{
description:
"Propose CPU architecture, endianness, and Cortex-M load-base candidates for a firmware blob without opening a disassembler",
positionals: ["path"],
callerPaths: ["path"],
fields: {
path: {
description:
"Local firmware blob, flash dump, or container image path",
},
max_file_bytes: {
name: "max-file-bytes",
description: "Whole-file admission ceiling in bytes (default 64 MiB)",
},
max_scan_bytes: {
name: "max-scan-bytes",
description:
"Contiguous prefix bytes examined by header and opcode detectors (default 4 MiB)",
},
},
},
inspectWithService(
async () =>
(
await import("../composition/binaryDiagnostics/firmwareArchitectureCandidates.js")
).createFirmwareArchitectureCandidatesService(),
"rea-firmware-architecture-candidates",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_firmware_literal_pools"),
{
description:
"Disassemble ARM Thumb/Thumb-2/A32 or Xtensa L32R PC-relative literal-pool loads and attribute MMIO pointers without executing firmware",
...singleCallerPath,
evidenceDelivery: true,
fields: {
path: { description: "Local firmware binary or flash slice path" },
isa: {
description: "Instruction encoding (arm-thumb, arm-a32, or xtensa)",
},
base_address: {
description:
"Explicit 32-bit hex load base address for file offset 0",
},
scan_offset: {
description:
"Start byte offset inside path for linear instruction scan",
},
max_scan_bytes: {
description: "Maximum instruction byte span to scan from scan_offset",
},
max_references: {
description:
"Maximum resolved literal-pool load references accepted before refusing",
},
max_representation_bytes: {
description:
"Maximum cumulative UTF-8 representation bytes accepted before building Evidence",
},
svd_xml: {
description:
"Optional CMSIS-SVD XML document for <peripheral> address-block attribution",
},
max_svd_nodes: {
description: "Maximum XML nodes accepted when parsing svd_xml",
},
max_file_bytes: {
description: "Maximum firmware file size in bytes",
},
},
},
deliverWithService(
async () =>
(
await import("../composition/binaryDiagnostics/firmwareLiteralPools.js")
).createFirmwareLiteralPoolsService(),
"rea-firmware-literal-pools",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_firmware_vector_table"),
{
description:
"Decode an ARM M-profile, ARM A/R, RISC-V mtvec, AVR, or M68000 interrupt/exception vector table without executing it",
...singleCallerPath,
evidenceDelivery: true,
fields: {
path: { description: "Local firmware binary or flash dump" },
architecture: {
description:
"Target profile: an ARM M-profile variant (armv6-m..armv8.1-m.main), arm-a-r, riscv, avr, or m68k",
},
base_address: {
description: "32-bit load base address for file offset 0",
},
vector_table_offset: {
description:
"Byte offset of the vector table (4-byte aligned for 32-bit profiles, 2-byte aligned for avr)",
},
avr_slot_bytes: {
description:
"Explicit AVR vector slot width in bytes (2 or 4) when observed bytes do not disambiguate stride",
},
max_entries: { description: "Maximum vector or trap slots to decode" },
svd_xml: {
description: "Optional CMSIS-SVD XML text for external IRQ names",
},
max_svd_xml_nodes: {
description: "Maximum XML nodes admitted when parsing svd_xml",
},
max_svd_expanded_chars: {
description:
"Maximum cumulative CMSIS-SVD interrupt metadata characters",
},
max_file_bytes: { description: "Maximum input file size in bytes" },
},
},
deliverWithService(
async () =>
(
await import("../composition/binaryDiagnostics/firmwareVectorTable.js")
).createFirmwareVectorTableService(),
"rea-firmware-vector-table",
),
);
registerContractCommand(
cli,
logger,
contract("inspect_firmware_mmio_synthesis"),
{
description:
"Disassemble RISC-V, MIPS32, PowerPC, or ARM64 split-immediate MMIO peripheral accesses without executing code",
...singleCallerPath,
evidenceDelivery: true,
fields: {
path: { description: "Local bare-metal firmware binary or flash dump" },
architecture: {
description:
"Instruction set: riscv32, riscv64, mips32le, mips32be, ppc32be, or arm64",
},
base_address: {
description: "Hex load base address for file offset 0",
},
scan_offset: {
description: "Instruction-aligned byte offset where scanning begins",
},
max_scan_bytes: {
description: "Maximum instruction stream bytes to scan",
},
max_syntheses: {
description: "Maximum split-immediate syntheses to return",
},
max_window_instructions: {
description: "Forward instruction tracking window after high-half op",
},
mmio_only: {
description:
"Filter out non-MMIO RAM/Flash syntheses unless matched by svd_xml",
},
svd_xml: {
description:
"Optional CMSIS-SVD XML text for peripheral and register names",
},
max_svd_xml_nodes: {
description: "Maximum XML nodes admitted when parsing svd_xml",
},
max_svd_expanded_chars: {
description:
"Maximum cumulative CMSIS-SVD peripheral/register characters",
},
max_representation_bytes: {
description:
"Maximum cumulative report representation bytes before serialization",
},
max_file_bytes: { description: "Maximum input file size in bytes" },
},
},
deliverWithService(
async () =>
(
await import("../composition/binaryDiagnostics/firmwareMmioSynthesis.js")
).createFirmwareMmioSynthesisService(),
"rea-firmware-mmio-synthesis",
),
);
};