Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resolving infinite loop with buffers longer than MaxArrayLength #345

Merged
merged 2 commits into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions UnitTests/Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4057,7 +4057,25 @@ protected override void TestDroppingLargeBuffer(long maxFreeLargeBufferSize)
}
}
}
#pragma warning disable 618 // Timeout is obsolete because it kills the thread, which isn't allowed, but it's still handy
// for tests that are expected to run indefinitely in the failure case.
[Test, Timeout(10000)]
public void TryGetBuffer_InfiniteLoop_Issue344()
{
// see https://github.com/microsoft/Microsoft.IO.RecyclableMemoryStream/issues/344
var memMgr = this.GetMemoryManager();
var size = 1073741825; // this will cause infinite loop in TryGetBuffer below, 1073741824 works.
var bytes = new byte[size];
using (var ms = memMgr.GetStream())
{
ms.Write(bytes, 0, size);
bool result = ms.TryGetBuffer(out var segment);
Assert.That(result, Is.False);
Assert.That(segment, Is.Empty);
}
}
}
#pragma warning restore 618

[TestFixture]
public sealed class RecyclableMemoryStreamTestsWithPassiveBufferReleaseUsingExponentialLargeBuffer : BaseRecyclableMemoryStreamTestsUsingExponentialLargeBuffer
Expand Down
6 changes: 3 additions & 3 deletions src/RecyclableMemoryStreamManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -378,13 +378,13 @@ internal byte[] GetBlock()
/// <exception cref="OutOfMemoryException">Requested array size is larger than the maximum allowed.</exception>
internal byte[] GetLargeBuffer(long requiredSize, Guid id, string? tag)
{
requiredSize = this.RoundToLargeBufferSize(requiredSize);

if (requiredSize > MaxArrayLength)
{
throw new OutOfMemoryException($"Requested size exceeds maximum array length of {MaxArrayLength}.");
throw new OutOfMemoryException($"Required buffer size exceeds maximum array length of {MaxArrayLength}.");
}

requiredSize = this.RoundToLargeBufferSize(requiredSize);

var poolIndex = this.GetPoolIndex(requiredSize);

bool createdNew = false;
Expand Down
Loading