File: TestNative.java

package info (click to toggle)
openjdk-21 21.0.8%2B9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 823,976 kB
  • sloc: java: 5,613,338; xml: 1,643,607; cpp: 1,296,296; ansic: 420,291; asm: 404,850; objc: 20,994; sh: 15,271; javascript: 11,245; python: 6,895; makefile: 2,362; perl: 357; awk: 351; sed: 172; jsp: 24; csh: 3
file content (263 lines) | stat: -rw-r--r-- 12,181 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/*
 * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved.
 *  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 *  This code is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License version 2 only, as
 *  published by the Free Software Foundation.
 *
 *  This code is distributed in the hope that it will be useful, but WITHOUT
 *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 *  version 2 for more details (a copy is included in the LICENSE file that
 *  accompanied this code).
 *
 *  You should have received a copy of the GNU General Public License version
 *  2 along with this work; if not, write to the Free Software Foundation,
 *  Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 *   Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 *  or visit www.oracle.com if you need additional information or have any
 *  questions.
 *
 */

/*
 * @test
 * @enablePreview
 * @requires jdk.foreign.linker != "UNSUPPORTED"
 * @run testng/othervm --enable-native-access=ALL-UNNAMED TestNative
 */

import java.lang.foreign.*;
import java.lang.foreign.MemoryLayout.PathElement;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.lang.invoke.VarHandle;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;

import static java.lang.foreign.ValueLayout.JAVA_INT;
import static org.testng.Assert.*;

public class TestNative extends NativeTestHelper {

    static SequenceLayout bytes = MemoryLayout.sequenceLayout(100,
            ValueLayout.JAVA_BYTE.withOrder(ByteOrder.nativeOrder())
    );

    static SequenceLayout chars = MemoryLayout.sequenceLayout(100,
            ValueLayout.JAVA_CHAR.withOrder(ByteOrder.nativeOrder())
    );

    static SequenceLayout shorts = MemoryLayout.sequenceLayout(100,
            ValueLayout.JAVA_SHORT.withOrder(ByteOrder.nativeOrder())
    );

    static SequenceLayout ints = MemoryLayout.sequenceLayout(100,
            JAVA_INT.withOrder(ByteOrder.nativeOrder())
    );

    static SequenceLayout floats = MemoryLayout.sequenceLayout(100,
            ValueLayout.JAVA_FLOAT.withOrder(ByteOrder.nativeOrder())
    );

    static SequenceLayout longs = MemoryLayout.sequenceLayout(100,
            ValueLayout.JAVA_LONG.withOrder(ByteOrder.nativeOrder())
    );

    static SequenceLayout doubles = MemoryLayout.sequenceLayout(100,
            ValueLayout.JAVA_DOUBLE.withOrder(ByteOrder.nativeOrder())
    );

    static VarHandle byteHandle = bytes.varHandle(PathElement.sequenceElement());
    static VarHandle charHandle = chars.varHandle(PathElement.sequenceElement());
    static VarHandle shortHandle = shorts.varHandle(PathElement.sequenceElement());
    static VarHandle intHandle = ints.varHandle(PathElement.sequenceElement());
    static VarHandle floatHandle = floats.varHandle(PathElement.sequenceElement());
    static VarHandle longHandle = longs.varHandle(PathElement.sequenceElement());
    static VarHandle doubleHandle = doubles.varHandle(PathElement.sequenceElement());

    static void initBytes(MemorySegment base, SequenceLayout seq, BiConsumer<MemorySegment, Long> handleSetter) {
        for (long i = 0; i < seq.elementCount() ; i++) {
            handleSetter.accept(base, i);
        }
    }

    static <Z extends Buffer> void checkBytes(MemorySegment base, SequenceLayout layout,
                                              BiFunction<MemorySegment, Long, Object> handleExtractor,
                                              Function<ByteBuffer, Z> bufferFactory,
                                              BiFunction<Z, Integer, Object> nativeBufferExtractor,
                                              BiFunction<Long, Integer, Object> nativeRawExtractor) {
        long nelems = layout.elementCount();
        ByteBuffer bb = base.asByteBuffer();
        Z z = bufferFactory.apply(bb);
        for (long i = 0 ; i < nelems ; i++) {
            Object handleValue = handleExtractor.apply(base, i);
            Object bufferValue = nativeBufferExtractor.apply(z, (int)i);
            Object rawValue = nativeRawExtractor.apply(base.address(), (int)i);
            if (handleValue instanceof Number) {
                assertEquals(((Number)handleValue).longValue(), i);
                assertEquals(((Number)bufferValue).longValue(), i);
                assertEquals(((Number)rawValue).longValue(), i);
            } else {
                assertEquals((long)(char)handleValue, i);
                assertEquals((long)(char)bufferValue, i);
                assertEquals((long)(char)rawValue, i);
            }
        }
    }

    public static native byte getByteBuffer(ByteBuffer buf, int index);
    public static native char getCharBuffer(CharBuffer buf, int index);
    public static native short getShortBuffer(ShortBuffer buf, int index);
    public static native int getIntBuffer(IntBuffer buf, int index);
    public static native float getFloatBuffer(FloatBuffer buf, int index);
    public static native long getLongBuffer(LongBuffer buf, int index);
    public static native double getDoubleBuffer(DoubleBuffer buf, int index);

    public static native byte getByteRaw(long addr, int index);
    public static native char getCharRaw(long addr, int index);
    public static native short getShortRaw(long addr, int index);
    public static native int getIntRaw(long addr, int index);
    public static native float getFloatRaw(long addr, int index);
    public static native long getLongRaw(long addr, int index);
    public static native double getDoubleRaw(long addr, int index);

    public static native long getCapacity(Buffer buffer);

    @Test(dataProvider="nativeAccessOps")
    public void testNativeAccess(Consumer<MemorySegment> checker, Consumer<MemorySegment> initializer, SequenceLayout seq) {
        try (Arena arena = Arena.ofConfined()) {
            MemorySegment segment = arena.allocate(seq);;
            initializer.accept(segment);
            checker.accept(segment);
        }
    }

    @Test(dataProvider="buffers")
    public void testNativeCapacity(Function<ByteBuffer, Buffer> bufferFunction, int elemSize) {
        int capacity = (int)doubles.byteSize();
        try (Arena arena = Arena.ofConfined()) {
            MemorySegment segment = arena.allocate(doubles);;
            ByteBuffer bb = segment.asByteBuffer();
            Buffer buf = bufferFunction.apply(bb);
            int expected = capacity / elemSize;
            assertEquals(buf.capacity(), expected);
            assertEquals(getCapacity(buf), expected);
        }
    }

    @Test
    public void testDefaultAccessModes() {
        MemorySegment addr = allocateMemory(12);
        try (Arena arena = Arena.ofConfined()) {
            MemorySegment mallocSegment = addr.asSlice(0, 12)
                    .reinterpret(arena, TestNative::freeMemory);
            assertFalse(mallocSegment.isReadOnly());
        }
    }

    @Test
    public void testMallocSegment() {
        MemorySegment addr = allocateMemory(12);
        MemorySegment mallocSegment = null;
        try (Arena arena = Arena.ofConfined()) {
            mallocSegment = addr.asSlice(0, 12)
                    .reinterpret(arena, TestNative::freeMemory);
            assertEquals(mallocSegment.byteSize(), 12);
            //free here
        }
        assertTrue(!mallocSegment.scope().isAlive());
    }

    @Test
    public void testAddressAccess() {
        MemorySegment addr = allocateMemory(4);
        addr.set(JAVA_INT, 0, 42);
        assertEquals(addr.get(JAVA_INT, 0), 42);
        freeMemory(addr);
    }

    @Test
    public void testBadResize() {
        try (Arena arena = Arena.ofConfined()) {
            MemorySegment segment = arena.allocate(4, 1);
            assertThrows(IllegalArgumentException.class, () -> segment.reinterpret(-1));
            assertThrows(IllegalArgumentException.class, () -> segment.reinterpret(-1, Arena.ofAuto(), null));
        }
    }

    static {
        System.loadLibrary("NativeAccess");
    }

    @DataProvider(name = "nativeAccessOps")
    public Object[][] nativeAccessOps() {
        Consumer<MemorySegment> byteInitializer =
                (base) -> initBytes(base, bytes, (addr, pos) -> byteHandle.set(addr, pos, (byte)(long)pos));
        Consumer<MemorySegment> charInitializer =
                (base) -> initBytes(base, chars, (addr, pos) -> charHandle.set(addr, pos, (char)(long)pos));
        Consumer<MemorySegment> shortInitializer =
                (base) -> initBytes(base, shorts, (addr, pos) -> shortHandle.set(addr, pos, (short)(long)pos));
        Consumer<MemorySegment> intInitializer =
                (base) -> initBytes(base, ints, (addr, pos) -> intHandle.set(addr, pos, (int)(long)pos));
        Consumer<MemorySegment> floatInitializer =
                (base) -> initBytes(base, floats, (addr, pos) -> floatHandle.set(addr, pos, (float)(long)pos));
        Consumer<MemorySegment> longInitializer =
                (base) -> initBytes(base, longs, (addr, pos) -> longHandle.set(addr, pos, (long)pos));
        Consumer<MemorySegment> doubleInitializer =
                (base) -> initBytes(base, doubles, (addr, pos) -> doubleHandle.set(addr, pos, (double)(long)pos));

        Consumer<MemorySegment> byteChecker =
                (base) -> checkBytes(base, bytes, byteHandle::get, bb -> bb, TestNative::getByteBuffer, TestNative::getByteRaw);
        Consumer<MemorySegment> charChecker =
                (base) -> checkBytes(base, chars, charHandle::get, ByteBuffer::asCharBuffer, TestNative::getCharBuffer, TestNative::getCharRaw);
        Consumer<MemorySegment> shortChecker =
                (base) -> checkBytes(base, shorts, shortHandle::get, ByteBuffer::asShortBuffer, TestNative::getShortBuffer, TestNative::getShortRaw);
        Consumer<MemorySegment> intChecker =
                (base) -> checkBytes(base, ints, intHandle::get, ByteBuffer::asIntBuffer, TestNative::getIntBuffer, TestNative::getIntRaw);
        Consumer<MemorySegment> floatChecker =
                (base) -> checkBytes(base, floats, floatHandle::get, ByteBuffer::asFloatBuffer, TestNative::getFloatBuffer, TestNative::getFloatRaw);
        Consumer<MemorySegment> longChecker =
                (base) -> checkBytes(base, longs, longHandle::get, ByteBuffer::asLongBuffer, TestNative::getLongBuffer, TestNative::getLongRaw);
        Consumer<MemorySegment> doubleChecker =
                (base) -> checkBytes(base, doubles, doubleHandle::get, ByteBuffer::asDoubleBuffer, TestNative::getDoubleBuffer, TestNative::getDoubleRaw);

        return new Object[][]{
                {byteChecker, byteInitializer, bytes},
                {charChecker, charInitializer, chars},
                {shortChecker, shortInitializer, shorts},
                {intChecker, intInitializer, ints},
                {floatChecker, floatInitializer, floats},
                {longChecker, longInitializer, longs},
                {doubleChecker, doubleInitializer, doubles}
        };
    }

    @DataProvider(name = "buffers")
    public Object[][] buffers() {
        return new Object[][] {
                { (Function<ByteBuffer, Buffer>)bb -> bb, 1 },
                { (Function<ByteBuffer, Buffer>)ByteBuffer::asCharBuffer, 2 },
                { (Function<ByteBuffer, Buffer>)ByteBuffer::asShortBuffer, 2 },
                { (Function<ByteBuffer, Buffer>)ByteBuffer::asIntBuffer, 4 },
                { (Function<ByteBuffer, Buffer>)ByteBuffer::asFloatBuffer, 4 },
                { (Function<ByteBuffer, Buffer>)ByteBuffer::asLongBuffer, 8 },
                { (Function<ByteBuffer, Buffer>)ByteBuffer::asDoubleBuffer, 8 },
        };
    }
}