Repository navigation
Description
Track the migration of .NET for Android's handwritten and generated interop code to the updated C# memory-safety model described in Improving C# memory safety and the language proposal.
Status as of 2026-10-29: the initial source-only assessment has progressed into merged correctness fixes and preparation changes. Compiler enforcement, binding-generator preparation, and the remaining Android runtime work are still in flight. This is not a completed repository-wide audit or a claim that all Android applications now use the new model.
Upstream tracking: dotnet/runtime#125800 and dotnet/csharplang#9704. The article describes an opt-in rollout toward .NET 12; the exact compiler, language version, reference assemblies, and opt-in mechanism must be checked as they evolve.
What we have already done
Merged correctness fixes and removal of unnecessary unsafe code
| PR | Result |
|---|---|
| #13041 | Removed unsafe managed-memory access from the existing CRC64 helpers, Files.XorLength, and typemap scanner UTF-8 encoding. Preserved the legacy CRC variant, hash bytes, offsets, incremental behavior, and naming policies; removed AllowUnsafeBlocks only where evaluated project inputs no longer needed it. |
| #13042 | Replaced name-based callback-delegate reinterpretation with actual delegate-type checking. A matching simple type name is not proof that Unsafe.As is valid. |
| #13043 | Added bounds validation before forwarding managed character arrays and lengths to JNI string creation, preserving the intended null behavior. |
| #13053 | Added primitive-array lease index bounds checks and checked size calculations. These guards address out-of-bounds access, not the separate lifetime problem of an escaped ref. |
The broader hashing replacement in #13036 remains draft/parked. It is separate from the already-merged removal of unsafe access in #13041; adopting a different hash engine is not a prerequisite for this migration.
Merged interop preparation
| PR | Result |
|---|---|
| #13156 | Documented callback ABI, aliasing, lifetime, and in-flight-call obligations. Retained the original registration array after successful JNI registration and corrected teardown/owner-retention behavior without cloning the array or redesigning registration ownership. Partial-registration recovery remains explicitly deferred. |
| #13183 | Prepared managed peer construction, replacing invalid-reference sentinels with local default references where appropriate and adding precise local unsafe scopes. Retained the reviewed initialization paths and corrected Java-origin JavaException stack capture for an already-installed peer. The existing eight registration test cases were restored and preserved. |
| #13184 | Added typed borrowed UTF-8 remapping surfaces and documented termination/lifetime requirements. Kept the eight released legacy APIs safe-callable and warning-obsolete, with virtual dispatch preserved. Diagnostics now print addresses rather than reading arbitrary borrowed memory. Complete zero-copy u8 literals remain intact. |
| #13186 | Kept all nine GetElements() acquisitions safe-callable and classified the eight escaped-ref indexers as caller-unsafe. Removed 40 implementation-only method modifiers from managed array operations, replacing them with explicit, justified body blocks. Updated the canonical T4 template and output together; preserved guards, allocation, ownership, and release behavior. |
| #13187 | Audited owned buffers, pinning, control blocks, native lookup, VM attachment, argument storage, and cleanup. Added caller contracts only where obligations remain with the caller, narrow implementation contexts with // SAFETY: explanations, and documented legacy-syntax exceptions. Recorded the review rules in the Java.Interop contributor instructions. |
| #13188 | Prepared the low-level JNI generator, raw forwarders, marshaling/invocation templates, and handwritten call sites. Documented descriptor/ABI, buffer, direct-buffer, critical-array, and callback obligations while keeping managed-owned wrappers safe-callable. Canonical generators/templates and their checked-in output were updated together. |
These are preparation changes, not blanket compiler activation. The original combined #13070 was closed unmerged and superseded by the smaller layers.
What remains
The remaining PRs are still open, not completed work:
| PR | Remaining layer |
|---|---|
| #13189 | Opt the two Android build-task projects into the updated rules locally; classify native declarations and audit borrowed PEReader resource-stream consumption and disposal. Do not change customer-project compiler settings. |
| #13190 | Prepare the binding generator and generated managed bindings: safe managed entry points, genuine raw-callback contracts, explicit body contexts, and matching existing golden outputs. Its latest local rebase is not yet a published or fully validated combined-stack revision. |
| #13191 | Complete the outer JNI generator and Android runtime/collection/conversion surfaces, including ABI corrections and their focused regression coverage. The locally prepared runtime work also contains the ThreadReuse test-diagnostic correction described below. |
| #13192 | Enable the updated rules for Java.Interop, complete the declaration/field transitions and API-baseline metadata, and enforce compatibility against real implementation and reference assemblies. This is not a global opt-in for Mono.Android or customer applications. |
- Finish and reconcile these layers against their current merged parents; validate the resulting source before publication/merge.
- Recheck the supported compiler switch, language baseline, and BCL annotations before the .NET 12 rollout. Remove temporary preview overrides when supported; Remove temporary memory-safety LangVersion=preview overrides when no longer required #13085 tracks that cleanup.
- Preserve the released compatibility exceptions and virtual dispatch while introducing new caller contracts.
- Keep the partial-registration ownership/recovery limitation explicit. JNI can partially install methods before reporting failure; successful-registration retention does not make the failure path self-owning or automatically recoverable.
- Address the broader non-
Throwableraw-peer constructor policy only with an agreed safe initialization design. Do not mechanically break existing derived constructors that use zero/DoNotTransferinitialization. - Continue reviewing paths outside normal C# enforcement, especially directly emitted PE/IL, reflection/dynamic invocation, and native typemap/callback integration. Compiling an emitter does not prove that the assembly it emits has the right safety contracts.
What we have learned
1. Caller contracts and implementation contexts are separate decisions
Under the updated model, member-level unsafe propagates a requirement to callers; it does not make the entire member body an unsafe context. An unsafe constructor's initializer context must also be considered separately from its body. Actual activated builds caught missing interior contexts that legacy compilation accepted.
For each audited operation:
- Use
/// <safety>for the caller's residual obligations: valid extent, ABI/descriptor, lifetime, aliasing, current-thread environment, and failure-path requirements. - Put unchecked operations inside explicit
unsafe { ... }regions with concrete// SAFETY:explanations. - Leave a managed wrapper safe-callable when its guards, ownership, pinning, and cleanup establish those invariants internally.
Do not turn every method containing a pointer or a safety comment into a caller-unsafe API. Conversely, an IntPtr signature or a nonzero check does not discharge native-memory obligations.
2. Carrying an address is not the same as consuming its storage
Address-only getters, descriptor construction that merely stores addresses, and owned allocation do not automatically impose caller obligations under the new model. Dereferencing, retaining borrowed storage, freeing it, or invoking a descriptor-dependent native function can.
This corrected an overbroad assumption in the initial assessment: a raw address getter is not caller-unsafe merely because it returns a pointer. The escaped-ref array indexers still need lifetime contracts because the returned managed reference can outlive its acquisition.
Do not convert every opaque JNI handle, method/field ID, callback address, or marshaled allocation to a typed pointer. Preserve the actual representation and released ABI unless a specific boundary requires a change.
3. Bounds checks and lifetime proofs solve different problems
A bounds/disposed check at acquisition cannot protect a returned ref after Release() or Dispose(), nor synchronize concurrent disposal. A span over native storage has the same underlying lifetime dependency. GC.KeepAlive prevents premature collection; it does not prevent explicit release from another alias or thread.
The array boundary is therefore nine safe acquisitions, eight caller-unsafe escaped-ref indexers, with explicit release/aliasing requirements. Safe search, clear, and copy wrappers keep unchecked operations local. Adding a new ownership API or copies merely to simplify the audit is a separate design change.
4. Source compatibility, language support, and enforcement are distinct
LangVersion=preview, AllowUnsafeBlocks, and the updated-rules opt-in are not interchangeable. The tested compiler uses the project-local Features entry updated-memory-safety-rules, preserving existing feature switches; that is an experimental toolchain detail, not a promise of the final public project-property name.
Actual C# 14 preparation builds rejected removal of ten pointer-declaration markers with CS0214. They remain documented compatibility exceptions until the language transition. Other probes showed that selecting a numbered language version was not enough for the preview syntax/feature combination; do not silently raise language versions or activate enforcement to make an annotation cleanup compile.
Preparation must remain buildable with its declared compiler baseline. Remove legacy-only markers under a compiler that supports the relaxed pointer declarations, rather than treating those markers as genuine new-model caller contracts.
5. Check what actually shipped before changing public contracts
The .NET 11 RC2 reference package already contained six TargetJni*Utf8 accessors and two protected virtual remapping hooks. Treating them as unshipped would have broken existing callers or overrides.
We kept those eight APIs safe-callable and warning-obsolete, added typed alternatives, and preserved dispatch through the old virtual slots. An unchanged RC2-compiled consumer exercised old member references, overrides, base calls, and new-to-old forwarding. An unchanged CLR signature alone is not sufficient evidence of source or behavioral compatibility.
6. ABI and call semantics need review even without pointer parameters
A JNI method ID must match the expected descriptor, receiver/static form, argument layout, and return representation. A parameterless invocation still has descriptor obligations; the absence of an argument pointer does not prove it safe.
Classify each P/Invoke, LibraryImport, and raw JNI call individually. Preserve native boolean/character widths, union layout, and calling conventions. For borrowed streams and returned pointers, document the backing owner's lifetime through normal and exceptional disposal paths, not just the immediate call.
7. An unsafe audit is not a general refactoring project
Preserve algorithms, accepted call sequences, allocation choices, ownership, dispatch, exception behavior, and cleanup order except for concrete bugs being fixed. Use normal formatting and the smallest useful unsafe regions rather than introducing helpers, buffer copies, callbacks, or large indentation-only rewrites.
Update canonical generators/templates and their outputs together. Generated output can dominate the diff even when the maintained implementation change is small; removing required golden updates only hides drift.
Preserve existing main-branch tests. Add focused regressions for demonstrated defects, not broad annotation-only/compiler-metadata matrices or invalid-pointer executions. Positive/negative compiler and metadata probes remain useful validation, but need not become a new committed test framework.
8. Runtime validation can reveal unsafe behavior in the tests themselves
ThreadReuse deliberately detaches and reattaches a native thread. Its diagnostic logging used Android.Util.Log, which calls JNI, before the existing GetObject(env, ...) operation refreshed the cached environment. A captured NativeAOT crash and the exact APK's machine code identified NewString being called through stale JNI environment storage.
The narrowly scoped, locally prepared fix saves the prior handle, preserves the first callback's cache initialization, and moves logging after the existing refresh operation. It does not eagerly refresh the environment before the operation under test, change the native helper, or skip the test. A later full run observed a different environment address and passed. A prior same-address pass had not exercised the failing path.
9. Attribute every validation result to its actual source and mode
Legacy compilation, updated-rule compilation, reference metadata, unchanged compiled consumers, and on-device runtime behavior are different evidence. Direct Roslyn compilations used by generator fixtures need their own options and real reference assemblies; project properties alone do not configure them.
Rebuild after source changes and compare actual artifacts, not just expected paths. Our device runs checked the installed APK and the complete 214-file CoreCLR fast-deployment payload before and after execution. They used the real test adapter without project-mode redeployment replacing the approved package. NativeAOT debug symbols must match the APK ELF's Build ID before symbolization.
Keep failed attempts and limitations. A passing rerun without the relevant lifetime/reattachment condition is not proof of a fix, and a passing old stack is not validation of a later rebase.
Validation achieved, and its limits
A locally prepared integrated snapshot was built and tested before the later PR rebases and review revisions:
- Legacy preparation:
544a7a9a93b06b004b4d92c03346d96989f21e30. - Java.Interop activation:
63b95fa9b2e18a83187109dfdec2a060b69a45c5.
For those exact sources, Debug/Release SDK builds, API levels 37/37.1/37.2 and local workload setup passed. Validation also passed for 18 activated implementation/reference/runtime-pack images, ten positive/negative caller-compilation probes, the unchanged RC2 consumer, 478 existing generator tests, 11 SourceWriter tests, and both CoreCLR/NativeAOT resource-import build cases. Canonical generation matched the changed outputs; an unchanged main fields file retained its existing UTF-8 BOM, explicitly distinguished from a source-content mismatch.
Four full suites ran on an isolated API 35 arm64 emulator with the exact rebuilt packages:
| Source mode | Runtime | Passed | Failed | Skipped |
|---|---|---|---|---|
| Legacy preparation | CoreCLR | 991 | 0 | 7 |
| Legacy preparation | NativeAOT | 928 | 0 | 7 |
| Activated | CoreCLR | 991 | 0 | 7 |
| Activated | NativeAOT | 928 | 0 | 7 |
All eight restored registration cases executed successfully in both CoreCLR runs; the existing NativeAOT exclusion remained in effect. ThreadReuse passed in every lane, and the activated CoreCLR run actually observed the changed-environment path. Earlier crashing attempts were retained, not counted as passes.
These are historical, source-specific integration results, not current CI status or validation of every subsequently merged/rebased PR tip. Later array, owned-memory, and generator review changes and the remaining layers need their own current-source validation. The open PRs remain open, and the wider .NET 12 migration is not complete.
Activity
[-][TrimmableTypeMap] Revisit use of `unsafe` in generated code and in libraries[/-][+]Revisit use of `unsafe` in generated code and in libraries[/+][build] Remove unsafe managed-memory access from hashing (#13041)
[Unsafe] Type-check JNI callback delegates (#13042)
[Unsafe] Guard JNI string lengths (#13043)
[Java.Interop] Opt into updated C# memory-safety rules
[Unsafe][Java.Interop] Prepare UTF-8 remapping contracts (#13184)
[Unsafe][Java.Interop] Prepare primitive-array borrowing (#13186)
[Unsafe][Java.Interop] Prepare owned JNI memory scopes (#13187)
[Unsafe][Java.Interop] Prepare generated JNI caller contracts (#13188)
[Unsafe] Opt tooling into updated C# memory-safety rules (#13189)
[Unsafe][generator] Prepare safe managed binding contracts (#13190)
[Unsafe] Prepare JNI and runtime memory-safety contracts (#13191)
[Unsafe][Java.Interop] Opt into updated C# memory-safety rules (#13192)
[tests] Refresh JNI environment before ThreadReuse diagnostics (#13337)
[Java.Interop] Replace legacy CRC64 tables with System.IO.Hashing (#1…