Skip to content

[Mono.Android] Retire JNI delegate wrapping, retain legacy API - #13130

Merged
simonrozsival merged 6 commits into
mainfrom
simonrozsival-jni-delegate-wrapper-retirement
Oct 21, 2026
Merged

simonrozsival merged 6 commits into
mainfrom
simonrozsival-jni-delegate-wrapper-retirement

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Pull Request
title and
description
should follow the
commit-messages.md workflow documentation, and in particular should include:

  • Useful description of why the change is necessary.
  • Links to issues fixed
  • Unit tests

Retire runtime JNI delegate wrapping in .NET for Android 12, without removing the shipped public API. Legacy generated connector methods can reference Android.Runtime.JNINativeWrapper.CreateDelegate(Delegate) even though trimmable typemaps read connector metadata and invoke the marshal method directly instead of executing the connector.

Retain the public class and exact Delegate CreateDelegate(Delegate) signature as [Obsolete(..., error: true)], and always throw NotSupportedException if it is called. Existing binary references therefore resolve; executing the unsupported API is a deliberate behavior break, and new direct source calls fail with CS0619. Remove RequiresDynamicCode, because the stub no longer generates code.

Related PR: #13128 targets release/11.0.1xx and marks the method obsolete while retaining its existing .NET 11 implementation. This independent main PR replaces wrapping with the throwing stub in .NET 12. Neither PR removes the public class/method; they are not stacked.

Remove all 40 built-in wrappers, private dispatch/exception helpers, Reflection.Emit fallback, dynamic-method counter, and canonical wrapper T4 input/output. Preserve shared _JniMarshal_* delegates, supported generated marshal callbacks, connector metadata, constructor activation, exception handling, GC bridge processing, and reference ownership. Generator changes are comments only. No framework/package/runtime pin upgrades. No linked issue.

The earlier revision removed the class and method. This revision restores them and removes all six PublicAPI removal records and the missing-type ApiCompat allowance. The only new compatibility baseline entry accepts removal of the class's compiler-generated ExtensionAttribute, which came from the deleted internal extension wrappers; no public API removal is suppressed.

Restore and update Documentation/project-docs/exception-handling.md rather than deleting it. The guide now explains current CoreCLR/NativeAOT callback boundaries, pending Java exception translation, synchronous round trips, notification-hook differences, and debugger integration, with implementation and regression-test links. Drop the standalone JNI delegate-wrapper release note in response to review feedback.

Two new runtime regressions use an actual legacy-shaped connector whose body references JNINativeWrapper.CreateDelegate: invoking the connector directly throws NotSupportedException, while a Java hashCode() call returns 42 through the marshal callback without invoking that connector. Both run under CoreCLR and NativeAOT.

Validation

Runtime-validation revision: d27c14600f2fda18921e2a157efca1f246be5c0a. The retained-stub validation below used this worktree's own coherently rebuilt Release SDK, including current native hosts and generators. Personal VS Code settings and five pre-existing generated resource-designer changes were excluded from the commit. Documentation-only follow-up 723f025325ff299f005eec56ef4303bd539174c7 changes no runtime code; all 18 relative guide links and code-fence balance were checked, and the described paths were verified against the implementation and official JNI/.NET debugger documentation. No SDK/device rerun was needed for that documentation update.

SDK and API contracts

make all CONFIGURATION=Release MSBUILD_ARGS='-m:1 --disable-build-servers -nr:false -p:UseSharedCompilation=false -p:NinjaPath=/Users/simon/.copilot/session-state/a1bca159-9474-4865-bfc1-0aefcda22a8c/files/ninja-j1'

Passed, including local workload configuration. The session-only wrapper executes the verified prepared Ninja with -j1. The first build identified the removed compiler-generated ExtensionAttribute; adding its exact compatibility baseline entry resolved that gate without suppressing class or method removal.

./dotnet-local.sh build src/Mono.Android/Mono.Android.csproj -c Release -v minimal -m:1 --disable-build-servers -nr:false -p:UseSharedCompilation=false -p:DisableApiCompatibilityCheck=false -p:AndroidApiLevel=37 -p:AndroidPlatformId=37.0 -p:AndroidFrameworkVersion=v17.0 -p:IsUnstableVersion=false
./dotnet-local.sh build src/Mono.Android/Mono.Android.csproj -c Release -v minimal -m:1 --disable-build-servers -nr:false -p:UseSharedCompilation=false -p:DisableApiCompatibilityCheck=false -p:AndroidApiLevel=37.1 -p:AndroidPlatformId=37.1 -p:AndroidFrameworkVersion=v17.1 -p:IsUnstableVersion=false
./dotnet-local.sh build src/Mono.Android/Mono.Android.csproj -c Release -v minimal -m:1 --disable-build-servers -nr:false -p:UseSharedCompilation=false -p:DisableApiCompatibilityCheck=false -p:AndroidApiLevel=37.2 -p:AndroidPlatformId=37.2 -p:AndroidFrameworkVersion=v17.2 -p:IsUnstableVersion=false
./dotnet-local.sh build build-tools/create-packs/Microsoft.Android.Sdk.proj -t:ConfigureLocalWorkload -c Release -v minimal -m:1 --disable-build-servers -nr:false -p:UseSharedCompilation=false

All passed, including implementation/reference production and PublicAPI analyzers. Existing nullable/unused-field/duplicate-baseline warnings remain (29/31/31). The existing reference-contract ApiCompat comparison applies to API 37/v17.0 only; the 37.1/37.2 targets do not perform that reference comparison.

A session-local Roslyn/Cecil proof was built with:

./dotnet-local.sh build /Users/simon/.copilot/session-state/a1bca159-9474-4865-bfc1-0aefcda22a8c/files/stub-20261015/contract-proof/contract-proof.csproj -c Release -v minimal -m:1 --disable-build-servers -nr:false -p:UseSharedCompilation=false

Passed. For each API 37, 37.1, and 37.2, it was then run as:

bin/Release/dotnet/dotnet <contract-proof.dll> <original-Mono.Android.dll> <revised-Mono.Android.dll> <compiler-reference-Mono.Android.dll> <workload-reference-Mono.Android.dll>

All passed: compile an old connector against the original public API, verify its actual Mono.Android MemberRef, and execute the unchanged binary against the revised implementation. It resolves the retained method and throws NotSupportedException, not TypeLoadException or MissingMethodException. Each implementation/compiler-reference/workload-reference also retains the exact public signature and Obsolete(message, true), no longer has RequiresDynamicCode, and makes a new direct source call fail with exactly CS0619.

Host tests

dotnet test external/Java.Interop/tests/generator-Tests/generator-Tests.csproj --no-restore -v minimal -m:1 --disable-build-servers -nr:false -p:UseSharedCompilation=false
./dotnet-local.sh test src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/Microsoft.Android.Build.Tasks.Tests.csproj -c Release -v minimal -m:1 --disable-build-servers -nr:false -p:UseSharedCompilation=false --filter 'FullyQualifiedName~GenerateTrimmableTypeMapTests|FullyQualifiedName~TrimmableTypeMapIncrementalTests|FullyQualifiedName~TrimmableTypeMapManifestAliasTests|FullyQualifiedName~TrimmableTypeMapRidCallbackTests|FullyQualifiedName~ExtractTypeMapKeysFromNativeAotObjectTests'

Passed: 478 generator tests and 57 typemap tests, no skips. The older 177-test callback/build run belongs to the earlier revision and is not claimed as current-revision validation.

CoreCLR and NativeAOT runtime tests

Both full suites used a new isolated API 35 arm64 emulator, explicitly selected as emulator-5598. Build/install was run once for each PublishAot=false and PublishAot=true:

ANDROID_SERIAL=emulator-5598 ./dotnet-local.sh build -t:Install -c Release tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -p:RuntimeIdentifier=android-arm64 -p:AndroidPackageFormat=apk -p:PublishAot=<false-or-true> -p:IlcSingleThreaded=true '-p:AdbTarget=-s emulator-5598' -m:1 --disable-build-servers -nr:false -p:UseSharedCompilation=false

Both passed. An initial fixture build declared a Java override absent from java.lang.Object; correcting the test fixture to override the real hashCode() method resolved it. No production workaround or test exclusion was added.

From the test project directory, with matching properties:

ANDROID_SERIAL=emulator-5598 ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Release -p:RuntimeIdentifier=android-arm64 -p:AndroidPackageFormat=apk -p:PublishAot=<false-or-true> -p:IlcSingleThreaded=true '-p:AdbTarget=-s emulator-5598' --device emulator-5598 --report-trx --results-directory <session-runtime-results>

Current results: CoreCLR 944 passed / 0 failed / 7 skipped; NativeAOT 889 passed / 0 failed / 7 skipped. Both new LegacyConnector_ThrowsWhenInvokedDirectly and LegacyConnector_IsBypassedByTrimmableTypeMap tests passed in both runtimes. The GC-cycle regression also passed in both on the first run. Existing runtime exclusions and documented skips remain unchanged.

For each runtime, the installed canonical base APK SHA-256 matched the locally built signed APK before running tests. CoreCLR: 5b597ed8396493eab9abaa562a131d96c721822646fc281707a13e5e79f45e2a; NativeAOT: 67c4c242e2ce046e441c1b2b1d1c01c202a1490b9343556a15f29c88e30f2c0d.

Historical caveat, earlier API-removal revision only: one NativeAOT GC-trace assertion failed and two unchanged full reruns passed; cause unknown. That evidence is retained but is not substituted for the corrected-revision runs above.

Raw logs, binlogs, binary-contract proof, APK identities, and TRXs are preserved locally. The device run had an absolute UTC stop/cleanup watchdog; its test app, own emulator process and exact new AVD were cleaned and all leases/ports released at 2026-10-15 12:07:44Z. No physical or shared device was modified.

Intended-path and staged git diff --check checks passed. No current CI-status claim.

simonrozsival and others added 2 commits October 13, 2026 18:18
Remove JNINativeWrapper.CreateDelegate, its generated built-in wrappers and T4 template, and the Reflection.Emit fallback/counter. Preserve shared marshal delegates and existing generated callback infrastructure.

Record intentional class/method removals across all six PublicAPI baselines and the reference compatibility gate, and document the .NET for Android 12 migration.

Co-authored-by: Copilot App <[email protected]>
The document describes retired runtime-generated JNI wrappers and Mono debugger behavior.  Remove it instead of keeping a historical disclaimer; the current JNI interop guide documents supported callback exception boundaries.

Co-authored-by: Copilot App <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 13, 2026 18:54

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

The intentional binary break affects JNI runtime compatibility and warrants final maintainer review despite comprehensive validation.

0 open findings

What changed in this PR

Retires the obsolete JNI delegate compatibility wrapper while preserving current generated callback infrastructure.

Changes:

  • Removes JNINativeWrapper, generated wrappers, fallback machinery, and preservation entries.
  • Records the intentional API break across all baselines.
  • Adds migration guidance and removes outdated exception documentation.
File Description
tests/​api-compatibility/​acceptable-breakages-vReference-net11.0.txt Accepts the intentional type removal.
src/​Mono.Android/​PublicAPI/​API-35/​PublicAPI.Unshipped.txt Records removed APIs.
src/​Mono.Android/​PublicAPI/​API-36/​PublicAPI.Unshipped.txt Records removed APIs.
src/​Mono.Android/​PublicAPI/​API-36.1/​PublicAPI.Unshipped.txt Records removed APIs.
src/​Mono.Android/​PublicAPI/​API-37/​PublicAPI.Unshipped.txt Records removed APIs.
src/​Mono.Android/​PublicAPI/​API-37.1/​PublicAPI.Unshipped.txt Records removed APIs.
src/​Mono.Android/​PublicAPI/​API-37.2/​PublicAPI.Unshipped.txt Records removed APIs.
src/​Mono.Android/​Mono.Android.csproj Removes deleted source and template entries.
src/​Mono.Android/​Android.Runtime/​JNINativeWrapper.g.tt Deletes wrapper generation template.
src/​Mono.Android/​Android.Runtime/​JNINativeWrapper.g.cs Deletes generated wrappers.
src/​Mono.Android/​Android.Runtime/​JNINativeWrapper.cs Deletes the public compatibility API.
src/​Mono.Android/​Android.Runtime/​DynamicMethodNameCounter.cs Removes obsolete fallback support.
src/​Microsoft.Android.Sdk.ILLink/​PreserveLists/​Mono.Android.xml Removes obsolete linker preservation.
external/​Java.Interop/​tools/​generator/​SourceWriters/​MethodCallback.cs Updates comments for current callback behavior.
external/​Java.Interop/​tests/​generator-Tests/​SupportFiles/​JavaObject.cs Removes obsolete compilation mock.
Documentation/​release-notes/​jni-delegate-wrapper-retirement.md Documents the break and migration.
Documentation/​project-docs/​exception-handling.md Removes outdated Mono-era guidance.

🧠 Review effort: Balanced

@jonathanpeppers

Copy link
Copy Markdown
Member

/review

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13130

@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

The removal is consistently wired through the implementation, project inputs, linker preservation list, public API baselines, API-compatibility allowance, generator support stub, and release notes. The surviving generated callback paths retain JNI transition and exception handling through JniMarshal.SafeInvokeAction/SafeInvokeFunc, and the migration warning correctly avoids suggesting plain delegate construction as an equivalent replacement.

Findings: 0 errors · 0 warnings · 1 suggestion

CI is green (Azure DevOps build 1633942 and all 42 reported checks passed).

Generated by Android PR Reviewer for #13130 · copilot · gpt56 · 153 AIC · ⌖ 11.1 AIC · ⊞ 26.4K
Comment /review to run again

code-generation fallback. This is an intentional source and binary compatibility
break for existing callers; no compatibility stub is provided.

Rebuild older binding libraries with the current .NET for Android binding

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 — Please name the minimum toolchain version here (for example, “Rebuild older binding libraries with the .NET for Android 12 binding generator or newer”). “Current” will become ambiguous once this release note is read after later SDK releases, while a concrete version keeps the migration guidance durable.

Rule: Release notes should give end users actionable migration guidance

Keep the upstream deletion of the unused Android ILLink project and its Mono.Android preservation file.  Preserve the JNI compatibility API retirement without restoring the obsolete linker descriptor.

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

Copy link
Copy Markdown
Member Author

These methods are called from legacy generated connector methods. We can't remove JNINativeWrapper.CreateDelegate but we should obsolete it and throw if called. With trimmable typemaps, the connector methods are never called and we invoke the marshal method directly.

Legacy generated connector methods can still reference CreateDelegate even though trimmable typemaps invoke marshal methods directly.  Preserve the public class and exact method signature as an obsolete-error API that throws NotSupportedException, without restoring runtime delegate wrapping.

Remove API-removal markers and replace the missing-type baseline with the exact compiler-generated ExtensionAttribute removal.  Cover direct connector invocation and JNI dispatch bypass on CoreCLR and NativeAOT, and update the migration note.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival simonrozsival changed the title [Mono.Android] Retire JNI delegate wrapper compatibility API [Mono.Android] Retire JNI delegate wrapping, retain legacy API Oct 15, 2026
@simonrozsival simonrozsival changed the title [Mono.Android] Retire JNI delegate wrapping, retain legacy API [Unsafe][Mono.Android] Retire JNI delegate wrapping, retain legacy API Oct 15, 2026
Resolve the upstream fallback-logging conflict by retaining the obsolete throwing CreateDelegate entry point.  Do not restore the retired wrapper or Reflection.Emit implementation.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival simonrozsival changed the title [Unsafe][Mono.Android] Retire JNI delegate wrapping, retain legacy API [Mono.Android] Retire JNI delegate wrapping, retain legacy API Oct 15, 2026
simonrozsival added a commit that referenced this pull request Oct 19, 2026
Mark `Android.Runtime.JNINativeWrapper.CreateDelegate(Delegate)` obsolete
with `error: true` in .NET 11, ahead of retiring runtime JNI delegate wrapping in .NET 12.
This is an independent PR targeting **release/11.0.1xx**, not a stack or
a backport of the .NET 12 implementation change. No linked issue.

**Related PR:** [#13130](#13130) retains the same public class and method on `main` for legacy binary references, but replaces runtime wrapping with an obsolete, throwing stub in .NET 12. Trimmable typemaps read connector metadata and invoke marshal methods directly, without executing the legacy connectors that reference `CreateDelegate`. This .NET 11 PR leaves the existing implementation intact; neither PR removes the public class/method, and they are not stacked.

The change deliberately makes direct source calls fail with CS0619.
Existing compiled bindings retain the public class, method signature,
`RequiresDynamicCode` annotation, and the entire wrapper implementation,
including built-in delegates, Reflection.Emit fallback, exception handling,
and GC bridge processing.

The migration message directs binding authors to rebuild with the current
.NET for Android binding generator. On this release branch its generated
callbacks already use `JniMarshal.SafeInvokeAction`/`SafeInvokeFunc`.
A delegate constructor alone is not a replacement for those JNI transition
and exception-handling semantics. Add a release note explaining this.

No generator, T4, dispatch, runtime, public API baseline, or compatibility
suppression changes are needed.
@simonrozsival simonrozsival added the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Oct 19, 2026
Comment on lines +1 to +7
### Breaking change: JNI delegate wrapping is no longer supported

.NET for Android 12 retains `Android.Runtime.JNINativeWrapper` and its
`CreateDelegate (Delegate)` method so that existing binding assemblies containing
legacy connector methods can still resolve their references. The method is marked
`[Obsolete (..., error: true)]` and throws `NotSupportedException` if called.
Its built-in wrappers and runtime code-generation fallback are removed.

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.

I don't think this .md file will go to the right place.

In either case, I don't think this API is important enough to advertise a notice.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Removed the standalone release note in 723f025. The PR description and obsolete diagnostic retain the compatibility context without adding a release announcement.

Auto-replied by the GitHub Copilot app

Comment on lines -1 to -5
# Exception Handling

Outside of Xamarin.Android, .NET exception handling
[when a debugger is attached][0] potentially involves walking the runtime stack
*twice*, involving three interactions between the runtime and the debugger:

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.

This doc seems useful?

Does it just need to be updated?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Restored and updated the guide in 723f025. It now describes the current typemap forwarders, SafeInvoke/JniTransition exception boundaries, JavaProxyThrowable round trips, and modern debugger APIs instead of the runtime-generated wrapper and Mono debugger walkthrough. It also distinguishes CoreCLR's notification-hook override from NativeAOT's inherited handler, and links the implementation and existing regression tests.

Auto-replied by the GitHub Copilot app

Restore the exception-handling guide with current CoreCLR and NativeAOT callback boundaries, pending-exception translation, debugger integration, and regression-test references.  Replace obsolete Mono debugger and dynamic-wrapper assumptions with source-verified behavior.

Drop the standalone JNI delegate-wrapper release note in response to review feedback.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival
simonrozsival merged commit 44d713f into main Oct 21, 2026
41 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-jni-delegate-wrapper-retirement branch October 21, 2026 06:38
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 20, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

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