Skip to content

Commit

Permalink
Merge pull request #2545 from SixLabors/af/fix-memorygroup-overalloca…
Browse files Browse the repository at this point in the history
…tion

Disallow allocation attempts of unrepresentable sizes
  • Loading branch information
JimBobSquarePants committed Oct 9, 2023
2 parents 8c1113e + 2302ec3 commit 9b24cc1
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/ImageSharp/ImageSharp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@
</PropertyGroup>

<PropertyGroup>
<!--Bump to V3 prior to tagged release.-->
<MinVerMinimumMajorMinor>3.0</MinVerMinimumMajorMinor>
<!--Bump to v3.1 prior to tagged release.-->
<MinVerMinimumMajorMinor>3.1</MinVerMinimumMajorMinor>
</PropertyGroup>

<Choose>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@ public UniformUnmanagedMemoryPoolMemoryAllocator(int? maxPoolSizeMegabytes)
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 9b24cc1

Please sign in to comment.