Skip to content

Commit

Permalink
Merge pull request #2553 from SixLabors/backport/2.1.x/2545
Browse files Browse the repository at this point in the history
[release/2.1] Disallow allocation attempts of unrepresentable sizes
  • Loading branch information
JimBobSquarePants authored Oct 16, 2023
2 parents 688e242 + f36ec12 commit 3064b78
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,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
4 changes: 4 additions & 0 deletions tests/ImageSharp.Tests/Image/ImageTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,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 @@ -111,6 +111,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 3064b78

Please sign in to comment.