Skip to content

fix(DexFactory): register injected proxy dex with a single class loader#1968

Merged
NathanWalker merged 1 commit into
mainfrom
fix/prod-inject-dex
Jun 12, 2026
Merged

fix(DexFactory): register injected proxy dex with a single class loader#1968
NathanWalker merged 1 commit into
mainfrom
fix/prod-inject-dex

Conversation

@edusperoni

@edusperoni edusperoni commented Jun 11, 2026

Copy link
Copy Markdown
Collaborator

Injecting a generated proxy into the app's PathClassLoader by opening it
through a temporary DexClassLoader and splicing its dex element left the
same DexFile claimed by two class loaders. ART rejects this
unconditionally ("Attempt to register dex file ... with multiple class
loaders"), but the second registration only materializes on
non-debuggable builds, so release apps crashed on the first
runtime-generated proxy while debug builds worked.

Build the dex element through the target class loader itself instead, so
the DexFile only ever has one owner: on API 24+ via
BaseDexClassLoader.addDexPath, below that via DexPathList's static
makePathElements/makeDexElements factories spliced into dexElements (the
MultiDex technique). If injection fails, fall back to the isolated
DexClassLoader path (pre-#1951 behavior) instead of failing the
subsequent loadClass with ClassNotFoundException.

Adds tests covering the original FragmentFactory scenario: proxies
generated at runtime (hidden from the static binding generator) must be
resolvable via Class.forName through the app's class loader.

Fixes #1962

Refs #1951

Summary by CodeRabbit

  • Tests

    • Added a startup-loaded test suite that verifies discovery and reflective instantiation of runtime-generated classes.
  • Refactor

    • Improved dynamic class-loading behavior: injection now reports success/failure and falls back to a safer loading path when injection isn’t possible.

@coderabbitai

coderabbitai Bot commented Jun 11, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 2e41e304-bd44-4837-b8a0-5ae5b7b1b72f

📥 Commits

Reviewing files that changed from the base of the PR and between 2f12361 and 56a78de.

📒 Files selected for processing (3)
  • test-app/app/src/main/assets/app/mainpage.js
  • test-app/app/src/main/assets/app/tests/testClassForNameDiscovery.js
  • test-app/runtime/src/main/java/com/tns/DexFactory.java
🚧 Files skipped from review as they are similar to previous changes (2)
  • test-app/app/src/main/assets/app/mainpage.js
  • test-app/app/src/main/assets/app/tests/testClassForNameDiscovery.js

📝 Walkthrough

Walkthrough

DexFactory's dex injection now returns a boolean and is SDK-gated; resolveClass uses this to fall back to an isolated DexClassLoader when injection fails. The app startup now requires a new test suite that asserts Class.forName discovery and reflective instantiation of runtime-generated classes.

Changes

Dex Injection Redesign and Validation

Layer / File(s) Summary
DexFactory injection implementation
test-app/runtime/src/main/java/com/tns/DexFactory.java
Adds android.os.Build and reflection imports and replaces the prior void injection with injectDexIntoClassLoader returning boolean; on API >=24 it reflectively calls BaseDexClassLoader.addDexPath(jarFilePath), otherwise it builds/appends dexElements via DexPathList reflection; exceptions cause false with a warning.
resolveClass conditional parent load and fallback
test-app/runtime/src/main/java/com/tns/DexFactory.java
Updates resolveClass to call the boolean injectDexIntoClassLoader and only attempt parent loadClass when injection returns true; otherwise it falls back to creating/using an isolated DexClassLoader.
Startup wiring and Class.forName discovery tests
test-app/app/src/main/assets/app/mainpage.js, test-app/app/src/main/assets/app/tests/testClassForNameDiscovery.js
Adds require("./tests/testClassForNameDiscovery") to startup and a new Jasmine test suite with three cases verifying Class.forName resolution of runtime-generated classes (extends, implements) and reflective instantiation behavior via the app class loader.
sequenceDiagram
  participant Client
  participant DexFactory
  participant BaseDexClassLoader
  participant DexClassLoader
  participant DexPathList

  Client->>DexFactory: request resolveClass(generatedName)
  DexFactory->>BaseDexClassLoader: if injectIntoParentClassLoader true -> injectDexIntoClassLoader(jar)
  alt API >= 24
    DexFactory->>BaseDexClassLoader: reflectively call addDexPath(jarFilePath)
  else API < 24
    DexFactory->>DexPathList: build/append dexElements and splice into BaseDexClassLoader
  end
  DexFactory->>DexFactory: injectDexIntoClassLoader returns (true/false)
  alt injection success
    DexFactory->>BaseDexClassLoader: parent.loadClass(generatedName)
  else injection failed
    DexFactory->>DexClassLoader: create isolated DexClassLoader and load class
  end
  DexFactory->>Client: return Class or throw
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

I’m a rabbit with bytes and hops,
I nudge the dex and check the ops,
If addDexPath sings, the classes meet,
If not, a lonely DexClassLoader greets,
Tests munch carrots — discovery complete! 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: registering injected proxy dex with a single class loader, which directly addresses the root cause of the issue.
Linked Issues check ✅ Passed The pull request comprehensively addresses all objectives: fixes the dual-loader registration crash via DexPathList/addDexPath approaches, implements fallback to isolated DexClassLoader, and adds tests for runtime proxy discoverability.
Out of Scope Changes check ✅ Passed All changes directly support the stated objectives: mainpage.js and testClassForNameDiscovery.js add required tests; DexFactory.java implements the core fix for single-owner dex registration.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@edusperoni edusperoni force-pushed the fix/prod-inject-dex branch from 8cfb514 to 03c811d Compare June 11, 2026 19:11

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test-app/runtime/src/main/java/com/tns/DexFactory.java`:
- Around line 409-424: The code wrongly assumes BaseDexClassLoader.addDexPath is
accessible; since it's a hidden non-SDK API its reflective invocation can fail
on Android 28+, so change injectDexIntoClassLoader to avoid calling the hidden
method: check Build.VERSION.SDK_INT and if >= 28 immediately return false (and
log that hidden-API restrictions prevent addDexPath use), remove the
setAccessible(...) attempt and the reflective invoke path for those versions,
and ensure callers of injectDexIntoClassLoader (and any code relying on its true
return) handle the false return (or switch to a supported alternative such as
creating a DexClassLoader and using it instead); reference symbols:
injectDexIntoClassLoader, BaseDexClassLoader.addDexPath, addDexPath.invoke,
setAccessible.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 30a8f9d7-1853-40d4-94d2-61096671615a

📥 Commits

Reviewing files that changed from the base of the PR and between 9b45990 and 8cfb514.

📒 Files selected for processing (3)
  • test-app/app/src/main/assets/app/mainpage.js
  • test-app/app/src/main/assets/app/tests/testClassForNameDiscovery.js
  • test-app/runtime/src/main/java/com/tns/DexFactory.java

Comment thread test-app/runtime/src/main/java/com/tns/DexFactory.java

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
test-app/runtime/src/main/java/com/tns/DexFactory.java (1)

415-420: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Hidden API reflection here can break the Class.forName contract on Android 9+

At Line 417, BaseDexClassLoader.addDexPath is invoked reflectively. If hidden-API enforcement blocks it, Line 426 returns false and resolution falls back to isolated DexClassLoader, which means framework lookups through the app class loader (the behavior this PR targets) can still fail on affected devices.

Is `dalvik.system.BaseDexClassLoader.addDexPath(String)` currently classified as a non-SDK API on Android API 28+ and can reflective invocation from third-party apps be blocked by hidden-API enforcement? Please cite official Android docs/AOSP sources and note behavior differences by API level.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test-app/runtime/src/main/java/com/tns/DexFactory.java` around lines 415 -
420, The reflective call to BaseDexClassLoader.addDexPath (invoked on
targetClassLoader) can be blocked by Android hidden-API enforcement on Android
9+; update the logic to detect and handle that failure explicitly: wrap
addDexPath invocation and catch
IllegalAccessException/InaccessibleObjectException/InvocationTargetException,
and if reflection is blocked or fails on API >= 28, do not silently return false
and fall back to an isolated DexClassLoader — instead construct or choose a
class loader that preserves app-classloader delegation (e.g., PathClassLoader or
a DexClassLoader that uses the app/targetClassLoader as parent) so framework
Class.forName lookups continue to work; ensure this behavior is implemented
where addDexPath, targetClassLoader and the DexClassLoader fallback are managed
in DexFactory.java.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@test-app/runtime/src/main/java/com/tns/DexFactory.java`:
- Around line 415-420: The reflective call to BaseDexClassLoader.addDexPath
(invoked on targetClassLoader) can be blocked by Android hidden-API enforcement
on Android 9+; update the logic to detect and handle that failure explicitly:
wrap addDexPath invocation and catch
IllegalAccessException/InaccessibleObjectException/InvocationTargetException,
and if reflection is blocked or fails on API >= 28, do not silently return false
and fall back to an isolated DexClassLoader — instead construct or choose a
class loader that preserves app-classloader delegation (e.g., PathClassLoader or
a DexClassLoader that uses the app/targetClassLoader as parent) so framework
Class.forName lookups continue to work; ensure this behavior is implemented
where addDexPath, targetClassLoader and the DexClassLoader fallback are managed
in DexFactory.java.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 16be212b-5cb6-43a6-9755-1aace4f86703

📥 Commits

Reviewing files that changed from the base of the PR and between 8cfb514 and 03c811d.

📒 Files selected for processing (3)
  • test-app/app/src/main/assets/app/mainpage.js
  • test-app/app/src/main/assets/app/tests/testClassForNameDiscovery.js
  • test-app/runtime/src/main/java/com/tns/DexFactory.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • test-app/app/src/main/assets/app/mainpage.js

@edusperoni edusperoni force-pushed the fix/prod-inject-dex branch 2 times, most recently from 815dcb3 to 2f12361 Compare June 12, 2026 16:20
Injecting a generated proxy into the app's PathClassLoader by opening it
through a temporary DexClassLoader and splicing its dex element left the
same DexFile claimed by two class loaders. ART rejects this
unconditionally ("Attempt to register dex file ... with multiple class
loaders"), but the second registration only materializes on
non-debuggable builds, so release apps crashed on the first
runtime-generated proxy while debug builds worked.

Build the dex element through the target class loader itself instead, so
the DexFile only ever has one owner: on API 24+ via
BaseDexClassLoader.addDexPath, below that via DexPathList's static
makePathElements/makeDexElements factories spliced into dexElements (the
MultiDex technique). If injection fails, fall back to the isolated
DexClassLoader path (pre-#1951 behavior) instead of failing the
subsequent loadClass with ClassNotFoundException.

Adds tests covering the original FragmentFactory scenario: proxies
generated at runtime (hidden from the static binding generator) must be
resolvable via Class.forName through the app's class loader.

Fixes #1962

Refs #1951
@edusperoni edusperoni force-pushed the fix/prod-inject-dex branch from 2f12361 to 56a78de Compare June 12, 2026 16:25
@NathanWalker NathanWalker merged commit fce8e29 into main Jun 12, 2026
8 checks passed
@NathanWalker NathanWalker deleted the fix/prod-inject-dex branch June 12, 2026 16:44
@adrian-niculescu

Copy link
Copy Markdown
Contributor

I validated this on a real Pixel 6a device with Android 17 (latest beta) and it works now. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DexFactory parent class loader injection (#1951) crashes release builds with "Attempt to register dex file ... with multiple class loaders"

3 participants