fix(hopper): preserve typed string values and verify real searches
This commit is contained in:
@@ -1,285 +0,0 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
const bridgePath = fileURLToPath(
|
||||
new URL("../../../../bridge/hopper_bridge.py", import.meta.url),
|
||||
);
|
||||
const probePath = fileURLToPath(
|
||||
new URL("../../../fixtures/bridgeSearchProbe.py", import.meta.url),
|
||||
);
|
||||
|
||||
const searchResultSchema = z.object({
|
||||
action: z.literal("search"),
|
||||
ok: z.literal(true),
|
||||
result: z.array(z.object({ address: z.string(), value: z.string() })),
|
||||
});
|
||||
const probeResultSchema = searchResultSchema;
|
||||
type ProbeResult = z.infer<typeof probeResultSchema>;
|
||||
|
||||
type ProbeInput = {
|
||||
readonly action: "search";
|
||||
readonly items: readonly (readonly [string, string])[];
|
||||
readonly params: Readonly<Record<string, string | number | boolean>>;
|
||||
};
|
||||
|
||||
interface PendingProbe {
|
||||
readonly resolve: (result: ProbeResult) => void;
|
||||
readonly reject: (error: Error) => void;
|
||||
timeout: NodeJS.Timeout | undefined;
|
||||
}
|
||||
|
||||
const PROBE_TIMEOUT_MS = 3_000;
|
||||
const PROBE_BUFFER_LIMIT = 1_024 * 1_024;
|
||||
const pendingProbes: PendingProbe[] = [];
|
||||
let probeProcess: ChildProcessWithoutNullStreams | undefined;
|
||||
let probeStdout = "";
|
||||
let probeStderr = "";
|
||||
let probeFailure: Error | undefined;
|
||||
let stoppingProbe = false;
|
||||
|
||||
const failureWithStderr = (message: string): Error => {
|
||||
const stderr = probeStderr.trim();
|
||||
return new Error(stderr.length === 0 ? message : `${message}: ${stderr}`);
|
||||
};
|
||||
|
||||
const rejectPendingProbes = (error: Error): void => {
|
||||
for (const pending of pendingProbes.splice(0)) {
|
||||
if (pending.timeout !== undefined) clearTimeout(pending.timeout);
|
||||
pending.reject(error);
|
||||
}
|
||||
};
|
||||
|
||||
const failProbeProcess = (error: Error): void => {
|
||||
probeFailure ??= error;
|
||||
rejectPendingProbes(probeFailure);
|
||||
if (
|
||||
!stoppingProbe &&
|
||||
probeProcess?.exitCode === null &&
|
||||
probeProcess.signalCode === null
|
||||
)
|
||||
probeProcess.kill("SIGKILL");
|
||||
};
|
||||
|
||||
const acceptProbeLine = (line: string): void => {
|
||||
const pending = pendingProbes.shift();
|
||||
if (pending === undefined) {
|
||||
failProbeProcess(
|
||||
failureWithStderr("Python probe returned an extra result"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (pending.timeout !== undefined) clearTimeout(pending.timeout);
|
||||
try {
|
||||
const decoded: unknown = JSON.parse(line);
|
||||
pending.resolve(probeResultSchema.parse(decoded));
|
||||
} catch (cause: unknown) {
|
||||
const error =
|
||||
cause instanceof Error
|
||||
? cause
|
||||
: failureWithStderr("Python probe returned an invalid result");
|
||||
pending.reject(error);
|
||||
failProbeProcess(error);
|
||||
}
|
||||
};
|
||||
|
||||
const acceptProbeOutput = (chunk: string): void => {
|
||||
probeStdout += chunk;
|
||||
if (Buffer.byteLength(probeStdout) > PROBE_BUFFER_LIMIT) {
|
||||
failProbeProcess(failureWithStderr("Python probe output exceeded 1 MiB"));
|
||||
return;
|
||||
}
|
||||
let newline = probeStdout.indexOf("\n");
|
||||
while (newline >= 0) {
|
||||
const line = probeStdout.slice(0, newline).replace(/\r$/u, "");
|
||||
probeStdout = probeStdout.slice(newline + 1);
|
||||
acceptProbeLine(line);
|
||||
newline = probeStdout.indexOf("\n");
|
||||
}
|
||||
};
|
||||
|
||||
const startProbeProcess = async (): Promise<void> => {
|
||||
stoppingProbe = false;
|
||||
probeFailure = undefined;
|
||||
probeStdout = "";
|
||||
probeStderr = "";
|
||||
const child = spawn("python3", [probePath, bridgePath], {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
probeProcess = child;
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stderr.setEncoding("utf8");
|
||||
child.stdout.on("data", acceptProbeOutput);
|
||||
child.stderr.on("data", (chunk: string) => {
|
||||
probeStderr += chunk;
|
||||
if (Buffer.byteLength(probeStderr) > PROBE_BUFFER_LIMIT)
|
||||
failProbeProcess(new Error("Python probe stderr exceeded 1 MiB"));
|
||||
});
|
||||
child.stdin.on("error", (error) => {
|
||||
if (!stoppingProbe) failProbeProcess(error);
|
||||
});
|
||||
child.on("error", (error) => {
|
||||
if (!stoppingProbe) failProbeProcess(error);
|
||||
});
|
||||
child.on("exit", (code, signal) => {
|
||||
if (!stoppingProbe)
|
||||
failProbeProcess(
|
||||
failureWithStderr(
|
||||
`Python probe exited before responding (code ${String(code)}, signal ${String(signal)})`,
|
||||
),
|
||||
);
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const onSpawn = (): void => {
|
||||
child.off("error", onError);
|
||||
resolve();
|
||||
};
|
||||
const onError = (error: Error): void => {
|
||||
child.off("spawn", onSpawn);
|
||||
reject(error);
|
||||
};
|
||||
child.once("spawn", onSpawn);
|
||||
child.once("error", onError);
|
||||
});
|
||||
};
|
||||
|
||||
const hasExited = (child: ChildProcessWithoutNullStreams): boolean =>
|
||||
child.exitCode !== null || child.signalCode !== null;
|
||||
|
||||
const waitForExit = (
|
||||
child: ChildProcessWithoutNullStreams,
|
||||
timeoutMs: number,
|
||||
): Promise<boolean> => {
|
||||
if (hasExited(child)) return Promise.resolve(true);
|
||||
return new Promise((resolve) => {
|
||||
const onExit = (): void => {
|
||||
clearTimeout(timeout);
|
||||
resolve(true);
|
||||
};
|
||||
const timeout = setTimeout(() => {
|
||||
child.off("exit", onExit);
|
||||
resolve(false);
|
||||
}, timeoutMs);
|
||||
child.once("exit", onExit);
|
||||
});
|
||||
};
|
||||
|
||||
const stopProbeProcess = async (): Promise<void> => {
|
||||
const child = probeProcess;
|
||||
if (child === undefined) return;
|
||||
stoppingProbe = true;
|
||||
rejectPendingProbes(new Error("Python probe stopped before responding"));
|
||||
if (!hasExited(child)) child.stdin.end();
|
||||
if (!(await waitForExit(child, 500))) child.kill("SIGTERM");
|
||||
if (!(await waitForExit(child, 500))) child.kill("SIGKILL");
|
||||
if (!(await waitForExit(child, 500)))
|
||||
throw new Error("Python probe did not stop after SIGKILL");
|
||||
probeProcess = undefined;
|
||||
};
|
||||
|
||||
const probe = (input: ProbeInput): Promise<ProbeResult> => {
|
||||
const child = probeProcess;
|
||||
if (probeFailure !== undefined) return Promise.reject(probeFailure);
|
||||
if (child === undefined || hasExited(child))
|
||||
return Promise.reject(new Error("Python probe is not running"));
|
||||
return new Promise((resolve, reject) => {
|
||||
const pending: PendingProbe = { resolve, reject, timeout: undefined };
|
||||
pending.timeout = setTimeout(() => {
|
||||
failProbeProcess(
|
||||
new Error(
|
||||
`Python probe request timed out after ${String(PROBE_TIMEOUT_MS)} ms`,
|
||||
),
|
||||
);
|
||||
}, PROBE_TIMEOUT_MS);
|
||||
pendingProbes.push(pending);
|
||||
child.stdin.write(`${JSON.stringify(input)}\n`, (error) => {
|
||||
if (error !== null && error !== undefined) failProbeProcess(error);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
beforeAll(startProbeProcess);
|
||||
beforeEach(async () => {
|
||||
if (
|
||||
probeFailure === undefined &&
|
||||
probeProcess !== undefined &&
|
||||
!hasExited(probeProcess)
|
||||
)
|
||||
return;
|
||||
await stopProbeProcess();
|
||||
await startProbeProcess();
|
||||
});
|
||||
afterAll(stopProbeProcess);
|
||||
|
||||
describe("Hopper bridge search", () => {
|
||||
it("returns matching literal values in deterministic order", async () => {
|
||||
await expect(
|
||||
probe({
|
||||
action: "search",
|
||||
items: [
|
||||
["0x1000", "REA_main_1"],
|
||||
["0x2000", "unrelated"],
|
||||
["0x3000", "rea_helper_42"],
|
||||
],
|
||||
params: {
|
||||
pattern: "REA",
|
||||
mode: "literal",
|
||||
case_sensitive: false,
|
||||
},
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
action: "search",
|
||||
ok: true,
|
||||
result: [
|
||||
{ address: "0x1000", value: "REA_main_1" },
|
||||
{ address: "0x3000", value: "rea_helper_42" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("returns matching entries for regex searches", async () => {
|
||||
await expect(
|
||||
probe({
|
||||
action: "search",
|
||||
items: [
|
||||
["0x1000", "REA_GHIDRA_INVENTORY_ENTRY"],
|
||||
["0x2000", "unrelated"],
|
||||
["0x3000", "REA_GHIDRA_LEAF_VALUE"],
|
||||
],
|
||||
params: {
|
||||
pattern: "^REA_GHIDRA_(?:INVENTORY_ENTRY|LEAF_VALUE)$",
|
||||
mode: "regex",
|
||||
case_sensitive: true,
|
||||
},
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
action: "search",
|
||||
ok: true,
|
||||
result: [
|
||||
{ address: "0x1000", value: "REA_GHIDRA_INVENTORY_ENTRY" },
|
||||
{ address: "0x3000", value: "REA_GHIDRA_LEAF_VALUE" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("returns the complete value for a long literal match", async () => {
|
||||
const value = `${"x".repeat(4_096)}needle`;
|
||||
await expect(
|
||||
probe({
|
||||
action: "search",
|
||||
items: [["0x1000", value]],
|
||||
params: {
|
||||
pattern: "needle",
|
||||
mode: "literal",
|
||||
case_sensitive: true,
|
||||
},
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
action: "search",
|
||||
ok: true,
|
||||
result: [{ address: "0x1000", value }],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -48,7 +48,6 @@ const probeResultSchema = z.strictObject({
|
||||
reason: z.string(),
|
||||
}),
|
||||
}),
|
||||
strings: z.strictObject({ "0x401234": z.literal("fixture string") }),
|
||||
procedure_references: z.strictObject({
|
||||
procedure: z.strictObject({
|
||||
address: z.literal("0x401000"),
|
||||
@@ -64,14 +63,6 @@ const probeResultSchema = z.strictObject({
|
||||
unresolved_calls: z.array(z.unknown()),
|
||||
references: z.array(z.unknown()),
|
||||
}),
|
||||
inventory_replies: z.array(
|
||||
z.strictObject({
|
||||
id: z.number().int(),
|
||||
result: z.array(
|
||||
z.strictObject({ address: z.string(), value: z.string() }),
|
||||
),
|
||||
}),
|
||||
),
|
||||
provider_faults: z.array(
|
||||
z.strictObject({
|
||||
id: z.literal(1),
|
||||
@@ -198,28 +189,6 @@ describe("Hopper API facade", () => {
|
||||
},
|
||||
{ id: 9, result: "0x401000" },
|
||||
]);
|
||||
expect(result.inventory_replies).toEqual([
|
||||
{
|
||||
id: 1,
|
||||
result: [
|
||||
{ address: "0x2", value: "string-2" },
|
||||
{ address: "0x10", value: "string-16" },
|
||||
{ address: "0x100", value: "string-256" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
result: [
|
||||
{ address: "0x2", value: "name-2" },
|
||||
{ address: "0x10", value: "name-16" },
|
||||
{ address: "0x100", value: "name-256" },
|
||||
],
|
||||
},
|
||||
{ id: 3, result: [{ address: "0x10", value: "string-16" }] },
|
||||
{ id: 4, result: [{ address: "0x10", value: "name-16" }] },
|
||||
{ id: 5, result: [] },
|
||||
{ id: 6, result: [] },
|
||||
]);
|
||||
expect(stdout).not.toContain("supersecret");
|
||||
expect(result.analysis_guard.message).toContain(
|
||||
"requires completed Hopper background analysis",
|
||||
|
||||
@@ -2,6 +2,18 @@
|
||||
|
||||
volatile int rea_c_global = 7;
|
||||
|
||||
#define REA_LONG_CHUNK "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
|
||||
#define REA_LONG_256 REA_LONG_CHUNK REA_LONG_CHUNK REA_LONG_CHUNK REA_LONG_CHUNK
|
||||
#define REA_LONG_1024 REA_LONG_256 REA_LONG_256 REA_LONG_256 REA_LONG_256
|
||||
__attribute__((noinline, used)) void rea_long_literal_procedure(void) {
|
||||
puts("REA_LONG_LITERAL_" REA_LONG_1024 REA_LONG_1024 REA_LONG_1024 REA_LONG_1024 "needle");
|
||||
puts("REA_UTF8_é_😀");
|
||||
puts("REA_ESCAPED_\"\\line\nend\t\r");
|
||||
puts("REA_LITERAL_BACKSLASH_\\n");
|
||||
puts("REA_LITERAL_…");
|
||||
puts("REA_LATIN1_\xff");
|
||||
}
|
||||
|
||||
__attribute__((noinline, used)) int rea_leaf(int value) {
|
||||
puts("REA_C_LEAF");
|
||||
return value + rea_c_global;
|
||||
|
||||
@@ -16,6 +16,9 @@ int main(void) {
|
||||
@autoreleasepool {
|
||||
Protocol *protocol = @protocol(REAWidgetDelegate);
|
||||
NSLog(@"%@", NSStringFromProtocol(protocol));
|
||||
NSLog(@"REA_UTF16_é_😀");
|
||||
NSLog(@"REA_UTF16_ESCAPED_é_\"\\line\nend\t\r");
|
||||
NSLog(@"\nREA_UTF16_LEADING_é");
|
||||
return [[[REAWidget alloc] init] performAction:@"run" error:0] ? 0 : 1;
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
-48
@@ -1,48 +0,0 @@
|
||||
"""Exercise REA's bridge inventory search without starting a Hopper socket."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
|
||||
def _load_bridge(path):
|
||||
source = Path(path).read_text(encoding="utf-8")
|
||||
namespace = {"__file__": path, "__name__": "rea_hopper_bridge"}
|
||||
exec(compile(source, path, "exec"), namespace)
|
||||
return namespace
|
||||
|
||||
|
||||
def _probe(namespace, payload):
|
||||
action = payload["action"]
|
||||
try:
|
||||
if action == "search":
|
||||
inventory = tuple(tuple(item) for item in payload["items"])
|
||||
namespace["_search_inventory"] = lambda _document, _kind: inventory
|
||||
return {
|
||||
"action": action,
|
||||
"ok": True,
|
||||
"result": namespace["_search_results"](
|
||||
object(), "string", payload["params"]
|
||||
),
|
||||
}
|
||||
raise ValueError("unknown probe action")
|
||||
except Exception as error:
|
||||
return {
|
||||
"action": action,
|
||||
"ok": False,
|
||||
"type": type(error).__name__,
|
||||
"diagnostic_type": namespace["_diagnostic_type"](error),
|
||||
"message": str(error),
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
bridge = _load_bridge(sys.argv[1])
|
||||
if len(sys.argv) >= 3:
|
||||
print(json.dumps(_probe(bridge, json.loads(sys.argv[2])), sort_keys=True))
|
||||
else:
|
||||
for line in sys.stdin:
|
||||
if not line.strip():
|
||||
continue
|
||||
request = json.loads(line)
|
||||
print(json.dumps(_probe(bridge, request), sort_keys=True), flush=True)
|
||||
+1
-55
@@ -30,7 +30,7 @@ class FakeDocument:
|
||||
return 0x401000
|
||||
|
||||
def getSegmentsList(self):
|
||||
return [FakeInventorySegment()]
|
||||
return []
|
||||
|
||||
|
||||
class FakeDocumentProvider:
|
||||
@@ -47,39 +47,6 @@ class FakeDocumentProvider:
|
||||
return cls.current
|
||||
|
||||
|
||||
class FakeStringSegment:
|
||||
def getStringsList(self):
|
||||
return [("fixture string", FakeStringAddress())]
|
||||
|
||||
|
||||
class FakeStringAddress:
|
||||
def __init__(self, value="0x401234"):
|
||||
self.value = value
|
||||
|
||||
def __str__(self):
|
||||
return self.value
|
||||
|
||||
|
||||
class FakeInventorySegment:
|
||||
addresses = [FakeStringAddress("0x10"), 0x100, 0x2]
|
||||
|
||||
def getStringsList(self):
|
||||
return [
|
||||
("string-" + str(self.number(address)), address)
|
||||
for address in self.addresses
|
||||
]
|
||||
|
||||
def getNamedAddresses(self):
|
||||
return self.addresses
|
||||
|
||||
def getNameAtAddress(self, address):
|
||||
return "name-" + str(self.number(address))
|
||||
|
||||
@staticmethod
|
||||
def number(address):
|
||||
return address if isinstance(address, int) else int(str(address), 16)
|
||||
|
||||
|
||||
class FakeReferenceSegment:
|
||||
def getNameAtAddress(self, address):
|
||||
return "fixture-procedure"
|
||||
@@ -120,13 +87,6 @@ class FakeBlock:
|
||||
|
||||
def getEndingAddress(self):
|
||||
return 0x401004
|
||||
|
||||
|
||||
class FakeStringsDocument:
|
||||
def getSegmentsList(self):
|
||||
return [FakeStringSegment()]
|
||||
|
||||
|
||||
def load_bridge(path):
|
||||
namespace = {
|
||||
"__file__": path,
|
||||
@@ -181,7 +141,6 @@ def main():
|
||||
bridge["REA_OWNS_PROCESS_LIFETIME"] = False
|
||||
bridge["_configure_hopper_api"](FakeDocumentProvider)
|
||||
bridge["_bind_session_document"]()
|
||||
strings = bridge["_strings"](FakeStringsDocument())
|
||||
current = bridge["_dispatch"]("current_document", {})
|
||||
current_address = bridge["_dispatch"]("current_address", {})
|
||||
selected = bridge["_session_document"]() is FakeDocumentProvider.current
|
||||
@@ -219,17 +178,6 @@ def main():
|
||||
procedure_info = bridge["_dispatch"](
|
||||
"procedure_info", {"procedure": "0x401000"}
|
||||
)
|
||||
inventories = bridge_replies(bridge, [
|
||||
request(method, params, index)
|
||||
for index, (method, params) in enumerate([
|
||||
("list_strings", {}),
|
||||
("list_names", {}),
|
||||
("list_strings", {"address": "0x10"}),
|
||||
("list_names", {"address": "0x10"}),
|
||||
("list_strings", {"address": "0xff"}),
|
||||
("list_names", {"address": "0xff"}),
|
||||
], 1)
|
||||
])
|
||||
provider_faults = []
|
||||
for error_type in (TypeError, ValueError, KeyError):
|
||||
FakeDocumentProvider.current.address_error = error_type("credential=supersecret")
|
||||
@@ -279,8 +227,6 @@ def main():
|
||||
"imported_without_hopper": unavailable,
|
||||
"current_document": current,
|
||||
"current_address": current_address,
|
||||
"strings": strings,
|
||||
"inventory_replies": inventories,
|
||||
"containing_procedure": containing_procedure,
|
||||
"procedure_references": procedure_references,
|
||||
"procedure_info": procedure_info,
|
||||
|
||||
Reference in New Issue
Block a user