diff --git a/bridge/ghidra/ReaGhidraBridge.java b/bridge/ghidra/ReaGhidraBridge.java index 144d80aea5..1012ce40b4 100644 --- a/bridge/ghidra/ReaGhidraBridge.java +++ b/bridge/ghidra/ReaGhidraBridge.java @@ -6,6 +6,7 @@ import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.Writer; import java.math.BigInteger; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -35,6 +36,7 @@ import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; @@ -42,6 +44,7 @@ import java.util.NavigableMap; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; @@ -49,6 +52,7 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; +import com.google.gson.JsonIOException; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonParser; @@ -65,6 +69,7 @@ import ghidra.app.util.bin.format.pdb.PdbParserConstants; import ghidra.app.util.opinion.ElfLoader; import ghidra.framework.options.Options; import ghidra.program.model.address.Address; +import ghidra.program.model.address.AddressFactory; import ghidra.program.model.address.AddressIterator; import ghidra.program.model.address.AddressSet; import ghidra.program.model.address.AddressSpace; @@ -89,6 +94,7 @@ import ghidra.program.model.listing.Data; import ghidra.program.model.listing.DataIterator; import ghidra.program.model.listing.Function; import ghidra.program.model.listing.FunctionIterator; +import ghidra.program.model.listing.FunctionManager; import ghidra.program.model.listing.Instruction; import ghidra.program.model.listing.InstructionIterator; import ghidra.program.model.listing.Listing; @@ -99,7 +105,6 @@ import ghidra.program.model.mem.MemoryBlockSourceInfo; import ghidra.program.database.mem.FileBytes; import ghidra.program.model.address.SegmentedAddress; import ghidra.program.model.reloc.Relocation; -import java.io.ByteArrayOutputStream; import ghidra.program.model.symbol.Namespace; import ghidra.program.model.symbol.FlowType; import ghidra.program.model.symbol.RefType; @@ -109,6 +114,8 @@ import ghidra.program.model.symbol.SourceType; import ghidra.program.model.symbol.Symbol; import ghidra.program.model.symbol.SymbolIterator; import ghidra.program.model.symbol.SymbolTable; +import ghidra.program.model.symbol.SymbolType; +import ghidra.program.model.symbol.SymbolUtilities; import ghidra.program.model.pcode.FunctionPrototype; import ghidra.program.model.pcode.HighFunction; import ghidra.program.model.pcode.HighParam; @@ -132,7 +139,15 @@ public final class ReaGhidraBridge extends HeadlessScript { private static final int DEFAULT_HIGH_PCODE_INPUTS_PER_OP = 64; private static final int DEFAULT_HIGH_PCODE_DEF_USE_EDGES = 12000; private static final Gson GSON = new GsonBuilder().serializeNulls().create(); + private static final Map NORMALIZED_SYMBOL_TYPES = new ConcurrentHashMap<>(); + private static final Map NORMALIZED_SOURCES = new ConcurrentHashMap<>(); + private static final Pattern NON_ALNUM_RUN = Pattern.compile("[^a-z0-9]+"); + private static final Pattern EDGE_UNDERSCORES = Pattern.compile("^_+|_+$"); + private static final Pattern FS_PTR_PREFIX = + Pattern.compile("(?i)\\b(?:byte|word|dword|qword)\\s+ptr\\s+"); + private static final Pattern WHITESPACE_RUN = Pattern.compile("\\s+"); private final Map targetSourceIdentity = new IdentityHashMap<>(); + private final Map originalFileBytesSha256 = new IdentityHashMap<>(); private final NavigableMap loaderInitializedRelocations = new TreeMap<>(); private String admittedTargetSha256; @@ -186,9 +201,10 @@ public final class ReaGhidraBridge extends HeadlessScript { "xrefs" }; - private List nameInventory; - private List procedureInventory; - private List stringInventory; + private List nameInventory; + private List procedureInventory; + private Map procedureNameIndex; + private List stringInventory; private DecompInterface decompiler; private boolean existingProject; // A refused Program may only report its admission failure to the client. @@ -669,6 +685,11 @@ public final class ReaGhidraBridge extends HeadlessScript { } private String hashFileBytes(FileBytes source, boolean modified) throws Exception { + if (!modified) { + // Original FileBytes are immutable across analysis edits. + String cached = originalFileBytesSha256.get(source); + if (cached != null) return cached; + } MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] chunk = new byte[65536]; for (long offset = 0; offset < source.getSize();) { @@ -681,7 +702,11 @@ public final class ReaGhidraBridge extends HeadlessScript { digest.update(chunk, 0, read); offset += read; } - return bytesHex(digest.digest()); + String hash = bytesHex(digest.digest()); + if (!modified) { + originalFileBytesSha256.put(source, hash); + } + return hash; } private String hashMemory(Address start, long length) throws Exception { @@ -1421,10 +1446,7 @@ public final class ReaGhidraBridge extends HeadlessScript { throw new RequestFailure("invalid_request", "direction must be incoming or outgoing"); } List references = collectReferences(function, direction); - JsonArray edges = new JsonArray(); - for (Reference reference : references) { - edges.add(referenceEdge(reference)); - } + JsonArray edges = referenceEdges(references); JsonObject result = new JsonObject(); result.add("procedure", procedureIdentity(function)); result.addProperty("direction", direction); @@ -1744,10 +1766,11 @@ public final class ReaGhidraBridge extends HeadlessScript { return result; } - private void invalidateAnalysisCaches() { + // Renames and comments never mutate DefinedData string literals, so keep stringInventory intact. + private void invalidateSymbolAndDecompilerCaches() { nameInventory = null; procedureInventory = null; - stringInventory = null; + procedureNameIndex = null; if (decompiler != null) decompiler.flushCache(); } @@ -1790,7 +1813,7 @@ public final class ReaGhidraBridge extends HeadlessScript { if (params.has("name")) function.setName(leafName, SourceType.USER_DEFINED); monitor.checkCancelled(); - invalidateAnalysisCaches(); + invalidateSymbolAndDecompilerCaches(); JsonObject readback = annotationReadback(function); for (String field : List.of("name", "comment", "inline_comment")) { if (!params.has(field)) continue; @@ -1822,7 +1845,7 @@ public final class ReaGhidraBridge extends HeadlessScript { finally { currentProgram.endTransaction(transaction, commit); // Rollback also invalidates inventory and decompiler views. - invalidateAnalysisCaches(); + invalidateSymbolAndDecompilerCaches(); } } @@ -1901,8 +1924,10 @@ public final class ReaGhidraBridge extends HeadlessScript { .filter(reference -> !function.getBody().contains(reference.getFromAddress())) .toList(); List outgoingReferences = collectReferences(function, "outgoing"); - JsonArray incoming = referenceEdges(incomingReferences); - JsonArray outgoing = referenceEdges(outgoingReferences); + Map resolvedFunctions = new HashMap<>(); + Map procedureIdentities = new HashMap<>(); + JsonArray incoming = referenceEdges(incomingReferences, resolvedFunctions, procedureIdentities); + JsonArray outgoing = referenceEdges(outgoingReferences, resolvedFunctions, procedureIdentities); JsonArray comments = comments(function); Set callerFunctions = function.getCallingFunctions(monitor); JsonArray callers = procedureIdentities(callerFunctions); @@ -2317,7 +2342,6 @@ public final class ReaGhidraBridge extends HeadlessScript { Symbol created = currentProgram.getSymbolTable().createLabel(address, target.leaf(), SourceType.USER_DEFINED); created.setPrimary(); } - invalidateAnalysisCaches(); Symbol readback = currentProgram.getSymbolTable().getPrimarySymbol(address); commit = readback != null && target.leaf().equals(readback.getName()); return commit ? null : "readback_mismatch"; @@ -2431,9 +2455,16 @@ public final class ReaGhidraBridge extends HeadlessScript { } // Independent edits have distinct destinations that no other address // holds, so their results do not depend on application order. - for (AddressNameTarget target : independent) { - String reason = applyAddressName(target); - if (reason != null) failures.put(target.address(), new AddressNameFailure(reason, null)); + try { + for (AddressNameTarget target : independent) { + String reason = applyAddressName(target); + if (reason != null) failures.put(target.address(), new AddressNameFailure(reason, null)); + } + } + finally { + if (!independent.isEmpty()) { + invalidateSymbolAndDecompilerCaches(); + } } // Requesters belong to exactly one destination, so ordering conflicts // by their first requester gives indexes independent of member order. @@ -2492,34 +2523,86 @@ public final class ReaGhidraBridge extends HeadlessScript { JsonObject result = new JsonObject(); result.addProperty("document", currentProgram.getName()); result.add("segments", segments()); - // Count the owning inventories, preserving their exact discovery rules - // without serializing function identities or string values for counts. - result.addProperty("procedure_count", procedures().size()); - result.addProperty("string_count", strings().size()); + // Preserve exact discovery deduplication and non-null string rules + // without materializing unrequested inventories in memory. + result.addProperty("procedure_count", countProcedures()); + result.addProperty("string_count", countStrings()); return result; } + private int countProcedures() throws Exception { + if (procedureInventory != null) { + return procedureInventory.size(); + } + Set
seen = new HashSet<>(); + countUniqueFunctions(seen, currentProgram.getFunctionManager().getFunctions(true)); + countUniqueFunctions(seen, currentProgram.getFunctionManager().getExternalFunctions()); + return seen.size(); + } + + private void countUniqueFunctions(Set
seen, FunctionIterator functions) throws Exception { + while (functions.hasNext()) { + monitor.checkCancelled(); + seen.add(functions.next().getEntryPoint()); + } + } + + private int countStrings() throws Exception { + if (stringInventory != null) { + return stringInventory.size(); + } + int count = 0; + DataIterator dataItems = currentProgram.getListing().getDefinedData(true); + while (dataItems.hasNext()) { + monitor.checkCancelled(); + Data data = dataItems.next(); + if (!data.hasStringValue()) { + continue; + } + if (StringDataInstance.getStringDataInstance(data).getStringValue() == null) { + continue; + } + count++; + } + return count; + } + private JsonArray listNames(JsonObject params) throws Exception { requireKeys(params, Set.of("document", "address")); requireDocument(params); - List inventory = names(); String requested = optionalString(params, "address"); if (requested != null) { Address address = parseReaAddress(requested); - inventory = inventory.stream() - .filter(item -> item.address.equals(address)) - .toList(); + if (nameInventory != null) { + return nameInventoryJson(sliceAtAddress(nameInventory, NameEntry::address, address)); + } + if (!address.isMemoryAddress() && !address.isExternalAddress()) { + return new JsonArray(); + } + List entries = new ArrayList<>(); + for (Symbol symbol : currentProgram.getSymbolTable().getSymbols(address)) { + monitor.checkCancelled(); + Address symbolAddress = symbol.getAddress(); + if (!symbolAddress.isMemoryAddress() && !symbolAddress.isExternalAddress()) { + continue; + } + entries.add(new NameEntry(symbolAddress, symbol.getName(true), symbolFacts(symbol))); + } + entries.sort(NAME_ORDER); + return nameInventoryJson(entries); } - return inventory(inventory, "symbol"); + return nameInventoryJson(names()); } private JsonArray listProcedures(JsonObject params) throws Exception { requireKeys(params, Set.of("document")); requireDocument(params); - List inventory = procedures().stream() - .map(FunctionEntry::item) - .toList(); - return inventory(inventory, "procedure"); + JsonArray result = new JsonArray(); + for (ProcedureEntry entry : procedures()) { + monitor.checkCancelled(); + result.add(resultItem(entry.address(), entry.value(), "procedure", entry.facts(), entry.symbol())); + } + return result; } private JsonArray listSegments(JsonObject params) { @@ -2545,15 +2628,21 @@ public final class ReaGhidraBridge extends HeadlessScript { private JsonArray listStrings(JsonObject params) throws Exception { requireKeys(params, Set.of("document", "address")); requireDocument(params); - List inventory = strings(); String requested = optionalString(params, "address"); if (requested != null) { Address address = parseReaAddress(requested); - inventory = inventory.stream() - .filter(item -> item.address.equals(address)) - .toList(); + if (stringInventory != null) { + return stringInventoryJson(sliceAtAddress(stringInventory, StringEntry::address, address)); + } + JsonArray result = new JsonArray(); + Data data = currentProgram.getListing().getDefinedDataAt(address); + StringEntry entry = data == null ? null : stringEntry(data); + if (entry != null) { + result.add(resultItem(entry.address(), entry.value(), "string", entry.facts(), null)); + } + return result; } - return inventory(inventory, "string"); + return stringInventoryJson(strings()); } private JsonElement procedureAddress(JsonObject params) throws Exception { @@ -2608,13 +2697,13 @@ public final class ReaGhidraBridge extends HeadlessScript { if (procedureSearch) { // Search the names exact lookup accepts, keeping one row per // procedure under its primary name. - for (FunctionEntry entry : procedures()) { + for (ProcedureEntry entry : procedures()) { monitor.checkCancelled(); ProcedureNameMatch match = matchProcedureNames(entry, matcher); if (!match.matched()) { continue; } - JsonObject item = resultItem(entry.item, "procedure"); + JsonObject item = resultItem(entry.address(), entry.value(), "procedure", entry.facts(), entry.symbol()); if (!match.aliases().isEmpty()) { JsonArray aliases = new JsonArray(); for (String alias : match.aliases()) aliases.add(alias); @@ -2624,12 +2713,12 @@ public final class ReaGhidraBridge extends HeadlessScript { } return items; } - for (InventoryItem item : strings()) { + for (StringEntry entry : strings()) { monitor.checkCancelled(); - if (!matcher.matches(item.value)) { + if (!matcher.matches(entry.value())) { continue; } - items.add(resultItem(item, procedureSearch ? "procedure" : "string")); + items.add(resultItem(entry.address(), entry.value(), "string", entry.facts(), null)); } return items; } @@ -2641,22 +2730,24 @@ public final class ReaGhidraBridge extends HeadlessScript { * body never names the procedure. Matching secondary symbols are reported * by their qualified names, sorted. */ - private ProcedureNameMatch matchProcedureNames(FunctionEntry entry, ValueMatcher matcher) throws Exception { - Function function = entry.function; - boolean primary = spellingMatches(function.getName(), entry.item.value, matcher); - Set aliases = null; - for (Symbol symbol : currentProgram.getSymbolTable().getSymbols(function.getEntryPoint())) { - monitor.checkCancelled(); - String qualified = symbol.getName(true); - if (!spellingMatches(symbol.getName(), qualified, matcher)) continue; - if (qualified.equals(entry.item.value)) { + private static ProcedureNameMatch matchProcedureNames(ProcedureEntry entry, ValueMatcher matcher) { + boolean primary = spellingMatches(entry.leafName(), entry.value(), matcher); + if (entry.aliases().isEmpty()) { + return new ProcedureNameMatch(primary, List.of()); + } + List matchedAliases = null; + for (ProcedureAlias alias : entry.aliases()) { + if (!spellingMatches(alias.leaf(), alias.qualified(), matcher)) continue; + if (alias.qualified().equals(entry.value())) { primary = true; continue; } - if (aliases == null) aliases = new TreeSet<>(); - aliases.add(qualified); + if (matchedAliases == null) matchedAliases = new ArrayList<>(2); + if (matchedAliases.isEmpty() || !matchedAliases.get(matchedAliases.size() - 1).equals(alias.qualified())) { + matchedAliases.add(alias.qualified()); + } } - return new ProcedureNameMatch(primary, aliases == null ? List.of() : List.copyOf(aliases)); + return new ProcedureNameMatch(primary, matchedAliases == null ? List.of() : matchedAliases); } /** A leaf is the suffix of its qualified spelling, so a literal found in it is found in both. */ @@ -2664,11 +2755,11 @@ public final class ReaGhidraBridge extends HeadlessScript { return matcher.matches(qualified) || (!leaf.equals(qualified) && matcher.matches(leaf)); } - private List names() throws Exception { + private List names() throws Exception { if (nameInventory != null) { return nameInventory; } - List result = new ArrayList<>(); + List result = new ArrayList<>(); SymbolIterator symbols = currentProgram.getSymbolTable().getAllSymbols(true); while (symbols.hasNext()) { monitor.checkCancelled(); @@ -2677,90 +2768,288 @@ public final class ReaGhidraBridge extends HeadlessScript { if (!address.isMemoryAddress() && !address.isExternalAddress()) { continue; } - JsonObject facts = symbolMetadata(symbol); - result.add(new InventoryItem(address, symbol.getName(true), facts, null)); + result.add(new NameEntry(address, symbol.getName(true), symbolFacts(symbol))); } - result.sort(INVENTORY_ORDER); + result.sort(NAME_ORDER); nameInventory = List.copyOf(result); return nameInventory; } - private List procedures() throws Exception { + private List procedures() throws Exception { if (procedureInventory != null) { return procedureInventory; } - List result = new ArrayList<>(); + List result = new ArrayList<>(); Set
seen = new HashSet<>(); appendFunctions(result, seen, currentProgram.getFunctionManager().getFunctions(true)); appendFunctions(result, seen, currentProgram.getFunctionManager().getExternalFunctions()); - result.sort((left, right) -> INVENTORY_ORDER.compare(left.item, right.item)); + result.sort(PROCEDURE_ORDER); procedureInventory = List.copyOf(result); return procedureInventory; } private void appendFunctions( - List destination, + List destination, Set
seen, FunctionIterator functions) throws Exception { + SymbolTable symbolTable = currentProgram.getSymbolTable(); while (functions.hasNext()) { monitor.checkCancelled(); Function function = functions.next(); - if (!seen.add(function.getEntryPoint())) { + Address entryPoint = function.getEntryPoint(); + if (!seen.add(entryPoint)) { continue; } - JsonObject facts = new JsonObject(); - facts.addProperty("external", function.isExternal()); - facts.addProperty("thunk", function.isThunk()); Function target = function.isThunk() ? function.getThunkedFunction(false) : null; - if (target == null) { - facts.add("thunk_target", JsonNull.INSTANCE); - } - else { - facts.addProperty("thunk_target", canonicalAddress(target.getEntryPoint())); - } - Symbol symbol = function.getSymbol(); - InventoryItem item = new InventoryItem( - function.getEntryPoint(), - symbol == null ? function.getName() : symbol.getName(true), - facts, - symbol == null ? null : symbolMetadata(symbol) + ProcedureFacts facts = new ProcedureFacts( + function.isExternal(), + function.isThunk(), + target == null ? null : target.getEntryPoint() ); - destination.add(new FunctionEntry(function, item)); + Symbol symbol = function.getSymbol(); + String leafName = function.getName(); + String value = symbol == null ? leafName : symbol.getName(true); + List aliases = List.of(); + for (Symbol candidate : symbolTable.getSymbols(entryPoint)) { + monitor.checkCancelled(); + String qualified = candidate.getName(true); + String candidateLeaf = candidate.getName(); + if (qualified.equals(value) && candidateLeaf.equals(leafName)) { + continue; + } + if (aliases.isEmpty()) { + aliases = new ArrayList<>(2); + } + aliases.add(new ProcedureAlias( + candidateLeaf.equals(qualified) ? qualified : candidateLeaf, + qualified + )); + } + if (aliases.size() > 1) { + aliases.sort(Comparator.comparing(ProcedureAlias::qualified)); + } + if (!aliases.isEmpty()) { + aliases = List.copyOf(aliases); + } + destination.add(new ProcedureEntry( + function, + entryPoint, + value, + leafName.equals(value) ? value : leafName, + aliases, + facts, + symbol == null ? null : symbolFacts(symbol) + )); } } - private List strings() throws Exception { + private List strings() throws Exception { if (stringInventory != null) { return stringInventory; } - List result = new ArrayList<>(); + List result = new ArrayList<>(); DataIterator dataItems = currentProgram.getListing().getDefinedData(true); while (dataItems.hasNext()) { monitor.checkCancelled(); - Data data = dataItems.next(); - if (!data.hasStringValue()) { - continue; + StringEntry entry = stringEntry(dataItems.next()); + if (entry != null) { + result.add(entry); } - StringDataInstance instance = StringDataInstance.getStringDataInstance(data); - String value = instance.getStringValue(); - if (value == null) { - continue; - } - JsonObject facts = new JsonObject(); - String charset = instance.getCharsetName(); - facts.addProperty("encoding", charset == null || charset.isEmpty() ? "unknown" : charset); - facts.addProperty( - "termination", - instance.isMissingNullTerminator() ? "missing" : "present_or_not_required" - ); - facts.addProperty("byte_length", Math.max(0, data.getLength())); - result.add(new InventoryItem(data.getAddress(), value, facts, null)); } - result.sort(INVENTORY_ORDER); + result.sort(STRING_ORDER); stringInventory = List.copyOf(result); return stringInventory; } + private static StringEntry stringEntry(Data data) { + if (!data.hasStringValue()) { + return null; + } + StringDataInstance instance = StringDataInstance.getStringDataInstance(data); + String value = instance.getStringValue(); + if (value == null) { + return null; + } + String charset = instance.getCharsetName(); + StringFacts facts = new StringFacts( + charset == null || charset.isEmpty() ? "unknown" : charset, + instance.isMissingNullTerminator(), + Math.max(0, data.getLength()) + ); + return new StringEntry(data.getAddress(), value, facts); + } + + private Map procedureIndex() { + if (procedureNameIndex != null) { + return procedureNameIndex; + } + Map index = new HashMap<>(procedureInventory.size() * 2); + for (ProcedureEntry entry : procedureInventory) { + Function function = entry.function(); + indexProcedureName(index, entry.value(), function); + if (!entry.leafName().equals(entry.value())) { + indexProcedureName(index, entry.leafName(), function); + } + for (ProcedureAlias alias : entry.aliases()) { + indexProcedureName(index, alias.qualified(), function); + if (!alias.leaf().equals(alias.qualified())) { + indexProcedureName(index, alias.leaf(), function); + } + } + } + procedureNameIndex = index; + return index; + } + + private static void indexProcedureName(Map index, String name, Function function) { + Object existing = index.get(name); + if (existing == null) { + index.put(name, function); + return; + } + if (existing instanceof Function single) { + if (!single.getEntryPoint().equals(function.getEntryPoint())) { + List list = new ArrayList<>(2); + list.add(single); + list.add(function); + index.put(name, list); + } + return; + } + @SuppressWarnings("unchecked") + List list = (List) existing; + if (!list.get(list.size() - 1).getEntryPoint().equals(function.getEntryPoint())) { + list.add(function); + } + } + + private Function resolveProcedureByName(String value) throws Exception { + if (procedureInventory != null) { + Object hit = procedureIndex().get(value); + if (hit == null) return null; + if (hit instanceof Function function) return function; + @SuppressWarnings("unchecked") + List matches = (List) hit; + throw ambiguousProcedureFailure(value, matches); + } + List matches = resolveProcedureCandidatesDirect(value); + if (matches.size() > 1) { + throw ambiguousProcedureFailure(value, matches); + } + return matches.size() == 1 ? matches.get(0) : null; + } + + private List resolveProcedureCandidatesDirect(String value) throws Exception { + SymbolTable symbolTable = currentProgram.getSymbolTable(); + FunctionManager functionManager = currentProgram.getFunctionManager(); + AddressFactory addressFactory = currentProgram.getAddressFactory(); + TreeMap candidates = new TreeMap<>(); + + // Ghidra leaf names can contain "::" (for example namespace "ns" + leaf + // "other::work" -> "ns::other::work"). Try every "::" suffix because + // SymbolTable.getSymbols(name) indexes leaf spellings rather than full paths. + Set candidateLeafNames = new LinkedHashSet<>(); + addProcedureLookupCandidate(candidateLeafNames, value); + int separator = value.indexOf("::"); + while (separator >= 0 && separator + 2 < value.length()) { + addProcedureLookupCandidate(candidateLeafNames, value.substring(separator + 2)); + separator = value.indexOf("::", separator + 1); + } + + for (String candidateName : candidateLeafNames) { + monitor.checkCancelled(); + SymbolIterator symbols = symbolTable.getSymbols(candidateName); + while (symbols.hasNext()) { + monitor.checkCancelled(); + addCandidateFunctionAndThunks(candidates, functionManager, symbols.next().getAddress()); + } + Address dynamicAddress = SymbolUtilities.parseDynamicName(addressFactory, candidateName); + if (dynamicAddress != null) { + addCandidateFunctionAndThunks(candidates, functionManager, dynamicAddress); + } + } + + if (candidates.isEmpty()) { + return List.of(); + } + List matches = new ArrayList<>(candidates.size() == 1 ? 1 : 4); + for (Function function : candidates.values()) { + monitor.checkCancelled(); + if (procedureExactMatch(symbolTable, function, value)) { + matches.add(function); + } + } + return matches; + } + + private static void addProcedureLookupCandidate(Set candidates, String candidate) { + if (!candidate.isEmpty()) { + candidates.add(candidate); + } + String stripped = candidate; + while (stripped.startsWith("thunk_")) { + stripped = stripped.substring("thunk_".length()); + if (!stripped.isEmpty()) { + candidates.add(stripped); + } + } + } + + private void addCandidateFunctionAndThunks( + TreeMap candidates, + FunctionManager functionManager, + Address address + ) throws Exception { + if (!address.isMemoryAddress() && !address.isExternalAddress()) { + return; + } + Function function = functionManager.getFunctionAt(address); + if (function == null) { + return; + } + if (candidates.putIfAbsent(function.getEntryPoint(), function) == null) { + Address[] thunkAddresses = function.getFunctionThunkAddresses(true); + if (thunkAddresses != null) { + for (Address thunkAddress : thunkAddresses) { + monitor.checkCancelled(); + Function thunk = functionManager.getFunctionAt(thunkAddress); + if (thunk != null) { + candidates.putIfAbsent(thunk.getEntryPoint(), thunk); + } + } + } + } + } + + private static boolean procedureExactMatch( + SymbolTable symbolTable, + Function function, + String value + ) { + if (function.getName().equals(value)) { + return true; + } + Symbol primarySymbol = function.getSymbol(); + if (primarySymbol != null && primarySymbol.getName(true).equals(value)) { + return true; + } + for (Symbol symbol : symbolTable.getSymbols(function.getEntryPoint())) { + if (symbol.getName().equals(value) || symbol.getName(true).equals(value)) { + return true; + } + } + return false; + } + + private static RequestFailure ambiguousProcedureFailure(String value, List matches) { + return new RequestFailure( + "procedure_ambiguous", + "Ghidra procedure name is ambiguous: " + value + + "; select an exact entry address from " + matches.stream() + .map(function -> canonicalAddress(function.getEntryPoint())).toList() + ); + } + private Function resolveProcedure(String value) throws Exception { // Explicit address syntax wins; an unprefixed identifier is first an // exact symbol name, even when every character is a hexadecimal digit. @@ -2768,17 +3057,8 @@ public final class ReaGhidraBridge extends HeadlessScript { if (!explicitAddress) { // Imported labels (for example Mach-O _main) can share a function // entry without becoming its primary symbol; search accepts the same. - ValueMatcher selector = value::equals; - List matches = new ArrayList<>(); - for (FunctionEntry entry : procedures()) { - monitor.checkCancelled(); - if (matchProcedureNames(entry, selector).matched()) matches.add(entry.function); - } - if (matches.size() > 1) - throw new RequestFailure("procedure_ambiguous", "Ghidra procedure name is ambiguous: " + value + - "; select an exact entry address from " + matches.stream() - .map(function -> canonicalAddress(function.getEntryPoint())).toList()); - if (matches.size() == 1) return matches.get(0); + Function matched = resolveProcedureByName(value); + if (matched != null) return matched; } // Retain legacy bare-hex address input only when no symbol matches. Address address = explicitAddress ? parseReaAddress(value) : tryParseAddress(value); @@ -2908,16 +3188,36 @@ public final class ReaGhidraBridge extends HeadlessScript { } JumpTable[] recoveredJumpTables = highFunction.getJumpTables(); - List caseTokens = new ArrayList<>(); - if (decompilation.getCCodeMarkup() != null) { - decompilation.getCCodeMarkup().flatten(caseTokens); - } - for (int index = 0; index < recoveredJumpTables.length; index += 1) { - jumpTables.add(inferredJumpTable(recoveredJumpTables[index], caseTokens)); + if (recoveredJumpTables.length > 0) { + List caseTokens = new ArrayList<>(); + ClangNode markup = decompilation.getCCodeMarkup(); + if (markup != null) { + collectCaseTokens(markup, caseTokens); + } + for (int index = 0; index < recoveredJumpTables.length; index += 1) { + jumpTables.add(inferredJumpTable(recoveredJumpTables[index], caseTokens)); + } } return result; } + private static void collectCaseTokens(ClangNode root, List caseTokens) { + ArrayDeque stack = new ArrayDeque<>(); + stack.push(root); + while (!stack.isEmpty()) { + ClangNode node = stack.pop(); + if (node instanceof ClangCaseToken) { + caseTokens.add(node); + } + for (int index = node.numChildren() - 1; index >= 0; index -= 1) { + ClangNode child = node.Child(index); + if (child != null) { + stack.push(child); + } + } + } + } + private JsonArray prototypeConflicts( Function function, FunctionPrototype prototype, @@ -4346,12 +4646,17 @@ public final class ReaGhidraBridge extends HeadlessScript { calls.observe(reference); } List computedCallSites = new ArrayList<>(); + boolean checkRelocations = !loaderInitializedRelocations.isEmpty(); for (Instruction instruction : instructions) { - boundary.observe(instruction); FlowType flow = instruction.getFlowType(); - if (!flow.isCall()) continue; + boolean isCall = flow.isCall(); + Reference[] referencesFrom = (checkRelocations || isCall) + ? instruction.getReferencesFrom() + : null; + boundary.observe(instruction, referencesFrom); + if (!isCall) continue; boolean destination = false; - for (Reference reference : instruction.getReferencesFrom()) { + for (Reference reference : referencesFrom) { if (!reference.getReferenceType().isCall()) continue; destination = true; break; @@ -4372,6 +4677,7 @@ public final class ReaGhidraBridge extends HeadlessScript { private final class FunctionBoundaryLimitations { private final Function function; + private final boolean checkLoaderRelocations = !loaderInitializedRelocations.isEmpty(); private final List limitations = new ArrayList<>(); private boolean inferredNoReturnCall; private final Set
observedLoaderRelocations = new HashSet<>(); @@ -4383,20 +4689,26 @@ public final class ReaGhidraBridge extends HeadlessScript { } private void observe(Instruction instruction) throws Exception { + observe(instruction, checkLoaderRelocations ? instruction.getReferencesFrom() : null); + } + + private void observe(Instruction instruction, Reference[] referencesFrom) throws Exception { monitor.checkCancelled(); TerminalCall terminal = terminalCall(instruction); if (terminal != null) { limitations.add(terminal.limitation()); if (terminal.inferredNoReturn()) inferredNoReturnCall = true; } - for (Reference reference : instruction.getReferencesFrom()) { - if (!reference.getReferenceType().isRead()) continue; - LoaderInitializedRelocation relocation = loaderInitializedRelocationAt( - reference.getToAddress() - ); - if (relocation == null || !observedLoaderRelocations.add(relocation.address())) - continue; - limitations.add(loaderInitializedRelocationLimitation(relocation)); + if (checkLoaderRelocations && referencesFrom != null) { + for (Reference reference : referencesFrom) { + if (!reference.getReferenceType().isRead()) continue; + LoaderInitializedRelocation relocation = loaderInitializedRelocationAt( + reference.getToAddress() + ); + if (relocation == null || !observedLoaderRelocations.add(relocation.address())) + continue; + limitations.add(loaderInitializedRelocationLimitation(relocation)); + } } if (beforePrevious != null && previous != null) { String seh = borlandSehHandlerLimitation( @@ -4498,10 +4810,11 @@ public final class ReaGhidraBridge extends HeadlessScript { private static String normalizedFsMemoryOperand(Instruction instruction) { String representation = instruction.getDefaultOperandRepresentation(0); - representation = representation.replaceAll("(?i)\\b(?:byte|word|dword|qword)\\s+ptr\\s+", "") - .replaceAll("\\s+", ""); - return representation.regionMatches(true, 0, "fs:", 0, 3) && - representation.indexOf('[') >= 0 ? representation : null; + if (representation.indexOf('[') < 0) return null; + representation = WHITESPACE_RUN.matcher( + FS_PTR_PREFIX.matcher(representation).replaceAll("") + ).replaceAll(""); + return representation.regionMatches(true, 0, "fs:", 0, 3) ? representation : null; } private static boolean hasRegisterOperand( @@ -4694,31 +5007,64 @@ public final class ReaGhidraBridge extends HeadlessScript { } private JsonArray referenceEdges(List references) { + return referenceEdges(references, new HashMap<>(), new HashMap<>()); + } + + private JsonArray referenceEdges( + List references, + Map resolvedFunctions, + Map procedureIdentities + ) { JsonArray result = new JsonArray(); for (Reference reference : references) { - result.add(referenceEdge(reference)); + result.add(referenceEdge(reference, resolvedFunctions, procedureIdentities)); } return result; } - private JsonObject referenceEdge(Reference reference) { + private JsonObject referenceEdge( + Reference reference, + Map resolvedFunctions, + Map procedureIdentities + ) { JsonObject result = new JsonObject(); - result.addProperty("source_address", canonicalAddress(reference.getFromAddress())); - result.addProperty("target_address", canonicalAddress(reference.getToAddress())); - Function source = functionAtOrContaining(reference.getFromAddress()); - Function target = functionAtOrContaining(reference.getToAddress()); + Address fromAddress = reference.getFromAddress(); + Address toAddress = reference.getToAddress(); + result.addProperty("source_address", canonicalAddress(fromAddress)); + result.addProperty("target_address", canonicalAddress(toAddress)); + Function source = cachedFunctionAtOrContaining(resolvedFunctions, fromAddress); + Function target = cachedFunctionAtOrContaining(resolvedFunctions, toAddress); result.add( "source_procedure", - source == null ? JsonNull.INSTANCE : procedureIdentity(source) + source == null ? JsonNull.INSTANCE : cachedProcedureIdentity(procedureIdentities, source) ); result.add( "target_procedure", - target == null ? JsonNull.INSTANCE : procedureIdentity(target) + target == null ? JsonNull.INSTANCE : cachedProcedureIdentity(procedureIdentities, target) ); result.add("kind", referenceKind(reference)); return result; } + private Function cachedFunctionAtOrContaining(Map cache, Address address) { + if (!cache.containsKey(address)) { + Function resolved = functionAtOrContaining(address); + cache.put(address, resolved); + return resolved; + } + return cache.get(address); + } + + private static JsonObject cachedProcedureIdentity(Map cache, Function function) { + Address entry = function.getEntryPoint(); + JsonObject identity = cache.get(entry); + if (identity == null) { + identity = procedureIdentity(function); + cache.put(entry, identity); + } + return identity; + } + private static JsonObject referenceKind(Reference reference) { RefType type = reference.getReferenceType(); JsonObject result = new JsonObject(); @@ -4866,9 +5212,10 @@ public final class ReaGhidraBridge extends HeadlessScript { return result; } - private JsonArray referencedStrings(List references) { + private JsonArray referencedStrings(List references) throws Exception { TreeMap observed = new TreeMap<>(); for (Reference reference : references) { + monitor.checkCancelled(); Data data = currentProgram.getListing().getDefinedDataContaining( reference.getToAddress() ); @@ -4892,9 +5239,10 @@ public final class ReaGhidraBridge extends HeadlessScript { return result; } - private JsonArray referencedNames(List references) { + private JsonArray referencedNames(List references) throws Exception { TreeMap observed = new TreeMap<>(); for (Reference reference : references) { + monitor.checkCancelled(); Symbol symbol = currentProgram.getSymbolTable().getPrimarySymbol( reference.getToAddress() ); @@ -4950,7 +5298,7 @@ public final class ReaGhidraBridge extends HeadlessScript { @Override public boolean evaluateContextBefore(VarnodeContext context, Instruction instruction) { // Returning true ends only the current flow, so every queued flow checks the shared stop. - if (budget.stopped()) return true; + if ((monitor != null && monitor.isCancelled()) || budget.stopped()) return true; FlowType flow = instruction.getFlowType(); Address[] flowTargets = instruction.getFlows(); boolean unresolvedJump = flow.isJump() && !flow.isConditional() && flowTargets.length == 0; @@ -4975,6 +5323,7 @@ public final class ReaGhidraBridge extends HeadlessScript { break; } value = selectedValue(function, instruction, register); + if (monitor != null && monitor.isCancelled()) return true; selectedValues.put(provenanceKey, value); } if (value) { @@ -5019,6 +5368,7 @@ public final class ReaGhidraBridge extends HeadlessScript { return false; } }, false, monitor); + monitor.checkCancelled(); JsonArray literals = new JsonArray(); observed.values().forEach(literals::add); JsonArray omissions = new JsonArray(); @@ -5077,6 +5427,7 @@ public final class ReaGhidraBridge extends HeadlessScript { targets.push(register.getBaseRegister()); } while (!instructions.isEmpty()) { + if (monitor != null && monitor.isCancelled()) return false; Instruction instruction = instructions.pop(); Register target = targets.pop(); if (!visited.add(canonicalAddress(instruction.getAddress()) + "\u0000" + target.getName())) continue; @@ -5300,26 +5651,64 @@ public final class ReaGhidraBridge extends HeadlessScript { return value.replaceAll("[\\r\\n]+", " "); } - private JsonArray inventory( - List inventory, - String factsName) throws Exception { + private JsonArray nameInventoryJson(List entries) throws Exception { JsonArray result = new JsonArray(); - for (InventoryItem item : inventory) { + for (NameEntry entry : entries) { monitor.checkCancelled(); - result.add(resultItem(item, factsName)); + result.add(resultItem(entry.address(), entry.value(), "symbol", entry.facts(), null)); } return result; } - private static JsonObject resultItem(InventoryItem item, String factsName) { - JsonObject result = new JsonObject(); - result.addProperty("address", canonicalAddress(item.address)); - result.addProperty("value", item.value); - if (factsName != null) { - result.add(factsName, item.facts.deepCopy()); + private JsonArray stringInventoryJson(List entries) throws Exception { + JsonArray result = new JsonArray(); + for (StringEntry entry : entries) { + monitor.checkCancelled(); + result.add(resultItem(entry.address(), entry.value(), "string", entry.facts(), null)); } - if (item.symbol != null) { - result.add("symbol", item.symbol.deepCopy()); + return result; + } + + private static List sliceAtAddress( + List sortedEntries, + java.util.function.Function addressExtractor, + Address target + ) { + int low = 0; + int high = sortedEntries.size(); + while (low < high) { + int mid = (low + high) >>> 1; + if (addressExtractor.apply(sortedEntries.get(mid)).compareTo(target) < 0) { + low = mid + 1; + } else { + high = mid; + } + } + if (low >= sortedEntries.size() || !addressExtractor.apply(sortedEntries.get(low)).equals(target)) { + return List.of(); + } + int end = low + 1; + while (end < sortedEntries.size() && addressExtractor.apply(sortedEntries.get(end)).equals(target)) { + end++; + } + return sortedEntries.subList(low, end); + } + + private static JsonObject resultItem( + Address address, + String value, + String factsName, + InventoryFacts facts, + SymbolFacts symbol + ) { + JsonObject result = new JsonObject(); + result.addProperty("address", canonicalAddress(address)); + result.addProperty("value", value); + if (factsName != null) { + result.add(factsName, facts.toJson()); + } + if (symbol != null) { + result.add("symbol", symbol.toJson()); } return result; } @@ -5425,14 +5814,17 @@ public final class ReaGhidraBridge extends HeadlessScript { } private static String canonicalAddress(Address address) { - return canonicalOffset( + return canonicalHexOffset( address.getAddressSpace(), - new BigInteger(Long.toUnsignedString(address.getOffset())) + "0x" + Long.toHexString(address.getOffset()) ); } private static String canonicalOffset(AddressSpace space, BigInteger offset) { - String value = "0x" + offset.toString(16); + return canonicalHexOffset(space, "0x" + offset.toString(16)); + } + + private static String canonicalHexOffset(AddressSpace space, String value) { if (space.equals(sessionDefaultAddressSpace)) { return value; } @@ -5522,6 +5914,19 @@ public final class ReaGhidraBridge extends HeadlessScript { } private static String encodeAddressSpace(String value) { + for (int index = 0; index < value.length(); index++) { + char item = value.charAt(index); + if (!((item >= 'A' && item <= 'Z') || + (item >= 'a' && item <= 'z') || + (item >= '0' && item <= '9') || + item == '.' || item == '_' || item == '~' || item == '-')) { + return encodeAddressSpaceBytes(value); + } + } + return value; + } + + private static String encodeAddressSpaceBytes(String value) { StringBuilder result = new StringBuilder(); for (byte item : value.getBytes(StandardCharsets.UTF_8)) { int unsigned = Byte.toUnsignedInt(item); @@ -5571,42 +5976,91 @@ public final class ReaGhidraBridge extends HeadlessScript { } private static String normalizedSymbolType(Symbol symbol) { - String value = symbol.getSymbolType().toString() - .toLowerCase(Locale.ROOT) - .replaceAll("[^a-z0-9]+", "_") - .replaceAll("^_+|_+$", ""); - return value.isEmpty() ? "unknown" : value; + return NORMALIZED_SYMBOL_TYPES.computeIfAbsent(symbol.getSymbolType(), type -> { + String value = EDGE_UNDERSCORES.matcher( + NON_ALNUM_RUN.matcher(type.toString().toLowerCase(Locale.ROOT)).replaceAll("_") + ).replaceAll(""); + return value.isEmpty() ? "unknown" : value; + }); + } + + private static SymbolFacts symbolFacts(Symbol symbol) { + return new SymbolFacts( + symbol.isPrimary(), + symbol.isDynamic(), + symbol.isExternal(), + normalizedSymbolType(symbol), + normalizedSource(symbol.getSource()) + ); } private static JsonObject symbolMetadata(Symbol symbol) { - JsonObject facts = new JsonObject(); - facts.addProperty("primary", symbol.isPrimary()); - facts.addProperty("dynamic", symbol.isDynamic()); - facts.addProperty("external", symbol.isExternal()); - facts.addProperty("type", normalizedSymbolType(symbol)); - facts.addProperty("source", normalizedSource(symbol.getSource())); - return facts; + return symbolFacts(symbol).toJson(); } private static String normalizedSource(SourceType source) { - return source.name().toLowerCase(Locale.ROOT); + return NORMALIZED_SOURCES.computeIfAbsent(source, item -> item.name().toLowerCase(Locale.ROOT)); } private static ValueMatcher literalMatcher(String pattern) { return value -> value.contains(pattern); } - // REA's host owns Unicode simple folding. Keep all non-ASCII source values - // for its final predicate, and filter ASCII-only values without Java regexes. + // REA's host owns ECMAScript /iu simple case folding. Across all 1,114,112 + // Unicode code points, only U+017F (ſ -> s) and U+212A (K -> k) fold to + // ASCII. When asciiPattern is null, the pattern has a non-ASCII char without + // an ASCII fold, so only source strings containing non-ASCII stay eligible. private static ValueMatcher literalCandidateMatcher(String asciiPattern) { - if (asciiPattern != null && asciiPattern.chars().anyMatch(character -> character > 127)) - throw new RequestFailure("invalid_request", "ASCII candidate contains a non-ASCII character"); + if (asciiPattern == null) { + return value -> { + for (int index = 0; index < value.length(); index++) { + if (value.charAt(index) > 127) return true; + } + return false; + }; + } + int patternLength = asciiPattern.length(); + for (int index = 0; index < patternLength; index++) { + if (asciiPattern.charAt(index) > 127) { + throw new RequestFailure("invalid_request", "ASCII candidate contains a non-ASCII character"); + } + } + if (patternLength == 0) { + return value -> true; + } + char firstTarget = asciiPattern.charAt(0); return value -> { - if (value.chars().anyMatch(character -> character > 127)) return true; - return asciiPattern != null && value.toLowerCase(Locale.ROOT).contains(asciiPattern); + int valueLength = value.length(); + if (valueLength < patternLength) { + return false; + } + int limit = valueLength - patternLength; + for (int index = 0; index <= limit; index++) { + if (foldAsciiCandidateChar(value.charAt(index)) != firstTarget) { + continue; + } + int matched = 1; + while (matched < patternLength && + foldAsciiCandidateChar(value.charAt(index + matched)) == asciiPattern.charAt(matched)) { + matched++; + } + if (matched == patternLength) { + return true; + } + } + return false; }; } + private static int foldAsciiCandidateChar(char ch) { + if (ch <= 127) { + return (ch >= 'A' && ch <= 'Z') ? ch + ('a' - 'A') : ch; + } + if (ch == '\u017F') return 's'; + if (ch == '\u212A') return 'k'; + return -1; + } + private static ValueMatcher regexMatcher(String expression, boolean caseSensitive) { Pattern pattern; try { @@ -5854,21 +6308,124 @@ public final class ReaGhidraBridge extends HeadlessScript { } private static void writeResponse(BufferedWriter writer, JsonObject response) throws IOException { - String encoded = GSON.toJson(response); - // Gson leaves UTF-16 surrogates literal. Escape them in JSON so even - // diagnostics quoting ill-formed caller text remain lossless UTF-8. - int start = 0; - for (int index = 0; index < encoded.length(); index++) { - if (!Character.isSurrogate(encoded.charAt(index))) continue; - writer.write(encoded, start, index - start); - writer.write("\\u" + Integer.toHexString(encoded.charAt(index))); - start = index + 1; + try { + GSON.toJson(response, new SurrogateEscapingWriter(writer)); + } + catch (JsonIOException exception) { + if (exception.getCause() instanceof IOException ioException) { + throw ioException; + } + throw exception; } - writer.write(encoded, start, encoded.length() - start); writer.newLine(); writer.flush(); } + // Gson leaves UTF-16 surrogates literal. Stream directly to the socket + // writer while escaping surrogates so large replies avoid multi-x heap copies. + private static final class SurrogateEscapingWriter extends Writer { + private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray(); + private final BufferedWriter delegate; + private final char[] surrogateEscape = { '\\', 'u', '0', '0', '0', '0' }; + + private SurrogateEscapingWriter(BufferedWriter delegate) { + this.delegate = delegate; + } + + private void writeSurrogateEscape(char ch) throws IOException { + surrogateEscape[2] = HEX_DIGITS[(ch >>> 12) & 0xf]; + surrogateEscape[3] = HEX_DIGITS[(ch >>> 8) & 0xf]; + surrogateEscape[4] = HEX_DIGITS[(ch >>> 4) & 0xf]; + surrogateEscape[5] = HEX_DIGITS[ch & 0xf]; + delegate.write(surrogateEscape, 0, 6); + } + + @Override + public void write(int ch) throws IOException { + char value = (char) ch; + if (Character.isSurrogate(value)) { + writeSurrogateEscape(value); + } else { + delegate.write(ch); + } + } + + @Override + public void write(char[] cbuf, int off, int len) throws IOException { + java.util.Objects.checkFromIndexSize(off, len, cbuf.length); + int start = off; + int end = off + len; + for (int index = off; index < end; index++) { + char ch = cbuf[index]; + if (!Character.isSurrogate(ch)) continue; + if (index > start) { + delegate.write(cbuf, start, index - start); + } + writeSurrogateEscape(ch); + start = index + 1; + } + if (end > start) { + delegate.write(cbuf, start, end - start); + } + } + + @Override + public void write(String str, int off, int len) throws IOException { + java.util.Objects.checkFromIndexSize(off, len, str.length()); + int start = off; + int end = off + len; + for (int index = off; index < end; index++) { + char ch = str.charAt(index); + if (!Character.isSurrogate(ch)) continue; + if (index > start) { + delegate.write(str, start, index - start); + } + writeSurrogateEscape(ch); + start = index + 1; + } + if (end > start) { + delegate.write(str, start, end - start); + } + } + + @Override + public Writer append(CharSequence csq) throws IOException { + if (csq == null) { + delegate.write("null"); + } else if (csq instanceof String str) { + write(str, 0, str.length()); + } else { + append(csq, 0, csq.length()); + } + return this; + } + + @Override + public Writer append(CharSequence csq, int start, int end) throws IOException { + if (csq == null) { + delegate.write("null", start, end - start); + } else if (csq instanceof String str) { + write(str, start, end - start); + } else { + java.util.Objects.checkFromToIndex(start, end, csq.length()); + for (int index = start; index < end; index++) { + write(csq.charAt(index)); + } + } + return this; + } + + @Override + public void flush() { + // Caller issues writer.newLine() + writer.flush() once at frame end. + } + + @Override + public void close() { + // Socket writer outlives one response frame. + } + } + private static String safeMessage(Exception exception) { String message = exception.getMessage(); return message == null || message.isBlank() ? "operation failed" : message; @@ -5878,10 +6435,32 @@ public final class ReaGhidraBridge extends HeadlessScript { boolean matches(String value); } - private static final Comparator INVENTORY_ORDER = - Comparator.comparing(InventoryItem::address) - .thenComparing(InventoryItem::value) - .thenComparing(item -> GSON.toJson(item.facts)); + private interface InventoryFacts { + JsonObject toJson(); + } + + private static int compareInventory( + Address leftAddress, + String leftValue, + InventoryFacts leftFacts, + Address rightAddress, + String rightValue, + InventoryFacts rightFacts + ) { + int cmp = leftAddress.compareTo(rightAddress); + if (cmp != 0) return cmp; + cmp = leftValue.compareTo(rightValue); + if (cmp != 0) return cmp; + if (leftFacts.equals(rightFacts)) return 0; + return GSON.toJson(leftFacts.toJson()).compareTo(GSON.toJson(rightFacts.toJson())); + } + + private static final Comparator NAME_ORDER = (left, right) -> + compareInventory(left.address(), left.value(), left.facts(), right.address(), right.value(), right.facts()); + private static final Comparator PROCEDURE_ORDER = (left, right) -> + compareInventory(left.address(), left.value(), left.facts(), right.address(), right.value(), right.facts()); + private static final Comparator STRING_ORDER = (left, right) -> + compareInventory(left.address(), left.value(), left.facts(), right.address(), right.value(), right.facts()); private static final Comparator REFERENCE_ORDER = Comparator.comparing(Reference::getFromAddress) .thenComparing(Reference::getToAddress) @@ -5889,7 +6468,74 @@ public final class ReaGhidraBridge extends HeadlessScript { .thenComparingInt(Reference::getOperandIndex) .thenComparing(Reference::isPrimary); - private record InventoryItem(Address address, String value, JsonObject facts, JsonObject symbol) {} + private record SymbolFacts( + boolean primary, + boolean dynamic, + boolean external, + String type, + String source + ) implements InventoryFacts { + @Override + public JsonObject toJson() { + JsonObject facts = new JsonObject(); + facts.addProperty("primary", primary); + facts.addProperty("dynamic", dynamic); + facts.addProperty("external", external); + facts.addProperty("type", type); + facts.addProperty("source", source); + return facts; + } + } + + private record ProcedureFacts( + boolean external, + boolean thunk, + Address thunkTarget + ) implements InventoryFacts { + @Override + public JsonObject toJson() { + JsonObject facts = new JsonObject(); + facts.addProperty("external", external); + facts.addProperty("thunk", thunk); + if (thunkTarget == null) { + facts.add("thunk_target", JsonNull.INSTANCE); + } else { + facts.addProperty("thunk_target", canonicalAddress(thunkTarget)); + } + return facts; + } + } + + private record StringFacts( + String encoding, + boolean missingNullTerminator, + int byteLength + ) implements InventoryFacts { + @Override + public JsonObject toJson() { + JsonObject facts = new JsonObject(); + facts.addProperty("encoding", encoding); + facts.addProperty( + "termination", + missingNullTerminator ? "missing" : "present_or_not_required" + ); + facts.addProperty("byte_length", byteLength); + return facts; + } + } + + private record NameEntry(Address address, String value, SymbolFacts facts) {} + private record ProcedureAlias(String leaf, String qualified) {} + private record ProcedureEntry( + Function function, + Address address, + String value, + String leafName, + List aliases, + ProcedureFacts facts, + SymbolFacts symbol + ) {} + private record StringEntry(Address address, String value, StringFacts facts) {} private record AddressNameRequest(String inputAddress, Address address, String name) {} private record AddressNameDestination(long namespace, String leaf) {} private record AddressNameTarget(Address address, Namespace namespace, String leaf) { @@ -5909,7 +6555,6 @@ public final class ReaGhidraBridge extends HeadlessScript { return displacement >= 0 && displacement < lengthInAddressableUnits; } } - private record FunctionEntry(Function function, InventoryItem item) {} private record ProcedureNameMatch(boolean primary, List aliases) { boolean matched() { return primary || !aliases.isEmpty(); diff --git a/tests/boundary/providers/ghidra/ghidraBridgeHelpers.fixture.ts b/tests/boundary/providers/ghidra/ghidraBridgeHelpers.fixture.ts new file mode 100644 index 0000000000..99ed7c8488 --- /dev/null +++ b/tests/boundary/providers/ghidra/ghidraBridgeHelpers.fixture.ts @@ -0,0 +1,868 @@ +import { execFile } from "node:child_process"; +import { existsSync } from "node:fs"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { join, resolve } from "node:path"; +import { promisify } from "node:util"; + +const execute = promisify(execFile); + +const BRIDGE_SOURCE_PATH = resolve("bridge/ghidra/ReaGhidraBridge.java"); +const JAVA_BINARY = process.platform === "win32" ? "java.exe" : "java"; +const JAVAC_BINARY = process.platform === "win32" ? "javac.exe" : "javac"; + +export interface JdkToolchain { + readonly javac: string; + readonly java: string; + readonly versionLine: string; +} + +export interface CompiledBridgeProbe { + readonly classesDir: string; + readonly jdk: JdkToolchain; +} + +const candidateToolchains = (): readonly { javac: string; java: string }[] => { + const candidates: { javac: string; java: string }[] = []; + const envHomes = [ + process.env.JAVA_HOME, + process.env.JAVA_HOME_25_X64, + process.env.JAVA_HOME_25_ARM64, + process.env.JAVA_HOME_21_X64, + process.env.JAVA_HOME_21_ARM64, + ]; + for (const home of envHomes) { + if (home !== undefined && home !== "") { + candidates.push({ + javac: join(home, "bin", JAVAC_BINARY), + java: join(home, "bin", JAVA_BINARY), + }); + } + } + const systemBins = + process.platform === "darwin" + ? [ + "/opt/homebrew/opt/openjdk@21/bin", + "/opt/homebrew/opt/openjdk/bin", + "/usr/local/opt/openjdk@21/bin", + "/usr/local/opt/openjdk/bin", + ] + : process.platform === "linux" + ? [ + "/usr/lib/jvm/java-21-openjdk-amd64/bin", + "/usr/lib/jvm/java-21-openjdk-arm64/bin", + "/usr/lib/jvm/java-25-openjdk-amd64/bin", + "/usr/lib/jvm/java-25-openjdk-arm64/bin", + ] + : []; + for (const bin of systemBins) { + candidates.push({ + javac: join(bin, JAVAC_BINARY), + java: join(bin, JAVA_BINARY), + }); + } + candidates.push({ javac: JAVAC_BINARY, java: JAVA_BINARY }); + return candidates; +}; + +const probeToolchain = async ( + javac: string, + java: string, +): Promise => { + const isBareCommand = !javac.includes("/") && !javac.includes("\\"); + if (!isBareCommand && (!existsSync(javac) || !existsSync(java))) { + return undefined; + } + try { + const javacVersion = await execute(javac, ["-version"], { timeout: 5_000 }); + const banner = `${javacVersion.stdout}\n${javacVersion.stderr}`.trim(); + const major = Number(/^javac (\d+)/mu.exec(banner)?.[1]); + if (!Number.isInteger(major) || major < 21) { + return undefined; + } + await execute(java, ["-version"], { timeout: 5_000 }); + return { javac, java, versionLine: banner }; + } catch { + return undefined; + } +}; + +/** Locate a JDK 21+ compiler and runtime, returning undefined when absent. */ +export const discoverJdk21Toolchain = async (): Promise< + JdkToolchain | undefined +> => { + const seen = new Set(); + for (const candidate of candidateToolchains()) { + const key = `${candidate.javac}\0${candidate.java}`; + if (seen.has(key)) continue; + seen.add(key); + const toolchain = await probeToolchain(candidate.javac, candidate.java); + if (toolchain !== undefined) return toolchain; + } + return undefined; +}; + +/** Encode a UTF-16 JS string (including lone surrogates) as comma-separated hex code units. */ +export const encodeUtf16Hex = (value: string): string => { + const units: string[] = []; + for (let index = 0; index < value.length; index += 1) { + units.push(value.charCodeAt(index).toString(16).padStart(4, "0")); + } + return units.join(","); +}; + +const extractBridgeSlice = ( + source: string, + startMarker: string, + endMarker: string, +): string => { + const start = source.indexOf(startMarker); + if (start < 0) { + throw new Error(`Missing bridge start marker: ${startMarker}`); + } + const end = source.indexOf(endMarker, start); + if (end < 0) { + throw new Error(`Missing bridge end marker: ${endMarker}`); + } + return source.slice(start, end); +}; + +const extractRequestFailureSlice = (source: string): string => { + const startMarker = + " private static final class RequestFailure extends RuntimeException {"; + const start = source.indexOf(startMarker); + if (start < 0) { + throw new Error(`Missing bridge start marker: ${startMarker}`); + } + const lastBrace = source.lastIndexOf("}"); + if (lastBrace <= start) { + throw new Error("Missing closing brace in ReaGhidraBridge.java"); + } + return source.slice(start, lastBrace); +}; + +const JAVA_HEADER = String.raw` +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.TreeMap; + +public final class ReaGhidraBridgeHelperProbe { +`; + +const JAVA_GSON_STUBS = String.raw` + private static class JsonElement {} + private static final class JsonNull extends JsonElement { + static final JsonNull INSTANCE = new JsonNull(); + } + private static final class JsonPrimitive extends JsonElement { + private final Object value; + JsonPrimitive(String value) { this.value = value; } + JsonPrimitive(Number value) { this.value = value; } + JsonPrimitive(Boolean value) { this.value = value; } + boolean isString() { return value instanceof String; } + boolean isNumber() { return value instanceof Number; } + boolean isBoolean() { return value instanceof Boolean; } + String getAsString() { return (String) value; } + Number getAsNumber() { return (Number) value; } + boolean getAsBoolean() { return (Boolean) value; } + } + private static final class JsonArray extends JsonElement implements Iterable { + private final List items = new ArrayList<>(); + void add(JsonElement value) { items.add(value == null ? JsonNull.INSTANCE : value); } + void add(String value) { items.add(value == null ? JsonNull.INSTANCE : new JsonPrimitive(value)); } + @Override public Iterator iterator() { return items.iterator(); } + } + private static final class JsonObject extends JsonElement { + private final Map members = new LinkedHashMap<>(); + void add(String property, JsonElement value) { + members.put(property, value == null ? JsonNull.INSTANCE : value); + } + void addProperty(String property, String value) { + members.put(property, value == null ? JsonNull.INSTANCE : new JsonPrimitive(value)); + } + void addProperty(String property, Number value) { + members.put(property, value == null ? JsonNull.INSTANCE : new JsonPrimitive(value)); + } + void addProperty(String property, Boolean value) { + members.put(property, value == null ? JsonNull.INSTANCE : new JsonPrimitive(value)); + } + Set> entrySet() { return members.entrySet(); } + } + private static final class JsonIOException extends RuntimeException { + JsonIOException(String message) { super(message); } + JsonIOException(Throwable cause) { super(cause); } + } + + private static class Gson { + private static final String[] REPLACEMENT_CHARS = new String[128]; + static { + for (int i = 0; i <= 0x1f; i++) { + REPLACEMENT_CHARS[i] = String.format("\\u%04x", i); + } + REPLACEMENT_CHARS['"'] = "\\\""; + REPLACEMENT_CHARS['\\'] = "\\\\"; + REPLACEMENT_CHARS['\t'] = "\\t"; + REPLACEMENT_CHARS['\b'] = "\\b"; + REPLACEMENT_CHARS['\n'] = "\\n"; + REPLACEMENT_CHARS['\r'] = "\\r"; + REPLACEMENT_CHARS['\f'] = "\\f"; + REPLACEMENT_CHARS['<'] = "\\u003c"; + REPLACEMENT_CHARS['>'] = "\\u003e"; + REPLACEMENT_CHARS['&'] = "\\u0026"; + REPLACEMENT_CHARS['='] = "\\u003d"; + REPLACEMENT_CHARS['\''] = "\\u0027"; + } + private boolean useCharArrayWrites; + void setUseCharArrayWrites(boolean useCharArrayWrites) { + this.useCharArrayWrites = useCharArrayWrites; + } + void toJson(JsonElement element, Appendable appendable) { + Writer out = (Writer) appendable; + try { + writeElement(out, element); + } + catch (IOException exception) { + throw new JsonIOException(exception); + } + } + private void writeElement(Writer out, JsonElement element) throws IOException { + if (element == null || element instanceof JsonNull) { + out.append("null"); + } else if (element instanceof JsonPrimitive primitive) { + if (primitive.isBoolean()) { + out.write(primitive.getAsBoolean() ? "true" : "false"); + } else if (primitive.isNumber()) { + out.write(primitive.getAsNumber().toString()); + } else { + writeString(out, primitive.getAsString()); + } + } else if (element instanceof JsonArray array) { + out.write('['); + boolean first = true; + for (JsonElement item : array) { + if (!first) out.write(','); + first = false; + writeElement(out, item); + } + out.write(']'); + } else if (element instanceof JsonObject object) { + out.write('{'); + boolean first = true; + for (Map.Entry entry : object.entrySet()) { + if (!first) out.write(','); + first = false; + writeString(out, entry.getKey()); + out.write(':'); + writeElement(out, entry.getValue()); + } + out.write('}'); + } + } + private void writeString(Writer out, String value) throws IOException { + out.write('"'); + int last = 0; + int length = value.length(); + char[] chars = useCharArrayWrites ? value.toCharArray() : null; + for (int index = 0; index < length; index++) { + char c = value.charAt(index); + String replacement = null; + if (c < 128) { + replacement = REPLACEMENT_CHARS[c]; + } else if (c == '\u2028') { + replacement = "\\u2028"; + } else if (c == '\u2029') { + replacement = "\\u2029"; + } + if (replacement == null) continue; + if (last < index) { + if (chars != null) { + out.write(chars, last, index - last); + } else { + out.write(value, last, index - last); + } + } + out.write(replacement); + last = index + 1; + } + if (last < length) { + if (chars != null) { + out.write(chars, last, length - last); + } else { + out.write(value, last, length - last); + } + } + out.write('"'); + } + } + private static Gson GSON = new Gson(); +`; + +const JAVA_GHIDRA_STUBS = String.raw` + private interface Address extends Comparable
{ + boolean isMemoryAddress(); + boolean isExternalAddress(); + long getOffset(); + String canonical(); + } + private record StubAddress(long offset, boolean external) implements Address { + @Override public boolean isMemoryAddress() { return !external; } + @Override public boolean isExternalAddress() { return external; } + @Override public long getOffset() { return offset; } + @Override public String canonical() { + return (external ? "EXTERNAL:" : "") + "0x" + Long.toHexString(offset); + } + @Override public int compareTo(Address other) { + int kind = Boolean.compare(external, other.isExternalAddress()); + if (kind != 0) return kind; + return Long.compareUnsigned(offset, other.getOffset()); + } + } + private interface Symbol { + Address getAddress(); + String getName(); + String getName(boolean includeNamespace); + } + private record StubSymbol(Address address, String leafName, String qualifiedName) implements Symbol { + @Override public Address getAddress() { return address; } + @Override public String getName() { return leafName; } + @Override public String getName(boolean includeNamespace) { + return includeNamespace ? qualifiedName : leafName; + } + } + private interface SymbolIterator { + boolean hasNext(); + Symbol next(); + } + private interface SymbolTable { + SymbolIterator getSymbols(String name); + List getSymbols(Address address); + } + private static final class StubSymbolTable implements SymbolTable { + private final Map> byLeafName = new HashMap<>(); + private final Map> byAddress = new HashMap<>(); + void register(Symbol symbol, boolean indexByLeaf) { + byAddress.computeIfAbsent(symbol.getAddress(), k -> new ArrayList<>()).add(symbol); + if (indexByLeaf) { + byLeafName.computeIfAbsent(symbol.getName(), k -> new ArrayList<>()).add(symbol); + } + } + @Override public SymbolIterator getSymbols(String name) { + List found = byLeafName.getOrDefault(name, List.of()); + Iterator iterator = found.iterator(); + return new SymbolIterator() { + @Override public boolean hasNext() { return iterator.hasNext(); } + @Override public Symbol next() { return iterator.next(); } + }; + } + @Override public List getSymbols(Address address) { + return byAddress.getOrDefault(address, List.of()); + } + } + private interface Function { + Address getEntryPoint(); + String getName(); + Symbol getSymbol(); + Address[] getFunctionThunkAddresses(boolean includeExternal); + } + private static final class StubFunction implements Function { + private final Address entryPoint; + private final String name; + private final Symbol primarySymbol; + private final List
thunkAddresses = new ArrayList<>(); + StubFunction(Address entryPoint, String name, Symbol primarySymbol) { + this.entryPoint = entryPoint; + this.name = name; + this.primarySymbol = primarySymbol; + } + void addThunk(Address thunkAddress) { thunkAddresses.add(thunkAddress); } + @Override public Address getEntryPoint() { return entryPoint; } + @Override public String getName() { return name; } + @Override public Symbol getSymbol() { return primarySymbol; } + @Override public Address[] getFunctionThunkAddresses(boolean includeExternal) { + return thunkAddresses.isEmpty() ? null : thunkAddresses.toArray(Address[]::new); + } + } + private interface FunctionManager { + Function getFunctionAt(Address address); + } + private static final class StubFunctionManager implements FunctionManager { + private final Map functions = new LinkedHashMap<>(); + void register(Function function) { functions.put(function.getEntryPoint(), function); } + List all() { return List.copyOf(functions.values()); } + @Override public Function getFunctionAt(Address address) { return functions.get(address); } + } + private static final class AddressFactory { + private final Set
dynamicTargets = new LinkedHashSet<>(); + void registerDynamic(Address address) { dynamicTargets.add(address); } + boolean contains(Address address) { return dynamicTargets.contains(address); } + } + private static final class SymbolUtilities { + static Address parseDynamicName(AddressFactory factory, String name) { + if (!name.startsWith("FUN_")) return null; + try { + Address addr = new StubAddress(Long.parseUnsignedLong(name.substring(4), 16), false); + return factory.contains(addr) ? addr : null; + } + catch (NumberFormatException ignored) { + return null; + } + } + } + private static final class TaskMonitor { + void checkCancelled() throws Exception {} + } + private static final class StubProgram { + private final StubSymbolTable symbolTable = new StubSymbolTable(); + private final StubFunctionManager functionManager = new StubFunctionManager(); + private final AddressFactory addressFactory = new AddressFactory(); + StubSymbolTable getSymbolTable() { return symbolTable; } + StubFunctionManager getFunctionManager() { return functionManager; } + AddressFactory getAddressFactory() { return addressFactory; } + } + private record ProcedureFacts() {} + private record SymbolFacts() {} + private final StubProgram currentProgram = new StubProgram(); + private final TaskMonitor monitor = new TaskMonitor(); + private List procedureInventory; + private Map procedureNameIndex; + private static String canonicalAddress(Address address) { + return address.canonical(); + } +`; + +const JAVA_PROBE_DRIVER = String.raw` + private static String decodeHex(String hex) { + if (hex == null || hex.isEmpty()) return ""; + String[] parts = hex.split(","); + char[] chars = new char[parts.length]; + for (int index = 0; index < parts.length; index++) { + chars[index] = (char) Integer.parseInt(parts[index], 16); + } + return new String(chars); + } + + private static List readStdinLines() throws IOException { + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); + List lines = new ArrayList<>(); + String line; + while ((line = reader.readLine()) != null) { + lines.add(line); + } + return lines; + } + + private static void runFoldChar() throws IOException { + for (String line : readStdinLines()) { + char ch = (char) Integer.parseInt(line, 16); + System.out.println(foldAsciiCandidateChar(ch)); + } + } + + private static void runLiteralBatch() throws IOException { + for (String line : readStdinLines()) { + String[] fields = line.split("\\|", -1); + String pattern = "0".equals(fields[0]) ? null : decodeHex(fields[1]); + String value = decodeHex(fields[2]); + try { + ValueMatcher matcher = literalCandidateMatcher(pattern); + System.out.println(matcher.matches(value) ? "1" : "0"); + } + catch (RequestFailure failure) { + System.out.println("ERR:" + failure.code + ":" + failure.getMessage()); + } + } + } + + private static void runLiteralDirect() throws IOException { + for (String line : readStdinLines()) { + String[] fields = line.split("\\|", -1); + String pattern = decodeHex(fields[0]); + String value = decodeHex(fields[1]); + System.out.println(literalMatcher(pattern).matches(value) ? "1" : "0"); + } + } + + private static void runWriteResponse() throws IOException { + for (String line : readStdinLines()) { + String[] fields = line.split("\\|", -1); + String mode = fields[0]; + String kind = fields[1]; + String key = decodeHex(fields[2]); + String value = decodeHex(fields[3]); + GSON.setUseCharArrayWrites("char-array".equals(mode)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8.newEncoder())); + if ("failure".equals(kind)) { + writeFailure(writer, 7, key, value); + } else { + JsonObject result = new JsonObject(); + result.addProperty(key, value); + writeSuccess(writer, 1, result); + } + System.out.println(Base64.getEncoder().encodeToString(out.toByteArray())); + } + GSON.setUseCharArrayWrites(false); + } + + private static final class TrackingWriter extends Writer { + final StringBuilder written = new StringBuilder(); + boolean flushed; + boolean closed; + boolean failOnWrite; + boolean failOnNewline; + boolean failOnFlush; + int writeBudget = Integer.MAX_VALUE; + @Override public void write(char[] cbuf, int off, int len) throws IOException { + Objects.checkFromIndexSize(off, len, cbuf.length); + if (failOnWrite || writeBudget <= 0) throw new IOException("simulated write failure"); + String slice = new String(cbuf, off, len); + if (failOnNewline && slice.contains("\n")) throw new IOException("simulated newline failure"); + writeBudget -= len; + written.append(slice); + } + @Override public void flush() throws IOException { + if (failOnFlush) throw new IOException("simulated flush failure"); + flushed = true; + } + @Override public void close() { closed = true; } + } + + private static void runSurrogateWriterChecks() throws IOException { + TrackingWriter tracking = new TrackingWriter(); + BufferedWriter buffered = new BufferedWriter(tracking, 8192); + SurrogateEscapingWriter writer = new SurrogateEscapingWriter(buffered); + writer.write('A'); + writer.write('\ud800'); + writer.write('\udfff'); + char[] cbuf = new char[] { 'X', 'b', '\ud83d', '\ude00', 'c', '\ud801', 'Y' }; + writer.write(cbuf, 1, 5); + writer.write("skip-d-\udc00-e-tail", 5, 6); + writer.append(null); + writer.append("S\ud800"); + writer.append(new StringBuilder("B\udfff")); + writer.append(null, 1, 3); + writer.append("01\ud80023", 1, 4); + writer.append(new StringBuilder("pq\udc01rs"), 1, 4); + writer.flush(); + writer.close(); + System.out.println("no_early_flush=" + (!tracking.flushed && !tracking.closed && tracking.written.length() == 0)); + buffered.write("!"); + buffered.flush(); + System.out.println("after_flush=" + Base64.getEncoder().encodeToString(tracking.written.toString().getBytes(StandardCharsets.UTF_8))); + + boolean cbufOob = false; + try { writer.write(new char[] { 'a' }, 1, 1); } + catch (IndexOutOfBoundsException expected) { cbufOob = true; } + boolean strOob = false; + try { writer.write("a", 0, 2); } + catch (IndexOutOfBoundsException expected) { strOob = true; } + boolean appendOob = false; + try { writer.append(new StringBuilder("ab"), 1, 3); } + catch (IndexOutOfBoundsException expected) { appendOob = true; } + System.out.println("bounds_checks=" + (cbufOob && strOob && appendOob)); + } + + private static void runWriteFailures() { + JsonObject payload = new JsonObject(); + payload.addProperty("msg", "hello"); + TrackingWriter writeFailTracker = new TrackingWriter(); + writeFailTracker.failOnWrite = true; + BufferedWriter writeFailWriter = new BufferedWriter(writeFailTracker, 1); + try { + writeResponse(writeFailWriter, payload); + System.out.println("unwrap_write_io=ERR"); + } + catch (IOException expected) { + System.out.println("unwrap_write_io=OK:" + expected.getMessage()); + } + + TrackingWriter newlineFailTracker = new TrackingWriter(); + newlineFailTracker.failOnNewline = true; + BufferedWriter newlineFailWriter = new BufferedWriter(newlineFailTracker, 1); + try { + writeResponse(newlineFailWriter, payload); + System.out.println("newline_io=ERR"); + } + catch (IOException expected) { + System.out.println("newline_io=OK:" + expected.getMessage()); + } + + TrackingWriter flushFailTracker = new TrackingWriter(); + flushFailTracker.failOnFlush = true; + BufferedWriter flushFailWriter = new BufferedWriter(flushFailTracker, 8192); + try { + writeResponse(flushFailWriter, payload); + System.out.println("flush_io=ERR"); + } + catch (IOException expected) { + System.out.println("flush_io=OK:" + expected.getMessage()); + } + + Gson previous = GSON; + try { + GSON = new Gson() { + @Override void toJson(JsonElement element, Appendable appendable) { + throw new JsonIOException(new IllegalStateException("non-io-cause")); + } + }; + try { + writeResponse(new BufferedWriter(new TrackingWriter()), payload); + System.out.println("rethrow_non_io_cause=ERR"); + } + catch (JsonIOException expected) { + System.out.println("rethrow_non_io_cause=OK:" + expected.getCause().getClass().getSimpleName()); + } + catch (IOException unexpected) { + System.out.println("rethrow_non_io_cause=ERR_IO"); + } + + GSON = new Gson() { + @Override void toJson(JsonElement element, Appendable appendable) { + throw new JsonIOException("bare-json-io"); + } + }; + try { + writeResponse(new BufferedWriter(new TrackingWriter()), payload); + System.out.println("rethrow_bare_json_io=ERR"); + } + catch (JsonIOException expected) { + System.out.println("rethrow_bare_json_io=OK:" + expected.getMessage()); + } + catch (IOException unexpected) { + System.out.println("rethrow_bare_json_io=ERR_IO"); + } + } + finally { + GSON = previous; + } + } + + private StubFunction addFunction(long offset, boolean external, String leafName, String qualifiedName, boolean indexByLeaf) { + Address addr = new StubAddress(offset, external); + Symbol symbol = new StubSymbol(addr, leafName, qualifiedName); + currentProgram.getSymbolTable().register(symbol, indexByLeaf); + StubFunction function = new StubFunction(addr, leafName, symbol); + currentProgram.getFunctionManager().register(function); + return function; + } + + private void populateProcedureProgram() { + StubFunction nsOtherWork = addFunction(0x1000L, false, "other::work", "ns::other::work", true); + StubFunction nsThunkOtherWork = addFunction(0x2500L, false, "thunk_other::work", "ns::thunk_other::work", false); + nsOtherWork.addThunk(nsThunkOtherWork.getEntryPoint()); + currentProgram.getSymbolTable().register( + new StubSymbol(nsOtherWork.getEntryPoint(), "sub::leaf", "alias_ns::sub::leaf"), true); + currentProgram.getSymbolTable().register( + new StubSymbol(new StubAddress(0x1004L, false), "body_label", "ns::inner::body_label"), true); + addFunction(0x1100L, false, "inner::do::step", "pkg::sub::inner::do::step", true); + addFunction(0x1300L, false, "other::work", "wrong::other::work", true); + addFunction(0x1400L, false, "shared::op", "ns::shared::op", true); + addFunction(0x1500L, false, "op", "shared::op", true); + addFunction(0x1600L, false, "unique::leaf", "ns::unique::leaf", true); + + StubFunction targetOp = addFunction(0x2100L, false, "target::op", "lib::target::op", true); + StubFunction thunkTargetOp = addFunction(0x2000L, false, "thunk_target::op", "ns::thunk_target::op", false); + targetOp.addThunk(thunkTargetOp.getEntryPoint()); + + StubFunction nestedOp = addFunction(0x2300L, false, "nested::op", "lib::nested::op", true); + StubFunction doubleThunk = addFunction(0x2200L, false, "thunk_thunk_nested::op", "ns::thunk_thunk_nested::op", false); + StubFunction nsThunk = addFunction(0x2400L, false, "nested::op", "thunk_ns::nested::op", false); + nestedOp.addThunk(doubleThunk.getEntryPoint()); + nestedOp.addThunk(nsThunk.getEntryPoint()); + + StubFunction extTarget = addFunction(0x3000L, true, "ext::work", "::ext::work", true); + StubFunction extThunk = addFunction(0x3100L, false, "thunk_ext::work", "ns::thunk_ext::work", false); + extTarget.addThunk(extThunk.getEntryPoint()); + + Address dynamicAddr = new StubAddress(0x401000L, false); + currentProgram.getAddressFactory().registerDynamic(dynamicAddr); + StubFunction dynamicFn = addFunction(0x401000L, false, "FUN_00401000", "FUN_00401000", false); + StubFunction dynamicThunk = addFunction(0x402000L, false, "thunk_FUN_00401000", "ns::thunk_FUN_00401000", false); + dynamicFn.addThunk(dynamicThunk.getEntryPoint()); + + addFunction(0x4100L, false, "triple", "ns:::triple", true); + addFunction(0x4200L, false, ":colon_leaf", "ns:::colon_leaf", true); + addFunction(0x5000L, false, "a::b", "dup::a::b", true); + addFunction(0x5100L, false, "a::b", "dup::a::b", true); + } + + private void buildInventoryFromProgram() { + List inventory = new ArrayList<>(); + for (Function function : currentProgram.getFunctionManager().all()) { + Symbol primary = function.getSymbol(); + String leafName = function.getName(); + String value = primary == null ? leafName : primary.getName(true); + List aliases = new ArrayList<>(); + for (Symbol candidate : currentProgram.getSymbolTable().getSymbols(function.getEntryPoint())) { + String qualified = candidate.getName(true); + String candidateLeaf = candidate.getName(); + if (qualified.equals(value) && candidateLeaf.equals(leafName)) continue; + aliases.add(new ProcedureAlias(candidateLeaf.equals(qualified) ? qualified : candidateLeaf, qualified)); + } + inventory.add(new ProcedureEntry( + function, + function.getEntryPoint(), + value, + leafName.equals(value) ? value : leafName, + List.copyOf(aliases), + new ProcedureFacts(), + new SymbolFacts() + )); + } + procedureInventory = List.copyOf(inventory); + procedureNameIndex = null; + } + + private String formatResolve(String query) throws Exception { + try { + Function fn = resolveProcedureByName(query); + return fn == null ? "null" : canonicalAddress(fn.getEntryPoint()); + } + catch (RequestFailure failure) { + return "ERR:" + failure.code + ":" + failure.getMessage(); + } + } + + private void runResolveProcedures() throws Exception { + populateProcedureProgram(); + List queries = readStdinLines(); + List directResults = new ArrayList<>(queries.size()); + for (String query : queries) { + directResults.add(formatResolve(query)); + } + buildInventoryFromProgram(); + for (int index = 0; index < queries.size(); index++) { + String query = queries.get(index); + String cached = formatResolve(query); + System.out.println(query + "\t" + directResults.get(index) + "\t" + cached); + } + } + + public static void main(String[] args) throws Exception { + switch (args[0]) { + case "fold-char" -> runFoldChar(); + case "literal-batch" -> runLiteralBatch(); + case "literal-direct" -> runLiteralDirect(); + case "write-response" -> runWriteResponse(); + case "surrogate-writer" -> runSurrogateWriterChecks(); + case "write-failures" -> runWriteFailures(); + case "resolve-procedures" -> new ReaGhidraBridgeHelperProbe().runResolveProcedures(); + default -> throw new IllegalArgumentException("Unknown probe mode: " + args[0]); + } + } +} +`; + +const buildBridgeProbeSource = (bridgeSource: string): string => { + const procedureMethods = extractBridgeSlice( + bridgeSource, + " private Map procedureIndex() {", + " private Function resolveProcedure(String value) throws Exception {", + ); + const literalMethods = extractBridgeSlice( + bridgeSource, + " private static ValueMatcher literalMatcher(String pattern) {", + " private static ValueMatcher regexMatcher(String expression, boolean caseSensitive) {", + ); + const responseMethods = extractBridgeSlice( + bridgeSource, + " private static void writeSuccess(BufferedWriter writer, int id, JsonElement result)", + " private static String safeMessage(Exception exception) {", + ); + const valueMatcherInterface = extractBridgeSlice( + bridgeSource, + " private interface ValueMatcher {", + " private interface InventoryFacts {", + ); + const procedureRecords = extractBridgeSlice( + bridgeSource, + " private record ProcedureAlias(", + " private record StringEntry(", + ); + const requestFailureClass = extractRequestFailureSlice(bridgeSource); + return [ + JAVA_HEADER, + JAVA_GSON_STUBS, + JAVA_GHIDRA_STUBS, + valueMatcherInterface, + procedureRecords, + procedureMethods, + literalMethods, + responseMethods, + requestFailureClass, + JAVA_PROBE_DRIVER, + ].join("\n"); +}; + +/** Compile the pure-JDK harness embedding production methods from ReaGhidraBridge.java. */ +export const compileBridgeProbe = async ( + jdk: JdkToolchain, + workspaceRoot: string, +): Promise => { + const bridgeSource = await readFile(BRIDGE_SOURCE_PATH, "utf8"); + const sourceDir = join(workspaceRoot, "src"); + const classesDir = join(workspaceRoot, "classes"); + await mkdir(sourceDir, { recursive: true }); + await mkdir(classesDir, { recursive: true }); + const probeSourcePath = join(sourceDir, "ReaGhidraBridgeHelperProbe.java"); + await writeFile( + probeSourcePath, + buildBridgeProbeSource(bridgeSource), + "utf8", + ); + await execute( + jdk.javac, + [ + "--release", + "21", + "-encoding", + "UTF-8", + "-d", + classesDir, + probeSourcePath, + ], + { timeout: 30_000 }, + ); + return { classesDir, jdk }; +}; + +/** Execute one mode of the compiled bridge probe with optional stdin lines. */ +export const runBridgeProbe = ( + probe: CompiledBridgeProbe, + mode: string, + stdinText = "", +): Promise => + new Promise((resolvePromise, rejectPromise) => { + const child = execFile( + probe.jdk.java, + ["-cp", probe.classesDir, "ReaGhidraBridgeHelperProbe", mode], + { timeout: 30_000, maxBuffer: 16 * 1024 * 1024 }, + (error, stdout, stderr) => { + if (error !== null) { + rejectPromise( + new Error( + `Java probe '${mode}' failed: ${error.message}\n${stderr}`, + ), + ); + return; + } + resolvePromise(stdout); + }, + ); + child.stdin?.end(stdinText, "utf8"); + }); diff --git a/tests/boundary/providers/ghidra/ghidraBridgeHelpers.test.ts b/tests/boundary/providers/ghidra/ghidraBridgeHelpers.test.ts new file mode 100644 index 0000000000..332746ed86 --- /dev/null +++ b/tests/boundary/providers/ghidra/ghidraBridgeHelpers.test.ts @@ -0,0 +1,411 @@ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { literalSubstringPredicate } from "../../../../src/domain/analysisSearch.js"; +import { decodeStrictUtf8 } from "../../../../src/domain/strictUtf8.js"; +import { ghidraAsciiLiteralCandidate } from "../../../../src/ghidra/GhidraLiteralSearch.js"; +import { + createTestWorkspace, + removeTestWorkspace, + type TestWorkspace, +} from "../../../support/workspace/workspaceFixture.js"; +import { + compileBridgeProbe, + discoverJdk21Toolchain, + encodeUtf16Hex, + runBridgeProbe, + type CompiledBridgeProbe, +} from "./ghidraBridgeHelpers.fixture.js"; + +const jdk = await discoverJdk21Toolchain(); + +let workspace: TestWorkspace | undefined; +let probe: CompiledBridgeProbe | undefined; + +const requireProbe = (): CompiledBridgeProbe => { + if (probe === undefined) { + throw new Error("Compiled bridge helper probe was not initialized"); + } + return probe; +}; + +const splitProbeLines = (output: string): string[] => + output.trim().split(/\r?\n/u); + +beforeAll(async () => { + if (jdk === undefined) return; + workspace = await createTestWorkspace("rea-ghidra-bridge-helpers-"); + probe = await compileBridgeProbe(jdk, workspace.root); +}, 60_000); + +afterAll(async () => { + if (workspace !== undefined) { + await removeTestWorkspace(workspace.root); + workspace = undefined; + } + probe = undefined; +}); + +describe.skipIf(jdk === undefined)( + "ReaGhidraBridge literalCandidateMatcher and foldAsciiCandidateChar", + () => { + it("folds ASCII letters, U+017F, and U+212A while rejecting other non-ASCII chars", async () => { + const cases: readonly [string, number][] = [ + ["a", "a".charCodeAt(0)], + ["A", "a".charCodeAt(0)], + ["z", "z".charCodeAt(0)], + ["Z", "z".charCodeAt(0)], + ["0", "0".charCodeAt(0)], + [":", ":".charCodeAt(0)], + ["\u017f", "s".charCodeAt(0)], + ["\u212a", "k".charCodeAt(0)], + ["\u00e9", -1], + ["\u0130", -1], + ["\u0131", -1], + ["\u00df", -1], + ["\ud800", -1], + ["\udfff", -1], + ]; + const stdin = cases + .map(([char]) => char.charCodeAt(0).toString(16).padStart(4, "0")) + .join("\n"); + const stdout = await runBridgeProbe(requireProbe(), "fold-char", stdin); + const observed = splitProbeLines(stdout).map(Number); + expect(observed).toEqual(cases.map(([, expected]) => expected)); + }); + + it("keeps literalCandidateMatcher sound and consistent with JS /iu across Unicode folds and surrogates", async () => { + const patterns = [ + "a", + "ABC.[x]", + "s", + "\u017f", + "k", + "\u212a", + "\u017f.\u212a", + "\u0130", + "\u0131", + "\u03a3", + "\u03c3", + "\u03c2", + "\u00df", + "ss", + "\ud801\udc00", + "\ud801\udc28", + "\ud83d\ude00", + "\ud800", + "\udfff", + "pre\ud800mid", + ]; + const values = [ + "", + "a", + "A", + "prefix_abc.[X]_suffix", + "s", + "S", + "\u017f", + "k", + "K", + "\u212a", + "x\u017f.Ky", + "i", + "I", + "\u0130", + "\u0131", + "\u03a3", + "\u03c3", + "\u03c2", + "\u00df", + "SS", + "\ud801\udc00", + "\ud801\udc28", + "wrap_\ud83d\ude00_end", + "\ud800", + "pre\ud800mid", + "\udfff", + "ascii_only_string", + ]; + + const pairs: { + readonly pattern: string; + readonly candidate: string | null; + readonly value: string; + }[] = []; + for (const pattern of patterns) { + const candidate = ghidraAsciiLiteralCandidate(pattern); + for (const value of values) { + pairs.push({ pattern, candidate, value }); + } + } + const stdin = pairs + .map(({ candidate, value }) => + candidate === null + ? `0||${encodeUtf16Hex(value)}` + : `1|${encodeUtf16Hex(candidate)}|${encodeUtf16Hex(value)}`, + ) + .join("\n"); + const stdout = await runBridgeProbe( + requireProbe(), + "literal-batch", + stdin, + ); + const observed = splitProbeLines(stdout); + expect(observed).toHaveLength(pairs.length); + + for (let index = 0; index < pairs.length; index += 1) { + const { pattern, candidate, value } = pairs[index]!; + const matched = observed[index] === "1"; + const jsMatches = literalSubstringPredicate(pattern, false)(value); + if (jsMatches) { + expect(matched).toBe(true); + } + const valueIsAscii = [...value].every((ch) => ch.charCodeAt(0) <= 127); + if (valueIsAscii) { + expect(matched).toBe(jsMatches); + } + if (candidate === null) { + expect(matched).toBe(!valueIsAscii); + } + } + }); + + it("handles empty, invalid non-ASCII, and case-sensitive literal matchers", async () => { + const invalidAndEdge = await runBridgeProbe( + requireProbe(), + "literal-batch", + [ + `1||${encodeUtf16Hex("anything")}`, + `1|${encodeUtf16Hex("é")}|${encodeUtf16Hex("é")}`, + `1|${encodeUtf16Hex("abc")}|${encodeUtf16Hex("ab")}`, + ].join("\n"), + ); + expect(splitProbeLines(invalidAndEdge)).toEqual([ + "1", + "ERR:invalid_request:ASCII candidate contains a non-ASCII character", + "0", + ]); + + const direct = await runBridgeProbe( + requireProbe(), + "literal-direct", + [ + `${encodeUtf16Hex("AbC")}|${encodeUtf16Hex("xxAbCyy")}`, + `${encodeUtf16Hex("AbC")}|${encodeUtf16Hex("xxabcyy")}`, + `${encodeUtf16Hex("\ud800")}|${encodeUtf16Hex("a\ud800b")}`, + `${encodeUtf16Hex("\ud83d\ude00")}|${encodeUtf16Hex("a\ud83d\ude00b")}`, + ].join("\n"), + ); + expect(splitProbeLines(direct)).toEqual(["1", "0", "1", "1"]); + }); + }, +); + +describe.skipIf(jdk === undefined)( + "ReaGhidraBridge writeResponse and SurrogateEscapingWriter", + () => { + it("streams valid UTF-8 NDJSON through writeResponse for surrogates and control chars", async () => { + const payloads: readonly { + readonly mode: "string-writer" | "char-array"; + readonly kind: "success" | "failure"; + readonly key: string; + readonly value: string; + }[] = [ + { + mode: "string-writer", + kind: "success", + key: "pair", + value: "emoji-\ud83d\ude00-deseret-\ud801\udc00-end", + }, + { + mode: "char-array", + kind: "success", + key: "pair_chars", + value: "emoji-\ud83d\ude00-deseret-\ud801\udc00-end", + }, + { + mode: "string-writer", + kind: "success", + key: "lone_high_\ud800", + value: "hi-\ud800-lo-\udfff-rev-\udc00\ud800-slash-\\\ud800", + }, + { + mode: "char-array", + kind: "success", + key: "lone_chars", + value: "hi-\ud800-lo-\udfff-slash-\\\ud83d\ude00", + }, + { + mode: "string-writer", + kind: "success", + key: "controls", + value: "\u0000\u0001\b\t\n\f\r\u001f\"\\<>&='\u2028\u2029é逆向", + }, + { + mode: "string-writer", + kind: "failure", + key: "invalid_request", + value: "bad-\u0000-\ud800-\ud83d\ude00-\n", + }, + ]; + + const stdin = payloads + .map( + ({ mode, kind, key, value }) => + `${mode}|${kind}|${encodeUtf16Hex(key)}|${encodeUtf16Hex(value)}`, + ) + .join("\n"); + const stdout = await runBridgeProbe( + requireProbe(), + "write-response", + stdin, + ); + const lines = splitProbeLines(stdout); + expect(lines).toHaveLength(payloads.length); + + for (let index = 0; index < payloads.length; index += 1) { + const expected = payloads[index]!; + const wireBytes = Buffer.from(lines[index]!, "base64"); + const wireText = decodeStrictUtf8(wireBytes, "preserve"); + expect(wireText.endsWith("\n")).toBe(true); + const frame = wireText.replace(/\r?\n$/u, ""); + expect(frame).not.toContain("\n"); + expect(frame).not.toContain("\r"); + expect(frame).not.toContain("\u0000"); + + if (expected.value.includes("\ud800")) { + expect(frame).toContain("\\ud800"); + } + if (expected.value.includes("\udfff")) { + expect(frame).toContain("\\udfff"); + } + if (expected.value.includes("\ud83d\ude00")) { + expect(frame).toContain("\\ud83d\\ude00"); + } + if (expected.value.includes("\u0000")) { + expect(frame).toContain("\\u0000"); + } + + const parsed: unknown = JSON.parse(frame); + if (expected.kind === "failure") { + expect(parsed).toEqual({ + id: 7, + ok: false, + error: { code: expected.key, message: expected.value }, + }); + } else { + expect(parsed).toEqual({ + id: 1, + ok: true, + result: { [expected.key]: expected.value }, + }); + } + } + }); + + it("exercises SurrogateEscapingWriter write/append/flush/close and writeResponse failures", async () => { + const writerOut = await runBridgeProbe( + requireProbe(), + "surrogate-writer", + ); + const writerEntries = Object.fromEntries( + splitProbeLines(writerOut).map((line) => { + const eq = line.indexOf("="); + return [line.slice(0, eq), line.slice(eq + 1)]; + }), + ); + expect(writerEntries.no_early_flush).toBe("true"); + expect(writerEntries.bounds_checks).toBe("true"); + const decoded = Buffer.from( + writerEntries.after_flush ?? "", + "base64", + ).toString("utf8"); + expect(decoded).toBe( + "A\\ud800\\udfffb\\ud83d\\ude00c\\ud801d-\\udc00-e-nullS\\ud800B\\udffful1\\ud8002q\\udc01r!", + ); + + const failureOut = await runBridgeProbe(requireProbe(), "write-failures"); + const failures = splitProbeLines(failureOut); + expect(failures).toEqual([ + "unwrap_write_io=OK:simulated write failure", + "newline_io=OK:simulated newline failure", + "flush_io=OK:simulated flush failure", + "rethrow_non_io_cause=OK:IllegalStateException", + "rethrow_bare_json_io=OK:bare-json-io", + ]); + }); + }, +); + +describe.skipIf(jdk === undefined)( + "ReaGhidraBridge resolveProcedureCandidatesDirect", + () => { + it("resolves qualified names with :: in the leaf before procedureInventory is cached", async () => { + const expected: readonly [string, string][] = [ + ["ns::other::work", "0x1000"], + ["ns::thunk_other::work", "0x2500"], + ["thunk_other::work", "0x2500"], + ["wrong::other::work", "0x1300"], + [ + "other::work", + "ERR:procedure_ambiguous:Ghidra procedure name is ambiguous: other::work; select an exact entry address from [0x1000, 0x1300]", + ], + ["ns::unique::leaf", "0x1600"], + ["unique::leaf", "0x1600"], + ["leaf", "null"], + ["other::unique::leaf", "null"], + ["work", "null"], + ["missing::other::work", "null"], + ["pkg::sub::inner::do::step", "0x1100"], + ["inner::do::step", "0x1100"], + ["do::step", "null"], + ["step", "null"], + ["ns::shared::op", "0x1400"], + [ + "shared::op", + "ERR:procedure_ambiguous:Ghidra procedure name is ambiguous: shared::op; select an exact entry address from [0x1400, 0x1500]", + ], + ["op", "0x1500"], + ["ns::thunk_target::op", "0x2000"], + ["thunk_target::op", "0x2000"], + ["lib::target::op", "0x2100"], + ["ns::thunk_thunk_nested::op", "0x2200"], + ["thunk_thunk_nested::op", "0x2200"], + ["thunk_ns::nested::op", "0x2400"], + [ + "nested::op", + "ERR:procedure_ambiguous:Ghidra procedure name is ambiguous: nested::op; select an exact entry address from [0x2300, 0x2400]", + ], + ["::ext::work", "EXTERNAL:0x3000"], + ["ext::work", "EXTERNAL:0x3000"], + ["ns::thunk_ext::work", "0x3100"], + ["FUN_00401000", "0x401000"], + ["ns::thunk_FUN_00401000", "0x402000"], + ["ns:::triple", "0x4100"], + ["ns:::colon_leaf", "0x4200"], + ["alias_ns::sub::leaf", "0x1000"], + ["sub::leaf", "0x1000"], + ["ns::inner::body_label", "null"], + [ + "dup::a::b", + "ERR:procedure_ambiguous:Ghidra procedure name is ambiguous: dup::a::b; select an exact entry address from [0x5000, 0x5100]", + ], + ]; + + const stdin = expected.map(([query]) => query).join("\n"); + const stdout = await runBridgeProbe( + requireProbe(), + "resolve-procedures", + stdin, + ); + const rows = splitProbeLines(stdout); + expect(rows).toHaveLength(expected.length); + + for (let index = 0; index < expected.length; index += 1) { + const [expectedQuery, expectedOutcome] = expected[index]!; + const [query, uncached, cached] = rows[index]!.split("\t"); + expect(query).toBe(expectedQuery); + expect(uncached).toBe(expectedOutcome); + expect(cached).toBe(expectedOutcome); + } + }); + }, +);