Skip to content

Commit

Permalink
Fix overflow in ByteBlockPool, apache#1003
Browse files Browse the repository at this point in the history
  • Loading branch information
paulirwin committed Dec 3, 2024
1 parent abe75de commit 0d59ddc
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 2 deletions.
53 changes: 52 additions & 1 deletion src/Lucene.Net.Tests/Util/TestByteBlockPool.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using NUnit.Framework;
using Lucene.Net.Attributes;
using NUnit.Framework;
using RandomizedTesting.Generators;
using System;
using System.Collections.Generic;
using JCG = J2N.Collections.Generic;
using Assert = Lucene.Net.TestFramework.Assert;
Expand Down Expand Up @@ -68,5 +70,54 @@ public virtual void TestReadAndWrite()
}
}
}

[Test]
[LuceneNetSpecific] // LUCENENET issue #1003
public void TestTooManyAllocs()
{
// Use a mock allocator that doesn't waste memory
ByteBlockPool pool = new ByteBlockPool(new MockAllocator(0));
pool.NextBuffer();

bool throwsException = false;
int maxIterations = int.MaxValue / ByteBlockPool.BYTE_BLOCK_SIZE + 1;

for (int i = 0; i < maxIterations; i++)
{
try
{
pool.NextBuffer();
}
catch (OverflowException)
{
// The offset overflows on the last attempt to call NextBuffer()
throwsException = true;
break;
}
}

Assert.IsTrue(throwsException);
Assert.IsTrue(pool.ByteOffset + ByteBlockPool.BYTE_BLOCK_SIZE < pool.ByteOffset);
}

private class MockAllocator : ByteBlockPool.Allocator
{
private readonly byte[] buffer;

public MockAllocator(int blockSize) : base(blockSize)
{
buffer = Array.Empty<byte>();
}

public override void RecycleByteBlocks(byte[][] blocks, int start, int end)
{
// No-op
}

public override byte[] GetByteBlock()
{
return buffer;
}
}
}
}
6 changes: 5 additions & 1 deletion src/Lucene.Net/Util/ByteBlockPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,11 @@ public void NextBuffer()
bufferUpto++;

ByteUpto = 0;
ByteOffset += BYTE_BLOCK_SIZE;

checked // LUCENENET specific - added checked to prevent overflow, issue #1003
{
ByteOffset += BYTE_BLOCK_SIZE;
}
}

/// <summary>
Expand Down

0 comments on commit 0d59ddc

Please sign in to comment.