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