Skip to content

Apache Lucene open-source search software

Catch offset overflows in byte pool (#9660) (#12392)

Stefan Voditab88d3e19889f
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 735d6320148..8c1f1e68915 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -143,6 +143,8 @@ Optimizations
Bug Fixes
---------------------
+* GITHUB#9660: Throw and ArithmeticException when the offset overflows in a ByteBlockPool. (Stefan Vodita)
+
* GITHUB#12388: JoinUtil queries were ignoring boosts. (Alan Woodward)
Other
diff --git a/lucene/core/src/java/org/apache/lucene/util/ByteBlockPool.java b/lucene/core/src/java/org/apache/lucene/util/ByteBlockPool.java
index 39216b85c31..d957e5bf2f9 100644
--- a/lucene/core/src/java/org/apache/lucene/util/ByteBlockPool.java
+++ b/lucene/core/src/java/org/apache/lucene/util/ByteBlockPool.java
@@ -197,7 +197,7 @@ public final class ByteBlockPool implements Accountable {
bufferUpto++;
byteUpto = 0;
- byteOffset += BYTE_BLOCK_SIZE;
+ byteOffset = Math.addExact(byteOffset, BYTE_BLOCK_SIZE);
}
/**
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestByteBlockPool.java b/lucene/core/src/test/org/apache/lucene/util/TestByteBlockPool.java
index 8068d06d72f..03f4e00bebc 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestByteBlockPool.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestByteBlockPool.java
@@ -135,4 +135,34 @@ public class TestByteBlockPool extends LuceneTestCase {
}
}
}
+
+ public void testTooManyAllocs() {
+ // Use a mock allocator that doesn't waste memory
+ ByteBlockPool pool =
+ new ByteBlockPool(
+ new ByteBlockPool.Allocator(0) {
+ final byte[] buffer = new byte[0];
+
+ @Override
+ public void recycleByteBlocks(byte[][] blocks, int start, int end) {}
+
+ @Override
+ public byte[] getByteBlock() {
+ return buffer;
+ }
+ });
+ pool.nextBuffer();
+
+ for (int i = 0; i < Integer.MAX_VALUE / ByteBlockPool.BYTE_BLOCK_SIZE + 1; i++) {
+ try {
+ pool.nextBuffer();
+ } catch (
+ @SuppressWarnings("unused")
+ ArithmeticException ignored) {
+ // The offset overflows on the last attempt to call nextBuffer()
+ break;
+ }
+ }
+ assertTrue(pool.byteOffset + ByteBlockPool.BYTE_BLOCK_SIZE < 0);
+ }
}