Repository navigation
[Mono.Android] Keep JNI peer owners alive in trimmable runtime paths - #13761
Conversation
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]>
There was a problem hiding this comment.
🟢 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]>
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
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
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
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]>
|
@dalexsoto review |
|
Reviewed this as part of the #13759 audit series (Bucket B, items #12–#15). The four audited placements are correct — what I verified:
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
left a comment
There was a problem hiding this comment.
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.
Context: #13759
Context: #12315
Context: #12754
Relates to #13759
On CoreCLR and NativeAOT,
JniObjectReferencecarries only a raw JNI handle and does not root its owning managed peer. In optimized builds, once.PeerReferenceis 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 inJavaMarshalGCBridge.TakeWeakGlobalReference(or finalize the peer outright) before the native JNI call completes, causing ART CheckJNI to abort withJNI DETECTED ERROR IN APPLICATION: use of deleted global reference.Retain the owning managed peer with
GC.KeepAliveacross the JNI call in theMono.Androidruntime and trimmable typemap sites (Bucket B, items #12–#15 of #13759):TrimmableTypeMapValueManager.CreateLocalObjectReferenceArgumentCore(IJavaPeerablebranch): readpeerable.PeerReferenceonce into a local, callNewLocalRef (), and callGC.KeepAlive (peerable).TrimmableTypeMapValueManager.CreateLocalObjectReferenceArgumentCore(TrimmableJavaProxyObjectbranch): storeproxy.PeerReference.NewLocalRef (), callGC.KeepAlive (proxy)so theConditionalWeakTableproxy stays rooted through the JNI call, and return the local ref.PrimitiveArrayInfo.Handler<T, TArray>.TryCreateObjectReference: readPeerReferenceonce into a local before checkingIsValidand callingNewLocalRef ()in both theTArrayandmarshaledArraybranches, and callGC.KeepAlive (array)in theTArraybranch.JavaMarshalRegisteredPeers.ReconcilePeerandAddPeer: callGC.KeepAlive (target)right afterJniEnvironment.Types.IsSameObjectbefore returningPeerReconciliationResult.NoMatch, and callGC.KeepAlive (value)on thePeerReconciliationResult.Keepbranch inAddPeerso an unregistered peer stays live throughIsSameObjectandWarnNotReplacing.Validation
Built the Release SDK locally and ran
Mono.Android.NET-Testson a dedicated API 29arm64-v8aAndroid 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.csprojand../../../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.csprojand../../../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).