1 /* 2 * Copyright (c) 2019, 2020, 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 jdk.incubator.foreign/jdk.incubator.foreign.unsafe 28 * jdk.incubator.foreign/jdk.internal.foreign 29 * jdk.incubator.foreign/jdk.internal.foreign.abi 30 * java.base/sun.security.action 31 * @build NativeTestHelper CallGeneratorHelper TestUpcall 32 * 33 * @run testng/othervm 34 * -Dforeign.restricted=permit 35 * TestUpcall 36 * @run testng/othervm 37 * -Dforeign.restricted=permit 38 * -Djdk.internal.foreign.ProgrammableInvoker.NO_SPEC=true 39 * TestUpcall 40 */ 41 42 import jdk.incubator.foreign.CSupport; 43 import jdk.incubator.foreign.FunctionDescriptor; 44 import jdk.incubator.foreign.GroupLayout; 45 import jdk.incubator.foreign.LibraryLookup; 46 import jdk.incubator.foreign.MemoryAddress; 47 import jdk.incubator.foreign.MemoryLayout; 48 import jdk.incubator.foreign.MemorySegment; 49 import jdk.incubator.foreign.ForeignLinker; 50 import jdk.incubator.foreign.ValueLayout; 51 import org.testng.annotations.AfterClass; 52 import org.testng.annotations.BeforeClass; 53 import org.testng.annotations.Test; 54 55 import java.lang.invoke.MethodHandle; 56 import java.lang.invoke.MethodHandles; 57 import java.lang.invoke.MethodType; 58 import java.lang.invoke.VarHandle; 59 import java.util.ArrayList; 60 import java.util.List; 61 import java.util.concurrent.atomic.AtomicReference; 62 import java.util.function.Consumer; 63 import java.util.stream.Collectors; 64 65 import static java.lang.invoke.MethodHandles.insertArguments; 66 import static jdk.incubator.foreign.CSupport.C_POINTER; 67 import static org.testng.Assert.assertEquals; 68 69 70 public class TestUpcall extends CallGeneratorHelper { 71 72 static LibraryLookup lib = LibraryLookup.ofLibrary("TestUpcall"); 73 static ForeignLinker abi = CSupport.getSystemLinker(); 74 75 static MethodHandle DUMMY; 76 static MethodHandle PASS_AND_SAVE; 77 78 static { 79 try { 80 DUMMY = MethodHandles.lookup().findStatic(TestUpcall.class, "dummy", MethodType.methodType(void.class)); 81 PASS_AND_SAVE = MethodHandles.lookup().findStatic(TestUpcall.class, "passAndSave", MethodType.methodType(Object.class, Object[].class, AtomicReference.class)); 82 } catch (Throwable ex) { 83 throw new IllegalStateException(ex); 84 } 85 } 86 87 static MemoryAddress dummyAddress; 88 89 @BeforeClass 90 void setup() { 91 dummyAddress = abi.upcallStub(DUMMY, FunctionDescriptor.ofVoid()).baseAddress(); 92 } 93 94 @AfterClass 95 void teardown() { 96 dummyAddress.segment().close(); 97 } 98 99 @Test(dataProvider="functions", dataProviderClass=CallGeneratorHelper.class) 100 public void testUpcalls(String fName, Ret ret, List<ParamType> paramTypes, List<StructFieldType> fields) throws Throwable { 101 List<Consumer<Object>> returnChecks = new ArrayList<>(); 102 List<Consumer<Object[]>> argChecks = new ArrayList<>(); 103 MemoryAddress addr = lib.lookup(fName); 104 MethodHandle mh = abi.downcallHandle(addr, methodType(ret, paramTypes, fields), function(ret, paramTypes, fields)); 105 Object[] args = makeArgs(ret, paramTypes, fields, returnChecks, argChecks); 106 mh = mh.asSpreader(Object[].class, paramTypes.size() + 1); 107 Object res = mh.invoke(args); 108 argChecks.forEach(c -> c.accept(args)); 109 if (ret == Ret.NON_VOID) { 110 returnChecks.forEach(c -> c.accept(res)); 111 } 112 for (Object arg : args) { 113 if (arg != dummyAddress) { 114 cleanup(arg); 115 } 116 } 117 } 118 119 static MethodType methodType(Ret ret, List<ParamType> params, List<StructFieldType> fields) { 120 MethodType mt = ret == Ret.VOID ? 121 MethodType.methodType(void.class) : MethodType.methodType(paramCarrier(params.get(0).layout(fields))); 122 for (ParamType p : params) { 123 mt = mt.appendParameterTypes(paramCarrier(p.layout(fields))); 124 } 125 mt = mt.appendParameterTypes(MemoryAddress.class); //the callback 126 return mt; 127 } 128 129 static FunctionDescriptor function(Ret ret, List<ParamType> params, List<StructFieldType> fields) { 130 List<MemoryLayout> paramLayouts = params.stream().map(p -> p.layout(fields)).collect(Collectors.toList()); 131 paramLayouts.add(C_POINTER); // the callback 132 MemoryLayout[] layouts = paramLayouts.toArray(new MemoryLayout[0]); 133 return ret == Ret.VOID ? 134 FunctionDescriptor.ofVoid(layouts) : 135 FunctionDescriptor.of(layouts[0], layouts); 136 } 137 138 static Object[] makeArgs(Ret ret, List<ParamType> params, List<StructFieldType> fields, List<Consumer<Object>> checks, List<Consumer<Object[]>> argChecks) throws ReflectiveOperationException { 139 Object[] args = new Object[params.size() + 1]; 140 for (int i = 0 ; i < params.size() ; i++) { 141 args[i] = makeArg(params.get(i).layout(fields), checks, i == 0); 142 } 143 args[params.size()] = makeCallback(ret, params, fields, checks, argChecks); 144 return args; 145 } 146 147 static MemoryAddress makeCallback(Ret ret, List<ParamType> params, List<StructFieldType> fields, List<Consumer<Object>> checks, List<Consumer<Object[]>> argChecks) { 148 if (params.isEmpty()) { 149 return dummyAddress; 150 } 151 152 AtomicReference<Object[]> box = new AtomicReference<>(); 153 MethodHandle mh = insertArguments(PASS_AND_SAVE, 1, box); 154 mh = mh.asCollector(Object[].class, params.size()); 155 156 for (int i = 0; i < params.size(); i++) { 157 ParamType pt = params.get(i); 158 MemoryLayout layout = pt.layout(fields); 159 Class<?> carrier = paramCarrier(layout); 160 mh = mh.asType(mh.type().changeParameterType(i, carrier)); 161 162 final int finalI = i; 163 if (carrier == MemorySegment.class) { 164 argChecks.add(o -> assertStructEquals((MemorySegment) box.get()[finalI], (MemorySegment) o[finalI], layout)); 165 } else { 166 argChecks.add(o -> assertEquals(box.get()[finalI], o[finalI])); 167 } 168 } 169 170 ParamType firstParam = params.get(0); 171 MemoryLayout firstlayout = firstParam.layout(fields); 172 Class<?> firstCarrier = paramCarrier(firstlayout); 173 174 if (firstCarrier == MemorySegment.class) { 175 checks.add(o -> assertStructEquals((MemorySegment) box.get()[0], (MemorySegment) o, firstlayout)); 176 } else { 177 checks.add(o -> assertEquals(o, box.get()[0])); 178 } 179 180 mh = mh.asType(mh.type().changeReturnType(ret == Ret.VOID ? void.class : firstCarrier)); 181 182 MemoryLayout[] paramLayouts = params.stream().map(p -> p.layout(fields)).toArray(MemoryLayout[]::new); 183 FunctionDescriptor func = ret != Ret.VOID 184 ? FunctionDescriptor.of(firstlayout, paramLayouts) 185 : FunctionDescriptor.ofVoid(paramLayouts); 186 MemoryAddress stub = abi.upcallStub(mh, func).baseAddress(); 187 return stub; 188 } 189 190 private static void assertStructEquals(MemorySegment actual, MemorySegment expected, MemoryLayout layout) { 191 assertEquals(actual.byteSize(), expected.byteSize()); 192 GroupLayout g = (GroupLayout) layout; 193 for (MemoryLayout field : g.memberLayouts()) { 194 if (field instanceof ValueLayout) { 195 VarHandle vh = g.varHandle(vhCarrier(field), MemoryLayout.PathElement.groupElement(field.name().orElseThrow())); 196 assertEquals(vh.get(actual.baseAddress()), vh.get(expected.baseAddress())); 197 } 198 } 199 } 200 201 private static Class<?> vhCarrier(MemoryLayout layout) { 202 if (layout instanceof ValueLayout) { 203 if (isIntegral(layout)) { 204 if (layout.bitSize() == 64) { 205 return long.class; 206 } 207 return int.class; 208 } else if (layout.bitSize() == 32) { 209 return float.class; 210 } 211 return double.class; 212 } else { 213 throw new IllegalStateException("Unexpected layout: " + layout); 214 } 215 } 216 217 static Object passAndSave(Object[] o, AtomicReference<Object[]> ref) { 218 ref.set(o); 219 return o[0]; 220 } 221 222 static void dummy() { 223 //do nothing 224 } 225 }