fix(hopper): resolve FAT loaders and original file coordinates
This commit is contained in:
@@ -3,7 +3,11 @@ import {
|
||||
type AnalysisProfileCommitment,
|
||||
} from "../../domain/analysisProfile.js";
|
||||
import type { BinaryTarget } from "../../domain/binaryTarget.js";
|
||||
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisUnsupportedTargetError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { jsonObjectSchema, type JsonValue } from "../../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import type { AnalysisProviderCandidate } from "../AnalysisProvider.js";
|
||||
@@ -16,6 +20,7 @@ export interface AnalysisProviderCandidateEvaluation {
|
||||
readonly status: AnalysisProviderCandidateStatus;
|
||||
readonly profile?: AnalysisProfileCommitment;
|
||||
readonly compatibility?: Readonly<Record<string, JsonValue>>;
|
||||
readonly profileError?: AnalysisError;
|
||||
}
|
||||
|
||||
/** Resolve and validate one provider profile without starting its client. */
|
||||
@@ -51,12 +56,27 @@ export const evaluateAnalysisProviderCandidate = async (
|
||||
return err(new AnalysisCancelledError("open_binary"));
|
||||
if (!resolved.ok && resolved.error instanceof AnalysisCancelledError)
|
||||
return err(resolved.error);
|
||||
if (!resolved.ok)
|
||||
return ok(
|
||||
rejectedProfile(candidate, status, resolved.error.message, {
|
||||
error_tag: resolved.error._tag,
|
||||
}),
|
||||
);
|
||||
if (!resolved.ok) {
|
||||
const error = resolved.error;
|
||||
const rejection =
|
||||
error instanceof AnalysisUnsupportedTargetError
|
||||
? {
|
||||
candidate,
|
||||
status: {
|
||||
...status,
|
||||
targetSupport: {
|
||||
status: "unsupported" as const,
|
||||
code: "target_format_unsupported" as const,
|
||||
reason: error.reason,
|
||||
diagnostics: { path: error.path, error_tag: error._tag },
|
||||
},
|
||||
},
|
||||
}
|
||||
: rejectedProfile(candidate, status, error.message, {
|
||||
error_tag: error._tag,
|
||||
});
|
||||
return ok({ ...rejection, profileError: error });
|
||||
}
|
||||
try {
|
||||
if (resolved.value.profile === null)
|
||||
return ok(
|
||||
|
||||
@@ -212,15 +212,10 @@ describe("analysis provider registry: binding failures and cancellation", () =>
|
||||
failed.provider,
|
||||
]).select(DATABASE_TARGET, "failed");
|
||||
if (explicit.ok) throw new Error("expected provider selection rejection");
|
||||
expect(explicit.error).toBeInstanceOf(ProviderSelectionError);
|
||||
if (explicit.error instanceof ProviderSelectionError)
|
||||
expect(explicit.error.rejections).toMatchObject([
|
||||
{
|
||||
providerId: "failed",
|
||||
code: "version_unresolved",
|
||||
diagnostics: { error_tag: "ProviderAdapterError" },
|
||||
},
|
||||
]);
|
||||
expect(explicit.error).toMatchObject({
|
||||
_tag: "ProviderAdapterError",
|
||||
providerId: "failed",
|
||||
});
|
||||
});
|
||||
|
||||
it("cancels a pending profile probe even when the adapter ignores its signal", async () => {
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
import type { AnalysisProfileCommitment } from "../../domain/analysisProfile.js";
|
||||
import type { BinaryTarget } from "../../domain/binaryTarget.js";
|
||||
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
ProviderSelectionError,
|
||||
type ProviderSelectionFailureReason,
|
||||
@@ -147,12 +148,7 @@ export class AnalysisProviderRegistry {
|
||||
target: BinaryTarget,
|
||||
requestedSelector?: AnalysisProviderSelector,
|
||||
options: { readonly signal?: AbortSignal } = {},
|
||||
): Promise<
|
||||
Result<
|
||||
AnalysisProviderSelection,
|
||||
ProviderSelectionError | AnalysisCancelledError
|
||||
>
|
||||
> {
|
||||
): Promise<Result<AnalysisProviderSelection, AnalysisError>> {
|
||||
if (signalIsAborted(options.signal))
|
||||
return err(new AnalysisCancelledError("open_binary"));
|
||||
const parsedRequest =
|
||||
@@ -224,12 +220,7 @@ export class AnalysisProviderRegistry {
|
||||
context: TargetSelectionContext,
|
||||
providerId: string,
|
||||
source: AnalysisProviderBinding["selectionSource"],
|
||||
): Promise<
|
||||
Result<
|
||||
AnalysisProviderSelection,
|
||||
ProviderSelectionError | AnalysisCancelledError
|
||||
>
|
||||
> {
|
||||
): Promise<Result<AnalysisProviderSelection, AnalysisError>> {
|
||||
const { baseline, signal, target } = context;
|
||||
const provider = this.#byId.get(providerId);
|
||||
if (provider === undefined)
|
||||
@@ -253,6 +244,8 @@ export class AnalysisProviderRegistry {
|
||||
);
|
||||
if (!evaluation.ok) return evaluation;
|
||||
const evaluated = evaluation.value;
|
||||
if (evaluated.profileError !== undefined)
|
||||
return err(evaluated.profileError);
|
||||
const statuses = replaceCandidate(baseline, evaluated.status);
|
||||
if (
|
||||
evaluated.profile === undefined ||
|
||||
@@ -275,12 +268,7 @@ export class AnalysisProviderRegistry {
|
||||
|
||||
async #selectAutomatically(
|
||||
context: TargetSelectionContext,
|
||||
): Promise<
|
||||
Result<
|
||||
AnalysisProviderSelection,
|
||||
ProviderSelectionError | AnalysisCancelledError
|
||||
>
|
||||
> {
|
||||
): Promise<Result<AnalysisProviderSelection, AnalysisError>> {
|
||||
const { baseline, signal, target } = context;
|
||||
const results = await Promise.all(
|
||||
this.#providers.map(
|
||||
|
||||
@@ -16,7 +16,7 @@ export const HOPPER_MEMORY_TOOL_DEFINITIONS = [
|
||||
{
|
||||
name: "address_to_file_offset",
|
||||
description:
|
||||
"Map one provider-normalized virtual address to its original nonnegative file offset. Unmapped addresses fail explicitly, and providers without an authoritative mapping API return typed capability unavailability.",
|
||||
"Map one provider-normalized virtual address to its original nonnegative file offset. Hopper translates FAT Mach-O image-relative offsets using the observed loaded header, preserving its provider coordinate, image base, and source path. Unmapped addresses fail explicitly, and unavailable or ambiguous original-file mappings return typed capability unavailability.",
|
||||
inputSchema: z.object({ address, document }),
|
||||
},
|
||||
] as const;
|
||||
|
||||
@@ -147,6 +147,30 @@ export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
z.object({
|
||||
address: z.string(),
|
||||
file_offset: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
||||
provider_file_offset: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.exactOptional()
|
||||
.describe(
|
||||
"Original coordinate returned by the provider's mapping API.",
|
||||
),
|
||||
image_base_file_offset: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.exactOptional()
|
||||
.describe(
|
||||
"File offset of the loaded image within its source container; zero for a thin executable.",
|
||||
),
|
||||
source_path: z
|
||||
.string()
|
||||
.exactOptional()
|
||||
.describe(
|
||||
"Observed original executable path used to verify the file mapping.",
|
||||
),
|
||||
}),
|
||||
),
|
||||
procedure_references: resultOf(
|
||||
|
||||
@@ -10,7 +10,11 @@ import type {
|
||||
BinaryArchitecture,
|
||||
BinaryTarget,
|
||||
} from "../domain/binaryTarget.js";
|
||||
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { BinaryTargetError } from "../domain/configurationErrors.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import { type AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
@@ -29,7 +33,17 @@ export const resolveHopperAnalysisProfile = async (
|
||||
): Promise<Result<AnalysisProfileResolution, AnalysisError>> => {
|
||||
if (target.kind !== "executable" && target.kind !== "database")
|
||||
return ok({ profile: null, compatibility: {} });
|
||||
const derived = hopperLoaderArgsForTarget(target);
|
||||
let machoContainer: "thin" | "fat32" | "fat64" | undefined;
|
||||
if (target.kind === "executable" && target.format === "mach-o") {
|
||||
const header = await readMachoMagic(target.path, options.signal);
|
||||
if (!header.ok) return header;
|
||||
machoContainer = [0xcafebabf, 0xbfbafeca].includes(header.value)
|
||||
? "fat64"
|
||||
: [0xcafebabe, 0xbebafeca].includes(header.value)
|
||||
? "fat32"
|
||||
: "thin";
|
||||
}
|
||||
const derived = hopperLoaderArgsForTarget(target, machoContainer);
|
||||
if (!derived.ok) return derived;
|
||||
const loaderArgs =
|
||||
options.loaderArgsOverride.length === 0
|
||||
@@ -53,6 +67,9 @@ export const resolveHopperAnalysisProfile = async (
|
||||
available_architectures: [
|
||||
...(target.availableArchitectures ?? []),
|
||||
].sort(),
|
||||
...(machoContainer === undefined
|
||||
? {}
|
||||
: { macho_container: machoContainer }),
|
||||
loader: {
|
||||
source:
|
||||
options.loaderArgsOverride.length === 0
|
||||
@@ -71,7 +88,11 @@ export const resolveHopperAnalysisProfile = async (
|
||||
/** Derive Hopper's complete non-interactive CLI loader selection. */
|
||||
export const hopperLoaderArgsForTarget = (
|
||||
target: BinaryTarget,
|
||||
): Result<readonly string[], ProviderAdapterError> => {
|
||||
machoContainer?: "thin" | "fat32" | "fat64",
|
||||
): Result<
|
||||
readonly string[],
|
||||
ProviderAdapterError | AnalysisCapabilityUnavailableError
|
||||
> => {
|
||||
if (target.kind === "database") return ok([]);
|
||||
if (target.kind !== "executable")
|
||||
return err(new ProviderAdapterError("hopper", "resolve_analysis_profile"));
|
||||
@@ -79,8 +100,16 @@ export const hopperLoaderArgsForTarget = (
|
||||
const flag = hopperArchitectureFlag(architecture);
|
||||
switch (target.format) {
|
||||
case "mach-o":
|
||||
if (machoContainer === undefined)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"hopper",
|
||||
"resolve_analysis_profile",
|
||||
"Mach-O container kind is unknown; resolve the Hopper analysis profile before starting its client.",
|
||||
),
|
||||
);
|
||||
return ok(
|
||||
(target.availableArchitectures?.length ?? 0) > 1
|
||||
machoContainer === "fat32" || machoContainer === "fat64"
|
||||
? ["-l", "FAT", flag, "-l", "Mach-O"]
|
||||
: ["-l", "Mach-O", flag],
|
||||
);
|
||||
@@ -109,6 +138,46 @@ const hopperArchitectureFlag = (architecture: BinaryArchitecture): string => {
|
||||
}
|
||||
};
|
||||
|
||||
const readMachoMagic = async (
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<number, AnalysisError>> => {
|
||||
if (signalIsAborted(signal))
|
||||
return err(new AnalysisCancelledError("open_binary"));
|
||||
const stream = createReadStream(path, { start: 0, end: 3 });
|
||||
const onAbort = (): void => {
|
||||
stream.destroy();
|
||||
};
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
try {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of stream) chunks.push(Buffer.from(chunk));
|
||||
if (signalIsAborted(signal))
|
||||
return err(new AnalysisCancelledError("open_binary"));
|
||||
const bytes = Buffer.concat(chunks);
|
||||
return bytes.length === 4
|
||||
? ok(bytes.readUInt32BE(0))
|
||||
: err(
|
||||
new BinaryTargetError(
|
||||
path,
|
||||
"Mach-O header became truncated before Hopper loader selection",
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return signalIsAborted(signal)
|
||||
? err(new AnalysisCancelledError("open_binary"))
|
||||
: err(
|
||||
new BinaryTargetError(
|
||||
path,
|
||||
`Cannot read the Mach-O container header: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
}
|
||||
};
|
||||
|
||||
const sha256File = async (
|
||||
path: string,
|
||||
signal: AbortSignal | undefined,
|
||||
|
||||
@@ -158,7 +158,13 @@ export class HopperProvider implements AnalysisProviderCandidate {
|
||||
),
|
||||
close: () => Promise.resolve(),
|
||||
};
|
||||
const derivedLoaderArgs = hopperLoaderArgsForTarget(target);
|
||||
const container = profile?.parameters.macho_container;
|
||||
const derivedLoaderArgs = hopperLoaderArgsForTarget(
|
||||
target,
|
||||
container === "thin" || container === "fat32" || container === "fat64"
|
||||
? container
|
||||
: undefined,
|
||||
);
|
||||
if (!derivedLoaderArgs.ok)
|
||||
return {
|
||||
execute: () => Promise.resolve(err(derivedLoaderArgs.error)),
|
||||
@@ -200,7 +206,9 @@ export class HopperProvider implements AnalysisProviderCandidate {
|
||||
value: createAnalysisExecution(result.value, executionProvider, {
|
||||
...(profile === undefined ? {} : { analysisProfile: profile }),
|
||||
limitations: [
|
||||
"Results depend on Hopper's completed static analysis.",
|
||||
...(CAPABILITIES.find(
|
||||
(descriptor) => descriptor.operation === operation,
|
||||
)?.limitations ?? []),
|
||||
...(operation === "read_bytes"
|
||||
? [
|
||||
"Hopper byte reads stop at the containing segment's exclusive end; a readable prefix is returned with complete=false when the requested range crosses it.",
|
||||
|
||||
Reference in New Issue
Block a user