Path: blob/master/test/jdk/java/foreign/TestSegments.java
41145 views
/*1* Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @requires ((os.arch == "amd64" | os.arch == "x86_64") & sun.arch.data.model == "64") | os.arch == "aarch64"26* @run testng/othervm -Xmx4G -XX:MaxDirectMemorySize=1M TestSegments27*/2829import jdk.incubator.foreign.MemoryAccess;30import jdk.incubator.foreign.MemoryLayout;31import jdk.incubator.foreign.MemoryLayouts;32import jdk.incubator.foreign.MemorySegment;33import jdk.incubator.foreign.ResourceScope;34import org.testng.annotations.DataProvider;35import org.testng.annotations.Test;3637import java.lang.invoke.VarHandle;38import java.nio.ByteBuffer;39import java.nio.ByteOrder;40import java.util.List;41import java.util.concurrent.atomic.AtomicReference;42import java.util.function.IntFunction;43import java.util.function.LongFunction;44import java.util.function.Supplier;4546import static org.testng.Assert.*;4748public class TestSegments {4950@Test(dataProvider = "badSizeAndAlignments", expectedExceptions = IllegalArgumentException.class)51public void testBadAllocateAlign(long size, long align) {52MemorySegment.allocateNative(size, align, ResourceScope.newImplicitScope());53}5455@Test(dataProvider = "badLayouts", expectedExceptions = UnsupportedOperationException.class)56public void testBadAllocateLayout(MemoryLayout layout) {57MemorySegment.allocateNative(layout, ResourceScope.newImplicitScope());58}5960@Test(expectedExceptions = { OutOfMemoryError.class,61IllegalArgumentException.class })62public void testAllocateTooBig() {63MemorySegment.allocateNative(Long.MAX_VALUE, ResourceScope.newImplicitScope());64}6566@Test(expectedExceptions = OutOfMemoryError.class)67public void testNativeAllocationTooBig() {68MemorySegment segment = MemorySegment.allocateNative(1024 * 1024 * 8 * 2, ResourceScope.newImplicitScope()); // 2M69}7071@Test72public void testNativeSegmentIsZeroed() {73VarHandle byteHandle = MemoryLayout.sequenceLayout(MemoryLayouts.JAVA_BYTE)74.varHandle(byte.class, MemoryLayout.PathElement.sequenceElement());75try (ResourceScope scope = ResourceScope.newConfinedScope()) {76MemorySegment segment = MemorySegment.allocateNative(1000, 1, scope);77for (long i = 0 ; i < segment.byteSize() ; i++) {78assertEquals(0, (byte)byteHandle.get(segment, i));79}80}81}8283@Test84public void testSlices() {85VarHandle byteHandle = MemoryLayout.sequenceLayout(MemoryLayouts.JAVA_BYTE)86.varHandle(byte.class, MemoryLayout.PathElement.sequenceElement());87try (ResourceScope scope = ResourceScope.newConfinedScope()) {88MemorySegment segment = MemorySegment.allocateNative(10, 1, scope);89//init90for (byte i = 0 ; i < segment.byteSize() ; i++) {91byteHandle.set(segment, (long)i, i);92}93for (int offset = 0 ; offset < 10 ; offset++) {94MemorySegment slice = segment.asSlice(offset);95for (long i = offset ; i < 10 ; i++) {96assertEquals(97byteHandle.get(segment, i),98byteHandle.get(slice, i - offset)99);100}101}102}103}104105@Test(expectedExceptions = IndexOutOfBoundsException.class)106public void testSmallSegmentMax() {107long offset = (long)Integer.MAX_VALUE + (long)Integer.MAX_VALUE + 2L + 6L; // overflows to 6 when casted to int108MemorySegment memorySegment = MemorySegment.allocateNative(10, ResourceScope.newImplicitScope());109MemoryAccess.getIntAtOffset(memorySegment, offset);110}111112@Test(expectedExceptions = IndexOutOfBoundsException.class)113public void testSmallSegmentMin() {114long offset = ((long)Integer.MIN_VALUE * 2L) + 6L; // underflows to 6 when casted to int115MemorySegment memorySegment = MemorySegment.allocateNative(10, ResourceScope.newImplicitScope());116MemoryAccess.getIntAtOffset(memorySegment, offset);117}118119@Test(dataProvider = "segmentFactories")120public void testAccessModesOfFactories(Supplier<MemorySegment> memorySegmentSupplier) {121MemorySegment segment = memorySegmentSupplier.get();122assertFalse(segment.isReadOnly());123tryClose(segment);124}125126static void tryClose(MemorySegment segment) {127if (!segment.scope().isImplicit()) {128segment.scope().close();129}130}131132@DataProvider(name = "segmentFactories")133public Object[][] segmentFactories() {134List<Supplier<MemorySegment>> l = List.of(135() -> MemorySegment.ofArray(new byte[] { 0x00, 0x01, 0x02, 0x03 }),136() -> MemorySegment.ofArray(new char[] {'a', 'b', 'c', 'd' }),137() -> MemorySegment.ofArray(new double[] { 1d, 2d, 3d, 4d} ),138() -> MemorySegment.ofArray(new float[] { 1.0f, 2.0f, 3.0f, 4.0f }),139() -> MemorySegment.ofArray(new int[] { 1, 2, 3, 4 }),140() -> MemorySegment.ofArray(new long[] { 1l, 2l, 3l, 4l } ),141() -> MemorySegment.ofArray(new short[] { 1, 2, 3, 4 } ),142() -> MemorySegment.allocateNative(4, ResourceScope.newImplicitScope()),143() -> MemorySegment.allocateNative(4, 8, ResourceScope.newImplicitScope()),144() -> MemorySegment.allocateNative(MemoryLayout.valueLayout(32, ByteOrder.nativeOrder()), ResourceScope.newImplicitScope()),145() -> MemorySegment.allocateNative(4, ResourceScope.newConfinedScope()),146() -> MemorySegment.allocateNative(4, 8, ResourceScope.newConfinedScope()),147() -> MemorySegment.allocateNative(MemoryLayout.valueLayout(32, ByteOrder.nativeOrder()), ResourceScope.newConfinedScope())148149);150return l.stream().map(s -> new Object[] { s }).toArray(Object[][]::new);151}152153@Test(dataProvider = "segmentFactories")154public void testFill(Supplier<MemorySegment> memorySegmentSupplier) {155VarHandle byteHandle = MemoryLayout.sequenceLayout(MemoryLayouts.JAVA_BYTE)156.varHandle(byte.class, MemoryLayout.PathElement.sequenceElement());157158for (byte value : new byte[] {(byte) 0xFF, (byte) 0x00, (byte) 0x45}) {159MemorySegment segment = memorySegmentSupplier.get();160segment.fill(value);161for (long l = 0; l < segment.byteSize(); l++) {162assertEquals((byte) byteHandle.get(segment, l), value);163}164165// fill a slice166var sliceSegment = segment.asSlice(1, segment.byteSize() - 2).fill((byte) ~value);167for (long l = 0; l < sliceSegment.byteSize(); l++) {168assertEquals((byte) byteHandle.get(sliceSegment, l), ~value);169}170// assert enclosing slice171assertEquals((byte) byteHandle.get(segment, 0L), value);172for (long l = 1; l < segment.byteSize() - 2; l++) {173assertEquals((byte) byteHandle.get(segment, l), (byte) ~value);174}175assertEquals((byte) byteHandle.get(segment, segment.byteSize() - 1L), value);176tryClose(segment);177}178}179180@Test(dataProvider = "segmentFactories")181public void testFillClosed(Supplier<MemorySegment> memorySegmentSupplier) {182MemorySegment segment = memorySegmentSupplier.get();183tryClose(segment);184if (!segment.scope().isAlive()) {185try {186segment.fill((byte) 0xFF);187fail();188} catch (IllegalStateException ex) {189assertTrue(true);190}191}192}193194@Test(dataProvider = "segmentFactories")195public void testNativeSegments(Supplier<MemorySegment> memorySegmentSupplier) throws Exception {196MemorySegment segment = memorySegmentSupplier.get();197try {198segment.address().toRawLongValue();199assertTrue(segment.isNative());200assertTrue(segment.address().isNative());201} catch (UnsupportedOperationException exception) {202assertFalse(segment.isNative());203assertFalse(segment.address().isNative());204}205tryClose(segment);206}207208@Test(dataProvider = "segmentFactories", expectedExceptions = UnsupportedOperationException.class)209public void testFillIllegalAccessMode(Supplier<MemorySegment> memorySegmentSupplier) {210MemorySegment segment = memorySegmentSupplier.get();211segment.asReadOnly().fill((byte) 0xFF);212tryClose(segment);213}214215@Test(dataProvider = "segmentFactories")216public void testFillThread(Supplier<MemorySegment> memorySegmentSupplier) throws Exception {217MemorySegment segment = memorySegmentSupplier.get();218AtomicReference<RuntimeException> exception = new AtomicReference<>();219Runnable action = () -> {220try {221segment.fill((byte) 0xBA);222} catch (RuntimeException e) {223exception.set(e);224}225};226Thread thread = new Thread(action);227thread.start();228thread.join();229230if (segment.scope().ownerThread() != null) {231RuntimeException e = exception.get();232if (!(e instanceof IllegalStateException)) {233throw e;234}235} else {236assertNull(exception.get());237}238tryClose(segment);239}240241@Test242public void testFillEmpty() {243MemorySegment.ofArray(new byte[] { }).fill((byte) 0xFF);244MemorySegment.ofArray(new byte[2]).asSlice(0, 0).fill((byte) 0xFF);245MemorySegment.ofByteBuffer(ByteBuffer.allocateDirect(0)).fill((byte) 0xFF);246}247248@Test(dataProvider = "heapFactories")249public void testBigHeapSegments(IntFunction<MemorySegment> heapSegmentFactory, int factor) {250int bigSize = (Integer.MAX_VALUE / factor) + 1;251MemorySegment segment = heapSegmentFactory.apply(bigSize);252assertTrue(segment.byteSize() > 0);253}254255@DataProvider(name = "badSizeAndAlignments")256public Object[][] sizesAndAlignments() {257return new Object[][] {258{ -1, 8 },259{ 1, 15 },260{ 1, -15 }261};262}263264@DataProvider(name = "badLayouts")265public Object[][] layouts() {266SizedLayoutFactory[] layoutFactories = SizedLayoutFactory.values();267Object[][] values = new Object[layoutFactories.length * 2][2];268for (int i = 0; i < layoutFactories.length ; i++) {269values[i * 2] = new Object[] { MemoryLayout.structLayout(layoutFactories[i].make(7), MemoryLayout.paddingLayout(9)) }; // good size, bad align270values[(i * 2) + 1] = new Object[] { layoutFactories[i].make(15).withBitAlignment(16) }; // bad size, good align271}272return values;273}274275enum SizedLayoutFactory {276VALUE_BE(size -> MemoryLayout.valueLayout(size, ByteOrder.BIG_ENDIAN)),277VALUE_LE(size -> MemoryLayout.valueLayout(size, ByteOrder.LITTLE_ENDIAN)),278PADDING(MemoryLayout::paddingLayout);279280private final LongFunction<MemoryLayout> factory;281282SizedLayoutFactory(LongFunction<MemoryLayout> factory) {283this.factory = factory;284}285286MemoryLayout make(long size) {287return factory.apply(size);288}289}290291@DataProvider(name = "heapFactories")292public Object[][] heapFactories() {293return new Object[][] {294{ (IntFunction<MemorySegment>) size -> MemorySegment.ofArray(new char[size]), 2 },295{ (IntFunction<MemorySegment>) size -> MemorySegment.ofArray(new short[size]), 2 },296{ (IntFunction<MemorySegment>) size -> MemorySegment.ofArray(new int[size]), 4 },297{ (IntFunction<MemorySegment>) size -> MemorySegment.ofArray(new float[size]), 4 },298{ (IntFunction<MemorySegment>) size -> MemorySegment.ofArray(new long[size]), 8 },299{ (IntFunction<MemorySegment>) size -> MemorySegment.ofArray(new double[size]), 8 }300};301}302}303304305