Skip to content

Commit 041e3b8

Browse files
sbomereerhardtIEvangelist
committed
Document new linker options and trimming libraries (dotnet#23766)
* Document new linker options and trimming libraries * Fix TOC * Document EnableTrimAnalyzer And fix typos, links * PR feedback - Move sample up - Call out TrimMode link default - Clarify app vs library - Publish Release * Change title to "Preparing libraries for trimming" * PR feedback - Fix typo - Avoid referencing sections with "above/below" * PR feedback Add code snippet for examples after annotation * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: Eric Erhardt <[email protected]> * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: Eric Erhardt <[email protected]> * Update docs/core/deploying/trimming-options.md Co-authored-by: Eric Erhardt <[email protected]> * PR feedback - Fix links - Clarify which assemblies are trimmed by default - Clarify which assemblies are affected by per-assembly metadata * PR feedback - Change example to call reflection directly - Avoid mentioning .NET 5 - Point out benefits of Roslyn analyzer - Avoid Foo/Bar - Recommend not annotating virtuals * Add advanced section Which mentions UnconditionalSuppressMessage * Remove whitespace * PR feedback - Clarify why we need an exe - Improve comments in sample csproj * More comments * PR feedback Simplify wording * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/trimming-options.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/preparing-libraries-for-trimming.md Co-authored-by: David Pine <[email protected]> * Update docs/core/deploying/trimming-options.md Co-authored-by: David Pine <[email protected]> * Add intro and fix links * Rename file to match title * Update trimming-options.md * Apply suggestions from code review * PR feedback - Don't require un-suppressing warnings, as this is now implied by TrimmerDefaultAction=link: dotnet/sdk#16865 - Clarify why publishing an app is necessary for library warnings Co-authored-by: Eric Erhardt <[email protected]> Co-authored-by: David Pine <[email protected]>
1 parent f2400b0 commit 041e3b8

File tree

3 files changed

+299
-7
lines changed

3 files changed

+299
-7
lines changed
Lines changed: 246 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,246 @@
1+
---
2+
title: Prepare .NET libraries for trimming
3+
description: Learn how to prepare .NET libraries for trimming.
4+
author: sbomer
5+
ms.author: svbomer
6+
ms.date: 04/16/2021
7+
---
8+
9+
# Prepare .NET libraries for trimming
10+
11+
The .NET SDK makes it possible to reduce the size of self-contained apps by [trimming](trim-self-contained.md), removing unused code from the app and its dependencies. Not all code is compatible with trimming, so .NET 6 provides trim analysis [warnings](trimming-options.md#analysis-warnings) to detect patterns that may break trimmed apps. This document describes how to prepare libraries for trimming with the aid of these warnings, including recommendations for fixing some common cases.
12+
13+
## Trim warnings in apps
14+
15+
In .NET 6+, when publishing an app, the `PublishTrimmed` project file element will produce trim analysis warnings for patterns that are not statically understood to be compatible with trimming, including patterns in your code and in dependencies.
16+
17+
You will encounter detailed warnings originating from your own code and `ProjectReference` dependencies. You may also see warnings like `warning IL2104: Assembly 'SomeAssembly' produced trim warnings` for `PackageReference` libraries. This warning means that the library contained patterns which are not guaranteed to work in the context of the trimmed app, and may result in a broken app. Consider contacting the author to see if the library can be annotated for trimming.
18+
19+
To resolve warnings originating from the app code, see [resolving trim warnings](#resolve-trim-warnings). If you are interested in making your own `ProjectReference` libraries trim friendly, follow the instructions to [enable library trim warnings](#enable-library-trim-warnings).
20+
21+
If your app only uses parts of a library that are compatible with trimming, consider [enabling trimming](trimming-options.md#trim-additional-assemblies) of this library if it is not already being trimmed. This will only produce warnings if your app uses problematic parts of the library. (You can also [show detailed warnings](trimming-options.md#show-detailed-warnings) for the library to see which parts of it are problematic.)
22+
23+
## Enable library trim warnings
24+
25+
These instructions show how to enable and resolve static analysis warnings to prepare a library for trimming. Follow these steps if you are authoring a library and either want to proactively make your library trimmable, or have been contacted by app authors who encountered trim warnings from your library.
26+
27+
Ensure you are using the .NET 6 SDK for these steps. They will not work correctly in previous versions.
28+
29+
## Enable Roslyn analyzer
30+
31+
Set `<EnableTrimAnalyzer>true</EnableTrimAnalyzer>` (in .NET 6+) in your library project. This will not have any effect on the output, but it will enable trim analysis during build via a Roslyn analyzer.
32+
33+
The Roslyn analyzer is useful for a fast feedback cycle with IDE integration, but is currently incomplete. It doesn't cover all trim analysis warnings, but the set of patterns it understands will improve over time to give more complete coverage. The Roslyn analyzer also isn't able to analyze the implementations of reference assemblies that you depend on. It is important to follow the next steps to ensure that your library is fully compatible with trimming.
34+
35+
### Show all warnings
36+
37+
To show all analysis warnings for your library, including warnings about dependencies, create a separate app project like the following that references your library, and publish it with `PublishTrimmed`.
38+
39+
The extra step of creating an app project just to get complete warnings for a library is necessary because the implementations of dependencies are not generally available during `dotnet build`, and reference assemblies don't contain enough information to determine whether they are compatible with trimming. Publishing a self-contained app ensures that the library is analyzed in a context where its dependencies are available, so that you are alerted if your library uses any code from dependencies that could break a trimmed app.
40+
41+
```xml
42+
<Project Sdk="Microsoft.NET.Sdk">
43+
44+
<PropertyGroup>
45+
<OutputType>Exe</OutputType>
46+
<TargetFramework>net6.0</TargetFramework>
47+
<!-- Use a RID of your choice. -->
48+
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
49+
<PublishTrimmed>true</PublishTrimmed>
50+
<!-- Prevent warnings from unused code in dependencies -->
51+
<TrimmerDefaultAction>link</TrimmerDefaultAction>
52+
</PropertyGroup>
53+
54+
<ItemGroup>
55+
<ProjectReference Include="path/to/MyLibrary.csproj" />
56+
<!-- Analyze the whole library, even if attributed with "IsTrimmable" -->
57+
<TrimmerRootAssembly Include="MyLibrary" />
58+
</ItemGroup>
59+
60+
</Project>
61+
```
62+
63+
```dotnetcli
64+
dotnet publish -c Release
65+
```
66+
67+
- `TrimmerRootAssembly` ensures that every part of the library is analyzed. This is necessary in case the library has `[AssemblyMetadata("IsTrimmable", "True")]`, which would otherwise let trimming remove the unused library without analyzing it.
68+
69+
- `<TrimmerDefaultAction>link</TrimmerDefaultAction>` ensures that only used parts of dependencies are analyzed. Without this option, you would see warnings originating from _any_ part of a dependency that doesn't set `[AssemblyMetadata("IsTrimmable", "True")]`, including parts that are unused by your library.
70+
71+
You can also follow the same pattern for multiple libraries, adding them all to the same project as `ProjectReference` and `TrimmerRootAssembly` item to see trim analysis warnings for more than one library at a time, but note that this will warn about dependencies if _any_ of the root libraries use a trim-unfriendly API in a dependency. To see warnings that have to do with only a particular library, reference that library only.
72+
73+
> [!NOTE]
74+
> The analysis results depend on the implementation details of your dependencies. If you update to a new version of a dependency, this may introduce analysis warnings if the new version added non-understood reflection patterns, even if there were no API changes. In other words, introducing trim analysis warnings to a library is a breaking change when the library is used with `PublishTrimmed`.
75+
76+
## Resolve trim warnings
77+
78+
The above steps will produce warnings about code that may cause problems when used in a trimmed app. Here are a few examples of the most common kinds of warnings you may encounter, with recommendations for fixing them.
79+
80+
### RequiresUnreferencedCode
81+
82+
```csharp
83+
using System.Diagnostics.CodeAnalysis;
84+
85+
public class MyLibrary
86+
{
87+
public static void Method()
88+
{
89+
// warning IL2026 : MyLibrary.Method: Using method 'MyLibrary.DynamicBehavior' which has
90+
// 'RequiresUnreferencedCodeAttribute' can break functionality
91+
// when trimming application code.
92+
DynamicBehavior();
93+
}
94+
95+
[RequiresUnreferencedCode("DynamicBehavior is incompatible with trimming.")]
96+
static void DynamicBehavior()
97+
{
98+
}
99+
}
100+
```
101+
102+
This means the library calls a method which has explicitly been annotated as incompatible with trimming, using [`RequiresUnreferencedCodeAttribute`](
103+
https://docs.microsoft.com/dotnet/api/system.diagnostics.codeanalysis.requiresunreferencedcodeattribute?view=net-5.0&preserve-view=true). To get rid of the warning, consider whether `Method` needs to call `DynamicBehavior` to do its job. If so, annotate the caller `Method` with `RequiresUnreferencedCode` as well; this will "bubble up" the warning so that callers of `Method` get a warning instead:
104+
105+
```csharp
106+
// Warn for calls to Method, but not for Method's call to DynamicBehavior.
107+
[RequiresUnreferencedCode("Calls DynamicBehavior.")]
108+
public static void Method()
109+
{
110+
DynamicBehavior(); // OK. Doesn't warn now.
111+
}
112+
```
113+
114+
Once you have "bubbled up" the attribute all the way to public APIs (so that these warnings are produced only for public methods, if at all), you are done. Apps which call your library will now get warnings if they call those public APIs, but these will no longer produce warnings like `IL2104: Assembly 'MyLibrary' produced trim warnings`.
115+
116+
### DynamicallyAccessedMembers
117+
118+
```csharp
119+
using System.Diagnostics.CodeAnalysis;
120+
121+
public class MyLibrary
122+
{
123+
static void UseMethods(Type type)
124+
{
125+
// warning IL2070: MyLibrary.UseMethods(Type): 'this' argument does not satisfy
126+
// 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethods()'.
127+
// The parameter 't' of method 'MyLibrary.UseMethods(Type)' does not have matching annotations.
128+
foreach (var method in type.GetMethods())
129+
{
130+
// ...
131+
}
132+
}
133+
}
134+
```
135+
136+
Here, `UseMethods` is calling a reflection method which has a [`DynamicallyAccessedMembers`](https://docs.microsoft.com/dotnet/api/system.diagnostics.codeanalysis.dynamicallyaccessedmembersattribute?view=net-5.0&preserve-view=true) requirement. The requirement states that the type's public methods are available. In this case, you can fix this by adding the same requirement to the parameter of `UseMethods`.
137+
138+
```csharp
139+
static void UseMethods(
140+
// State the requirement in the UseMethods parameter.
141+
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)]
142+
Type type)
143+
{
144+
// ...
145+
}
146+
```
147+
148+
Now any calls to `UseMethods` will produce warnings if they pass in values which don't satisfy the `PublicMethods` requirement. Like with `RequiresUnreferencedCode`, once you have bubbled up such warnings to public APIs, you are done.
149+
150+
Here is another example where an unknown `Type` flows into the annotated method parameter, this time from a field:
151+
152+
```csharp
153+
static Type type;
154+
155+
static void UseMethodsHelper()
156+
{
157+
// warning IL2077: MyLibrary.UseMethodsHelper(Type): 'type' argument does not satisfy
158+
// 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'MyLibrary.UseMethods(Type)'.
159+
// The field 'System.Type MyLibrary::type' does not have matching annotations.
160+
UseMethods(type);
161+
}
162+
```
163+
164+
Similarly, here the problem is that the field `type` is passed into a parameter with these requinements. You can fix it by adding `DynamicallyAccessedMembers` to the field. This will warn about code that assigns incompatible values to the field instead. Sometimes this process will continue until a public API is annotated, and other times it will end when a concrete type flows into a location with these requirements. For example:
165+
166+
```csharp
167+
[DynamicallyAccessedMembers(DynamicallyAccessedMembers.PublicMethods)]
168+
static Type type;
169+
170+
static void InitializeTypeField()
171+
{
172+
MyLibrary.type = typeof(System.Tuple);
173+
}
174+
```
175+
176+
In this case the trim analysis will simply keep public methods of `System.Tuple`, and will not produce further warnings.
177+
178+
## Recommendations
179+
180+
In general, try to avoid reflection if possible. When using reflection, limit it in scope so that it is reachable only from a small part of the library.
181+
182+
- Avoid using non-understood patterns in places like static constructors that will result in the warning propagating to all members of the class.
183+
- Avoid annotating virtual methods or interface methods, which will require all overrides to have matching annotations.
184+
- In some cases, you will be able to mechanically propagate warnings through your code without issues. Sometimes this will result in much of your public API being annotated with `RequiresUnreferencedCode`, which is the right thing to do if the library indeed behaves in ways that can't be understood statically by the trim analysis.
185+
- In other cases, you might discover that your code uses patterns which can't be expressed in terms of the `DynamicallyAccessedMembers` attributes, even if it only uses reflection to operate on statically-known types. In these cases, you may need to reorganize some of your code to make it follow an analyzable pattern.
186+
- Sometimes the existing design of an API will render it mostly trim-incompatible, and you may need to find other ways to accomplish what it is doing. A common example is reflection-based serializers. In these cases, consider adopting other technology like source generators to produce code that is more easily statically analyzed.
187+
188+
## Resolve warnings for non-analyzable patterns
189+
190+
You should prefer resolving warnings by expressing the intent of your code using `RequiresUnreferencedCode` and `DynamicallyAccessedMembers` when possible. However, in some cases you may be interested in enabling trimming of a library that uses patterns which can't be expressed with those attributes, or without refactoring existing code. This section describes additional advanced ways to resolve trim analysis warnings.
191+
192+
> [!WARNING]
193+
> These techniques might break your code if used incorrectly.
194+
195+
When suppressing warnings, you are responsible for guaranteeing the trim compatibility of your code based on invariants that you know to be true by inspection. Be very careful with these annotations, because if they are incorrect, or if invariants of your code change, they might end up hiding real issues.
196+
197+
### UnconditionalSuppressMessage
198+
199+
If the intent of your code can't be expressed with the annotations, but you know that the warning doesn't represent a real issue at runtime, you can suppress the warnings using [`UnconditionalSuppressMessageAttribute`](https://docs.microsoft.com/dotnet/api/system.diagnostics.codeanalysis.unconditionalsuppressmessageattribute?view=net-5.0&preserve-view=true). This is similar to `SuppressMessageAttribute`, but it is persisted in IL and respected during trim analysis. For example:
200+
201+
```csharp
202+
class TypeCollection
203+
{
204+
Type[] types;u
205+
206+
// Ensure that only types with ctors are stored in the array
207+
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
208+
public Type this[int i]
209+
{
210+
// warning IL2063: TypeCollection.Item.get: Value returned from method 'TypeCollection.Item.get'
211+
// can not be statically determined and may not meet 'DynamicallyAccessedMembersAttribute' requirements.
212+
get => types[i];
213+
set => types[i] = value;
214+
}
215+
}
216+
217+
class TypeCreator
218+
{
219+
TypeCollection types;
220+
221+
public void CreateType(int i)
222+
{
223+
types[i] = typeof(TypeWithConstructor);
224+
Activator.CreateInstance(types[i]); // No warning!
225+
}
226+
}
227+
228+
class TypeWithConstructor
229+
{
230+
}
231+
```
232+
233+
Here, the indexer property has been annotated so that the returned `Type` meets the requirements of `CreateInstance`. This already ensures that the `TypeWithConstructor` constructor is kept, and that the call to `CreateInstance` doesn't warn. Furthermore, the indexer setter annotation ensures that any types stored in the `Type[]` have a constructor. However, the analysis isn't able to see this, and still produces a warning for the getter, because it doesn't know that the returned type has its constructor preserved.
234+
235+
If you are sure that the requirements are met, you can silence this warning by adding `UnconditionalSuppressMessage` to the getter:
236+
237+
```csharp
238+
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
239+
public Type this[int i]
240+
{
241+
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2063",
242+
Justification = "The list only contains types stored through the annotated setter.")]
243+
get => types[i];
244+
set => types[i] = value;
245+
}
246+
```

0 commit comments

Comments
 (0)