Skip to content

[API Proposal]: Mark MemoryMarshal APIs as caller-unsafe #127098

Closed

Description

@EgorBo

Background and motivation

#125145

API Proposal

public static partial class MemoryMarshal
{
+   /// <safety>Reinterprets a span of T as a read-only byte span, exposing any padding bytes of T.</safety>
+   unsafe
    public static ReadOnlySpan<byte> AsBytes<T>(ReadOnlySpan<T> span) where T : struct { throw null; }

+   /// <safety>Reinterprets a span of T as a writable byte span, exposing any padding bytes of T.</safety>
+   unsafe
    public static Span<byte> AsBytes<T>(Span<T> span) where T : struct { throw null; }

+   /// <safety>Strips read-only protection, producing a writable Memory&lt;T&gt; over read-only data; writing through it can mutate memory presented as immutable (e.g. a string or read-only-backed buffer).</safety>
+   unsafe
    public static Memory<T> AsMemory<T>(ReadOnlyMemory<T> memory) { throw null; }

+   /// <safety>Reinterprets a byte span's contents as a T; the read may be misaligned and may include uninitialized padding.</safety>
+   unsafe
    public static ref readonly T AsRef<T>(ReadOnlySpan<byte> span) where T : struct { throw null; }

+   /// <safety>Reinterprets a byte span's contents as a writable T; the access may be misaligned and can set a pointer/reference field of T without an unsafe context.</safety>
+   unsafe
    public static ref T AsRef<T>(Span<byte> span) where T : struct { throw null; }

+   /// <safety>Reinterprets a span's elements as another type; elements may become misaligned and any padding bytes are exposed.</safety>
+   unsafe
    public static ReadOnlySpan<TTo> Cast<TFrom, TTo>(ReadOnlySpan<TFrom> span) where TFrom : struct where TTo : struct { throw null; }

+   /// <safety>Reinterprets a span's elements as another writable type; elements may become misaligned and a pointer/reference field can be set without an unsafe context.</safety>
+   unsafe
    public static Span<TTo> Cast<TFrom, TTo>(Span<TFrom> span) where TFrom : struct where TTo : struct { throw null; }

+   /// <safety>
+   /// Creates a Memory&lt;T&gt; whose Pin() does not actually pin the array (it assumes the array is already
+   /// pinned). If the array is not pinned, a pointer obtained from the result can dangle when the GC moves it.
+   /// </safety>
+   unsafe
    public static Memory<T> CreateFromPinnedArray<T>(T[]? array, int start, int length) { throw null; }

+   /// <safety>Builds a read-only span of caller-specified length over a reference with no bounds validation; the span may extend past the referenced data.</safety>
+   unsafe
    public static ReadOnlySpan<T> CreateReadOnlySpan<T>(scoped ref readonly T reference, int length) { throw null; }

+   /// <safety>Builds a writable span of caller-specified length over a reference with no bounds validation; the span may extend past the referenced data.</safety>
+   unsafe
    public static Span<T> CreateSpan<T>(scoped ref T reference, int length) { throw null; }

+   /// <safety>Returns a reference to the first array element without checking for an empty array; the reference must not be dereferenced when the array is empty.</safety>
+   unsafe
    public static ref byte GetArrayDataReference(Array array) { throw null; }

+   /// <safety>Returns a reference to the first array element without checking for an empty array; the reference must not be dereferenced when the array is empty.</safety>
+   unsafe
    public static ref T GetArrayDataReference<T>(T[] array) { throw null; }

+   /// <safety>Returns a writable reference to a read-only span's first element, stripping read-only protection, and does not check for an empty span; the reference must not be dereferenced when the span is empty, and writes through it mutate read-only data.</safety>
+   unsafe
    public static ref T GetReference<T>(ReadOnlySpan<T> span) { throw null; }

+   /// <safety>Returns a reference to the span's first element without checking for an empty span; the reference must not be dereferenced when the span is empty.</safety>
+   unsafe
    public static ref T GetReference<T>(Span<T> span) { throw null; }

+   /// <safety>Reinterprets a byte span's contents as a T; can set a pointer/reference field of T without an unsafe context.</safety>
+   unsafe
    public static T Read<T>(ReadOnlySpan<byte> source) where T : struct { throw null; }

+   /// <safety>Strips read-only protection by exposing the writable array backing a ReadOnlyMemory&lt;T&gt;; writes through it mutate data presented as read-only.</safety>
+   unsafe
    public static bool TryGetArray<T>(ReadOnlyMemory<T> memory, out ArraySegment<T> segment) { throw null; }

+   /// <safety>Strips read-only protection by exposing the backing MemoryManager, whose span is writable; writes through it mutate data presented as read-only.</safety>
+   unsafe
    public static bool TryGetMemoryManager<T, TManager>(ReadOnlyMemory<T> memory, [NotNullWhen(true)] out TManager? manager) where TManager : MemoryManager<T> { throw null; }

+   /// <safety>Strips read-only protection by exposing the backing MemoryManager, whose span is writable; writes through it mutate data presented as read-only.</safety>
+   unsafe
    public static bool TryGetMemoryManager<T, TManager>(ReadOnlyMemory<T> memory, [NotNullWhen(true)] out TManager? manager, out int start, out int length) where TManager : MemoryManager<T> { throw null; }

+   /// <safety>Reinterprets a byte span's contents as a T; can set a pointer/reference field of T without an unsafe context.</safety>
+   unsafe
    public static bool TryRead<T>(ReadOnlySpan<byte> source, out T value) where T : struct { throw null; }

+   /// <safety>Writes T's raw bytes, including any padding, into the destination span, exposing otherwise-inaccessible bytes of T.</safety>
+   unsafe
    public static bool TryWrite<T>(Span<byte> destination, in T value) where T : struct { throw null; }

+   /// <safety>Writes T's raw bytes, including any padding, into the destination span, exposing otherwise-inaccessible bytes of T.</safety>
+   unsafe
    public static void Write<T>(Span<byte> destination, in T value) where T : struct { }

    // safe:

    public static IEnumerable<T> ToEnumerable<T>(ReadOnlyMemory<T> memory) { throw null; }
    public static bool TryGetString(ReadOnlyMemory<char> memory, [NotNullWhen(true)] out string? text, out int start, out int length) { throw null; }
}

API Usage

The annotated APIs will require unsafe { } context at their call site once the language-level unsafe requirement is enforced.

Alternative Designs

No response

Risks

No response

Activity

  1. added
    api-suggestion
    on Apr 17, 2026
  2. added
    untriaged
    on Apr 17, 2026
  3. dotnet-policy-service commented on Apr 17, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/interop-contrib
    See info in area-owners.md if you want to be subscribed.

  4. tannergooding commented on Apr 20, 2026

    @tannergooding
    Member

    public static Memory<T> CreateFromPinnedArray<T>(T[]? array, int start, int length) { throw null; }

    I believe this one should be unsafe for the reasons we discussed internally. It violates an invariant and can potentially allow for an AV.

    While the actual dereference will occur by the user through a pointer (indirecting MemoryHandle.Pointer), the actual point of unsafety is in the creation from an array that we claim is pinned if it actually isn't. In safe code MemoryHandle would otherwise guarantee that there are Memory<T>.Length elements of type T accessible from the pointer, while we cannot maintain such a claim for an invalid CreateFromPinnedArray<T> call.

    public static T Read<T>(ReadOnlySpan<byte> source) where T : struct { throw null; }
    public static bool TryRead<T>(ReadOnlySpan<byte> source, out T value) where T : struct { throw null; }

    Similar here, this is unsafe because it may produce a T that has an unsafe U _field;

    public static unsafe bool TryGetArray<T>(ReadOnlyMemory<T> memory, out ArraySegment<T> segment) { throw null; }
    public static unsafe bool TryGetMemoryManager<T, TManager>(ReadOnlyMemory<T> memory, [NotNullWhen(true)] out TManager? manager) where TManager : MemoryManager<T> { throw null; }
    public static unsafe bool TryGetMemoryManager<T, TManager>(ReadOnlyMemory<T> memory, [NotNullWhen(true)] out TManager? manager, out int start, out int length) where TManager : MemoryManager<T> { throw null; }
    public static bool TryGetString(ReadOnlyMemory<char> memory, [NotNullWhen(true)] out string? text, out int start, out int length) { throw null; }

    It isn't clear why these would be unsafe. They aren't violating any invariants of ROMemory<T> and only return the backing storage if it could be recovered. That may create an alias to the backing storage, but no more than just holding on to the original may have already done.

    Essentially beware dragons and potential data races, but no potential for AVs or violating things.


    The other annotations and addition of unsafe look correct.

  5. agocke commented on Apr 20, 2026

    @agocke
    Member

    I think we need comments for each of these -- to explain what's unsafe and what's needed by the caller to make the call sound.

  6. added
    api-ready-for-review
    and removed
    api-suggestion
    untriaged
    on Jun 23, 2026
  7. added this to the 11.0.0 milestone on Jun 23, 2026
  8. bartonjs commented on Jul 7, 2026

    @bartonjs
    Member

    Video

    Looks good as proposed.

    public static partial class MemoryMarshal
    {
    +   unsafe
        public static ReadOnlySpan<byte> AsBytes<T>(ReadOnlySpan<T> span) where T : struct { throw null; }
    
    +   unsafe
        public static Span<byte> AsBytes<T>(Span<T> span) where T : struct { throw null; }
    
    +   unsafe
        public static Memory<T> AsMemory<T>(ReadOnlyMemory<T> memory) { throw null; }
    
    +   unsafe
        public static ref readonly T AsRef<T>(ReadOnlySpan<byte> span) where T : struct { throw null; }
    
    +   unsafe
        public static ref T AsRef<T>(Span<byte> span) where T : struct { throw null; }
    
    +   unsafe
        public static ReadOnlySpan<TTo> Cast<TFrom, TTo>(ReadOnlySpan<TFrom> span) where TFrom : struct where TTo : struct { throw null; }
    
    +   unsafe
        public static Span<TTo> Cast<TFrom, TTo>(Span<TFrom> span) where TFrom : struct where TTo : struct { throw null; }
    
    +   unsafe
        public static Memory<T> CreateFromPinnedArray<T>(T[]? array, int start, int length) { throw null; }
    
    +   unsafe
        public static ReadOnlySpan<T> CreateReadOnlySpan<T>(scoped ref readonly T reference, int length) { throw null; }
    
    +   unsafe
        public static Span<T> CreateSpan<T>(scoped ref T reference, int length) { throw null; }
    
    +   unsafe
        public static ref byte GetArrayDataReference(Array array) { throw null; }
    
    +   unsafe
        public static ref T GetArrayDataReference<T>(T[] array) { throw null; }
    
    +   unsafe
        public static ref T GetReference<T>(ReadOnlySpan<T> span) { throw null; }
    
    +   unsafe
        public static ref T GetReference<T>(Span<T> span) { throw null; }
    
    +   unsafe
        public static T Read<T>(ReadOnlySpan<byte> source) where T : struct { throw null; }
    
    +   unsafe
        public static bool TryGetArray<T>(ReadOnlyMemory<T> memory, out ArraySegment<T> segment) { throw null; }
    
    +   unsafe
        public static bool TryGetMemoryManager<T, TManager>(ReadOnlyMemory<T> memory, [NotNullWhen(true)] out TManager? manager) where TManager : MemoryManager<T> { throw null; }
    
    +   unsafe
        public static bool TryGetMemoryManager<T, TManager>(ReadOnlyMemory<T> memory, [NotNullWhen(true)] out TManager? manager, out int start, out int length) where TManager : MemoryManager<T> { throw null; }
    
    +   unsafe
        public static bool TryRead<T>(ReadOnlySpan<byte> source, out T value) where T : struct { throw null; }
    
    +   unsafe
        public static bool TryWrite<T>(Span<byte> destination, in T value) where T : struct { throw null; }
    
    +   unsafe
        public static void Write<T>(Span<byte> destination, in T value) where T : struct { }
    }
  9. added
    api-approved
    and removed
    api-ready-for-review
    on Jul 7, 2026
  10. agocke commented on Aug 14, 2026

    @agocke
    Member

    Fixed by #131733

  11. locked and limited conversation to collaborators on Sep 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedarea-System.Runtime.InteropServicesreduce-unsafe

    Type

    No type

    Projects

    • Status
      No status

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions