Skip to content

Annotate libraries with caller-unsafe keyword #125145

Open

Description

@agocke

Per the description in https://github.com/dotnet/designs/blob/main/accepted/2025/memory-safety/caller-unsafe.md, we need to annotate functions that should be considered unsafe.

Links to API Proposals:

Criteria

The doc defines a safe API when it meets two criteria:

  • Code never accesses memory that is not managed by the runtime
  • No access to uninitialized memory

Here are a few more fine-grained criteria based on those two:

  • May create a potentially incorrect managed pointer. Examples include all Unsafe.Add* and Unsafe.Subtract*. Such pointers may crash an app even when not directly dereferenced anywhere.
  • May create a managed pointer that should never be directly dereferenced. Example: MemoryMarshal.GetArrayDataReference over an empty array.
  • Dereferences a caller-supplied unmanaged address - reads or writes through a raw IntPtr/nint/T* parameter (or any kind of wrapper with those e.g. SafeHandle) directly or just lets it flow into a system where it might be dereferenced later.
  • May strip readonly-ness from a pointer. Example: Unsafe.AsRef removing readonly and making a pointer to a readonly memory (e.g. RVA) writeable. This also may violate security invariants a type may hold.
  • May read uninitialized data. Examples include reading padding/alignment in structs via various MemoryMarshal APIs, Unsafe.BitCast, Unsafe.As. Also, various Unsafe.SkipInit, GC.AllocateUninitialized*, etc.
  • May set an unsafe field without an unsafe context. A good example is MemoryMarshal.Read<T>(ROS<byte>) where T might theoretically have an unsafe field that this API lets you set without an unsafe context.
  • Produces a misaligned pointer from a properly aligned input. Examples: MemoryMarshal.Cast, [StructLayout(LayoutKind.Explicit)].

Edge-cases

A section for edge-cases if any.

  • Sometimes it's just not realistic to mark some widely used interface as unsafe e.g. IDisposable.Dispose to make some particular dangerous Dispose unsafe to call. In that case we need annotate all APIs that create that kind object as unsafe. Example: GCHandle<T>.Dispose may lead to a global state corruption if called twice (e.g. on two copies of the same handle).
  • All extern/[LibraryImport]/InternalCall APIs are considered unsafe by default unless explicitly annotated with safe keyword.

Out of scope

  • Reflection. Eventually we will likely make it mostly unsafe, but today it's completely out of scope.
  • Shapes considered safe today because C# doesn't have lifetimes/ownership, allows static mutable state, etc.
  • Thread-safety (although there are some intersections, it's generally considered orthogonal to memory safety)
  • APIs in OOB packages (for now)

Activity

  1. added
    untriaged
    on Mar 3, 2026
  2. added this to the 11.0.0 milestone on Mar 3, 2026
  3. removed
    untriaged
    on Mar 3, 2026
  4. hamarb123 commented on Mar 3, 2026

    @hamarb123
    Contributor

    In this document memory safety is strictly defined as: code never accesses memory that is not managed by the runtime.

    This definition seems problematic to me. What about this definition says I should have to mark the following as [RequiresUnsafe]:

    static T2[] Transmute<T1, T2>(T1[] arr)
    {
        if (typeof(T1) != typeof(int) && typeof(T1) != typeof(MyIntWrapper)) throw new ArgumentOutOfRangeException(nameof(T1), "T1 must be int or MyIntWrapper");
        if (typeof(T2) != typeof(int) && typeof(T2) != typeof(MyIntWrapper)) throw new ArgumentOutOfRangeException(nameof(T2), "T2 must be int or MyIntWrapper");
        unsafe
        {
            return Unsafe.As<T2[]>(arr);
        }
    }
    
    [StructLayout(LayoutKind.Sequential)]
    struct MyIntWrapper
    {
        int Value;
    }

    Shouldn't it also discuss that it's not memory-safe to:

    • Reinterpret an object reference to a type for which (object)x is MyType would give false (maybe this also interacts with IDIC, not certain)
    • Create any invalid (per c# rules, which require that it's assignable/readable for mutable or readable for readonly, or null byref is also fine just gives an exception on access) by-reference
    • Etc.

    None of these seem to be memory-unsafe by the unsafe definition, if I do not "access them" (which would then imply that if I can create them safely, that any potential accessing must have to have [RequiresUnsafe] if it would break the definition, which seems problematic also) - but they are actually unsafe (and can lead to AV's & etc.).

    If it's intended to be implied by the definition, imo it would be great to add these as examples so there's no ambiguity it's meant to be covered.

  5. agocke commented on Mar 4, 2026

    @agocke
    MemberAuthor

    What about this definition says I should have to mark the following as [RequiresUnsafe]:

    That is not the operative definition for your use case because you are not manipulating the memory directly. You are using Unsafe.As. For your function to be safe you must follow the stated rules on Unsafe.As. The remarks on Unsafe.As state:

    This API is used to cast an object to the given type, suppressing the runtime's normal type safety checks. It is the caller's responsibility to ensure that the cast is legal. No InvalidCastException will be thrown.

    The behavior of Unsafe.As(o) is only well-defined if the typical "safe" casting operation (T)o would have succeeded. Use of this API to circumvent casts that would otherwise have failed is unsupported and could result in runtime instability.

    So your function is correct only if you use Unsafe.As for casts that would otherwise be valid in the language.

  6. EgorBo commented on Mar 4, 2026

    @EgorBo
  7. vyrp commented on Jun 25, 2026

    @vyrp
  8. changed the title [-]Annotate libraries with RequiresUnsafe attribute[/-] [+]Annotate libraries with caller-unsafe keyword[/+] on Jun 30, 2026
  9. modified the milestones: 11.0.0, 12.0.0 on Sep 9, 2026
  10. jeffhandley commented on Sep 9, 2026

    @jeffhandley
    Member

    @EgorBo I moved this to .NET 12. Please pull back in to .NET 11 if that's still the target.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions