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