Repository navigation
[Mono.Android] Fix AbstractSpliterator.TryAdvance JNI dispatch - #13335
Conversation
Java.Util.Spliterators.AbstractSpliteratorInvoker.TryAdvance() used a void JNI descriptor and static dispatch for an instance method returning boolean. Call the virtual instance Boolean method on the receiver and release the temporary Consumer local reference in the finally block. Add a Java subclass fixture and a focused regression covering the true/true/false results, delivered values, and unchanged JNI local-reference count after warmup. Give it a dedicated Spliterator category so it can run without unrelated runtime tests. Validation: prepare and build the local Debug SDK, build the test APK, and pass the single Spliterator regression on an API 35 arm64 CoreCLR emulator. Shut down and delete the owned emulator afterward. Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
🟢 Approval recommended
No active review issues remain for the JNI dispatch and local-reference lifetime changes.
No open issues 🎉
What changed in this PR
Fixes JNI dispatch in AbstractSpliteratorInvoker.TryAdvance() so .NET for Android correctly invokes the Java instance method and releases its temporary Consumer reference.
Changes:
- Uses the Boolean JNI return descriptor and receiver-based virtual dispatch while preserving the public
unsafeoverride. - Releases the local reference in
finallyand keeps the receiver and argument alive. - Adds an unbound Java fixture and focused regression covering return values, delivered values, and local-reference cleanup.
| File | Description |
|---|---|
tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj |
Includes the regression test and disables binding generation for its Java fixture. |
tests/Mono.Android-Tests/Mono.Android-Tests/java/net/dot/android/test/JniSpliteratorFixture.java |
Supplies a two-element Java spliterator for testing. |
tests/Mono.Android-Tests/Mono.Android-Tests/Java.Util/SpliteratorTests.cs |
Verifies instance dispatch, results, and local-reference cleanup. |
src/Mono.Android/Java.Util/Spliterators.cs |
Corrects the JNI descriptor, dispatch, and reference lifetime handling. |
Review effort: Balanced
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
No blocking code findings; CI verification incomplete. Findings: 0 ❌ errors, 0
The Z descriptor and virtual instance dispatch match the Java boolean method. The temporary Consumer reference is now released in finally, with both managed peers kept alive. The unbound Java fixture exercises the invoker rather than bypassing it with a managed override, and checks both iteration results and local-reference balance. I also checked R8 handling: unbound user Java sources receive generated keep rules, so an additional fixture-specific rule is not needed.
CI: All 42 GitHub checks report success, including the aggregate dotnet-android check for Azure build 1655686. The direct az devops invoke --area build --resource builds query failed because Azure authentication is required, so independent Azure build/timeline verification remains incomplete; I am not claiming fully verified green CI. This review was source-based; I did not rerun device tests or independently reproduce the description’s red/green runs.
Generated by Android PR Reviewer for #13335 · copilot · gpt61 · 32.3 AIC · ⌖ 7.39 AIC · ⊞ 19.3K
Comment /review to run again
| Assert.IsTrue (iterator.TryAdvance (consumer)); | ||
| int localReferences = Java.Interop.Runtime.LocalReferenceCount; | ||
| Assert.IsTrue (iterator.TryAdvance (consumer)); | ||
| Assert.IsFalse (iterator.TryAdvance (consumer)); |
There was a problem hiding this comment.
🤖 💡 Testing — Consider adding a case with a non-null IConsumer whose Accept() throws, then asserting that the exception propagates and the JNI local-reference count returns to its pre-call baseline. The current assertions cover normal completion, but not the exceptional path through the newly populated finally; a throwing consumer would exercise cleanup while a temporary Consumer reference actually exists.
{Rule: Test edge cases and JNI reference lifecycle}
Preserve the AbstractSpliterator JNI fix and lifetime guards already merged in #13335. Consolidate the audit coverage into its existing regression: stress exhausted-state calls and verify null-consumer exception propagation without retaining duplicate fixtures. Co-authored-by: Copilot App <[email protected]>
Context: #11467 Context: #13190 Prepare the Android runtime for the updated C# memory-safety rules without enabling them in the product. JNI handles and member IDs, callback signatures, borrowed buffers, and VM initialization carry requirements the managed type system cannot establish. Making every managed wrapper unsafe would push those requirements onto callers that cannot discharge them; relying on a method-level `unsafe` modifier alone would leave the implementation proof implicit. Separate the two responsibilities: document and mark APIs whose callers supply raw lifetime, ownership, bounds, thread, or JNI ABI guarantees; keep managed wrappers safe-callable when they establish those guarantees internally. Add local unsafe contexts with concrete `// SAFETY:` explanations, preserving existing dispatch, marshaling, cleanup, and failure paths. ### Runtime contracts and implementation * Cover raw JNI forwarding, callbacks, runtime creation, native imports, collection marshaling, and remapping-table access. Preserve native layouts and distinguish managed storage from native memory: `JValue` stores bits, and the readonly `UnsafeAccessor` methods access typed, GC-tracked managed static fields. * Use `unsafe(...)` for value-producing operations, retain expression-bodied properties and lambdas, and avoid hoisted temporaries. Keep blocks for pinning, multi-step lifetimes, and void calls the current compiler cannot wrap as expression statements. Remove empty handwritten `finally` blocks without removing actual transition or reference cleanup. * Keep JNI generator caller contracts declarative beside each entry, with shared operation-family text and an explicit `RequiresUnsafe` flag. Generate fixed forwarding/pinning proofs instead of constructing prose from parameter names or types. Keep canonical templates and generated callback output synchronized. Product memory-safety `Features` remain off. New unsafe enforcement on 13 raw peer constructors remains deferred to preserve accepted derived initialization chains; the approved Object/Throwable contracts and Throwable None-only route stay intact. Runtime-creation opt-in coverage and the constructor API records remain with activation [#13192](#13192), not this preparation layer. This PR does not close #11467. ### Behavioral fixes tracked independently The audit also exposed existing bugs, which are separated for review: instance/Boolean Spliterator dispatch and Consumer-local cleanup in [#13335](#13335); ThreadReuse diagnostics using a stale JNI environment in [#13337](#13337); checked generic array conversion and owner retention in draft [#13339](#13339); and `Collection.remove(Object)`'s JNI signature in [#13340](#13340). Their working implementations and regressions are still present here pending inheritance of the independent fixes, rather than temporarily restoring known-broken JNI calls. Nullable Java collection elements retain their existing behavior. Related issue context for the ThreadReuse follow-up: #1191 (`ThreadReuse` failing because the native fixture library was missing), #3363 (`NewString()` during logging ending in Java `OutOfMemoryError`), and #7623 (native crashes during `AttachCurrentThread()`). These are related test/JNI reports, not confirmed duplicates of the stale-environment logging SIGSEGV, and this contract-preparation PR does not claim to resolve or close them. The exact diagnostic-ordering bug is documented in #11467 and fixed independently in #13337.
Context: #13191
Calling
Java.Util.Spliterators.AbstractSpliterator.TryAdvance()on a Java-defined subclass wrapped byAbstractSpliteratorInvokerthrows on the first call:This pre-existing bug surfaced while reviewing the JNI memory-safety changes. The Java method is an instance method returning
boolean, but the hand-written invoker looked up a static method with a void return descriptor,(Ljava/util/function/Consumer;)V. Method lookup fails before the Java implementation can run. A managed subclass overridingTryAdvance()bypasses this invoker, so that usage does not exercise the broken path. There was no existing executable C#/Java test coverage for spliterators; the previous test references were API snapshots and generator metadata.Use the Boolean return descriptor
Zand invoke the virtual instance method onthis. Also release the temporary Consumer local reference infinally, keeping the Consumer and receiver alive through the call. The existing publicunsafeoverride declaration is unchanged; this fix is independent of the memory-safety changes.The regression marshals an unbound Java subclass through the invoker, verifies
true,true,falseand the values"first","second", and checks that the JNI local-reference count is unchanged after warmup. Its dedicatedSpliteratorcategory allows running just this regression.To verify that the test catches the original bug, temporarily restored the old implementation, including its void descriptor, static dispatch, and empty
finally, without changing the new test. Rebuilt the local SDK and test APK:AbstractInvokerTryAdvanceUsesInstanceBooleanAbifailed with the exception above on its firstTryAdvance()call. Restored the fix, rebuilt both, and reran the same test successfully. Decompilation confirmed the old and fixed implementations in their respective built framework assemblies.Both runs used an Android API 35 arm64 CoreCLR emulator:
The temporary source change was fully reverted, and the owned emulator was shut down and deleted. MonoVM and NativeAOT were not tested.
Validation commands and results
make prepare CONFIGURATION=Debugpassed during initial provisioning.make leeroy CONFIGURATION=Debugpassed separately for the original and restored fixed implementations, rebuilding the SDK, additional API levels, and local workload. Builds succeeded with SourceLinkRepository has no commitwarnings.With the original implementation:
./dotnet-local.sh build -t:Install -c Debug tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -p:IncludeCategories=Spliterator '-p:AdbTarget=-s emulator-5558' -v:minimal -bl:bin/BuildDebug/spliterator-red-install.binlog— passed.tests/Mono.Android-Tests/Mono.Android-Tests:ANDROID_SERIAL=emulator-5558 ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Debug -p:IncludeCategories=Spliterator '-p:AdbTarget=-s emulator-5558' --device emulator-5558 --report-trx --results-directory ../../../bin/TestDebug/SpliteratorRedResults— failed as expected, exit code 2; exactly one test failed withJava.Lang.NoSuchMethodErrorat the firstTryAdvance()call.After restoring the fix:
./dotnet-local.sh build -t:Install -c Debug tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -p:IncludeCategories=Spliterator '-p:AdbTarget=-s emulator-5558' -v:minimal -bl:bin/BuildDebug/spliterator-green-install.binlog— passed.tests/Mono.Android-Tests/Mono.Android-Tests:ANDROID_SERIAL=emulator-5558 ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Debug -p:IncludeCategories=Spliterator '-p:AdbTarget=-s emulator-5558' --device emulator-5558 --report-trx --results-directory ../../../bin/TestDebug/SpliteratorGreenResults— passed, exit code 0; exactly one test passed.The test source checksum was unchanged between runs. Both TRX files confirm exactly one executed test, and the device logs confirm the
Spliteratorcategory filter.