Repository navigation
Description
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:
- When a managed peer has no remaining managed roots on the stack, CLR GC includes it in the GC bridge cycle.
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)).- Even if the Java object survives Java GC (e.g., an immortal
java.lang.Classor a peer currently referenced in Java),TakeGlobalReference(:341-368) allocates a new global reference handle. - When the suspended thread resumes and passes the previously copied
IntPtr/JniObjectReferenceinto JNI, that handle is now a deleted global reference, causing ART CheckJNI to abort withJNI DETECTED ERROR IN APPLICATION: use of deleted global reference(or undefined behavior / native memory corruption without CheckJNI). - If the Java object is not otherwise rooted in Java (e.g., newly allocated peer before
<init>runs, temporary wrapper, orJava<T>Array), finalization deletes the global ref and freesJniObjectReferenceControlBlockoutright.
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 referencecrash 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 ()callsStartCreateInstance→Construct/SetHandle→FinishCreateInstance. Afterself.PeerReferenceis read,selfhas no remaining use if the caller discards the constructed object or does not touchthisafterward. Before Java<init>starts (and during it if a bridge cycle swaps the gref), the copiedPeerReferencecan be deleted whileCallNonvirtualVoidMethoduses 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 intoJavaPrimitiveArrays.csforBoolean,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>ArrayElementsstores only a copiedJniObjectReferenceand rawT*buffer without rooting its owningJava<T>Array. BothIndexOf ()andClear ()stop usingthisafterGetElements ()returns, violating the constructor's own<safety>contract; externalGetElements ()callers hit the same trap. Retaining the owningJava<T>ArrayinsideJni<T>ArrayElements(and callingGC.KeepAlive (owner)afterRelease*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 inJavaPrimitiveArrays.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:
fixedpinsdestinationArray, notthis.JavaArray<T>.ToArray ()ends withCopyTo (a, 0)and never touchesthisagain, so a temporarynew JavaInt32Array (...).ToArray ()can be finalized duringGet<T>ArrayRegion.
4. Java<T>Array.CopyFrom (all 8 primitive array types)
- Location:
src/Java.Interop/Java.Interop/JavaPrimitiveArrays.tt:195-208(generated inJavaPrimitiveArrays.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
}
}- Why: Identical to "clang" is not always available. It needs to be customizible. #3 —
fixedpins onlysourceArray, leavingthisdead oncePeerReferenceis copied beforeSet<T>ArrayRegionfinishes.
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:
ris an owned local reference forvalue, but nothing keepsthisalive acrossSetObjectArrayElement(e.g.,arr [i] = xas the last use ofarr).
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
PeerReferenceis read,thisis unused whileGetObjectArrayElementruns (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
PeerReferenceread),thishas no remaining use duringSetObjectArrayElement.
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 8Java<T>Arraytypes. On a transient orforMarshalCollectionarray (GetArray ().Length),thisis dead beforeGetArrayLengthexecutes.
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.Objectinherits this method (hot path viaobject.Equals,Dictionary,HashSet, LINQ). BothPeerReferencevalues are copied beforeIsSameObjectruns, leaving boththisandodead.
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;
}- Why: Same as Get Linux build working. #9; inherited by
Java.Lang.Throwable.
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;
}- Why: Copies
value.PeerReferenceand callsNewLocalRef ()with nothing keepingvaluealive (same bug class as PR [Mono.Android] Prevent premature JNI handle collection #12315'sJNIEnv.ToLocalJniHandlefix). ReadingPeerReferenceonce also eliminates the double property read.
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,peerableis dead beforeNewLocalRef ()completes. Cachingralso avoids the doublePeerReferenceread.
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:
proxyis only weakly held in aConditionalWeakTable<object, TrimmableJavaProxyObject>keyed byvalue. Neithervaluenorproxyis referenced afterproxy.PeerReferenceis copied. Keepingproxyalive also retainsvalueviaproxy.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
marshaledArraybranch right below it (which retainsmarshaledArrayinfinally { marshaledArray.Dispose (); }),arrayhas no later use and can be finalized beforeNewLocalRef ()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:
targetcomes from a weak/reference-tracking handle; theReplace(:137) andKeep(:143) branches explicitly callGC.KeepAlive (target), whileNoMatchdoes not. MakingKeepAlive (target)explicit right afterIsSameObjectprotects 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)extractsitem.PeerReference.Handleintoparameters [1].InvokeAbstractObjectMethodkeepsthisalive, notitem. Every other object-taking method inJavaList(InternalSet,Add,Contains,IndexOf,LastIndexOf,Insert) callsGC.KeepAliveon its argument;Setis 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>andGetArrayItem<T>allocate managed arrays and element wrappers in a loop while still reading fromHandle, actively causing GC pressure whilethisis 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,JavaCollectioncalls rawJNIEnv.Call*Method (Handle, ...). In lambda-based methods,WithLocalJniHandlekeepsitemalive, notthis(the closure andthisboth become dead onceHandleis loaded). (CopyToand theIEnumerablectors already usethisafterward 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 viaJavaDictionary.Keys(JavaDictionary.cs:264, 594), which creates a brand-new transientJavaSeton 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 asJavaCollectionandJavaSet.
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.sopassing rawHandle, andJNIEnv.AndroidBitmap_*explicitly require the caller to retain theBitmap.UnlockPixels ()is commonly the final use of aBitmapbefore 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:
GetCharSequenceinvokes JavaObject.toString ()and allocates a managedstringwhilethisis dead after readingHandle(e.g.,new Java.Lang.String (...).ToString ()or final-usejavaStr.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;Putoverloads 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:
finallyonly deletesjkeyandusingonly retainsval; nothing retainsthisacross 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.InstanceMethodsand pass rawHandledirectly;WithLocalJniHandleonly keepsvaluealive, notthis.
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:
thisis dead after readingHandlebefore JNIGetDirectBufferAddressruns. (Callers remain responsible for keeping theBufferalive 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/SetFieldbypassJniPeerMembers.InstanceFields(which does callGC.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-30andsrc/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
WeakReferenceallows GC to collect it betweennew WeakReference (...),SetTabListener/AddListener, andreturn (XxxEventDispatcher) dispatcher.Target!, causingNullReferenceExceptionwhen 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
HandleintoJNIEnv.CallNonvirtual*Methodwithout retainingthis(whereasSort ()at:299-300explicitly callsGC.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:
Handleis read into anIntPtrandthisis unused for the entire JNI call (including blockingget ()and fire-and-forgetnew MyAsyncTask ().Execute (...)). UnderJavaMarshalGCBridge, 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-203and459-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-347already initializesHandleinJavaSet (), 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:81tests/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.Classreturns aJava.Lang.Classwrapper owning a JNI global ref. BecauseJavaMarshalGCBridge.TakeWeakGlobalReferencedeletes and replaces the global ref of any managed-unreachable peer (even whenjava.lang.Classsurvives via itsClassLoader), the rawIntPtrextracted bypeer.Class.Handlebecomes a deleted global reference if a GC bridge round runs beforeGetMethodID/GetFieldID/NewObjectArrayreads it.
Steps to Reproduce
- 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).
- 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 (), orpeer.Class.Handle). - 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 ...
Activity
[Mono.Android] Clarify SAFETY comments for collection GC.KeepAlive sites
[docs] Incorporate PR review learnings and tighten KeepAlive guidelines
[Mono.Android] Keep JNI peer handles alive in handwritten collections (…
[Mono.Android] Keep peers alive in handwritten bindings (#13764)
[Mono.Android] Keep JNI peer owners alive in trimmable runtime paths (#…
[Java.Interop] Keep peers alive across array, Equals, and ref calls (#…