Repository navigation
Blazor linker strips away a method in a generated class even if the settings indicate not to. #2358
Description
Environment:
- Windows 10 Enterprise
- Version 10.0.19043 Build 19043
- Visual Studio 2022 Current
- .NET 6.0
Steps to reproduce the issue:
- clone the repository at https://github.com/kephas-software/kephas (master)
- open the src/Kephas.sln solution and build it.
- start the Blazor app in Tests/Kephas.AspNetCore.Blazor.InteractiveTests/Kephas.AspNetCore.Blazor.InteractiveTests.Server
- the application crashes while bootstrapping, the stack trace is visible in the browser console (see the attachment).

Due to the fact that it happens during bootstrap I cannot debug properly, but I managed to trace down to the code causing the issue:
\src\Kephas.Injection\Services\AppServicesAttribute.cs, line 131.
When the returned instance is returned to the caller, either the ToArray() extension method or the SelectMany() crashes.
Background:
- the AppServicesAttribute is used to collect services for the dependency injection through a provider class, provided in the constructor and implementing the IAppServiceInfosProvider interface.
- This attribute implements itself the IAppServiceInfosProvider interface, redirecting the interface methods to the instance created upon request.
- The provider type is annotated with
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]in the AppServicesAttribute's constructor. - The provider classes are generated by an analyzer, one per assembly. The generated class where the issue occurs is listed below (can be found, after compilation, in src/Kephas.Application/obj/.generated/Kephas.Analyzers/Kephas.Analyzers.Injection.AppServicesSourceGenerator/AppServices.g.cs
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Kephas.Services;
[assembly: AppServices(typeof(Kephas.Injection.Generated.AppServices_Kephas_Application))]
namespace Kephas.Injection.Generated
{
#if NET6_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
#endif
internal partial class AppServices_Kephas_Application: IAppServiceInfosProvider
{
IEnumerable<Type>? IAppServiceInfosProvider.GetContractDeclarationTypes(IContext? context)
{
yield return typeof(Kephas.Application.IAppMainLoop);
yield return typeof(Kephas.Application.IAppManager);
yield return typeof(Kephas.Application.IFeatureLifecycleBehavior);
yield return typeof(Kephas.Application.IFeatureManager);
}
IEnumerable<ServiceDeclaration> IAppServiceInfosProvider.GetAppServices(IContext? context)
{
yield return new ServiceDeclaration(typeof(Kephas.Application.CommandsAppSetupHandler), typeof(Kephas.Application.IAppSetupHandler));
yield return new ServiceDeclaration(typeof(Kephas.Application.DefaultAppMainLoop), typeof(Kephas.Application.IAppMainLoop));
yield return new ServiceDeclaration(typeof(Kephas.Application.DefaultAppManager), typeof(Kephas.Application.IAppManager));
yield return new ServiceDeclaration(typeof(Kephas.Application.FeatureEnabledServiceBehavior), typeof(Kephas.Services.Behaviors.IEnabledServiceBehaviorRule<, >));
yield return new ServiceDeclaration(typeof(Kephas.Application.Interaction.InteractionFeatureLifecycleBehavior), typeof(Kephas.Application.IFeatureLifecycleBehavior));
yield return new ServiceDeclaration(typeof(Kephas.Application.MainLoopAppLifecycleBehavior), typeof(Kephas.Application.IAppLifecycleBehavior));
yield return new ServiceDeclaration(typeof(Kephas.Application.SetupAppLifecycleBehavior), typeof(Kephas.Application.IAppLifecycleBehavior));
yield return new ServiceDeclaration(typeof(Kephas.Application.StartupAppLifecycleBehavior), typeof(Kephas.Application.IAppLifecycleBehavior));
}
}
}From intermediary steps, which I cannot reproduce anymore, I am quite certain that the method IAppServiceInfosProvider.GetAppServices is called for AppServices_Kephas_Application. However, presumably, the object returned is missing some methods leading to the error in class-setup-vtable.c. I tried to indicate at all steps that the assemblies should not be trimmed, due to heavy use of reflection, but to no avail.
Activity
marek-safar commentedon Nov 10, 2021
@vitek-karas @sbomer could this be investigated?
vitek-karas commentedon Nov 11, 2021
Thanks for reporting the issue.
Unfortunately I can't repro it because trying to build it fails. I don't have access to Telerik's feeds.
There's a good intro page on trimming in Blazor here: https://docs.microsoft.com/en-us/aspnet/core/blazor/host-and-deploy/configure-trimmer?view=aspnetcore-6.0.
I would suggest you start by enabling trim analysis warnings:
This should produce warnings pointing to potentially problematic code in your app. If the problematic code is from a NuGet dependency, it will just generate a single warning that the dll has issues. You can "look inside" by setting
TrimmerSingleWarn=false, then it will show detailed warnings even from NuGets and such.More details on how to configure the trimmer are here: https://docs.microsoft.com/en-us/dotnet/core/deploying/trimming/trimming-options
I noticed that you added illink descriptors (LinkerConfig.xml) into your project. Please look at the format description for details. For the file to be used, the embedded resource should be called
ILLink.Descriptors.xml(in your case it's called<ProjectName>.xml).ioancrisan commentedon Nov 11, 2021
Thanks for the feedback. I took the LinkerConfig.xml configuration from the MS docs, I don't remember exactly now where from. Anyway, I changed the projects' settings according to your suggestions and the error still persists. To avoid Telerik feed related issues I removed it from the nuget.config. Please also consider the stripped version of the initial solution, KephasBlazorInteractiveTests.sln.
Anyway, all assemblies are decorated with [assembly: AssemblyMetadata("IsTrimmable", "False")]. I suppose this should suffice. Am I wrong?
vitek-karas commentedon Nov 11, 2021
Thanks - I can try to build the project now.
The actual failure
Blazor doesn't trim when just building the app - so if I follow your repro steps, it never actually runs the illink. So I highly doubt that this problem has anything to do with trimming. I can repro the failure though - so there's definitely something wrong. But this honestly feels like an issue with the mono/wasm runtime - it fails on an assert:
@lewing - I assume you would like a bug in the dotnet/runtime repo for this, right?
IsTrimmable=false
The
IsTrimmableattribute can only be set to "true". The default is false. This means that all assemblies except those which have IsTrimmable=true will not be trimmed at all (action "copy" which means leave the file alone).I tried to publish the Client project which will actually run the illink and checked the command line, as far as I can tell it would not trim any of the app's code at all - only the core framework assemblies would be trimmed.
Actual illink bug
Trying to publish the Client test project uncovers a bug in the illink though. The linker crashes with:
I'll look into this later today and probably create a separate issue for that.
ioancrisan commentedon Nov 11, 2021
The interface I try to implement has default method implementations. Could this trigger the issue?
vitek-karas commentedon Nov 11, 2021
It could be - but it's hard to guess without looking into this in more detail.
The linker issue is a bit tricky - still trying to come with a clean repro. But the root cause is a problem with
NullableAttribute. It's marked for removal from CoreLib, but then it's declared explicitly in one of the "copy" assemblies. This leads the trimmer to raise warning 2045 (attribute marked for removal, but also kept), but without a "source location". The lack of source location leads to the exception from the warning system, as it doesn't know what location/origin to give the warning.That said, the simple cases to repro this all work just fine, so I'm trying to figure out what exactly is different about this case.
ioancrisan commentedon Nov 14, 2021
Could it be that the source it should refer is in the generated file? That would explain why the location is empty.
vitek-karas commentedon Nov 14, 2021
Not sure I understand what you mean by generated file, but the warning actually comes from the descriptor XML.
The fix is pretty simple, but I'm having a hard time distilling it into a simpler repro which we can add as a test (while I absolutely appreciate you providing a repro, it's not exactly what we can add into the test suite 😉 ).
The bug is that
ProcessMarkedPendingsets up annullscope (for location) and callsMarkType. If the stars align just right, this will mean that theMarkTypewill try to generate a warning with anulllocation and cause the crash.The "mark" comes from a descriptor XML (in your repro it's the descriptor in the "client" test project - which roots the entire Client assembly (among other assemblies). So technically the source of the warning should be the descriptor XML, but currently we don't really have a way to do this (would require a larger change). I think it would be OK if the warning was generated with the type itself as a location for now (and make the bigger change to correctly blame the XML in the 7.0 release).
ioancrisan commentedon Nov 15, 2021
The error is triggered, if I can estimate correctly, for the Kephas_Application_AppServices class from the Kephas.Application project, which is generated at build time by the AppServicesSourceGenerator in the referenced Kephas.Analyzers project. This is what I mean with the "generated file".
Later edit: while reading again your comments, I see that this error has nothing to to with the build, instead with the publish. Source generators are used during build. However, what made me think that they were involved is that a class implementing the same interface was successfully called (ServiceCollectionAppServiceInfosProvider), while the generated class caused the crash. Maybe, if you check both of them, can figure out what the differences are.
Add a test for dotnet#2358
vitek-karas commentedon Nov 15, 2021
Sorry - I'm confusing two things here.
There are two issues:
vitek-karas commentedon Nov 15, 2021
The root cause of the failure in the linker (repro in #2369):
ToBeRemovedAttributeand in a linkattribute.xml marks it for removal.IL2045(attribute to be removed being used), but because of where the marking of the attribute comes from linker crashes when trying to report the warning.vitek-karas commentedon Nov 15, 2021
We should consider this for 6.0.xxx fix.
It's actually not that hard to make this happen in a Blazor app. Just add a custom library to the app, which has a descriptor which roots for example
System.Linq.Expressionsassembly as a whole.System.Linq.Expressionsdefines its own copy ofNullableAttribute, which is marked for removal by linkattributes.xml in CoreLib. In the app, reference something fromSystem.Linq.Expressionswhich uses the attribute (almost any method with nullable annotation will do this). Later on reference the custom library -> illink will crash.Add a test for #2358 (#2369)
ioancrisan commentedon Nov 18, 2021
Until this is fixed, is there any workaround I could use? That would be extremely helpful.
vitek-karas commentedon Nov 19, 2021
Well - one really dirty hack I found might be:
In the
Kephas.Abstraction/LinkerConfig.xml(the only descriptor which keeps system assemblies):Either remove all of the
System.*assemblies - but then things will probably break (I assume you added these for a reason).Or modify them to look like this:
This will include all types from the assembly except any nested types. It's not ideal, it could break the app still, but it's probably much better. If you find that you need some specific nested type, you can list it with another
typeelement, just make sure it's not a type forward (the type should be actually defined in the assembly).I didn't try if the app works, but it does publish without errors with this change.
ioancrisan commentedon Nov 22, 2021
Thank you for the tip, but unfortunately the app does not work :(.
vitek-karas commentedon Nov 25, 2021
Fix for .NET 7 is prepared in #2396.
We will discuss fix for .NET 6. #2396 is a rather large change with relatively high risk of introducing slightly different behavior in certain cases. .NET 6 fix could simply take the change in https://github.com/dotnet/linker/pull/2396/files#diff-def1ef03e82e365340df66675a5e03b938b6e72f487f05df130a77d1c297750aL162-L170. On its own this should fix the problem, it will just cause some warnings to be produced without an origin/location.
ioancrisan commentedon Nov 25, 2021
Thanks for the information! Waiting to see the fix in 6.0.1. BTW, it's just the tooling around .NET 6, or the runtime itself? I was wondering if I can disable the stripping completely for now, and let this optimization act only with the next release.
ioancrisan commentedon Nov 25, 2021
Additionally, is there any chance with these fixes that the mono runtime does not fail? Or this is another issue?
vitek-karas commentedon Nov 25, 2021
The mono runtime failure is a separate issue - that happens even if this tool doesn't run.
You can disable trimming - you should be able to set
PublishTrimmed=falsein your project file and that should do it. But that will very likely do nothing about the runtime failure.vitek-karas commentedon Nov 25, 2021
I already did that some time ago: dotnet/runtime#61603
vitek-karas commentedon Dec 1, 2021
The PR #2396 is now merged and so this is fixed in linker/main (.NET 7).
The fix is relatively large, there's is a much simpler way to fix this (which is not perfect, but probably acceptable for .NET 6).
We should consider the #2396 for 6.0, and if that doesn't work, we can do the simpler fix.
Add a test for dotnet/linker#2358 (dotnet/linker#2369)