Repository navigation
[Mono.Android] Keep peers alive in handwritten bindings - #13764
Conversation
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]>
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]>
There was a problem hiding this comment.
🔵 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
* 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]>
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
⚠️ 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
|
@dalexsoto review |
|
Reviewed the full diff at head What I verified:
I did not re-run the device tests; the Release CoreCLR on-device results in the description are author-reported. |
dalexsoto
left a comment
There was a problem hiding this comment.
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.
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
Handleinto anIntPtrand passes it to JNI or NDK P/Invokes without retainingthis, the managed peer can enter a GC bridge cycle while native code is still using the handle.JavaMarshalGCBridge.TakeWeakGlobalReferencedeletes the existing global reference, causing ART CheckJNI to abort withJNI DETECTED ERROR IN APPLICATION: use of deleted global reference.Additionally,
ActionBar.Tab.Dispatcher,Animator.Dispatcher, andTextView's text-change event accessors (AfterTextChanged,BeforeTextChanged,TextChanged) previously stored newly constructed event dispatchers/watchers only inside aWeakReferencebefore registering the listener and readingTarget!, allowing GC to collect the peer mid-initialization and throwNullReferenceException.Changes (Bucket D, items #21–#29)
thisviaGC.KeepAlive (this)afterJNIEnv.AndroidBitmap_*calls inAndroid.Graphics.Bitmap(GetBitmapInfo,LockPixels,UnlockPixels), afterJNIEnv.GetCharSequenceinJava.Lang.String.ToString, afterJNIEnv.GetDirectBufferAddressinJava.Nio.Buffer.GetDirectBufferAddress, and afterJNIEnv.FinishCreateInstanceinAnimatorEventDispatcherandTabEventDispatcherconstructors, updating adjacent// SAFETY:comments.thisin the existingfinallyblocks of all 7GetAs*and 7Putoverloads inAndroid.Content.ContentValues, inAndroid.App.Notification.Vibratesetter'sfinallyblock (with straight-lineGC.KeepAlive (this)in the getter), and inAndroid.OS.AsyncTask<TParams, TProgress, TResult>.Execute(plus straight-lineGC.KeepAlive (this)afterJNIEnv.CallObjectMethodinGetResult).thisoutsideJavaConvert.WithLocalJniHandlelambdas and afterJNIEnv.CallNonvirtualObjectMethodin all 7 handwritten methods ofAndroid.Util.SparseArray<E>(Append,Get,IndexOfValue,Put,SetValueAt,ValueAt) and inAdd,GetItem,GetPosition,Insert, andRemoveofAndroid.Widget.ArrayAdapter<T>(matchingSort). Constructors inArrayAdapter<T>andAsyncTask<,,>are intentionally left untouched for Bucket E.WeakReferenceGC race inActionBar.Tab.Dispatcher,Animator.Dispatcher, andTextView(AfterTextChanged,BeforeTextChanged,TextChanged) by holding the dispatcher/watcher in a strong local acrossWeakReferencecreation, listener registration, and use.Validation
Built the local Release SDK (
make leeroy CONFIGURATION=Release MSBUILD_ARGS='-m:4') and ran the existingMono.Android.NET-Testssuite in Release (CoreCLR) on a dedicated API 29arm64-v8aemulator (emulator-5560, now stopped and removed), then verifiedMono.Android.NET-Tests.csprojbuilds 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)