From 702dc9f9329559a86a52fbf379a8d799f8856783 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 12 Oct 2026 05:04:18 +0000 Subject: [PATCH] fix(ghidra): bound Swift literal reads and compare decoded strings Large immortal literals are measured against the remaining heap before allocation, and a failed fit stays visible as a limitation. The canonical empty string is kept. Small and large literals now require matching address nullability, and function comparison treats decoded literals as string evidence without equating a missing record to an empty one. --- bridge/ghidra/ReaGhidraBridge.java | 63 ++++++++++++++---- src/domain/functionComparison.test.ts | 65 +++++++++++++++++++ src/domain/functionComparisonDimensions.ts | 19 ++++++ src/domain/functionComparisonNormalization.ts | 17 +++++ src/domain/hopperValues.ts | 38 +++++++---- src/ghidra/GhidraFunctionValues.test.ts | 53 ++++++++++----- 6 files changed, 212 insertions(+), 43 deletions(-) diff --git a/bridge/ghidra/ReaGhidraBridge.java b/bridge/ghidra/ReaGhidraBridge.java index 4767a8b6b..c0889022e 100644 --- a/bridge/ghidra/ReaGhidraBridge.java +++ b/bridge/ghidra/ReaGhidraBridge.java @@ -1242,8 +1242,11 @@ public final class ReaGhidraBridge extends HeadlessScript { result.add("referenced_names", referencedNames); boolean swift = swiftProgram(); boolean aarch64 = currentProgram.getLanguageID().getIdAsString().startsWith("AARCH64:"); + boolean omittedSwiftLiteralForCapacity = false; if (swift && aarch64) { - result.add("swift_string_literals", swiftStringLiterals(function)); + SwiftStringLiteralDecode decoded = swiftStringLiterals(function); + result.add("swift_string_literals", decoded.literals()); + omittedSwiftLiteralForCapacity = decoded.omittedForCapacity(); } result.add("basic_blocks", blocks); result.add( @@ -1268,6 +1271,11 @@ public final class ReaGhidraBridge extends HeadlessScript { limitations.add( "Swift String literals are decoded from constant register pairs at calls, returns and paired stores; literals stored one word at a time, chosen by two conditional selects, or built at runtime are not reported." ); + if (omittedSwiftLiteralForCapacity) { + limitations.add( + "A Swift String literal matched the immortal layout but was omitted because its byte length does not fit in the remaining Java heap before UTF-16 and JSON expansion." + ); + } } else if (swift) { limitations.add( "Swift String literal decoding is implemented for AArch64 register pairs only; no Swift literals were decoded for this architecture." @@ -3328,13 +3336,15 @@ public final class ReaGhidraBridge extends HeadlessScript { * immortal large literals carry their count and a biased pointer to the bytes. Ghidra keeps * neither as a data reference, so decode constant pairs where Swift consumes them: argument * and return registers at calls, tail calls and returns, and both registers of one STP. + * The canonical empty string is a small literal with a zero count. */ - private JsonArray swiftStringLiterals(Function function) throws Exception { + private SwiftStringLiteralDecode swiftStringLiterals(Function function) throws Exception { Register[] registers = new Register[31]; for (int index = 0; index < registers.length; index++) { registers[index] = currentProgram.getRegister("x" + index); } TreeMap observed = new TreeMap<>(); + boolean[] omittedForCapacity = { false }; SymbolicPropogator propagator = new SymbolicPropogator(currentProgram, false); propagator.flowConstants(function.getEntryPoint(), function.getBody(), new ContextEvaluatorAdapter() { @Override @@ -3343,7 +3353,7 @@ public final class ReaGhidraBridge extends HeadlessScript { Long word = registerConstant(context, pair[0]); Long object = registerConstant(context, pair[1]); if (word == null || object == null) continue; - JsonObject item = swiftStringLiteral(word, object); + JsonObject item = swiftStringLiteral(word, object, omittedForCapacity); // Ghidra forks each select without correlating its condition, so a pair whose // registers are both selected may combine words from different cases. if (item == null || (selectedValue(instruction, pair[0]) && selectedValue(instruction, pair[1]))) continue; @@ -3363,7 +3373,7 @@ public final class ReaGhidraBridge extends HeadlessScript { }, false, monitor); JsonArray result = new JsonArray(); observed.values().forEach(result::add); - return result; + return new SwiftStringLiteralDecode(result, omittedForCapacity[0]); } private static List swiftStringPairs( @@ -3418,7 +3428,7 @@ public final class ReaGhidraBridge extends HeadlessScript { return false; } - private JsonObject swiftStringLiteral(long word, long object) { + private JsonObject swiftStringLiteral(long word, long object, boolean[] omittedForCapacity) { int discriminator = (int) (object >>> 60); if (discriminator == 0xE || discriminator == 0xA) { int count = (int) ((object >>> 56) & 0xF); @@ -3428,7 +3438,8 @@ public final class ReaGhidraBridge extends HeadlessScript { for (int index = count; index < bytes.length; index++) { if (bytes[index] != 0) return null; } - String value = swiftStringText(Arrays.copyOf(bytes, count), discriminator == 0xE); + // Count zero is the canonical empty string (object 0xE000000000000000, word 0). + String value = swiftStringText(bytes, count, discriminator == 0xE); return value == null ? null : swiftStringItem(value, "small", null, word, object); } int flags = (int) (word >>> 60); @@ -3445,27 +3456,54 @@ public final class ReaGhidraBridge extends HeadlessScript { MemoryBlock block = currentProgram.getMemory().getBlock(address); // The bytes and their terminator must lie in one initialized, non-executable block. if (block == null || !block.isInitialized() || block.isExecute() || - count >= block.getEnd().subtract(address) + 1 || count >= Integer.MAX_VALUE) { + count >= block.getEnd().subtract(address) + 1) { + return null; + } + if (!swiftLiteralBytesFit(count)) { + omittedForCapacity[0] = true; return null; } bytes = new byte[(int) count + 1]; if (currentProgram.getMemory().getBytes(address, bytes) != bytes.length) return null; + } catch (OutOfMemoryError exhausted) { + omittedForCapacity[0] = true; + return null; } catch (Exception unreadable) { return null; } if (bytes[(int) count] != 0) return null; - String value = swiftStringText(Arrays.copyOf(bytes, (int) count), flags == 0xD); + String value = swiftStringText(bytes, (int) count, flags == 0xD); return value == null ? null : swiftStringItem(value, "large", address, word, object); } - private static String swiftStringText(byte[] bytes, boolean ascii) { - if (bytes.length == 0) return null; - for (byte value : bytes) { + /** + * A large literal is retained as a byte array, a UTF-16 String, and JSON text. + * ASCII expands to two UTF-16 bytes and JSON serialization retains another copy, + * so require five bytes of remaining heap per content byte and leave half the heap + * for the rest of the dossier. Measure that before allocating. + */ + private static boolean swiftLiteralBytesFit(long count) { + if (count < 0 || count >= Integer.MAX_VALUE) return false; + Runtime runtime = Runtime.getRuntime(); + long available = runtime.maxMemory() - runtime.totalMemory() + runtime.freeMemory(); + long expanded; + try { + expanded = Math.addExact(Math.multiplyExact(count, 5L), 1L); + } catch (ArithmeticException overflow) { + return false; + } + return available > 0 && expanded <= available / 2; + } + + private static String swiftStringText(byte[] bytes, int length, boolean ascii) { + if (length < 0 || length > bytes.length) return null; + for (int index = 0; index < length; index++) { + byte value = bytes[index]; if ((value >= 0 && value < 0x20 && value != '\t' && value != '\n' && value != '\r') || value == 0x7f) return null; if (ascii && value < 0) return null; } try { - return StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString(); + return StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes, 0, length)).toString(); } catch (CharacterCodingException invalid) { return null; } @@ -4032,6 +4070,7 @@ public final class ReaGhidraBridge extends HeadlessScript { private record AddressNameRequest(String inputAddress, Address address, String name) {} private record FunctionEntry(Function function, InventoryItem item) {} private record FunctionAnalysisObservation(JsonObject dossier, List limitations) {} + private record SwiftStringLiteralDecode(JsonArray literals, boolean omittedForCapacity) {} private record InstructionScan(List instructions, boolean truncated) {} private record SessionDescriptor( String transport, diff --git a/src/domain/functionComparison.test.ts b/src/domain/functionComparison.test.ts index f846217c5..e937dd953 100644 --- a/src/domain/functionComparison.test.ts +++ b/src/domain/functionComparison.test.ts @@ -572,6 +572,71 @@ describe("function comparison", () => { }); }); +describe("function comparison Swift string literals", () => { + const withLiterals = (base: "0x1000" | "0x2000", values: readonly string[]) => + functionDossierSchema.parse({ + ...dossier("return 0;", base), + swift_string_literals: values.map((value) => ({ + source_address: base, + value, + representation: "small" as const, + address: null, + registers: ["x0", "x1"] as const, + words: ["0x0", "0xe"] as const, + })), + }); + const stringsDimension = ( + leftDigit: string, + left: ReturnType | ReturnType, + rightDigit: string, + right: ReturnType | ReturnType, + ) => + compareFunctions( + observe(leftDigit, left), + observe(rightDigit, right), + ).dimensions.find(({ dimension }) => dimension === "strings_names"); + + it("treats differing decoded literals as a strings and names change", () => { + expect( + stringsDimension( + "1", + withLiterals("0x1000", ["SleepDisabled"]), + "2", + withLiterals("0x2000", ["Holding awake"]), + ), + ).toMatchObject({ status: "changed" }); + }); + + it("matches the same decoded literal after the function is relocated", () => { + expect( + stringsDimension( + "3", + withLiterals("0x1000", ["SleepDisabled"]), + "4", + withLiterals("0x2000", ["SleepDisabled"]), + ), + ).toMatchObject({ status: "unchanged" }); + }); + + it("keeps strings and names unknown when only one dossier recorded Swift literals", () => { + expect( + stringsDimension( + "5", + withLiterals("0x1000", []), + "6", + dossier("return 0;", "0x2000"), + ), + ).toMatchObject({ + status: "unknown", + left_count: 0, + right_count: null, + limitations: [ + "Swift String literal coverage differs; one dossier did not record decoded literals.", + ], + }); + }); +}); + const expectInlineComparisonEvidence = ( result: ReturnType, ): void => { diff --git a/src/domain/functionComparisonDimensions.ts b/src/domain/functionComparisonDimensions.ts index f4d7d86a1..c390dd8b9 100644 --- a/src/domain/functionComparisonDimensions.ts +++ b/src/domain/functionComparisonDimensions.ts @@ -139,6 +139,18 @@ const compareStringsAndNames = ( right: FunctionSnapshot, context: ComparisonContext, ): FunctionDimension => { + const leftRecorded = left.dossier.swift_string_literals !== undefined; + const rightRecorded = right.dossier.swift_string_literals !== undefined; + if (leftRecorded !== rightRecorded) + return unresolvedDimension({ + dimension: "strings_names", + links: context.links, + leftCount: recordedStringFactCount(left), + rightCount: recordedStringFactCount(right), + limitations: [ + "Swift String literal coverage differs; one dossier did not record decoded literals.", + ], + }); const leftValues = stringAndNameProjection(left); const rightValues = stringAndNameProjection(right); if (leftValues === null || rightValues === null) @@ -154,6 +166,13 @@ const compareStringsAndNames = ( return compareValues("strings_names", leftValues, rightValues, context); }; +const recordedStringFactCount = (snapshot: FunctionSnapshot): number | null => + snapshot.dossier.swift_string_literals === undefined + ? null + : snapshot.dossier.referenced_strings.length + + snapshot.dossier.referenced_names.length + + snapshot.dossier.swift_string_literals.length; + const compareReferences = ( left: FunctionSnapshot, right: FunctionSnapshot, diff --git a/src/domain/functionComparisonNormalization.ts b/src/domain/functionComparisonNormalization.ts index a676e1e49..f00dce1a7 100644 --- a/src/domain/functionComparisonNormalization.ts +++ b/src/domain/functionComparisonNormalization.ts @@ -167,6 +167,23 @@ export const stringAndNameProjection = ( value, }), ), + ...(snapshot.dossier.swift_string_literals ?? []).map( + ({ + source_address: sourceAddress, + value, + representation, + registers, + }) => ({ + kind: "swift_string", + source_offset: relativeAddress( + sourceAddress, + snapshot.dossier.procedure.address, + ), + value, + representation, + registers, + }), + ), ]; return values.some(({ source_offset: offset }) => offset === null) ? null diff --git a/src/domain/hopperValues.ts b/src/domain/hopperValues.ts index a42005109..b706cd22e 100644 --- a/src/domain/hopperValues.ts +++ b/src/domain/hopperValues.ts @@ -286,30 +286,40 @@ export const unresolvedCallSchema = z.strictObject({ reason: z.string(), }); -/** A Swift String literal decoded from the two words of its ABI value, not a data reference. */ -export const swiftStringLiteralSchema = z.strictObject({ +const swiftStringLiteralFields = { source_address: z .string() .describe( "Instruction that consumes both words: a call, tail call, return, or paired store.", ), - value: z.string(), - representation: z - .enum(["small", "large"]) - .describe( - "small: the UTF-8 bytes are inside the two words. large: an immortal literal whose words hold its count and a pointer to its bytes.", - ), - address: z + value: z .string() - .nullable() - .describe( - "Address of a large literal's bytes; null for a small literal, which has no storage of its own.", - ), + .describe("Decoded UTF-8 text, including the canonical empty string."), registers: z.tuple([z.string(), z.string()]), words: z .tuple([z.string(), z.string()]) .describe("Observed constant register values, in register order."), -}); +}; + +/** A Swift String literal decoded from the two words of its ABI value, not a data reference. */ +export const swiftStringLiteralSchema = z.discriminatedUnion("representation", [ + z.strictObject({ + ...swiftStringLiteralFields, + representation: z + .literal("small") + .describe("The UTF-8 bytes are inside the two words."), + address: z.null().describe("A small literal has no storage of its own."), + }), + z.strictObject({ + ...swiftStringLiteralFields, + representation: z + .literal("large") + .describe( + "An immortal literal whose words hold its count and a pointer to its bytes.", + ), + address: z.string().describe("Address of a large literal's bytes."), + }), +]); /** Observed endpoints with complete or partial reference classification evidence. */ export const referenceEdgeSchema = z diff --git a/src/ghidra/GhidraFunctionValues.test.ts b/src/ghidra/GhidraFunctionValues.test.ts index 2892c65e8..b8f6ab4d4 100644 --- a/src/ghidra/GhidraFunctionValues.test.ts +++ b/src/ghidra/GhidraFunctionValues.test.ts @@ -189,6 +189,14 @@ describe("Ghidra Swift String literals", () => { registers: ["x0", "x1"], words: ["0x7265737520656854", "0xee0020656d616e20"], }, + { + source_address: "0x401006", + value: "", + representation: "small", + address: null, + registers: ["x0", "x1"], + words: ["0x0", "0xe000000000000000"], + }, { source_address: "0x401008", value: " cannot be written into a sudoers rule safely.", @@ -435,6 +443,33 @@ describe("Ghidra function-analysis malformed results", () => { ); }); +const malformedSwiftStringLiterals = ( + dossier: Record, +): Array<[string, GhidraFunctionOperation, JsonValue]> => + ( + [ + ["non-canonical Swift literal address", "large", "402240"], + ["small Swift literal with storage", "small", "0x402270"], + ["large Swift literal without storage", "large", null], + ] as const + ).map(([name, representation, address]) => [ + name, + "analyze_function", + { + ...dossier, + swift_string_literals: [ + { + source_address: "0x401004", + value: "The power setting could not be changed.", + representation, + address, + registers: ["x0", "x1"], + words: ["0xd000000000000027", "0x8000000000402220"], + }, + ], + }, + ]); + const malformedOutputs = (): Array< [string, GhidraFunctionOperation, JsonValue] > => { @@ -479,23 +514,7 @@ const malformedOutputs = (): Array< Object.entries(dossier).filter(([key]) => key !== "native_api"), ), ], - [ - "non-canonical Swift literal address", - "analyze_function", - { - ...dossier, - swift_string_literals: [ - { - source_address: "0x401004", - value: "The power setting could not be changed.", - representation: "large", - address: "402240", - registers: ["x0", "x1"], - words: ["0xd000000000000027", "0x8000000000402220"], - }, - ], - }, - ], + ...malformedSwiftStringLiterals(dossier), [ "non-canonical native API target", "analyze_function",