refactor: return complete tool results inline
This commit is contained in:
@@ -83,21 +83,12 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
private static final int MAX_RESPONSE_BYTES = 1024 * 1024;
|
||||
private static final int RESPONSE_ENVELOPE_RESERVE_BYTES = 32 * 1024;
|
||||
private static final int MAX_NATIVE_API_RESPONSE_BYTES = 192 * 1024;
|
||||
private static final int MAX_INVENTORY_ITEMS = 1_000_000;
|
||||
private static final int MAX_FUNCTION_ITEMS = 100_000;
|
||||
private static final int MAX_FUNCTION_INSTRUCTIONS = 100_000;
|
||||
private static final int MAX_NATIVE_API_PARAMETERS = 64;
|
||||
private static final int MAX_NATIVE_API_JUMP_TABLES = 4;
|
||||
private static final int MAX_NATIVE_API_LOAD_TABLES = 4;
|
||||
private static final int MAX_NATIVE_API_MAPPINGS = 32;
|
||||
private static final int DECOMPILE_TIMEOUT_SECONDS = 30;
|
||||
private static final int DECOMPILE_PAYLOAD_MBYTES = 8;
|
||||
private static final int MAX_LIST_VALUE_CODE_POINTS = 1_024;
|
||||
private static final int MAX_SEARCH_VALUE_CODE_POINTS = 4_096;
|
||||
private static final int MAX_REGEX_CANDIDATE_CHARACTERS = 4_096;
|
||||
private static final long MAX_REGEX_BACKTRACKING_PATHS = 10_000;
|
||||
private static final long MAX_LITERAL_SEARCH_WORK_UNITS = 1_000_000;
|
||||
private static final long MAX_REGEX_SEARCH_WORK_UNITS = 1_000_000;
|
||||
private static final Gson GSON = new GsonBuilder().serializeNulls().create();
|
||||
private static final Set<String> DESCRIPTOR_KEYS = Set.of(
|
||||
"schema_version",
|
||||
@@ -375,7 +366,7 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
DecompileOptions options = new DecompileOptions();
|
||||
options.setDefaultTimeout(DECOMPILE_TIMEOUT_SECONDS);
|
||||
options.setMaxPayloadMBytes(DECOMPILE_PAYLOAD_MBYTES);
|
||||
options.setMaxInstructions(MAX_FUNCTION_INSTRUCTIONS);
|
||||
options.setMaxInstructions(Integer.MAX_VALUE);
|
||||
decompiler = new DecompInterface();
|
||||
decompiler.setOptions(options);
|
||||
decompiler.toggleCCode(true);
|
||||
@@ -398,43 +389,19 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
requireKeys(params, Set.of("document", "procedure"));
|
||||
requireDocument(params);
|
||||
Function function = resolveProcedure(requireString(params, "procedure"));
|
||||
InstructionScan scan = scanInstructions(function, MAX_FUNCTION_INSTRUCTIONS);
|
||||
if (scan.truncated) {
|
||||
throw functionLimit("Procedure assembly exceeds the 100000-instruction limit");
|
||||
}
|
||||
InstructionScan scan = scanInstructions(function, Integer.MAX_VALUE);
|
||||
return GSON.toJsonTree(renderAssembly(scan.instructions));
|
||||
}
|
||||
|
||||
private JsonObject readFunctionInstructions(JsonObject params) throws Exception {
|
||||
requireKeys(params, Set.of("document", "procedure", "offset", "limit"));
|
||||
requireKeys(params, Set.of("document", "procedure"));
|
||||
requireDocument(params);
|
||||
Function function = resolveProcedure(requireString(params, "procedure"));
|
||||
int offset = requireBoundedInteger(params, "offset", 0, 100_000);
|
||||
int limit = requireBoundedInteger(params, "limit", 1, 500);
|
||||
InstructionScan scan = scanInstructions(function, offset + limit + 1);
|
||||
int start = Math.min(offset, scan.instructions.size());
|
||||
int end = Math.min(scan.instructions.size(), start + limit);
|
||||
InstructionScan scan = scanInstructions(function, Integer.MAX_VALUE);
|
||||
JsonArray items = new JsonArray();
|
||||
for (String line : renderAssemblyLines(scan.instructions.subList(start, end))) {
|
||||
for (String line : renderAssemblyLines(scan.instructions)) {
|
||||
items.add(line);
|
||||
}
|
||||
boolean hasMore = scan.truncated || end < scan.instructions.size();
|
||||
JsonObject instructions = new JsonObject();
|
||||
instructions.add("items", items);
|
||||
if (scan.truncated) {
|
||||
instructions.add("total", JsonNull.INSTANCE);
|
||||
}
|
||||
else {
|
||||
instructions.addProperty("total", scan.instructions.size());
|
||||
}
|
||||
instructions.addProperty("returned", items.size());
|
||||
instructions.addProperty("truncated", hasMore);
|
||||
if (hasMore) {
|
||||
instructions.addProperty("next_offset", end);
|
||||
}
|
||||
else {
|
||||
instructions.add("next_offset", JsonNull.INSTANCE);
|
||||
}
|
||||
|
||||
JsonArray limitations = new JsonArray();
|
||||
limitations.add("Instruction text and ordering are Ghidra-specific representations.");
|
||||
@@ -443,9 +410,7 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
);
|
||||
JsonObject result = new JsonObject();
|
||||
result.add("procedure", procedureIdentity(function));
|
||||
result.add("instructions", instructions);
|
||||
result.addProperty("instructions_scanned", scan.instructions.size());
|
||||
result.addProperty("instruction_scan_truncated", scan.truncated);
|
||||
result.add("instructions", items);
|
||||
result.add("limitations", limitations);
|
||||
return result;
|
||||
}
|
||||
@@ -457,9 +422,6 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
Set<Function> observed = callers
|
||||
? function.getCallingFunctions(monitor)
|
||||
: function.getCalledFunctions(monitor);
|
||||
if (observed.size() > MAX_FUNCTION_ITEMS) {
|
||||
throw functionLimit("Resolved call set exceeds the 100000-item limit");
|
||||
}
|
||||
List<Function> ordered = new ArrayList<>(observed);
|
||||
ordered.sort(Comparator.comparing(Function::getEntryPoint));
|
||||
JsonArray result = new JsonArray();
|
||||
@@ -490,10 +452,7 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
Set.of(
|
||||
"document",
|
||||
"procedure",
|
||||
"direction",
|
||||
"offset",
|
||||
"limit",
|
||||
"max_instructions"
|
||||
"direction"
|
||||
)
|
||||
);
|
||||
requireDocument(params);
|
||||
@@ -502,10 +461,7 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
if (!direction.equals("incoming") && !direction.equals("outgoing")) {
|
||||
throw new RequestFailure("invalid_request", "direction must be incoming or outgoing");
|
||||
}
|
||||
int offset = requireBoundedInteger(params, "offset", 0, Integer.MAX_VALUE);
|
||||
int limit = requireBoundedInteger(params, "limit", 1, 500);
|
||||
int maximum = requireBoundedInteger(params, "max_instructions", 1, 5_000);
|
||||
InstructionScan scan = scanInstructions(function, maximum);
|
||||
InstructionScan scan = scanInstructions(function, Integer.MAX_VALUE);
|
||||
List<Reference> references = collectReferences(scan.instructions, direction);
|
||||
JsonArray edges = new JsonArray();
|
||||
for (Reference reference : references) {
|
||||
@@ -514,9 +470,7 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
JsonObject result = new JsonObject();
|
||||
result.add("procedure", procedureIdentity(function));
|
||||
result.addProperty("direction", direction);
|
||||
result.add("references", bounded(edges, offset, limit, !scan.truncated));
|
||||
result.addProperty("instructions_scanned", scan.instructions.size());
|
||||
result.addProperty("instruction_scan_truncated", scan.truncated);
|
||||
result.add("references", edges);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -533,10 +487,7 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
continue;
|
||||
}
|
||||
sources.add(reference.getFromAddress());
|
||||
if (sources.size() > MAX_FUNCTION_ITEMS) {
|
||||
throw functionLimit("Cross-reference set exceeds the 100000-item limit");
|
||||
}
|
||||
}
|
||||
List<Address> ordered = new ArrayList<>(sources);
|
||||
ordered.sort(Address::compareTo);
|
||||
JsonArray result = new JsonArray();
|
||||
@@ -547,48 +498,9 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
}
|
||||
|
||||
private JsonObject analyzeFunction(JsonObject params) throws Exception {
|
||||
requireKeys(
|
||||
params,
|
||||
Set.of(
|
||||
"procedure",
|
||||
"include_assembly",
|
||||
"limit",
|
||||
"max_pseudocode_chars",
|
||||
"max_instructions",
|
||||
"pseudocode_offset",
|
||||
"assembly_offset",
|
||||
"collection_offset"
|
||||
)
|
||||
);
|
||||
requireKeys(params, Set.of("procedure"));
|
||||
Function function = resolveProcedure(requireString(params, "procedure"));
|
||||
boolean includeAssembly = requireBoolean(params, "include_assembly");
|
||||
int limit = requireBoundedInteger(params, "limit", 1, 500);
|
||||
int maximumCharacters = requireBoundedInteger(
|
||||
params,
|
||||
"max_pseudocode_chars",
|
||||
1,
|
||||
100_000
|
||||
);
|
||||
int maximumInstructions = requireBoundedInteger(
|
||||
params,
|
||||
"max_instructions",
|
||||
1,
|
||||
5_000
|
||||
);
|
||||
int pseudocodeOffset = requireBoundedInteger(
|
||||
params,
|
||||
"pseudocode_offset",
|
||||
0,
|
||||
Integer.MAX_VALUE
|
||||
);
|
||||
int assemblyOffset = requireBoundedInteger(
|
||||
params,
|
||||
"assembly_offset",
|
||||
0,
|
||||
Integer.MAX_VALUE
|
||||
);
|
||||
JsonObject offsets = requireCollectionOffsets(params);
|
||||
InstructionScan scan = scanInstructions(function, maximumInstructions);
|
||||
InstructionScan scan = scanInstructions(function, Integer.MAX_VALUE);
|
||||
DecompileResults decompilation = decompile(function);
|
||||
String pseudocode = decompiledText(decompilation);
|
||||
if (pseudocode == null) {
|
||||
@@ -607,75 +519,24 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
JsonArray referencedStrings = referencedStrings(outgoingReferences);
|
||||
JsonArray referencedNames = referencedNames(outgoingReferences);
|
||||
JsonArray blocks = basicBlockValues(function);
|
||||
JsonArray assembly = includeAssembly
|
||||
? GSON.toJsonTree(renderAssemblyLines(scan.instructions)).getAsJsonArray()
|
||||
: new JsonArray();
|
||||
JsonArray assembly = GSON.toJsonTree(renderAssemblyLines(scan.instructions))
|
||||
.getAsJsonArray();
|
||||
|
||||
JsonObject procedure = procedureIdentity(function);
|
||||
procedure.addProperty("signature", function.getPrototypeString(false, true));
|
||||
procedure.add("locals", functionLocals(function));
|
||||
JsonObject result = new JsonObject();
|
||||
result.add("procedure", procedure);
|
||||
result.add(
|
||||
"pseudocode",
|
||||
pseudocodePage(pseudocode, pseudocodeOffset, maximumCharacters)
|
||||
);
|
||||
result.add(
|
||||
"assembly",
|
||||
includeAssembly
|
||||
? bounded(assembly, assemblyOffset, maximumInstructions, !scan.truncated)
|
||||
: bounded(assembly, 0, maximumInstructions, true)
|
||||
);
|
||||
result.add(
|
||||
"comments",
|
||||
bounded(comments, collectionOffset(offsets, "comments"), limit, !scan.truncated)
|
||||
);
|
||||
result.add("callers", bounded(callers, collectionOffset(offsets, "callers"), limit, true));
|
||||
result.add("callees", bounded(callees, collectionOffset(offsets, "callees"), limit, true));
|
||||
result.add(
|
||||
"incoming_references",
|
||||
bounded(
|
||||
incoming,
|
||||
collectionOffset(offsets, "incoming_references"),
|
||||
limit,
|
||||
!scan.truncated
|
||||
)
|
||||
);
|
||||
result.add(
|
||||
"outgoing_references",
|
||||
bounded(
|
||||
outgoing,
|
||||
collectionOffset(offsets, "outgoing_references"),
|
||||
limit,
|
||||
!scan.truncated
|
||||
)
|
||||
);
|
||||
result.add(
|
||||
"referenced_strings",
|
||||
bounded(
|
||||
referencedStrings,
|
||||
collectionOffset(offsets, "referenced_strings"),
|
||||
limit,
|
||||
!scan.truncated
|
||||
)
|
||||
);
|
||||
result.add(
|
||||
"referenced_names",
|
||||
bounded(
|
||||
referencedNames,
|
||||
collectionOffset(offsets, "referenced_names"),
|
||||
limit,
|
||||
!scan.truncated
|
||||
)
|
||||
);
|
||||
result.add(
|
||||
"basic_blocks",
|
||||
bounded(blocks, collectionOffset(offsets, "basic_blocks"), limit, true)
|
||||
);
|
||||
JsonObject instructionScan = new JsonObject();
|
||||
instructionScan.addProperty("scanned", scan.instructions.size());
|
||||
instructionScan.addProperty("truncated", scan.truncated);
|
||||
result.add("instruction_scan", instructionScan);
|
||||
result.addProperty("pseudocode", pseudocode);
|
||||
result.add("assembly", assembly);
|
||||
result.add("comments", comments);
|
||||
result.add("callers", callers);
|
||||
result.add("callees", callees);
|
||||
result.add("incoming_references", incoming);
|
||||
result.add("outgoing_references", outgoing);
|
||||
result.add("referenced_strings", referencedStrings);
|
||||
result.add("referenced_names", referencedNames);
|
||||
result.add("basic_blocks", blocks);
|
||||
int nativeApiBudget = Math.min(
|
||||
MAX_NATIVE_API_RESPONSE_BYTES,
|
||||
Math.max(
|
||||
@@ -721,8 +582,8 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
return result;
|
||||
}
|
||||
|
||||
private JsonObject listNames(JsonObject params) throws Exception {
|
||||
requireKeys(params, Set.of("document", "address", "offset", "limit"));
|
||||
private JsonArray listNames(JsonObject params) throws Exception {
|
||||
requireKeys(params, Set.of("document", "address"));
|
||||
requireDocument(params);
|
||||
List<InventoryItem> inventory = names();
|
||||
String requested = optionalString(params, "address");
|
||||
@@ -732,26 +593,16 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
.filter(item -> item.address.equals(address))
|
||||
.toList();
|
||||
}
|
||||
return page(
|
||||
inventory,
|
||||
requireBoundedInteger(params, "offset", 0, Integer.MAX_VALUE),
|
||||
requireBoundedInteger(params, "limit", 1, 500),
|
||||
"symbol"
|
||||
);
|
||||
return inventory(inventory, "symbol");
|
||||
}
|
||||
|
||||
private JsonObject listProcedures(JsonObject params) throws Exception {
|
||||
requireKeys(params, Set.of("document", "offset", "limit"));
|
||||
private JsonArray listProcedures(JsonObject params) throws Exception {
|
||||
requireKeys(params, Set.of("document"));
|
||||
requireDocument(params);
|
||||
List<InventoryItem> inventory = procedures().stream()
|
||||
.map(FunctionEntry::item)
|
||||
.toList();
|
||||
return page(
|
||||
inventory,
|
||||
requireBoundedInteger(params, "offset", 0, Integer.MAX_VALUE),
|
||||
requireBoundedInteger(params, "limit", 1, 500),
|
||||
"procedure"
|
||||
);
|
||||
return inventory(inventory, "procedure");
|
||||
}
|
||||
|
||||
private JsonArray listSegments(JsonObject params) {
|
||||
@@ -760,9 +611,6 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
JsonArray result = new JsonArray();
|
||||
String imageBase = canonicalAddress(currentProgram.getImageBase());
|
||||
MemoryBlock[] blocks = currentProgram.getMemory().getBlocks();
|
||||
if (blocks.length > MAX_INVENTORY_ITEMS) {
|
||||
throw inventoryLimit();
|
||||
}
|
||||
List<MemoryBlock> ordered = new ArrayList<>(List.of(blocks));
|
||||
ordered.sort(Comparator.comparing(MemoryBlock::getStart));
|
||||
for (MemoryBlock block : ordered) {
|
||||
@@ -773,8 +621,8 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
return result;
|
||||
}
|
||||
|
||||
private JsonObject listStrings(JsonObject params) throws Exception {
|
||||
requireKeys(params, Set.of("document", "address", "offset", "limit"));
|
||||
private JsonArray listStrings(JsonObject params) throws Exception {
|
||||
requireKeys(params, Set.of("document", "address"));
|
||||
requireDocument(params);
|
||||
List<InventoryItem> inventory = strings();
|
||||
String requested = optionalString(params, "address");
|
||||
@@ -784,12 +632,7 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
.filter(item -> item.address.equals(address))
|
||||
.toList();
|
||||
}
|
||||
return page(
|
||||
inventory,
|
||||
requireBoundedInteger(params, "offset", 0, Integer.MAX_VALUE),
|
||||
requireBoundedInteger(params, "limit", 1, 500),
|
||||
"string"
|
||||
);
|
||||
return inventory(inventory, "string");
|
||||
}
|
||||
|
||||
private JsonElement procedureAddress(JsonObject params) throws Exception {
|
||||
@@ -823,23 +666,15 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
private JsonObject search(JsonObject params, boolean procedureSearch) throws Exception {
|
||||
requireKeys(
|
||||
params,
|
||||
Set.of("pattern", "mode", "case_sensitive", "offset", "limit", "document")
|
||||
Set.of("pattern", "mode", "case_sensitive", "document")
|
||||
);
|
||||
requireDocument(params);
|
||||
String expression = requireString(params, "pattern");
|
||||
if (expression.codePointCount(0, expression.length()) > 256) {
|
||||
throw new RequestFailure(
|
||||
"invalid_request",
|
||||
"pattern must contain between 1 and 256 characters"
|
||||
);
|
||||
}
|
||||
String mode = requireString(params, "mode");
|
||||
if (!mode.equals("literal") && !mode.equals("regex")) {
|
||||
throw new RequestFailure("invalid_request", "mode must be literal or regex");
|
||||
}
|
||||
boolean caseSensitive = requireBoolean(params, "case_sensitive");
|
||||
int offset = requireBoundedInteger(params, "offset", 0, Integer.MAX_VALUE);
|
||||
int limit = requireBoundedInteger(params, "limit", 1, 100);
|
||||
List<InventoryItem> inventory = procedureSearch
|
||||
? procedures().stream().map(FunctionEntry::item).toList()
|
||||
: strings();
|
||||
@@ -847,18 +682,13 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
? literalMatcher(expression, caseSensitive)
|
||||
: regexMatcher(expression, caseSensitive);
|
||||
JsonArray items = new JsonArray();
|
||||
int total = 0;
|
||||
long pageEnd = (long) offset + limit;
|
||||
for (InventoryItem item : inventory) {
|
||||
if (!matcher.matches(item.value)) {
|
||||
continue;
|
||||
}
|
||||
if (total >= offset && total < pageEnd) {
|
||||
items.add(resultItem(item, null, MAX_SEARCH_VALUE_CODE_POINTS));
|
||||
}
|
||||
total += 1;
|
||||
items.add(resultItem(item, null));
|
||||
}
|
||||
return pageResult(items, offset, limit, total);
|
||||
return items;
|
||||
}
|
||||
|
||||
private List<InventoryItem> names() throws Exception {
|
||||
@@ -929,9 +759,6 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
symbol == null ? function.getName() : symbol.getName(true),
|
||||
facts
|
||||
);
|
||||
if (destination.size() >= MAX_INVENTORY_ITEMS) {
|
||||
throw inventoryLimit();
|
||||
}
|
||||
destination.add(new FunctionEntry(function, item));
|
||||
}
|
||||
}
|
||||
@@ -1540,9 +1367,6 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
reference.getOperandIndex() + "\u0000" +
|
||||
reference.isPrimary();
|
||||
observed.putIfAbsent(key, reference);
|
||||
if (observed.size() > MAX_FUNCTION_ITEMS) {
|
||||
throw functionLimit("Reference set exceeds the 100000-item limit");
|
||||
}
|
||||
}
|
||||
|
||||
private JsonArray referenceEdges(List<Reference> references) {
|
||||
@@ -1623,9 +1447,6 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
|
||||
private static JsonArray functionLocals(Function function) {
|
||||
Variable[] variables = function.getLocalVariables();
|
||||
if (variables.length > MAX_FUNCTION_ITEMS) {
|
||||
throw functionLimit("Local-variable set exceeds the 100000-item limit");
|
||||
}
|
||||
List<Variable> ordered = new ArrayList<>(List.of(variables));
|
||||
ordered.sort(
|
||||
Comparator.comparing(Variable::getName)
|
||||
@@ -1646,9 +1467,6 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
}
|
||||
|
||||
private JsonArray procedureIdentities(Set<Function> functions) {
|
||||
if (functions.size() > MAX_FUNCTION_ITEMS) {
|
||||
throw functionLimit("Resolved call set exceeds the 100000-item limit");
|
||||
}
|
||||
List<Function> ordered = new ArrayList<>(functions);
|
||||
ordered.sort(Comparator.comparing(Function::getEntryPoint));
|
||||
JsonArray result = new JsonArray();
|
||||
@@ -1664,9 +1482,6 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
List<CodeBlock> result = new ArrayList<>();
|
||||
while (iterator.hasNext()) {
|
||||
monitor.checkCancelled();
|
||||
if (result.size() >= MAX_FUNCTION_ITEMS) {
|
||||
throw functionLimit("Basic-block set exceeds the 100000-item limit");
|
||||
}
|
||||
result.add(iterator.next());
|
||||
}
|
||||
result.sort(Comparator.comparing(CodeBlock::getFirstStartAddress));
|
||||
@@ -1723,10 +1538,7 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
String key = canonicalAddress(instruction.getAddress()) + "\u0000" +
|
||||
kind + "\u0000" + type.name() + "\u0000" + text;
|
||||
observed.put(key, item);
|
||||
if (observed.size() > MAX_FUNCTION_ITEMS) {
|
||||
throw functionLimit("Comment set exceeds the 100000-item limit");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
JsonArray result = new JsonArray();
|
||||
observed.values().forEach(result::add);
|
||||
@@ -1753,10 +1565,7 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
String key = canonicalAddress(data.getAddress()) + "\u0000" + value + "\u0000" +
|
||||
canonicalAddress(reference.getFromAddress());
|
||||
observed.put(key, item);
|
||||
if (observed.size() > MAX_FUNCTION_ITEMS) {
|
||||
throw functionLimit("Referenced-string set exceeds the 100000-item limit");
|
||||
}
|
||||
}
|
||||
JsonArray result = new JsonArray();
|
||||
observed.values().forEach(result::add);
|
||||
return result;
|
||||
@@ -1778,36 +1587,12 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
String key = canonicalAddress(reference.getToAddress()) + "\u0000" +
|
||||
symbol.getName(true) + "\u0000" + canonicalAddress(reference.getFromAddress());
|
||||
observed.put(key, item);
|
||||
if (observed.size() > MAX_FUNCTION_ITEMS) {
|
||||
throw functionLimit("Referenced-name set exceeds the 100000-item limit");
|
||||
}
|
||||
}
|
||||
JsonArray result = new JsonArray();
|
||||
observed.values().forEach(result::add);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static JsonObject pseudocodePage(String value, int offset, int limit) {
|
||||
int total = value.codePointCount(0, value.length());
|
||||
int start = Math.min(offset, total);
|
||||
int returned = Math.min(limit, total - start);
|
||||
int startIndex = value.offsetByCodePoints(0, start);
|
||||
int endIndex = value.offsetByCodePoints(startIndex, returned);
|
||||
int next = start + returned;
|
||||
JsonObject result = new JsonObject();
|
||||
result.addProperty("text", value.substring(startIndex, endIndex));
|
||||
result.addProperty("total_chars", total);
|
||||
result.addProperty("returned_chars", returned);
|
||||
result.addProperty("truncated", next < total);
|
||||
if (next < total) {
|
||||
result.addProperty("next_offset", next);
|
||||
}
|
||||
else {
|
||||
result.add("next_offset", JsonNull.INSTANCE);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static JsonObject bounded(
|
||||
JsonArray values,
|
||||
int offset,
|
||||
@@ -1839,35 +1624,6 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
return result;
|
||||
}
|
||||
|
||||
private static JsonObject requireCollectionOffsets(JsonObject params) {
|
||||
JsonElement value = params.get("collection_offset");
|
||||
if (value == null || !value.isJsonObject()) {
|
||||
throw new RequestFailure("invalid_request", "collection_offset must be an object");
|
||||
}
|
||||
JsonObject result = value.getAsJsonObject();
|
||||
requireKeys(
|
||||
result,
|
||||
Set.of(
|
||||
"comments",
|
||||
"callers",
|
||||
"callees",
|
||||
"incoming_references",
|
||||
"outgoing_references",
|
||||
"referenced_strings",
|
||||
"referenced_names",
|
||||
"basic_blocks"
|
||||
)
|
||||
);
|
||||
for (String name : result.keySet()) {
|
||||
requireBoundedInteger(result, name, 0, Integer.MAX_VALUE);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int collectionOffset(JsonObject offsets, String name) {
|
||||
return requireBoundedInteger(offsets, name, 0, Integer.MAX_VALUE);
|
||||
}
|
||||
|
||||
private static String exclusiveAddress(Address inclusive) {
|
||||
Address next = inclusive.next();
|
||||
if (next != null && next.getAddressSpace().equals(inclusive.getAddressSpace())) {
|
||||
@@ -1884,51 +1640,21 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
return truncate(value.replaceAll("[\\r\\n]+", " "), 512).value;
|
||||
}
|
||||
|
||||
private static RequestFailure functionLimit(String message) {
|
||||
return new RequestFailure("limit_exceeded", message);
|
||||
}
|
||||
|
||||
private JsonObject page(
|
||||
List<InventoryItem> inventory,
|
||||
int offset,
|
||||
int limit,
|
||||
String factsName) {
|
||||
int start = Math.min(offset, inventory.size());
|
||||
int end = Math.min(inventory.size(), start + limit);
|
||||
JsonArray items = new JsonArray();
|
||||
for (int index = start; index < end; index += 1) {
|
||||
items.add(resultItem(inventory.get(index), factsName, MAX_LIST_VALUE_CODE_POINTS));
|
||||
private JsonArray inventory(
|
||||
List<InventoryItem> inventory,
|
||||
String factsName) {
|
||||
JsonArray result = new JsonArray();
|
||||
for (InventoryItem item : inventory) {
|
||||
monitor.checkCancelled();
|
||||
result.add(resultItem(item, factsName));
|
||||
}
|
||||
return pageResult(items, offset, limit, inventory.size());
|
||||
}
|
||||
|
||||
private static JsonObject pageResult(JsonArray items, int offset, int limit, int total) {
|
||||
int next = offset + items.size();
|
||||
boolean hasMore = next < total;
|
||||
JsonObject result = new JsonObject();
|
||||
result.add("items", items);
|
||||
result.addProperty("offset", offset);
|
||||
result.addProperty("limit", limit);
|
||||
result.addProperty("total", total);
|
||||
if (hasMore) {
|
||||
result.addProperty("next_offset", next);
|
||||
}
|
||||
else {
|
||||
result.add("next_offset", JsonNull.INSTANCE);
|
||||
}
|
||||
result.addProperty("has_more", hasMore);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static JsonObject resultItem(
|
||||
InventoryItem item,
|
||||
String factsName,
|
||||
int maximumCodePoints) {
|
||||
TruncatedValue truncated = truncate(item.value, maximumCodePoints);
|
||||
private static JsonObject resultItem(InventoryItem item, String factsName) {
|
||||
JsonObject result = new JsonObject();
|
||||
result.addProperty("address", canonicalAddress(item.address));
|
||||
result.addProperty("value", truncated.value);
|
||||
result.addProperty("value_truncated", truncated.truncated);
|
||||
result.addProperty("value", item.value);
|
||||
if (factsName != null) {
|
||||
result.add(factsName, item.facts.deepCopy());
|
||||
}
|
||||
@@ -2089,19 +1815,9 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
}
|
||||
|
||||
private static void addBounded(List<InventoryItem> destination, InventoryItem item) {
|
||||
if (destination.size() >= MAX_INVENTORY_ITEMS) {
|
||||
throw inventoryLimit();
|
||||
}
|
||||
destination.add(item);
|
||||
}
|
||||
|
||||
private static RequestFailure inventoryLimit() {
|
||||
return new RequestFailure(
|
||||
"limit_exceeded",
|
||||
"Ghidra inventory exceeds the 1000000-item safety limit"
|
||||
);
|
||||
}
|
||||
|
||||
private static TruncatedValue truncate(String value, int maximumCodePoints) {
|
||||
int codePoints = value.codePointCount(0, value.length());
|
||||
if (codePoints <= maximumCodePoints) {
|
||||
@@ -2113,30 +1829,15 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
|
||||
private static ValueMatcher literalMatcher(String pattern, boolean caseSensitive) {
|
||||
String needle = caseSensitive ? pattern : pattern.toLowerCase(Locale.ROOT);
|
||||
return new ValueMatcher() {
|
||||
private long remaining = MAX_LITERAL_SEARCH_WORK_UNITS;
|
||||
|
||||
@Override
|
||||
public boolean matches(String value) {
|
||||
long required = (long) Math.max(value.length(), 1) + needle.length();
|
||||
if (required > remaining) {
|
||||
throw new RequestFailure(
|
||||
"limit_exceeded",
|
||||
"Literal search exceeds the 1000000-unit work budget"
|
||||
);
|
||||
}
|
||||
remaining -= required;
|
||||
String candidate = caseSensitive ? value : value.toLowerCase(Locale.ROOT);
|
||||
return candidate.contains(needle);
|
||||
}
|
||||
return value -> {
|
||||
String candidate = caseSensitive ? value : value.toLowerCase(Locale.ROOT);
|
||||
return candidate.contains(needle);
|
||||
};
|
||||
}
|
||||
|
||||
private static ValueMatcher regexMatcher(String expression, boolean caseSensitive) {
|
||||
RegexMetrics metrics;
|
||||
Pattern pattern;
|
||||
try {
|
||||
metrics = new BoundedRegexParser(expression).parse();
|
||||
pattern = Pattern.compile(
|
||||
expression,
|
||||
caseSensitive ? 0 : Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE
|
||||
@@ -2145,29 +1846,7 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
catch (PatternSyntaxException exception) {
|
||||
throw new RequestFailure("invalid_request", "Invalid regex pattern");
|
||||
}
|
||||
long workPerCharacter = metrics.paths * Math.max(metrics.steps, 1);
|
||||
return new ValueMatcher() {
|
||||
private long remaining = MAX_REGEX_SEARCH_WORK_UNITS;
|
||||
|
||||
@Override
|
||||
public boolean matches(String value) {
|
||||
if (value.length() > MAX_REGEX_CANDIDATE_CHARACTERS) {
|
||||
throw new RequestFailure(
|
||||
"limit_exceeded",
|
||||
"Regex candidate exceeds the 4096-character safety limit"
|
||||
);
|
||||
}
|
||||
long required = workPerCharacter * Math.max(value.length(), 1);
|
||||
if (required > remaining) {
|
||||
throw new RequestFailure(
|
||||
"limit_exceeded",
|
||||
"Regex search exceeds the 1000000-unit work budget"
|
||||
);
|
||||
}
|
||||
remaining -= required;
|
||||
return pattern.matcher(value).find();
|
||||
}
|
||||
};
|
||||
return value -> pattern.matcher(value).find();
|
||||
}
|
||||
|
||||
private static SessionDescriptor readDescriptor(Path path) throws IOException {
|
||||
@@ -2407,7 +2086,6 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
String profileDigest
|
||||
) {}
|
||||
private record Request(int id, String method, JsonObject params) {}
|
||||
private record RegexMetrics(long paths, long steps, boolean containsRepeat) {}
|
||||
|
||||
private static final class RequestFailure extends RuntimeException {
|
||||
private final String code;
|
||||
@@ -2418,263 +2096,4 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
}
|
||||
}
|
||||
|
||||
private static final class BoundedRegexParser {
|
||||
private final String expression;
|
||||
private int index;
|
||||
|
||||
BoundedRegexParser(String expression) {
|
||||
this.expression = expression;
|
||||
}
|
||||
|
||||
RegexMetrics parse() {
|
||||
RegexMetrics result = parseExpression(false);
|
||||
if (index != expression.length()) {
|
||||
throw invalidRegex();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private RegexMetrics parseExpression(boolean grouped) {
|
||||
RegexMetrics result = parseSequence(grouped);
|
||||
while (peek('|')) {
|
||||
index += 1;
|
||||
RegexMetrics branch = parseSequence(grouped);
|
||||
result = new RegexMetrics(
|
||||
checkedPaths(result.paths, branch.paths, false),
|
||||
Math.max(result.steps, branch.steps),
|
||||
result.containsRepeat || branch.containsRepeat
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private RegexMetrics parseSequence(boolean grouped) {
|
||||
RegexMetrics result = new RegexMetrics(1, 0, false);
|
||||
while (index < expression.length() && !peek('|') && !(grouped && peek(')'))) {
|
||||
RegexMetrics item = parseAtom();
|
||||
result = new RegexMetrics(
|
||||
checkedPaths(result.paths, item.paths, true),
|
||||
result.steps + item.steps,
|
||||
result.containsRepeat || item.containsRepeat
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private RegexMetrics parseAtom() {
|
||||
if (index >= expression.length()) {
|
||||
throw invalidRegex();
|
||||
}
|
||||
char item = expression.charAt(index++);
|
||||
RegexMetrics atom;
|
||||
if (item == '(') {
|
||||
if (peek('?')) {
|
||||
if (index + 1 >= expression.length() || expression.charAt(index + 1) != ':') {
|
||||
throw new RequestFailure(
|
||||
"invalid_request",
|
||||
"Regex lookarounds and backreferences are not supported"
|
||||
);
|
||||
}
|
||||
index += 2;
|
||||
}
|
||||
atom = parseExpression(true);
|
||||
if (!peek(')')) {
|
||||
throw invalidRegex();
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
else if (item == '[') {
|
||||
consumeCharacterClass();
|
||||
atom = leaf();
|
||||
}
|
||||
else if (item == '\\') {
|
||||
consumeEscape();
|
||||
atom = leaf();
|
||||
}
|
||||
else if (item == '*' || item == '+') {
|
||||
throw unboundedRepeat();
|
||||
}
|
||||
else if (item == '?' || item == '{' || item == '}' || item == ')') {
|
||||
throw invalidRegex();
|
||||
}
|
||||
else {
|
||||
atom = leaf();
|
||||
}
|
||||
if (index >= expression.length()) {
|
||||
return atom;
|
||||
}
|
||||
if (peek('*') || peek('+')) {
|
||||
throw unboundedRepeat();
|
||||
}
|
||||
int minimum;
|
||||
int maximum;
|
||||
if (peek('?')) {
|
||||
index += 1;
|
||||
minimum = 0;
|
||||
maximum = 1;
|
||||
}
|
||||
else if (peek('{')) {
|
||||
int[] bounds = consumeBounds();
|
||||
minimum = bounds[0];
|
||||
maximum = bounds[1];
|
||||
}
|
||||
else {
|
||||
return atom;
|
||||
}
|
||||
if (atom.containsRepeat) {
|
||||
throw new RequestFailure(
|
||||
"invalid_request",
|
||||
"Nested regex repetitions are not supported"
|
||||
);
|
||||
}
|
||||
if (maximum > 1_000) {
|
||||
throw unboundedRepeat();
|
||||
}
|
||||
return new RegexMetrics(
|
||||
repeatPaths(atom.paths, minimum, maximum),
|
||||
maximum * atom.steps,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
private void consumeCharacterClass() {
|
||||
boolean escaped = false;
|
||||
boolean hasContent = false;
|
||||
while (index < expression.length()) {
|
||||
char item = expression.charAt(index++);
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
hasContent = true;
|
||||
}
|
||||
else if (item == '\\') {
|
||||
escaped = true;
|
||||
}
|
||||
else if (item == ']' && hasContent) {
|
||||
return;
|
||||
}
|
||||
else {
|
||||
hasContent = true;
|
||||
}
|
||||
}
|
||||
throw invalidRegex();
|
||||
}
|
||||
|
||||
private void consumeEscape() {
|
||||
if (index >= expression.length()) {
|
||||
throw invalidRegex();
|
||||
}
|
||||
char escaped = expression.charAt(index++);
|
||||
if (Character.isDigit(escaped) || escaped == 'k') {
|
||||
throw new RequestFailure(
|
||||
"invalid_request",
|
||||
"Regex lookarounds and backreferences are not supported"
|
||||
);
|
||||
}
|
||||
if (escaped == 'Q' || escaped == 'E' || escaped == 'p' || escaped == 'P') {
|
||||
throw new RequestFailure(
|
||||
"invalid_request",
|
||||
"Regex operation is not supported by the bounded matcher"
|
||||
);
|
||||
}
|
||||
if (escaped == 'x') {
|
||||
consumeHexDigits(2);
|
||||
}
|
||||
else if (escaped == 'u') {
|
||||
consumeHexDigits(4);
|
||||
}
|
||||
}
|
||||
|
||||
private void consumeHexDigits(int count) {
|
||||
if (index + count > expression.length()) {
|
||||
throw invalidRegex();
|
||||
}
|
||||
for (int current = 0; current < count; current += 1) {
|
||||
if (Character.digit(expression.charAt(index + current), 16) < 0) {
|
||||
throw invalidRegex();
|
||||
}
|
||||
}
|
||||
index += count;
|
||||
}
|
||||
|
||||
private int[] consumeBounds() {
|
||||
index += 1;
|
||||
int minimum = consumeDecimal();
|
||||
int maximum = minimum;
|
||||
if (peek(',')) {
|
||||
index += 1;
|
||||
if (peek('}')) {
|
||||
throw unboundedRepeat();
|
||||
}
|
||||
maximum = consumeDecimal();
|
||||
}
|
||||
if (!peek('}') || minimum > maximum) {
|
||||
throw invalidRegex();
|
||||
}
|
||||
index += 1;
|
||||
return new int[] { minimum, maximum };
|
||||
}
|
||||
|
||||
private int consumeDecimal() {
|
||||
int start = index;
|
||||
long value = 0;
|
||||
while (index < expression.length() && Character.isDigit(expression.charAt(index))) {
|
||||
value = value * 10 + Character.digit(expression.charAt(index), 10);
|
||||
if (value > Integer.MAX_VALUE) {
|
||||
throw unboundedRepeat();
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
if (index == start) {
|
||||
throw invalidRegex();
|
||||
}
|
||||
return (int) value;
|
||||
}
|
||||
|
||||
private boolean peek(char expected) {
|
||||
return index < expression.length() && expression.charAt(index) == expected;
|
||||
}
|
||||
|
||||
private static RegexMetrics leaf() {
|
||||
return new RegexMetrics(1, 1, false);
|
||||
}
|
||||
|
||||
private static long repeatPaths(long childPaths, int minimum, int maximum) {
|
||||
long result = 0;
|
||||
long repeated = 1;
|
||||
for (int count = 0; count <= maximum; count += 1) {
|
||||
if (count >= minimum) {
|
||||
result = checkedPaths(result, repeated, false);
|
||||
}
|
||||
if (count < maximum) {
|
||||
repeated = checkedPaths(repeated, childPaths, true);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static long checkedPaths(long left, long right, boolean multiply) {
|
||||
boolean exceeded = multiply
|
||||
? right != 0 && left > MAX_REGEX_BACKTRACKING_PATHS / right
|
||||
: left > MAX_REGEX_BACKTRACKING_PATHS - right;
|
||||
long result = multiply ? left * right : left + right;
|
||||
if (exceeded || result > MAX_REGEX_BACKTRACKING_PATHS) {
|
||||
throw new RequestFailure(
|
||||
"invalid_request",
|
||||
"Regex exceeds the 10000-path backtracking budget"
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static RequestFailure unboundedRepeat() {
|
||||
return new RequestFailure(
|
||||
"invalid_request",
|
||||
"Unbounded or excessive regex repetitions are not supported"
|
||||
);
|
||||
}
|
||||
|
||||
private static RequestFailure invalidRegex() {
|
||||
return new RequestFailure("invalid_request", "Invalid regex pattern");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+90
-307
@@ -9,7 +9,6 @@ import json
|
||||
import hmac
|
||||
import os
|
||||
import re
|
||||
import sre_parse
|
||||
import socket
|
||||
from typing import Any, Optional, Protocol, Sequence
|
||||
|
||||
@@ -17,11 +16,10 @@ MAX_LINE_BYTES = 10 * 1024 * 1024
|
||||
MAX_READ_BYTES = 4096
|
||||
BAD_ADDRESSES = (-1, 0xFFFFFFFFFFFFFFFF, None)
|
||||
_selected_document = None
|
||||
_rea_session_document = None
|
||||
_search_inventory_cache = {}
|
||||
_pseudocode_cache = {}
|
||||
_hopper_api = None
|
||||
MAX_SEARCH_PATTERN_LENGTH = 256
|
||||
MAX_SEARCH_VALUE_LENGTH = 4096
|
||||
|
||||
|
||||
class HopperDocument(Protocol):
|
||||
@@ -69,8 +67,9 @@ class HopperApiFacade:
|
||||
|
||||
def _configure_hopper_api(document_provider):
|
||||
"""Inject Hopper's document provider or a standalone test facade."""
|
||||
global _hopper_api
|
||||
global _hopper_api, _rea_session_document
|
||||
_hopper_api = HopperApiFacade(document_provider)
|
||||
_rea_session_document = None
|
||||
|
||||
|
||||
def _api():
|
||||
@@ -88,21 +87,45 @@ def _api():
|
||||
|
||||
|
||||
def _session_document():
|
||||
"""Find only the document opened for this authenticated REA session."""
|
||||
"""Return the exact document bound to this authenticated REA session."""
|
||||
global _rea_session_document
|
||||
documents = _api().documents()
|
||||
if _rea_session_document is not None:
|
||||
return (
|
||||
_rea_session_document
|
||||
if any(document is _rea_session_document for document in documents)
|
||||
else None
|
||||
)
|
||||
return _bind_session_document(documents)
|
||||
|
||||
|
||||
def _bind_session_document(documents=None):
|
||||
"""Bind this bridge to Hopper's current document for its target."""
|
||||
global _rea_session_document
|
||||
api = _api()
|
||||
if documents is None:
|
||||
documents = api.documents()
|
||||
target = os.path.realpath(REA_TARGET_PATH)
|
||||
for document in _api().documents():
|
||||
|
||||
def matches_target(document):
|
||||
paths = (document.getExecutableFilePath(), document.getDatabaseFilePath())
|
||||
for path in paths:
|
||||
if path and os.path.realpath(path) == target:
|
||||
return document
|
||||
return any(path and os.path.realpath(path) == target for path in paths)
|
||||
|
||||
current = api.current_document()
|
||||
if current is not None and matches_target(current):
|
||||
_rea_session_document = current
|
||||
return current
|
||||
matching = [document for document in documents if matches_target(document)]
|
||||
if len(matching) == 1:
|
||||
_rea_session_document = matching[0]
|
||||
return matching[0]
|
||||
if len(matching) > 1:
|
||||
raise CapabilityUnavailableError(
|
||||
"The REA session document is ambiguous; Hopper did not identify the launched document"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
MAX_REGEX_BACKTRACKING_PATHS = 10000
|
||||
MAX_REGEX_CANDIDATE_LENGTH = 4096
|
||||
MAX_REGEX_SEARCH_WORK_UNITS = 1000000
|
||||
|
||||
|
||||
class CapabilityUnavailableError(Exception):
|
||||
"""The active Hopper build lacks one admitted public API operation."""
|
||||
|
||||
@@ -149,14 +172,22 @@ def _document(name=None):
|
||||
api = _api()
|
||||
documents = api.documents()
|
||||
if name is not None:
|
||||
for candidate in documents:
|
||||
if candidate.getDocumentName() == name:
|
||||
return candidate
|
||||
matches = [candidate for candidate in documents if candidate.getDocumentName() == name]
|
||||
if len(matches) == 1:
|
||||
return matches[0]
|
||||
if len(matches) > 1:
|
||||
current = api.current_document()
|
||||
if current is not None and current.getDocumentName() == name:
|
||||
return current
|
||||
raise ValueError("Hopper document name is ambiguous")
|
||||
raise ValueError("Unknown Hopper document")
|
||||
if _selected_document is not None:
|
||||
for candidate in documents:
|
||||
if candidate.getDocumentName() == _selected_document:
|
||||
return candidate
|
||||
session_document = _session_document()
|
||||
if session_document is not None:
|
||||
return session_document
|
||||
current = api.current_document()
|
||||
if current is None:
|
||||
raise ValueError("No Hopper document is loaded")
|
||||
@@ -225,7 +256,7 @@ def _containing_procedure(document, address):
|
||||
return (procedure, None) if procedure is not None else (None, "not_in_procedure")
|
||||
|
||||
|
||||
def _instruction_addresses(procedure, limit):
|
||||
def _instruction_addresses(procedure, limit=None):
|
||||
result = []
|
||||
seen = set()
|
||||
segment = procedure.getSegment()
|
||||
@@ -234,7 +265,7 @@ def _instruction_addresses(procedure, limit):
|
||||
address = block.getStartingAddress()
|
||||
end = block.getEndingAddress()
|
||||
while address < end and address not in seen:
|
||||
if len(result) >= limit:
|
||||
if limit is not None and len(result) >= limit:
|
||||
truncated = True
|
||||
return result, truncated
|
||||
seen.add(address)
|
||||
@@ -252,18 +283,9 @@ def _instruction_addresses(procedure, limit):
|
||||
def _procedure_references(document, params):
|
||||
procedure = _procedure(document, params.get("procedure"))
|
||||
direction = params.get("direction", "outgoing")
|
||||
offset = params.get("offset", 0)
|
||||
limit = params.get("limit", 100)
|
||||
max_instructions = params.get("max_instructions", 500)
|
||||
if direction not in ("incoming", "outgoing"):
|
||||
raise ValueError("direction must be incoming or outgoing")
|
||||
if not isinstance(offset, int) or isinstance(offset, bool) or offset < 0:
|
||||
raise ValueError("offset must be a non-negative integer")
|
||||
if not isinstance(limit, int) or isinstance(limit, bool) or limit < 1 or limit > 500:
|
||||
raise ValueError("limit must be an integer between 1 and 500")
|
||||
if not isinstance(max_instructions, int) or isinstance(max_instructions, bool) or max_instructions < 1 or max_instructions > 5000:
|
||||
raise ValueError("max_instructions must be an integer between 1 and 5000")
|
||||
addresses, scan_truncated = _instruction_addresses(procedure, max_instructions)
|
||||
addresses, _ = _instruction_addresses(procedure)
|
||||
edges = set()
|
||||
for address in addresses:
|
||||
segment = _segment(document, address)
|
||||
@@ -272,8 +294,7 @@ def _procedure_references(document, params):
|
||||
edges.add((address, reference) if direction == "outgoing" else (reference, address))
|
||||
ordered = sorted(edges)
|
||||
items = []
|
||||
selected = ordered[offset:offset + limit]
|
||||
for source, target in selected:
|
||||
for source, target in ordered:
|
||||
source_procedure, _ = _containing_procedure(document, source)
|
||||
target_procedure, _ = _containing_procedure(document, target)
|
||||
items.append({
|
||||
@@ -283,13 +304,9 @@ def _procedure_references(document, params):
|
||||
"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"),
|
||||
})
|
||||
next_offset = offset + len(selected)
|
||||
has_more = next_offset < len(ordered)
|
||||
truncated = scan_truncated or has_more
|
||||
return {
|
||||
"procedure": _procedure_identity(procedure), "direction": direction,
|
||||
"references": {"items": items, "total": None if scan_truncated else len(ordered), "returned": len(items), "truncated": truncated, "next_offset": next_offset if has_more and not scan_truncated else None},
|
||||
"instructions_scanned": len(addresses), "instruction_scan_truncated": scan_truncated,
|
||||
"references": items,
|
||||
}
|
||||
|
||||
|
||||
@@ -352,230 +369,39 @@ def _search_inventory(document, kind):
|
||||
return inventory
|
||||
|
||||
|
||||
def _checked_regex_paths(left, right, operation):
|
||||
"""Apply one path-count operation without crossing the static work budget."""
|
||||
if operation == "add":
|
||||
exceeded = left > MAX_REGEX_BACKTRACKING_PATHS - right
|
||||
result = left + right
|
||||
else:
|
||||
exceeded = right != 0 and left > MAX_REGEX_BACKTRACKING_PATHS // right
|
||||
result = left * right
|
||||
if exceeded or result > MAX_REGEX_BACKTRACKING_PATHS:
|
||||
raise ValueError(
|
||||
"Regex exceeds the %d-path backtracking budget"
|
||||
% MAX_REGEX_BACKTRACKING_PATHS
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _repeat_regex_paths(child_paths, minimum, maximum):
|
||||
"""Count every bounded repetition path, including alternative child paths."""
|
||||
paths = 0
|
||||
repeated_paths = 1
|
||||
for count in range(maximum + 1):
|
||||
if count >= minimum:
|
||||
paths = _checked_regex_paths(paths, repeated_paths, "add")
|
||||
if count < maximum:
|
||||
repeated_paths = _checked_regex_paths(
|
||||
repeated_paths, child_paths, "multiply"
|
||||
)
|
||||
return paths
|
||||
|
||||
|
||||
def _validate_regex_class(items):
|
||||
"""Accept only constant-time character-class operations."""
|
||||
allowed = {
|
||||
sre_parse.CATEGORY,
|
||||
sre_parse.LITERAL,
|
||||
sre_parse.NEGATE,
|
||||
sre_parse.RANGE,
|
||||
}
|
||||
if any(operation not in allowed for operation, _ in items):
|
||||
raise ValueError("Regex operation is not supported by the bounded matcher")
|
||||
|
||||
|
||||
def _validate_regex_node(node, inside_repeat=False):
|
||||
"""Return capped path and step bounds for Python regex evaluation."""
|
||||
leaf_operations = {
|
||||
sre_parse.ANY,
|
||||
sre_parse.AT,
|
||||
sre_parse.CATEGORY,
|
||||
sre_parse.LITERAL,
|
||||
sre_parse.NOT_LITERAL,
|
||||
}
|
||||
forbidden = {
|
||||
sre_parse.ASSERT,
|
||||
sre_parse.ASSERT_NOT,
|
||||
sre_parse.GROUPREF,
|
||||
sre_parse.GROUPREF_EXISTS,
|
||||
}
|
||||
for name in ("GROUPREF_IGNORE", "GROUPREF_LOC_IGNORE", "GROUPREF_UNI_IGNORE"):
|
||||
operation = getattr(sre_parse, name, None)
|
||||
if operation is not None:
|
||||
forbidden.add(operation)
|
||||
repeat_tokens = {sre_parse.MAX_REPEAT, sre_parse.MIN_REPEAT}
|
||||
possessive = getattr(sre_parse, "POSSESSIVE_REPEAT", None)
|
||||
if possessive is not None:
|
||||
repeat_tokens.add(possessive)
|
||||
atomic = getattr(sre_parse, "ATOMIC_GROUP", None)
|
||||
|
||||
paths = 1
|
||||
steps = 0
|
||||
for operation, argument in node:
|
||||
if operation in forbidden:
|
||||
raise ValueError("Regex lookarounds and backreferences are not supported")
|
||||
if operation in leaf_operations:
|
||||
operation_paths = 1
|
||||
operation_steps = 1
|
||||
elif operation == sre_parse.IN:
|
||||
_validate_regex_class(argument)
|
||||
operation_paths = 1
|
||||
operation_steps = 1
|
||||
elif operation in repeat_tokens:
|
||||
if inside_repeat:
|
||||
raise ValueError("Nested regex repetitions are not supported")
|
||||
minimum, maximum, child = argument
|
||||
if maximum == sre_parse.MAXREPEAT or maximum > 1000:
|
||||
raise ValueError(
|
||||
"Unbounded or excessive regex repetitions are not supported"
|
||||
)
|
||||
child_paths, child_steps = _validate_regex_node(child, True)
|
||||
operation_paths = _repeat_regex_paths(
|
||||
child_paths, minimum, maximum
|
||||
)
|
||||
operation_steps = maximum * child_steps
|
||||
elif operation == sre_parse.SUBPATTERN:
|
||||
operation_paths, operation_steps = _validate_regex_node(
|
||||
argument[-1], inside_repeat
|
||||
)
|
||||
elif operation == sre_parse.BRANCH:
|
||||
operation_paths = 0
|
||||
operation_steps = 0
|
||||
for branch in argument[1]:
|
||||
branch_paths, branch_steps = _validate_regex_node(
|
||||
branch, inside_repeat
|
||||
)
|
||||
operation_paths = _checked_regex_paths(
|
||||
operation_paths,
|
||||
branch_paths,
|
||||
"add",
|
||||
)
|
||||
operation_steps = max(operation_steps, branch_steps)
|
||||
elif atomic is not None and operation == atomic:
|
||||
operation_paths, operation_steps = _validate_regex_node(
|
||||
argument, inside_repeat
|
||||
)
|
||||
else:
|
||||
raise ValueError("Regex operation is not supported by the bounded matcher")
|
||||
paths = _checked_regex_paths(paths, operation_paths, "multiply")
|
||||
steps += operation_steps
|
||||
return paths, steps
|
||||
|
||||
|
||||
def _bounded_regex_matcher(expression, backtracking_paths, steps_per_path):
|
||||
"""Create a matcher with per-candidate and cumulative work bounds."""
|
||||
remaining_work = MAX_REGEX_SEARCH_WORK_UNITS
|
||||
work_per_character = backtracking_paths * max(steps_per_path, 1)
|
||||
|
||||
def matches(value):
|
||||
nonlocal remaining_work
|
||||
if not isinstance(value, str):
|
||||
raise ValueError("Regex candidates must be strings")
|
||||
if len(value) > MAX_REGEX_CANDIDATE_LENGTH:
|
||||
raise ValueError(
|
||||
"Regex candidate exceeds the %d-character safety limit"
|
||||
% MAX_REGEX_CANDIDATE_LENGTH
|
||||
)
|
||||
required_work = work_per_character * max(len(value), 1)
|
||||
if required_work > remaining_work:
|
||||
raise ValueError(
|
||||
"Regex search exceeds the %d-unit work budget"
|
||||
% MAX_REGEX_SEARCH_WORK_UNITS
|
||||
)
|
||||
remaining_work -= required_work
|
||||
return expression.search(value) is not None
|
||||
|
||||
return matches
|
||||
|
||||
|
||||
def _search_page(document, kind, params):
|
||||
def _search_results(document, kind, params):
|
||||
pattern = params.get("pattern")
|
||||
if not isinstance(pattern, str) or not pattern or len(pattern) > MAX_SEARCH_PATTERN_LENGTH:
|
||||
raise ValueError("pattern must contain between 1 and 256 characters")
|
||||
if not isinstance(pattern, str) or not pattern:
|
||||
raise ValueError("pattern must be a non-empty string")
|
||||
mode = params.get("mode", "literal")
|
||||
if mode not in ("literal", "regex"):
|
||||
raise ValueError("mode must be literal or regex")
|
||||
case_sensitive = params.get("case_sensitive", False)
|
||||
if not isinstance(case_sensitive, bool):
|
||||
raise ValueError("case_sensitive must be a boolean")
|
||||
offset = params.get("offset", 0)
|
||||
limit = params.get("limit", 100)
|
||||
if not isinstance(offset, int) or isinstance(offset, bool) or offset < 0:
|
||||
raise ValueError("offset must be a non-negative integer")
|
||||
if not isinstance(limit, int) or isinstance(limit, bool) or limit < 1 or limit > 100:
|
||||
raise ValueError("limit must be an integer between 1 and 100")
|
||||
|
||||
if mode == "literal":
|
||||
needle = pattern if case_sensitive else pattern.casefold()
|
||||
matches = lambda value: needle in (value if case_sensitive else value.casefold())
|
||||
else:
|
||||
try:
|
||||
parsed = sre_parse.parse(pattern)
|
||||
backtracking_paths, steps_per_path = _validate_regex_node(parsed)
|
||||
expression = re.compile(pattern, 0 if case_sensitive else re.IGNORECASE)
|
||||
except (re.error, OverflowError) as error:
|
||||
raise ValueError("Invalid regex pattern") from error
|
||||
matches = _bounded_regex_matcher(
|
||||
expression, backtracking_paths, steps_per_path
|
||||
)
|
||||
matches = lambda value: expression.search(value) is not None
|
||||
|
||||
selected = []
|
||||
total = 0
|
||||
page_end = offset + limit
|
||||
for item in _search_inventory(document, kind):
|
||||
if not matches(item[1]):
|
||||
continue
|
||||
if offset <= total < page_end:
|
||||
selected.append(item)
|
||||
total += 1
|
||||
next_offset = offset + len(selected)
|
||||
has_more = next_offset < total
|
||||
return {
|
||||
"items": [
|
||||
selected.append(item)
|
||||
return [
|
||||
{
|
||||
"address": address,
|
||||
"value": value[:MAX_SEARCH_VALUE_LENGTH],
|
||||
"value_truncated": len(value) > MAX_SEARCH_VALUE_LENGTH,
|
||||
"value": value,
|
||||
}
|
||||
for address, value in selected
|
||||
],
|
||||
"offset": offset,
|
||||
"limit": limit,
|
||||
"total": total,
|
||||
"next_offset": next_offset if has_more else None,
|
||||
"has_more": has_more,
|
||||
}
|
||||
|
||||
|
||||
def _page(values, offset, limit):
|
||||
"""Return one deterministically address-sorted page without crossing an unbounded map."""
|
||||
if not isinstance(offset, int) or isinstance(offset, bool) or offset < 0:
|
||||
raise ValueError("offset must be a non-negative integer")
|
||||
if not isinstance(limit, int) or isinstance(limit, bool) or limit < 1 or limit > 500:
|
||||
raise ValueError("limit must be an integer between 1 and 500")
|
||||
ordered = sorted(values.items(), key=lambda item: int(item[0], 16))
|
||||
selected = ordered[offset:offset + limit]
|
||||
total = len(ordered)
|
||||
next_offset = offset + len(selected)
|
||||
has_more = next_offset < total
|
||||
return {
|
||||
"items": [{"address": address, "value": value} for address, value in selected],
|
||||
"offset": offset,
|
||||
"limit": limit,
|
||||
"total": total,
|
||||
"next_offset": next_offset if has_more else None,
|
||||
"has_more": has_more,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def _unavailable(reason):
|
||||
@@ -590,16 +416,6 @@ def _offset(params, name):
|
||||
return value
|
||||
|
||||
|
||||
def _collection_offset(params, name):
|
||||
values = params.get("collection_offset", {})
|
||||
if not isinstance(values, dict):
|
||||
raise ValueError("collection_offset must be an object")
|
||||
value = values.get(name, 0)
|
||||
if not isinstance(value, int) or isinstance(value, bool) or value < 0:
|
||||
raise ValueError("collection_offset.%s must be a non-negative integer" % name)
|
||||
return value
|
||||
|
||||
|
||||
def _bounded(items, offset, limit, total=None, scan_truncated=False):
|
||||
selected = items[offset:offset + limit]
|
||||
known_total = len(items) if total is None and not scan_truncated else total
|
||||
@@ -665,37 +481,18 @@ def _assembly(procedure, limit=None):
|
||||
|
||||
|
||||
def _read_function_instructions(document, params):
|
||||
"""Read one bounded raw-instruction window without invoking decompilation."""
|
||||
"""Read all raw instructions without invoking decompilation."""
|
||||
procedure = _procedure(document, params.get("procedure"))
|
||||
offset = _offset(params, "offset")
|
||||
limit = params.get("limit", 64)
|
||||
if offset > 100000:
|
||||
raise ValueError("offset must not exceed 100000")
|
||||
if not isinstance(limit, int) or isinstance(limit, bool) or limit < 1 or limit > 500:
|
||||
raise ValueError("limit must be an integer between 1 and 500")
|
||||
addresses, scan_truncated = _instruction_addresses(
|
||||
procedure, offset + limit + 1
|
||||
)
|
||||
start = min(offset, len(addresses))
|
||||
end = min(len(addresses), start + limit)
|
||||
addresses, _ = _instruction_addresses(procedure)
|
||||
segment = procedure.getSegment()
|
||||
items = []
|
||||
for address in addresses[start:end]:
|
||||
for address in addresses:
|
||||
line = _render_instruction(segment, address)
|
||||
if line is not None:
|
||||
items.append(line)
|
||||
has_more = scan_truncated or end < len(addresses)
|
||||
return {
|
||||
"procedure": _procedure_identity(procedure),
|
||||
"instructions": {
|
||||
"items": items,
|
||||
"total": None if scan_truncated else len(addresses),
|
||||
"returned": len(items),
|
||||
"truncated": has_more,
|
||||
"next_offset": end if has_more else None,
|
||||
},
|
||||
"instructions_scanned": len(addresses),
|
||||
"instruction_scan_truncated": scan_truncated,
|
||||
"instructions": items,
|
||||
"limitations": [
|
||||
"Instruction text and ordering are Hopper-specific representations.",
|
||||
"The fast path does not decompile the procedure or scan whole-program names and strings.",
|
||||
@@ -704,20 +501,9 @@ def _read_function_instructions(document, params):
|
||||
|
||||
|
||||
def _analyze_function(document, params):
|
||||
"""Collect a bounded, single-pass function dossier for agent callers."""
|
||||
"""Collect the complete function dossier for agent callers."""
|
||||
procedure = _procedure(document, params.get("procedure"))
|
||||
limit = params.get("limit", 100)
|
||||
max_chars = params.get("max_pseudocode_chars", 20000)
|
||||
max_instructions = params.get("max_instructions", 500)
|
||||
pseudocode_offset = _offset(params, "pseudocode_offset")
|
||||
assembly_offset = _offset(params, "assembly_offset")
|
||||
if not isinstance(limit, int) or isinstance(limit, bool) or limit < 1 or limit > 500:
|
||||
raise ValueError("limit must be an integer between 1 and 500")
|
||||
if not isinstance(max_chars, int) or isinstance(max_chars, bool) or max_chars < 1 or max_chars > 100000:
|
||||
raise ValueError("max_pseudocode_chars must be between 1 and 100000")
|
||||
if not isinstance(max_instructions, int) or isinstance(max_instructions, bool) or max_instructions < 1 or max_instructions > 5000:
|
||||
raise ValueError("max_instructions must be between 1 and 5000")
|
||||
addresses, instruction_scan_truncated = _instruction_addresses(procedure, max_instructions)
|
||||
addresses, instruction_scan_truncated = _instruction_addresses(procedure)
|
||||
blocks = []
|
||||
all_blocks = list(procedure.basicBlockIterator())
|
||||
for block in all_blocks:
|
||||
@@ -732,7 +518,7 @@ def _analyze_function(document, params):
|
||||
"successors": sorted(set(successors), key=lambda value: int(value, 16)),
|
||||
})
|
||||
pseudo = _pseudocode(document, procedure) or ""
|
||||
assembly_lines = _assembly(procedure, max_instructions).splitlines() if params.get("include_assembly", False) else []
|
||||
assembly_lines = _assembly(procedure).splitlines()
|
||||
callers = sorted((_procedure_identity(item) for item in procedure.getAllCallerProcedures()), key=lambda item: int(item["address"], 16))
|
||||
callees = sorted((_procedure_identity(item) for item in procedure.getAllCalleeProcedures()), key=lambda item: int(item["address"], 16))
|
||||
comments = []
|
||||
@@ -785,28 +571,17 @@ def _analyze_function(document, params):
|
||||
comments.sort(key=lambda item: (int(item["address"], 16), item["kind"]))
|
||||
referenced_strings.sort(key=lambda item: (int(item["address"], 16), int(item["source_address"], 16)))
|
||||
referenced_names.sort(key=lambda item: (int(item["address"], 16), int(item["source_address"], 16)))
|
||||
pseudo_text = pseudo[pseudocode_offset:pseudocode_offset + max_chars]
|
||||
pseudo_next = pseudocode_offset + len(pseudo_text)
|
||||
def collection(name, items, scan_limited=False):
|
||||
return _bounded(items, _collection_offset(params, name), limit, None, scan_limited)
|
||||
return {
|
||||
"procedure": {"address": _hex(procedure.getEntryPoint()), "name": _procedure_name(procedure), "classification": None, "signature": procedure.signatureString(), "locals": _procedure_locals(procedure)},
|
||||
"pseudocode": {"text": pseudo_text, "total_chars": len(pseudo), "returned_chars": len(pseudo_text), "truncated": pseudo_next < len(pseudo), "next_offset": pseudo_next if pseudo_next < len(pseudo) else None},
|
||||
"assembly": _bounded(
|
||||
assembly_lines,
|
||||
assembly_offset,
|
||||
max_instructions,
|
||||
None,
|
||||
instruction_scan_truncated if params.get("include_assembly", False) else False,
|
||||
),
|
||||
"comments": collection("comments", comments, instruction_scan_truncated),
|
||||
"callers": collection("callers", callers), "callees": collection("callees", callees),
|
||||
"incoming_references": collection("incoming_references", incoming, instruction_scan_truncated),
|
||||
"outgoing_references": collection("outgoing_references", outgoing, instruction_scan_truncated),
|
||||
"referenced_strings": collection("referenced_strings", referenced_strings, instruction_scan_truncated),
|
||||
"referenced_names": collection("referenced_names", referenced_names, instruction_scan_truncated),
|
||||
"basic_blocks": collection("basic_blocks", blocks),
|
||||
"instruction_scan": {"scanned": len(addresses), "truncated": instruction_scan_truncated},
|
||||
"pseudocode": pseudo,
|
||||
"assembly": assembly_lines,
|
||||
"comments": comments,
|
||||
"callers": callers, "callees": callees,
|
||||
"incoming_references": incoming,
|
||||
"outgoing_references": outgoing,
|
||||
"referenced_strings": referenced_strings,
|
||||
"referenced_names": referenced_names,
|
||||
"basic_blocks": blocks,
|
||||
"limitations": [
|
||||
"Hopper's public Python API does not classify reference kinds.",
|
||||
"Hopper's public Python API does not expose equivalent external or thunk classification in this dossier.",
|
||||
@@ -825,6 +600,13 @@ def _dispatch(method, params):
|
||||
document = _session_document()
|
||||
if document is None:
|
||||
return {"shutdown": True, "analysis_stopped": True, "document_closed": True}
|
||||
if method == "shutdown" and not REA_OWNS_PROCESS_LIFETIME:
|
||||
return {
|
||||
"shutdown": True,
|
||||
"analysis_stopped": not document.backgroundProcessActive(),
|
||||
"document_closed": False,
|
||||
"document_retained": True,
|
||||
}
|
||||
if document.backgroundProcessActive():
|
||||
document.requestBackgroundProcessStop()
|
||||
if method == "shutdown" and REA_OWNS_PROCESS_LIFETIME:
|
||||
@@ -968,24 +750,24 @@ def _dispatch(method, params):
|
||||
})
|
||||
return result
|
||||
if method == "list_procedures":
|
||||
return _page(dict(_search_inventory(document, "procedure")), params.get("offset", 0), params.get("limit", 100))
|
||||
return [{"address": address, "value": value} for address, value in _search_inventory(document, "procedure")]
|
||||
if method == "list_strings":
|
||||
values = dict(_search_inventory(document, "string"))
|
||||
requested = params.get("address")
|
||||
if requested is not None:
|
||||
key = _hex(_address(document, requested))
|
||||
values = {key: values[key]} if key in values else {}
|
||||
return _page(values, params.get("offset", 0), params.get("limit", 100))
|
||||
return [{"address": _hex(address), "value": value} for address, value in sorted(values.items())]
|
||||
if method == "list_names":
|
||||
result = dict(_search_inventory(document, "name"))
|
||||
requested = params.get("address")
|
||||
if requested is not None:
|
||||
key = _hex(_address(document, requested))
|
||||
result = {key: result[key]} if key in result else {}
|
||||
return _page(result, params.get("offset", 0), params.get("limit", 100))
|
||||
return [{"address": _hex(address), "value": value} for address, value in sorted(result.items(), key=lambda item: int(item[0]))]
|
||||
if method in ("search_procedures", "search_strings"):
|
||||
kind = "procedure" if method == "search_procedures" else "string"
|
||||
return _search_page(document, kind, params)
|
||||
return _search_results(document, kind, params)
|
||||
if method.startswith("procedure_"):
|
||||
procedure = _procedure(document, params.get("procedure"))
|
||||
if method == "procedure_address":
|
||||
@@ -1147,6 +929,7 @@ def _run():
|
||||
|
||||
|
||||
# Hopper's public objects are bound to its dedicated Python execution thread.
|
||||
# Keep dispatch on that thread; moving calls to an arbitrary worker can deadlock.
|
||||
# Keep dispatch on that thread; moving calls to a worker can deadlock.
|
||||
if __name__ == "__main__":
|
||||
_bind_session_document()
|
||||
_run()
|
||||
|
||||
Reference in New Issue
Block a user