fix(hopper): preserve partial native call and string evidence

This commit is contained in:
morluto
2026-10-09 05:12:36 +08:00
parent 0a49d5bfb9
commit 246170238e
11 changed files with 188 additions and 77 deletions
+52 -25
View File
@@ -408,6 +408,22 @@ def _instruction_addresses(procedure):
return result
def _native_calls(procedure, direction):
references = procedure.getAllCallees() if direction == "outgoing" else procedure.getAllCallers()
kinds = {0: "none", 1: "unknown", 2: "direct", 3: "objective_c"}
calls = {}
unresolved = []
for reference in references:
source, target, kind = reference.fromAddress(), reference.toAddress(), reference.type()
if source in BAD_ADDRESSES:
continue
if target in BAD_ADDRESSES:
unresolved.append({"address": _hex(source), "reason": "Native CallReference has no resolved target (type %s)" % kind})
continue
calls[(source, target)] = {"classification": kinds.get(kind, "unknown"), "provider_type": kind, "provenance": "hopper-public-python-api:CallReference"}
return calls, sorted(unresolved, key=lambda item: int(item["address"], 16))
def _procedure_references(document, params):
procedure = _procedure(document, params.get("procedure"))
direction = params.get("direction", "outgoing")
@@ -420,6 +436,8 @@ def _procedure_references(document, params):
references = segment.getReferencesFromAddress(address) if direction == "outgoing" else segment.getReferencesOfAddress(address)
for reference in references:
edges.add((address, reference) if direction == "outgoing" else (reference, address))
calls, unresolved = _native_calls(procedure, direction)
edges.update(calls)
ordered = sorted(edges)
items = []
for source, target in ordered:
@@ -430,16 +448,15 @@ def _procedure_references(document, params):
"target_address": _hex(target),
"source_procedure": _procedure_identity(source_procedure) if source_procedure is not None else None,
"target_procedure": _procedure_identity(target_procedure) if target_procedure is not None else None,
"kind": _unavailable("Hopper's public Python API does not classify reference kinds"),
"kind": _unavailable("Hopper exposes partial CallReference classification, but not detailed reference flags"),
**({"call": calls[(source, target)]} if (source, target) in calls else {}),
})
return {
"procedure": _procedure_identity(procedure), "direction": direction,
"reference_kinds_available": False,
# The public Hopper API returns observed references but does not expose
# enough flow metadata to enumerate calls with no resolved target.
# Keep the required list field explicit; the provider records this as
# unknown coverage rather than claiming the list is exhaustive.
"unresolved_calls": [],
# These are native CallReference objects, not proof that every unresolved
# dispatch site has been enumerated by Hopper.
"unresolved_calls": unresolved,
"references": items,
}
@@ -491,14 +508,24 @@ def _string_record(segment, address, display):
raise CapabilityUnavailableError("Hopper's string display cannot be reconciled with its typed bytes at %s; inspect the bytes and encoding explicitly" % _hex(address))
def _string_inventory(document):
def _string_inventory(document, addresses=None):
key = (id(document), "string_objects")
objects = _search_inventory_cache.get(key)
if objects is None:
objects = {address: (segment, display) for segment in document.getSegmentsList() for display, address in segment.getStringsList()}
_search_inventory_cache[key] = objects
key = (id(document), "string_records")
inventory = _search_inventory_cache.get(key)
if inventory is None:
records = {_hex(address): _string_record(segment, address, display) for segment in document.getSegmentsList() for display, address in segment.getStringsList()}
inventory = dict(sorted(records.items(), key=lambda item: int(item[0], 16)))
_search_inventory_cache[key] = inventory
return inventory
records = _search_inventory_cache.setdefault(key, {})
selected = sorted(objects if addresses is None else objects.keys() & addresses)
for address in selected:
name = _hex(address)
if name not in records:
segment, display = objects[address]
try:
records[name] = _string_record(segment, address, display)
except CapabilityUnavailableError as error:
records[name] = {"value": display, "provider_value": display, "decoding": _unavailable(str(error))}
return {_hex(address): records[_hex(address)] for address in selected}
def _invalidate_search_inventory(document):
@@ -690,6 +717,10 @@ def _analyze_function(document, params):
incoming = []
outgoing = []
procedure_addresses = set(addresses)
outgoing_calls, unresolved_calls = _native_calls(procedure, "outgoing")
incoming_calls, _ = _native_calls(procedure, "incoming")
calls = {**incoming_calls, **outgoing_calls}
edges.update(calls)
for source, target in sorted(edges):
source_procedure, _ = _containing_procedure(document, source)
target_procedure, _ = _containing_procedure(document, target)
@@ -698,16 +729,14 @@ def _analyze_function(document, params):
"target_address": _hex(target),
"source_procedure": _procedure_identity(source_procedure) if source_procedure is not None else None,
"target_procedure": _procedure_identity(target_procedure) if target_procedure is not None else None,
"kind": _unavailable("Hopper's public Python API does not classify reference kinds"),
"kind": _unavailable("Hopper exposes partial CallReference classification, but not detailed reference flags"),
**({"call": calls[(source, target)]} if (source, target) in calls else {}),
}
if target in procedure_addresses and source not in procedure_addresses:
incoming.append(item)
if source in procedure_addresses:
outgoing.append(item)
string_map = {
int(address, 16): value
for address, value in _search_inventory(document, "string")
}
string_map = {int(address, 16): record for address, record in _string_inventory(document, {int(edge["target_address"], 16) for edge in outgoing}).items()}
name_map = {
int(address, 16): value
for address, value in _search_inventory(document, "name")
@@ -717,7 +746,7 @@ def _analyze_function(document, params):
for edge in outgoing:
target = int(edge["target_address"], 16)
if target in string_map:
referenced_strings.append({"address": edge["target_address"], "value": string_map[target], "source_address": edge["source_address"]})
referenced_strings.append({"address": edge["target_address"], **string_map[target], "source_address": edge["source_address"]})
if target in name_map:
referenced_names.append({"address": edge["target_address"], "value": name_map[target], "source_address": edge["source_address"]})
comments.sort(key=lambda item: (int(item["address"], 16), item["kind"]))
@@ -735,13 +764,14 @@ def _analyze_function(document, params):
"callers": callers, "callees": callees,
"incoming_references": incoming,
"outgoing_references": outgoing,
"unresolved_calls": unresolved_calls,
"referenced_strings": referenced_strings,
"referenced_names": referenced_names,
"basic_blocks": blocks,
"limitations": [
"Hopper's public Python API does not classify reference kinds.",
"Native CallReference classifications are observed where available; detailed reference flags remain unknown.",
"Hopper's public Python API does not expose equivalent external or thunk classification in this dossier.",
"Unresolved indirect calls without reported target addresses are not represented as call edges.",
"Native calls without resolved target addresses are not represented as edges; enumeration beyond reported CallReference objects is unknown.",
"Pseudocode and assembly are provider-specific representations, not original source.",
],
}
@@ -934,11 +964,8 @@ def _dispatch(method, params):
if method == "list_procedures":
return [{"address": address, "value": value} for address, value in _search_inventory(document, "procedure")]
if method == "list_strings":
values = _string_inventory(document)
requested = params.get("address")
if requested is not None:
key = _hex(_address(document, requested))
values = {key: values[key]} if key in values else {}
values = _string_inventory(document, None if requested is None else {_address(document, requested)})
return [{"address": address, **record} for address, record in values.items()]
if method == "list_names":
result = dict(_search_inventory(document, "name"))
+5
View File
@@ -353,6 +353,11 @@ provider display in `provider_value`, and report its encoding, byte length, and
termination. `encoding_status: inferred` distinguishes REA's decoding from an
observed source encoding. Hopper can split long literals into adjacent
unterminated objects; search matches each object's decoded bytes independently.
Undecodable objects retain native display text with `decoding.available: false`
and a reason, so one uncertain object does not block unrelated inspections.
Function dossiers retain this same string evidence. Native call edges retain
Hopper's partial `CallReference` classification and exact endpoints; detailed
reference flags remain unavailable rather than being invented.
Closing or switching a target closes its bound Hopper document, shuts down REA's
bridge and removes its temporary socket directory while preserving the Hopper
+3 -1
View File
@@ -206,7 +206,9 @@ No provider is mocked in this lane.
Real search probes cover Unicode names, literal metacharacters, case and regex
modes, annotation cache invalidation, complete native fragments of long literals
checked against byte reads, escaped UTF-8/control text, byte-preserving Latin-1
decoding, and Hopper's UTF-16 symbol-name truncation boundary. When the macOS
decoding, and Hopper's UTF-16 symbol-name truncation boundary. It verifies native
CallReference classifications across reference and dossier results, retains long
string fragment metadata in dossiers. When the macOS
Objective-C fixture is present, the lane also verifies native UTF-16 string objects
and their inferred encodings against their actual bytes.
Unmapped annotation destinations and
+25
View File
@@ -110,6 +110,31 @@ async function verifySearchModes(call, address) {
assert.ok(long.startsWith(longItem.value));
assert.ok(longItem.provider_value.endsWith("…"));
assert.equal(longItem.string.termination, "missing");
const literalProcedure = (await call("list_procedures")).find((item) =>
item.value.endsWith("rea_long_literal_procedure"),
);
assert.ok(literalProcedure);
const dossier = await call("analyze_function", {
procedure: literalProcedure.address,
});
const referenced = dossier.referenced_strings.find(
(item) => item.address === longItem.address,
);
assert.ok(referenced, "function dossier omitted its long literal reference");
const { source_address, ...stringRecord } = referenced;
assert.ok(
dossier.outgoing_references.some(
(edge) =>
edge.source_address === source_address &&
edge.target_address === longItem.address,
),
);
assert.deepEqual(
stringRecord,
longItem,
"function dossier discarded typed string provenance",
);
const fragments = strings.filter((item) => {
const offset = BigInt(item.address) - BigInt(longItem.address);
return offset >= 0n && offset < BigInt(Buffer.byteLength(long));
+39
View File
@@ -1,3 +1,4 @@
import assert from "node:assert/strict";
import { requireFunctionDossierOracle } from "../../dist/application/RealHopperAssertions.js";
/** Require truthful tri-state permissions from real Hopper memory regions. */
@@ -122,6 +123,44 @@ export async function verifyRealHopperFixture({
require_assembly: true,
},
);
const calls = entryDossier.outgoing_references.filter(
(edge) => edge.call?.classification === "direct",
);
assert.ok(
calls.some((edge) => edge.target_address === branch.address),
"Hopper native direct-call classification was discarded",
);
const observed = normalizedResult(
await client.callTool(
{
name: "procedure_references",
arguments: { procedure: entry.address, direction: "outgoing" },
},
options,
),
"procedure_references native calls",
);
assert.deepEqual(entryDossier.unresolved_calls, observed.unresolved_calls);
for (const call of calls) {
assert.equal(call.call.provider_type, 2);
assert.equal(
call.call.provenance,
"hopper-public-python-api:CallReference",
);
assert.equal(
call.kind.available,
false,
"partial call metadata invented detailed reference flags",
);
assert.deepEqual(
observed.references.find(
(edge) =>
edge.source_address === call.source_address &&
edge.target_address === call.target_address,
)?.call,
call.call,
);
}
const branchDossier = requireFunctionDossierOracle(
await analyzeFixtureProcedure(client, options, branch, normalizedResult),
{
+2 -2
View File
@@ -174,7 +174,7 @@ export const OFFICIAL_TOOL_CONTRACTS = [
),
official(
"procedure_references",
"Return every raw incoming or outgoing reference edge for one procedure. Endpoint procedures are resolved only from provider containment; Ghidra preserves observed reference kinds while providers without kind authority mark them unavailable.",
"Return every raw incoming or outgoing reference edge for one procedure. Endpoint procedures are resolved only from provider containment. Ghidra preserves detailed reference flags. Hopper preserves native CallReference classifications and exact endpoints while leaving unavailable detailed flags explicit.",
z.object({
procedure,
direction: z.enum(["incoming", "outgoing"]).default("outgoing"),
@@ -198,7 +198,7 @@ export const OFFICIAL_TOOL_CONTRACTS = [
),
official(
"search_strings",
"Search every analyzed string object using literal matching by default or regex when requested. Results are deterministic and complete over the native inventory. Hopper searches complete typed bytes rather than shortened displays; adjacent fragments of a long literal are matched independently, with their termination and original display retained.",
"Search every analyzed string object using literal matching by default or regex when requested. Results are deterministic and complete over the native inventory. Hopper retains typed byte decoding, native display, and explicit decoding unknowns. Adjacent long-literal fragments match independently.",
z.object(analysisSearchInput),
),
official(
+7 -39
View File
@@ -20,7 +20,9 @@ import {
import {
analysisBookmarkSchema,
functionInstructionWindowSchema,
referenceKindSchema,
referenceEdgeSchema,
unresolvedCallSchema,
analysisStringSchema,
} from "../domain/hopperValues.js";
import { nativeApiInspectionResultSchema } from "../domain/native/nativeApiBoundary.js";
import {
@@ -94,30 +96,6 @@ const bookmarkFacetSchema = z.discriminatedUnion("state", [
}),
]);
const addressedString = z.object({
address: z.string(),
value: z.string(),
provider_value: z
.string()
.exactOptional()
.describe(
"Original provider display text, which may shorten the typed object.",
),
string: z
.object({
encoding: z.string().min(1),
encoding_status: z
.enum(["observed", "inferred"])
.exactOptional()
.describe(
"Whether the provider declares the encoding or REA infers it from the typed bytes and native display. This does not establish the original source's intended encoding.",
),
termination: z.enum(["missing", "present_or_not_required"]),
byte_length: z.number().int().min(0),
})
.optional(),
});
/** Exact structured-content schemas shared by direct analysis providers. */
export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
annotate_native_function: resultOf(nativeFunctionAnnotationsSchema),
@@ -137,7 +115,7 @@ export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
list_names: resultOf(z.array(addressedValue)),
list_procedures: resultOf(z.array(addressedValue)),
list_segments: segmentOutput,
list_strings: resultOf(z.array(addressedString)),
list_strings: resultOf(z.array(analysisStringSchema)),
next_address: resultOf(z.string()),
prev_address: resultOf(z.string()),
procedure_address: resultOf(z.string()),
@@ -190,18 +168,8 @@ export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
procedure: procedureIdentity,
direction: z.enum(["incoming", "outgoing"]),
reference_kinds_available: z.boolean().optional(),
unresolved_calls: z
.array(z.object({ address: z.string(), reason: z.string() }))
.default([]),
references: z.array(
z.object({
source_address: z.string(),
target_address: z.string(),
source_procedure: procedureIdentity.nullable(),
target_procedure: procedureIdentity.nullable(),
kind: referenceKindSchema,
}),
),
unresolved_calls: z.array(unresolvedCallSchema).default([]),
references: z.array(referenceEdgeSchema),
}),
),
procedure_pseudo_code: resultOf(nullableText),
@@ -209,7 +177,7 @@ export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
search_procedures: resultOf(
z.array(z.object({ address: z.string(), value: z.string() })),
),
search_strings: resultOf(z.array(addressedString)),
search_strings: resultOf(z.array(analysisStringSchema)),
set_address_name: resultOf(z.boolean()),
set_addresses_names: resultOf(z.record(z.string(), z.boolean())),
set_bookmark: resultOf(z.boolean()),
+47 -8
View File
@@ -62,6 +62,36 @@ const segmentSchema = z.object({
const unavailableAnalysisFactSchema = z
.object({ available: z.literal(false), reason: z.string() })
.strict();
/** Typed string evidence shared by inventories and referenced function literals. */
export const analysisStringSchema = z.object({
address: z.string(),
value: z.string(),
provider_value: z
.string()
.exactOptional()
.describe(
"Original provider display text, which may shorten the typed object.",
),
decoding: unavailableAnalysisFactSchema
.exactOptional()
.describe(
"When present, value retains native display text because typed bytes could not be decoded.",
),
string: z
.object({
encoding: z.string().min(1),
encoding_status: z
.enum(["observed", "inferred"])
.exactOptional()
.describe(
"Whether the provider declares the encoding or REA infers it from the typed bytes and native display. This does not establish the original source's intended encoding.",
),
termination: z.enum(["missing", "present_or_not_required"]),
byte_length: z.number().int().min(0),
})
.exactOptional(),
});
/** An analyzed bookmark retains a missing provider label as null. */
export const analysisBookmarkSchema = z.strictObject({
address: z.string(),
@@ -256,13 +286,27 @@ export const referenceKindSchema = z.discriminatedUnion("available", [
unavailableAnalysisFactSchema,
availableReferenceKindSchema,
]);
const referenceEdgeSchema = z
/** Reported call sites without resolved targets; unreported dispatch stays unknown. */
export const unresolvedCallSchema = z.strictObject({
address: z.string(),
reason: z.string(),
});
/** Observed endpoints with complete or partial reference classification evidence. */
export const referenceEdgeSchema = z
.object({
source_address: z.string(),
target_address: z.string(),
source_procedure: procedureIdentitySchema.nullable(),
target_procedure: procedureIdentitySchema.nullable(),
kind: referenceKindSchema,
call: z
.strictObject({
classification: z.enum(["none", "unknown", "direct", "objective_c"]),
provider_type: z.number().int(),
provenance: z.string().min(1),
})
.exactOptional(),
})
.strict();
export const functionDossierSchema = z
@@ -286,14 +330,9 @@ export const functionDossierSchema = z
callees: z.array(procedureIdentitySchema),
incoming_references: z.array(referenceEdgeSchema),
outgoing_references: z.array(referenceEdgeSchema),
unresolved_calls: z.array(unresolvedCallSchema).exactOptional(),
referenced_strings: z.array(
z
.object({
address: z.string(),
value: z.string(),
source_address: z.string(),
})
.strict(),
analysisStringSchema.extend({ source_address: z.string() }),
),
referenced_names: z.array(
z
+1 -1
View File
@@ -253,7 +253,7 @@ export class HopperProvider implements AnalysisProviderCandidate {
: []),
...(operation === "procedure_references"
? [
"Hopper's public Python API does not expose flow classification for calls without resolved targets; unresolved_calls is empty and its coverage is unknown.",
"Native CallReference classifications and unresolved targets are preserved. Detailed reference flags and coverage beyond reported CallReference objects remain unknown.",
]
: []),
],
+4 -1
View File
@@ -79,9 +79,12 @@ export const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
}),
limitations: Object.freeze([
"Results depend on Hopper's completed static analysis.",
...(operation === "list_strings" || operation === "search_strings"
...(operation === "list_strings" ||
operation === "search_strings" ||
operation === "analyze_function"
? [
"String values cover native typed objects. Hopper may split long literals into adjacent unterminated fragments; string searches match each object independently.",
"Undecodable typed objects retain native display text with an explicit decoding unknown; these values do not establish decoded source literals.",
"Reported string encodings are inferred from typed bytes and native display; the original source's intended encoding is unknown.",
]
: []),
+3
View File
@@ -80,6 +80,9 @@ class FakeProcedure:
def getLocalVariableList(self):
return []
def getAllCallees(self):
return []
class FakeBlock:
def getStartingAddress(self):