diff --git a/src/ImageSharp/Formats/Jpeg/Components/Decoder/ComponentProcessors/ComponentProcessor.cs b/src/ImageSharp/Formats/Jpeg/Components/Decoder/ComponentProcessors/ComponentProcessor.cs index f0cc4d5e82..3bdaf2dc27 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/Decoder/ComponentProcessors/ComponentProcessor.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/Decoder/ComponentProcessors/ComponentProcessor.cs @@ -16,7 +16,7 @@ public ComponentProcessor(MemoryAllocator memoryAllocator, JpegFrame frame, Size this.Component = component; this.BlockAreaSize = component.SubSamplingDivisors * blockSize; - this.ColorBuffer = memoryAllocator.Allocate2DOveraligned( + this.ColorBuffer = memoryAllocator.Allocate2DOverAligned( postProcessorBufferSize.Width, postProcessorBufferSize.Height, this.BlockAreaSize.Height); diff --git a/src/ImageSharp/Formats/Jpeg/Components/Encoder/ComponentProcessor.cs b/src/ImageSharp/Formats/Jpeg/Components/Encoder/ComponentProcessor.cs index c33a8a1968..9346b11e7b 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/Encoder/ComponentProcessor.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/Encoder/ComponentProcessor.cs @@ -28,7 +28,7 @@ public ComponentProcessor(MemoryAllocator memoryAllocator, Component component, this.blockAreaSize = component.SubSamplingDivisors * 8; // alignment of 8 so each block stride can be sampled from a single 'ref pointer' - this.ColorBuffer = memoryAllocator.Allocate2DOveraligned( + this.ColorBuffer = memoryAllocator.Allocate2DOverAligned( postProcessorBufferSize.Width, postProcessorBufferSize.Height, 8, diff --git a/src/ImageSharp/Formats/Png/PngDecoderCore.cs b/src/ImageSharp/Formats/Png/PngDecoderCore.cs index a96c53c104..abd5cadeb1 100644 --- a/src/ImageSharp/Formats/Png/PngDecoderCore.cs +++ b/src/ImageSharp/Formats/Png/PngDecoderCore.cs @@ -1968,6 +1968,9 @@ private IMemoryOwner ReadChunkData(int length) } // We rent the buffer here to return it afterwards in Decode() + // We don't want to throw a degenerated memory exception here as we want to allow partial decoding + // so limit the length. + length = (int)Math.Min(length, this.currentStream.Length - this.currentStream.Position); IMemoryOwner buffer = this.configuration.MemoryAllocator.Allocate(length, AllocationOptions.Clean); this.currentStream.Read(buffer.GetSpan(), 0, length); diff --git a/src/ImageSharp/Memory/Allocators/MemoryAllocator.cs b/src/ImageSharp/Memory/Allocators/MemoryAllocator.cs index 2bd9cb5eef..6a2cf79c7c 100644 --- a/src/ImageSharp/Memory/Allocators/MemoryAllocator.cs +++ b/src/ImageSharp/Memory/Allocators/MemoryAllocator.cs @@ -2,6 +2,8 @@ // Licensed under the Six Labors Split License. using System.Buffers; +using System.Runtime.CompilerServices; +using SixLabors.ImageSharp.PixelFormats; namespace SixLabors.ImageSharp.Memory; @@ -10,6 +12,16 @@ namespace SixLabors.ImageSharp.Memory; /// public abstract class MemoryAllocator { + /// + /// Gets the default max allocatable size of a 1D buffer in bytes. + /// + public static readonly int DefaultMaxAllocatableSize1DInBytes = GetDefaultMaxAllocatableSize1DInBytes(); + + /// + /// Gets the default max allocatable size of a 2D buffer in bytes. + /// + public static readonly ulong DefaultMaxAllocatableSize2DInBytes = GetDefaultMaxAllocatableSize2DInBytes(); + /// /// Gets the default platform-specific global instance that /// serves as the default value for . @@ -20,6 +32,18 @@ public abstract class MemoryAllocator /// public static MemoryAllocator Default { get; } = Create(); + /// + /// Gets or sets the maximum allowable allocatable size of a 2 dimensional buffer. + /// Defaults to . + /// + public ulong MaxAllocatableSize2DInBytes { get; set; } = DefaultMaxAllocatableSize2DInBytes; + + /// + /// Gets or sets the maximum allowable allocatable size of a 1 dimensional buffer. + /// + /// Defaults to . + public int MaxAllocatableSize1DInBytes { get; set; } = DefaultMaxAllocatableSize1DInBytes; + /// /// Gets the length of the largest contiguous buffer that can be handled by this allocator instance in bytes. /// @@ -42,7 +66,7 @@ public static MemoryAllocator Create(MemoryAllocatorOptions options) => new UniformUnmanagedMemoryPoolMemoryAllocator(options.MaximumPoolSizeMegabytes); /// - /// Allocates an , holding a of length . + /// Allocates an , holding a of length . /// /// Type of the data stored in the buffer. /// Size of the buffer to allocate. @@ -64,6 +88,7 @@ public virtual void ReleaseRetainedResources() /// /// Allocates a . /// + /// Type of the data stored in the buffer. /// The total length of the buffer. /// The expected alignment (eg. to make sure image rows fit into single buffers). /// The . @@ -75,4 +100,61 @@ internal virtual MemoryGroup AllocateGroup( AllocationOptions options = AllocationOptions.None) where T : struct => MemoryGroup.Allocate(this, totalLength, bufferAlignment, options); + + internal void MemoryGuardAllocation2D(Size value, string paramName) + where T : struct + { + if (value.Width < 0 || value.Height < 0) + { + throw new InvalidMemoryOperationException($"An allocation was attempted that exceeded allowable limits; \"{paramName}\" at {value.Width}x{value.Height}"); + } + + ulong typeSizeInBytes = (ulong)Unsafe.SizeOf(); + ulong valueInBytes = (ulong)value.Width * typeSizeInBytes * (ulong)value.Height; + + if (valueInBytes <= this.MaxAllocatableSize2DInBytes) + { + return; + } + + throw new InvalidMemoryOperationException( + $"An allocation was attempted that exceeded allowable limits; \"{paramName}\" at {value.Width}x{value.Height} must be less than or equal to {this.MaxAllocatableSize2DInBytes}, was {valueInBytes}"); + } + + internal void MemoryGuardAllocation1D(int value, string paramName) + where T : struct + { + if (value < 0) + { + throw new InvalidMemoryOperationException($"An allocation was attempted that exceeded allowable limits; {paramName} must be greater than or equal to zero, was {value}"); + } + + ulong typeSizeInBytes = (ulong)Unsafe.SizeOf(); + ulong valueInBytes = (ulong)value * typeSizeInBytes; + + if (valueInBytes <= (ulong)this.MaxAllocatableSize1DInBytes) + { + return; + } + + throw new InvalidMemoryOperationException( + $"An allocation was attempted that exceeded allowable limits; \"{paramName}\" must be less than or equal {this.MaxAllocatableSize1DInBytes}, was {valueInBytes}"); + } + + private static ulong GetDefaultMaxAllocatableSize2DInBytes() + { + // Limit dimensions to 32767x32767 and 16383x16383 @ 4 bytes per pixel for 64 and 32 bit processes respectively. + ulong maxLength = Environment.Is64BitProcess ? ushort.MaxValue / 2 : (ulong)short.MaxValue / 4; + return maxLength * (ulong)Unsafe.SizeOf() * maxLength; + } + + private static int GetDefaultMaxAllocatableSize1DInBytes() + { + // It's possible to require buffers that are not related to image dimensions. + // For example, when we need to allocate buffers for IDAT chunks in PNG files or when allocating + // cache buffers for image quantization. + // Limit the maximum buffer size to 64MB for 64-bit processes and 32MB for 32-bit processes. + int limitInMB = Environment.Is64BitProcess ? 64 : 32; + return limitInMB * 1024 * 1024; + } } diff --git a/src/ImageSharp/Memory/Allocators/SimpleGcMemoryAllocator.cs b/src/ImageSharp/Memory/Allocators/SimpleGcMemoryAllocator.cs index 41730d9678..a5f7499ed4 100644 --- a/src/ImageSharp/Memory/Allocators/SimpleGcMemoryAllocator.cs +++ b/src/ImageSharp/Memory/Allocators/SimpleGcMemoryAllocator.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System.Buffers; @@ -7,17 +7,17 @@ namespace SixLabors.ImageSharp.Memory; /// -/// Implements by newing up managed arrays on every allocation request. +/// Implements by creating new managed arrays on every allocation request. /// public sealed class SimpleGcMemoryAllocator : MemoryAllocator { /// - protected internal override int GetBufferCapacityInBytes() => int.MaxValue; + protected internal override int GetBufferCapacityInBytes() => this.MaxAllocatableSize1DInBytes; /// public override IMemoryOwner Allocate(int length, AllocationOptions options = AllocationOptions.None) { - Guard.MustBeGreaterThanOrEqualTo(length, 0, nameof(length)); + this.MemoryGuardAllocation1D(length, nameof(length)); return new BasicArrayBuffer(new T[length]); } diff --git a/src/ImageSharp/Memory/Allocators/UniformUnmanagedMemoryPoolMemoryAllocator.cs b/src/ImageSharp/Memory/Allocators/UniformUnmanagedMemoryPoolMemoryAllocator.cs index 0bae193632..47cfaad351 100644 --- a/src/ImageSharp/Memory/Allocators/UniformUnmanagedMemoryPoolMemoryAllocator.cs +++ b/src/ImageSharp/Memory/Allocators/UniformUnmanagedMemoryPoolMemoryAllocator.cs @@ -79,16 +79,14 @@ internal UniformUnmanagedMemoryPoolMemoryAllocator( protected internal override int GetBufferCapacityInBytes() => this.poolBufferSizeInBytes; /// - public override IMemoryOwner Allocate( - int length, - AllocationOptions options = AllocationOptions.None) + public override IMemoryOwner Allocate(int length, AllocationOptions options = AllocationOptions.None) { - Guard.MustBeGreaterThanOrEqualTo(length, 0, nameof(length)); + this.MemoryGuardAllocation1D(length, nameof(length)); int lengthInBytes = length * Unsafe.SizeOf(); if (lengthInBytes <= this.sharedArrayPoolThresholdInBytes) { - var buffer = new SharedArrayPoolBuffer(length); + SharedArrayPoolBuffer buffer = new(length); if (options.Has(AllocationOptions.Clean)) { buffer.GetSpan().Clear(); @@ -102,8 +100,7 @@ public override IMemoryOwner Allocate( UnmanagedMemoryHandle mem = this.pool.Rent(); if (mem.IsValid) { - UnmanagedBuffer buffer = this.pool.CreateGuardedBuffer(mem, length, options.Has(AllocationOptions.Clean)); - return buffer; + return this.pool.CreateGuardedBuffer(mem, length, options.Has(AllocationOptions.Clean)); } } @@ -124,7 +121,7 @@ internal override MemoryGroup AllocateGroup( if (totalLengthInBytes <= this.sharedArrayPoolThresholdInBytes) { - var buffer = new SharedArrayPoolBuffer((int)totalLength); + SharedArrayPoolBuffer buffer = new((int)totalLength); return MemoryGroup.CreateContiguous(buffer, options.Has(AllocationOptions.Clean)); } diff --git a/src/ImageSharp/Memory/Allocators/UnmanagedMemoryAllocator.cs b/src/ImageSharp/Memory/Allocators/UnmanagedMemoryAllocator.cs index da202aa596..99a6e5b1ff 100644 --- a/src/ImageSharp/Memory/Allocators/UnmanagedMemoryAllocator.cs +++ b/src/ImageSharp/Memory/Allocators/UnmanagedMemoryAllocator.cs @@ -20,7 +20,9 @@ internal class UnmanagedMemoryAllocator : MemoryAllocator public override IMemoryOwner Allocate(int length, AllocationOptions options = AllocationOptions.None) { - var buffer = UnmanagedBuffer.Allocate(length); + this.MemoryGuardAllocation1D(length, nameof(length)); + + UnmanagedBuffer buffer = UnmanagedBuffer.Allocate(length); if (options.Has(AllocationOptions.Clean)) { buffer.GetSpan().Clear(); diff --git a/src/ImageSharp/Memory/MemoryAllocatorExtensions.cs b/src/ImageSharp/Memory/MemoryAllocatorExtensions.cs index ff306e1e45..add27ea717 100644 --- a/src/ImageSharp/Memory/MemoryAllocatorExtensions.cs +++ b/src/ImageSharp/Memory/MemoryAllocatorExtensions.cs @@ -18,20 +18,22 @@ public static class MemoryAllocatorExtensions /// The memory allocator. /// The buffer width. /// The buffer height. - /// A value indicating whether the allocated buffer should be contiguous, unless bigger than . + /// A value indicating whether the allocated buffer should be contiguous, unless bigger than . /// The allocation options. /// The . public static Buffer2D Allocate2D( this MemoryAllocator memoryAllocator, int width, int height, - bool preferContiguosImageBuffers, + bool preferContiguousImageBuffers, AllocationOptions options = AllocationOptions.None) where T : struct { + memoryAllocator.MemoryGuardAllocation2D(new Size(width, height), "size"); + long groupLength = (long)width * height; MemoryGroup memoryGroup; - if (preferContiguosImageBuffers && groupLength < int.MaxValue) + if (preferContiguousImageBuffers && groupLength < int.MaxValue) { IMemoryOwner buffer = memoryAllocator.Allocate((int)groupLength, options); memoryGroup = MemoryGroup.CreateContiguous(buffer, false); @@ -69,16 +71,16 @@ public static Buffer2D Allocate2D( /// The type of buffer items to allocate. /// The memory allocator. /// The buffer size. - /// A value indicating whether the allocated buffer should be contiguous, unless bigger than . + /// A value indicating whether the allocated buffer should be contiguous, unless bigger than . /// The allocation options. /// The . public static Buffer2D Allocate2D( this MemoryAllocator memoryAllocator, Size size, - bool preferContiguosImageBuffers, + bool preferContiguousImageBuffers, AllocationOptions options = AllocationOptions.None) where T : struct => - Allocate2D(memoryAllocator, size.Width, size.Height, preferContiguosImageBuffers, options); + Allocate2D(memoryAllocator, size.Width, size.Height, preferContiguousImageBuffers, options); /// /// Allocates a buffer of value type objects interpreted as a 2D region @@ -96,7 +98,7 @@ public static Buffer2D Allocate2D( where T : struct => Allocate2D(memoryAllocator, size.Width, size.Height, false, options); - internal static Buffer2D Allocate2DOveraligned( + internal static Buffer2D Allocate2DOverAligned( this MemoryAllocator memoryAllocator, int width, int height, @@ -104,6 +106,8 @@ internal static Buffer2D Allocate2DOveraligned( AllocationOptions options = AllocationOptions.None) where T : struct { + memoryAllocator.MemoryGuardAllocation2D(new Size(width, height), "size"); + long groupLength = (long)width * height; MemoryGroup memoryGroup = memoryAllocator.AllocateGroup( groupLength, @@ -127,6 +131,7 @@ internal static IMemoryOwner AllocatePaddedPixelRowBuffer( int paddingInBytes) { int length = (width * pixelSizeInBytes) + paddingInBytes; + memoryAllocator.MemoryGuardAllocation1D(length, nameof(length)); return memoryAllocator.Allocate(length); } } diff --git a/src/ImageSharp/Processing/Processors/Transforms/Resize/ResizeKernelMap.cs b/src/ImageSharp/Processing/Processors/Transforms/Resize/ResizeKernelMap.cs index c1907bb520..da26cbefcd 100644 --- a/src/ImageSharp/Processing/Processors/Transforms/Resize/ResizeKernelMap.cs +++ b/src/ImageSharp/Processing/Processors/Transforms/Resize/ResizeKernelMap.cs @@ -50,7 +50,7 @@ private ResizeKernelMap( this.sourceLength = sourceLength; this.DestinationLength = destinationLength; this.MaxDiameter = (radius * 2) + 1; - this.data = memoryAllocator.Allocate2D(this.MaxDiameter, bufferHeight, preferContiguosImageBuffers: true, AllocationOptions.Clean); + this.data = memoryAllocator.Allocate2D(this.MaxDiameter, bufferHeight, preferContiguousImageBuffers: true, AllocationOptions.Clean); this.pinHandle = this.data.DangerousGetSingleMemory().Pin(); this.kernels = new ResizeKernel[destinationLength]; this.tempValues = new double[this.MaxDiameter]; diff --git a/src/ImageSharp/Processing/Processors/Transforms/Resize/ResizeWorker.cs b/src/ImageSharp/Processing/Processors/Transforms/Resize/ResizeWorker.cs index cce27a401c..fd13d7b5a6 100644 --- a/src/ImageSharp/Processing/Processors/Transforms/Resize/ResizeWorker.cs +++ b/src/ImageSharp/Processing/Processors/Transforms/Resize/ResizeWorker.cs @@ -83,7 +83,7 @@ public ResizeWorker( this.transposedFirstPassBuffer = configuration.MemoryAllocator.Allocate2D( this.workerHeight, targetWorkingRect.Width, - preferContiguosImageBuffers: true, + preferContiguousImageBuffers: true, options: AllocationOptions.Clean); this.tempRowBuffer = configuration.MemoryAllocator.Allocate(this.sourceRectangle.Width); diff --git a/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs index e76f21d0e9..7e89bc1ea6 100644 --- a/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs @@ -558,4 +558,13 @@ public void BmpDecoder_CanDecode_Os2BitmapArray(TestImageProvider(TestImageProvider provider) + where TPixel : unmanaged, IPixel + => Assert.Throws(() => + { + using Image image = provider.GetImage(BmpDecoder.Instance); + }); } diff --git a/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs index 42cbd90f3b..00cf0b984a 100644 --- a/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs @@ -3,6 +3,7 @@ using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Formats.Bmp; +using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.Metadata; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; @@ -348,14 +349,21 @@ public void Encode_PreservesColorProfile(TestImageProvider provi Assert.Equal(expectedProfileBytes, actualProfileBytes); } + public static TheoryData Encode_WorksWithSizeGreaterThen65k_Data { get; set; } = new() + { + { new Size(65535, 1) }, + { new Size(1, 65535) }, + }; + [Theory] - [InlineData(1, 66535)] - [InlineData(66535, 1)] - public void Encode_WorksWithSizeGreaterThen65k(int width, int height) + [MemberData(nameof(Encode_WorksWithSizeGreaterThen65k_Data))] + public void Encode_WorksWithSizeGreaterThen65k(Size size) { Exception exception = Record.Exception(() => { - using Image image = new Image(width, height); + Configuration configuration = Configuration.CreateDefaultInstance(); + configuration.MemoryAllocator = new UniformUnmanagedMemoryPoolMemoryAllocator(null) { MaxAllocatableSize2DInBytes = ulong.MaxValue }; + using Image image = new Image(configuration, size.Width, size.Height); using MemoryStream memStream = new(); image.Save(memStream, BmpEncoder); }); diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs index 6a94a98ac6..dbfd1c1c20 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs @@ -338,21 +338,10 @@ public void Issue2564_DecodeWorks(TestImageProvider provider) } [Theory] - [WithFile(TestImages.Jpeg.Issues.HangBadScan, PixelTypes.L8)] - public void DecodeHang(TestImageProvider provider) + [WithFile(TestImages.Jpeg.Issues.HangBadScan, PixelTypes.Rgba32)] + public void DecodeHang_ThrowsException(TestImageProvider provider) where TPixel : unmanaged, IPixel - { - if (TestEnvironment.IsWindows && - TestEnvironment.RunsOnCI) - { - // Windows CI runs consistently fail with OOM. - return; - } - - using Image image = provider.GetImage(JpegDecoder.Instance); - Assert.Equal(65503, image.Width); - Assert.Equal(65503, image.Height); - } + => Assert.Throws(() => { using Image image = provider.GetImage(JpegDecoder.Instance); }); // https://github.com/SixLabors/ImageSharp/issues/2517 [Theory] diff --git a/tests/ImageSharp.Tests/Memory/Allocators/SimpleGcMemoryAllocatorTests.cs b/tests/ImageSharp.Tests/Memory/Allocators/SimpleGcMemoryAllocatorTests.cs index 780ba7f20e..405ed13754 100644 --- a/tests/ImageSharp.Tests/Memory/Allocators/SimpleGcMemoryAllocatorTests.cs +++ b/tests/ImageSharp.Tests/Memory/Allocators/SimpleGcMemoryAllocatorTests.cs @@ -17,20 +17,23 @@ public BufferTests() } } - protected SimpleGcMemoryAllocator MemoryAllocator { get; } = new SimpleGcMemoryAllocator(); + protected SimpleGcMemoryAllocator TestMemoryAllocator { get; } = new SimpleGcMemoryAllocator(); + + public static TheoryData InvalidLengths { get; set; } = new() + { + { -1 }, + { MemoryAllocator.DefaultMaxAllocatableSize1DInBytes + 1 } + }; [Theory] - [InlineData(-1)] + [MemberData(nameof(InvalidLengths))] public void Allocate_IncorrectAmount_ThrowsCorrect_ArgumentOutOfRangeException(int length) - { - ArgumentOutOfRangeException ex = Assert.Throws(() => this.MemoryAllocator.Allocate(length)); - Assert.Equal("length", ex.ParamName); - } + => Assert.Throws(() => this.TestMemoryAllocator.Allocate(length)); [Fact] public unsafe void Allocate_MemoryIsPinnableMultipleTimes() { - SimpleGcMemoryAllocator allocator = this.MemoryAllocator; + SimpleGcMemoryAllocator allocator = this.TestMemoryAllocator; using IMemoryOwner memoryOwner = allocator.Allocate(100); using (MemoryHandle pin = memoryOwner.Memory.Pin()) diff --git a/tests/ImageSharp.Tests/Memory/Allocators/UniformUnmanagedPoolMemoryAllocatorTests.cs b/tests/ImageSharp.Tests/Memory/Allocators/UniformUnmanagedPoolMemoryAllocatorTests.cs index 7e7c136635..f8006a35d7 100644 --- a/tests/ImageSharp.Tests/Memory/Allocators/UniformUnmanagedPoolMemoryAllocatorTests.cs +++ b/tests/ImageSharp.Tests/Memory/Allocators/UniformUnmanagedPoolMemoryAllocatorTests.cs @@ -114,6 +114,17 @@ public void AllocateGroup_SizeInBytesOverLongMaxValue_ThrowsInvalidMemoryOperati Assert.Throws(() => allocator.AllocateGroup(int.MaxValue * (long)int.MaxValue, int.MaxValue)); } + public static TheoryData InvalidLengths { get; set; } = new() + { + { -1 }, + { MemoryAllocator.DefaultMaxAllocatableSize1DInBytes + 1 } + }; + + [Theory] + [MemberData(nameof(InvalidLengths))] + public void Allocate_IncorrectAmount_ThrowsCorrect_ArgumentOutOfRangeException(int length) + => Assert.Throws(() => new UniformUnmanagedMemoryPoolMemoryAllocator(null).Allocate(length)); + [Fact] public unsafe void Allocate_MemoryIsPinnableMultipleTimes() { diff --git a/tests/ImageSharp.Tests/Memory/Buffer2DTests.cs b/tests/ImageSharp.Tests/Memory/Buffer2DTests.cs index 5364de0652..00c09b87a6 100644 --- a/tests/ImageSharp.Tests/Memory/Buffer2DTests.cs +++ b/tests/ImageSharp.Tests/Memory/Buffer2DTests.cs @@ -4,6 +4,7 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using SixLabors.ImageSharp.Memory; +using SixLabors.ImageSharp.PixelFormats; // ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Memory; @@ -23,7 +24,7 @@ public static void SpanPointsTo(Span span, Memory buffer, int bufferOff } } - private TestMemoryAllocator MemoryAllocator { get; } = new TestMemoryAllocator(); + private TestMemoryAllocator TestMemoryAllocator { get; } = new TestMemoryAllocator(); private const int Big = 99999; @@ -33,9 +34,9 @@ public static void SpanPointsTo(Span span, Memory buffer, int bufferOff [InlineData(300, 42, 777)] public unsafe void Construct(int bufferCapacity, int width, int height) { - this.MemoryAllocator.BufferCapacityInBytes = sizeof(TestStructs.Foo) * bufferCapacity; + this.TestMemoryAllocator.BufferCapacityInBytes = sizeof(TestStructs.Foo) * bufferCapacity; - using (Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height)) + using (Buffer2D buffer = this.TestMemoryAllocator.Allocate2D(width, height)) { Assert.Equal(width, buffer.Width); Assert.Equal(height, buffer.Height); @@ -51,9 +52,9 @@ public unsafe void Construct(int bufferCapacity, int width, int height) [InlineData(3, 0, 0)] public unsafe void Construct_Empty(int bufferCapacity, int width, int height) { - this.MemoryAllocator.BufferCapacityInBytes = sizeof(TestStructs.Foo) * bufferCapacity; + this.TestMemoryAllocator.BufferCapacityInBytes = sizeof(TestStructs.Foo) * bufferCapacity; - using (Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height)) + using (Buffer2D buffer = this.TestMemoryAllocator.Allocate2D(width, height)) { Assert.Equal(width, buffer.Width); Assert.Equal(height, buffer.Height); @@ -67,16 +68,16 @@ public unsafe void Construct_Empty(int bufferCapacity, int width, int height) [InlineData(true)] public void Construct_PreferContiguousImageBuffers_AllocatesContiguousRegardlessOfCapacity(bool useSizeOverload) { - this.MemoryAllocator.BufferCapacityInBytes = 10_000; + this.TestMemoryAllocator.BufferCapacityInBytes = 10_000; using Buffer2D buffer = useSizeOverload ? - this.MemoryAllocator.Allocate2D( + this.TestMemoryAllocator.Allocate2D( new Size(200, 200), - preferContiguosImageBuffers: true) : - this.MemoryAllocator.Allocate2D( + preferContiguousImageBuffers: true) : + this.TestMemoryAllocator.Allocate2D( 200, 200, - preferContiguosImageBuffers: true); + preferContiguousImageBuffers: true); Assert.Equal(1, buffer.FastMemoryGroup.Count); Assert.Equal(200 * 200, buffer.FastMemoryGroup.TotalLength); } @@ -85,9 +86,9 @@ public void Construct_PreferContiguousImageBuffers_AllocatesContiguousRegardless [InlineData(50, 10, 20, 4)] public void Allocate2DOveraligned(int bufferCapacity, int width, int height, int alignmentMultiplier) { - this.MemoryAllocator.BufferCapacityInBytes = sizeof(int) * bufferCapacity; + this.TestMemoryAllocator.BufferCapacityInBytes = sizeof(int) * bufferCapacity; - using Buffer2D buffer = this.MemoryAllocator.Allocate2DOveraligned(width, height, alignmentMultiplier); + using Buffer2D buffer = this.TestMemoryAllocator.Allocate2DOverAligned(width, height, alignmentMultiplier); MemoryGroup memoryGroup = buffer.FastMemoryGroup; int expectedAlignment = width * alignmentMultiplier; @@ -97,7 +98,7 @@ public void Allocate2DOveraligned(int bufferCapacity, int width, int height, int [Fact] public void CreateClean() { - using (Buffer2D buffer = this.MemoryAllocator.Allocate2D(42, 42, AllocationOptions.Clean)) + using (Buffer2D buffer = this.TestMemoryAllocator.Allocate2D(42, 42, AllocationOptions.Clean)) { Span span = buffer.DangerousGetSingleSpan(); for (int j = 0; j < span.Length; j++) @@ -117,9 +118,9 @@ public void CreateClean() [InlineData(200, 100, 30, 4, 2)] public unsafe void DangerousGetRowSpan_TestAllocator(int bufferCapacity, int width, int height, int y, int expectedBufferIndex) { - this.MemoryAllocator.BufferCapacityInBytes = sizeof(TestStructs.Foo) * bufferCapacity; + this.TestMemoryAllocator.BufferCapacityInBytes = sizeof(TestStructs.Foo) * bufferCapacity; - using (Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height)) + using (Buffer2D buffer = this.TestMemoryAllocator.Allocate2D(width, height)) { Span span = buffer.DangerousGetRowSpan(y); @@ -194,8 +195,8 @@ public unsafe void DangerousGetRowSpan_UnmanagedAllocator(int width, int height) [InlineData(30, 4, 1, -1)] public void TryGetPaddedRowSpanY(int bufferCapacity, int y, int padding, int expectedBufferIndex) { - this.MemoryAllocator.BufferCapacityInBytes = bufferCapacity; - using Buffer2D buffer = this.MemoryAllocator.Allocate2D(3, 5); + this.TestMemoryAllocator.BufferCapacityInBytes = bufferCapacity; + using Buffer2D buffer = this.TestMemoryAllocator.Allocate2D(3, 5); bool expectSuccess = expectedBufferIndex >= 0; bool success = buffer.DangerousTryGetPaddedRowSpan(y, padding, out Span paddedSpan); @@ -219,8 +220,8 @@ public void TryGetPaddedRowSpanY(int bufferCapacity, int y, int padding, int exp [MemberData(nameof(GetRowSpanY_OutOfRange_Data))] public void GetRowSpan_OutOfRange(int bufferCapacity, int width, int height, int y) { - this.MemoryAllocator.BufferCapacityInBytes = bufferCapacity; - using Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height); + this.TestMemoryAllocator.BufferCapacityInBytes = bufferCapacity; + using Buffer2D buffer = this.TestMemoryAllocator.Allocate2D(width, height); Exception ex = Assert.ThrowsAny(() => buffer.DangerousGetRowSpan(y)); Assert.True(ex is ArgumentOutOfRangeException || ex is IndexOutOfRangeException); @@ -242,8 +243,8 @@ public void GetRowSpan_OutOfRange(int bufferCapacity, int width, int height, int [MemberData(nameof(Indexer_OutOfRange_Data))] public void Indexer_OutOfRange(int bufferCapacity, int width, int height, int x, int y) { - this.MemoryAllocator.BufferCapacityInBytes = bufferCapacity; - using Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height); + this.TestMemoryAllocator.BufferCapacityInBytes = bufferCapacity; + using Buffer2D buffer = this.TestMemoryAllocator.Allocate2D(width, height); Exception ex = Assert.ThrowsAny(() => buffer[x, y]++); Assert.True(ex is ArgumentOutOfRangeException || ex is IndexOutOfRangeException); @@ -257,9 +258,9 @@ public void Indexer_OutOfRange(int bufferCapacity, int width, int height, int x, [InlineData(500, 200, 30, 199, 29)] public unsafe void Indexer(int bufferCapacity, int width, int height, int x, int y) { - this.MemoryAllocator.BufferCapacityInBytes = sizeof(TestStructs.Foo) * bufferCapacity; + this.TestMemoryAllocator.BufferCapacityInBytes = sizeof(TestStructs.Foo) * bufferCapacity; - using (Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height)) + using (Buffer2D buffer = this.TestMemoryAllocator.Allocate2D(width, height)) { int bufferIndex = (width * y) / buffer.FastMemoryGroup.BufferLength; int subBufferStart = (width * y) - (bufferIndex * buffer.FastMemoryGroup.BufferLength); @@ -284,7 +285,7 @@ public unsafe void Indexer(int bufferCapacity, int width, int height, int x, int public void CopyColumns(int width, int height, int startIndex, int destIndex, int columnCount) { var rnd = new Random(123); - using (Buffer2D b = this.MemoryAllocator.Allocate2D(width, height)) + using (Buffer2D b = this.TestMemoryAllocator.Allocate2D(width, height)) { rnd.RandomFill(b.DangerousGetSingleSpan(), 0, 1); @@ -306,7 +307,7 @@ public void CopyColumns(int width, int height, int startIndex, int destIndex, in public void CopyColumns_InvokeMultipleTimes() { var rnd = new Random(123); - using (Buffer2D b = this.MemoryAllocator.Allocate2D(100, 100)) + using (Buffer2D b = this.TestMemoryAllocator.Allocate2D(100, 100)) { rnd.RandomFill(b.DangerousGetSingleSpan(), 0, 1); @@ -328,8 +329,8 @@ public void CopyColumns_InvokeMultipleTimes() [Fact] public void PublicMemoryGroup_IsMemoryGroupView() { - using Buffer2D buffer1 = this.MemoryAllocator.Allocate2D(10, 10); - using Buffer2D buffer2 = this.MemoryAllocator.Allocate2D(10, 10); + using Buffer2D buffer1 = this.TestMemoryAllocator.Allocate2D(10, 10); + using Buffer2D buffer2 = this.TestMemoryAllocator.Allocate2D(10, 10); IMemoryGroup mgBefore = buffer1.MemoryGroup; Buffer2D.SwapOrCopyContent(buffer1, buffer2); @@ -337,4 +338,26 @@ public void PublicMemoryGroup_IsMemoryGroupView() Assert.False(mgBefore.IsValid); Assert.NotSame(mgBefore, buffer1.MemoryGroup); } + + public static TheoryData InvalidLengths { get; set; } = new() + { + { new(-1, -1) }, + { new(32768, 32767) }, + { new(32767, 32768) } + }; + + [Theory] + [MemberData(nameof(InvalidLengths))] + public void Allocate_IncorrectAmount_ThrowsCorrect_InvalidMemoryOperationException(Size size) + => Assert.Throws(() => this.TestMemoryAllocator.Allocate2D(size.Width, size.Height)); + + [Theory] + [MemberData(nameof(InvalidLengths))] + public void Allocate_IncorrectAmount_ThrowsCorrect_InvalidMemoryOperationException_Size(Size size) + => Assert.Throws(() => this.TestMemoryAllocator.Allocate2D(new Size(size))); + + [Theory] + [MemberData(nameof(InvalidLengths))] + public void Allocate_IncorrectAmount_ThrowsCorrect_InvalidMemoryOperationException_OverAligned(Size size) + => Assert.Throws(() => this.TestMemoryAllocator.Allocate2DOverAligned(size.Width, size.Height, 1)); } diff --git a/tests/ImageSharp.Tests/TestImages.cs b/tests/ImageSharp.Tests/TestImages.cs index fe633fddc3..c1da2ce540 100644 --- a/tests/ImageSharp.Tests/TestImages.cs +++ b/tests/ImageSharp.Tests/TestImages.cs @@ -441,6 +441,8 @@ public static class Bmp public const string BlackWhitePalletDataMatrix = "Bmp/bit1datamatrix.bmp"; + public const string Issue2696 = "Bmp/issue-2696.bmp"; + public static readonly string[] BitFields = { Rgb32bfdef, diff --git a/tests/Images/Input/Bmp/issue-2696.bmp b/tests/Images/Input/Bmp/issue-2696.bmp new file mode 100644 index 0000000000..6770dd9469 --- /dev/null +++ b/tests/Images/Input/Bmp/issue-2696.bmp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc42cda9bac8fc73351ad03bf55214069bb8d31ea5bdd806321a8cc8b56c282e +size 126