Skip to content

[tests] Keep Java.Lang.Class peers alive in JNI lookups - #13777

Open
simonrozsival wants to merge 1 commit into
mainfrom
simonrozsival-fix-test-temp-class-handle
Open

simonrozsival wants to merge 1 commit into
mainfrom
simonrozsival-fix-test-temp-class-handle

Conversation

@simonrozsival

Copy link
Copy Markdown
Member

Context: #13759
Relates to #13759

In optimized CoreCLR and NativeAOT builds, peer.Class.Handle extracts a raw IntPtr from an unretained temporary Java.Lang.Class wrapper. Because JavaMarshalGCBridge.TakeWeakGlobalReference deletes and replaces the global reference of any managed-unreachable peer — even an immortal java.lang.Class — a GC bridge cycle running before JNIEnv.GetMethodID, JNIEnv.GetFieldID, JNIEnv.NewObjectArray, or native JNI timing code reads that handle can abort ART CheckJNI with JNI DETECTED ERROR IN APPLICATION: use of deleted global reference. Chained .Class accesses also leave temporary Java.Lang.Class global references alive until GC instead of disposing them deterministically.

Changes (Bucket F, item #37)

  • Replace chained .Class.Handle (and bare Class.Handle in ExportReentrant.ReentrantOuter) expressions with a scoped using var klass = ...Class; local across all 7 test files (TrimmableTypeMapExportTests, ExportTests, TrimmableTypeMapRuntimeCoverageTests, JnienvTest, TrimmableTypeMapDirectCallbackTests, NinePatchTests, and TimingTests), reusing a single klass per method when looking up multiple members on the same peer.
  • Reuse a single using var peerClass = peer.Class; in TrimmableTypeMapRuntimeCoverageTests.JavaAnnotation_LongValueOutsideIntRange_UsesJavaLongLiteral.
  • Retain unretained peer owners across direct JNIEnv handle calls in the same files: GC.KeepAlive (this) in ExportReentrant.ReentrantOuter, GC.KeepAlive (manager) in NinePatchTests.OpenNonAsset, GC.KeepAlive (values [0]) after JNIEnv.IsSameObject in NonGenericCollection_CopyTo_ViewArray_UsesTrimmableTypeMapForArrayElementConversion, and GC.KeepAlive (arrayList) in CopyToJavaCollection, CopyToJavaList, and AddToJavaCollection.

Validation

Built the local Release SDK (make prepare CONFIGURATION=Release && make leeroy CONFIGURATION=Release MSBUILD_ARGS='-m:4') and ran Mono.Android.NET-Tests in Release (CoreCLR) on a dedicated API 29 arm64-v8a emulator (emulator-5554, now stopped and removed):

  • ./dotnet-local.sh build -t:Install -c Release -p:Device=emulator-5554 tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -v minimal + (cd tests/Mono.Android-Tests/Mono.Android-Tests && ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Release -p:Device=emulator-5554 --report-trx --results-directory ../../../bin/TestRelease/TestResults): Passed (1124 passed, 0 failed, 4 pre-existing skips; all modified test classes passed: TrimmableTypeMapExportTests 10/10, ExportTests 15/15, TrimmableTypeMapRuntimeCoverageTests 19/19, JnienvTest 36/36 with 1 pre-existing [Ignore], TrimmableTypeMapDirectCallbackTests 2/2, NinePatchTests 8/8).
  • ./dotnet-local.sh build -c Release tests/CodeGen-Binding/Xamarin.Android.JcwGen-Tests/Xamarin.Android.JcwGen-Tests.csproj -v minimal: Succeeded (0 errors). Note that TimingTests.cs is excluded from compilation via <Compile Remove="TimingTests.cs" /> in Xamarin.Android.JcwGen-Tests.csproj.

Context: #13759
Relates to #13759

Replace chained temporary .Class.Handle expressions in device tests with
scoped using locals so the Java.Lang.Class wrapper remains alive across
JNI lookups and is disposed deterministically instead of risking a
deleted global reference under CoreCLR/NativeAOT GC bridge cycles. Also
keep unretained peer receivers alive across JNI calls in the same files
(ExportReentrant.ReentrantOuter, NinePatchTests.OpenNonAsset, and
TrimmableTypeMapRuntimeCoverageTests helpers/assertions).

Co-authored-by: Copilot App <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 25, 2026 12:32

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues block the JNI handle-lifetime test changes.

No open issues 🎉

What changed in this PR

Addresses the test-side JNI handle lifetime work in #13759. The changes retain managed Java peers while their handles are in use, preventing deleted-global-reference failures in optimized CoreCLR and NativeAOT builds.

Changes:

  • Replace temporary .Class.Handle expressions with scoped, disposable class locals, reusing them for related lookups.
  • Add GC.KeepAlive markers for peer owners used by direct JNI calls.
  • Reuse the class wrapper during annotation lookup.
File Description
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Java.Interop/​TrimmableTypeMapRuntimeCoverageTests.cs Retains class wrappers and collection peers during JNI operations.
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Java.Interop/​TrimmableTypeMapExportTests.cs Reuses scoped class wrappers for exported-method lookups.
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Java.Interop/​TrimmableTypeMapDirectCallbackTests.cs Retains class wrappers during callback-method lookups.
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Java.Interop/​JnienvTest.cs Scopes class wrappers for method, field, and object-array operations.
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Java.Interop/​ExportTests.cs Retains lookup wrappers and the reentrant call’s peer owner.
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Android.Graphics/​NinePatchTests.cs Retains the class wrapper and asset manager during JNI access.
tests/​CodeGen-Binding/​Xamarin.Android.JcwGen-Tests/​TimingTests.cs Retains the class wrapper during native timing calls.

Review effort: Balanced

@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13777

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Pending CI

Reviewed the full source of all seven changed files, the JNI ownership/lifetime paths, and the consuming test projects. 0 errors, 0 warnings, 1 optional testing suggestion posted inline. No blocking code defect identified: the scoped class wrappers retain their global references through JNI use and provide deterministic disposal; the added GC.KeepAlive calls retain the raw-handle owners without changing dispatch or assertions. The bridge implementation confirms that an unreachable peer's global reference can be deleted even when its Java object survives.

CI is not yet green: the head commit has 37 checks, with 5 successful, 31 in progress, and 1 queued; no failed checks were reported. Azure DevOps build 1699110 is associated with these checks, but direct build/timeline inspection was blocked by Azure CLI initialization/authentication errors, so its final result remains unverified.

The description reports a passing Release CoreCLR device run; I did not independently rerun device tests or establish NativeAOT coverage. I also verified that TimingTests.cs is excluded from its project's compilation, as disclosed in the description.

Generated by Android PR Reviewer for #13777 · copilot · gpt61 · 35 AIC · ⌖ 7.94 AIC · ⊞ 20.3K
Comment /review to run again

{
using var e = new ExportPrimitiveInt ();
var m = JNIEnv.GetMethodID (e.Class.Handle, "EchoInt", "(I)I");
using var klass = e.Class;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 💡 Testing — Could we add focused GC-pressure coverage for this class-handle lifetime pattern? The existing round-trip assertions verify dispatch, but do not force a bridge cycle between extracting klass.Handle and consuming it in JNI, so they can also pass with the original temporary-wrapper expression. A small optimized CoreCLR/NativeAOT regression case that retains the class owner across a forced bridge round and then performs the lookup would protect the reason for this change; the existing GCBridgeTestHelpers can supply the bridge synchronization.

{Rule: Bug fixes need regression coverage for the failing lifetime window}

@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto review

@simonrozsival
simonrozsival enabled auto-merge (squash) November 25, 2026 18:52
@simonrozsival
simonrozsival enabled auto-merge (squash) November 25, 2026 18:53

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants