Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove printf and vprintf tests #536

Closed
Closed
Changes from 2 commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -39,6 +39,7 @@
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Function;
@@ -49,6 +50,7 @@

import static jdk.incubator.foreign.MemoryAccess.*;

import org.testng.SkipException;
This conversation was marked as resolved by JornVernee

This comment has been minimized.

@mcimadamore

mcimadamore May 14, 2021
Collaborator Outdated

Still needed?

import org.testng.annotations.*;

import static jdk.incubator.foreign.CLinker.*;
@@ -122,41 +124,109 @@ void test_rand() throws Throwable {
fail("All values are the same! " + val);
}

@Test(dataProvider = "printfArgs")
void test_printf(List<PrintfArg> args) throws Throwable {
String formatArgs = args.stream()
.map(a -> a.format)
.collect(Collectors.joining(","));

String formatString = "hello(" + formatArgs + ")\n";

String expected = String.format(formatString, args.stream()
.map(a -> a.javaValue).toArray());

int found = stdLibHelper.printf(formatString, args);
assertEquals(found, expected.length());
}

@Test(dataProvider = "printfArgs")
void test_vprintf(List<PrintfArg> args) throws Throwable {
String formatArgs = args.stream()
.map(a -> a.format)
.collect(Collectors.joining(","));

String formatString = "hello(" + formatArgs + ")\n";

String expected = String.format(formatString, args.stream()
.map(a -> a.javaValue).toArray());

int found = stdLibHelper.vprintf(formatString, args);
assertEquals(found, expected.length());
}

static class StdLibHelper {

final static MethodHandle strcat = abi.downcallHandle(CLinker.systemLookup().lookup("strcat").get(),
final static SymbolLookup LOOKUP;

private static final int F_PRINTF = 0;
private static final int F_VPRINTF = 1;
private static final int F_GMTIME = 2;

static {
System.loadLibrary("StdLib");
SymbolLookup stdLibLookup = SymbolLookup.loaderLookup();
MethodHandle MH_get_ptr = abi.downcallHandle(stdLibLookup.lookup("get_ptr").get(),
MethodType.methodType(MemoryAddress.class, int.class),
FunctionDescriptor.of(C_POINTER, C_INT));

SymbolLookup fallbackLookup = name -> {
MemoryAddress ma;
try {
ma = (MemoryAddress) MH_get_ptr.invokeExact((int) switch (name) {
case "printf" -> F_PRINTF;
case "vprintf" -> F_VPRINTF;
case "gmtime" -> F_GMTIME;
default -> -1;
});
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
return ma == MemoryAddress.NULL ? Optional.empty() : Optional.of(ma);
};

LOOKUP = name -> CLinker.systemLookup().lookup(name).or(() -> fallbackLookup.lookup(name));
}

final static MethodHandle strcat = abi.downcallHandle(LOOKUP.lookup("strcat").get(),
MethodType.methodType(MemoryAddress.class, MemoryAddress.class, MemoryAddress.class),
FunctionDescriptor.of(C_POINTER, C_POINTER, C_POINTER));

final static MethodHandle strcmp = abi.downcallHandle(CLinker.systemLookup().lookup("strcmp").get(),
final static MethodHandle strcmp = abi.downcallHandle(LOOKUP.lookup("strcmp").get(),
MethodType.methodType(int.class, MemoryAddress.class, MemoryAddress.class),
FunctionDescriptor.of(C_INT, C_POINTER, C_POINTER));

final static MethodHandle puts = abi.downcallHandle(CLinker.systemLookup().lookup("puts").get(),
final static MethodHandle puts = abi.downcallHandle(LOOKUP.lookup("puts").get(),
MethodType.methodType(int.class, MemoryAddress.class),
FunctionDescriptor.of(C_INT, C_POINTER));

final static MethodHandle strlen = abi.downcallHandle(CLinker.systemLookup().lookup("strlen").get(),
final static MethodHandle strlen = abi.downcallHandle(LOOKUP.lookup("strlen").get(),
MethodType.methodType(int.class, MemoryAddress.class),
FunctionDescriptor.of(C_INT, C_POINTER));

final static MethodHandle gmtime = abi.downcallHandle(
CLinker.systemLookup().lookup(NativeTestHelper.IS_WINDOWS ? "_gmtime64" : "gmtime").get(),
final static MethodHandle gmtime = abi.downcallHandle(LOOKUP.lookup("gmtime").get(),
MethodType.methodType(MemoryAddress.class, MemoryAddress.class),
FunctionDescriptor.of(C_POINTER, C_POINTER));

final static MethodHandle qsort = abi.downcallHandle(CLinker.systemLookup().lookup("qsort").get(),
final static MethodHandle qsort = abi.downcallHandle(LOOKUP.lookup("qsort").get(),
MethodType.methodType(void.class, MemoryAddress.class, long.class, long.class, MemoryAddress.class),
FunctionDescriptor.ofVoid(C_POINTER, C_LONG_LONG, C_LONG_LONG, C_POINTER));

final static FunctionDescriptor qsortComparFunction = FunctionDescriptor.of(C_INT, C_POINTER, C_POINTER);

final static MethodHandle qsortCompar;

final static MethodHandle rand = abi.downcallHandle(CLinker.systemLookup().lookup("rand").get(),
final static MethodHandle rand = abi.downcallHandle(LOOKUP.lookup("rand").get(),
MethodType.methodType(int.class),
FunctionDescriptor.of(C_INT));

final static MethodHandle vprintf = abi.downcallHandle(LOOKUP.lookup("vprintf").get(),
MethodType.methodType(int.class, MemoryAddress.class, VaList.class),
FunctionDescriptor.of(C_INT, C_POINTER, C_VA_LIST));

final static MemoryAddress printfAddr = LOOKUP.lookup("printf").get();

final static FunctionDescriptor printfBase = FunctionDescriptor.of(C_INT, C_POINTER);

static {
try {
//qsort upcall handle
@@ -275,6 +345,34 @@ static int qsortCompare(MemorySegment base, MemoryAddress addr1, MemoryAddress a
int rand() throws Throwable {
return (int)rand.invokeExact();
}

int printf(String format, List<PrintfArg> args) throws Throwable {
try (ResourceScope scope = ResourceScope.newConfinedScope()) {
MemorySegment formatStr = toCString(format, scope);
return (int)specializedPrintf(args).invokeExact(formatStr.address(),
args.stream().map(a -> a.nativeValue(scope)).toArray());
}
}

int vprintf(String format, List<PrintfArg> args) throws Throwable {
try (ResourceScope scope = ResourceScope.newConfinedScope()) {
MemorySegment formatStr = toCString(format, scope);
VaList vaList = VaList.make(b -> args.forEach(a -> a.accept(b, scope)), scope);
return (int)vprintf.invokeExact(formatStr.address(), vaList);
}
}

private MethodHandle specializedPrintf(List<PrintfArg> args) {
//method type
MethodType mt = MethodType.methodType(int.class, MemoryAddress.class);
FunctionDescriptor fd = printfBase;
for (PrintfArg arg : args) {
mt = mt.appendParameterTypes(arg.carrier);
fd = fd.withAppendedArgumentLayouts(arg.layout);
}
MethodHandle mh = abi.downcallHandle(printfAddr, mt, fd);
return mh.asSpreader(1, Object[].class, args.size());
}
}

/*** data providers ***/
@@ -318,6 +416,58 @@ int rand() throws Throwable {
return instants;
}

@DataProvider
public static Object[][] printfArgs() {
ArrayList<List<PrintfArg>> res = new ArrayList<>();
List<List<PrintfArg>> perms = new ArrayList<>(perms(0, PrintfArg.values()));
for (int i = 0 ; i < 100 ; i++) {
Collections.shuffle(perms);
res.addAll(perms);
}
return res.stream()
.map(l -> new Object[] { l })
.toArray(Object[][]::new);
}

enum PrintfArg implements BiConsumer<VaList.Builder, ResourceScope> {

INTEGRAL(int.class, asVarArg(C_INT), "%d", scope -> 42, 42, VaList.Builder::vargFromInt),
STRING(MemoryAddress.class, asVarArg(C_POINTER), "%s", scope -> toCString("str", scope).address(), "str", VaList.Builder::vargFromAddress),
CHAR(byte.class, asVarArg(C_CHAR), "%c", scope -> (byte) 'h', 'h', (builder, layout, value) -> builder.vargFromInt(C_INT, (int)value)),
DOUBLE(double.class, asVarArg(C_DOUBLE), "%.4f", scope ->1.2345d, 1.2345d, VaList.Builder::vargFromDouble);

final Class<?> carrier;
final ValueLayout layout;
final String format;
final Function<ResourceScope, ?> nativeValueFactory;
final Object javaValue;
@SuppressWarnings("rawtypes")
final VaListBuilderCall builderCall;

<Z> PrintfArg(Class<?> carrier, ValueLayout layout, String format, Function<ResourceScope, Z> nativeValueFactory, Object javaValue, VaListBuilderCall<Z> builderCall) {
this.carrier = carrier;
this.layout = layout;
this.format = format;
this.nativeValueFactory = nativeValueFactory;
this.javaValue = javaValue;
this.builderCall = builderCall;
}

@Override
@SuppressWarnings("unchecked")
public void accept(VaList.Builder builder, ResourceScope scope) {
builderCall.build(builder, layout, nativeValueFactory.apply(scope));
}

interface VaListBuilderCall<V> {
void build(VaList.Builder builder, ValueLayout layout, V value);
}

public Object nativeValue(ResourceScope scope) {
return nativeValueFactory.apply(scope);
}
}

static <Z> Set<List<Z>> perms(int count, Z[] arr) {
if (count == arr.length) {
return Set.of(List.of());
@@ -0,0 +1,47 @@
/*
* Copyright (c) 2021, 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.
*
*/

#include <stdio.h>
#include <time.h>

#ifdef _WIN64
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif

enum Func {
F_PRINTF = 0,
F_VPRINTF = 1,
F_GMTIME = 2
};

EXPORT void* get_ptr(int func) {
switch(func) {
case F_PRINTF: return &printf;
case F_VPRINTF: return &vprintf;
case F_GMTIME: return &gmtime;
}
return NULL;
}