< prev index next >

src/java.base/share/classes/java/lang/invoke/VarHandles.java

Print this page

 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.lang.invoke;
 27 
 28 import sun.invoke.util.Wrapper;
 29 
 30 import java.lang.reflect.Constructor;
 31 import java.lang.reflect.Field;
 32 import java.lang.reflect.Method;
 33 import java.lang.reflect.Modifier;
 34 import java.lang.reflect.Parameter;
 35 import java.nio.ByteOrder;
 36 import java.util.ArrayList;
 37 import java.util.LinkedHashMap;
 38 import java.util.List;
 39 import java.util.Map;
 40 import java.util.Objects;
 41 import java.util.concurrent.ConcurrentHashMap;
 42 import java.util.concurrent.ConcurrentMap;
 43 import java.util.stream.Stream;
 44 
 45 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
 46 import static java.lang.invoke.MethodHandleStatics.VAR_HANDLE_IDENTITY_ADAPT;
 47 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
 48 import static java.util.stream.Collectors.joining;
 49 import static java.util.stream.Collectors.toList;
 50 
 51 final class VarHandles {
 52 
 53     static ClassValue<ConcurrentMap<Integer, MethodHandle>> ADDRESS_FACTORIES = new ClassValue<>() {
 54         @Override
 55         protected ConcurrentMap<Integer, MethodHandle> computeValue(Class<?> type) {
 56             return new ConcurrentHashMap<>();
 57         }
 58     };
 59 
 60     static VarHandle makeFieldHandle(MemberName f, Class<?> refc, Class<?> type, boolean isWriteAllowedOnFinalFields) {
 61         if (!f.isStatic()) {
 62             long foffset = MethodHandleNatives.objectFieldOffset(f);
 63             if (!type.isPrimitive()) {
 64                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 65                        ? new VarHandleReferences.FieldInstanceReadOnly(refc, foffset, type)
 66                        : new VarHandleReferences.FieldInstanceReadWrite(refc, foffset, type));
 67             }
 68             else if (type == boolean.class) {
 69                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields

342         } else if (carrier == long.class) {
343             return maybeAdapt(new MemoryAccessVarHandleLongHelper(skipAlignmentMaskCheck, be, size, alignmentMask, exact));
344         } else if (carrier == double.class) {
345             return maybeAdapt(new MemoryAccessVarHandleDoubleHelper(skipAlignmentMaskCheck, be, size, alignmentMask, exact));
346         } else {
347             throw new IllegalStateException("Cannot get here");
348         }
349     }
350 
351     private static VarHandle maybeAdapt(VarHandle target) {
352         if (!VAR_HANDLE_IDENTITY_ADAPT) return target;
353         target = filterValue(target,
354                         MethodHandles.identity(target.varType()), MethodHandles.identity(target.varType()));
355         MethodType mtype = target.accessModeType(VarHandle.AccessMode.GET);
356         for (int i = 0 ; i < mtype.parameterCount() ; i++) {
357             target = filterCoordinates(target, i, MethodHandles.identity(mtype.parameterType(i)));
358         }
359         return target;
360     }
361 
362     public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) {
363         Objects.requireNonNull(target);
364         Objects.requireNonNull(filterToTarget);
365         Objects.requireNonNull(filterFromTarget);
366         //check that from/to filters do not throw checked exceptions
367         noCheckedExceptions(filterToTarget);
368         noCheckedExceptions(filterFromTarget);
369 
370         List<Class<?>> newCoordinates = new ArrayList<>();
371         List<Class<?>> additionalCoordinates = new ArrayList<>();
372         newCoordinates.addAll(target.coordinateTypes());
373 
374         //check that from/to filters have right signatures
375         if (filterFromTarget.type().parameterCount() != filterToTarget.type().parameterCount()) {
376             throw newIllegalArgumentException("filterFromTarget and filterToTarget have different arity", filterFromTarget.type(), filterToTarget.type());
377         } else if (filterFromTarget.type().parameterCount() < 1) {
378             throw newIllegalArgumentException("filterFromTarget filter type has wrong arity", filterFromTarget.type());
379         } else if (filterToTarget.type().parameterCount() < 1) {
380             throw newIllegalArgumentException("filterToTarget filter type has wrong arity", filterFromTarget.type());
381         } else if (filterFromTarget.type().lastParameterType() != filterToTarget.type().returnType() ||
382                 filterToTarget.type().lastParameterType() != filterFromTarget.type().returnType()) {
383             throw newIllegalArgumentException("filterFromTarget and filterToTarget filter types do not match", filterFromTarget.type(), filterToTarget.type());
384         } else if (target.varType() != filterFromTarget.type().lastParameterType()) {
385             throw newIllegalArgumentException("filterFromTarget filter type does not match target var handle type", filterFromTarget.type(), target.varType());
386         } else if (target.varType() != filterToTarget.type().returnType()) {
387             throw newIllegalArgumentException("filterFromTarget filter type does not match target var handle type", filterToTarget.type(), target.varType());
388         } else if (filterFromTarget.type().parameterCount() > 1) {

456         return MethodHandles.permuteArguments(handle,
457                 handle.type().dropParameterTypes(dropStart, dropStart + length),
458                 perms);
459     }
460 
461     public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
462         Objects.requireNonNull(target);
463         Objects.requireNonNull(filters);
464 
465         List<Class<?>> targetCoordinates = target.coordinateTypes();
466         if (pos < 0 || pos >= targetCoordinates.size()) {
467             throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
468         } else if (pos + filters.length > targetCoordinates.size()) {
469             throw new IllegalArgumentException("Too many filters");
470         }
471 
472         if (filters.length == 0) return target;
473 
474         List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
475         for (int i = 0 ; i < filters.length ; i++) {
476             noCheckedExceptions(filters[i]);
477             MethodType filterType = filters[i].type();

478             if (filterType.parameterCount() != 1) {
479                 throw newIllegalArgumentException("Invalid filter type " + filterType);
480             } else if (newCoordinates.get(pos + i) != filterType.returnType()) {
481                 throw newIllegalArgumentException("Invalid filter type " + filterType + " for coordinate type " + newCoordinates.get(i));
482             }
483             newCoordinates.set(pos + i, filters[i].type().parameterType(0));
484         }
485 
486         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
487                 (mode, modeHandle) -> MethodHandles.filterArguments(modeHandle, 1 + pos, filters));
488     }
489 
490     public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
491         Objects.requireNonNull(target);
492         Objects.requireNonNull(values);
493 
494         List<Class<?>> targetCoordinates = target.coordinateTypes();
495         if (pos < 0 || pos >= targetCoordinates.size()) {
496             throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
497         } else if (pos + values.length > targetCoordinates.size()) {

547         adjustedReorder[0] = 0;
548         for (int i = 0 ; i < reorder.length ; i++) {
549             adjustedReorder[i + 1] = reorder[i] + 1;
550         }
551         for (int i = 0 ; i < numTrailingArgs ; i++) {
552             adjustedReorder[i + reorder.length + 1] = i + newCoordinates.size() + 1;
553         }
554         return adjustedReorder;
555     }
556 
557     private static MethodType methodTypeFor(VarHandle.AccessType at, MethodType oldType, List<Class<?>> oldCoordinates, List<Class<?>> newCoordinates) {
558         int numTrailingArgs = numTrailingArgs(at);
559         MethodType adjustedType = MethodType.methodType(oldType.returnType(), oldType.parameterType(0));
560         adjustedType = adjustedType.appendParameterTypes(newCoordinates);
561         for (int i = 0 ; i < numTrailingArgs ; i++) {
562             adjustedType = adjustedType.appendParameterTypes(oldType.parameterType(1 + oldCoordinates.size() + i));
563         }
564         return adjustedType;
565     }
566 
567     public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) {
568         Objects.requireNonNull(target);
569         Objects.requireNonNull(filter);
570         noCheckedExceptions(filter);
571 
572         List<Class<?>> targetCoordinates = target.coordinateTypes();
573         if (pos < 0 || pos >= targetCoordinates.size()) {
574             throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
575         } else if (filter.type().returnType() == void.class) {
576             throw newIllegalArgumentException("Invalid filter type " + filter.type() + " ; filter cannot be void");
577         } else if (filter.type().returnType() != targetCoordinates.get(pos)) {
578             throw newIllegalArgumentException("Invalid filter type " + filter.type() + " for coordinate type " + targetCoordinates.get(pos));
579         }
580 
581         List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
582         newCoordinates.remove(pos);
583         newCoordinates.addAll(pos, filter.type().parameterList());
584 
585         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
586                 (mode, modeHandle) -> MethodHandles.collectArguments(modeHandle, 1 + pos, filter));
587     }
588 
589     public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
590         Objects.requireNonNull(target);
591         Objects.requireNonNull(valueTypes);
592 
593         List<Class<?>> targetCoordinates = target.coordinateTypes();
594         if (pos < 0 || pos > targetCoordinates.size()) {
595             throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
596         }
597 
598         if (valueTypes.length == 0) return target;
599 
600         List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
601         newCoordinates.addAll(pos, List.of(valueTypes));
602 
603         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
604                 (mode, modeHandle) -> MethodHandles.dropArguments(modeHandle, 1 + pos, valueTypes));
605     }
606 
607     private static void noCheckedExceptions(MethodHandle handle) {






















608         if (handle instanceof DirectMethodHandle directHandle) {
609             byte refKind = directHandle.member.getReferenceKind();
610             MethodHandleInfo info = new InfoFromMemberName(
611                     MethodHandles.Lookup.IMPL_LOOKUP,
612                     directHandle.member,
613                     refKind);
614             final Class<?>[] exceptionTypes;
615             if (MethodHandleNatives.refKindIsMethod(refKind)) {
616                 exceptionTypes = info.reflectAs(Method.class, MethodHandles.Lookup.IMPL_LOOKUP)
617                         .getExceptionTypes();
618             } else if (MethodHandleNatives.refKindIsField(refKind)) {
619                 exceptionTypes = null;
620             } else if (MethodHandleNatives.refKindIsConstructor(refKind)) {
621                 exceptionTypes = info.reflectAs(Constructor.class, MethodHandles.Lookup.IMPL_LOOKUP)
622                         .getExceptionTypes();
623             } else {
624                 throw new AssertionError("Cannot get here");
625             }
626             if (exceptionTypes != null) {
627                 if (Stream.of(exceptionTypes).anyMatch(VarHandles::isCheckedException)) {
628                     throw newIllegalArgumentException("Cannot adapt a var handle with a method handle which throws checked exceptions");
629                 }
630             }
631         } else if (handle instanceof DelegatingMethodHandle) {
632             noCheckedExceptions(((DelegatingMethodHandle)handle).getTarget());
633         } else {
634             //bound
635             BoundMethodHandle boundHandle = (BoundMethodHandle)handle;
636             for (int i = 0 ; i < boundHandle.fieldCount() ; i++) {
637                 Object arg = boundHandle.arg(i);
638                 if (arg instanceof MethodHandle){
639                     noCheckedExceptions((MethodHandle) arg);
640                 }
641             }
642         }




643     }
644 
645     private static boolean isCheckedException(Class<?> clazz) {
646         return Throwable.class.isAssignableFrom(clazz) &&
647                 !RuntimeException.class.isAssignableFrom(clazz) &&
648                 !Error.class.isAssignableFrom(clazz);
649     }
650 
651 //    /**
652 //     * A helper program to generate the VarHandleGuards class with a set of
653 //     * static guard methods each of which corresponds to a particular shape and
654 //     * performs a type check of the symbolic type descriptor with the VarHandle
655 //     * type descriptor before linking/invoking to the underlying operation as
656 //     * characterized by the operation member name on the VarForm of the
657 //     * VarHandle.
658 //     * <p>
659 //     * The generated class essentially encapsulates pre-compiled LambdaForms,
660 //     * one for each method, for the most set of common method signatures.
661 //     * This reduces static initialization costs, footprint costs, and circular
662 //     * dependencies that may arise if a class is generated per LambdaForm.

 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.lang.invoke;
 27 
 28 import sun.invoke.util.Wrapper;
 29 
 30 import java.lang.reflect.Constructor;
 31 import java.lang.reflect.Field;
 32 import java.lang.reflect.Method;
 33 import java.lang.reflect.Modifier;

 34 import java.nio.ByteOrder;
 35 import java.util.ArrayList;

 36 import java.util.List;

 37 import java.util.Objects;
 38 import java.util.concurrent.ConcurrentHashMap;
 39 import java.util.concurrent.ConcurrentMap;
 40 import java.util.stream.Stream;
 41 
 42 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
 43 import static java.lang.invoke.MethodHandleStatics.VAR_HANDLE_IDENTITY_ADAPT;
 44 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;


 45 
 46 final class VarHandles {
 47 
 48     static ClassValue<ConcurrentMap<Integer, MethodHandle>> ADDRESS_FACTORIES = new ClassValue<>() {
 49         @Override
 50         protected ConcurrentMap<Integer, MethodHandle> computeValue(Class<?> type) {
 51             return new ConcurrentHashMap<>();
 52         }
 53     };
 54 
 55     static VarHandle makeFieldHandle(MemberName f, Class<?> refc, Class<?> type, boolean isWriteAllowedOnFinalFields) {
 56         if (!f.isStatic()) {
 57             long foffset = MethodHandleNatives.objectFieldOffset(f);
 58             if (!type.isPrimitive()) {
 59                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 60                        ? new VarHandleReferences.FieldInstanceReadOnly(refc, foffset, type)
 61                        : new VarHandleReferences.FieldInstanceReadWrite(refc, foffset, type));
 62             }
 63             else if (type == boolean.class) {
 64                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields

337         } else if (carrier == long.class) {
338             return maybeAdapt(new MemoryAccessVarHandleLongHelper(skipAlignmentMaskCheck, be, size, alignmentMask, exact));
339         } else if (carrier == double.class) {
340             return maybeAdapt(new MemoryAccessVarHandleDoubleHelper(skipAlignmentMaskCheck, be, size, alignmentMask, exact));
341         } else {
342             throw new IllegalStateException("Cannot get here");
343         }
344     }
345 
346     private static VarHandle maybeAdapt(VarHandle target) {
347         if (!VAR_HANDLE_IDENTITY_ADAPT) return target;
348         target = filterValue(target,
349                         MethodHandles.identity(target.varType()), MethodHandles.identity(target.varType()));
350         MethodType mtype = target.accessModeType(VarHandle.AccessMode.GET);
351         for (int i = 0 ; i < mtype.parameterCount() ; i++) {
352             target = filterCoordinates(target, i, MethodHandles.identity(mtype.parameterType(i)));
353         }
354         return target;
355     }
356 
357     public static VarHandle filterValue(VarHandle target, MethodHandle pFilterToTarget, MethodHandle pFilterFromTarget) {
358         Objects.requireNonNull(target);
359         Objects.requireNonNull(pFilterToTarget);
360         Objects.requireNonNull(pFilterFromTarget);
361         //check that from/to filters do not throw checked exceptions
362         MethodHandle filterToTarget = adaptForCheckedExceptions(pFilterToTarget);
363         MethodHandle filterFromTarget = adaptForCheckedExceptions(pFilterFromTarget);
364 
365         List<Class<?>> newCoordinates = new ArrayList<>();
366         List<Class<?>> additionalCoordinates = new ArrayList<>();
367         newCoordinates.addAll(target.coordinateTypes());
368 
369         //check that from/to filters have right signatures
370         if (filterFromTarget.type().parameterCount() != filterToTarget.type().parameterCount()) {
371             throw newIllegalArgumentException("filterFromTarget and filterToTarget have different arity", filterFromTarget.type(), filterToTarget.type());
372         } else if (filterFromTarget.type().parameterCount() < 1) {
373             throw newIllegalArgumentException("filterFromTarget filter type has wrong arity", filterFromTarget.type());
374         } else if (filterToTarget.type().parameterCount() < 1) {
375             throw newIllegalArgumentException("filterToTarget filter type has wrong arity", filterFromTarget.type());
376         } else if (filterFromTarget.type().lastParameterType() != filterToTarget.type().returnType() ||
377                 filterToTarget.type().lastParameterType() != filterFromTarget.type().returnType()) {
378             throw newIllegalArgumentException("filterFromTarget and filterToTarget filter types do not match", filterFromTarget.type(), filterToTarget.type());
379         } else if (target.varType() != filterFromTarget.type().lastParameterType()) {
380             throw newIllegalArgumentException("filterFromTarget filter type does not match target var handle type", filterFromTarget.type(), target.varType());
381         } else if (target.varType() != filterToTarget.type().returnType()) {
382             throw newIllegalArgumentException("filterFromTarget filter type does not match target var handle type", filterToTarget.type(), target.varType());
383         } else if (filterFromTarget.type().parameterCount() > 1) {

451         return MethodHandles.permuteArguments(handle,
452                 handle.type().dropParameterTypes(dropStart, dropStart + length),
453                 perms);
454     }
455 
456     public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
457         Objects.requireNonNull(target);
458         Objects.requireNonNull(filters);
459 
460         List<Class<?>> targetCoordinates = target.coordinateTypes();
461         if (pos < 0 || pos >= targetCoordinates.size()) {
462             throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
463         } else if (pos + filters.length > targetCoordinates.size()) {
464             throw new IllegalArgumentException("Too many filters");
465         }
466 
467         if (filters.length == 0) return target;
468 
469         List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
470         for (int i = 0 ; i < filters.length ; i++) {
471             MethodHandle filter = Objects.requireNonNull(filters[i]);
472             filter = adaptForCheckedExceptions(filter);
473             MethodType filterType = filter.type();
474             if (filterType.parameterCount() != 1) {
475                 throw newIllegalArgumentException("Invalid filter type " + filterType);
476             } else if (newCoordinates.get(pos + i) != filterType.returnType()) {
477                 throw newIllegalArgumentException("Invalid filter type " + filterType + " for coordinate type " + newCoordinates.get(i));
478             }
479             newCoordinates.set(pos + i, filters[i].type().parameterType(0));
480         }
481 
482         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
483                 (mode, modeHandle) -> MethodHandles.filterArguments(modeHandle, 1 + pos, filters));
484     }
485 
486     public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
487         Objects.requireNonNull(target);
488         Objects.requireNonNull(values);
489 
490         List<Class<?>> targetCoordinates = target.coordinateTypes();
491         if (pos < 0 || pos >= targetCoordinates.size()) {
492             throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
493         } else if (pos + values.length > targetCoordinates.size()) {

543         adjustedReorder[0] = 0;
544         for (int i = 0 ; i < reorder.length ; i++) {
545             adjustedReorder[i + 1] = reorder[i] + 1;
546         }
547         for (int i = 0 ; i < numTrailingArgs ; i++) {
548             adjustedReorder[i + reorder.length + 1] = i + newCoordinates.size() + 1;
549         }
550         return adjustedReorder;
551     }
552 
553     private static MethodType methodTypeFor(VarHandle.AccessType at, MethodType oldType, List<Class<?>> oldCoordinates, List<Class<?>> newCoordinates) {
554         int numTrailingArgs = numTrailingArgs(at);
555         MethodType adjustedType = MethodType.methodType(oldType.returnType(), oldType.parameterType(0));
556         adjustedType = adjustedType.appendParameterTypes(newCoordinates);
557         for (int i = 0 ; i < numTrailingArgs ; i++) {
558             adjustedType = adjustedType.appendParameterTypes(oldType.parameterType(1 + oldCoordinates.size() + i));
559         }
560         return adjustedType;
561     }
562 
563     public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle pFilter) {
564         Objects.requireNonNull(target);
565         Objects.requireNonNull(pFilter);
566         MethodHandle filter = adaptForCheckedExceptions(pFilter);
567 
568         List<Class<?>> targetCoordinates = target.coordinateTypes();
569         if (pos < 0 || pos >= targetCoordinates.size()) {
570             throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
571         } else if (filter.type().returnType() == void.class) {
572             throw newIllegalArgumentException("Invalid filter type " + filter.type() + " ; filter cannot be void");
573         } else if (filter.type().returnType() != targetCoordinates.get(pos)) {
574             throw newIllegalArgumentException("Invalid filter type " + filter.type() + " for coordinate type " + targetCoordinates.get(pos));
575         }
576 
577         List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
578         newCoordinates.remove(pos);
579         newCoordinates.addAll(pos, filter.type().parameterList());
580 
581         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
582                 (mode, modeHandle) -> MethodHandles.collectArguments(modeHandle, 1 + pos, filter));
583     }
584 
585     public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
586         Objects.requireNonNull(target);
587         Objects.requireNonNull(valueTypes);
588 
589         List<Class<?>> targetCoordinates = target.coordinateTypes();
590         if (pos < 0 || pos > targetCoordinates.size()) {
591             throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
592         }
593 
594         if (valueTypes.length == 0) return target;
595 
596         List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
597         newCoordinates.addAll(pos, List.of(valueTypes));
598 
599         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
600                 (mode, modeHandle) -> MethodHandles.dropArguments(modeHandle, 1 + pos, valueTypes));
601     }
602 
603     private static MethodHandle adaptForCheckedExceptions(MethodHandle target) {
604         Class<?>[] exceptionTypes = exceptionTypes(target);
605         if (exceptionTypes != null) { // exceptions known
606             if (Stream.of(exceptionTypes).anyMatch(VarHandles::isCheckedException)) {
607                 throw newIllegalArgumentException("Cannot adapt a var handle with a method handle which throws checked exceptions");
608             }
609             return target; // no adaptation needed
610         } else {
611             MethodHandle handler = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_VarHandles_handleCheckedExceptions);
612             MethodHandle zero = MethodHandles.zero(target.type().returnType()); // dead branch
613             handler = MethodHandles.collectArguments(zero, 0, handler);
614             return MethodHandles.catchException(target, Throwable.class, handler);
615         }
616     }
617 
618     static void handleCheckedExceptions(Throwable throwable) throws Throwable {
619         if (isCheckedException(throwable.getClass())) {
620             throw new IllegalStateException("Adapter handle threw checked exception", throwable);
621         }
622         throw throwable;
623     }
624 
625     static Class<?>[] exceptionTypes(MethodHandle handle) {
626         if (handle instanceof DirectMethodHandle directHandle) {
627             byte refKind = directHandle.member.getReferenceKind();
628             MethodHandleInfo info = new InfoFromMemberName(
629                     MethodHandles.Lookup.IMPL_LOOKUP,
630                     directHandle.member,
631                     refKind);

632             if (MethodHandleNatives.refKindIsMethod(refKind)) {
633                 return info.reflectAs(Method.class, MethodHandles.Lookup.IMPL_LOOKUP)
634                         .getExceptionTypes();
635             } else if (MethodHandleNatives.refKindIsField(refKind)) {
636                 return new Class<?>[0];
637             } else if (MethodHandleNatives.refKindIsConstructor(refKind)) {
638                 return info.reflectAs(Constructor.class, MethodHandles.Lookup.IMPL_LOOKUP)
639                         .getExceptionTypes();
640             } else {
641                 throw new AssertionError("Cannot get here");
642             }





643         } else if (handle instanceof DelegatingMethodHandle) {
644             return exceptionTypes(((DelegatingMethodHandle)handle).getTarget());
645         } else if (handle instanceof NativeMethodHandle) {
646             return new Class<?>[0];







647         }
648 
649         assert handle instanceof BoundMethodHandle : "Unexpected handle type: " + handle;
650         // unknown
651         return null;
652     }
653 
654     private static boolean isCheckedException(Class<?> clazz) {
655         return Throwable.class.isAssignableFrom(clazz) &&
656                 !RuntimeException.class.isAssignableFrom(clazz) &&
657                 !Error.class.isAssignableFrom(clazz);
658     }
659 
660 //    /**
661 //     * A helper program to generate the VarHandleGuards class with a set of
662 //     * static guard methods each of which corresponds to a particular shape and
663 //     * performs a type check of the symbolic type descriptor with the VarHandle
664 //     * type descriptor before linking/invoking to the underlying operation as
665 //     * characterized by the operation member name on the VarForm of the
666 //     * VarHandle.
667 //     * <p>
668 //     * The generated class essentially encapsulates pre-compiled LambdaForms,
669 //     * one for each method, for the most set of common method signatures.
670 //     * This reduces static initialization costs, footprint costs, and circular
671 //     * dependencies that may arise if a class is generated per LambdaForm.
< prev index next >