Skip to content

[Mono.Android] Keep JNI peer owners alive in trimmable runtime paths - #13761

Merged
simonrozsival merged 2 commits into
mainfrom
simonrozsival-fix-bucket-b-keepalive-runtime
Nov 25, 2026
Merged

simonrozsival merged 2 commits into
mainfrom
simonrozsival-fix-bucket-b-keepalive-runtime

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Context: #13759
Context: #12315
Context: #12754
Relates to #13759

On CoreCLR and NativeAOT, JniObjectReference carries only a raw JNI handle and does not root its owning managed peer. In optimized builds, once .PeerReference is copied into a local or argument without a subsequent use of the peer, a GC bridge round can convert and delete the peer's global reference in JavaMarshalGCBridge.TakeWeakGlobalReference (or finalize the peer outright) before the native JNI call completes, causing ART CheckJNI to abort with JNI DETECTED ERROR IN APPLICATION: use of deleted global reference.

Retain the owning managed peer with GC.KeepAlive across the JNI call in the Mono.Android runtime and trimmable typemap sites (Bucket B, items #12–#15 of #13759):

  • TrimmableTypeMapValueManager.CreateLocalObjectReferenceArgumentCore (IJavaPeerable branch): read peerable.PeerReference once into a local, call NewLocalRef (), and call GC.KeepAlive (peerable).
  • TrimmableTypeMapValueManager.CreateLocalObjectReferenceArgumentCore (TrimmableJavaProxyObject branch): store proxy.PeerReference.NewLocalRef (), call GC.KeepAlive (proxy) so the ConditionalWeakTable proxy stays rooted through the JNI call, and return the local ref.
  • PrimitiveArrayInfo.Handler<T, TArray>.TryCreateObjectReference: read PeerReference once into a local before checking IsValid and calling NewLocalRef () in both the TArray and marshaledArray branches, and call GC.KeepAlive (array) in the TArray branch.
  • JavaMarshalRegisteredPeers.ReconcilePeer and AddPeer: call GC.KeepAlive (target) right after JniEnvironment.Types.IsSameObject before returning PeerReconciliationResult.NoMatch, and call GC.KeepAlive (value) on the PeerReconciliationResult.Keep branch in AddPeer so an unregistered peer stays live through IsSameObject and WarnNotReplacing.

Validation

Built the Release SDK locally and ran Mono.Android.NET-Tests on a dedicated API 29 arm64-v8a Android emulator (emulator-5556, subsequently stopped and removed) for both CoreCLR and NativeAOT:

  • make leeroy CONFIGURATION=Release MSBUILD_ARGS='-m:4' — succeeded (0 errors).
  • ./dotnet-local.sh build -t:Install -c Release -p:RuntimeIdentifier=android-arm64 -p:Device=emulator-5556 -m:4 tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj and ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Release -p:RuntimeIdentifier=android-arm64 -p:Device=emulator-5556 --report-trx --results-directory ../../../bin/TestRelease/TestResults-Rev (CoreCLR) — passed: 1126 total, 1122 succeeded, 0 failed, 4 skipped (14.8s).
  • ./dotnet-local.sh build -t:Install -c Release -p:PublishAot=true -p:RuntimeIdentifier=android-arm64 -p:Device=emulator-5556 -m:4 tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj and ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Release -p:PublishAot=true -p:RuntimeIdentifier=android-arm64 -p:Device=emulator-5556 --report-trx --results-directory ../../../bin/TestRelease/TestResults-Rev-NativeAOT (NativeAOT) — passed: 1063 total, 1059 succeeded, 0 failed, 4 skipped (5.4s).

Context: #13759
Relates to #13759

On CoreCLR and NativeAOT, copying a peer's PeerReference does not retain
its managed owner. In optimized builds, if no subsequent use keeps the
peer rooted while a native JNI call uses the copied handle, a GC bridge
round can convert and delete the peer's global reference in
JavaMarshalGCBridge.TakeWeakGlobalReference (or finalize the peer
outright), causing JNI to observe a deleted global reference.

Retain the owning managed peer with GC.KeepAlive across the JNI call in
the four Mono.Android runtime and trimmable typemap sites (Bucket B):

  * TrimmableTypeMapValueManager.CreateLocalObjectReferenceArgumentCore
    (IJavaPeerable branch): read PeerReference once into a local, call
    NewLocalRef (), and call GC.KeepAlive (peerable).
  * TrimmableTypeMapValueManager.CreateLocalObjectReferenceArgumentCore
    (TrimmableJavaProxyObject branch): retain proxy with
    GC.KeepAlive (proxy) after NewLocalRef () so the ConditionalWeakTable
    entry cannot be collected before the local ref is created.
  * PrimitiveArrayInfo.Handler<T, TArray>.TryCreateObjectReference
    (TArray branch): read array.PeerReference once, call NewLocalRef (),
    and call GC.KeepAlive (array).
  * JavaMarshalRegisteredPeers.ReconcilePeer: call GC.KeepAlive (target)
    immediately after IsSameObject before returning NoMatch, keeping
    retention explicit on all reconciliation paths.

Co-authored-by: Copilot App <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 20:01

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues are reported for the JNI peer-lifetime changes in the trimmable runtime paths.

No open issues 🎉

What changed in this PR

This PR extends the JNI peer-lifetime fixes tracked in #13759 to Mono.Android’s trimmable runtime paths, keeping managed owners alive until JNI finishes using their borrowed handles.

Changes:

  • Retain peer and proxy owners while creating local JNI references.
  • Retain primitive-array wrappers while creating local references.
  • Keep the registered peer alive through the JNI identity comparison, including the no-match path.
File Description
src/​Mono.Android/​Microsoft.Android.Runtime/​TrimmableTypeMapValueManager.cs Keeps peer and proxy owners alive during local-reference creation.
src/​Mono.Android/​Microsoft.Android.Runtime/​PrimitiveArrayInfo.cs Keeps primitive-array owners alive during local-reference creation.
src/​Mono.Android/​Microsoft.Android.Runtime/​JavaMarshalRegisteredPeers.cs Keeps the registered peer alive through the identity comparison.

Review effort: Balanced

…erence

Address code review feedback on #13761:

  * JavaMarshalRegisteredPeers.AddPeer: call GC.KeepAlive (value) on the
    PeerReconciliationResult.Keep branch so an unregistered peer's
    finalizer cannot run while ReconcilePeer compares or logs its
    PeerReference.
  * PrimitiveArrayInfo.Handler<T, TArray>.TryCreateObjectReference: cache
    marshaledArray.PeerReference once in a local before checking IsValid
    and calling NewLocalRef (), matching the TArray branch above it.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13761

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review complete — no blocking code findings; CI verification limited.

Reviewed all three full source files, the JNI reference/control-block implementation, GC bridge transitions, value-manager entry point, and relevant existing tests. The change correctly retains the owning peer through NewLocalRef and the nonmatching IsSameObject path. The AddPeer keep branch also retains the incoming peer through reconciliation/logging; replacement and insertion already use it to create the tracking handle. The copied-array branch remains rooted by its existing finally disposal. Reference ownership, invalid-reference behavior, and peer replacement semantics are preserved, with no new reflection or API-surface changes.

Findings: 0 ❌ errors, 0 ⚠️ warnings, 1 💡 inline suggestion for targeted optimized-build lifetime regression coverage.

CI: All 38 returned GitHub checks completed successfully, including dotnet-android and license/cla, for head 412f13d1e65a3fcf778a78060774a58ee88135a8. Independent Azure build-result/timeline verification for build 1697960 was blocked: az devops invoke required authentication, and the public HTTP read was denied by the execution environment. I am therefore not declaring fully verified green CI or unconditional LGTM. The Release CoreCLR/NativeAOT device-suite passes in the description are author-reported; I did not rerun device tests during this review. Linked issue bodies were unavailable through the configured GitHub read tools.

The patch is focused and uses the existing lifetime-management pattern without introducing additional synchronization or ownership machinery.

Generated by Android PR Reviewer for #13761 · copilot · gpt61 · 31.8 AIC · ⌖ 4.42 AIC · ⊞ 21K
Comment /review to run again

simonrozsival added a commit that referenced this pull request Nov 25, 2026
Fold learnings from the #13759 PR reviews (#13758, #13761-#13766) into the JNI peer-lifetime instructions and review rules, and cut added word count by 45% (1,366 -> 750 words) without losing technical precision:

- Cover terminal Release clearing (including Release(Commit)) and avoiding throwing calls between native acquisition (Get*ArrayElements) and wrapper construction.
- Cover all reconciliation branches (including unregistered Keep peers), WeakReference IsAlive/Target split races, GC.KeepAlive placement before error checks/conversions, and // SAFETY: contract preservation + 180-col line limit.
- Emphasize warmed-up JniEnvironment.LocalReferenceCount leak checks and generator expected-output assertions over non-deterministic GC-timing tests.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto review

@PeppersMuse

Copy link
Copy Markdown

Reviewed this as part of the #13759 audit series (Bucket B, items #12–#15). The four audited placements are correct — what I verified:

  • TrimmableTypeMapValueManager.CreateLocalObjectReferenceArgumentCore, IJavaPeerable branch: peerable.PeerReference is read once into a local, NewLocalRef () is called on the copy, and GC.KeepAlive (peerable) follows — the peer stays live through the JNI call.
  • Same method, TrimmableJavaProxyObject branch: the local ref is stored first and GC.KeepAlive (proxy) follows, so the ConditionalWeakTable proxy (and value via proxy.Value) stays rooted through the call.
  • PrimitiveArrayInfo.Handler<T, TArray>.TryCreateObjectReference, TArray branch: single read of array.PeerReference into a local plus GC.KeepAlive (array) after NewLocalRef (). The marshaledArray branch below it needs no added call — it is already rooted by the finally { marshaledArray.Dispose (); }.
  • JavaMarshalRegisteredPeers.ReconcilePeer / AddPeer: GC.KeepAlive (target) immediately after IsSameObject covers the NoMatch path (and the Replace/Keep paths keep their existing KeepAlive (target) calls); AddPeer also keeps value alive on the Keep branch, and on the Replace/fall-through paths value is used afterwards to build the tracking handle.

One follow-up in the same file, same pattern, but not in this PR's diff and not listed in #13759 items #12–#15 — flagging for a follow-up item rather than this PR:

Also considered Copilot's / the agentic reviewer's testing suggestions (a Release-mode lifetime regression test for these branches): non-blocking, per the author's reply — JIT liveness and concurrent GC/bridge timing can't be enforced deterministically without flakiness, and this is being documented as a testing guideline in #13766. Existing conversion tests cover functional correctness on both CoreCLR and NativeAOT.

No blocking issues in the diff itself. All CI checks on this head are green.

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed all three changed files and the JNI reference/GC bridge integration. The KeepAlive calls cover the raw-handle use windows while preserving local-reference ownership, branch disposal, locking and trimming/AOT behavior. No blocking issues found in this static review. The unchanged PeekPeer follow-up is outside this revision.

@simonrozsival
simonrozsival merged commit 73aa2b0 into main Nov 25, 2026
38 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-fix-bucket-b-keepalive-runtime branch November 25, 2026 18:52
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.

4 participants