fix(ghidra): resolve file offsets in decompile (#2101)
* fix(native): expose loaded image bases in overviews * test(ghidra): retain resources when verifier cleanup fails * docs(ghidra): spell out file-offset address mapping * fix(ci): separate and retry NativeAOT dependency restoration * fix(test): resolve CI script file URLs on Windows * fix(native): retain conflict observations and actionable CLI guidance * fix(fixtures): keep NativeAOT retry logs credential-safe * fix(fixtures): redact authenticated URLs at diagnostic creation * fix(ghidra): restrict source-coordinate observations to decompilation * fix(cli): identify conflicting file-offset selectors accurately * fix(ghidra): bind file offsets to admitted target sources * fix(ghidra): preserve resolved file-offset failure context * test(ghidra): verify ELF address and file-offset round trips * test(nativeaot): align diagnostic regressions with fixture host support
This commit is contained in:
@@ -21,8 +21,8 @@ import {
|
||||
parseFunctionDossier,
|
||||
parseListCount,
|
||||
parseRelatedAddresses,
|
||||
parseSegmentImageBase,
|
||||
parseSegments,
|
||||
parseSegmentImageBase,
|
||||
} from "../domain/hopperValues.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
@@ -46,6 +46,7 @@ import { traceCallPath } from "./CallPathTracing.js";
|
||||
import { resolveProcedureAddress } from "./ProcedureAddressResolution.js";
|
||||
import { traceLiteralFeature } from "./EnhancedLiteralTracing.js";
|
||||
import { projectNativeApiInspection } from "./native/NativeApiInspection.js";
|
||||
|
||||
/**
|
||||
* Composes direct provider operations into bounded reverse-engineering tools.
|
||||
* Direct callers use `execute`; adapters that own validation use
|
||||
@@ -528,24 +529,29 @@ export class EnhancedTools {
|
||||
|
||||
const segments = parseSegments(segmentsResult.value);
|
||||
if (!segments.ok) return segments;
|
||||
const imageBase = parseSegmentImageBase(segmentsResult.value);
|
||||
const procedureCount = parseListCount(proceduresResult.value, "procedures");
|
||||
if (!procedureCount.ok) return procedureCount;
|
||||
const stringCount = parseListCount(stringsResult.value, "strings");
|
||||
if (!stringCount.ok) return stringCount;
|
||||
|
||||
const imageBase = parseSegmentImageBase(segments.value);
|
||||
|
||||
return ok({
|
||||
document: document.value,
|
||||
segments: segments.value.map(({ name, start, end }) => ({
|
||||
name,
|
||||
start,
|
||||
end,
|
||||
length: addressDistance(start, end),
|
||||
})),
|
||||
...(imageBase === undefined ? {} : { image_base: imageBase }),
|
||||
segments: segments.value.map(
|
||||
({ name, start, end, image_base, address_space }) => ({
|
||||
name,
|
||||
start,
|
||||
end,
|
||||
length: addressDistance(start, end),
|
||||
...(image_base === undefined ? {} : { image_base }),
|
||||
...(address_space === undefined ? {} : { address_space }),
|
||||
}),
|
||||
),
|
||||
segment_count: segments.value.length,
|
||||
procedure_count: procedureCount.value,
|
||||
string_count: stringCount.value,
|
||||
...(imageBase === undefined ? {} : { image_base: imageBase }),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -18,11 +18,11 @@ export const workflowAnalysisProfile = (
|
||||
): AnalysisProfileCommitment =>
|
||||
createAnalysisProfile(REA_WORKFLOW_PROVIDER, {
|
||||
upstream_analysis_profile: upstream,
|
||||
...(operation === "binary_overview" ||
|
||||
operation === "batch_decompile" ||
|
||||
operation === "get_call_graph"
|
||||
? { workflow_revision: 2 }
|
||||
: {}),
|
||||
...(operation === "binary_overview"
|
||||
? { workflow_revision: 3 }
|
||||
: operation === "batch_decompile" || operation === "get_call_graph"
|
||||
? { workflow_revision: 2 }
|
||||
: {}),
|
||||
});
|
||||
|
||||
/** Provider identity for deterministic artifact inventories. */
|
||||
|
||||
@@ -137,6 +137,13 @@ const registerDecompileCommand = (
|
||||
.describe(
|
||||
"Procedure name or address; use --procedure=<value> for leading dashes",
|
||||
),
|
||||
"file-offset": z
|
||||
.string()
|
||||
.regex(/^0x[0-9a-fA-F]+$/u)
|
||||
.optional()
|
||||
.describe(
|
||||
"Ghidra source-file byte offset; mapped internally to an analysis address",
|
||||
),
|
||||
snapshot: z
|
||||
.string()
|
||||
.min(1)
|
||||
@@ -152,8 +159,17 @@ const registerDecompileCommand = (
|
||||
{
|
||||
procedure: resolveCliAnalysisSelector(
|
||||
args.address,
|
||||
options.procedure,
|
||||
"procedure",
|
||||
options["file-offset"] === undefined
|
||||
? options.procedure
|
||||
: resolveCliAnalysisSelector(
|
||||
options.procedure,
|
||||
`file-offset:${options["file-offset"]}`,
|
||||
"file-offset",
|
||||
"procedure_pseudo_code",
|
||||
),
|
||||
options["file-offset"] === undefined
|
||||
? "procedure"
|
||||
: "file-offset",
|
||||
"procedure_pseudo_code",
|
||||
),
|
||||
},
|
||||
|
||||
@@ -181,7 +181,7 @@ export const OFFICIAL_TOOL_CONTRACTS = [
|
||||
),
|
||||
official(
|
||||
"procedure_pseudo_code",
|
||||
"Decompile one analyzed procedure by symbol name or provider-normalized address. Returns provider-specific pseudocode, never original source or cross-provider text equivalence, and may return null; request procedure_assembly when instruction precision matters. Ghidra no-return assumptions may cut the analyzed body; Evidence limitations report observed terminal calls and available callee identities.",
|
||||
"Decompile one analyzed procedure by symbol name or provider-normalized address. Ghidra also accepts file-offset:0x... selectors and falls back to a unique source-file mapping when a 0x-prefixed number resolves to no procedure; existing analysis addresses take precedence and ambiguous mappings fail explicitly. Returns provider-specific pseudocode, never original source or cross-provider text equivalence, and may return null; request procedure_assembly when instruction precision matters. Ghidra no-return assumptions may cut the analyzed body; Evidence limitations report observed terminal calls and available callee identities.",
|
||||
z.object({ procedure, document }),
|
||||
),
|
||||
official(
|
||||
|
||||
@@ -357,18 +357,20 @@ export const enhancedOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
binary_overview: evidenceResultOf(
|
||||
z.object({
|
||||
document: z.string(),
|
||||
image_base: z.string().min(1).optional(),
|
||||
segments: z.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
start: z.string(),
|
||||
end: z.string(),
|
||||
length: z.number().min(0),
|
||||
image_base: z.string().exactOptional(),
|
||||
address_space: z.string().exactOptional(),
|
||||
}),
|
||||
),
|
||||
segment_count: z.number().int().min(0),
|
||||
procedure_count: z.number().int().min(0),
|
||||
string_count: z.number().int().min(0),
|
||||
image_base: z.string().min(1).optional(),
|
||||
}),
|
||||
),
|
||||
analyze_function: functionDossierOutput,
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
parseNames,
|
||||
parseProcedures,
|
||||
parseRelatedAddresses,
|
||||
parseSegmentImageBase,
|
||||
parseSegments,
|
||||
} from "./hopperValues.js";
|
||||
|
||||
@@ -66,19 +65,6 @@ describe("Hopper boundary values", () => {
|
||||
ok: true,
|
||||
value: ["fixture"],
|
||||
});
|
||||
expect(
|
||||
parseSegmentImageBase([
|
||||
{ image_base: "0x100000" },
|
||||
{ image_base: "0x100000" },
|
||||
]),
|
||||
).toBe("0x100000");
|
||||
expect(
|
||||
parseSegmentImageBase([
|
||||
{ image_base: "0x100000" },
|
||||
{ image_base: "0x200000" },
|
||||
]),
|
||||
).toBeUndefined();
|
||||
expect(parseSegmentImageBase([{ name: "__TEXT" }])).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([
|
||||
|
||||
+14
-12
@@ -20,6 +20,8 @@ export interface SegmentSummary {
|
||||
readonly readable: boolean | null;
|
||||
readonly writable: boolean | null;
|
||||
readonly executable: boolean | null;
|
||||
readonly image_base?: string;
|
||||
readonly address_space?: string;
|
||||
}
|
||||
|
||||
/** Return a bounded byte distance between canonical addresses in one space. */
|
||||
@@ -58,10 +60,9 @@ const segmentSchema = z.object({
|
||||
readable: z.boolean().nullable(),
|
||||
writable: z.boolean().nullable(),
|
||||
executable: z.boolean().nullable(),
|
||||
image_base: z.string().min(1).exactOptional(),
|
||||
address_space: z.string().min(1).exactOptional(),
|
||||
});
|
||||
const segmentImageBaseSchema = z
|
||||
.object({ image_base: z.string().min(1) })
|
||||
.passthrough();
|
||||
const unavailableAnalysisFactSchema = z
|
||||
.object({ available: z.literal(false), reason: z.string() })
|
||||
.strict();
|
||||
@@ -415,7 +416,7 @@ export const parseRelatedAddresses = (
|
||||
: invalid(`${relation} list`, parsed.error);
|
||||
};
|
||||
|
||||
/** Parse direct or wrapped Hopper segment records. */
|
||||
/** Preserve reported address context in direct or wrapped provider segments. */
|
||||
export const parseSegments = (
|
||||
value: JsonValue,
|
||||
): Result<readonly SegmentSummary[], HopperProtocolError> => {
|
||||
@@ -427,14 +428,15 @@ export const parseSegments = (
|
||||
: invalid("segment list", parsed.error);
|
||||
};
|
||||
|
||||
/** Return a provider-reported image base only when every segment agrees on it. */
|
||||
export const parseSegmentImageBase = (value: JsonValue): string | undefined => {
|
||||
const parsed = z
|
||||
.array(segmentImageBaseSchema)
|
||||
.safeParse(unwrapProperty(value, "segments"));
|
||||
if (!parsed.success) return undefined;
|
||||
const bases = new Set(parsed.data.map(({ image_base }) => image_base));
|
||||
return bases.size === 1 ? parsed.data[0]?.image_base : undefined;
|
||||
/** Return a reported overview base only when every parsed segment agrees. */
|
||||
export const parseSegmentImageBase = (
|
||||
segments: readonly SegmentSummary[],
|
||||
): string | undefined => {
|
||||
const base = segments[0]?.image_base;
|
||||
return base !== undefined &&
|
||||
segments.every((segment) => segment.image_base === base)
|
||||
? base
|
||||
: undefined;
|
||||
};
|
||||
|
||||
/** Parse direct or wrapped Hopper document names. */
|
||||
|
||||
@@ -123,6 +123,8 @@ export const resolveGhidraAnalysisProfile = async (
|
||||
call_relationship_coverage: "resolved-call-reference-diagnostics-v1",
|
||||
string_inventory_evidence: "defined-data-coverage-v1",
|
||||
location_resolution: "explicit-address-exact-entry-symbol-first-v3",
|
||||
procedure_file_offset_resolution:
|
||||
"address-first-unique-target-source-mapping-v2",
|
||||
instruction_flow_evidence: "decoded-return-pcode-v1",
|
||||
instruction_references: "exact-address-incoming-v1",
|
||||
function_boundary_observations: "ghidra-terminal-call-limitations-v1",
|
||||
@@ -212,6 +214,8 @@ export const resolveGhidraAnalysisProfile = async (
|
||||
call_relationship_coverage: "resolved-call-reference-diagnostics-v1",
|
||||
string_inventory_evidence: "defined-data-coverage-v1",
|
||||
location_resolution: "explicit-address-exact-entry-symbol-first-v3",
|
||||
procedure_file_offset_resolution:
|
||||
"address-first-unique-target-source-mapping-v2",
|
||||
instruction_flow_evidence: "decoded-return-pcode-v1",
|
||||
instruction_references: "exact-address-incoming-v1",
|
||||
function_boundary_observations: "ghidra-terminal-call-limitations-v1",
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { runDoctor, type DoctorHost } from "../application/Doctor.js";
|
||||
import { createDoctorHostFixture } from "../application/Doctor.fixture.js";
|
||||
import { providerRegistrationEnvironment } from "../application/SetupRegistrationEnvironment.js";
|
||||
import { WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON } from "../process/WindowsAuthority.js";
|
||||
import * as windowsAuthority from "../process/WindowsAuthority.js";
|
||||
import {
|
||||
inspectGhidraInstallation,
|
||||
type GhidraInstallationHost,
|
||||
@@ -173,6 +174,16 @@ describe("Ghidra doctor integration", () => {
|
||||
});
|
||||
|
||||
describe("Windows Ghidra doctor authority", () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(windowsAuthority, "hasWindowsNativeAuthority").mockReturnValue(
|
||||
false,
|
||||
);
|
||||
vi.spyOn(
|
||||
windowsAuthority,
|
||||
"windowsNativeAuthorityUnavailableReason",
|
||||
).mockReturnValue(WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON);
|
||||
});
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
it("distinguishes a valid Windows installation from unavailable native authority", async () => {
|
||||
const ghidra = inspection({
|
||||
installDir: "C:\\tools\\ghidra_12.1.4_PUBLIC",
|
||||
|
||||
@@ -42,6 +42,30 @@ const parseFunctionValueFixture = (
|
||||
};
|
||||
|
||||
describe("Ghidra function-analysis result values", () => {
|
||||
it("preserves file-offset resolution in Evidence locations and rejects inexact offsets", () => {
|
||||
const selection = {
|
||||
file_offset: 0x210,
|
||||
mapped_address: "0x140001010",
|
||||
procedure_address: "0x140001010",
|
||||
};
|
||||
const wire = { value: "return 42;", limitations: [], selection };
|
||||
expect(parseGhidraFunctionResult("procedure_assembly", wire)).toMatchObject(
|
||||
{ ok: false, error: { _tag: "AnalysisOutputError" } },
|
||||
);
|
||||
const parsed = parseGhidraFunctionResult("procedure_pseudo_code", wire);
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
expect(parsed.value.locations).toEqual([
|
||||
{ kind: "file-offset", offset: 0x210 },
|
||||
{ kind: "address", address: "0x140001010" },
|
||||
{ kind: "address", address: "0x140001010" },
|
||||
]);
|
||||
expect(
|
||||
parseGhidraFunctionResult("procedure_pseudo_code", {
|
||||
...wire,
|
||||
selection: { ...selection, file_offset: Number.MAX_SAFE_INTEGER + 1 },
|
||||
}),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } });
|
||||
});
|
||||
it.each([...observationOperations])(
|
||||
"requires the function-observation limitations envelope for %s",
|
||||
(operation) => {
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
} from "../domain/jsonValue.js";
|
||||
import { nativeApiBoundarySchema } from "../domain/native/nativeApiBoundary.js";
|
||||
import { nativeValueFlowSchema } from "../domain/native/nativeValueFlow.js";
|
||||
import type { EvidenceLocation } from "../domain/evidence.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
|
||||
import {
|
||||
@@ -399,11 +400,19 @@ const functionBoundaryObservationOperations: ReadonlySet<GhidraFunctionOperation
|
||||
const functionObservationEnvelope = z.strictObject({
|
||||
value: z.unknown(),
|
||||
limitations: z.array(z.string()),
|
||||
selection: z
|
||||
.strictObject({
|
||||
file_offset: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
||||
mapped_address: ghidraCanonicalAddressSchema,
|
||||
procedure_address: ghidraCanonicalAddressSchema,
|
||||
})
|
||||
.exactOptional(),
|
||||
});
|
||||
|
||||
export interface ParsedGhidraFunctionResult {
|
||||
readonly value: JsonValue;
|
||||
readonly limitations: readonly string[];
|
||||
readonly locations?: readonly EvidenceLocation[];
|
||||
}
|
||||
|
||||
/** Require exact, bounded Java-bridge function output before creating Evidence. */
|
||||
@@ -414,15 +423,22 @@ export const parseGhidraFunctionResult = (
|
||||
let observation: {
|
||||
readonly value: unknown;
|
||||
readonly limitations: readonly string[];
|
||||
readonly selection?: z.infer<
|
||||
typeof functionObservationEnvelope
|
||||
>["selection"];
|
||||
};
|
||||
if (functionBoundaryObservationOperations.has(operation)) {
|
||||
const envelope = functionObservationEnvelope.safeParse(value);
|
||||
if (!envelope.success)
|
||||
if (
|
||||
!envelope.success ||
|
||||
(operation !== "procedure_pseudo_code" &&
|
||||
envelope.data.selection !== undefined)
|
||||
)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
"Ghidra bridge omitted the function observation envelope",
|
||||
{ cause: envelope.error },
|
||||
envelope.success ? undefined : { cause: envelope.error },
|
||||
),
|
||||
);
|
||||
observation = envelope.data;
|
||||
@@ -434,6 +450,24 @@ export const parseGhidraFunctionResult = (
|
||||
? ok({
|
||||
value: jsonValueSchema.parse(parsed.data),
|
||||
limitations: observation.limitations,
|
||||
...(observation.selection === undefined
|
||||
? {}
|
||||
: {
|
||||
locations: [
|
||||
{
|
||||
kind: "file-offset" as const,
|
||||
offset: observation.selection.file_offset,
|
||||
},
|
||||
{
|
||||
kind: "address" as const,
|
||||
address: observation.selection.mapped_address,
|
||||
},
|
||||
{
|
||||
kind: "address" as const,
|
||||
address: observation.selection.procedure_address,
|
||||
},
|
||||
],
|
||||
}),
|
||||
})
|
||||
: err(
|
||||
new AnalysisOutputError(
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
AnalysisTimeoutError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { EvidenceLocation } from "../domain/evidence.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
@@ -678,10 +679,12 @@ export const createGhidraProviderClient = (input: {
|
||||
normalized: JsonValue,
|
||||
rawResult: JsonValue,
|
||||
observationLimitations: readonly string[] = [],
|
||||
locations: readonly EvidenceLocation[] = [],
|
||||
) => {
|
||||
const relationshipCoverage = relationshipCoverageFor(operation);
|
||||
return createAnalysisExecution(normalized, committedProfile.provider, {
|
||||
rawResult,
|
||||
locations,
|
||||
analysisProfile: committedProfile,
|
||||
...(relationshipCoverage === undefined ? {} : { relationshipCoverage }),
|
||||
limitations: [
|
||||
@@ -776,11 +779,13 @@ export const createGhidraProviderClient = (input: {
|
||||
);
|
||||
let normalized: JsonValue;
|
||||
let observationLimitations: readonly string[] = [];
|
||||
let observationLocations: readonly EvidenceLocation[] = [];
|
||||
if (isGhidraFunctionOperation(operation)) {
|
||||
const result = parseGhidraFunctionResult(operation, called.value);
|
||||
if (!result.ok) return result;
|
||||
normalized = result.value.value;
|
||||
observationLimitations = result.value.limitations;
|
||||
observationLocations = result.value.locations ?? [];
|
||||
} else {
|
||||
const result = parseGhidraInventoryResult(operation, called.value);
|
||||
if (!result.ok) return result;
|
||||
@@ -875,6 +880,7 @@ export const createGhidraProviderClient = (input: {
|
||||
normalized,
|
||||
called.value,
|
||||
observationLimitations,
|
||||
observationLocations,
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user