fix(cli): resolve xrefs symbol selectors after address validation (#1209)
* fix(cli): resolve xrefs symbol selectors after address validation * style(cli): format xrefs fallback call
This commit is contained in:
@@ -45,6 +45,21 @@ export async function verifyGhidraEntryAliases({
|
||||
({ address }) => address === alias.address,
|
||||
);
|
||||
assert.ok(canonical, "Fixture alias is not at a function entry");
|
||||
const xrefsSelectors = [];
|
||||
for (const value of [
|
||||
canonical.value,
|
||||
alias.value,
|
||||
`${prefix}rea_xrefs_data`,
|
||||
`${prefix}rea_xrefs_unreferenced`,
|
||||
]) {
|
||||
const symbol = names.find((item) => item.value === value);
|
||||
assert.ok(symbol, `Missing xrefs selector ${value}`);
|
||||
const expected = await call("xrefs", { address: symbol.address });
|
||||
if (value === `${prefix}rea_xrefs_unreferenced`)
|
||||
assert.deepEqual(expected, []);
|
||||
else assert.ok(expected.length > 0, `Missing references for ${value}`);
|
||||
xrefsSelectors.push({ symbol, expected });
|
||||
}
|
||||
for (const procedure of [
|
||||
alias.value,
|
||||
"dead",
|
||||
@@ -118,6 +133,55 @@ export async function verifyGhidraEntryAliases({
|
||||
JSON.parse(stdout).normalized_result.procedure.address,
|
||||
alias.address,
|
||||
);
|
||||
for (const { symbol, expected } of xrefsSelectors) {
|
||||
for (const selector of [
|
||||
[symbol.value],
|
||||
["--address", symbol.value],
|
||||
[symbol.address],
|
||||
]) {
|
||||
const { stdout } = await exec(
|
||||
process.execPath,
|
||||
[
|
||||
entrypoint,
|
||||
"xrefs",
|
||||
path,
|
||||
...selector,
|
||||
"--provider",
|
||||
"ghidra",
|
||||
"--json",
|
||||
],
|
||||
{ env, timeout: 240000, maxBuffer: 16 * 1024 * 1024 },
|
||||
);
|
||||
const evidence = JSON.parse(stdout);
|
||||
assert.deepEqual(evidence.normalized_result, expected);
|
||||
assert.equal(evidence.parameters.address, selector.at(-1));
|
||||
}
|
||||
}
|
||||
await assert.rejects(
|
||||
exec(
|
||||
process.execPath,
|
||||
[
|
||||
entrypoint,
|
||||
"xrefs",
|
||||
path,
|
||||
"rea_missing_symbol",
|
||||
"--provider",
|
||||
"ghidra",
|
||||
"--json",
|
||||
],
|
||||
{ env, timeout: 240000, maxBuffer: 16 * 1024 * 1024 },
|
||||
),
|
||||
(error) => {
|
||||
const failure = JSON.parse(error.stdout);
|
||||
assert.equal(failure.code, "invalid_request");
|
||||
assert.equal(failure.details.operation, "xrefs");
|
||||
assert.match(
|
||||
JSON.stringify(failure.details.issues),
|
||||
/Unknown analyzed symbol name.*rea_missing_symbol/u,
|
||||
);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
assert.deepEqual(await readFile(path), bytes);
|
||||
await call("open_binary", { path: target.path, provider_id: "ghidra" });
|
||||
} finally {
|
||||
|
||||
@@ -48,6 +48,8 @@ import {
|
||||
} from "./WorkflowEvidence.js";
|
||||
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
|
||||
import { artifactInspectionResultSchema } from "../domain/artifactInspection.js";
|
||||
import { resolveXrefsAddress } from "./XrefsAddressResolution.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
|
||||
type DirectAnalysisTool =
|
||||
| "annotate_native_function"
|
||||
@@ -356,7 +358,34 @@ const executeAnalysisTool = async (input: {
|
||||
});
|
||||
return { output: evidence, evidence };
|
||||
}
|
||||
const result = await session.execute(tool, input.arguments, { signal });
|
||||
let result = await session.execute(tool, input.arguments, { signal });
|
||||
if (
|
||||
tool === "xrefs" &&
|
||||
typeof input.arguments.address === "string" &&
|
||||
!result.ok &&
|
||||
result.error instanceof AnalysisInputError &&
|
||||
!result.error.cleanupIncomplete &&
|
||||
result.error.issues.length > 0 &&
|
||||
result.error.issues.every(
|
||||
({ path, reason }) =>
|
||||
path.length === 1 &&
|
||||
path[0] === "address" &&
|
||||
reason === "invalid_format",
|
||||
)
|
||||
) {
|
||||
const address = await resolveXrefsAddress(
|
||||
session,
|
||||
input.arguments.address,
|
||||
signal,
|
||||
);
|
||||
if (!address.ok) return { output: cliError(address.error) };
|
||||
if (address.value !== input.arguments.address)
|
||||
result = await session.execute(
|
||||
tool,
|
||||
{ ...input.arguments, address: address.value },
|
||||
{ signal },
|
||||
);
|
||||
}
|
||||
if (!result.ok) return { output: cliError(result.error) };
|
||||
const evidence = createEvidence(
|
||||
result.value.subject ?? input.openedTarget,
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { addressedValue } from "../contracts/toolOutputSchemaPrimitives.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { AnalysisOperationPort } from "./AnalysisProvider.js";
|
||||
import { resolveProcedureAddress } from "./ProcedureAddressResolution.js";
|
||||
|
||||
/** Resolve a CLI symbol selector without changing existing address spellings. */
|
||||
export const resolveXrefsAddress = async (
|
||||
analysis: AnalysisOperationPort,
|
||||
selector: string,
|
||||
signal: AbortSignal,
|
||||
): Promise<Result<string, AnalysisError>> => {
|
||||
if (
|
||||
selector.length === 0 ||
|
||||
/^[0-9a-f]+$/iu.test(selector) ||
|
||||
/^0x/iu.test(selector) ||
|
||||
/:0x/iu.test(selector)
|
||||
)
|
||||
return ok(selector);
|
||||
|
||||
const inventory = await analysis.execute("list_names", {}, { signal });
|
||||
if (!inventory.ok) {
|
||||
if (
|
||||
inventory.error instanceof AnalysisCapabilityUnavailableError &&
|
||||
inventory.error.operation === "list_names" &&
|
||||
!inventory.error.cleanupIncomplete
|
||||
)
|
||||
return resolveProcedureAddress(
|
||||
async (operation, parameters, signal) => {
|
||||
const result = await analysis.execute(
|
||||
operation,
|
||||
parameters,
|
||||
signal === undefined ? {} : { signal },
|
||||
);
|
||||
return result.ok ? ok(result.value.result) : result;
|
||||
},
|
||||
selector,
|
||||
signal,
|
||||
);
|
||||
return inventory;
|
||||
}
|
||||
if (!Array.isArray(inventory.value.result))
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
"list_names",
|
||||
"Expected a symbol inventory array",
|
||||
),
|
||||
);
|
||||
|
||||
const addresses = new Set<string>();
|
||||
for (const [index, item] of inventory.value.result.entries()) {
|
||||
const parsed = addressedValue.safeParse(item);
|
||||
if (!parsed.success || parsed.data.address.length === 0)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
"list_names",
|
||||
`Invalid symbol inventory entry at index ${index}`,
|
||||
),
|
||||
);
|
||||
if (parsed.data.value === selector) addresses.add(parsed.data.address);
|
||||
}
|
||||
const [address] = addresses;
|
||||
if (addresses.size === 1 && address !== undefined) return ok(address);
|
||||
return err(
|
||||
new AnalysisInputError("xrefs", undefined, [
|
||||
{
|
||||
path: ["address"],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
addresses.size === 0
|
||||
? `Unknown analyzed symbol name ${JSON.stringify(selector)}. Use an exact analyzed name or a hexadecimal address.`
|
||||
: `Analyzed symbol name ${JSON.stringify(selector)} is ambiguous at ${[...addresses].join(", ")}. Select an exact address.`,
|
||||
},
|
||||
]),
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,238 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { runDirectAnalysis } from "../../src/application/DirectAnalysis.js";
|
||||
import type { DirectAnalysisDependencies } from "../../src/application/DirectAnalysisDependencies.js";
|
||||
import type { AnalysisError } from "../../src/domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
} from "../../src/domain/analysisErrorCore.js";
|
||||
import { parseEvidence } from "../../src/domain/evidence.js";
|
||||
import { err } from "../../src/domain/result.js";
|
||||
import { observed } from "../fixtures/analysisExecution.js";
|
||||
import {
|
||||
createBinarySessionTargets,
|
||||
createTestBinarySession,
|
||||
} from "../fixtures/binarySession.js";
|
||||
|
||||
const inventory = [
|
||||
{ address: "0x1000", value: "table_only" },
|
||||
{ address: "0x1000", value: "entry_alias" },
|
||||
{ address: "0x1000", value: "namespace::function" },
|
||||
{ address: "0x2000", value: "data_symbol" },
|
||||
{ address: "0x3000", value: "unreferenced" },
|
||||
{ address: "0x1000", value: "same_address" },
|
||||
{ address: "0x1000", value: "same_address" },
|
||||
{ address: "0x1000", value: "ambiguous" },
|
||||
{ address: "0x2000", value: "ambiguous" },
|
||||
];
|
||||
|
||||
const fixture = (
|
||||
options: {
|
||||
readonly inventoryError?: AnalysisError;
|
||||
readonly malformedInventory?: boolean;
|
||||
readonly acceptsNamedSelectors?: boolean;
|
||||
readonly xrefsError?: AnalysisInputError;
|
||||
} = {},
|
||||
) => {
|
||||
let closed = 0;
|
||||
const createSession = () =>
|
||||
createTestBinarySession(() => ({
|
||||
execute: (operation, parameters) => {
|
||||
if (operation === "list_names")
|
||||
return Promise.resolve(
|
||||
options.inventoryError !== undefined
|
||||
? err(options.inventoryError)
|
||||
: observed(
|
||||
options.malformedInventory ? "not an inventory" : inventory,
|
||||
),
|
||||
);
|
||||
if (operation === "procedure_address")
|
||||
return Promise.resolve(observed("0x1000"));
|
||||
if (operation === "xrefs") {
|
||||
if (options.xrefsError !== undefined)
|
||||
return Promise.resolve(err(options.xrefsError));
|
||||
const address = parameters.address;
|
||||
if (
|
||||
!options.acceptsNamedSelectors &&
|
||||
(typeof address !== "string" ||
|
||||
!/^(?:(?:0[xX])?[0-9a-fA-F]+|space%20name:0[xX][0-9a-fA-F]+)$/u.test(
|
||||
address,
|
||||
))
|
||||
)
|
||||
return Promise.resolve(
|
||||
err(
|
||||
new AnalysisInputError("xrefs", undefined, [
|
||||
{ path: ["address"], reason: "invalid_format" },
|
||||
]),
|
||||
),
|
||||
);
|
||||
return Promise.resolve(
|
||||
observed(address === "0x3000" ? [] : ["0x4000"]),
|
||||
);
|
||||
}
|
||||
return Promise.resolve(observed(null));
|
||||
},
|
||||
close: () => {
|
||||
closed += 1;
|
||||
return Promise.resolve();
|
||||
},
|
||||
}));
|
||||
const dependencies: DirectAnalysisDependencies = {
|
||||
createBinarySession: createSession,
|
||||
createManagedBinarySession: createSession,
|
||||
};
|
||||
return { dependencies, closed: () => closed };
|
||||
};
|
||||
|
||||
describe("direct CLI cross-reference selectors", () => {
|
||||
it("retains validation issues unrelated to symbol resolution", async () => {
|
||||
const [path] = await createBinarySessionTargets();
|
||||
const issues = [
|
||||
{ path: ["address"], reason: "invalid_format" },
|
||||
{ path: ["extra"], reason: "unknown_argument" },
|
||||
] as const;
|
||||
const provider = fixture({
|
||||
xrefsError: new AnalysisInputError("xrefs", undefined, issues),
|
||||
});
|
||||
const result = await runDirectAnalysis(
|
||||
provider.dependencies,
|
||||
path,
|
||||
"xrefs",
|
||||
{ address: "table_only", extra: true },
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { operation: "xrefs", issues },
|
||||
});
|
||||
expect(provider.closed()).toBe(1);
|
||||
});
|
||||
it.each(["hidden_alias", "dead"])(
|
||||
"retains the provider's existing interpretation of %s",
|
||||
async (address) => {
|
||||
const [path] = await createBinarySessionTargets();
|
||||
const provider = fixture({
|
||||
acceptsNamedSelectors: true,
|
||||
malformedInventory: true,
|
||||
});
|
||||
const evidence = parseEvidence(
|
||||
await runDirectAnalysis(provider.dependencies, path, "xrefs", {
|
||||
address,
|
||||
}),
|
||||
);
|
||||
expect(evidence.parameters).toEqual({ address });
|
||||
expect(evidence.normalized_result).toEqual(["0x4000"]);
|
||||
expect(provider.closed()).toBe(1);
|
||||
},
|
||||
);
|
||||
it.each([
|
||||
"table_only",
|
||||
"entry_alias",
|
||||
"namespace::function",
|
||||
"data_symbol",
|
||||
"same_address",
|
||||
"0x1000",
|
||||
"1000",
|
||||
"0X1000",
|
||||
"space%20name:0x1000",
|
||||
])(
|
||||
"inspects %s and retains the original selector in Evidence",
|
||||
async (address) => {
|
||||
const [path] = await createBinarySessionTargets();
|
||||
const provider = fixture();
|
||||
const evidence = parseEvidence(
|
||||
await runDirectAnalysis(provider.dependencies, path, "xrefs", {
|
||||
address,
|
||||
}),
|
||||
);
|
||||
expect(evidence.parameters).toEqual({ address });
|
||||
expect(evidence.normalized_result).toEqual(["0x4000"]);
|
||||
expect(provider.closed()).toBe(1);
|
||||
},
|
||||
);
|
||||
|
||||
it("distinguishes a resolved unreferenced symbol from an unknown name", async () => {
|
||||
const [path] = await createBinarySessionTargets();
|
||||
const provider = fixture();
|
||||
const empty = parseEvidence(
|
||||
await runDirectAnalysis(provider.dependencies, path, "xrefs", {
|
||||
address: "unreferenced",
|
||||
}),
|
||||
);
|
||||
expect(empty.normalized_result).toEqual([]);
|
||||
const missing = await runDirectAnalysis(
|
||||
provider.dependencies,
|
||||
path,
|
||||
"xrefs",
|
||||
{
|
||||
address: "missing_symbol",
|
||||
},
|
||||
);
|
||||
expect(missing).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { operation: "xrefs", issues: [{ path: ["address"] }] },
|
||||
});
|
||||
expect(JSON.stringify(missing)).toContain("missing_symbol");
|
||||
expect(provider.closed()).toBe(2);
|
||||
});
|
||||
|
||||
it("reports every candidate for an ambiguous exact name", async () => {
|
||||
const [path] = await createBinarySessionTargets();
|
||||
const provider = fixture();
|
||||
const result = await runDirectAnalysis(
|
||||
provider.dependencies,
|
||||
path,
|
||||
"xrefs",
|
||||
{
|
||||
address: "ambiguous",
|
||||
},
|
||||
);
|
||||
expect(result).toMatchObject({ code: "invalid_request" });
|
||||
expect(JSON.stringify(result)).toContain("0x1000");
|
||||
expect(JSON.stringify(result)).toContain("0x2000");
|
||||
expect(provider.closed()).toBe(1);
|
||||
});
|
||||
|
||||
it("uses procedure resolution when the provider has no symbol inventory", async () => {
|
||||
const [path] = await createBinarySessionTargets();
|
||||
const provider = fixture({
|
||||
inventoryError: new AnalysisCapabilityUnavailableError(
|
||||
"fixture",
|
||||
"list_names",
|
||||
"only procedure inventory is supported",
|
||||
),
|
||||
});
|
||||
const evidence = parseEvidence(
|
||||
await runDirectAnalysis(provider.dependencies, path, "xrefs", {
|
||||
address: "table_only",
|
||||
}),
|
||||
);
|
||||
expect(evidence.parameters).toEqual({ address: "table_only" });
|
||||
expect(evidence.normalized_result).toEqual(["0x4000"]);
|
||||
expect(provider.closed()).toBe(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
options: { inventoryError: new AnalysisCancelledError("list_names") },
|
||||
code: "cancelled",
|
||||
},
|
||||
{ options: { malformedInventory: true }, code: "unreadable_output" },
|
||||
])(
|
||||
"preserves $code from inventory resolution and releases the session",
|
||||
async ({ options, code }) => {
|
||||
const [path] = await createBinarySessionTargets();
|
||||
const provider = fixture(options);
|
||||
const result = await runDirectAnalysis(
|
||||
provider.dependencies,
|
||||
path,
|
||||
"xrefs",
|
||||
{
|
||||
address: "table_only",
|
||||
},
|
||||
);
|
||||
expect(result).toMatchObject({ code });
|
||||
expect(provider.closed()).toBe(1);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -5,10 +5,13 @@
|
||||
#define REA_SYMBOL(name) name
|
||||
#endif
|
||||
|
||||
volatile int rea_xrefs_data = 17;
|
||||
__attribute__((used)) volatile int rea_xrefs_unreferenced = 41;
|
||||
|
||||
__attribute__((noinline, used)) int rea_alias_target(void) {
|
||||
__asm__ volatile(".globl " REA_SYMBOL("rea_interior") "\n"
|
||||
REA_SYMBOL("rea_interior") ":");
|
||||
return 17;
|
||||
return rea_xrefs_data;
|
||||
}
|
||||
|
||||
__asm__(".globl " REA_SYMBOL("rea_entry_alias") "\n"
|
||||
|
||||
Reference in New Issue
Block a user