Skip to content

[Mono.Android] Keep peers alive during FinishCreateInstance - #13762

Open
simonrozsival wants to merge 4 commits into
mainfrom
simonrozsival-fix-bucket-e-keepalive-constructors
Open

simonrozsival wants to merge 4 commits into
mainfrom
simonrozsival-fix-bucket-e-keepalive-constructors

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Context: #13759
Relates to #13759

Handwritten peer constructors and initializers that call JNIEnv.FinishCreateInstance (Handle, ...) bypass JniPeerMembers.InstanceMethods.FinishCreateInstance and pass a copied raw IntPtr handle with no subsequent use of this. In optimized CoreCLR and NativeAOT builds, the GC can collect or include an unrooted peer in a GC bridge cycle while Java <init> is still running; JavaMarshalGCBridge.TakeWeakGlobalReference deletes the peer's original global reference, causing ART CheckJNI aborts (JNI DETECTED ERROR IN APPLICATION: use of deleted global reference) or undefined behavior.

Keep this alive with GC.KeepAlive (this) after JNIEnv.FinishCreateInstance in the Bucket E initializers from #13759 (and align their adjacent // SAFETY: comments):

  • Android.Widget.ArrayAdapter<T> (all 6 constructors; the 4 array and IList<T> overloads also wrap JNIEnv.DeleteLocalRef and GC.KeepAlive in finally so temporary local references are released if Java construction throws)
  • Android.Widget.BaseAdapter<T> ()
  • Android.Widget.AdapterView<T> (all 3 constructors)
  • Android.Runtime.JavaDictionary () and JavaDictionary<K, V> ()
  • Android.Runtime.JavaSet () (which also provides the active protection for JavaSet<T> () : base (), since JavaSet () initializes Handle; JavaSet<T> () retains GC.KeepAlive (this) defensively)
  • Android.OS.AsyncTask<TParams, TProgress, TResult> ()
  • Java.Lang.Object.SetHandleOnDeserialized

Add a deterministic regression test (AdapterTests.ArrayAdapterConstructorsReleaseLocalRefsOnFailure) warming up lazy state and asserting JniEnvironment.LocalReferenceCount remains unchanged after each throwing ArrayAdapter<T> array/IList<T> constructor (direct and derived).

Validation

Built the Release local SDK and ran Mono.Android.NET-Tests on an API 29 arm64-v8a emulator (emulator-5554, stopped and removed afterward) for both CoreCLR and NativeAOT:

  • make prepare CONFIGURATION=Release MSBUILD_ARGS='-m:4 -nr:false' && make leeroy CONFIGURATION=Release MSBUILD_ARGS='-m:4 -nr:false' — succeeded
  • ./dotnet-local.sh build -t:Install -c Release -p:Device=emulator-5554 -p:RuntimeIdentifier=android-arm64 -m:4 -nr:false 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:Device=emulator-5554 -p:RuntimeIdentifier=android-arm64 --report-trx --results-directory ../../../bin/TestRelease/TestResults (CoreCLR) — 1123 passed, 0 failed, 4 skipped (ArrayAdapterConstructorsReleaseLocalRefsOnFailure passed)
  • Same commands with -p:PublishAot=true (NativeAOT) — 1060 passed, 0 failed, 4 skipped (ArrayAdapterConstructorsReleaseLocalRefsOnFailure passed)

Relates to #13759

Handwritten constructors and initializers that call JNIEnv.FinishCreateInstance (Handle, ...) bypass JniPeerMembers.InstanceMethods.FinishCreateInstance and pass a copied raw Handle with no subsequent use of this. In optimized CoreCLR and NativeAOT builds, the GC bridge can convert and delete the peer's global reference while Java <init> is still executing, triggering ART CheckJNI aborts ('use of deleted global reference').

Keep this alive after JNIEnv.FinishCreateInstance in the handwritten initializers for ArrayAdapter<T>, BaseAdapter<T>, AdapterView<T>, JavaDictionary, JavaDictionary<K, V>, JavaSet, JavaSet<T>, AsyncTask<TParams, TProgress, TResult>, and Java.Lang.Object.SetHandleOnDeserialized. In the four ArrayAdapter<T> array/list overloads, wrap JNIEnv.DeleteLocalRef and the GC.KeepAlive calls in finally so temporary JNI local references are also released when construction throws.

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

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

The constructor-failure tests also pass with the leaking pre-change implementation and need to verify that JNI local-reference counts remain unchanged.

1 open issue
What changed in this PR

This PR addresses the handwritten peer-initialization portion of #13759, keeping managed peers alive while Java constructors run to prevent invalid JNI handles in optimized CoreCLR and NativeAOT builds.

Changes:

  • Add GC.KeepAlive (this) after handwritten FinishCreateInstance calls.
  • Release temporary array/list local references in finally blocks when ArrayAdapter<T> construction fails.
  • Add constructor success, failure, and concurrent garbage-collection tests.
File Description
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Android.Widget/​AdapterTests.cs Adds constructor coverage and concurrent collection stress tests.
src/​Mono.Android/​Java.Lang/​Object.cs Retains the peer during deserialization initialization.
src/​Mono.Android/​Android.Widget/​BaseAdapter.cs Retains the peer during construction.
src/​Mono.Android/​Android.Widget/​ArrayAdapter.cs Retains peers and ensures exception-safe local-reference cleanup.
src/​Mono.Android/​Android.Widget/​AdapterView.cs Retains peers across all three constructors.
src/​Mono.Android/​Android.Runtime/​JavaSet.cs Retains generic and nongeneric set peers during construction.
src/​Mono.Android/​Android.Runtime/​JavaDictionary.cs Retains generic and nongeneric dictionary peers during construction.
src/​Mono.Android/​Android.OS/​AsyncTask.cs Retains the generic task peer during construction.

Review effort: Balanced

simonrozsival and others added 2 commits November 24, 2026 21:35
…eepAlive

- Update SAFETY comments in the touched FinishCreateInstance initializers to reference AllocObject, finally local-ref cleanup, and GC.KeepAlive retention.
- Assert JniEnvironment.LocalReferenceCount in ArrayAdapterConstructorsReleaseLocalRefsOnFailure after warming up lazily-initialized state.
- Exercise derived ArrayAdapter<string> subclass constructors in AdapterTests so both direct and subclass branches are covered.
- Remove the non-deterministic FinishCreateInstanceConstructorsSurviveConcurrentCollection test.

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

@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 concerns missing regression coverage for the four ArrayAdapter<T> exception-path cleanup changes; no implementation defect was identified in the reviewed diff.

The lifetime fix is appropriately scoped: GC.KeepAlive (this) follows the raw-handle constructor calls, existing context/attribute-set retention is preserved, and temporary array/list locals are now released in finally. JNI signatures, exact-type versus derived-type dispatch, and public API shape remain unchanged. The JavaSet base constructor supplies the active guard for JavaSet<T>, consistent with the description. I reviewed all seven full changed source files, the diff, JNI constructor/marshaling helpers, the GC bridge reference replacement, and existing adapter coverage.

CI: All 38 head-commit GitHub checks report success, including the aggregate dotnet-android check linked to Azure build 1698001. Independent Azure build/timeline verification could not be completed: az devops invoke required authentication, and a public build API read was denied by the execution environment. This is a review limitation, not evidence of a CI failure. The CoreCLR/NativeAOT device results in the description are author-reported; I did not rerun device tests in this review.

Generated by Android PR Reviewer for #13762 · copilot · gpt61 · 39.7 AIC · ⌖ 5.15 AIC · ⊞ 21K
Comment /review to run again

Restore ArrayAdapterConstructorsReleaseLocalRefsOnFailure in AdapterTests to verify via JniEnvironment.LocalReferenceCount that each of the four throwing ArrayAdapter<T> array/IList<T> constructors (direct and derived) releases its temporary JNI local reference in finally.

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

Copy link
Copy Markdown

Reviewed the full diff at head 191130b8e9. No issues found — posting a clean check rather than inline comments.

What I verified:

  • ArrayAdapter<T> — all 6 constructors: GC.KeepAlive (this) after FinishCreateInstance in the two context/resource overloads, and in the 4 array/IList<T> overloads the try/finally wraps DeleteLocalRef plus GC.KeepAlive (context) and GC.KeepAlive (this), so the temporary local is released and the peer retained even when Java construction throws. The KeepAlive (this) sits after the exact-type/derived-type if/else, so both branches are covered.
  • AdapterView<T> — all 3 constructors: KeepAlive (this) added after the existing KeepAlive (context) / KeepAlive (attrs).
  • BaseAdapter<T> (), JavaDictionary () / JavaDictionary<K, V> (), JavaSet () / JavaSet<T> (), AsyncTask<TParams, TProgress, TResult> (), and Java.Lang.Object.SetHandleOnDeserialized — each gains KeepAlive (this) after FinishCreateInstance. I checked the if/else placement in JavaDictionary/JavaSet: the KeepAlive is outside the branch, so the derived-type path is covered too. The description's note that JavaSet () supplies the active guard for JavaSet<T> () : base () matches the code.
  • Regression test AdapterTests.ArrayAdapterConstructorsReleaseLocalRefsOnFailure: warms up all 8 throwing cases (4 overloads, direct + DerivedStringArrayAdapter), then asserts JniEnvironment.LocalReferenceCount is unchanged after each. This directly addresses Copilot's earlier flag that the assertions-only version of the test also passed against the leaking pre-change constructors — the count assertion is present in the current diff, so that thread is resolved.
  • Scope: no behavior change beyond the audit — JNI signatures, dispatch, and public API are untouched (plus a drive-by ;; fix in one ArrayAdapter<T> constructor).

I did not re-run the device tests; the CoreCLR (1123 passed) / NativeAOT (1060 passed) results in the description are author-reported.

@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto review

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

Copy link
Copy Markdown
Member

In response to @simonrozsival's request: The changed hunks show the intended lifetime guards and exception cleanup, but my review coverage for 191130b8e9ac3652233dd0d09ce348a61bba2baa is not complete. I still need full constructor/context reads and the JNI creation/local-reference/weak-global implementations, including JNIEnv.FinishCreateInstance, JavaList<T>.ToLocalJniHandle, and JavaMarshalGCBridge.TakeWeakGlobalReference, to check the Mono/CoreCLR and trimming/AOT paths. This is a reviewer coverage gap, not a defect identified in the PR; no tool failure was encountered. The retained hunk checks will be continued next tick.

This branch has not been deployed

No deployments
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