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