sonar-dotnet icon indicating copy to clipboard operation
sonar-dotnet copied to clipboard

New Rule Idea: UnsafeAccessorAttribute should define a valid name

Open antonioaversa opened this issue 1 year ago • 0 comments

The Name parameter of the UnsafeAccessorAttribute should be:

  • not specified, when kind is UnsafeAccessorKind.Constructor
  • the name of an existing member (including unspeakable fields), when kind is UnsafeAccessorKind.Method, UnsafeAccessorKind.StaticMethod, UnsafeAccessorKind.Field or UnsafeAccessorKind.StaticField

Not respecting this rule would result in a System.BadImageFormatException: 'Invalid usage of UnsafeAccessorAttribute.'.

using System.Runtime.CompilerServices;

[UnsafeAccessor(UnsafeAccessorKind.Constructor, Name = "AnInvalidName")] // Noncompliant: Name should not be specified with kind Constructor
extern static UserData CallCtor();

[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "NonExistingMethod")] // Noncompliant: There is no "NonExistingMethod" in UserData
extern static void CallMethod();

CallCtor(); // BadImageFormatException
CallMethod(); // BadImageFormatException

class UserData
{
    private UserData() { }
}

nameof is not usable in most scenarios, since the member being targeted by the UnsafeAccessorAttribute is private, hence it cannot be referenced inside the nameof.

Related new rule ideas on C# 12 Zero-overhead member access:

  • https://github.com/SonarSource/sonar-dotnet/issues/8151
  • https://github.com/SonarSource/sonar-dotnet/issues/8154

antonioaversa avatar Oct 06 '23 12:10 antonioaversa