Skip to content

Commit

Permalink
Disallow allocation attempts of unrepresentable sizes
Browse files Browse the repository at this point in the history
  • Loading branch information
antonfirsov committed Oct 8, 2023
1 parent 8c1113e commit c4150b9
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@ internal override MemoryGroup<T> AllocateGroup<T>(
AllocationOptions options = AllocationOptions.None)
{
long totalLengthInBytes = totalLength * Unsafe.SizeOf<T>();
if (totalLengthInBytes < 0)
{
throw new InvalidMemoryOperationException("Attempted to allocate a MemoryGroup of a size that is not representable.");
}

if (totalLengthInBytes <= this.sharedArrayPoolThresholdInBytes)
{
var buffer = new SharedArrayPoolBuffer<T>((int)totalLength);
Expand Down
5 changes: 5 additions & 0 deletions tests/ImageSharp.Tests/Image/ImageTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.Memory;
using SixLabors.ImageSharp.Metadata;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Tests.Memory;
Expand Down Expand Up @@ -35,6 +36,10 @@ public void Width_Height()
}
}

[Fact]
public void Width_Height_SizeNotRepresentable_ThrowsInvalidImageOperationException()
=> Assert.Throws<InvalidMemoryOperationException>(() => new Image<Rgba32>(int.MaxValue, int.MaxValue));

[Fact]
public void Configuration_Width_Height()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,13 @@ public void AllocateGroup_MultipleTimes_ExceedPoolLimit()
}
}

[Fact]
public void AllocateGroup_SizeInBytesOverLongMaxValue_ThrowsInvalidMemoryOperationException()
{
var allocator = new UniformUnmanagedMemoryPoolMemoryAllocator(null);
Assert.Throws<InvalidMemoryOperationException>(() => allocator.AllocateGroup<S4>(int.MaxValue * (long)int.MaxValue, int.MaxValue));
}

[Fact]
public unsafe void Allocate_MemoryIsPinnableMultipleTimes()
{
Expand Down

0 comments on commit c4150b9

Please sign in to comment.