# ReferenceTrimmer [![NuGet Version](https://img.shields.io/nuget/v/ReferenceTrimmer.svg)](https://www.nuget.org/packages/ReferenceTrimmer) [![NuGet Downloads](https://img.shields.io/nuget/dt/ReferenceTrimmer.svg)](https://www.nuget.org/packages/ReferenceTrimmer) Easily identify which C# dependencies can be removed from an MSBuild project, and expose MSVC output to show unused libraries and delay-load DLLs at link time. Removing project dependencies flattens your build dependency graph which can improve build parallelism and reduce end-to-end build time. ## Rules The following warnings are generated by this package: | Id | Description | |--------|-------------| | RT0000 | Enable documentation generation for accuracy of used references detection | | RT0001 | Unnecessary reference | | RT0002 | Unnecessary project reference | | RT0003 | Unnecessary package reference | ## How to use Add a package reference to the [ReferenceTrimmer](https://www.nuget.org/packages/ReferenceTrimmer) package in your projects, or as a common package reference in the repo's [`Directory.Packages.props`](./Directory.Build.props). If you're using [Central Package Management](https://learn.microsoft.com/en-us/nuget/consume-packages/Central-Package-Management), you can use it as a `GlobalPackageReference` in your `Directory.Packages.props` to apply it to the entire repo. ```xml ``` ### C# You'll need to enable C# documentation XML generation to ensure good analysis results. If your repo is not already using docxml globally, this can introduce a large number of errors and warnings specific to docxml. Additionally, turning on docxml adds additional output I/O that can slow down large repos. You can turn off specific docxml related warnings and errors while defaulting ReferenceTrimmer to off using a block of code like this in your `Directory.Build.props`. Turn on the ReferenceTrimmer build by setting `/p:EnableReferenceTrimmer=true` on the MSBuild command line or setting the same property value as an environment variable. You could create a separate build pipeline for your repo to run ReferenceTrimmer builds. ```xml false true $(NoWarn);419;1570;1573;1574;1584;1591;SA1602 ``` Note: To get better results, enable the [`IDE0005`](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0005) unnecessary `using` rule. This avoids the C# compiler seeing a false positive assembly usage from unneeded `using` directives causing it to miss a removable dependency. See also the note for why IDE0005 code analysis rule requires `` property to be enabled. Documentation generation is also required for accuracy of used references detection (based on https://github.com/dotnet/roslyn/issues/66188). ### C++ (.vcxproj projects) ReferenceTrimmer for C++ is an MSBuild [distributed logger](https://learn.microsoft.com/en-us/visualstudio/msbuild/logging-in-a-multi-processor-environment?view=vs-2022). It writes guidance to the MSBuild stdout stream (not to the MSBuild internal logger at this time) and writes `ReferenceTrimmerUnusedMSVCLibraries.json.log` to the build working directory. The distributed logger requires configuration at the MSBuild command line using the `-distributedlogger` parameter. See the [BuildWithReferenceTrimmer example script](./examples/BuildWithReferenceTrimmer.cmd) for how to orchestrate pulling and using the package's loggers. Use `msbuild -restore` or `msbuild /t:Restore` instead of `dotnet restore` to ensure .vcxproj restore will work to add the ReferenceTrimmer props and targets to your build. *NOTE*: If you are seeing a `Sequence contains no elements` exception from MSBuild, see https://github.com/dotnet/NuGet.BuildTasks/issues/154 for a workaround or status on a fix. The current implementation turns on MSVC `link.exe` flags `/VERBOSE:UNUSEDLIBS` and `/VERBOSE:UNUSEDDELAYLOAD`. These flags tell the linker to print out unused .lib files and delay-load DLLs to stdout. This will include .lib files containing code bundles as well as import libraries for DLLs. Removing these libraries reduces I/O and memory usage by the linker. Here's an example of the linker output: ```text Unused libraries: C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\um\x64\gdi32.lib C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\um\x64\winspool.lib C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\um\x64\comdlg32.lib ``` ReferenceTrimmer reads this output and splits the resulting libraries into two sets: #### Windows SDK import libraries The Microsoft C++ SDK for MSBuild includes in the `AdditionalDependencies` property a default list of Win32 import libraries like kernel32.lib and user32.lib. You can find the default list in your local VS installation by searching: ```cmd findstr /s CoreLibraryDependencies "\Program Files"\*props ``` To disable these, modify the vcxproj `` property to just the list of SDK .lib files needed for the project, and do not add `%(AdditionalDependencies)` to the property to avoid the default list. Example: ```xml kernel32.lib;shlwapi.lib;ws2_32.lib ``` Not all SDK .lib files can be removed this way. You might need to use `` as well: ```xml OLDNAMES.lib;%(IgnoreSpecificDefaultLibraries) ``` #### Package or Project libraries If you find an unused .lib that is created by a .vcxproj in your repo, you should be able to remove the `ProjectReference` to that vcxproj to improve your build dependency graph and allow greater parallelism during build. If you find an unused .lib that is from a package, remove the reference to that .lib from your project to speed up linking. ## Disabling a rule on a reference To turn off a rule on a specific project or package reference, add the relevant RTxxxx code to a NoWarn metadata attribute. For example: ```xml ``` ## Configuration `$(EnableReferenceTrimmer)` - Controls whether the build logic should run for a given project. Defaults to `true`. `$(ReferenceTrimmerEnableVcxproj)` - Controls whether MSVC link flags are set up to print out unused libraries and delay-load DLLs. Defaults to `true`. ## How does it work? ### C# There are two main pieces to C# support. First there is an MSBuild task which collects all references passed to the compiler. There is also a Roslyn Analyzer which uses the [`GetUsedAssemblyReferences`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.codeanalysis.compilation.getusedassemblyreferences) analyzer API which is available starting with Roslyn compiler that shipped with Visual Studio 2019 version 16.10, .NET 5. (see https://github.com/dotnet/roslyn/blob/main/docs/wiki/NuGet-packages.md#versioning). This is the compiler telling us exactly what references were needed as part of compilation. The analyzer then compares the set of references the Task gathered with the references the compiler says were used. ### C++ (.vcxproj projects) ReferenceTrimmer enables the MSVC `link.exe` flags noted above, then parses output coming from the `Link` MSBuild task. It categorizes the outputs and emits them into the MSBuild console output and the JSON output file noted above. It does not issue MSBuild warnings at this time. ## Future development The outcome of https://github.com/dotnet/sdk/issues/10414 may be of use for `ReferenceTrimmer` future updates.