perf(ghidra): reuse inventory body metadata in full decompile exports (#15072)

* perf(ghidra): reuse inventory body metadata in full decompile exports

* Verify export body caveats through the Ghidra provider

* fix(ghidra): keep export inventory enrichment advisory

* fix(ghidra): require local entry coverage for export body metadata

* test(ghidra): cover export metadata reply budgets

---------

Co-authored-by: ShuaixinHuang <197200901+ShuaixinHuang@users.noreply.github.com>
This commit is contained in:
ShuaixinHuangandShuaixinHuang authored and GitHub committed 2026-11-29 00:57:55 +00:00
1 parent 295bdfaf73
commit a113939e78
14 files changed
+654 -51

No files matched your search

+132 -13
View File
@@ -4260,11 +4260,83 @@ public final class ReaGhidraBridge extends HeadlessScript {
}
private StreamingResult listProcedures(JsonObject params) throws Exception {
requireKeys(params, Set.of("document"));
boolean enriched = params.has("export_body_metadata");
requireKeys(params, enriched ? Set.of("document", "export_body_metadata") : Set.of("document"));
requireDocument(params);
List<ProcedureEntry> entries = procedures();
Map<ProcedureEntry, JsonObject> metadata = enriched
? exportBodyMetadata(entries, requireInteger(params, "export_body_metadata")) : Map.of();
monitor.checkCancelled();
return out -> writeProcedureEntries(out, entries);
return out -> writeProcedureEntries(out, entries, metadata);
}
private Map<ProcedureEntry, JsonObject> exportBodyMetadata(List<ProcedureEntry> entries, int replyBytes)
throws Exception {
// Count the ordinary rows with the real encoder. Reserve framing for the
// response object, request ID and newline before admitting any extra work.
Utf8CountingWriter counter = new Utf8CountingWriter();
JsonWriter plain = GSON.newJsonWriter(new SurrogateEscapingWriter(counter));
plain.setSerializeNulls(true);
plain.beginArray();
for (ProcedureEntry entry : entries) {
monitor.checkCancelled();
writeProcedureEntry(plain, entry, null);
}
plain.endArray();
ExportMetadataBudget budget = new ExportMetadataBudget(
Math.min(4 * 1024 * 1024L, replyBytes - counter.bytes - 64)
);
Map<ProcedureEntry, JsonObject> metadata = new IdentityHashMap<>();
for (ProcedureEntry entry : entries) {
monitor.checkCancelled();
// Covers the field name, fixed JSON members, extra punctuation and
// the single shared inferred-no-return explanation.
if (!budget.claim(1024)) break;
Function function = entry.function();
JsonObject body;
try {
body = functionBody(function, budget);
} catch (IllegalStateException unsupportedBody) {
continue; // The ordinary procedure_info path projects the refusal.
}
if (body == null) break;
FunctionBoundaryLimitations boundary = new FunctionBoundaryLimitations(function, budget);
for (Instruction instruction : currentProgram.getListing().getInstructions(function.getBody(), true)) {
boundary.observe(instruction);
if (boundary.budgetExhausted) break;
}
if (boundary.budgetExhausted) break;
JsonObject item = new JsonObject();
item.add("body", body);
item.add("limitations", GSON.toJsonTree(boundary.values()));
metadata.put(entry, item);
}
return metadata;
}
private static final class ExportMetadataBudget {
private long remaining;
private ExportMetadataBudget(long remaining) {
this.remaining = remaining;
}
private boolean claim(long bytes) {
if (bytes > remaining) return false;
remaining -= bytes;
return true;
}
}
private static final class Utf8CountingWriter extends Writer {
private long bytes;
@Override
public void write(char[] chars, int offset, int length) {
for (int i = offset; i < offset + length; i++) {
char ch = chars[i];
bytes += ch < 0x80 ? 1 : ch < 0x800 ? 2 : 3;
}
}
@Override public void flush() {}
@Override public void close() {}
}
private JsonArray listSegments(JsonObject params) {
@@ -6776,6 +6848,8 @@ public final class ReaGhidraBridge extends HeadlessScript {
private final class FunctionBoundaryLimitations {
private final Function function;
private final ExportMetadataBudget budget;
private boolean budgetExhausted;
private final boolean checkLoaderRelocations = !loaderInitializedRelocations.isEmpty();
private final boolean checkBorlandSeh = isX86_32Program();
private final List<String> limitations = new ArrayList<>();
@@ -6785,7 +6859,21 @@ public final class ReaGhidraBridge extends HeadlessScript {
private Instruction previous;
private FunctionBoundaryLimitations(Function function) {
this(function, null);
}
private FunctionBoundaryLimitations(Function function, ExportMetadataBudget budget) {
this.function = function;
this.budget = budget;
}
private boolean retain(String limitation) {
if (budget != null && !budget.claim(4L + 6L * limitation.length())) {
budgetExhausted = true;
return false;
}
limitations.add(limitation);
return true;
}
private void observe(Instruction instruction) throws Exception {
@@ -6796,7 +6884,7 @@ public final class ReaGhidraBridge extends HeadlessScript {
monitor.checkCancelled();
TerminalCall terminal = terminalCall(instruction);
if (terminal != null) {
limitations.add(terminal.limitation());
if (!retain(terminal.limitation())) return;
if (terminal.inferredNoReturn()) inferredNoReturnCall = true;
}
if (checkLoaderRelocations && referencesFrom != null) {
@@ -6807,14 +6895,14 @@ public final class ReaGhidraBridge extends HeadlessScript {
);
if (relocation == null || !observedLoaderRelocations.add(relocation.address()))
continue;
limitations.add(loaderInitializedRelocationLimitation(relocation));
if (!retain(loaderInitializedRelocationLimitation(relocation))) return;
}
}
if (checkBorlandSeh) {
if (beforePrevious != null && previous != null) {
String seh = borlandSehHandlerLimitation(
function, beforePrevious, previous, instruction);
if (seh != null) limitations.add(seh);
if (seh != null && !retain(seh)) return;
}
beforePrevious = previous;
previous = instruction;
@@ -7798,14 +7886,20 @@ public final class ReaGhidraBridge extends HeadlessScript {
out.endArray();
}
private static void writeProcedureEntries(JsonWriter out, List<ProcedureEntry> entries) throws IOException {
private static void writeProcedureEntries(JsonWriter out, List<ProcedureEntry> entries,
Map<ProcedureEntry, JsonObject> metadata) throws IOException {
out.beginArray();
for (ProcedureEntry entry : entries) {
writeResultItem(out, entry.address(), entry.value(), "procedure", entry.facts(), entry.symbol(), List.of());
}
for (ProcedureEntry entry : entries)
writeProcedureEntry(out, entry, metadata.get(entry));
out.endArray();
}
private static void writeProcedureEntry(JsonWriter out, ProcedureEntry entry, JsonObject metadata)
throws IOException {
writeResultItem(out, entry.address(), entry.value(), "procedure", entry.facts(), entry.symbol(),
List.of(), metadata);
}
private static void writeMatchedProcedures(JsonWriter out, List<MatchedProcedure> matches) throws IOException {
out.beginArray();
for (MatchedProcedure match : matches) {
@@ -7864,8 +7958,25 @@ public final class ReaGhidraBridge extends HeadlessScript {
InventoryFacts facts,
SymbolFacts symbol,
List<String> matchedAliases
) throws IOException {
writeResultItem(out, address, value, factsName, facts, symbol, matchedAliases, null);
}
private static void writeResultItem(
JsonWriter out,
Address address,
String value,
String factsName,
InventoryFacts facts,
SymbolFacts symbol,
List<String> matchedAliases,
JsonObject exportBodyMetadata
) throws IOException {
out.beginObject();
if (exportBodyMetadata != null) {
out.name("export_body_metadata");
GSON.toJson(exportBodyMetadata, out);
}
out.name("address").value(canonicalAddress(address));
out.name("value").value(value);
if (factsName != null) {
@@ -7920,6 +8031,10 @@ public final class ReaGhidraBridge extends HeadlessScript {
/** Observe the entire AddressSet; range endpoints are inclusive, not a guessed span. */
private static JsonObject functionBody(Function function) {
return functionBody(function, null);
}
private static JsonObject functionBody(Function function, ExportMetadataBudget budget) {
JsonArray ranges = new JsonArray();
BigInteger total = BigInteger.ZERO;
Address first = null;
@@ -7934,9 +8049,13 @@ public final class ReaGhidraBridge extends HeadlessScript {
if (start.getAddressSpace().getAddressableUnitSize() != 1) {
throw new IllegalStateException("Function body byte coverage requires a byte-addressed space");
}
String startText = canonicalAddress(start);
String endText = canonicalAddress(end);
if (budget != null && !budget.claim(40L + 6L * (startText.length() + endText.length())))
return null;
JsonObject value = new JsonObject();
value.addProperty("start", canonicalAddress(start));
value.addProperty("end", canonicalAddress(end));
value.addProperty("start", startText);
value.addProperty("end", endText);
ranges.add(value);
BigInteger begin = new BigInteger(Long.toUnsignedString(start.getOffset()));
BigInteger finish = new BigInteger(Long.toUnsignedString(end.getOffset()));
@@ -8585,10 +8704,10 @@ public final class ReaGhidraBridge extends HeadlessScript {
// writer while escaping surrogates so large replies avoid multi-x heap copies.
private static final class SurrogateEscapingWriter extends Writer {
private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
private final BufferedWriter delegate;
private final Writer delegate;
private final char[] surrogateEscape = { '\\', 'u', '0', '0', '0', '0' };
private SurrogateEscapingWriter(BufferedWriter delegate) {
private SurrogateEscapingWriter(Writer delegate) {
this.delegate = delegate;
}
+2 -2
View File
@@ -106,7 +106,7 @@ export interface WorkflowAnalysisPort extends AnalysisOperationPort {
/** Publish caveats only after admitting an observation for a workflow item. */
recordItemLimitations?(
operation: AnalysisOperation,
execution: AnalysisExecution,
execution: Pick<AnalysisExecution, "provider" | "limitations">,
): void;
}
@@ -126,7 +126,7 @@ export const executeComposedWorkflow = async (
const workScope = new AnalysisWorkScope();
const recordLimitations = (
operation: AnalysisOperation,
execution: AnalysisExecution,
execution: Pick<AnalysisExecution, "provider" | "limitations">,
): void => {
for (const limitation of execution.limitations) {
const fact = {
@@ -162,6 +162,7 @@ const harness = (options?: {
readonly addressCaveats?: boolean;
/** Addresses procedure_info classifies as external, as Ghidra does for imports. */
readonly external?: readonly string[];
readonly exportMetadata?: readonly string[];
}) => {
const procedures = options?.procedures ?? [
{ address: "0x3000", name: "Bar::late" },
@@ -169,6 +170,7 @@ const harness = (options?: {
{ address: "0x2000", name: "Foo::helper" },
];
const calls: RecordedCall[] = [];
const metadataRequests: boolean[] = [];
const port: AnalysisOperationPort = {
execute: (operation, parameters, execution) => {
calls.push({
@@ -179,14 +181,34 @@ const harness = (options?: {
? {}
: { upcoming: execution.upcomingDecompiles }),
});
if (operation === "list_procedures")
if (operation === "list_procedures") {
const enriched = execution?.includeExportBodyMetadata === true;
metadataRequests.push(enriched);
return Promise.resolve(
ok(
createAnalysisExecution(
procedures.map((procedure) => ({
address: procedure.address,
value: procedure.name,
})),
procedures.map(({ address, name }) => {
if (
!execution?.includeExportBodyMetadata ||
!options?.exportMetadata?.includes(address)
)
return { address, value: name };
const external = options.external?.includes(address) === true;
return {
address,
value: name,
procedure: { external, thunk: false, thunk_target: null },
export_body_metadata: {
body: (external
? externalInfoFor(address)
: infoFor(address)
).body,
limitations: options.addressCaveats
? [`info caveat at ${address}`]
: [],
},
};
}),
provider,
{
analysisProfile: options?.listProfile ?? profile,
@@ -198,6 +220,7 @@ const harness = (options?: {
),
),
);
}
if (operation === "procedure_info") {
if (options?.info === "unavailable")
return Promise.resolve(
@@ -273,7 +296,13 @@ const harness = (options?: {
return Promise.resolve(err(new AnalysisInputError(operation)));
},
};
return { calls, port, tools: new EnhancedTools(port), procedures };
return {
calls,
port,
tools: new EnhancedTools(port),
procedures,
metadataRequests,
};
};
const run = (
@@ -469,6 +498,50 @@ describe("decompile_all inventory limitations", () => {
describe("decompile_all external functions", () => {
const directory = useOutputDirectory();
it("reuses inventory body facts, falls back for uncovered rows, and resumes the same export", async () => {
const options = { external: ["0x1000"], addressCaveats: true };
const baseline = harness(options);
const optimized = harness({
...options,
exportMetadata: ["0x1000", "0x2000"],
});
const baselinePath = join(
await createTestTempDirectory("rea-decompile-reference-"),
"out",
);
for (const [fixture, path] of [
[baseline, baselinePath],
[optimized, directory()],
] as const) {
const first = await run(fixture.tools, path);
expect(first.ok).toBe(true);
const second = await run(fixture.tools, path, { resume: true });
expect(second.ok).toBe(true);
}
expect(
of(baseline.calls, "procedure_info").map(({ procedure }) => procedure),
).toEqual(["0x1000", "0x2000", "0x3000"]);
expect(
of(optimized.calls, "procedure_info").map(({ procedure }) => procedure),
).toEqual(["0x3000"]);
for (const path of [
DECOMPILE_DIRECTORY_INDEX_NAME,
DECOMPILE_DIRECTORY_JOURNAL_NAME,
"functions/0x2000.c",
"functions/0x3000.c",
])
expect(await readFile(join(directory(), path), "utf8")).toBe(
await readFile(join(baselinePath, path), "utf8"),
);
});
it("avoids computing full inventory metadata for limited exports", async () => {
const limited = harness({ exportMetadata: ["0x1000", "0x2000", "0x3000"] });
expect((await run(limited.tools, directory(), { limit: 1 })).ok).toBe(true);
expect(limited.metadataRequests).toEqual([false]);
expect(of(limited.calls, "procedure_info")).toHaveLength(1);
});
it("reports an external function as external without requesting its pseudocode", async () => {
const { calls, tools } = harness({ external: ["0x1000", "0x2000"] });
const result = await run(tools, directory());
@@ -37,8 +37,9 @@ import {
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { functionBodyEntryAgrees } from "../../domain/native/functionBody.js";
import { procedureInfoSchema } from "../../domain/native/procedureInfo.js";
import { listProceduresFact } from "../../domain/native/nativeOperationFacts.js";
import { decompileExportInventoryFact } from "../../domain/native/nativeOperationFacts.js";
import { executeFact } from "../AnalysisOperationFacts.js";
import { addressCoordinate } from "../../domain/native/addressCoordinate.js";
import type { JsonValue } from "../../domain/jsonValue.js";
@@ -167,7 +168,7 @@ export const decompileAll = async (
);
if (!placement.ok) return placement;
if (isAborted(signal)) return err(cancelledBy("decompile_all", signal));
const loaded = await loadProcedures(analysis, input.layout, signal);
const loaded = await loadProcedures(analysis, input, signal);
if (!loaded.ok) return loaded;
if (isAborted(signal)) return err(cancelledBy("decompile_all", signal));
const selection = selectProcedures(
@@ -327,7 +328,7 @@ const attemptOrder = (
const loadProcedures = async (
analysis: AnalysisOperationPort,
layout: DecompileDirectoryInput["layout"],
input: DecompileDirectoryInput,
signal: AbortSignal | undefined,
): Promise<
Result<
@@ -340,14 +341,24 @@ const loadProcedures = async (
AnalysisError
>
> => {
const options = executionOptions(signal);
// Selected and resumed exports may need only a few bodies. Keep their
// per-function reads so verified or excluded functions incur no body work.
const enrich =
!input.resume &&
input.limit === undefined &&
input.name === undefined &&
input.namespace === undefined &&
input.address_start === undefined &&
input.address_end === undefined;
const inventory = await executeFact(
analysis,
listProceduresFact,
decompileExportInventoryFact,
{},
executionOptions(signal),
enrich ? { ...options, includeExportBodyMetadata: true } : options,
);
if (!inventory.ok) return inventory;
const identity = identityFrom(inventory.value.execution, layout);
const identity = identityFrom(inventory.value.execution, input.layout);
if (!identity.ok) return identity;
// An empty address cannot name a file or a journal record.
const addressed = inventory.value.fact.filter(
@@ -357,6 +368,16 @@ const loadProcedures = async (
procedures: addressed.map((row) => ({
address: row.address,
name: row.value.length === 0 ? null : row.value,
...(row.export_body_metadata !== undefined &&
row.procedure !== undefined &&
functionBodyEntryAgrees(row.export_body_metadata.body, row.address)
? {
exportBodyMetadata: {
...row.export_body_metadata,
external: row.procedure.external,
},
}
: {}),
})),
identity: identity.value,
unaddressed: inventory.value.fact.length - addressed.length,
@@ -992,14 +1013,29 @@ const observeOne = async (input: {
readonly state: PublishState;
readonly providerWait: ProviderWait;
}): Promise<Attempt> => {
const body = await readBody(
input.analysis,
input.procedure.address,
input.identity,
input.signal,
input.bodySupport,
input.providerWait,
);
const metadata = input.procedure.exportBodyMetadata;
if (metadata !== undefined)
input.analysis.recordItemLimitations?.("procedure_info", {
provider: input.identity.provider,
limitations: metadata.limitations,
});
const body =
metadata === undefined
? await readBody(
input.analysis,
input.procedure.address,
input.identity,
input.signal,
input.bodySupport,
input.providerWait,
)
: {
kind: "body" as const,
fact: metadata.body,
support: input.bodySupport,
limitations: metadata.limitations,
...(metadata.external ? { external: true as const } : {}),
};
if (body.kind === "error")
return {
outcome: { kind: "stopped", error: body.error },
@@ -1,3 +1,5 @@
import type { z } from "zod";
import type { exportBodyMetadataSchema } from "../../domain/native/nativeOperationFacts.js";
import type { DecompileDirectoryInput } from "../../contracts/decompileDirectory.js";
import {
addressCoordinate,
@@ -12,6 +14,9 @@ import { decompileInputError } from "./inputError.js";
export interface SelectedProcedure {
readonly address: string;
readonly name: string | null;
readonly exportBodyMetadata?: z.infer<typeof exportBodyMetadataSchema> & {
readonly external: boolean;
};
}
interface AddressBound {
+17 -1
View File
@@ -1,4 +1,5 @@
import type { z } from "zod";
import { z } from "zod";
import { functionBodySchema } from "./functionBody.js";
import { nativeInventoryRowsSchemas } from "./nativeInventory.js";
import { containingProcedureResolutionSchema } from "./nativeObservation.js";
@@ -32,6 +33,21 @@ export const listProceduresFact = factContract(
"procedure inventory",
nativeInventoryRowsSchemas.names,
);
export const exportBodyMetadataSchema = z.strictObject({
body: functionBodySchema,
limitations: z.array(z.string()),
});
export const decompileExportInventoryFact = factContract(
"list_procedures",
"procedure inventory for decompile export",
z.array(
nativeInventoryRowsSchemas.names.element.extend({
export_body_metadata: exportBodyMetadataSchema.exactOptional(),
}),
),
);
export const searchProceduresFact = factContract(
"search_procedures",
"procedure search result",
+15 -5
View File
@@ -134,11 +134,25 @@ export class GhidraWire {
),
);
const timeoutMs = options.timeoutMs;
const limits =
options.limits === undefined ? this.admitLimits() : ok(options.limits);
if (!limits.ok) return limits;
const { requestLimit, replyLimit } = limits.value;
const payloadValue = {
id,
token,
method,
params,
params:
method === "list_procedures" &&
params !== null &&
typeof params === "object" &&
!Array.isArray(params) &&
params.export_body_metadata === true
? {
...params,
export_body_metadata: replyLimit.maximumBytes,
}
: params,
...(options.decompileTimeoutSeconds === undefined
? {}
: { decompile_timeout_seconds: options.decompileTimeoutSeconds }),
@@ -152,10 +166,6 @@ export class GhidraWire {
? {}
: { decompile_read_ahead: [...options.decompileReadAhead] }),
};
const limits =
options.limits === undefined ? this.admitLimits() : ok(options.limits);
if (!limits.ok) return limits;
const { requestLimit, replyLimit } = limits.value;
const payloadBytes = jsonValueByteLength(
payloadValue,
requestLimit.maximumBytes,
+7 -5
View File
@@ -42,7 +42,6 @@ import {
swiftSmallStringLiteralOmissionSchema,
swiftLargeStringLiteralOmissionSchema,
} from "../domain/native/swiftStringLiteral.js";
import { functionBodyEntryAgrees } from "../domain/native/functionBody.js";
import { ownedJsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
import type { EvidenceLocation } from "../domain/evidence.js";
import {
@@ -57,6 +56,7 @@ import {
ghidraInputAddressSchema,
ghidraFunctionClassificationSchema as classification,
ghidraFunctionBodySchema as ghidraFunctionBody,
ghidraProcedureBodyEntryAgrees,
ghidraProcedureIdentitySchema as procedureIdentity,
ghidraFunctionIdentitySchema as dossierProcedureIdentity,
} from "./GhidraInventoryValues.js";
@@ -192,10 +192,12 @@ const procedureInfo = procedureInfoSchema
.strict()
.superRefine((value, context) => {
if (
!functionBodyEntryAgrees(value.body, value.entrypoint) ||
(value.body.available &&
(value.length !== value.body.total_bytes ||
(!value.classification.external && !value.body.contains_entry)))
!ghidraProcedureBodyEntryAgrees(
value.body,
value.entrypoint,
value.classification.external,
) ||
value.length !== value.body.total_bytes
)
context.addIssue({
code: "custom",
+27 -1
View File
@@ -3,6 +3,7 @@ import {
parseGhidraAddressNameResult,
} from "./GhidraAddressNameValues.js";
import { GHIDRA_INVENTORY_OPERATIONS } from "./GhidraInventoryOperations.js";
import { exportBodyMetadataSchema } from "../domain/native/nativeOperationFacts.js";
import { nativeSearchFields } from "../domain/native/nativeSearch.js";
import { nativeSymbolMetadataSchema } from "../domain/native/nativeSymbol.js";
import { nativeAddressObservationSchema } from "../domain/native/nativeAddress.js";
@@ -30,6 +31,7 @@ import { outputContractDiagnostics } from "../domain/native/nativeProviderOutput
import {
availableFunctionBodySchema,
functionBodyEntryAgrees,
type functionBodySchema,
} from "../domain/native/functionBody.js";
import { procedureIdentitySchema } from "../domain/native/procedureInfo.js";
import type { JsonValue } from "../domain/jsonValue.js";
@@ -200,6 +202,15 @@ export const ghidraFunctionBodySchema = availableFunctionBodySchema.safeExtend({
),
});
/** A reported local function body must cover its own entry point. */
export const ghidraProcedureBodyEntryAgrees = (
body: z.infer<typeof functionBodySchema>,
entry: string,
external: boolean,
): boolean =>
functionBodyEntryAgrees(body, entry) &&
(!body.available || external || body.contains_entry);
/** Canonical Ghidra identity, retaining the generic dossier's name and symbol admission. */
export const ghidraFunctionIdentitySchema = procedureIdentitySchema
.safeExtend({
@@ -349,7 +360,22 @@ const resultSchemas = {
address_name: z.string().nullable(),
list_documents: z.array(z.string().min(1)).length(1),
list_names: z.array(symbolItem),
list_procedures: z.array(procedureItem),
list_procedures: z.array(
procedureItem
.extend({ export_body_metadata: z.unknown().exactOptional() })
.transform(({ export_body_metadata: advisory, ...row }) => {
if (advisory === undefined) return row;
const parsed = exportBodyMetadataSchema.safeParse(advisory);
return parsed.success &&
ghidraProcedureBodyEntryAgrees(
parsed.data.body,
row.address,
row.procedure.external,
)
? { ...row, export_body_metadata: parsed.data }
: row;
}),
),
list_segments: z.array(segment),
list_strings: z.array(stringItem),
procedure_address: nativeAddressObservationSchema,
+140
View File
@@ -1463,6 +1463,146 @@ it("reobserves value-flow budgets on the same session while ordinary address loo
});
describe("Ghidra client projection", () => {
it("projects export inventory body caveats like a direct procedure read", async () => {
const body = {
available: true,
provenance: "ghidra-function-body-address-set",
ranges: [{ start: "0x1000", end: "0x1000" }],
total_bytes: 1,
span_bytes: 1,
non_contiguous: false,
contains_entry: true,
};
const emptyBody = {
...body,
ranges: [],
total_bytes: 0,
span_bytes: 0,
contains_entry: false,
};
const limitations = [
"Ghidra Listing reports a terminal call in the fixture.",
];
const callTool = vi.fn<ReturnType<GhidraProviderClientFactory>["callTool"]>(
async (operation) =>
operation === "list_procedures"
? ok([
{
address: "0x1000",
value: "fixture_main",
procedure: {
external: false,
thunk: false,
thunk_target: null,
},
export_body_metadata: { body, limitations },
},
{
address: "0x2000",
value: "fixture_second",
procedure: {
external: false,
thunk: false,
thunk_target: null,
},
export_body_metadata: {
body: {
...body,
ranges: [{ start: "0x2000", end: "0x2000" }],
total_bytes: 2,
},
limitations,
},
},
{
address: "0x3000",
value: "fixture_empty_local",
procedure: {
external: false,
thunk: false,
thunk_target: null,
},
export_body_metadata: { body: emptyBody, limitations },
},
{
address: "EXTERNAL:0x4000",
value: "fixture_external",
procedure: { external: true, thunk: false, thunk_target: null },
export_body_metadata: { body: emptyBody, limitations },
},
])
: ok({
value: {
name: "fixture_main",
entrypoint: "0x1000",
basicblock_count: 1,
length: 1,
signature: null,
locals: [],
classification: {
external: false,
thunk: false,
thunk_target: null,
provenance: "ghidra-function-manager",
},
body,
},
limitations,
}),
);
const client = await createElfClient(
provider(installationHost(), () => ({
start: async () => ok(sessionInfo()),
callTool,
close: async () => ok(null),
})),
);
try {
const inventory = await client.execute(
"list_procedures",
{},
{
includeExportBodyMetadata: true,
},
);
const direct = await client.execute("procedure_info", {
procedure: "0x1000",
});
expect(callTool).toHaveBeenCalledWith(
"list_procedures",
{ document: null, export_body_metadata: true },
{},
);
if (!inventory.ok) throw inventory.error;
if (!direct.ok) throw direct.error;
expect(direct.value.limitations).toEqual(
expect.arrayContaining(limitations),
);
expect(inventory.value.result).toMatchObject([
{
address: "0x1000",
export_body_metadata: { body, limitations: direct.value.limitations },
},
{ address: "0x2000", value: "fixture_second" },
{ address: "0x3000", value: "fixture_empty_local" },
{
address: "EXTERNAL:0x4000",
export_body_metadata: { body: emptyBody },
},
]);
if (!Array.isArray(inventory.value.result))
throw new Error("Expected procedure rows");
expect(inventory.value.result[1]).not.toHaveProperty(
"export_body_metadata",
);
expect(inventory.value.result[2]).not.toHaveProperty(
"export_body_metadata",
);
} finally {
await client.close();
}
});
it("commits exact provider, isolation, and resource semantics", async () => {
const toolCalls: Array<{
readonly operation: string;
+48 -3
View File
@@ -1066,6 +1066,10 @@ export const createGhidraProviderClient = (input: {
projectSessionError(operation, failure, projection),
})
: undefined;
const commonLimitations = ghidraSessionCommonLimitations(
projection.source,
cancelGrace,
);
const projectExecution = (
operation: AnalysisOperation,
normalized: JsonValue,
@@ -1089,7 +1093,7 @@ export const createGhidraProviderClient = (input: {
}),
analysisProfile: committedProfile,
...sessionScopedLimitations(
ghidraSessionCommonLimitations(projection.source, cancelGrace),
commonLimitations,
[
...ghidraOperationLimitations(operation, projection.source),
...(observation.limitations ?? []),
@@ -1101,6 +1105,7 @@ export const createGhidraProviderClient = (input: {
const inventoryExecution = (
operation: "list_documents" | "list_procedures",
called: Result<JsonValue, GhidraSessionError>,
includesExportBodyMetadata = false,
) => {
if (!called.ok)
return err(
@@ -1114,6 +1119,37 @@ export const createGhidraProviderClient = (input: {
const parsed = parseGhidraInventoryResult(operation, called.value, null);
if (!parsed.ok) return parsed;
const { value, ...observation } = parsed.value;
if (includesExportBodyMetadata && Array.isArray(value)) {
const perOperation = ghidraOperationLimitations(
"procedure_info",
projection.source,
);
const session = sessionLimitations("procedure_info");
const rows = value.map((row) => {
if (!isRecord(row) || !isRecord(row.export_body_metadata)) return row;
const metadata = row.export_body_metadata;
if (!Array.isArray(metadata.limitations)) return row;
return {
...row,
export_body_metadata: {
...metadata,
limitations: [
...commonLimitations,
...perOperation,
...metadata.limitations,
...session,
],
},
};
});
return ok(
projectExecution(
operation,
ownedJsonValueSchema.parse(rows),
observation,
),
);
}
return ok(projectExecution(operation, value, observation));
};
const loadImageExecution = async (raw: JsonValue, signal?: AbortSignal) => {
@@ -1242,7 +1278,11 @@ export const createGhidraProviderClient = (input: {
// attempt, so `callTool` reuses this launch; a restart is checked again.
const started = await startSession(operation, options);
if (!started.ok) return started;
const called = await client.callTool(operation, input.value, {
const wireInput =
operation === "list_procedures" && options?.includeExportBodyMetadata
? { ...input.value, export_body_metadata: true }
: input.value;
const called = await client.callTool(operation, wireInput, {
...operationLimits,
...(operation === "procedure_pseudo_code" &&
options?.upcomingDecompiles !== undefined
@@ -1255,7 +1295,11 @@ export const createGhidraProviderClient = (input: {
});
if (called.ok) providerStarted = true;
if (operation === "list_documents" || operation === "list_procedures")
return inventoryExecution(operation, called);
return inventoryExecution(
operation,
called,
options?.includeExportBodyMetadata === true,
);
if (!called.ok) {
const entry = await machoMainEntryHint(
called.error,
@@ -1380,6 +1424,7 @@ export const createGhidraProviderClient = (input: {
executeIfReady: async (operation, parameters, options) => {
if (operation !== "list_documents" && operation !== "list_procedures")
return undefined;
if (options?.includeExportBodyMetadata) return undefined;
if (extensionFailure !== undefined) return err(extensionFailure);
const input = parseGhidraInventoryInput(operation, parameters);
if (!input.ok) return input;
+2
View File
@@ -50,6 +50,8 @@ import {
export const UPCOMING_DECOMPILES_WINDOW = 32;
export interface ExecutionOptions {
/** Request available export-body facts with the procedure inventory. */
readonly includeExportBodyMetadata?: true;
/** Ephemeral state shared only by one composed workflow. */
readonly workScope?: AnalysisWorkScope;
/**
@@ -148,10 +148,13 @@ import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
@@ -185,6 +188,7 @@ const JAVA_GSON_STUBS = String.raw`
}
private static final class JsonArray extends JsonElement implements Iterable<JsonElement> {
private final List<JsonElement> items = new ArrayList<>();
int size() { return items.size(); }
void add(JsonElement value) { items.add(value == null ? JsonNull.INSTANCE : value); }
void add(String value) { items.add(value == null ? JsonNull.INSTANCE : new JsonPrimitive(value)); }
@Override public Iterator<JsonElement> iterator() { return items.iterator(); }
@@ -348,9 +352,23 @@ const JAVA_GSON_STUBS = String.raw`
void setUseCharArrayWrites(boolean useCharArrayWrites) {
this.useCharArrayWrites = useCharArrayWrites;
}
JsonArray toJsonTree(List<String> values) {
JsonArray array = new JsonArray();
for (String value : values) array.add(new JsonPrimitive(value));
return array;
}
JsonWriter newJsonWriter(Writer out) {
return new JsonWriter(out, this);
}
void toJson(JsonElement element, JsonWriter writer) {
try {
writer.beforeValue();
writeElement(writer.out, element);
}
catch (IOException exception) {
throw new JsonIOException(exception);
}
}
void toJson(JsonElement element, Appendable appendable) {
Writer out = (Writer) appendable;
try {
@@ -438,6 +456,26 @@ const JAVA_GHIDRA_STUBS = String.raw`
boolean isExternalAddress();
long getOffset();
String canonical();
default AddressSpace getAddressSpace() { return AddressSpace.BYTES; }
}
private enum AddressSpace {
BYTES;
int getAddressableUnitSize() { return 1; }
}
private record AddressRange(Address address) {
Address getMinAddress() { return address; }
Address getMaxAddress() { return address; }
}
private interface AddressRangeIterator extends Iterator<AddressRange> {}
private record AddressSet(Address entry) {
AddressRangeIterator getAddressRanges(boolean forward) {
Iterator<AddressRange> ranges = List.of(new AddressRange(entry)).iterator();
return new AddressRangeIterator() {
public boolean hasNext() { return ranges.hasNext(); }
public AddressRange next() { return ranges.next(); }
};
}
boolean contains(Address address) { return entry.equals(address); }
}
private record StubAddress(long offset, boolean external) implements Address {
@Override public boolean isMemoryAddress() { return !external; }
@@ -497,6 +535,7 @@ const JAVA_GHIDRA_STUBS = String.raw`
Address getEntryPoint();
String getName();
Symbol getSymbol();
default AddressSet getBody() { return new AddressSet(getEntryPoint()); }
Address[] getFunctionThunkAddresses(boolean includeExternal);
}
private static final class StubFunction implements Function {
@@ -553,8 +592,35 @@ const JAVA_GHIDRA_STUBS = String.raw`
StubSymbolTable getSymbolTable() { return symbolTable; }
StubFunctionManager getFunctionManager() { return functionManager; }
AddressFactory getAddressFactory() { return addressFactory; }
StubProgram getListing() { return this; }
List<Instruction> getInstructions(AddressSet body, boolean forward) {
return List.of(new Instruction("first caveat"), new Instruction("second caveat"));
}
}
private final StubProgram currentProgram = new StubProgram();
private record Instruction(String caveat) {
Reference[] getReferencesFrom() { return new Reference[0]; }
}
private interface Reference {
ReferenceType getReferenceType();
Address getToAddress();
}
private interface ReferenceType { boolean isRead(); }
private record LoaderInitializedRelocation(Address address) {}
private final List<LoaderInitializedRelocation> loaderInitializedRelocations = List.of();
private boolean isX86_32Program() { return false; }
private TerminalCall terminalCall(Instruction instruction) {
return new TerminalCall(instruction.caveat(), false);
}
private LoaderInitializedRelocation loaderInitializedRelocationAt(Address address) {
throw new AssertionError("No loader relocations in this probe");
}
private String loaderInitializedRelocationLimitation(LoaderInitializedRelocation relocation) {
throw new AssertionError("No loader relocations in this probe");
}
private String borlandSehHandlerLimitation(Function function, Instruction a, Instruction b, Instruction c) {
throw new AssertionError("No x86 instructions in this probe");
}
private final TaskMonitor monitor = new TaskMonitor();
private List<ProcedureEntry> procedureInventory;
private Map<String, Object> procedureNameIndex;
@@ -935,7 +1001,7 @@ const JAVA_PROBE_DRIVER = String.raw`
StreamingResult[] streams = new StreamingResult[] {
out -> writeNameEntries(out, names),
out -> writeProcedureEntries(out, List.of(proc1, proc2)),
out -> writeProcedureEntries(out, List.of(proc1, proc2), Map.of()),
out -> writeMatchedProcedures(out, matched),
out -> writeStringEntries(out, strings),
};
@@ -947,6 +1013,22 @@ const JAVA_PROBE_DRIVER = String.raw`
}
}
private void runExportMetadataBudget(int ceiling) throws Exception {
List<ProcedureEntry> entries = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
Address address = new StubAddress(0x1000L * i, false);
String name = "work" + i;
Function function = new StubFunction(address, name, null);
entries.add(new ProcedureEntry(function, address, name, name, true, List.of(),
new ProcedureFacts(false, false, null), null));
}
Map<ProcedureEntry, JsonObject> metadata = exportBodyMetadata(entries, ceiling);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(bytes, StandardCharsets.UTF_8));
writeStreamingSuccess(writer, 1, out -> writeProcedureEntries(out, entries, metadata));
System.out.print(Base64.getEncoder().encodeToString(bytes.toByteArray()));
}
public static void main(String[] args) throws Exception {
switch (args[0]) {
case "fold-char" -> runFoldChar();
@@ -955,6 +1037,8 @@ const JAVA_PROBE_DRIVER = String.raw`
case "spelling-match" -> runSpellingMatch();
case "write-response" -> runWriteResponse();
case "stream-inventory" -> runStreamInventory();
case "export-metadata-budget" -> new ReaGhidraBridgeHelperProbe().runExportMetadataBudget(
Integer.parseInt(new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)).readLine()));
case "surrogate-writer" -> runSurrogateWriterChecks();
case "write-failures" -> runWriteFailures();
case "resolve-procedures" -> new ReaGhidraBridgeHelperProbe().runResolveProcedures();
@@ -1018,6 +1102,21 @@ const buildBridgeProbeSource = (bridgeSource: string): string => {
literalMethods,
streamingInventoryWriters,
responseMethods,
extractBridgeSlice(
bridgeSource,
" private Map<ProcedureEntry, JsonObject> exportBodyMetadata(",
" private JsonArray listSegments(",
),
extractBridgeSlice(
bridgeSource,
" private final class FunctionBoundaryLimitations {",
" /**\n * Ghidra's Non-Returning Functions",
),
extractBridgeSlice(
bridgeSource,
" private static JsonObject functionBody(Function function) {",
" private static String exclusiveEnd(",
),
requestFailureClass,
JAVA_PROBE_DRIVER,
].join("\n");
@@ -611,3 +611,33 @@ describe.skipIf(jdk === undefined)(
});
},
);
describe.skipIf(jdk === undefined)(
"ReaGhidraBridge export metadata budget",
() => {
it("fits the reply ceiling and retains complete caveats only on enriched rows", async () => {
const ceiling = 1_700;
const output = await runBridgeProbe(
requireProbe(),
"export-metadata-budget",
String(ceiling),
);
const reply = Buffer.from(output, "base64");
expect(reply.byteLength).toBeLessThanOrEqual(ceiling);
const { result } = JSON.parse(reply.toString("utf8"));
expect(result.map(({ address }: { address: string }) => address)).toEqual(
["0x1000", "0x2000", "0x3000"],
);
expect(result[0].export_body_metadata).toEqual({
body: expect.objectContaining({
ranges: [{ start: "0x1000", end: "0x1000" }],
total_bytes: 1,
contains_entry: true,
}),
limitations: ["first caveat", "second caveat"],
});
expect(result[1]).not.toHaveProperty("export_body_metadata");
expect(result[2]).not.toHaveProperty("export_body_metadata");
});
},
);