Skip to content

[API Proposal]: RequiresUnsafeAttribute(bool requiresUnsafe) ctor #125904

@EgorBo

Description

@EgorBo

Background and motivation

We plan to ship analyzers and code fixers that will issue warnings for various patterns, such as APIs with unmanaged pointers in their signatures, LibraryImport attributes, and extern methods (among others). We need a better mechanism than #pragma warning to inform the analyzer that an API is safe. For example, all Math extern methods are pretty safe to require unsafe context on call sites:

#pragma warning disable IL5005 // whatever id for "'extern' must be [RequiresUnsafe]"
        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern double Sin(double a);
#pragma warning restore IL5005

with this API proposal it can be just:

        [RequiresUnsafe(false)]
        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern double Sin(double a);

API Proposal

namespace System.Diagnostics.CodeAnalysis
{
    public sealed class RequiresUnsafeAttribute : Attribute
    {
+       public RequiresUnsafeAttribute(bool requiresUnsafe = true) { }
    }
}

NOTE: since we've just introduced the attribute, I suspect it's not a breaking change to "remove" the default constructor.

API Usage

        [RequiresUnsafe(false)]
        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern double Sin(double a);

        [RequiresUnsafe] // 'true' by default
        [LibraryImport(RuntimeHelpers.QCall)]
        private static partial void _AddMemoryPressure(ulong bytesAllocated);

Alternative Designs

Alternatively, can be a new attribute with the opposite meaning, e.g.:

namespace System.Diagnostics.CodeAnalysis
{
    public sealed class DoesNotRequireUnsafeAttribute : Attribute { }
}

The new attribute would be simpler for us as it won't require changes in C# spec/Roslyn.

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions