Skip to content

Commit

Permalink
Add an analyzer for PublishSingleFile (#3921)
Browse files Browse the repository at this point in the history
When publishing single-file applications, certain APIs are very likely
to return incorrect results. Most notably, asking for the Location of
any Assembly loaded from the single-file will return an empty string,
instead of a file path. To minimize surprise, this analyzer flags all
usages of the APIs most likely to break when used in single-file when
the PublishSingleFile property is set to true, and the
IncludeAllContentForSelfExtractProperty is not true (which provides the
legacy API behavior).

Co-authored-by: Amaury Levé <evangelink@gmail.com>
Co-authored-by: Manish Vasani <mavasani@microsoft.com>
  • Loading branch information
3 people authored Aug 3, 2020
1 parent 30c2edf commit 0c78e1e
Show file tree
Hide file tree
Showing 23 changed files with 573 additions and 30 deletions.
3 changes: 3 additions & 0 deletions src/NetAnalyzers/Core/AnalyzerReleases.Unshipped.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ CA2361 | Security | Disabled | DoNotUseDataSetReadXml, [Documentation](https://d
CA2362 | Security | Disabled | DataSetDataTableInSerializableTypeAnalyzer, [Documentation](https://docs.microsoft.com/visualstudio/code-quality/ca2362)
CA2363 | Security | Disabled | DataSetDataTableInSerializableTypeAnalyzer, [Documentation](https://docs.microsoft.com/visualstudio/code-quality/ca2363)

IL3000 | Publish | Warning | DoNotUseAssemblyLocationInSingleFile, [Documentation](https://docs.microsoft.com/visualstudio/code-quality/il3000)
IL3001 | Publish | Warning | DoNotUseAssemblyGetFilesInSingleFile, [Documentation](https://docs.microsoft.com/visualstudio/code-quality/il3001)

### Changed Rules
Rule ID | New Category | New Severity | Old Category | Old Severity | Notes
--------|--------------|--------------|--------------|--------------|-------
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -1455,4 +1455,13 @@
<data name="AvoidStringBuilderPInvokeParametersTitle" xml:space="preserve">
<value>Avoid 'StringBuilder' parameters for P/Invokes</value>
</data>
<data name="AvoidAssemblyLocationInSingleFileTitle" xml:space="preserve">
<value>Avoid using accessing Assembly file path when publishing as a single-file</value>
</data>
<data name="AvoidAssemblyLocationInSingleFileMessage" xml:space="preserve">
<value>'{0}' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'.</value>
</data>
<data name="AvoidAssemblyGetFilesInSingleFile" xml:space="preserve">
<value>'{0}' will throw for assemblies embedded in a single-file app.</value>
</data>
</root>
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;

namespace Microsoft.NetCore.Analyzers.Publish
{
/// <summary>
/// IL3000, IL3001: Do not use Assembly file path in single-file publish
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AvoidAssemblyLocationInSingleFile : DiagnosticAnalyzer
{
public const string IL3000 = nameof(IL3000);
public const string IL3001 = nameof(IL3001);

internal static DiagnosticDescriptor LocationRule = DiagnosticDescriptorHelper.Create(
IL3000,
new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.AvoidAssemblyLocationInSingleFileTitle),
MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)),
new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.AvoidAssemblyLocationInSingleFileMessage),
MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)),
DiagnosticCategory.Publish,
RuleLevel.BuildWarning,
description: null,
isPortedFxCopRule: false,
isDataflowRule: false);

internal static DiagnosticDescriptor GetFilesRule = DiagnosticDescriptorHelper.Create(
IL3001,
new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.AvoidAssemblyLocationInSingleFileTitle),
MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)),
new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.AvoidAssemblyGetFilesInSingleFile),
MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)),
DiagnosticCategory.Publish,
RuleLevel.BuildWarning,
description: null,
isPortedFxCopRule: false,
isDataflowRule: false);

public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(LocationRule, GetFilesRule);

public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.ReportDiagnostics);

context.RegisterCompilationStartAction(context =>
{
var compilation = context.Compilation;
var isSingleFilePublish = context.Options.GetMSBuildPropertyValue(
MSBuildPropertyOptionNames.PublishSingleFile, compilation, context.CancellationToken);
if (!string.Equals(isSingleFilePublish?.Trim(), "true", StringComparison.OrdinalIgnoreCase))
{
return;
}
var includesAllContent = context.Options.GetMSBuildPropertyValue(
MSBuildPropertyOptionNames.IncludeAllContentForSelfExtract, compilation, context.CancellationToken);
if (string.Equals(includesAllContent?.Trim(), "true", StringComparison.OrdinalIgnoreCase))
{
return;
}

var propertiesBuilder = ImmutableArray.CreateBuilder<IPropertySymbol>();
var methodsBuilder = ImmutableArray.CreateBuilder<IMethodSymbol>();

if (compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemReflectionAssembly, out var assemblyType))
{
// properties
AddIfNotNull(propertiesBuilder, TryGetSingleSymbol<IPropertySymbol>(assemblyType.GetMembers("Location")));

// methods
methodsBuilder.AddRange(assemblyType.GetMembers("GetFile").OfType<IMethodSymbol>());
methodsBuilder.AddRange(assemblyType.GetMembers("GetFiles").OfType<IMethodSymbol>());
}

if (compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemReflectionAssemblyName, out var assemblyNameType))
{
AddIfNotNull(propertiesBuilder, TryGetSingleSymbol<IPropertySymbol>(assemblyNameType.GetMembers("CodeBase")));
AddIfNotNull(propertiesBuilder, TryGetSingleSymbol<IPropertySymbol>(assemblyNameType.GetMembers("EscapedCodeBase")));
}

var properties = propertiesBuilder.ToImmutable();
var methods = methodsBuilder.ToImmutable();

context.RegisterOperationAction(operationContext =>
{
var access = (IPropertyReferenceOperation)operationContext.Operation;
var property = access.Property;
if (!Contains(properties, property, SymbolEqualityComparer.Default))
{
return;
}

operationContext.ReportDiagnostic(access.CreateDiagnostic(LocationRule, property));
}, OperationKind.PropertyReference);

context.RegisterOperationAction(operationContext =>
{
var invocation = (IInvocationOperation)operationContext.Operation;
var targetMethod = invocation.TargetMethod;
if (!Contains(methods, targetMethod, SymbolEqualityComparer.Default))
{
return;
}

operationContext.ReportDiagnostic(invocation.CreateDiagnostic(GetFilesRule, targetMethod));
}, OperationKind.Invocation);

return;

static bool Contains<T, TComp>(ImmutableArray<T> list, T elem, TComp comparer)
where TComp : IEqualityComparer<T>
{
foreach (var e in list)
{
if (comparer.Equals(e, elem))
{
return true;
}
}
return false;
}

static TSymbol? TryGetSingleSymbol<TSymbol>(ImmutableArray<ISymbol> members) where TSymbol : class, ISymbol
{
TSymbol? candidate = null;
foreach (var m in members)
{
if (m is TSymbol tsym)
{
if (candidate is null)
{
candidate = tsym;
}
else
{
return null;
}
}
}
return candidate;
}

static void AddIfNotNull<TSymbol>(ImmutableArray<TSymbol>.Builder properties, TSymbol? p) where TSymbol : class, ISymbol
{
if (p is not null)
{
properties.Add(p);
}
}
});
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public sealed class DoNotCallDangerousMethodsInDeserialization : DiagnosticAnaly
(WellKnownTypeNames.SystemIOFileInfo, new[] { "Delete" }),
(WellKnownTypeNames.SystemIODirectoryInfo, new[] { "Delete" }),
(WellKnownTypeNames.SystemIOLogLogStore, new[] { "Delete" }),
(WellKnownTypeNames.SystemReflectionAssemblyFullName, new[] { "GetLoadedModules", "Load", "LoadFile", "LoadFrom", "LoadModule", "LoadWithPartialName", "ReflectionOnlyLoad", "ReflectionOnlyLoadFrom", "UnsafeLoadFrom" })
(WellKnownTypeNames.SystemReflectionAssembly, new[] { "GetLoadedModules", "Load", "LoadFile", "LoadFrom", "LoadModule", "LoadWithPartialName", "ReflectionOnlyLoad", "ReflectionOnlyLoadFrom", "UnsafeLoadFrom" })
);

internal static DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,21 @@
<target state="translated">Literály řetězců atributů by se měly správně parsovat</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssemblyGetFilesInSingleFile">
<source>'{0}' will throw for assemblies embedded in a single-file app.</source>
<target state="new">'{0}' will throw for assemblies embedded in a single-file app.</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssemblyLocationInSingleFileMessage">
<source>'{0}' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'.</source>
<target state="new">'{0}' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'.</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssemblyLocationInSingleFileTitle">
<source>Avoid using accessing Assembly file path when publishing as a single-file</source>
<target state="new">Avoid using accessing Assembly file path when publishing as a single-file</target>
<note />
</trans-unit>
<trans-unit id="AvoidStringBuilderPInvokeParametersDescription">
<source>Marshalling of 'StringBuilder' always creates a native buffer copy, resulting in multiple allocations for one marshalling operation.</source>
<target state="new">Marshalling of 'StringBuilder' always creates a native buffer copy, resulting in multiple allocations for one marshalling operation.</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,21 @@
<target state="translated">Attributzeichenfolgenliterale müssen richtig analysiert werden</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssemblyGetFilesInSingleFile">
<source>'{0}' will throw for assemblies embedded in a single-file app.</source>
<target state="new">'{0}' will throw for assemblies embedded in a single-file app.</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssemblyLocationInSingleFileMessage">
<source>'{0}' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'.</source>
<target state="new">'{0}' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'.</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssemblyLocationInSingleFileTitle">
<source>Avoid using accessing Assembly file path when publishing as a single-file</source>
<target state="new">Avoid using accessing Assembly file path when publishing as a single-file</target>
<note />
</trans-unit>
<trans-unit id="AvoidStringBuilderPInvokeParametersDescription">
<source>Marshalling of 'StringBuilder' always creates a native buffer copy, resulting in multiple allocations for one marshalling operation.</source>
<target state="new">Marshalling of 'StringBuilder' always creates a native buffer copy, resulting in multiple allocations for one marshalling operation.</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,21 @@
<target state="translated">Los literales de cadena de atributo se deben analizar correctamente</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssemblyGetFilesInSingleFile">
<source>'{0}' will throw for assemblies embedded in a single-file app.</source>
<target state="new">'{0}' will throw for assemblies embedded in a single-file app.</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssemblyLocationInSingleFileMessage">
<source>'{0}' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'.</source>
<target state="new">'{0}' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'.</target>
<note />
</trans-unit>
<trans-unit id="AvoidAssemblyLocationInSingleFileTitle">
<source>Avoid using accessing Assembly file path when publishing as a single-file</source>
<target state="new">Avoid using accessing Assembly file path when publishing as a single-file</target>
<note />
</trans-unit>
<trans-unit id="AvoidStringBuilderPInvokeParametersDescription">
<source>Marshalling of 'StringBuilder' always creates a native buffer copy, resulting in multiple allocations for one marshalling operation.</source>
<target state="new">Marshalling of 'StringBuilder' always creates a native buffer copy, resulting in multiple allocations for one marshalling operation.</target>
Expand Down
Loading

0 comments on commit 0c78e1e

Please sign in to comment.