1 /*
  2  *  Copyright (c) 2019, 2020, 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  * @test
 26  * @requires ((os.arch == "amd64" | os.arch == "x86_64") & sun.arch.data.model == "64") | os.arch == "aarch64"
 27  * @run testng/othervm -Xmx4G -XX:MaxDirectMemorySize=1M TestSegments
 28  */
 29 
 30 import jdk.incubator.foreign.MemoryAccess;
 31 import jdk.incubator.foreign.MemoryLayout;
 32 import jdk.incubator.foreign.MemoryLayouts;
 33 import jdk.incubator.foreign.MemorySegment;
 34 import jdk.incubator.foreign.ResourceScope;
 35 import org.testng.annotations.DataProvider;
 36 import org.testng.annotations.Test;
 37 
 38 import java.lang.invoke.VarHandle;
 39 import java.nio.ByteBuffer;
 40 import java.nio.ByteOrder;
 41 import java.util.List;
 42 import java.util.concurrent.atomic.AtomicReference;
 43 import java.util.function.IntFunction;
 44 import java.util.function.LongFunction;
 45 import java.util.function.Supplier;
 46 
 47 import static org.testng.Assert.*;
 48 
 49 public class TestSegments {
 50 
 51     @Test(dataProvider = "badSizeAndAlignments", expectedExceptions = IllegalArgumentException.class)
 52     public void testBadAllocateAlign(long size, long align) {
 53         MemorySegment.allocateNative(size, align, ResourceScope.newImplicitScope());
 54     }
 55 
 56     @Test(dataProvider = "badLayouts", expectedExceptions = UnsupportedOperationException.class)
 57     public void testBadAllocateLayout(MemoryLayout layout) {
 58         MemorySegment.allocateNative(layout, ResourceScope.newImplicitScope());
 59     }
 60 
 61     @Test(expectedExceptions = { OutOfMemoryError.class,
 62                                  IllegalArgumentException.class })
 63     public void testAllocateTooBig() {
 64         MemorySegment.allocateNative(Long.MAX_VALUE, ResourceScope.newImplicitScope());
 65     }
 66 
 67     @Test(expectedExceptions = OutOfMemoryError.class)
 68     public void testNativeAllocationTooBig() {
 69         MemorySegment segment = MemorySegment.allocateNative(1024 * 1024 * 8 * 2, ResourceScope.newImplicitScope()); // 2M
 70     }
 71 
 72     @Test
 73     public void testNativeSegmentIsZeroed() {
 74         VarHandle byteHandle = MemoryLayout.sequenceLayout(MemoryLayouts.JAVA_BYTE)
 75                 .varHandle(byte.class, MemoryLayout.PathElement.sequenceElement());
 76         try (ResourceScope scope = ResourceScope.newConfinedScope()) {
 77             MemorySegment segment = MemorySegment.allocateNative(1000, 1, scope);
 78             for (long i = 0 ; i < segment.byteSize() ; i++) {
 79                 assertEquals(0, (byte)byteHandle.get(segment, i));
 80             }
 81         }
 82     }
 83 
 84     @Test
 85     public void testSlices() {
 86         VarHandle byteHandle = MemoryLayout.sequenceLayout(MemoryLayouts.JAVA_BYTE)
 87                 .varHandle(byte.class, MemoryLayout.PathElement.sequenceElement());
 88         try (ResourceScope scope = ResourceScope.newConfinedScope()) {
 89             MemorySegment segment = MemorySegment.allocateNative(10, 1, scope);
 90             //init
 91             for (byte i = 0 ; i < segment.byteSize() ; i++) {
 92                 byteHandle.set(segment, (long)i, i);
 93             }
 94             for (int offset = 0 ; offset < 10 ; offset++) {
 95                 MemorySegment slice = segment.asSlice(offset);
 96                 for (long i = offset ; i < 10 ; i++) {
 97                     assertEquals(
 98                             byteHandle.get(segment, i),
 99                             byteHandle.get(slice, i - offset)
100                     );
101                 }
102             }
103         }
104     }
105 
106     @Test(expectedExceptions = IndexOutOfBoundsException.class)
107     public void testSmallSegmentMax() {
108         long offset = (long)Integer.MAX_VALUE + (long)Integer.MAX_VALUE + 2L + 6L; // overflows to 6 when casted to int
109         MemorySegment memorySegment = MemorySegment.allocateNative(10, ResourceScope.newImplicitScope());
110         MemoryAccess.getIntAtOffset(memorySegment, offset);
111     }
112 
113     @Test(expectedExceptions = IndexOutOfBoundsException.class)
114     public void testSmallSegmentMin() {
115         long offset = ((long)Integer.MIN_VALUE * 2L) + 6L; // underflows to 6 when casted to int
116         MemorySegment memorySegment = MemorySegment.allocateNative(10, ResourceScope.newImplicitScope());
117         MemoryAccess.getIntAtOffset(memorySegment, offset);
118     }
119 
120     @Test(dataProvider = "segmentFactories")
121     public void testAccessModesOfFactories(Supplier<MemorySegment> memorySegmentSupplier) {
122         MemorySegment segment = memorySegmentSupplier.get();
123         assertFalse(segment.isReadOnly());
124         tryClose(segment);
125     }
126 
127     static void tryClose(MemorySegment segment) {
128         if (!segment.scope().isImplicit()) {
129             segment.scope().close();
130         }
131     }
132 
133     @DataProvider(name = "segmentFactories")
134     public Object[][] segmentFactories() {
135         List<Supplier<MemorySegment>> l = List.of(
136                 () -> MemorySegment.ofArray(new byte[] { 0x00, 0x01, 0x02, 0x03 }),
137                 () -> MemorySegment.ofArray(new char[] {'a', 'b', 'c', 'd' }),
138                 () -> MemorySegment.ofArray(new double[] { 1d, 2d, 3d, 4d} ),
139                 () -> MemorySegment.ofArray(new float[] { 1.0f, 2.0f, 3.0f, 4.0f }),
140                 () -> MemorySegment.ofArray(new int[] { 1, 2, 3, 4 }),
141                 () -> MemorySegment.ofArray(new long[] { 1l, 2l, 3l, 4l } ),
142                 () -> MemorySegment.ofArray(new short[] { 1, 2, 3, 4 } ),
143                 () -> MemorySegment.allocateNative(4, ResourceScope.newImplicitScope()),
144                 () -> MemorySegment.allocateNative(4, 8, ResourceScope.newImplicitScope()),
145                 () -> MemorySegment.allocateNative(MemoryLayout.valueLayout(32, ByteOrder.nativeOrder()), ResourceScope.newImplicitScope()),
146                 () -> MemorySegment.allocateNative(4, ResourceScope.newConfinedScope()),
147                 () -> MemorySegment.allocateNative(4, 8, ResourceScope.newConfinedScope()),
148                 () -> MemorySegment.allocateNative(MemoryLayout.valueLayout(32, ByteOrder.nativeOrder()), ResourceScope.newConfinedScope())
149 
150         );
151         return l.stream().map(s -> new Object[] { s }).toArray(Object[][]::new);
152     }
153 
154     @Test(dataProvider = "segmentFactories")
155     public void testFill(Supplier<MemorySegment> memorySegmentSupplier) {
156         VarHandle byteHandle = MemoryLayout.sequenceLayout(MemoryLayouts.JAVA_BYTE)
157                 .varHandle(byte.class, MemoryLayout.PathElement.sequenceElement());
158 
159         for (byte value : new byte[] {(byte) 0xFF, (byte) 0x00, (byte) 0x45}) {
160             MemorySegment segment = memorySegmentSupplier.get();
161             segment.fill(value);
162             for (long l = 0; l < segment.byteSize(); l++) {
163                 assertEquals((byte) byteHandle.get(segment, l), value);
164             }
165 
166             // fill a slice
167             var sliceSegment = segment.asSlice(1, segment.byteSize() - 2).fill((byte) ~value);
168             for (long l = 0; l < sliceSegment.byteSize(); l++) {
169                 assertEquals((byte) byteHandle.get(sliceSegment, l), ~value);
170             }
171             // assert enclosing slice
172             assertEquals((byte) byteHandle.get(segment, 0L), value);
173             for (long l = 1; l < segment.byteSize() - 2; l++) {
174                 assertEquals((byte) byteHandle.get(segment, l), (byte) ~value);
175             }
176             assertEquals((byte) byteHandle.get(segment, segment.byteSize() - 1L), value);
177             tryClose(segment);
178         }
179     }
180 
181     @Test(dataProvider = "segmentFactories")
182     public void testFillClosed(Supplier<MemorySegment> memorySegmentSupplier) {
183         MemorySegment segment = memorySegmentSupplier.get();
184         tryClose(segment);
185         if (!segment.scope().isAlive()) {
186             try {
187                 segment.fill((byte) 0xFF);
188                 fail();
189             } catch (IllegalStateException ex) {
190                 assertTrue(true);
191             }
192         }
193     }
194 
195     @Test(dataProvider = "segmentFactories")
196     public void testNativeSegments(Supplier<MemorySegment> memorySegmentSupplier) throws Exception {
197         MemorySegment segment = memorySegmentSupplier.get();
198         try {
199             segment.address().toRawLongValue();
200             assertTrue(segment.isNative());
201             assertTrue(segment.address().isNative());
202         } catch (UnsupportedOperationException exception) {
203             assertFalse(segment.isNative());
204             assertFalse(segment.address().isNative());
205         }
206         tryClose(segment);
207     }
208 
209     @Test(dataProvider = "segmentFactories", expectedExceptions = UnsupportedOperationException.class)
210     public void testFillIllegalAccessMode(Supplier<MemorySegment> memorySegmentSupplier) {
211         MemorySegment segment = memorySegmentSupplier.get();
212         segment.asReadOnly().fill((byte) 0xFF);
213         tryClose(segment);
214     }
215 
216     @Test(dataProvider = "segmentFactories")
217     public void testFillThread(Supplier<MemorySegment> memorySegmentSupplier) throws Exception {
218         MemorySegment segment = memorySegmentSupplier.get();
219         AtomicReference<RuntimeException> exception = new AtomicReference<>();
220         Runnable action = () -> {
221             try {
222                 segment.fill((byte) 0xBA);
223             } catch (RuntimeException e) {
224                 exception.set(e);
225             }
226         };
227         Thread thread = new Thread(action);
228         thread.start();
229         thread.join();
230 
231         if (segment.scope().ownerThread() != null) {
232             RuntimeException e = exception.get();
233             if (!(e instanceof IllegalStateException)) {
234                 throw e;
235             }
236         } else {
237             assertNull(exception.get());
238         }
239         tryClose(segment);
240     }
241 
242     @Test
243     public void testFillEmpty() {
244         MemorySegment.ofArray(new byte[] { }).fill((byte) 0xFF);
245         MemorySegment.ofArray(new byte[2]).asSlice(0, 0).fill((byte) 0xFF);
246         MemorySegment.ofByteBuffer(ByteBuffer.allocateDirect(0)).fill((byte) 0xFF);
247     }
248 
249     @Test(dataProvider = "heapFactories")
250     public void testBigHeapSegments(IntFunction<MemorySegment> heapSegmentFactory, int factor) {
251         int bigSize = (Integer.MAX_VALUE / factor) + 1;
252         MemorySegment segment = heapSegmentFactory.apply(bigSize);
253         assertTrue(segment.byteSize() > 0);
254     }
255 
256     @DataProvider(name = "badSizeAndAlignments")
257     public Object[][] sizesAndAlignments() {
258         return new Object[][] {
259                 { -1, 8 },
260                 { 1, 15 },
261                 { 1, -15 }
262         };
263     }
264 
265     @DataProvider(name = "badLayouts")
266     public Object[][] layouts() {
267         SizedLayoutFactory[] layoutFactories = SizedLayoutFactory.values();
268         Object[][] values = new Object[layoutFactories.length * 2][2];
269         for (int i = 0; i < layoutFactories.length ; i++) {
270             values[i * 2] = new Object[] { MemoryLayout.structLayout(layoutFactories[i].make(7), MemoryLayout.paddingLayout(9)) }; // good size, bad align
271             values[(i * 2) + 1] = new Object[] { layoutFactories[i].make(15).withBitAlignment(16) }; // bad size, good align
272         }
273         return values;
274     }
275 
276     enum SizedLayoutFactory {
277         VALUE_BE(size -> MemoryLayout.valueLayout(size, ByteOrder.BIG_ENDIAN)),
278         VALUE_LE(size -> MemoryLayout.valueLayout(size, ByteOrder.LITTLE_ENDIAN)),
279         PADDING(MemoryLayout::paddingLayout);
280 
281         private final LongFunction<MemoryLayout> factory;
282 
283         SizedLayoutFactory(LongFunction<MemoryLayout> factory) {
284             this.factory = factory;
285         }
286 
287         MemoryLayout make(long size) {
288             return factory.apply(size);
289         }
290     }
291 
292     @DataProvider(name = "heapFactories")
293     public Object[][] heapFactories() {
294         return new Object[][] {
295                 { (IntFunction<MemorySegment>) size -> MemorySegment.ofArray(new char[size]), 2 },
296                 { (IntFunction<MemorySegment>) size -> MemorySegment.ofArray(new short[size]), 2 },
297                 { (IntFunction<MemorySegment>) size -> MemorySegment.ofArray(new int[size]), 4 },
298                 { (IntFunction<MemorySegment>) size -> MemorySegment.ofArray(new float[size]), 4 },
299                 { (IntFunction<MemorySegment>) size -> MemorySegment.ofArray(new long[size]), 8 },
300                 { (IntFunction<MemorySegment>) size -> MemorySegment.ofArray(new double[size]), 8 }
301         };
302     }
303 }