Skip to content

[Java.Interop] Keep peer alive during FinishCreateInstance - #13758

Merged
simonrozsival merged 1 commit into
mainfrom
simonrozsival-finish-create-instance-keepalive
Nov 25, 2026
Merged

simonrozsival merged 1 commit into
mainfrom
simonrozsival-finish-create-instance-keepalive

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Context: #13757

FinishCreateInstance reads self.PeerReference before 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 self alive in a finally block 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 reference crash 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 in FinishCreateInstance. There is no deterministic regression test.

Validation

dotnet build src/Java.Interop/Java.Interop.csproj -v minimal passed 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:

  • Stress harness: 0 crashes across three CoreCLR runs (600 rounds total) and one NativeAOT run (200 rounds).
  • Full Mono.Android.NET-Tests suite: 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.

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]>

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 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/finally and calls GC.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

@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13758

@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.

✅ 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

simonrozsival added a commit that referenced this pull request Nov 25, 2026
…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]>
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 added a commit that referenced this pull request Nov 25, 2026
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]>
@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto review

@PeppersMuse

Copy link
Copy Markdown

Reviewed this as part of the #13759 audit series. This one is clean — what I checked:

  • FinishCreateInstance (src/Java.Interop/Java.Interop/JniPeerMembers.JniInstanceMethods.cs): the try/finally with GC.KeepAlive (self) keeps the peer reachable through the whole CallNonvirtualVoidMethod call, including the throwing path — self.PeerReference is read inside the try, and the finally runs on exception propagation too. Constructor lookup, dispatch, signatures, and caller-owned argument lifetimes are unchanged, and the updated safety comment accurately describes the new guarantee.
  • Sibling paths in the same file: StartCreateInstance only allocates a fresh peer via AllocObject (no existing peer handle is read into a JNI call), and no other method in this file passes a peer handle to JNI — so there is no missed sibling here.
  • Copilot's inline testing suggestion (a focused device regression test for receiver reachability, covering returning and throwing constructors): I agree it's non-blocking. As the author replied, JIT liveness and concurrent GC/bridge timing can't be enforced deterministically in a test without flakiness, and the description is appropriately honest that the stress-test crash is suspected, not proven, to be this site.

No correctness issues found. 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 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.

@simonrozsival
simonrozsival merged commit 71f0c51 into main Nov 25, 2026
39 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-finish-create-instance-keepalive branch November 25, 2026 18:47
simonrozsival added a commit that referenced this pull request Nov 25, 2026
… 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]>
simonrozsival added a commit that referenced this pull request Nov 25, 2026
…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.
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