From dc6799d4880f3e0737be54dddfd4d48a8080fbf4 Mon Sep 17 00:00:00 2001 From: Ahmed Date: Thu, 19 Nov 2026 01:23:34 +0500 Subject: [PATCH] fix(android): report method disassembly failure as unavailable body (#12090) * fix(android): report method disassembly failure as unavailable body Catch JADX bridge get_method_body failures in inspectMethod and project as an unavailable body with disassembly_failed marker, avoiding generic execution_failure with irrelevant rea doctor remediation. Fixes #10482 * fix(android): preserve method identity when disassembly is unavailable * fix(android): retain method identity when smali generation fails --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --- bridge/android/ReaJadxBridge.java | 43 ++++++++---- docs/guides/android/android-analysis.md | 5 +- src/android/JadxAnalysis.ts | 21 ++++-- src/android/JadxProtocol.ts | 22 ++++-- .../analysisView/androidSymbolView.test.ts | 43 ++++++++---- src/domain/analysisView/androidSymbolView.ts | 5 +- src/domain/android/androidAnalysis.ts | 39 +++++++---- .../boundary/process/jadxIntegration.test.ts | 56 ++++++++++++++-- .../android/ReaJadxMetadataRegression.java | 67 +++++++++++++++++-- tests/fixtures/android/jadx-mcp.mjs | 15 ++++- 10 files changed, 251 insertions(+), 65 deletions(-) diff --git a/bridge/android/ReaJadxBridge.java b/bridge/android/ReaJadxBridge.java index 603da79a26..1fc9e322d1 100644 --- a/bridge/android/ReaJadxBridge.java +++ b/bridge/android/ReaJadxBridge.java @@ -713,10 +713,19 @@ class ReaJadxBridge { TextUtilKt.truncateToBytes(block, current.getMaxSourceBytes()), "smali", true, markers); } + private static final class MethodDisassemblyUnavailable extends IllegalArgumentException { + MethodDisassemblyUnavailable(String message) { super(message); } + } + private static String selectMethodSmali(JadxSession.MethodSmali smali, String shortId) { - if (!smali.getFound()) - throw new IllegalArgumentException("JADX could not disassemble " + shortId - + (smali.getNote() == null ? "" : ": " + smali.getNote())); + if (!smali.getFound()) { + String reason = "JADX could not disassemble " + shortId + + (smali.getNote() == null ? "" : ": " + smali.getNote()); + // JADX folds caller interruption into the same result as failed generation + // and missing blocks, but leaves the interrupt flag set. + if (Thread.currentThread().isInterrupted()) throw new IllegalArgumentException(reason); + throw new MethodDisassemblyUnavailable(reason); + } // Upstream returns every same-name overload, and can return an unterminated // trailing block. Match the full original identity before applying output limits. List matches = smali.getBlocks().stream().filter(block -> { @@ -724,10 +733,10 @@ class ReaJadxBridge { return header.startsWith(".method ") && header.endsWith(" " + shortId); }).toList(); if (matches.size() != 1) - throw new IllegalArgumentException("Disassembly could not establish one selected method: " + shortId); + throw new MethodDisassemblyUnavailable("Disassembly could not establish one selected method: " + shortId); String block = matches.get(0); if (!block.stripTrailing().endsWith("\n.end method")) - throw new IllegalArgumentException("Selected method disassembly is incomplete: " + shortId); + throw new MethodDisassemblyUnavailable("Selected method disassembly is incomplete: " + shortId); return block; } @@ -1003,14 +1012,22 @@ class ReaJadxBridge { List overloads = methods(cls, args); int index = integer(args, "overload_index", 0); if (index >= overloads.size()) throw new InputFailure("overload_index", "overload_index out of range: " + index); - JavaMethod method = method(cls, overloads.get(index)); - JadxSession.SmartCode code = methodBody(current, cls, overloads.get(index), method); - return json(Map.of("class_name", cls.summary().get("full_name"), - "method_name", overloads.get(index).name(), "full_name", method.getFullName(), - "dex_descriptor", overloads.get(index).summary().get("dex_descriptor"), - "overload_index", index, "overload_count", overloads.size(), - "mode", code.getKind(), "fell_back", code.getFellBack(), - "markers", code.getMarkers(), "body", code.getText())); + MethodSnapshot selected = overloads.get(index); + JavaMethod method = method(cls, selected); + Map result = new LinkedHashMap<>(Map.of( + "class_name", cls.summary().get("full_name"), + "method_name", selected.name(), "full_name", method.getFullName(), + "dex_descriptor", selected.summary().get("dex_descriptor"), + "overload_index", index, "overload_count", overloads.size())); + try { + JadxSession.SmartCode code = methodBody(current, cls, selected, method); + result.putAll(Map.of("mode", code.getKind(), "fell_back", code.getFellBack(), + "markers", code.getMarkers(), "body", code.getText())); + } catch (MethodDisassemblyUnavailable failure) { + result.put("mode", "unavailable"); + result.put("body_unavailable_reason", failure.getMessage()); + } + return json(result); } List uses; String target = (String) cls.summary().get("full_name"); diff --git a/docs/guides/android/android-analysis.md b/docs/guides/android/android-analysis.md index eb734fa6f2..51f9ddbdda 100644 --- a/docs/guides/android/android-analysis.md +++ b/docs/guides/android/android-analysis.md @@ -307,8 +307,9 @@ overload even when Java code generation renames a method. If the selected Java body was omitted, including a method merged into a synthetic bridge, REA returns its original smali with the `java_body_unavailable` marker. The marker describes missing Java; it does not infer why the method was omitted or name a replacement. -Unresolved or duplicate disassembly identities fail instead of attributing another -method's instructions to the selection. +If disassembly cannot establish one complete block for the selected method, the +result keeps that method's identity and reports `body_status: "not_available"` +with a `body_unavailable_reason`. Both `representation` and `source` are null. Native and abstract methods are identified from access flags captured before code generation. They report `body_status: "not_available"`, an diff --git a/src/android/JadxAnalysis.ts b/src/android/JadxAnalysis.ts index b5da2323db..be0034329e 100644 --- a/src/android/JadxAnalysis.ts +++ b/src/android/JadxAnalysis.ts @@ -437,11 +437,22 @@ const inspectMethod = async ( class_name: summary.full_name, method: selected, overload_count: candidates.length, - representation: body.mode, - body_status: body.body.length === 0 ? "not_available" : "available", - fell_back: body.fell_back, - markers: body.markers, - source: normalizeJadxText(body.body), + ...(body.mode === "unavailable" + ? { + representation: null, + body_status: "not_available", + body_unavailable_reason: body.body_unavailable_reason, + fell_back: false, + markers: ["disassembly_failed"], + source: null, + } + : { + representation: body.mode, + body_status: body.body.length === 0 ? "not_available" : "available", + fell_back: body.fell_back, + markers: body.markers, + source: normalizeJadxText(body.body), + }), ...mappingOf(mapping, () => [ classQuery(summary), ...methodQueries(summary).filter( diff --git a/src/android/JadxProtocol.ts b/src/android/JadxProtocol.ts index a4d3788ca3..8fc96e5b22 100644 --- a/src/android/JadxProtocol.ts +++ b/src/android/JadxProtocol.ts @@ -139,18 +139,28 @@ export const jadxExternalReferenceSummarySchema = z.object({ observed_method_count: count, prototypes: z.array(jadxMethodMetadataSchema).min(1), }); -export const jadxMethodSchema = z.object({ +const jadxMethodIdentity = { class_name: z.string(), method_name: z.string(), full_name: z.string(), overload_index: count, overload_count: count, dex_descriptor: dexDescriptorSchema, - mode: z.enum(["java", "smali"]), - fell_back: z.boolean(), - markers: z.array(z.string()), - body: z.string(), -}); +}; +export const jadxMethodSchema = z.discriminatedUnion("mode", [ + z.object({ + ...jadxMethodIdentity, + mode: z.enum(["java", "smali"]), + fell_back: z.boolean(), + markers: z.array(z.string()), + body: z.string(), + }), + z.strictObject({ + ...jadxMethodIdentity, + mode: z.literal("unavailable"), + body_unavailable_reason: z.string().min(1), + }), +]); export const jadxXrefsSchema = z.object({ target: z.string(), reference_target: z.literal("external").optional(), diff --git a/src/domain/analysisView/androidSymbolView.test.ts b/src/domain/analysisView/androidSymbolView.test.ts index 58c0cf8af7..cd05d959fe 100644 --- a/src/domain/analysisView/androidSymbolView.test.ts +++ b/src/domain/analysisView/androidSymbolView.test.ts @@ -217,21 +217,38 @@ it.each(["inspect_android_class", "inspect_android_method"] as const)( }, ); -it("preserves native absence and optional historical omission without inventing mapping facts", () => { - const { mapping: _mapping, ...native } = methodReport(); - const facts = { - ...native, - body_status: "not_available", +it.each([ + { markers: ["native_method"], source: { status: "complete", text: "", reported_total_bytes: 0 }, - }; - const { parent } = fixture("inspect_android_method", facts); - const result = projectAnalysisView(parent, { kind: "summary" }); - if (!result.ok) throw result.error; - const view = androidMethodSummaryViewResultSchema.parse(result.value); - expect(view.summary).toEqual(facts); - expect(Object.hasOwn(view.summary, "mapping")).toBe(false); -}); + }, + { + representation: null, + body_unavailable_reason: + "Selected method disassembly is incomplete: update()V", + markers: ["disassembly_failed"], + source: null, + }, +])( + "preserves method absence with $markers and historical omission of mapping", + (absence) => { + const { mapping: _mapping, ...method } = methodReport(); + const facts = { + ...method, + body_status: "not_available", + fell_back: false, + ...absence, + }; + const { parent } = fixture("inspect_android_method", facts); + const result = projectAnalysisView(parent, { kind: "summary" }); + if (!result.ok) throw result.error; + const view = androidMethodSummaryViewResultSchema.parse(result.value); + expect(view.summary).toEqual(facts); + expect(Object.hasOwn(view.summary, "mapping")).toBe(false); + if (absence.source === null) + expect(view.unknowns).toContain(absence.body_unavailable_reason); + }, +); it.each(["inspect_android_class", "inspect_android_method"] as const)( "rejects malformed historical %s facts with a typed source error", diff --git a/src/domain/analysisView/androidSymbolView.ts b/src/domain/analysisView/androidSymbolView.ts index 9a6456ecf5..c6f2e127d0 100644 --- a/src/domain/analysisView/androidSymbolView.ts +++ b/src/domain/analysisView/androidSymbolView.ts @@ -127,7 +127,10 @@ export const projectAndroidSymbolSummary = ( summary: parsed.value, unknowns: [ ...shared.unknowns, - ...(parsed.value.source.status === "partial" + ...(parsed.value.source === null + ? [parsed.value.body_unavailable_reason] + : []), + ...(parsed.value.source?.status === "partial" ? [ "The selected method source is partial; retained text does not establish a complete method body.", ] diff --git a/src/domain/android/androidAnalysis.ts b/src/domain/android/androidAnalysis.ts index 7f153d1353..75deee8c46 100644 --- a/src/domain/android/androidAnalysis.ts +++ b/src/domain/android/androidAnalysis.ts @@ -223,6 +223,14 @@ const engine = z.strictObject({ const common = { engine }; /** Portable observations with explicit decompiler and identity limitations. */ +const methodInspectionIdentity = { + ...common, + class_name: z.string(), + method, + overload_count: z.int().positive(), + mapping: androidMappingReportSchema.exactOptional(), +}; + export const androidResultSchemas = { inspect_android_jni_bindings: androidJniReportSchema.extend(common), inspect_android_package: z.strictObject({ @@ -267,18 +275,25 @@ export const androidResultSchemas = { inner_classes: z.array(z.string()), mapping: androidMappingReportSchema.exactOptional(), }), - inspect_android_method: z.strictObject({ - ...common, - class_name: z.string(), - method: method, - overload_count: z.int().positive(), - representation: z.enum(["java", "smali"]), - body_status: z.enum(["available", "not_available"]), - fell_back: z.boolean(), - markers: z.array(z.string()), - source: textCoverage, - mapping: androidMappingReportSchema.exactOptional(), - }), + inspect_android_method: z.union([ + z.strictObject({ + ...methodInspectionIdentity, + representation: z.enum(["java", "smali"]), + body_status: z.enum(["available", "not_available"]), + fell_back: z.boolean(), + markers: z.array(z.string()), + source: textCoverage, + }), + z.strictObject({ + ...methodInspectionIdentity, + representation: z.null(), + body_status: z.literal("not_available"), + body_unavailable_reason: z.string().min(1), + fell_back: z.literal(false), + markers: z.array(z.string()), + source: z.null(), + }), + ]), trace_android_references: z.strictObject({ ...common, target_definition: z.enum(["defined", "external"]), diff --git a/tests/boundary/process/jadxIntegration.test.ts b/tests/boundary/process/jadxIntegration.test.ts index 5b258acc50..0afd229f52 100644 --- a/tests/boundary/process/jadxIntegration.test.ts +++ b/tests/boundary/process/jadxIntegration.test.ts @@ -1,4 +1,6 @@ import { fileIdentity } from "../../fixtures/evidenceSubject.js"; +import { canonicalOutputSchema } from "../../fixtures/canonicalOutputSchema.js"; +import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; import { SdkErrorCode } from "@modelcontextprotocol/client"; import { packagedJadxBridgeIdentity } from "../../support/packagedJadxBridge.js"; import { ArtifactResourceScope } from "../../../src/resources/ArtifactResourceScope.js"; @@ -748,7 +750,7 @@ it("exposes overload candidates and executes only an explicitly selected ambiguo reported_signature: "choose(int): void", dex_descriptor: "(I)V", }); - expect(result.source.text).toContain("overload 1"); + expect(result.source?.text).toContain("overload 1"); const references = await service.execute("trace_android_references", input); expect(references).toMatchObject({ ok: false, @@ -844,12 +846,12 @@ it.each(["truncated", "smali"])( const result = androidResultSchemas.inspect_android_method.parse( outcome.value.normalized_result, ); - expect(result.source.status).toBe( + expect(result.source?.status).toBe( mode === "truncated" ? "partial" : "complete", ); expect(result.representation).toBe(mode === "smali" ? "smali" : "java"); if (mode === "truncated") - expect(result.source.reported_total_bytes).toBe(100); + expect(result.source?.reported_total_bytes).toBe(100); else expect(result.fell_back).toBe(true); await provider.close(); await verifyCleanup(launches); @@ -1471,6 +1473,52 @@ it("accepts exact selected-overload smali from the bridge", async () => { await verifyCleanup(launches); }); +it.each(["unavailable-body", "unavailable-wrong-descriptor"] as const)( + "preserves verified method identity for %s", + async (mode) => { + const { service, apk, launches, provider } = await setup(mode); + try { + const outcome = await service.execute("inspect_android_method", { + path: apk, + class_name: "fixture.Target", + method_name: "choose", + overload_index: 1, + }); + if (mode === "unavailable-wrong-descriptor") { + expect(outcome).toMatchObject({ + ok: false, + error: { _tag: "AnalysisOutputError" }, + }); + return; + } + if (!outcome.ok) throw outcome.error; + expect(outcome.value.normalized_result).toMatchObject({ + method: { overload_index: 1, dex_descriptor: "(I)V" }, + overload_count: 2, + representation: null, + body_status: "not_available", + body_unavailable_reason: + "Disassembly could not establish one selected method: choose(I)V", + markers: ["disassembly_failed"], + source: null, + }); + const { assertions } = createMcpSchemaValidation(); + const advertised = canonicalOutputSchema("inspect_android_method"); + expect( + assertions.validateSchema(advertised), + JSON.stringify(assertions.errors), + ).toBe(true); + expect( + assertions.validate(advertised, outcome.value), + JSON.stringify(assertions.errors), + ).toBe(true); + } finally { + await provider.close(); + await verifyCleanup(launches); + } + }, +); + it("retains parsed native body absence without claiming an empty implementation", async () => { const { service, apk, launches, provider } = await setup("native-method"); const outcome = await service.execute("inspect_android_method", { @@ -1483,7 +1531,7 @@ it("retains parsed native body absence without claiming an empty implementation" outcome.value.normalized_result, ); expect(result.body_status).toBe("not_available"); - expect(result.source.text).toBe(""); + expect(result.source?.text).toBe(""); expect(result.markers).toEqual(["native_method"]); await provider.close(); await verifyCleanup(launches); diff --git a/tests/conformance/android/ReaJadxMetadataRegression.java b/tests/conformance/android/ReaJadxMetadataRegression.java index 6b0bdba59a..1eafe01692 100644 --- a/tests/conformance/android/ReaJadxMetadataRegression.java +++ b/tests/conformance/android/ReaJadxMetadataRegression.java @@ -12,6 +12,8 @@ import java.lang.reflect.*; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.util.*; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.zip.*; import kotlin.coroutines.EmptyCoroutineContext; import kotlinx.coroutines.BuildersKt; @@ -697,6 +699,7 @@ public class ReaJadxMetadataRegression { require(ordinary.get("mode").getAsString().equals("java") && ordinary.get("body").getAsString().contains("COUNT"), "Ordinary executable method no longer produces Java"); verifyNoBodyMethods(handle, bridge, holder.current()); + verifyDisassemblyGenerationFailure(handle, bridge, holder.current()); verifyMergedMethods(handle, bridge); verifyConstantFields(handle, bridge, holder.current()); verifyRawMemberNames(handle, bridge); @@ -855,17 +858,67 @@ public class ReaJadxMetadataRegression { select.invoke(null, new JadxSession.MethodSmali("highlightText", blocks, true, null), "highlightText()V"); throw new AssertionError("Unproven disassembly identity or completeness was accepted"); } catch (InvocationTargetException failure) { - require(failure.getCause() instanceof IllegalArgumentException, - "Disassembly uncertainty lost its failure reason"); + require(failure.getCause().getClass().getSimpleName().equals("MethodDisassemblyUnavailable") + && failure.getCause().getMessage().contains("highlightText()V"), + "Disassembly uncertainty lost its method-scoped reason"); } } - String reason = "smali generation failed: controlled timeout"; + for (String reason : Arrays.asList(null, "class has no smali (no code)", + "smali generation failed: controlled timeout")) { + try { + select.invoke(null, new JadxSession.MethodSmali("highlightText", List.of(), false, reason), "highlightText()V"); + throw new AssertionError("Missing disassembly was accepted as a body"); + } catch (InvocationTargetException failure) { + require(failure.getCause().getClass().getSimpleName().equals("MethodDisassemblyUnavailable") + && failure.getCause().getMessage().contains("highlightText()V") + && (reason == null || failure.getCause().getMessage().contains(reason)), + "Missing disassembly lost its method-scoped reason: " + failure.getCause()); + } + } + Thread.currentThread().interrupt(); try { - select.invoke(null, new JadxSession.MethodSmali("highlightText", List.of(), false, reason), "highlightText()V"); - throw new AssertionError("Disassembly generation failure was accepted"); + select.invoke(null, new JadxSession.MethodSmali("highlightText", List.of(), false, "smali generation failed: null"), + "highlightText()V"); + throw new AssertionError("Interrupted disassembly returned a body"); } catch (InvocationTargetException failure) { - require(failure.getCause() instanceof IllegalArgumentException - && failure.getCause().getMessage().contains(reason), "Original disassembly failure reason was lost"); + require(failure.getCause().getClass() == IllegalArgumentException.class + && Thread.currentThread().isInterrupted(), "Disassembly consumed the caller interruption"); + } finally { + Thread.interrupted(); + } + } + + private static void verifyDisassemblyGenerationFailure(Method handle, Object bridge, JadxSession session) + throws Exception { + JsonObject input = methodArguments("fixture.MixedInitialization", ""); + JsonObject complete = call(handle, bridge, "get_method_body", input); + Field pool = JadxSession.class.getDeclaredField("decompilePool"); + pool.setAccessible(true); + ExecutorService rejected = Executors.newSingleThreadExecutor(); + rejected.shutdown(); + Object original = pool.get(session); + pool.set(session, rejected); + try { + JsonObject unavailable = call(handle, bridge, "get_method_body", input); + require(unavailable.get("mode").getAsString().equals("unavailable") + && !unavailable.has("body") && !unavailable.has("fell_back") && !unavailable.has("markers"), + "Rejected disassembly work did not report an unavailable body: " + unavailable); + require(unavailable.get("body_unavailable_reason").getAsString().contains("smali generation failed"), + "JADX generation failure reason was discarded: " + unavailable); + for (String key : List.of("class_name", "method_name", "full_name", "dex_descriptor", + "overload_index", "overload_count")) { + require(complete.get(key).equals(unavailable.get(key)), "Disassembly failure changed " + key); + } + try { + call(handle, bridge, "get_method_body", methodArguments("fixture.MixedInitialization", "touch")); + throw new AssertionError("A Java generation error was classified as unavailable disassembly"); + } catch (AssertionError failure) { + require(failure.getCause() instanceof IllegalArgumentException + && failure.getCause().getMessage().startsWith("// ERROR:"), + "Java generation did not keep its provider error: " + failure); + } + } finally { + pool.set(session, original); } } diff --git a/tests/fixtures/android/jadx-mcp.mjs b/tests/fixtures/android/jadx-mcp.mjs index 5212545636..3fdba4286d 100644 --- a/tests/fixtures/android/jadx-mcp.mjs +++ b/tests/fixtures/android/jadx-mcp.mjs @@ -239,7 +239,7 @@ register("get_method_body", ({ method_name, overload_index }) => { const selected = methods.filter((method) => method.name === method_name)[ overload_index ]; - return json({ + const identity = { class_name: "fixture.Target", method_name, full_name: `fixture.Target.${method_name}`, @@ -247,7 +247,18 @@ register("get_method_body", ({ method_name, overload_index }) => { mode === "wrong-method" ? overload_index + 1 : overload_index, overload_count: method_name === "choose" ? 2 : 1, dex_descriptor: - mode === "wrong-descriptor" ? "()V" : selected.dex_descriptor, + mode === "wrong-descriptor" || mode === "unavailable-wrong-descriptor" + ? "()V" + : selected.dex_descriptor, + }; + if (mode === "unavailable-body" || mode === "unavailable-wrong-descriptor") + return json({ + ...identity, + mode: "unavailable", + body_unavailable_reason: `Disassembly could not establish one selected method: ${selected.raw_name}${selected.dex_descriptor}`, + }); + return json({ + ...identity, mode: mode === "smali" || mode === "selected-overload-smali" ? "smali" : "java", fell_back: mode === "smali" || mode === "selected-overload-smali",