Skip to content

[AOT] Fix runtime warnings #45604

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 45 commits into from
Jan 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
a4fdc61
Enable AOT warnings
amcasey Dec 12, 2022
4ccee5b
Suppress AOT warning
amcasey Dec 12, 2022
f0b1c81
Simplify annotations on PropertyHelper
amcasey Dec 12, 2022
68229ac
Annotate ProblemDetailJsonConverters
amcasey Dec 12, 2022
61879ea
Fix whitespace
amcasey Dec 12, 2022
cb77b1b
Annotate RouteValueDictionary
amcasey Dec 12, 2022
de06e39
Guess suppression for WebApplicationBuilder
amcasey Dec 12, 2022
54c7263
Annotate ManagedAuthenticatedEncryptorFactory
amcasey Dec 12, 2022
4451703
Address some RouteValueDictionary fallout
amcasey Dec 12, 2022
1965ede
Annotate ILEmitTrie*
amcasey Dec 13, 2022
c02a56b
Annotate RequestDelegateFactory
amcasey Dec 13, 2022
462eb2a
Annotate Http*JsonExtensions
amcasey Dec 13, 2022
541b6b9
Annotate ParameterBindingMethodCache and EndpointMetadataPopulator
amcasey Dec 13, 2022
29fcad9
Annotate FSharpAsync codepath
amcasey Dec 13, 2022
88a9dd5
Annotate RouteEndpointDataSource
amcasey Dec 13, 2022
90f8c6a
DefaultServiceProvider fallout
amcasey Dec 13, 2022
790bc44
Update AOT suppressions
JamesNK Dec 15, 2022
f8b05e8
Clean up
JamesNK Dec 15, 2022
124b150
Update
JamesNK Dec 15, 2022
2eb8f4b
Update
JamesNK Dec 15, 2022
70afebf
PR feedback
JamesNK Dec 16, 2022
b6bf700
Clean up
JamesNK Dec 16, 2022
6ac2199
Apply suggestions from code review
JamesNK Dec 16, 2022
d2b0838
PR feedback
JamesNK Dec 16, 2022
9dbcc98
PR feedback
JamesNK Dec 16, 2022
4f9f679
PR feedback
JamesNK Dec 16, 2022
361b03e
PR feedback
JamesNK Dec 16, 2022
a782198
PR feedback
JamesNK Dec 16, 2022
f2846a8
PR feedback
JamesNK Dec 16, 2022
946ac3c
PR feedback
JamesNK Dec 16, 2022
7a8a57e
PR feedback
JamesNK Dec 16, 2022
f99a847
Clean up
JamesNK Dec 16, 2022
bca72d2
PR feedback
JamesNK Dec 17, 2022
baf2fb5
PR feedback
JamesNK Dec 17, 2022
6722fbb
PR feedback
JamesNK Dec 17, 2022
20dd7af
Update src/Hosting/Hosting/src/GenericHost/GenericWebHostBuilder.cs
JamesNK Dec 20, 2022
7b9537f
Update src/Hosting/Hosting/src/Internal/StartupLoader.cs
JamesNK Dec 20, 2022
4e48ef7
[AOT] Fixing the problems with ProblemDetails (#45646)
JamesNK Dec 20, 2022
e4c98a8
PR feedback
JamesNK Dec 20, 2022
3b27d80
PR feedback
JamesNK Dec 21, 2022
dcd762e
Fix
JamesNK Dec 21, 2022
c755e78
Update src/Http/Http.Extensions/src/DefaultProblemDetailsWriter.cs
JamesNK Jan 4, 2023
f6ff8fe
PR feedback
JamesNK Jan 4, 2023
51ca4ec
PR feedback
JamesNK Jan 4, 2023
09e0fdf
PR feedback
JamesNK Jan 4, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions Directory.Build.targets
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
<!-- Only build Microsoft.AspNetCore.App, Microsoft.AspNetCore.App.Ref, ref/ assemblies, and ProjectTemplates in source build. -->
<!-- Analyzer package are needed in source build for WebSDK -->
<ExcludeFromSourceBuild
Condition="'$(ExcludeFromSourceBuild)' == '' and
'$(DotNetBuildFromSource)' == 'true' and
'$(IsAspNetCoreApp)' != 'true' and
'$(MSBuildProjectName)' != '$(TargetingPackName)' and
'$(IsAnalyzersProject)' != 'true' and
Condition="'$(ExcludeFromSourceBuild)' == '' and
'$(DotNetBuildFromSource)' == 'true' and
'$(IsAspNetCoreApp)' != 'true' and
'$(MSBuildProjectName)' != '$(TargetingPackName)' and
'$(IsAnalyzersProject)' != 'true' and
'$(IsProjectTemplateProject)' != 'true'">true</ExcludeFromSourceBuild>

<EnableAOTAnalyzer Condition=" '$(EnableAOTAnalyzer)' == '' ">$([MSBuild]::ValueOrDefault($(IsTrimmable),'false'))</EnableAOTAnalyzer>

<!-- If the user has specified that they want to skip building any test related projects with SkipTestBuild,
suppress all targets for TestProjects using ExcludeFromBuild. -->
<ExcludeFromBuild Condition="'$(IsPackable)' != 'true' and
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<Nullable>enable</Nullable>
<IsTrimmable>true</IsTrimmable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<EnableAOTAnalyzer>false</EnableAOTAnalyzer>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<RootNamespace>Microsoft.AspNetCore.Components</RootNamespace>
<Nullable>enable</Nullable>
<IsTrimmable>true</IsTrimmable>
<EnableAOTAnalyzer>false</EnableAOTAnalyzer>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<IsShippingPackage>true</IsShippingPackage>
<Nullable>enable</Nullable>
<IsTrimmable>true</IsTrimmable>
<EnableAOTAnalyzer>false</EnableAOTAnalyzer>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<IsTrimmable>true</IsTrimmable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<EnableAOTAnalyzer>false</EnableAOTAnalyzer>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<Nullable>enable</Nullable>
<IsTrimmable>true</IsTrimmable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<EnableAOTAnalyzer>false</EnableAOTAnalyzer>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ private Func<KeyedHashAlgorithm> GetKeyedHashAlgorithmFactory(ManagedAuthenticat
throw Error.Common_PropertyCannotBeNullOrEmpty(nameof(configuration.ValidationAlgorithmType));
}

typeof(KeyedHashAlgorithm).AssertIsAssignableFrom(configuration.ValidationAlgorithmType);
_logger.UsingManagedKeyedHashAlgorithm(configuration.ValidationAlgorithmType.FullName!);
if (configuration.ValidationAlgorithmType == typeof(HMACSHA256))
{
Expand Down Expand Up @@ -111,7 +112,8 @@ private static class AlgorithmActivator
/// <summary>
/// Creates a factory that wraps a call to <see cref="Activator.CreateInstance{T}"/>.
/// </summary>
public static Func<T> CreateFactory<T>([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type implementation)
[UnconditionalSuppressMessage("AOT", "IL3050", Justification = "MakeGenericType is safe to use because implementation is either a KeyedHashAlgorithm or SymmetricAlgorithm type.")]
public static Func<T> CreateFactory<T>([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type implementation) where T : class
{
return ((IActivator<T>)Activator.CreateInstance(typeof(AlgorithmActivatorCore<>).MakeGenericType(implementation))!).Creator;
}
Expand Down
3 changes: 3 additions & 0 deletions src/DataProtection/Extensions/src/DataProtectionProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,9 @@ internal static IDataProtectionProvider CreateProvider(
setupAction(builder);

// extract the provider instance from the service collection
// TODO: Remove when DI no longer has RequiresDynamicCodeAttribute https://github.com/dotnet/runtime/pull/79425
#pragma warning disable IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
return serviceCollection.BuildServiceProvider().GetRequiredService<IDataProtectionProvider>();
#pragma warning restore IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
}
}
3 changes: 3 additions & 0 deletions src/DefaultBuilder/src/WebApplicationBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ internal WebApplicationBuilder(WebApplicationOptions options, Action<IHostBuilde

configuration.AddEnvironmentVariables(prefix: "ASPNETCORE_");

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

// Set WebRootPath if necessary
if (options.WebRootPath is not null)
Expand Down
42 changes: 29 additions & 13 deletions src/Hosting/Hosting/src/GenericHost/GenericWebHostBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Builder;
Expand Down Expand Up @@ -210,7 +211,10 @@ public IWebHostBuilder UseDefaultServiceProvider(Action<WebHostBuilderContext, S
var webHostBuilderContext = GetWebHostBuilderContext(context);
var options = new ServiceProviderOptions();
configure(webHostBuilderContext, options);
// TODO: Remove when DI no longer has RequiresDynamicCodeAttribute https://github.com/dotnet/runtime/pull/79425
#pragma warning disable IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
return new DefaultServiceProviderFactory(options);
#pragma warning restore IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
});

return this;
Expand Down Expand Up @@ -267,7 +271,6 @@ void ConfigureStartup(HostBuilderContext context, IServiceCollection services)
return this;
}

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

var actionType = typeof(Action<,>).MakeGenericType(typeof(HostBuilderContext), containerType);

// Get the private ConfigureContainer method on this type then close over the container type
var configureCallback = typeof(GenericWebHostBuilder).GetMethod(nameof(ConfigureContainerImpl), BindingFlags.NonPublic | BindingFlags.Instance)!
.MakeGenericMethod(containerType)
.CreateDelegate(actionType, this);

// _builder.ConfigureContainer<T>(ConfigureContainer);
typeof(IHostBuilder).GetMethod(nameof(IHostBuilder.ConfigureContainer))!
.MakeGenericMethod(containerType)
.InvokeWithoutWrappingExceptions(_builder, new object[] { configureCallback });
InvokeContainer(this, configureContainerBuilder);
}

// Resolve Configure after calling ConfigureServices and ConfigureContainer
Expand All @@ -342,6 +334,30 @@ private void UseStartup([DynamicallyAccessedMembers(StartupLinkerOptions.Accessi
}
};
});

[UnconditionalSuppressMessage("AOT", "IL3050:RequiresDynamicCode",
Justification = "There is a runtime check for ValueType startup container. It's unlikely anyone will use a ValueType here.")]
static void InvokeContainer(GenericWebHostBuilder genericWebHostBuilder, ConfigureContainerBuilder configureContainerBuilder)
{
var containerType = configureContainerBuilder.GetContainerType();

if (containerType.IsValueType && !RuntimeFeature.IsDynamicCodeSupported)
{
throw new InvalidOperationException("A ValueType TContainerBuilder isn't supported with AOT.");
}

var actionType = typeof(Action<,>).MakeGenericType(typeof(HostBuilderContext), containerType);

// Get the private ConfigureContainer method on this type then close over the container type
var configureCallback = typeof(GenericWebHostBuilder).GetMethod(nameof(ConfigureContainerImpl), BindingFlags.NonPublic | BindingFlags.Instance)!
.MakeGenericMethod(containerType)
.CreateDelegate(actionType, genericWebHostBuilder);

// _builder.ConfigureContainer<T>(ConfigureContainer);
typeof(IHostBuilder).GetMethod(nameof(IHostBuilder.ConfigureContainer))!
.MakeGenericMethod(containerType)
.InvokeWithoutWrappingExceptions(genericWebHostBuilder._builder, new object[] { configureCallback });
}
}

private void ConfigureContainerImpl<TContainer>(HostBuilderContext context, TContainer container) where TContainer : notnull
Expand Down
19 changes: 18 additions & 1 deletion src/Hosting/Hosting/src/Internal/StartupLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.Extensions.DependencyInjection;

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

var builder = (ConfigureServicesDelegateBuilder)Activator.CreateInstance(
typeof(ConfigureServicesDelegateBuilder<>).MakeGenericType(type),
CreateConfigureServicesDelegateBuilder(type),
hostingServiceProvider,
servicesMethod,
configureContainerMethod,
instance)!;

return new StartupMethods(instance, configureMethod.Build(instance), builder.Build());

[return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
[UnconditionalSuppressMessage("AOT", "IL3050:RequiresDynamicCode",
Justification = "There is a runtime check for ValueType startup container. It's unlikely anyone will use a ValueType here.")]
static Type CreateConfigureServicesDelegateBuilder(Type type)
{
if (type.IsValueType && !RuntimeFeature.IsDynamicCodeSupported)
{
throw new InvalidOperationException("ValueType startup container isn't supported with AOT.");
}

return typeof(ConfigureServicesDelegateBuilder<>).MakeGenericType(type);
}
}

private abstract class ConfigureServicesDelegateBuilder
Expand Down Expand Up @@ -146,7 +160,10 @@ IServiceProvider ConfigureServicesWithContainerConfiguration(IServiceCollection
applicationServiceProvider = serviceProviderFactory.CreateServiceProvider(builder);
}

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

Expand Down
3 changes: 3 additions & 0 deletions src/Hosting/Hosting/src/Internal/WebHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,10 @@ public void Initialize()
// EnsureApplicationServices may have failed due to a missing or throwing Startup class.
if (_applicationServices == null)
{
// TODO: Remove when DI no longer has RequiresDynamicCodeAttribute https://github.com/dotnet/runtime/pull/79425
#pragma warning disable IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
_applicationServices = _applicationServiceCollection.BuildServiceProvider();
#pragma warning restore IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
}

if (!_options.CaptureStartupErrors)
Expand Down
3 changes: 3 additions & 0 deletions src/Hosting/Hosting/src/Startup/StartupBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@ public virtual void ConfigureServices(IServiceCollection services)
/// <returns>The <see cref="IServiceProvider"/>.</returns>
public virtual IServiceProvider CreateServiceProvider(IServiceCollection services)
{
// TODO: Remove when DI no longer has RequiresDynamicCodeAttribute https://github.com/dotnet/runtime/pull/79425
#pragma warning disable IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
return services.BuildServiceProvider();
#pragma warning restore IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
}
}

Expand Down
3 changes: 3 additions & 0 deletions src/Hosting/Hosting/src/WebHostBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,10 @@ public IWebHost Build()

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

if (factory != null && factory is not DefaultServiceProviderFactory)
Expand Down
3 changes: 3 additions & 0 deletions src/Hosting/Hosting/src/WebHostBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,10 @@ public static IWebHostBuilder UseDefaultServiceProvider(this IWebHostBuilder hos
{
var options = new ServiceProviderOptions();
configure(context, options);
// TODO: Remove when DI no longer has RequiresDynamicCodeAttribute https://github.com/dotnet/runtime/pull/79425
#pragma warning disable IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
services.Replace(ServiceDescriptor.Singleton<IServiceProviderFactory<IServiceCollection>>(new DefaultServiceProviderFactory(options)));
#pragma warning restore IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
});
}

Expand Down
2 changes: 1 addition & 1 deletion src/Hosting/Hosting/test/Internal/MyContainer.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.Extensions.DependencyInjection;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics.CodeAnalysis;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Http;

Expand All @@ -12,6 +13,8 @@ namespace Microsoft.AspNetCore.Mvc;
[JsonConverter(typeof(ProblemDetailsJsonConverter))]
public class ProblemDetails
{
private readonly IDictionary<string, object?> _extensions = new Dictionary<string, object?>(StringComparer.Ordinal);

/// <summary>
/// A URI reference [RFC3986] that identifies the problem type. This specification encourages that, when
/// dereferenced, it provide human-readable documentation for the problem type
Expand Down Expand Up @@ -59,5 +62,10 @@ public class ProblemDetails
/// In particular, complex types or collection types may not round-trip to the original type when using the built-in JSON or XML formatters.
/// </remarks>
[JsonExtensionData]
public IDictionary<string, object?> Extensions { get; } = new Dictionary<string, object?>(StringComparer.Ordinal);
public IDictionary<string, object?> Extensions
{
[RequiresUnreferencedCode("JSON serialization and deserialization of ProblemDetails.Extensions might require types that cannot be statically analyzed.")]
[RequiresDynamicCode("JSON serialization and deserialization of ProblemDetails.Extensions might require types that cannot be statically analyzed.")]
get => _extensions;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -818,12 +818,12 @@ public void Reset()
}
}

[RequiresUnreferencedCode("This API is not trim safe - from PropertyHelper")]
internal sealed class PropertyStorage
{
public readonly object Value;
public readonly PropertyHelper[] Properties;

[RequiresUnreferencedCode("This API is not trim safe.")]
public PropertyStorage(object value)
{
Debug.Assert(value != null);
Expand Down
Loading