Skip to content

Audit and fix missing GC.KeepAlive calls for JNI peer handles across Java.Interop and Mono.Android #13759

Backlog

Description

@simonrozsival

Android framework version

net12.0-android (Preview), net11.0-android, net10.0-android

Affected platform version

dotnet/android main (audited at commit cd0e8cb55c) — CoreCLR and NativeAOT runtimes

Description

Following up on #12315, #12754, and a CoreCLR stress-test crash (use of deleted global reference inside JavaObject's constructor via JniPeerMembers.JniInstanceMethods.FinishCreateInstance), we audited the codebase for places where a raw JNI handle (IntPtr from .Handle or JniObjectReference from .PeerReference) is extracted and passed into JNI/native calls without retaining its managed peer owner (GC.KeepAlive or equivalent).

Why this causes real crashes on CoreCLR & NativeAOT

In optimized builds, the JIT/AOT compiler tracks managed object liveness per instruction rather than to the end of a method or lexical scope. Once .Handle or .PeerReference is copied into a value type, nothing connects that handle back to the managed peer.

Crucially, on CoreCLR and NativeAOT, the Java object being alive on the Java side does not protect an already-copied raw handle:

  1. When a managed peer has no remaining managed roots on the stack, CLR GC includes it in the GC bridge cycle.
  2. JavaMarshalGCBridge.TakeWeakGlobalReference (src/Mono.Android/Microsoft.Android.Runtime/JavaMarshalGCBridge.cs:313-336) converts the peer's global reference to a weak global reference and deletes the old global reference (JniObjectReference.Dispose (ref global)).
  3. Even if the Java object survives Java GC (e.g., an immortal java.lang.Class or a peer currently referenced in Java), TakeGlobalReference (:341-368) allocates a new global reference handle.
  4. When the suspended thread resumes and passes the previously copied IntPtr / JniObjectReference into JNI, that handle is now a deleted global reference, causing ART CheckJNI to abort with JNI DETECTED ERROR IN APPLICATION: use of deleted global reference (or undefined behavior / native memory corruption without CheckJNI).
  5. If the Java object is not otherwise rooted in Java (e.g., newly allocated peer before <init> runs, temporary wrapper, or Java<T>Array), finalization deletes the global ref and frees JniObjectReferenceControlBlock outright.

Below are the 37 audited locations organized into logical buckets, each with exact code snippets showing where GC.KeepAlive (or equivalent retention) is missing, why GC can collect the peer, and estimated severity.


Bucket A — Java.Interop Core (11 items)

1. JniPeerMembers.JniInstanceMethods.FinishCreateInstance

  • Location: src/Java.Interop/Java.Interop/JniPeerMembers.JniInstanceMethods.cs:187-198
  • Severity: High (observed use of deleted global reference crash in CoreCLR stress test)
public unsafe void FinishCreateInstance (string constructorSignature, IJavaPeerable self, JniArgumentValue* parameters)
{
	ArgumentNullException.ThrowIfNull (constructorSignature);
	ArgumentNullException.ThrowIfNull (self);

	var methods = GetConstructorsForType (self.GetType ());
	var ctor    = methods.GetConstructor (constructorSignature);
	unsafe {
		// SAFETY: The caller keeps constructor-compatible slots/references alive for the nonvirtual JNI call.
		JniEnvironment.InstanceMethods.CallNonvirtualVoidMethod (self.PeerReference, methods.JniPeerType.PeerReference, ctor, parameters);
		// Insert GC.KeepAlive (self) here (or wrap CallNonvirtualVoidMethod in try { ... } finally { GC.KeepAlive (self); })
	}
}
  • Why: Every generated binding constructor and new JavaObject () calls StartCreateInstance → Construct/SetHandle → FinishCreateInstance. After self.PeerReference is read, self has no remaining use if the caller discards the constructed object or does not touch this afterward. Before Java <init> starts (and during it if a bridge cycle swaps the gref), the copied PeerReference can be deleted while CallNonvirtualVoidMethod uses it.

2. Jni<T>ArrayElements & Java<T>Array.GetElements / IndexOf / Clear (all 8 primitive array types)

  • Location: src/Java.Interop/Java.Interop/JavaPrimitiveArrays.tt:50-97, 133-179 (generated into JavaPrimitiveArrays.cs for Boolean, SByte, Char, Int16, Int32, Int64, Single, Double)
  • Severity: High
public sealed class Jni<#= info.TypeModifier #>ArrayElements : JniArrayElements {

	JniObjectReference      arrayHandle;
	// Retain owning Java<#= info.TypeModifier #>Array? owner field here so the peer cannot be finalized
	// while native Elements are acquired and before Release<#= info.JniMarshalType #>ArrayElements runs.

	internal unsafe Jni<#= info.TypeModifier #>ArrayElements (JniObjectReference arrayHandle, <#= info.ManagedType #>* elements, int elementCount)
		: base (elements, elementCount, sizeof (<#= info.ManagedType #>))
	{
		this.arrayHandle = arrayHandle;
	}
	...
	protected override void Synchronize (JniReleaseArrayElementsMode releaseMode)
	{
		unsafe {
			JniEnvironment.Arrays.Release<#= info.JniMarshalType #>ArrayElements (arrayHandle, Elements, releaseMode);
			// Insert GC.KeepAlive (owner) here (and clear owner when releaseMode != JniReleaseArrayElementsMode.Commit)
		}
	}
}

public override int IndexOf (<#= info.ManagedType #> item)
{
	int len = Length;
	if (len == 0)
		return -1;
	using (var e = GetElements ()) {
		...
		for (int i = 0; i < len; ++i) {
			unsafe {
				if (e [i] == item)
					return i;
			}
		}
	}
	// Without retaining `this` inside Jni<T>ArrayElements, `this` is dead as soon as GetElements() returns,
	// before `e.Dispose()` invokes Release<T>ArrayElements(arrayHandle, ...).
	// (Same in Clear() at lines 167-178 and any external `using var e = arr.GetElements()` caller.)
	return -1;
}
  • Why: Jni<T>ArrayElements stores only a copied JniObjectReference and raw T* buffer without rooting its owning Java<T>Array. Both IndexOf () and Clear () stop using this after GetElements () returns, violating the constructor's own <safety> contract; external GetElements () callers hit the same trap. Retaining the owning Java<T>Array inside Jni<T>ArrayElements (and calling GC.KeepAlive (owner) after Release*ArrayElements, clearing on final release, and updating the <safety> doc) fixes all callers.

3. Java<T>Array.CopyTo (all 8 primitive array types)

  • Location: src/Java.Interop/Java.Interop/JavaPrimitiveArrays.tt:180-193 (generated in JavaPrimitiveArrays.cs)
  • Severity: High
public override void CopyTo (int sourceIndex, <#= info.ManagedType #>[] destinationArray, int destinationIndex, int length)
{
	if (destinationArray == null)
		throw new ArgumentNullException (nameof (destinationArray));
	CheckArrayCopy (sourceIndex, Length, destinationIndex, destinationArray.Length, length);
	if (destinationArray.Length == 0)
		return;

	unsafe {
		fixed (<#= info.ManagedType #>* b = destinationArray)
			JniEnvironment.Arrays.Get<#= info.JniMarshalType #>ArrayRegion (PeerReference, sourceIndex, length, (b+destinationIndex));
		// Insert GC.KeepAlive (this) here
	}
}
  • Why: fixed pins destinationArray, not this. JavaArray<T>.ToArray () ends with CopyTo (a, 0) and never touches this again, so a temporary new JavaInt32Array (...).ToArray () can be finalized during Get<T>ArrayRegion.

4. Java<T>Array.CopyFrom (all 8 primitive array types)

  • Location: src/Java.Interop/Java.Interop/JavaPrimitiveArrays.tt:195-208 (generated in JavaPrimitiveArrays.cs)
  • Severity: High
public override void CopyFrom (<#= info.ManagedType #>[] sourceArray, int sourceIndex, int destinationIndex, int length)
{
	if (sourceArray == null)
		throw new ArgumentNullException (nameof (sourceArray));
	CheckArrayCopy (sourceIndex, sourceArray.Length, destinationIndex, Length, length);
	if (sourceArray.Length == 0)
		return;

	unsafe {
		fixed (<#= info.ManagedType #>* b = sourceArray)
			JniEnvironment.Arrays.Set<#= info.JniMarshalType #>ArrayRegion (PeerReference, destinationIndex, length, (b+sourceIndex));
		// Insert GC.KeepAlive (this) here
	}
}

5. JavaObjectArray<T>.SetElementAt

  • Location: src/Java.Interop/Java.Interop/JavaObjectArray.cs:88-98
  • Severity: High
void SetElementAt (int index, T value)
{
	var vm  = JniEnvironment.Runtime.ValueManager;
	var r   = vm.CreateLocalObjectReferenceArgument (typeof (T), value);
	try {
		JniEnvironment.Arrays.SetObjectArrayElement (PeerReference, index, r);
	} finally {
		JniObjectReference.Dispose (ref r);
		// Insert GC.KeepAlive (this) here
	}
}
  • Why: r is an owned local reference for value, but nothing keeps this alive across SetObjectArrayElement (e.g., arr [i] = x as the last use of arr).

6. JavaObjectArray<T>.GetElementAt

  • Location: src/Java.Interop/Java.Interop/JavaObjectArray.cs:82-86
  • Severity: Medium
[return: MaybeNull]
T GetElementAt (int index)
{
	var lref = JniEnvironment.Arrays.GetObjectArrayElement (PeerReference, index);
	// Insert GC.KeepAlive (this) here
	return JniEnvironment.Runtime.ValueManager.GetValue<T> (ref lref, JniObjectReferenceOptions.CopyAndDispose);
}
  • Why: After PeerReference is read, this is unused while GetObjectArrayElement runs (e.g., GetArray () [0]).

7. JavaObjectArray<T>.Clear

  • Location: src/Java.Interop/Java.Interop/JavaObjectArray.cs:109-116
  • Severity: Medium
public override void Clear ()
{
	int len = Length;
	var nullReference = new JniObjectReference ();
	try {
		for (int i = 0; i < len; i++) {
			JniEnvironment.Arrays.SetObjectArrayElement (PeerReference, i, nullReference);
		}
	} finally {
		// Insert GC.KeepAlive (this) here
	}
}
  • Why: On the last loop iteration (or earlier if the JIT hoists the PeerReference read), this has no remaining use during SetObjectArrayElement.

8. JavaArray<T>.Length

  • Location: src/Java.Interop/Java.Interop/JavaArray.cs:33-35
  • Severity: Medium
public int Length {
	get {
		int length = JniEnvironment.Arrays.GetArrayLength (PeerReference);
		// Insert GC.KeepAlive (this) here
		return length;
	}
}
  • Why: Inherited by JavaObjectArray<T> and all 8 Java<T>Array types. On a transient or forMarshalCollection array (GetArray ().Length), this is dead before GetArrayLength executes.

9. JavaObject.Equals (object?)

  • Location: src/Java.Interop/Java.Interop/JavaObject.cs:127-137
  • Severity: Medium
public override bool Equals (object? obj)
{
	JniPeerMembers.AssertSelf (this);

	if (object.ReferenceEquals (obj, this))
		return true;
	var o = obj as IJavaPeerable;
	if (o != null) {
		bool result = JniEnvironment.Types.IsSameObject (PeerReference, o.PeerReference);
		// Insert GC.KeepAlive (this) here
		// Insert GC.KeepAlive (o) here
		return result;
	}
	return false;
}
  • Why: Java.Lang.Object inherits this method (hot path via object.Equals, Dictionary, HashSet, LINQ). Both PeerReference values are copied before IsSameObject runs, leaving both this and o dead.

10. JavaException.Equals (object?)

  • Location: src/Java.Interop/Java.Interop/JavaException.cs:220-230
  • Severity: Medium
public override bool Equals (object? obj)
{
	JniPeerMembers.AssertSelf (this);

	if (object.ReferenceEquals (obj, this))
		return true;
	var o = obj as IJavaPeerable;
	if (o != null) {
		bool result = JniEnvironment.Types.IsSameObject (PeerReference, o.PeerReference);
		// Insert GC.KeepAlive (this) here
		// Insert GC.KeepAlive (o) here
		return result;
	}
	return false;
}

11. JniEnvironment.References.NewReturnToJniRef (IJavaPeerable)

  • Location: src/Java.Interop/Java.Interop/JniEnvironment.References.cs:70-75
  • Severity: Low–Medium (shipped public API; no internal callers in src/)
public static IntPtr NewReturnToJniRef (IJavaPeerable value)
{
	if (value == null)
		return IntPtr.Zero;
	var r = value.PeerReference;
	if (!r.IsValid)
		return IntPtr.Zero;
	IntPtr result = NewReturnToJniRef (r);
	// Insert GC.KeepAlive (value) here
	return result;
}

Bucket B — Mono.Android Runtime & Trimmable TypeMap (4 items)

12. TrimmableTypeMapValueManager.CreateLocalObjectReferenceArgumentCore — IJavaPeerable branch

  • Location: src/Mono.Android/Microsoft.Android.Runtime/TrimmableTypeMapValueManager.cs:384-388
  • Severity: Medium
if (value is IJavaPeerable peerable) {
	var r = peerable.PeerReference;
	var local = r.IsValid ? r.NewLocalRef () : new JniObjectReference ();
	// Insert GC.KeepAlive (peerable) here
	return local;
}
  • Why: Core trimmable-typemap marshaling path. After reading peerable.PeerReference, peerable is dead before NewLocalRef () completes. Caching r also avoids the double PeerReference read.

13. TrimmableTypeMapValueManager.CreateLocalObjectReferenceArgumentCore — TrimmableJavaProxyObject branch

  • Location: src/Mono.Android/Microsoft.Android.Runtime/TrimmableTypeMapValueManager.cs:396-397
  • Severity: Medium
var proxy = TrimmableJavaProxyObject.GetProxy (value);
var local = proxy.PeerReference.NewLocalRef ();
// Insert GC.KeepAlive (proxy) here
return local;
  • Why: proxy is only weakly held in a ConditionalWeakTable<object, TrimmableJavaProxyObject> keyed by value. Neither value nor proxy is referenced after proxy.PeerReference is copied. Keeping proxy alive also retains value via proxy.Value.

14. PrimitiveArrayInfo.Handler<T, TArray>.TryCreateObjectReference — existing TArray branch

  • Location: src/Mono.Android/Microsoft.Android.Runtime/PrimitiveArrayInfo.cs:101-108
  • Severity: Medium
public override bool TryCreateObjectReference (object value, out JniObjectReference reference)
{
	if (value is TArray array) {
		var r = array.PeerReference;
		reference = r.IsValid
			? r.NewLocalRef ()
			: new JniObjectReference ();
		// Insert GC.KeepAlive (array) here
		return true;
	}
  • Why: Unlike the marshaledArray branch right below it (which retains marshaledArray in finally { marshaledArray.Dispose (); }), array has no later use and can be finalized before NewLocalRef () finishes.

15. JavaMarshalRegisteredPeers.ReconcilePeer — NoMatch branch

  • Location: src/Mono.Android/Microsoft.Android.Runtime/JavaMarshalRegisteredPeers.cs:116-120
  • Severity: Low
if (registered.Target is not IJavaPeerable target)
	return PeerReconciliationResult.NoMatch;
bool same = JniEnvironment.Types.IsSameObject (target.PeerReference, value.PeerReference);
// Insert GC.KeepAlive (target) here
if (!same)
	return PeerReconciliationResult.NoMatch;
  • Why: target comes from a weak/reference-tracking handle; the Replace (:137) and Keep (:143) branches explicitly call GC.KeepAlive (target), while NoMatch does not. Making KeepAlive (target) explicit right after IsSameObject protects all three paths consistently.

Bucket C — Mono.Android Handwritten Collections (5 items)

16. JavaList.Set (int location, Java.Lang.Object item)

  • Location: src/Mono.Android/Android.Runtime/JavaList.cs:505-531
  • Severity: High
public virtual Java.Lang.Object? Set (int location, Java.Lang.Object item)
{
	const string id = "set.(ILjava/lang/Object;)Ljava/lang/Object;";
	JniObjectReference obj;
	try {
		unsafe {
			JniArgumentValue* parameters = stackalloc JniArgumentValue [2] {
				new JniArgumentValue (location),
				new JniArgumentValue (item),
			};
			obj = list_members.InstanceMethods.InvokeAbstractObjectMethod (id, this, parameters);
		}
	} catch (...) {
		...
	} finally {
		// Insert GC.KeepAlive (item) here
	}
	return Java.Lang.Object.GetObject<Java.Lang.Object> (
			obj.Handle,
			JniHandleOwnership.TransferLocalRef);
}
  • Why: new JniArgumentValue (item) extracts item.PeerReference.Handle into parameters [1]. InvokeAbstractObjectMethod keeps this alive, not item. Every other object-taking method in JavaList (InternalSet, Add, Contains, IndexOf, LastIndexOf, Insert) calls GC.KeepAlive on its argument; Set is the sole omission.

17. Android.Runtime.JavaArray<T> — Count, indexer get/set, GetEnumerator, IndexOf

  • Location: src/Mono.Android/Android.Runtime/JavaArray.cs:28-99
  • Severity: Medium
public int Count {
	get {
		int count = unsafe(JNIEnv.GetArrayLength (Handle));
		// Insert GC.KeepAlive (this) here
		return count;
	}
}

public T this [int index] {
	get {
		if (index < 0 || index >= Count)
			throw new ArgumentOutOfRangeException ("index");
		var item = unsafe(JNIEnv.GetArrayItem<T> (Handle, index));
		// Insert GC.KeepAlive (this) here
		return item;
	}
	set {
		unsafe {
			JNIEnv.SetArrayItem<T> (Handle, index, value);
			// Insert GC.KeepAlive (this) here
		}
	}
}

public IEnumerator<T> GetEnumerator ()
{
	var items = unsafe(JNIEnv.GetArray<T> (Handle));
	// Insert GC.KeepAlive (this) here
	for (int i = 0; i < items!.Length; i++)
		yield return items [i];
}

public int IndexOf (T item)
{
	unsafe {
		var items = JNIEnv.GetArray<T> (Handle)!;
		// Insert GC.KeepAlive (this) here
		return Array.IndexOf (items, item);
	}
}
  • Why: GetArray<T> and GetArrayItem<T> allocate managed arrays and element wrappers in a loop while still reading from Handle, actively causing GC pressure while this is already dead. (Also update the // SAFETY: comments.)

18. JavaCollection & JavaCollection<T> — 8 JNIEnv.Call*Method (Handle, ...) methods

  • Location: src/Mono.Android/Android.Runtime/JavaCollection.cs:
    • JavaCollection: Add (:78), Iterator (:111), Count (:131), ToArray (:161)
    • JavaCollection<T>: Add (:321), Clear (:357), Contains (:383), Remove (:444)
  • Severity: Medium
// Representative direct call (Iterator, Count, ToArray, Clear):
public int Count {
	get {
		unsafe {
			if (id_size == IntPtr.Zero)
				id_size = JNIEnv.GetMethodID (collection_class, "size", "()I");
			int count = JNIEnv.CallIntMethod (Handle, id_size);
			// Insert GC.KeepAlive (this) here
			return count;
		}
	}
}

// Representative WithLocalJniHandle lambda (Add, Contains, Remove):
public bool Contains (T item)
{
	if (id_contains == IntPtr.Zero)
		id_contains = unsafe(JNIEnv.GetMethodID (collection_class, "contains", "(Ljava/lang/Object;)Z"));
	bool result = JavaConvert.WithLocalJniHandle (item, lref => {
		try {
			return unsafe(JNIEnv.CallBooleanMethod (Handle, id_contains, new JValue (lref)));
		} catch (...) { ... }
	});
	// Insert GC.KeepAlive (this) here
	return result;
}
  • Why: Unlike JavaList, JavaCollection calls raw JNIEnv.Call*Method (Handle, ...). In lambda-based methods, WithLocalJniHandle keeps item alive, not this (the closure and this both become dead once Handle is loaded). (CopyTo and the IEnumerable ctors already use this afterward on the normal path.)

19. JavaSet & JavaSet<T> — 9 JNIEnv.Call*Method (Handle, ...) methods

  • Location: src/Mono.Android/Android.Runtime/JavaSet.cs:
    • JavaSet: Iterator (:29), Count (:111), Add (:153), Clear (:187), Contains (:213), Remove (:260)
    • JavaSet<T>: Add (:392), Contains (:424), Remove (:476)
  • Severity: Medium
// Representative — same pattern across all 9 methods above:
internal Java.Util.IIterator Iterator ()
{
	unsafe {
		if (id_iterator == IntPtr.Zero)
			id_iterator = JNIEnv.GetMethodID (set_class, "iterator", "()Ljava/util/Iterator;");
		IntPtr lref = JNIEnv.CallObjectMethod (Handle, id_iterator);
		// Insert GC.KeepAlive (this) here
		return Java.Lang.Object.GetObject<Java.Util.IIterator> (lref, JniHandleOwnership.TransferLocalRef)!;
	}
}
  • Why: Same pattern as JavaCollection, and especially exposed via JavaDictionary.Keys (JavaDictionary.cs:264, 594), which creates a brand-new transient JavaSet on every property access (dict.Keys.Count, foreach (var k in dict.Keys)).

20. JavaDictionary & JavaDictionary<K, V> — 12 JNIEnv.Call*Method (Handle, ...) methods

  • Location: src/Mono.Android/Android.Runtime/JavaDictionary.cs:
    • JavaDictionary: Get (:82), GetKeys (:107), GetValues (:126), Put (:151), Count (:246), Clear (:308), Contains (:334), Remove (:386)
    • JavaDictionary<K, V>: Get (:524), Put (:557), ContainsKey (:638), Remove (:698)
  • Severity: Medium
// Representative — same pattern across all 12 methods above:
internal IntPtr GetKeys ()
{
	unsafe {
		if (id_keySet == IntPtr.Zero)
			id_keySet = JNIEnv.GetMethodID (map_class, "keySet", "()Ljava/util/Set;");
		IntPtr keys = JNIEnv.CallObjectMethod (Handle, id_keySet);
		// Insert GC.KeepAlive (this) here
		return keys;
	}
}
  • Why: Same raw JNIEnv.Call*Method (Handle, ...) receiver-lifetime gap as JavaCollection and JavaSet.

Bucket D — Mono.Android Handwritten Bindings & Event Dispatchers (9 items)

21. Android.Graphics.Bitmap — GetBitmapInfo, LockPixels, UnlockPixels

  • Location: src/Mono.Android/Android.Graphics/Bitmap.cs:37-89
  • Severity: High
public AndroidBitmapInfo GetBitmapInfo ()
{
	unsafe {
		AndroidBitmapInfo info;
		int r = JNIEnv.AndroidBitmap_getInfo (Handle, out info);
		// Insert GC.KeepAlive (this) here
		CheckNdkError ("AndroidBitmap_getInfo", r);
		return info;
	}
}

public IntPtr LockPixels ()
{
	unsafe {
		IntPtr p;
		int r = JNIEnv.AndroidBitmap_lockPixels (Handle, out p);
		// Insert GC.KeepAlive (this) here
		CheckNdkError ("AndroidBitmap_lockPixels", r);
		return p;
	}
}

public void UnlockPixels ()
{
	unsafe {
		int r = JNIEnv.AndroidBitmap_unlockPixels (Handle);
		// Insert GC.KeepAlive (this) here
		CheckNdkError ("AndroidBitmap_unlockPixels", r);
	}
}
  • Why: All three P/Invoke into libjnigraphics.so passing raw Handle, and JNIEnv.AndroidBitmap_* explicitly require the caller to retain the Bitmap. UnlockPixels () is commonly the final use of a Bitmap before it goes out of scope.

22. Java.Lang.String.ToString

  • Location: src/Mono.Android/Java.Lang/String.cs:44-48
  • Severity: High
public override string ToString ()
{
	string result = unsafe(JNIEnv.GetCharSequence (Handle, JniHandleOwnership.DoNotTransfer)!);
	// Insert GC.KeepAlive (this) here
	return result;
}
  • Why: GetCharSequence invokes Java Object.toString () and allocates a managed string while this is dead after reading Handle (e.g., new Java.Lang.String (...).ToString () or final-use javaStr.ToString ()).

23. Android.Content.ContentValues — all 7 GetAs* and 7 Put overloads

  • Location: src/Mono.Android/Android.Content/ContentValues.cs:10-275 (GetAsBoolean:18, GetAsByte:37, GetAsDouble:56, GetAsFloat:75, GetAsInteger:94, GetAsLong:113, GetAsShort:132; Put overloads at :153,172,191,210,229,248,267)
  • Severity: Medium
// Representative — all 14 overloads have the same finally block:
try {
	using (var val = new Java.Lang.Boolean (value))
		JNIEnv.CallVoidMethod (Handle, id_put_Ljava_lang_String_Ljava_lang_Boolean_, new JValue (jkey), new JValue (val));
} finally {
	JNIEnv.DeleteLocalRef (jkey);
	// Insert GC.KeepAlive (this) here
}
  • Why: finally only deletes jkey and using only retains val; nothing retains this across the JNI call. (Alternatively, migrate these to _members.InstanceMethods.Invoke*.)

24. Android.Util.SparseArray<E> — all 7 handwritten methods

  • Location: src/Mono.Android/Android.Util/SparseArray.cs:31-130 (Append:40, Get(int):55, Get(int, E):69, IndexOfValue:83, Put:96, SetValueAt:111, ValueAt:127)
  • Severity: Medium
// Representative direct call (Get(int), ValueAt):
try {
	return JavaConvert.FromJniHandle<E> (
		JNIEnv.CallNonvirtualObjectMethod (Handle, GetPeerMembers (null).GetPeerTypeHandle (), id_get_I, new JValue (key)),
		JniHandleOwnership.TransferLocalRef);
} finally {
	// Insert GC.KeepAlive (this) here
}

// Representative lambda call (Append, Get(int, E), IndexOfValue, Put, SetValueAt):
try {
	JavaConvert.WithLocalJniHandle (value, lref => {
		JNIEnv.CallNonvirtualVoidMethod (Handle, GetPeerMembers (null).GetPeerTypeHandle (), id_put_ILjava_lang_Object_, new JValue (key), new JValue (lref));
		return IntPtr.Zero;
	});
} finally {
	// Insert GC.KeepAlive (this) here
}
  • Why: All 7 methods bypass JniPeerMembers.InstanceMethods and pass raw Handle directly; WithLocalJniHandle only keeps value alive, not this.

25. Java.Nio.Buffer.GetDirectBufferAddress

  • Location: src/Mono.Android/Java.Nio/Buffer.cs:8-16
  • Severity: Medium
public IntPtr GetDirectBufferAddress ()
{
	unsafe {
		if (IsDirect) {
			IntPtr address = JNIEnv.GetDirectBufferAddress (Handle);
			// Insert GC.KeepAlive (this) here
			return address;
		}
		return IntPtr.Zero;
	}
}
  • Why: this is dead after reading Handle before JNI GetDirectBufferAddress runs. (Callers remain responsible for keeping the Buffer alive while using the returned native pointer.)

26. Android.App.Notification.Vibrate — getter and setter

  • Location: src/Mono.Android/Android.App/Notification.cs:18-41
  • Severity: Medium
public long[] Vibrate {
	get {
		unsafe {
			if (vibrate_jfieldId == IntPtr.Zero)
				vibrate_jfieldId = JNIEnv.GetFieldID (_members.GetPeerTypeHandle (), "vibrate", "[J");
			try {
				return (long[]) JNIEnv.GetArray (JNIEnv.GetObjectField (Handle, vibrate_jfieldId), JniHandleOwnership.TransferLocalRef, typeof (long))!;
			} finally {
				// Insert GC.KeepAlive (this) here
			}
		}
	}
	set {
		unsafe {
			if (vibrate_jfieldId == IntPtr.Zero)
				vibrate_jfieldId = JNIEnv.GetFieldID (_members.GetPeerTypeHandle (), "vibrate", "[J");
			IntPtr native_pattern = JNIEnv.NewArray (value);
			try {
				JNIEnv.SetField (Handle, vibrate_jfieldId, native_pattern);
			} finally {
				JNIEnv.DeleteLocalRef (native_pattern);
				// Insert GC.KeepAlive (this) here
			}
		}
	}
}
  • Why: Raw JNIEnv.GetObjectField / SetField bypass JniPeerMembers.InstanceFields (which does call GC.KeepAlive (self)). Also update the // SAFETY: comments.

27. ActionBar.Tab.Dispatcher & Animator.Dispatcher (bonus GC-lifetime race found during review)

  • Location: src/Mono.Android/Android.App/ActionBar.cs:22-30 and src/Mono.Android/Android.Animation/Animator.cs:10-19
  • Severity: Medium
// Current code (same in ActionBar.cs:22-30 and Animator.cs:10-19):
TabEventDispatcher Dispatcher {
	get {
		if (dispatcher == null || !dispatcher.IsAlive) {
			dispatcher = new WeakReference (new TabEventDispatcher ());
			// No strong root keeps the new dispatcher alive here; GC can collect it before the next lines!
			SetTabListener ((TabEventDispatcher) dispatcher.Target!);
		}
		return (TabEventDispatcher) dispatcher.Target!;
	}
}

// Fix: hold in a strong local `d`:
// if (dispatcher?.Target is TabEventDispatcher d)
//     return d;
// d = new TabEventDispatcher ();
// dispatcher = new WeakReference (d);
// SetTabListener (d); // or AddListener (d) in Animator.cs
// return d;
  • Why: Storing the newly constructed dispatcher only in a WeakReference allows GC to collect it between new WeakReference (...), SetTabListener/AddListener, and return (XxxEventDispatcher) dispatcher.Target!, causing NullReferenceException when subscribing to events.

28. Android.Widget.ArrayAdapter<T> — Add, GetItem, GetPosition, Insert, Remove

  • Location: src/Mono.Android/Android.Widget/ArrayAdapter.cs:204-289 (Add:212, GetItem:243, GetPosition:257, Insert:270, Remove:284)
  • Severity: Low–Medium
// Representative — all 5 methods omit GC.KeepAlive (this), unlike Sort () right below at line 300:
public new T? GetItem (int position)
{
	unsafe {
		if (id_getItem_I == IntPtr.Zero)
			id_getItem_I = JNIEnv.GetMethodID (GetPeerMembers (null).GetPeerTypeHandle (), "getItem", "(I)Ljava/lang/Object;");
		IntPtr lref = JNIEnv.CallNonvirtualObjectMethod (Handle, GetPeerMembers (null).GetPeerTypeHandle (), id_getItem_I, new JValue (position));
		// Insert GC.KeepAlive (this) here
		return JavaConvert.FromJniHandle<T> (lref, JniHandleOwnership.TransferLocalRef);
	}
}
  • Why: All 5 pass raw Handle into JNIEnv.CallNonvirtual*Method without retaining this (whereas Sort () at :299-300 explicitly calls GC.KeepAlive (this);).

29. Android.OS.AsyncTask<TParams, TProgress, TResult> — Execute & GetResult

  • Location: src/Mono.Android/Android.OS/AsyncTask.cs:76-110
  • Severity: Low–Medium
// Execute (:84-94):
try {
	var __ret = Java.Lang.Object.GetObject<Android.OS.AsyncTask<TParams, TProgress, TResult>> (JNIEnv.CallObjectMethod (Handle, id_execute_arrayLjava_lang_Object_, new JValue (native__params)), JniHandleOwnership.TransferLocalRef);
	if (@params != null)
		JNIEnv.CopyObjectArray (native__params, @params);
	return __ret;
} finally {
	if (@params != null) {
		JNIEnv.DeleteLocalRef (native__params);
	}
	// Insert GC.KeepAlive (this) here
}

// GetResult (:103-107):
IntPtr lref = JNIEnv.CallObjectMethod (Handle, id_get);
// Insert GC.KeepAlive (this) here
return JavaConvert.FromJniHandle<TResult> (lref, JniHandleOwnership.TransferLocalRef);
  • Why: Handle is read into an IntPtr and this is unused for the entire JNI call (including blocking get () and fire-and-forget new MyAsyncTask ().Execute (...)). Under JavaMarshalGCBridge, a bridge round before JNI dereferences the handle replaces/deletes the old global ref.

Bucket E — Handwritten JNIEnv.FinishCreateInstance (Handle, ...) Initializers (7 items)

These bypass JniPeerMembers.InstanceMethods.FinishCreateInstance (#1) and pass raw Handle directly to JNIEnv.FinishCreateInstance, with nothing using this afterward.

30. Android.Widget.ArrayAdapter<T> — all 6 constructors

  • Location: src/Mono.Android/Android.Widget/ArrayAdapter.cs:34-200 (:48,53, :75,80, :103,108, :132,137, :161,166, :190,195)
  • Severity: Medium
// Representative (all 6 constructors keep `context` alive, not `this`;
// the 4 array/list overloads at :95-199 also call DeleteLocalRef outside try/finally):
if (GetType () == typeof (ArrayAdapter<T>)) {
	...
	SetHandle (JNIEnv.AllocObject (GetPeerMembers (null).GetPeerTypeHandle ()), JniHandleOwnership.TransferLocalRef);
	JNIEnv.FinishCreateInstance (Handle, GetPeerMembers (null).GetPeerTypeHandle (), id_ctor_Landroid_content_Context_I, new JValue (context), new JValue (textViewResourceId));
} else {
	SetHandle (JNIEnv.AllocObject (GetType ()), JniHandleOwnership.TransferLocalRef);
	JNIEnv.FinishCreateInstance (Handle, "(Landroid/content/Context;I)V"u8, new JValue (context), new JValue (textViewResourceId));
}
GC.KeepAlive (context);
// Insert GC.KeepAlive (this) here (and wrap DeleteLocalRef in finally for the 4 array/list overloads)

31. Android.Widget.BaseAdapter<T> ()

  • Location: src/Mono.Android/Android.Widget/BaseAdapter.cs:24-37
  • Severity: Medium
unsafe {
	SetHandle (
			JNIEnv.AllocObject (GetType ()),
			JniHandleOwnership.TransferLocalRef);
	JNIEnv.FinishCreateInstance (Handle, "()V"u8);
	// Insert GC.KeepAlive (this) here
}

32. Android.Widget.AdapterView<T> — all 3 constructors

  • Location: src/Mono.Android/Android.Widget/AdapterView.cs:70-120 (:81, :98, :116)
  • Severity: Low–Medium
// Representative (all 3 constructors):
unsafe {
	SetHandle (
			JNIEnv.AllocObject (GetType ()),
			JniHandleOwnership.TransferLocalRef);
	JNIEnv.FinishCreateInstance (Handle, "(Landroid/content/Context;Landroid/util/AttributeSet;I)V"u8, new JValue (context), new JValue (attrs), new JValue (defStyle));
	GC.KeepAlive (context);
	GC.KeepAlive (attrs);
	// Insert GC.KeepAlive (this) here
}

33. Android.Runtime.JavaDictionary () & JavaDictionary<K, V> ()

  • Location: src/Mono.Android/Android.Runtime/JavaDictionary.cs:182-203 and 459-479
  • Severity: Low–Medium
unsafe {
	if (GetType () == typeof (JavaDictionary)) {
		SetHandle (unsafe (JNIEnv.AllocObject ("java/util/HashMap"u8)), JniHandleOwnership.TransferLocalRef);
		JNIEnv.FinishCreateInstance (Handle, "()V"u8);
	} else {
		SetHandle (JNIEnv.AllocObject (GetType ()), JniHandleOwnership.TransferLocalRef);
		JNIEnv.FinishCreateInstance (Handle, "()V"u8);
	}
	// Insert GC.KeepAlive (this) here (and in JavaDictionary<K, V>() at line 477)
}

34. Android.Runtime.JavaSet ()

  • Location: src/Mono.Android/Android.Runtime/JavaSet.cs:48-68 (note: JavaSet<T> () : base () at :327-347 already initializes Handle in JavaSet (), making lines 333-345 unreachable)
  • Severity: Low
unsafe {
	if (GetType () == typeof (JavaSet)) {
		SetHandle (unsafe (JNIEnv.AllocObject ("java/util/HashSet"u8)), JniHandleOwnership.TransferLocalRef);
	} else {
		SetHandle (JNIEnv.AllocObject (GetType ()), JniHandleOwnership.TransferLocalRef);
	}
	JNIEnv.FinishCreateInstance (Handle, "()V"u8);
	// Insert GC.KeepAlive (this) here
}

35. Android.OS.AsyncTask<TParams, TProgress, TResult> ()

  • Location: src/Mono.Android/Android.OS/AsyncTask.cs:46-60
  • Severity: Low
unsafe {
	SetHandle (
			JNIEnv.AllocObject (GetType ()),
			JniHandleOwnership.TransferLocalRef);
	JNIEnv.FinishCreateInstance (Handle, "()V"u8);
	// Insert GC.KeepAlive (this) here
}

36. Java.Lang.Object.SetHandleOnDeserialized

  • Location: src/Mono.Android/Java.Lang/Object.cs:54-68
  • Severity: Low
unsafe {
	SetHandle (
			JNIEnv.AllocObject (GetType ()),
			JniHandleOwnership.TransferLocalRef);
	JNIEnv.FinishCreateInstance (Handle, "()V"u8);
	// Insert GC.KeepAlive (this) here
}

Bucket F — Device Tests (1 item)

37. Temporary .Class.Handle in JNI lookups (7 test files)

  • Locations:
    • tests/Mono.Android-Tests/Mono.Android-Tests/Java.Interop/TrimmableTypeMapExportTests.cs (:36-41, 59, 70-72, 89, 99-100, 114-115, 128, 136, 156, 191, 200-201, 223)
    • tests/Mono.Android-Tests/Mono.Android-Tests/Java.Interop/ExportTests.cs (:30, 40, 50, 73, 88, 102, 142, 180, 202, 219, 230, 247)
    • tests/Mono.Android-Tests/Mono.Android-Tests/Java.Interop/TrimmableTypeMapRuntimeCoverageTests.cs (:38, 53, 78, 102, 117, 136, 338)
    • tests/Mono.Android-Tests/Mono.Android-Tests/Java.Interop/JnienvTest.cs (:50, 53, 229, 403, 416)
    • tests/Mono.Android-Tests/Mono.Android-Tests/Java.Interop/TrimmableTypeMapDirectCallbackTests.cs (:22, 23, 38)
    • tests/Mono.Android-Tests/Mono.Android-Tests/Android.Graphics/NinePatchTests.cs:81
    • tests/CodeGen-Binding/Xamarin.Android.JcwGen-Tests/TimingTests.cs:225
  • Severity: Low–Medium (intermittent test crashes under GC bridge stress)
// Current pattern:
var intMethod = GetRequiredMethodID (peer.Class.Handle, "remove", "(I)V");

// Fix (retains the Java.Lang.Class wrapper and avoids leaking grefs until GC):
using var klass = peer.Class;
var intMethod = GetRequiredMethodID (klass.Handle, "remove", "(I)V");
// Insert GC.KeepAlive (klass) here (already guaranteed by `using var klass` Dispose at scope exit)
  • Why: peer.Class returns a Java.Lang.Class wrapper owning a JNI global ref. Because JavaMarshalGCBridge.TakeWeakGlobalReference deletes and replaces the global ref of any managed-unreachable peer (even when java.lang.Class survives via its ClassLoader), the raw IntPtr extracted by peer.Class.Handle becomes a deleted global reference if a GC bridge round runs before GetMethodID/GetFieldID/NewObjectArray reads it.

Steps to Reproduce

  1. Run an optimized (Release) CoreCLR or NativeAOT Android application or device test suite under heavy concurrent Java/managed GC allocation pressure (e.g., 4 background Java-allocating threads triggering GC bridge rounds).
  2. Invoke any of the affected APIs above on a short-lived / final-use managed peer (e.g., new JavaObject (), new JavaInt32Array (...).IndexOf (...), new Java.Lang.String ("x").ToString (), dict.Keys.Count, bitmap.UnlockPixels (), or peer.Class.Handle).
  3. Observe intermittent ART CheckJNI aborts (JNI DETECTED ERROR IN APPLICATION: use of deleted global reference) when the GC bridge deletes/swaps the peer's global reference before JNI consumes the copied handle.

Did you find any workaround?

For external callers, holding an explicit strong reference (GC.KeepAlive (peer) or using) past the call avoids the race in caller-controlled paths, though internal temporaries (such as JavaDictionary.Keys, Jni<T>ArrayElements inside IndexOf/Clear, TrimmableJavaProxyObject, and ActionBar/Animator Dispatcher) require runtime fixes.

Relevant log output

# Observed under CoreCLR stress testing on item #1 (JavaObject constructor via FinishCreateInstance):
JNI DETECTED ERROR IN APPLICATION: use of deleted global reference ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area: App Runtime

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions