Skip to content

[Xamarin.Android.Build.Tasks] Initialize .NET from an AppComponentFactory - #13662

Draft
simonrozsival wants to merge 2 commits into
mainfrom
simonrozsival-issue-13568-investigation
Draft

simonrozsival wants to merge 2 commits into
mainfrom
simonrozsival-issue-13568-investigation

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Fixes: #13568
Context: #13568 (comment)
Context: #2292
Context: #4028

A managed component that runs in a restricted full-backup process crashes before any managed code runs:

E AndroidRuntime: FATAL EXCEPTION: main
E AndroidRuntime: java.lang.UnsatisfiedLinkError: No implementation found for void mono.android.Runtime.registerNatives(java.lang.Class)
E AndroidRuntime:   at mono.android.Runtime.registerNatives(Native Method)

The issue reports this for NativeAOT, but it is not runtime-specific. We reproduced it with CoreCLR and NativeAOT on main, and with MonoVM in .NET 10. The older reports above are the same failure, so this has never worked.

Cause

When Android binds an app for a full backup (bmgr backupnow --all, adb backup, or a device transfer), ActivityThread.handleBindApplication() runs in restricted backup mode:

  • makeApplicationInner(data.restrictedBackupMode, …) instantiates the base android.app.Application instead of the app's Application subclass.
  • installContentProviders() is skipped (if (!data.restrictedBackupMode)).

.NET for Android initializes the runtime from a ContentProvider (MonoRuntimeProvider/NativeAotRuntimeProvider), so in this process the runtime is never initialized. The first managed Java callable wrapper to load (the custom BackupAgent, or a JobService the scheduler routes into the already-running backup process) calls Runtime.registerNatives() from its static initializer and crashes.

How we arrived at the fix

We went through the hooks Android offers to run code before app components start:

Hook Runs in restricted backup mode? Notes
ContentProvider (current) No Skipped by installContentProviders()
Application subclass (attachBaseContext/onCreate) No Replaced by base android.app.Application
androidx.startup No Itself a ContentProvider
Lazy init from the JCW static initializer Yes No Context/ApplicationInfo available; changes every generated wrapper
AppComponentFactory (API 28+) Yes instantiateApplication() runs in every process, before the Application exists

AppComponentFactory is the only supported hook that runs for every entry point. Two details shaped the design:

  • instantiateApplication() doesn't receive a Context or ApplicationInfo. instantiateClassLoader() does receive the ApplicationInfo, but it was added in API 29. So the factory can only initialize the runtime on API 29+. On API 28 it is instantiated but does nothing.
  • Initialization can't be deferred to a later factory callback. ActivityThread.handleCreateBackupAgent() creates the BackupAgent with cl.loadClass(classname).newInstance(), not through the factory, so instantiateApplication() is the last point every entry path is guaranteed to go through.

Changes

The trimmable typemap path (CoreCLR and NativeAOT) now emits:

<application android:appComponentFactory="net.dot.android.CoreClrAppComponentFactory"
             tools:replace="android:appComponentFactory" …>

NativeAOT uses net.dot.jni.nativeaot.NativeAotAppComponentFactory instead. tools:replace is needed because library manifests (e.g. androidx.core's CoreComponentFactory) also declare a factory. If the app's own manifest template already declares android:appComponentFactory, it is left alone and the provider keeps initializing the runtime.

  • RuntimeAppComponentFactory (in java_runtime_trimmable.jar) captures the ApplicationInfo in instantiateClassLoader() and calls initializeRuntime() from instantiateApplication().
  • The two subclasses are each one method: CoreCLR calls mono.MonoPackageManager.LoadApplication(), and NativeAOT calls JavaInteropRuntime.initialize().
    • JavaInteropRuntime is generated per app because it embeds the app's library name, so the NativeAOT factory is generated with it by <GenerateNativeAotBootstrapSources/>.
  • The runtime providers and the factories share the same init entry points, which are now idempotent and synchronized. The providers are kept unconditionally: on API 24–28 they initialize the runtime, and on API 29+ their call is a no-op.
    • We prototyped disabling the providers on API 29+ via a values-v29 bool resource and android:enabled, but dropped it. It added a target, a resource visible in the app's Resource designer, and removed the fallback, for no functional gain.
  • Without a Context, the files and cache directories are computed as new File(ApplicationInfo.dataDir, "files"/"cache"). This is exactly what ContextImpl.getFilesDir()/getCacheDir() compute for the app context; ApplicationInfo.dataDir already points at device-protected storage for defaultToDeviceProtectedStorage apps. RuntimeDirectories also creates the directories, as the Context methods do. Android only creates cache/ and code_cache/ at install, so files/ would otherwise be missing when the backup process is the app's first process.
  • NativeLibraryHelper and JavaInteropRuntime.loadLibrary() gained ApplicationInfo overloads, since no Context is available yet.

C# Application subclasses

The factory calls super.instantiateApplication() first, so Android still instantiates the generated Java wrapper for a C# Application subclass. Wrappers for Application types (CannotRegisterInStaticConstructor) don't call registerNatives from their static initializer, and their constructors don't call into native code, so this is safe before the runtime exists. The factory then initializes the runtime with that not-yet-attached instance. ApplicationRegistration.registerApplications() registers the app class's natives, and Android continues with attach() → attachBaseContext() → onCreate().

This also fixes a pre-existing crash on API 29+. With only the content provider, a C# Application that overrides AttachBaseContext crashes at startup on every API level:

java.lang.UnsatisfiedLinkError: No implementation found for void mono.android.Runtime.registerNatives(java.lang.Class)
  at crc64….MyApp.__md_registerNatives
  at crc64….MyApp.attachBaseContext
  at android.app.Application.attach

Android calls attachBaseContext() before installing content providers, and the generated lazy __md_registerNatives() can't help there, because Runtime.registerNatives isn't bound until the runtime is initialized. With the factory, the runtime is already up on API 29+. On API 24–28 the crash remains. A possible follow-up is to have the generated attachBaseContext (Context base) for Application types initialize the runtime from base before calling __md_registerNatives().

In the restricted backup process, Android always uses the base android.app.Application, so a C# Application subclass is never instantiated and its OnCreate() doesn't run. The runtime is initialized, but state set up in Application.OnCreate() (e.g. MAUI's service provider) isn't available to a backup agent or a job running in that process.

Compatibility

No public Java type is renamed or removed, and the only API changes are additions:

  • mono.MonoPackageManager.LoadApplication (ApplicationInfo, ClassLoader, Context)
  • mono.NativeLibraryHelper.loadLibrary (String, ApplicationInfo)

Renaming the remaining mono.* Java types is proposed separately in #13664 because it is breaking.

The behavior changes are:

  • The app's merged manifest declares our android:appComponentFactory with tools:replace. That replaces a factory declared by a library manifest, such as AndroidX's CoreComponentFactory. A factory declared in the app's own manifest template is kept, and then the fix doesn't apply.
  • .NET now initializes in restricted backup processes, which previously crashed whenever managed code ran.

Limitations

  • API 24–28 is not fixed. There, instantiateClassLoader() doesn't exist, so the runtime provider remains the only initializer and the restricted-backup crash remains. According to https://apilevels.com/, API 29+ covers ≥ 96.6% of devices. We're still looking into ways to get this working on all API 24+ levels, but right now full coverage doesn't seem likely.
  • AttachBaseContext overrides on API 24–28: a C# Application overriding AttachBaseContext still crashes there (pre-existing; see above).
  • No C# Application in the backup process: its OnCreate() never runs in restricted backup mode (Android behavior).
  • Apps that declare their own android:appComponentFactory keep it and don't get the fix.
  • AndroidX's CoreComponentFactory is replaced. It only adds support for AndroidX's CompatWrapped components.
  • The runtime now starts in backup processes, which previously crashed whenever managed code ran. A process that runs no managed code pays the startup cost.
  • Only the trimmable typemap path is wired up.

Validation

Focused unit tests:

./dotnet-local.sh test src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/Microsoft.Android.Build.Tasks.Tests.csproj \
    --filter "FullyQualifiedName~TrimmableTypeMap|FullyQualifiedName~NativeAotBootstrapTargetsTests"

Passed: 142/142. This includes a new AppComponentFactoryIsAddedUnlessTemplateDeclaresOne test (3 cases). The full-build tests that were updated (NativeAotBuildTests, TrimmableTypeMapBuildTests, FastDevTest) were not run locally.

On-device validation used a test app with a managed JobService and a managed full-backup agent (android:fullBackupOnly="true"). The app was built with -c Release for CoreCLR and with -p:PublishAot=true for NativeAOT; the NativeAOT APK contains only libProto.so. The restricted backup process was started through IBackupManager/bindBackupAgent, after which the job was run with cmd jobscheduler run -f.

Scenario (API 33 emulator) Without factory With factory
Normal start + job ✅ ✅
Restricted backup process: managed backup agent created ❌ UnsatisfiedLinkError ✅
Job routed into the backup process ❌ (process crashed) ✅
Fresh install, backup process is the first process ❌ UnsatisfiedLinkError ✅, files/ created

The results were identical for CoreCLR and NativeAOT. The "without factory" builds used -p:_TrimmableAppComponentFactoryJavaName=.

A second test app declares a C# Application subclass ([Application]) that overrides AttachBaseContext and OnCreate, with the managed backup agent and JobService:

Scenario CoreCLR NativeAOT
API 33 with factory: normal start ✅ managed ctor → AttachBaseContext (FilesDir works) → OnCreate → activity/job see MyApp ✅ same
API 33 with factory: restricted backup agent + job ✅ no crash; Application.Context is Android.App.Application; MyApp.OnCreate didn't run ✅ same
API 33 without factory (-p:_TrimmableAppComponentFactoryJavaName=) ❌ UnsatisfiedLinkError in MyApp.attachBaseContext ❌ same
API 27 (provider path) ❌ UnsatisfiedLinkError in MyApp.attachBaseContext ❌ same
API 27, C# Application overriding only OnCreate ✅ ctor → OnCreate → activity → job ✅ same

These runs used a local SDK rebuilt from this branch with make leeroy CONFIGURATION=Debug.

On an API 27 emulator, CoreCLR and NativeAOT both started normally and ran the job. The provider initialized the runtime, and there was no VerifyError from the API 28+ factory class. That run used an earlier iteration of this change, before the RuntimeDirectories refactoring. API 28 was not tested on a device.

simonrozsival added a commit that referenced this pull request Nov 19, 2026
Stacked on #13662. This is a pure rename: no behavior changes.

Every Java-visible `mono` name (Java packages and classes, JNI names,
Java member names, the runtime provider authority suffix) and the
packaged native runtime library name are renamed:

  * `mono.android.Runtime` -> `net.dot.android.Runtime`, including
    `XamarinUncaughtExceptionHandler`
  * `mono.android.IGCUserPeer` / `mono.android.GCUserPeer` ->
    `net.dot.android.IGCUserPeer` / `net.dot.android.GCUserPeer`
  * `mono.android.app.IntentService` -> `net.dot.android.app.IntentService`
  * `mono.NativeLibraryHelper` -> `net.dot.android.NativeLibraryHelper`
  * `mono.MonoPackageManager_Resources` ->
    `net.dot.android.CoreClrPackageManager_Resources`
  * `mono.MonoRuntimeProvider` (and `_N` copies) ->
    `net.dot.android.CoreClrRuntimeProvider` (and `_N`); the template
    `MonoRuntimeProvider.Bundled.java` -> `CoreClrRuntimeProvider.Bundled.java`
  * `Runtime` fields `mono_NativeLibraryHelper` / `mono_android_IGCUserPeer`
    -> `nativeLibraryHelperClass` / `igcUserPeerClass`
  * `IGCUserPeer.monodroidAddReference()` / `monodroidClearReferences()`
    -> `dotnetAddReference()` / `dotnetClearReferences()`
  * `Java_mono_android_Runtime_*` JNI exports ->
    `Java_net_dot_android_Runtime_*`; `mono_android_Runtime.h` ->
    `net_dot_android_Runtime.h`
  * Provider authority suffix `.__mono_init__` -> `.__dotnet_init__`
  * Mono.Android binding helpers: `mono/android/X` -> `net/dot/android/X`
    and `mono/java/lang/X` -> `net/dot/android/java/lang/X`
  * `generator` output: `mono/internal/X` -> `net/dot/android/internal/X`;
    event `*Implementor` names `mono/android/X` -> `net/dot/android/X`
    and `mono/<other>/X` -> `net/dot/android/<other>/X`
  * Packaged `lib/<abi>/libmonodroid.so` -> `lib/<abi>/libnet-android.so`.
    Java loads it as `net-android`, and native extract-mode detection
    probes `libnet-android.so`.

C++ identifiers, CMake variables, MSBuild properties, `Mono.Android.dll`,
C# namespaces, and log tags are unchanged.
`mono.android.__FastDevLauncher` is only a legacy-manifest filter in
`AndroidAppManifest`, so it is unchanged.

The Mono.Android `[Register]` changes are recorded in
`acceptable-breakages-vReference-net12.0.txt`.

Stale generated Java under `obj/.../android/src/mono/` is removed by
`_CleanIntermediateIfNeeded` when `$(AndroidNETSdkVersion)` changes.
`BuildTest.RemoveOldMonoPackageManager` covers that path and still
simulates the legacy files.

Compatibility:

  * Third-party binding assemblies built by an older `generator` keep
    their own `mono/...` JNI names for their generated types. Those names
    are self-consistent and continue to work.
  * Java code, for example in an AAR, that directly references
    `mono.android.*`, `mono.MonoRuntimeProvider`, or implements
    `monodroidAddReference` / `monodroidClearReferences` breaks.
  * Custom manifests that declare the old provider/authority must be updated.

Validation (local Debug SDK, macOS):

  * `make leeroy CONFIGURATION=Debug MSBUILD_ARGS='-nr:false -m:4
    -p:EnableSourceLink=false -p:EnableSourceControlManagerQueries=false'`
    succeeds after the ApiCompat update. Locally, a stale
    `Mono.Android.xml` from the previous javadoc build was copied back into
    `xbuild-frameworks` for `ConfigureLocalWorkload`. The deployed pack
    contains `net/dot/android/*.class` in `java_runtime_trimmable.jar`,
    `Java_net_dot_android_Runtime_*` exports, and no `mono/android` in
    `Mono.Android.dll`.
  * Microsoft.Android.Build.Tasks.Tests, filtered to TrimmableTypeMap,
    NativeAotBootstrapTargetsTests, GeneratePackageManagerJava,
    JavaRuntimeTargets, GenerateTrimmableTypeMap, and
    GenerateCoreClrRuntimeProviderSources: 147/147 passed.
  * generator-Tests 489/489, Java.Interop.Tools.JavaTypeSystem-Tests
    17/17, and Xamarin.Android.Tools.ApiXmlAdjuster-Tests 13/13 passed.
  * Xamarin.Android.Build.Tests: R8Tests, RemoveOldMonoPackageManager,
    DirectBootAwareAttribute, CoreClrBootstrapInputsAreIndependentOfJavaResources,
    NativeLibraryJniPreload_DefaultsWork,
    TrimmableTypeMap_RuntimeArtifacts_ArePackagedInSdk, RetainedTypeMapRulesDriveR8,
    ReleaseCoreClrTrimmableTypeMap_TrimsUnusedBindingListenerImplementors,
    BuildProguardEnabledProject, and Build_WithTrimmableTypeMap_Succeeds
    passed.
  * Xamarin.Android.Build.Tests: BuildReleaseArm64 (4 cases) failed apkdiff
    size thresholds (local Debug SDK size drift). Entry names match the
    renamed `libnet-android.so`.
  * Mono.Android.NET-Tests, CoreCLR Debug, on an API 33 emulator:
    1087 passed, 8 skipped, 0 failed. An earlier run aborted on a Debug
    `LREF count is -1` assertion in
    `TrimmableTypeMapTypeManagerTests.RegisteredPeer_Dispose_Finalized`.
    It did not reproduce on rerun.
  * Restricted-backup startup harness, CoreCLR and NativeAOT, API 33:
    Activity, job (x2), and backup agent startup work, with no FATAL,
    UnsatisfiedLinkError, or ClassNotFoundException.

Co-authored-by: Copilot App <[email protected]>
simonrozsival and others added 2 commits November 21, 2026 08:03
…tory

Fixes: #13568

Managed components that run in a restricted full-backup process crash with `UnsatisfiedLinkError: No implementation found for void mono.android.Runtime.registerNatives(java.lang.Class)`, because Android skips content providers there and the runtime provider never initializes .NET. On API 29+ the trimmable typemap path now declares an `android:appComponentFactory` that initializes the runtime from `instantiateApplication()`, which runs in every process. The runtime provider stays and becomes a no-op once the factory has initialized the runtime.

Rename `mono.MonoPackageManager` to `net.dot.android.CoreClrPackageManager`.

Co-authored-by: Copilot App <[email protected]>
Renaming the public `mono.MonoPackageManager` breaks custom Java code that calls `mono.MonoPackageManager.LoadApplication (context)` (a known workaround for the restricted-backup crash) and makes custom ProGuard rules that name it no-ops. Keep this PR free of breaking renames; the rename moves to the stacked rename PR.

Co-authored-by: Copilot App <[email protected]>
simonrozsival added a commit that referenced this pull request Nov 21, 2026
Stacked on #13662. This is a pure rename: no behavior changes.

Every Java-visible `mono` name (Java packages and classes, JNI names,
Java member names, the runtime provider authority suffix) and the
packaged native runtime library name are renamed:

  * `mono.android.Runtime` -> `net.dot.android.Runtime`, including
    `XamarinUncaughtExceptionHandler`
  * `mono.android.IGCUserPeer` / `mono.android.GCUserPeer` ->
    `net.dot.android.IGCUserPeer` / `net.dot.android.GCUserPeer`
  * `mono.android.app.IntentService` -> `net.dot.android.app.IntentService`
  * `mono.NativeLibraryHelper` -> `net.dot.android.NativeLibraryHelper`
  * `mono.MonoPackageManager_Resources` ->
    `net.dot.android.CoreClrPackageManager_Resources`
  * `mono.MonoRuntimeProvider` (and `_N` copies) ->
    `net.dot.android.CoreClrRuntimeProvider` (and `_N`); the template
    `MonoRuntimeProvider.Bundled.java` -> `CoreClrRuntimeProvider.Bundled.java`
  * `Runtime` fields `mono_NativeLibraryHelper` / `mono_android_IGCUserPeer`
    -> `nativeLibraryHelperClass` / `igcUserPeerClass`
  * `IGCUserPeer.monodroidAddReference()` / `monodroidClearReferences()`
    -> `dotnetAddReference()` / `dotnetClearReferences()`
  * `Java_mono_android_Runtime_*` JNI exports ->
    `Java_net_dot_android_Runtime_*`; `mono_android_Runtime.h` ->
    `net_dot_android_Runtime.h`
  * Provider authority suffix `.__mono_init__` -> `.__dotnet_init__`
  * Mono.Android binding helpers: `mono/android/X` -> `net/dot/android/X`
    and `mono/java/lang/X` -> `net/dot/android/java/lang/X`
  * `generator` output: `mono/internal/X` -> `net/dot/android/internal/X`;
    event `*Implementor` names `mono/android/X` -> `net/dot/android/X`
    and `mono/<other>/X` -> `net/dot/android/<other>/X`
  * Packaged `lib/<abi>/libmonodroid.so` -> `lib/<abi>/libnet-android.so`.
    Java loads it as `net-android`, and native extract-mode detection
    probes `libnet-android.so`.

C++ identifiers, CMake variables, MSBuild properties, `Mono.Android.dll`,
C# namespaces, and log tags are unchanged.
`mono.android.__FastDevLauncher` is only a legacy-manifest filter in
`AndroidAppManifest`, so it is unchanged.

The Mono.Android `[Register]` changes are recorded in
`acceptable-breakages-vReference-net12.0.txt`.

Stale generated Java under `obj/.../android/src/mono/` is removed by
`_CleanIntermediateIfNeeded` when `$(AndroidNETSdkVersion)` changes.
`BuildTest.RemoveOldMonoPackageManager` covers that path and still
simulates the legacy files.

Compatibility:

  * Third-party binding assemblies built by an older `generator` keep
    their own `mono/...` JNI names for their generated types. Those names
    are self-consistent and continue to work.
  * Java code, for example in an AAR, that directly references
    `mono.android.*`, `mono.MonoRuntimeProvider`, or implements
    `monodroidAddReference` / `monodroidClearReferences` breaks.
  * Custom manifests that declare the old provider/authority must be updated.

Validation (local Debug SDK, macOS):

  * `make leeroy CONFIGURATION=Debug MSBUILD_ARGS='-nr:false -m:4
    -p:EnableSourceLink=false -p:EnableSourceControlManagerQueries=false'`
    succeeds after the ApiCompat update. Locally, a stale
    `Mono.Android.xml` from the previous javadoc build was copied back into
    `xbuild-frameworks` for `ConfigureLocalWorkload`. The deployed pack
    contains `net/dot/android/*.class` in `java_runtime_trimmable.jar`,
    `Java_net_dot_android_Runtime_*` exports, and no `mono/android` in
    `Mono.Android.dll`.
  * Microsoft.Android.Build.Tasks.Tests, filtered to TrimmableTypeMap,
    NativeAotBootstrapTargetsTests, GeneratePackageManagerJava,
    JavaRuntimeTargets, GenerateTrimmableTypeMap, and
    GenerateCoreClrRuntimeProviderSources: 147/147 passed.
  * generator-Tests 489/489, Java.Interop.Tools.JavaTypeSystem-Tests
    17/17, and Xamarin.Android.Tools.ApiXmlAdjuster-Tests 13/13 passed.
  * Xamarin.Android.Build.Tests: R8Tests, RemoveOldMonoPackageManager,
    DirectBootAwareAttribute, CoreClrBootstrapInputsAreIndependentOfJavaResources,
    NativeLibraryJniPreload_DefaultsWork,
    TrimmableTypeMap_RuntimeArtifacts_ArePackagedInSdk, RetainedTypeMapRulesDriveR8,
    ReleaseCoreClrTrimmableTypeMap_TrimsUnusedBindingListenerImplementors,
    BuildProguardEnabledProject, and Build_WithTrimmableTypeMap_Succeeds
    passed.
  * Xamarin.Android.Build.Tests: BuildReleaseArm64 (4 cases) failed apkdiff
    size thresholds (local Debug SDK size drift). Entry names match the
    renamed `libnet-android.so`.
  * Mono.Android.NET-Tests, CoreCLR Debug, on an API 33 emulator:
    1087 passed, 8 skipped, 0 failed. An earlier run aborted on a Debug
    `LREF count is -1` assertion in
    `TrimmableTypeMapTypeManagerTests.RegisteredPeer_Dispose_Finalized`.
    It did not reproduce on rerun.
  * Restricted-backup startup harness, CoreCLR and NativeAOT, API 33:
    Activity, job (x2), and backup agent startup work, with no FATAL,
    UnsatisfiedLinkError, or ClassNotFoundException.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival
simonrozsival force-pushed the simonrozsival-issue-13568-investigation branch from 97dbdb3 to 34cd05f Compare November 21, 2026 07:03

This branch has not been deployed

No deployments
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.

Native AOT JobService crashes in Runtime.registerNatives when Android reuses a backup process

2 participants