Skip to content

feat(android): trace callers of external DEX methods - #8096

Closed
xu91102 wants to merge 2 commits into
morluto:mainfrom
xu91102:codex/android-external-method-references
Closed

xu91102 wants to merge 2 commits into
morluto:mainfrom
xu91102:codex/android-external-method-references

Conversation

@xu91102

@xu91102 xu91102 commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Find APK callers of a framework/library method even when the APK does not define its declaring class. The existing trace_android_references CLI/MCP operation now accepts these method targets from exact, directly encoded DEX invokes, reports observed prototypes, and returns selectors for inspecting the actual APK caller bodies.

Fixes #7811. Measured baseline and controls: #7811 (comment) (recorded before implementation).

Problem and expected behavior

On main317bf3fe, trace-android-references fixture.apk android.app.NotificationManager --method-name notify refuses the target because NotificationManager is absent from APK definitions, although the APK contains exact invokes. Defined-method references and reading the caller body already work. This extends that defined-only contract; it does not claim unknown runtime dispatch or every conservative refusal is a bug.

With multiple observed prototypes, the caller must choose overload_index. The selected result preserves one using-node row per APK method, repeated instruction sites, the raw DEX carrier/index/code-unit offset/opcode, and a source_selector accepted by inspect_android_method.

Change and scope

  • Reuse the bridge's frozen class/member inventory and one shared raw invoke decoder. External targets have a distinct prototype inventory, not invented class definitions, field counts, or external bodies.
  • Keep APK-defined queries, class-only references, method/class inspection, aliases, input identity, cancellation and awaited cleanup ownership. No external classpath, reflection/JNI/method-handle resolution, inheritance/runtime dispatch inference or APK execution is added.
  • Reserve the complete mandatory caller inventory before optional instruction positions, and bound external method/caller representations before retained/raw/normalized/text copies. Oversized inventories return a typed, nonretryable resource constraint; bounded site evidence keeps its explicit exhaustive flag.
  • Add permanent real-engine single/multidex, overloaded/nested callers, source follow-up, refusal/recovery and large-inventory conformance to the existing real Android workflow. No new workflow event types, permissions or approval bypass; the existing push path filter also covers the new fixtures.
  • Eight prerequisite paths are the identical independently reproduced main317 Knip fix already in feat(dotnet): expose field constant defaults #8015 and fix(snapshot): retain one-shot Ghidra pseudocode results #8089: remove unused internal exports and reuse existing equal-valued timeout/output constants. No field-constant or snapshot feature is included here; these paths are not another contribution root.

Contract and boundary impact

  • Semantic owner and earliest changed stage: ReaJadxBridge observes direct METHOD_REF invokes; JadxAnalysis validates/normalizes a distinct external prototype reply. Shared method selector schema supplies follow-up source identity.
  • Contribution scope fit and linked maintainer decision: ordinary read-only static cross-references in the existing Android provider. No new target execution/injection/mutation/protection-recovery authority. No individual maintainer scope acceptance or assignment is claimed; maintainer review remains separate from the author declarations below.
  • CLI and MCP/tool-catalog contract: existing operation/arguments; method_name admits externally referenced exact classes. Overload ambiguity stays explicit. No new tool (233 tools/6 prompts).
  • Provider, bridge, target-format, or platform compatibility: pinned unmodified JADX0.7.1 remains; internal bridge identity9→10. Tested on macOS arm64/JDK21.0.11 with real APK/DEX input.
  • Evidence/artifact/provenance: additive optional target_definition, reference_scope and caller source_selector; old retained Evidence may omit them and omission remains unknown. Existing digest/carrier/source facts remain primary.
  • Target/authority/cleanup: explicit local APK, private snapshot and original digest checks; no APK execution or network service contact; existing provider process and cleanup ownership retained.
  • Generated/package impact: authored Android docs/contracts updated; ignored catalogs generated/validated by docs checks. No generated binaries, new dependency or release metadata committed.

Expected effects:

  • Read existing files or captured data.
  • Launch or attach to a process. (The existing local read-only JADX provider process; not the APK.)
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

  • Baseline: two external selections refused; defined references/caller source positive and unknown-class negative controls recorded. Six focused new cases failed before implementation.
  • Permanent real-engine controls: two observed prototypes,3 using nodes/4 int-overload sites, repeated sites, overloaded and nested callers, single/multidex carrier, no source generation during reference scan, follow-up source then stable identity, explicit ambiguity/bad-index/unknown-class refusal/recovery, and oversized caller inventory typed refusal.
  • A real fixture with one method containing10,000 direct calls followed by10 short callers originally triggered a false caller-inventory refusal during local review. The shared owner now reserves all11 exact caller selectors before optional sites; CLI/MCP retain the complete caller list, explicitly partial positions, bounded output and replay/refusal/target-replacement recovery. The same immutable APK was used before and after; a512MiB-heap real bridge conformance also passes.
  • Actual installed CLI excerpt (local paths omitted):
{
  "class_name": "android.app.NotificationManager",
  "method_name": "notify",
  "dex_descriptor": "(ILandroid/app/Notification;)V",
  "target_definition": "external",
  "reference_scope": "direct_dex_invokes",
  "reference_unit": "using_node",
  "total": 3,
  "first_caller": {
    "source_selector": {
      "class_name": "fixture.Caller",
      "method_name": "notify0",
      "overload_index": 0
    },
    "direct_invokes_exhaustive": true,
    "direct_invokes": [
      {
        "dex_entry": "classes.dex",
        "source_raw_method_id": "fixture.Caller.notify0(Landroid/app/NotificationManager;Landroid/app/Notification;)V",
        "dex_code_unit_offset": 1,
        "dex_method_index": 0,
        "opcode": "INVOKE_VIRTUAL"
      },
      {
        "dex_entry": "classes.dex",
        "source_raw_method_id": "fixture.Caller.notify0(Landroid/app/NotificationManager;Landroid/app/Notification;)V",
        "dex_code_unit_offset": 4,
        "dex_method_index": 0,
        "opcode": "INVOKE_VIRTUAL"
      }
    ]
  }
}

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

Review fixes and CI boundary

The normal follow-up commit fdfaa08171c8d9f75cf63c2f0a2e1935eeb53de9 addresses three concrete review findings:

  • Check raw prototype/short-id lengths against the same resource budget before copying descriptors or joining signatures. A single oversized real method_inventory prototype now returns the existing typed resource refusal and recovers on a valid subsequent request. Canonical upstream MethodInfo allocation remains outside this additional guard; this is not a general memory or performance guarantee.
  • Reuse one bounded, successful external prototype inventory for the current exact JADX session and class/method query, shared by summary and cross-reference operations. Release it on target/session change and rebuild failure; caller/invoke scans remain fresh.
  • Include the exact DEX descriptors in external overload ambiguity errors using the shared choice formatter; keep APK-defined error wording unchanged.

The original head 6fcda30f had one actual JavaScript worker test failure in CI run41010775127 (plus two aggregate failures): the assertion found the abort signal still unset while using a raw stdout-chunk observer. The exact CI chunk/timer order is not established and three local unmodified-worker attempts did not reproduce that CI failure. A separate valid-schema fragmented-frame control demonstrates the observer gap. The test now uses the existing framed observer after stream ownership and awaits the original abort event, retaining all original error/evidence/close assertions. Production worker, cancellation, timeouts, retries and skips are unchanged. The full worker test file passes36 cases. Old failed output and the initial invalid-UUID harness control remain preserved; a later green run will not erase them.

Validation performed

  • Final accounting:22 distinct files,469 passed and1 existing Windows-specific skip. The final7-case Android file replaces its previous7;19 unchanged Android files retain417 passed/1 skip, README retains9, and the complete worker file retains36. These are not all newly rerun at the final metadata update.
  • Final source npm run check and test-discovery both PASS;2866 test files discovered once. Docs/package/real-engine gates retain their actual earlier timestamps: only two unshipped test files changed afterward, and all runtime/product inputs and2661 product bytes remain identical.
  • npm run verify:android with pinned unmodified JADX0.7.1/JDK21.0.11/macOS arm64: complete existing real lane plus new single/multidex, ambiguity/descriptor, oversized-prototype, refusal/recovery and caller-inventory controls PASS. New compiled controls include7 CLI calls and3 stdio MCP sessions/25 calls, separately counted.
  • Actual packed/installed feature:15 CLI calls and3 stdio MCP sessions/25 calls PASS, including actual schema advertisement, retained raw replies, original APK hashes and awaited cleanup. Archive/current/installed2661 files match byte for byte.
  • npm run verify:package and explicit pack dry-run PASS: official installed REA MCP233 tools/6 prompts, exact6.8.0 update, verified lineage and awaited cleanup.
  • Final immutable Standards and Spec V5 reviews both PASS without findings. Normal hooks and complete source/gitlink/patch/evidence/product gates PASS before normal fork push and again afterward. Fork and upstream head/tree/parent match fdfaa081 / 9174d507 / parent 6fcda30f. No history rewriting or hook bypass.
  • Upstream code CI and automated review are evaluated against each exact head separately. Old6fc CI failure is retained as history and does not establish the new fdf head's outcome. No new-head CI success or full Codex approval is claimed from these local results.

Compatibility, safety, and release

  • No breaking call migration; existing defined targets stay valid. External method overload indices identify observed exact prototypes, not an inferred full external class API.
  • Unverified: Android device/emulator/runtime dispatch, external method bodies, Windows/Linux host runtime, full agent/model/real-app workflows and performance improvement. No target APK was executed; no other author's runtime results are used.
  • Real boundary refusals and cleanup controls remain. Raw original RED/format/HARNESS failures are retained. Two hook-generated normalizations in already-touched files were caught before push, then the final code was fully revalidated/reviewed. Corrected SDK import layout, initial non-UUID frame fixture and local evidence labels were harness/receipt issues. The original6fc CI worker assertion failure remains a separately recorded actual failure.
  • Source prepared/locally tested does not imply upstream CI/Codex, security approval, human ownership declaration or maintainer integration approval.

Author readiness

Human owner: @xu91102

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

@greptile-apps

greptile-apps Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5 Tier: apex

[Medium impact] The reviewed changes appear safe to merge; all previous findings are addressed and no new blocking issue was found.

Summary

Adds APK caller tracing for external methods named directly by DEX invokes.

  • Reference tracing finds APK callers of directly invoked external methods.
  • Unused exports are removed and equal-valued constants are reused.

Reviews (2) · Last reviewed commit: "fix(android): bound and reuse external p..." · Reviewed by Greptile

Comment thread bridge/android/ReaJadxBridge.java Resolved
Comment thread bridge/android/ReaJadxBridge.java Resolved
Comment thread docs/android-analysis.md Resolved
@xu91102
xu91102 marked this pull request as ready for review October 30, 2026 06:53
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-30T06:53:31.506967Z
We couldn’t complete this review. Comment @codex review to try again.
6fcda30 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@Rinkia

Rinkia commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

I tested this PR at fdfaa0817 against two public APKs, in a Linux x64 container with the bundled JADX headless 0.7.1 (bridge version 10) and Node 24.22.1. I compared it with main at 45cc93596.

  • NewPipe 0.29.1 from the GitHub release (18447bfb…ab79, 3 DEX files)
  • Binary Eye (568cec65…44f1)

The reference is dexdump -d over every classes*.dex. For each exact method reference, I indexed the caller method, the code-unit offset, the opcode and the DEX file of every invoke-*, then compared those sets with normalized_result.references[].direct_invokes.

Exact match with dexdump. The callers and sites (DEX entry, caller, offset, opcode) are equal in all 18 cases:

Target APK Callers / sites
android.app.NotificationManager.notify (ILandroid/app/Notification;)V NewPipe 6 / 7, in classes.dex and classes3.dex
notify (Ljava/lang/String;ILandroid/app/Notification;)V NewPipe 1 / 1
android.content.Intent.<init> (Ljava/lang/String;)V NewPipe 36 / 40
android.content.Intent.<init> (Landroid/content/Context;Ljava/lang/Class;)V NewPipe 42 / 46
android.text.TextUtils.isEmpty (invoke-static and invoke-static/range) NewPipe 179 / 244
android.text.TextUtils.isEmpty Binary Eye 49 / 72
java.util.List.add, both prototypes (invoke-interface, three DEX files) NewPipe 145 / 210 and 15 / 19
android.app.Activity.onCreate (invoke-super only) NewPipe 4 / 4
android.app.Activity.onSaveInstanceState (invoke-super only) Binary Eye 1 / 1
android.view.ViewGroup$MarginLayoutParams.<init> (II)V (nested external class) NewPipe 8 / 8
java.lang.String.<init> ([BLjava/nio/charset/Charset;)V (one of 7 prototypes) NewPipe 20 / 20
java.lang.StringBuilder.append (C) NewPipe 533 / 897
java.lang.StringBuilder.append (Ljava/lang/String;) Binary Eye 643 / 2157
android.util.Log.d (Ljava/lang/String;Ljava/lang/String;)I Binary Eye 44 / 54

Other checks:

  • Every ambiguous query listed exactly the prototypes that dexdump shows. Examples: 2 for notify, 5 for Intent.<init>, 7 for String.<init>. An out-of-range index, an unreferenced method name and an unknown class each return a clear invalid_request.
  • source_selector works as a follow-up. inspect-android-method opened the callers, including JADX-renamed ones such as androidx.cardview.widget.CardView.AnonymousClass1.toString.
  • MCP gives the same result as the CLI.
  • A defined-class query (org.schabi.newpipe.player.Player.triggerProgressUpdate) returns the same references as main; the only addition is target_definition: "defined".

Three observations, none blocking:

  1. Position budget visible only per node. java.lang.StringBuilder.append(Ljava/lang/String;) in NewPipe has 1,849 callers and 6,070 sites. All 1,849 callers come back, and the 722 sites that are kept are all correct. However, 1,589 nodes have direct_invokes_exhaustive: false, and 1,587 of those have no positions at all. At the top level the result says coverage: "complete", and none of the limitations mentions that positions were cut, so a caller has to scan every node to find out. A top-level count of nodes with partial positions, or a limitation when the position budget is reached, would make this visible. Binary Eye's 2,157 sites for the same method were all kept, so the cut depends on the input.
  2. Nested external classes only accept the $ spelling. android.view.ViewGroup$MarginLayoutParams works. android.view.ViewGroup.MarginLayoutParams returns "No APK definition or direct DEX invoke references the exact class". For classes the APK defines, trace-android-references and inspect-android-class accept both spellings. Accepting the dotted form here, or mentioning $ in the error, would keep the two consistent.
  3. Class-only error on an external class. A class-only query on an external class (android.app.NotificationManager without --method-name) still says "Exact class not found … use search_android_classes". That is documented ("Class-only queries … still require an APK definition"). Since the class is referenced, a hint to add --method-name would point the caller to the new path.

I didn't test reflection, JNI, inherited lookups (calls through an app subclass's method reference) or the oversized-inventory refusal path.

@gensokyo-dev

Copy link
Copy Markdown
Collaborator

Absorbing this contribution in #8154 because the source branch does not allow maintainer edits and needs a current-main conflict resolution. The integration preserves author credit, excludes unrelated resource-limit/JavaScript-test edits, and adds shared aggregate instruction-position coverage. All 322 Android boundary tests (1 existing Windows skip), the complete real Android CLI/MCP lane, and an independent NewPipe/dexdump check passed locally. The original PR will remain open until the integration merges.

gensokyo-dev added a commit that referenced this pull request Oct 30, 2026
Resolve exact external method targets from directly encoded DEX invokes.
Preserve complete caller identity, bounded position evidence and follow-up
selectors. Report aggregate position coverage independently of the caller
inventory, and reuse bounded prototype facts within the exact session.

Absorbs #8096. Fixes #7811.

Co-authored-by: hhang <[email protected]>
@gensokyo-dev

Copy link
Copy Markdown
Collaborator

Integrated in #8154 / 0ffed7a, with original author credit retained. The integration keeps this Android feature and its real conformance, adds aggregate instruction-position coverage, and preserves current-main resource controls. Current code CI, CodeQL and Greptile passed; real CLI/MCP and independent NewPipe/dexdump verification are recorded in #8154.

@morluto morluto added enhancement New feature or request area: runtime Process capture and runtime observation labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: runtime Process capture and runtime observation enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] trace_android_references: find APK callers of a framework or library method that the APK doesn't define

4 participants