Skip to content

Commit bcc8a77

Browse files
committed
fix(ghidra): preserve decoded return flow evidence
1 parent c5c75c3 commit bcc8a77

8 files changed

Lines changed: 174 additions & 4 deletions

File tree

‎bridge/ghidra/ReaGhidraBridge.java‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -866,6 +866,7 @@ private JsonObject inspectNativeInstruction(JsonObject params) throws Exception
866866
JsonArray operands = new JsonArray();
867867
JsonArray references = new JsonArray();
868868
JsonArray destinations = new JsonArray();
869+
JsonArray flowEvidence = new JsonArray();
869870
JsonObject flow = new JsonObject();
870871
flow.addProperty("kind", "unavailable");
871872
flow.addProperty("conditional", false);
@@ -881,7 +882,20 @@ private JsonObject inspectNativeInstruction(JsonObject params) throws Exception
881882
result.addProperty("mnemonic", instruction.getMnemonicString());
882883
result.addProperty("raw_disassembly", instruction.toString());
883884
RefType type = instruction.getFlowType();
884-
flow.addProperty("kind", type.isCall() ? "call" : type.isJump() ? "jump" : type.isTerminal() ? "terminal" : "fallthrough");
885+
JsonObject listingFlow = new JsonObject();
886+
listingFlow.addProperty("source", "ghidra-listing-flow-type");
887+
listingFlow.addProperty("value", type.getName());
888+
flowEvidence.add(listingFlow);
889+
boolean decodedReturn = false;
890+
for (PcodeOp operation : instruction.getPcode()) {
891+
if (operation.getOpcode() != PcodeOp.RETURN) continue;
892+
decodedReturn = true;
893+
JsonObject returnEvidence = new JsonObject();
894+
returnEvidence.addProperty("source", "ghidra-instruction-pcode");
895+
returnEvidence.addProperty("value", operation.getMnemonic());
896+
flowEvidence.add(returnEvidence);
897+
}
898+
flow.addProperty("kind", type.isCall() ? "call" : type.isJump() ? "jump" : decodedReturn ? "return" : type.isTerminal() ? "terminal" : "fallthrough");
885899
flow.addProperty("conditional", type.isConditional());
886900
flow.addProperty("computed", type.isComputed());
887901
if (!type.isComputed()) for (Address target : instruction.getFlows()) destinations.add(canonicalAddress(target));
@@ -917,10 +931,13 @@ private JsonObject inspectNativeInstruction(JsonObject params) throws Exception
917931
}
918932
}
919933
flow.add("direct_destinations", destinations);
934+
flow.add("classification_evidence", flowEvidence);
920935
result.add("operands", operands);
921936
result.add("flow", flow);
922937
result.add("references", references);
923-
result.add("limitations", GSON.toJsonTree(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.", "Terminal flow is not classified as a return without provider evidence.")));
938+
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."));
939+
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.");
940+
result.add("limitations", GSON.toJsonTree(limitations));
924941
return result;
925942
}
926943

‎docs/native-investigation.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,19 @@ outside-memory and undecodable addresses have separate outcomes. Effective
185185
memory base/index/displacement roles and per-instruction context mode remain
186186
unavailable; `mode` is the program language variant.
187187

188+
Ghidra distinguishes a return using decoded instruction p-code's `RETURN`
189+
operation. `flow.classification_evidence` preserves the Listing flow type and
190+
the observed return evidence; mnemonic spelling alone is not the classifier.
191+
Other terminal or trap flows retain the provider's classification, and this
192+
inspection does not change function extents or prove a calling convention.
193+
The analysis profile commits this decoder behavior. Snapshots from the earlier
194+
profile produce a profile mismatch rather than replaying the former generic
195+
terminal result. The old snapshot's `evidence_bundle` remains valid retained
196+
Evidence: copy that object to a separate JSON file and use `rea evidence-import`
197+
to validate it. Run analysis without the old snapshot and save a fresh one
198+
under the current profile. Other providers and older captures may omit the
199+
classification evidence field.
200+
188201
Call resolution reports direct, resolved indirect, ambiguous, unresolved and
189202
non-call outcomes from static call references. It does not establish runtime
190203
execution or classify Objective-C/Swift/vtable/closure mechanisms from names.

‎scripts/lib/real-ghidra-boundaries.mjs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { verifyGhidraTargetAdmission } from "./real-ghidra-target-admission.mjs"
1515
import { verifyGhidraLargeResults } from "./real-ghidra-large-results.mjs";
1616
import { verifyGhidraEntryAliases } from "./real-ghidra-entry-aliases.mjs";
1717
import { verifyGhidraNamespaceAnnotations } from "./real-ghidra-namespace-annotations.mjs";
18+
import { verifyGhidraInstructionFlow } from "./real-ghidra-instruction-flow.mjs";
1819

1920
/** Probe real Ghidra location, annotation and error contracts through public adapters. */
2021
export async function verifyGhidraBoundaries(
@@ -157,6 +158,7 @@ export async function verifyGhidraBoundaries(
157158
/Annotations require a local function entry/u,
158159
);
159160
const names = await call("list_names");
161+
const instructionFlow = await verifyGhidraInstructionFlow(call, names, cli);
160162
const leaf = names.find((item) =>
161163
item.value.endsWith("rea_ghidra_inventory_leaf"),
162164
);
@@ -766,6 +768,7 @@ export async function verifyGhidraBoundaries(
766768
missing_and_nonregular_source_rejected: true,
767769
imported_source_identity_retained: true,
768770
equivalent_instruction_address_spellings: true,
771+
instruction_flow: instructionFlow,
769772
qualified_annotation_name_roundtrip: true,
770773
imported_entry_alias_selection: true,
771774
oversized_result_retention_and_complete_export: true,
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import assert from "node:assert/strict";
2+
3+
/** Verify decoded return evidence and distinct non-return flows on owned fixtures. */
4+
export async function verifyGhidraInstructionFlow(call, names, cli) {
5+
const leaf = names.find((item) =>
6+
item.value.endsWith("rea_ghidra_inventory_leaf"),
7+
);
8+
assert.ok(leaf, "Source fixture lacks its returning leaf");
9+
const leafInstructions = await inspectFunction(call, leaf.address);
10+
const returned = leafInstructions.find(
11+
(instruction) => instruction.flow.kind === "return",
12+
);
13+
assert.ok(returned, "Returning source leaf lacks decoded RETURN evidence");
14+
assertReturnEvidence(returned);
15+
assert.equal(
16+
(await call("resolve_native_call_targets", { address: returned.address }))
17+
.status,
18+
"not-call",
19+
);
20+
assert.deepEqual(
21+
await cli("inspect-native-instruction", returned.address),
22+
returned,
23+
);
24+
25+
const controls = [
26+
["rea_ghidra_flow_return", "RET", "c3"],
27+
["rea_ghidra_flow_cleanup_return", "RET", "c21000"],
28+
["rea_ghidra_flow_shared_tail", "JMP", null],
29+
["rea_ghidra_flow_trap", "UD2", "0f0b"],
30+
];
31+
let checked = 0;
32+
for (const [symbol, mnemonic, bytes] of controls) {
33+
const procedure = names.find((item) => item.value === symbol);
34+
if (procedure === undefined) continue;
35+
const before = await call("resolve_containing_procedure", {
36+
address: procedure.address,
37+
});
38+
const instructions = await inspectFunction(call, procedure.address);
39+
const instruction = instructions.find((item) => item.mnemonic === mnemonic);
40+
assert.ok(instruction, `Source fixture lacks ${symbol}'s ${mnemonic}`);
41+
if (bytes !== null) assert.equal(instruction.bytes, bytes);
42+
if (mnemonic === "RET") {
43+
assertReturnEvidence(instruction);
44+
assert.equal(instruction.flow.kind, "return");
45+
if (bytes === "c21000")
46+
assert.equal(instruction.operands[0]?.raw, "0x10");
47+
} else {
48+
assert.notEqual(instruction.flow.kind, "return");
49+
assert.ok(
50+
instruction.flow.classification_evidence.some(
51+
(item) => item.source === "ghidra-listing-flow-type",
52+
),
53+
);
54+
}
55+
assert.deepEqual(
56+
await call("resolve_containing_procedure", {
57+
address: procedure.address,
58+
}),
59+
before,
60+
);
61+
checked++;
62+
}
63+
const unavailable = await call("inspect_native_instruction", {
64+
address: "0x0",
65+
});
66+
assert.equal(unavailable.status, "outside-memory");
67+
assert.equal(unavailable.flow.kind, "unavailable");
68+
assert.deepEqual(unavailable.flow.classification_evidence, []);
69+
return {
70+
return_instruction: returned.address,
71+
decoded_pcode_return: true,
72+
return_cli_mcp_parity: true,
73+
explicit_x86_elf_controls: checked,
74+
explicit_control_scope:
75+
checked === 0
76+
? "Not present on this host-native fixture format/architecture"
77+
: "x86-64 ELF",
78+
generic_unknown_preserved: true,
79+
};
80+
}
81+
82+
async function inspectFunction(call, procedure) {
83+
const listing = await call("read_function_instructions", { procedure });
84+
const instructions = [];
85+
for (const line of listing.instructions) {
86+
const delimiter = line.indexOf(": ");
87+
assert.ok(delimiter > 0, `Malformed provider instruction listing: ${line}`);
88+
instructions.push(
89+
await call("inspect_native_instruction", {
90+
address: line.slice(0, delimiter),
91+
}),
92+
);
93+
}
94+
return instructions;
95+
}
96+
97+
function assertReturnEvidence(instruction) {
98+
assert.equal(instruction.status, "decoded");
99+
assert.ok(
100+
instruction.flow.classification_evidence.some(
101+
(item) =>
102+
item.source === "ghidra-instruction-pcode" && item.value === "RETURN",
103+
),
104+
);
105+
assert.ok(
106+
!instruction.limitations.some((text) =>
107+
text.includes("not classified as a return"),
108+
),
109+
);
110+
}

‎scripts/verify-real-ghidra-function.mjs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,7 @@ export async function verifyDebugFunctionOperations(
9292
if (
9393
instruction.status !== "decoded" ||
9494
instruction.length < 1 ||
95-
instruction.bytes.length !== instruction.length * 2 ||
96-
instruction.operands.length === 0
95+
instruction.bytes.length !== instruction.length * 2
9796
)
9897
throw new Error("Structured native instruction facts drifted");
9998
const directSite = outgoing.references.find(

‎src/domain/native/nativeInstruction.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,17 @@ export const nativeInstructionSchema = z.strictObject({
5959
conditional: z.boolean(),
6060
computed: z.boolean(),
6161
direct_destinations: z.array(z.string()),
62+
classification_evidence: z
63+
.array(
64+
z.strictObject({
65+
source: z.string().min(1),
66+
value: z.string().min(1),
67+
}),
68+
)
69+
.optional()
70+
.describe(
71+
"Observed provider facts used to classify flow; older captures or other providers may omit them.",
72+
),
6273
}),
6374
references: z.array(reference),
6475
limitations: z.array(z.string()),

‎src/ghidra/GhidraAnalysisProfile.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ export const resolveGhidraAnalysisProfile = (
4444
function_body_evidence: "complete-inclusive-ranges-v1",
4545
function_references: "complete-body-and-entry-reference-manager-v2",
4646
location_resolution: "explicit-address-exact-entry-symbol-first-v3",
47+
instruction_flow_evidence: "decoded-return-pcode-v1",
4748
process_launch:
4849
installation.platform === "win32"
4950
? "official-headless-script-v1"

‎tests/conformance/ghidra/inventory.c‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,22 @@
22

33
volatile int rea_ghidra_inventory_global = 7;
44

5+
#if defined(__x86_64__) && defined(__ELF__)
6+
// Static decoder controls: these functions are retained but never executed.
7+
__attribute__((naked, noinline, used)) void rea_ghidra_flow_return(void) {
8+
__asm__("ret");
9+
}
10+
__attribute__((naked, noinline, used)) void rea_ghidra_flow_cleanup_return(void) {
11+
__asm__("ret $16");
12+
}
13+
__attribute__((naked, noinline, used)) void rea_ghidra_flow_shared_tail(void) {
14+
__asm__("jmp rea_ghidra_flow_return");
15+
}
16+
__attribute__((naked, noinline, used)) void rea_ghidra_flow_trap(void) {
17+
__asm__("ud2");
18+
}
19+
#endif
20+
521
// This literal reproduces stack exhaustion in Java's recursive regex matcher.
622
#define REA_REPEAT_4(value) value value value value
723
#define REA_REPEAT_16(value) REA_REPEAT_4(REA_REPEAT_4(value))

0 commit comments

Comments
 (0)