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