1 /*
   2  * Copyright (c) 2016, 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package jdk.internal.foreign.abi.x64.sysv;
  26 
  27 import jdk.internal.foreign.ScopeImpl;
  28 import jdk.internal.foreign.Util;
  29 import jdk.internal.foreign.abi.*;
  30 import jdk.internal.foreign.memory.LayoutTypeImpl;
  31 
  32 import java.foreign.Library;
  33 import java.foreign.NativeMethodType;
  34 import java.foreign.NativeTypes;
  35 import java.foreign.Scope;
  36 import java.foreign.layout.*;
  37 import java.foreign.memory.LayoutType;
  38 import java.foreign.memory.Pointer;
  39 import java.foreign.memory.Struct;
  40 import java.lang.invoke.MethodHandle;
  41 import java.lang.invoke.WrongMethodTypeException;
  42 import java.util.*;
  43 
  44 import static sun.security.action.GetPropertyAction.privilegedGetProperty;
  45 
  46 /**
  47  * ABI implementation based on System V ABI AMD64 supplement v.0.99.6
  48  */
  49 public class SysVx64ABI implements SystemABI {
  50     private static final String fastPath = privilegedGetProperty("jdk.internal.foreign.NativeInvoker.FASTPATH");
  51     private static SysVx64ABI instance;
  52 
  53     public static SysVx64ABI getInstance() {
  54         if (instance == null) {
  55             instance = new SysVx64ABI();
  56         }
  57         return instance;
  58     }
  59 
  60     @Override
  61     public MethodHandle downcallHandle(CallingConvention cc, Library.Symbol symbol, NativeMethodType nmt) {
  62         if (nmt.isVarArgs()) {
  63             return VarargsInvokerImpl.make(symbol, nmt);
  64         }
  65 
  66         StandardCall sc = new StandardCall();
  67         CallingSequence callingSequence = sc.arrangeCall(nmt);
  68 
  69         if (fastPath == null || !fastPath.equals("none")) {
  70             if (DirectSignatureShuffler.acceptDowncall(nmt, callingSequence)) {
  71                 return DirectNativeInvoker.make(symbol, callingSequence, nmt);
  72             } else if (fastPath != null && fastPath.equals("direct")) {
  73                 throw new IllegalStateException(
  74                         String.format("No fast path for: %s", symbol.getName()));
  75             }
  76         }
  77         return UniversalNativeInvokerImpl.make(symbol, callingSequence, nmt).getBoundMethodHandle();
  78     }
  79 
  80     @Override
  81     public Library.Symbol upcallStub(CallingConvention cc, MethodHandle target, NativeMethodType nmt) {
  82         if (!target.type().equals(nmt.methodType())) {
  83             throw new WrongMethodTypeException("Native method type has wrong type: " + nmt.methodType());
  84         }
  85         StandardCall sc = new StandardCall();
  86         CallingSequence callingSequence = sc.arrangeCall(nmt);
  87         if (fastPath == null || !fastPath.equals("none")) {
  88             if (DirectSignatureShuffler.acceptUpcall(nmt, callingSequence)) {
  89                 return UpcallStubs.registerUpcallStub(new DirectUpcallHandler(target, callingSequence, nmt));
  90             } else if (fastPath != null && fastPath.equals("direct")) {
  91                 throw new IllegalStateException(
  92                         String.format("No fast path for function type %s", nmt.function()));
  93             }
  94         }
  95         return UpcallStubs.registerUpcallStub(new UniversalUpcallHandlerImpl(target, callingSequence, nmt));
  96     }
  97 
  98     private static final Map<String, CallingConvention> SysVCallingConventions = new HashMap<>();
  99     private static final CallingConvention CV_C = () -> "C";
 100 
 101     static {
 102         SysVCallingConventions.put("C", CV_C);
 103     }
 104 
 105     @Override
 106     public CallingConvention defaultCallingConvention() {
 107         return CV_C;
 108     }
 109 
 110     @Override
 111     public CallingConvention namedCallingConvention(String name) throws IllegalArgumentException {
 112         CallingConvention cv = SysVCallingConventions.get(name);
 113         if (null == cv) {
 114             throw new IllegalArgumentException("Unknown calling convention " + name);
 115         }
 116         return cv;
 117     }
 118 
 119     @Override
 120     public Collection<CallingConvention> callingConventions() {
 121         return Collections.unmodifiableCollection(SysVCallingConventions.values());
 122     }
 123 
 124     static void unboxValue(Object o, LayoutType<?> type, java.util.function.Function<ArgumentBinding, Pointer<?>> dstPtrFunc,
 125                            List<ArgumentBinding> bindings) throws Throwable {
 126         if (o instanceof Struct) {
 127             Struct<?> struct = (Struct<?>) o;
 128             if (struct.ptr().type().bytesSize() != 0) {
 129                 Pointer<Long> src = Util.unsafeCast(struct.ptr(), NativeTypes.UINT64);
 130                 for (ArgumentBinding binding : bindings) {
 131                     Pointer<?> dst = dstPtrFunc.apply(binding);
 132                     Pointer<Long> srcPtr = src.offset(binding.getOffset() / NativeTypes.UINT64.bytesSize());
 133                     Pointer.copy(srcPtr, dst, binding.getStorage().getSize());
 134                 }
 135             }
 136         } else {
 137             assert bindings.size() <= 2;
 138             Pointer<?> dst = Util.unsafeCast(dstPtrFunc.apply(bindings.get(0)), type);
 139             dst.type().setter().invoke(dst, o);
 140         }
 141     }
 142 
 143     @SuppressWarnings("unchecked")
 144     static Object boxValue(LayoutType<?> type, java.util.function.Function<ArgumentBinding, Pointer<?>> srcPtrFunc,
 145                            List<ArgumentBinding> bindings) throws IllegalAccessException {
 146         Class<?> carrier = ((LayoutTypeImpl<?>)type).carrier();
 147         if (Util.isCStruct(carrier)) {
 148             /*
 149              * Leak memory for now
 150              */
 151             Scope scope = Scope.globalScope().fork();
 152 
 153             if (type.bytesSize() == 0) {
 154                 //empty struct!
 155                 return scope.allocateStruct((Class)carrier);
 156             }
 157 
 158             @SuppressWarnings({"rawtypes", "unchecked"})
 159             Pointer<?> rtmp = ((ScopeImpl)scope).allocate(type, 8);
 160 
 161             for (ArgumentBinding binding : bindings) {
 162                 Pointer<Long> dst = Util.unsafeCast(rtmp, NativeTypes.UINT64).offset(binding.getOffset() / NativeTypes.UINT64.bytesSize());
 163                 Pointer.copy(srcPtrFunc.apply(binding), dst, binding.getStorage().getSize());
 164             }
 165 
 166             return rtmp.get();
 167         } else {
 168             assert bindings.size() <= 2;
 169             return Util.unsafeCast(srcPtrFunc.apply(bindings.get(0)), type).get();
 170         }
 171     }
 172 }
 173