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:
记得吃中饭
2026-10-13 18:23:17 +08:00
committed by GitHub
parent ec3db37457
commit 2995ec6910
34 changed files with 1588 additions and 86 deletions
@@ -12,6 +12,38 @@ const selectors = [
] as const;
describe("CLI analysis selector boundaries", () => {
cliTest(
"accepts file offsets and rejects mixed coordinate selectors before opening a target",
async ({ cli }) => {
const selected = await cli.run({
arguments: [
"decompile",
"does-not-exist",
"--file-offset=0x210",
"--json",
],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(selected.json).toMatchObject({ code: "target_unavailable" });
const conflicting = await cli.run({
arguments: [
"decompile",
"does-not-exist",
"0x140001010",
"--file-offset=0x210",
"--json",
],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(conflicting.json).toMatchObject({
code: "invalid_request",
details: {
operation: "procedure_pseudo_code",
issues: [{ path: ["file-offset"], reason: "invalid_value" }],
},
});
},
);
cliTest(
"rejects missing and conflicting selectors before opening a target",
async ({ cli }) => {
@@ -8,6 +8,7 @@ import {
writeFile,
} from "node:fs/promises";
import { dirname, join, matchesGlob } from "node:path";
import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, expect, it } from "vitest";
import { parse } from "yaml";
@@ -85,7 +86,7 @@ async function classify(
await writeFile(output, "");
const result = await execFileAsync(
process.execPath,
[new URL("../../../scripts/ci/plan.mjs", import.meta.url).pathname],
[fileURLToPath(new URL("../../../scripts/ci/plan.mjs", import.meta.url))],
{
cwd: directory,
env: {
@@ -658,8 +659,9 @@ it.each([
);
it("rejects skipped selected work while allowing unselected lanes to skip", async () => {
const command = new URL("../../../scripts/ci/required.mjs", import.meta.url)
.pathname;
const command = fileURLToPath(
new URL("../../../scripts/ci/required.mjs", import.meta.url),
);
const jobs = {
changes: { result: "success", outputs: { evm: "true" } },
static: { result: "success" },
@@ -144,14 +144,26 @@ describe("enhanced MCP tools", () => {
);
expect(result).toEqual({
document: "fixture",
image_base: "0x1000",
segments: [
{ name: "__TEXT", start: "0x1000", end: "0x1800", length: 2048 },
{ name: "__DATA", start: "0x1800", end: "0x2000", length: 2048 },
{
name: "__TEXT",
start: "0x1000",
end: "0x1800",
length: 2048,
image_base: "0x1000",
},
{
name: "__DATA",
start: "0x1800",
end: "0x2000",
length: 2048,
image_base: "0x1000",
},
],
segment_count: 2,
procedure_count: 2,
string_count: 700,
image_base: "0x1000",
});
});
@@ -0,0 +1,121 @@
import { afterEach, expect, it } from "vitest";
import { Ajv2020 } from "ajv/dist/2020.js";
import type { AnySchemaObject } from "ajv";
import {
closeEnhancedToolResources,
connect,
jsonResult,
} from "./enhancedToolsHarness.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import type { SegmentSummary } from "../../../src/domain/hopperValues.js";
afterEach(closeEnhancedToolResources);
const segment = {
name: ".text",
start: "0x101000",
end: "0x101100",
readable: true,
writable: false,
executable: true,
image_base: "0x100000",
address_space: "ram",
};
const overviewClient = (segments: SegmentSummary[]) =>
connect({
execute: (name) => {
switch (name) {
case "current_document":
return Promise.resolve(ok("fixture"));
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_segments":
return Promise.resolve(ok(segments));
case "list_procedures":
return Promise.resolve(ok([{ address: "0x101013", value: "entry" }]));
case "list_strings":
return Promise.resolve(ok([]));
default:
throw new Error(`Unexpected operation: ${name}`);
}
},
});
it("preserves observed coordinates and main's optional-string output contract after SDK conversion", async () => {
const client = await overviewClient([segment]);
const schema = (await client.listTools()).tools.find(
({ name }) => name === "binary_overview",
)?.outputSchema;
if (schema === undefined) throw new Error("Missing overview output schema");
const validate = new Ajv2020({ strict: false }).compile(
schema as AnySchemaObject,
);
const response = await client.callTool({
name: "binary_overview",
arguments: {},
});
expect(validate(response.structuredContent)).toBe(true);
expect(jsonResult(response)).toMatchObject({
image_base: "0x100000",
segments: [
{ start: "0x101000", image_base: "0x100000", address_space: "ram" },
],
});
const absent = JSON.parse(JSON.stringify(response.structuredContent));
delete absent.normalized_result.image_base;
expect(validate(absent)).toBe(true);
absent.normalized_result.image_base = null;
expect(validate(absent)).toBe(false);
});
it("omits unreported bases without inventing zero and preserves explicit zero", async () => {
const { image_base: _base, ...unreported } = segment;
const client = await overviewClient([unreported]);
expect(
jsonResult(
await client.callTool({ name: "binary_overview", arguments: {} }),
),
).not.toHaveProperty("image_base");
const zero = await overviewClient([{ ...segment, image_base: "0x0" }]);
expect(
jsonResult(await zero.callTool({ name: "binary_overview", arguments: {} })),
).toMatchObject({ image_base: "0x0" });
});
it("keeps a partially reported base unknown while retaining the reported segment observation", async () => {
const { image_base: _base, ...unreported } = segment;
const client = await overviewClient([
segment,
{ ...unreported, name: ".data" },
]);
const result = jsonResult(
await client.callTool({ name: "binary_overview", arguments: {} }),
);
expect(result).not.toHaveProperty("image_base");
expect(result).toMatchObject({
segments: [{ image_base: "0x100000" }, { name: ".data" }],
});
});
it("retains all conflicting observations after repeated early bases without selecting one", async () => {
const { address_space: _space, ...unreported } = segment;
const client = await overviewClient([
...Array.from({ length: 40 }, () => unreported),
{
...segment,
name: ".data",
start: "other%20space:0x201000",
end: "other%20space:0x201100",
image_base: "0x200000",
address_space: "other space",
},
]);
const result = jsonResult(
await client.callTool({ name: "binary_overview", arguments: {} }),
);
expect(result).not.toHaveProperty("image_base");
expect(result).toHaveProperty("segments.length", 41);
expect(result).toHaveProperty("segments.40.image_base", "0x200000");
expect(result).toHaveProperty("segments.40.address_space", "other space");
expect(result).not.toHaveProperty("segments.0.address_space");
});
@@ -0,0 +1,7 @@
__attribute__((noinline)) int rea_pie_add(int value) {
return value + 7;
}
int rea_pie_entry(void) {
return rea_pie_add(35);
}
@@ -0,0 +1,118 @@
//@category REA Verification
import java.io.ByteArrayInputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import ghidra.app.script.GhidraScriptUtil;
import ghidra.app.util.headless.HeadlessScript;
import ghidra.program.model.address.AddressSet;
import ghidra.program.model.listing.Function;
import ghidra.program.model.symbol.SourceType;
import ghidra.app.decompiler.DecompInterface;
import ghidra.app.decompiler.DecompileResults;
import ghidra.app.decompiler.DecompileProcess.DisposeState;
import ghidra.util.task.TaskMonitor;
/** Real source-identity cases unavailable through ordinary single-file CLI imports. */
public final class ReaFileOffsetSourceProbe extends HeadlessScript {
@Override
public void run() throws Exception {
var file = GhidraScriptUtil.findScriptByName("ReaGhidraBridge.java");
var bridge = GhidraScriptUtil.getProvider(file).getScriptInstance(file, new PrintWriter(System.out, true));
bridge.set(state, monitor, new PrintWriter(System.out, true));
var space = bridge.getClass().getDeclaredField("sessionDefaultAddressSpace");
space.setAccessible(true);
space.set(null, currentProgram.getAddressFactory().getDefaultAddressSpace());
var identity = bridge.getClass().getDeclaredField("admittedTargetSha256");
identity.setAccessible(true);
identity.set(bridge, currentProgram.getExecutableSHA256().toLowerCase(Locale.ROOT));
var resolve = bridge.getClass().getDeclaredMethod("resolveDecompileProcedure", String.class, JsonObject.class);
resolve.setAccessible(true);
var reverse = bridge.getClass().getDeclaredMethod("addressToFileOffset", JsonObject.class);
reverse.setAccessible(true);
var memory = currentProgram.getMemory();
var original = memory.getAllFileBytes().get(0);
byte[] bytes = new byte[Math.toIntExact(original.getSize())];
require(original.getOriginalBytes(0, bytes) == bytes.length, "complete fixture source");
byte[] auxiliary = new byte[0x1000];
auxiliary[0x910] = (byte)0xc3;
var foreign = memory.createFileBytes("auxiliary.bin", 0, auxiliary.length,
new ByteArrayInputStream(auxiliary), monitor);
var address = toAddr(0x140100000L);
memory.createInitializedBlock("auxiliary", address, foreign, 0, auxiliary.length, false);
var entry = address.add(0x910);
currentProgram.getFunctionManager().createFunction("foreign_only", entry,
new AddressSet(entry), SourceType.USER_DEFINED);
rejected(resolve, bridge, "no loaded source mapping", "file-offset:0x910", new JsonObject());
rejected(reverse, bridge, "0 authoritative target-file mappings", reverseInput("0x140100910"));
// A source object's declared original-file start does not make its local
// offsets a complete, digest-matched target representation.
var partial = memory.createFileBytes("partial.bin", 0x200, 0x200,
new ByteArrayInputStream(bytes, 0x200, 0x200), monitor);
memory.createInitializedBlock("partial", toAddr(0x140300000L), partial, 0, 0x200, false);
rejected(reverse, bridge, "0 authoritative target-file mappings", reverseInput("0x140300010"));
var selected = (Function)resolve.invoke(bridge, "file-offset:0x210", new JsonObject());
require(selected.getEntryPoint().equals(toAddr(0x140001010L)), "original target selected despite other sources");
var mapped = (JsonObject)reverse.invoke(bridge, reverseInput("0x140001010"));
require(mapped.get("file_offset").getAsLong() == 0x210, "original target round trip");
// Inject backend failures after real source/function resolution. This
// verifies context propagation, not a naturally failing decompiler.
var pseudocode = bridge.getClass().getDeclaredMethod("procedurePseudocode", JsonObject.class);
pseudocode.setAccessible(true);
var decompiler = bridge.getClass().getDeclaredField("decompiler");
decompiler.setAccessible(true);
JsonObject request = new JsonObject();
request.add("document", JsonNull.INSTANCE);
request.addProperty("procedure", "file-offset:0x210");
for (DisposeState disposition : new DisposeState[] { DisposeState.NOT_DISPOSED, DisposeState.DISPOSED_ON_CANCEL }) {
decompiler.set(bridge, new DecompInterface() {
@Override
public DecompileResults decompileFunction(Function function, int timeout, TaskMonitor taskMonitor) {
return new DecompileResults(function, currentProgram.getLanguage(),
currentProgram.getCompilerSpec(), null, "Injected backend failure", null, disposition);
}
});
Throwable failure = rejected(pseudocode, bridge,
"Selector file-offset:0x210 mapped to analysis address 0x140001010 and procedure 0x140001010", request);
var code = failure.getClass().getDeclaredField("code");
code.setAccessible(true);
require(code.get(failure).equals(disposition == DisposeState.DISPOSED_ON_CANCEL
? "decompile_cancelled" : "decompile_failed"), "backend failure code retained");
}
var duplicate = memory.createFileBytes("duplicate.bin", 0, bytes.length,
new ByteArrayInputStream(bytes), monitor);
memory.createInitializedBlock("duplicate", toAddr(0x140201000L), duplicate, 0x200, 0x200, false);
rejected(resolve, bridge, "multiple loaded mappings", "file-offset:0x210", new JsonObject());
println("REA_FILE_OFFSET_SOURCE_OK foreign/partial rejected; original round trip; duplicate ambiguity; injected backend failure context retained");
}
private JsonObject reverseInput(String address) {
JsonObject params = new JsonObject();
params.add("document", JsonNull.INSTANCE);
params.addProperty("address", address);
return params;
}
private Throwable rejected(Method method, Object bridge, String reason, Object... arguments) throws Exception {
try {
method.invoke(bridge, arguments);
} catch (InvocationTargetException rejected) {
require(rejected.getCause().getMessage().contains(reason), "expected mapping failure: " + reason);
return rejected.getCause();
}
throw new AssertionError("Expected mapping failure: " + reason);
}
private void require(boolean condition, String message) {
if (!condition) throw new AssertionError(message);
}
}
@@ -0,0 +1,90 @@
import { join } from "node:path";
import { expect, it, vi } from "vitest";
import { buildNativeAotFixture } from "../../../scripts/lib/nativeaot-build.mjs";
const options = {
dotnet: "dotnet",
project: "fixture.csproj",
runtime: "win-x64",
output: "fixture-output",
};
it("restores the exact publish target before compiling without network restore", async () => {
const run = vi.fn<(command: string, args: string[]) => void>();
await buildNativeAotFixture(run, options);
expect(run).toHaveBeenCalledTimes(2);
const restore = run.mock.calls[0]?.[1] ?? [];
const publish = run.mock.calls[1]?.[1] ?? [];
expect(restore[0]).toBe("restore");
expect(publish[0]).toBe("publish");
expect(publish).toContain("--no-restore");
for (const argument of [
options.project,
options.runtime,
"-p:Configuration=Release",
`-p:BaseIntermediateOutputPath=${join(options.output, "obj")}/`,
]) {
expect(restore).toContain(argument);
expect(publish).toContain(argument);
}
});
it("retries without logging credential-bearing restore diagnostics", async () => {
const logged = vi.spyOn(console, "error").mockImplementation(() => {});
const timeout = Object.assign(
new Error(
"dotnet restore ETIMEDOUT https://fixture-user:fixture-password@feed.invalid/v3/index.json",
),
{
code: "ETIMEDOUT",
},
);
const run = vi
.fn<(command: string, args: string[]) => void>()
.mockImplementationOnce(() => {
throw timeout;
});
try {
await buildNativeAotFixture(run, options);
expect(
logged.mock.calls.flat().every((value) => typeof value === "string"),
).toBe(true);
expect(logged.mock.calls.flat().join("\n")).not.toContain(
"fixture-password",
);
} finally {
logged.mockRestore();
}
expect(run.mock.calls.map((call) => call[1][0])).toEqual([
"restore",
"restore",
"publish",
]);
});
it("stops after two restore failures and preserves the final diagnostic", async () => {
const failure = new Error("NuGet source unavailable");
const run = vi.fn<(command: string, args: string[]) => void>(() => {
throw failure;
});
await expect(buildNativeAotFixture(run, options)).rejects.toMatchObject({
message: "NativeAOT dependency restore failed after two attempts",
cause: failure,
});
expect(run).toHaveBeenCalledTimes(2);
expect(run.mock.calls.every((call) => call[1][0] === "restore")).toBe(true);
});
it("does not retry compilation failures", async () => {
const failure = new Error("Native compiler rejected the fixture");
const run = vi
.fn<(command: string, args: string[]) => void>()
.mockImplementationOnce(() => {})
.mockImplementationOnce(() => {
throw failure;
});
await expect(buildNativeAotFixture(run, options)).rejects.toBe(failure);
expect(run).toHaveBeenCalledTimes(2);
});
@@ -0,0 +1,150 @@
import { execFile } from "node:child_process";
import { readdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import {
nativeAotCommandError,
supportsNativeAotFixtureHost,
} from "../../../scripts/lib/nativeaot-build.mjs";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const generator = fileURLToPath(
new URL("../../../scripts/generate-nativeaot-fixtures.mjs", import.meta.url),
);
const supportedHost = supportsNativeAotFixtureHost(
process.platform,
process.arch,
);
it.skipIf(!supportedHost).each(["restore", "publish"])(
"redacts authenticated feed URLs from the uncaught %s diagnostic",
async (operation) => {
const directory = await createTestTempDirectory(
"rea-nativeaot-diagnostic-",
);
const hook = join(directory, "child-output.cjs");
await writeFile(
hook,
`
const child = require("node:child_process");
child.spawnSync = (_command, args) => {
if (args[0] === "--version") return { status: 0, stdout: "8.0.416\\n", stderr: "" };
if (args[0] === ${JSON.stringify(operation)}) return {
status: 1,
error: new Error("failed HTTPS://error-user:error-secret@feed.invalid/v3/index.json"),
stdout: "NU1301 https://stdout-user:stdout-secret@feed.invalid/v3/index.json\\n",
stderr: "source https://stderr-user:stderr-secret%40suffix@feed.invalid/v3/index.json\\nkeep https://feed.invalid/path/user@name?label=token-name\\n"
};
return { status: 0, stdout: "", stderr: "" };
};
require("node:module").syncBuiltinESMExports();
`,
"utf8",
);
const failure = await promisify(execFile)(
process.execPath,
["--require", hook, generator],
{
env: {
...process.env,
REA_NATIVEAOT_FIXTURE_ROOT: join(directory, "output"),
},
timeout: 15_000,
},
).then(
() => {
throw new Error("Expected fixture generation to fail");
},
(error: { stderr: string; code: number }) => error,
);
expect(failure.code).toBe(1);
for (const secret of [
"error-user",
"error-secret",
"stdout-user",
"stdout-secret",
"stderr-user",
"stderr-secret",
])
expect(failure.stderr).not.toContain(secret);
expect(failure.stderr).toContain("NU1301");
expect(failure.stderr).toContain("feed.invalid/v3/index.json");
expect(failure.stderr).toContain(
"https://feed.invalid/path/user@name?label=token-name",
);
if (operation === "restore") {
expect(failure.stderr).toContain("attempt 2/2");
expect(failure.stderr).toContain("failed after two attempts");
expect(failure.stderr).toContain("[cause]");
}
},
);
it.skipIf(supportedHost)(
"refuses unsupported fixture hosts before tooling or output creation",
async () => {
const directory = await createTestTempDirectory("rea-nativeaot-host-");
const hook = join(directory, "unexpected-child.cjs");
await writeFile(
hook,
`const child = require("node:child_process");
child.spawnSync = () => { throw new Error("Unexpected fixture tooling invocation"); };
require("node:module").syncBuiltinESMExports();
`,
"utf8",
);
const failure = await promisify(execFile)(
process.execPath,
["--require", hook, generator],
{
env: {
...process.env,
REA_NATIVEAOT_FIXTURE_ROOT: join(directory, "output"),
},
timeout: 15_000,
},
).then(
() => {
throw new Error("Expected unsupported fixture host refusal");
},
(error: { stderr: string; code: number }) => error,
);
expect(failure.code).toBe(1);
expect(failure.stderr).toContain("requires Linux or Windows x64");
expect(failure.stderr).not.toContain(
"Unexpected fixture tooling invocation",
);
expect(await readdir(directory)).toEqual(["unexpected-child.cjs"]);
},
);
it("preserves diagnostics without transport authentication exactly", () => {
const error = nativeAotCommandError(
"C:/token projects/dotnet.exe",
"restore",
{
status: 1,
stdout: "NU1301 https://feed.invalid/user@name?label=password\n",
stderr: "project C:/token projects/fixture.csproj unavailable",
},
);
expect(error.message).toBe(
"NativeAOT fixture lane requires/action failed C:/token projects/dotnet.exe restore: exit 1\nNU1301 https://feed.invalid/user@name?label=password\nproject C:/token projects/fixture.csproj unavailable",
);
expect(error.cause).toBeUndefined();
});
it("treats HTTP backslashes as path separators rather than authentication", () => {
const output = String.raw`https://feed.invalid\path\user@name`;
expect(new URL(output).username).toBe("");
const error = nativeAotCommandError("dotnet", "restore", {
status: 1,
stdout: output,
});
expect(error.message).toContain(output);
});