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