mirror of
https://github.com/morluto/rea.git
synced 2026-11-22 22:45:47 +00:00
perf(ida): bootstrap Hex-Rays bridge once, push down string_at and list_funcs filter, and cache imports (#13469)
* perf(ida): bootstrap Hex-Rays bridge once, push down string_at and list_funcs filter, and cache imports (#13276, #13353) * fix(ida): reload the Python bridge only when its entry point is missing
This commit is contained in:
1 parent
366dbc20bf
commit
522452da70
7 files changed
+340
-78
No files matched your search
@@ -36,6 +36,7 @@ _HEX_ADDRESS = re.compile(r"^0x[0-9a-f]+$", re.IGNORECASE)
|
||||
# one consistent list. REA finishes each enumeration before starting another,
|
||||
# so the lease retains only the most recent snapshot.
|
||||
_rea_pages = globals().setdefault("_rea_pages", {})
|
||||
_rea_imports_cache = globals().setdefault("_rea_imports_cache", {})
|
||||
|
||||
|
||||
def _hex(ea):
|
||||
@@ -83,10 +84,25 @@ def health():
|
||||
|
||||
def list_funcs(queries):
|
||||
offset, count = queries["offset"], queries["count"]
|
||||
total = ida_funcs.get_func_qty()
|
||||
end = min(offset + count, total)
|
||||
data = [_function(ida_funcs.getn_func(i)) for i in range(offset, end)]
|
||||
return [{"data": data, "next_offset": end if end < total else None}]
|
||||
pattern = queries.get("filter")
|
||||
if pattern is None:
|
||||
total = ida_funcs.get_func_qty()
|
||||
end = min(offset + count, total)
|
||||
data = [_function(ida_funcs.getn_func(i)) for i in range(offset, end)]
|
||||
return [{"data": data, "next_offset": end if end < total else None}]
|
||||
|
||||
def build():
|
||||
matcher = re.compile(pattern)
|
||||
result = []
|
||||
for i in range(ida_funcs.get_func_qty()):
|
||||
fn = _function(ida_funcs.getn_func(i))
|
||||
if matcher.search(fn["name"]):
|
||||
result.append(fn)
|
||||
return result
|
||||
|
||||
matches = _snapshot(("funcs", pattern), offset, build)
|
||||
end = min(offset + count, len(matches))
|
||||
return [{"data": matches[offset:end], "next_offset": end if end < len(matches) else None}]
|
||||
|
||||
|
||||
def _lookup(query):
|
||||
@@ -119,6 +135,18 @@ def find_regex(pattern, offset, limit):
|
||||
return {"matches": matches[offset:end], "cursor": _cursor(end, len(matches))}
|
||||
|
||||
|
||||
def string_at(addr):
|
||||
ea = _address(addr)
|
||||
if ea is None:
|
||||
return {"matches": [], "cursor": {"done": True}}
|
||||
matches = [
|
||||
{"addr": _hex(item.ea), "string": str(item)}
|
||||
for item in idautils.Strings()
|
||||
if item.ea == ea
|
||||
]
|
||||
return {"matches": matches, "cursor": {"done": True}}
|
||||
|
||||
|
||||
def decompile(addr, offset, max_lines):
|
||||
f = _entry(addr)
|
||||
if f is None:
|
||||
@@ -191,6 +219,9 @@ def disasm(addr, offset, max_instructions):
|
||||
|
||||
|
||||
def _imports():
|
||||
cached = _rea_imports_cache.get("imports")
|
||||
if cached is not None:
|
||||
return cached
|
||||
found = {}
|
||||
|
||||
def record(ea, name, ordinal):
|
||||
@@ -199,6 +230,7 @@ def _imports():
|
||||
|
||||
for index in range(ida_nalt.get_import_module_qty()):
|
||||
ida_nalt.enum_import_names(index, record)
|
||||
_rea_imports_cache["imports"] = found
|
||||
return found
|
||||
|
||||
|
||||
@@ -325,6 +357,7 @@ _REA_QUERIES = {
|
||||
"list_funcs": list_funcs,
|
||||
"lookup_funcs": lookup_funcs,
|
||||
"find_regex": find_regex,
|
||||
"string_at": string_at,
|
||||
"decompile": decompile,
|
||||
"disasm": disasm,
|
||||
"callees": callees,
|
||||
|
||||
@@ -255,6 +255,19 @@ class BridgeTest(unittest.TestCase):
|
||||
batch_rows[1]["callees"],
|
||||
)
|
||||
self.assertEqual(batch_rows[1], batch_rows[2])
|
||||
self.query("callees", {"addrs": ["0x1000"], "limit": 500})
|
||||
self.assertEqual(enum_calls, [0])
|
||||
|
||||
def test_list_funcs_filter_and_string_at(self):
|
||||
filtered = self.query("list_funcs", {"queries": {"offset": 0, "count": 10, "filter": "help"}})
|
||||
self.assertEqual(
|
||||
filtered,
|
||||
[{"data": [{"addr": "0x2000", "name": "helper", "size": "0x8"}], "next_offset": None}],
|
||||
)
|
||||
found = self.query("string_at", {"addr": "0x6002"})
|
||||
self.assertEqual(found, {"matches": [{"addr": "0x6002", "string": "string 2"}], "cursor": {"done": True}})
|
||||
missing = self.query("string_at", {"addr": "0x9999"})
|
||||
self.assertEqual(missing, {"matches": [], "cursor": {"done": True}})
|
||||
|
||||
def test_callgraph_reports_function_entries_only(self):
|
||||
[row] = self.query("callgraph", {"roots": ["0x1000"], "max_depth": 0})
|
||||
|
||||
@@ -225,9 +225,9 @@ The `hexrays` profile also opens an existing `.idb` or `.i64`, so analysis start
|
||||
|
||||
For an executable, REA checks the private input path and file digest. When IDA reports a recorded input hash, REA compares it with the admitted copy, including the selected thin slice for a universal Mach-O. For a saved database, REA binds the opened copy by `idb_path`. Its `input_path` and `input_sha256` describe the original executable. Results reflect the database's saved content: unsaved changes held by another IDA session, including an unpacked `.id0`/`.id1` set beside it, are not included. Evidence subjects identify the database file, not the input binary. Attached and database-supervisor registrations reject database targets, and Hopper rejects IDA databases.
|
||||
|
||||
Hex-Rays MCP exposes database reads only through `execute_python`. REA therefore sends one fixed, read-only query module, [`bridge/ida/hexrays_queries.py`](https://github.com/morluto/rea/blob/main/bridge/ida/hexrays_queries.py), followed by a single `_rea_query(name, arguments_json)` call. The module answers the same database-supervisor reads REA already validates: health, function inventory and lookup, strings, paged pseudocode and assembly, callees, a depth-zero call graph, xrefs to an address, and a minimal segment survey. Caller-supplied text only ever reaches the module as JSON data, never as Python source, and REA forwards no other Python. Each observation records `execute_python` as the upstream tool, plus the query name, its arguments, and the module's SHA-256 instead of its body. The health reads behind each operation's identity checks are kept the same way, as `health_observations` beside the parsed metadata. Call scans skip data items inside functions.
|
||||
Hex-Rays MCP exposes database reads only through `execute_python`. REA loads a fixed, read-only query module once per database lease, [`bridge/ida/hexrays_queries.py`](https://github.com/morluto/rea/blob/main/bridge/ida/hexrays_queries.py), and invokes `_rea_query(name, arguments_json)` for each read. If the worker no longer defines that entry point, REA reloads the module and retries the read once. The module answers the same database-supervisor reads REA already validates: health, function inventory and lookup, strings, paged pseudocode and assembly, callees, a depth-zero call graph, xrefs to an address, and a minimal segment survey. Caller-supplied text only ever reaches the module as JSON data, never as Python source, and REA forwards no other Python. Each observation records `execute_python` as the upstream tool, plus the query name, its arguments, and the module's SHA-256 instead of its body. The health reads behind each operation's identity checks are kept the same way, as `health_observations` beside the parsed metadata. Call scans skip data items inside functions.
|
||||
|
||||
`execute_python` waits for initial auto-analysis, so readiness is checked before the first read. Function sizes are enclosing spans, as with other IDA profiles. Strings come from IDA's default string list. Xrefs exclude ordinary flow from the preceding instruction. Callees on x86-only targets report every direct code or pointer target of a call instruction: targets inside a function are internal and resolve to that function, and imports, pointer slots, and code outside every function are reported by address as external. Indirect calls without a reference remain unknown. Other targets use the processor-neutral call graph, which reports function entries reached by IDA’s near or far call references. Direct callers remain unavailable for the same reason as in the database-supervisor profile. The observed Hex-Rays MCP does not truncate or preview `execute_python` results, and REA keeps every page to 100 items or fewer. Nonempty engine stdout and stderr are retained in the observation.
|
||||
`execute_python` waits for initial auto-analysis, so readiness is checked before the first read. Function sizes are enclosing spans, as with other IDA profiles. Strings come from IDA's default string list. Xrefs exclude ordinary flow from the preceding instruction. Callees on x86-only targets report every direct code or pointer target of a call instruction: targets inside a function are internal and resolve to that function, and imports, pointer slots, and code outside every function are reported by address as external. Indirect calls without a reference remain unknown. Other targets use the processor-neutral call graph, which reports function entries reached by IDA’s near or far call references. Direct callers remain unavailable for the same reason as in the database-supervisor profile. The observed Hex-Rays MCP does not truncate or preview `execute_python` results, and REA requests up to 1,000 entries per function or string page and up to 1,000 lines or instructions per pseudocode or disassembly page. Nonempty engine stdout and stderr are retained in the observation.
|
||||
|
||||
On close, REA releases its lease with `close_database`. Before removing the workspace, it checks `list_databases` for its lease ID and for any database path inside the workspace. An unleased row can represent a peer or a worker still shutting down. Nexus keeps an `idat` worker's lifetime lock through process exit. Hex-Rays can flush and repack the private database during analysis and release. These database writes stay in the private workspace.
|
||||
|
||||
|
||||
@@ -1,13 +1,22 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { access, readdir, rm } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { createInterface } from "node:readline";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createIdaTarget } from "../../tests/fixtures/idaMcp.js";
|
||||
import { RecordingHexRaysIdaMcp } from "../../tests/fixtures/idaHexRaysMcp.js";
|
||||
import {
|
||||
processTest,
|
||||
type TestProcesses,
|
||||
} from "../../tests/support/process/processFixture.js";
|
||||
import { functionDossierSchema } from "../domain/native/functionDossier.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import { IdaToolRejection, type IdaMcpConnection } from "./IdaMcpConnection.js";
|
||||
import {
|
||||
decodeIdaToolResult,
|
||||
IdaToolRejection,
|
||||
type IdaMcpConnection,
|
||||
} from "./IdaMcpConnection.js";
|
||||
import { readCallGraphCallees } from "./IdaCallGraph.js";
|
||||
import { IdaSessionClient } from "./IdaSessionClient.js";
|
||||
import { runHexRaysQuery } from "./IdaHexRaysProtocol.js";
|
||||
@@ -66,6 +75,72 @@ const workspaces = async (root: string) =>
|
||||
|
||||
const hasPython = spawnSync("python3", ["--version"]).status === 0;
|
||||
|
||||
/** Run the actual generated bridge and queries in one owned Python namespace. */
|
||||
const pythonBridgeFixture = (processes: TestProcesses) => {
|
||||
const fixturePath = fileURLToPath(
|
||||
new URL("../../bridge/ida/test_hexrays_queries.py", import.meta.url),
|
||||
);
|
||||
const python = processes.spawn("python3", [
|
||||
"-I",
|
||||
"-u",
|
||||
"-c",
|
||||
[
|
||||
"import json, runpy, sys, traceback",
|
||||
"sys.modules.update(runpy.run_path(sys.argv[1])['stand_ins']())",
|
||||
"namespace = {}",
|
||||
"for line in sys.stdin:",
|
||||
" code = json.loads(line)",
|
||||
" if code is None:",
|
||||
" namespace.clear()",
|
||||
" print('null')",
|
||||
" continue",
|
||||
" try:",
|
||||
" source, query = code.rsplit('\\n', 1)",
|
||||
" exec(source, namespace)",
|
||||
" print(json.dumps({'result': eval(query, namespace), 'stdout': '', 'stderr': ''}))",
|
||||
" except Exception:",
|
||||
" print(json.dumps({'error': traceback.format_exc()}))",
|
||||
].join("\n"),
|
||||
fixturePath,
|
||||
]);
|
||||
const lines = createInterface({ input: python.stdout });
|
||||
const replies = lines[Symbol.asyncIterator]();
|
||||
const execute = async (code: string | null): Promise<JsonValue> => {
|
||||
python.stdin.write(`${JSON.stringify(code)}\n`);
|
||||
const reply = await replies.next();
|
||||
if (reply.done === true) throw new Error("Hex-Rays fixture exited");
|
||||
return JSON.parse(reply.value) as JsonValue;
|
||||
};
|
||||
const call = vi.fn<IdaMcpConnection["call"]>(async (_name, args) => {
|
||||
const reply = await execute(String(args.code));
|
||||
return typeof reply === "object" &&
|
||||
reply !== null &&
|
||||
"error" in reply &&
|
||||
typeof reply.error === "string"
|
||||
? decodeIdaToolResult({
|
||||
isError: true,
|
||||
content: [{ type: "text", text: reply.error }],
|
||||
})
|
||||
: reply;
|
||||
});
|
||||
const connection: IdaMcpConnection = {
|
||||
connect: async () => [],
|
||||
serverInfo: () => null,
|
||||
close: async () => undefined,
|
||||
detach: () => undefined,
|
||||
call,
|
||||
};
|
||||
return {
|
||||
connection,
|
||||
call,
|
||||
reset: () => execute(null),
|
||||
close: () => {
|
||||
python.stdin.end();
|
||||
lines.close();
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
it.each([1, 500, 1000, 300_000])(
|
||||
"keeps the Hex-Rays Python deadline inside the %sms MCP deadline",
|
||||
async (timeoutMs) => {
|
||||
@@ -262,56 +337,24 @@ describe("Hex-Rays IDA MCP startup profile", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.skipIf(!hasPython)(
|
||||
processTest.skipIf(!hasPython)(
|
||||
"reports complete root scan coverage from the Hex-Rays query bridge",
|
||||
async () => {
|
||||
const fixturePath = fileURLToPath(
|
||||
new URL("../../bridge/ida/test_hexrays_queries.py", import.meta.url),
|
||||
);
|
||||
const connection = {
|
||||
connect: async () => [],
|
||||
serverInfo: () => null,
|
||||
close: async () => undefined,
|
||||
detach: () => undefined,
|
||||
call: async (
|
||||
_tool: string,
|
||||
args: Readonly<Record<string, JsonValue>>,
|
||||
) => {
|
||||
const result = spawnSync(
|
||||
"python3",
|
||||
[
|
||||
"-I",
|
||||
"-c",
|
||||
[
|
||||
"import json, runpy, sys",
|
||||
"fixture = runpy.run_path(sys.argv[1])",
|
||||
"sys.modules.update(fixture['stand_ins']())",
|
||||
"source, query = sys.stdin.read().rsplit('\\n', 1)",
|
||||
"namespace = {}",
|
||||
"exec(source, namespace)",
|
||||
"print(json.dumps(eval(query, namespace)))",
|
||||
].join("\n"),
|
||||
fixturePath,
|
||||
],
|
||||
{ input: String(args.code), encoding: "utf8", timeout: 5000 },
|
||||
);
|
||||
if (result.status !== 0)
|
||||
throw new Error("Hex-Rays fixture query failed", {
|
||||
cause: result.error ?? result.stderr,
|
||||
});
|
||||
return { result: JSON.parse(result.stdout), stdout: "", stderr: "" };
|
||||
},
|
||||
};
|
||||
const graph = await readCallGraphCallees(
|
||||
async (tool, args) =>
|
||||
(await runHexRaysQuery(connection, "lease", tool, args, 1000)).result,
|
||||
"0x1000",
|
||||
);
|
||||
expect(graph.callees).toEqual([{ address: "0x2000", name: "helper" }]);
|
||||
expect(graph.coverage).toMatchObject({
|
||||
status: "complete",
|
||||
discovery: { callees: { status: "unknown" } },
|
||||
});
|
||||
async ({ processes }) => {
|
||||
const { connection, close } = pythonBridgeFixture(processes);
|
||||
try {
|
||||
const graph = await readCallGraphCallees(
|
||||
async (tool, args) =>
|
||||
(await runHexRaysQuery(connection, "lease", tool, args, 1000)).result,
|
||||
"0x1000",
|
||||
);
|
||||
expect(graph.callees).toEqual([{ address: "0x2000", name: "helper" }]);
|
||||
expect(graph.coverage).toMatchObject({
|
||||
status: "complete",
|
||||
discovery: { callees: { status: "unknown" } },
|
||||
});
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -438,9 +481,14 @@ describe("Hex-Rays IDA MCP session", () => {
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
reads.every(({ args }) =>
|
||||
String(args.code).startsWith('"""Read-only REA queries'),
|
||||
),
|
||||
String(reads[0]?.args.code).startsWith('"""Read-only REA queries'),
|
||||
).toBe(true);
|
||||
expect(
|
||||
reads
|
||||
.slice(1)
|
||||
.every(({ args }) =>
|
||||
String(args.code).startsWith("# rea-bridge\n_rea_query("),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(result.value.rawResult).toMatchObject({ worker_backend: backend });
|
||||
const raw = result.value.rawResult as {
|
||||
@@ -611,3 +659,93 @@ describe("Hex-Rays unleased database inventory", () => {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("Hex-Rays query bridge bootstrap and predicate pushdown", () => {
|
||||
processTest.skipIf(!hasPython)(
|
||||
"executes the full bridge once and reloads only when Python loses its entry point",
|
||||
async ({ processes }) => {
|
||||
const { connection, call, reset, close } = pythonBridgeFixture(processes);
|
||||
const health = () =>
|
||||
runHexRaysQuery(connection, "lease-1", "server_health", {}, 1000);
|
||||
try {
|
||||
const initial = await health();
|
||||
expect(initial.result).toMatchObject({
|
||||
status: "ok",
|
||||
input_path: "/private/input",
|
||||
imagebase: "0x400000",
|
||||
});
|
||||
const initialSource = call.mock.calls[0]?.[1].code;
|
||||
const compact = '# rea-bridge\n_rea_query("server_health", "{}")';
|
||||
expect(initialSource).not.toBe(compact);
|
||||
expect((await health()).result).toEqual(initial.result);
|
||||
expect(call.mock.calls.map(([, { code }]) => code)).toEqual([
|
||||
initialSource,
|
||||
compact,
|
||||
]);
|
||||
|
||||
await expect(
|
||||
runHexRaysQuery(
|
||||
connection,
|
||||
"lease-1",
|
||||
"list_funcs",
|
||||
{
|
||||
queries: { offset: 0 },
|
||||
},
|
||||
1000,
|
||||
),
|
||||
).rejects.toThrow(/KeyError: 'count'/);
|
||||
expect(call).toHaveBeenCalledTimes(3);
|
||||
|
||||
await reset();
|
||||
expect((await health()).result).toEqual(initial.result);
|
||||
expect(call.mock.calls.slice(3).map(([, { code }]) => code)).toEqual([
|
||||
compact,
|
||||
initialSource,
|
||||
]);
|
||||
expect((await health()).result).toEqual(initial.result);
|
||||
expect(call.mock.lastCall?.[1].code).toBe(compact);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("pushes exact string address lookup and procedure search filters into the Hex-Rays bridge", async () => {
|
||||
const { producer, client } = await fixture();
|
||||
const byAddress = await client.execute("list_strings", {
|
||||
address: "0x3000",
|
||||
});
|
||||
expect(byAddress.ok).toBe(true);
|
||||
if (!byAddress.ok) throw new Error("expected string_at success");
|
||||
expect(byAddress.value.result).toEqual([
|
||||
{ address: "0x3000", value: "a.b\nC" },
|
||||
]);
|
||||
expect(
|
||||
producer.reads.calls.some(
|
||||
({ name, args }) => name === "string_at" && args.addr === "0x3000",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(producer.reads.calls.some(({ name }) => name === "find_regex")).toBe(
|
||||
false,
|
||||
);
|
||||
|
||||
const procSearch = await client.execute("search_procedures", {
|
||||
pattern: "main",
|
||||
mode: "literal",
|
||||
case_sensitive: true,
|
||||
});
|
||||
expect(procSearch.ok).toBe(true);
|
||||
expect(
|
||||
producer.reads.calls.some(
|
||||
({ name, args }) =>
|
||||
name === "list_funcs" &&
|
||||
typeof args.queries === "object" &&
|
||||
args.queries !== null &&
|
||||
!Array.isArray(args.queries) &&
|
||||
"filter" in args.queries &&
|
||||
args.queries.count === 1000,
|
||||
),
|
||||
).toBe(true);
|
||||
await client.close();
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import { z } from "zod";
|
||||
import { AnalysisProtocolError } from "../domain/analysisErrorCore.js";
|
||||
import { sha256Hex } from "../kernel/sha256Hex.js";
|
||||
import { ownedJsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import type { IdaMcpConnection } from "./IdaMcpConnection.js";
|
||||
import { IdaToolRejection, type IdaMcpConnection } from "./IdaMcpConnection.js";
|
||||
import type { IdaRawObservation } from "./IdaOperationRunner.js";
|
||||
|
||||
/** The official Hex-Rays IDA MCP catalog this profile requires. */
|
||||
@@ -21,6 +21,7 @@ const hexRaysQueries: ReadonlySet<string> = new Set([
|
||||
"list_funcs",
|
||||
"lookup_funcs",
|
||||
"find_regex",
|
||||
"string_at",
|
||||
"decompile",
|
||||
"disasm",
|
||||
"callees",
|
||||
@@ -98,6 +99,18 @@ const queryBridge = () => {
|
||||
return querySource;
|
||||
};
|
||||
|
||||
/** Leases on a connection whose Python globals already have `queryBridge()` loaded. */
|
||||
const bootstrappedLeases = new WeakMap<IdaMcpConnection, Set<string>>();
|
||||
|
||||
const isMissingBridgeError = (error: unknown): boolean => {
|
||||
if (!(error instanceof IdaToolRejection)) return false;
|
||||
const reason = error.diagnostics?.reason;
|
||||
const detail = typeof reason === "string" ? reason : error.message;
|
||||
return /(?:^|\n)NameError: name '_rea_query' is not defined$/u.test(
|
||||
detail.trimEnd(),
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Answer one database-supervisor read through `execute_python` with REA's
|
||||
* fixed, read-only query bridge. Only the query name and its JSON arguments
|
||||
@@ -120,18 +133,38 @@ export const runHexRaysQuery = async (
|
||||
const { database: _database, ...queryArguments } = args;
|
||||
const bridge = queryBridge();
|
||||
const timeoutSeconds = timeoutMs / 1000;
|
||||
const raw = await connection.call(
|
||||
"execute_python",
|
||||
{
|
||||
instance_id: instanceId,
|
||||
// A JSON string literal is also a valid Python string literal.
|
||||
code: `${bridge.code}\n_rea_query(${JSON.stringify(query)}, ${JSON.stringify(JSON.stringify(queryArguments))})`,
|
||||
// Reserve up to five seconds for the reply, including on short budgets.
|
||||
// Upstream times the initial auto-analysis separately.
|
||||
timeout: timeoutSeconds - Math.min(5, timeoutSeconds / 2),
|
||||
},
|
||||
{ timeoutMs, ...(signal === undefined ? {} : { signal }) },
|
||||
);
|
||||
// A JSON string literal is also a valid Python string literal.
|
||||
const callLine = `_rea_query(${JSON.stringify(query)}, ${JSON.stringify(JSON.stringify(queryArguments))})`;
|
||||
const callOptions = {
|
||||
timeoutMs,
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
};
|
||||
const engineTimeout = timeoutSeconds - Math.min(5, timeoutSeconds / 2);
|
||||
let leases = bootstrappedLeases.get(connection);
|
||||
const invoke = (code: string) =>
|
||||
connection.call(
|
||||
"execute_python",
|
||||
{ instance_id: instanceId, code, timeout: engineTimeout },
|
||||
callOptions,
|
||||
);
|
||||
let raw: JsonValue;
|
||||
if (leases?.has(instanceId)) {
|
||||
try {
|
||||
raw = await invoke(`# rea-bridge\n${callLine}`);
|
||||
} catch (error) {
|
||||
if (!isMissingBridgeError(error)) throw error;
|
||||
leases.delete(instanceId);
|
||||
raw = await invoke(`${bridge.code}\n${callLine}`);
|
||||
leases.add(instanceId);
|
||||
}
|
||||
} else {
|
||||
raw = await invoke(`${bridge.code}\n${callLine}`);
|
||||
if (leases === undefined) {
|
||||
leases = new Set();
|
||||
bootstrappedLeases.set(connection, leases);
|
||||
}
|
||||
leases.add(instanceId);
|
||||
}
|
||||
const execution = executionSchema.parse(raw);
|
||||
return {
|
||||
tool: "execute_python",
|
||||
|
||||
@@ -153,13 +153,22 @@ export class IdaOperationRunner {
|
||||
return observation.result;
|
||||
}
|
||||
|
||||
async functions(): Promise<IdaFunction[]> {
|
||||
private get isHexRaysBridge(): boolean {
|
||||
return this.options.invoke !== undefined;
|
||||
}
|
||||
|
||||
async functions(candidatePattern?: string): Promise<IdaFunction[]> {
|
||||
const result: IdaFunction[] = [];
|
||||
const count = this.isHexRaysBridge ? 1000 : 100;
|
||||
let offset: number | null = 0;
|
||||
while (offset !== null) {
|
||||
const current: number = offset;
|
||||
const queries =
|
||||
candidatePattern !== undefined && this.isHexRaysBridge
|
||||
? { offset, count, filter: candidatePattern }
|
||||
: { offset, count };
|
||||
const value = modernPageSchema.parse(
|
||||
await this.call("list_funcs", { queries: { offset, count: 100 } }),
|
||||
await this.call("list_funcs", { queries }),
|
||||
)[0];
|
||||
if (value === undefined)
|
||||
throw new AnalysisProtocolError("IDA MCP omitted its function page.");
|
||||
@@ -324,6 +333,7 @@ export class IdaOperationRunner {
|
||||
if (this.protocol === "native")
|
||||
this.limitations.push(IDA_NATIVE_STRING_LIMITATION);
|
||||
const result: { address: string; value: string }[] = [];
|
||||
const limit = this.isHexRaysBridge ? 1000 : 100;
|
||||
let offset: number | null = 0;
|
||||
while (offset !== null) {
|
||||
const current: number = offset;
|
||||
@@ -333,7 +343,7 @@ export class IdaOperationRunner {
|
||||
candidatePattern ??
|
||||
(this.protocol === "native" ? "[\\s\\S]*" : "(?s).*"),
|
||||
offset,
|
||||
limit: 100,
|
||||
limit,
|
||||
}),
|
||||
);
|
||||
if (page.error !== undefined && page.error !== null)
|
||||
@@ -348,8 +358,22 @@ export class IdaOperationRunner {
|
||||
return result;
|
||||
}
|
||||
|
||||
private async stringAt(
|
||||
address: string,
|
||||
): Promise<{ address: string; value: string }[]> {
|
||||
const page = idaStringsPageSchema.parse(
|
||||
await this.call("string_at", { addr: address }),
|
||||
);
|
||||
if (page.error !== undefined && page.error !== null)
|
||||
throw new AnalysisProtocolError(
|
||||
`IDA string lookup failed: ${page.error}`,
|
||||
);
|
||||
return page.matches.map((s) => ({ address: s.addr, value: s.string }));
|
||||
}
|
||||
|
||||
async assembly(fn: IdaFunction): Promise<IdaDisassembly> {
|
||||
let result: IdaDisassembly | undefined;
|
||||
const maxInstructions = this.isHexRaysBridge ? 1000 : 100;
|
||||
let offset: number | null = 0;
|
||||
while (offset !== null) {
|
||||
const page = (
|
||||
@@ -360,7 +384,7 @@ export class IdaOperationRunner {
|
||||
await this.call("disasm", {
|
||||
addr: fn.address,
|
||||
offset,
|
||||
max_instructions: 100,
|
||||
max_instructions: maxInstructions,
|
||||
}),
|
||||
);
|
||||
if (page.asm === null || page.error !== undefined)
|
||||
@@ -403,13 +427,14 @@ export class IdaOperationRunner {
|
||||
return page.pseudocode;
|
||||
}
|
||||
const result: string[] = [];
|
||||
const maxLines = this.isHexRaysBridge ? 1000 : 100;
|
||||
let offset: number | null = 0;
|
||||
while (offset !== null) {
|
||||
const page = modernDecompileSchema.parse(
|
||||
await this.call("decompile", {
|
||||
addr: fn.address,
|
||||
offset,
|
||||
max_lines: 100,
|
||||
max_lines: maxLines,
|
||||
}),
|
||||
);
|
||||
if (page.code === null || page.error !== undefined)
|
||||
@@ -586,7 +611,17 @@ export class IdaOperationRunner {
|
||||
? analysisSearchQuerySchema.parse(parameters)
|
||||
: undefined;
|
||||
if (operation === "list_procedures" || operation === "search_procedures") {
|
||||
const items = (await this.functions()).map((fn) => ({
|
||||
const candidateLiteral =
|
||||
query === undefined
|
||||
? undefined
|
||||
: query.mode === "literal"
|
||||
? query.pattern
|
||||
: extractRequiredRegexLiteral(query.pattern, query.case_sensitive);
|
||||
const candidatePattern =
|
||||
candidateLiteral === undefined || query === undefined
|
||||
? undefined
|
||||
: idaLiteralSearchPattern(candidateLiteral, query.case_sensitive);
|
||||
const items = (await this.functions(candidatePattern)).map((fn) => ({
|
||||
address: fn.address,
|
||||
value: fn.name,
|
||||
}));
|
||||
@@ -597,6 +632,8 @@ export class IdaOperationRunner {
|
||||
query === undefined && parameters.address !== undefined
|
||||
? idaAddressSchema.parse(parameters.address)
|
||||
: undefined;
|
||||
if (selectedAddress !== undefined && this.isHexRaysBridge)
|
||||
return this.stringAt(selectedAddress);
|
||||
const candidateLiteral =
|
||||
query === undefined
|
||||
? undefined
|
||||
|
||||
Vendored
+8
@@ -228,6 +228,14 @@ export class RecordingIdaMcp implements IdaMcpConnection {
|
||||
matches: [{ addr: "0x3000", string: "a.b\nC" }],
|
||||
cursor: { done: true },
|
||||
};
|
||||
case "string_at":
|
||||
return {
|
||||
matches:
|
||||
args.addr === "0x3000"
|
||||
? [{ addr: "0x3000", string: "a.b\nC" }]
|
||||
: [],
|
||||
cursor: { done: true },
|
||||
};
|
||||
default:
|
||||
throw new Error(`Unimplemented producer tool ${name}`);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user