Skip to content

[Mono.Android] Validate generic JNI array conversions - #13339

Merged
jonathanpeppers merged 2 commits into
mainfrom
simonrozsival-checked-jni-array-conversion
Nov 4, 2026
Merged

jonathanpeppers merged 2 commits into
mainfrom
simonrozsival-checked-jni-array-conversion

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Context: #13191
Context: #13192

The original early array-kind validation and Java.Lang.Object.ToArray<T>() owner retention are now on main, 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.Array selects an object-array element reader, but AssertArrayConversionType() 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. Include System.Array with the reference-array destinations so incompatible primitive sources are rejected before object-array element access. Do not change primitive boxing to object/managed interfaces or valid element-wise Object[] conversions.

Retain regression coverage for empty/populated IJavaObject and System.Array destinations, 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 on 0f31c5667fd31777170801e7603596a3ab1e6e2a:

  • make prepare CONFIGURATION=Debug — passed.
  • make leeroy CONFIGURATION=Debug — passed, including extra API levels and local workload configuration.
  • Build/install of the existing runtime test app for android-arm64 with embedded assemblies — passed.
  • From 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.
  • After removing temporary selection categories: ./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.

@simonrozsival
simonrozsival marked this pull request as ready for review October 30, 2026 11:53
Copilot AI balanced review requested due to automatic review settings October 30, 2026 11:53

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.

🟡 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 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 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.
simonrozsival and others added 2 commits November 3, 2026 14:29
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
simonrozsival force-pushed the simonrozsival-checked-jni-array-conversion branch from f817747 to 5134e27 Compare November 3, 2026 14:33
@jonathanpeppers
jonathanpeppers merged commit 044eb87 into main Nov 4, 2026
41 checks passed
@jonathanpeppers
jonathanpeppers deleted the simonrozsival-checked-jni-array-conversion branch November 4, 2026 07:47
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