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         if (!componentType.isPrimitive()) {
280             // Here we always return a reference array element var handle. This is because
281             // the access semantics is determined at runtime, when an actual array object is passed
282             // to the var handle. The var handle implementation will switch to use flat access
283             // primitives if it sees a flat array.
284             return maybeAdapt(new ArrayVarHandle(arrayClass));
285         }
286         else if (componentType == boolean.class) {
287             return maybeAdapt(VarHandleBooleans.Array.NON_EXACT_INSTANCE);
288         }
289         else if (componentType == byte.class) {
290             return maybeAdapt(VarHandleBytes.Array.NON_EXACT_INSTANCE);
291         }
292         else if (componentType == short.class) {
293             return maybeAdapt(VarHandleShorts.Array.NON_EXACT_INSTANCE);
294         }
295         else if (componentType == char.class) {
296             return maybeAdapt(VarHandleChars.Array.NON_EXACT_INSTANCE);
297         }
298         else if (componentType == int.class) {
299             return maybeAdapt(VarHandleInts.Array.NON_EXACT_INSTANCE);
300         }
301         else if (componentType == long.class) {
302             return maybeAdapt(VarHandleLongs.Array.NON_EXACT_INSTANCE);
303         }
304         else if (componentType == float.class) {
305             return maybeAdapt(VarHandleFloats.Array.NON_EXACT_INSTANCE);
306         }
307         else if (componentType == double.class) {
308             return maybeAdapt(VarHandleDoubles.Array.NON_EXACT_INSTANCE);
309         }
310         else {
311             throw new UnsupportedOperationException();
312         }
313     }
314 
315     static VarHandle byteArrayViewHandle(Class<?> viewArrayClass,
316                                          boolean be) {
317         if (!viewArrayClass.isArray())
318             throw new IllegalArgumentException("not an array: " + viewArrayClass);
319 
320         Class<?> viewComponentType = viewArrayClass.getComponentType();
321 
322         if (viewComponentType == long.class) {
323             return maybeAdapt(new VarHandleByteArrayAsLongs.ArrayHandle(be));
324         }
325         else if (viewComponentType == int.class) {
326             return maybeAdapt(new VarHandleByteArrayAsInts.ArrayHandle(be));
327         }
328         else if (viewComponentType == short.class) {
329             return maybeAdapt(new VarHandleByteArrayAsShorts.ArrayHandle(be));
330         }
331         else if (viewComponentType == char.class) {
332             return maybeAdapt(new VarHandleByteArrayAsChars.ArrayHandle(be));
333         }
334         else if (viewComponentType == double.class) {
335             return maybeAdapt(new VarHandleByteArrayAsDoubles.ArrayHandle(be));
336         }
337         else if (viewComponentType == float.class) {
338             return maybeAdapt(new VarHandleByteArrayAsFloats.ArrayHandle(be));
339         }
340 
341         throw new UnsupportedOperationException();
342     }
343 
344     static VarHandle makeByteBufferViewHandle(Class<?> viewArrayClass,
345                                               boolean be) {
346         if (!viewArrayClass.isArray())
347             throw new IllegalArgumentException("not an array: " + viewArrayClass);
348 
349         Class<?> viewComponentType = viewArrayClass.getComponentType();
350 
351         if (viewComponentType == long.class) {
352             return maybeAdapt(new VarHandleByteArrayAsLongs.ByteBufferHandle(be));
353         }
354         else if (viewComponentType == int.class) {
355             return maybeAdapt(new VarHandleByteArrayAsInts.ByteBufferHandle(be));
356         }
357         else if (viewComponentType == short.class) {
358             return maybeAdapt(new VarHandleByteArrayAsShorts.ByteBufferHandle(be));
359         }
360         else if (viewComponentType == char.class) {
361             return maybeAdapt(new VarHandleByteArrayAsChars.ByteBufferHandle(be));
362         }
363         else if (viewComponentType == double.class) {
364             return maybeAdapt(new VarHandleByteArrayAsDoubles.ByteBufferHandle(be));
365         }
366         else if (viewComponentType == float.class) {
367             return maybeAdapt(new VarHandleByteArrayAsFloats.ByteBufferHandle(be));
368         }
369 
370         throw new UnsupportedOperationException();
371     }
372 
373     /**
374      * Creates a memory segment view var handle accessing a {@code carrier} element. It has access coordinates
375      * {@code (MS, long)} if {@code constantOffset}, {@code (MS, long, (validated) long)} otherwise.
376      * <p>
377      * The resulting var handle will take a memory segment as first argument (the segment to be dereferenced),
378      * and a {@code long} as second argument (the offset into the segment). Both arguments are checked.
379      * <p>
380      * If {@code constantOffset == false}, the resulting var handle will take a third pre-validated additional
381      * offset instead of the given fixed {@code offset}, and caller must ensure that passed additional offset,
382      * either to the handle (such as computing through method handles) or as fixed {@code offset} here, is valid.
383      *
384      * @param carrier the Java carrier type of the element
385      * @param enclosing the enclosing layout to perform bound and alignment checks against
386      * @param alignmentMask alignment of this accessed element in the enclosing layout
387      * @param constantOffset if access path has a constant offset value, i.e. it has no strides
388      * @param offset the offset value, if the offset is constant
389      * @param byteOrder the byte order
390      * @return the created var handle
391      */
392     static VarHandle memorySegmentViewHandle(Class<?> carrier, MemoryLayout enclosing, long alignmentMask,
393                                              boolean constantOffset, long offset, ByteOrder byteOrder) {
394         if (!carrier.isPrimitive() || carrier == void.class) {
395             throw new IllegalArgumentException("Invalid carrier: " + carrier.getName());
396         }
397         boolean be = byteOrder == ByteOrder.BIG_ENDIAN;
398         boolean exact = VAR_HANDLE_SEGMENT_FORCE_EXACT;
399 
400         // All carrier types must persist across MethodType erasure
401         VarForm form;
402         if (carrier == byte.class) {
403             form = VarHandleSegmentAsBytes.selectForm(alignmentMask, constantOffset);
404         } else if (carrier == char.class) {
405             form = VarHandleSegmentAsChars.selectForm(alignmentMask, constantOffset);
406         } else if (carrier == short.class) {
407             form = VarHandleSegmentAsShorts.selectForm(alignmentMask, constantOffset);
408         } else if (carrier == int.class) {
409             form = VarHandleSegmentAsInts.selectForm(alignmentMask, constantOffset);
410         } else if (carrier == float.class) {
411             form = VarHandleSegmentAsFloats.selectForm(alignmentMask, constantOffset);
412         } else if (carrier == long.class) {
413             form = VarHandleSegmentAsLongs.selectForm(alignmentMask, constantOffset);
414         } else if (carrier == double.class) {
415             form = VarHandleSegmentAsDoubles.selectForm(alignmentMask, constantOffset);
416         } else if (carrier == boolean.class) {
417             form = VarHandleSegmentAsBooleans.selectForm(alignmentMask, constantOffset);
418         } else {
419             throw new IllegalStateException("Cannot get here");
420         }
421 
422         return maybeAdapt(new SegmentVarHandle(form, be, enclosing, offset, exact));
423     }
424 
425     private static VarHandle maybeAdapt(VarHandle target) {
426         if (!VAR_HANDLE_IDENTITY_ADAPT) return target;
427         target = filterValue(target,
428                         MethodHandles.identity(target.varType()), MethodHandles.identity(target.varType()));
429         MethodType mtype = target.accessModeType(VarHandle.AccessMode.GET);
430         for (int i = 0 ; i < mtype.parameterCount() ; i++) {
431             target = filterCoordinates(target, i, MethodHandles.identity(mtype.parameterType(i)));
432         }
433         return target;
434     }
435 
436     public static VarHandle filterValue(VarHandle target, MethodHandle pFilterToTarget, MethodHandle pFilterFromTarget) {
437         Objects.requireNonNull(target);
438         Objects.requireNonNull(pFilterToTarget);
439         Objects.requireNonNull(pFilterFromTarget);
440         //check that from/to filters do not throw checked exceptions
441         MethodHandle filterToTarget = adaptForCheckedExceptions(pFilterToTarget);
442         MethodHandle filterFromTarget = adaptForCheckedExceptions(pFilterFromTarget);
443 
444         List<Class<?>> newCoordinates = new ArrayList<>();
445         List<Class<?>> additionalCoordinates = new ArrayList<>();
446         newCoordinates.addAll(target.coordinateTypes());
447 
448         //check that from/to filters have right signatures
449         if (filterFromTarget.type().parameterCount() != filterToTarget.type().parameterCount()) {
450             throw newIllegalArgumentException("filterFromTarget and filterToTarget have different arity", filterFromTarget.type(), filterToTarget.type());
451         } else if (filterFromTarget.type().parameterCount() < 1) {
452             throw newIllegalArgumentException("filterFromTarget filter type has wrong arity", filterFromTarget.type());
453         } else if (filterToTarget.type().parameterCount() < 1) {
454             throw newIllegalArgumentException("filterToTarget filter type has wrong arity", filterFromTarget.type());
455         } else if (filterFromTarget.type().lastParameterType() != filterToTarget.type().returnType() ||
456                 filterToTarget.type().lastParameterType() != filterFromTarget.type().returnType()) {
457             throw newIllegalArgumentException("filterFromTarget and filterToTarget filter types do not match", filterFromTarget.type(), filterToTarget.type());
458         } else if (target.varType() != filterFromTarget.type().lastParameterType()) {
459             throw newIllegalArgumentException("filterFromTarget filter type does not match target var handle type", filterFromTarget.type(), target.varType());
460         } else if (target.varType() != filterToTarget.type().returnType()) {
461             throw newIllegalArgumentException("filterFromTarget filter type does not match target var handle type", filterToTarget.type(), target.varType());
462         } else if (filterFromTarget.type().parameterCount() > 1) {
463             for (int i = 0 ; i < filterFromTarget.type().parameterCount() - 1 ; i++) {
464                 if (filterFromTarget.type().parameterType(i) != filterToTarget.type().parameterType(i)) {
465                     throw newIllegalArgumentException("filterFromTarget and filterToTarget filter types do not match", filterFromTarget.type(), filterToTarget.type());
466                 } else {
467                     newCoordinates.add(filterFromTarget.type().parameterType(i));
468                     additionalCoordinates.add((filterFromTarget.type().parameterType(i)));
469                 }
470             }
471         }
472 
473         return new IndirectVarHandle(target, filterFromTarget.type().returnType(), newCoordinates.toArray(new Class<?>[0]),
474                 (mode, modeHandle) -> {
475                     int lastParameterPos = modeHandle.type().parameterCount() - 1;
476                     return switch (mode.at) {
477                         case GET -> MethodHandles.collectReturnValue(modeHandle, filterFromTarget);
478                         case SET -> MethodHandles.collectArguments(modeHandle, lastParameterPos, filterToTarget);
479                         case GET_AND_UPDATE -> {
480                             MethodHandle adapter = MethodHandles.collectReturnValue(modeHandle, filterFromTarget);
481                             MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos, filterToTarget);
482                             if (additionalCoordinates.size() > 0) {
483                                 res = joinDuplicateArgs(res, lastParameterPos,
484                                         lastParameterPos + additionalCoordinates.size() + 1,
485                                         additionalCoordinates.size());
486                             }
487                             yield res;
488                         }
489                         case COMPARE_AND_EXCHANGE -> {
490                             MethodHandle adapter = MethodHandles.collectReturnValue(modeHandle, filterFromTarget);
491                             adapter = MethodHandles.collectArguments(adapter, lastParameterPos, filterToTarget);
492                             if (additionalCoordinates.size() > 0) {
493                                 adapter = joinDuplicateArgs(adapter, lastParameterPos,
494                                         lastParameterPos + additionalCoordinates.size() + 1,
495                                         additionalCoordinates.size());
496                             }
497                             MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos - 1, filterToTarget);
498                             if (additionalCoordinates.size() > 0) {
499                                 res = joinDuplicateArgs(res, lastParameterPos - 1,
500                                         lastParameterPos + additionalCoordinates.size(),
501                                         additionalCoordinates.size());
502                             }
503                             yield res;
504                         }
505                         case COMPARE_AND_SET -> {
506                             MethodHandle adapter = MethodHandles.collectArguments(modeHandle, lastParameterPos, filterToTarget);
507                             MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos - 1, filterToTarget);
508                             if (additionalCoordinates.size() > 0) {
509                                 res = joinDuplicateArgs(res, lastParameterPos - 1,
510                                         lastParameterPos + additionalCoordinates.size(),
511                                         additionalCoordinates.size());
512                             }
513                             yield res;
514                         }
515                     };
516                 });
517     }
518 
519     private static MethodHandle joinDuplicateArgs(MethodHandle handle, int originalStart, int dropStart, int length) {
520         int[] perms = new int[handle.type().parameterCount()];
521         for (int i = 0 ; i < dropStart; i++) {
522             perms[i] = i;
523         }
524         for (int i = 0 ; i < length ; i++) {
525             perms[dropStart + i] = originalStart + i;
526         }
527         for (int i = dropStart + length ; i < perms.length ; i++) {
528             perms[i] = i - length;
529         }
530         return MethodHandles.permuteArguments(handle,
531                 handle.type().dropParameterTypes(dropStart, dropStart + length),
532                 perms);
533     }
534 
535     public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
536         Objects.requireNonNull(target);
537         Objects.requireNonNull(filters);
538 
539         List<Class<?>> targetCoordinates = target.coordinateTypes();
540         if (pos < 0 || pos >= targetCoordinates.size()) {
541             throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
542         } else if (pos + filters.length > targetCoordinates.size()) {
543             throw new IllegalArgumentException("Too many filters");
544         }
545 
546         if (filters.length == 0) return target;
547 
548         List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
549         for (int i = 0 ; i < filters.length ; i++) {
550             MethodHandle filter = Objects.requireNonNull(filters[i]);
551             filter = adaptForCheckedExceptions(filter);
552             MethodType filterType = filter.type();
553             if (filterType.parameterCount() != 1) {
554                 throw newIllegalArgumentException("Invalid filter type " + filterType);
555             } else if (newCoordinates.get(pos + i) != filterType.returnType()) {
556                 throw newIllegalArgumentException("Invalid filter type " + filterType + " for coordinate type " + newCoordinates.get(i));
557             }
558             newCoordinates.set(pos + i, filters[i].type().parameterType(0));
559         }
560 
561         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
562                 (mode, modeHandle) -> MethodHandles.filterArguments(modeHandle, 1 + pos, filters));
563     }
564 
565     public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
566         Objects.requireNonNull(target);
567         Objects.requireNonNull(values);
568 
569         List<Class<?>> targetCoordinates = target.coordinateTypes();
570         if (pos < 0 || pos >= targetCoordinates.size()) {
571             throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
572         } else if (pos + values.length > targetCoordinates.size()) {
573             throw new IllegalArgumentException("Too many values");
574         }
575 
576         if (values.length == 0) return target;
577 
578         List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
579         for (int i = 0 ; i < values.length ; i++) {
580             Class<?> pt = newCoordinates.get(pos);
581             if (pt.isPrimitive()) {
582                 Wrapper w = Wrapper.forPrimitiveType(pt);
583                 w.convert(values[i], pt);
584             } else {
585                 pt.cast(values[i]);
586             }
587             newCoordinates.remove(pos);
588         }
589 
590         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
591                 (mode, modeHandle) -> MethodHandles.insertArguments(modeHandle, 1 + pos, values));
592     }
593 
594     public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) {
595         Objects.requireNonNull(target);
596         Objects.requireNonNull(newCoordinates);
597         Objects.requireNonNull(reorder);
598 
599         List<Class<?>> targetCoordinates = target.coordinateTypes();
600         MethodHandles.permuteArgumentChecks(reorder,
601                 MethodType.methodType(void.class, newCoordinates),
602                 MethodType.methodType(void.class, targetCoordinates));
603 
604         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
605                 (mode, modeHandle) ->
606                         MethodHandles.permuteArguments(modeHandle,
607                                 methodTypeFor(mode.at, modeHandle.type(), targetCoordinates, newCoordinates),
608                                 reorderArrayFor(mode.at, newCoordinates, reorder)));
609     }
610 
611     private static int numTrailingArgs(VarHandle.AccessType at) {
612         return switch (at) {
613             case GET -> 0;
614             case GET_AND_UPDATE, SET -> 1;
615             case COMPARE_AND_SET, COMPARE_AND_EXCHANGE -> 2;
616         };
617     }
618 
619     private static int[] reorderArrayFor(VarHandle.AccessType at, List<Class<?>> newCoordinates, int[] reorder) {
620         int numTrailingArgs = numTrailingArgs(at);
621         int[] adjustedReorder = new int[reorder.length + 1 + numTrailingArgs];
622         adjustedReorder[0] = 0;
623         for (int i = 0 ; i < reorder.length ; i++) {
624             adjustedReorder[i + 1] = reorder[i] + 1;
625         }
626         for (int i = 0 ; i < numTrailingArgs ; i++) {
627             adjustedReorder[i + reorder.length + 1] = i + newCoordinates.size() + 1;
628         }
629         return adjustedReorder;
630     }
631 
632     private static MethodType methodTypeFor(VarHandle.AccessType at, MethodType oldType, List<Class<?>> oldCoordinates, List<Class<?>> newCoordinates) {
633         int numTrailingArgs = numTrailingArgs(at);
634         MethodType adjustedType = MethodType.methodType(oldType.returnType(), oldType.parameterType(0));
635         adjustedType = adjustedType.appendParameterTypes(newCoordinates);
636         for (int i = 0 ; i < numTrailingArgs ; i++) {
637             adjustedType = adjustedType.appendParameterTypes(oldType.parameterType(1 + oldCoordinates.size() + i));
638         }
639         return adjustedType;
640     }
641 
642     public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle pFilter) {
643         Objects.requireNonNull(target);
644         Objects.requireNonNull(pFilter);
645         MethodHandle filter = adaptForCheckedExceptions(pFilter);
646 
647         List<Class<?>> targetCoordinates = target.coordinateTypes();
648         if (pos < 0 || pos >= targetCoordinates.size()) {
649             throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
650         } else if (filter.type().returnType() != void.class && filter.type().returnType() != targetCoordinates.get(pos)) {
651             throw newIllegalArgumentException("Invalid filter type " + filter.type() + " for coordinate type " + targetCoordinates.get(pos));
652         }
653 
654         List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
655         if (filter.type().returnType() != void.class) {
656             newCoordinates.remove(pos);
657         }
658         newCoordinates.addAll(pos, filter.type().parameterList());
659 
660         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
661                 (mode, modeHandle) -> MethodHandles.collectArguments(modeHandle, 1 + pos, filter));
662     }
663 
664     public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
665         Objects.requireNonNull(target);
666         Objects.requireNonNull(valueTypes);
667 
668         List<Class<?>> targetCoordinates = target.coordinateTypes();
669         if (pos < 0 || pos > targetCoordinates.size()) {
670             throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
671         }
672 
673         if (valueTypes.length == 0) return target;
674 
675         List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
676         newCoordinates.addAll(pos, List.of(valueTypes));
677 
678         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
679                 (mode, modeHandle) -> MethodHandles.dropArguments(modeHandle, 1 + pos, valueTypes));
680     }
681 
682     private static MethodHandle adaptForCheckedExceptions(MethodHandle target) {
683         Class<?>[] exceptionTypes = exceptionTypes(target);
684         if (exceptionTypes != null) { // exceptions known
685             if (Stream.of(exceptionTypes).anyMatch(VarHandles::isCheckedException)) {
686                 throw newIllegalArgumentException("Cannot adapt a var handle with a method handle which throws checked exceptions");
687             }
688             return target; // no adaptation needed
689         } else {
690             MethodHandle handler = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_VarHandles_handleCheckedExceptions);
691             MethodHandle zero = MethodHandles.zero(target.type().returnType()); // dead branch
692             handler = MethodHandles.collectArguments(zero, 0, handler);
693             return MethodHandles.catchException(target, Throwable.class, handler);
694         }
695     }
696 
697     static void handleCheckedExceptions(Throwable throwable) throws Throwable {
698         if (isCheckedException(throwable.getClass())) {
699             throw new IllegalStateException("Adapter handle threw checked exception", throwable);
700         }
701         throw throwable;
702     }
703 
704     static Class<?>[] exceptionTypes(MethodHandle handle) {
705         if (handle instanceof DirectMethodHandle directHandle) {
706             byte refKind = directHandle.member.getReferenceKind();
707             MethodHandleInfo info = new InfoFromMemberName(
708                     MethodHandles.Lookup.IMPL_LOOKUP,
709                     directHandle.member,
710                     refKind);
711             if (MethodHandleNatives.refKindIsMethod(refKind)) {
712                 return info.reflectAs(Method.class, MethodHandles.Lookup.IMPL_LOOKUP)
713                         .getExceptionTypes();
714             } else if (MethodHandleNatives.refKindIsField(refKind)) {
715                 return new Class<?>[0];
716             } else if (MethodHandleNatives.refKindIsConstructor(refKind)) {
717                 return info.reflectAs(Constructor.class, MethodHandles.Lookup.IMPL_LOOKUP)
718                         .getExceptionTypes();
719             } else {
720                 throw new AssertionError("Cannot get here");
721             }
722         } else if (handle instanceof DelegatingMethodHandle delegatingMh) {
723             return exceptionTypes(delegatingMh.getTarget());
724         } else if (handle instanceof NativeMethodHandle) {
725             return new Class<?>[0];
726         }
727 
728         assert handle instanceof BoundMethodHandle : "Unexpected handle type: " + handle;
729         // unknown
730         return null;
731     }
732 
733     private static boolean isCheckedException(Class<?> clazz) {
734         return Throwable.class.isAssignableFrom(clazz) &&
735                 !RuntimeException.class.isAssignableFrom(clazz) &&
736                 !Error.class.isAssignableFrom(clazz);
737     }
738 
739 //    /**
740 //     * A helper program to generate the VarHandleGuards class with a set of
741 //     * static guard methods each of which corresponds to a particular shape and
742 //     * performs a type check of the symbolic type descriptor with the VarHandle
743 //     * type descriptor before linking/invoking to the underlying operation as
744 //     * characterized by the operation member name on the VarForm of the
745 //     * VarHandle.
746 //     * <p>
747 //     * The generated class essentially encapsulates pre-compiled LambdaForms,
748 //     * one for each method, for the most set of common method signatures.
749 //     * This reduces static initialization costs, footprint costs, and circular
750 //     * dependencies that may arise if a class is generated per LambdaForm.
751 //     * <p>
752 //     * A maximum of L*T*S methods will be generated where L is the number of
753 //     * access modes kinds (or unique operation signatures) and T is the number
754 //     * of variable types and S is the number of shapes (such as instance field,
755 //     * static field, or array access).
756 //     * If there are 4 unique operation signatures, 5 basic types (Object, int,
757 //     * long, float, double), and 3 shapes then a maximum of 60 methods will be
758 //     * generated.  However, the number is likely to be less since there
759 //     * be duplicate signatures.
760 //     * <p>
761 //     * Each method is annotated with @LambdaForm.Compiled to inform the runtime
762 //     * that such methods should be treated as if a method of a class that is the
763 //     * result of compiling a LambdaForm.  Annotation of such methods is
764 //     * important for correct evaluation of certain assertions and method return
765 //     * type profiling in HotSpot.
766 //     */
767 //    public static class GuardMethodGenerator {
768 //
769 //        static final String GUARD_METHOD_SIG_TEMPLATE = "<RETURN> <NAME>_<SIGNATURE>(<PARAMS>)";
770 //
771 //        static final String GUARD_METHOD_TEMPLATE =
772 //                """
773 //                @ForceInline
774 //                @LambdaForm.Compiled
775 //                @Hidden
776 //                static final <METHOD> throws Throwable {
777 //                    boolean direct = handle.checkAccessModeThenIsDirect(ad);
778 //                    if (direct && handle.vform.methodType_table[ad.type] == ad.symbolicMethodTypeErased) {
779 //                        <RESULT_ERASED>MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);<RETURN_ERASED>
780 //                    } else {
781 //                        MethodHandle mh = handle.getMethodHandle(ad.mode);
782 //                        <RETURN>mh.asType(ad.symbolicMethodTypeInvoker).invokeBasic(<LINK_TO_INVOKER_ARGS>);
783 //                    }
784 //                }""";
785 //
786 //        static final String GUARD_METHOD_TEMPLATE_V =
787 //                """
788 //                @ForceInline
789 //                @LambdaForm.Compiled
790 //                @Hidden
791 //                static final <METHOD> throws Throwable {
792 //                    boolean direct = handle.checkAccessModeThenIsDirect(ad);
793 //                    if (direct && handle.vform.methodType_table[ad.type] == ad.symbolicMethodTypeErased) {
794 //                        MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);
795 //                    } else if (direct && handle.vform.getMethodType_V(ad.type) == ad.symbolicMethodTypeErased) {
796 //                        MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);
797 //                    } else {
798 //                        MethodHandle mh = handle.getMethodHandle(ad.mode);
799 //                        mh.asType(ad.symbolicMethodTypeInvoker).invokeBasic(<LINK_TO_INVOKER_ARGS>);
800 //                    }
801 //                }""";
802 //
803 //        // A template for deriving the operations
804 //        // could be supported by annotating VarHandle directly with the
805 //        // operation kind and shape
806 //        interface VarHandleTemplate {
807 //            Object get();
808 //
809 //            void set(Object value);
810 //
811 //            boolean compareAndSet(Object actualValue, Object expectedValue);
812 //
813 //            Object compareAndExchange(Object actualValue, Object expectedValue);
814 //
815 //            Object getAndUpdate(Object value);
816 //        }
817 //
818 //        record HandleType(Class<?> receiver, Class<?>... intermediates) {
819 //        }
820 //
821 //        /**
822 //         * @param args parameters
823 //         */
824 //        public static void main(String[] args) {
825 //            System.out.println("package java.lang.invoke;");
826 //            System.out.println();
827 //            System.out.println("import jdk.internal.vm.annotation.ForceInline;");
828 //            System.out.println("import jdk.internal.vm.annotation.Hidden;");
829 //            System.out.println();
830 //            System.out.println("// This class is auto-generated by " +
831 //                               GuardMethodGenerator.class.getName() +
832 //                               ". Do not edit.");
833 //            System.out.println("final class VarHandleGuards {");
834 //
835 //            System.out.println();
836 //
837 //            // Declare the stream of shapes
838 //            List<HandleType> hts = List.of(
839 //                    // Object->T
840 //                    new HandleType(Object.class),
841 //
842 //                    // <static>->T
843 //                    new HandleType(null),
844 //
845 //                    // Array[index]->T
846 //                    new HandleType(Object.class, int.class),
847 //
848 //                    // MS[base]->T
849 //                    new HandleType(Object.class, long.class),
850 //
851 //                    // MS[base][offset]->T
852 //                    new HandleType(Object.class, long.class, long.class)
853 //            );
854 //
855 //            Stream.of(VarHandleTemplate.class.getMethods()).<MethodType>
856 //                    mapMulti((m, sink) -> {
857 //                        for (var ht : hts) {
858 //                            for (var bt : LambdaForm.BasicType.ARG_TYPES) {
859 //                                sink.accept(generateMethodType(m, ht.receiver, bt.btClass, ht.intermediates));
860 //                            }
861 //                        }
862 //                    }).
863 //                    distinct().
864 //                    map(GuardMethodGenerator::generateMethod).
865 //                    forEach(System.out::println);
866 //
867 //            System.out.println("}");
868 //        }
869 //
870 //        static MethodType generateMethodType(Method m, Class<?> receiver, Class<?> value, Class<?>... intermediates) {
871 //            Class<?> returnType = m.getReturnType() == Object.class
872 //                                  ? value : m.getReturnType();
873 //
874 //            List<Class<?>> params = new ArrayList<>();
875 //            if (receiver != null)
876 //                params.add(receiver);
877 //            java.util.Collections.addAll(params, intermediates);
878 //            for (var p : m.getParameters()) {
879 //                params.add(value);
880 //            }
881 //            return MethodType.methodType(returnType, params);
882 //        }
883 //
884 //        static String generateMethod(MethodType mt) {
885 //            Class<?> returnType = mt.returnType();
886 //
887 //            var params = new java.util.LinkedHashMap<String, Class<?>>();
888 //            params.put("handle", VarHandle.class);
889 //            for (int i = 0; i < mt.parameterCount(); i++) {
890 //                params.put("arg" + i, mt.parameterType(i));
891 //            }
892 //            params.put("ad", VarHandle.AccessDescriptor.class);
893 //
894 //            // Generate method signature line
895 //            String RETURN = className(returnType);
896 //            String NAME = "guard";
897 //            String SIGNATURE = getSignature(mt);
898 //            String PARAMS = params.entrySet().stream().
899 //                    map(e -> className(e.getValue()) + " " + e.getKey()).
900 //                    collect(java.util.stream.Collectors.joining(", "));
901 //            String METHOD = GUARD_METHOD_SIG_TEMPLATE.
902 //                    replace("<RETURN>", RETURN).
903 //                    replace("<NAME>", NAME).
904 //                    replace("<SIGNATURE>", SIGNATURE).
905 //                    replace("<PARAMS>", PARAMS);
906 //
907 //            // Generate method
908 //            params.remove("ad");
909 //
910 //            List<String> LINK_TO_STATIC_ARGS = new ArrayList<>(params.keySet());
911 //            LINK_TO_STATIC_ARGS.add("handle.vform.getMemberName(ad.mode)");
912 //
913 //            List<String> LINK_TO_INVOKER_ARGS = new ArrayList<>(params.keySet());
914 //            LINK_TO_INVOKER_ARGS.set(0, LINK_TO_INVOKER_ARGS.get(0) + ".asDirect()");
915 //
916 //            RETURN = returnType == void.class
917 //                     ? ""
918 //                     : returnType == Object.class
919 //                       ? "return "
920 //                       : "return (" + returnType.getName() + ") ";
921 //
922 //            String RESULT_ERASED = returnType == void.class
923 //                                   ? ""
924 //                                   : returnType != Object.class
925 //                                     ? "return (" + returnType.getName() + ") "
926 //                                     : "Object r = ";
927 //
928 //            String RETURN_ERASED = returnType != Object.class
929 //                                   ? ""
930 //                                   : "\n        return ad.returnType.cast(r);";
931 //
932 //            String template = returnType == void.class
933 //                              ? GUARD_METHOD_TEMPLATE_V
934 //                              : GUARD_METHOD_TEMPLATE;
935 //            return template.
936 //                    replace("<METHOD>", METHOD).
937 //                    replace("<NAME>", NAME).
938 //                    replaceAll("<RETURN>", RETURN).
939 //                    replace("<RESULT_ERASED>", RESULT_ERASED).
940 //                    replace("<RETURN_ERASED>", RETURN_ERASED).
941 //                    replaceAll("<LINK_TO_STATIC_ARGS>", String.join(", ", LINK_TO_STATIC_ARGS)).
942 //                    replace("<LINK_TO_INVOKER_ARGS>", String.join(", ", LINK_TO_INVOKER_ARGS))
943 //                    .indent(4);
944 //        }
945 //
946 //        static String className(Class<?> c) {
947 //            String n = c.getName();
948 //            if (n.startsWith("java.lang.")) {
949 //                n = n.replace("java.lang.", "");
950 //                if (n.startsWith("invoke.")) {
951 //                    n = n.replace("invoke.", "");
952 //                }
953 //            }
954 //            return n.replace('$', '.');
955 //        }
956 //
957 //        static String getSignature(MethodType m) {
958 //            StringBuilder sb = new StringBuilder(m.parameterCount() + 1);
959 //
960 //            for (int i = 0; i < m.parameterCount(); i++) {
961 //                Class<?> pt = m.parameterType(i);
962 //                sb.append(getCharType(pt));
963 //            }
964 //
965 //            sb.append('_').append(getCharType(m.returnType()));
966 //
967 //            return sb.toString();
968 //        }
969 //
970 //        static char getCharType(Class<?> pt) {
971 //            return Wrapper.forBasicType(pt).basicTypeChar();
972 //        }
973 //    }
974 }