Skip to content

[Mono.Android] Fix AbstractSpliterator.TryAdvance JNI dispatch - #13335

Merged
simonrozsival merged 1 commit into
mainfrom
simonrozsival-spliterator-jni-bug-fix
Oct 30, 2026
Merged

simonrozsival merged 1 commit into
mainfrom
simonrozsival-spliterator-jni-bug-fix

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Context: #13191

Calling Java.Util.Spliterators.AbstractSpliterator.TryAdvance() on a Java-defined subclass wrapped by AbstractSpliteratorInvoker throws on the first call:

Java.Lang.NoSuchMethodError : no static method "Ljava/util/Spliterators$AbstractSpliterator;.tryAdvance(Ljava/util/function/Consumer;)V"

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 overriding TryAdvance() 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 Z and invoke the virtual instance method on this. Also release the temporary Consumer local reference in finally, keeping the Consumer and receiver alive through the call. The existing public unsafe override 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, false and the values "first", "second", and checks that the JNI local-reference count is unchanged after warmup. Its dedicated Spliterator category 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: AbstractInvokerTryAdvanceUsesInstanceBooleanAbi failed with the exception above on its first TryAdvance() 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:

Implementation Passed Failed Skipped
Original 0 1 0
Fixed 1 0 0

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=Debug passed during initial provisioning. make leeroy CONFIGURATION=Debug passed separately for the original and restored fixed implementations, rebuilding the SDK, additional API levels, and local workload. Builds succeeded with SourceLink Repository has no commit warnings.

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.
  • From 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 with Java.Lang.NoSuchMethodError at the first TryAdvance() 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.
  • From 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 Spliterator category filter.

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]>
Copilot AI balanced review requested due to automatic review settings October 30, 2026 08:43

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 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 unsafe override.
  • Releases the local reference in finally and 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

@simonrozsival simonrozsival added the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Oct 30, 2026
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13335

@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.

No blocking code findings; CI verification incomplete. Findings: 0 ❌ errors, 0 ⚠️ warnings, 1 💡 suggestion posted inline.

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));

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 — 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}

@simonrozsival
simonrozsival merged commit 1c9806a into main Oct 30, 2026
42 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-spliterator-jni-bug-fix branch October 30, 2026 15:10
simonrozsival added a commit that referenced this pull request Oct 30, 2026
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]>
simonrozsival added a commit that referenced this pull request Oct 31, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable).

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants