fix(ghidra): point to the LC_MAIN entry when a stripped Mach-O has no main symbol (#12966)

* fix(ghidra): derive the LC_MAIN entry address from bounded snapshot reads

* fix(ghidra): point to the LC_MAIN entry when a stripped Mach-O has no main symbol

* fix(ghidra): keep snapshot cleanup failures from the LC_MAIN hint read

* fix(ghidra): admit the LC_MAIN segment's file range before hinting

* fix(ghidra): give no LC_MAIN hint for an entry in a file-only segment

admitMachoSegmentCommand admits a segment with no VM size and no protection but marks it unmapped; it owns no analysis address, so the hint must not name one.

* fix(ghidra): confirm Mach-O entry retries against the function inventory

* fix(hopper): offer inventory recovery for unresolved selectors

* fix(ida): offer inventory recovery for missing procedures

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
ashritandmorluto authored and GitHub committed 2026-11-22 14:14:21 +00:00
1 parent ec29a6deae
commit 3db9120c5e
15 files changed
+905 -69

No files matched your search

+9 -3
View File
@@ -219,6 +219,10 @@ class InvalidRequestError(Exception):
"""Caller input failed bridge request or operation validation."""
class SelectorNotFoundError(InvalidRequestError):
"""A valid selector did not resolve in the current Hopper document."""
EXHAUSTIVE_ANALYSIS_METHODS = frozenset(
(
"analyze_function",
@@ -457,7 +461,7 @@ def _address_selection(document, value=None):
try:
address = int(value, 16)
except ValueError as error:
raise InvalidRequestError("Unknown Hopper address or name: %s" % value) from error
raise SelectorNotFoundError("Unknown Hopper address or name: %s" % value) from error
if not 0 <= address < 0xFFFFFFFFFFFFFFFF:
raise InvalidRequestError("Address is outside Hopper's usable unsigned 64-bit range: %s" % value)
return address, source
@@ -478,7 +482,7 @@ def _procedure(document, value=None):
address, source = _address_selection(document, value)
result = _segment(document, address).getProcedureAtAddress(address)
if result is None:
raise InvalidRequestError("No procedure exists at the requested address")
raise SelectorNotFoundError("No procedure exists at the requested address")
if source == "symbol" and address != result.getEntryPoint():
raise InvalidRequestError(
"Symbol %s at %s is inside procedure %s at %s; select its entry name/address or use resolve_containing_procedure for explicit containment"
@@ -1586,6 +1590,8 @@ def _diagnostic_type(error):
return "capability_unavailable"
if isinstance(error, PermissionError):
return "authorization"
if isinstance(error, SelectorNotFoundError):
return "selector_not_found"
if isinstance(error, InvalidRequestError):
return "invalid_request"
return "bridge_exception"
@@ -1598,7 +1604,7 @@ def _safe_diagnostic(error):
message = str(error)
elif diagnostic_type == "authorization":
message = "Invalid bridge capability"
elif diagnostic_type == "invalid_request":
elif diagnostic_type in ("invalid_request", "selector_not_found"):
message = str(error)
else:
message = "%s: Hopper bridge operation failed" % type(error).__name__
+1
View File
@@ -97,6 +97,7 @@ HopperProtocolError,,unreadable_output,execution_failure,false
HopperRemoteError,diagnostic_type=remote,execution_failure,execution_failure,false
HopperRemoteError,diagnostic_type=authorization,execution_failure,unavailable,false
HopperRemoteError,diagnostic_type=invalid_request,invalid_request,invalid_input,false
HopperRemoteError,diagnostic_type=selector_not_found,invalid_request,invalid_input,false
HopperRemoteError,diagnostic_type=capability_unavailable,execution_failure,execution_failure,false
HopperRemoteError,diagnostic_type=bridge_exception,execution_failure,execution_failure,false
HopperProcessError,,provider_unavailable,unavailable,true
1 tag discriminant code category retryable_by_default
97 HopperRemoteError diagnostic_type=remote execution_failure execution_failure false
98 HopperRemoteError diagnostic_type=authorization execution_failure unavailable false
99 HopperRemoteError diagnostic_type=invalid_request invalid_request invalid_input false
100 HopperRemoteError diagnostic_type=selector_not_found invalid_request invalid_input false
101 HopperRemoteError diagnostic_type=capability_unavailable execution_failure execution_failure false
102 HopperRemoteError diagnostic_type=bridge_exception execution_failure execution_failure false
103 HopperProcessError provider_unavailable unavailable true
+2 -2
View File
@@ -60,7 +60,7 @@ export function requireBridgeProgress(updates) {
);
}
/** Require one sanitized invalid-request diagnostic from the real bridge. */
/** Require one sanitized selector-miss diagnostic from the real bridge. */
export function requireBridgeDiagnostic(chunks) {
const diagnostics = chunks
.join("")
@@ -71,7 +71,7 @@ export function requireBridgeDiagnostic(chunks) {
!diagnostics.some(
(diagnostic) =>
diagnostic.type === "bridge-diagnostic" &&
diagnostic.category === "invalid_request" &&
diagnostic.category === "selector_not_found" &&
diagnostic.message.includes(
"Unknown Hopper address or name: __rea_missing_procedure__",
),
+34 -5
View File
@@ -103,6 +103,7 @@ import {
readArtifactFileChunks,
} from "../resources/index.js";
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
import { readFileHandleRange } from "../filesystem/readFileHandleRange.js";
import {
assertRegularFileActive,
RegularFileChangedError,
@@ -727,12 +728,40 @@ export class GhidraClient {
);
}
/**
* Read caller-chosen positional ranges of the private immutable source. A
* range past the end returns the bytes that exist. Nothing is retained as a
* partial observation, so callers use this only for advisory reads.
*/
readTargetSnapshotRanges<T>(
read: (
range: (position: number, length: number) => Promise<Uint8Array>,
size: number,
) => Promise<T>,
signal?: AbortSignal,
): Promise<Result<T, GhidraSessionError>> {
return this.#withTargetSnapshot(
(handle, initial) =>
read(
(position, length) =>
readFileHandleRange(handle, position, length, () =>
assertRegularFileActive(signal),
),
initial.size,
),
undefined,
signal,
);
}
async #withTargetSnapshot<T>(
read: (handle: FileHandle, initial: Stats, path: string) => Promise<T>,
observe: (
value: T,
path: string,
) => FileSnapshotPartialObservation | NativeLoadImagePartialObservation,
observe:
| ((
value: T,
path: string,
) => FileSnapshotPartialObservation | NativeLoadImagePartialObservation)
| undefined,
signal?: AbortSignal,
): Promise<Result<T, GhidraSessionError>> {
let completedObservation:
@@ -768,7 +797,7 @@ export class GhidraClient {
assertRegularFileActive(signal);
if (!sameRegularFileState(initial, after))
throw new RegularFileChangedError(path);
completedObservation = observe(value, path);
completedObservation = observe?.(value, path);
return value;
},
),
@@ -0,0 +1,68 @@
import {
LC,
machoImage,
segmentCommand,
} from "../artifacts/apple/MachoImage.fixture.js";
/** `LC_SEGMENT_64` with a VM range backed by the given file range. */
export const mappedSegment = (options: {
readonly name: string;
readonly vmaddr: bigint;
readonly fileoff: bigint;
readonly filesize: bigint;
readonly vmsize?: bigint;
}): Uint8Array => {
const bytes = segmentCommand({
name: options.name,
vmaddr: options.vmaddr,
vmsize: options.vmsize ?? options.filesize,
});
const view = new DataView(bytes.buffer);
view.setBigUint64(40, options.fileoff, true);
view.setBigUint64(48, options.filesize, true);
return bytes;
};
/** `LC_MAIN` with the given entry offset and no stack size. */
export const mainCommand = (entryoff: bigint): Uint8Array => {
const bytes = new Uint8Array(24);
const view = new DataView(bytes.buffer);
view.setUint32(0, LC.MAIN, true);
view.setUint32(4, bytes.length, true);
view.setBigUint64(8, entryoff, true);
return bytes;
};
export const TEXT_SEGMENT = mappedSegment({
name: "__TEXT",
vmaddr: 0x100000000n,
fileoff: 0n,
filesize: 0x4000n,
});
/** Zero-pad an image so its file holds every byte its segments declare. */
export const paddedTo = (image: Uint8Array, size: number): Uint8Array => {
const bytes = new Uint8Array(size);
bytes.set(image);
return bytes;
};
/**
* A stripped arm64 executable shape: __PAGEZERO, __TEXT, LC_MAIN at 0x460,
* in a file as long as its __TEXT file range.
*/
export const strippedMachoWithMain = (): Uint8Array =>
paddedTo(
machoImage({
commands: [
segmentCommand({
name: "__PAGEZERO",
vmaddr: 0n,
vmsize: 0x100000000n,
}),
TEXT_SEGMENT,
mainCommand(0x460n),
],
}),
0x4000,
);
+241
View File
@@ -0,0 +1,241 @@
import { open, truncate, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it, onTestFinished } from "vitest";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
import {
CPU,
FILE_TYPE,
fatImage,
machoImage,
} from "../artifacts/apple/MachoImage.fixture.js";
import { elf } from "../domain/binaryTarget.fixture.js";
import { readFileHandleRange } from "../filesystem/readFileHandleRange.js";
import {
mainCommand,
mappedSegment,
paddedTo,
strippedMachoWithMain,
TEXT_SEGMENT,
} from "./GhidraMachoEntryHint.fixture.js";
import {
ghidraMachoMainEntryCandidate,
isGhidraMainSelector,
type GhidraSnapshotRangeReader,
} from "./GhidraMachoEntryHint.js";
const CANDIDATE = { fileOffset: "0x460", address: "0x100000460" };
/** In-memory reader that records each requested range. */
const recordingReader = (bytes: Uint8Array) => {
const reads: { readonly position: number; readonly length: number }[] = [];
const read: GhidraSnapshotRangeReader = (position, length) => {
reads.push({ position, length });
return Promise.resolve(bytes.subarray(position, position + length));
};
return { read, reads };
};
const hintFor = (bytes: Uint8Array) =>
ghidraMachoMainEntryCandidate(recordingReader(bytes).read, bytes.byteLength);
const NO_HINT_IMAGES: readonly {
readonly name: string;
readonly image: Uint8Array;
}[] = [
{
name: "a dylib without LC_MAIN",
image: machoImage({
fileType: FILE_TYPE.dylib,
commands: [TEXT_SEGMENT],
}),
},
{
name: "an executable without LC_MAIN",
image: machoImage({ commands: [TEXT_SEGMENT] }),
},
{
name: "a non-executable that declares LC_MAIN",
image: machoImage({
fileType: FILE_TYPE.bundle,
commands: [TEXT_SEGMENT, mainCommand(0x460n)],
}),
},
{
name: "an entry outside every mapped file range",
image: paddedTo(
machoImage({ commands: [TEXT_SEGMENT, mainCommand(0x8000n)] }),
0x9000,
),
},
{
name: "an entry past the end of the file inside a declared segment",
image: machoImage({ commands: [TEXT_SEGMENT, mainCommand(0x460n)] }),
},
{
name: "an entry offset of zero, which Ghidra ignores",
image: paddedTo(
machoImage({ commands: [TEXT_SEGMENT, mainCommand(0n)] }),
0x4000,
),
},
{
name: "a containing segment whose file range exceeds the file",
image: paddedTo(
machoImage({ commands: [TEXT_SEGMENT, mainCommand(0x460n)] }),
0x1000,
),
},
{
name: "a containing segment whose file range overflows",
image: paddedTo(
machoImage({
commands: [
mappedSegment({
name: "__TEXT",
vmaddr: 0x100000000n,
fileoff: 0x400n,
filesize: 0xffff_ffff_ffff_fc00n,
vmsize: 0xffff_ffff_ffff_fc00n,
}),
mainCommand(0x460n),
],
}),
0x1000,
),
},
{
name: "a containing segment with more file bytes than memory",
image: paddedTo(
machoImage({
commands: [
mappedSegment({
name: "__TEXT",
vmaddr: 0x100000000n,
fileoff: 0n,
filesize: 0x1000n,
vmsize: 0x800n,
}),
mainCommand(0x460n),
],
}),
0x1000,
),
},
{
name: "a containing file-only segment with no VM range",
image: paddedTo(
machoImage({
commands: [
mappedSegment({
name: "__TEXT",
vmaddr: 0x100000000n,
fileoff: 0n,
filesize: 0x1000n,
vmsize: 0n,
}),
mainCommand(0x460n),
],
}),
0x1000,
),
},
{
name: "two LC_MAIN commands",
image: machoImage({
commands: [TEXT_SEGMENT, mainCommand(0x460n), mainCommand(0x480n)],
}),
},
{ name: "an ELF image", image: elf(2, 1, 0xb7) },
{ name: "an empty file", image: new Uint8Array(0) },
{
name: "a file shorter than a Mach-O header",
image: strippedMachoWithMain().subarray(0, 20),
},
{
name: "load commands cut short by the end of the file",
image: strippedMachoWithMain().subarray(0, 64),
},
];
describe("isGhidraMainSelector", () => {
it.each(["main", "_main", "MAIN", "_Main", " main\t"])(
"accepts %j",
(selector) => {
expect(isGhidraMainSelector(selector)).toBe(true);
},
);
it.each(["foo", "mainly", "__main", "main_", "0x100000460", "", 1, null])(
"rejects %j",
(selector) => {
expect(isGhidraMainSelector(selector)).toBe(false);
},
);
});
describe("ghidraMachoMainEntryCandidate", () => {
it("names the LC_MAIN entry after reading only the header and load commands", async () => {
const image = strippedMachoWithMain();
const commandsEnd = 32 + new DataView(image.buffer).getUint32(20, true);
const { read, reads } = recordingReader(image);
await expect(
ghidraMachoMainEntryCandidate(read, image.byteLength),
).resolves.toEqual(CANDIDATE);
expect(reads).toEqual([
{ position: 0, length: 32 },
{ position: 0, length: commandsEnd },
]);
});
it("rejects a file mapping outside the __TEXT entry range used by Ghidra", async () => {
const image = paddedTo(
machoImage({
commands: [
TEXT_SEGMENT,
mappedSegment({
name: "__CODE",
vmaddr: 0x200000000n,
fileoff: 0x4000n,
filesize: 0x1000n,
}),
mainCommand(0x4010n),
],
}),
0x5000,
);
await expect(hintFor(image)).resolves.toBeUndefined();
});
it("gives no hint for a FAT container", async () => {
const fat = fatImage([{ cpu: CPU.arm64, bytes: strippedMachoWithMain() }]);
const { read, reads } = recordingReader(fat);
await expect(
ghidraMachoMainEntryCandidate(read, fat.byteLength),
).resolves.toBeUndefined();
expect(reads).toEqual([{ position: 0, length: 32 }]);
});
it("still names the entry of a target larger than 128 MiB", async () => {
const root = await createTestTempDirectory("rea-macho-entry-hint-");
const path = join(root, "large-stripped");
await writeFile(path, strippedMachoWithMain());
const size = 160 * 1024 * 1024;
await truncate(path, size);
const handle = await open(path, "r");
onTestFinished(() => handle.close());
let bytesRead = 0;
const read: GhidraSnapshotRangeReader = async (position, length) => {
const bytes = await readFileHandleRange(handle, position, length);
bytesRead += bytes.byteLength;
return bytes;
};
expect((await handle.stat()).size).toBe(size);
await expect(ghidraMachoMainEntryCandidate(read, size)).resolves.toEqual(
CANDIDATE,
);
expect(bytesRead).toBeLessThan(1024);
});
it.each(NO_HINT_IMAGES)("returns no hint for $name", async ({ image }) => {
await expect(hintFor(image)).resolves.toBeUndefined();
});
});
+131
View File
@@ -0,0 +1,131 @@
import { decodeMachoFixedName } from "../domain/apple/appleMachoNames.js";
import { readMachoCommandNames } from "../domain/apple/machoCommandNames.js";
import { MAX_LOAD_COMMAND_BYTES } from "../domain/apple/machoLoadCommandReader.js";
import { readMachoLoadCommandTableHeader } from "../domain/apple/machoLoadCommands.js";
import {
admitMachoSegmentCommand,
machoSegmentHeaderSize,
} from "../domain/apple/machoSegmentHeader.js";
import { parseFailureFromCause } from "../domain/parseFailure.js";
const MH_EXECUTE = 2;
const MACHO_HEADER_BYTES = 32;
const MAX_HINT_RECORDS = 65_536;
/** Positional read that may return fewer bytes at the end of the file. */
export type GhidraSnapshotRangeReader = (
position: number,
length: number,
) => Promise<Uint8Array>;
/** Whether a procedure selector asks for the C `main` symbol. */
export const isGhidraMainSelector = (procedure: unknown): boolean => {
if (typeof procedure !== "string") return false;
const name = procedure.trim().toLowerCase();
return name === "main" || name === "_main";
};
const hex = (value: bigint): string => `0x${value.toString(16)}`;
const readExactly = async (
read: GhidraSnapshotRangeReader,
position: number,
length: number,
): Promise<Uint8Array | undefined> => {
const bytes = await read(position, length);
return bytes.byteLength === length ? bytes : undefined;
};
/**
* Artifact-derived candidate for Ghidra's LC_MAIN lookup. The caller must
* confirm the exact procedure in the loaded program before advising a retry.
*/
export const ghidraMachoMainEntryCandidate = async (
read: GhidraSnapshotRangeReader,
fileSize: number,
): Promise<
{ readonly fileOffset: string; readonly address: string } | undefined
> => {
const header = await readExactly(
read,
0,
Math.min(MACHO_HEADER_BYTES, fileSize),
);
if (header === undefined) return undefined;
const table = readMachoLoadCommandTableHeader(header, fileSize);
if (
!table.ok ||
table.value === null ||
table.value.commandBytes > MAX_LOAD_COMMAND_BYTES
)
return undefined;
const commands = await readExactly(
read,
0,
table.value.headerSize + table.value.commandBytes,
);
if (commands === undefined) return undefined;
let parsed: Awaited<ReturnType<typeof readMachoCommandNames>>;
try {
parsed = await readMachoCommandNames(
(offset, size) =>
Promise.resolve(commands.subarray(offset, offset + size)),
fileSize,
MAX_LOAD_COMMAND_BYTES,
MAX_HINT_RECORDS,
);
} catch (cause: unknown) {
if (parseFailureFromCause(cause) !== undefined) return undefined;
throw cause;
}
if (parsed.header.fileType !== MH_EXECUTE) return undefined;
const entrypoints = parsed.commands.flatMap(({ entrypoint }) =>
entrypoint === undefined ? [] : [entrypoint.offset],
);
const [entryOffset] = entrypoints;
if (
entrypoints.length !== 1 ||
entryOffset === undefined ||
entryOffset === 0n ||
entryOffset >= BigInt(fileSize)
)
return undefined;
const containing = parsed.commands.filter(
({ segment }) =>
segment !== undefined &&
segment.fileSize > 0n &&
segment.fileOffset <= entryOffset &&
entryOffset - segment.fileOffset < segment.fileSize,
);
const [command] = containing;
if (
containing.length !== 1 ||
command?.segmentName === undefined ||
decodeMachoFixedName(Buffer.from(command.segmentName)) !== "__TEXT" ||
command.segment === undefined ||
command.segment.fileOffset !== 0n ||
command.sections === undefined
)
return undefined;
const admitted = admitMachoSegmentCommand(
{
...command.segment,
headerSize: machoSegmentHeaderSize(parsed.header.wide),
sectionCount: command.sections.length,
},
command.size,
parsed.header.wide ? 64 : 32,
fileSize,
);
// Ghidra uses __TEXT.vmaddr + entryoff. Require the file mapping to agree.
if (
!admitted.ok ||
admitted.value.unmapped ||
admitted.value.fileAddress !== command.segment.address
)
return undefined;
return {
fileOffset: hex(entryOffset),
address: hex(command.segment.address + entryOffset),
};
};
+254 -12
View File
@@ -21,7 +21,6 @@ import {
ghidraEmptyInstructionOutgoingLimitation,
ghidraEmptyOutgoingReferencesLimitation,
ghidraEmptyXrefsLimitation,
ghidraFunctionSeedRecovery,
ghidraNotInListingLimitation,
ghidraNotInProcedureLimitation,
limitationsFor,
@@ -106,6 +105,7 @@ import {
type GhidraProviderClientFactory,
} from "./GhidraProviderClient.js";
import { GhidraLaunchError, GhidraHeadlessLauncher } from "./GhidraLauncher.js";
import { strippedMachoWithMain } from "./GhidraMachoEntryHint.fixture.js";
import {
AnalysisArtifactChangedError,
AnalysisCancelledError,
@@ -1726,14 +1726,14 @@ describe("Ghidra procedure lookup projection", () => {
message:
"Unknown Ghidra procedure name or address: Unresolved_Selected_Name",
remedy: "list_procedures",
qualification: "does not prove",
qualification: "presence in the artifact unknown",
},
{
code: "procedure_not_found",
selector: "0x14b0c",
message: "No procedure exists at the requested address: 0x14b0c",
remedy: "list_procedures",
qualification: "does not prove",
qualification: "presence in the artifact unknown",
},
{
code: "file_offset_unmapped",
@@ -1791,10 +1791,9 @@ describe("Ghidra procedure lookup projection", () => {
expect(projected.remediation.action).not.toContain(
"REA_GHIDRA_PROJECT_PATH",
);
// Code that auto-analysis never reached has a declared-entry recovery.
expect(
projected.remediation.action.includes("REA_GHIDRA_SEED_FILE"),
).toBe(code === "procedure_not_found");
expect(projected.remediation.action).not.toContain(
"REA_GHIDRA_SEED_FILE",
);
} finally {
await client.close();
}
@@ -1850,11 +1849,7 @@ describe("Ghidra procedure lookup projection", () => {
"completeness is unknown",
);
expect(projected.remediation.action).toContain(
"will not include the selected project's annotations or other edits",
);
// Seeds apply only to that fresh import, never to the selected project.
expect(projected.remediation.action).toContain(
ghidraFunctionSeedRecovery("existing-project"),
"excludes the selected project's annotations and other edits",
);
} finally {
await client.close();
@@ -1865,6 +1860,253 @@ describe("Ghidra procedure lookup projection", () => {
});
});
const MACHO_MAIN_RETRY =
"Retry the same operation at Ghidra procedure address 0x100000460";
const universalArm64Target: BinaryTarget = {
path: "/tmp/fixture",
sha256: "a".repeat(64),
kind: "executable",
format: "mach-o-universal",
architecture: "arm64",
availableArchitectures: ["arm64"],
universalSlice: { offset: 0, size: 32 },
};
const missingMachoMain = async (options: {
readonly target: BinaryTarget;
readonly selector: string;
readonly remoteCode?: string;
readonly observedEntry?: string | null;
readonly lookupFailure?: GhidraSessionError;
readonly snapshotFailure?: GhidraSessionError;
readonly session?: GhidraSessionInfo;
readonly environment?: Readonly<Record<string, string>>;
}) => {
const remoteCode = options.remoteCode ?? "procedure_not_found";
const message = `Unknown Ghidra procedure name or address: ${options.selector}`;
const image = strippedMachoWithMain();
const snapshot = { reads: 0 };
const ghidra = provider(
installationHost(),
() => ({
start: async () => ok(options.session ?? sessionInfo()),
callTool: async (operation) => {
if (operation === "procedure_address") {
if (options.lookupFailure !== undefined)
return err(options.lookupFailure);
if (options.observedEntry !== null)
return ok(options.observedEntry ?? "0x100000460");
}
return err(
new GhidraSessionError(
"remote",
message,
{ remote_code: remoteCode },
{ remoteCode },
),
);
},
readTargetSnapshotRanges: async <T>(
read: (
range: (position: number, length: number) => Promise<Uint8Array>,
size: number,
) => Promise<T>,
) => {
snapshot.reads += 1;
if (options.snapshotFailure !== undefined)
return err(options.snapshotFailure);
return ok(
await read(
async (position, length) =>
image.subarray(position, position + length),
image.byteLength,
),
);
},
close: async () => ok(null),
}),
options.environment,
);
onTestFinished(async () => {
await ghidra.closeOwnedResources();
});
const resolved = await ghidra.resolveAnalysisProfile(options.target);
if (!resolved.ok) throw resolved.error;
if (resolved.value.profile === null)
throw new Error("Expected a bound Ghidra profile");
const client = ghidra.createClient(options.target, resolved.value.profile);
try {
const result = await client.execute("procedure_pseudo_code", {
procedure: options.selector,
});
if (result.ok) throw new Error("Expected a missing procedure");
return {
error: result.error,
projected: projectAnalysisError(result.error),
snapshot,
};
} finally {
await client.close();
}
};
describe("Ghidra missing main on a Mach-O with LC_MAIN", () => {
it.each(["main", "_main", "MAIN", " main "])(
"names the LC_MAIN entry address for %j on a thin Mach-O",
async (selector) => {
const { projected, snapshot } = await missingMachoMain({
target: executableTarget("mach-o", "arm64"),
selector,
});
expect(projected).toMatchObject({
code: "invalid_request",
details: {
related_operations: ["list_procedures", "search_procedures"],
diagnostics: { remote_code: "procedure_not_found" },
},
});
expect(projected.remediation.action).toContain("list_procedures");
expect(projected.remediation.action.startsWith(MACHO_MAIN_RETRY)).toBe(
true,
);
expect(projected.remediation.action).toContain("--procedure 0x100000460");
expect(projected.remediation.action).not.toContain(
"REA_GHIDRA_SEED_FILE",
);
expect(snapshot.reads).toBe(1);
},
);
it.each([null, "0x100000450"])(
"keeps inventory recovery if the provider reports %s instead of the exact candidate",
async (observedEntry) => {
const { projected } = await missingMachoMain({
target: executableTarget("mach-o", "arm64"),
selector: "main",
observedEntry,
});
expect(projected.remediation.action).toContain("search_procedures");
expect(projected.remediation.action).not.toContain("LC_MAIN");
},
);
it.each([
{
name: "another procedure name",
target: executableTarget("mach-o", "arm64"),
selector: "foo",
},
{
name: "an ELF target",
target: executableTarget("elf", "x86_64"),
selector: "main",
},
{
name: "a universal Mach-O whose Ghidra slice is not committed",
target: universalArm64Target,
selector: "main",
},
{
name: "an ambiguous main",
target: executableTarget("mach-o", "arm64"),
selector: "main",
remoteCode: "procedure_ambiguous",
},
])(
"leaves the recovery unchanged for $name without reading the snapshot",
async (options) => {
const { projected, snapshot } = await missingMachoMain(options);
expect(projected.remediation.action).not.toContain("LC_MAIN");
expect(snapshot.reads).toBe(0);
},
);
it("leaves a selected project's recovery unchanged because its image base is not established", async () => {
const root = await createTestTempDirectory("rea-missing-main-project-");
await mkdir(join(root, "selected.rep"));
await writeFile(join(root, "selected.gpr"), "marker");
const { projected, snapshot } = await missingMachoMain({
target: executableTarget("mach-o", "arm64"),
selector: "main",
session: {
...sessionInfo(),
read_only: true,
existing_project: true as const,
analysis_complete: null,
capabilities: GHIDRA_SESSION_CAPABILITIES.filter(
(name) => !GHIDRA_MUTATING_OPERATIONS.has(name),
),
},
environment: { REA_GHIDRA_PROJECT_PATH: join(root, "selected.gpr") },
});
expect(projected.remediation.action).toContain("REA_GHIDRA_PROJECT_PATH");
expect(projected.remediation.action).not.toContain("LC_MAIN");
expect(snapshot.reads).toBe(0);
});
});
describe("Ghidra advisory entry observation failures", () => {
it("keeps the original failure and generic recovery when the snapshot read fails", async () => {
const { projected, snapshot } = await missingMachoMain({
target: executableTarget("mach-o", "arm64"),
selector: "main",
snapshotFailure: new GhidraSessionError(
"protocol",
"Ghidra target snapshot read or finalization did not complete",
),
});
expect(snapshot.reads).toBe(1);
expect(projected).toMatchObject({
code: "invalid_request",
details: { diagnostics: { remote_code: "procedure_not_found" } },
});
expect(projected.remediation.action).toContain("search_procedures");
expect(projected.remediation.action).not.toContain("LC_MAIN");
});
it.each(["snapshot", "lookup"] as const)(
"attaches failed %s cleanup to the original missing-procedure error",
async (stage) => {
const cleanup = new ProviderCleanupError(
"ghidra",
["controlled snapshot descriptor"],
{ reason: "controlled close failure" },
);
const lease = new AnalysisCleanupLease(async () => {}, [
"controlled snapshot descriptor",
]);
lease.bindCleanupError(cleanup);
onTestFinished(() => lease.release());
const failure = new GhidraSessionError(
"protocol",
"Ghidra entry observation finalization did not complete",
).withCleanupFailure(cleanup);
const { error, snapshot } = await missingMachoMain({
target: executableTarget("mach-o", "arm64"),
selector: "main",
...(stage === "snapshot"
? { snapshotFailure: failure }
: { lookupFailure: failure }),
});
expect(snapshot.reads).toBe(1);
expect(error.cleanupIncomplete).toBe(true);
expect(error.cleanupResources).toEqual([
"controlled snapshot descriptor",
]);
const primary = error.cleanupPrimary;
if (primary === undefined) throw new Error("Expected a cleanup primary");
const projected = projectAnalysisError(primary);
expect(projected).toMatchObject({
code: "invalid_request",
details: { diagnostics: { remote_code: "procedure_not_found" } },
});
expect(projected.remediation.action).toContain("search_procedures");
expect(projected.remediation.action).not.toContain("LC_MAIN");
await lease.release();
expect(error.cleanupIncomplete).toBe(false);
},
);
});
describe("Ghidra file-offset outcome projection", () => {
it.each([
[
+85 -14
View File
@@ -142,13 +142,16 @@ import {
ghidraEmptyExternalOutgoingLimitation,
ghidraEmptyInstructionOutgoingLimitation,
ghidraEmptyOutgoingReferencesLimitation,
ghidraFunctionSeedRecovery,
ghidraNotInListingLimitation,
ghidraNotInProcedureLimitation,
windowsP0Limitations,
limitationsFor,
} from "./GhidraProviderCapabilities.js";
import { GHIDRA_PROVIDER_IDENTITY } from "./GhidraProviderMetadata.js";
import {
ghidraMachoMainEntryCandidate,
isGhidraMainSelector,
} from "./GhidraMachoEntryHint.js";
import {
GHIDRA_STARTUP_DEADLINE_ELAPSED,
isGhidraInputFailureCode,
@@ -192,6 +195,7 @@ export type GhidraProviderClientFactory = (
| "operationHealthSnapshot"
| "runtimeLineage"
| "readTargetSnapshot"
| "readTargetSnapshotRanges"
| "hashTargetSnapshot"
| "hashTargetSnapshotRanges"
| "attestDosTargetSnapshot"
@@ -802,6 +806,56 @@ export const createGhidraProviderClient = (input: {
riscvCallingConvention !== undefined;
const lostProviderHealth = (): ProviderOperationHealth | undefined =>
providerStarted ? client.operationHealthSnapshot?.() : undefined;
// Only a thin image REA imported itself has Ghidra's import at the declared
// vmaddrs; universal slices and caller projects are not established here.
const machoMainEntryHint = async (
failure: GhidraSessionError,
request: Readonly<Record<string, JsonValue>>,
signal: AbortSignal | undefined,
): Promise<{
readonly hint?: string;
readonly cleanupFailure?: AnalysisError;
}> => {
if (
target.format !== "mach-o" ||
projection.source === "existing-project" ||
failure.kind !== "remote" ||
failure.remoteCode !== "procedure_not_found" ||
!isGhidraMainSelector(request.procedure) ||
client.readTargetSnapshotRanges === undefined
)
return {};
const read = await client.readTargetSnapshotRanges(
ghidraMachoMainEntryCandidate,
signal,
);
if (!read.ok)
return read.error.cleanupFailure === undefined
? {}
: { cleanupFailure: read.error.cleanupFailure };
if (read.value === undefined) return {};
const { address, fileOffset } = read.value;
const observed = await client.callTool(
"procedure_address",
{
procedure: address,
...(request.document === undefined
? {}
: { document: request.document }),
},
signal === undefined ? undefined : { signal },
);
if (!observed.ok)
return observed.error.cleanupFailure === undefined
? {}
: { cleanupFailure: observed.error.cleanupFailure };
// This lookup can also resolve a containing function. Only its exact
// entry can substantiate the candidate derived from LC_MAIN.
if (observed.value !== address) return {};
return {
hint: `Retry the same operation at Ghidra procedure address ${address} (Mach-O LC_MAIN file offset ${fileOffset}). For CLI decompile, use --procedure ${address}. For MCP, set procedure to "${address}".`,
};
};
let projectHistory: Evidence | undefined;
const checkSessionObservations = async (
operation: AnalysisOperation,
@@ -1133,16 +1187,30 @@ export const createGhidraProviderClient = (input: {
if (called.ok) providerStarted = true;
if (operation === "list_documents" || operation === "list_procedures")
return inventoryExecution(operation, called);
if (!called.ok)
return err(
projectSessionError(
operation,
called.error,
projection,
lostProviderHealth(),
input.value,
),
if (!called.ok) {
const entry = await machoMainEntryHint(
called.error,
input.value,
options?.signal,
);
const projected = projectSessionError(
operation,
called.error,
projection,
lostProviderHealth(),
input.value,
entry.hint,
);
return err(
entry.cleanupFailure === undefined
? projected
: analysisErrorWithCleanupDependencies(
projected,
entry.cleanupFailure,
operation,
),
);
}
if (operation === "inspect_native_load_image")
return loadImageExecution(called.value, options?.signal);
const result = isGhidraFunctionOperation(operation)
@@ -1382,6 +1450,7 @@ const projectSessionError = (
projection: GhidraProjection,
health?: ProviderOperationHealth,
request?: Readonly<Record<string, JsonValue>>,
entryHint?: string,
): AnalysisError => {
const primary = projectPrimarySessionError(
operation,
@@ -1389,6 +1458,7 @@ const projectSessionError = (
projection,
health,
request,
entryHint,
);
return failure.cleanupFailure === undefined
? primary
@@ -1405,6 +1475,7 @@ const projectPrimarySessionError = (
{ limits, programName, source }: GhidraProjection,
health?: ProviderOperationHealth,
request?: Readonly<Record<string, JsonValue>>,
entryHint?: string,
): AnalysisError => {
const context = {
cause: failure,
@@ -1559,11 +1630,11 @@ const projectPrimarySessionError = (
break;
default:
recovery =
"Use list_procedures or search_procedures to inspect the current Ghidra inventory and choose an observed name or address. An absent entry does not prove the function is absent from the artifact." +
(entryHint === undefined ? "" : `${entryHint} `) +
"Choose an observed name or address from the current Ghidra inventory. CLI: rea search <path> . --kind procedures --mode regex --provider ghidra. MCP: use search_procedures or list_procedures. An inventory miss leaves the function's presence in the artifact unknown." +
(source === "existing-project"
? " The selected project's previous analysis completeness is unknown. To explicitly request a separate fresh import, start a new REA process without REA_GHIDRA_PROJECT_PATH and REA_GHIDRA_PROGRAM_NAME; that analysis will not include the selected project's annotations or other edits."
: "") +
` ${ghidraFunctionSeedRecovery(source)}`;
? " The selected project's previous analysis completeness is unknown. To explicitly request a separate fresh import, start a new REA process without REA_GHIDRA_PROJECT_PATH and REA_GHIDRA_PROGRAM_NAME. That separate analysis excludes the selected project's annotations and other edits."
: "");
relatedOperations = ["list_procedures", "search_procedures"];
}
return new AnalysisInputError(
+1
View File
@@ -532,6 +532,7 @@ describe("Hopper error catalogue", () => {
"remote",
"authorization",
"invalid_request",
"selector_not_found",
"capability_unavailable",
"bridge_exception",
] as const
+27 -19
View File
@@ -37,7 +37,8 @@ const HOPPER_CLASSIFICATIONS = {
const hopperRemoteClassification = (
diagnosticType: HopperDiagnosticType,
): AnalysisErrorClassification =>
diagnosticType === "invalid_request"
diagnosticType === "invalid_request" ||
diagnosticType === "selector_not_found"
? { code: "invalid_request", category: "invalid_input" }
: {
code: "execution_failure",
@@ -239,12 +240,16 @@ export class HopperProtocolError extends HopperError {
}
}
export type HopperDiagnosticType =
| "remote"
| "authorization"
| "invalid_request"
| "capability_unavailable"
| "bridge_exception";
export const HOPPER_DIAGNOSTIC_TYPES = [
"remote",
"authorization",
"invalid_request",
"selector_not_found",
"capability_unavailable",
"bridge_exception",
] as const;
export type HopperDiagnosticType = (typeof HOPPER_DIAGNOSTIC_TYPES)[number];
/** Hopper's JSON-RPC endpoint returned an expected remote error response. */
export interface HopperRemoteErrorContext extends AnalysisErrorOptions {
@@ -288,17 +293,28 @@ export class HopperRemoteError extends HopperError {
}
override ownPresentation(): AnalysisErrorOwnPresentation {
const lookupMiss = this.diagnosticType === "selector_not_found";
return {
...hopperRemoteClassification(this.diagnosticType),
message: `Hopper ${this.operation ?? "analysis"} failed (${String(this.code)}, ${this.diagnosticType}): ${this.safeMessage}`,
remediation:
this.diagnosticType === "invalid_request"
remediation: lookupMiss
? "Choose an observed name or address from the current Hopper document. For procedures, use CLI rea search <path> . --kind procedures --mode regex --provider hopper or MCP list_procedures. For other symbols, use list_names."
: this.diagnosticType === "invalid_request"
? "Correct the reported address, document, or arguments and retry."
: "Review the Hopper diagnostic details and correct the request or target; run `rea doctor` if the provider itself is failing. Repeating the unchanged request is not expected to succeed.",
details: {
stage: "analysis",
provider_code: this.code,
diagnostic_type: this.diagnosticType,
...(lookupMiss
? {
related_operations: [
"list_procedures",
"search_procedures",
"list_names",
],
}
: {}),
...(this.operation === undefined ? {} : { operation: this.operation }),
...(this.requestId === undefined ? {} : { request_id: this.requestId }),
},
@@ -595,14 +611,6 @@ export class HopperStartError extends HopperError {
}
}
const HOPPER_DIAGNOSTIC_TYPES = {
remote: true,
authorization: true,
invalid_request: true,
capability_unavailable: true,
bridge_exception: true,
} as const satisfies Record<HopperDiagnosticType, true>;
/** Hopper's rows in the generated error catalogue. */
export const hopperErrorCatalogue =
(): readonly AnalysisErrorCatalogueEntry[] => [
@@ -621,11 +629,11 @@ export const hopperErrorCatalogue =
"",
HOPPER_CLASSIFICATIONS.protocol,
),
...Object.keys(HOPPER_DIAGNOSTIC_TYPES).map((diagnosticType) =>
...HOPPER_DIAGNOSTIC_TYPES.map((diagnosticType) =>
catalogueRow(
providerErrorTag("HopperRemoteError"),
`diagnostic_type=${diagnosticType}`,
hopperRemoteClassification(diagnosticType as HopperDiagnosticType),
hopperRemoteClassification(diagnosticType),
),
),
catalogueRow(
+6 -10
View File
@@ -1,6 +1,10 @@
import { z } from "zod";
import { HopperProtocolError, HopperRemoteError } from "./HopperErrors.js";
import {
HOPPER_DIAGNOSTIC_TYPES,
HopperProtocolError,
HopperRemoteError,
} from "./HopperErrors.js";
import { ownedJsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import { safeParseJson } from "../domain/safeJson.js";
@@ -10,15 +14,7 @@ const remoteErrorSchema = z
.object({
code: z.int(),
message: z.string(),
type: z
.enum([
"remote",
"authorization",
"invalid_request",
"capability_unavailable",
"bridge_exception",
])
.default("remote"),
type: z.enum(HOPPER_DIAGNOSTIC_TYPES).default("remote"),
})
.strict();
+12 -2
View File
@@ -504,6 +504,7 @@ describe("headless IDA procedure lookup failures", () => {
it.each([
["Not found", "main\nsecond line"],
["Not a function", "0x1000"],
["Not found", "main\nsecond line"],
] as const)(
"attributes %s for %s according to the selector origin",
async (upstream, procedure) => {
@@ -516,15 +517,22 @@ describe("headless IDA procedure lookup failures", () => {
if (caller.ok) throw new Error("Expected invalid caller input");
if (!(caller.error instanceof AnalysisInputError)) throw caller.error;
expect(projectAnalysisError(caller.error)).toMatchObject({
const projected = projectAnalysisError(caller.error);
expect(projected).not.toHaveProperty("recovery");
expect(projected.remediation.action).toContain(
"--kind procedures --mode regex --provider ida",
);
expect(projected).toMatchObject({
code: "invalid_request",
category: "invalid_input",
retryable: false,
details: {
operation,
related_operations: ["list_procedures", "search_procedures"],
issues: [
{
path: [],
path: ["procedure"],
observed: { procedure },
reason: "invalid_value",
message: `IDA could not resolve procedure ${JSON.stringify(procedure)}: ${upstream}.`,
},
@@ -562,7 +570,9 @@ describe("headless IDA procedure lookup failures", () => {
}
},
);
});
describe("headless IDA invalid lookup replies", () => {
it.each([
["an upstream exception text", lookup("main", null, "Database is closed")],
["a function with an error", lookup("main", knownFunction, "Not found")],
+9 -2
View File
@@ -230,18 +230,25 @@ export class IdaOperationRunner {
throw new AnalysisProtocolError(
`IDA function lookup failed for ${query}: ${outcome.missing}`,
);
const message = `IDA could not resolve procedure ${JSON.stringify(query)}: ${outcome.missing}.`;
throw new AnalysisInputError(
requestedBy,
{
cause: new AnalysisProtocolError(
`IDA function lookup failed for ${query}: ${outcome.missing}`,
),
userMessage: message,
conformsToInputContract: true,
related: { operations: ["list_procedures", "search_procedures"] },
remediationAction:
"Choose an observed name or address from the current IDA inventory. CLI: rea search <path> . --kind procedures --mode regex --provider ida. MCP: use search_procedures or list_procedures. An inventory miss leaves the function's presence in the artifact unknown.",
},
[
{
path: [],
path: ["procedure"],
reason: "invalid_value",
message: `IDA could not resolve procedure ${JSON.stringify(query)}: ${outcome.missing}.`,
message,
observed: { procedure: query },
},
],
);
@@ -479,6 +479,31 @@ it("hashes snapshot section ranges in the same pass as the whole-file digest", a
});
});
it("reads bounded positional ranges of the snapshot without capturing the file", async () => {
const client = clientFor(new FixtureLauncher());
const started = await client.start();
if (!started.ok) throw started.error;
onTestFinished(async () => {
await client.close();
});
const bytes = readFileSync(fixturePath);
const result = await client.readTargetSnapshotRanges(async (range, size) => ({
size,
head: Buffer.from(await range(0, 4)),
middle: Buffer.from(await range(2, 3)),
pastEnd: Buffer.from(await range(bytes.length - 2, 16)),
}));
expect(result).toEqual({
ok: true,
value: {
size: bytes.length,
head: bytes.subarray(0, 4),
middle: bytes.subarray(2, 5),
pastEnd: bytes.subarray(bytes.length - 2),
},
});
});
it("reports snapshot descriptor cleanup immediately and resolves its exact error on retry", async () => {
const client = clientFor(new FixtureLauncher());
const started = await client.start();