Skip to content

Commit d597a5f

Browse files
authored
Fix overflow in ByteBlockPool, #1003 (#1055)
1 parent 5b7d0ac commit d597a5f

File tree

2 files changed

+57
-2
lines changed

2 files changed

+57
-2
lines changed

src/Lucene.Net.Tests/Util/TestByteBlockPool.cs

+52-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1-
using NUnit.Framework;
1+
using Lucene.Net.Attributes;
2+
using NUnit.Framework;
23
using RandomizedTesting.Generators;
4+
using System;
35
using System.Collections.Generic;
46
using JCG = J2N.Collections.Generic;
57
using Assert = Lucene.Net.TestFramework.Assert;
@@ -68,5 +70,54 @@ public virtual void TestReadAndWrite()
6870
}
6971
}
7072
}
73+
74+
[Test]
75+
[LuceneNetSpecific] // LUCENENET issue #1003
76+
public void TestTooManyAllocs()
77+
{
78+
// Use a mock allocator that doesn't waste memory
79+
ByteBlockPool pool = new ByteBlockPool(new MockAllocator(0));
80+
pool.NextBuffer();
81+
82+
bool throwsException = false;
83+
int maxIterations = int.MaxValue / ByteBlockPool.BYTE_BLOCK_SIZE + 1;
84+
85+
for (int i = 0; i < maxIterations; i++)
86+
{
87+
try
88+
{
89+
pool.NextBuffer();
90+
}
91+
catch (OverflowException)
92+
{
93+
// The offset overflows on the last attempt to call NextBuffer()
94+
throwsException = true;
95+
break;
96+
}
97+
}
98+
99+
Assert.IsTrue(throwsException);
100+
Assert.IsTrue(pool.ByteOffset + ByteBlockPool.BYTE_BLOCK_SIZE < pool.ByteOffset);
101+
}
102+
103+
private class MockAllocator : ByteBlockPool.Allocator
104+
{
105+
private readonly byte[] buffer;
106+
107+
public MockAllocator(int blockSize) : base(blockSize)
108+
{
109+
buffer = Array.Empty<byte>();
110+
}
111+
112+
public override void RecycleByteBlocks(byte[][] blocks, int start, int end)
113+
{
114+
// No-op
115+
}
116+
117+
public override byte[] GetByteBlock()
118+
{
119+
return buffer;
120+
}
121+
}
71122
}
72123
}

src/Lucene.Net/Util/ByteBlockPool.cs

+5-1
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,11 @@ public void NextBuffer()
262262
bufferUpto++;
263263

264264
ByteUpto = 0;
265-
ByteOffset += BYTE_BLOCK_SIZE;
265+
266+
checked // LUCENENET specific - added checked to prevent overflow, issue #1003
267+
{
268+
ByteOffset += BYTE_BLOCK_SIZE;
269+
}
266270
}
267271

268272
/// <summary>

0 commit comments

Comments
 (0)