[TrimmableTypeMap] Add ManifestGenerator#10991
Conversation
There was a problem hiding this comment.
Pull request overview
Adds a Cecil-free ManifestGenerator to the TrimmableTypeMap generator pipeline, producing AndroidManifest.xml from scanner-captured component/assembly attributes, plus a new unit test suite validating expected manifest output.
Changes:
- Introduces
ManifestGeneratorto synthesize/merge manifest elements (components, permissions/features/libraries, runtime provider injection, placeholder replacement). - Adds xUnit tests covering activity/service/receiver/provider/application/instrumentation emission, template merging, placeholder replacement, and enum conversions.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 6 comments.
| File | Description |
|---|---|
| src/Microsoft.Android.Sdk.TrimmableTypeMap/Generator/ManifestGenerator.cs | New manifest generation/merge implementation driven by scanned attribute metadata (no Cecil). |
| tests/Microsoft.Android.Sdk.TrimmableTypeMap.Tests/Generator/ManifestGeneratorTests.cs | New unit tests validating generated manifest structure, merging, and attribute mapping behaviors. |
src/Microsoft.Android.Sdk.TrimmableTypeMap/Generator/ManifestGenerator.cs
Outdated
Show resolved
Hide resolved
src/Microsoft.Android.Sdk.TrimmableTypeMap/Generator/ManifestGenerator.cs
Outdated
Show resolved
Hide resolved
src/Microsoft.Android.Sdk.TrimmableTypeMap/Generator/ManifestGenerator.cs
Show resolved
Hide resolved
tests/Microsoft.Android.Sdk.TrimmableTypeMap.Tests/Generator/ManifestGeneratorTests.cs
Show resolved
Hide resolved
tests/Microsoft.Android.Sdk.TrimmableTypeMap.Tests/Generator/ManifestGeneratorTests.cs
Show resolved
Hide resolved
tests/Microsoft.Android.Sdk.TrimmableTypeMap.Tests/Generator/ManifestGeneratorTests.cs
Show resolved
Hide resolved
b686f08 to
c4c214f
Compare
71ed636 to
2b80737
Compare
3637001 to
e3b02dd
Compare
6a9cdd3 to
8eba142
Compare
e3b02dd to
7377bdf
Compare
c0bb477 to
d1ae3a5
Compare
…avaConvert (#10967) Fixes: #10791 ## Summary Adds the runtime-side support for the trimmable typemap: type resolution, peer creation, native method registration, and AOT-safe collection marshaling. All behind `RuntimeFeature.TrimmableTypeMap` (defaults to `false`). ### New runtime types - **`JavaPeerProxy` / `JavaPeerProxy<T>`** — AOT-safe proxy attribute base. Generated proxy types extend this and provide `CreateInstance()` for peer creation and `GetContainerFactory()` for collection marshaling. - **`IAndroidCallableWrapper`** — `RegisterNatives(JniType)` interface for ACW proxy types to register JNI native methods. - **`JavaPeerContainerFactory`** — AOT-safe factories for arrays, lists, collections, and dictionaries without `MakeGenericType()`. - **`TrimmableTypeMap`** — Central class owning the `TypeMapping` dictionary. Encapsulates all proxy attribute access: peer creation, invoker resolution, container factories, and native method registration bootstrap. - **`TrimmableTypeMapTypeManager`** — `JniTypeManager` subclass delegating type lookups to `TrimmableTypeMap`. `RegisterNativeMembers` throws `UnreachableException` (JCW static blocks handle registration). ### Type resolution - `GetProxyForManagedType(Type)` resolves managed type → JNI name via `IJniNameProviderAttribute` (shared interface for `[Register]` and `[JniTypeSignature]`) → TypeMap dictionary → proxy. Results cached in `ConcurrentDictionary`. - `TryGetJniNameForType` shared between `TrimmableTypeMap` and `TrimmableTypeMapTypeManager`. - `ActivateInstance` uses JNI `GetObjectClass` → `GetJniTypeNameFromClass` → TypeMap lookup for constructor activation (proxy types have self-applied attribute, not the target type). ### TypeMap dictionary initialization - The runtime's `GetOrCreateExternalTypeMapping<Java.Lang.Object>()` handles assembly resolution automatically via the `System.Runtime.InteropServices.TypeMappingEntryAssembly` runtimeconfig property (set in `Trimmable.targets`). No manual `Assembly.Load` pre-loading is needed — the runtime walks `TypeMapAssemblyTargetAttribute` attributes from the entry assembly recursively. ### Native interop refactoring - **`RegisterJniNatives` passed via init args** — `Initialize` sets `args->registerJniNativesFn` (null when `TrimmableTypeMap=true`). Eliminates the `create_delegate` call for `RegisterJniNatives`, letting the trimmer remove it cleanly in the trimmable path. - **C++ `registerNatives` stub** — `Host::Java_mono_android_Runtime_registerNatives` no-op for the trimmable path (managed code handles registration via `Initialize`). - **Null guard** on `jnienv_register_jni_natives` call site. - `Initialize` is now the **single** `create_delegate` entry point from native code. ### RegisterNatives bootstrap - `mono.android.Runtime.registerNatives(Class)` Java native method added - `TrimmableTypeMap.Initialize()` registers the JNI callback during init (behind explicit `if (RuntimeFeature.TrimmableTypeMap)` guard for trimmer compatibility) - When Java loads a JCW class, `OnRegisterNatives` resolves the proxy and calls `IAndroidCallableWrapper.RegisterNatives()` to bind UCO function pointers ### AOT-safe JavaConvert - `JavaConvert.GetJniHandleConverter()` uses `JavaPeerContainerFactory` for `IList`, `ICollection`, `IDictionary` - `JNIEnv.ArrayCreateInstance()` uses factory path ### Peer creation - `JavaMarshalValueManager` (renamed from `ManagedValueManager`) overrides `CreatePeer` for the trimmable path — calls `proxy.CreateInstance()` directly, bypassing `GetUninitializedObject` - `GetSimpleReferences` walks base type chain for managed-only subclasses without `[Register]` ### Wiring - `RuntimeFeature.TrimmableTypeMap` feature switch with ILLink substitutions - `JNIEnvInit` (CoreCLR) and `JavaInteropRuntime` + `JreRuntime` (NativeAOT) create the new managers when the feature is on - `JavaMarshalValueManager` (renamed from `ManagedValueManager`) gets proxy-based peer creation in `TryConstructPeer` ### Dependencies - dotnet/java-interop#1391 (RegisterNatives with raw function pointers — follow-up optimization) - Manifest generator: #10991 - Build pipeline: #10980 ### Test coverage - 255/255 generator tests pass - End-to-end HelloWorld app runs on device with Activity, layout XML, FindViewById\<Button\>, Click events - Runtime tests require device integration (tracked by #10793) ### Trimmer size regression prevention - Add ILLink substitutions for `IsMonoRuntime` and `IsCoreClrRuntime` — enables trimmer to eliminate runtime-specific branches - `JavaMarshalValueManager`: remove `TrimmableTypeMap?` field, use `TrimmableTypeMap.Instance` singleton - `TrimmableTypeMap`: private ctor, `Initialize()` static method, `Instance` throws if not initialized - `TrimmableTypeMapTypeManager`: no constructor parameter, uses singleton - No `TrimmableTypeMap` type references outside feature guards — clean trimming for MonoVM/NativeAOT Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jonathan Peppers <jonathan.peppers@microsoft.com>
ManifestGenerator in Microsoft.Android.Sdk.TrimmableTypeMap assembly. Converts ComponentInfo records from JavaPeerScanner into AndroidManifest.xml. - Data-driven property mapping (7 static arrays, 9 enum converters) - MainLauncher intent-filter, runtime provider, template merging, deduplication - Assembly-level: Permission, UsesPermission, UsesFeature, UsesLibrary, UsesConfiguration, Application, MetaData, Property - ManifestPlaceholders, debuggable/extractNativeLibs, ApplicationJavaClass - XA4213 constructor validation, duplicate Application detection - VersionCode defaults to '1' matching legacy 23 unit tests (xunit). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Split into focused classes in Microsoft.Android.Sdk.TrimmableTypeMap: - ManifestGenerator: orchestration (load template, call builders, write output) - ManifestConstants: shared AndroidNs and AttName - PropertyMapper: data-driven property mapping (7 arrays, MappingKind enum) - AndroidEnumConverter: 9 enum-to-string converters - ComponentElementBuilder: Activity/Service/Receiver/Provider/Instrumentation XML - AssemblyLevelElementBuilder: permissions, uses-permissions, features, libraries Features: MainLauncher, runtime provider (with dedup), template merging, ManifestPlaceholders, debuggable/extractNativeLibs, XA4213 validation. 30 unit tests (xunit, 130ms). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
7377bdf to
683c0be
Compare
simonrozsival
left a comment
There was a problem hiding this comment.
🤖 AI Review Summary
Verdict: ✅ LGTM
Found 1 suggestion (no blockers):
- 💡 Formatting: Use
[]instead ofArray.Empty<T>()inManifestModel.cs(4 occurrences)
👍 Clean, well-structured manifest generator with good separation of concerns — enum conversion, property mapping, component building, and assembly-level elements are each in focused files. Excellent test coverage (30 cases) covering all component types, template merging, dedup, placeholders, enum flags, and edge cases (abstract types, existing components). Proper use of CultureInfo.InvariantCulture for numeric formatting. Data models are kept together in ManifestModel.cs which is pragmatic for 13 small DTOs.
CI: All checks pending (branch just rebased). Cannot verify build status yet.
Review generated by android-reviewer from review guidelines.
| public class MetaDataInfo | ||
| { | ||
| public string Name { get; set; } = ""; | ||
| public string? Value { get; set; } |
There was a problem hiding this comment.
🤖 💡 Formatting — Per repo conventions, use [] instead of Array.Empty<T>():
public IReadOnlyList<IntentFilterInfo> IntentFilters { get; set; } = [];
public IReadOnlyList<MetaDataInfo> MetaData { get; set; } = [];Same applies to IntentFilterInfo.Actions, IntentFilterInfo.Categories below.
Rule: Use [] not Array.Empty<T>()
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Summary
Cecil-free Android manifest generation from component attributes captured by the SRM-based
JavaPeerScanner. Part of #10807.All code lives in the
Microsoft.Android.Sdk.TrimmableTypeMapassembly (netstandard2.0) — no MSBuild dependency.Depends on #10967. Used by #10980.
Features
Component attributes
[Activity],[Service],[BroadcastReceiver],[ContentProvider]with all named propertiesMainLauncher→<intent-filter>with MAIN/LAUNCHER +android:exported="true"[IntentFilter]→<intent-filter>with actions, categories, data elements[MetaData]→<meta-data>with name/value/resource[Application]→ updates<application>element attributes[Instrumentation]→<instrumentation>under<manifest>Assembly-level attributes
[Permission],[PermissionGroup],[PermissionTree]→<permission>etc. with dedup[UsesPermission]→<uses-permission>with maxSdkVersion[UsesFeature]→<uses-feature>(named + GL ES version variants)[UsesLibrary],[UsesConfiguration]→ inside<application>[assembly: Application]→ merged into<application>attributes[assembly: MetaData],[assembly: Property]→ inside<application>Build properties
ManifestPlaceholders—${key}→ value replacementCheckedBuild→android:debuggable+android:extractNativeLibsApplicationJavaClass→<application android:name="...">VersionCodedefaults to"1",VersionNamedefaults to"1.0"(matching legacy)Validation
Runtime provider
MonoRuntimeProvider/NativeAotRuntimeProviderinjectionTests
[Fact]/[Theory]), ~130ms