Repository navigation
[Mono.Android] Fix IL3050 in NativeAOT apps and correct trimming waivers - #13656
Conversation
There was a problem hiding this comment.
🟢 Approval recommended
The NativeAOT warning and trimming-waiver updates have no active review issues.
No open issues 🎉
What changed in this PR
This PR addresses Mono.Android’s NativeAOT IL3050/IL3053 warnings and updates trimming-waiver justifications as part of the audit tracked in #13618.
Changes:
- Isolates the
IsDynamicCodeSupportedguard in a collection-converter helper without changing converter selection. - Adds explicit dependencies to preserve reflected collection
FromJniHandlemethods. - Corrects peer-activation waiver explanations and removes an inapplicable array suppression.
| File | Description |
|---|---|
| src/Mono.Android/Java.Interop/SafeJavaCollectionFactory.cs | Corrects waiver explanations for collection element activation. |
| src/Mono.Android/Java.Interop/SafeArrayFactory.cs | Removes the inapplicable IL2055 suppression from array construction. |
| src/Mono.Android/Java.Interop/JavaConvert.cs | Separates the dynamic-code guard, preserves reflected converters, and updates waivers. |
| src/Mono.Android/Android.Runtime/JNIEnv.cs | Replaces the placeholder IL2067 justification with the peer-activation rationale. |
Review effort: Balanced
a778318 to
6fe7fdb
Compare
Context: #13618 Every NativeAOT app gets an IL3053 warning for Mono.Android. With `$(TrimmerSingleWarn)`=false it expands to IL3050 in `JavaConvert.GetJniHandleConverter ()`, for its call to the `[RequiresDynamicCode]` `TryMakeGenericCollectionTypeFactory ()`. The call was guarded by `RuntimeFeature.UseTypeMapAttributesForJavaDictionaryValueTypeLookups || !RuntimeFeature.IsDynamicCodeSupported`. The Roslyn analyzer accepts that, but ILC only treats `IsDynamicCodeSupported` as a guard when it is tested on its own. The converter lookup moves into `GetGenericCollectionConverter ()`, which tests `IsDynamicCodeSupported` alone in its own `if`; behavior is unchanged. `TryMakeGenericCollectionTypeFactory ()` becomes a static method with `[DynamicDependency]` on `FromJniHandle` of `JavaList<>`, `JavaCollection<>` and `JavaDictionary<,>`. ILLink sees the `typeof (X<>).MakeGenericType ()` calls today, so this doesn't change current output, but it keeps the reflected method alive if that code is restructured; without it `CreateDelegate ()` throws `ArgumentNullException`. The remaining waivers on this path got justifications that match the code, as the audit in #13618 found several outdated ones: * `JNIEnv.GetArray ()` IL2067, `JavaConvert` IL2055/IL2067, and the `SafeJavaCollectionFactory` IL2071s now describe the actual flow: elements are activated by their generated `JavaPeerProxy`, and only closed generic peers are activated by reflection, whose constructor the generator keeps (the previous commit). The old IL2071 text claimed the wrappers never activate elements. * `SafeArrayFactory.MakeReferenceArrayType ()` drops an IL2055 suppression: `MakeArrayType ()` doesn't produce IL2055, and the build has no warning without it. Co-authored-by: Copilot App <[email protected]>
6fe7fdb to
527e0c4
Compare
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
No blocking code findings: 0 ❌ errors, 0
Reviewed all four changed source files and traced converter selection, collection element activation, and generated generic-peer constructor preservation. The reordered guard preserves the reflective-versus-safe converter selection and the existing untyped fallbacks. The explicit FromJniHandle dependencies match the three wrapper types reflected over; the revised constructor justifications match TrimmableTypeMap and the generator's activation-constructor dependency. Removing IL2055 from the MakeArrayType helper is appropriately scoped. The follow-up test coverage is tracked in #13657/#13658, rather than included here.
CI verification is limited: all 38 GitHub checks passed, including the aggregate dotnet-android check for Azure build 1693060. Direct Azure build/timeline queries were blocked by Azure CLI initialization/authentication errors, so I could not independently confirm its build result or inspect non-gating device-test outcomes. No local build or device tests were run; the reported warning-elimination results were not independently reproduced. No CI failure or code regression was identified in the available evidence.
Generated by Android PR Reviewer for #13656 · copilot · gpt61 · 47.9 AIC · ⌖ 4.76 AIC · ⊞ 21K
Comment /review to run again
…vert ILLink tracks typeof (X<>).MakeGenericType () as X<>, so the [DynamicallyAccessedMembers (PublicMethods)] parameter of GetJniHandleConverterForType () already keeps FromJniHandle. Explain why CoreCLR and PublishAot builds take different paths. Co-authored-by: Copilot App <[email protected]>
Resolve FromJniHandle on each statically known open collection wrapper, then map its metadata definition onto the closed type. Remove the IL2067 suppression and the PublicMethods requirement without changing the existing dynamic-code guard or MakeGenericType IL2055 rationale. Add a JavaConvert test category to run the existing conversion fixture independently. Validation: Release make leeroy and Mono.Android build passed with no IL2067/IL3050 diagnostics from JavaConvert. Full-trim CoreCLR Release and NativeAOT Release app builds passed with TrimmerSingleWarn=false; runtime selection was confirmed from binlogs and APK contents. Device reruns were blocked by boot-time SIGSEGV in both installed emulator versions on an isolated AVD; emulator-5590 was untouched. Co-authored-by: Copilot App <[email protected]>
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
Code assessment: no blocking findings — 0 errors, 0 warnings, 1 non-blocking inline testing suggestion.
The standalone IsDynamicCodeSupported guard preserves converter selection, including the PublishAot feature-switch path. Resolving the declared method on each known open wrapper and mapping its metadata definition avoids preserving all public methods. The revised constructor-preservation justifications match TrimmableTypeMap.CreateInstance and the generator's conditional DynamicDependency emission. JNI ownership handling is unchanged.
CI: All 38 reported GitHub checks succeeded, including the overall dotnet-android check for Azure build 1694996. Independent Azure build/timeline verification was blocked: az devops invoke required login, and the public HTTP read was denied. Thus the GitHub check results are verified, but a full Azure CI assessment remains incomplete. No local builds or device tests were run for this review.
Generated by Android PR Reviewer for #13656 · copilot · gpt61 · 49.6 AIC · ⌖ 7.38 AIC · ⊞ 20.3K
Comment /review to run again
Context: #8724 Context: #13656 `JNIEnv.GetArray()` converts Java object arrays through a `Dictionary<Type, Func<Type, IntPtr, int, object?>>`. Its `IJavaObject` converter passed the element `Type` to `Java.Lang.Object.GetObject()`, whose `type` parameter required `[DynamicallyAccessedMembers(PublicConstructors | NonPublicConstructors)]`. A `Type` taken from a dictionary of lambdas carries no annotation, so ILLink reported IL2067, and the converter silenced it with `[UnconditionalSuppressMessage]` and a FIXME. The suppression hid a real question: would trimmed and NativeAOT apps keep the constructor that activation needs? If they didn't, a trimmed app would fail at run time with no build warning. ### Where the DAM requirement came from With the trimmable typemap, most peers are created by their generated proxy's `CreateInstance()`, which calls the constructor directly and needs no reflection. Closed instantiations of open generic peers, such as `JavaList<string>`, are the exception. Their proxy is generated for the open definition, so it can't `newobj` an arbitrary closed type. Until now, `TrimmableTypeMap.CreateInstance()` found the `(IntPtr, JniHandleOwnership)` constructor by calling `GetConstructor()` on the caller's closed `Type`. That call needed DAM on the closed `Type`. The requirement spread up through `TrimmableTypeMapValueManager.CreatePeer()`, the public `JniValueManager.GetPeer()` and `CreatePeer()`, and `Object.GetObject()`. It finally reached callers like `JNIEnv.GetArray()` that can't satisfy it. The generated proxy added a `[DynamicDependency]` on the definition's constructor to keep it, but that didn't satisfy the data-flow requirement on the caller's `Type`. ### Mapping the constructor by metadata identity Generated proxies for eligible open generic peers now override a new protected virtual method, `JavaPeerProxy.GetGenericTargetTypeDefinition()`. The override returns `typeof(Definition<>)`, and its return value is annotated with `[DynamicallyAccessedMembers(PublicConstructors | NonPublicConstructors)]`. That annotation replaces the old `[DynamicDependency]`. ILLink and ILC keep the definition's constructors whenever the proxy is kept. At run time, `JavaPeerProxy.CreateClosedGenericInstance()` does the following: 1. Checks that the requested closed type is an instantiation of the returned definition. 2. Looks up the `(IntPtr, JniHandleOwnership)` constructor on the definition. The annotation keeps that lookup warning-free. 3. Calls `closedType.GetMemberWithSameMetadataDefinitionAs(definitionCtor)` to get the matching constructor on the closed type, then invokes it. `GetMemberWithSameMetadataDefinitionAs()` matches the constructor on the closed type by metadata definition, not by name and signature, so it never reflects over the caller's `Type`. Because the definition's constructor is kept, the matching constructor on each instantiation is kept too. The annotation is still needed: the mapping doesn't keep members by itself. ### Selecting the requested generic proxy The first compatible Java alias can be a base generic proxy even when the caller requests a derived generic peer. Mapping the base proxy's constructor to the derived type would fail. For that case, activation finds the exact requested generic definition in the Java object's class and interface hierarchy, with an assignability-checked managed lookup as a fallback. Managed alias lookup also prefers an exact generic definition over an earlier compatible base alias. This preserves the Java compatibility check and does not rely solely on `FindClass`, which may use another class loader. The regression tests cover aliases on the same Java class, on a superclass, and on an interface, as well as an incompatible Java object. They also verify that a managed alias group prefers the exact proxy. ### Regression proof The new tests were run against the same final test assemblies twice: first with the proxy-selection fix removed, then with the fix restored. Without the fix, four tests failed: the same-class, superclass, and interface activation tests threw `NotSupportedException` because no compatible generic proxy could activate the requested type, and `TryGetProxyType_GenericAlias_PrefersExactTarget` selected the base proxy instead of the exact derived proxy. With the fix, those four tests passed, and the complete 53-test set passed on both trimmed CoreCLR and NativeAOT. This verifies that the tests reproduce the regression and that the implementation fixes it. ### Scope and compatibility * The override is generated only when the activation constructor is a Xamarin.Android-style `(IntPtr, JniHandleOwnership)` constructor declared on the leaf type. This is the same condition that previously added `[DynamicDependency]`. Other proxies use the base method, which returns `null`, so activation returns `null` as it did when no constructor was found. * For a compatible closed generic peer, activation invokes the same constructor with the same handle and ownership arguments. * Public API: adds `protected virtual Type? JavaPeerProxy.GetGenericTargetTypeDefinition()`. Removes `[DynamicallyAccessedMembers]` from the `targetType` parameter of `JniRuntime.JniValueManager.GetPeer()` and `CreatePeer()`. This is an intentional .NET 12 contract change. Custom value managers that override `CreatePeer()` should drop the annotation too, or they get IL2092 for the mismatch. * The `CreateValue()`/`GetValue()` and `JavaConvert` conversion paths still need DAM and are left unchanged. Removing it there means auditing their public and custom value-manager contracts separately.
) Context: #13721 Context: #13656 `SafeJavaCollectionFactory` uses `Activator.CreateInstance` on runtime-constructed collection wrappers, so the trimmer cannot identify their activation constructors and requires three IL2072 suppressions. Find each `(IntPtr, JniHandleOwnership)` constructor on the statically known open `JavaList<>`, `JavaCollection<>`, or `JavaDictionary<,>` definition, then map it to the closed wrapper with `GetMemberWithSameMetadataDefinitionAs` and invoke it. This removes all three IL2072 suppressions without adding new ones. Keep the separate `MakeGenericType` IL2071/IL3050 waivers and the concrete NativeAOT canonical-template roots: mapping a preserved member does not itself root a generic native template. Include the existing three-row reference-argument canonical-template test in `NativeAOTTrimmable`, so focused device runs exercise these paths while keeping expected wrapper types open. ### Size Measured the same android-arm64 Release test application before and after the change on macOS arm64, using SDK `12.0.100-alpha.1.26556.115` and identical category filters. The signed CoreCLR APK changed from 35,666,702 to 35,658,510 bytes (-8,192); the signed NativeAOT APK changed from 13,215,861 to 13,211,765 bytes (-4,096). The NativeAOT application library changed from 33,337,216 to 33,336,224 bytes (-992). These are test-app measurements, not a general size guarantee.
Convert untyped java.util.ArrayList, HashSet, and HashMap instances to IList<string>, ICollection<string>, and IDictionary<string, string> through JNIEnv.GetArray<T> (), which reaches JavaConvert with only a runtime Type. The app never names JavaList<T>, JavaCollection<T>, or JavaDictionary<K,V> or calls their FromJniHandle (), so only JavaConvert's open-definition mapping (#13656) can keep those methods under full trimming. Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Convert untyped java.util.ArrayList, HashSet, and HashMap instances to IList<string>, ICollection<string>, and IDictionary<string, string> through JNIEnv.GetArray<T> (), which reaches JavaConvert with only a runtime Type. The app never names JavaList<T>, JavaCollection<T>, or JavaDictionary<K,V> or calls their FromJniHandle (), so only JavaConvert's open-definition mapping (#13656) can keep those methods under full trimming. Co-authored-by: Copilot App <[email protected]>
Context: #13721 Context: #13656 `Java.Interop.ValueTypeFactory<T>.CreateReferenceMixedDictionary()` requires an IL2072 suppression because `Activator.CreateInstance()` receives a runtime-constructed dictionary type whose constructors the trimmer cannot track. Obtain the activation constructor from the statically rooted closed exemplar, map it onto the requested dictionary type with `GetMemberWithSameMetadataDefinitionAs()`, and invoke it. This applies the constructor-mapping approach from #13721 independently of that change and removes IL2072. Retain the closed exemplar roots: mapping preserves neither constructors nor the NativeAOT canonical templates for the exact value-type argument. The separate IL2055 and IL3050 suppressions for `MakeGenericType()` remain. Add reference-key/value-type dictionary coverage alongside the existing value-key/reference-value test. A `string`/`bool?` case avoids the independently rooted `string`/`int` wrapper, allowing the reference-key exemplar to be tested in isolation.
Context: #13618
Every NativeAOT app gets an IL3053 warning for Mono.Android. With
$(TrimmerSingleWarn)=false it expands to IL3050 inJavaConvert.GetJniHandleConverter (), for its call to the[RequiresDynamicCode]TryMakeGenericCollectionTypeFactory ().The call was guarded by
RuntimeFeature.UseTypeMapAttributesForJavaDictionaryValueTypeLookups || !RuntimeFeature.IsDynamicCodeSupported. The Roslyn analyzer accepts that, but ILC only treatsIsDynamicCodeSupportedas a guard when it is tested on its own. The converter lookup moves intoGetGenericCollectionConverter (), which testsIsDynamicCodeSupportedalone in its ownif; behavior is unchanged.TryMakeGenericCollectionTypeFactory ()becomes a static method. Instead of reflecting over a runtime-closed collection type, it resolves the declaredFromJniHandle (IntPtr, JniHandleOwnership)method on each statically known open definition (JavaList<>,JavaCollection<>, andJavaDictionary<,>), then usesGetMemberWithSameMetadataDefinitionAs ()to map that method onto the closed wrapper type. The open-definition lookup preserves the converter, so the helper no longer needs[DynamicallyAccessedMembers (PublicMethods)]or an IL2067 suppression. Redundant[DynamicDependency]attributes are also unnecessary. This does not make runtime generic construction NativeAOT-safe: the existing dynamic-code guard and AOT-safe converter path remain unchanged.The remaining waivers on this path get justifications that match the code, as the audit in #13618 found several outdated ones:
JNIEnv.GetArray ()IL2067,JavaConvertIL2055, and theSafeJavaCollectionFactoryIL2071s describe the actual flow: elements are activated by their generatedJavaPeerProxy, and only closed generic peers are activated by reflection, whose constructor the generator keeps.JavaConvertstill needs IL2055 becauseMakeGenericType ()cannot prove that runtime generic arguments satisfy the wrapper parameters' constructor-preservation requirements; metadata-definition mapping does not resolve that separate requirement. The old IL2071 text claimed the wrappers never activate elements.SafeArrayFactory.MakeReferenceArrayType ()drops an IL2055 suppression:MakeArrayType ()doesn't produce IL2055, and the build has no warning without it.The existing
JavaConvertTestfixture gains aJavaConvertcategory so it can be run independently.Validation
Validated the combined changes on
dev/simonrozsival/trimming-waivers. Builds usedMSBUILDDISABLENODEREUSE=1 DOTNET_CLI_USE_MSBUILD_SERVER=0; session-local binlog paths and output redirection are omitted below.make leeroy CONFIGURATION=Release MSBUILD_ARGS='-nr:false -m:4'— passed; rebuilt the local SDK../dotnet-local.sh build src/Mono.Android/Mono.Android.csproj -c Release -nr:false -warnaserror:IL2067,IL3050— passed, no IL2067/IL3050 diagnostics; two unrelated generated-code CS8603 warnings../dotnet-local.sh build tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -c Release -t:SignAndroidPackage -p:RuntimeIdentifier=android-arm64 -p:PublishAot=false -p:PublishTrimmed=true -p:TrimMode=full -p:TrimmerSingleWarn=false -p:IncludeCategories=JavaConvert -nr:false— passed;_AndroidRuntime=CoreCLRconfirmed in the binlog andlibcoreclr.soin the APK.-p:PublishAot=true— passed;_AndroidRuntime=NativeAOTconfirmed in the binlog andlibMono.Android.NET-Tests.soin the APK. Both app builds retain unrelated runtime-test/framework trim/AOT warnings, but none fromJavaConvert.Device tests could not be rerun on this combined branch: the isolated
copilot_javaconvert_63acda40AVD crashed during boot with both installed emulator versions (37.2.12 and 37.2.13, exit 139), including GPU-disabled/software-rendering attempts. The temporary AVD was removed; the sharedemulator-5590was not used or stopped. The earlier standalone mapping prototype passed all 27 JavaConvert tests on both trimmed CoreCLR Release and NativeAOT Release, but those results are not a device validation of this combined branch.