1 /*
  2  * Copyright (c) 2022, 2023, 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  * @test
 26  * @enablePreview
 27  * @requires jdk.foreign.linker != "UNSUPPORTED"
 28  * @requires !vm.musl
 29  * @modules java.base/jdk.internal.foreign
 30  * @build NativeTestHelper CallGeneratorHelper TestUpcallBase
 31  *
 32  * @run testng/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-VerifyDependencies
 33  *   --enable-native-access=ALL-UNNAMED -Dgenerator.sample.factor=17
 34  *   TestUpcallAsync
 35  */
 36 
 37 import java.lang.foreign.*;
 38 
 39 import org.testng.annotations.Test;
 40 
 41 import java.lang.invoke.MethodHandle;
 42 import java.lang.invoke.MethodHandles;
 43 import java.util.ArrayList;
 44 import java.util.HashMap;
 45 import java.util.List;
 46 import java.util.Map;
 47 import java.util.concurrent.atomic.AtomicReference;
 48 import java.util.function.Consumer;
 49 
 50 public class TestUpcallAsync extends TestUpcallBase {
 51 
 52     static {
 53         System.loadLibrary("TestUpcall");
 54         System.loadLibrary("AsyncInvokers");
 55     }
 56 
 57     @Test(dataProvider="functions", dataProviderClass=CallGeneratorHelper.class)
 58     public void testUpcallsAsync(int count, String fName, Ret ret, List<ParamType> paramTypes, List<StructFieldType> fields) throws Throwable {
 59         List<Consumer<Object>> returnChecks = new ArrayList<>();
 60         List<Consumer<Object>> argChecks = new ArrayList<>();
 61         MemorySegment addr = findNativeOrThrow(fName);
 62         try (Arena arena = Arena.ofShared()) {
 63             FunctionDescriptor descriptor = function(ret, paramTypes, fields);
 64             MethodHandle mh = downcallHandle(LINKER, addr, arena, descriptor);
 65             AtomicReference<Object[]> capturedArgs = new AtomicReference<>();
 66             Object[] args = makeArgs(capturedArgs, arena, descriptor, returnChecks, argChecks, 0);
 67 
 68             mh = mh.asSpreader(Object[].class, args.length);
 69             mh = MethodHandles.insertArguments(mh, 0, (Object) args);
 70             FunctionDescriptor callbackDesc = descriptor.returnLayout()
 71                     .map(FunctionDescriptor::of)
 72                     .orElse(FunctionDescriptor.ofVoid());
 73             MemorySegment callback = LINKER.upcallStub(mh, callbackDesc, arena);
 74 
 75             MethodHandle invoker = asyncInvoker(ret, ret == Ret.VOID ? null : paramTypes.get(0), fields);
 76 
 77             Object res = (descriptor.returnLayout().isPresent() &&
 78                          descriptor.returnLayout().get() instanceof GroupLayout)
 79                     ? invoker.invoke(arena, callback)
 80                     : invoker.invoke(callback);
 81 
 82             if (ret == Ret.NON_VOID) {
 83                 returnChecks.forEach(c -> c.accept(res));
 84             }
 85 
 86             Object[] capturedArgsArr = capturedArgs.get();
 87             for (int i = 0; i < capturedArgsArr.length; i++) {
 88                 argChecks.get(i).accept(capturedArgsArr[i]);
 89             }
 90         }
 91     }
 92 
 93     private static final Map<String, MethodHandle> INVOKERS = new HashMap<>();
 94 
 95     private MethodHandle asyncInvoker(Ret ret, ParamType returnType, List<StructFieldType> fields) {
 96         if (ret == Ret.VOID) {
 97             String name = "call_async_V";
 98             return INVOKERS.computeIfAbsent(name, symbol ->
 99                     LINKER.downcallHandle(
100                             findNativeOrThrow(symbol),
101                             FunctionDescriptor.ofVoid(C_POINTER)));
102         }
103 
104         String name = "call_async_" + returnType.name().charAt(0)
105                 + (returnType == ParamType.STRUCT ? "_" + sigCode(fields) : "");
106 
107         return INVOKERS.computeIfAbsent(name, symbol -> {
108             MemorySegment invokerSymbol = findNativeOrThrow(symbol);
109             MemoryLayout returnLayout = returnType.layout(fields);
110             FunctionDescriptor desc = FunctionDescriptor.of(returnLayout, C_POINTER);
111 
112             return LINKER.downcallHandle(invokerSymbol, desc);
113         });
114     }
115 
116 }