1 /*
  2  * Copyright (c) 2014, 2018, 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 java.lang.invoke;
 27 
 28 import sun.invoke.util.Wrapper;
 29 
 30 import java.lang.reflect.Constructor;
 31 import java.lang.reflect.Field;
 32 import java.lang.reflect.Method;
 33 import java.lang.reflect.Modifier;
 34 import java.lang.reflect.Parameter;
 35 import java.nio.ByteOrder;
 36 import java.util.ArrayList;
 37 import java.util.LinkedHashMap;
 38 import java.util.List;
 39 import java.util.Map;
 40 import java.util.Objects;
 41 import java.util.concurrent.ConcurrentHashMap;
 42 import java.util.concurrent.ConcurrentMap;
 43 import java.util.stream.Stream;
 44 
 45 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
 46 import static java.lang.invoke.MethodHandleStatics.VAR_HANDLE_IDENTITY_ADAPT;
 47 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
 48 import static java.util.stream.Collectors.joining;
 49 import static java.util.stream.Collectors.toList;
 50 
 51 final class VarHandles {
 52 
 53     static ClassValue<ConcurrentMap<Integer, MethodHandle>> ADDRESS_FACTORIES = new ClassValue<>() {
 54         @Override
 55         protected ConcurrentMap<Integer, MethodHandle> computeValue(Class<?> type) {
 56             return new ConcurrentHashMap<>();
 57         }
 58     };
 59 
 60     static VarHandle makeFieldHandle(MemberName f, Class<?> refc, Class<?> type, boolean isWriteAllowedOnFinalFields) {
 61         if (!f.isStatic()) {
 62             long foffset = MethodHandleNatives.objectFieldOffset(f);
 63             if (!type.isPrimitive()) {
 64                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 65                        ? new VarHandleReferences.FieldInstanceReadOnly(refc, foffset, type)
 66                        : new VarHandleReferences.FieldInstanceReadWrite(refc, foffset, type));
 67             }
 68             else if (type == boolean.class) {
 69                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 70                        ? new VarHandleBooleans.FieldInstanceReadOnly(refc, foffset)
 71                        : new VarHandleBooleans.FieldInstanceReadWrite(refc, foffset));
 72             }
 73             else if (type == byte.class) {
 74                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 75                        ? new VarHandleBytes.FieldInstanceReadOnly(refc, foffset)
 76                        : new VarHandleBytes.FieldInstanceReadWrite(refc, foffset));
 77             }
 78             else if (type == short.class) {
 79                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 80                        ? new VarHandleShorts.FieldInstanceReadOnly(refc, foffset)
 81                        : new VarHandleShorts.FieldInstanceReadWrite(refc, foffset));
 82             }
 83             else if (type == char.class) {
 84                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 85                        ? new VarHandleChars.FieldInstanceReadOnly(refc, foffset)
 86                        : new VarHandleChars.FieldInstanceReadWrite(refc, foffset));
 87             }
 88             else if (type == int.class) {
 89                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 90                        ? new VarHandleInts.FieldInstanceReadOnly(refc, foffset)
 91                        : new VarHandleInts.FieldInstanceReadWrite(refc, foffset));
 92             }
 93             else if (type == long.class) {
 94                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 95                        ? new VarHandleLongs.FieldInstanceReadOnly(refc, foffset)
 96                        : new VarHandleLongs.FieldInstanceReadWrite(refc, foffset));
 97             }
 98             else if (type == float.class) {
 99                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
100                        ? new VarHandleFloats.FieldInstanceReadOnly(refc, foffset)
101                        : new VarHandleFloats.FieldInstanceReadWrite(refc, foffset));
102             }
103             else if (type == double.class) {
104                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
105                        ? new VarHandleDoubles.FieldInstanceReadOnly(refc, foffset)
106                        : new VarHandleDoubles.FieldInstanceReadWrite(refc, foffset));
107             }
108             else {
109                 throw new UnsupportedOperationException();
110             }
111         }
112         else {
113             // TODO This is not lazy on first invocation
114             // and might cause some circular initialization issues
115 
116             // Replace with something similar to direct method handles
117             // where a barrier is used then elided after use
118 
119             if (UNSAFE.shouldBeInitialized(refc))
120                 UNSAFE.ensureClassInitialized(refc);
121 
122             Object base = MethodHandleNatives.staticFieldBase(f);
123             long foffset = MethodHandleNatives.staticFieldOffset(f);
124             if (!type.isPrimitive()) {
125                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
126                        ? new VarHandleReferences.FieldStaticReadOnly(base, foffset, type)
127                        : new VarHandleReferences.FieldStaticReadWrite(base, foffset, type));
128             }
129             else if (type == boolean.class) {
130                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
131                        ? new VarHandleBooleans.FieldStaticReadOnly(base, foffset)
132                        : new VarHandleBooleans.FieldStaticReadWrite(base, foffset));
133             }
134             else if (type == byte.class) {
135                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
136                        ? new VarHandleBytes.FieldStaticReadOnly(base, foffset)
137                        : new VarHandleBytes.FieldStaticReadWrite(base, foffset));
138             }
139             else if (type == short.class) {
140                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
141                        ? new VarHandleShorts.FieldStaticReadOnly(base, foffset)
142                        : new VarHandleShorts.FieldStaticReadWrite(base, foffset));
143             }
144             else if (type == char.class) {
145                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
146                        ? new VarHandleChars.FieldStaticReadOnly(base, foffset)
147                        : new VarHandleChars.FieldStaticReadWrite(base, foffset));
148             }
149             else if (type == int.class) {
150                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
151                        ? new VarHandleInts.FieldStaticReadOnly(base, foffset)
152                        : new VarHandleInts.FieldStaticReadWrite(base, foffset));
153             }
154             else if (type == long.class) {
155                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
156                        ? new VarHandleLongs.FieldStaticReadOnly(base, foffset)
157                        : new VarHandleLongs.FieldStaticReadWrite(base, foffset));
158             }
159             else if (type == float.class) {
160                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
161                        ? new VarHandleFloats.FieldStaticReadOnly(base, foffset)
162                        : new VarHandleFloats.FieldStaticReadWrite(base, foffset));
163             }
164             else if (type == double.class) {
165                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
166                        ? new VarHandleDoubles.FieldStaticReadOnly(base, foffset)
167                        : new VarHandleDoubles.FieldStaticReadWrite(base, foffset));
168             }
169             else {
170                 throw new UnsupportedOperationException();
171             }
172         }
173     }
174 
175     // Required by instance field handles
176     static Field getFieldFromReceiverAndOffset(Class<?> receiverType,
177                                                long offset,
178                                                Class<?> fieldType) {
179         for (Field f : receiverType.getDeclaredFields()) {
180             if (Modifier.isStatic(f.getModifiers())) continue;
181 
182             if (offset == UNSAFE.objectFieldOffset(f)) {
183                 assert f.getType() == fieldType;
184                 return f;
185             }
186         }
187         throw new InternalError("Field not found at offset");
188     }
189 
190     // Required by instance static field handles
191     static Field getStaticFieldFromBaseAndOffset(Object base,
192                                                  long offset,
193                                                  Class<?> fieldType) {
194         // @@@ This is a little fragile assuming the base is the class
195         Class<?> receiverType = (Class<?>) base;
196         for (Field f : receiverType.getDeclaredFields()) {
197             if (!Modifier.isStatic(f.getModifiers())) continue;
198 
199             if (offset == UNSAFE.staticFieldOffset(f)) {
200                 assert f.getType() == fieldType;
201                 return f;
202             }
203         }
204         throw new InternalError("Static field not found at offset");
205     }
206 
207     static VarHandle makeArrayElementHandle(Class<?> arrayClass) {
208         if (!arrayClass.isArray())
209             throw new IllegalArgumentException("not an array: " + arrayClass);
210 
211         Class<?> componentType = arrayClass.getComponentType();
212 
213         int aoffset = UNSAFE.arrayBaseOffset(arrayClass);
214         int ascale = UNSAFE.arrayIndexScale(arrayClass);
215         int ashift = 31 - Integer.numberOfLeadingZeros(ascale);
216 
217         if (!componentType.isPrimitive()) {
218             return maybeAdapt(new VarHandleReferences.Array(aoffset, ashift, arrayClass));
219         }
220         else if (componentType == boolean.class) {
221             return maybeAdapt(new VarHandleBooleans.Array(aoffset, ashift));
222         }
223         else if (componentType == byte.class) {
224             return maybeAdapt(new VarHandleBytes.Array(aoffset, ashift));
225         }
226         else if (componentType == short.class) {
227             return maybeAdapt(new VarHandleShorts.Array(aoffset, ashift));
228         }
229         else if (componentType == char.class) {
230             return maybeAdapt(new VarHandleChars.Array(aoffset, ashift));
231         }
232         else if (componentType == int.class) {
233             return maybeAdapt(new VarHandleInts.Array(aoffset, ashift));
234         }
235         else if (componentType == long.class) {
236             return maybeAdapt(new VarHandleLongs.Array(aoffset, ashift));
237         }
238         else if (componentType == float.class) {
239             return maybeAdapt(new VarHandleFloats.Array(aoffset, ashift));
240         }
241         else if (componentType == double.class) {
242             return maybeAdapt(new VarHandleDoubles.Array(aoffset, ashift));
243         }
244         else {
245             throw new UnsupportedOperationException();
246         }
247     }
248 
249     static VarHandle byteArrayViewHandle(Class<?> viewArrayClass,
250                                          boolean be) {
251         if (!viewArrayClass.isArray())
252             throw new IllegalArgumentException("not an array: " + viewArrayClass);
253 
254         Class<?> viewComponentType = viewArrayClass.getComponentType();
255 
256         if (viewComponentType == long.class) {
257             return maybeAdapt(new VarHandleByteArrayAsLongs.ArrayHandle(be));
258         }
259         else if (viewComponentType == int.class) {
260             return maybeAdapt(new VarHandleByteArrayAsInts.ArrayHandle(be));
261         }
262         else if (viewComponentType == short.class) {
263             return maybeAdapt(new VarHandleByteArrayAsShorts.ArrayHandle(be));
264         }
265         else if (viewComponentType == char.class) {
266             return maybeAdapt(new VarHandleByteArrayAsChars.ArrayHandle(be));
267         }
268         else if (viewComponentType == double.class) {
269             return maybeAdapt(new VarHandleByteArrayAsDoubles.ArrayHandle(be));
270         }
271         else if (viewComponentType == float.class) {
272             return maybeAdapt(new VarHandleByteArrayAsFloats.ArrayHandle(be));
273         }
274 
275         throw new UnsupportedOperationException();
276     }
277 
278     static VarHandle makeByteBufferViewHandle(Class<?> viewArrayClass,
279                                               boolean be) {
280         if (!viewArrayClass.isArray())
281             throw new IllegalArgumentException("not an array: " + viewArrayClass);
282 
283         Class<?> viewComponentType = viewArrayClass.getComponentType();
284 
285         if (viewComponentType == long.class) {
286             return maybeAdapt(new VarHandleByteArrayAsLongs.ByteBufferHandle(be));
287         }
288         else if (viewComponentType == int.class) {
289             return maybeAdapt(new VarHandleByteArrayAsInts.ByteBufferHandle(be));
290         }
291         else if (viewComponentType == short.class) {
292             return maybeAdapt(new VarHandleByteArrayAsShorts.ByteBufferHandle(be));
293         }
294         else if (viewComponentType == char.class) {
295             return maybeAdapt(new VarHandleByteArrayAsChars.ByteBufferHandle(be));
296         }
297         else if (viewComponentType == double.class) {
298             return maybeAdapt(new VarHandleByteArrayAsDoubles.ByteBufferHandle(be));
299         }
300         else if (viewComponentType == float.class) {
301             return maybeAdapt(new VarHandleByteArrayAsFloats.ByteBufferHandle(be));
302         }
303 
304         throw new UnsupportedOperationException();
305     }
306 
307     /**
308      * Creates a memory access VarHandle.
309      *
310      * Resulting VarHandle will take a memory address as first argument,
311      * and a certain number of coordinate {@code long} parameters, depending on the length
312      * of the {@code strides} argument array.
313      *
314      * Coordinates are multiplied with corresponding scale factors ({@code strides}) and added
315      * to a single fixed offset to compute an effective offset from the given MemoryAddress for the access.
316      *
317      * @param carrier the Java carrier type.
318      * @param skipAlignmentMaskCheck if true, only the base part of the address will be checked for alignment.
319      * @param alignmentMask alignment requirement to be checked upon access. In bytes. Expressed as a mask.
320      * @param byteOrder the byte order.
321      * @return the created VarHandle.
322      */
323     static VarHandle makeMemoryAddressViewHandle(Class<?> carrier, boolean skipAlignmentMaskCheck, long alignmentMask,
324                                                  ByteOrder byteOrder) {
325         if (!carrier.isPrimitive() || carrier == void.class || carrier == boolean.class) {
326             throw new IllegalArgumentException("Invalid carrier: " + carrier.getName());
327         }
328         long size = Wrapper.forPrimitiveType(carrier).bitWidth() / 8;
329         boolean be = byteOrder == ByteOrder.BIG_ENDIAN;
330         boolean exact = false;
331 
332         if (carrier == byte.class) {
333             return maybeAdapt(new MemoryAccessVarHandleByteHelper(skipAlignmentMaskCheck, be, size, alignmentMask, exact));
334         } else if (carrier == char.class) {
335             return maybeAdapt(new MemoryAccessVarHandleCharHelper(skipAlignmentMaskCheck, be, size, alignmentMask, exact));
336         } else if (carrier == short.class) {
337             return maybeAdapt(new MemoryAccessVarHandleShortHelper(skipAlignmentMaskCheck, be, size, alignmentMask, exact));
338         } else if (carrier == int.class) {
339             return maybeAdapt(new MemoryAccessVarHandleIntHelper(skipAlignmentMaskCheck, be, size, alignmentMask, exact));
340         } else if (carrier == float.class) {
341             return maybeAdapt(new MemoryAccessVarHandleFloatHelper(skipAlignmentMaskCheck, be, size, alignmentMask, exact));
342         } else if (carrier == long.class) {
343             return maybeAdapt(new MemoryAccessVarHandleLongHelper(skipAlignmentMaskCheck, be, size, alignmentMask, exact));
344         } else if (carrier == double.class) {
345             return maybeAdapt(new MemoryAccessVarHandleDoubleHelper(skipAlignmentMaskCheck, be, size, alignmentMask, exact));
346         } else {
347             throw new IllegalStateException("Cannot get here");
348         }
349     }
350 
351     private static VarHandle maybeAdapt(VarHandle target) {
352         if (!VAR_HANDLE_IDENTITY_ADAPT) return target;
353         target = filterValue(target,
354                         MethodHandles.identity(target.varType()), MethodHandles.identity(target.varType()));
355         MethodType mtype = target.accessModeType(VarHandle.AccessMode.GET);
356         for (int i = 0 ; i < mtype.parameterCount() ; i++) {
357             target = filterCoordinates(target, i, MethodHandles.identity(mtype.parameterType(i)));
358         }
359         return target;
360     }
361 
362     public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) {
363         Objects.requireNonNull(target);
364         Objects.requireNonNull(filterToTarget);
365         Objects.requireNonNull(filterFromTarget);
366         //check that from/to filters do not throw checked exceptions
367         noCheckedExceptions(filterToTarget);
368         noCheckedExceptions(filterFromTarget);
369 
370         List<Class<?>> newCoordinates = new ArrayList<>();
371         List<Class<?>> additionalCoordinates = new ArrayList<>();
372         newCoordinates.addAll(target.coordinateTypes());
373 
374         //check that from/to filters have right signatures
375         if (filterFromTarget.type().parameterCount() != filterToTarget.type().parameterCount()) {
376             throw newIllegalArgumentException("filterFromTarget and filterToTarget have different arity", filterFromTarget.type(), filterToTarget.type());
377         } else if (filterFromTarget.type().parameterCount() < 1) {
378             throw newIllegalArgumentException("filterFromTarget filter type has wrong arity", filterFromTarget.type());
379         } else if (filterToTarget.type().parameterCount() < 1) {
380             throw newIllegalArgumentException("filterToTarget filter type has wrong arity", filterFromTarget.type());
381         } else if (filterFromTarget.type().lastParameterType() != filterToTarget.type().returnType() ||
382                 filterToTarget.type().lastParameterType() != filterFromTarget.type().returnType()) {
383             throw newIllegalArgumentException("filterFromTarget and filterToTarget filter types do not match", filterFromTarget.type(), filterToTarget.type());
384         } else if (target.varType() != filterFromTarget.type().lastParameterType()) {
385             throw newIllegalArgumentException("filterFromTarget filter type does not match target var handle type", filterFromTarget.type(), target.varType());
386         } else if (target.varType() != filterToTarget.type().returnType()) {
387             throw newIllegalArgumentException("filterFromTarget filter type does not match target var handle type", filterToTarget.type(), target.varType());
388         } else if (filterFromTarget.type().parameterCount() > 1) {
389             for (int i = 0 ; i < filterFromTarget.type().parameterCount() - 1 ; i++) {
390                 if (filterFromTarget.type().parameterType(i) != filterToTarget.type().parameterType(i)) {
391                     throw newIllegalArgumentException("filterFromTarget and filterToTarget filter types do not match", filterFromTarget.type(), filterToTarget.type());
392                 } else {
393                     newCoordinates.add(filterFromTarget.type().parameterType(i));
394                     additionalCoordinates.add((filterFromTarget.type().parameterType(i)));
395                 }
396             }
397         }
398 
399         return new IndirectVarHandle(target, filterFromTarget.type().returnType(), newCoordinates.toArray(new Class<?>[0]),
400                 (mode, modeHandle) -> {
401                     int lastParameterPos = modeHandle.type().parameterCount() - 1;
402                     return switch (mode.at) {
403                         case GET -> MethodHandles.collectReturnValue(modeHandle, filterFromTarget);
404                         case SET -> MethodHandles.collectArguments(modeHandle, lastParameterPos, filterToTarget);
405                         case GET_AND_UPDATE -> {
406                             MethodHandle adapter = MethodHandles.collectReturnValue(modeHandle, filterFromTarget);
407                             MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos, filterToTarget);
408                             if (additionalCoordinates.size() > 0) {
409                                 res = joinDuplicateArgs(res, lastParameterPos,
410                                         lastParameterPos + additionalCoordinates.size() + 1,
411                                         additionalCoordinates.size());
412                             }
413                             yield res;
414                         }
415                         case COMPARE_AND_EXCHANGE -> {
416                             MethodHandle adapter = MethodHandles.collectReturnValue(modeHandle, filterFromTarget);
417                             adapter = MethodHandles.collectArguments(adapter, lastParameterPos, filterToTarget);
418                             if (additionalCoordinates.size() > 0) {
419                                 adapter = joinDuplicateArgs(adapter, lastParameterPos,
420                                         lastParameterPos + additionalCoordinates.size() + 1,
421                                         additionalCoordinates.size());
422                             }
423                             MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos - 1, filterToTarget);
424                             if (additionalCoordinates.size() > 0) {
425                                 res = joinDuplicateArgs(res, lastParameterPos - 1,
426                                         lastParameterPos + additionalCoordinates.size(),
427                                         additionalCoordinates.size());
428                             }
429                             yield res;
430                         }
431                         case COMPARE_AND_SET -> {
432                             MethodHandle adapter = MethodHandles.collectArguments(modeHandle, lastParameterPos, filterToTarget);
433                             MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos - 1, filterToTarget);
434                             if (additionalCoordinates.size() > 0) {
435                                 res = joinDuplicateArgs(res, lastParameterPos - 1,
436                                         lastParameterPos + additionalCoordinates.size(),
437                                         additionalCoordinates.size());
438                             }
439                             yield res;
440                         }
441                     };
442                 });
443     }
444 
445     private static MethodHandle joinDuplicateArgs(MethodHandle handle, int originalStart, int dropStart, int length) {
446         int[] perms = new int[handle.type().parameterCount()];
447         for (int i = 0 ; i < dropStart; i++) {
448             perms[i] = i;
449         }
450         for (int i = 0 ; i < length ; i++) {
451             perms[dropStart + i] = originalStart + i;
452         }
453         for (int i = dropStart + length ; i < perms.length ; i++) {
454             perms[i] = i - length;
455         }
456         return MethodHandles.permuteArguments(handle,
457                 handle.type().dropParameterTypes(dropStart, dropStart + length),
458                 perms);
459     }
460 
461     public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
462         Objects.requireNonNull(target);
463         Objects.requireNonNull(filters);
464 
465         List<Class<?>> targetCoordinates = target.coordinateTypes();
466         if (pos < 0 || pos >= targetCoordinates.size()) {
467             throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
468         } else if (pos + filters.length > targetCoordinates.size()) {
469             throw new IllegalArgumentException("Too many filters");
470         }
471 
472         if (filters.length == 0) return target;
473 
474         List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
475         for (int i = 0 ; i < filters.length ; i++) {
476             noCheckedExceptions(filters[i]);
477             MethodType filterType = filters[i].type();
478             if (filterType.parameterCount() != 1) {
479                 throw newIllegalArgumentException("Invalid filter type " + filterType);
480             } else if (newCoordinates.get(pos + i) != filterType.returnType()) {
481                 throw newIllegalArgumentException("Invalid filter type " + filterType + " for coordinate type " + newCoordinates.get(i));
482             }
483             newCoordinates.set(pos + i, filters[i].type().parameterType(0));
484         }
485 
486         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
487                 (mode, modeHandle) -> MethodHandles.filterArguments(modeHandle, 1 + pos, filters));
488     }
489 
490     public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
491         Objects.requireNonNull(target);
492         Objects.requireNonNull(values);
493 
494         List<Class<?>> targetCoordinates = target.coordinateTypes();
495         if (pos < 0 || pos >= targetCoordinates.size()) {
496             throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
497         } else if (pos + values.length > targetCoordinates.size()) {
498             throw new IllegalArgumentException("Too many values");
499         }
500 
501         if (values.length == 0) return target;
502 
503         List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
504         for (int i = 0 ; i < values.length ; i++) {
505             Class<?> pt = newCoordinates.get(pos);
506             if (pt.isPrimitive()) {
507                 Wrapper w = Wrapper.forPrimitiveType(pt);
508                 w.convert(values[i], pt);
509             } else {
510                 pt.cast(values[i]);
511             }
512             newCoordinates.remove(pos);
513         }
514 
515         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
516                 (mode, modeHandle) -> MethodHandles.insertArguments(modeHandle, 1 + pos, values));
517     }
518 
519     public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) {
520         Objects.requireNonNull(target);
521         Objects.requireNonNull(newCoordinates);
522         Objects.requireNonNull(reorder);
523 
524         List<Class<?>> targetCoordinates = target.coordinateTypes();
525         MethodHandles.permuteArgumentChecks(reorder,
526                 MethodType.methodType(void.class, newCoordinates),
527                 MethodType.methodType(void.class, targetCoordinates));
528 
529         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
530                 (mode, modeHandle) ->
531                         MethodHandles.permuteArguments(modeHandle,
532                                 methodTypeFor(mode.at, modeHandle.type(), targetCoordinates, newCoordinates),
533                                 reorderArrayFor(mode.at, newCoordinates, reorder)));
534     }
535 
536     private static int numTrailingArgs(VarHandle.AccessType at) {
537         return switch (at) {
538             case GET -> 0;
539             case GET_AND_UPDATE, SET -> 1;
540             case COMPARE_AND_SET, COMPARE_AND_EXCHANGE -> 2;
541         };
542     }
543 
544     private static int[] reorderArrayFor(VarHandle.AccessType at, List<Class<?>> newCoordinates, int[] reorder) {
545         int numTrailingArgs = numTrailingArgs(at);
546         int[] adjustedReorder = new int[reorder.length + 1 + numTrailingArgs];
547         adjustedReorder[0] = 0;
548         for (int i = 0 ; i < reorder.length ; i++) {
549             adjustedReorder[i + 1] = reorder[i] + 1;
550         }
551         for (int i = 0 ; i < numTrailingArgs ; i++) {
552             adjustedReorder[i + reorder.length + 1] = i + newCoordinates.size() + 1;
553         }
554         return adjustedReorder;
555     }
556 
557     private static MethodType methodTypeFor(VarHandle.AccessType at, MethodType oldType, List<Class<?>> oldCoordinates, List<Class<?>> newCoordinates) {
558         int numTrailingArgs = numTrailingArgs(at);
559         MethodType adjustedType = MethodType.methodType(oldType.returnType(), oldType.parameterType(0));
560         adjustedType = adjustedType.appendParameterTypes(newCoordinates);
561         for (int i = 0 ; i < numTrailingArgs ; i++) {
562             adjustedType = adjustedType.appendParameterTypes(oldType.parameterType(1 + oldCoordinates.size() + i));
563         }
564         return adjustedType;
565     }
566 
567     public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) {
568         Objects.requireNonNull(target);
569         Objects.requireNonNull(filter);
570         noCheckedExceptions(filter);
571 
572         List<Class<?>> targetCoordinates = target.coordinateTypes();
573         if (pos < 0 || pos >= targetCoordinates.size()) {
574             throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
575         } else if (filter.type().returnType() == void.class) {
576             throw newIllegalArgumentException("Invalid filter type " + filter.type() + " ; filter cannot be void");
577         } else if (filter.type().returnType() != targetCoordinates.get(pos)) {
578             throw newIllegalArgumentException("Invalid filter type " + filter.type() + " for coordinate type " + targetCoordinates.get(pos));
579         }
580 
581         List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
582         newCoordinates.remove(pos);
583         newCoordinates.addAll(pos, filter.type().parameterList());
584 
585         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
586                 (mode, modeHandle) -> MethodHandles.collectArguments(modeHandle, 1 + pos, filter));
587     }
588 
589     public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
590         Objects.requireNonNull(target);
591         Objects.requireNonNull(valueTypes);
592 
593         List<Class<?>> targetCoordinates = target.coordinateTypes();
594         if (pos < 0 || pos > targetCoordinates.size()) {
595             throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
596         }
597 
598         if (valueTypes.length == 0) return target;
599 
600         List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
601         newCoordinates.addAll(pos, List.of(valueTypes));
602 
603         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
604                 (mode, modeHandle) -> MethodHandles.dropArguments(modeHandle, 1 + pos, valueTypes));
605     }
606 
607     private static void noCheckedExceptions(MethodHandle handle) {
608         if (handle instanceof DirectMethodHandle directHandle) {
609             byte refKind = directHandle.member.getReferenceKind();
610             MethodHandleInfo info = new InfoFromMemberName(
611                     MethodHandles.Lookup.IMPL_LOOKUP,
612                     directHandle.member,
613                     refKind);
614             final Class<?>[] exceptionTypes;
615             if (MethodHandleNatives.refKindIsMethod(refKind)) {
616                 exceptionTypes = info.reflectAs(Method.class, MethodHandles.Lookup.IMPL_LOOKUP)
617                         .getExceptionTypes();
618             } else if (MethodHandleNatives.refKindIsField(refKind)) {
619                 exceptionTypes = null;
620             } else if (MethodHandleNatives.refKindIsConstructor(refKind)) {
621                 exceptionTypes = info.reflectAs(Constructor.class, MethodHandles.Lookup.IMPL_LOOKUP)
622                         .getExceptionTypes();
623             } else {
624                 throw new AssertionError("Cannot get here");
625             }
626             if (exceptionTypes != null) {
627                 if (Stream.of(exceptionTypes).anyMatch(VarHandles::isCheckedException)) {
628                     throw newIllegalArgumentException("Cannot adapt a var handle with a method handle which throws checked exceptions");
629                 }
630             }
631         } else if (handle instanceof DelegatingMethodHandle) {
632             noCheckedExceptions(((DelegatingMethodHandle)handle).getTarget());
633         } else {
634             //bound
635             BoundMethodHandle boundHandle = (BoundMethodHandle)handle;
636             for (int i = 0 ; i < boundHandle.fieldCount() ; i++) {
637                 Object arg = boundHandle.arg(i);
638                 if (arg instanceof MethodHandle){
639                     noCheckedExceptions((MethodHandle) arg);
640                 }
641             }
642         }
643     }
644 
645     private static boolean isCheckedException(Class<?> clazz) {
646         return Throwable.class.isAssignableFrom(clazz) &&
647                 !RuntimeException.class.isAssignableFrom(clazz) &&
648                 !Error.class.isAssignableFrom(clazz);
649     }
650 
651 //    /**
652 //     * A helper program to generate the VarHandleGuards class with a set of
653 //     * static guard methods each of which corresponds to a particular shape and
654 //     * performs a type check of the symbolic type descriptor with the VarHandle
655 //     * type descriptor before linking/invoking to the underlying operation as
656 //     * characterized by the operation member name on the VarForm of the
657 //     * VarHandle.
658 //     * <p>
659 //     * The generated class essentially encapsulates pre-compiled LambdaForms,
660 //     * one for each method, for the most set of common method signatures.
661 //     * This reduces static initialization costs, footprint costs, and circular
662 //     * dependencies that may arise if a class is generated per LambdaForm.
663 //     * <p>
664 //     * A maximum of L*T*S methods will be generated where L is the number of
665 //     * access modes kinds (or unique operation signatures) and T is the number
666 //     * of variable types and S is the number of shapes (such as instance field,
667 //     * static field, or array access).
668 //     * If there are 4 unique operation signatures, 5 basic types (Object, int,
669 //     * long, float, double), and 3 shapes then a maximum of 60 methods will be
670 //     * generated.  However, the number is likely to be less since there
671 //     * be duplicate signatures.
672 //     * <p>
673 //     * Each method is annotated with @LambdaForm.Compiled to inform the runtime
674 //     * that such methods should be treated as if a method of a class that is the
675 //     * result of compiling a LambdaForm.  Annotation of such methods is
676 //     * important for correct evaluation of certain assertions and method return
677 //     * type profiling in HotSpot.
678 //     */
679 //    public static class GuardMethodGenerator {
680 //
681 //        static final String GUARD_METHOD_SIG_TEMPLATE = "<RETURN> <NAME>_<SIGNATURE>(<PARAMS>)";
682 //
683 //        static final String GUARD_METHOD_TEMPLATE =
684 //                """
685 //                @ForceInline
686 //                @LambdaForm.Compiled
687 //                @Hidden
688 //                static final <METHOD> throws Throwable {
689 //                    handle.checkExactAccessMode(ad);
690 //                    if (handle.isDirect() && handle.vform.methodType_table[ad.type] == ad.symbolicMethodTypeErased) {
691 //                        <RESULT_ERASED>MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);<RETURN_ERASED>
692 //                    } else {
693 //                        MethodHandle mh = handle.getMethodHandle(ad.mode);
694 //                        <RETURN>mh.asType(ad.symbolicMethodTypeInvoker).invokeBasic(<LINK_TO_INVOKER_ARGS>);
695 //                    }
696 //                }""";
697 //
698 //        static final String GUARD_METHOD_TEMPLATE_V =
699 //                """
700 //                @ForceInline
701 //                @LambdaForm.Compiled
702 //                @Hidden
703 //                static final <METHOD> throws Throwable {
704 //                    handle.checkExactAccessMode(ad);
705 //                    if (handle.isDirect() && handle.vform.methodType_table[ad.type] == ad.symbolicMethodTypeErased) {
706 //                        MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);
707 //                    } else if (handle.isDirect() && handle.vform.getMethodType_V(ad.type) == ad.symbolicMethodTypeErased) {
708 //                        MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);
709 //                    } else {
710 //                        MethodHandle mh = handle.getMethodHandle(ad.mode);
711 //                        mh.asType(ad.symbolicMethodTypeInvoker).invokeBasic(<LINK_TO_INVOKER_ARGS>);
712 //                    }
713 //                }""";
714 //
715 //        // A template for deriving the operations
716 //        // could be supported by annotating VarHandle directly with the
717 //        // operation kind and shape
718 //        interface VarHandleTemplate {
719 //            Object get();
720 //
721 //            void set(Object value);
722 //
723 //            boolean compareAndSet(Object actualValue, Object expectedValue);
724 //
725 //            Object compareAndExchange(Object actualValue, Object expectedValue);
726 //
727 //            Object getAndUpdate(Object value);
728 //        }
729 //
730 //        static class HandleType {
731 //            final Class<?> receiver;
732 //            final Class<?>[] intermediates;
733 //            final Class<?> value;
734 //
735 //            HandleType(Class<?> receiver, Class<?> value, Class<?>... intermediates) {
736 //                this.receiver = receiver;
737 //                this.intermediates = intermediates;
738 //                this.value = value;
739 //            }
740 //        }
741 //
742 //        /**
743 //         * @param args parameters
744 //         */
745 //        public static void main(String[] args) {
746 //            System.out.println("package java.lang.invoke;");
747 //            System.out.println();
748 //            System.out.println("import jdk.internal.vm.annotation.ForceInline;");
749 //            System.out.println("import jdk.internal.vm.annotation.Hidden;");
750 //            System.out.println();
751 //            System.out.println("// This class is auto-generated by " +
752 //                               GuardMethodGenerator.class.getName() +
753 //                               ". Do not edit.");
754 //            System.out.println("final class VarHandleGuards {");
755 //
756 //            System.out.println();
757 //
758 //            // Declare the stream of shapes
759 //            Stream<HandleType> hts = Stream.of(
760 //                    // Object->Object
761 //                    new HandleType(Object.class, Object.class),
762 //                    // Object->int
763 //                    new HandleType(Object.class, int.class),
764 //                    // Object->long
765 //                    new HandleType(Object.class, long.class),
766 //                    // Object->float
767 //                    new HandleType(Object.class, float.class),
768 //                    // Object->double
769 //                    new HandleType(Object.class, double.class),
770 //
771 //                    // <static>->Object
772 //                    new HandleType(null, Object.class),
773 //                    // <static>->int
774 //                    new HandleType(null, int.class),
775 //                    // <static>->long
776 //                    new HandleType(null, long.class),
777 //                    // <static>->float
778 //                    new HandleType(null, float.class),
779 //                    // <static>->double
780 //                    new HandleType(null, double.class),
781 //
782 //                    // Array[int]->Object
783 //                    new HandleType(Object.class, Object.class, int.class),
784 //                    // Array[int]->int
785 //                    new HandleType(Object.class, int.class, int.class),
786 //                    // Array[int]->long
787 //                    new HandleType(Object.class, long.class, int.class),
788 //                    // Array[int]->float
789 //                    new HandleType(Object.class, float.class, int.class),
790 //                    // Array[int]->double
791 //                    new HandleType(Object.class, double.class, int.class),
792 //
793 //                    // Array[long]->int
794 //                    new HandleType(Object.class, int.class, long.class),
795 //                    // Array[long]->long
796 //                    new HandleType(Object.class, long.class, long.class)
797 //            );
798 //
799 //            hts.flatMap(ht -> Stream.of(VarHandleTemplate.class.getMethods()).
800 //                    map(m -> generateMethodType(m, ht.receiver, ht.value, ht.intermediates))).
801 //                    distinct().
802 //                    map(GuardMethodGenerator::generateMethod).
803 //                    forEach(System.out::println);
804 //
805 //            System.out.println("}");
806 //        }
807 //
808 //        static MethodType generateMethodType(Method m, Class<?> receiver, Class<?> value, Class<?>... intermediates) {
809 //            Class<?> returnType = m.getReturnType() == Object.class
810 //                                  ? value : m.getReturnType();
811 //
812 //            List<Class<?>> params = new ArrayList<>();
813 //            if (receiver != null)
814 //                params.add(receiver);
815 //            for (int i = 0; i < intermediates.length; i++) {
816 //                params.add(intermediates[i]);
817 //            }
818 //            for (Parameter p : m.getParameters()) {
819 //                params.add(value);
820 //            }
821 //            return MethodType.methodType(returnType, params);
822 //        }
823 //
824 //        static String generateMethod(MethodType mt) {
825 //            Class<?> returnType = mt.returnType();
826 //
827 //            LinkedHashMap<String, Class<?>> params = new LinkedHashMap<>();
828 //            params.put("handle", VarHandle.class);
829 //            for (int i = 0; i < mt.parameterCount(); i++) {
830 //                params.put("arg" + i, mt.parameterType(i));
831 //            }
832 //            params.put("ad", VarHandle.AccessDescriptor.class);
833 //
834 //            // Generate method signature line
835 //            String RETURN = className(returnType);
836 //            String NAME = "guard";
837 //            String SIGNATURE = getSignature(mt);
838 //            String PARAMS = params.entrySet().stream().
839 //                    map(e -> className(e.getValue()) + " " + e.getKey()).
840 //                    collect(joining(", "));
841 //            String METHOD = GUARD_METHOD_SIG_TEMPLATE.
842 //                    replace("<RETURN>", RETURN).
843 //                    replace("<NAME>", NAME).
844 //                    replace("<SIGNATURE>", SIGNATURE).
845 //                    replace("<PARAMS>", PARAMS);
846 //
847 //            // Generate method
848 //            params.remove("ad");
849 //
850 //            List<String> LINK_TO_STATIC_ARGS = params.keySet().stream().
851 //                    collect(toList());
852 //            LINK_TO_STATIC_ARGS.add("handle.vform.getMemberName(ad.mode)");
853 //            List<String> LINK_TO_STATIC_ARGS_V = params.keySet().stream().
854 //                    collect(toList());
855 //            LINK_TO_STATIC_ARGS_V.add("handle.vform.getMemberName_V(ad.mode)");
856 //
857 //            List<String> LINK_TO_INVOKER_ARGS = params.keySet().stream().
858 //                    collect(toList());
859 //            LINK_TO_INVOKER_ARGS.set(0, LINK_TO_INVOKER_ARGS.get(0) + ".asDirect()");
860 //
861 //            RETURN = returnType == void.class
862 //                     ? ""
863 //                     : returnType == Object.class
864 //                       ? "return "
865 //                       : "return (" + returnType.getName() + ") ";
866 //
867 //            String RESULT_ERASED = returnType == void.class
868 //                                   ? ""
869 //                                   : returnType != Object.class
870 //                                     ? "return (" + returnType.getName() + ") "
871 //                                     : "Object r = ";
872 //
873 //            String RETURN_ERASED = returnType != Object.class
874 //                                   ? ""
875 //                                   : "\n        return ad.returnType.cast(r);";
876 //
877 //            String template = returnType == void.class
878 //                              ? GUARD_METHOD_TEMPLATE_V
879 //                              : GUARD_METHOD_TEMPLATE;
880 //            return template.
881 //                    replace("<METHOD>", METHOD).
882 //                    replace("<NAME>", NAME).
883 //                    replaceAll("<RETURN>", RETURN).
884 //                    replace("<RESULT_ERASED>", RESULT_ERASED).
885 //                    replace("<RETURN_ERASED>", RETURN_ERASED).
886 //                    replaceAll("<LINK_TO_STATIC_ARGS>", LINK_TO_STATIC_ARGS.stream().
887 //                            collect(joining(", "))).
888 //                    replaceAll("<LINK_TO_STATIC_ARGS_V>", LINK_TO_STATIC_ARGS_V.stream().
889 //                            collect(joining(", "))).
890 //                    replace("<LINK_TO_INVOKER_ARGS>", LINK_TO_INVOKER_ARGS.stream().
891 //                            collect(joining(", ")))
892 //                    .indent(4);
893 //        }
894 //
895 //        static String className(Class<?> c) {
896 //            String n = c.getName();
897 //            if (n.startsWith("java.lang.")) {
898 //                n = n.replace("java.lang.", "");
899 //                if (n.startsWith("invoke.")) {
900 //                    n = n.replace("invoke.", "");
901 //                }
902 //            }
903 //            return n.replace('$', '.');
904 //        }
905 //
906 //        static String getSignature(MethodType m) {
907 //            StringBuilder sb = new StringBuilder(m.parameterCount() + 1);
908 //
909 //            for (int i = 0; i < m.parameterCount(); i++) {
910 //                Class<?> pt = m.parameterType(i);
911 //                sb.append(getCharType(pt));
912 //            }
913 //
914 //            sb.append('_').append(getCharType(m.returnType()));
915 //
916 //            return sb.toString();
917 //        }
918 //
919 //        static char getCharType(Class<?> pt) {
920 //            if (pt == void.class) {
921 //                return 'V';
922 //            }
923 //            else if (!pt.isPrimitive()) {
924 //                return 'L';
925 //            }
926 //            else if (pt == boolean.class) {
927 //                return 'Z';
928 //            }
929 //            else if (pt == int.class) {
930 //                return 'I';
931 //            }
932 //            else if (pt == long.class) {
933 //                return 'J';
934 //            }
935 //            else if (pt == float.class) {
936 //                return 'F';
937 //            }
938 //            else if (pt == double.class) {
939 //                return 'D';
940 //            }
941 //            else {
942 //                throw new IllegalStateException(pt.getName());
943 //            }
944 //        }
945 //    }
946 }