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