Skip to content

[Mono.Android] Enable C# memory-safety rules v2 - #13539

Merged
jonathanpeppers merged 4 commits into
mainfrom
simonrozsival-memory-safety-mono-android
Nov 23, 2026
Merged

jonathanpeppers merged 4 commits into
mainfrom
simonrozsival-memory-safety-mono-android

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Context: #13585

Complete Mono.Android's C# memory-safety-rules v2 compatibility adjustments.

Under v2, an unsafe declaration makes the member caller-unsafe (RequiresUnsafe). Keep implementation-only unsafe operations in method bodies where existing managed callers must remain supported. Preserve the released raw-handle constructor behavior, including generated base initializers, and keep the typed-marshaler template and checked-in output consistent. Update the typed helpers' Unshipped API entries to match their safe-callable declarations; Shipped inventories are unchanged.

Compatibility

The compatibility exceptions do not validate JNI references, buffers, callback ABIs, thread affinity, ownership or lifetime. Their documented <safety> obligations still apply even where the compiler does not enforce them.

The five new, unshipped UTF-8 allocation and construction overloads retain unsafe. ReadOnlySpan<byte> does not guarantee NUL-terminated backing storage, and its length does not bound JNI's native read. These APIs therefore retain caller acknowledgement under v2 rather than inheriting the released-constructor exception. Their implementations are unchanged.

The unrelated javac option change was removed; java-runtime.targets matches the selected main base.

Validation

Current review fix: 83c155c52795b96728c6af1fe5885593134aedea. Builds ran on its parent plus the exact five-file patch subsequently committed, using SDK 12.0.100-alpha.1.26556.115, Release, the existing owned private package/JDK/temp state, CPU1, -m:1 -nr:false, and no shared compilation. PublicAPI analyzers and normal API-compatibility targets remained enabled.

$V denotes the retained session-local mono-pr13539-validation directory. $PY is /Users/simon/.local/share/uv/python/cpython-3.12.14-macos-aarch64-none/bin/python3.12. The unshipped wrapper records complete expanded arguments and logs/binlogs for each stage.

Actual command Result
$PY "$V/run.py" utf8-review-37 build src/Mono.Android/Mono.Android.csproj -p:AndroidApiLevel=37 -p:AndroidPlatformId=37.0 -p:AndroidFrameworkVersion=v17.0 -p:IsUnstableVersion=false Passed; 0 errors, 3 warnings; ApiCompat reported 0 issues.
$PY "$V/run.py" utf8-review-37-1 build src/Mono.Android/Mono.Android.csproj -p:AndroidApiLevel=37.1 -p:AndroidPlatformId=37.1 -p:AndroidFrameworkVersion=v17.1 -p:IsUnstableVersion=false Passed; 0 errors, 4 warnings.
$PY "$V/run.py" utf8-review-37-2 build src/Mono.Android/Mono.Android.csproj -p:AndroidApiLevel=37.2 -p:AndroidPlatformId=37.2 -p:AndroidFrameworkVersion=v17.2 -p:IsUnstableVersion=false Passed; 0 errors, 4 warnings.

No RS0016/RS0017 errors remain. Warnings are the existing nullable listener returns, duplicate Shipped entries on the additional profiles, and the javac system-modules warning from retaining main's original options.

Read both the actual implementation and true-reference PE: module rules are [2], exactly the five UTF-8 JNIEnv methods carry RequiresUnsafe, and the 60 typed helpers and inspected released Object/Throwable constructors do not. A compile-only checked call to JNIEnv.AllocObject(ReadOnlySpan<byte>) fails with CS9362; the same call in an explicit unsafe block compiles. The probes did not execute JNI.

No device or generator test-suite rerun is claimed for this annotation-only revision. The earlier generator-suite results are historical, not current-head test evidence. Owned validation processes were released within the approved bounds.

@simonrozsival
simonrozsival marked this pull request as ready for review November 13, 2026 07:53
Copilot AI balanced review requested due to automatic review settings November 13, 2026 07: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

Targeted regression coverage is missing for override and deprecation inference, inherited nullability normalization, and eventDefaultReturn behavior in the generated code.

3 open issues
What changed in this PR

Enables C# memory-safety rules v2 for Mono.Android while preserving existing public member metadata and documenting caller obligations that remain unenforced.

Changes:

  • Moves implementation-only unsafe contexts into method bodies and updates JNI emitters and marshaling templates.
  • Adjusts binding generation for inherited nullability, abstract interface slots, listener assignment, and fallback return values.
  • Updates generation inputs, Java compiler options, compatibility documentation, and the existing IOException snapshot.
File Description
tests/​generator-Tests/​Unit-Tests/​CodeGeneratorTestBase.cs Runs interface nullability normalization in the test pipeline.
tests/​generator-Tests/​expected.xaji/​Streams/​Java.IO.IOException.cs Updates raw-constructor declarations and compatibility remarks.
src/​Mono.Android/​Mono.Android.targets Tracks generator changes as binding-generation inputs.
src/​Mono.Android/​Mono.Android.csproj Enables memory-safety rules v2.
src/​Mono.Android/​Microsoft.Android.Runtime/​TrimmableTypeMap.cs Adds local unsafe contexts and UTF-8 JNI lookups.
src/​Mono.Android/​metadata Defines fallback returns for two listener methods.
src/​Mono.Android/​Java.Lang/​Throwable.cs Preserves constructor callability and scopes reference cleanup.
src/​Mono.Android/​Java.Lang/​Object.cs Preserves public contracts and scopes reference cleanup.
src/​Mono.Android/​Java.Interop/​SafeJavaCollectionFactory.cs Adds local unsafe contexts to collection converters.
src/​Mono.Android/​Java.Interop/​Runtime.cs Moves unsafe context into the raw-reference type check.
src/​Mono.Android/​Java.Interop/​JniMarshalTyped.tt Updates typed-marshaling declarations and compatibility documentation.
src/​Mono.Android/​Java.Interop/​JniMarshalTyped.cs Synchronizes generated marshaling methods with the template.
src/​Mono.Android/​Java.Interop/​JavaConvert.cs Adds local unsafe contexts around lookup and cleanup operations.
src/​Mono.Android/​Android.Runtime/​JNIEnvInit.cs Moves pointer validation into the existing unsafe block.
src/​Mono.Android/​Android.Runtime/​JNIEnv.cs Preserves public JNI declarations under v2 rules.
src/​Mono.Android/​Android.Runtime/​JavaSet.cs Preserves conversion callability and scopes reference release.
src/​Mono.Android/​Android.Runtime/​JavaList.cs Preserves conversion callability and scopes reference release.
src/​Mono.Android/​Android.Runtime/​JavaDictionary.cs Preserves conversion callability and scopes reference release.
src/​Mono.Android/​Android.Runtime/​JavaCollection.cs Preserves conversion callability and scopes reference release.
src/​Mono.Android/​Android.Runtime/​JavaArray.cs Preserves conversion callability and scopes reference release.
src/​Mono.Android/​Android.Graphics/​Bitmap.cs Keeps pixel unlocking callable without declaration-level unsafe.
src/​Mono.Android/​Android.Bluetooth/​BluetoothDevice.cs Removes unsafe qualifiers from managed forwarding overloads.
src/​Mono.Android/​Android.Bluetooth/​AdvertisingSetParametersBuilder.cs Removes unsafe qualifiers from managed forwarding methods.
src/​java-runtime/​java-runtime.targets Uses javac --release for equal source/target versions.
src/​generator/​SourceWriters/​MethodCallback.cs Emits null checks for inherited default-interface contracts.
src/​generator/​SourceWriters/​JavaLangObjectConstructor.cs Generates safe-callable Throwable raw constructors.
src/​generator/​SourceWriters/​InterfaceListenerProperty.cs Assigns the first handler to newly created implementors.
src/​generator/​SourceWriters/​InterfaceEventHandlerImplClass.cs Emits configurable listener fallback returns.
src/​generator/​SourceWriters/​GenericExplicitInterfaceImplementationMethod.cs Adds null checks for non-null string arguments.
src/​generator/​SourceWriters/​Extensions/​SourceWriterExtensions.cs Refines listener selection and inherited return checks.
src/​generator/​SourceWriters/​ClassInvokerClass.cs Preserves raw invoker-constructor callability.
src/​generator/​Java.Interop.Tools.Generator.ObjectModel/​Method.cs Stores and clones listener fallback expressions.
src/​generator/​Java.Interop.Tools.Generator.ObjectModel/​GenBase.cs Infers abstract interface slots and normalizes inherited nullability.
src/​generator/​Java.Interop.Tools.Generator.Importers/​XmlApiImporter.cs Imports eventDefaultReturn metadata.
src/​generator/​CodeGenerator.cs Runs interface nullability normalization during generation.
Documentation/​Java.Interop/​Architecture.md Explains project-scoped activation and compatibility exceptions.
Documentation/​docs-mobile/​binding-libs/​customizing-bindings/​java-bindings-metadata.md Documents listener fallback expressions.
build-tools/​jnienv-gen/​Generator.cs Omits public unsafe declaration qualifiers in JNI output.

Review effort: Balanced

@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13539

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

⚠️ Needs Changes

Reviewed all 38 changed files and traced the generator changes through their consumers. New findings: 0 errors, 1 warning, 0 suggestions. The inline warning identifies a behavioral regression: normalizing a default-interface override's parameter to its base annotation can remove an explicitly nullable input allowance, and the newly generated callback null check then rejects previously accepted calls. Existing inline test-coverage findings are not duplicated here.

The project-scoped v2 activation, documented compatibility exceptions, and corresponding JNI-emitter/typed-marshaling-template changes are consistent with the stated compatibility approach. The documentation correctly distinguishes unchanged member metadata from broadened compiler-accepted calls.

CI: GitHub reports Azure build 1679195 still in progress, with no failed checks reported at inspection time; Linux/macOS build checks and Android Tools checks have passed. CI is not yet confirmed green. The standalone Azure build-status query was blocked by an authentication requirement, so the underlying Azure result/timeline could not be independently confirmed.

Local validation: Attempted the focused DefaultInterfaceMethods generator tests using dotnet test tests/generator-Tests/generator-Tests.csproj --no-restore -v minimal --filter 'FullyQualifiedName~DefaultInterfaceMethods' with intermediate/output paths redirected under /tmp/gh-aw/agent/. The .NET CLI failed before project evaluation with a first-run NuGet-Migrations mutex IOException; no tests executed. The finding is based on the source/data-flow trace, not an executed reproduction. No repository files were modified.

Generated by Android PR Reviewer for #13539 · copilot · gpt61 · 121.9 AIC · ⌖ 5.06 AIC · ⊞ 20.2K
Comment /review to run again

simonrozsival added a commit that referenced this pull request Nov 13, 2026
Context: #13539

Copying the root interface's non-null parameter annotation onto an overriding default method erased an explicit nullable allowance. The callback writer then rejected null with NullPointerException instead of forwarding it. Combine parameter contracts contravariantly and return contracts covariantly across every override level, retaining intermediate annotations instead of consulting only the root.

Callback dispatch still binds to the original interface signature. Reuse the existing generated null-forgiveness mechanism only when that signature is stricter than the DIM's nullable input, without rejecting null at runtime or changing the public interface contract.

The requested skipInterfaceMethods regression also exposed two older interface-aware override lookups that bypassed the skip-aware abstract-slot inference. Restrict those fallback lookups to actual base-class members; interface-only abstract slots continue through the existing filtered inference.

Add five focused regression cases for the nullable DIM chain, interface-only override/obsolete inference with and without skipped slots, and imported eventDefaultReturn fallback/handler dispatch. Compile the generated DIM and event code with the existing Roslyn compiler and an opt-in strict warning check, without changing existing compilation defaults.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Warning

Firewall blocked 1 domain

The following domain was blocked by the firewall during workflow execution:

  • 169.254.169.254

To allow these domains, add them to the network.allowed list in your workflow frontmatter:

network:
  allowed:
    - defaults
    - "169.254.169.254"

See Network Configuration for more information.

Generated by Android PR Reviewer for #13539

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

✅ LGTM — no blocking code findings

Findings: 0 errors, 0 warnings, 1 non-blocking inline suggestion. Reviewed head d23cb4f37eaa5f712e6d2a3e886f62ff7b8c9309, the changed files and surrounding source, generator consumers, and the previously resolved review threads. The project-scoped v2 opt-in, local implementation unsafe contexts, canonical JNI emitter and typed-marshaling template/output changes are consistent with the documented compatibility exceptions. The new regressions specifically cover multi-level DIM nullability, skipped interface-only abstract slots, and listener fallback/handler dispatch. PublicAPI inventories are unchanged in the diff.

CI: All 40 head-commit GitHub checks report success, including the aggregate dotnet-android check for Azure build 1679319. The direct Azure build-details query required unavailable authentication, so I did not independently verify its build result or timeline beyond the GitHub checks.

Local validation limit: Attempted dotnet test tests/generator-Tests/generator-Tests.csproj --no-restore --filter 'Name~DefaultInterfaceNullabilityPreservesNullableOverridesAcrossLevels|Name~InterfaceOnlyAbstractBaseInfersOverrideAndObsoleteUnlessSkipped|Name~EventDefaultReturnPreservesFallbackAndHandlerDispatch' -v minimal. The .NET CLI failed during first-run setup with DirectoryNotFoundException, before compilation or test execution. No local test pass, independent metadata-equivalence check, or device validation is claimed by this review.

Warning

Firewall blocked 1 domain

The following domain was blocked by the firewall during workflow execution:

  • 169.254.169.254

To allow these domains, add them to the network.allowed list in your workflow frontmatter:

network:
  allowed:
    - defaults
    - "169.254.169.254"

See Network Configuration for more information.

Generated by Android PR Reviewer for #13539 · copilot · gpt61 · 169.3 AIC · ⌖ 5.03 AIC · ⊞ 20.2K
Comment /review to run again

@simonrozsival simonrozsival added the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Nov 13, 2026
simonrozsival added a commit that referenced this pull request Nov 13, 2026
Context: #13539 (comment)

Calling eventDefaultReturn a return expression did not explain that the binding generator inserts its value verbatim without expression-only validation. Calls can have side effects and crafted metadata can inject additional source, so this is not a sandbox for untrusted configuration.

Document the source-code trust boundary, the no-handler execution timing, and ordinary compiler/runtime failure behavior. Recommend small fallbacks and hand-written listeners for complex logic. Keep the existing listener behavior and generator contract unchanged; the window-insets fallback needs a method call, and expression-only parsing would not make that call side-effect-free.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival simonrozsival added ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). and removed ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). labels Nov 13, 2026
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13539

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

Review assessment: no new blocking code defects found; validation remains limited. New findings: 0 ❌ errors, 0 ⚠️ warnings, 1 💡 non-blocking suggestion, posted inline. Existing review feedback was checked and not duplicated.

The project-scoped v2 opt-in, local implementation unsafe contexts, and corresponding JNI emitter/T4 changes are consistent with the stated compatibility policy. The documentation clearly distinguishes preserved member metadata from broadened compiler-accepted calls. The added regressions cover the previously reported nullable DIM inheritance, skipped interface slots, and fallback/handler dispatch cases.

CI: All 40 GitHub check runs report success, including the aggregate dotnet-android check for Azure build 1679889. The direct Azure build query required authentication, so its build result and timeline could not be independently confirmed; this is not an unconditional CI-green verdict.

Local validation: Attempted the focused generator tests with dotnet test tests/generator-Tests/generator-Tests.csproj --filter 'Name~DefaultInterfaceNullabilityPreservesNullableOverridesAcrossLevels|Name~InterfaceOnlyAbstractBaseInfersOverrideAndObsoleteUnlessSkipped|Name~EventDefaultReturnPreservesFallbackAndHandlerDispatch' -v minimal --results-directory /tmp/gh-aw/agent/review-results. The command failed during .NET CLI initialization with a NuGet-Migrations IOException, before tests ran. No local build/device-test or API-metadata validation is claimed by this review. No repository files were changed.

Generated by Android PR Reviewer for #13539 · copilot · gpt61 · 175 AIC · ⌖ 4.78 AIC · ⊞ 21K
Comment /review to run again

@simonrozsival simonrozsival removed the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Nov 14, 2026
simonrozsival added a commit that referenced this pull request Nov 14, 2026
Context: #13539 (comment)

eventDefaultReturn injected a C# expression into metadata-generated listener bodies. A source-code trust warning did not address the request to keep custom behavior in ordinary C# additions instead.

Replace the raw-source hook with generateEventHandlerMethod=false. This omits only the implementor method; the existing internal partial type, handler field, constructor, registration, and __IsEmpty remain generated. A hand-written partial class supplies the same interface member without introducing new public slots.

Move the window-insets and loudness-codec no-handler fallbacks into partial implementors, preserving installed-handler dispatch and the existing non-null return check. Ordinary listeners retain their generated default-return and Handled behavior. Document the partial-class pattern and replace the focused fallback tests with generated/default and hand-written/handler cases, plus an implementor-infrastructure check.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Warning

Firewall blocked 1 domain

The following domain was blocked by the firewall during workflow execution:

  • 169.254.169.254

To allow these domains, add them to the network.allowed list in your workflow frontmatter:

network:
  allowed:
    - defaults
    - "169.254.169.254"

See Network Configuration for more information.

Generated by Android PR Reviewer for #13539

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

Review of 4ee596eb61

Code assessment: no blocking correctness defects identified. Findings: 0 errors, 0 warnings, 1 non-blocking testing suggestion, posted inline.

The public JNI/raw-handle compatibility exceptions are explicitly documented, implementation unsafe scopes remain local, and the typed-marshaling template matches its checked-in output. The DIM normalization preserves less restrictive inputs across the override chain. Replacing eventDefaultReturn with declarative method suppression and ordinary partial classes addresses the maintainer's design feedback without inserting C# through metadata. The new override/obsolete and partial-listener regressions are useful; existing review threads were checked to avoid repeating their findings.

⚠️ Validation incomplete — not a demonstrated PR regression. All 40 head-commit GitHub checks report success, including the aggregate dotnet-android check for Azure build 1681292. The independent Azure build query was blocked by the CLI's login requirement, so I could not corroborate its build result/timeline directly.

I attempted dotnet test tests/generator-Tests/generator-Tests.csproj --filter 'Name~PartialListenerMethod|Name~DefaultInterfaceNullabilityPreservesNullableOverridesAcrossLevels|Name~InterfaceOnlyAbstractBaseInfersOverrideAndObsoleteUnlessSkipped' --results-directory /tmp/gh-aw/agent/test-results -v minimal. It stopped before test execution with CS9363 in unchanged src/Java.Interop/Java.Interop/JniNativeMethodRegistration.cs:50–51. This runner uses SDK 11.0.100; the repository pins 12.0.100-alpha.1.26556.115, and no local preview SDK is provisioned. These environment-specific compiler errors are not inline findings against this PR. The description's author-reported validation was distinguished from checks independently completed here; no local runtime/device or API-metadata verification is claimed.

Warning

Firewall blocked 1 domain

The following domain was blocked by the firewall during workflow execution:

  • 169.254.169.254

To allow these domains, add them to the network.allowed list in your workflow frontmatter:

network:
  allowed:
    - defaults
    - "169.254.169.254"

See Network Configuration for more information.

Generated by Android PR Reviewer for #13539 · copilot · gpt61 · 163.7 AIC · ⌖ 4.34 AIC · ⊞ 21K
Comment /review to run again

@simonrozsival simonrozsival added the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Nov 14, 2026
@jonathanpeppers
jonathanpeppers force-pushed the simonrozsival-memory-safety-mono-android branch from 4ee596e to 9e44c36 Compare November 16, 2026 20:51
@jonathanpeppers
jonathanpeppers changed the base branch from main to jonathanpeppers-generator-warning-fixes November 16, 2026 20:51
@simonrozsival simonrozsival removed the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Nov 17, 2026
Base automatically changed from jonathanpeppers-generator-warning-fixes to main November 18, 2026 10:25
@simonrozsival
simonrozsival force-pushed the simonrozsival-memory-safety-mono-android branch from 9e44c36 to 9ddb555 Compare November 18, 2026 10:34
Comment thread src/java-runtime/java-runtime.targets Resolved
simonrozsival added a commit that referenced this pull request Nov 19, 2026
Context: #13539 (comment)

The --release override removed a local JDK 25 system-modules warning, but the original build already succeeded. It is not required for the C# memory-safety changes. Restore the existing javac options to keep this change scoped to memory safety.

Validation: the target parses as XML and matches main exactly; git diff --check passes. No Java compilation was rerun for this restoration.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival simonrozsival added the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Nov 19, 2026
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13539

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

⚠️ Needs Changes

Findings: 0 errors · 1 warning · 0 suggestions.

The inline finding concerns removing caller-unsafe enforcement from the unshipped UTF-8 span overloads. Their NUL-termination requirement remains unchecked, and preserving the released raw-handle constructor behavior does not require extending that compatibility exception to these new APIs.

The typed-marshaler template and generated output are updated together, and the reviewed implementation changes preserve dispatch, reference cleanup, and exception handling. The new documentation explicitly distinguishes safe-callable compatibility exceptions from validated inputs.

CI: All 38 GitHub check runs report success, including the aggregate dotnet-android check for Azure build 1690319. Independent Azure build/timeline verification was blocked because az devops invoke requires login in this environment; no Azure failure is inferred from that access limitation.

Generated by Android PR Reviewer for #13539 · copilot · gpt61 · 62.8 AIC · ⌖ 7.94 AIC · ⊞ 20.3K
Comment /review to run again

simonrozsival added a commit that referenced this pull request Nov 19, 2026
Context: #13539 (comment)

The five new UTF-8 allocation and construction overloads require readable NUL-terminated backing storage. ReadOnlySpan<byte> does not guarantee that storage, and its length does not bound the native JNI lookup. These unshipped APIs do not need the compatibility exception retained for released raw-handle constructors.

Restore unsafe on those five declarations and their matching entries in the three Unshipped inventories. Keep their implementation bodies, the 60 typed marshal helpers, released constructors, and Shipped inventories unchanged. Clarify the distinction in the JNI and architecture documentation.

Validation: normal Release builds passed for API 37/v17.0, 37.1/v17.1 and 37.2/v17.2 with PublicAPI analysis enabled (3, 4 and 4 existing warnings respectively, no errors). Both the implementation and reference PE carry RequiresUnsafe on exactly these five JNIEnv methods, not on the typed helpers or released constructors inspected. A compile-only checked caller fails with CS9362; the same call in an explicit unsafe block compiles. No JNI call was executed.

Co-authored-by: Copilot App <[email protected]>
jonathanpeppers and others added 4 commits November 21, 2026 00:18
Set `$(MemorySafetyRulesVersion)` to 2 for Mono.Android. Under v2, an
`unsafe` declaration makes the member caller-unsafe (`RequiresUnsafe`).
Move implementation-only unsafe contexts into method bodies, so the
public members keep their existing metadata and the PublicAPI files do
not change. Update the `jnienv-gen` emitter and the `JniMarshalTyped`
template with their output.

Use `javac --release` when the source and target levels match, to
remove the "location of system modules is not set" warning.

Co-authored-by: Copilot App <[email protected]>
Context: https://dev.azure.com/dnceng-public/public/_build/results?buildId=1687541

Rebasing onto main left 60 JniMarshalTyped methods and five UTF-8 JNIEnv overloads declared without unsafe while their Unshipped API entries still included it. Linux and macOS each reported 65 RS0016/RS0017 pairs.

Remove only the unsafe token from those entries in the API-37, API-37.1 and API-37.2 Unshipped inventories. Keep the intended caller-safe declarations, implementation and template unchanged instead of restoring caller-unsafe contracts to satisfy the analyzer. Shipped inventories are untouched.

Validation: normal Release builds of src/Mono.Android/Mono.Android.csproj passed for AndroidApiLevel/AndroidPlatformId/AndroidFrameworkVersion tuples 37/37.0/v17.0, 37.1/37.1/v17.1 and 37.2/37.2/v17.2, with IsUnstableVersion=false for the additional profiles. Public API analysis remained enabled with RS0016/RS0017 treated as errors; none remain. Existing warning counts were 2, 4 and 4 respectively (nullable listener returns and duplicate Shipped entries).

Co-authored-by: Copilot App <[email protected]>
Context: #13539 (comment)

The --release override removed a local JDK 25 system-modules warning, but the original build already succeeded. It is not required for the C# memory-safety changes. Restore the existing javac options to keep this change scoped to memory safety.

Validation: the target parses as XML and matches main exactly; git diff --check passes. No Java compilation was rerun for this restoration.

Co-authored-by: Copilot App <[email protected]>
Context: #13539 (comment)

The five new UTF-8 allocation and construction overloads require readable NUL-terminated backing storage. ReadOnlySpan<byte> does not guarantee that storage, and its length does not bound the native JNI lookup. These unshipped APIs do not need the compatibility exception retained for released raw-handle constructors.

Restore unsafe on those five declarations and their matching entries in the three Unshipped inventories. Keep their implementation bodies, the 60 typed marshal helpers, released constructors, and Shipped inventories unchanged. Clarify the distinction in the JNI and architecture documentation.

Validation: normal Release builds passed for API 37/v17.0, 37.1/v17.1 and 37.2/v17.2 with PublicAPI analysis enabled (3, 4 and 4 existing warnings respectively, no errors). Both the implementation and reference PE carry RequiresUnsafe on exactly these five JNIEnv methods, not on the typed helpers or released constructors inspected. A compile-only checked caller fails with CS9362; the same call in an explicit unsafe block compiles. No JNI call was executed.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival
simonrozsival force-pushed the simonrozsival-memory-safety-mono-android branch from 83c155c to 6064e82 Compare November 20, 2026 23:18
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13539

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

Code verdict: no blocking findings — 0 errors, 0 warnings, 1 documentation suggestion. Reviewed the current diff at 6064e82f1ba824bc7240a234ec1a84f3971b502a, the changed implementations and generator template/output, the relevant callers, project safety configuration, and API changes across 37/37.1/37.2. The typed helpers retain their transition, peer conversion, exception reporting and finally-based cleanup. The five UTF-8 construction/allocation overloads remain caller-unsafe, distinct from the documented compatibility exceptions. The typemap's complete ASCII UTF-8 literals satisfy the lookup termination contract, and its class-reference cleanup is preserved. The earlier UTF-8 review concern is addressed; I found no new correctness regression in the current changes.

CI verification is limited. GitHub reports all 38 current-head checks successful, including the aggregate dotnet-android check for Azure build 1693091. Direct Azure build/timeline queries were attempted but unavailable in this environment: the build query failed during CLI initialization and the timeline query required authentication. Consequently, this is not an independently confirmed Azure-green or mergeability verdict. No local build, generator-suite run, device execution or PE-metadata inspection was performed during this review; the validation in the PR description is author-reported evidence, not a new reviewer run.

Generated by Android PR Reviewer for #13539 · copilot · gpt61 · 56.3 AIC · ⌖ 7.58 AIC · ⊞ 20.3K
Comment /review to run again

/// and friends for those.
/// </para>
/// <para>
/// Existing public member metadata is preserved for compatibility. Updated-rule callers can

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 saying “Existing method signatures and binary compatibility are preserved” instead of “Existing public member metadata is preserved.” With MemorySafetyRulesVersion=2, removing declaration-level unsafe changes the compiler-emitted RequiresUnsafeAttribute metadata for these helpers; that is the intended checked-consumer contract change reflected in the three API inventories. The following sentence correctly explains the broader compiler-accepted calls, but “metadata is preserved” could suggest the safety attribute is unchanged. Please keep this wording aligned in the template and JniMarshalTyped.cs.

{Rule: Documentation should distinguish binary signatures from caller-safety metadata}

@jonathanpeppers
jonathanpeppers merged commit e019233 into main Nov 23, 2026
38 checks passed
@jonathanpeppers
jonathanpeppers deleted the simonrozsival-memory-safety-mono-android branch November 23, 2026 14:54
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