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.memory.LayoutType;
  37 import java.foreign.memory.Pointer;
  38 import java.foreign.memory.Struct;
  39 import java.lang.invoke.MethodHandle;
  40 import java.lang.invoke.WrongMethodTypeException;
  41 import java.util.*;
  42 import java.util.function.Function;
  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     public static final int MAX_INTEGER_ARGUMENT_REGISTERS = 6;
  51     public static final int MAX_INTEGER_RETURN_REGISTERS = 2;
  52     public static final int MAX_VECTOR_ARGUMENT_REGISTERS = 8;
  53     public static final int MAX_VECTOR_RETURN_REGISTERS = 2;
  54     public static final int MAX_X87_RETURN_REGISTERS = 2;
  55 
  56     private static final String fastPath = privilegedGetProperty("jdk.internal.foreign.NativeInvoker.FASTPATH");
  57     private static SysVx64ABI instance;
  58 
  59     public static SysVx64ABI getInstance() {
  60         if (instance == null) {
  61             instance = new SysVx64ABI();
  62         }
  63         return instance;
  64     }
  65 
  66     @Override
  67     public MethodHandle downcallHandle(CallingConvention cc, Library.Symbol symbol, NativeMethodType nmt) {
  68         if (nmt.isVarArgs()) {
  69             return VarargsInvoker.make(symbol, nmt, CallingSequenceBuilderImpl::new, adapter);
  70         }
  71 
  72         CallingSequence callingSequence = arrangeCall(nmt);
  73         if (fastPath == null || !fastPath.equals("none")) {
  74             if (DirectSignatureShuffler.acceptDowncall(nmt, callingSequence)) {
  75                 return DirectNativeInvoker.make(symbol, callingSequence, nmt);
  76             } else if (fastPath != null && fastPath.equals("direct")) {
  77                 throw new IllegalStateException(
  78                         String.format("No fast path for: %s", symbol.getName()));
  79             }
  80         }
  81         try {
  82             return new UniversalNativeInvoker(symbol, callingSequence, nmt,
  83                     adapter).getBoundMethodHandle();
  84         } catch (IllegalAccessException ex) {
  85             throw new IllegalStateException(ex);
  86         }
  87     }
  88 
  89     @Override
  90     public Library.Symbol upcallStub(CallingConvention cc, MethodHandle target, NativeMethodType nmt) {
  91         if (!target.type().equals(nmt.methodType())) {
  92             throw new WrongMethodTypeException("Native method type has wrong type: " + nmt.methodType());
  93         }
  94         CallingSequence callingSequence = arrangeCall(nmt);
  95         if (fastPath == null || !fastPath.equals("none")) {
  96             if (DirectSignatureShuffler.acceptUpcall(nmt, callingSequence)) {
  97                 return UpcallStubs.registerUpcallStub(new DirectUpcallHandler(target, callingSequence, nmt));
  98             } else if (fastPath != null && fastPath.equals("direct")) {
  99                 throw new IllegalStateException(
 100                         String.format("No fast path for function type %s", nmt.function()));
 101             }
 102         }
 103         return UpcallStubs.registerUpcallStub(new UniversalUpcallHandler(target, callingSequence, nmt,
 104                 adapter));
 105     }
 106 
 107     CallingSequence arrangeCall(NativeMethodType nmt) {
 108         CallingSequenceBuilder stdc = new CallingSequenceBuilderImpl(nmt.function().returnLayout().orElse(null));
 109         nmt.function().argumentLayouts().forEach(stdc::addArgument);
 110         return stdc.build();
 111     }
 112 
 113     private static final Map<String, CallingConvention> SysVCallingConventions = new HashMap<>();
 114     private static final CallingConvention CV_C = () -> "C";
 115 
 116     static {
 117         SysVCallingConventions.put("C", CV_C);
 118     }
 119 
 120     @Override
 121     public CallingConvention defaultCallingConvention() {
 122         return CV_C;
 123     }
 124 
 125     @Override
 126     public CallingConvention namedCallingConvention(String name) throws IllegalArgumentException {
 127         CallingConvention cv = SysVCallingConventions.get(name);
 128         if (null == cv) {
 129             throw new IllegalArgumentException("Unknown calling convention " + name);
 130         }
 131         return cv;
 132     }
 133 
 134     @Override
 135     public Collection<CallingConvention> callingConventions() {
 136         return Collections.unmodifiableCollection(SysVCallingConventions.values());
 137     }
 138 
 139     UniversalAdapter adapter = new UniversalAdapter() {
 140         @Override
 141         public void unboxValue(Object o, LayoutType<?> type, java.util.function.Function<ArgumentBinding, Pointer<?>> dstPtrFunc,
 142                            List<ArgumentBinding> bindings) throws Throwable {
 143             if (o instanceof Struct) {
 144                 Struct<?> struct = (Struct<?>) o;
 145                 if (struct.ptr().type().bytesSize() != 0) {
 146                     Pointer<Long> src = Util.unsafeCast(struct.ptr(), NativeTypes.UINT64);
 147                     for (ArgumentBinding binding : bindings) {
 148                         Pointer<?> dst = dstPtrFunc.apply(binding);
 149                         Pointer<Long> srcPtr = src.offset(binding.offset() / NativeTypes.UINT64.bytesSize());
 150                         Pointer.copy(srcPtr, dst, binding.storage().getSize());
 151                     }
 152                 }
 153             } else {
 154                 assert bindings.size() <= 2;
 155                 Pointer<?> dst = Util.unsafeCast(dstPtrFunc.apply(bindings.get(0)), type);
 156                 dst.type().setter().invoke(dst, o);
 157             }
 158         }
 159 
 160         @SuppressWarnings("unchecked")
 161         public Object boxValue(LayoutType<?> type, java.util.function.Function<ArgumentBinding, Pointer<?>> srcPtrFunc,
 162                                List<ArgumentBinding> bindings) throws IllegalAccessException {
 163             Class<?> carrier = ((LayoutTypeImpl<?>)type).carrier();
 164             if (Util.isCStruct(carrier)) {
 165                 /*
 166                  * Leak memory for now
 167                  */
 168                 Scope scope = Scope.globalScope().fork();
 169 
 170                 if (type.bytesSize() == 0) {
 171                     //empty struct!
 172                     return scope.allocateStruct((Class)carrier);
 173                 }
 174 
 175                 @SuppressWarnings({"rawtypes", "unchecked"})
 176                 Pointer<?> rtmp = ((ScopeImpl)scope).allocate(type, 8);
 177 
 178                 for (ArgumentBinding binding : bindings) {
 179                     Pointer<Long> dst = Util.unsafeCast(rtmp, NativeTypes.UINT64).offset(binding.offset() / NativeTypes.UINT64.bytesSize());
 180                     Pointer.copy(srcPtrFunc.apply(binding), dst, binding.storage().getSize());
 181                 }
 182 
 183                 return rtmp.get();
 184             } else {
 185                 assert bindings.size() <= 2;
 186                 return Util.unsafeCast(srcPtrFunc.apply(bindings.get(0)), type).get();
 187             }
 188         }
 189     };
 190 }
 191