Files
reverse-engineering-anything/src/cli/binaryDiagnosticsCommands.ts
T
gensokyo-dev 766c45de1d feat(firmware)!: replace the literal-pool and split-immediate MMIO tools with inspect_firmware_mmio
inspect_firmware_literal_pools and inspect_firmware_mmio_synthesis answered
the same question and differed only in the instruction idiom they decode.
One tool, inspect_firmware_mmio, now takes a single architecture vocabulary
across all nine ISAs and dispatches to the literal-pool or split-immediate
decoder.

Both decoders write the same report:
- accesses rows: instruction, address register, access kind and width,
  address and MIPS physical address, region kind, architectural block, and
  CMSIS-SVD peripheral and register facts;
- a source object with the decoder's own facts: pool slot and disassembly,
  or pattern and high instruction;
- decoder facts on the report.

firmwareMmioGroups.ts owns grouping MMIO accesses by SVD peripheral,
architectural block or 4 KiB page. mmioAttributionBasis owns the group
basis. The retained view kind is firmware-mmio, with collections accesses,
peripheral_groups and anomalies, and its summary lists the top 16 groups as
compact rows.

max_references and max_syntheses are removed, since max_representation_bytes
already bounds the rows they counted. The literal-pool pre-allocation
measurement now includes an upper bound for each group, so its refusal
reports the exact required bytes. max_scan_bytes defaults to its 16 MiB
maximum, so one call covers a whole application image. mmio_only, default
true, now also drops literal-pool constants that are not MMIO;
counts.candidate_accesses still counts every decoded access.

BREAKING CHANGE: inspect_firmware_literal_pools and
inspect_firmware_mmio_synthesis (CLI inspect-firmware-literal-pools and
inspect-firmware-mmio-synthesis) and the retained view kinds
firmware-literal-pools and firmware-mmio-synthesis are replaced by
inspect_firmware_mmio (inspect-firmware-mmio) and view kind firmware-mmio.
isa becomes architecture, max_svd_nodes becomes max_svd_xml_nodes, and
max_references and max_syntheses are removed. Neither old tool has been
released.

Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
2026-12-03 21:19:29 +08:00

777 lines
24 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_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"),
{
description:
"Find MMIO peripheral addresses accessed by ARM, Xtensa, RISC-V, MIPS32, PowerPC, or ARM64 firmware without executing code",
...singleCallerPath,
evidenceDelivery: true,
fields: {
path: { description: "Local firmware binary or flash image" },
architecture: {
description:
"Instruction set: arm-thumb, arm-a32, xtensa, 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_window_instructions: {
description:
"Split-immediate tracking window after a high-immediate producer",
},
mmio_only: {
description:
"Drop RAM, flash, and unclassified addresses 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 CMSIS-SVD peripheral/register characters (split-immediate)",
},
max_representation_bytes: {
description:
"Maximum cumulative report representation bytes before Evidence",
},
max_file_bytes: { description: "Maximum input file size in bytes" },
},
},
deliverWithService(
async () =>
(
await import("../composition/binaryDiagnostics/firmwareMmio.js")
).createFirmwareMmioService(),
"rea-firmware-mmio",
),
);
};