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