Skip to content

[Mono.Android] Fix JavaCollection<T>.Remove() JNI signature - #13340

Merged
simonrozsival merged 3 commits into
mainfrom
simonrozsival-collection-remove-jni-abi
Oct 30, 2026
Merged

simonrozsival merged 3 commits into
mainfrom
simonrozsival-collection-remove-jni-abi

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Context: #12561
Context: 5777337
Context: https://developer.android.com/reference/java/util/Collection#remove(java.lang.Object)

Before this change, Android.Runtime.JavaCollection<T>.Remove() fails during method lookup, before removing an item. Restoring the old descriptor and running the new integer, string, and custom managed-object regressions reproduces the same exception in all three tests:

Java.Lang.NoSuchMethodError : no non-static method "Ljava/util/Collection;.remove(I)Ljava/lang/Object;"

The stack reaches JniEnvironment.InstanceMethods.GetMethodID(), JNIEnv.GetMethodID(), and JavaCollection<T>.Remove(). The operation throws rather than silently returning false; an unhandled exception can terminate the application. In the regression run, NUnit catches and reports all three failures without a native crash.

The method looks up remove with (I)Ljava/lang/Object;: an integer argument and an object result, matching List.remove(int). However, the lookup targets java.util.Collection, which only declares remove(Object) returning boolean. The supplied object argument and CallBooleanMethod invocation already match the intended overload.

The incorrect descriptor was present in the initial April 2016 Mono.Android import. The closed issue #12561 records the broken descriptor but excludes it from the typemap-parity work.

Resolve (Ljava/lang/Object;)Z and link the Android API documentation beside the lookup. The three regressions verify successful and unsuccessful removal for integers, strings, and instances of a custom plain managed class, including retained-item identity for managed objects.

Validation

Ran the same three tests on an isolated Android 10/API 29 arm64-v8a emulator with CoreCLR, Debug:

Test Old descriptor Corrected descriptor
GenericRemoveUsesObjectArgumentAndBooleanResult Failed: NoSuchMethodError Passed
GenericRemoveStrings Failed: NoSuchMethodError Passed
GenericRemoveManagedObjects Failed: NoSuchMethodError Passed

The old run reports 0 passed, 3 failed, 0 skipped (exit 2); the corrected run reports 3 passed, 0 failed, 0 skipped (exit 0). Temporary category annotations select only these tests and are identical in both runs. The test DLLs are byte-identical (SHA-256 e3a70a6b8b975996e2ac21c2d5259a6eace24b042285d7792731ad5c2a748de3); decompilation confirms the respective runtime-pack descriptors, and each pulled installed APK matches its locally built signed APK. Restored all committed source afterward and stopped/deleted only the session-owned emulator/AVD.

  • make prepare — passed; fresh SDK provisioning and prerequisite preparation.
  • make leeroy — passed; fresh SDK, extra API levels, and local workload configuration; zero errors (51/62/0 warnings by stage).
  • ./dotnet-local.sh build src/Mono.Android/Mono.Android.csproj -c Debug -v:minimal — passed with both descriptors; 29 warnings, zero errors in each build.
  • ANDROID_SERIAL=emulator-5556 ./dotnet-local.sh build -t:Install -c Debug tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -p:RuntimeIdentifier=android-arm64 -p:IncludeCategories=CollectionRemoveRegression -p:EmbedAssembliesIntoApk=true '-p:AdbTarget=-s emulator-5556' -v:minimal — passed in both runs; zero warnings/errors.

From tests/Mono.Android-Tests/Mono.Android-Tests, ran the following commands. The first fails as expected with the old descriptor; the second passes after restoring the fix:

ANDROID_SERIAL=emulator-5556 ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --device emulator-5556 --no-build -c Debug -p:RuntimeIdentifier=android-arm64 -p:IncludeCategories=CollectionRemoveRegression -p:EmbedAssembliesIntoApk=true '-p:AdbTarget=-s emulator-5556' --report-trx --results-directory /Users/simon/.copilot/session-state/53717edc-9508-4f55-b7ae-7a3253eaa056/files/collection-remove-old
ANDROID_SERIAL=emulator-5556 ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --device emulator-5556 --no-build -c Debug -p:RuntimeIdentifier=android-arm64 -p:IncludeCategories=CollectionRemoveRegression -p:EmbedAssembliesIntoApk=true '-p:AdbTarget=-s emulator-5556' --report-trx --results-directory /Users/simon/.copilot/session-state/53717edc-9508-4f55-b7ae-7a3253eaa056/files/collection-remove-fixed

After restoring the committed sources, git diff --exit-code passed and ./dotnet-local.sh build -c Debug tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -v:minimal passed with zero warnings/errors. NativeAOT, Release, other ABIs/API levels, and the complete collection fixture were not run in this comparison.

Context: #12561
Context: 5777337
Context: https://developer.android.com/reference/java/util/Collection#remove(java.lang.Object)

Android.Runtime.JavaCollection<T>.Remove() looks up remove(int), returning Object, on java.util.Collection.  That interface only declares remove(Object), returning boolean, so the lookup cannot resolve the requested method.  The object argument and CallBooleanMethod invocation already match the intended overload.

The incorrect descriptor was present in the initial 2016 Mono.Android import.  The closed typemap-parity issue explicitly notes the defect but excludes it as an independent problem.

Resolve (Ljava/lang/Object;)Z and link the Android API documentation beside the lookup.  Add a regression that removes value 2 from [1, 2], checks the boolean result and remaining count, and verifies that removing absent value 3 returns false without changing the count.

Validation: make prepare and make leeroy passed; the Debug Mono.Android.NET-Tests project build passed with 0 warnings and 0 errors.  Android runtime tests were not run because device/emulator/ADB access was outside the authorized validation scope.

Co-authored-by: Copilot App <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 30, 2026 11:14
Extend Android.Runtime.JavaCollection<T>.Remove() regression coverage beyond boxed integers.  Exercise strings and instances of a custom managed class, which travel through managed-object proxies rather than Java built-in value wrappers.

Check successful removal, preservation of the retained item, false results for absent items, and unchanged counts after unsuccessful removal.  The managed-object case also checks reference identity after removal.

Validation: ./dotnet-local.sh build -c Debug tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -v:minimal passed with 0 warnings and 0 errors.  On-device execution remains unrun because device/emulator/ADB access is outside the authorized validation scope.

Co-authored-by: Copilot App <[email protected]>

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.

🔵 Needs a closer look

The JNI lookup fix and regression were built but not run on Android, leaving runtime method resolution and dispatch unverified pending on-device regression and collection tests.

No open issues 🎉

What changed in this PR

Fixes JavaCollection<T>.Remove() in the Android runtime bindings so its JNI lookup matches Collection.remove(Object), rather than the indexed List.remove(int) overload.

Changes:

  • Corrects the JNI descriptor to (Ljava/lang/Object;)Z and adds an Android API documentation link.
  • Adds a regression test covering successful value removal and an absent value, including return values and collection state.

The PR reports successful SDK and test-project builds; on-device tests were not run.

File Description
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Android.Runtime/​JavaCollectionTest.cs Adds regression coverage for generic collection removal.
src/​Mono.Android/​Android.Runtime/​JavaCollection.cs Corrects the removal method’s JNI descriptor and documents its API reference.

Review effort: Balanced

Restore the existing closing-brace and final-newline layout so the combined test-coverage diff contains only the requested additions.

Co-authored-by: Copilot App <[email protected]>
@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 #13340

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

✅ LGTM — code review

0 errors · 0 warnings · 1 non-blocking suggestion (inline).

The corrected (Ljava/lang/Object;)Z descriptor matches Collection.remove(Object), the existing object-handle argument, and CallBooleanMethod. The fix preserves method-ID caching, local-reference cleanup, and exception translation, and matches the existing JavaSet<T>.Remove implementation. The regressions cover successful and unsuccessful removal for integers, strings, and plain managed objects; the retained-object identity assertion is particularly useful. No blocking correctness or resource-management issues found in either full changed file.

CI: All 41 GitHub check runs for head dd23d6d completed successfully, including the aggregate dotnet-android check for Azure build 1655895. Direct Azure build/timeline inspection was unavailable because the CLI required authentication and the parallel timeline call encountered a CLI initialization error; therefore I could not independently confirm the Azure build result or inspect non-gating device-test failures. Device tests were not rerun in this review; the old-versus-fixed device results are reported by the PR author, not independently reproduced here.

Generated by Android PR Reviewer for #13340 · copilot · gpt61 · 21.2 AIC · ⌖ 7.19 AIC · ⊞ 19.3K
Comment /review to run again

list.Add ("first");
list.Add ("second");
using var collection = new JavaCollection<string> (list.Handle, JniHandleOwnership.DoNotTransfer);

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 null-element removal case alongside the string regression: put a null and a non-null string in the backing ArrayList, assert that removing null returns true and preserves the string, then assert that removing null again returns false. Java collections explicitly allow null here, and this exercises the IntPtr.Zero argument path in JavaConvert.WithLocalJniHandle, which the three new tests do not cover.

{Rule: Test edge cases}

@simonrozsival
simonrozsival merged commit 534f673 into main Oct 30, 2026
41 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-collection-remove-jni-abi branch October 30, 2026 15:09
simonrozsival added a commit that referenced this pull request Oct 30, 2026
Main already includes the Collection.remove(Object):boolean JNI fix and integer, string, and managed-object coverage from #13340. Keep its documentation placement and regressions, retaining only the additional repeated-null-removal test from this unsafe-audit branch.

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