Skip to content

Commit cdd9fe7

Browse files
authored
feat(native): expose typed incoming references at exact addresses (#1715)
1 parent 031d778 commit cdd9fe7

9 files changed

Lines changed: 212 additions & 10 deletions

File tree

‎bridge/ghidra/ReaGhidraBridge.java‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -375,7 +375,7 @@ private JsonElement handleRequest(Request request, SessionDescriptor descriptor)
375375
case "search_procedures" -> search(request.params, true);
376376
case "search_strings" -> search(request.params, false);
377377
case "inspect_native_data_type" -> inspectNativeDataType(request.params);
378-
case "inspect_native_instruction" -> inspectNativeInstruction(request.params);
378+
case "inspect_native_instruction" -> inspectNativeInstruction(request.params, true);
379379
case "resolve_native_call_targets" -> resolveNativeCallTargets(request.params);
380380
case "xrefs" -> xrefs(request.params);
381381
case "analyze_function" -> {
@@ -885,7 +885,7 @@ private JsonObject instructionReference(Reference reference) {
885885
return item;
886886
}
887887

888-
private JsonObject inspectNativeInstruction(JsonObject params) throws Exception {
888+
private JsonObject inspectNativeInstruction(JsonObject params, boolean includeIncoming) throws Exception {
889889
requireKeys(params, Set.of("document", "address"));
890890
requireDocument(params);
891891
Address address = requireAddress(params, "address");
@@ -968,14 +968,27 @@ private JsonObject inspectNativeInstruction(JsonObject params) throws Exception
968968
result.add("operands", operands);
969969
result.add("flow", flow);
970970
result.add("references", references);
971+
if (includeIncoming) {
972+
TreeMap<String, Reference> incoming = new TreeMap<>();
973+
ReferenceIterator incomingIterator = currentProgram.getReferenceManager().getReferencesTo(address);
974+
while (incomingIterator.hasNext()) {
975+
monitor.checkCancelled();
976+
addReference(incoming, incomingIterator.next());
977+
}
978+
List<Reference> orderedIncoming = new ArrayList<>(incoming.values());
979+
orderedIncoming.sort(REFERENCE_ORDER);
980+
JsonArray incomingReferences = new JsonArray();
981+
for (Reference reference : orderedIncoming) incomingReferences.add(instructionReference(reference));
982+
result.add("incoming_references", incomingReferences);
983+
}
971984
List<String> limitations = new ArrayList<>(List.of("Operand components are Ghidra Listing decoder tokens; effective memory base/index/displacement roles and per-instruction context mode are unavailable. The mode field is the program language variant."));
972985
if (flow.get("kind").getAsString().equals("terminal")) limitations.add("No RETURN operation was observed in the provider's instruction p-code; terminal classification remains generic.");
973986
result.add("limitations", GSON.toJsonTree(limitations));
974987
return result;
975988
}
976989

977990
private JsonObject resolveNativeCallTargets(JsonObject params) throws Exception {
978-
JsonObject instruction = inspectNativeInstruction(params);
991+
JsonObject instruction = inspectNativeInstruction(params, false);
979992
JsonObject result = new JsonObject();
980993
result.add("call_site", instruction.get("address"));
981994
result.add("procedure", instruction.get("procedure"));

‎docs/native-investigation.md‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,20 @@ outside-memory and undecodable addresses have separate outcomes. Effective
195195
memory base/index/displacement roles and per-instruction context mode remain
196196
unavailable; `mode` is the program language variant.
197197

198-
Compact instruction references and call-target references preserve the source
198+
`inspect_native_instruction` also returns `incoming_references` to the exact
199+
queried address, including data, interior-instruction and undecodable addresses.
200+
Ghidra enumerates its ReferenceManager, excludes synthetic entry-point
201+
references, and returns deterministic source-address ordering while retaining
202+
distinct operand references from the same source. `[]` means that enumeration
203+
found no references; omission or `null` means this facet is unavailable in an
204+
older capture or another provider. Empty static references do not prove that
205+
the address is unused at runtime. The existing `references` field still holds
206+
outgoing instruction references, and `xrefs` still returns bare source addresses.
207+
The Ghidra analysis profile versions this incoming-reference coverage. Reopen
208+
the target without an older snapshot and save a fresh snapshot to acquire it;
209+
the older snapshot's Evidence bundle remains readable with this facet unavailable.
210+
211+
Compact incoming, outgoing instruction and call-target references preserve the source
199212
address, operand index, DATA/READ/WRITE classification, primary status, provider
200213
`provenance`, and reference `source` (for Ghidra: `analysis`, `default`, `imported`
201214
or `user_defined`). Primary status reports the provider's chosen reference; it

‎scripts/lib/real-ghidra-compact-references.mjs‎

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ export async function verifyGhidraCompactReferences(call, x86, cli) {
1313
procedure: address(0x1020),
1414
});
1515
const inspected = {};
16+
const incomingByTarget = new Map();
1617
for (const [kind, offset, target] of cases) {
1718
const instruction = await call("inspect_native_instruction", {
1819
address: address(offset),
@@ -26,6 +27,12 @@ export async function verifyGhidraCompactReferences(call, x86, cli) {
2627
assert.equal(reference.data, true);
2728
assert.equal(reference.read, kind === "read");
2829
assert.equal(reference.write, kind === "write");
30+
const incoming = await call("inspect_native_instruction", {
31+
address: address(target),
32+
});
33+
assert.notEqual(incoming.status, "decoded");
34+
assertIncomingReference(incoming, reference);
35+
incomingByTarget.set(incoming.address, incoming);
2936
}
3037
const indexed = await call("inspect_native_instruction", {
3138
address: address(x86 ? 0x103d : 0x1045),
@@ -39,6 +46,15 @@ export async function verifyGhidraCompactReferences(call, x86, cli) {
3946
),
4047
"Indexed fixture lacks a non-primary analyzer reference",
4148
);
49+
for (const reference of indexed.references) {
50+
const incoming = await call("inspect_native_instruction", {
51+
address: reference.target_address,
52+
});
53+
assertIncomingReference(incoming, reference);
54+
incomingByTarget.set(incoming.address, incoming);
55+
}
56+
for (const incoming of incomingByTarget.values())
57+
await verifyIncomingReferences(call, incoming);
4258

4359
const { direct, targets } = await verifyDirectCall(
4460
call,
@@ -64,7 +80,13 @@ export async function verifyGhidraCompactReferences(call, x86, cli) {
6480
);
6581

6682
if (cli !== undefined) {
67-
for (const instruction of [inspected.write, indexed, direct, returned])
83+
for (const instruction of [
84+
inspected.write,
85+
indexed,
86+
direct,
87+
returned,
88+
...incomingByTarget.values(),
89+
])
6890
assert.deepEqual(
6991
await cli("inspect-native-instruction", instruction.address),
7092
instruction,
@@ -82,6 +104,10 @@ export async function verifyGhidraCompactReferences(call, x86, cli) {
82104
data_read_write: true,
83105
source_primary_provenance: true,
84106
full_reference_parity: true,
107+
typed_incoming_reference_parity: true,
108+
incoming_reference_ordering: true,
109+
incoming_xrefs_parity: true,
110+
synthetic_entry_reference_excluded: true,
85111
direct_call_reference_parity: true,
86112
indexed_reference_count: indexed.references.length,
87113
indexed_non_primary_count: indexed.references.filter(
@@ -115,9 +141,64 @@ async function verifyDirectCall(call, entry, callee) {
115141
const full = await call("procedure_references", { procedure: entry });
116142
for (const reference of direct.references)
117143
assertReference(reference, entry, full.references);
144+
const incoming = await call("inspect_native_instruction", {
145+
address: callee,
146+
});
147+
const callReference = direct.references.find(
148+
(reference) => reference.target_address === callee && reference.call,
149+
);
150+
assert.ok(callReference, "Direct fixture call lacks its reference");
151+
assertIncomingReference(incoming, callReference);
152+
await verifyIncomingReferences(call, incoming);
153+
// PE header pointers are real incoming data references; synthetic loader
154+
// entry-point references must not be presented as callers.
155+
await verifyIncomingReferences(call, direct);
156+
for (const reference of direct.incoming_references) {
157+
assert.equal(reference.type, "DATA");
158+
assert.equal(reference.data, true);
159+
assert.equal(reference.source, "default");
160+
}
118161
return { direct, targets };
119162
}
120163

164+
function assertIncomingReference(instruction, reference) {
165+
const incoming = instruction.incoming_references.find(
166+
(item) =>
167+
item.source_address === reference.source_address &&
168+
item.target_address === reference.target_address &&
169+
item.type === reference.type &&
170+
item.operand_index === reference.operand_index &&
171+
item.primary === reference.primary,
172+
);
173+
assert.ok(
174+
incoming,
175+
"Outgoing reference lacks its typed incoming counterpart",
176+
);
177+
assert.deepEqual(incoming, reference);
178+
}
179+
180+
async function verifyIncomingReferences(call, instruction) {
181+
const repeated = await call("inspect_native_instruction", {
182+
address: instruction.address,
183+
});
184+
assert.deepEqual(
185+
repeated.incoming_references,
186+
instruction.incoming_references,
187+
"Repeated incoming reference queries changed order or provider facts",
188+
);
189+
assert.deepEqual(
190+
[
191+
...new Set(
192+
instruction.incoming_references.map(
193+
(reference) => reference.source_address,
194+
),
195+
),
196+
],
197+
await call("xrefs", { address: instruction.address }),
198+
"Incoming references differ from xrefs source addresses or their order",
199+
);
200+
}
201+
121202
async function verifyEmptyReferences(call, address) {
122203
const returned = await call("inspect_native_instruction", { address });
123204
assert.equal(returned.flow.kind, "return");
@@ -129,6 +210,7 @@ async function verifyEmptyReferences(call, address) {
129210
const outside = await call("inspect_native_instruction", { address: "0x0" });
130211
assert.equal(outside.status, "outside-memory");
131212
assert.deepEqual(outside.references, []);
213+
assert.deepEqual(outside.incoming_references, []);
132214
assert.equal(
133215
(await call("resolve_native_call_targets", { address: "0x0" })).status,
134216
"unavailable",

‎src/contracts/officialToolContracts.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ export const OFFICIAL_TOOL_CONTRACTS = [
5454
),
5555
official(
5656
"inspect_native_instruction",
57-
"Inspect one exact instruction address: decoded bytes, mnemonic, ordered operand tokens, flow and typed references. Memory addressing decomposition is unavailable when the provider supplies only tokens. Data, interior instruction addresses and undecodable bytes are distinct outcomes.",
57+
"Inspect one exact code or data address: decoded bytes, mnemonic, ordered operand tokens, flow, outgoing instruction references and typed incoming references where available. Incoming references preserve source, access kind, operand index and analysis provenance even at data addresses; they do not prove runtime access. Memory addressing decomposition is unavailable when the provider supplies only tokens. Data, interior instruction addresses and undecodable bytes are distinct outcomes.",
5858
nativeInstructionInputSchema,
5959
),
6060
official(
@@ -231,7 +231,7 @@ export const OFFICIAL_TOOL_CONTRACTS = [
231231
),
232232
official(
233233
"xrefs",
234-
"Return analyzed references to a code or data address. Hopper may default to its current cursor; headless providers such as Ghidra require an explicit address. Use to connect strings, globals, selectors, and functions; bare addresses are untyped and indirect references may be incomplete.",
234+
"Return analyzed references to a code or data address. Hopper may default to its current cursor; headless providers such as Ghidra require an explicit address. Use to connect strings, globals, selectors, and functions; bare addresses are untyped and indirect references may be incomplete. Use inspect_native_instruction at the target address for typed incoming references where supported.",
235235
z.object({ document, address: optionalAddress }),
236236
),
237237
] as const satisfies readonly ToolContract[];

‎src/domain/native/nativeInstruction.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { z } from "zod";
22

3-
/** Exact instruction location within the active analysis program. */
3+
/** Exact code or data location within the active analysis program. */
44
export const nativeInstructionInputSchema = z.strictObject({
55
address: z.string().min(1),
66
document: z.string().optional(),
@@ -99,6 +99,13 @@ export const nativeInstructionSchema = z.strictObject({
9999
),
100100
}),
101101
references: z.array(reference),
102+
incoming_references: z
103+
.array(reference)
104+
.nullable()
105+
.optional()
106+
.describe(
107+
"Static references to this exact code or data address, excluding synthetic entry-point references. An empty array means the provider examined the address and found none; null or omission means unavailable. Analyzer references do not prove literal addressing or runtime access.",
108+
),
102109
limitations: z.array(z.string()),
103110
});
104111

‎src/ghidra/GhidraAnalysisProfile.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ export const resolveGhidraAnalysisProfile = async (
113113
string_inventory_evidence: "defined-data-coverage-v1",
114114
location_resolution: "explicit-address-exact-entry-symbol-first-v3",
115115
instruction_flow_evidence: "decoded-return-pcode-v1",
116+
instruction_references: "exact-address-incoming-v1",
116117
function_boundary_observations: "ghidra-terminal-call-limitations-v1",
117118
no_return_repair:
118119
installation.platform === "win32"

‎src/ghidra/GhidraFunctionValues.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,45 @@ describe("Ghidra function-analysis result values", () => {
172172
});
173173

174174
describe("Ghidra compact reference provenance", () => {
175+
it("distinguishes incoming references, examined emptiness and unavailable coverage at data addresses", () => {
176+
const instruction = {
177+
...compactInstruction(),
178+
address: "ram:00402000",
179+
status: "data",
180+
procedure: null,
181+
};
182+
const reference = {
183+
...compactReference(),
184+
source_address: "ram:00401000",
185+
target_address: instruction.address,
186+
type: "WRITE",
187+
call: false,
188+
data: true,
189+
write: true,
190+
};
191+
for (const incoming of [
192+
{},
193+
{ incoming_references: null },
194+
{ incoming_references: [] },
195+
{ incoming_references: [reference] },
196+
{ incoming_references: [{ ...reference, primary: null, source: null }] },
197+
]) {
198+
const expected = { ...instruction, ...incoming };
199+
const parsed = parseFunctionValueFixture(
200+
"inspect_native_instruction",
201+
expected,
202+
);
203+
if (!parsed.ok) throw parsed.error;
204+
expect(parsed.value).toEqual(expected);
205+
}
206+
expect(
207+
parseFunctionValueFixture("inspect_native_instruction", {
208+
...instruction,
209+
incoming_references: [{ ...reference, primary: "false" }],
210+
}),
211+
).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } });
212+
});
213+
175214
const operations = [
176215
["inspect_native_instruction", compactInstruction],
177216
["resolve_native_call_targets", compactCallTargets],

‎src/ghidra/GhidraSnapshotCache.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { createTestBinarySession } from "../../tests/fixtures/binarySession.js";
44
import { parseConfig } from "../config/parseConfig.js";
55
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
66
import { functionDossierSchema } from "../domain/hopperValues.js";
7+
import { createAnalysisProfile } from "../domain/analysisProfile.js";
78
import { ghidraFunctionDossier } from "../domain/ghidraValues.fixture.js";
89
import { err, ok } from "../domain/result.js";
910
import { silentLogger } from "../logger.js";
@@ -130,6 +131,41 @@ const open = async (session: ReturnType<typeof fixture>["session"]) => {
130131
};
131132

132133
describe("Ghidra snapshot cache", () => {
134+
it("refuses snapshots whose profile predates typed incoming references", async () => {
135+
const initial = fixture();
136+
await open(initial.session);
137+
const snapshot = initial.session.exportAnalysisSnapshot();
138+
if (!snapshot.ok) throw snapshot.error;
139+
await initial.session.close();
140+
const profile = snapshot.value.binding.analysis_profile;
141+
expect(profile.parameters.instruction_references).toBe(
142+
"exact-address-incoming-v1",
143+
);
144+
const legacy = {
145+
...snapshot.value,
146+
binding: {
147+
...snapshot.value.binding,
148+
analysis_profile: createAnalysisProfile(
149+
profile.provider,
150+
Object.fromEntries(
151+
Object.entries(profile.parameters).filter(
152+
([key]) => key !== "instruction_references",
153+
),
154+
),
155+
),
156+
},
157+
};
158+
const replay = fixture();
159+
const imported = replay.session.importAnalysisSnapshot(legacy);
160+
if (!imported.ok) throw imported.error;
161+
expect(await replay.session.previewTarget(TARGET)).toMatchObject({
162+
ok: false,
163+
error: { _tag: "EvidenceIntegrityError" },
164+
});
165+
expect(replay.calls).toEqual([]);
166+
await replay.session.close();
167+
});
168+
133169
it.each([
134170
{ operation: "analyze_function", parameters: { procedure: "0x1000" } },
135171
{

‎tests/boundary/mcp/ghidraCompactReferencesMcp.test.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,14 @@ describe("compact Ghidra reference MCP evidence", () => {
2121
{ ...base, type: "WRITE", primary: false, write: true, operand_index: 0 },
2222
];
2323
const outputs = {
24-
inspect_native_instruction: compactInstruction(references),
24+
inspect_native_instruction: {
25+
...compactInstruction(references),
26+
incoming_references: references.map((reference) => ({
27+
...reference,
28+
source_address: "ram:00403000",
29+
target_address: "0x401000",
30+
})),
31+
},
2532
resolve_native_call_targets: compactCallTargets([compactReference()]),
2633
};
2734
const harness = await connectGhidraMcp(
@@ -58,7 +65,11 @@ describe("compact Ghidra reference MCP evidence", () => {
5865

5966
it("preserves empty references and unresolved targets without manufacturing provenance", async () => {
6067
const outputs = {
61-
inspect_native_instruction: compactInstruction(),
68+
inspect_native_instruction: {
69+
...compactInstruction(),
70+
status: "data",
71+
incoming_references: [],
72+
},
6273
resolve_native_call_targets: compactCallTargets(),
6374
};
6475
const harness = await connectGhidraMcp(

0 commit comments

Comments
 (0)