Prevent potential integer overflow in BuilderArena.allocate().

This commit is contained in:
David Renshaw 2021-05-13 17:49:01 -04:00
parent 754184fd74
commit d310db1e88

View file

@ -87,6 +87,10 @@ public final class BuilderArena implements Arena {
} }
} }
/**
* Allocates `amount` words in an existing segment or, if no suitable segment
* exists, in a new segment.
*/
public AllocateResult allocate(int amount) { public AllocateResult allocate(int amount) {
int len = this.segments.size(); int len = this.segments.size();
@ -97,6 +101,10 @@ public final class BuilderArena implements Arena {
return new AllocateResult(this.segments.get(len - 1), result); return new AllocateResult(this.segments.get(len - 1), result);
} }
} }
if (amount >= 1 << 28) {
// Computing `amount * Constants.BYTES_PER_WORD` would overflow.
throw new RuntimeException("Too many words to allocate: " + amount);
}
SegmentBuilder newSegment = new SegmentBuilder( SegmentBuilder newSegment = new SegmentBuilder(
this.allocator.allocateSegment(amount * Constants.BYTES_PER_WORD), this.allocator.allocateSegment(amount * Constants.BYTES_PER_WORD),
this); this);