Path: blob/master/test/jdk/java/foreign/StdLibTest.java
66643 views
/*1* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @requires ((os.arch == "amd64" | os.arch == "x86_64") & sun.arch.data.model == "64") | os.arch == "aarch64"26* @run testng/othervm --enable-native-access=ALL-UNNAMED StdLibTest27*/2829import java.lang.invoke.MethodHandle;30import java.lang.invoke.MethodHandles;31import java.lang.invoke.MethodType;32import java.time.Instant;33import java.time.LocalDateTime;34import java.time.ZoneOffset;35import java.time.ZonedDateTime;36import java.util.ArrayList;37import java.util.Arrays;38import java.util.Collections;39import java.util.LinkedHashSet;40import java.util.List;41import java.util.Optional;42import java.util.Set;43import java.util.function.BiConsumer;44import java.util.function.Function;45import java.util.stream.Collectors;46import java.util.stream.Stream;4748import jdk.incubator.foreign.*;4950import static jdk.incubator.foreign.MemoryAccess.*;5152import org.testng.annotations.*;5354import static jdk.incubator.foreign.CLinker.*;55import static org.testng.Assert.*;5657@Test58public class StdLibTest {5960final static CLinker abi = CLinker.getInstance();6162private StdLibHelper stdLibHelper = new StdLibHelper();6364@Test(dataProvider = "stringPairs")65void test_strcat(String s1, String s2) throws Throwable {66assertEquals(stdLibHelper.strcat(s1, s2), s1 + s2);67}6869@Test(dataProvider = "stringPairs")70void test_strcmp(String s1, String s2) throws Throwable {71assertEquals(Math.signum(stdLibHelper.strcmp(s1, s2)), Math.signum(s1.compareTo(s2)));72}7374@Test(dataProvider = "strings")75void test_puts(String s) throws Throwable {76assertTrue(stdLibHelper.puts(s) >= 0);77}7879@Test(dataProvider = "strings")80void test_strlen(String s) throws Throwable {81assertEquals(stdLibHelper.strlen(s), s.length());82}8384@Test(dataProvider = "instants")85void test_time(Instant instant) throws Throwable {86StdLibHelper.Tm tm = stdLibHelper.gmtime(instant.getEpochSecond());87LocalDateTime localTime = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);88assertEquals(tm.sec(), localTime.getSecond());89assertEquals(tm.min(), localTime.getMinute());90assertEquals(tm.hour(), localTime.getHour());91//day pf year in Java has 1-offset92assertEquals(tm.yday(), localTime.getDayOfYear() - 1);93assertEquals(tm.mday(), localTime.getDayOfMonth());94//days of week starts from Sunday in C, but on Monday in Java, also account for 1-offset95assertEquals((tm.wday() + 6) % 7, localTime.getDayOfWeek().getValue() - 1);96//month in Java has 1-offset97assertEquals(tm.mon(), localTime.getMonth().getValue() - 1);98assertEquals(tm.isdst(), ZoneOffset.UTC.getRules()99.isDaylightSavings(Instant.ofEpochMilli(instant.getEpochSecond() * 1000)));100}101102@Test(dataProvider = "ints")103void test_qsort(List<Integer> ints) throws Throwable {104if (ints.size() > 0) {105int[] input = ints.stream().mapToInt(i -> i).toArray();106int[] sorted = stdLibHelper.qsort(input);107Arrays.sort(input);108assertEquals(sorted, input);109}110}111112@Test113void test_rand() throws Throwable {114int val = stdLibHelper.rand();115for (int i = 0 ; i < 100 ; i++) {116int newVal = stdLibHelper.rand();117if (newVal != val) {118return; //ok119}120val = newVal;121}122fail("All values are the same! " + val);123}124125@Test(dataProvider = "printfArgs")126void test_printf(List<PrintfArg> args) throws Throwable {127String formatArgs = args.stream()128.map(a -> a.format)129.collect(Collectors.joining(","));130131String formatString = "hello(" + formatArgs + ")\n";132133String expected = String.format(formatString, args.stream()134.map(a -> a.javaValue).toArray());135136int found = stdLibHelper.printf(formatString, args);137assertEquals(found, expected.length());138}139140@Test(dataProvider = "printfArgs")141void test_vprintf(List<PrintfArg> args) throws Throwable {142String formatArgs = args.stream()143.map(a -> a.format)144.collect(Collectors.joining(","));145146String formatString = "hello(" + formatArgs + ")\n";147148String expected = String.format(formatString, args.stream()149.map(a -> a.javaValue).toArray());150151int found = stdLibHelper.vprintf(formatString, args);152assertEquals(found, expected.length());153}154155static class StdLibHelper {156157static final SymbolLookup LOOKUP = CLinker.systemLookup();158159final static MethodHandle strcat = abi.downcallHandle(LOOKUP.lookup("strcat").get(),160MethodType.methodType(MemoryAddress.class, MemoryAddress.class, MemoryAddress.class),161FunctionDescriptor.of(C_POINTER, C_POINTER, C_POINTER));162163final static MethodHandle strcmp = abi.downcallHandle(LOOKUP.lookup("strcmp").get(),164MethodType.methodType(int.class, MemoryAddress.class, MemoryAddress.class),165FunctionDescriptor.of(C_INT, C_POINTER, C_POINTER));166167final static MethodHandle puts = abi.downcallHandle(LOOKUP.lookup("puts").get(),168MethodType.methodType(int.class, MemoryAddress.class),169FunctionDescriptor.of(C_INT, C_POINTER));170171final static MethodHandle strlen = abi.downcallHandle(LOOKUP.lookup("strlen").get(),172MethodType.methodType(int.class, MemoryAddress.class),173FunctionDescriptor.of(C_INT, C_POINTER));174175final static MethodHandle gmtime = abi.downcallHandle(LOOKUP.lookup("gmtime").get(),176MethodType.methodType(MemoryAddress.class, MemoryAddress.class),177FunctionDescriptor.of(C_POINTER, C_POINTER));178179final static MethodHandle qsort = abi.downcallHandle(LOOKUP.lookup("qsort").get(),180MethodType.methodType(void.class, MemoryAddress.class, long.class, long.class, MemoryAddress.class),181FunctionDescriptor.ofVoid(C_POINTER, C_LONG_LONG, C_LONG_LONG, C_POINTER));182183final static FunctionDescriptor qsortComparFunction = FunctionDescriptor.of(C_INT, C_POINTER, C_POINTER);184185final static MethodHandle qsortCompar;186187final static MethodHandle rand = abi.downcallHandle(LOOKUP.lookup("rand").get(),188MethodType.methodType(int.class),189FunctionDescriptor.of(C_INT));190191final static MethodHandle vprintf = abi.downcallHandle(LOOKUP.lookup("vprintf").get(),192MethodType.methodType(int.class, MemoryAddress.class, VaList.class),193FunctionDescriptor.of(C_INT, C_POINTER, C_VA_LIST));194195final static MemoryAddress printfAddr = LOOKUP.lookup("printf").get();196197final static FunctionDescriptor printfBase = FunctionDescriptor.of(C_INT, C_POINTER);198199static {200try {201//qsort upcall handle202qsortCompar = MethodHandles.lookup().findStatic(StdLibTest.StdLibHelper.class, "qsortCompare",203MethodType.methodType(int.class, MemorySegment.class, MemoryAddress.class, MemoryAddress.class));204} catch (ReflectiveOperationException ex) {205throw new IllegalStateException(ex);206}207}208209String strcat(String s1, String s2) throws Throwable {210try (ResourceScope scope = ResourceScope.newConfinedScope()) {211MemorySegment buf = MemorySegment.allocateNative(s1.length() + s2.length() + 1, scope);212MemorySegment other = toCString(s2, scope);213char[] chars = s1.toCharArray();214for (long i = 0 ; i < chars.length ; i++) {215setByteAtOffset(buf, i, (byte)chars[(int)i]);216}217setByteAtOffset(buf, chars.length, (byte)'\0');218return toJavaString(((MemoryAddress)strcat.invokeExact(buf.address(), other.address())));219}220}221222int strcmp(String s1, String s2) throws Throwable {223try (ResourceScope scope = ResourceScope.newConfinedScope()) {224MemorySegment ns1 = toCString(s1, scope);225MemorySegment ns2 = toCString(s2, scope);226return (int)strcmp.invokeExact(ns1.address(), ns2.address());227}228}229230int puts(String msg) throws Throwable {231try (ResourceScope scope = ResourceScope.newConfinedScope()) {232MemorySegment s = toCString(msg, scope);233return (int)puts.invokeExact(s.address());234}235}236237int strlen(String msg) throws Throwable {238try (ResourceScope scope = ResourceScope.newConfinedScope()) {239MemorySegment s = toCString(msg, scope);240return (int)strlen.invokeExact(s.address());241}242}243244Tm gmtime(long arg) throws Throwable {245try (ResourceScope scope = ResourceScope.newConfinedScope()) {246MemorySegment time = MemorySegment.allocateNative(8, scope);247setLong(time, arg);248return new Tm((MemoryAddress)gmtime.invokeExact(time.address()));249}250}251252static class Tm {253254//Tm pointer should never be freed directly, as it points to shared memory255private final MemorySegment base;256257static final long SIZE = 56;258259Tm(MemoryAddress addr) {260this.base = addr.asSegment(SIZE, ResourceScope.globalScope());261}262263int sec() {264return getIntAtOffset(base, 0);265}266int min() {267return getIntAtOffset(base, 4);268}269int hour() {270return getIntAtOffset(base, 8);271}272int mday() {273return getIntAtOffset(base, 12);274}275int mon() {276return getIntAtOffset(base, 16);277}278int year() {279return getIntAtOffset(base, 20);280}281int wday() {282return getIntAtOffset(base, 24);283}284int yday() {285return getIntAtOffset(base, 28);286}287boolean isdst() {288byte b = getByteAtOffset(base, 32);289return b != 0;290}291}292293int[] qsort(int[] arr) throws Throwable {294//init native array295try (ResourceScope scope = ResourceScope.newConfinedScope()) {296SegmentAllocator allocator = SegmentAllocator.ofScope(scope);297MemorySegment nativeArr = allocator.allocateArray(C_INT, arr);298299//call qsort300MemoryAddress qsortUpcallStub = abi.upcallStub(qsortCompar.bindTo(nativeArr), qsortComparFunction, scope);301302qsort.invokeExact(nativeArr.address(), (long)arr.length, C_INT.byteSize(), qsortUpcallStub);303304//convert back to Java array305return nativeArr.toIntArray();306}307}308309static int qsortCompare(MemorySegment base, MemoryAddress addr1, MemoryAddress addr2) {310return getIntAtOffset(base, addr1.segmentOffset(base)) -311getIntAtOffset(base, addr2.segmentOffset(base));312}313314int rand() throws Throwable {315return (int)rand.invokeExact();316}317318int printf(String format, List<PrintfArg> args) throws Throwable {319try (ResourceScope scope = ResourceScope.newConfinedScope()) {320MemorySegment formatStr = toCString(format, scope);321return (int)specializedPrintf(args).invokeExact(formatStr.address(),322args.stream().map(a -> a.nativeValue(scope)).toArray());323}324}325326int vprintf(String format, List<PrintfArg> args) throws Throwable {327try (ResourceScope scope = ResourceScope.newConfinedScope()) {328MemorySegment formatStr = toCString(format, scope);329VaList vaList = VaList.make(b -> args.forEach(a -> a.accept(b, scope)), scope);330return (int)vprintf.invokeExact(formatStr.address(), vaList);331}332}333334private MethodHandle specializedPrintf(List<PrintfArg> args) {335//method type336MethodType mt = MethodType.methodType(int.class, MemoryAddress.class);337FunctionDescriptor fd = printfBase;338for (PrintfArg arg : args) {339mt = mt.appendParameterTypes(arg.carrier);340fd = fd.withAppendedArgumentLayouts(arg.layout);341}342MethodHandle mh = abi.downcallHandle(printfAddr, mt, fd);343return mh.asSpreader(1, Object[].class, args.size());344}345}346347/*** data providers ***/348349@DataProvider350public static Object[][] ints() {351return perms(0, new Integer[] { 0, 1, 2, 3, 4 }).stream()352.map(l -> new Object[] { l })353.toArray(Object[][]::new);354}355356@DataProvider357public static Object[][] strings() {358return perms(0, new String[] { "a", "b", "c" }).stream()359.map(l -> new Object[] { String.join("", l) })360.toArray(Object[][]::new);361}362363@DataProvider364public static Object[][] stringPairs() {365Object[][] strings = strings();366Object[][] stringPairs = new Object[strings.length * strings.length][];367int pos = 0;368for (Object[] s1 : strings) {369for (Object[] s2 : strings) {370stringPairs[pos++] = new Object[] { s1[0], s2[0] };371}372}373return stringPairs;374}375376@DataProvider377public static Object[][] instants() {378Instant start = ZonedDateTime.of(LocalDateTime.parse("2017-01-01T00:00:00"), ZoneOffset.UTC).toInstant();379Instant end = ZonedDateTime.of(LocalDateTime.parse("2017-12-31T00:00:00"), ZoneOffset.UTC).toInstant();380Object[][] instants = new Object[100][];381for (int i = 0 ; i < instants.length ; i++) {382Instant instant = start.plusSeconds((long)(Math.random() * (end.getEpochSecond() - start.getEpochSecond())));383instants[i] = new Object[] { instant };384}385return instants;386}387388@DataProvider389public static Object[][] printfArgs() {390ArrayList<List<PrintfArg>> res = new ArrayList<>();391List<List<PrintfArg>> perms = new ArrayList<>(perms(0, PrintfArg.values()));392for (int i = 0 ; i < 100 ; i++) {393Collections.shuffle(perms);394res.addAll(perms);395}396return res.stream()397.map(l -> new Object[] { l })398.toArray(Object[][]::new);399}400401enum PrintfArg implements BiConsumer<VaList.Builder, ResourceScope> {402403INTEGRAL(int.class, asVarArg(C_INT), "%d", scope -> 42, 42, VaList.Builder::vargFromInt),404STRING(MemoryAddress.class, asVarArg(C_POINTER), "%s", scope -> toCString("str", scope).address(), "str", VaList.Builder::vargFromAddress),405CHAR(byte.class, asVarArg(C_CHAR), "%c", scope -> (byte) 'h', 'h', (builder, layout, value) -> builder.vargFromInt(C_INT, (int)value)),406DOUBLE(double.class, asVarArg(C_DOUBLE), "%.4f", scope ->1.2345d, 1.2345d, VaList.Builder::vargFromDouble);407408final Class<?> carrier;409final ValueLayout layout;410final String format;411final Function<ResourceScope, ?> nativeValueFactory;412final Object javaValue;413@SuppressWarnings("rawtypes")414final VaListBuilderCall builderCall;415416<Z> PrintfArg(Class<?> carrier, ValueLayout layout, String format, Function<ResourceScope, Z> nativeValueFactory, Object javaValue, VaListBuilderCall<Z> builderCall) {417this.carrier = carrier;418this.layout = layout;419this.format = format;420this.nativeValueFactory = nativeValueFactory;421this.javaValue = javaValue;422this.builderCall = builderCall;423}424425@Override426@SuppressWarnings("unchecked")427public void accept(VaList.Builder builder, ResourceScope scope) {428builderCall.build(builder, layout, nativeValueFactory.apply(scope));429}430431interface VaListBuilderCall<V> {432void build(VaList.Builder builder, ValueLayout layout, V value);433}434435public Object nativeValue(ResourceScope scope) {436return nativeValueFactory.apply(scope);437}438}439440static <Z> Set<List<Z>> perms(int count, Z[] arr) {441if (count == arr.length) {442return Set.of(List.of());443} else {444return Arrays.stream(arr)445.flatMap(num -> {446Set<List<Z>> perms = perms(count + 1, arr);447return Stream.concat(448//take n449perms.stream().map(l -> {450List<Z> li = new ArrayList<>(l);451li.add(num);452return li;453}),454//drop n455perms.stream());456}).collect(Collectors.toCollection(LinkedHashSet::new));457}458}459}460461462