Skip to content

[Unsafe][Java.Interop] Opt into updated C# memory-safety rules - #13192

Merged
simonrozsival merged 10 commits into
mainfrom
simonrozsival-unsafe-java-interop-activation-stack
Nov 2, 2026
Merged

simonrozsival merged 10 commits into
mainfrom
simonrozsival-unsafe-java-interop-activation-stack

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

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.

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.

Validation and publication

Rebased and pushed onto current main. The published head is 1dd097958533ab09a2c62241197d9064909df535, based on main d9811fc24a96c12f28f52ff7abaac2d9e387d5dd; GitHub reports no merge conflicts. The diff is 14 files, +412/-115; PublicAPI.Unshipped.txt accounts for +372/-58. Outside that file, the diff is +40/-57, including the final two private-field modifier removals. PublicAPI.Shipped.txt and the Copilot instructions have no net changes.

The effective API inventory is identical before and after moving the records into Unshipped. With the existing preview SDK 12.0.100-alpha.1.26509.101, dotnet build external/Java.Interop/src/Java.Interop/Java.Interop.csproj -c Debug -m:1 -p:DotNetTargetFrameworkVersion=11.0 -p:UseSharedCompilation=false -nr:false -v:minimal, setting DotnetToolPath to that same preview host, passed with 0 warnings and 0 errors; the corresponding -c Release build also passed with 0 warnings and 0 errors, including the public API analyzer.

Fresh Debug/Release builds and actual implementation/reference metadata checks passed for this exact pushed source, including rules version 2 and the intended caller contracts. Canonical T4 rendering preserves main's newly merged unsafe (...) expression contexts and matches the generated array source. The rebase preserves main's executable code apart from the reviewed declaration modifiers; comment reductions and baseline bookkeeping introduce no runtime algorithm changes. Full Android SDK packaging and device suites have not been rerun for this new main rebase; no CI-green claim is made.

Earlier exact snapshots—legacy runtime 544a7a9 and activated top 63b95fa—passed Debug/Release SDK builds for APIs 37/37.1/37.2, actual implementation/reference/runtime image audits, caller probes, unchanged RC2 consumer checks, and four API 35 arm64 full suites. CoreCLR had 991 passed, 0 failed, 7 skipped in each mode; NativeAOT had 928 passed, 0 failed, 7 skipped in each mode. ThreadReuse passed in all four lanes, including an activated CoreCLR run that observed a changed JNI environment. Those results remain evidence for those snapshots, not the current rebase.

Original published-chain validation and commands

These older results belong to activated source cd9e12f2d482a0ed9260c7e866b2cb73bbf5e212 and unactivated preparation source bf917a5d38c36e87e4b8e2ced7739ccdc8246d4a. The original activation commit was 13 files, +483/-213 on runtime preparation 88a2829eb7d3d91fa27ebfd085c7d1be2c176c62. They are actual local SDK results, not proof of the later reduced or rebased source.

  • DOTNET_PROCESSOR_COUNT=2 CMAKE_BUILD_PARALLEL_LEVEL=2 MSBUILDDISABLENODEREUSE=1 make prepare CONFIGURATION=Debug MSBUILD_ARGS='-m:1 -p:UseSharedCompilation=false': passed, 0 warnings/errors. The same make prepare command with CONFIGURATION=Release also passed, 0 warnings/errors.
  • DOTNET_PROCESSOR_COUNT=2 CMAKE_BUILD_PARALLEL_LEVEL=2 MSBUILDDISABLENODEREUSE=1 make leeroy CONFIGURATION=Debug MSBUILD_ARGS='-m:1 -p:UseSharedCompilation=false': passed the primary SDK, APIs 37/37.1/37.2, API compatibility, and workload setup; 39 existing primary and 62 extra-API warnings, 0 errors. The corresponding Release command passed with 57 existing primary and 62 extra-API warnings, 0 errors; warnings were retained, not suppressed.
  • NUNIT_MSBUILD_ARGS set to newline-separated -m:1, -p:UseSharedCompilation=false, and -nr:false, followed by ./dotnet-local.sh test bin/TestDebug/net10.0/Xamarin.Android.Build.Tests.dll --filter 'FullyQualifiedName~JniEnvMemorySafetyTests': 6 passed, 0 failed/skipped. The bin/TestRelease run also passed all 6. These were the original compiler-contract fixtures, which were subsequently removed from the reduced proposal under the bug-only-test policy.
  • All 18 implementation/reference/runtime images across three API levels and two configurations passed the original rules-2, caller-contract, safe acquisition/address getter, ref-return ABI, and released-RC2-signature audits. All 32 actual-library metadata cases passed; an unchanged consumer compiled against the actual .NET 11 RC2 reference pack bound all eight legacy MemberRefs and preserved override dispatch.
  • Original canonical JNI C#/C/header generation and T4/output checks passed. Compiler probes accepted safe address getters and explicit unsafe callers, rejected exactly seven boundary violations with CS9362, and accepted all eight legacy calls without unsafe with exactly eight deprecation warnings. For the later 63b95 validation, four canonical pairs were byte-exact; the unchanged main JniFields output had only its inherited UTF-8 BOM difference, which was recorded rather than rewritten.
Original SDK mode Runtime Passed Failed Skipped
Preparation, rules not activated CoreCLR 1,012 0 7
Preparation, rules not activated NativeAOT 946 0 7
Activated original SDK CoreCLR 1,041 0 10
Activated original SDK NativeAOT 976 0 7

Canonical fixture builds used ./dotnet-local.sh build tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -t:SignAndroidPackage -p:RuntimeIdentifier=android-arm64 -p:IncludeCategories= -p:UseSharedCompilation=false -m:1, with -c Debug -p:PublishAot=false -p:Optimize=false for CoreCLR and -c Release -p:PublishAot=true -p:Optimize=true for NativeAOT. Both passed: CoreCLR had 0 warnings/errors; NativeAOT retained 11 existing EventSource/trimming/AOT warnings with 0 errors.

Activated suites used canonical MTP dotnet test --no-build from the test-project directory with matching configuration/runtime properties and an exact owned --device. Preparation suites used the same SDK Android adapter through dotnet test --test-modules Microsoft.Android.Run.dll --root-directory <owned-SDK-tools> -- --adb=<adb> '--adb-target=-s <owned-serial>' --package=Mono.Android.NET_Tests --instrument=xamarin.android.runtimetests.TestInstrumentation --report-trx --results-directory <results>. This avoided the pinned CLI's unexpected DeployToDevice call despite --no-build; it was a harness workaround, not a product fix or a different adapter.

The original activated CoreCLR run's three extra skips were existing diagnostic metadata cases against a Release-built Java.Interop library. Installed APKs, actual CoreCLR fast-deploy payloads, and real AArch64 NativeAOT libraries were verified rather than inferred from package names. Failed deployment/identity attempts and native crashes remain failed attempts, not passing tests. Owned emulators, processes, homes, and ports were released within their authorized deadlines; no shared or physical devices were used.

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

Public JNI contract activation across compiler modes and runtime packs warrants final human review of compatibility and validation evidence.

No open issues 🎉

What changed in this PR

Activates updated C# memory-safety rules in Java.Interop, completing the prepared JNI caller-contract migration without enabling them in Mono.Android or customer projects.

Changes:

  • Enforces unsafe caller obligations while preserving safe address getters and managed array acquisition.
  • Updates API baselines, paired generated output, and architecture documentation.
  • Adds compiler and metadata regression tests for safety contracts and legacy compatibility.
File Description
tests/​Mono.Android-Tests/​Java.Interop-Tests/​Java.Interop/​JniCallerSafetyTests.cs Tests caller-contract metadata and legacy compatibility.
tests/​Mono.Android-Tests/​Java.Interop-Tests/​Java.Interop/​JavaPrimitiveArraySafetyTests.cs Tests unsafe ref indexers and safe acquisition/getters.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​JniEnvMemorySafetyTests.cs Adds consumer compilation checks.
external/​Java.Interop/​src/​Java.Interop/​PublicAPI.Unshipped.txt Records pending unsafe API contracts.
external/​Java.Interop/​src/​Java.Interop/​PublicAPI.Shipped.txt Updates existing API safety annotations.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JniRuntime.JniTypeManager.cs Restricts unsafe requirements to pointer setters.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JniPeerMembers.cs Removes pointer-field unsafe modifier.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JniMethodInfo.cs Updates diagnostic pointer-field declarations.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JavaPrimitiveArrays.tt Keeps generated address getters safe.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JavaPrimitiveArrays.cs Synchronizes generated address getters.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JavaArray.cs Updates pointer storage and address getter declarations.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop.csproj Enables updated memory-safety rules locally.
external/​Java.Interop/​Documentation/​Architecture.md Documents activated contracts and compatibility boundaries.

Review effort: Balanced

simonrozsival added a commit that referenced this pull request Oct 22, 2026
Replace `ref *InvalidJniObjectReference` constructor sentinels with local default references and the options-only forwarding chain without invoking the allocating default base constructor.  Keep all 11 managed constructors caller-safe: parameterless `Java.Interop.JavaObject` and `Java.Interop.JavaException`, `Java.Interop.JavaObjectArray<T>(int)`, and eight primitive-array length constructors.  Pointer/native initialization stays inside explicit local unsafe blocks.  Keep `JavaPrimitiveArrays.tt` and its canonically regenerated `.cs` together.

The audit adds concrete `// SAFETY:` proofs and documents actual raw-JNI ABI, thread, lifetime, aliasing, transfer, and failure obligations while preserving genuine caller-unsafe declarations.  It does not redesign ownership, change allocations, or introduce new accepted-call restrictions.

**User-directed constructor layout:** the public parameterless `JavaException` remains first and delegates to a private options constructor below it.  Its original `if (PeerReference.IsValid) return;` is preserved.  The private constructor conditionally captures an already-installed peer's Java stack; fresh creation keeps its existing JNI sequence and capture.  Each constructor has one capture site and each path captures once.  This private forwarding change was explicitly requested in review; it adds no public API.

**Separate bug coverage:** the pinned extraction source omitted stack capture on the preinstalled-peer path; preserving the original delegating-constructor behavior avoids that regression.  `JavaSideExceptionConstructorCapturesStackFromPreinstalledPeer` exercises real Java-origin activation.  `Transition_RejectsNullEnvironmentPointer` covers zero-JNIEnv rejection before TLS mutation/native dispatch.  These are the only two new construction bug tests; the added ordinary managed-construction parity test was removed.  Existing baseline tests remain intact.

`Features` stays off in this preparation layer.  Final **Java.Interop-only** compiler activation/metadata assertions are in [#13192](#13192).  **Mono.Android product feature activation is outside this stack.**
simonrozsival added a commit that referenced this pull request Oct 23, 2026
Prepare UTF-8 remapping metadata for the updated C# memory-safety rules without breaking the APIs shipped in .NET 11 RC2. Related to #11467.

Store borrowed JNI type names, method names, and signatures as `byte*`, while keeping JNI handles and method IDs as opaque `IntPtr` values. Add typed remapping properties and the `GetReplacementTypeInfoUnsafe` / `GetReplacementMethodInfoUnsafe` hooks, and use them throughout peer-member lookup and the runtime remapping consumers. Document the NUL-termination and lifetime requirements for retained buffers, preserving managed-string alternatives, lazy caching, pointer precedence, and zero-copy UTF-8 literals.

Keep the six released native-int accessors and both legacy virtual hooks safe-callable and warning-obsolete. The typed hooks continue to dispatch through the legacy virtual slots so existing overrides and base calls still work.

Make remapping diagnostics format pointer addresses rather than dereference borrowed memory. Include coverage for diagnostic formatting, legacy compatibility, override dispatch, and borrowed metadata reads.

This PR does not enable the updated memory-safety rules; activation is handled separately in [#13192](#13192).
simonrozsival added a commit that referenced this pull request Oct 28, 2026
Context: [#11467](#11467), revisiting `unsafe` in generated code and libraries.
Context: [#13070](#13070), the original combined memory-safety change; final enforcement is separated into [#13192](#13192).

Java.Interop uses native pointers both to consume caller-owned storage and to implement wrappers which own their buffers, pinning, and cleanup.  Broad `unsafe` contexts obscure that distinction.  Under the updated memory-safety model, a caller-unsafe declaration also does not replace an implementation-local unsafe region.  Prepare the handwritten owned-memory implementations without enabling the new enforcement rules or redesigning runtime behavior.

### Owned-memory implementations

Scope unchecked operations around control-block allocation/access/release, managed string and array pinning, native name buffers, JNI argument forwarding, and JavaVM table access and thread attachment.  Add concrete `// SAFETY:` explanations to local regions and `<safety>` contracts where callers must provide descriptor-compatible arguments or borrowed storage with sufficient bounds, lifetime, and thread affinity.  Managed-owned wrappers remain safe-callable when the implementation discharges those obligations.

Preserve CLR signatures, virtual dispatch, GC reachability, native layout, allocation choices, and failure/cleanup ordering.  Opaque JNI handles and IDs, callback addresses, and marshaled thread-name addresses remain `IntPtr`.  Mark the overlapping `Java.Interop.JniArgumentValue` scalar fields `safe`: every view is reference-free and retains its existing offset and size.  Label legacy-only unsafe modifiers so their eventual removal is distinct from genuine caller obligations.

Callback lifetime documentation requires successful unregistration and completion of in-flight callbacks before releasing callback storage.  This does not redesign the inherited success-only registration rooting policy or add partial-registration recovery.  The generated `JniEnvironment.StaticMethods` and `InstanceMethods` APIs are not reclassified here.

### Compiler preparation

Keep `<LangVersion>preview</LangVersion>` local to `Java.Interop.csproj`, with a comment explaining its removal condition.  The selected compiler still requires preview for safe explicit-layout fields and relaxed pointer declarations; this is parser preparation, not an opt-in to `updated-memory-safety-rules`.  No `Features` activation, generated/T4 changes, public API baseline changes, or dependency updates are included.

Record the review-derived audit rules in the existing Java.Interop contributor instructions and explain the owned-memory boundary in the architecture documentation.  Preserve the existing tests rather than adding annotation-only matrices.

### Validation

Results below apply to published revision `e8539717ddb66308737ff6f3fd590b87600591a2`, using SDK `12.0.100-alpha.1.26509.101`.  The later inline-review span/stackalloc follow-ups remain local and are not included in this published revision.

Run the following command for each `version=10.0,11.0` and `configuration=Debug,Release`, with `DOTNET_PROCESSOR_COUNT=2`, `CMAKE_BUILD_PARALLEL_LEVEL=2`, `DOTNET_ROLL_FORWARD=Major`, `MSBUILDDISABLENODEREUSE=1`, and `DOTNET_CLI_USE_MSBUILD_SERVER=0`; put the checkout's `bin/Debug/dotnet` first on `PATH`:

	bin/Debug/dotnet/dotnet build external/Java.Interop/src/Java.Interop/Java.Interop.csproj --no-restore -c "$configuration" -p:DotNetTargetFrameworkVersion="$version" -p:TreatWarningsAsErrors=true -p:UseSharedCompilation=false -m:1 -nr:false -v:minimal -nologo

**Result:** all four library builds passed with zero warnings and zero errors.  Initial missing-target `NETSDK1005` attempts failed when assets described the other framework; cache-only restores of the core project and its direct generator dependency recovered them, followed by successful reruns.  With `$artifacts` denoting the retained session-evidence directory, the recovery command was:

	bin/Debug/dotnet/dotnet restore external/Java.Interop/src/Java.Interop/Java.Interop.csproj -p:DotNetTargetFrameworkVersion="$version" -p:RestoreSources="$artifacts/owned-audit-empty-feed" -p:RestoreAdditionalProjectSources= -p:NuGetAudit=false -p:UseSharedCompilation=false -m:1 -nr:false --disable-parallel -v:minimal -nologo

A signed, session-only host runner links the unchanged production `JniNativeInterfaceTests.cs` fixture and checks each built library:

	bin/Debug/dotnet/dotnet build "$artifacts/owned-layout/OwnedLayout.csproj" --no-restore -c "$configuration" -p:LibraryFramework="net$version" -p:UseSharedCompilation=false -m:1 -nr:false -v:minimal -nologo
	bin/Debug/dotnet/dotnet "$artifacts/owned-layout/bin/$configuration/net11.0/Java.Interop-Tests.dll"

**Result:** all four runner builds passed with zero warnings/errors; each run passed the eight preexisting function-table offset/signature cases and two session-only reference-free guards for `JniArgumentValue` and `JniNativeMethod`.  No repository tests are added.  These are host metadata checks, not JNI execution.  Full-SDK, device/runtime, and final-enforcement validation for this published revision are not claimed; earlier source-specific SDK and IL comparisons are not evidence for this revision.
Base automatically changed from simonrozsival-unsafe-runtime-contracts-stack to main October 31, 2026 14:48
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 6 commits November 1, 2026 07:48
Enable project-local caller enforcement after the focused preparation layers. Keep address getters and managed acquisition safe, enforce borrowed setters and raw ABI contracts, and preserve the warning-obsolete RC2 IntPtr APIs.

Retain compiler and metadata regressions for runtime creation, borrowed-pointer publication, primitive-array references, and safe legacy compatibility boundaries.

Co-authored-by: Copilot App <[email protected]>
Keep address-only descriptor construction, owned allocation, and the
ignored-buffer instance-allocation step caller-safe.  Preserve unsafe
registration, release, and constructor-invocation boundaries without
changing storage, signatures, allocation, expressions, or cleanup.

Remove final-layer annotation-only compiler and metadata fixtures at the
user's request.  Keep inherited tests unchanged for their owning layers
to remove, and retain the necessary runtime-constructor API records.
Keep RC2 compatibility slots and array acquisition/ref-return contracts.

Static source and patch checks pass; existing canonical T4 output still
matches both recorded renders.  SDK/compiler/runtime validation and
integration onto revised parents remain pending separate authorization.

Co-authored-by: Copilot App <[email protected]>
Persist the user's audit boundaries in the shared contributor guidance.
Separate caller contracts from native implementation contexts, minimize
indentation churn, and reserve new tests for concrete behavior fixes.

Keep this guidance change separate from production activation and parent
integration.  It adds no runtime behavior, API, build or test scaffolding.

Co-authored-by: Copilot App <[email protected]>
Match the thirty-three raw JNI overloads now declared caller-unsafe by the merged canonical generator.  Update only API-baseline unsafe markers; retain every signature and the existing generated implementation.

Focused net11.0 Debug and Release builds pass with zero warnings or errors.  Implementation and reference metadata checks preserve rules2, safe acquisition/address storage, unsafe raw consumption, and released compatibility slots.

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

Remove the duplicate Copilot audit-policy section from this activation branch. The dedicated instructions PR owns that change. Preserve all existing main instructions and leave the activation code untouched.

Co-authored-by: Copilot App <[email protected]>
Keep the existing architecture structure and remove duplicated audit-policy and pointer-lifetime exposition. Document the activated compiler metadata, safe address operations, and caller contracts where they already belong.

Preserve current native ownership, RC2 dispatch, and internal Throwable initialization limits. Clarify that deferred raw-constructor enforcement concerns non-Throwable peers and that Mono.Android/customer projects remain separate opt-ins. No implementation changes.

Co-authored-by: Copilot App <[email protected]>
simonrozsival and others added 4 commits November 1, 2026 07:49
Keep the typed address getter change focused on removing its transitional unsafe declaration. The repeated general pointer guidance adds noise without clarifying this getter; retain the concrete acquisition/ref-return safety contracts and implementation SAFETY rationale.

Regenerate all eight getters from the canonical template. No declarations or executable code change.

Co-authored-by: Copilot App <[email protected]>
Drop the repeated address-getter prose and the StartCreateInstance implementation narration. Existing caller safety contracts and local SAFETY explanations already cover the relevant obligations. Keep activation focused on declaration and metadata changes.

No new comment blocks remain in the activation code diff; all existing safety contracts and executable code are unchanged.

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

Keep the released PublicAPI.Shipped.txt baseline unchanged. Record each of the 156 unsafe-marker changes as an old-entry removal and replacement in PublicAPI.Unshipped.txt, following existing API-change bookkeeping. Preserve all existing unshipped entries and the runtime-constructor pair.

The effective API inventory is unchanged. Focused Java.Interop net11.0 Debug and Release builds pass with zero warnings and errors, including the public API analyzer.

Co-authored-by: Copilot App <[email protected]>
The memory-safety feature is enabled, so the private JavaObject and JavaException control-block pointer fields no longer need legacy unsafe declaration syntax. Remove their opt-in notes as well; retain NonSerialized and every implementation-local unsafe scope.

Static checks confirm only these declarations and notes changed. No public API entries or runtime behavior change.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival
simonrozsival force-pushed the simonrozsival-unsafe-java-interop-activation-stack branch from cd9e12f to 1dd0979 Compare November 1, 2026 06:50
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13192

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

Verdict: no blocking code findings. Reviewed all 14 changed files at 1dd097958533ab09a2c62241197d9064909df535, including their full source context and relevant consumers. 0 errors, 0 warnings, 1 non-blocking documentation suggestion, posted inline.

The activation preserves the intended distinction between safe address retrieval/managed-owned operations and caller-unsafe JNI consumption. All nine GetElements() methods remain safe, all eight borrowed-ref indexers remain unsafe, and the typed remapping properties restrict only their setters. The array template and generated source change together; the released API baseline remains untouched, and the inspected declaration changes preserve CLR signatures and runtime algorithms.

CI and validation limits: All 41 reported GitHub checks are successful, including the aggregate dotnet-android check for Azure build 1658538. Independent Azure build/timeline inspection was unavailable because the CLI could not complete its unauthenticated queries, so I cannot independently confirm underlying stage or non-gating device-test results. Local compilation was not run: this environment has SDKs through .NET 10, not the preview compiler required by this branch. The PR description's earlier build/device results were treated as author-reported evidence, not fresh validation of this review.

Generated by Android PR Reviewer for #13192 · copilot · gpt61 · 58.4 AIC · ⌖ 7.86 AIC · ⊞ 19.3K
Comment /review to run again

// Note: Remove unsafe with the memory-safety opt-in; required only for legacy pointer syntax.
// SAFETY: Cast the checked address only; no dereference or lifetime extension.
public new unsafe Boolean* Elements => unsafe ((Boolean*) ElementsPointer);
public new Boolean* Elements => unsafe ((Boolean*) ElementsPointer);

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.

🤖 💡 Documentation — Consider adding XML <remarks> for this getter in JavaPrimitiveArrays.tt, then regenerating all eight typed Elements properties. The getter is correctly safe-callable because it only returns an address, but the returned buffer is still borrowed: dereferencing it requires keeping the acquisition and Java array peer alive and excluding concurrent release/disposal. The adjacent lifetime documentation belongs to the indexer, while this public pointer getter currently exposes only an implementation comment, so its IntelliSense does not communicate that distinction. This does not require making the getter caller-unsafe.

{Rule: Document borrowed-pointer lifetime without conflating address retrieval with unsafe consumption}

@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto review

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed all 14 changed files and the affected JNI generation, caller-contract, API-baseline, runtime/consumer and current-target integration paths at 1dd097958533ab09a2c62241197d9064909df535. No high-confidence blocking issue found. The activation remains confined to Java.Interop, preserving safe acquisition/address getters, caller-unsafe JNI and borrowed-reference obligations, and the accepted legacy compatibility exceptions.

Static source review with existing CI evidence inspected; no builds, tests, generators or devices were run.

@simonrozsival
simonrozsival merged commit d6ad29b into main Nov 2, 2026
41 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-unsafe-java-interop-activation-stack branch November 2, 2026 11:34
jonathanpeppers pushed a commit that referenced this pull request Nov 4, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Revisit use of unsafe in generated code and in libraries

3 participants