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