Skip to content

Commit 38cdcfd

Browse files
JamesNKhalter73eerhardtamcasey
authored
[AOT] Fix runtime warnings (#45604)
Co-authored-by: Stephen Halter <[email protected]> Co-authored-by: Eric Erhardt <[email protected]> Co-authored-by: Andrew Casey <[email protected]>
1 parent 09b0db0 commit 38cdcfd

File tree

44 files changed

+505
-169
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+505
-169
lines changed

Directory.Build.targets

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@
33
<!-- Only build Microsoft.AspNetCore.App, Microsoft.AspNetCore.App.Ref, ref/ assemblies, and ProjectTemplates in source build. -->
44
<!-- Analyzer package are needed in source build for WebSDK -->
55
<ExcludeFromSourceBuild
6-
Condition="'$(ExcludeFromSourceBuild)' == '' and
7-
'$(DotNetBuildFromSource)' == 'true' and
8-
'$(IsAspNetCoreApp)' != 'true' and
9-
'$(MSBuildProjectName)' != '$(TargetingPackName)' and
10-
'$(IsAnalyzersProject)' != 'true' and
6+
Condition="'$(ExcludeFromSourceBuild)' == '' and
7+
'$(DotNetBuildFromSource)' == 'true' and
8+
'$(IsAspNetCoreApp)' != 'true' and
9+
'$(MSBuildProjectName)' != '$(TargetingPackName)' and
10+
'$(IsAnalyzersProject)' != 'true' and
1111
'$(IsProjectTemplateProject)' != 'true'">true</ExcludeFromSourceBuild>
1212

13+
<EnableAOTAnalyzer Condition=" '$(EnableAOTAnalyzer)' == '' ">$([MSBuild]::ValueOrDefault($(IsTrimmable),'false'))</EnableAOTAnalyzer>
14+
1315
<!-- If the user has specified that they want to skip building any test related projects with SkipTestBuild,
1416
suppress all targets for TestProjects using ExcludeFromBuild. -->
1517
<ExcludeFromBuild Condition="'$(IsPackable)' != 'true' and

src/Components/Components/src/Microsoft.AspNetCore.Components.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
<Nullable>enable</Nullable>
99
<IsTrimmable>true</IsTrimmable>
1010
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
11+
<EnableAOTAnalyzer>false</EnableAOTAnalyzer>
1112
</PropertyGroup>
1213

1314
<ItemGroup>

src/Components/Web/src/Microsoft.AspNetCore.Components.Web.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
<RootNamespace>Microsoft.AspNetCore.Components</RootNamespace>
99
<Nullable>enable</Nullable>
1010
<IsTrimmable>true</IsTrimmable>
11+
<EnableAOTAnalyzer>false</EnableAOTAnalyzer>
1112
</PropertyGroup>
1213

1314
<ItemGroup>

src/Components/WebAssembly/JSInterop/src/Microsoft.JSInterop.WebAssembly.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
<IsShippingPackage>true</IsShippingPackage>
99
<Nullable>enable</Nullable>
1010
<IsTrimmable>true</IsTrimmable>
11+
<EnableAOTAnalyzer>false</EnableAOTAnalyzer>
1112
</PropertyGroup>
1213

1314
<ItemGroup>

src/Components/WebAssembly/WebAssembly.Authentication/src/Microsoft.AspNetCore.Components.WebAssembly.Authentication.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
<GenerateDocumentationFile>true</GenerateDocumentationFile>
1010
<IsTrimmable>true</IsTrimmable>
1111
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
12+
<EnableAOTAnalyzer>false</EnableAOTAnalyzer>
1213
</PropertyGroup>
1314

1415
<ItemGroup>

src/Components/WebAssembly/WebAssembly/src/Microsoft.AspNetCore.Components.WebAssembly.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
<Nullable>enable</Nullable>
1111
<IsTrimmable>true</IsTrimmable>
1212
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
13+
<EnableAOTAnalyzer>false</EnableAOTAnalyzer>
1314
</PropertyGroup>
1415

1516
<ItemGroup>

src/DataProtection/DataProtection/src/AuthenticatedEncryption/ManagedAuthenticatedEncryptorFactory.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ private Func<KeyedHashAlgorithm> GetKeyedHashAlgorithmFactory(ManagedAuthenticat
6363
throw Error.Common_PropertyCannotBeNullOrEmpty(nameof(configuration.ValidationAlgorithmType));
6464
}
6565

66+
typeof(KeyedHashAlgorithm).AssertIsAssignableFrom(configuration.ValidationAlgorithmType);
6667
_logger.UsingManagedKeyedHashAlgorithm(configuration.ValidationAlgorithmType.FullName!);
6768
if (configuration.ValidationAlgorithmType == typeof(HMACSHA256))
6869
{
@@ -111,7 +112,8 @@ private static class AlgorithmActivator
111112
/// <summary>
112113
/// Creates a factory that wraps a call to <see cref="Activator.CreateInstance{T}"/>.
113114
/// </summary>
114-
public static Func<T> CreateFactory<T>([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type implementation)
115+
[UnconditionalSuppressMessage("AOT", "IL3050", Justification = "MakeGenericType is safe to use because implementation is either a KeyedHashAlgorithm or SymmetricAlgorithm type.")]
116+
public static Func<T> CreateFactory<T>([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type implementation) where T : class
115117
{
116118
return ((IActivator<T>)Activator.CreateInstance(typeof(AlgorithmActivatorCore<>).MakeGenericType(implementation))!).Creator;
117119
}

src/DataProtection/Extensions/src/DataProtectionProvider.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,9 @@ internal static IDataProtectionProvider CreateProvider(
172172
setupAction(builder);
173173

174174
// extract the provider instance from the service collection
175+
// TODO: Remove when DI no longer has RequiresDynamicCodeAttribute https://github.com/dotnet/runtime/pull/79425
176+
#pragma warning disable IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
175177
return serviceCollection.BuildServiceProvider().GetRequiredService<IDataProtectionProvider>();
178+
#pragma warning restore IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
176179
}
177180
}

src/DefaultBuilder/src/WebApplicationBuilder.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ internal WebApplicationBuilder(WebApplicationOptions options, Action<IHostBuilde
3333

3434
configuration.AddEnvironmentVariables(prefix: "ASPNETCORE_");
3535

36+
// TODO: Remove when DI no longer has RequiresDynamicCodeAttribute https://github.com/dotnet/runtime/pull/79425
37+
#pragma warning disable IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
3638
_hostApplicationBuilder = new HostApplicationBuilder(new HostApplicationBuilderSettings
3739
{
3840
Args = options.Args,
@@ -41,6 +43,7 @@ internal WebApplicationBuilder(WebApplicationOptions options, Action<IHostBuilde
4143
ContentRootPath = options.ContentRootPath,
4244
Configuration = configuration,
4345
});
46+
#pragma warning restore IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
4447

4548
// Set WebRootPath if necessary
4649
if (options.WebRootPath is not null)

src/Hosting/Hosting/src/GenericHost/GenericWebHostBuilder.cs

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Diagnostics;
55
using System.Diagnostics.CodeAnalysis;
66
using System.Reflection;
7+
using System.Runtime.CompilerServices;
78
using System.Runtime.ExceptionServices;
89
using Microsoft.AspNetCore.Builder;
910
using Microsoft.AspNetCore.Hosting.Builder;
@@ -210,7 +211,10 @@ public IWebHostBuilder UseDefaultServiceProvider(Action<WebHostBuilderContext, S
210211
var webHostBuilderContext = GetWebHostBuilderContext(context);
211212
var options = new ServiceProviderOptions();
212213
configure(webHostBuilderContext, options);
214+
// TODO: Remove when DI no longer has RequiresDynamicCodeAttribute https://github.com/dotnet/runtime/pull/79425
215+
#pragma warning disable IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
213216
return new DefaultServiceProviderFactory(options);
217+
#pragma warning restore IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
214218
});
215219

216220
return this;
@@ -267,7 +271,6 @@ void ConfigureStartup(HostBuilderContext context, IServiceCollection services)
267271
return this;
268272
}
269273

270-
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2006:UnrecognizedReflectionPattern", Justification = "We need to call a generic method on IHostBuilder.")]
271274
private void UseStartup([DynamicallyAccessedMembers(StartupLinkerOptions.Accessibility)] Type startupType, HostBuilderContext context, IServiceCollection services, object? instance = null)
272275
{
273276
var webHostBuilderContext = GetWebHostBuilderContext(context);
@@ -302,21 +305,10 @@ private void UseStartup([DynamicallyAccessedMembers(StartupLinkerOptions.Accessi
302305
var configureContainerBuilder = StartupLoader.FindConfigureContainerDelegate(startupType, context.HostingEnvironment.EnvironmentName);
303306
if (configureContainerBuilder.MethodInfo != null)
304307
{
305-
var containerType = configureContainerBuilder.GetContainerType();
306308
// Store the builder in the property bag
307309
_builder.Properties[typeof(ConfigureContainerBuilder)] = configureContainerBuilder;
308310

309-
var actionType = typeof(Action<,>).MakeGenericType(typeof(HostBuilderContext), containerType);
310-
311-
// Get the private ConfigureContainer method on this type then close over the container type
312-
var configureCallback = typeof(GenericWebHostBuilder).GetMethod(nameof(ConfigureContainerImpl), BindingFlags.NonPublic | BindingFlags.Instance)!
313-
.MakeGenericMethod(containerType)
314-
.CreateDelegate(actionType, this);
315-
316-
// _builder.ConfigureContainer<T>(ConfigureContainer);
317-
typeof(IHostBuilder).GetMethod(nameof(IHostBuilder.ConfigureContainer))!
318-
.MakeGenericMethod(containerType)
319-
.InvokeWithoutWrappingExceptions(_builder, new object[] { configureCallback });
311+
InvokeContainer(this, configureContainerBuilder);
320312
}
321313

322314
// Resolve Configure after calling ConfigureServices and ConfigureContainer
@@ -342,6 +334,30 @@ private void UseStartup([DynamicallyAccessedMembers(StartupLinkerOptions.Accessi
342334
}
343335
};
344336
});
337+
338+
[UnconditionalSuppressMessage("AOT", "IL3050:RequiresDynamicCode",
339+
Justification = "There is a runtime check for ValueType startup container. It's unlikely anyone will use a ValueType here.")]
340+
static void InvokeContainer(GenericWebHostBuilder genericWebHostBuilder, ConfigureContainerBuilder configureContainerBuilder)
341+
{
342+
var containerType = configureContainerBuilder.GetContainerType();
343+
344+
if (containerType.IsValueType && !RuntimeFeature.IsDynamicCodeSupported)
345+
{
346+
throw new InvalidOperationException("A ValueType TContainerBuilder isn't supported with AOT.");
347+
}
348+
349+
var actionType = typeof(Action<,>).MakeGenericType(typeof(HostBuilderContext), containerType);
350+
351+
// Get the private ConfigureContainer method on this type then close over the container type
352+
var configureCallback = typeof(GenericWebHostBuilder).GetMethod(nameof(ConfigureContainerImpl), BindingFlags.NonPublic | BindingFlags.Instance)!
353+
.MakeGenericMethod(containerType)
354+
.CreateDelegate(actionType, genericWebHostBuilder);
355+
356+
// _builder.ConfigureContainer<T>(ConfigureContainer);
357+
typeof(IHostBuilder).GetMethod(nameof(IHostBuilder.ConfigureContainer))!
358+
.MakeGenericMethod(containerType)
359+
.InvokeWithoutWrappingExceptions(genericWebHostBuilder._builder, new object[] { configureCallback });
360+
}
345361
}
346362

347363
private void ConfigureContainerImpl<TContainer>(HostBuilderContext context, TContainer container) where TContainer : notnull

src/Hosting/Hosting/src/Internal/StartupLoader.cs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Globalization;
66
using System.Linq;
77
using System.Reflection;
8+
using System.Runtime.CompilerServices;
89
using Microsoft.AspNetCore.Hosting.Internal;
910
using Microsoft.Extensions.DependencyInjection;
1011

@@ -54,13 +55,26 @@ public static StartupMethods LoadMethods(IServiceProvider hostingServiceProvider
5455
var type = configureContainerMethod.MethodInfo != null ? configureContainerMethod.GetContainerType() : typeof(object);
5556

5657
var builder = (ConfigureServicesDelegateBuilder)Activator.CreateInstance(
57-
typeof(ConfigureServicesDelegateBuilder<>).MakeGenericType(type),
58+
CreateConfigureServicesDelegateBuilder(type),
5859
hostingServiceProvider,
5960
servicesMethod,
6061
configureContainerMethod,
6162
instance)!;
6263

6364
return new StartupMethods(instance, configureMethod.Build(instance), builder.Build());
65+
66+
[return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
67+
[UnconditionalSuppressMessage("AOT", "IL3050:RequiresDynamicCode",
68+
Justification = "There is a runtime check for ValueType startup container. It's unlikely anyone will use a ValueType here.")]
69+
static Type CreateConfigureServicesDelegateBuilder(Type type)
70+
{
71+
if (type.IsValueType && !RuntimeFeature.IsDynamicCodeSupported)
72+
{
73+
throw new InvalidOperationException("ValueType startup container isn't supported with AOT.");
74+
}
75+
76+
return typeof(ConfigureServicesDelegateBuilder<>).MakeGenericType(type);
77+
}
6478
}
6579

6680
private abstract class ConfigureServicesDelegateBuilder
@@ -146,7 +160,10 @@ IServiceProvider ConfigureServicesWithContainerConfiguration(IServiceCollection
146160
applicationServiceProvider = serviceProviderFactory.CreateServiceProvider(builder);
147161
}
148162

163+
// TODO: Remove when DI no longer has RequiresDynamicCodeAttribute https://github.com/dotnet/runtime/pull/79425
164+
#pragma warning disable IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
149165
return applicationServiceProvider ?? services.BuildServiceProvider();
166+
#pragma warning restore IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
150167
}
151168
}
152169

src/Hosting/Hosting/src/Internal/WebHost.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,10 @@ public void Initialize()
115115
// EnsureApplicationServices may have failed due to a missing or throwing Startup class.
116116
if (_applicationServices == null)
117117
{
118+
// TODO: Remove when DI no longer has RequiresDynamicCodeAttribute https://github.com/dotnet/runtime/pull/79425
119+
#pragma warning disable IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
118120
_applicationServices = _applicationServiceCollection.BuildServiceProvider();
121+
#pragma warning restore IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
119122
}
120123

121124
if (!_options.CaptureStartupErrors)

src/Hosting/Hosting/src/Startup/StartupBase.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,10 @@ public virtual void ConfigureServices(IServiceCollection services)
3838
/// <returns>The <see cref="IServiceProvider"/>.</returns>
3939
public virtual IServiceProvider CreateServiceProvider(IServiceCollection services)
4040
{
41+
// TODO: Remove when DI no longer has RequiresDynamicCodeAttribute https://github.com/dotnet/runtime/pull/79425
42+
#pragma warning disable IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
4143
return services.BuildServiceProvider();
44+
#pragma warning restore IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
4245
}
4346
}
4447

src/Hosting/Hosting/src/WebHostBuilder.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,10 @@ public IWebHost Build()
200200

201201
static IServiceProvider GetProviderFromFactory(IServiceCollection collection)
202202
{
203+
// TODO: Remove when DI no longer has RequiresDynamicCodeAttribute https://github.com/dotnet/runtime/pull/79425
204+
#pragma warning disable IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
203205
var provider = collection.BuildServiceProvider();
206+
#pragma warning restore IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
204207
var factory = provider.GetService<IServiceProviderFactory<IServiceCollection>>();
205208

206209
if (factory != null && factory is not DefaultServiceProviderFactory)

src/Hosting/Hosting/src/WebHostBuilderExtensions.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,10 @@ public static IWebHostBuilder UseDefaultServiceProvider(this IWebHostBuilder hos
216216
{
217217
var options = new ServiceProviderOptions();
218218
configure(context, options);
219+
// TODO: Remove when DI no longer has RequiresDynamicCodeAttribute https://github.com/dotnet/runtime/pull/79425
220+
#pragma warning disable IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
219221
services.Replace(ServiceDescriptor.Singleton<IServiceProviderFactory<IServiceCollection>>(new DefaultServiceProviderFactory(options)));
222+
#pragma warning restore IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
220223
});
221224
}
222225

src/Hosting/Hosting/test/Internal/MyContainer.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Licensed to the .NET Foundation under one or more agreements.
1+
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

44
using Microsoft.Extensions.DependencyInjection;

src/Http/Http.Abstractions/src/ProblemDetails/ProblemDetails.cs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

4+
using System.Diagnostics.CodeAnalysis;
45
using System.Text.Json.Serialization;
56
using Microsoft.AspNetCore.Http;
67

@@ -12,6 +13,8 @@ namespace Microsoft.AspNetCore.Mvc;
1213
[JsonConverter(typeof(ProblemDetailsJsonConverter))]
1314
public class ProblemDetails
1415
{
16+
private readonly IDictionary<string, object?> _extensions = new Dictionary<string, object?>(StringComparer.Ordinal);
17+
1518
/// <summary>
1619
/// A URI reference [RFC3986] that identifies the problem type. This specification encourages that, when
1720
/// dereferenced, it provide human-readable documentation for the problem type
@@ -59,5 +62,10 @@ public class ProblemDetails
5962
/// In particular, complex types or collection types may not round-trip to the original type when using the built-in JSON or XML formatters.
6063
/// </remarks>
6164
[JsonExtensionData]
62-
public IDictionary<string, object?> Extensions { get; } = new Dictionary<string, object?>(StringComparer.Ordinal);
65+
public IDictionary<string, object?> Extensions
66+
{
67+
[RequiresUnreferencedCode("JSON serialization and deserialization of ProblemDetails.Extensions might require types that cannot be statically analyzed.")]
68+
[RequiresDynamicCode("JSON serialization and deserialization of ProblemDetails.Extensions might require types that cannot be statically analyzed.")]
69+
get => _extensions;
70+
}
6371
}

src/Http/Http.Abstractions/src/Routing/RouteValueDictionary.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -818,12 +818,12 @@ public void Reset()
818818
}
819819
}
820820

821+
[RequiresUnreferencedCode("This API is not trim safe - from PropertyHelper")]
821822
internal sealed class PropertyStorage
822823
{
823824
public readonly object Value;
824825
public readonly PropertyHelper[] Properties;
825826

826-
[RequiresUnreferencedCode("This API is not trim safe.")]
827827
public PropertyStorage(object value)
828828
{
829829
Debug.Assert(value != null);

0 commit comments

Comments
 (0)