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