1 /*
  2  *  Copyright (c) 2019, 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  */
 26 package jdk.internal.foreign;
 27 
 28 import jdk.incubator.foreign.MemoryHandles;
 29 import jdk.incubator.foreign.MemoryLayout;
 30 import jdk.incubator.foreign.MemorySegment;
 31 import jdk.internal.access.JavaLangInvokeAccess;
 32 import jdk.internal.access.SharedSecrets;
 33 import jdk.internal.access.foreign.MemorySegmentProxy;
 34 
 35 import jdk.incubator.foreign.GroupLayout;
 36 import jdk.incubator.foreign.SequenceLayout;
 37 import jdk.incubator.foreign.ValueLayout;
 38 
 39 import java.lang.invoke.MethodHandle;
 40 import java.lang.invoke.MethodHandles;
 41 import java.lang.invoke.MethodType;
 42 import java.lang.invoke.VarHandle;
 43 import java.util.ArrayDeque;
 44 import java.util.ArrayList;
 45 import java.util.Deque;
 46 import java.util.List;
 47 import java.util.function.ToLongFunction;
 48 import java.util.function.UnaryOperator;
 49 
 50 /**
 51  * This class provide support for constructing layout paths; that is, starting from a root path (see {@link #rootPath(MemoryLayout, ToLongFunction)},
 52  * a path can be constructed by selecting layout elements using the selector methods provided by this class
 53  * (see {@link #sequenceElement()}, {@link #sequenceElement(long)}, {@link #sequenceElement(long, long)}, {@link #groupElement(String)}).
 54  * Once a path has been fully constructed, clients can ask for the offset associated with the layout element selected
 55  * by the path (see {@link #offset}), or obtain a memory access var handle to access the selected layout element
 56  * given an address pointing to a segment associated with the root layout (see {@link #dereferenceHandle(Class)}).
 57  */
 58 public class LayoutPath {
 59 
 60     private static final JavaLangInvokeAccess JLI = SharedSecrets.getJavaLangInvokeAccess();
 61 
 62     private static final MethodHandle ADD_STRIDE;
 63     private static final MethodHandle MH_ADD_SCALED_OFFSET;
 64     private static final MethodHandle MH_SLICE;
 65 
 66     private static final int UNSPECIFIED_ELEM_INDEX = -1;
 67 
 68     static {
 69         try {
 70             MethodHandles.Lookup lookup = MethodHandles.lookup();
 71             ADD_STRIDE = lookup.findStatic(LayoutPath.class, "addStride",
 72                     MethodType.methodType(long.class, MemorySegment.class, long.class, long.class, long.class));
 73             MH_ADD_SCALED_OFFSET = lookup.findStatic(LayoutPath.class, "addScaledOffset",
 74                     MethodType.methodType(long.class, long.class, long.class, long.class));
 75             MH_SLICE = lookup.findVirtual(MemorySegment.class, "asSlice",
 76                     MethodType.methodType(MemorySegment.class, long.class, long.class));
 77         } catch (Throwable ex) {
 78             throw new ExceptionInInitializerError(ex);
 79         }
 80     }
 81 
 82     private final MemoryLayout layout;
 83     private final long offset;
 84     private final LayoutPath enclosing;
 85     private final long[] strides;
 86     private final long elementIndex;
 87     private final ToLongFunction<MemoryLayout> sizeFunc;
 88 
 89     private LayoutPath(MemoryLayout layout, long offset, long[] strides, long elementIndex, LayoutPath enclosing, ToLongFunction<MemoryLayout> sizeFunc) {
 90         this.layout = layout;
 91         this.offset = offset;
 92         this.strides = strides;
 93         this.enclosing = enclosing;
 94         this.elementIndex = elementIndex;
 95         this.sizeFunc = sizeFunc;
 96     }
 97 
 98     // Layout path selector methods
 99 
100     public LayoutPath sequenceElement() {
101         check(SequenceLayout.class, "attempting to select a sequence element from a non-sequence layout");
102         SequenceLayout seq = (SequenceLayout)layout;
103         MemoryLayout elem = seq.elementLayout();
104         return LayoutPath.nestedPath(elem, offset, addStride(sizeFunc.applyAsLong(elem)), UNSPECIFIED_ELEM_INDEX, this);
105     }
106 
107     public LayoutPath sequenceElement(long start, long step) {
108         check(SequenceLayout.class, "attempting to select a sequence element from a non-sequence layout");
109         SequenceLayout seq = (SequenceLayout)layout;
110         checkSequenceBounds(seq, start);
111         MemoryLayout elem = seq.elementLayout();
112         long elemSize = sizeFunc.applyAsLong(elem);
113         return LayoutPath.nestedPath(elem, offset + (start * elemSize), addStride(elemSize * step),
114                 UNSPECIFIED_ELEM_INDEX, this);
115     }
116 
117     public LayoutPath sequenceElement(long index) {
118         check(SequenceLayout.class, "attempting to select a sequence element from a non-sequence layout");
119         SequenceLayout seq = (SequenceLayout)layout;
120         checkSequenceBounds(seq, index);
121         long elemOffset = 0;
122         if (index > 0) {
123             //if index == 0, we do not depend on sequence element size, so skip
124             long elemSize = sizeFunc.applyAsLong(seq.elementLayout());
125             elemOffset = elemSize * index;
126         }
127         return LayoutPath.nestedPath(seq.elementLayout(), offset + elemOffset, strides, index, this);
128     }
129 
130     public LayoutPath groupElement(String name) {
131         check(GroupLayout.class, "attempting to select a group element from a non-group layout");
132         GroupLayout g = (GroupLayout)layout;
133         long offset = 0;
134         MemoryLayout elem = null;
135         int index = -1;
136         for (int i = 0; i < g.memberLayouts().size(); i++) {
137             MemoryLayout l = g.memberLayouts().get(i);
138             if (l.name().isPresent() &&
139                 l.name().get().equals(name)) {
140                 elem = l;
141                 index = i;
142                 break;
143             } else if (g.isStruct()) {
144                 offset += sizeFunc.applyAsLong(l);
145             }
146         }
147         if (elem == null) {
148             throw badLayoutPath("cannot resolve '" + name + "' in layout " + layout);
149         }
150         return LayoutPath.nestedPath(elem, this.offset + offset, strides, index, this);
151     }
152 
153     // Layout path projections
154 
155     public long offset() {
156         return offset;
157     }
158 
159     public VarHandle dereferenceHandle(Class<?> carrier) {
160         Utils.checkPrimitiveCarrierCompat(carrier, layout);
161         checkAlignment(this);
162 
163         List<Class<?>> expectedCoordinates = new ArrayList<>();
164         Deque<Integer> perms = new ArrayDeque<>();
165         perms.addFirst(0);
166         expectedCoordinates.add(MemorySegment.class);
167 
168         VarHandle handle = Utils.fixUpVarHandle(JLI.memoryAccessVarHandle(carrier, true, layout.byteAlignment() - 1,
169                 ((ValueLayout)layout).order()));
170 
171         for (int i = 0 ; i < strides.length ; i++) {
172             expectedCoordinates.add(long.class);
173             perms.addFirst(0);
174             perms.addLast(i + 1);
175             //add stride
176             handle = MemoryHandles.collectCoordinates(handle, 1 + i,
177                     MethodHandles.insertArguments(ADD_STRIDE, 1, Utils.bitsToBytesOrThrow(strides[strides.length - 1 - i], IllegalStateException::new))); // MS, long, MS_n, long_n, long
178         }
179         //add offset
180         handle = MemoryHandles.insertCoordinates(handle, 1 + strides.length, Utils.bitsToBytesOrThrow(offset, IllegalStateException::new));
181 
182         if (strides.length > 0) {
183             // remove duplicate MS args
184             handle = MemoryHandles.permuteCoordinates(handle, expectedCoordinates, perms.stream().mapToInt(i -> i).toArray());
185         }
186         return handle;
187     }
188 
189     private static long addScaledOffset(long base, long index, long stride) {
190         return base + (stride * index);
191     }
192 
193     public MethodHandle offsetHandle() {
194         MethodHandle mh = MethodHandles.identity(long.class);
195         for (int i = strides.length - 1; i >=0; i--) {
196             MethodHandle collector = MethodHandles.insertArguments(MH_ADD_SCALED_OFFSET, 2, strides[i]);
197             // (J, ...) -> J to (J, J, ...) -> J
198             // i.e. new coord is prefixed. Last coord will correspond to innermost layout
199             mh = MethodHandles.collectArguments(mh, 0, collector);
200         }
201         mh = MethodHandles.insertArguments(mh, 0, offset);
202         return mh;
203     }
204 
205     public MethodHandle sliceHandle() {
206         if (strides.length == 0) {
207             // trigger checks eagerly
208             Utils.bitsToBytesOrThrow(offset, Utils.bitsToBytesThrowOffset);
209         }
210 
211         MethodHandle offsetHandle = offsetHandle(); // bit offset
212         offsetHandle = MethodHandles.filterReturnValue(offsetHandle, Utils.MH_bitsToBytesOrThrowForOffset); // byte offset
213 
214         MethodHandle sliceHandle = MH_SLICE; // (MS, long, long) -> MS
215         sliceHandle = MethodHandles.insertArguments(sliceHandle, 2, layout.byteSize()); // (MS, long) -> MS
216         sliceHandle = MethodHandles.collectArguments(sliceHandle, 1, offsetHandle); // (MS, ...) -> MS
217 
218         return sliceHandle;
219     }
220 
221     public MemoryLayout layout() {
222         return layout;
223     }
224 
225     public MemoryLayout map(UnaryOperator<MemoryLayout> op) {
226         MemoryLayout newLayout = op.apply(layout);
227         if (enclosing == null) {
228             return newLayout;
229         } else if (enclosing.layout instanceof SequenceLayout) {
230             SequenceLayout seq = (SequenceLayout)enclosing.layout;
231             if (seq.elementCount().isPresent()) {
232                 return enclosing.map(l -> dup(l, MemoryLayout.sequenceLayout(seq.elementCount().getAsLong(), newLayout)));
233             } else {
234                 return enclosing.map(l -> dup(l, MemoryLayout.sequenceLayout(newLayout)));
235             }
236         } else if (enclosing.layout instanceof GroupLayout) {
237             GroupLayout g = (GroupLayout)enclosing.layout;
238             List<MemoryLayout> newElements = new ArrayList<>(g.memberLayouts());
239             //if we selected a layout in a group we must have a valid index
240             newElements.set((int)elementIndex, newLayout);
241             if (g.isUnion()) {
242                 return enclosing.map(l -> dup(l, MemoryLayout.unionLayout(newElements.toArray(new MemoryLayout[0]))));
243             } else {
244                 return enclosing.map(l -> dup(l, MemoryLayout.structLayout(newElements.toArray(new MemoryLayout[0]))));
245             }
246         } else {
247             return newLayout;
248         }
249     }
250 
251     private MemoryLayout dup(MemoryLayout oldLayout, MemoryLayout newLayout) {
252         newLayout = newLayout.withBitAlignment(oldLayout.bitAlignment());
253         if (oldLayout.name().isPresent()) {
254             newLayout.withName(oldLayout.name().get());
255         }
256         return newLayout;
257     }
258 
259     // Layout path construction
260 
261     public static LayoutPath rootPath(MemoryLayout layout, ToLongFunction<MemoryLayout> sizeFunc) {
262         return new LayoutPath(layout, 0L, EMPTY_STRIDES, -1, null, sizeFunc);
263     }
264 
265     private static LayoutPath nestedPath(MemoryLayout layout, long offset, long[] strides, long elementIndex, LayoutPath encl) {
266         return new LayoutPath(layout, offset, strides, elementIndex, encl, encl.sizeFunc);
267     }
268 
269     // Helper methods
270 
271     private void check(Class<?> layoutClass, String msg) {
272         if (!layoutClass.isAssignableFrom(layout.getClass())) {
273             throw badLayoutPath(msg);
274         }
275     }
276 
277     private void checkSequenceBounds(SequenceLayout seq, long index) {
278         if (seq.elementCount().isPresent() && index >= seq.elementCount().getAsLong()) {
279             throw badLayoutPath(String.format("Sequence index out of bound; found: %d, size: %d", index, seq.elementCount().getAsLong()));
280         }
281     }
282 
283     private static IllegalArgumentException badLayoutPath(String cause) {
284         return new IllegalArgumentException("Bad layout path: " + cause);
285     }
286 
287     private static void checkAlignment(LayoutPath path) {
288         MemoryLayout layout = path.layout;
289         long alignment = layout.bitAlignment();
290         if (path.offset % alignment != 0) {
291             throw new UnsupportedOperationException("Invalid alignment requirements for layout " + layout);
292         }
293         for (long stride : path.strides) {
294             if (stride % alignment != 0) {
295                 throw new UnsupportedOperationException("Alignment requirements for layout " + layout + " do not match stride " + stride);
296             }
297         }
298         LayoutPath encl = path.enclosing;
299         if (encl != null) {
300             if (encl.layout.bitAlignment() < alignment) {
301                 throw new UnsupportedOperationException("Alignment requirements for layout " + layout + " do not match those for enclosing layout " + encl.layout);
302             }
303             checkAlignment(encl);
304         }
305     }
306 
307     private long[] addStride(long stride) {
308         long[] newStrides = new long[strides.length + 1];
309         System.arraycopy(strides, 0, newStrides, 0, strides.length);
310         newStrides[strides.length] = stride;
311         return newStrides;
312     }
313 
314     private static final long[] EMPTY_STRIDES = new long[0];
315 
316     /**
317      * This class provides an immutable implementation for the {@code PathElement} interface. A path element implementation
318      * is simply a pointer to one of the selector methods provided by the {@code LayoutPath} class.
319      */
320     public static final class PathElementImpl implements MemoryLayout.PathElement, UnaryOperator<LayoutPath> {
321 
322         public enum PathKind {
323             SEQUENCE_ELEMENT("unbound sequence element"),
324             SEQUENCE_ELEMENT_INDEX("bound sequence element"),
325             SEQUENCE_RANGE("sequence range"),
326             GROUP_ELEMENT("group element");
327 
328             final String description;
329 
330             PathKind(String description) {
331                 this.description = description;
332             }
333 
334             public String description() {
335                 return description;
336             }
337         }
338 
339         final PathKind kind;
340         final UnaryOperator<LayoutPath> pathOp;
341 
342         public PathElementImpl(PathKind kind, UnaryOperator<LayoutPath> pathOp) {
343             this.kind = kind;
344             this.pathOp = pathOp;
345         }
346 
347         @Override
348         public LayoutPath apply(LayoutPath layoutPath) {
349             return pathOp.apply(layoutPath);
350         }
351 
352         public PathKind kind() {
353             return kind;
354         }
355     }
356 
357     private static long addStride(MemorySegment segment, long stride, long base, long index) {
358         return MemorySegmentProxy.addOffsets(base,
359                     MemorySegmentProxy.multiplyOffsets(stride, index, ((MemorySegmentProxy)segment)), (MemorySegmentProxy)segment);
360     }
361 }