Skip to content

Fatal error. Internal CLR error when working with image created by pointer-based overload of Image.WrapMemory<TPixel> #2779

Description

@KirillAldashkin

Prerequisites

  • I have written a descriptive issue title
  • I have verified that I am running the latest version of ImageSharp
  • I have verified if the problem exist in both DEBUG and RELEASE mode
  • I have searched open and closed issues to ensure it has not already been reported

ImageSharp version

3.1.5

Other ImageSharp packages and versions

none

Environment (Operating system, version and so on)

Windows 11 23H2 22631.3880

.NET Framework version

.NET SDK 8.0

Description

This happens when using WrapMemory<TPixel>(void* pointer, int bufferSizeInBytes, int width, int height) and passing buffer that is too small for given width, height and TPixel even with correct bufferSizeInBytes value

Expected behaviour

Exception saying that given buffer is too small for given image size and pixel format

Actual behaviour

Fatal error. Internal CLR error

Steps to Reproduce

Run this code

using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using System.Runtime.InteropServices;

unsafe
{
    // these two lines are correct: no overflow ("checked") and no overrun ("bufferSize" is used)
    int bufferSize = checked(8192 * 8192);
    void* data = NativeMemory.Alloc(checked((nuint)bufferSize));
    // passing correct buffer size
    using Image<Rgba64> img = Image.WrapMemory<Rgba64>(data, bufferSize, 8192, 8192);
    // oops!
    img.SaveAsPng("output.png");
    // already crashed at this point
    NativeMemory.Free(data);
}

Images

No response

Activity

  1. KirillAldashkin commented on Jul 22, 2024

    @KirillAldashkin
    ContributorAuthor

    Already found the reason:

    Guard.MustBeGreaterThanOrEqualTo(bufferSizeInBytes, memoryManager.Memory.Span.Length, nameof(bufferSizeInBytes));

    bufferSizeInBytes (in bytes) is compared with memoryManager.Memory.Span.Length (in pixels).
    X bytes is smaller than X multibyte pixels so it overruns passed buffer

  2. added a commit that references this issue on Jul 26, 2024
    57ecebf
  3. added 2 commits that reference this issue on Oct 16, 2024
    911480d
    e69a507
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions