Skip to content

[Java.Interop] Keep peers alive across array, Equals, and ref calls - #13765

Merged
simonrozsival merged 3 commits into
mainfrom
simonrozsival-fix-java-interop-keepalive
Nov 25, 2026
Merged

simonrozsival merged 3 commits into
mainfrom
simonrozsival-fix-java-interop-keepalive

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

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.

Validation

  • dotnet build src/Java.Interop/Java.Interop.csproj -v minimal and -c Release: 0 compiler warnings, 0 errors.
  • make leeroy CONFIGURATION=Release MSBUILD_ARGS='-m:4 -nr:false': succeeded.
  • CoreCLR Release on API 29 arm64 emulator (./dotnet-local.sh build -t:Install -c Release -p:RuntimeIdentifier=android-arm64 -p:Device=emulator-5558 tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj + dotnet test --no-build): 1122 passed, 0 failed, 4 skipped.
  • NativeAOT Release on API 29 arm64 emulator (-p:PublishAot=true, confirmed NativeAOT via NativeAotStartupOffsetMatchesDevice passing): 1059 passed, 0 failed, 4 skipped.

Context: #13758
Relates to #13759

On CoreCLR and NativeAOT, optimized builds track managed object liveness per instruction rather than to method or lexical-scope end. Once a JNI handle is read from PeerReference into a value type, the GC bridge can convert the peer's global reference to a weak global reference and delete the old global reference before JNI finishes using the copied handle.

Retain the managed peer across the remaining Bucket A Java.Interop JNI calls (item #1 FinishCreateInstance is already covered by #13758):

  * Retain the owning Java<T>Array on Jni<T>ArrayElements across all 8 primitive array types, keep the owner alive in Synchronize via finally, clear it on non-Commit release, and update the constructor <safety> contract (fixes GetElements, IndexOf, and Clear).
  * Add GC.KeepAlive (this) to Java<T>Array.CopyTo and CopyFrom, JavaArray<T>.Length, and JavaObjectArray<T>.GetElementAt, SetElementAt, and Clear.
  * Add GC.KeepAlive (this) and GC.KeepAlive (o) after JniEnvironment.Types.IsSameObject in JavaObject.Equals and JavaException.Equals.
  * Read value.PeerReference once and call GC.KeepAlive (value) in JniEnvironment.References.NewReturnToJniRef (IJavaPeerable).
  * Add JniArrayElementsTests.GetElements_RetainsOwnerUntilReleased to verify JniInt32ArrayElements roots its owning JavaInt32Array across GC bridge rounds and CopyToJava (Commit), then allows collection after Dispose.

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

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.

🟡 Changes recommended

After Release(Commit), the cleared elements pointer makes Dispose() a no-op while the owner reference remains set, keeping the Java array alive; this needs a fix and regression coverage.

1 open issue
What changed in this PR

This PR continues the peer-lifetime fixes tracked in #13759, following #13758. It keeps managed Java peers reachable while JNI uses their handles, addressing premature collection in optimized CoreCLR and NativeAOT builds.

Changes:

  • Retain primitive-array owners until final release across all eight generated array types.
  • Add lifetime protection to array operations, identity comparisons, and return-to-JNI reference creation.
  • Add a regression test covering owner retention through Commit and collection after disposal.
File Description
tests/​Mono.Android-Tests/​Java.Interop-Tests/​Java.Interop/​JavaInt32ArrayContractTests.cs Tests array-owner retention and collection after disposal.
src/​Java.Interop/​Java.Interop/​JniEnvironment.References.cs Reads the peer reference once and retains its owner during conversion.
src/​Java.Interop/​Java.Interop/​JavaPrimitiveArrays.tt Updates the template with owner retention and copy-operation lifetime protection.
src/​Java.Interop/​Java.Interop/​JavaPrimitiveArrays.cs Applies the template changes to all eight primitive types.
src/​Java.Interop/​Java.Interop/​JavaObjectArray.cs Retains the array during element reads, writes, and clearing.
src/​Java.Interop/​Java.Interop/​JavaObject.cs Retains both peers during JNI identity comparison.
src/​Java.Interop/​Java.Interop/​JavaException.cs Applies the same lifetime protection to exception equality.
src/​Java.Interop/​Java.Interop/​JavaArray.cs Retains the array while querying its length.

Review effort: Balanced

Move the owning IJavaPeerable field onto the JniArrayElements base class so
CopyToJava and Release share a single KeepAlive implementation and Release
always clears owner (including Release(Commit)) after Synchronize succeeds.
Make the constructor owner parameter non-nullable with ThrowIfNull, compute
GetArrayLength before Get<T>ArrayElements in GetElements to avoid leaking
the acquired buffer on throw, and use straight-line GC.KeepAlive (this) in
JavaObjectArray<T>.Clear.

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 #13765

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

⚠️ Needs Changes

Findings: 0 errors · 1 warning · 0 suggestions. The inline warning requests focused regression coverage for the new array-owner retention guarantee; I found no additional correctness defect introduced by this diff.

Reviewed all seven changed files in full, the primitive-array template and generated implementations, relevant callers, project configuration, GC-bridge reference conversion, existing lifetime tests, and the resolved review thread. The changes consistently retain both operands for equality checks, retain wrappers across raw-handle JNI calls, and move the length query before buffer acquisition. Centralizing ownership in JniArrayElements covers all eight primitive types, with matching template updates and exception-safe retention during synchronization. The previously reported retained-owner issue is addressed by clearing the owner after successful terminal release.

CI: All 38 checks returned for the current PR head report success, including the aggregate dotnet-android check for Azure build 1697961. The direct Azure build query failed because authentication is required, so I could not independently verify its timeline or non-gating device-test results. The PR reports successful local Release builds and CoreCLR/NativeAOT device runs; I did not rerun them in this review. Linked issues #13758/#13759 could not both be reconciled with their full issue context because the configured GitHub read tools do not expose issue reads; this assessment is scoped to the submitted diff and available PR context.

Generated by Android PR Reviewer for #13765 · copilot · gpt61 · 48.2 AIC · ⌖ 4.39 AIC · ⊞ 21K
Comment /review to run again

@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto review

@PeppersMuse

Copy link
Copy Markdown

Reviewed as part of the #13759 Bucket A audit. I checked the full diff against the audit items and found the placements correct — no issues to raise:

  • JniArrayElements now roots its owning array (owner field, null-checked in the ctor) across all 8 primitive types, with the template and generated code in sync; CopyToJava keeps the owner alive via finally, and Release keeps it alive via finally while clearing it only after a successful release — including Release (Commit), which is correct since Release is terminal (elements is nulled regardless of mode), so retaining the owner after Commit would only root the array pointlessly. GetElements now reads PeerReference once and computes the length before acquiring the native buffer, so a throwing length check can't leak the buffer.
  • GC.KeepAlive (this) verified after Get<T>ArrayRegion/Set<T>ArrayRegion in all 8 CopyTo/CopyFrom pairs, in JavaArray<T>.Length, and in JavaObjectArray<T>.GetElementAt/SetElementAt/Clear (the last two in finally/after the loop, covering all iterations).
  • JavaObject.Equals and JavaException.Equals retain both this and o across IsSameObject; NewReturnToJniRef (IJavaPeerable) reads PeerReference once and retains value.
  • Copilot's Commit-retention thread reads as addressed by the change above. No regression test was added; the stated reason (GC-timing assertions are non-deterministic/flaky) is consistent with the testing guidance in [copilot] Add JNI peer lifetime (GC.KeepAlive) guidelines #13766, so I'm not re-raising that here.

@simonrozsival
simonrozsival enabled auto-merge (squash) November 25, 2026 18:54

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

The JNI peer lifetime fixes consistently keep wrappers alive through native access, and JniArrayElements now retains and releases its owner with the elements lifetime. The primitive-array template and generated implementations agree for all eight types; the changed internal constructors have no other callers in the pinned friend assembly. No blocking issues found, including after checking the current target-branch integration.

@simonrozsival
simonrozsival merged commit 34ab19a into main Nov 25, 2026
38 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-fix-java-interop-keepalive branch November 25, 2026 19:06
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