Repository navigation
[Mono.Android] Keep JNI peer handles alive in handwritten collections - #13763
Conversation
Context: #13759 Relates to #13759 In optimized CoreCLR and NativeAOT builds, the JIT/AOT compiler tracks managed object liveness per instruction rather than to the end of a method. Once a raw JNI handle is read from `Handle` or copied into a `JniArgumentValue`, the managed peer owner can become eligible for collection while the JNI call is still executing. Under `JavaMarshalGCBridge`, a bridge cycle converts unreachable peers' global references to weak global references and deletes the old global reference (allocating a new one if the Java object survives), causing ART CheckJNI to abort with `JNI DETECTED ERROR IN APPLICATION: use of deleted global reference`. Add missing `GC.KeepAlive` calls across the handwritten `Android.Runtime` collection types (Bucket C, items #16–#20 of #13759): * `JavaList.Set (int, Java.Lang.Object)`: keep `item` alive in `finally` around `InvokeAbstractObjectMethod`, matching the other object-taking methods in `JavaList`. * `JavaArray<T>`: keep `this` alive across `JNIEnv.GetArrayLength`, `JNIEnv.GetArrayItem<T>`, `JNIEnv.SetArrayItem<T>`, and `JNIEnv.GetArray<T>` in `Count`, the indexer getter/setter, `GetEnumerator`, and `IndexOf`, and update the adjacent `// SAFETY:` comments. * `JavaCollection` and `JavaCollection<T>`: keep `this` alive across all 8 raw `JNIEnv.Call*Method (Handle, ...)` call sites (`Add`, `Iterator`, `Count`, `ToArray`, `Clear`, `Contains`, `Remove`). * `JavaSet` and `JavaSet<T>`: keep `this` alive across all 9 raw `JNIEnv.Call*Method (Handle, ...)` call sites (`Iterator`, `Count`, `Add`, `Clear`, `Contains`, `Remove`). Constructors are left untouched for the separate initializer PR. * `JavaDictionary` and `JavaDictionary<K, V>`: keep `this` alive across all 12 raw `JNIEnv.Call*Method (Handle, ...)` call sites (`Get`, `GetKeys`, `GetValues`, `Put`, `Count`, `Clear`, `Contains`, `ContainsKey`, `Remove`). Constructors are left untouched for the separate initializer PR. Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
🟢 Approval recommended
No active review issues block approval of the JNI peer-lifetime changes.
No open issues 🎉
What changed in this PR
Addresses the handwritten-collection portion of #13759 by retaining managed JNI peer owners during native calls, preventing premature collection from invalidating handles in optimized CoreCLR and NativeAOT builds.
Changes:
- Adds receiver retention around JNI operations in arrays, collections, sets, and dictionaries.
- Keeps the argument to
JavaList.Setalive through afinallyblock. - Updates array safety comments to describe the lifetime protection; constructor changes remain out of scope.
| File | Description |
|---|---|
src/Mono.Android/Android.Runtime/JavaSet.cs |
Retains set receivers during JNI operations. |
src/Mono.Android/Android.Runtime/JavaList.cs |
Retains the Set argument on success and exception paths. |
src/Mono.Android/Android.Runtime/JavaDictionary.cs |
Retains dictionary receivers during JNI operations. |
src/Mono.Android/Android.Runtime/JavaCollection.cs |
Retains collection receivers during JNI operations. |
src/Mono.Android/Android.Runtime/JavaArray.cs |
Retains array peers during access and conversion; updates safety comments. |
Review effort: Balanced
Context: #13759 Relates to #13759 Address code review feedback on SAFETY comments: * Restore the T-compatible array element contract alongside `GC.KeepAlive (this)` in `JavaArray<T>` (`this[int]`, `GetEnumerator`, `IndexOf`). * Document `GC.KeepAlive (this)` receiver retention alongside `WithLocalJniHandle` argument retention across the updated `JavaCollection`, `JavaSet`, and `JavaDictionary` methods, keeping lines within the 180-column limit. Co-authored-by: Copilot App <[email protected]>
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
✅ LGTM — code review
Findings: 0 errors · 0 warnings · 1 non-blocking testing suggestion, posted inline.
Reviewed the full source of all five changed files at aafe40b90840e50325f871e9f3c5ae69f7f84c0e, including the JNI conversion helpers and existing collection/GC tests. The new lifetime barriers retain the relevant managed owners through the synchronous JNI operations without changing signatures, exception wrapping, or local-reference ownership. JavaList.Set now matches the argument-retention pattern in its sibling methods. The unchanged CopyTo paths still access this.Count after their raw JNI calls, supporting the stated exclusion; constructors remain outside this PR's scope. I found no merge-blocking correctness regression.
CI: All 38 published GitHub checks passed, including the aggregate dotnet-android check for Azure build 1697939 and license/cla. A direct Azure build query could not be completed because the installed Azure CLI requires login, so Azure timeline/non-gating test details were not independently inspected. The CoreCLR/NativeAOT local results in the PR description are author-reported; I did not rerun builds or device tests during this review.
Generated by Android PR Reviewer for #13763 · copilot · gpt61 · 36.3 AIC · ⌖ 8.02 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 CoreCLR (1122 passed) / NativeAOT (1059 passed) results in the description are author-reported. |
dalexsoto
left a comment
There was a problem hiding this comment.
Reviewed the five handwritten collection changes and their JNI call paths. The added receiver/item retention covers raw-handle use without changing local-reference ownership, exception wrapping or collection behavior. No blocking issues found.
Context: #13759
Relates to #13759
In optimized CoreCLR and NativeAOT builds, the JIT/AOT compiler tracks managed object liveness per instruction rather than to the end of a method. Once a raw JNI handle is read from
Handleor copied into aJniArgumentValue, the managed peer owner can become eligible for collection while the JNI call is still executing. UnderJavaMarshalGCBridge, a bridge cycle converts unreachable peers' global references to weak global references and deletes the old global reference (allocating a new one if the Java object survives), causing ART CheckJNI to abort withJNI DETECTED ERROR IN APPLICATION: use of deleted global reference.Add missing
GC.KeepAlivecalls across the handwrittenAndroid.Runtimecollection types (Bucket C, items #16–#20 of #13759):JavaList.Set (int, Java.Lang.Object): keepitemalive infinallyaroundInvokeAbstractObjectMethod, matching the other object-taking methods inJavaList.JavaArray<T>: keepthisalive acrossJNIEnv.GetArrayLength,JNIEnv.GetArrayItem<T>,JNIEnv.SetArrayItem<T>, andJNIEnv.GetArray<T>inCount, the indexer getter/setter,GetEnumerator, andIndexOf, and update the adjacent// SAFETY:comments.JavaCollectionandJavaCollection<T>: keepthisalive across all 8 rawJNIEnv.Call*Method (Handle, ...)sites (Add,Iterator,Count,ToArray,Clear,Contains,Remove) and update their// SAFETY:comments.JavaSetandJavaSet<T>: keepthisalive across all 9 rawJNIEnv.Call*Method (Handle, ...)sites (Iterator,Count,Add,Clear,Contains,Remove) and update their// SAFETY:comments. Constructors are left untouched for the separate Bucket E initializer PR.JavaDictionaryandJavaDictionary<K, V>: keepthisalive across all 12 rawJNIEnv.Call*Method (Handle, ...)sites (Get,GetKeys,GetValues,Put,Count,Clear,Contains,ContainsKey,Remove) and update their// SAFETY:comments. Constructors are left untouched for the separate Bucket E initializer PR.JavaArray<T>.CopyToand bothJavaCollection.CopyTooverloads are intentionally unchanged: each loop readsCountonthisafter the JNI call, keepingthisalive through the call.Validation
make prepare CONFIGURATION=Release && make leeroy CONFIGURATION=Release MSBUILD_ARGS='-m:4 -nr:false'): passed (0 errors, API levels 37, 37.1, 37.2, ApiCompat and PublicAPI analyzers passed).Mono.Android.csprojafter the comment-only follow-up (./bin/Release/dotnet/dotnet build src/Mono.Android/Mono.Android.csproj -c Release -m:4 -nr:false --no-dependencies): passed (0 errors, 0 ApiCompat issues).emulator-5556, API 29 arm64):emulator-5556, API 29 arm64):