Repository navigation
[Unsafe] Prepare JNI and runtime memory-safety contracts - #13191
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
Array validation rejects previously supported element-wise conversions from Java Object arrays.
1 open issue
What changed in this PR
Prepares .NET for Android’s JNI and runtime contracts for updated C# memory-safety rules, following the binding preparation layer. Product activation remains off.
Changes:
- Documents caller obligations and moves implementation-only unsafe operations into local blocks.
- Corrects collection removal, spliterator dispatch, and array validation.
- Adds compiler-contract and runtime regression coverage.
| File | Description |
|---|---|
| tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj | Includes spliterator tests and fixture. |
| tests/Mono.Android-Tests/Mono.Android-Tests/java/net/dot/android/test/JniSpliteratorFixture.java | Adds Java spliterator fixture. |
| tests/Mono.Android-Tests/Mono.Android-Tests/Java.Util/SpliteratorTests.cs | Tests instance Boolean dispatch. |
| tests/Mono.Android-Tests/Mono.Android-Tests/Java.Lang/ObjectArrayMarshaling.cs | Tests array validation and conversions. |
| tests/Mono.Android-Tests/Mono.Android-Tests/Java.Interop/JnienvTest.cs | Categorizes string-length coverage. |
| tests/Mono.Android-Tests/Mono.Android-Tests/Java.Interop/JavaMarshalGCBridgeTests.cs | Categorizes GC-bridge coverage. |
| tests/Mono.Android-Tests/Mono.Android-Tests/Android.Runtime/RuntimeEventSourceTests.cs | Categorizes event coverage. |
| tests/Mono.Android-Tests/Mono.Android-Tests/Android.Runtime/JnienvArrayMarshaling.cs | Categorizes array-marshaling coverage. |
| tests/Mono.Android-Tests/Mono.Android-Tests/Android.Runtime/JavaCollectionTest.cs | Tests collection removal signature. |
| src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/JniEnvMemorySafetyTests.cs | Tests generated contracts and compiler enforcement. |
| src/Mono.Android/System.Linq/Extensions.cs | Scopes iterator JNI operations locally. |
| src/Mono.Android/Mono.Android.csproj | Enables preview syntax without activation. |
| src/Mono.Android/Microsoft.Android.Runtime/TrimmableTypeMapValueManager.cs | Scopes cast-diagnostic JNI access. |
| src/Mono.Android/Microsoft.Android.Runtime/TrimmableTypeMapTypeManager.cs | Documents remapping pointer lifetimes. |
| src/Mono.Android/Microsoft.Android.Runtime/RuntimeEventSource.cs | Keeps event methods safe-callable. |
| src/Mono.Android/Microsoft.Android.Runtime/JavaMarshalRegisteredPeers.cs | Scopes tracking-handle operations. |
| src/Mono.Android/Microsoft.Android.Runtime/JavaMarshalGCBridgeJni.cs | Scopes GC-bridge JNI calls. |
| src/Mono.Android/Microsoft.Android.Runtime/HandleContext.cs | Documents native context obligations. |
| src/Mono.Android/Java.Util/Spliterators.cs | Fixes dispatch, signature, and reference cleanup. |
| src/Mono.Android/Java.Util/ISortedMap.cs | Keeps interface implementation safe-callable. |
| src/Mono.Android/Java.Util/IList.cs | Keeps interface implementation safe-callable. |
| src/Mono.Android/Java.Nio/Buffer.cs | Scopes direct-buffer address lookup. |
| src/Mono.Android/Java.Lang/Throwable.cs | Documents raw construction; scopes Class access. |
| src/Mono.Android/Java.Lang/Thread.cs | Scopes Runnable initialization. |
| src/Mono.Android/Java.Lang/String.cs | Keeps managed constructors safe-callable. |
| src/Mono.Android/Java.Lang/Runnable.cs | Scopes peer initialization. |
| src/Mono.Android/Java.Lang/Object.cs | Documents raw lookup and retains array peer lifetime. |
| src/Mono.Android/Java.Lang/Class.cs | Scopes cached method lookup. |
| src/Mono.Android/Java.Interop/JniMarshalTyped.tt | Emits callback contracts and local regions. |
| src/Mono.Android/Java.Interop/JavaConvert.cs | Scopes marshaling operations. |
| src/Mono.Android/Android.Widget/TextView.cs | Scopes listener registration. |
| src/Mono.Android/Android.Widget/BaseAdapter.cs | Scopes peer construction. |
| src/Mono.Android/Android.Widget/AdapterViewAnimator.cs | Keeps adapter accessors safe-callable. |
| src/Mono.Android/Android.Widget/AdapterView.cs | Scopes constructor JNI calls. |
| src/Mono.Android/Android.Widget/AbsListView.cs | Scopes adapter callbacks and accessors. |
| src/Mono.Android/Android.Util/SparseArray.cs | Classifies accessor and scopes JNI calls. |
| src/Mono.Android/Android.Text/ITextWatcher.cs | Scopes watcher initialization. |
| src/Mono.Android/Android.Telephony/CellInfo.cs | Keeps getters safe-callable. |
| src/Mono.Android/Android.Security/KeyChain.cs | Documents certificate handle lifetime. |
| src/Mono.Android/Android.Runtime/XmlReaderPullParser.cs | Scopes parser-reference duplication. |
| src/Mono.Android/Android.Runtime/XAPeerMembers.cs | Scopes threshold-class lookup. |
| src/Mono.Android/Android.Runtime/OutputStreamAdapter.cs | Scopes stream peer initialization. |
| src/Mono.Android/Android.Runtime/Logger.cs | Documents native logging format obligations. |
| src/Mono.Android/Android.Runtime/JValue.cs | Classifies union fields without layout changes. |
| src/Mono.Android/Android.Runtime/JNIEnvInit.cs | Documents initialization contracts and scopes startup. |
| src/Mono.Android/Android.Runtime/JavaSet.cs | Scopes collection JNI operations. |
| src/Mono.Android/Android.Runtime/JavaObject.cs | Scopes conversion and initialization. |
| src/Mono.Android/Android.Runtime/JavaCollection.cs | Fixes removal signature and scopes JNI calls. |
| src/Mono.Android/Android.Runtime/JavaArray.cs | Scopes managed array operations. |
| src/Mono.Android/Android.Runtime/InputStreamAdapter.cs | Scopes stream peer initialization. |
| src/Mono.Android/Android.Runtime/AndroidRuntime.cs | Documents VM construction obligations. |
| src/Mono.Android/Android.Runtime/AndroidEnvironment.cs | Classifies exit import and scopes throwable access. |
| src/Mono.Android/Android.OS/Handler.cs | Scopes callback initialization. |
| src/Mono.Android/Android.OS/AsyncTask.cs | Classifies accessor and scopes JNI calls. |
| src/Mono.Android/Android.Hardware/HardwareBuffer.cs | Keeps managed APIs safe-callable. |
| src/Mono.Android/Android.Graphics/Bitmap.cs | Scopes native bitmap operations. |
| src/Mono.Android/Android.Content/CursorLoader.cs | Keeps override safe-callable. |
| src/Mono.Android/Android.Bluetooth/BluetoothGattServerCallback.cs | Scopes callback marshaling. |
| src/Mono.Android/Android.App/Notification.cs | Scopes vibration-array field access. |
| src/Mono.Android/Android.App/Application.cs | Scopes application-context lookup. |
| src/Mono.Android/Android.App/Activity.cs | Scopes reporting and callback operations. |
| src/Mono.Android/Android.App/ActionBar.cs | Scopes dispatcher initialization. |
| src/Mono.Android/Android.Animation/ValueAnimator.cs | Keeps duration override safe-callable. |
| src/Mono.Android/Android.Animation/AnimatorSet.cs | Keeps duration override safe-callable. |
| src/Mono.Android/Android.Animation/Animator.cs | Scopes dispatcher initialization. |
| src/Microsoft.Android.Runtime.NativeAOT/Microsoft.Android.Runtime.NativeAOT.csproj | Enables preview syntax without activation. |
| src/Microsoft.Android.Runtime.NativeAOT/Java.Interop/JreRuntime.cs | Documents VM creation contracts. |
| src/Microsoft.Android.Runtime.NativeAOT/Android.Runtime.NativeAOT/Logging.cs | Documents logging format obligations. |
| src/Microsoft.Android.Runtime.NativeAOT/Android.Runtime.NativeAOT/JavaInteropRuntime.cs | Documents and scopes native startup calls. |
| external/Java.Interop/src/Java.Interop/Java.Interop/JniRuntime.cs | Adds caller-unsafe runtime construction contract. |
| build-tools/jnienv-gen/JNIEnvEntries.cs | Defines operation-specific caller obligations. |
| build-tools/jnienv-gen/Generator.cs | Emits safety contracts and implementation regions. |
Review effort: Balanced
88a2829 to
518128e
Compare
Context: #13191 Keep the safety audit focused on caller obligations instead of expanding expression-bodied code and inferring contracts from parameter names. Declare the outer JNI generator's unsafe flags and shared caller contracts alongside each entry. Render fixed forwarding and pinning proofs without deriving prose from names or types, and preserve generated signatures and executable output. Use unsafe expressions for value-producing operations, restore expression-bodied members and converter lambdas, narrow cached JNI lookups, and remove redundant temporaries and empty handwritten finally blocks. Retain blocks where void-expression syntax, pinning or multi-step lifetimes require them. Correct the HardwareBuffer lifetime proof to identify the callee's GC.KeepAlive rather than an empty finally. Preserve API layouts, caller safety attributes, nullable Java collection elements, constructor-enforcement deferrals, real cleanup and existing behavioral fixes pending their separate-PR inheritance. Validation: fresh Debug SDK builds for APIs 37, 37.1 and 37.2; final NativeAOT runtime and existing test-APK builds; seven compiled contract/layout comparisons; deterministic JNI generation with identical non-comment output. No new compiler diagnostics. No device execution for this source. Co-authored-by: Copilot App <[email protected]>
Context: #13191 Calling `Java.Util.Spliterators.AbstractSpliterator.TryAdvance()` on a Java-defined subclass wrapped by `AbstractSpliteratorInvoker` throws on the first call: ```text 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.
Context: #13191 Keep the safety audit focused on caller obligations instead of expanding expression-bodied code and inferring contracts from parameter names. Declare the outer JNI generator's unsafe flags and shared caller contracts alongside each entry. Render fixed forwarding and pinning proofs without deriving prose from names or types, and preserve generated signatures and executable output. Use unsafe expressions for value-producing operations, restore expression-bodied members and converter lambdas, narrow cached JNI lookups, and remove redundant temporaries and empty handwritten finally blocks. Retain blocks where void-expression syntax, pinning or multi-step lifetimes require them. Correct the HardwareBuffer lifetime proof to identify the callee's GC.KeepAlive rather than an empty finally. Preserve API layouts, caller safety attributes, nullable Java collection elements, constructor-enforcement deferrals, real cleanup and existing behavioral fixes pending their separate-PR inheritance. Validation: fresh Debug SDK builds for APIs 37, 37.1 and 37.2; final NativeAOT runtime and existing test-APK builds; seven compiled contract/layout comparisons; deterministic JNI generation with identical non-comment output. No new compiler diagnostics. No device execution for this source. Co-authored-by: Copilot App <[email protected]>
Context: #13191 (comment) Requiring a JNI reference array to have the destination array's declared class rejects existing element-wise conversions. Even an empty java.lang.Object[] fails ToArray<string>() or ToArray<Java.Lang.String>() before the element converters run. Validate reference-array kind separately from element conversion while retaining exact primitive-array checks. Check each nonnull string element before string-specific JNI access, release validation-failure locals, and hand successful locals to the existing converters without changing their transfer or peer-lookup behavior. Route string copying through the checked converter and validate nested/inferred array paths before native length access. Add ten cases covering empty and populated Object[] conversions, null elements, incompatible elements with stable local-reference counts, nested string arrays and invalid nested elements. On API35 ARM64 CoreCLR Debug, the same focused 54-case suite reproduces seven failures before the fix and passes all 54 afterward. Fresh SDK builds cover APIs 37, 37.1 and 37.2; temporary selection categories are removed and the ordinary test APK rebuild passes. NativeAOT, Release and other device configurations are not claimed. Co-authored-by: Copilot App <[email protected]>
bc1580c to
b5244fb
Compare
Context: #13191 Requiring every reference-type destination to come from a Java Object[] rejects supported primitive-array conversions. ToArray<object>() and ToArray<IConvertible>() must still select the primitive reader from the source JNI signature and box each value; the non-generic GetArray(..., typeof(object)) path must retain its concrete primitive-array result. Share array-kind validation between generic and non-generic conversion. Destination-selected primitive, string, jagged-array and Java-peer readers retain their existing kind checks. Inferred and managed-boxing destinations validate the actual source is an array before native length access, then use the existing source-signature reader and managed casts. Preserve checked string elements, transfer cleanup and public signatures. Add nine cases covering empty and populated arrays of all eight JNI primitive kinds, managed-interface boxing, non-array rejection and incompatible destination kinds. The focused API35 ARM64 CoreCLR Debug suite reproduces seven failures before the fix and passes all 63 cases afterward with identical test bodies. Debug SDK builds cover APIs 37, 37.1 and 37.2; the exact final test-APK build passes after removing temporary selection categories. NativeAOT, Release and other device configurations are not claimed. Co-authored-by: Copilot App <[email protected]>
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
🔵 Needs a closer look
Cross-runtime JNI lifetime, callback ABI, and GC-bridge ownership contracts require specialist review and current-source device validation because current-tip evidence covers builds and metadata checks but no executed runtime tests.
No open issues 🎉
1 resolved since last review
Review effort: Balanced
There was a problem hiding this comment.
Review: no blocking code findings; CI pending
Reviewed all 74 changed files against base 097b23e5f2e7 at head 0f8dd14e2394. 0 errors, 0 warnings, 1 non-blocking suggestion posted inline.
The separation between raw caller obligations and internally established unsafe scopes is consistent with the preparation-only goal. The updated array checks preserve element-wise Object[] conversions and primitive boxing while checking string elements before string-specific JNI access. The added owner retention in ToArray<T>() covers exceptional exits, and the callback/template changes preserve transition cleanup. The earlier reference-array review finding is addressed by the current implementation and regressions.
CI is not yet green. Azure build 1656802 has passing Windows/macOS Android Tools checks; Linux, macOS, and Windows product builds remain in progress, with the aggregate check queued. CLA passed. The direct Azure build query required authentication, so Azure timeline, final result, and device-lane outcomes could not be independently confirmed. This is a static review; no local builds or device tests were run.
Generated by Android PR Reviewer for #13191 · copilot · gpt61 · 178.1 AIC · ⌖ 4.82 AIC · ⊞ 20K
Comment /review to run again
|
|
||
| using var array = new Java.Lang.Object (JNIEnv.NewArray (values), JniHandleOwnership.TransferLocalRef); | ||
| Assert.AreEqual ("[Ljava/lang/Object;", JNIEnv.GetClassNameFromInstance (array.Handle)); | ||
| CollectionAssert.AreEqual (expected, array.ToArray<string> ()); |
There was a problem hiding this comment.
🤖 💡 Testing — Consider running these reference-array conversion cases through the non-generic JNIEnv.GetArray(handle, JniHandleOwnership.DoNotTransfer, typeof(string)) entry point as well, including the Java-string and incompatible-element counterparts. The primitive regression above already covers both entry points, but the new Object[] narrowing cases only exercise ToArray<T>(). Since this change also updates _GetArray, covering its separate NativeArrayToManaged converter selection would protect the same compatibility guarantees there.
Rule: Cover changed API paths and edge cases.
|
@dalexsoto review |
|
In response to @simonrozsival's request: The 74-file static source review is complete at head |
Extract only the published JNI runtime preparation delta onto pinned main, preserving the current typed GC-bridge startup and deleted internal native surface. Keep legacy constructor initialization and legacy memory-safety compilation. Relocate the runtime-creation activation assertion and unsafe API baseline expectations to the preserved session patch for final Java.Interop activation. Co-authored-by: Copilot App <[email protected]>
Move the existing Spliterator source Update before the unrelated Java fixture Updates. Evaluated item identities and all metadata remain identical; preserve current-main additions without importing new upstream source. Co-authored-by: Copilot App <[email protected]>
Separate raw caller obligations from implementation scopes and document actual JNI bounds, ownership, ABI, and failure requirements. Preserve managed-safe wrappers and the user-directed raw peer constructor deferral. Reduce scope/indentation scaffolding while retaining the demonstrated collection ABI, spliterator, and array-kind bug regressions. Remove newly introduced annotation-only test matrices; archive prior proposals outside the repository. Product compilation and runtime validation remain pending. Co-authored-by: Copilot App <[email protected]>
ThreadReuse deliberately detaches and reattaches a native thread. Logging through Android.Util.Log before GetObject refreshes the cached environment can call JNI NewString through the previous attachment's invalid table. Save the prior environment before the null-instance callback returns, then leave GetObject as the operation under test and log only after it returns. Preserve the old-versus-supplied environment diagnostic, callback rooting, wrapper disposal, and result reporting on the original NUnit test thread. Co-authored-by: Copilot App <[email protected]>
Context: #13191 Keep the safety audit focused on caller obligations instead of expanding expression-bodied code and inferring contracts from parameter names. Declare the outer JNI generator's unsafe flags and shared caller contracts alongside each entry. Render fixed forwarding and pinning proofs without deriving prose from names or types, and preserve generated signatures and executable output. Use unsafe expressions for value-producing operations, restore expression-bodied members and converter lambdas, narrow cached JNI lookups, and remove redundant temporaries and empty handwritten finally blocks. Retain blocks where void-expression syntax, pinning or multi-step lifetimes require them. Correct the HardwareBuffer lifetime proof to identify the callee's GC.KeepAlive rather than an empty finally. Preserve API layouts, caller safety attributes, nullable Java collection elements, constructor-enforcement deferrals, real cleanup and existing behavioral fixes pending their separate-PR inheritance. Validation: fresh Debug SDK builds for APIs 37, 37.1 and 37.2; final NativeAOT runtime and existing test-APK builds; seven compiled contract/layout comparisons; deterministic JNI generation with identical non-comment output. No new compiler diagnostics. No device execution for this source. Co-authored-by: Copilot App <[email protected]>
Context: #13191 (comment) Requiring a JNI reference array to have the destination array's declared class rejects existing element-wise conversions. Even an empty java.lang.Object[] fails ToArray<string>() or ToArray<Java.Lang.String>() before the element converters run. Validate reference-array kind separately from element conversion while retaining exact primitive-array checks. Check each nonnull string element before string-specific JNI access, release validation-failure locals, and hand successful locals to the existing converters without changing their transfer or peer-lookup behavior. Route string copying through the checked converter and validate nested/inferred array paths before native length access. Add ten cases covering empty and populated Object[] conversions, null elements, incompatible elements with stable local-reference counts, nested string arrays and invalid nested elements. On API35 ARM64 CoreCLR Debug, the same focused 54-case suite reproduces seven failures before the fix and passes all 54 afterward. Fresh SDK builds cover APIs 37, 37.1 and 37.2; temporary selection categories are removed and the ordinary test APK rebuild passes. NativeAOT, Release and other device configurations are not claimed. Co-authored-by: Copilot App <[email protected]>
Context: #13191 Requiring every reference-type destination to come from a Java Object[] rejects supported primitive-array conversions. ToArray<object>() and ToArray<IConvertible>() must still select the primitive reader from the source JNI signature and box each value; the non-generic GetArray(..., typeof(object)) path must retain its concrete primitive-array result. Share array-kind validation between generic and non-generic conversion. Destination-selected primitive, string, jagged-array and Java-peer readers retain their existing kind checks. Inferred and managed-boxing destinations validate the actual source is an array before native length access, then use the existing source-signature reader and managed casts. Preserve checked string elements, transfer cleanup and public signatures. Add nine cases covering empty and populated arrays of all eight JNI primitive kinds, managed-interface boxing, non-array rejection and incompatible destination kinds. The focused API35 ARM64 CoreCLR Debug suite reproduces seven failures before the fix and passes all 63 cases afterward with identical test bodies. Debug SDK builds cover APIs 37, 37.1 and 37.2; the exact final test-APK build passes after removing temporary selection categories. NativeAOT, Release and other device configurations are not claimed. Co-authored-by: Copilot App <[email protected]>
|
@dalexsoto review |
|
In response to @simonrozsival's request: Review remains deferred at head |
0f8dd14 to
b69edbd
Compare
dalexsoto
left a comment
There was a problem hiding this comment.
Reviewed all 74 changed files and affected integration at b69edbdaec86, against merge-base d9e631129a3d with current target 44f58b4af5f6, reusing verified unchanged coverage and completing a separate final whole-PR pass. No blocking code issues remain.
The resolved NativeAOT initialization preserves the safety scopes, matches Java's UTC-offset argument, and seeds AppContext before managed runtime construction. The inherited Notification cleanup and SparseArray dispatch fixes are retained; the earlier Object[] finding remains fixed, and the preparation-only/activation-layer decisions are respected.
Static source review only: no builds, tests, generators, devices, or CI runs were executed.
Context: #11467 Context: #13191 Enable `updated-memory-safety-rules` in `Java.Interop` now that the preparation PRs have merged. The preparation distinguished APIs whose callers own JNI ABI, buffer, or lifetime obligations from managed wrappers that establish those guarantees internally. This change turns on compiler enforcement without making those managed wrappers caller-unsafe. **Most of the reduced diff is API bookkeeping in `PublicAPI.Unshipped.txt`, not implementation changes.** Leave `PublicAPI.Shipped.txt` unchanged. Record the 156 changed shipped contracts as `*REMOVED*` entries followed by their replacements, and update already-unshipped entries in place. These changes track `unsafe` markers and the two runtime-constructor records; they do not change CLR signatures. The additional lines make the released-to-current contract changes explicit rather than rewriting the released baseline. ### Activation Add the compiler feature and remove the transitional declaration-level `unsafe` modifiers marked for removal at opt-in: pointer storage and address getters, address-only `JniNativeMethod` construction, owned control-block allocation, and `StartCreateInstance`, which ignores its pointer argument. Narrow the typed remapping properties to unsafe setters only. Existing implementation-local unsafe regions and their concrete safety explanations remain intact. Keep all nine `GetElements()` methods safe-callable and all eight ref-returning array indexers caller-unsafe. Raw JNI consumption, registration, VM construction, `FinishCreateInstance`, and frees retain their caller contracts. Preserve the six released RC2 native-int accessors and two virtual hooks as safe-callable, warning-obsolete exceptions, including existing override/base dispatch. Only Java.Interop opts in; Mono.Android and customer projects do not. There are no runtime algorithm, allocation, ownership, cleanup, or native-layout changes, and no new tests or generic comment blocks. Main's `IntPtr` callback storage is preserved. `Architecture.md` receives only the activation and accuracy updates; Copilot audit guidance belongs to [#13332](#13332). Broader non-Throwable raw-peer constructor enforcement remains deferred because accepted zero/`DoNotTransfer` derived initializers would require a separate initialization redesign. The approved Object/Throwable None-only route remains intact. Partial JNI registration ownership redesign also remains deferred: callers must retain callback roots after failed or partial registration. This PR does not close #11467.
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. Co-authored-by: Copilot App <[email protected]>
Context: #13191 Context: #11467 `Java.InteropTests.JnienvTest.ThreadReuse()` can crash in its own diagnostic logging before reaching the operation it is supposed to test. The native fixture first calls managed code with a null instance, then detaches the pthread from the JVM, waits for GC, and reattaches before invoking the callback with a Java object. The cached `JNIEnv.Handle` can still refer to the previous attachment; `Java.Lang.Object.GetObject()` is meant to refresh it before use. Rebuilding the test with the pre-PR logging order reproduced a **SIGSEGV** on CoreCLR. The first, null-instance callback logged successfully; the second callback crashed while constructing a Java string for `Android.Util.Log.Info()`. The captured stack was: ```text Fatal error. Got a SIGSEGV while executing native code. at Java.Interop.JniNativeMethods.NewString(IntPtr, Char*, Int32) at Java.Interop.JniEnvironment+Strings.NewString(Char*, Int32) at Java.Interop.JniEnvironment+Strings.NewString(System.String) at Android.Runtime.JNIEnv.NewString(System.String) at Android.Util.Log.Info(System.String, System.String) at Android.Util.Log.Info(System.String, System.String, System.Object[]) at Java.InteropTests.JnienvTest+<>c__DisplayClass9_0.<ThreadReuse>b__0(IntPtr, IntPtr) ``` This is process termination, not a failed NUnit assertion: instrumentation returned `shortMsg=Process crashed.` The logging itself crosses JNI through `NewString()` before `GetObject()` can refresh the cached environment. Capture `JNIEnv.Handle` at callback entry, before the null-instance early return, so the first callback still seeds the cache. Leave `GetObject(env, instance, DoNotTransfer)` as the operation under test, then log the saved handle and supplied environment after it returns. Do not add an eager transition that would bypass the regression. This repairs the existing test; it adds no new test or product-runtime change. The native fixture, ownership, wrapper disposal, callback rooting, and original-thread assertion are unchanged. Related reports: #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 useful context, not confirmed duplicates of this stale-environment SIGSEGV; this PR does not claim to resolve or close those reports. The exact diagnostic-ordering bug is documented in #11467.

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
unsafemodifier 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
JValuestores bits, and the readonlyUnsafeAccessormethods access typed, GC-tracked managed static fields.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 handwrittenfinallyblocks without removing actual transition or reference cleanup.RequiresUnsafeflag. 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
Featuresremain 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, 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; ThreadReuse diagnostics using a stale JNI environment in #13337; checked generic array conversion and owner retention in draft #13339; and
Collection.remove(Object)'s JNI signature in #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 (
ThreadReusefailing because the native fixture library was missing), #3363 (NewString()during logging ending in JavaOutOfMemoryError), and #7623 (native crashes duringAttachCurrentThread()). 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.Validation
The current published source is
bc1580c3f46c, above binding preparatione4473175aba5. The final source hashes match the locally validated tree; the commit contains no subsequent source changes.Fresh Debug SDK builds passed for APIs 37, 37.1, and 37.2, including workload configuration. Final runtime, generator, and existing runtime-test APK builds passed. No new compiler diagnostics appeared against the baseline. Seven compiled assembly contract/layout comparisons matched, normalizing only compiler-generated state-machine ordinal suffixes. Two actual JNI generator runs were byte-identical; the refactoring preserved all non-comment output bytes, caller XML, 168 method signatures, 157 caller-unsafe methods, and 164 implementation proofs.
Current-source commands and results
ARTdenotes the local validation artifact directory;-bl:only selects the recorded binary-log destination. The local SDK was12.0.100-alpha.1.26523.103.make prepare CONFIGURATION=Debugmake leeroy CONFIGURATION=Debug MSBUILD_ARGS='-m:1 -nr:false -p:UseSharedCompilation=false'./dotnet-local.sh build src/Microsoft.Android.Runtime.NativeAOT/Microsoft.Android.Runtime.NativeAOT.csproj --no-restore -c Debug -m:1 -nr:false -p:UseSharedCompilation=false -v:minimal -bl:"$ART/final-runtime.binlog"./dotnet-local.sh msbuild Microsoft.Android.slnx -t:BuildExtraApiLevels -p:Configuration=Debug -m:1 -nr:false -p:UseSharedCompilation=false -v:minimal -bl:"$ART/final-extra-api.binlog"./dotnet-local.sh build build-tools/jnienv-gen/jnienv-gen.csproj --no-restore -c Release -m:1 -nr:false -p:UseSharedCompilation=false -v:minimalDOTNET_ROLL_FORWARD=Major DOTNET_ROLL_FORWARD_TO_PRERELEASE=1 ./dotnet-local.sh bin/BuildRelease/jnienv-gen.dll -o="$ART/generated.g.cs"-o="$ART/generated-repeat.g.cs", thencmp "$ART/generated.g.cs" "$ART/generated-repeat.g.cs"passed../dotnet-local.sh build tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -c Debug -m:1 -nr:false -p:UseSharedCompilation=false -v:minimal -bl:"$ART/tests-build.binlog"git diff --checkNo device tests or host test suites were executed for this tip; the current pass compiled the existing tests and checked source/output/metadata equivalence. No current Release SDK or activated-stack runtime result is claimed.
Historical full validation of runtime
544a7a9aand activated source63b95fa9included Debug/Release SDKs and 491 host tests. On API35 arm64, both legacy and activated CoreCLR suites passed 991 tests with 0 failures and 7 skips; both NativeAOT suites passed 928 with 0 failures and 7 skips. ThreadReuse passed all four lanes, with a different prior/supplied JNI environment observed in activated CoreCLR. Those results predate the latest upstream rebase and refactoring and are not validation of the current tip. Independent-fix validation is recorded in the corresponding PRs.No CI-green claim is made.