Skip to content

Commit 10ba0ab

Browse files
Harald EilertsenKurt Miller
authored andcommitted
8371637: allocateNativeInternal sometimes return incorrectly aligned memory
Co-authored-by: Kurt Miller <kurt@openjdk.org> Reviewed-by: mcimadamore, jvernee
1 parent 1ce2a44 commit 10ba0ab

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,9 @@ private static long allocateNativeInternal(long byteSize, long byteAlignment, Me
212212
allocationBase = allocateMemoryWrapper(allocationSize);
213213
result = Utils.alignUp(allocationBase, byteAlignment);
214214
} else {
215-
allocationSize = alignedSize;
215+
// always allocate at least 'byteAlignment' bytes, so that malloc is guaranteed to
216+
// return a pointer aligned to that alignment, for cases where byteAlignment > alignedSize
217+
allocationSize = Math.max(alignedSize, byteAlignment);
216218
if (shouldReserve) {
217219
AbstractMemorySegmentImpl.NIO_ACCESS.reserveMemory(allocationSize, byteSize);
218220
}

test/jdk/java/foreign/TestMemoryAlignment.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,14 @@ public void testAlignedAccess(long align) {
6060
assertEquals(aligned.byteAlignment(), align); //unreasonable alignment here, to make sure access throws
6161
VarHandle vh = aligned.varHandle();
6262
try (Arena arena = Arena.ofConfined()) {
63-
MemorySegment segment = arena.allocate(aligned);;
63+
MemorySegment segment = arena.allocate(aligned);
6464
vh.set(segment, 0L, -42);
65+
66+
// Allocate another segment and fill it with data to
67+
// check that the first segment is not overwritten
68+
MemorySegment nextSegment = arena.allocate(aligned);
69+
vh.set(nextSegment, 0L, 0xffffff);
70+
6571
int val = (int)vh.get(segment, 0L);
6672
assertEquals(val, -42);
6773
}

0 commit comments

Comments
 (0)