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