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