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