Files
reverse-engineering-anything/src/cli/options.ts
T
morluto 4eafd9dee5 refactor(cli): project core native commands with open_binary target options (#10736)
* refactor(cli): project core native commands with open_binary target options

A session target's opening fields may now be caller paths, admitted
resolved and passed on as the caller spelled them, and a union of text
forms such as the provider selector renders as one argv token.

nativeTarget declares a native executable opened with open_binary's
format, architecture, entry point and provider fields, plus the snapshot
where a command loads one. runDirectOnTarget runs an operation on that
target through runDirectAnalysis, with Evidence delivery when declared.

Eleven core native commands are now derived from their contracts. Their
inputs are admitted by the service's contract parse, which replaces the
CLI's copies of the byte-pattern and data-type selector checks.
inspect-native-dispatch-metadata now exposes the contract's Objective-C
class import address fields.

* fix(cli): read core native contracts from their contract groups so startup stays lazy

* refactor(cli): project procedure-references and inspect-native-api with named selector options (#10738)

* refactor(cli): project procedure-references and inspect-native-api with named selector options

A contract projection may let the caller give a positional selector with
a named option instead, for values that begin with a dash. The positional
becomes optional; equal values agree (native addresses by identity), and
different values, or neither for a required field, are refused before the
target is opened. selectCliAnalysisSelector owns that rule and returns a
Result; resolveCliAnalysisSelector remains for the hand-written core
binary commands.

procedure-references and inspect-native-api are now derived from their
contracts on the native session target, which completes the core native
family.

* fix(cli): refuse empty named and positional selectors before opening the target

* refactor(cli): project inspect, xrefs, trace, function and instructions from their contracts (#10747)

The five core binary commands are derived from their contracts on the
native session target with the snapshot option, using named selector
options for the procedure, address and query.

A selector projection may require a selector the contract lets the MCP
caller omit: xrefs' address defaults to Hopper's cursor, which a one-shot
CLI command does not have. A selector names one object, so neither
spelling may be empty, as before, even where the contract's text admits
it.

open_binary's pairing rules now refuse an unpaired --target-format,
--architecture or --entry-point for inspect before the target is opened,
naming the CLI key.

* fix(cli): read core binary contracts from their contract groups so startup stays lazy
2026-11-15 21:32:33 +08:00

276 lines
9.1 KiB
TypeScript

import { z } from "incur";
import { localPathStringSchema } from "../domain/localPath.js";
import {
executableFormatHintSchema,
type ExecutableFormatHint,
} from "../domain/dosCom.js";
import type { BinaryArchitecture } from "../domain/binaryTargetTypes.js";
import {
binaryArchitectureSchema,
rawBinaryEntryPointSchema,
} from "../domain/rawBinary.js";
import { analysisProviderSelectorSchema } from "../domain/providerSelection.js";
import type { AnalysisProviderSelector } from "../domain/providerSelection.js";
import type { Logger } from "pino";
import { OPEN_BINARY_TOOL_CONTRACT } from "../contracts/sessionToolContracts.js";
import type { CliSessionTarget } from "./contractCliDescription.js";
/** Decimal integer argv text. Leading zeros stay decimal; `0x` and exponent spellings do not. */
const DECIMAL_INTEGER_TOKEN = /^[0-9]+$/u;
type DecimalWrapper =
| { readonly kind: "default"; readonly value: number | null }
| { readonly kind: "prefault"; readonly value: number | null }
| {
readonly kind: "optional" | "exactOptional" | "nullable" | "readonly";
};
const decimalToken = (domain: z.ZodNumber) =>
z
.string()
.regex(DECIMAL_INTEGER_TOKEN, "Expected a decimal integer")
.pipe(z.coerce.number<string>())
.pipe(domain);
const unwrapSchema = (field: { unwrap: () => unknown }): z.ZodType =>
field.unwrap() as z.ZodType;
/**
* Incur advertises Zod's output view. Publish the input view so an argv token
* grammar that transforms text survives `--schema` and other SDK conversions.
*/
export const publishArgvInput = <Field extends z.ZodType>(
field: Field,
): Field => {
const { $schema: _dialect, ...inputSchema } = z.toJSONSchema(field, {
io: "input",
});
return field.meta(inputSchema);
};
const numericStack = (
field: z.ZodType,
):
| {
readonly core: z.ZodNumber;
readonly wrappers: readonly DecimalWrapper[];
readonly description: string | undefined;
}
| undefined => {
const wrappers: DecimalWrapper[] = [];
let description: string | undefined;
let current = field;
for (;;) {
if (description === undefined && current.description !== undefined)
description = current.description;
if (current instanceof z.ZodDefault) {
wrappers.push({
kind: "default",
value: current.parse(undefined) as number | null,
});
current = unwrapSchema(current);
continue;
}
if (current instanceof z.ZodPrefault) {
wrappers.push({
kind: "prefault",
value: current.parse(undefined) as number | null,
});
current = unwrapSchema(current);
continue;
}
if (current instanceof z.ZodOptional) {
wrappers.push({ kind: "optional" });
current = unwrapSchema(current);
continue;
}
if (current instanceof z.ZodExactOptional) {
wrappers.push({ kind: "exactOptional" });
current = unwrapSchema(current);
continue;
}
if (current instanceof z.ZodNullable) {
wrappers.push({ kind: "nullable" });
current = unwrapSchema(current);
continue;
}
if (current instanceof z.ZodReadonly) {
wrappers.push({ kind: "readonly" });
current = unwrapSchema(current);
continue;
}
break;
}
return current instanceof z.ZodNumber
? { core: current, wrappers, description }
: undefined;
};
const applyDecimalWrappers = (
field: z.ZodType,
wrappers: readonly DecimalWrapper[],
): z.ZodType => {
let admitted = field;
for (const wrapper of wrappers.toReversed()) {
if (wrapper.kind === "nullable") admitted = admitted.nullable();
else if (wrapper.kind === "optional") admitted = admitted.optional();
else if (wrapper.kind === "exactOptional")
admitted = admitted.exactOptional();
else if (wrapper.kind === "readonly") admitted = admitted.readonly();
else if (wrapper.kind === "prefault")
admitted = admitted.prefault(wrapper.value as never);
else if (wrapper.kind === "default")
admitted = admitted.default(wrapper.value as never);
}
return admitted;
};
/**
* Parse a decimal token, then let the domain field own bounds, defaults,
* nullability and help. JSON numbers remain valid for schema consumers.
*/
export const cliDecimalField = <Field extends z.ZodType>(
field: Field,
): z.ZodType<z.output<Field>> => {
const numeric = numericStack(field);
if (numeric === undefined)
throw new Error(
`cliDecimalField expected a numeric domain field, received ${field.constructor.name}`,
);
const admitted = applyDecimalWrappers(
z.union([numeric.core, decimalToken(numeric.core)]),
numeric.wrappers,
);
const described =
numeric.description === undefined
? admitted
: admitted.describe(numeric.description);
return publishArgvInput(described) as z.ZodType<z.output<Field>>;
};
/** Adapt each numeric property of a shared shape; other properties stay unchanged. */
export const cliDecimalShape = <Shape extends Record<string, z.ZodType>>(
shape: Shape,
): Shape =>
Object.fromEntries(
Object.entries(shape).map(([key, field]) => [
key,
numericStack(field) === undefined ? field : cliDecimalField(field),
]),
) as Shape;
/** Help of the flags that bind a native target interpretation. */
const NATIVE_OPEN_HELP = {
format:
"Explicit interpretation: dos-com or raw-binary (headerless), or gamecube-dol (GameCube/Wii DOL, never auto-detected); omission preserves header-based detection",
architecture:
"Caller-supplied CPU family; required with --target-format raw-binary, must be omitted with gamecube-dol",
entryPoint:
"Caller-supplied load and entry address (0xhex); required with --target-format raw-binary, optional with gamecube-dol (must equal the DOL header entry)",
provider:
"Bind deep analysis to a provider ID or use deterministic auto selection",
snapshot: "Load and update a local analysis snapshot",
} as const;
export const providerSelectionOption = analysisProviderSelectorSchema
.optional()
.describe(NATIVE_OPEN_HELP.provider);
/** Optional path to the local analysis snapshot loaded or updated by a command. */
export const snapshotSelectionOption = localPathStringSchema
.optional()
.describe(NATIVE_OPEN_HELP.snapshot);
/**
* Explicit interpretation for headerless native executable formats. Flash
* dumps take their offsets on the artifact commands instead.
*/
const formatSelectionOption = executableFormatHintSchema
.exclude(["esp-flash-image"])
.optional()
.describe(NATIVE_OPEN_HELP.format);
export const architectureSelectionOption = binaryArchitectureSchema
.optional()
.describe(NATIVE_OPEN_HELP.architecture);
export const entryPointSelectionOption = rawBinaryEntryPointSchema
.optional()
.describe(NATIVE_OPEN_HELP.entryPoint);
/** Shared CLI flags that bind a native target interpretation. */
export const nativeOpenOptionFields = {
"target-format": formatSelectionOption,
architecture: architectureSelectionOption,
"entry-point": entryPointSelectionOption,
provider: providerSelectionOption,
};
/**
* A native executable opened as an MCP client opens it, with `open_binary`'s
* format, architecture, entry point and provider fields. An operation that
* loads and updates an analysis snapshot also takes `snapshot_path`, with
* `snapshot` as its help when it differs from the shared one.
*/
export const nativeTarget = (
description: string,
snapshot?: true | string,
): CliSessionTarget => ({
description,
open: {
contract: OPEN_BINARY_TOOL_CONTRACT,
fields: {
...(snapshot === undefined
? {}
: {
snapshot_path: {
name: "snapshot",
callerPath: true,
description:
snapshot === true ? NATIVE_OPEN_HELP.snapshot : snapshot,
},
}),
format: {
name: "target-format",
values: ["dos-com", "raw-binary", "gamecube-dol"],
description: NATIVE_OPEN_HELP.format,
},
architecture: { description: NATIVE_OPEN_HELP.architecture },
entry_point: {
name: "entry-point",
description: NATIVE_OPEN_HELP.entryPoint,
},
provider_id: { name: "provider", description: NATIVE_OPEN_HELP.provider },
},
},
});
/** Native CLI flags consumed when opening a target for one-shot analysis. */
export interface NativeOpenCliFlags {
readonly snapshot?: string | undefined;
readonly provider?: AnalysisProviderSelector | undefined;
readonly "target-format"?: ExecutableFormatHint | undefined;
readonly architecture?: BinaryArchitecture | undefined;
readonly "entry-point"?: string | undefined;
}
/** Map native CLI flags onto the shared one-shot analysis options. */
export const directAnalysisOptionsFromCli = (
logger: Logger,
options: NativeOpenCliFlags,
) => ({
logger,
snapshotPath: options.snapshot,
...(options["target-format"] === undefined
? {}
: { formatHint: options["target-format"] }),
...(options.architecture === undefined
? {}
: { architecture: options.architecture }),
...(options["entry-point"] === undefined
? {}
: { entryPoint: options["entry-point"] }),
...(options.provider === undefined ? {} : { providerId: options.provider }),
});