1 /*
  2  * Copyright (c) 2019, 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  * @requires ((os.arch == "amd64" | os.arch == "x86_64") & sun.arch.data.model == "64") | os.arch == "aarch64"
 28  * @modules jdk.incubator.foreign/jdk.internal.foreign
 29  * @run testng/othervm --enable-native-access=ALL-UNNAMED TestNative
 30  */
 31 
 32 import jdk.incubator.foreign.MemoryAddress;
 33 import jdk.incubator.foreign.MemoryLayout;
 34 import jdk.incubator.foreign.MemoryLayout.PathElement;
 35 import jdk.incubator.foreign.MemorySegment;
 36 import jdk.incubator.foreign.ResourceScope;
 37 import jdk.incubator.foreign.SequenceLayout;
 38 import jdk.incubator.foreign.ValueLayout;
 39 import org.testng.annotations.DataProvider;
 40 import org.testng.annotations.Test;
 41 
 42 import java.lang.invoke.VarHandle;
 43 import java.nio.Buffer;
 44 import java.nio.ByteBuffer;
 45 import java.nio.ByteOrder;
 46 import java.nio.CharBuffer;
 47 import java.nio.DoubleBuffer;
 48 import java.nio.FloatBuffer;
 49 import java.nio.IntBuffer;
 50 import java.nio.LongBuffer;
 51 import java.nio.ShortBuffer;
 52 import java.util.function.BiConsumer;
 53 import java.util.function.BiFunction;
 54 import java.util.function.Consumer;
 55 import java.util.function.Function;
 56 
 57 import static jdk.incubator.foreign.ValueLayout.JAVA_INT;
 58 import static org.testng.Assert.*;
 59 
 60 public class TestNative extends NativeTestHelper {
 61 
 62     static SequenceLayout bytes = MemoryLayout.sequenceLayout(100,
 63             ValueLayout.JAVA_BYTE.withOrder(ByteOrder.nativeOrder())
 64     );
 65 
 66     static SequenceLayout chars = MemoryLayout.sequenceLayout(100,
 67             ValueLayout.JAVA_CHAR.withOrder(ByteOrder.nativeOrder())
 68     );
 69 
 70     static SequenceLayout shorts = MemoryLayout.sequenceLayout(100,
 71             ValueLayout.JAVA_SHORT.withOrder(ByteOrder.nativeOrder())
 72     );
 73 
 74     static SequenceLayout ints = MemoryLayout.sequenceLayout(100,
 75             JAVA_INT.withOrder(ByteOrder.nativeOrder())
 76     );
 77 
 78     static SequenceLayout floats = MemoryLayout.sequenceLayout(100,
 79             ValueLayout.JAVA_FLOAT.withOrder(ByteOrder.nativeOrder())
 80     );
 81 
 82     static SequenceLayout longs = MemoryLayout.sequenceLayout(100,
 83             ValueLayout.JAVA_LONG.withOrder(ByteOrder.nativeOrder())
 84     );
 85 
 86     static SequenceLayout doubles = MemoryLayout.sequenceLayout(100,
 87             ValueLayout.JAVA_DOUBLE.withOrder(ByteOrder.nativeOrder())
 88     );
 89 
 90     static VarHandle byteHandle = bytes.varHandle(PathElement.sequenceElement());
 91     static VarHandle charHandle = chars.varHandle(PathElement.sequenceElement());
 92     static VarHandle shortHandle = shorts.varHandle(PathElement.sequenceElement());
 93     static VarHandle intHandle = ints.varHandle(PathElement.sequenceElement());
 94     static VarHandle floatHandle = floats.varHandle(PathElement.sequenceElement());
 95     static VarHandle longHandle = longs.varHandle(PathElement.sequenceElement());
 96     static VarHandle doubleHandle = doubles.varHandle(PathElement.sequenceElement());
 97 
 98     static void initBytes(MemorySegment base, SequenceLayout seq, BiConsumer<MemorySegment, Long> handleSetter) {
 99         for (long i = 0; i < seq.elementCount().getAsLong() ; i++) {
100             handleSetter.accept(base, i);
101         }
102     }
103 
104     static <Z extends Buffer> void checkBytes(MemorySegment base, SequenceLayout layout,
105                                               BiFunction<MemorySegment, Long, Object> handleExtractor,
106                                               Function<ByteBuffer, Z> bufferFactory,
107                                               BiFunction<Z, Integer, Object> nativeBufferExtractor,
108                                               BiFunction<Long, Integer, Object> nativeRawExtractor) {
109         long nelems = layout.elementCount().getAsLong();
110         ByteBuffer bb = base.asByteBuffer();
111         Z z = bufferFactory.apply(bb);
112         for (long i = 0 ; i < nelems ; i++) {
113             Object handleValue = handleExtractor.apply(base, i);
114             Object bufferValue = nativeBufferExtractor.apply(z, (int)i);
115             Object rawValue = nativeRawExtractor.apply(base.address().toRawLongValue(), (int)i);
116             if (handleValue instanceof Number) {
117                 assertEquals(((Number)handleValue).longValue(), i);
118                 assertEquals(((Number)bufferValue).longValue(), i);
119                 assertEquals(((Number)rawValue).longValue(), i);
120             } else {
121                 assertEquals((long)(char)handleValue, i);
122                 assertEquals((long)(char)bufferValue, i);
123                 assertEquals((long)(char)rawValue, i);
124             }
125         }
126     }
127 
128     public static native byte getByteBuffer(ByteBuffer buf, int index);
129     public static native char getCharBuffer(CharBuffer buf, int index);
130     public static native short getShortBuffer(ShortBuffer buf, int index);
131     public static native int getIntBuffer(IntBuffer buf, int index);
132     public static native float getFloatBuffer(FloatBuffer buf, int index);
133     public static native long getLongBuffer(LongBuffer buf, int index);
134     public static native double getDoubleBuffer(DoubleBuffer buf, int index);
135 
136     public static native byte getByteRaw(long addr, int index);
137     public static native char getCharRaw(long addr, int index);
138     public static native short getShortRaw(long addr, int index);
139     public static native int getIntRaw(long addr, int index);
140     public static native float getFloatRaw(long addr, int index);
141     public static native long getLongRaw(long addr, int index);
142     public static native double getDoubleRaw(long addr, int index);
143 
144     public static native long getCapacity(Buffer buffer);
145 
146     @Test(dataProvider="nativeAccessOps")
147     public void testNativeAccess(Consumer<MemorySegment> checker, Consumer<MemorySegment> initializer, SequenceLayout seq) {
148         try (ResourceScope scope = ResourceScope.newConfinedScope()) {
149             MemorySegment segment = MemorySegment.allocateNative(seq, scope);
150             initializer.accept(segment);
151             checker.accept(segment);
152         }
153     }
154 
155     @Test(dataProvider="buffers")
156     public void testNativeCapacity(Function<ByteBuffer, Buffer> bufferFunction, int elemSize) {
157         int capacity = (int)doubles.byteSize();
158         try (ResourceScope scope = ResourceScope.newConfinedScope()) {
159             MemorySegment segment = MemorySegment.allocateNative(doubles, scope);
160             ByteBuffer bb = segment.asByteBuffer();
161             Buffer buf = bufferFunction.apply(bb);
162             int expected = capacity / elemSize;
163             assertEquals(buf.capacity(), expected);
164             assertEquals(getCapacity(buf), expected);
165         }
166     }
167 
168     @Test
169     public void testDefaultAccessModes() {
170         MemoryAddress addr = allocateMemory(12);
171         try (ResourceScope scope = ResourceScope.newConfinedScope()) {
172             scope.addCloseAction(() -> freeMemory(addr));
173             MemorySegment mallocSegment = MemorySegment.ofAddressNative(addr, 12, scope);
174             assertFalse(mallocSegment.isReadOnly());
175         }
176     }
177 
178     @Test
179     public void testMallocSegment() {
180         MemoryAddress addr = allocateMemory(12);
181         MemorySegment mallocSegment = null;
182         try (ResourceScope scope = ResourceScope.newConfinedScope()) {
183             scope.addCloseAction(() -> freeMemory(addr));
184             mallocSegment = MemorySegment.ofAddressNative(addr, 12, scope);
185             assertEquals(mallocSegment.byteSize(), 12);
186             //free here
187         }
188         assertTrue(!mallocSegment.scope().isAlive());
189     }
190 
191     @Test
192     public void testAddressAccess() {
193         MemoryAddress addr = allocateMemory(4);
194         addr.set(JAVA_INT, 0, 42);
195         assertEquals(addr.get(JAVA_INT, 0), 42);
196         freeMemory(addr);
197     }
198 
199     @Test(expectedExceptions = IllegalArgumentException.class)
200     public void testBadResize() {
201         try (ResourceScope scope = ResourceScope.newConfinedScope()) {
202             MemorySegment segment = MemorySegment.allocateNative(4, 1, scope);
203             MemorySegment.ofAddressNative(segment.address(), 0, ResourceScope.globalScope());
204         }
205     }
206 
207     static {
208         System.loadLibrary("NativeAccess");
209     }
210 
211     @DataProvider(name = "nativeAccessOps")
212     public Object[][] nativeAccessOps() {
213         Consumer<MemorySegment> byteInitializer =
214                 (base) -> initBytes(base, bytes, (addr, pos) -> byteHandle.set(addr, pos, (byte)(long)pos));
215         Consumer<MemorySegment> charInitializer =
216                 (base) -> initBytes(base, chars, (addr, pos) -> charHandle.set(addr, pos, (char)(long)pos));
217         Consumer<MemorySegment> shortInitializer =
218                 (base) -> initBytes(base, shorts, (addr, pos) -> shortHandle.set(addr, pos, (short)(long)pos));
219         Consumer<MemorySegment> intInitializer =
220                 (base) -> initBytes(base, ints, (addr, pos) -> intHandle.set(addr, pos, (int)(long)pos));
221         Consumer<MemorySegment> floatInitializer =
222                 (base) -> initBytes(base, floats, (addr, pos) -> floatHandle.set(addr, pos, (float)(long)pos));
223         Consumer<MemorySegment> longInitializer =
224                 (base) -> initBytes(base, longs, (addr, pos) -> longHandle.set(addr, pos, (long)pos));
225         Consumer<MemorySegment> doubleInitializer =
226                 (base) -> initBytes(base, doubles, (addr, pos) -> doubleHandle.set(addr, pos, (double)(long)pos));
227 
228         Consumer<MemorySegment> byteChecker =
229                 (base) -> checkBytes(base, bytes, byteHandle::get, bb -> bb, TestNative::getByteBuffer, TestNative::getByteRaw);
230         Consumer<MemorySegment> charChecker =
231                 (base) -> checkBytes(base, chars, charHandle::get, ByteBuffer::asCharBuffer, TestNative::getCharBuffer, TestNative::getCharRaw);
232         Consumer<MemorySegment> shortChecker =
233                 (base) -> checkBytes(base, shorts, shortHandle::get, ByteBuffer::asShortBuffer, TestNative::getShortBuffer, TestNative::getShortRaw);
234         Consumer<MemorySegment> intChecker =
235                 (base) -> checkBytes(base, ints, intHandle::get, ByteBuffer::asIntBuffer, TestNative::getIntBuffer, TestNative::getIntRaw);
236         Consumer<MemorySegment> floatChecker =
237                 (base) -> checkBytes(base, floats, floatHandle::get, ByteBuffer::asFloatBuffer, TestNative::getFloatBuffer, TestNative::getFloatRaw);
238         Consumer<MemorySegment> longChecker =
239                 (base) -> checkBytes(base, longs, longHandle::get, ByteBuffer::asLongBuffer, TestNative::getLongBuffer, TestNative::getLongRaw);
240         Consumer<MemorySegment> doubleChecker =
241                 (base) -> checkBytes(base, doubles, doubleHandle::get, ByteBuffer::asDoubleBuffer, TestNative::getDoubleBuffer, TestNative::getDoubleRaw);
242 
243         return new Object[][]{
244                 {byteChecker, byteInitializer, bytes},
245                 {charChecker, charInitializer, chars},
246                 {shortChecker, shortInitializer, shorts},
247                 {intChecker, intInitializer, ints},
248                 {floatChecker, floatInitializer, floats},
249                 {longChecker, longInitializer, longs},
250                 {doubleChecker, doubleInitializer, doubles}
251         };
252     }
253 
254     @DataProvider(name = "buffers")
255     public Object[][] buffers() {
256         return new Object[][] {
257                 { (Function<ByteBuffer, Buffer>)bb -> bb, 1 },
258                 { (Function<ByteBuffer, Buffer>)ByteBuffer::asCharBuffer, 2 },
259                 { (Function<ByteBuffer, Buffer>)ByteBuffer::asShortBuffer, 2 },
260                 { (Function<ByteBuffer, Buffer>)ByteBuffer::asIntBuffer, 4 },
261                 { (Function<ByteBuffer, Buffer>)ByteBuffer::asFloatBuffer, 4 },
262                 { (Function<ByteBuffer, Buffer>)ByteBuffer::asLongBuffer, 8 },
263                 { (Function<ByteBuffer, Buffer>)ByteBuffer::asDoubleBuffer, 8 },
264         };
265     }
266 }