Skip to content

[Mono.Android] Keep peers alive in handwritten bindings - #13764

Merged
simonrozsival merged 4 commits into
mainfrom
simonrozsival-fix-bindings-keepalive-bucket-d
Nov 25, 2026
Merged

simonrozsival merged 4 commits into
mainfrom
simonrozsival-fix-bindings-keepalive-bucket-d

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Context: #13759
Relates to #13759

In optimized CoreCLR and NativeAOT builds, managed object liveness is tracked per instruction rather than to the end of a method. When a handwritten binding copies Handle into an IntPtr and passes it to JNI or NDK P/Invokes without retaining this, the managed peer can enter a GC bridge cycle while native code is still using the handle. JavaMarshalGCBridge.TakeWeakGlobalReference deletes the existing global reference, causing ART CheckJNI to abort with JNI DETECTED ERROR IN APPLICATION: use of deleted global reference.

Additionally, ActionBar.Tab.Dispatcher, Animator.Dispatcher, and TextView's text-change event accessors (AfterTextChanged, BeforeTextChanged, TextChanged) previously stored newly constructed event dispatchers/watchers only inside a WeakReference before registering the listener and reading Target!, allowing GC to collect the peer mid-initialization and throw NullReferenceException.

Changes (Bucket D, items #21–#29)

  • Retain this via GC.KeepAlive (this) after JNIEnv.AndroidBitmap_* calls in Android.Graphics.Bitmap (GetBitmapInfo, LockPixels, UnlockPixels), after JNIEnv.GetCharSequence in Java.Lang.String.ToString, after JNIEnv.GetDirectBufferAddress in Java.Nio.Buffer.GetDirectBufferAddress, and after JNIEnv.FinishCreateInstance in AnimatorEventDispatcher and TabEventDispatcher constructors, updating adjacent // SAFETY: comments.
  • Retain this in the existing finally blocks of all 7 GetAs* and 7 Put overloads in Android.Content.ContentValues, in Android.App.Notification.Vibrate setter's finally block (with straight-line GC.KeepAlive (this) in the getter), and in Android.OS.AsyncTask<TParams, TProgress, TResult>.Execute (plus straight-line GC.KeepAlive (this) after JNIEnv.CallObjectMethod in GetResult).
  • Retain this outside JavaConvert.WithLocalJniHandle lambdas and after JNIEnv.CallNonvirtualObjectMethod in all 7 handwritten methods of Android.Util.SparseArray<E> (Append, Get, IndexOfValue, Put, SetValueAt, ValueAt) and in Add, GetItem, GetPosition, Insert, and Remove of Android.Widget.ArrayAdapter<T> (matching Sort). Constructors in ArrayAdapter<T> and AsyncTask<,,> are intentionally left untouched for Bucket E.
  • Fix the WeakReference GC race in ActionBar.Tab.Dispatcher, Animator.Dispatcher, and TextView (AfterTextChanged, BeforeTextChanged, TextChanged) by holding the dispatcher/watcher in a strong local across WeakReference creation, listener registration, and use.

Validation

Built the local Release SDK (make leeroy CONFIGURATION=Release MSBUILD_ARGS='-m:4') and ran the existing Mono.Android.NET-Tests suite in Release (CoreCLR) on a dedicated API 29 arm64-v8a emulator (emulator-5560, now stopped and removed), then verified Mono.Android.NET-Tests.csproj builds cleanly after dropping the redundant smoke tests:

  • ./dotnet-local.sh build -t:Install -c Release -p:Device=emulator-5560 tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj + dotnet test --no-build: existing runtime tests passed (0 failed, 4 pre-existing skips)
  • ./dotnet-local.sh build -c Release tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -v minimal: succeeded (0 errors)

Context: #13759
Relates to #13759

In optimized CoreCLR and NativeAOT builds, the JIT/AOT compiler tracks managed
object liveness per instruction. Once a handwritten binding extracts `Handle`
into an `IntPtr` and passes it to JNI or NDK P/Invokes without retaining `this`,
the managed peer can enter a GC bridge cycle, causing `JavaMarshalGCBridge` to
delete the global reference while native code is still using it (`JNI DETECTED
ERROR IN APPLICATION: use of deleted global reference`).

Keep `this` alive across raw JNI/NDK calls in the Bucket D handwritten bindings
and fix the `WeakReference` GC race in event dispatchers:

  * Retain `this` with `GC.KeepAlive (this)` after `JNIEnv.AndroidBitmap_*`
    calls in `Android.Graphics.Bitmap` (`GetBitmapInfo`, `LockPixels`,
    `UnlockPixels`), after `JNIEnv.GetCharSequence` in `Java.Lang.String.ToString`,
    and after `JNIEnv.GetDirectBufferAddress` in `Java.Nio.Buffer.GetDirectBufferAddress`.
  * Retain `this` in the existing `finally` blocks of all 7 `GetAs*` and 7 `Put`
    overloads in `Android.Content.ContentValues`, in `Android.App.Notification.Vibrate`
    getter and setter `finally` blocks, and in `Android.OS.AsyncTask<,,>.Execute`
    (plus after `JNIEnv.CallObjectMethod` in `GetResult`).
  * Retain `this` outside `JavaConvert.WithLocalJniHandle` lambdas and after
    `JNIEnv.CallNonvirtualObjectMethod` in all 7 handwritten methods of
    `Android.Util.SparseArray<E>` and in `Add`, `GetItem`, `GetPosition`,
    `Insert`, and `Remove` of `Android.Widget.ArrayAdapter<T>`.
  * Fix the `WeakReference` race in `ActionBar.Tab.Dispatcher` and
    `Animator.Dispatcher` by holding the dispatcher in a strong local across
    `WeakReference` creation, listener registration, and return.
  * Add concurrent-GC on-device regression tests in
    `HandwrittenBindingLifetimeTests`.

Co-authored-by: Copilot App <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 20:09
Drop the concurrent-GC stress tests from Mono.Android.NET-Tests to avoid
introducing probabilistic GC-loop tests that risk CI flakiness.

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.

🔵 Needs a closer look

The regression tests keep receivers reachable during most changed calls, leaving the lifetime bug untested for those overloads; each needs a final-managed-use case validated in an optimized build.

No open issues 🎉

What changed in this PR

This PR addresses the handwritten-binding portion of #13759, keeping managed peers alive while JNI and native calls use their handles in optimized CoreCLR and NativeAOT builds.

Changes:

  • Add receiver retention across handwritten binding calls and update safety comments.
  • Keep event dispatchers strongly referenced during listener registration and return.
  • Add concurrent-GC device tests and include them in the test project.
File Description
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Mono.Android.NET-Tests.csproj Includes the new lifetime tests.
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Android.Runtime/​HandwrittenBindingLifetimeTests.cs Adds concurrent-GC binding tests.
src/​Mono.Android/​Java.Nio/​Buffer.cs Retains the buffer during address retrieval.
src/​Mono.Android/​Java.Lang/​String.cs Retains the string during conversion.
src/​Mono.Android/​Android.Widget/​ArrayAdapter.cs Retains receivers across handwritten adapter calls.
src/​Mono.Android/​Android.Util/​SparseArray.cs Retains receivers across handwritten array calls.
src/​Mono.Android/​Android.OS/​AsyncTask.cs Retains receivers during execution and result retrieval.
src/​Mono.Android/​Android.Graphics/​Bitmap.cs Retains bitmaps during native information and pixel calls.
src/​Mono.Android/​Android.Content/​ContentValues.cs Retains receivers in getter and setter cleanup blocks.
src/​Mono.Android/​Android.App/​Notification.cs Retains notifications during vibration-field access.
src/​Mono.Android/​Android.App/​ActionBar.cs Holds tab dispatchers strongly during registration.
src/​Mono.Android/​Android.Animation/​Animator.cs Holds animator dispatchers strongly during registration.

Review effort: Balanced

simonrozsival and others added 2 commits November 24, 2026 21:39
  * Fix the WeakReference GC race in TextView's AfterTextChanged,
    BeforeTextChanged, and TextChanged event accessors using a strong local.
  * Add GC.KeepAlive (this) after JNIEnv.FinishCreateInstance in
    AnimatorEventDispatcher and TabEventDispatcher constructors.
  * Simplify Notification.Vibrate getter to straight-line GC.KeepAlive (this)
    without a keepalive-only finally block.
  * Wrap modified // SAFETY: comments to fit within 180 columns (tab width 8).
  * Add deterministic functional smoke tests for ValueAnimator events,
    Bitmap pixel info/lock/unlock, direct ByteBuffer address, and TextView
    text change events.

Co-authored-by: Copilot App <[email protected]>
These smoke tests pass even without the GC.KeepAlive and WeakReference
fixes, so they do not provide meaningful regression coverage for this change.

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

@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 asks for GC-sensitive regression coverage rather than redundant happy-path smoke tests.

Reviewed the full source of all 11 changed files, the diff, the project’s preview-language/nullable configuration, and the relevant JNI conversion and listener helpers. The GC.KeepAlive (this) placements retain receivers through native use without changing JNI ownership or dispatch semantics; the existing cleanup blocks remain intact. Reading WeakReference.Target once into a strong local correctly removes the check/read race and retains newly created listeners through registration. I found no introduced functional regression. The explicitly deferred ArrayAdapter<T> and AsyncTask<,,> constructors are outside this patch’s stated scope.

CI: All 38 GitHub check runs report success, including the aggregate dotnet-android check for Azure build 1697999. Independent Azure build/timeline verification was blocked by the CLI’s authentication requirement, so I could not verify underlying non-gating device-test results. The PR reports a successful Release CoreCLR device run; no new local build or device run was performed during this review.

Generated by Android PR Reviewer for #13764 · copilot · gpt61 · 32 AIC · ⌖ 7.88 AIC · ⊞ 20.3K
Comment /review to run again

@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto review

@PeppersMuse

Copy link
Copy Markdown

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

What I verified:

  • GC.KeepAlive (this) placements, each after the native call and before the result is consumed: Bitmap.GetBitmapInfo / LockPixels / UnlockPixels (after the AndroidBitmap_* calls, before CheckNdkError), Java.Lang.String.ToString (after GetCharSequence), Buffer.GetDirectBufferAddress (after the call, on the IsDirect path), AnimatorEventDispatcher / TabEventDispatcher constructors (after FinishCreateInstance), ContentValues all 7 GetAs* and all 7 Put overloads (in the existing finally blocks, alongside DeleteLocalRef (jkey)), Notification.Vibrate getter (KeepAlive after GetObjectField, before the returned local is converted by GetArray) and setter (finally), AsyncTask<,,>.Execute (finally) and GetResult (after CallObjectMethod, before conversion), all 7 SparseArray<E> methods (Append, both Get overloads, IndexOfValue, Put, SetValueAt, ValueAt), and ArrayAdapter<T>.Add / GetItem / GetPosition / Insert / Remove.
  • Nothing missed in the touched files: ContentValues.cs contains only the 14 methods above; SparseArray.cs only its constructors (no JNI call) plus the 7 methods above; Bitmap.cs only the 3 NDK methods; ArrayAdapter<T>.Sort already had KeepAlive (this) (this PR matches it), and CreateFromResource is static with no instance handle. ArrayAdapter<T> / AsyncTask<,,> constructors are intentionally untouched here (Bucket E, [Mono.Android] Keep peers alive during FinishCreateInstance #13762).
  • WeakReference race fix: in ActionBar.Tab.Dispatcher, Animator.Dispatcher, and TextView's AfterTextChanged / BeforeTextChanged / TextChanged accessors, the dispatcher/watcher is now held in a strong local across WeakReference creation, listener registration, and use, and Target is read once via the is pattern instead of IsAlive + a second Target! read — which removes the collect-then-NullReferenceException window. The remove accessors preserve the old null behavior. The dispatcher constructors also gain the KeepAlive (this) noted above.
  • Tests: the current diff contains no test files — the smoke tests were removed in cfb96d91 because they pass with and without the fix, which is the right call for a test that cannot distinguish the two. The review-bot request for a GC-pressure regression test for the listener race was declined by the author (reproducing the pre-registration collection window depends on non-deterministic GC timing) and is tracked in [copilot] Add JNI peer lifetime (GC.KeepAlive) guidelines #13766 — I agree; a happy-path smoke test would not have caught the race either.
  • Scope: no behavior change beyond the audit — JNI ownership, dispatch semantics, and the SAFETY comments (updated to describe the retention) are consistent with the code.

I did not re-run the device tests; the Release CoreCLR on-device results in the description are author-reported.

@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 eleven framework interop changes, listener lifetimes and relevant JNI conversion paths. Strong locals close the weak-reference window, and the added retention preserves handle ownership and exception behavior. No blocking issues found.

@simonrozsival
simonrozsival merged commit 9d18994 into main Nov 25, 2026
38 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-fix-bindings-keepalive-bucket-d branch November 25, 2026 18:51
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