From cecf817f5ed8e6ca290f8da0f07f694f35ec4c7e Mon Sep 17 00:00:00 2001 From: Maurizio Cimadamore Date: Thu, 4 May 2023 09:44:31 +0000 Subject: [PATCH] 8307181: MemoryLayout.structLayout uses undocumented strict alignment constraints Reviewed-by: jvernee --- .../java/lang/foreign/MemoryLayout.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/java.base/share/classes/java/lang/foreign/MemoryLayout.java b/src/java.base/share/classes/java/lang/foreign/MemoryLayout.java index ecef9f55a82e2..eaac5cb936d44 100644 --- a/src/java.base/share/classes/java/lang/foreign/MemoryLayout.java +++ b/src/java.base/share/classes/java/lang/foreign/MemoryLayout.java @@ -739,6 +739,28 @@ static SequenceLayout sequenceLayout(MemoryLayout elementLayout) { * @return a struct layout with the given member layouts. * @throws IllegalArgumentException if the sum of the {@linkplain #bitSize() bit sizes} of the member layouts * overflows. + * @throws IllegalArgumentException if a member layout in {@code elements} occurs at an offset (relative to the start + * of the struct layout) which is not compatible with its alignment constraint. + * + * @apiNote This factory does not automatically align element layouts, by inserting additional {@linkplain PaddingLayout + * padding layout} elements. As such, the following struct layout creation will fail with an exception: + * + * {@snippet lang = java: + * structLayout(JAVA_SHORT, JAVA_INT) + * } + * + * To avoid the exception, clients can either insert additional padding layout elements: + * + * {@snippet lang = java: + * structLayout(JAVA_SHORT, MemoryLayout.ofPadding(16), JAVA_INT) + * } + * + * Or, alternatively, they can use a member layout which features a smaller alignment constraint. This will result + * in a packed struct layout: + * + * {@snippet lang = java: + * structLayout(JAVA_SHORT, JAVA_INT.withBitAlignment(16)) + * } */ static StructLayout structLayout(MemoryLayout... elements) { Objects.requireNonNull(elements);