fix(android)!: preserve JVM settings and reuse metadata sessions (#908)
* perf(graph): avoid repeated traversal edge scans and copies * fix(android)!: preserve JVM settings and reuse metadata sessions Read class metadata without generating application source, retain immutable serialized APK sessions, and join owned cleanup on cancellation and shutdown. BREAKING CHANGE: Android analysis now requires a full JDK 17 or newer with its compiler module for the packaged Java source bridge.
This commit is contained in:
@@ -163,7 +163,7 @@ Deep native binary analysis requires [Hopper](https://www.hopperapp.com/), [Ghid
|
||||
|
||||
Firmware region inspection and explicit extraction use caller-supplied Binwalk and Unblob on Linux. See [Firmware analysis](docs/firmware-analysis.md) for setup, provenance, resource limits and native handoff.
|
||||
|
||||
Static APK analysis uses a separately supplied headless JADX JAR and Java, with no emulator or APK execution. See [Android analysis](docs/android-analysis.md) for setup, CLI/MCP operations, coverage and public test fixtures. Authenticated IPA inventory Evidence can be projected with [Apple application analysis](docs/apple-application-analysis.md).
|
||||
Static APK analysis uses a separately supplied headless JADX JAR and a full JDK, with no emulator or APK execution. See [Android analysis](docs/android-analysis.md) for setup, CLI/MCP operations, coverage and public test fixtures. Authenticated IPA inventory Evidence can be projected with [Apple application analysis](docs/apple-application-analysis.md).
|
||||
|
||||
Repository main and npm 4.1.0 include experimental Windows x64 Ghidra support for native x86-64 PE applications on local NTFS, with bundled Job Object, private-DACL, and path-admission controls. Check the [release boundary](docs/installation.md#released-package-and-main) before expecting this from an older npm package. See [Windows Ghidra P0](docs/windows-ghidra-p0.md) for prerequisites and verified scope.
|
||||
|
||||
@@ -420,7 +420,7 @@ The public interface describes what the agent is trying to learn. Providers deci
|
||||
|
||||
REA supports native application, JavaScript, Electron, .NET, and browser investigation on macOS and Linux. Individual tools have platform and runtime prerequisites. `rea capabilities` and `rea providers` describe the binary-session providers and auxiliary operations; they are not an inventory of every browser, Android, or application workflow. Use the connected MCP tool list and `binary_session` tool availability for the full MCP surface, and the relevant guide for each tool's prerequisites. Repository main can be ahead of [the npm release](docs/installation.md#released-package-and-main).
|
||||
|
||||
Static Android APK inspection is verified on Linux with headless JADX; see [Android analysis](docs/android-analysis.md) for its separate prerequisites and coverage.
|
||||
Static Android APK inspection supports Linux and macOS; the current metadata bridge is verified on macOS arm64 with headless JADX; see [Android analysis](docs/android-analysis.md) for its separate prerequisites and coverage.
|
||||
|
||||
- **Native binaries:** Open Mach-O, ELF, PE, and Mac `.app` targets through a selected deep provider. Hopper and Ghidra cover broad inventory and function analysis; the IDA adapter supplies its documented read-only function/string operations. Hopper also accepts `.hop` databases and supports annotations.
|
||||
- **Packages and resources:** Inspect directories, ZIP, APK, IPA, ASAR, plists, compiled Interface Builder files, and Apple asset catalogs. Artifact requests name the input and requested extraction or traversal directly; macOS DMG traversal also requires the host's native mounting support.
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
import com.atxx.jhmcp.*;
|
||||
import com.google.gson.*;
|
||||
import io.modelcontextprotocol.kotlin.sdk.server.*;
|
||||
import io.modelcontextprotocol.kotlin.sdk.types.*;
|
||||
import jadx.api.*;
|
||||
import jadx.core.dex.nodes.*;
|
||||
import java.io.PrintStream;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.stream.Collectors;
|
||||
import kotlin.Unit;
|
||||
import kotlin.coroutines.EmptyCoroutineContext;
|
||||
import kotlinx.coroutines.BuildersKt;
|
||||
import kotlinx.io.CoreKt;
|
||||
import kotlinx.io.JvmCoreKt;
|
||||
import kotlinx.serialization.json.JsonObject;
|
||||
|
||||
/** REA-owned metadata boundary for the unmodified jadx-headless-mcp 0.7.1 JAR. */
|
||||
class ReaJadxBridge {
|
||||
private static final Gson JSON = new Gson();
|
||||
private final SessionHolder holder;
|
||||
private JadxSession indexedSession;
|
||||
private Map<String, List<ClassSnapshot>> classes = Map.of();
|
||||
|
||||
private record MethodSnapshot(String name, String shortId, Map<String, Object> summary) {}
|
||||
private record ClassSnapshot(JavaClass node, List<MethodSnapshot> methods, Map<String, Object> summary) {}
|
||||
|
||||
private ReaJadxBridge(SessionHolder holder) { this.holder = holder; }
|
||||
|
||||
private static CallToolResult text(String value, boolean failed) {
|
||||
return new CallToolResult(List.of(new TextContent(value, null, null)), failed, null, null);
|
||||
}
|
||||
|
||||
private static CallToolResult json(Object value) { return text(JSON.toJson(value), false); }
|
||||
|
||||
private static String string(JsonObject args, String name) {
|
||||
JsonElement value = JsonParser.parseString(args.toString()).getAsJsonObject().get(name);
|
||||
if (value == null || !value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString())
|
||||
throw new IllegalArgumentException(name + " must be a string");
|
||||
return value.getAsString();
|
||||
}
|
||||
|
||||
private static int integer(JsonObject args, String name, int fallback) {
|
||||
JsonElement value = JsonParser.parseString(args.toString()).getAsJsonObject().get(name);
|
||||
if (value == null) return fallback;
|
||||
if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isNumber())
|
||||
throw new IllegalArgumentException(name + " must be a nonnegative integer");
|
||||
try {
|
||||
int result = value.getAsBigDecimal().intValueExact();
|
||||
if (result < 0) throw new ArithmeticException();
|
||||
return result;
|
||||
} catch (ArithmeticException error) {
|
||||
throw new IllegalArgumentException(name + " must be a nonnegative integer", error);
|
||||
}
|
||||
}
|
||||
|
||||
private JadxSession session() {
|
||||
JadxSession current = holder.current();
|
||||
if (current == null) throw new IllegalArgumentException("No APK loaded");
|
||||
return current;
|
||||
}
|
||||
|
||||
private ClassSnapshot selected(JsonObject args) {
|
||||
JadxSession current = session();
|
||||
if (indexedSession != current) {
|
||||
Map<String, List<ClassSnapshot>> index = new LinkedHashMap<>();
|
||||
if (!current.getClasses().isEmpty()) {
|
||||
JadxDecompiler decompiler = current.getClasses().get(0).getClassNode().root().getDecompiler();
|
||||
// JavaClass.getMethods/getFields/getInnerClasses all load code. Raw nodes do not.
|
||||
// Snapshot every identity before code generation can rewrite aliases or members.
|
||||
for (JavaClass cls : decompiler.getClassesWithInners()) {
|
||||
ClassNode node = cls.getClassNode();
|
||||
List<MethodNode> ordered = new ArrayList<>(node.getMethods());
|
||||
ordered.sort(Comparator.comparing(MethodNode::getAlias));
|
||||
List<MethodSnapshot> methods = ordered.stream().map(method -> {
|
||||
String name = method.getAlias();
|
||||
String signature = name + "(" + method.getArgTypes().stream()
|
||||
.map(Object::toString).collect(Collectors.joining(", "))
|
||||
+ "): " + method.getReturnType().toString();
|
||||
return new MethodSnapshot(name, method.getMethodInfo().getShortId(), Map.of(
|
||||
"name", name, "signature", signature,
|
||||
"is_constructor", method.isConstructor(), "def_pos", 0));
|
||||
}).toList();
|
||||
List<Map<String, Object>> fields = node.getFields().stream()
|
||||
.sorted(Comparator.comparing(FieldNode::getAlias))
|
||||
.map(field -> Map.<String, Object>of("name", field.getAlias(),
|
||||
"type", field.getType().toString(), "def_pos", 0)).toList();
|
||||
List<String> inner = node.getInnerClasses().stream().map(ClassNode::getFullName).toList();
|
||||
Map<String, Object> summary = Map.of(
|
||||
"full_name", cls.getFullName(), "name", cls.getName(),
|
||||
"method_count", methods.size(), "field_count", fields.size(),
|
||||
"inner_class_count", inner.size(), "inner_classes", inner,
|
||||
"methods", methods.stream().map(MethodSnapshot::summary).toList(), "fields", fields);
|
||||
index.computeIfAbsent(cls.getFullName(), ignored -> new ArrayList<>())
|
||||
.add(new ClassSnapshot(cls, methods, summary));
|
||||
}
|
||||
}
|
||||
classes = Collections.unmodifiableMap(index);
|
||||
indexedSession = current;
|
||||
}
|
||||
String name = string(args, "class_name");
|
||||
List<ClassSnapshot> candidates = classes.get(name);
|
||||
if (candidates == null) throw new IllegalArgumentException("Exact class not found: " + name);
|
||||
if (candidates.size() != 1) throw new IllegalArgumentException("Ambiguous metadata class identity: " + name
|
||||
+ "; raw identities: " + candidates.stream().map(candidate -> candidate.node().getRawName()).toList());
|
||||
return candidates.get(0);
|
||||
}
|
||||
|
||||
private List<MethodSnapshot> methods(ClassSnapshot cls, JsonObject args) {
|
||||
String name = string(args, "method_name");
|
||||
List<MethodSnapshot> result = cls.methods().stream().filter(method -> method.name().equals(name)).toList();
|
||||
if (result.isEmpty()) throw new IllegalArgumentException("Method not found: " + name);
|
||||
return result;
|
||||
}
|
||||
|
||||
private JavaMethod method(ClassSnapshot cls, MethodSnapshot selected) {
|
||||
JavaMethod result = cls.node().searchMethodByShortId(selected.shortId());
|
||||
if (result == null) throw new IllegalArgumentException("Method identity no longer available: " + selected.shortId());
|
||||
return result;
|
||||
}
|
||||
|
||||
private CallToolResult handle(String name, JsonObject args) {
|
||||
if (name.equals("rea_jvm_status")) return json(Map.of(
|
||||
"engine_reported_version", BuildInfo.VERSION,
|
||||
"max_heap_bytes", Runtime.getRuntime().maxMemory(),
|
||||
"available_processors", Runtime.getRuntime().availableProcessors(),
|
||||
"java_version", System.getProperty("java.version"),
|
||||
"metadata_scope", "parsed_members"));
|
||||
JadxSession current = session();
|
||||
if (name.equals("list_classes")) {
|
||||
List<String> names = current.getClassFqns();
|
||||
int offset = integer(args, "offset", 0);
|
||||
int limit = integer(args, "limit", 200);
|
||||
int start = Math.min(offset, names.size());
|
||||
int end = (int) Math.min((long) start + limit, names.size());
|
||||
return json(Map.of("total", names.size(), "offset", offset, "limit", limit,
|
||||
"items", names.subList(start, end)));
|
||||
}
|
||||
ClassSnapshot cls = selected(args);
|
||||
if (name.equals("get_class_summary")) return json(cls.summary());
|
||||
if (name.equals("get_method_body")) {
|
||||
List<MethodSnapshot> overloads = methods(cls, args);
|
||||
int index = integer(args, "overload_index", 0);
|
||||
if (index >= overloads.size()) throw new IllegalArgumentException("overload_index out of range: " + index);
|
||||
JavaMethod method = method(cls, overloads.get(index));
|
||||
JadxSession.SmartCode code = current.getMethodBodySmart(method, current.getMaxSourceBytes(), true);
|
||||
return json(Map.of("class_name", cls.summary().get("full_name"),
|
||||
"method_name", overloads.get(index).name(), "full_name", method.getFullName(),
|
||||
"overload_index", index, "overload_count", overloads.size(),
|
||||
"mode", code.getKind(), "fell_back", code.getFellBack(),
|
||||
"markers", code.getMarkers(), "body", code.getText()));
|
||||
}
|
||||
List<JavaNode> uses;
|
||||
String target = string(args, "class_name");
|
||||
if (name.equals("get_xrefs_to_class")) uses = cls.node().getUseIn();
|
||||
else {
|
||||
List<MethodSnapshot> overloads = methods(cls, args);
|
||||
if (overloads.size() != 1) throw new IllegalArgumentException("Method references require a unique overload");
|
||||
target += "." + overloads.get(0).name();
|
||||
uses = method(cls, overloads.get(0)).getUseIn();
|
||||
}
|
||||
// REA consumes all references without materializing source line information.
|
||||
List<Map<String, Object>> items = uses.stream().map(node -> current.describeUsage(node, false)).toList();
|
||||
return json(Map.of("target", target, "total", uses.size(), "count", items.size(),
|
||||
"resolve_line", false, "items", items));
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
PrintStream protocolOut = System.out;
|
||||
System.setOut(System.err);
|
||||
SessionHolder holder = new SessionHolder(new SessionConfig(
|
||||
1048576, 0, 90000L, 1, List.of(), List.of(), 64, ResourceMode.FULL));
|
||||
ServerCapabilities capabilities = new ServerCapabilities(
|
||||
new ServerCapabilities.Tools(null), null, null, null, null, null, null, Map.of());
|
||||
Server server = new Server(new Implementation("rea-jadx-bridge", "1", null, null, null),
|
||||
new ServerOptions(capabilities), "", ignored -> Unit.INSTANCE);
|
||||
SessionToolsKt.registerSessionTools(server, holder);
|
||||
ManifestToolsKt.registerManifestTools(server, holder);
|
||||
ClassToolsKt.registerClassTools(server, holder);
|
||||
MethodToolsKt.registerMethodTools(server, holder);
|
||||
XrefToolsKt.registerXrefTools(server, holder);
|
||||
ReaJadxBridge bridge = new ReaJadxBridge(holder);
|
||||
Set<String> consumed = Set.of("load_apk", "get_app_info", "get_android_manifest",
|
||||
"list_classes", "get_class_summary", "get_method_body",
|
||||
"get_xrefs_to_class", "get_xrefs_to_method");
|
||||
for (String name : new ArrayList<>(server.getTools().keySet()))
|
||||
if (!consumed.contains(name)) server.removeTool(name);
|
||||
Tool diagnostics = new Tool("rea_jvm_status",
|
||||
new ToolSchema(null, new JsonObject(Map.of()), List.of(), null),
|
||||
"Observed worker JVM and metadata scope", null, null, null, null, null, null);
|
||||
server.addTool(diagnostics, (connection, request, continuation) -> bridge.handle("rea_jvm_status", request.getArguments()));
|
||||
for (String name : List.of("list_classes", "get_class_summary",
|
||||
"get_method_body", "get_xrefs_to_class", "get_xrefs_to_method")) {
|
||||
Tool tool = server.getTools().get(name).getTool();
|
||||
server.removeTool(name);
|
||||
List<String> fields = switch (name) {
|
||||
case "list_classes" -> List.of("offset", "limit");
|
||||
case "get_method_body" -> List.of("class_name", "method_name", "overload_index");
|
||||
case "get_xrefs_to_method" -> List.of("class_name", "method_name");
|
||||
default -> List.of("class_name");
|
||||
};
|
||||
Map<String, kotlinx.serialization.json.JsonElement> properties = new LinkedHashMap<>();
|
||||
for (String field : fields) properties.put(field, tool.getInputSchema().getProperties().get(field));
|
||||
String description = switch (name) {
|
||||
case "list_classes" -> "Indexed pages of all top-level class names, with offset and limit.";
|
||||
case "get_class_summary" -> "Parsed member metadata for one exact class name; no source generation.";
|
||||
case "get_method_body" -> "Source for an exact class and stable same-name overload index, with smali fallback.";
|
||||
default -> "Complete static references to an exact class or unique method; source lines are unresolved.";
|
||||
};
|
||||
Tool narrowed = new Tool(name, new ToolSchema(null, new JsonObject(properties),
|
||||
tool.getInputSchema().getRequired(), null), description, null, null, null, null, null, null);
|
||||
server.addTool(narrowed, (connection, request, continuation) -> {
|
||||
try { return bridge.handle(name, request.getArguments()); }
|
||||
catch (IllegalArgumentException error) { return text(error.getMessage(), true); }
|
||||
});
|
||||
}
|
||||
CountDownLatch done = new CountDownLatch(1);
|
||||
server.onClose(() -> { done.countDown(); return Unit.INSTANCE; });
|
||||
StdioServerTransport transport = new StdioServerTransport(
|
||||
CoreKt.buffered(JvmCoreKt.asSource(System.in)),
|
||||
CoreKt.buffered(JvmCoreKt.asSink(protocolOut)));
|
||||
transport.onClose(() -> { done.countDown(); return Unit.INSTANCE; });
|
||||
ServerSession connection = null;
|
||||
try {
|
||||
connection = BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> server.createSession(transport, continuation));
|
||||
done.await();
|
||||
} finally {
|
||||
try {
|
||||
if (connection != null) {
|
||||
ServerSession connected = connection;
|
||||
// Unsubscribe the connection before the SDK joins its notification service.
|
||||
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> connected.close(continuation));
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> server.close(continuation));
|
||||
} finally {
|
||||
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> holder.unload(continuation));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+41
-10
@@ -11,7 +11,9 @@ connected server's tool list before selecting it.
|
||||
|
||||
## Supply tools
|
||||
|
||||
Use **Java 17 or newer** and **jadx-headless-mcp 0.7.1**. REA does not install Java,
|
||||
Use a **full JDK 17 or newer** (including its compiler module) and
|
||||
**jadx-headless-mcp 0.7.1**. REA runs its packaged Java metadata bridge in
|
||||
source-file mode against the unmodified engine JAR. REA does not install Java,
|
||||
an Android SDK, JADX, a device service or an emulator. Set the path in the shell
|
||||
or MCP server environment:
|
||||
|
||||
@@ -21,8 +23,9 @@ export REA_JADX_MCP_JAR=/absolute/path/jadx-headless-mcp-0.7.1-all.jar
|
||||
export JAVA_HOME=/absolute/path/existing-jdk
|
||||
```
|
||||
|
||||
Linux is verified with the public Appium ApiDemos fixture. The POSIX adapter can
|
||||
run on macOS, but that host has not undergone real Android verification.
|
||||
The current metadata bridge is verified on macOS arm64 with OpenJDK 21 and the
|
||||
public Appium ApiDemos fixture. The POSIX adapter also supports Linux; the new
|
||||
bridge has not yet undergone real verification on Linux/JDK 25.
|
||||
Windows is unsupported for this provider's owned stdio process boundary.
|
||||
|
||||
## Answer an analyst question
|
||||
@@ -72,7 +75,10 @@ selected overload. Native/abstract methods with no decompiled body report
|
||||
Signature verification is explicitly `not_performed`.
|
||||
- Class search consumes all pages and checks their counts. An empty `query`
|
||||
inventories all class names; class names are decompiler representations.
|
||||
- Class inventories return display signatures, fields and inner class names.
|
||||
- Class inventories read parsed metadata without generating source and return
|
||||
full reported display types, fields and inner class names. Synthetic members
|
||||
that code generation hides can appear in the inventory; it stays consistent
|
||||
after method decompilation within the retained session.
|
||||
Exact DEX descriptors are unknown. Overload indices are tied to this artifact
|
||||
and engine, not stable identities across different builds.
|
||||
- Method inspection reports Java or smali, fallback markers and complete/partial
|
||||
@@ -109,23 +115,48 @@ runtime calls.
|
||||
|
||||
## Resource and lifecycle limits
|
||||
|
||||
Each request creates private, immutable APK and JAR copies. Their workspace and
|
||||
owned process group are cleaned on success, failure, timeout and cancellation.
|
||||
REA retains one serialized session with private, immutable APK, engine JAR and
|
||||
metadata-bridge copies. Matching requests reuse the loaded engine. APK/engine
|
||||
digests and JVM configuration are checked before reuse; changed inputs retire
|
||||
the previous session. Sessions are cleaned after 60 seconds of inactivity, on
|
||||
target/configuration changes, failure, timeout, cancellation, MCP disconnect or
|
||||
server shutdown. One-shot CLI commands always join cleanup before returning.
|
||||
REA never writes to the original APK or launches target code.
|
||||
|
||||
If process cleanup cannot be confirmed, REA retains the workspace and reports its
|
||||
location. That provider instance blocks subsequent engine launches until the
|
||||
caller resolves the reported resources and starts a fresh instance.
|
||||
|
||||
The provider serializes requests within each REA instance, uses one worker and
|
||||
sets JVM maximum heap to **512 MiB**. Heap is not a total RSS cap: the JVM also
|
||||
The provider uses one JADX analysis worker independently of JVM processor and
|
||||
garbage-collector settings. REA supplies no default heap or visible-CPU override;
|
||||
Java uses its normal ergonomics and inherits caller JVM settings. Optional
|
||||
provider settings add explicit JVM arguments:
|
||||
|
||||
```sh
|
||||
export REA_JADX_HEAP_MIB=8192
|
||||
# Optional, independent of the single JADX worker:
|
||||
export REA_JADX_ACTIVE_PROCESSOR_COUNT=4
|
||||
# Or select settings through Java's standard environment options:
|
||||
export JAVA_TOOL_OPTIONS=-Xmx8g
|
||||
```
|
||||
|
||||
Both REA settings must be positive safe integers; processor counts must also fit
|
||||
the JVM's signed 32-bit range. REA preserves
|
||||
`JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS` and `_JAVA_OPTIONS` rather than replacing
|
||||
them. Java's standard precedence applies: explicit command-line heap settings
|
||||
override `JAVA_TOOL_OPTIONS`, while `_JAVA_OPTIONS` can override command-line
|
||||
settings. Evidence reports the worker's observed `Runtime.maxMemory()` rounded
|
||||
down to MiB and retains exact bytes, Java version and visible processors in its
|
||||
raw runtime response. The observed allocatable heap can differ from configured
|
||||
`-Xmx`, especially with Serial GC. Heap is not a total RSS cap: the JVM also
|
||||
uses native memory. Independent REA instances have independent queues. Whole
|
||||
operations have a **120-second** execution deadline after reaching the queue's
|
||||
front; upstream decompilation is limited to **90 seconds**.
|
||||
|
||||
Decoded manifest and method text have a **1 MiB** upstream byte budget and report
|
||||
truncation. A protocol frame above **8 MiB**, or cumulative stdout/stderr above
|
||||
**32 MiB**, fails with a diagnostic instead of returning an incomplete inventory
|
||||
truncation. Class-name pages use indexed slices of up to 4,096 names without changing the
|
||||
complete, case-sensitive search contract. A protocol frame above **8 MiB**, or combined stdout/stderr above
|
||||
**32 MiB per operation**, fails with a diagnostic instead of returning an incomplete inventory
|
||||
as complete. These are memory-safety boundaries, not undocumented result caps.
|
||||
|
||||
## Real verification
|
||||
|
||||
@@ -669,9 +669,9 @@
|
||||
"mcp_prompts": 6
|
||||
},
|
||||
"digests": {
|
||||
"tools_sha256": "7d34beb174889c873bad4bae9668558fd72ee6e67f610e06127554dae875ea7e",
|
||||
"tools_sha256": "bfb106573792db139ad5c651705435818ec9dceb07aad8da6076836c8f77cc6b",
|
||||
"prompts_sha256": "ef2de8814390b340623c32001610aa2709d90bed51537b6e562ab3abf144ab4d",
|
||||
"combined_sha256": "2ea72f46db5355f3427fd7b2d7f733bacec0d7c334f2e60fe2da78e8323b92ba",
|
||||
"combined_sha256": "95ad932755e4fbcaed940d2e4f968563c63b77d9dcfbc5058c91dff3f844829e",
|
||||
"providers_sha256": "a7d885531ee25d42c51385444faec544d34cd7eba6250a7dc75c4faedd4454a3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"manifest_id": "ecm_ce4060c0134f89240982703dc2ed56d182edc7bb35ea40ae9c0efba3373be81a",
|
||||
"manifest_id": "ecm_2e2c32ffd3a91da87fde91e199a2d3ce8a804aebd07c23dd4b5170ba40fe4bc7",
|
||||
"verifier": {
|
||||
"id": "rea-managed-conformance",
|
||||
"version": "1"
|
||||
@@ -13,7 +13,7 @@
|
||||
"skill_digests": [
|
||||
{
|
||||
"skill_id": "reverse-engineer-anything",
|
||||
"sha256": "deb344fea1b58757709540664e8ab1d3f941f36161a0bb597cd32f9cce53d0ee"
|
||||
"sha256": "088de4627ea17da86dfffe32bd937df8601822deee124e36795112d380c14784"
|
||||
}
|
||||
],
|
||||
"claims": [
|
||||
|
||||
@@ -46,6 +46,7 @@
|
||||
"bridge/ghidra/ReaGhidraBridge.java",
|
||||
"bridge/ghidra/ReaGhidraExtensions.java",
|
||||
"bridge/ghidra/ReaGhidraPrepareCom.java",
|
||||
"bridge/android/ReaJadxBridge.java",
|
||||
"scripts/rea.mjs",
|
||||
"scripts/electron-active-hook.cjs",
|
||||
"scripts/electron-active-hook-boundaries.cjs",
|
||||
|
||||
@@ -11,6 +11,7 @@ import { hashAndroidFile } from "../../../dist/android/AndroidTargetSnapshot.js"
|
||||
import { JADX_RELEASE } from "../../../dist/android/JadxRelease.js";
|
||||
import fixture from "../../fixtures/android/apidemos.json" with { type: "json" };
|
||||
import { verifyAndroidCliCancellation } from "./cli-cancellation.mjs";
|
||||
import { verifyAndroidMetadata } from "./metadata.mjs";
|
||||
|
||||
const repository = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
|
||||
const apk = process.env.REA_ANDROID_TEST_APK;
|
||||
@@ -41,6 +42,14 @@ const entrypoint =
|
||||
process.env.REA_ANDROID_ENTRYPOINT ?? resolve(repository, "scripts/rea.mjs");
|
||||
const environment = { ...process.env, REA_JADX_MCP_JAR: resolve(jar) };
|
||||
const path = resolve(apk);
|
||||
await verifyAndroidMetadata({
|
||||
java,
|
||||
jar: resolve(jar),
|
||||
apk: path,
|
||||
repository,
|
||||
execute,
|
||||
bridge: resolve(dirname(entrypoint), "../bridge/android/ReaJadxBridge.java"),
|
||||
});
|
||||
const tasks = [
|
||||
{
|
||||
name: "inspect_android_package",
|
||||
@@ -212,6 +221,8 @@ const report = {
|
||||
original_apk_unchanged: true,
|
||||
apk_executed: false,
|
||||
cli_sigterm_cleanup: true,
|
||||
metadata_without_code_generation: true,
|
||||
stable_overload_selection: true,
|
||||
};
|
||||
if (process.env.REA_ANDROID_REPORT !== undefined)
|
||||
await writeFile(
|
||||
|
||||
@@ -47,7 +47,7 @@ export const verifyAndroidCliCancellation = async ({
|
||||
entry !== null &&
|
||||
Number(entry[2]) === child.pid &&
|
||||
entry[4].includes("engine.jar") &&
|
||||
entry[4].includes("-Xmx512m")
|
||||
entry[4].includes("ReaJadxBridge.java")
|
||||
) {
|
||||
group = Number(entry[3]);
|
||||
const runId = await readProcessRunId(Number(entry[1]));
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { delimiter, join, resolve } from "node:path";
|
||||
|
||||
/** Prove cold metadata stays unmaterialized and overload identities survive code generation. */
|
||||
export const verifyAndroidMetadata = async ({
|
||||
java,
|
||||
jar,
|
||||
apk,
|
||||
bridge,
|
||||
repository,
|
||||
execute,
|
||||
}) => {
|
||||
const javac =
|
||||
process.env.JAVA_HOME === undefined
|
||||
? "javac"
|
||||
: resolve(process.env.JAVA_HOME, "bin/javac");
|
||||
try {
|
||||
await execute(javac, ["-version"], { timeout: 10_000 });
|
||||
} catch (cause) {
|
||||
throw new Error(
|
||||
"verify:android metadata requires the full selected JDK, including javac",
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
const classes = await mkdtemp(join(tmpdir(), "rea-android-metadata-"));
|
||||
try {
|
||||
await execute(
|
||||
javac,
|
||||
[
|
||||
"-classpath",
|
||||
jar,
|
||||
"-d",
|
||||
classes,
|
||||
bridge,
|
||||
resolve(
|
||||
repository,
|
||||
"tests/conformance/android/ReaJadxMetadataRegression.java",
|
||||
),
|
||||
],
|
||||
{ timeout: 30_000 },
|
||||
);
|
||||
const result = await execute(
|
||||
java,
|
||||
[
|
||||
"-classpath",
|
||||
`${classes}${delimiter}${jar}`,
|
||||
"ReaJadxMetadataRegression",
|
||||
apk,
|
||||
],
|
||||
{ timeout: 120_000, maxBuffer: 8 * 1024 * 1024 },
|
||||
);
|
||||
assert.match(
|
||||
result.stdout,
|
||||
/METADATA_REGRESSION_PASS classes=\d+ overloads=3/u,
|
||||
);
|
||||
console.log(
|
||||
"PASS real cold metadata, full generic types and stable overloaded method selection",
|
||||
);
|
||||
} finally {
|
||||
await rm(classes, { recursive: true, force: true });
|
||||
}
|
||||
};
|
||||
@@ -4,7 +4,7 @@ description: Reverse engineer native, managed, Electron/JavaScript, packaged, fi
|
||||
metadata:
|
||||
version: "26"
|
||||
tool_count: 131
|
||||
catalog_digest: "2ea72f46db5355f3427fd7b2d7f733bacec0d7c334f2e60fe2da78e8323b92ba"
|
||||
catalog_digest: "95ad932755e4fbcaed940d2e4f968563c63b77d9dcfbc5058c91dff3f844829e"
|
||||
---
|
||||
|
||||
# REA
|
||||
|
||||
@@ -2,7 +2,10 @@ import { constants, createReadStream } from "node:fs";
|
||||
import { chmod, copyFile } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import type { AndroidOperation } from "../domain/android/androidAnalysis.js";
|
||||
|
||||
/** Stream a local file digest without retaining the APK or JAR in memory. */
|
||||
@@ -37,10 +40,18 @@ export const snapshotAndroidTarget = async (
|
||||
/** Fingerprint the actual immutable engine bytes executed for this observation. */
|
||||
export const snapshotAndroidEngine = async (
|
||||
source: string,
|
||||
sha256: string,
|
||||
root: string,
|
||||
operation: AndroidOperation,
|
||||
): Promise<{ path: string; sha256: string }> => {
|
||||
const path = join(root, "engine.jar");
|
||||
await copyFile(source, path, constants.COPYFILE_EXCL);
|
||||
await chmod(path, 0o400);
|
||||
return { path, sha256: await hashAndroidFile(path) };
|
||||
if ((await hashAndroidFile(path)) !== sha256)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"jadx",
|
||||
operation,
|
||||
"REA_JADX_MCP_JAR bytes changed during admission; retry with a stable engine file.",
|
||||
);
|
||||
return { path, sha256 };
|
||||
};
|
||||
|
||||
@@ -137,19 +137,20 @@ const searchClasses = async (
|
||||
engine: Engine,
|
||||
): Promise<JsonValue> => {
|
||||
const classes: string[] = [];
|
||||
const pageSize = 4096;
|
||||
let total: number | undefined;
|
||||
do {
|
||||
const page = jadxClassPageSchema.parse(
|
||||
await tools.json("list_classes", {
|
||||
offset: classes.length,
|
||||
limit: 200,
|
||||
limit: pageSize,
|
||||
}),
|
||||
);
|
||||
if (
|
||||
(total !== undefined && total !== page.total) ||
|
||||
page.offset !== classes.length ||
|
||||
page.limit !== 200 ||
|
||||
page.items.length > 200
|
||||
page.limit !== pageSize ||
|
||||
page.items.length > pageSize
|
||||
)
|
||||
throw new AnalysisOutputError(
|
||||
request.operation,
|
||||
@@ -307,7 +308,7 @@ const traceReferences = async (
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"jadx",
|
||||
request.operation,
|
||||
`JADX ${JADX_RELEASE.version} references select the first same-name method; ${summary.full_name}.${methodName} has ${candidates.length} overloads. No unambiguous reference result is available.`,
|
||||
`References require a unique method name; ${summary.full_name}.${methodName} has ${candidates.length} overloads. No unambiguous reference result is available.`,
|
||||
);
|
||||
const expectedTarget =
|
||||
methodName === undefined
|
||||
|
||||
@@ -9,6 +9,7 @@ import { JADX_JAR_CONFIGURATION_REMEDIATION } from "./JadxRelease.js";
|
||||
export interface JadxConfiguration {
|
||||
readonly jar: string;
|
||||
readonly java: string;
|
||||
readonly jvmArguments: readonly string[];
|
||||
}
|
||||
|
||||
/** Admit explicit local tooling without installing or changing host configuration. */
|
||||
@@ -20,7 +21,7 @@ export const resolveJadxConfiguration = async (
|
||||
new AnalysisCapabilityUnavailableError("jadx", operation, reason);
|
||||
if (process.platform !== "linux" && process.platform !== "darwin")
|
||||
throw unavailable(
|
||||
`Android JADX subprocess ownership is unsupported on ${process.platform}; use Linux or macOS. Only Linux has real-provider verification.`,
|
||||
`Android JADX subprocess ownership is unsupported on ${process.platform}; use Linux or macOS. The metadata bridge has real-provider verification on macOS arm64.`,
|
||||
);
|
||||
const jar = environment.REA_JADX_MCP_JAR;
|
||||
if (environment.JAVA_HOME !== undefined && !isAbsolute(environment.JAVA_HOME))
|
||||
@@ -55,5 +56,25 @@ export const resolveJadxConfiguration = async (
|
||||
);
|
||||
}
|
||||
}
|
||||
return { jar: await realpath(jar), java };
|
||||
const jvmArguments: string[] = [];
|
||||
for (const [name, prefix, suffix] of [
|
||||
["REA_JADX_HEAP_MIB", "-Xmx", "m"],
|
||||
["REA_JADX_ACTIVE_PROCESSOR_COUNT", "-XX:ActiveProcessorCount=", ""],
|
||||
] as const) {
|
||||
const value = environment[name];
|
||||
if (value === undefined) continue;
|
||||
if (!/^[1-9]\d*$/u.test(value) || !Number.isSafeInteger(Number(value)))
|
||||
throw unavailable(
|
||||
`${name} must be a positive safe integer; received ${value}.`,
|
||||
);
|
||||
if (
|
||||
name === "REA_JADX_ACTIVE_PROCESSOR_COUNT" &&
|
||||
Number(value) > 2_147_483_647
|
||||
)
|
||||
throw unavailable(
|
||||
`${name} exceeds the JVM's signed 32-bit processor-count range.`,
|
||||
);
|
||||
jvmArguments.push(`${prefix}${value}${suffix}`);
|
||||
}
|
||||
return { jar: await realpath(jar), java, jvmArguments };
|
||||
};
|
||||
|
||||
@@ -17,7 +17,7 @@ import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
|
||||
const MAX_FRAME_BYTES = 8 * 1024 * 1024;
|
||||
const MAX_SESSION_BYTES = 32 * 1024 * 1024;
|
||||
const MAX_OPERATION_BYTES = 32 * 1024 * 1024;
|
||||
|
||||
/** Injectable process acquisition seam; the production launcher owns a POSIX group. */
|
||||
export type JadxLauncher = (
|
||||
@@ -109,6 +109,12 @@ export class JadxMcpTransport implements Transport {
|
||||
return this.#failure;
|
||||
}
|
||||
|
||||
/** Scope both the byte budget and diagnostic retention to the next serialized request. */
|
||||
beginOperation(): void {
|
||||
this.#bytes = 0;
|
||||
this.#supervisor?.resetOutput();
|
||||
}
|
||||
|
||||
async #stop(): Promise<void> {
|
||||
this.#closed = true;
|
||||
// A cancellation may race acquisition. Join it before inspecting ownership.
|
||||
@@ -136,10 +142,10 @@ export class JadxMcpTransport implements Transport {
|
||||
};
|
||||
readonly #countStderr = (chunk: Buffer | string): void => {
|
||||
this.#bytes += Buffer.byteLength(chunk);
|
||||
if (this.#bytes > MAX_SESSION_BYTES)
|
||||
if (this.#bytes > MAX_OPERATION_BYTES)
|
||||
this.#fail(
|
||||
new Error(
|
||||
`JADX session output exceeds ${MAX_SESSION_BYTES} bytes; no complete result is available`,
|
||||
`JADX operation output exceeds ${MAX_OPERATION_BYTES} bytes; no complete result is available`,
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -147,10 +153,10 @@ export class JadxMcpTransport implements Transport {
|
||||
if (this.#closed) return;
|
||||
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
this.#bytes += bytes.length;
|
||||
if (this.#bytes > MAX_SESSION_BYTES) {
|
||||
if (this.#bytes > MAX_OPERATION_BYTES) {
|
||||
this.#fail(
|
||||
new Error(
|
||||
`JADX session output exceeds ${MAX_SESSION_BYTES} bytes; no complete result is available`,
|
||||
`JADX operation output exceeds ${MAX_OPERATION_BYTES} bytes; no complete result is available`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
|
||||
@@ -4,6 +4,14 @@ import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import type { AndroidOperation } from "../domain/android/androidAnalysis.js";
|
||||
|
||||
const count = z.number().int().nonnegative();
|
||||
/** Values observed inside the exact JVM producing the analysis. */
|
||||
export const jadxRuntimeSchema = z.object({
|
||||
engine_reported_version: z.string().min(1),
|
||||
max_heap_bytes: z.number().int().positive().safe(),
|
||||
available_processors: z.number().int().positive(),
|
||||
java_version: z.string().min(1),
|
||||
metadata_scope: z.literal("parsed_members"),
|
||||
});
|
||||
export const jadxLoadSchema = z.object({
|
||||
state: z.literal("LOADED"),
|
||||
apk_path: z.string(),
|
||||
|
||||
+157
-41
@@ -1,4 +1,7 @@
|
||||
import { z } from "zod";
|
||||
import { chmod, copyFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { AndroidAnalysisPort } from "../application/android/AndroidAnalysisPort.js";
|
||||
import type { ExecutionOptions } from "../application/AnalysisProvider.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
@@ -6,24 +9,29 @@ import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisOutputError,
|
||||
AnalysisInputError,
|
||||
AnalysisTimeoutError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import type { AndroidRequest } from "../domain/android/androidAnalysis.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
import {
|
||||
snapshotAndroidEngine,
|
||||
hashAndroidFile,
|
||||
snapshotAndroidTarget,
|
||||
} from "./AndroidTargetSnapshot.js";
|
||||
import { resolveJadxConfiguration } from "./JadxConfiguration.js";
|
||||
import type { JadxLauncher } from "./JadxMcpTransport.js";
|
||||
import { JADX_HEAP_XMX_ARGUMENT } from "./JadxRelease.js";
|
||||
|
||||
import { JadxSession } from "./JadxSession.js";
|
||||
|
||||
const OPERATION_TIMEOUT_MS = 120_000;
|
||||
const BRIDGE_SOURCE = fileURLToPath(
|
||||
new URL("../../bridge/android/ReaJadxBridge.java", import.meta.url),
|
||||
);
|
||||
type Outcome = Awaited<ReturnType<AndroidAnalysisPort["execute"]>>;
|
||||
|
||||
const waitForTurn = (
|
||||
@@ -74,11 +82,11 @@ const executionError = (context: {
|
||||
});
|
||||
};
|
||||
|
||||
const cleanup = async (
|
||||
const cleanup = async <Value>(
|
||||
session: JadxSession | undefined,
|
||||
root: PrivateRuntimeRoot | undefined,
|
||||
previous: Outcome,
|
||||
): Promise<Outcome> => {
|
||||
previous: Result<Value, AnalysisError>,
|
||||
): Promise<Result<Value, AnalysisError>> => {
|
||||
const diagnostics = {
|
||||
previous_error: previous.ok
|
||||
? null
|
||||
@@ -125,10 +133,23 @@ const cleanup = async (
|
||||
return previous;
|
||||
};
|
||||
|
||||
/** One queued engine per REA instance, with a fresh owned workspace for every request. */
|
||||
interface RetainedSession {
|
||||
readonly key: string;
|
||||
readonly root: PrivateRuntimeRoot;
|
||||
readonly session: JadxSession;
|
||||
readonly snapshot: string;
|
||||
readonly jarHash: string;
|
||||
readonly bridgeHash: string;
|
||||
}
|
||||
|
||||
/** One serialized, immutable APK session per REA instance, retired on idle or shutdown. */
|
||||
export class JadxProvider implements AndroidAnalysisPort {
|
||||
#tail: Promise<void> = Promise.resolve();
|
||||
#cleanupFailure: AnalysisError | undefined;
|
||||
#retained: RetainedSession | undefined;
|
||||
#idle: NodeJS.Timeout | undefined;
|
||||
readonly #shutdown = new AbortController();
|
||||
#closePromise: Promise<void> | undefined;
|
||||
constructor(
|
||||
readonly environment: Readonly<
|
||||
Record<string, string | undefined>
|
||||
@@ -142,30 +163,69 @@ export class JadxProvider implements AndroidAnalysisPort {
|
||||
request: AndroidRequest,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Outcome> {
|
||||
if (this.#shutdown.signal.aborted)
|
||||
return err(new AnalysisCancelledError(request.operation));
|
||||
const signal =
|
||||
options?.signal === undefined
|
||||
? this.#shutdown.signal
|
||||
: AbortSignal.any([options.signal, this.#shutdown.signal]);
|
||||
const predecessor = this.#tail;
|
||||
let release: () => void = () => {};
|
||||
this.#tail = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
try {
|
||||
await waitForTurn(predecessor, request, options?.signal);
|
||||
await waitForTurn(predecessor, request, signal);
|
||||
} catch {
|
||||
void predecessor.then(release);
|
||||
return err(new AnalysisCancelledError(request.operation));
|
||||
}
|
||||
try {
|
||||
if (options?.signal?.aborted === true)
|
||||
if (signal.aborted)
|
||||
return err(new AnalysisCancelledError(request.operation));
|
||||
if (this.#cleanupFailure !== undefined) return err(this.#cleanupFailure);
|
||||
const outcome = await this.#execute(target, request, options);
|
||||
clearTimeout(this.#idle);
|
||||
const outcome = await this.#execute(target, request, { signal });
|
||||
if (!outcome.ok && outcome.error.cleanupIncomplete)
|
||||
this.#cleanupFailure = outcome.error;
|
||||
if (outcome.ok) this.#scheduleIdle();
|
||||
return outcome;
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
/** Cancel queued/active operations and join the owned engine and workspace cleanup. */
|
||||
close(): Promise<void> {
|
||||
this.#shutdown.abort();
|
||||
clearTimeout(this.#idle);
|
||||
this.#closePromise ??= this.#tail.then(() => this.#retire());
|
||||
return this.#closePromise;
|
||||
}
|
||||
|
||||
async #retire(): Promise<void> {
|
||||
if (this.#cleanupFailure !== undefined) throw this.#cleanupFailure;
|
||||
const retained = this.#retained;
|
||||
this.#retained = undefined;
|
||||
const result = await cleanup(
|
||||
retained?.session,
|
||||
retained?.root,
|
||||
ok(undefined),
|
||||
);
|
||||
if (!result.ok) {
|
||||
this.#cleanupFailure = result.error;
|
||||
throw result.error;
|
||||
}
|
||||
}
|
||||
|
||||
#scheduleIdle(): void {
|
||||
this.#idle = setTimeout(() => {
|
||||
const retirement = this.#tail.then(() => this.#retire());
|
||||
this.#tail = retirement.catch(() => undefined);
|
||||
}, 60_000);
|
||||
this.#idle.unref();
|
||||
}
|
||||
|
||||
async #execute(
|
||||
target: BinaryTarget,
|
||||
request: AndroidRequest,
|
||||
@@ -191,47 +251,99 @@ export class JadxProvider implements AndroidAnalysisPort {
|
||||
request.operation,
|
||||
);
|
||||
signal.throwIfAborted();
|
||||
root = await PrivateRuntimeRoot.create({ prefix: "rea-android-" });
|
||||
const engine = await snapshotAndroidEngine(configuration.jar, root.path);
|
||||
const snapshot = await snapshotAndroidTarget(
|
||||
target.path,
|
||||
target.sha256,
|
||||
root.path,
|
||||
request.operation,
|
||||
);
|
||||
signal.throwIfAborted();
|
||||
session = new JadxSession(
|
||||
{
|
||||
command: configuration.java,
|
||||
arguments: [
|
||||
JADX_HEAP_XMX_ARGUMENT,
|
||||
"-XX:ActiveProcessorCount=1",
|
||||
"-jar",
|
||||
engine.path,
|
||||
"--threads",
|
||||
"1",
|
||||
"--max-source-bytes",
|
||||
"1048576",
|
||||
"--decompile-timeout-ms",
|
||||
"90000",
|
||||
],
|
||||
cwd: root.path,
|
||||
hostEnvironment: this.environment,
|
||||
env: {
|
||||
_JAVA_OPTIONS: `${JADX_HEAP_XMX_ARGUMENT} -XX:ActiveProcessorCount=1`,
|
||||
const jarHash = await hashAndroidFile(configuration.jar);
|
||||
const bridgeHash = await hashAndroidFile(BRIDGE_SOURCE);
|
||||
if ((await hashAndroidFile(target.path)) !== target.sha256)
|
||||
throw new AnalysisInputError(request.operation, undefined, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"APK bytes changed after admission; retry against a stable file.",
|
||||
},
|
||||
},
|
||||
this.launcher,
|
||||
);
|
||||
]);
|
||||
const key = JSON.stringify({
|
||||
path: target.path,
|
||||
sha256: target.sha256,
|
||||
jar: configuration.jar,
|
||||
jarHash,
|
||||
bridgeHash,
|
||||
java: configuration.java,
|
||||
arguments: configuration.jvmArguments,
|
||||
options: [
|
||||
this.environment.JAVA_TOOL_OPTIONS,
|
||||
this.environment._JAVA_OPTIONS,
|
||||
this.environment.JDK_JAVA_OPTIONS,
|
||||
this.environment.PATH,
|
||||
this.environment.JAVA_HOME,
|
||||
],
|
||||
});
|
||||
if (this.#retained !== undefined && this.#retained.key !== key)
|
||||
await this.#retire();
|
||||
let retained = this.#retained;
|
||||
if (retained === undefined) {
|
||||
root = await PrivateRuntimeRoot.create({ prefix: "rea-android-" });
|
||||
const engine = await snapshotAndroidEngine(
|
||||
configuration.jar,
|
||||
jarHash,
|
||||
root.path,
|
||||
request.operation,
|
||||
);
|
||||
const snapshot = await snapshotAndroidTarget(
|
||||
target.path,
|
||||
target.sha256,
|
||||
root.path,
|
||||
request.operation,
|
||||
);
|
||||
const bridge = join(root.path, "ReaJadxBridge.java");
|
||||
await copyFile(BRIDGE_SOURCE, bridge);
|
||||
await chmod(bridge, 0o400);
|
||||
if ((await hashAndroidFile(bridge)) !== bridgeHash)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"jadx",
|
||||
request.operation,
|
||||
"REA Android bridge bytes changed during admission; retry with a stable installation.",
|
||||
);
|
||||
signal.throwIfAborted();
|
||||
session = new JadxSession(
|
||||
{
|
||||
command: configuration.java,
|
||||
arguments: [
|
||||
...configuration.jvmArguments,
|
||||
"--class-path",
|
||||
engine.path,
|
||||
bridge,
|
||||
],
|
||||
cwd: root.path,
|
||||
hostEnvironment: this.environment,
|
||||
},
|
||||
this.launcher,
|
||||
);
|
||||
retained = {
|
||||
key,
|
||||
root,
|
||||
session,
|
||||
snapshot,
|
||||
jarHash: engine.sha256,
|
||||
bridgeHash,
|
||||
};
|
||||
}
|
||||
root = retained.root;
|
||||
session = retained.session;
|
||||
const { snapshot } = retained;
|
||||
outcome = ok(
|
||||
await session.execute({
|
||||
request,
|
||||
target,
|
||||
snapshot,
|
||||
jarHash: engine.sha256,
|
||||
jarHash: retained.jarHash,
|
||||
bridgeHash: retained.bridgeHash,
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
signal.throwIfAborted();
|
||||
this.#retained = retained;
|
||||
return outcome;
|
||||
} catch (cause) {
|
||||
outcome = err(
|
||||
executionError({
|
||||
@@ -243,6 +355,10 @@ export class JadxProvider implements AndroidAnalysisPort {
|
||||
}),
|
||||
);
|
||||
}
|
||||
// An existing session also needs retirement when admission fails before selection.
|
||||
root ??= this.#retained?.root;
|
||||
session ??= this.#retained?.session;
|
||||
this.#retained = undefined;
|
||||
return cleanup(session, root, outcome);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,11 +6,11 @@ export const JADX_RELEASE = Object.freeze({
|
||||
url: "https://github.com/1013503897/jadx-headless-mcp/releases/download/v0.7.1/jadx-headless-mcp-0.7.1-all.jar",
|
||||
});
|
||||
|
||||
/** JVM heap ceiling applied to every owned JADX worker process. */
|
||||
export const JADX_HEAP_LIMIT_MIB = 512;
|
||||
|
||||
/** JVM `-Xmx` argument matching {@link JADX_HEAP_LIMIT_MIB}. */
|
||||
export const JADX_HEAP_XMX_ARGUMENT = `-Xmx${JADX_HEAP_LIMIT_MIB}m`;
|
||||
/** Identity of REA's metadata bridge, distinct from the producing engine. */
|
||||
export const JADX_BRIDGE_IDENTITY = Object.freeze({
|
||||
name: "rea-jadx-bridge",
|
||||
version: "1",
|
||||
});
|
||||
|
||||
/** Remediation when `REA_JADX_MCP_JAR` is missing or not an absolute path. */
|
||||
export const JADX_JAR_CONFIGURATION_REMEDIATION = `Set REA_JADX_MCP_JAR to the absolute path of a caller-supplied jadx-headless-mcp ${JADX_RELEASE.version} JAR. REA does not download or install it.`;
|
||||
@@ -26,5 +26,6 @@ export const JADX_PROVIDER_IDENTITY = Object.freeze({
|
||||
export const JADX_LIMITATIONS = [
|
||||
"Static decompiler observations do not establish runtime behavior; the APK is never executed.",
|
||||
"Method signatures use provider display types; exact DEX descriptors and instruction offsets are unavailable. Overload indices are local to this engine and artifact.",
|
||||
"Class inventories use parsed metadata before code generation, including synthetic members that may be omitted from decompiled source. Source positions remain unknown.",
|
||||
"Manifest summary fields are extracted by the upstream engine; decoded XML is retained for verification. APK signatures, split APKs, native libraries and Android runtime capture are not verified by this provider.",
|
||||
] as const;
|
||||
|
||||
+42
-17
@@ -16,11 +16,12 @@ import { analyzeJadxRequest, type JadxToolPort } from "./JadxAnalysis.js";
|
||||
import { JadxMcpTransport, type JadxLauncher } from "./JadxMcpTransport.js";
|
||||
import {
|
||||
jadxLoadSchema,
|
||||
jadxRuntimeSchema,
|
||||
parseJadxEnvelope,
|
||||
parseJadxJson,
|
||||
} from "./JadxProtocol.js";
|
||||
import {
|
||||
JADX_HEAP_LIMIT_MIB,
|
||||
JADX_BRIDGE_IDENTITY,
|
||||
JADX_RELEASE,
|
||||
JADX_PROVIDER_IDENTITY,
|
||||
JADX_LIMITATIONS,
|
||||
@@ -30,7 +31,7 @@ import {
|
||||
export class JadxSession {
|
||||
readonly transport: JadxMcpTransport;
|
||||
readonly #client = new Client({ name: "rea-android-adapter", version: "1" });
|
||||
readonly #raw: JsonValue[] = [];
|
||||
#loaded: ReturnType<typeof jadxLoadSchema.parse> | undefined;
|
||||
|
||||
constructor(
|
||||
options: Omit<OwnedProviderProcessSpawnOptions, "runId" | "stdin">,
|
||||
@@ -45,6 +46,7 @@ export class JadxSession {
|
||||
readonly target: BinaryTarget;
|
||||
readonly snapshot: string;
|
||||
readonly jarHash: string;
|
||||
readonly bridgeHash: string;
|
||||
readonly signal: AbortSignal;
|
||||
}): Promise<AnalysisExecution> {
|
||||
const { request, target, snapshot, jarHash, signal } = context;
|
||||
@@ -54,42 +56,64 @@ export class JadxSession {
|
||||
signal.addEventListener("abort", abort, { once: true });
|
||||
try {
|
||||
signal.throwIfAborted();
|
||||
await this.#client.connect(this.transport, { timeout: 30_000 });
|
||||
this.transport.beginOperation();
|
||||
const raw: JsonValue[] = [];
|
||||
if (this.#loaded === undefined)
|
||||
await this.#client.connect(this.transport, { timeout: 30_000 });
|
||||
const server = this.#client.getServerVersion();
|
||||
if (
|
||||
server?.name !== "jadx-headless-mcp" ||
|
||||
server.version !== JADX_RELEASE.version
|
||||
server?.name !== JADX_BRIDGE_IDENTITY.name ||
|
||||
server.version !== JADX_BRIDGE_IDENTITY.version
|
||||
)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"jadx",
|
||||
request.operation,
|
||||
`Expected jadx-headless-mcp ${JADX_RELEASE.version}; server reported ${server?.name ?? "unknown"} ${server?.version ?? "unknown"}.`,
|
||||
`Expected ${JADX_BRIDGE_IDENTITY.name} ${JADX_BRIDGE_IDENTITY.version}; server reported ${server?.name ?? "unknown"} ${server?.version ?? "unknown"}.`,
|
||||
);
|
||||
const tools = this.#tools(request, target, signal);
|
||||
const loaded = jadxLoadSchema.parse(
|
||||
await tools.json("load_apk", {
|
||||
path: snapshot,
|
||||
threads: 1,
|
||||
resources: "full",
|
||||
}),
|
||||
const tools = this.#tools(request, target, signal, raw);
|
||||
const runtime = jadxRuntimeSchema.parse(
|
||||
await tools.json("rea_jvm_status", {}),
|
||||
);
|
||||
if (runtime.engine_reported_version !== JADX_RELEASE.version)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"jadx",
|
||||
request.operation,
|
||||
`Expected engine ${JADX_RELEASE.version}; JAR reported ${runtime.engine_reported_version}.`,
|
||||
);
|
||||
const loaded =
|
||||
this.#loaded ??
|
||||
jadxLoadSchema.parse(
|
||||
await tools.json("load_apk", {
|
||||
path: snapshot,
|
||||
threads: 1,
|
||||
resources: "full",
|
||||
}),
|
||||
);
|
||||
if (loaded.apk_path !== snapshot)
|
||||
throw new AnalysisOutputError(
|
||||
request.operation,
|
||||
"JADX loaded a different APK path than the admitted snapshot",
|
||||
);
|
||||
this.#loaded = loaded;
|
||||
const engine = {
|
||||
name: "jadx-headless-mcp",
|
||||
version: JADX_RELEASE.version,
|
||||
version: runtime.engine_reported_version,
|
||||
artifact_sha256: jarHash,
|
||||
source_revision:
|
||||
jarHash === JADX_RELEASE.sha256 ? JADX_RELEASE.revision : null,
|
||||
worker_count: 1,
|
||||
heap_limit_mib: JADX_HEAP_LIMIT_MIB,
|
||||
heap_limit_mib:
|
||||
Math.floor(runtime.max_heap_bytes / (1024 * 1024)) || null,
|
||||
} as const;
|
||||
const result = await analyzeJadxRequest(tools, request, loaded, engine);
|
||||
return createAnalysisExecution(result, JADX_PROVIDER_IDENTITY, {
|
||||
rawResult: { server, jar_sha256: jarHash, calls: this.#raw },
|
||||
rawResult: {
|
||||
server,
|
||||
bridge_sha256: context.bridgeHash,
|
||||
jar_sha256: jarHash,
|
||||
loaded,
|
||||
calls: raw,
|
||||
},
|
||||
subject: target,
|
||||
limitations: JADX_LIMITATIONS,
|
||||
locations:
|
||||
@@ -115,6 +139,7 @@ export class JadxSession {
|
||||
request: AndroidRequest,
|
||||
target: BinaryTarget,
|
||||
signal: AbortSignal,
|
||||
raw: JsonValue[],
|
||||
): JadxToolPort {
|
||||
const call = async (
|
||||
name: string,
|
||||
@@ -126,7 +151,7 @@ export class JadxSession {
|
||||
{ timeout: 120_000, signal },
|
||||
);
|
||||
const envelope = parseJadxEnvelope(response, request.operation);
|
||||
this.#raw.push({
|
||||
raw.push({
|
||||
operation: name,
|
||||
input,
|
||||
response: jsonValueSchema.parse(response),
|
||||
|
||||
@@ -9,6 +9,8 @@ import type { Result } from "../../domain/result.js";
|
||||
|
||||
/** Static Android inspection boundary; implementation details belong to the provider. */
|
||||
export interface AndroidAnalysisPort {
|
||||
/** Cancel active work and join cleanup of any retained provider resources. */
|
||||
close(): Promise<void>;
|
||||
execute(
|
||||
target: BinaryTarget,
|
||||
request: AndroidRequest,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "incur";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { AndroidAnalysisService } from "../application/android/AndroidAnalysisService.js";
|
||||
import { createAndroidAnalysisProvider } from "../composition/android.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
@@ -15,13 +16,19 @@ export const registerAndroidCommands = (
|
||||
logger: Logger,
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
): void => {
|
||||
const service = new AndroidAnalysisService(
|
||||
createAndroidAnalysisProvider(environment),
|
||||
);
|
||||
const provider = createAndroidAnalysisProvider(environment);
|
||||
const service = new AndroidAnalysisService(provider);
|
||||
const execute = (name: string, operation: AndroidOperation, input: unknown) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, name, async () => {
|
||||
const result = await service.execute(operation, input, { signal });
|
||||
try {
|
||||
await provider.close();
|
||||
} catch (cause) {
|
||||
if (cause instanceof AnalysisError)
|
||||
return projectAnalysisError(cause);
|
||||
throw cause;
|
||||
}
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -12,7 +12,7 @@ export const ANDROID_TOOL_CONTRACTS = [
|
||||
name: "inspect_android_package",
|
||||
...toolContractMetadata("inspect_android_package"),
|
||||
description:
|
||||
"Inspect a local APK's package, SDK and permission declarations, decoded manifest and class/resource counts. Does not execute the APK or verify signatures. Requires a caller-supplied JADX MCP JAR and Java; uses one worker in an isolated temporary workspace.",
|
||||
"Inspect a local APK's package, SDK and permission declarations, decoded manifest and class/resource counts. Does not execute the APK or verify signatures. Requires a caller-supplied JADX MCP JAR and JDK; uses one worker in an isolated temporary workspace.",
|
||||
kind: "android-provider",
|
||||
inputSchema: androidInputSchemas.inspect_android_package,
|
||||
outputSchema: evidenceResultOf(
|
||||
@@ -41,7 +41,7 @@ export const ANDROID_TOOL_CONTRACTS = [
|
||||
name: "inspect_android_class",
|
||||
...toolContractMetadata("inspect_android_class"),
|
||||
description:
|
||||
"Inspect one exact Android class's methods, fields and inner classes. Returns display signatures and explicit unknown DEX descriptors without materializing the whole application source.",
|
||||
"Inspect one exact Android class's parsed methods, fields and inner classes, including synthetic members. Returns display signatures and explicit unknown DEX descriptors without generating source. Overload indices remain consistent within the artifact and engine session.",
|
||||
kind: "android-provider",
|
||||
inputSchema: androidInputSchemas.inspect_android_class,
|
||||
outputSchema: evidenceResultOf(androidResultSchemas.inspect_android_class),
|
||||
|
||||
@@ -93,5 +93,7 @@ const addAdjacency = (
|
||||
nodeId: string,
|
||||
entry: AdjacencyEntry,
|
||||
): void => {
|
||||
adjacency.set(nodeId, [...(adjacency.get(nodeId) ?? []), entry]);
|
||||
const entries = adjacency.get(nodeId);
|
||||
if (entries === undefined) adjacency.set(nodeId, [entry]);
|
||||
else entries.push(entry);
|
||||
};
|
||||
|
||||
@@ -204,16 +204,20 @@ export const traceNativeInvestigationGraph = (
|
||||
let reachedDepth = 0;
|
||||
let truncated = false;
|
||||
let reason: string | null = null;
|
||||
const adjacency = new Map<string, NativeInvestigationEdge[]>();
|
||||
for (const edge of graph.edges) {
|
||||
const nodeId = direction === "forward" ? edge.from : edge.to;
|
||||
if (nodeId === null) continue;
|
||||
const entries = adjacency.get(nodeId);
|
||||
if (entries === undefined) adjacency.set(nodeId, [edge]);
|
||||
else entries.push(edge);
|
||||
}
|
||||
|
||||
while (queue.length > 0) {
|
||||
const current = queue.shift();
|
||||
if (current === undefined) break;
|
||||
reachedDepth = Math.max(reachedDepth, current.depth);
|
||||
const adjacent = graph.edges.filter((edge) =>
|
||||
direction === "forward"
|
||||
? edge.from === current.id
|
||||
: edge.to === current.id,
|
||||
);
|
||||
const adjacent = adjacency.get(current.id) ?? [];
|
||||
|
||||
for (const edge of adjacent) {
|
||||
if (selectedEdges.size + unresolved.size >= limits.max_edges) {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -81,6 +81,7 @@ export const run = async (
|
||||
});
|
||||
createShutdown({
|
||||
handle: transport.handle,
|
||||
closeAndroid: transport.closeAndroid,
|
||||
session,
|
||||
unregisterReload,
|
||||
dependencies,
|
||||
|
||||
@@ -7,6 +7,7 @@ import { MCP_SHUTDOWN_FAILED } from "./messages.js";
|
||||
|
||||
export const createShutdown = (input: {
|
||||
readonly handle: StdioServerHandle;
|
||||
readonly closeAndroid?: () => Promise<void>;
|
||||
readonly session: BinarySession;
|
||||
readonly unregisterReload: () => void;
|
||||
readonly dependencies: RuntimeDependencies;
|
||||
@@ -23,8 +24,13 @@ export const createShutdown = (input: {
|
||||
shutdownPromise ??= (async () => {
|
||||
unregisterReload();
|
||||
unregisterShutdown();
|
||||
await handle.close();
|
||||
await session.close({ retainProviderDocuments: true });
|
||||
const results = await Promise.allSettled([
|
||||
handle.close(),
|
||||
input.closeAndroid?.(),
|
||||
session.close({ retainProviderDocuments: true }),
|
||||
]);
|
||||
for (const result of results)
|
||||
if (result.status === "rejected") throw result.reason;
|
||||
})();
|
||||
return shutdownPromise;
|
||||
};
|
||||
|
||||
+21
-5
@@ -1,3 +1,5 @@
|
||||
import { createAndroidAnalysisProvider } from "../composition/android.js";
|
||||
import type { AndroidAnalysisPort } from "../application/android/AndroidAnalysisPort.js";
|
||||
import type { StdioServerHandle } from "@modelcontextprotocol/server/stdio";
|
||||
|
||||
import type { BinarySession } from "../application/binary/BinarySession.js";
|
||||
@@ -27,6 +29,7 @@ export const startMcpTransport = async (
|
||||
| {
|
||||
readonly ok: true;
|
||||
readonly handle: StdioServerHandle;
|
||||
readonly closeAndroid: () => Promise<void>;
|
||||
}
|
||||
| { readonly ok: false }
|
||||
> => {
|
||||
@@ -50,14 +53,27 @@ export const startMcpTransport = async (
|
||||
"Optional MCP adapter could not load; its peers remain available",
|
||||
);
|
||||
}
|
||||
const androidProviders: AndroidAnalysisPort[] = [];
|
||||
const closeAndroid = async (): Promise<void> => {
|
||||
const results = await Promise.allSettled(
|
||||
androidProviders.map((provider) => provider.close()),
|
||||
);
|
||||
for (const result of results)
|
||||
if (result.status === "rejected") throw result.reason;
|
||||
};
|
||||
let handle: StdioServerHandle;
|
||||
try {
|
||||
handle = dependencies.serve(
|
||||
() =>
|
||||
(dependencies.createServer ?? createServer)(session, session, {
|
||||
() => {
|
||||
// The SDK can discard a discovery probe and construct a replacement server.
|
||||
const android = createAndroidAnalysisProvider(dependencies.env);
|
||||
androidProviders.push(android);
|
||||
return (dependencies.createServer ?? createServer)(session, session, {
|
||||
logger: serverContext.logger,
|
||||
...optionalProviders,
|
||||
}),
|
||||
androidAnalysis: android,
|
||||
});
|
||||
},
|
||||
{
|
||||
onerror: () => {
|
||||
serverLogger.error(MCP_CONNECTION_LOST);
|
||||
@@ -66,7 +82,7 @@ export const startMcpTransport = async (
|
||||
},
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
await session.close();
|
||||
await Promise.allSettled([session.close(), closeAndroid()]);
|
||||
serverLogger.error(
|
||||
{
|
||||
error: cause instanceof Error ? cause.message : String(cause),
|
||||
@@ -76,5 +92,5 @@ export const startMcpTransport = async (
|
||||
dependencies.writeStderr(`${MCP_CONNECTION_START_FAILED}\n`);
|
||||
return { ok: false };
|
||||
}
|
||||
return { ok: true, handle };
|
||||
return { ok: true, handle, closeAndroid };
|
||||
};
|
||||
|
||||
@@ -254,6 +254,12 @@ export class ProviderProcessSupervisor {
|
||||
};
|
||||
}
|
||||
|
||||
/** Begin a new observation on a retained process without retaining earlier output. */
|
||||
resetOutput(): void {
|
||||
this.#stdout.reset();
|
||||
this.#stderr.reset();
|
||||
}
|
||||
|
||||
/** Wait for process exit up to a caller-owned bounded interval. */
|
||||
async waitForExit(timeoutMs: number): Promise<boolean> {
|
||||
return waitForProcessEvent(
|
||||
@@ -403,6 +409,11 @@ class ProcessOutputCapture {
|
||||
return this.#bytes;
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.#chunks.length = 0;
|
||||
this.#bytes = 0;
|
||||
}
|
||||
|
||||
append(chunk: Buffer): void {
|
||||
this.#bytes += chunk.byteLength;
|
||||
this.#chunks.push(Buffer.from(chunk));
|
||||
|
||||
@@ -159,11 +159,26 @@ export const createServer = (
|
||||
recordEvidenceWithUnknown,
|
||||
};
|
||||
registerBinaryAnalysisTools(toolContext);
|
||||
const android = options.androidAnalysis ?? createAndroidAnalysisProvider();
|
||||
const previousOnclose = server.server.onclose;
|
||||
server.server.onclose = () => {
|
||||
previousOnclose?.();
|
||||
void android.close().catch((cause: unknown) => {
|
||||
logger.error(
|
||||
{ error: cause instanceof Error ? cause.message : String(cause) },
|
||||
"Android provider cleanup failed",
|
||||
);
|
||||
});
|
||||
};
|
||||
const closeServer = server.close.bind(server);
|
||||
server.close = async () => {
|
||||
const results = await Promise.allSettled([closeServer(), android.close()]);
|
||||
for (const result of results)
|
||||
if (result.status === "rejected") throw result.reason;
|
||||
};
|
||||
registerAndroidTools(
|
||||
server,
|
||||
new AndroidAnalysisService(
|
||||
options.androidAnalysis ?? createAndroidAnalysisProvider(),
|
||||
),
|
||||
new AndroidAnalysisService(android),
|
||||
toolLogger,
|
||||
recordEvidence,
|
||||
);
|
||||
|
||||
@@ -40,5 +40,43 @@ it("accepts a verified explicit java binary and canonicalizes the JAR", async ()
|
||||
{ REA_JADX_MCP_JAR: jar, JAVA_HOME: javaHome },
|
||||
"inspect_android_package",
|
||||
),
|
||||
).resolves.toEqual({ jar: await realpath(jar), java });
|
||||
).resolves.toEqual({ jar: await realpath(jar), java, jvmArguments: [] });
|
||||
});
|
||||
|
||||
it("configures heap and visible processors independently without forcing either", async () => {
|
||||
const root = await createTestTempDirectory("rea-jadx-config-");
|
||||
const jar = join(root, "engine.jar");
|
||||
await writeFile(jar, "fixture jar");
|
||||
const configuration = await resolveJadxConfiguration(
|
||||
{
|
||||
REA_JADX_MCP_JAR: jar,
|
||||
REA_JADX_HEAP_MIB: "8192",
|
||||
REA_JADX_ACTIVE_PROCESSOR_COUNT: "4",
|
||||
},
|
||||
"inspect_android_package",
|
||||
);
|
||||
expect(configuration.jvmArguments).toEqual([
|
||||
"-Xmx8192m",
|
||||
"-XX:ActiveProcessorCount=4",
|
||||
]);
|
||||
await expect(
|
||||
resolveJadxConfiguration(
|
||||
{ REA_JADX_MCP_JAR: jar, REA_JADX_ACTIVE_PROCESSOR_COUNT: "2147483648" },
|
||||
"inspect_android_package",
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
reason: expect.stringContaining("32-bit"),
|
||||
});
|
||||
for (const name of ["REA_JADX_HEAP_MIB", "REA_JADX_ACTIVE_PROCESSOR_COUNT"])
|
||||
for (const value of ["", "0", "-1", "1.5", "8g", " 4", "9007199254740992"])
|
||||
await expect(
|
||||
resolveJadxConfiguration(
|
||||
{ REA_JADX_MCP_JAR: jar, [name]: value },
|
||||
"inspect_android_package",
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
reason: expect.stringContaining(name),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import { expect, it as test } from "vitest";
|
||||
import { expect, it as test, vi } from "vitest";
|
||||
import { access, readFile, writeFile } from "node:fs/promises";
|
||||
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
|
||||
import { AndroidAnalysisService } from "../../../src/application/android/AndroidAnalysisService.js";
|
||||
import { JadxProvider } from "../../../src/android/JadxProvider.js";
|
||||
import { androidResultSchemas } from "../../../src/domain/android/androidAnalysis.js";
|
||||
import {
|
||||
hashAndroidFile,
|
||||
snapshotAndroidEngine,
|
||||
} from "../../../src/android/AndroidTargetSnapshot.js";
|
||||
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
|
||||
import {
|
||||
createJadxProtocolFixture as setup,
|
||||
verifyJadxFixtureCleanup as verifyCleanup,
|
||||
@@ -11,6 +16,182 @@ import {
|
||||
|
||||
const it = test.skipIf(process.platform === "win32");
|
||||
|
||||
it("rejects a copied JAR that differs from its admitted session identity", async () => {
|
||||
const { jar } = await setup();
|
||||
const admitted = await hashAndroidFile(jar);
|
||||
await writeFile(jar, "engine changed between hashing and copying");
|
||||
const root = await PrivateRuntimeRoot.create({
|
||||
prefix: "rea-jadx-admission-",
|
||||
});
|
||||
try {
|
||||
await expect(
|
||||
snapshotAndroidEngine(
|
||||
jar,
|
||||
admitted,
|
||||
root.path,
|
||||
"inspect_android_package",
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
reason: expect.stringContaining("bytes changed"),
|
||||
});
|
||||
} finally {
|
||||
await root.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("reuses immutable engine state while keeping each Evidence observation separate", async () => {
|
||||
const { service, apk, launches, provider } = await setup();
|
||||
const first = await service.execute("inspect_android_package", { path: apk });
|
||||
if (!first.ok) throw first.error;
|
||||
const preserved = JSON.stringify(first.value);
|
||||
const second = await service.execute("inspect_android_class", {
|
||||
path: apk,
|
||||
class_name: "fixture.Target",
|
||||
});
|
||||
if (!second.ok) throw second.error;
|
||||
expect(launches).toHaveLength(1);
|
||||
expect(JSON.stringify(first.value)).toBe(preserved);
|
||||
expect(second.value.raw_result).toMatchObject({
|
||||
loaded: { class_count: 401 },
|
||||
calls: [
|
||||
expect.objectContaining({ operation: "rea_jvm_status" }),
|
||||
expect.objectContaining({ operation: "get_class_summary" }),
|
||||
],
|
||||
});
|
||||
expect(
|
||||
androidResultSchemas.inspect_android_class.parse(
|
||||
second.value.normalized_result,
|
||||
).engine.heap_limit_mib,
|
||||
).toBe(8192);
|
||||
await provider.close();
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
it("bounds output per operation across a retained session rather than accumulating earlier captures", async () => {
|
||||
const { service, apk, launches, provider } = await setup("large-manifest");
|
||||
for (let index = 0; index < 34; index += 1) {
|
||||
const result = await service.execute("inspect_android_package", {
|
||||
path: apk,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(
|
||||
androidResultSchemas.inspect_android_package.parse(
|
||||
result.value.normalized_result,
|
||||
).manifest.text.length,
|
||||
).toBe(1024 * 1024);
|
||||
}
|
||||
expect(launches).toHaveLength(1);
|
||||
await provider.close();
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
it("retire sessions when APK bytes, engine bytes or JVM options change", async () => {
|
||||
const { service, apk, jar, launches, provider, environment } = await setup();
|
||||
const inspect = async () => {
|
||||
const result = await service.execute("inspect_android_package", {
|
||||
path: apk,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
return result.value;
|
||||
};
|
||||
const first = await inspect();
|
||||
await writeFile(
|
||||
apk,
|
||||
Buffer.concat([await readFile(apk), Buffer.from("new artifact bytes")]),
|
||||
);
|
||||
const changed = await inspect();
|
||||
expect(changed.subject?.digest.sha256).not.toBe(first.subject?.digest.sha256);
|
||||
await verifyCleanup(launches.slice(0, 1));
|
||||
await writeFile(jar, "new engine bytes");
|
||||
await inspect();
|
||||
environment.JAVA_TOOL_OPTIONS = "-Xmx8g";
|
||||
environment._JAVA_OPTIONS = "-XX:+UseG1GC";
|
||||
await inspect();
|
||||
expect(launches).toHaveLength(4);
|
||||
expect(launches[3]).toMatchObject({
|
||||
javaToolOptions: "-Xmx8g",
|
||||
legacyJavaOptions: "-XX:+UseG1GC",
|
||||
});
|
||||
expect(launches[3]?.arguments).not.toContain("-Xmx512m");
|
||||
expect(launches[3]?.arguments).not.toContain("-XX:ActiveProcessorCount=1");
|
||||
await provider.close();
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
it("retires an idle engine and starts a fresh one for a later request", async () => {
|
||||
const { service, apk, launches, provider } = await setup();
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
||||
try {
|
||||
const first = await service.execute("inspect_android_package", {
|
||||
path: apk,
|
||||
});
|
||||
if (!first.ok) throw first.error;
|
||||
vi.advanceTimersByTime(60_000);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
await expect
|
||||
.poll(async () => {
|
||||
try {
|
||||
await verifyCleanup(launches);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})
|
||||
.toBe(true);
|
||||
const later = await service.execute("inspect_android_package", { path: apk });
|
||||
if (!later.ok) throw later.error;
|
||||
expect(launches).toHaveLength(2);
|
||||
await provider.close();
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
it("completes large class inventories with exact case-sensitive search semantics", async () => {
|
||||
const { service, apk, provider } = await setup("large-inventory");
|
||||
const full = await service.execute("search_android_classes", {
|
||||
path: apk,
|
||||
query: "",
|
||||
});
|
||||
if (!full.ok) throw full.error;
|
||||
const inventory = androidResultSchemas.search_android_classes.parse(
|
||||
full.value.normalized_result,
|
||||
);
|
||||
expect(inventory.matches).toHaveLength(9001);
|
||||
expect(inventory.matches.at(-1)).toBe("fixture.Class8999");
|
||||
const mixedCase = await service.execute("search_android_classes", {
|
||||
path: apk,
|
||||
query: "target",
|
||||
});
|
||||
if (!mixedCase.ok) throw mixedCase.error;
|
||||
expect(
|
||||
androidResultSchemas.search_android_classes.parse(
|
||||
mixedCase.value.normalized_result,
|
||||
).matches,
|
||||
).toEqual([]);
|
||||
await provider.close();
|
||||
});
|
||||
|
||||
it("close cancels active and queued work and prevents later acquisition", async () => {
|
||||
const { service, apk, launches, provider } = await setup("stall");
|
||||
const active = service.execute("inspect_android_package", { path: apk });
|
||||
await expect.poll(() => launches.length).toBe(1);
|
||||
const queued = service.execute("inspect_android_package", { path: apk });
|
||||
await provider.close();
|
||||
for (const result of [
|
||||
await active,
|
||||
await queued,
|
||||
await service.execute("inspect_android_package", { path: apk }),
|
||||
])
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
expect(launches).toHaveLength(1);
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
it("does not carry a factory instance's cleanup failure into another instance", async () => {
|
||||
const failed = await setup("cleanup-failure");
|
||||
const healthy = await setup();
|
||||
@@ -25,11 +206,12 @@ it("does not carry a factory instance's cleanup failure into another instance",
|
||||
path: healthy.apk,
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
await healthy.provider.close();
|
||||
await verifyCleanup(healthy.launches);
|
||||
});
|
||||
|
||||
it("retains APK identity, original input, raw producer data and normalized observations", async () => {
|
||||
const { service, apk, launches } = await setup();
|
||||
const { service, apk, launches, provider } = await setup();
|
||||
const outcome = await service.execute("inspect_android_package", {
|
||||
path: apk,
|
||||
});
|
||||
@@ -47,11 +229,12 @@ it("retains APK identity, original input, raw producer data and normalized obser
|
||||
expect.objectContaining({ operation: "get_android_manifest" }),
|
||||
]),
|
||||
});
|
||||
await provider.close();
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
it("fetches all class pages rather than silently retaining the first upstream page", async () => {
|
||||
const { service, apk, launches } = await setup();
|
||||
const { service, apk, launches, provider } = await setup();
|
||||
const outcome = await service.execute("search_android_classes", {
|
||||
path: apk,
|
||||
query: "",
|
||||
@@ -63,11 +246,12 @@ it("fetches all class pages rather than silently retaining the first upstream pa
|
||||
expect(result.total_classes).toBe(401);
|
||||
expect(result.matches).toHaveLength(401);
|
||||
expect(result.matches.at(-1)).toBe("fixture.Class399");
|
||||
await provider.close();
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
it("exposes overload candidates and executes only an explicitly selected ambiguous method", async () => {
|
||||
const { service, apk, launches } = await setup();
|
||||
const { service, apk, launches, provider } = await setup();
|
||||
const input = {
|
||||
path: apk,
|
||||
class_name: "fixture.Target",
|
||||
@@ -105,9 +289,10 @@ it("exposes overload candidates and executes only an explicitly selected ambiguo
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
reason: expect.stringContaining("first same-name"),
|
||||
reason: expect.stringContaining("unique method name"),
|
||||
},
|
||||
});
|
||||
await provider.close();
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
@@ -121,7 +306,7 @@ it.each([
|
||||
])(
|
||||
"rejects producer failure %s rather than claiming complete analysis",
|
||||
async (mode) => {
|
||||
const { service, apk, launches } = await setup(mode);
|
||||
const { service, apk, launches, provider } = await setup(mode);
|
||||
const operation =
|
||||
mode === "wrong-apk"
|
||||
? "inspect_android_package"
|
||||
@@ -142,13 +327,14 @@ it.each([
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisOutputError" },
|
||||
});
|
||||
await provider.close();
|
||||
await verifyCleanup(launches);
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects fuzzy class resolution and unsupported upstream versions", async () => {
|
||||
for (const mode of ["wrong-class", "version"]) {
|
||||
const { service, apk, launches } = await setup(mode);
|
||||
for (const mode of ["wrong-class", "version", "engine-version"]) {
|
||||
const { service, apk, launches, provider } = await setup(mode);
|
||||
const outcome = await service.execute("inspect_android_class", {
|
||||
path: apk,
|
||||
class_name: "fixture.Target",
|
||||
@@ -157,11 +343,12 @@ it("rejects fuzzy class resolution and unsupported upstream versions", async ()
|
||||
ok: false,
|
||||
error: {
|
||||
_tag:
|
||||
mode === "version"
|
||||
mode === "version" || mode === "engine-version"
|
||||
? "AnalysisCapabilityUnavailableError"
|
||||
: "AnalysisInputError",
|
||||
},
|
||||
});
|
||||
await provider.close();
|
||||
await verifyCleanup(launches);
|
||||
}
|
||||
});
|
||||
@@ -169,7 +356,7 @@ it("rejects fuzzy class resolution and unsupported upstream versions", async ()
|
||||
it.each(["truncated", "smali"])(
|
||||
"retains %s source coverage instead of presenting it as successful complete Java",
|
||||
async (mode) => {
|
||||
const { service, apk, launches } = await setup(mode);
|
||||
const { service, apk, launches, provider } = await setup(mode);
|
||||
const outcome = await service.execute("inspect_android_method", {
|
||||
path: apk,
|
||||
class_name: "fixture.Target",
|
||||
@@ -186,12 +373,13 @@ it.each(["truncated", "smali"])(
|
||||
if (mode === "truncated")
|
||||
expect(result.source.reported_total_bytes).toBe(100);
|
||||
else expect(result.fell_back).toBe(true);
|
||||
await provider.close();
|
||||
await verifyCleanup(launches);
|
||||
},
|
||||
);
|
||||
|
||||
it("cancels active and queued requests, cleans ownership and never launches a queued cancelled request", async () => {
|
||||
const { service, apk, launches } = await setup("stall");
|
||||
const { service, apk, launches, provider } = await setup("stall");
|
||||
const activeController = new AbortController();
|
||||
const active = service.execute(
|
||||
"inspect_android_package",
|
||||
@@ -216,6 +404,7 @@ it("cancels active and queued requests, cleans ownership and never launches a qu
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
await provider.close();
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
@@ -240,7 +429,7 @@ it("reports missing explicit tools without trying to install or launch them", as
|
||||
it.each(["tool-error", "frame-overflow"])(
|
||||
"preserves the actual failed provider constraint for %s",
|
||||
async (mode) => {
|
||||
const { service, apk, launches } = await setup(mode);
|
||||
const { service, apk, launches, provider } = await setup(mode);
|
||||
const outcome = await service.execute("inspect_android_package", {
|
||||
path: apk,
|
||||
});
|
||||
@@ -257,6 +446,7 @@ it.each(["tool-error", "frame-overflow"])(
|
||||
_tag: "AnalysisOutputError",
|
||||
reason: expect.stringContaining("MCP frame exceeds"),
|
||||
});
|
||||
await provider.close();
|
||||
await verifyCleanup(launches);
|
||||
},
|
||||
);
|
||||
@@ -287,7 +477,7 @@ it("rejects bytes changed after target admission without launching an engine", a
|
||||
});
|
||||
|
||||
it("retains an uncertain workspace and blocks later launches after cleanup cannot be verified", async () => {
|
||||
const { service, apk, launches } = await setup("cleanup-failure");
|
||||
const { service, apk, launches, provider } = await setup("cleanup-failure");
|
||||
const outcome = await service.execute("inspect_android_package", {
|
||||
path: apk,
|
||||
});
|
||||
@@ -305,7 +495,7 @@ it("retains an uncertain workspace and blocks later launches after cleanup canno
|
||||
});
|
||||
|
||||
it("does not attribute upstream smali containing all overloads to the selected method", async () => {
|
||||
const { service, apk, launches } = await setup("overloaded-smali");
|
||||
const { service, apk, launches, provider } = await setup("overloaded-smali");
|
||||
const outcome = await service.execute("inspect_android_method", {
|
||||
path: apk,
|
||||
class_name: "fixture.Target",
|
||||
@@ -319,11 +509,12 @@ it("does not attribute upstream smali containing all overloads to the selected m
|
||||
reason: expect.stringContaining("joins all same-name overloads"),
|
||||
},
|
||||
});
|
||||
await provider.close();
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
it("reports missing native/abstract method source without claiming an empty implementation", async () => {
|
||||
const { service, apk, launches } = await setup("no-body");
|
||||
const { service, apk, launches, provider } = await setup("no-body");
|
||||
const outcome = await service.execute("inspect_android_method", {
|
||||
path: apk,
|
||||
class_name: "fixture.Target",
|
||||
@@ -335,5 +526,6 @@ it("reports missing native/abstract method source without claiming an empty impl
|
||||
);
|
||||
expect(result.body_status).toBe("not_available");
|
||||
expect(result.source.text).toContain("no decompiled body");
|
||||
await provider.close();
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
@@ -4,6 +4,11 @@ import { access } from "node:fs/promises";
|
||||
import { ANDROID_TOOL_CONTRACTS } from "../../../src/contracts/android/androidToolContracts.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { startMcpTransport } from "../../../src/main/transport.js";
|
||||
import type { RuntimeDependencies } from "../../../src/main/types.js";
|
||||
import type { AndroidAnalysisPort } from "../../../src/application/android/AndroidAnalysisPort.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import {
|
||||
createJadxProtocolFixture,
|
||||
@@ -12,6 +17,61 @@ import {
|
||||
|
||||
const it = test.skipIf(process.platform === "win32");
|
||||
|
||||
it("keeps a replacement server usable after the SDK discards its discovery probe", async () => {
|
||||
const { apk } = await createJadxProtocolFixture();
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("Unexpected deep provider");
|
||||
});
|
||||
const factories: Parameters<RuntimeDependencies["serve"]>[0][] = [];
|
||||
const providers: AndroidAnalysisPort[] = [];
|
||||
const runtime: RuntimeDependencies = {
|
||||
env: {},
|
||||
serve: (factory) => {
|
||||
factories.push(factory);
|
||||
return { close: async () => undefined };
|
||||
},
|
||||
createServer: (analysis, binary, options) => {
|
||||
if (options?.androidAnalysis === undefined)
|
||||
throw new Error("Expected owned Android provider");
|
||||
providers.push(options.androidAnalysis);
|
||||
return createServer(analysis, binary, options);
|
||||
},
|
||||
writeStderr: () => undefined,
|
||||
setExitCode: () => undefined,
|
||||
registerShutdown: () => () => undefined,
|
||||
};
|
||||
const transport = await startMcpTransport(runtime, session, {
|
||||
logger: silentLogger,
|
||||
serverLogger: silentLogger,
|
||||
loadOptionalProviders: async () => ({}),
|
||||
});
|
||||
if (!transport.ok) throw new Error("Transport failed");
|
||||
const factory = factories[0];
|
||||
if (factory === undefined) throw new Error("Missing SDK server factory");
|
||||
const probe = await factory({ era: "modern" });
|
||||
await probe.close();
|
||||
const replacement = await factory({ era: "legacy" });
|
||||
const provider = providers[1];
|
||||
if (provider === undefined) throw new Error("Missing replacement provider");
|
||||
const target = await parseBinaryTarget(apk);
|
||||
if (!target.ok) throw target.error;
|
||||
try {
|
||||
expect(
|
||||
await provider.execute(target.value, {
|
||||
operation: "inspect_android_package",
|
||||
input: { path: apk },
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCapabilityUnavailableError" },
|
||||
});
|
||||
} finally {
|
||||
await replacement.close();
|
||||
await transport.closeAndroid();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("publishes and executes all APK contracts with inline Evidence and no active binary", async () => {
|
||||
const { provider, apk, launches } = await createJadxProtocolFixture();
|
||||
const session = createTestBinarySession(() => {
|
||||
@@ -67,7 +127,9 @@ it("publishes and executes all APK contracts with inline Evidence and no active
|
||||
expect(evidence.operation).toBe(contract.name);
|
||||
expect(evidence.raw_result).not.toBeNull();
|
||||
}
|
||||
expect(launches).toHaveLength(5);
|
||||
expect(launches).toHaveLength(1);
|
||||
await client.close();
|
||||
await server.close();
|
||||
await verifyJadxFixtureCleanup(launches);
|
||||
});
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ it("keeps shutdown output stable while logging the rejected cause at debug level
|
||||
const output: string[] = [];
|
||||
const exitCodes: number[] = [];
|
||||
const requests: Array<() => void> = [];
|
||||
let androidClosed = false;
|
||||
const failure = Object.assign(
|
||||
new TypeError("fixture transport close failed"),
|
||||
{
|
||||
@@ -36,6 +37,9 @@ it("keeps shutdown output stable while logging the rejected cause at debug level
|
||||
const logger = pino({ level: "debug" }, { write: (line) => logs.push(line) });
|
||||
createShutdown({
|
||||
handle,
|
||||
closeAndroid: async () => {
|
||||
androidClosed = true;
|
||||
},
|
||||
session: createManagedBinarySession(),
|
||||
unregisterReload: () => undefined,
|
||||
dependencies,
|
||||
@@ -46,6 +50,7 @@ it("keeps shutdown output stable while logging the rejected cause at debug level
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
expect(exitCodes).toEqual([1]);
|
||||
expect(androidClosed).toBe(true);
|
||||
expect(output).toEqual([`${MCP_SHUTDOWN_FAILED}\n`]);
|
||||
expect(logs.map((line) => JSON.parse(line))).toContainEqual(
|
||||
expect.objectContaining({
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import com.atxx.jhmcp.*;
|
||||
import com.google.gson.*;
|
||||
import io.modelcontextprotocol.kotlin.sdk.types.CallToolResult;
|
||||
import io.modelcontextprotocol.kotlin.sdk.types.TextContent;
|
||||
import jadx.api.*;
|
||||
import jadx.core.dex.nodes.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.util.*;
|
||||
import kotlin.coroutines.EmptyCoroutineContext;
|
||||
import kotlinx.coroutines.BuildersKt;
|
||||
|
||||
/** Real audited-JAR regression; synthetic protocol fixtures cannot prove absence of code generation. */
|
||||
public class ReaJadxMetadataRegression {
|
||||
private static void require(boolean condition, String reason) {
|
||||
if (!condition) throw new AssertionError(reason);
|
||||
}
|
||||
|
||||
private static JsonObject call(Method handle, Object bridge, String operation, JsonObject arguments)
|
||||
throws Exception {
|
||||
var input = (kotlinx.serialization.json.JsonObject)
|
||||
kotlinx.serialization.json.Json.Default.parseToJsonElement(arguments.toString());
|
||||
CallToolResult response;
|
||||
try {
|
||||
response = (CallToolResult) handle.invoke(bridge, operation, input);
|
||||
} catch (InvocationTargetException failure) {
|
||||
throw new AssertionError(operation + " failed", failure.getCause());
|
||||
}
|
||||
require(!Boolean.TRUE.equals(response.isError()), operation + " returned an error");
|
||||
require(response.getContent().size() == 1 && response.getContent().get(0) instanceof TextContent,
|
||||
"Unsupported response envelope");
|
||||
return JsonParser.parseString(((TextContent) response.getContent().get(0)).getText()).getAsJsonObject();
|
||||
}
|
||||
|
||||
private static JsonObject arguments(String className) {
|
||||
JsonObject value = new JsonObject();
|
||||
value.addProperty("class_name", className);
|
||||
return value;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SessionConfig config = new SessionConfig(1048576, 0, 90000L, 1, List.of(), List.of(), 64, ResourceMode.FULL);
|
||||
SessionHolder holder = new SessionHolder(config);
|
||||
try {
|
||||
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> holder.load(args[0], config, continuation));
|
||||
JadxSession session = holder.current();
|
||||
require(session != null && !session.getClasses().isEmpty(), "Fixture did not load classes");
|
||||
JadxDecompiler decompiler = session.getClasses().get(0).getClassNode().root().getDecompiler();
|
||||
IdentityHashMap<ClassNode, ProcessState> states = new IdentityHashMap<>();
|
||||
for (ClassNode node : decompiler.getRoot().getClasses()) {
|
||||
require(node.getState() == ProcessState.NOT_LOADED, "Fixture unexpectedly generated source");
|
||||
states.put(node, node.getState());
|
||||
}
|
||||
Class<?> bridgeType = Class.forName("ReaJadxBridge");
|
||||
Constructor<?> constructor = bridgeType.getDeclaredConstructor(SessionHolder.class);
|
||||
constructor.setAccessible(true);
|
||||
Object bridge = constructor.newInstance(holder);
|
||||
Method handle = bridgeType.getDeclaredMethod("handle", String.class, kotlinx.serialization.json.JsonObject.class);
|
||||
handle.setAccessible(true);
|
||||
JsonObject apiArgs = arguments("io.appium.android.apis.ApiDemos");
|
||||
JsonObject apiSummary = call(handle, bridge, "get_class_summary", apiArgs);
|
||||
for (var entry : states.entrySet()) require(entry.getKey().getState() == entry.getValue(),
|
||||
"Metadata generated source: " + entry.getKey().getRawName());
|
||||
require(states.size() == decompiler.getRoot().getClasses().size(), "Metadata changed class inventory");
|
||||
require(apiSummary.getAsJsonArray("fields").get(0).getAsJsonObject().get("type").getAsString().contains("Comparator"),
|
||||
"Generic field type was truncated");
|
||||
JsonObject componentArgs = arguments("androidx.activity.ComponentActivity");
|
||||
JsonObject componentSummary = call(handle, bridge, "get_class_summary", componentArgs);
|
||||
List<String> signatures = new ArrayList<>();
|
||||
for (JsonElement entry : componentSummary.getAsJsonArray("methods")) {
|
||||
JsonObject method = entry.getAsJsonObject();
|
||||
if (method.get("name").getAsString().equals("setContentView"))
|
||||
signatures.add(method.get("signature").getAsString());
|
||||
}
|
||||
require(signatures.size() == 3, "Fixture must contain three setContentView overloads");
|
||||
String[] declarations = { "setContentView(int ", "setContentView(View ", "setContentView(View view, ViewGroup.LayoutParams " };
|
||||
for (int index = 0; index < signatures.size(); index++) {
|
||||
JsonObject methodArgs = arguments("androidx.activity.ComponentActivity");
|
||||
methodArgs.addProperty("method_name", "setContentView");
|
||||
methodArgs.addProperty("overload_index", index);
|
||||
JsonObject first = call(handle, bridge, "get_method_body", methodArgs);
|
||||
require(first.equals(call(handle, bridge, "get_method_body", methodArgs)), "Repeated body changed");
|
||||
require(first.get("overload_index").getAsInt() == index && first.get("overload_count").getAsInt() == 3,
|
||||
"Overload envelope mismatch");
|
||||
require(first.get("mode").getAsString().equals("java"), "Fixture did not produce Java");
|
||||
require(first.get("body").getAsString().contains(declarations[index]), "Wrong overload: " + signatures.get(index));
|
||||
}
|
||||
require(componentSummary.equals(call(handle, bridge, "get_class_summary", componentArgs)),
|
||||
"Frozen summary changed after code generation");
|
||||
require(apiSummary.equals(call(handle, bridge, "get_class_summary", apiArgs)), "Unrelated frozen summary changed");
|
||||
System.out.println("METADATA_REGRESSION_PASS classes=" + states.size() + " overloads=" + signatures.size());
|
||||
} finally {
|
||||
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> holder.unload(continuation));
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+17
-4
@@ -6,12 +6,15 @@ import { z } from "zod";
|
||||
// It is a protocol fixture, not evidence of JADX decompiler support.
|
||||
const mode = process.env.REA_FAKE_JADX_MODE ?? "normal";
|
||||
const server = new McpServer({
|
||||
name: "jadx-headless-mcp",
|
||||
version: mode === "version" ? "99.0.0" : "0.7.1",
|
||||
name: "rea-jadx-bridge",
|
||||
version: mode === "version" ? "99.0.0" : "1",
|
||||
});
|
||||
const classes = [
|
||||
"fixture.Target",
|
||||
...Array.from({ length: 400 }, (_, index) => `fixture.Class${index}`),
|
||||
...Array.from(
|
||||
{ length: mode === "large-inventory" ? 9000 : 400 },
|
||||
(_, index) => `fixture.Class${index}`,
|
||||
),
|
||||
];
|
||||
const methods = [
|
||||
{
|
||||
@@ -37,6 +40,15 @@ const text = (value) => ({ content: [{ type: "text", text: value }] });
|
||||
const json = (value) => text(JSON.stringify(value));
|
||||
const register = (name, handler) =>
|
||||
server.registerTool(name, { inputSchema: z.looseObject({}) }, handler);
|
||||
register("rea_jvm_status", () =>
|
||||
json({
|
||||
engine_reported_version: mode === "engine-version" ? "0.7.0" : "0.7.1",
|
||||
max_heap_bytes: 8 * 1024 * 1024 * 1024,
|
||||
available_processors: 4,
|
||||
java_version: "21-fixture",
|
||||
metadata_scope: "parsed_members",
|
||||
}),
|
||||
);
|
||||
register("load_apk", async ({ path }) => {
|
||||
if (mode === "stall") await new Promise(() => {});
|
||||
return json({
|
||||
@@ -59,12 +71,13 @@ register("get_app_info", () =>
|
||||
}),
|
||||
);
|
||||
register("get_android_manifest", () => {
|
||||
if (mode === "tool-error")
|
||||
if (mode === "tool-error" || mode === "cleanup-failure")
|
||||
return {
|
||||
...text("manifest decoder rejected malformed binary XML"),
|
||||
isError: true,
|
||||
};
|
||||
if (mode === "frame-overflow") return text("x".repeat(9 * 1024 * 1024));
|
||||
if (mode === "large-manifest") return text("x".repeat(1024 * 1024));
|
||||
return text('<manifest package="fixture"/>');
|
||||
});
|
||||
register("list_classes", ({ offset, limit }) =>
|
||||
|
||||
Vendored
+14
-1
@@ -25,9 +25,16 @@ export const createJadxProtocolFixture = async (mode = "normal") => {
|
||||
runId: string;
|
||||
cwd: string | undefined;
|
||||
pid: number | undefined;
|
||||
arguments: readonly string[] | undefined;
|
||||
javaToolOptions: string | undefined;
|
||||
legacyJavaOptions: string | undefined;
|
||||
}[] = [];
|
||||
const environment: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
REA_JADX_MCP_JAR: jar,
|
||||
};
|
||||
const provider = createAndroidAnalysisProvider(
|
||||
{ ...process.env, REA_JADX_MCP_JAR: jar },
|
||||
environment,
|
||||
async (options) => {
|
||||
const spawned = await spawnOwnedProviderProcess({
|
||||
...options,
|
||||
@@ -40,6 +47,10 @@ export const createJadxProtocolFixture = async (mode = "normal") => {
|
||||
runId: options.runId,
|
||||
cwd: options.cwd,
|
||||
pid: spawned.process.pid,
|
||||
arguments: options.arguments,
|
||||
javaToolOptions: options.hostEnvironment?.JAVA_TOOL_OPTIONS,
|
||||
legacyJavaOptions:
|
||||
options.env?._JAVA_OPTIONS ?? options.hostEnvironment?._JAVA_OPTIONS,
|
||||
});
|
||||
if (mode === "cleanup-failure") {
|
||||
onTestFinished(async () => {
|
||||
@@ -63,11 +74,13 @@ export const createJadxProtocolFixture = async (mode = "normal") => {
|
||||
return spawned;
|
||||
},
|
||||
);
|
||||
onTestFinished(() => provider.close().catch(() => undefined));
|
||||
return {
|
||||
service: new AndroidAnalysisService(provider),
|
||||
provider,
|
||||
apk,
|
||||
jar,
|
||||
environment,
|
||||
launches,
|
||||
};
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user