1 /*
  2  * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved.
  3  *  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  *  This code is free software; you can redistribute it and/or modify it
  6  *  under the terms of the GNU General Public License version 2 only, as
  7  *  published by the Free Software Foundation.
  8  *
  9  *  This code is distributed in the hope that it will be useful, but WITHOUT
 10  *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  *  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  *  version 2 for more details (a copy is included in the LICENSE file that
 13  *  accompanied this code).
 14  *
 15  *  You should have received a copy of the GNU General Public License version
 16  *  2 along with this work; if not, write to the Free Software Foundation,
 17  *  Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  *   Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  *  or visit www.oracle.com if you need additional information or have any
 21  *  questions.
 22  *
 23  */
 24 
 25 /*
 26  * @test
 27  * @enablePreview
 28  * @run testng TestLayoutPaths
 29  */
 30 
 31 import java.lang.foreign.*;
 32 import java.lang.foreign.MemoryLayout.PathElement;
 33 
 34 import org.testng.annotations.*;
 35 
 36 import java.lang.invoke.MethodHandle;
 37 import java.lang.invoke.VarHandle;
 38 import java.util.ArrayList;
 39 import java.util.List;
 40 import java.util.function.IntFunction;
 41 
 42 import static java.lang.foreign.MemoryLayout.PathElement.groupElement;
 43 import static java.lang.foreign.MemoryLayout.PathElement.sequenceElement;
 44 import static java.lang.foreign.ValueLayout.JAVA_INT;
 45 import static java.lang.foreign.ValueLayout.JAVA_SHORT;
 46 import static org.testng.Assert.*;
 47 
 48 public class TestLayoutPaths {
 49 
 50     @Test(expectedExceptions = IllegalArgumentException.class)
 51     public void testBadByteSelectFromSeq() {
 52         SequenceLayout seq = MemoryLayout.sequenceLayout(5, JAVA_INT);
 53         seq.byteOffset(groupElement("foo"));
 54     }
 55 
 56     @Test(expectedExceptions = IllegalArgumentException.class)
 57     public void testBadByteSelectFromStruct() {
 58         GroupLayout g = MemoryLayout.structLayout(JAVA_INT);
 59         g.byteOffset(sequenceElement());
 60     }
 61 
 62     @Test(expectedExceptions = IllegalArgumentException.class)
 63     public void testBadByteSelectFromValue() {
 64         SequenceLayout seq = MemoryLayout.sequenceLayout(5, JAVA_INT);
 65         seq.byteOffset(sequenceElement(), sequenceElement());
 66     }
 67 
 68     @Test(expectedExceptions = IllegalArgumentException.class)
 69     public void testUnknownByteStructField() {
 70         GroupLayout g = MemoryLayout.structLayout(JAVA_INT);
 71         g.byteOffset(groupElement("foo"));
 72     }
 73 
 74     @Test(expectedExceptions = IllegalArgumentException.class)
 75     public void testTooBigGroupElementIndex() {
 76         GroupLayout g = MemoryLayout.structLayout(JAVA_INT);
 77         g.byteOffset(groupElement(1));
 78     }
 79 
 80     @Test(expectedExceptions = IllegalArgumentException.class)
 81     public void testNegativeGroupElementIndex() {
 82         GroupLayout g = MemoryLayout.structLayout(JAVA_INT);
 83         g.byteOffset(groupElement(-1));
 84     }
 85 
 86     @Test(expectedExceptions = IllegalArgumentException.class)
 87     public void testByteOutOfBoundsSeqIndex() {
 88         SequenceLayout seq = MemoryLayout.sequenceLayout(5, JAVA_INT);
 89         seq.byteOffset(sequenceElement(6));
 90     }
 91 
 92     @Test(expectedExceptions = IllegalArgumentException.class)
 93     public void testNegativeSeqIndex() {
 94        sequenceElement(-2);
 95     }
 96 
 97     @Test(expectedExceptions = IllegalArgumentException.class)
 98     public void testByteNegativeSeqIndex() {
 99         SequenceLayout seq = MemoryLayout.sequenceLayout(5, JAVA_INT);
100         seq.byteOffset(sequenceElement(-2));
101     }
102 
103     @Test(expectedExceptions = IllegalArgumentException.class)
104     public void testOutOfBoundsSeqRange() {
105         SequenceLayout seq = MemoryLayout.sequenceLayout(5, JAVA_INT);
106         seq.byteOffset(sequenceElement(6, 2));
107     }
108 
109     @Test(expectedExceptions = IllegalArgumentException.class)
110     public void testNegativeSeqRange() {
111         sequenceElement(-2, 2);
112     }
113 
114     @Test(expectedExceptions = IllegalArgumentException.class)
115     public void testByteNegativeSeqRange() {
116         SequenceLayout seq = MemoryLayout.sequenceLayout(5, JAVA_INT);
117         seq.byteOffset(sequenceElement(-2, 2));
118     }
119 
120     @Test(expectedExceptions = IllegalArgumentException.class)
121     public void testIncompleteAccess() {
122         SequenceLayout seq = MemoryLayout.sequenceLayout(5, MemoryLayout.structLayout(JAVA_INT));
123         seq.varHandle(sequenceElement());
124     }
125 
126     @Test
127     public void testByteOffsetHandleRange() {
128         SequenceLayout seq = MemoryLayout.sequenceLayout(5, MemoryLayout.structLayout(JAVA_INT));
129         seq.byteOffsetHandle(sequenceElement(0, 1));
130     }
131 
132     @Test(expectedExceptions = IllegalArgumentException.class)
133     public void testByteOffsetHandleBadRange() {
134         SequenceLayout seq = MemoryLayout.sequenceLayout(5, MemoryLayout.structLayout(JAVA_INT));
135         seq.byteOffsetHandle(sequenceElement(5, 1)); // invalid range (starting position is outside the sequence)
136     }
137 
138     @Test
139     public void testBadAlignmentOfRoot() throws Throwable {
140         MemoryLayout struct = MemoryLayout.structLayout(
141             JAVA_INT,
142             JAVA_SHORT.withName("x"));
143         assertEquals(struct.byteAlignment(), 4);
144 
145         try (Arena arena = Arena.ofConfined()) {
146             MemorySegment seg = arena.allocate(struct.byteSize() + 2, struct.byteAlignment()).asSlice(2);
147             assertEquals(seg.address() % JAVA_SHORT.byteAlignment(), 0); // should be aligned
148             assertNotEquals(seg.address() % struct.byteAlignment(), 0); // should not be aligned
149 
150             String expectedMessage = "Target offset incompatible with alignment constraints: " + struct.byteAlignment();
151 
152             VarHandle vhX = struct.varHandle(groupElement("x"));
153             IllegalArgumentException iae = expectThrows(IllegalArgumentException.class, () -> {
154                 vhX.set(seg, (short) 42);
155             });
156             assertEquals(iae.getMessage(), expectedMessage);
157 
158             MethodHandle sliceX = struct.sliceHandle(groupElement("x"));
159             iae = expectThrows(IllegalArgumentException.class, () -> {
160                 MemorySegment slice = (MemorySegment) sliceX.invokeExact(seg);
161             });
162             assertEquals(iae.getMessage(), expectedMessage);
163         }
164     }
165 
166     @Test
167     public void testBadSequencePathInOffset() {
168         SequenceLayout seq = MemoryLayout.sequenceLayout(10, JAVA_INT);
169         // bad path elements
170         for (PathElement e : List.of( sequenceElement(), sequenceElement(0, 2) )) {
171             try {
172                 seq.byteOffset(e);
173                 fail();
174             } catch (IllegalArgumentException ex) {
175                 assertTrue(true);
176             }
177         }
178     }
179 
180     @Test
181     public void testBadSequencePathInSelect() {
182         SequenceLayout seq = MemoryLayout.sequenceLayout(10, JAVA_INT);
183         for (PathElement e : List.of( sequenceElement(0), sequenceElement(0, 2) )) {
184             try {
185                 seq.select(e);
186                 fail();
187             } catch (IllegalArgumentException ex) {
188                 assertTrue(true);
189             }
190         }
191     }
192 
193     @Test(dataProvider = "groupSelectors")
194     public void testStructPaths(IntFunction<PathElement> groupSelector) {
195         long[] offsets = { 0, 1, 3, 7 };
196         GroupLayout g = MemoryLayout.structLayout(
197                 ValueLayout.JAVA_BYTE.withName("0"),
198                 ValueLayout.JAVA_CHAR_UNALIGNED.withName("1"),
199                 ValueLayout.JAVA_FLOAT_UNALIGNED.withName("2"),
200                 ValueLayout.JAVA_LONG_UNALIGNED.withName("3")
201         );
202 
203         // test select
204 
205         for (int i = 0 ; i < 4 ; i++) {
206             MemoryLayout selected = g.select(groupSelector.apply(i));
207             assertTrue(selected == g.memberLayouts().get(i));
208         }
209 
210         // test offset
211 
212         for (int i = 0 ; i < 4 ; i++) {
213             long byteOffset = g.byteOffset(groupSelector.apply(i));
214             assertEquals(offsets[i], byteOffset);
215         }
216     }
217 
218     @Test(dataProvider = "groupSelectors")
219     public void testUnionPaths(IntFunction<PathElement> groupSelector) {
220         long[] offsets = { 0, 0, 0, 0 };
221         GroupLayout g = MemoryLayout.unionLayout(
222                 ValueLayout.JAVA_BYTE.withName("0"),
223                 ValueLayout.JAVA_CHAR.withName("1"),
224                 ValueLayout.JAVA_FLOAT.withName("2"),
225                 ValueLayout.JAVA_LONG.withName("3")
226         );
227 
228         // test select
229 
230         for (int i = 0 ; i < 4 ; i++) {
231             MemoryLayout selected = g.select(groupSelector.apply(i));
232             assertTrue(selected == g.memberLayouts().get(i));
233         }
234 
235         // test offset
236 
237         for (int i = 0 ; i < 4 ; i++) {
238             long byteOffset = g.byteOffset(groupSelector.apply(i));
239             assertEquals(offsets[i], byteOffset);
240         }
241     }
242 
243     @DataProvider
244     public static Object[][] groupSelectors() {
245         return new Object[][] {
246                 { (IntFunction<PathElement>) PathElement::groupElement }, // by index
247                 { (IntFunction<PathElement>) i -> PathElement.groupElement(String.valueOf(i)) } // by name
248         };
249     }
250 
251     @Test
252     public void testSequencePaths() {
253         long[] offsets = { 0, 1, 2, 3 };
254         SequenceLayout g = MemoryLayout.sequenceLayout(4, ValueLayout.JAVA_BYTE);
255 
256         // test select
257 
258         MemoryLayout selected = g.select(sequenceElement());
259         assertTrue(selected == ValueLayout.JAVA_BYTE);
260 
261         // test offset
262 
263         for (int i = 0 ; i < 4 ; i++) {
264             long byteOffset = g.byteOffset(sequenceElement(i));
265             assertEquals(offsets[i], byteOffset);
266         }
267     }
268 
269     @Test(dataProvider = "testLayouts")
270     public void testOffsetHandle(MemoryLayout layout, PathElement[] pathElements, long[] indexes,
271                                  long expectedByteOffset) throws Throwable {
272         MethodHandle byteOffsetHandle = layout.byteOffsetHandle(pathElements);
273         byteOffsetHandle = byteOffsetHandle.asSpreader(long[].class, indexes.length);
274         long actualByteOffset = (long) byteOffsetHandle.invokeExact(indexes);
275         assertEquals(actualByteOffset, expectedByteOffset);
276     }
277 
278     @DataProvider
279     public static Object[][] testLayouts() {
280         List<Object[]> testCases = new ArrayList<>();
281 
282         testCases.add(new Object[] {
283             MemoryLayout.sequenceLayout(10, JAVA_INT),
284             new PathElement[] { sequenceElement() },
285             new long[] { 4 },
286             JAVA_INT.byteSize() * 4
287         });
288         testCases.add(new Object[] {
289             MemoryLayout.sequenceLayout(10, MemoryLayout.structLayout(JAVA_INT, JAVA_INT.withName("y"))),
290             new PathElement[] { sequenceElement(), groupElement("y") },
291             new long[] { 4 },
292             (JAVA_INT.byteSize() * 2) * 4 + JAVA_INT.byteSize()
293         });
294         testCases.add(new Object[] {
295             MemoryLayout.sequenceLayout(10, MemoryLayout.structLayout(MemoryLayout.paddingLayout(4), JAVA_INT.withName("y"))),
296             new PathElement[] { sequenceElement(), groupElement("y") },
297             new long[] { 4 },
298             (JAVA_INT.byteSize() + 4) * 4 + 4
299         });
300         testCases.add(new Object[] {
301             MemoryLayout.sequenceLayout(10, JAVA_INT),
302             new PathElement[] { sequenceElement() },
303             new long[] { 4 },
304             JAVA_INT.byteSize() * 4
305         });
306         testCases.add(new Object[] {
307             MemoryLayout.structLayout(
308                 MemoryLayout.sequenceLayout(10, JAVA_INT).withName("data")
309             ),
310             new PathElement[] { groupElement("data"), sequenceElement() },
311             new long[] { 4 },
312             JAVA_INT.byteSize() * 4
313         });
314 
315         MemoryLayout complexLayout = MemoryLayout.structLayout(
316             MemoryLayout.sequenceLayout(10,
317                 MemoryLayout.sequenceLayout(10,
318                     MemoryLayout.structLayout(
319                         JAVA_INT.withName("x"),
320                         JAVA_INT.withName("y")
321                     )
322                 )
323             ).withName("data")
324         );
325 
326         testCases.add(new Object[] {
327             complexLayout,
328             new PathElement[] { groupElement("data"), sequenceElement(), sequenceElement(), groupElement("x") },
329             new long[] { 0, 1 },
330             (JAVA_INT.byteSize() * 2)
331         });
332         testCases.add(new Object[] {
333             complexLayout,
334             new PathElement[] { groupElement("data"), sequenceElement(), sequenceElement(), groupElement("x") },
335             new long[] { 1, 0 },
336             (JAVA_INT.byteSize() * 2) * 10
337         });
338         testCases.add(new Object[] {
339             complexLayout,
340             new PathElement[] { groupElement("data"), sequenceElement(), sequenceElement(), groupElement("y") },
341             new long[] { 0, 1 },
342             (JAVA_INT.byteSize() * 2) + JAVA_INT.byteSize()
343         });
344         testCases.add(new Object[] {
345             complexLayout,
346             new PathElement[] { groupElement("data"), sequenceElement(), sequenceElement(), groupElement("y") },
347             new long[] { 1, 0 },
348             (JAVA_INT.byteSize() * 2) * 10 + JAVA_INT.byteSize()
349         });
350 
351         return testCases.toArray(Object[][]::new);
352     }
353 
354     @Test(dataProvider = "testLayouts")
355     public void testSliceHandle(MemoryLayout layout, PathElement[] pathElements, long[] indexes,
356                                 long expectedByteOffset) throws Throwable {
357         MemoryLayout selected = layout.select(pathElements);
358         MethodHandle sliceHandle = layout.sliceHandle(pathElements);
359         sliceHandle = sliceHandle.asSpreader(long[].class, indexes.length);
360 
361         try (Arena arena = Arena.ofConfined()) {
362             MemorySegment segment = arena.allocate(layout);
363             MemorySegment slice = (MemorySegment) sliceHandle.invokeExact(segment, indexes);
364             assertEquals(slice.address() - segment.address(), expectedByteOffset);
365             assertEquals(slice.byteSize(), selected.byteSize());
366         }
367     }
368 
369 }