Skip to content

Commit 0671309

Browse files
committed
8357919: Arena::allocate returns segments with address zero if the segment length is zero after JDK-8345687
Reviewed-by: mcimadamore
1 parent 627ef34 commit 0671309

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/java.base/share/classes/jdk/internal/foreign/SegmentFactories.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,13 @@ private static long allocateNativeInternal(long byteSize, long byteAlignment, Me
192192
}
193193
// Align the allocation size up to a multiple of 8 so we can init the memory with longs
194194
long alignedSize = init ? Utils.alignUp(byteSize, Long.BYTES) : byteSize;
195+
// Check for wrap around
196+
if (alignedSize < 0) {
197+
throw new OutOfMemoryError();
198+
}
199+
// Always allocate at least some memory so that zero-length segments have distinct
200+
// non-zero addresses.
201+
alignedSize = Math.max(1, alignedSize);
195202

196203
long allocationSize;
197204
long allocationBase;

test/jdk/java/foreign/TestSegments.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
/*
2525
* @test
2626
* @requires vm.bits == 64
27+
* @modules java.base/sun.nio.ch
2728
* @run testng/othervm -Xmx4G -XX:MaxDirectMemorySize=1M --enable-native-access=ALL-UNNAMED TestSegments
2829
*/
2930

@@ -58,6 +59,12 @@ public void testZeroLengthNativeSegment() {
5859
try (Arena arena = Arena.ofConfined()) {
5960
var segment = arena.allocate(0, 1);
6061
assertEquals(segment.byteSize(), 0);
62+
if (segment.address() == 0) {
63+
fail("Segment address is zero");
64+
}
65+
if (segment.address() == arena.allocate(0, 1).address()) {
66+
fail("Segment address was not distinct");
67+
}
6168
MemoryLayout seq = MemoryLayout.sequenceLayout(0, JAVA_INT);
6269
segment = arena.allocate(seq);
6370
assertEquals(segment.byteSize(), 0);
@@ -71,6 +78,20 @@ public void testZeroLengthNativeSegment() {
7178
}
7279
}
7380

81+
@Test
82+
public void testZeroLengthNativeSegmentHyperAligned() {
83+
long byteAlignment = 1024;
84+
try (Arena arena = Arena.ofConfined()) {
85+
var segment = arena.allocate(0, byteAlignment);
86+
assertEquals(segment.byteSize(), 0);
87+
if (segment.address() == 0) {
88+
fail("Segment address is zero");
89+
}
90+
assertTrue(segment.maxByteAlignment() >= byteAlignment);
91+
}
92+
}
93+
94+
7495
@Test(expectedExceptions = { OutOfMemoryError.class,
7596
IllegalArgumentException.class })
7697
public void testAllocateTooBig() {

0 commit comments

Comments
 (0)