Repository navigation
[Java.Interop] Keep peer alive during FinishCreateInstance - #13758
Conversation
Context: #13757 Keep self reachable through the nonvirtual JNI constructor call, including exceptional exits, so the GC/bridge cannot delete its global reference while the call is in progress. Validation: dotnet build src/Java.Interop/Java.Interop.csproj -v minimal passed with 0 errors and 4 Git/SourceLink metadata warnings. Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
🟢 Approval recommended
No active review issues are identified for the change protecting managed peer lifetime during Java constructor invocation.
No open issues 🎉
What changed in this PR
This PR protects managed peer lifetime during Java constructor invocation in Java.Interop, addressing a potential deleted-global-reference race observed during the #13757 investigation.
Changes:
- Wraps the constructor call in
try/finallyand callsGC.KeepAlive (self), including when the constructor throws. - Updates the safety comment while leaving caller-owned JNI argument lifetimes unchanged.
| File | Description |
|---|---|
src/Java.Interop/Java.Interop/JniPeerMembers.JniInstanceMethods.cs |
Keeps the managed peer alive throughout FinishCreateInstance’s JNI constructor call. |
Review effort: Balanced
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
✅ LGTM on code correctness — 0 errors, 0 warnings, 1 non-blocking testing suggestion inline.
The try/finally keeps the managed receiver reachable through the nonvirtual constructor call and exception propagation, matching the existing InvokeNonvirtualVoidMethod pattern. Constructor lookup, dispatch, public signatures, and caller-owned argument lifetimes remain unchanged. I found no correctness regression in the full changed file or the inspected callers and sibling wrappers. The description appropriately distinguishes the suspected race from a proven explanation of the stress crash.
CI: All 39 GitHub check runs succeeded, including the aggregate dotnet-android check for Azure build 1697757. Independent Azure build/timeline verification was blocked because az devops invoke required authentication; no claim is made about non-gating device-test results. This was a source review; I did not rerun the build or device tests.
Generated by Android PR Reviewer for #13758 · copilot · gpt61 · 25.5 AIC · ⌖ 4.84 AIC · ⊞ 21K
Comment /review to run again
…uidelines Address review feedback on #13766: JniPeerMembers.InstanceMethods.FinishCreateInstance does not yet retain self on main (pending #13758), so require explicit GC.KeepAlive (this) for handwritten JNIEnv.FinishCreateInstance calls rather than suggesting migration to JniPeerMembers as sufficient today. Co-authored-by: Copilot App <[email protected]>
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]>
Remove one-off method, PR, and test-file specifics (Get*ArrayElements, Release(Commit), Synchronize, #13758, NormalMethods.cs, unregistered Keep peers, 180-col restatement) so the JNI peer-lifetime guidelines express durable, general principles while staying 41% shorter than before compression. Co-authored-by: Copilot App <[email protected]>
|
@dalexsoto review |
|
Reviewed this as part of the #13759 audit series. This one is clean — what I checked:
No correctness issues found. All CI checks on this head are green. |
dalexsoto
left a comment
There was a problem hiding this comment.
Reviewed the complete FinishCreateInstance change and its lifetime, exception, ownership and integration paths. The try/finally GC.KeepAlive pattern protects the peer through the native constructor call; no blocking issues found.
… checklist Address review feedback on #13766: - Note that single-read PeerReference + GC.KeepAlive protects against early GC collection, not concurrent Dispose () (which still requires synchronization or a caller contract). - Reflect that JniPeerMembers.InstanceMethods.FinishCreateInstance now retains self on main (merged in #13758, commit 71f0c51). Co-authored-by: Copilot App <[email protected]>
…13765) Context: #13758 Relates to #13759 In optimized CoreCLR and NativeAOT builds, managed object liveness is tracked per instruction rather than to method or lexical-scope end. Once `PeerReference` is copied into a `JniObjectReference` value, nothing keeps the managed peer reachable; a GC bridge cycle (`JavaMarshalGCBridge.TakeWeakGlobalReference`) can convert and delete the peer's global reference before JNI finishes using the copied handle, leading to ART CheckJNI `use of deleted global reference` aborts. Retain the owning managed peers across the remaining Bucket A `Java.Interop` call sites from #13759 (Bucket A item #1, `JniPeerMembers.JniInstanceMethods.FinishCreateInstance`, is tracked in open PR #13758; Bucket A will be complete once both PRs land): * Retain the owning `IJavaPeerable` on the `JniArrayElements` base class (non-nullable constructor parameter checked with `ArgumentNullException.ThrowIfNull`), keep it alive in `CopyToJava` and `Release` via `finally`, clear it once `Release` succeeds (including `Release (Commit)`), and update the constructor `<safety>` contracts in `JavaArray.cs` and `JavaPrimitiveArrays.tt` / `JavaPrimitiveArrays.cs`. Compute `GetArrayLength` before `Get<T>ArrayElements` in `Java<T>Array.GetElements` so a throwing length check cannot leak the acquired native buffer. This fixes `GetElements`, `IndexOf`, and `Clear` across all 8 primitive array types as well as external `GetElements ()` callers. * Keep `this` alive across `Get<T>ArrayRegion` / `Set<T>ArrayRegion` in `Java<T>Array.CopyTo` and `CopyFrom`, across `GetArrayLength` in `JavaArray<T>.Length`, and across `GetObjectArrayElement` / `SetObjectArrayElement` in `JavaObjectArray<T>.GetElementAt`, `SetElementAt`, and `Clear`. * Keep both `this` and `o` alive across `JniEnvironment.Types.IsSameObject` in `JavaObject.Equals (object?)` and `JavaException.Equals (object?)`. * Read `value.PeerReference` once and keep `value` alive in `JniEnvironment.References.NewReturnToJniRef (IJavaPeerable)`. No GC-timing or early-collection retention regression test is added, as such tests are inherently timing-sensitive/flaky.
Context: #13757
FinishCreateInstancereadsself.PeerReferencebefore calling the nonvirtual Java constructor, but does not keep the managed peer reachable during that call. The GC/bridge can finalize or collect the peer and delete its global reference while JNI is still using it.Keep
selfalive in afinallyblock around the constructor call, including when the call throws. Caller-owned JNI argument lifetimes remain unchanged.Stress testing in the investigation for #13757, with four background threads allocating Java objects, hit one intermittent
JNI DETECTED ERROR IN APPLICATION: use of deleted global referencecrash on CoreCLR before the fix. An excerpt of the crash log was preserved, but the complete logcat was not saved and it does not establish that the crash occurred inFinishCreateInstance. There is no deterministic regression test.Validation
dotnet build src/Java.Interop/Java.Interop.csproj -v minimalpassed in this branch with 0 errors and 4 Git/SourceLink metadata warnings.The #13757 investigation reported the following results with a local Release SDK on an arm64 API 29 emulator and this fix combined with that PR's test changes; these device runs were not repeated on this isolated branch:
Mono.Android.NET-Testssuite: CoreCLR 1125 passed, 1 skipped, 0 failed; NativeAOT 1061 passed, 2 skipped, 0 failed.The stress harness was temporary and is not included. These results do not establish deterministic reproduction or coverage of the race.