Skip to content

Commit 3064b78

Browse files
Merge pull request #2553 from SixLabors/backport/2.1.x/2545
[release/2.1] Disallow allocation attempts of unrepresentable sizes
2 parents 688e242 + f36ec12 commit 3064b78

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

src/ImageSharp/Memory/Allocators/UniformUnmanagedMemoryPoolMemoryAllocator.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,11 @@ internal override MemoryGroup<T> AllocateGroup<T>(
121121
AllocationOptions options = AllocationOptions.None)
122122
{
123123
long totalLengthInBytes = totalLength * Unsafe.SizeOf<T>();
124+
if (totalLengthInBytes < 0)
125+
{
126+
throw new InvalidMemoryOperationException("Attempted to allocate a MemoryGroup of a size that is not representable.");
127+
}
128+
124129
if (totalLengthInBytes <= this.sharedArrayPoolThresholdInBytes)
125130
{
126131
var buffer = new SharedArrayPoolBuffer<T>((int)totalLength);

tests/ImageSharp.Tests/Image/ImageTests.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,10 @@ public void Width_Height()
4040
}
4141
}
4242

43+
[Fact]
44+
public void Width_Height_SizeNotRepresentable_ThrowsInvalidImageOperationException()
45+
=> Assert.Throws<InvalidMemoryOperationException>(() => new Image<Rgba32>(int.MaxValue, int.MaxValue));
46+
4347
[Fact]
4448
public void Configuration_Width_Height()
4549
{

tests/ImageSharp.Tests/Memory/Allocators/UniformUnmanagedPoolMemoryAllocatorTests.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,13 @@ public void AllocateGroup_MultipleTimes_ExceedPoolLimit()
111111
}
112112
}
113113

114+
[Fact]
115+
public void AllocateGroup_SizeInBytesOverLongMaxValue_ThrowsInvalidMemoryOperationException()
116+
{
117+
var allocator = new UniformUnmanagedMemoryPoolMemoryAllocator(null);
118+
Assert.Throws<InvalidMemoryOperationException>(() => allocator.AllocateGroup<S4>(int.MaxValue * (long)int.MaxValue, int.MaxValue));
119+
}
120+
114121
[Fact]
115122
public unsafe void Allocate_MemoryIsPinnableMultipleTimes()
116123
{

0 commit comments

Comments
 (0)