Repository navigation
[Mono.Android] Keep peers alive during FinishCreateInstance - #13762
simonrozsival wants to merge 4 commits into
Conversation
Relates to #13759 Handwritten constructors and initializers that call JNIEnv.FinishCreateInstance (Handle, ...) bypass JniPeerMembers.InstanceMethods.FinishCreateInstance and pass a copied raw Handle with no subsequent use of this. In optimized CoreCLR and NativeAOT builds, the GC bridge can convert and delete the peer's global reference while Java <init> is still executing, triggering ART CheckJNI aborts ('use of deleted global reference'). Keep this alive after JNIEnv.FinishCreateInstance in the handwritten initializers for ArrayAdapter<T>, BaseAdapter<T>, AdapterView<T>, JavaDictionary, JavaDictionary<K, V>, JavaSet, JavaSet<T>, AsyncTask<TParams, TProgress, TResult>, and Java.Lang.Object.SetHandleOnDeserialized. In the four ArrayAdapter<T> array/list overloads, wrap JNIEnv.DeleteLocalRef and the GC.KeepAlive calls in finally so temporary JNI local references are also released when construction throws. Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
The constructor-failure tests also pass with the leaking pre-change implementation and need to verify that JNI local-reference counts remain unchanged.
1 open issue
What changed in this PR
This PR addresses the handwritten peer-initialization portion of #13759, keeping managed peers alive while Java constructors run to prevent invalid JNI handles in optimized CoreCLR and NativeAOT builds.
Changes:
- Add
GC.KeepAlive (this)after handwrittenFinishCreateInstancecalls. - Release temporary array/list local references in
finallyblocks whenArrayAdapter<T>construction fails. - Add constructor success, failure, and concurrent garbage-collection tests.
| File | Description |
|---|---|
tests/Mono.Android-Tests/Mono.Android-Tests/Android.Widget/AdapterTests.cs |
Adds constructor coverage and concurrent collection stress tests. |
src/Mono.Android/Java.Lang/Object.cs |
Retains the peer during deserialization initialization. |
src/Mono.Android/Android.Widget/BaseAdapter.cs |
Retains the peer during construction. |
src/Mono.Android/Android.Widget/ArrayAdapter.cs |
Retains peers and ensures exception-safe local-reference cleanup. |
src/Mono.Android/Android.Widget/AdapterView.cs |
Retains peers across all three constructors. |
src/Mono.Android/Android.Runtime/JavaSet.cs |
Retains generic and nongeneric set peers during construction. |
src/Mono.Android/Android.Runtime/JavaDictionary.cs |
Retains generic and nongeneric dictionary peers during construction. |
src/Mono.Android/Android.OS/AsyncTask.cs |
Retains the generic task peer during construction. |
Review effort: Balanced
…eepAlive - Update SAFETY comments in the touched FinishCreateInstance initializers to reference AllocObject, finally local-ref cleanup, and GC.KeepAlive retention. - Assert JniEnvironment.LocalReferenceCount in ArrayAdapterConstructorsReleaseLocalRefsOnFailure after warming up lazily-initialized state. - Exercise derived ArrayAdapter<string> subclass constructors in AdapterTests so both direct and subclass branches are covered. - Remove the non-deterministic FinishCreateInstanceConstructorsSurviveConcurrentCollection test. Co-authored-by: Copilot App <[email protected]>
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 concerns missing regression coverage for the four ArrayAdapter<T> exception-path cleanup changes; no implementation defect was identified in the reviewed diff.
The lifetime fix is appropriately scoped: GC.KeepAlive (this) follows the raw-handle constructor calls, existing context/attribute-set retention is preserved, and temporary array/list locals are now released in finally. JNI signatures, exact-type versus derived-type dispatch, and public API shape remain unchanged. The JavaSet base constructor supplies the active guard for JavaSet<T>, consistent with the description. I reviewed all seven full changed source files, the diff, JNI constructor/marshaling helpers, the GC bridge reference replacement, and existing adapter coverage.
CI: All 38 head-commit GitHub checks report success, including the aggregate dotnet-android check linked to Azure build 1698001. Independent Azure build/timeline verification could not be completed: az devops invoke required authentication, and a public build API read was denied by the execution environment. This is a review limitation, not evidence of a CI failure. The CoreCLR/NativeAOT device results in the description are author-reported; I did not rerun device tests in this review.
Generated by Android PR Reviewer for #13762 · copilot · gpt61 · 39.7 AIC · ⌖ 5.15 AIC · ⊞ 21K
Comment /review to run again
Restore ArrayAdapterConstructorsReleaseLocalRefsOnFailure in AdapterTests to verify via JniEnvironment.LocalReferenceCount that each of the four throwing ArrayAdapter<T> array/IList<T> constructors (direct and derived) releases its temporary JNI local reference in finally. Co-authored-by: Copilot App <[email protected]>
|
Reviewed the full diff at head What I verified:
I did not re-run the device tests; the CoreCLR (1123 passed) / NativeAOT (1060 passed) results in the description are author-reported. |
|
@dalexsoto review |
|
In response to @simonrozsival's request: The changed hunks show the intended lifetime guards and exception cleanup, but my review coverage for |

Context: #13759
Relates to #13759
Handwritten peer constructors and initializers that call
JNIEnv.FinishCreateInstance (Handle, ...)bypassJniPeerMembers.InstanceMethods.FinishCreateInstanceand pass a copied rawIntPtrhandle with no subsequent use ofthis. In optimized CoreCLR and NativeAOT builds, the GC can collect or include an unrooted peer in a GC bridge cycle while Java<init>is still running;JavaMarshalGCBridge.TakeWeakGlobalReferencedeletes the peer's original global reference, causing ART CheckJNI aborts (JNI DETECTED ERROR IN APPLICATION: use of deleted global reference) or undefined behavior.Keep
thisalive withGC.KeepAlive (this)afterJNIEnv.FinishCreateInstancein the Bucket E initializers from #13759 (and align their adjacent// SAFETY:comments):Android.Widget.ArrayAdapter<T>(all 6 constructors; the 4 array andIList<T>overloads also wrapJNIEnv.DeleteLocalRefandGC.KeepAliveinfinallyso temporary local references are released if Java construction throws)Android.Widget.BaseAdapter<T> ()Android.Widget.AdapterView<T>(all 3 constructors)Android.Runtime.JavaDictionary ()andJavaDictionary<K, V> ()Android.Runtime.JavaSet ()(which also provides the active protection forJavaSet<T> () : base (), sinceJavaSet ()initializesHandle;JavaSet<T> ()retainsGC.KeepAlive (this)defensively)Android.OS.AsyncTask<TParams, TProgress, TResult> ()Java.Lang.Object.SetHandleOnDeserializedAdd a deterministic regression test (
AdapterTests.ArrayAdapterConstructorsReleaseLocalRefsOnFailure) warming up lazy state and assertingJniEnvironment.LocalReferenceCountremains unchanged after each throwingArrayAdapter<T>array/IList<T>constructor (direct and derived).Validation
Built the Release local SDK and ran
Mono.Android.NET-Testson an API 29arm64-v8aemulator (emulator-5554, stopped and removed afterward) for both CoreCLR and NativeAOT:make prepare CONFIGURATION=Release MSBUILD_ARGS='-m:4 -nr:false' && make leeroy CONFIGURATION=Release MSBUILD_ARGS='-m:4 -nr:false'— succeeded./dotnet-local.sh build -t:Install -c Release -p:Device=emulator-5554 -p:RuntimeIdentifier=android-arm64 -m:4 -nr:false tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csprojand../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Release -p:Device=emulator-5554 -p:RuntimeIdentifier=android-arm64 --report-trx --results-directory ../../../bin/TestRelease/TestResults(CoreCLR) — 1123 passed, 0 failed, 4 skipped (ArrayAdapterConstructorsReleaseLocalRefsOnFailurepassed)-p:PublishAot=true(NativeAOT) — 1060 passed, 0 failed, 4 skipped (ArrayAdapterConstructorsReleaseLocalRefsOnFailurepassed)