Skip to content
This repository was archived by the owner on Sep 25, 2026. It is now read-only.
This repository was archived by the owner on Sep 25, 2026. It is now read-only.

Blazor linker strips away a method in a generated class even if the settings indicate not to. #2358

Open

Description

@ioancrisan

Environment:

  • Windows 10 Enterprise
  • Version 10.0.19043 Build 19043
  • Visual Studio 2022 Current
  • .NET 6.0

Steps to reproduce the issue:

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

  1. marek-safar commented on Nov 10, 2021

    @marek-safar
    Contributor

    @vitek-karas @sbomer could this be investigated?

  2. vitek-karas commented on Nov 11, 2021

    @vitek-karas
    Member

    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:

    <SuppressTrimAnalysisWarnings>false</SuppressTrimAnalysisWarnings>

    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).

  3. ioancrisan commented on Nov 11, 2021

    @ioancrisan
    Author

    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?

  4. vitek-karas commented on Nov 11, 2021

    @vitek-karas
    Member

    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:

    Assertion at /__w/1/s/src/mono/mono/metadata/class-setup-vtable.c:1747, condition `<disabled>' not met
    

    @lewing - I assume you would like a bug in the dotnet/runtime repo for this, right?

    IsTrimmable=false

    The IsTrimmable attribute 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:

      Fatal error in IL Linker
      Unhandled exception. System.NotSupportedException: Specified method is not supported.
         at Mono.Linker.MessageContainer.TryLogSingleWarning(LinkContext context, Int32 code, MessageOrigin origin, String subcategory)
         at Mono.Linker.MessageContainer.CreateWarningMessageContainer(LinkContext context, String text, Int32 code, MessageOrigin origin, WarnVersion version, String subcategory)
         at Mono.Linker.Steps.MarkStep.MarkType(TypeReference reference, DependencyInfo reason, Nullable`1 origin)
         at Mono.Linker.Steps.MarkStep.ProcessMarkedPending()
         at Mono.Linker.Steps.MarkStep.Process()
         at Mono.Linker.Steps.MarkStep.Process(LinkContext context)
         at Mono.Linker.Pipeline.ProcessStep(LinkContext context, IStep step)
         at Mono.Linker.Pipeline.Process(LinkContext context)
         at Mono.Linker.Driver.Run(ILogger customLogger)
         at Mono.Linker.Driver.Main(String[] args)

    I'll look into this later today and probably create a separate issue for that.

  5. ioancrisan commented on Nov 11, 2021

    @ioancrisan
    Author

    The interface I try to implement has default method implementations. Could this trigger the issue?

  6. vitek-karas commented on Nov 11, 2021

    @vitek-karas
    Member

    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.

  7. ioancrisan commented on Nov 14, 2021

    @ioancrisan
    Author

    Could it be that the source it should refer is in the generated file? That would explain why the location is empty.

  8. vitek-karas commented on Nov 14, 2021

    @vitek-karas
    Member

    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 ProcessMarkedPending sets up an null scope (for location) and calls MarkType. If the stars align just right, this will mean that the MarkType will try to generate a warning with a null location 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).

  9. ioancrisan commented on Nov 15, 2021

    @ioancrisan
    Author

    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.

  10. added a commit that references this issue on Nov 15, 2021
  11. vitek-karas commented on Nov 15, 2021

    @vitek-karas
    Member

    Sorry - I'm confusing two things here.

    There are two issues:

  12. vitek-karas commented on Nov 15, 2021

    @vitek-karas
    Member

    The root cause of the failure in the linker (repro in #2369):

    • Assembly A defines an attribute ToBeRemovedAttribute and in a linkattribute.xml marks it for removal.
    • Assembly A uses this attribute in its code.
    • Assembly A also references assembly B
    • Assembly B as an embedded descriptor XML which marks entire assembly A
    • This causes the attribute to be marked, which causes a warning 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.
  13. added this to the .NET 6.0 milestone on Nov 15, 2021
  14. vitek-karas commented on Nov 15, 2021

    @vitek-karas
    Member

    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.Expressions assembly as a whole. System.Linq.Expressions defines its own copy of NullableAttribute, which is marked for removal by linkattributes.xml in CoreLib. In the app, reference something from System.Linq.Expressions which uses the attribute (almost any method with nullable annotation will do this). Later on reference the custom library -> illink will crash.

  15. added a commit that references this issue on Nov 15, 2021
  16. ioancrisan commented on Nov 18, 2021

    @ioancrisan
    Author

    Until this is fixed, is there any workaround I could use? That would be extremely helpful.

  17. vitek-karas commented on Nov 19, 2021

    @vitek-karas
    Member

    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:

        <assembly fullname="System.Linq">
          <type fullname="^(?!.*/).*"/>
        </assembly>

    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 type element, 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.

  18. ioancrisan commented on Nov 22, 2021

    @ioancrisan
    Author

    Thank you for the tip, but unfortunately the app does not work :(.

  19. vitek-karas commented on Nov 25, 2021

    @vitek-karas
    Member

    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.

  20. ioancrisan commented on Nov 25, 2021

    @ioancrisan
    Author

    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.

  21. ioancrisan commented on Nov 25, 2021

    @ioancrisan
    Author

    Additionally, is there any chance with these fixes that the mono runtime does not fail? Or this is another issue?

  22. vitek-karas commented on Nov 25, 2021

    @vitek-karas
    Member

    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=false in your project file and that should do it. But that will very likely do nothing about the runtime failure.

  23. vitek-karas commented on Nov 25, 2021

    @vitek-karas
    Member

    I already did that some time ago: dotnet/runtime#61603

  24. vitek-karas commented on Dec 1, 2021

    @vitek-karas
    Member

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions