在构建过程中找出PlatformNotSupportedException

pev*_*l27 7 c# code-analysis cross-platform .net-core

我正在开发一个要Windows使用的项目.NET Core 2.2。我将在Linux明年构建和支持它。我正在寻找一种方法来标记错误并破坏构建(如果PlatformNotSupportedException在代码中使用的话)。

我见过.NET API分析器,该分析器仍处于预发布阶段,并且自去年以来未更新。

Ale*_*lex 5

您可以Mono.Cecil用来检查是否在程序集中的某个地方抛出了异常。

public static class ExceptionHelper<TException> where TException : Exception
{
    private static readonly string typeName = typeof(TException).FullName;

    public static void ThrowIfDetected(Assembly assembly)
    {
        var definition = AssemblyDefinition.ReadAssembly(assembly.Location);
        var exceptions = CreateExceptions(definition);
        if (exceptions.Any())
            throw new AggregateException(exceptions);
    }

    public static void ThrowIfDetected(params Assembly[] assemblies) =>
        ThrowIfDetected(assemblies as IEnumerable<Assembly>);

    public static void ThrowIfDetected(IEnumerable<Assembly> assemblies)
    {
        var exceptions = CreateExceptions(assemblies);
        if (exceptions.Any())
            throw new AggregateException(exceptions);
    }

    private static IEnumerable<Exception> CreateExceptions(IEnumerable<Assembly> assemblies) =>
        assemblies.Select(assembly => AssemblyDefinition.ReadAssembly(assembly.Location))
                  .SelectMany(definition => CreateExceptions(definition));

    private static IEnumerable<Exception> CreateExceptions(AssemblyDefinition definition)
    {
        var methods =
                definition.Modules
                          .SelectMany(m => m.GetTypes())
                          .SelectMany(t => t.Methods)
                          .Where(m => m.HasBody);
        foreach (var method in methods)
        {
            var instructions = method.Body.Instructions
                .Where(i => i.OpCode.Code == Code.Newobj && // new object is created
                            ((MethodReference)i.Operand).DeclaringType.FullName == typeName && // the object is 'TException'
                            i.Next.OpCode.Code == Code.Throw); // and it's immediately thrown
            foreach (var i in instructions)
            {
                var message = $"{definition.FullName} {method.FullName} offset {i.Offset} throws {typeName}";
                yield return new Exception(message);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要获取引用的程序集,请使用以下扩展方法:

public static class AssemblyExtensions
{
    public static Assembly[] ReflectionOnlyLoadReferencedAssemblies(this Assembly assembly) =>
        assembly.GetReferencedAssemblies()
                .Select(a => Assembly.ReflectionOnlyLoad(a.FullName))
                .ToArray();
}
Run Code Online (Sandbox Code Playgroud)

用法:

创建一个新的控制台应用程序,并使用上述代码添加对程序集的引用。尝试:

try
{
    ExceptionHelper<PlatformNotSupportedException>.ThrowIfDetected(Assembly.GetEntryAssembly().ReflectionOnlyLoadReferencedAssemblies());
}
catch(AggregateException e)
{
    foreach (var inner in e.InnerExceptions)
        Console.WriteLine($"{inner.Message}\n");
}
Run Code Online (Sandbox Code Playgroud)

它给:

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Void System.Environment::SetEnvironmentVariable(System.String,System.String) offset 82 throws System.PlatformNotSupportedException

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.String System.Environment::InternalGetFolderPath(System.Environment/SpecialFolder,System.Environment/SpecialFolderOption,System.Boolean) offset 75 throws System.PlatformNotSupportedException

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Void System.Security.Principal.SecurityIdentifier::.ctor(System.Security.Principal.WellKnownSidType,System.Security.Principal.SecurityIdentifier) offset 49 throws System.PlatformNotSupportedException

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Int32 System.Security.Principal.Win32::CreateWellKnownSid(System.Security.Principal.WellKnownSidType,System.Security.Principal.SecurityIdentifier,System.Byte[]&) offset 17 throws System.PlatformNotSupportedException

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Boolean System.Security.Principal.Win32::IsEqualDomainSid(System.Security.Principal.SecurityIdentifier,System.Security.Principal.SecurityIdentifier) offset 17 throws System.PlatformNotSupportedException

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Int32 System.Security.Principal.Win32::GetWindowsAccountDomainSid(System.Security.Principal.SecurityIdentifier,System.Security.Principal.SecurityIdentifier&) offset 17 throws System.PlatformNotSupportedException

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Boolean System.Security.Principal.Win32::IsWellKnownSid(System.Security.Principal.SecurityIdentifier,System.Security.Principal.WellKnownSidType) offset 17 throws System.PlatformNotSupportedException

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.IntPtr System.StubHelpers.HStringMarshaler::ConvertToNative(System.String) offset 17 throws System.PlatformNotSupportedException

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.IntPtr System.StubHelpers.HStringMarshaler::ConvertToNativeReference(System.String,System.Runtime.InteropServices.WindowsRuntime.HSTRING_HEADER*) offset 17 throws System.PlatformNotSupportedException

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.String System.StubHelpers.HStringMarshaler::ConvertToManaged(System.IntPtr) offset 17 throws System.PlatformNotSupportedException

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Void System.StubHelpers.SystemTypeMarshaler::ConvertToNative(System.Type,System.StubHelpers.TypeNameNative*) offset 17 throws System.PlatformNotSupportedException

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Void System.StubHelpers.SystemTypeMarshaler::ConvertToManaged(System.StubHelpers.TypeNameNative*,System.Type&) offset 17 throws System.PlatformNotSupportedException

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Int32 System.StubHelpers.HResultExceptionMarshaler::ConvertToNative(System.Exception) offset 17 throws System.PlatformNotSupportedException

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Exception System.StubHelpers.HResultExceptionMarshaler::ConvertToManaged(System.Int32) offset 17 throws System.PlatformNotSupportedException

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.IntPtr System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal::StringToHString(System.String) offset 17 throws System.PlatformNotSupportedException

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.String System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal::PtrToStringHString(System.IntPtr) offset 17 throws System.PlatformNotSupportedException

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Void System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal::FreeHString(System.IntPtr) offset 17 throws System.PlatformNotSupportedException
Run Code Online (Sandbox Code Playgroud)

现在,您可以在单元测试中使用它(例如,使用NUnit)来自动检查您引用的程序集是否可以抛出PlatformNotSupportedException

[TestFixture]
public class Tests
{
    [Test]
    public void ReferencedAssembliesDoNOtThrowPlatformNotSupportedException()
    {
        Assert.DoesNotThrow(() => ExceptionHelper<PlatformNotSupportedException>.ThrowIfDetected(yourAssembly.ReflectionOnlyLoadReferencedAssemblies()));
    }
}
Run Code Online (Sandbox Code Playgroud)

如果像描述的测试失败,打破建立在这里


Ale*_*lex 4

我建议使用.NET Compiler Platform SDK来创建自己的规则。您可以在此处找到安装指南。安装时可能会遇到一些问题。解决方案位于 stackoverflow 上。完成后

  • 在 Visual Studio 中,选择“文件”>“新建”>“项目...带代码修复的分析器”(.NET Standard)。命名它PlatformNotSupportedExceptionAnalyzer
  • 在解决方案资源管理器中删除除PlatformNotSupportedExceptionAnalyzer.
  • PlatformNotSupportedExceptionAnalyzer删除.cs.resx文件。
  • 添加新班级Analyzer

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;

// ...

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class Analyzer : DiagnosticAnalyzer
{
    private static readonly string typeName =
        typeof(System.PlatformNotSupportedException).FullName;

    private static readonly DiagnosticDescriptor rule =
        new DiagnosticDescriptor(id: "ThrowsPlatformNotSupportedException",
                                 title: "Throws 'PlatformNotSupportedException'",
                                 messageFormat: "Do not throw 'PlatformNotSupportedException'",
                                 category: "Usage",
                                 defaultSeverity: DiagnosticSeverity.Error,
                                 isEnabledByDefault: true,
                                 description: "Throws 'PlatformNotSupportedException'");

    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
        ImmutableArray.Create(rule);

    public override void Initialize(AnalysisContext context) =>
        context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ThrowStatement);

    private void AnalyzeNode(SyntaxNodeAnalysisContext context)
    {
        if (!(context.Node.ChildNodes().SingleOrDefault() is ObjectCreationExpressionSyntax node))
            return;

        var type = context.SemanticModel.GetTypeInfo(node).Type;
        if ($"{type.ContainingNamespace}.{type.Name}".Equals(typeName))
            context.ReportDiagnostic(Diagnostic.Create(rule, context.Node.GetLocation()));
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 构建解决方案

测试一下:

  • 创建新项目。
  • 转到管理 NuGet 包... -> 设置。
  • 添加新的包源。
  • 将位置设置为您的PlatformNotSupportedExceptionAnalyzer \bin\Debug文件夹。
  • 命名AnalyzerSource并保存。
  • 将包源设置为AnalyzerSource
  • 在浏览中选择PlatformNotSupportedExceptionAnalyzer并安装它。

现在尝试:

throw new PlatformNotSupportedException();
Run Code Online (Sandbox Code Playgroud)

得到错误:

错误抛出PlatformNotSupportedException 不要抛出“PlatformNotSupportedException”

在此输入图像描述

你可以用#pragma warning disable#pragma warning restore来控制它:

在此输入图像描述

或者SuppressMessageAttribute像这样:

在此输入图像描述

您还可以更改其严重性:解决方案资源管理器 -> 项目 -> 引用 -> 分析器 -> 您的分析器

在此输入图像描述

在此输入图像描述