Skip to content

Question: What is our policy regarding API support of unaligned spans? #44497

Closed

Description

@GrabYourPitchforks

Scenario: Let's say that somebody creates a Span<T> where the addresses are not properly aligned for type T. As far as I'm aware this can only be done via unsafe code (new Span<T>(<unaligned ptr>)) or unsafe-equivalent code (MemoryMarshal.Cast or MemoryMarshal.CreateSpan(<ref to unaligned field>).

Question: What guarantees should our in-box APIs make when such spans are provided as input?

For example, MemoryExtensions.IndexOf contains special-cased logic to handle unaligned ReadOnlySpan<char> on all platforms, but it doesn't contain special logic for things like unaligned ReadOnlySpan<float>. Depending on the current architecture, such accesses could fault.

As another example, UTF8Encoding.GetBytes(ReadOnlySpan<char>) assumes that the input is always char-aligned, and it could fault or return nonsensical answers if given unaligned input, even on x86 processors.

Is our default stance that all APIs which accept Span<T>, ref T, and similar should guard against misaligned addresses? Or that consumers must assume that misaligned spans do not work unless they API they're calling has been documented as allowing these?

Activity

  1. added
    questionAnswer questions and provide assistance, not an issue with source code or documentation.
    on Nov 10, 2020
  2. jkotas commented on Nov 11, 2020

    @jkotas
    Member

    MemoryExtensions.IndexOf contains special-cased logic to handle unaligned ReadOnlySpan

    IIRC, this was done to allow IndexOf to be repurposed as wcslen. APIs that take zero-terminated strings always handled misaligned pointers gracefully and we had tests that failed without it.

    consumers must assume that misaligned spans do not work unless they API they're calling has been documented as allowing these

    Correct, pointers are assumed to be aligned according to the platform rules.

    As usual, we may find that code out there depends on undocumented behaviors that we treat case-by-case.

  3. GrabYourPitchforks commented on Nov 12, 2020

    @GrabYourPitchforks
    MemberAuthor

    Thank you for the response. :)
    If I see any other questions regarding this I'll redirect them to this thread.

  4. ghost locked as resolved and limited conversation to collaborators on Dec 12, 2020
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

    area-MetaquestionAnswer questions and provide assistance, not an issue with source code or documentation.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions