[NativeAOT] Fix AOT analysis warning IL3050 · Issue #19505 · dotnet/macios (original) (raw)

This issue is a follow-up to #19043

When building apps with NativeAOT, the ILC prints an AOT analysis warning IL3050: ..cctor(): Using member 'System.Enum.GetValues(Type)' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling.

The problem is caused by the [DynamicDependency] attributes we generate in the ApplyPreserveAttributeBase custom linker step when we're transforming [Preserve(AllMembers = true)]. There are two cases in which we get this warning:

We transform the attribute by generating a [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(T))] attribute on the module cctor. This will pull all members of T, but also all members of its base types. In the case of enums, this unfortunately includes the GetValues(Type) static method which is annotated with RequiresDynamicCode.

I see some potential solutions, each of them has a different trade-off:

What other solutions should we consider?

/cc @rolfbjarne @ivanpovazan @vitek-karas

Steps to Reproduce

  1. Build the MySingleView test app with NativeAOT:
dotnet publish -f net8.0-ios -r ios-arm64 \
    -p:PublishAot=true -p:PublishAotUsingRuntimepack=true \
    -p:EnableTrimAnalyzer=true -p:TrimmerSingleWarn=false \
    tests/dotnet/MySingleView/
  1. Inspect warnings

Expected Behavior

There are no build warnings.

Actual Behavior

ILC prints this warning:

ILC : AOT analysis warning IL3050: <Module>..cctor(): Using member 'System.Enum.GetValues(Type)' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. It might not be possible to create an array of the enum type at runtime. Use the GetValues<TEnum> overload or the GetValuesAsUnderlyingType method instead. [/.../xamarin-macios/tests/dotnet/MySingleView/MySingleView.csproj]