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