Repository navigation
[Mono.Android] Validate generic JNI array conversions - #13339
Merged
Merged
Conversation
Contributor
There was a problem hiding this comment.
🟡 Changes recommended
Unconditional JNI validation breaks previously supported conversions to IJavaObject[] and System.Array[] by throwing on missing Java type mappings, requiring explicit handling and regression tests.
1 open issue
What changed in this PR
This PR hardens generic JNI array conversion in Mono.Android to reject incompatible inputs before native array access and retain the owning Java wrapper throughout conversion.
Changes:
- Apply array compatibility validation to all generic element types.
- Keep the wrapper alive through conversion success or failure.
- Add regressions for non-array inputs and empty/non-empty primitive arrays converted to reference arrays.
| File | Description |
|---|---|
| tests/Mono.Android-Tests/Mono.Android-Tests/Java.Lang/ObjectArrayMarshaling.cs | Adds rejection tests and verifies valid primitive-array conversion. |
| src/Mono.Android/Java.Lang/Object.cs | Adds GC.KeepAlive(this) in a finally block. |
| src/Mono.Android/Android.Runtime/JNIEnv.cs | Validates compatibility before reading the native array length for every T. |
Review effort: Balanced
simonrozsival
added a commit
that referenced
this pull request
Oct 30, 2026
Context: #13339 (comment) Unconditional array validation attempts to obtain Java type signatures for IJavaObject and System.Array. These managed-only destination types have no direct Java mapping, so valid conversions fail with InvalidOperationException in JniTypeSignature.AddArrayRank(). After unwrapping jagged dimensions, validate these two element types through java.lang.Object references while preserving the original array rank. This retains the existing converters without bypassing the checks for non-arrays, incompatible primitive arrays, or insufficient array rank. Add empty and populated conversion regressions for both destinations and their jagged forms, and extend invalid-input coverage. The expanded API 35 ARM64 CoreCLR suite reproduces 13 failures before the correction and passes all 54 cases afterward. 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.
Context: #13339 (comment) Unconditional array validation attempts to obtain Java type signatures for IJavaObject and System.Array. These managed-only destination types have no direct Java mapping, so valid conversions fail with InvalidOperationException in JniTypeSignature.AddArrayRank(). After unwrapping jagged dimensions, validate these two element types through java.lang.Object references while preserving the original array rank. This retains the existing converters without bypassing the checks for non-arrays, incompatible primitive arrays, or insufficient array rank. Add empty and populated conversion regressions for both destinations and their jagged forms, and extend invalid-input coverage. The expanded API 35 ARM64 CoreCLR suite reproduces 13 failures before the correction and passes all 54 cases afterward. Co-authored-by: Copilot App <[email protected]>
The runtime safety changes now on main already include early array-kind validation and wrapper retention, together with compatible element-wise reference conversion. Preserve those upstream paths instead of restoring the stricter whole-array and declared-rank checks. Keep managed-only destination coverage, accept empty and null nested-array elements, and reject actual non-array nested values. System.Array selects an object-array reader, so classify it with the other reference-array destinations before native element access rather than treating it as an inferred boxing destination. Local SDK and emulator validation is pending: concurrent validation on the shared volume exhausted disk headroom. Do not treat earlier array-suite passes as proof for this rebased head. Co-authored-by: Copilot App <[email protected]>
simonrozsival
force-pushed
the
simonrozsival-checked-jni-array-conversion
branch
from
November 3, 2026 14:33
f817747 to
5134e27
Compare
jonathanpeppers
approved these changes
Nov 4, 2026
jonathanpeppers
deleted the
simonrozsival-checked-jni-array-conversion
branch
November 4, 2026 07:47
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Context: #13191
Context: #13192
The original early array-kind validation and
Java.Lang.Object.ToArray<T>()owner retention are now onmain, together with the newer element-wise reference conversion and primitive boxing behavior. This rebased PR preserves those upstream paths rather than restoring the earlier strict whole-array assignability check.System.Arrayselects an object-array element reader, butAssertArrayConversionType()currently treats it as an inferred/boxing destination. A primitive JNI array can therefore pass the initial validation even though that reader requires an object array. IncludeSystem.Arraywith the reference-array destinations so incompatible primitive sources are rejected before object-array element access. Do not change primitive boxing toobject/managed interfaces or valid element-wiseObject[]conversions.Retain regression coverage for empty/populated
IJavaObjectandSystem.Arraydestinations, their jagged forms, and non-array/primitive-array rejection. Replace the obsolete declared-rank rejection expectation with successful empty/null nested-array conversions and rejection of actual non-array child elements. The runtime's upstream Object[]-to-string, null, nested-string, and boxing regressions remain intact.Validation
Fresh validation at rebased head
5134e27c602c2b0960d0e39fd5557b1a13b378e6, based on0f31c5667fd31777170801e7603596a3ab1e6e2a:make prepare CONFIGURATION=Debug— passed.make leeroy CONFIGURATION=Debug— passed, including extra API levels and local workload configuration.android-arm64with embedded assemblies — passed.tests/Mono.Android-Tests/Mono.Android-Tests:../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Debug -p:RuntimeIdentifier=android-arm64 -p:EmbedAssembliesIntoApk=true -p:IncludeCategories=CheckedArrayConversionRebase --device emulator-5564 --report-trx --results-directory /Users/simon/.copilot/session-state/443d0085-e08b-4892-891f-b281326827e0/files/rebase-validation/results— 74 passed, 0 failed, 0 skipped on an isolated Android 15/API 35 ARM64/CoreCLR emulator: 35 ObjectArrayMarshaling cases and 39 JnienvArrayMarshaling cases../dotnet-local.sh build -c Debug tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -v:minimal— passed, 0 errors; 6 existing SourceLink/Git metadata warnings (Repository has no commit).Temporary fixture categories were used only to select the two existing test fixtures; test bodies match the committed source. The owned emulator was stopped and deleted, and the worktree is clean. NativeAOT, other APIs/ABIs, and GC-finalization timing were not tested. Earlier 44/54-case results are historical, not evidence for this rebased head.