1 /*
  2  *  Copyright (c) 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.  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;
 26 
 27 import jdk.incubator.foreign.FunctionDescriptor;
 28 import jdk.incubator.foreign.MemoryLayout;
 29 import jdk.incubator.foreign.MemorySegment;
 30 import jdk.incubator.foreign.NativeSymbol;
 31 import jdk.incubator.foreign.ValueLayout;
 32 import jdk.internal.foreign.Utils;
 33 import sun.security.action.GetPropertyAction;
 34 
 35 import java.lang.invoke.MethodType;
 36 import java.util.ArrayDeque;
 37 import java.util.ArrayList;
 38 import java.util.Deque;
 39 import java.util.EnumSet;
 40 import java.util.List;
 41 import java.util.Set;
 42 
 43 import static jdk.internal.foreign.abi.Binding.Tag.*;
 44 
 45 public class CallingSequenceBuilder {
 46     private static final boolean VERIFY_BINDINGS = Boolean.parseBoolean(
 47             GetPropertyAction.privilegedGetProperty("jdk.incubator.foreign.VERIFY_BINDINGS", "true"));
 48 
 49     private final ABIDescriptor abi;
 50 
 51     private boolean isTrivial;
 52     private final boolean forUpcall;
 53     private final List<List<Binding>> inputBindings = new ArrayList<>();
 54     private List<Binding> outputBindings = List.of();
 55 
 56     private MethodType mt = MethodType.methodType(void.class);
 57     private FunctionDescriptor desc = FunctionDescriptor.ofVoid();
 58 
 59     public CallingSequenceBuilder(ABIDescriptor abi, boolean forUpcall) {
 60         this.abi = abi;
 61         this.forUpcall = forUpcall;
 62     }
 63 
 64     public final CallingSequenceBuilder addArgumentBindings(Class<?> carrier, MemoryLayout layout,
 65                                                             List<Binding> bindings) {
 66         addArgumentBinding(inputBindings.size(), carrier, layout, bindings);



 67         return this;
 68     }
 69 
 70     private void addArgumentBinding(int index, Class<?> carrier, MemoryLayout layout, List<Binding> bindings) {
 71         verifyBindings(true, carrier, bindings);
 72         inputBindings.add(index, bindings);
 73         mt = mt.insertParameterTypes(index, carrier);
 74         desc = desc.insertArgumentLayouts(index, layout);
 75     }
 76 
 77     public CallingSequenceBuilder setReturnBindings(Class<?> carrier, MemoryLayout layout,
 78                                                     List<Binding> bindings) {
 79         verifyBindings(false, carrier, bindings);
 80         this.outputBindings = bindings;
 81         mt = mt.changeReturnType(carrier);
 82         desc = desc.withReturnLayout(layout);
 83         return this;
 84     }
 85 
 86     public CallingSequenceBuilder setTrivial(boolean isTrivial) {
 87         this.isTrivial = isTrivial;
 88         return this;
 89     }
 90 
 91     private boolean needsReturnBuffer() {
 92         return outputBindings.stream()
 93             .filter(Binding.Move.class::isInstance)
 94             .count() > 1;
 95     }
 96 
 97     public CallingSequence build() {
 98         boolean needsReturnBuffer = needsReturnBuffer();
 99         long returnBufferSize = needsReturnBuffer ? computeReturnBuferSize() : 0;
100         long allocationSize = computeAllocationSize() + returnBufferSize;
101         if (!forUpcall) {
102             addArgumentBinding(0, NativeSymbol.class, ValueLayout.ADDRESS, List.of(
103                 Binding.unboxAddress(NativeSymbol.class),
104                 Binding.vmStore(abi.targetAddrStorage(), long.class)));
105             if (needsReturnBuffer) {
106                 addArgumentBinding(0, MemorySegment.class, ValueLayout.ADDRESS, List.of(
107                     Binding.unboxAddress(MemorySegment.class),
108                     Binding.vmStore(abi.retBufAddrStorage(), long.class)));
109             }
110         } else if (needsReturnBuffer) { // forUpcall == true
111             addArgumentBinding(0, MemorySegment.class, ValueLayout.ADDRESS, List.of(
112                 Binding.vmLoad(abi.retBufAddrStorage(), long.class),
113                 Binding.boxAddress(),
114                 Binding.toSegment(returnBufferSize)));
115         }
116         return new CallingSequence(mt, desc, isTrivial, needsReturnBuffer, returnBufferSize, allocationSize, inputBindings, outputBindings);
117     }
118 
119     private long computeAllocationSize() {
120         // FIXME: > 16 bytes alignment might need extra space since the
121         // starting address of the allocator might be un-aligned.
122         long size = 0;
123         for (List<Binding> bindings : inputBindings) {
124             for (Binding b : bindings) {
125                 if (b instanceof Binding.Copy copy) {
126                     size = Utils.alignUp(size, copy.alignment());
127                     size += copy.size();
128                 } else if (b instanceof Binding.Allocate allocate) {
129                     size = Utils.alignUp(size, allocate.alignment());
130                     size += allocate.size();
131                 }
132             }
133         }
134         return size;
135     }
136 
137     private long computeReturnBuferSize() {
138         return outputBindings.stream()
139                 .filter(Binding.Move.class::isInstance)
140                 .map(Binding.Move.class::cast)
141                 .map(Binding.Move::storage)
142                 .map(VMStorage::type)
143                 .mapToLong(abi.arch::typeSize)
144                 .sum();
145     }
146 
147     private void verifyBindings(boolean forArguments, Class<?> carrier, List<Binding> bindings) {
148         if (VERIFY_BINDINGS) {
149             if (forUpcall == forArguments) {
150                 verifyBoxBindings(carrier, bindings);
151             } else {
152                 verifyUnboxBindings(carrier, bindings);
153             }
154         }
155     }
156 
157     private static final Set<Binding.Tag> UNBOX_TAGS = EnumSet.of(
158         VM_STORE,
159         //VM_LOAD,
160         //BUFFER_STORE,
161         BUFFER_LOAD,
162         COPY_BUFFER,
163         //ALLOC_BUFFER,
164         //BOX_ADDRESS,
165         UNBOX_ADDRESS,
166         //TO_SEGMENT,
167         DUP
168     );
169 
170     private static void verifyUnboxBindings(Class<?> inType, List<Binding> bindings) {
171         Deque<Class<?>> stack = new ArrayDeque<>();
172         stack.push(inType);
173 
174         for (Binding b : bindings) {
175             if (!UNBOX_TAGS.contains(b.tag()))
176                 throw new IllegalArgumentException("Unexpected operator: " + b);
177             b.verify(stack);
178         }
179 
180         if (!stack.isEmpty()) {
181             throw new IllegalArgumentException("Stack must be empty after recipe");
182         }
183     }
184 
185     private static final Set<Binding.Tag> BOX_TAGS = EnumSet.of(
186         //VM_STORE,
187         VM_LOAD,
188         BUFFER_STORE,
189         //BUFFER_LOAD,
190         COPY_BUFFER,
191         ALLOC_BUFFER,
192         BOX_ADDRESS,
193         //UNBOX_ADDRESS,
194         TO_SEGMENT,
195         DUP
196     );
197 
198     private static void verifyBoxBindings(Class<?> expectedOutType, List<Binding> bindings) {
199         Deque<Class<?>> stack = new ArrayDeque<>();
200 
201         for (Binding b : bindings) {
202             if (!BOX_TAGS.contains(b.tag()))
203                 throw new IllegalArgumentException("Unexpected operator: " + b);
204             b.verify(stack);
205         }
206 
207         if (stack.size() != 1) {
208             throw new IllegalArgumentException("Stack must contain exactly 1 value");
209         }
210 
211         Class<?> actualOutType = stack.pop();
212         SharedUtils.checkType(actualOutType, expectedOutType);
213     }
214 }
--- EOF ---