Repository navigation
[Xamarin.Android.Build.Tasks] Initialize .NET from an AppComponentFactory - #13662
Draft
simonrozsival wants to merge 2 commits into
Draft
simonrozsival wants to merge 2 commits into
simonrozsival wants to merge 2 commits into
Conversation
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]>
…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
force-pushed
the
simonrozsival-issue-13568-investigation
branch
from
November 21, 2026 07:03
97dbdb3 to
34cd05f
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
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 baseandroid.app.Applicationinstead of the app'sApplicationsubclass.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 customBackupAgent, or aJobServicethe scheduler routes into the already-running backup process) callsRuntime.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:
ContentProvider(current)installContentProviders()Applicationsubclass (attachBaseContext/onCreate)android.app.Applicationandroidx.startupContentProviderContext/ApplicationInfoavailable; changes every generated wrapperAppComponentFactory(API 28+)instantiateApplication()runs in every process, before theApplicationexistsAppComponentFactoryis the only supported hook that runs for every entry point. Two details shaped the design:instantiateApplication()doesn't receive aContextorApplicationInfo.instantiateClassLoader()does receive theApplicationInfo, 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.ActivityThread.handleCreateBackupAgent()creates theBackupAgentwithcl.loadClass(classname).newInstance(), not through the factory, soinstantiateApplication()is the last point every entry path is guaranteed to go through.Changes
The trimmable typemap path (CoreCLR and NativeAOT) now emits:
NativeAOT uses
net.dot.jni.nativeaot.NativeAotAppComponentFactoryinstead.tools:replaceis needed because library manifests (e.g. androidx.core'sCoreComponentFactory) also declare a factory. If the app's own manifest template already declaresandroid:appComponentFactory, it is left alone and the provider keeps initializing the runtime.RuntimeAppComponentFactory(injava_runtime_trimmable.jar) captures theApplicationInfoininstantiateClassLoader()and callsinitializeRuntime()frominstantiateApplication().mono.MonoPackageManager.LoadApplication(), and NativeAOT callsJavaInteropRuntime.initialize().JavaInteropRuntimeis generated per app because it embeds the app's library name, so the NativeAOT factory is generated with it by<GenerateNativeAotBootstrapSources/>.values-v29bool resource andandroid:enabled, but dropped it. It added a target, a resource visible in the app'sResourcedesigner, and removed the fallback, for no functional gain.Context, the files and cache directories are computed asnew File(ApplicationInfo.dataDir, "files"/"cache"). This is exactly whatContextImpl.getFilesDir()/getCacheDir()compute for the app context;ApplicationInfo.dataDiralready points at device-protected storage fordefaultToDeviceProtectedStorageapps.RuntimeDirectoriesalso creates the directories, as theContextmethods do. Android only createscache/andcode_cache/at install, sofiles/would otherwise be missing when the backup process is the app's first process.NativeLibraryHelperandJavaInteropRuntime.loadLibrary()gainedApplicationInfooverloads, since noContextis available yet.C#
ApplicationsubclassesThe factory calls
super.instantiateApplication()first, so Android still instantiates the generated Java wrapper for a C#Applicationsubclass. Wrappers forApplicationtypes (CannotRegisterInStaticConstructor) don't callregisterNativesfrom 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 withattach()→attachBaseContext()→onCreate().This also fixes a pre-existing crash on API 29+. With only the content provider, a C#
Applicationthat overridesAttachBaseContextcrashes at startup on every API level:Android calls
attachBaseContext()before installing content providers, and the generated lazy__md_registerNatives()can't help there, becauseRuntime.registerNativesisn'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 generatedattachBaseContext (Context base)forApplicationtypes initialize the runtime frombasebefore calling__md_registerNatives().In the restricted backup process, Android always uses the base
android.app.Application, so a C#Applicationsubclass is never instantiated and itsOnCreate()doesn't run. The runtime is initialized, but state set up inApplication.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:
android:appComponentFactorywithtools:replace. That replaces a factory declared by a library manifest, such as AndroidX'sCoreComponentFactory. A factory declared in the app's own manifest template is kept, and then the fix doesn't apply.Limitations
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.AttachBaseContextoverrides on API 24–28: a C#ApplicationoverridingAttachBaseContextstill crashes there (pre-existing; see above).Applicationin the backup process: itsOnCreate()never runs in restricted backup mode (Android behavior).android:appComponentFactorykeep it and don't get the fix.CoreComponentFactoryis replaced. It only adds support for AndroidX'sCompatWrappedcomponents.Validation
Focused unit tests:
Passed: 142/142. This includes a new
AppComponentFactoryIsAddedUnlessTemplateDeclaresOnetest (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
JobServiceand a managed full-backup agent (android:fullBackupOnly="true"). The app was built with-c Releasefor CoreCLR and with-p:PublishAot=truefor NativeAOT; the NativeAOT APK contains onlylibProto.so. The restricted backup process was started throughIBackupManager/bindBackupAgent, after which the job was run withcmd jobscheduler run -f.UnsatisfiedLinkErrorUnsatisfiedLinkErrorfiles/createdThe results were identical for CoreCLR and NativeAOT. The "without factory" builds used
-p:_TrimmableAppComponentFactoryJavaName=.A second test app declares a C#
Applicationsubclass ([Application]) that overridesAttachBaseContextandOnCreate, with the managed backup agent andJobService:AttachBaseContext(FilesDirworks) →OnCreate→ activity/job seeMyAppApplication.ContextisAndroid.App.Application;MyApp.OnCreatedidn't run-p:_TrimmableAppComponentFactoryJavaName=)UnsatisfiedLinkErrorinMyApp.attachBaseContextUnsatisfiedLinkErrorinMyApp.attachBaseContextApplicationoverriding onlyOnCreateOnCreate→ activity → jobThese 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
VerifyErrorfrom the API 28+ factory class. That run used an earlier iteration of this change, before theRuntimeDirectoriesrefactoring. API 28 was not tested on a device.