< prev index next >

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

Print this page




   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.access.SharedSecrets;
  29 import jdk.internal.module.IllegalAccessLogger;
  30 import jdk.internal.org.objectweb.asm.ClassReader;
  31 import jdk.internal.reflect.CallerSensitive;
  32 import jdk.internal.reflect.Reflection;
  33 import jdk.internal.vm.annotation.ForceInline;
  34 import sun.invoke.util.ValueConversions;
  35 import sun.invoke.util.VerifyAccess;
  36 import sun.invoke.util.Wrapper;
  37 import sun.reflect.misc.ReflectUtil;
  38 import sun.security.util.SecurityConstants;
  39 
  40 import java.lang.invoke.LambdaForm.BasicType;
  41 import java.lang.reflect.Constructor;
  42 import java.lang.reflect.Field;
  43 import java.lang.reflect.Member;
  44 import java.lang.reflect.Method;
  45 import java.lang.reflect.Modifier;
  46 import java.lang.reflect.ReflectPermission;
  47 import java.nio.ByteOrder;
  48 import java.security.AccessController;
  49 import java.security.PrivilegedAction;
  50 import java.security.ProtectionDomain;
  51 import java.util.ArrayList;
  52 import java.util.Arrays;
  53 import java.util.BitSet;
  54 import java.util.Iterator;
  55 import java.util.List;
  56 import java.util.Objects;
  57 import java.util.Set;

  58 import java.util.concurrent.ConcurrentHashMap;
  59 import java.util.stream.Collectors;
  60 import java.util.stream.Stream;
  61 

  62 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  63 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  64 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  65 import static java.lang.invoke.MethodType.methodType;
  66 
  67 /**
  68  * This class consists exclusively of static methods that operate on or return
  69  * method handles. They fall into several categories:
  70  * <ul>
  71  * <li>Lookup methods which help create method handles for methods and fields.
  72  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  73  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  74  * </ul>
  75  * A lookup, combinator, or factory method will fail and throw an
  76  * {@code IllegalArgumentException} if the created method handle's type
  77  * would have <a href="MethodHandle.html#maxarity">too many parameters</a>.
  78  *
  79  * @author John Rose, JSR 292 EG
  80  * @since 1.7
  81  */


 163      * do <em>deep reflection</em> on the target class. If {@code m1} is the module containing
 164      * the {@link Lookup#lookupClass() lookup class}, and {@code m2} is the module containing
 165      * the target class, then this check ensures that
 166      * <ul>
 167      *     <li>{@code m1} {@link Module#canRead reads} {@code m2}.</li>
 168      *     <li>{@code m2} {@link Module#isOpen(String,Module) opens} the package containing
 169      *     the target class to at least {@code m1}.</li>
 170      *     <li>The lookup has the {@link Lookup#MODULE MODULE} lookup mode.</li>
 171      * </ul>
 172      * <p>
 173      * If there is a security manager, its {@code checkPermission} method is called to
 174      * check {@code ReflectPermission("suppressAccessChecks")}.
 175      * @apiNote The {@code MODULE} lookup mode serves to authenticate that the lookup object
 176      * was created by code in the caller module (or derived from a lookup object originally
 177      * created by the caller). A lookup object with the {@code MODULE} lookup mode can be
 178      * shared with trusted parties without giving away {@code PRIVATE} and {@code PACKAGE}
 179      * access to the caller.
 180      * @param targetClass the target class
 181      * @param lookup the caller lookup object
 182      * @return a lookup object for the target class, with private access
 183      * @throws IllegalArgumentException if {@code targetClass} is a primitve type or array class
 184      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 185      * @throws IllegalAccessException if the access check specified above fails
 186      * @throws SecurityException if denied by the security manager
 187      * @since 9
 188      * @spec JPMS
 189      * @see Lookup#dropLookupMode
 190      */
 191     public static Lookup privateLookupIn(Class<?> targetClass, Lookup lookup) throws IllegalAccessException {




 192         SecurityManager sm = System.getSecurityManager();
 193         if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
 194         if (targetClass.isPrimitive())
 195             throw new IllegalArgumentException(targetClass + " is a primitive class");
 196         if (targetClass.isArray())
 197             throw new IllegalArgumentException(targetClass + " is an array class");
 198         Module targetModule = targetClass.getModule();
 199         Module callerModule = lookup.lookupClass().getModule();
 200         if (!callerModule.canRead(targetModule))
 201             throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 202         if (targetModule.isNamed()) {
 203             String pn = targetClass.getPackageName();
 204             assert !pn.isEmpty() : "unnamed package cannot be in named module";
 205             if (!targetModule.isOpen(pn, callerModule))
 206                 throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 207         }
 208         if ((lookup.lookupModes() & Lookup.MODULE) == 0)
 209             throw new IllegalAccessException("lookup does not have MODULE lookup mode");
 210         if (!callerModule.isNamed() && targetModule.isNamed()) {
 211             IllegalAccessLogger logger = IllegalAccessLogger.illegalAccessLogger();


 758          *  so that it can access only names which can be reached by the original
 759          *  lookup object, and also by the new lookup class.
 760          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
 761          *  @see #in
 762          *  @see #dropLookupMode
 763          *
 764          *  @revised 9
 765          *  @spec JPMS
 766          */
 767         public int lookupModes() {
 768             return allowedModes & ALL_MODES;
 769         }
 770 
 771         /** Embody the current class (the lookupClass) as a lookup class
 772          * for method handle creation.
 773          * Must be called by from a method in this package,
 774          * which in turn is called by a method not in this package.
 775          */
 776         Lookup(Class<?> lookupClass) {
 777             this(lookupClass, FULL_POWER_MODES);
 778             // make sure we haven't accidentally picked up a privileged class:
 779             checkUnprivilegedlookupClass(lookupClass);
 780         }
 781 
 782         private Lookup(Class<?> lookupClass, int allowedModes) {
 783             this.lookupClass = lookupClass;
 784             this.allowedModes = allowedModes;

 785         }
 786 
 787         /**
 788          * Creates a lookup on the specified new lookup class.
 789          * The resulting object will report the specified
 790          * class as its own {@link #lookupClass() lookupClass}.
 791          * <p>
 792          * However, the resulting {@code Lookup} object is guaranteed
 793          * to have no more access capabilities than the original.
 794          * In particular, access capabilities can be lost as follows:<ul>
 795          * <li>If the old lookup class is in a {@link Module#isNamed() named} module, and
 796          * the new lookup class is in a different module {@code M}, then no members, not
 797          * even public members in {@code M}'s exported packages, will be accessible.
 798          * The exception to this is when this lookup is {@link #publicLookup()
 799          * publicLookup}, in which case {@code PUBLIC} access is not lost.
 800          * <li>If the old lookup class is in an unnamed module, and the new lookup class
 801          * is a different module then {@link #MODULE MODULE} access is lost.
 802          * <li>If the new lookup class differs from the old one then {@code UNCONDITIONAL} is lost.
 803          * <li>If the new lookup class is in a different package
 804          * than the old one, protected and default (package) members will not be accessible.
 805          * <li>If the new lookup class is not within the same package member
 806          * as the old one, private members will not be accessible, and protected members
 807          * will not be accessible by virtue of inheritance.
 808          * (Protected members may continue to be accessible because of package sharing.)
 809          * <li>If the new lookup class is not accessible to the old lookup class,
 810          * then no members, not even public members, will be accessible.
 811          * (In all other cases, public members will continue to be accessible.)
 812          * </ul>
 813          * <p>
 814          * The resulting lookup's capabilities for loading classes
 815          * (used during {@link #findClass} invocations)
 816          * are determined by the lookup class' loader,
 817          * which may change due to this operation.
 818          *
 819          * @param requestedLookupClass the desired lookup class for the new lookup object
 820          * @return a lookup object which reports the desired lookup class, or the same object
 821          * if there is no change


 822          * @throws NullPointerException if the argument is null
 823          *
 824          * @revised 9
 825          * @spec JPMS
 826          */
 827         public Lookup in(Class<?> requestedLookupClass) {
 828             Objects.requireNonNull(requestedLookupClass);





 829             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
 830                 return new Lookup(requestedLookupClass, FULL_POWER_MODES);
 831             if (requestedLookupClass == this.lookupClass)
 832                 return this;  // keep same capabilities
 833             int newModes = (allowedModes & FULL_POWER_MODES);
 834             if (!VerifyAccess.isSameModule(this.lookupClass, requestedLookupClass)) {
 835                 // Need to drop all access when teleporting from a named module to another
 836                 // module. The exception is publicLookup where PUBLIC is not lost.
 837                 if (this.lookupClass.getModule().isNamed()
 838                     && (this.allowedModes & UNCONDITIONAL) == 0)
 839                     newModes = 0;
 840                 else
 841                     newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
 842             }
 843             if ((newModes & PACKAGE) != 0
 844                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
 845                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
 846             }
 847             // Allow nestmate lookups to be created without special privilege:
 848             if ((newModes & PRIVATE) != 0


 883             int oldModes = lookupModes();
 884             int newModes = oldModes & ~(modeToDrop | PROTECTED | UNCONDITIONAL);
 885             switch (modeToDrop) {
 886                 case PUBLIC: newModes &= ~(ALL_MODES); break;
 887                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
 888                 case PACKAGE: newModes &= ~(PRIVATE); break;
 889                 case PROTECTED:
 890                 case PRIVATE:
 891                 case UNCONDITIONAL: break;
 892                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
 893             }
 894             if (newModes == oldModes) return this;  // return self if no change
 895             return new Lookup(lookupClass(), newModes);
 896         }
 897 
 898         /**
 899          * Defines a class to the same class loader and in the same runtime package and
 900          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
 901          * {@linkplain #lookupClass() lookup class}.
 902          *




 903          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
 904          * {@link #PACKAGE PACKAGE} access as default (package) members will be
 905          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
 906          * that the lookup object was created by a caller in the runtime package (or derived
 907          * from a lookup originally created by suitably privileged code to a target class in
 908          * the runtime package). </p>
 909          *
 910          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
 911          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
 912          * same package as the lookup class. </p>
 913          *
 914          * <p> This method does not run the class initializer. The class initializer may
 915          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
 916          * Specification</em>. </p>
 917          *
 918          * <p> If there is a security manager, its {@code checkPermission} method is first called
 919          * to check {@code RuntimePermission("defineClass")}. </p>
 920          *
 921          * @param bytes the class bytes
 922          * @return the {@code Class} object for the class
 923          * @throws IllegalArgumentException the bytes are for a class in a different package
 924          * to the lookup class
 925          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
 926          * @throws LinkageError if the class is malformed ({@code ClassFormatError}), cannot be
 927          * verified ({@code VerifyError}), is already defined, or another linkage error occurs
 928          * @throws SecurityException if denied by the security manager
 929          * @throws NullPointerException if {@code bytes} is {@code null}
 930          * @since 9
 931          * @spec JPMS
 932          * @see Lookup#privateLookupIn
 933          * @see Lookup#dropLookupMode
 934          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
 935          */
 936         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {



























































































































 937             SecurityManager sm = System.getSecurityManager();
 938             if (sm != null)
 939                 sm.checkPermission(new RuntimePermission("defineClass"));
 940             if ((lookupModes() & PACKAGE) == 0)


























































 941                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
 942             assert (lookupModes() & (MODULE|PUBLIC)) != 0;
 943 





























































































 944             // parse class bytes to get class name (in internal form)
 945             bytes = bytes.clone();
 946             String name;
 947             try {
 948                 ClassReader reader = new ClassReader(bytes);
 949                 name = reader.getClassName();
 950             } catch (RuntimeException e) {
 951                 // ASM exceptions are poorly specified
 952                 ClassFormatError cfe = new ClassFormatError();
 953                 cfe.initCause(e);
 954                 throw cfe;
 955             }
 956 
 957             // get package and class name in binary form
 958             String cn, pn;
 959             int index = name.lastIndexOf('/');
 960             if (index == -1) {
 961                 cn = name;
 962                 pn = "";
 963             } else {
 964                 cn = name.replace('/', '.');
 965                 pn = cn.substring(0, index);
 966             }
 967             if (!pn.equals(lookupClass.getPackageName())) {
 968                 throw new IllegalArgumentException("Class not in same package as lookup class");





 969             }
 970 
 971             // invoke the class loader's defineClass method
 972             ClassLoader loader = lookupClass.getClassLoader();
 973             ProtectionDomain pd = (loader != null) ? lookupClassProtectionDomain() : null;
 974             String source = "__Lookup_defineClass__";
 975             Class<?> clazz = SharedSecrets.getJavaLangAccess().defineClass(loader, cn, bytes, pd, source);


 976             return clazz;
 977         }
 978 


 979         private ProtectionDomain lookupClassProtectionDomain() {
 980             ProtectionDomain pd = cachedProtectionDomain;
 981             if (pd == null) {
 982                 cachedProtectionDomain = pd = protectionDomain(lookupClass);
 983             }
 984             return pd;
 985         }
 986 
 987         private ProtectionDomain protectionDomain(Class<?> clazz) {
 988             PrivilegedAction<ProtectionDomain> pa = clazz::getProtectionDomain;
 989             return AccessController.doPrivileged(pa);
 990         }
 991 
 992         // cached protection domain
 993         private volatile ProtectionDomain cachedProtectionDomain;
 994 
 995 
 996         // Make sure outer class is initialized first.
 997         static { IMPL_NAMES.getClass(); }
 998 
 999         /** Package-private version of lookup which is trusted. */
1000         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED);
1001 
1002         /** Version of lookup which is trusted minimally.
1003          *  It can only be used to create method handles to publicly accessible
1004          *  members in packages that are exported unconditionally.
1005          */
1006         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, (PUBLIC|UNCONDITIONAL));
1007 


1008         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
1009             String name = lookupClass.getName();
1010             if (name.startsWith("java.lang.invoke."))
1011                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
1012         }
1013 
1014         /**
1015          * Displays the name of the class from which lookups are to be made.
1016          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
1017          * If there are restrictions on the access permitted to this lookup,
1018          * this is indicated by adding a suffix to the class name, consisting
1019          * of a slash and a keyword.  The keyword represents the strongest
1020          * allowed access, and is chosen as follows:
1021          * <ul>
1022          * <li>If no access is allowed, the suffix is "/noaccess".
1023          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
1024          * <li>If only public access and unconditional access are allowed, the suffix is "/publicLookup".
1025          * <li>If only public and module access are allowed, the suffix is "/module".
1026          * <li>If only public, module and package access are allowed, the suffix is "/package".
1027          * <li>If only public, module, package, and private access are allowed, the suffix is "/private".


1269         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1270             if (refc.isArray()) {
1271                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
1272             }
1273             String name = "<init>";
1274             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
1275             return getDirectConstructor(refc, ctor);
1276         }
1277 
1278         /**
1279          * Looks up a class by name from the lookup context defined by this {@code Lookup} object. The static
1280          * initializer of the class is not run.
1281          * <p>
1282          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, its class
1283          * loader, and the {@linkplain #lookupModes() lookup modes}. In particular, the method first attempts to
1284          * load the requested class, and then determines whether the class is accessible to this lookup object.
1285          *
1286          * @param targetName the fully qualified name of the class to be looked up.
1287          * @return the requested class.
1288          * @exception SecurityException if a security manager is present and it
1289          *            <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1290          * @throws LinkageError if the linkage fails
1291          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
1292          * @throws IllegalAccessException if the class is not accessible, using the allowed access
1293          * modes.
1294          * @exception SecurityException if a security manager is present and it
1295          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1296          * @since 9

1297          */
1298         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
1299             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
1300             return accessClass(targetClass);
1301         }
1302 
1303         /**
1304          * Determines if a class can be accessed from the lookup context defined by this {@code Lookup} object. The
1305          * static initializer of the class is not run.
1306          * <p>
1307          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class} and the
1308          * {@linkplain #lookupModes() lookup modes}.
1309          *
1310          * @param targetClass the class to be access-checked
1311          *
1312          * @return the class that has been access-checked
1313          *
1314          * @throws IllegalAccessException if the class is not accessible from the lookup class, using the allowed access
1315          * modes.
1316          * @exception SecurityException if a security manager is present and it


2537             } catch (SecurityException ex) {
2538                 return false;
2539             }
2540             return true;
2541         }
2542         private
2543         MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
2544                 throws ReflectiveOperationException {
2545             if (MethodHandleNatives.refKindIsField(refKind)) {
2546                 return getDirectFieldNoSecurityManager(refKind, defc, member);
2547             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
2548                 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass);
2549             } else if (refKind == REF_newInvokeSpecial) {
2550                 return getDirectConstructorNoSecurityManager(defc, member);
2551             }
2552             // oops
2553             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
2554         }
2555 
2556         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();














































2557     }
2558 
2559     /**
2560      * Produces a method handle constructing arrays of a desired type,
2561      * as if by the {@code anewarray} bytecode.
2562      * The return type of the method handle will be the array type.
2563      * The type of its sole argument will be {@code int}, which specifies the size of the array.
2564      *
2565      * <p> If the returned method handle is invoked with a negative
2566      * array size, a {@code NegativeArraySizeException} will be thrown.
2567      *
2568      * @param arrayClass an array type
2569      * @return a method handle which can create arrays of the given type
2570      * @throws NullPointerException if the argument is {@code null}
2571      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
2572      * @see java.lang.reflect.Array#newInstance(Class, int)
2573      * @jvms 6.5 {@code anewarray} Instruction
2574      * @since 9
2575      */
2576     public static




   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.access.JavaLangAccess;
  29 import jdk.internal.access.SharedSecrets;
  30 import jdk.internal.module.IllegalAccessLogger;
  31 import jdk.internal.org.objectweb.asm.ClassReader;
  32 import jdk.internal.reflect.CallerSensitive;
  33 import jdk.internal.reflect.Reflection;
  34 import jdk.internal.vm.annotation.ForceInline;
  35 import sun.invoke.util.ValueConversions;
  36 import sun.invoke.util.VerifyAccess;
  37 import sun.invoke.util.Wrapper;
  38 import sun.reflect.misc.ReflectUtil;
  39 import sun.security.util.SecurityConstants;
  40 
  41 import java.lang.invoke.LambdaForm.BasicType;
  42 import java.lang.reflect.Constructor;
  43 import java.lang.reflect.Field;
  44 import java.lang.reflect.Member;
  45 import java.lang.reflect.Method;
  46 import java.lang.reflect.Modifier;
  47 import java.lang.reflect.ReflectPermission;
  48 import java.nio.ByteOrder;


  49 import java.security.ProtectionDomain;
  50 import java.util.ArrayList;
  51 import java.util.Arrays;
  52 import java.util.BitSet;
  53 import java.util.Iterator;
  54 import java.util.List;
  55 import java.util.Objects;
  56 import java.util.Set;
  57 import java.util.WeakHashMap;
  58 import java.util.concurrent.ConcurrentHashMap;
  59 import java.util.stream.Collectors;
  60 import java.util.stream.Stream;
  61 
  62 import static java.lang.invoke.MethodHandles.Lookup.ClassProperty.*;
  63 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  64 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  65 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  66 import static java.lang.invoke.MethodType.methodType;
  67 
  68 /**
  69  * This class consists exclusively of static methods that operate on or return
  70  * method handles. They fall into several categories:
  71  * <ul>
  72  * <li>Lookup methods which help create method handles for methods and fields.
  73  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  74  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  75  * </ul>
  76  * A lookup, combinator, or factory method will fail and throw an
  77  * {@code IllegalArgumentException} if the created method handle's type
  78  * would have <a href="MethodHandle.html#maxarity">too many parameters</a>.
  79  *
  80  * @author John Rose, JSR 292 EG
  81  * @since 1.7
  82  */


 164      * do <em>deep reflection</em> on the target class. If {@code m1} is the module containing
 165      * the {@link Lookup#lookupClass() lookup class}, and {@code m2} is the module containing
 166      * the target class, then this check ensures that
 167      * <ul>
 168      *     <li>{@code m1} {@link Module#canRead reads} {@code m2}.</li>
 169      *     <li>{@code m2} {@link Module#isOpen(String,Module) opens} the package containing
 170      *     the target class to at least {@code m1}.</li>
 171      *     <li>The lookup has the {@link Lookup#MODULE MODULE} lookup mode.</li>
 172      * </ul>
 173      * <p>
 174      * If there is a security manager, its {@code checkPermission} method is called to
 175      * check {@code ReflectPermission("suppressAccessChecks")}.
 176      * @apiNote The {@code MODULE} lookup mode serves to authenticate that the lookup object
 177      * was created by code in the caller module (or derived from a lookup object originally
 178      * created by the caller). A lookup object with the {@code MODULE} lookup mode can be
 179      * shared with trusted parties without giving away {@code PRIVATE} and {@code PACKAGE}
 180      * access to the caller.
 181      * @param targetClass the target class
 182      * @param lookup the caller lookup object
 183      * @return a lookup object for the target class, with private access
 184      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or array class
 185      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 186      * @throws IllegalAccessException if the access check specified above fails
 187      * @throws SecurityException if denied by the security manager
 188      * @since 9
 189      * @spec JPMS
 190      * @see Lookup#dropLookupMode
 191      */
 192     public static Lookup privateLookupIn(Class<?> targetClass, Lookup lookup) throws IllegalAccessException {
 193         if (lookup.allowedModes == Lookup.TRUSTED) {
 194             return new Lookup(targetClass);
 195         }
 196 
 197         SecurityManager sm = System.getSecurityManager();
 198         if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
 199         if (targetClass.isPrimitive())
 200             throw new IllegalArgumentException(targetClass + " is a primitive class");
 201         if (targetClass.isArray())
 202             throw new IllegalArgumentException(targetClass + " is an array class");
 203         Module targetModule = targetClass.getModule();
 204         Module callerModule = lookup.lookupClass().getModule();
 205         if (!callerModule.canRead(targetModule))
 206             throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 207         if (targetModule.isNamed()) {
 208             String pn = targetClass.getPackageName();
 209             assert !pn.isEmpty() : "unnamed package cannot be in named module";
 210             if (!targetModule.isOpen(pn, callerModule))
 211                 throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 212         }
 213         if ((lookup.lookupModes() & Lookup.MODULE) == 0)
 214             throw new IllegalAccessException("lookup does not have MODULE lookup mode");
 215         if (!callerModule.isNamed() && targetModule.isNamed()) {
 216             IllegalAccessLogger logger = IllegalAccessLogger.illegalAccessLogger();


 763          *  so that it can access only names which can be reached by the original
 764          *  lookup object, and also by the new lookup class.
 765          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
 766          *  @see #in
 767          *  @see #dropLookupMode
 768          *
 769          *  @revised 9
 770          *  @spec JPMS
 771          */
 772         public int lookupModes() {
 773             return allowedModes & ALL_MODES;
 774         }
 775 
 776         /** Embody the current class (the lookupClass) as a lookup class
 777          * for method handle creation.
 778          * Must be called by from a method in this package,
 779          * which in turn is called by a method not in this package.
 780          */
 781         Lookup(Class<?> lookupClass) {
 782             this(lookupClass, FULL_POWER_MODES);


 783         }
 784 
 785         private Lookup(Class<?> lookupClass, int allowedModes) {
 786             this.lookupClass = lookupClass;
 787             this.allowedModes = allowedModes;
 788             assert !lookupClass.isPrimitive() && !lookupClass.isArray();
 789         }
 790 
 791         /**
 792          * Creates a lookup on the specified new lookup class.
 793          * The resulting object will report the specified
 794          * class as its own {@link #lookupClass() lookupClass}.
 795          * <p>
 796          * However, the resulting {@code Lookup} object is guaranteed
 797          * to have no more access capabilities than the original.
 798          * In particular, access capabilities can be lost as follows:<ul>
 799          * <li>If the old lookup class is in a {@link Module#isNamed() named} module, and
 800          * the new lookup class is in a different module {@code M}, then no members, not
 801          * even public members in {@code M}'s exported packages, will be accessible.
 802          * The exception to this is when this lookup is {@link #publicLookup()
 803          * publicLookup}, in which case {@code PUBLIC} access is not lost.
 804          * <li>If the old lookup class is in an unnamed module, and the new lookup class
 805          * is a different module then {@link #MODULE MODULE} access is lost.
 806          * <li>If the new lookup class differs from the old one then {@code UNCONDITIONAL} is lost.
 807          * <li>If the new lookup class is in a different package
 808          * than the old one, protected and default (package) members will not be accessible.
 809          * <li>If the new lookup class is not within the same package member
 810          * as the old one, private members will not be accessible, and protected members
 811          * will not be accessible by virtue of inheritance.
 812          * (Protected members may continue to be accessible because of package sharing.)
 813          * <li>If the new lookup class is not accessible to the old lookup class,
 814          * then no members, not even public members, will be accessible.
 815          * (In all other cases, public members will continue to be accessible.)
 816          * </ul>
 817          * <p>
 818          * The resulting lookup's capabilities for loading classes
 819          * (used during {@link #findClass} invocations)
 820          * are determined by the lookup class' loader,
 821          * which may change due to this operation.
 822          *
 823          * @param requestedLookupClass the desired lookup class for the new lookup object
 824          * @return a lookup object which reports the desired lookup class, or the same object
 825          * if there is no change
 826          * @throws IllegalArgumentException if {@code requestedLookupClass} is
 827          * a primitive type or array class
 828          * @throws NullPointerException if the argument is null
 829          *
 830          * @revised 9
 831          * @spec JPMS
 832          */
 833         public Lookup in(Class<?> requestedLookupClass) {
 834             Objects.requireNonNull(requestedLookupClass);
 835             if (requestedLookupClass.isPrimitive())
 836                 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class");
 837             if (requestedLookupClass.isArray())
 838                 throw new IllegalArgumentException(requestedLookupClass + " is an array class");
 839 
 840             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
 841                 return new Lookup(requestedLookupClass, FULL_POWER_MODES);
 842             if (requestedLookupClass == this.lookupClass)
 843                 return this;  // keep same capabilities
 844             int newModes = (allowedModes & FULL_POWER_MODES);
 845             if (!VerifyAccess.isSameModule(this.lookupClass, requestedLookupClass)) {
 846                 // Need to drop all access when teleporting from a named module to another
 847                 // module. The exception is publicLookup where PUBLIC is not lost.
 848                 if (this.lookupClass.getModule().isNamed()
 849                     && (this.allowedModes & UNCONDITIONAL) == 0)
 850                     newModes = 0;
 851                 else
 852                     newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
 853             }
 854             if ((newModes & PACKAGE) != 0
 855                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
 856                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
 857             }
 858             // Allow nestmate lookups to be created without special privilege:
 859             if ((newModes & PRIVATE) != 0


 894             int oldModes = lookupModes();
 895             int newModes = oldModes & ~(modeToDrop | PROTECTED | UNCONDITIONAL);
 896             switch (modeToDrop) {
 897                 case PUBLIC: newModes &= ~(ALL_MODES); break;
 898                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
 899                 case PACKAGE: newModes &= ~(PRIVATE); break;
 900                 case PROTECTED:
 901                 case PRIVATE:
 902                 case UNCONDITIONAL: break;
 903                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
 904             }
 905             if (newModes == oldModes) return this;  // return self if no change
 906             return new Lookup(lookupClass(), newModes);
 907         }
 908 
 909         /**
 910          * Defines a class to the same class loader and in the same runtime package and
 911          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
 912          * {@linkplain #lookupClass() lookup class}.
 913          *
 914          * This method is equivalent to calling
 915          * {@link #defineClass(byte[], ClassProperty[])
 916          * defineClass(bytes, (ClassProperty[])null)}.
 917          *
 918          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
 919          * {@link #PACKAGE PACKAGE} access as default (package) members will be
 920          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
 921          * that the lookup object was created by a caller in the runtime package (or derived
 922          * from a lookup originally created by suitably privileged code to a target class in
 923          * the runtime package). </p>
 924          *
 925          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
 926          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
 927          * same package as the lookup class. </p>
 928          *
 929          * <p> This method does not run the class initializer. The class initializer may
 930          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
 931          * Specification</em>. </p>
 932          *
 933          * <p> If there is a security manager, its {@code checkPermission} method is first called
 934          * to check {@code RuntimePermission("defineClass")}. </p>
 935          *
 936          * @param bytes the class bytes
 937          * @return the {@code Class} object for the class
 938          * @throws IllegalArgumentException the bytes are for a class in a different package
 939          * to the lookup class
 940          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
 941          * @throws LinkageError if the class is malformed ({@code ClassFormatError}), cannot be
 942          * verified ({@code VerifyError}), is already defined, or another linkage error occurs
 943          * @throws SecurityException if denied by the security manager
 944          * @throws NullPointerException if {@code bytes} is {@code null}
 945          * @since 9
 946          * @spec JPMS
 947          * @see Lookup#privateLookupIn
 948          * @see Lookup#dropLookupMode
 949          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
 950          */
 951         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
 952             return defineClass(bytes, (ClassProperty[])null);
 953         }
 954 
 955         /**
 956          * Defines a class to the same class loader and in the same runtime package
 957          * and {@linkplain java.security.ProtectionDomain protection domain} as
 958          * this lookup's {@linkplain #lookupClass() lookup class}.
 959          * The {@code props} parameter specifies the properties of the class.
 960          *
 961          * <p> A class can be defined with the following properties:
 962          * <ul>
 963          * <li>A {@linkplain ClassProperty#NESTMATE <em>nestmate</em>} of the lookup class,
 964          *     i.e. in the same {@linkplain Class#getNestHost nest}
 965          *     of the lookup class.  The class will have access to the private members
 966          *     of all classes and interfaces in the same nest.
 967          *     </li>
 968          * <li>A {@linkplain ClassProperty#HIDDEN <em>hidden</em>} class,
 969          *     i.e. a class cannot be referenced by other classes.
 970          *     A hidden class has the following properties:
 971          *     <ul>
 972          *     <li>Naming:
 973          *     The name of this class is derived from the name of
 974          *     the class in the class bytes so that the class name does not
 975          *     collide with other classes defined to the same class loader.
 976          *     <li>Class resolution:
 977          *     The Java virtual machine does not find a hidden class with
 978          *     its name.  A hidden class can reference its members
 979          *     locally with the name of the class in the class bytes as if
 980          *     a non-hidden class. The name returned by {@link Class#getName()}
 981          *     is not known when the class bytes are generated.
 982          *     <li>Class retransformation:
 983          *     The class is not modifiable by Java agents or tool agents using
 984          *     the <a href="{@docRoot}/../specs/jvmti.html">JVM Tool Interface</a>.
 985          *     </ul>
 986          *     </li>
 987          * <li>A {@linkplain ClassProperty#WEAK <em>weak</em>} class,
 988          *     i.e. a class may be unloaded even if its defining class loader is
 989          *     <a href="../ref/package.html#reachability">reachable</a>,
 990          *     as if the defining class loader would only hold a
 991          *     {@linkplain java.lang.ref.WeakReference weak reference} of
 992          *     the class.
 993          *     A weak class is hidden.  If the {@code WEAK} property is set,
 994          *     then it implies that {@code HIDDEN} property is also set.</li>
 995          * </ul>
 996          *
 997          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must
 998          * include {@link #PACKAGE PACKAGE} access as default (package) members
 999          * will be accessible to the class. The {@code PACKAGE} lookup mode serves
1000          * to authenticate that the lookup object was created by a caller in
1001          * the runtime package (or derived from a lookup originally created by
1002          * suitably privileged code to a target class in the runtime package).
1003          * If the class is defined as a {@linkplain ClassProperty#NESTMATE nestmate}
1004          * then the {@linkplain #lookupModes() lookup modes} for this lookup must
1005          * include {@link #PRIVATE PRIVATE} access. </p>
1006          *
1007          * <p> The {@code bytes} parameter is the class bytes of a valid class file
1008          * (as defined by the <em>The Java Virtual Machine Specification</em>)
1009          * with a class name in the same package as the lookup class.
1010          * The class bytes of a nestmate class must not contain
1011          * the {@code NestHost} attribute nor the {@code NestMembers} attribute. </p>
1012          *
1013          * <p> If there is a security manager, its {@code checkPermission} method is first called
1014          * to check {@code RuntimePermission("defineClass")}. </p>
1015          *
1016          * <p> This method does not run the class initializer. The class initializer
1017          * may run at a later time, as detailed in section 12.4 of the The Java Language Specification.
1018          *
1019          * <p> The class can obtain {@code classData} by calling
1020          * the {@link Lookup#classData()} method of its {@code Lookup} object.
1021          *
1022          * @apiNote  An implementation of the Java Progamming Language may
1023          * unload classes as specified in section 12.7 of the Java Language Specification.
1024          * A class or interface may be unloaded if and only if
1025          * its defining class loader may be reclaimed by the garbage collector.
1026          * If the implementation supports class loading, a weak class
1027          * may become weakly reachable as if the defining class loader would
1028          * only hold a {@linkplain java.lang.ref.WeakReference weak reference}
1029          * of the class.
1030          *
1031          * @param bytes      the class bytes
1032          * @param props {@linkplain ClassProperty class properties}
1033          * @return the {@code Class} object for the class
1034          *
1035          * @throws IllegalArgumentException the bytes are for a class in a different package
1036          *                                  to the lookup class
1037          * @throws IllegalAccessException   if this lookup does not have {@code PACKAGE} access, or
1038          *                                  if {@code properties} contains {@code NESTMATE} but this lookup
1039          *                                  does not have {@code PRIVATE} access
1040          * @throws LinkageError             if the class is malformed ({@code ClassFormatError}), cannot be
1041          *                                  verified ({@code VerifyError}), is already defined,
1042          *                                  or another linkage error occurs
1043          * @throws SecurityException        if denied by the security manager
1044          * @throws NullPointerException     if {@code bytes} is {@code null}
1045          *
1046          * @since 12
1047          * @jls 12.7 Unloading of Classes and Interfaces
1048          * @see Lookup#privateLookupIn(Class, Lookup)
1049          * @see Lookup#dropLookupMode(int)
1050          */
1051         public Class<?> defineClass(byte[] bytes, ClassProperty... props) throws IllegalAccessException {
1052             Objects.requireNonNull(bytes);
1053 
1054             // clone the properties before access
1055             Set<ClassProperty> properties;
1056             if (props == null || props.length == 0) {
1057                 properties = EMPTY_PROPS;
1058             } else {
1059                 properties = Set.of(props);
1060             }
1061 
1062             // Is it ever possible to create Lookup for int.class or Object[].class?
1063             assert !lookupClass.isPrimitive() && !lookupClass.isArray();
1064 
1065             if ((lookupModes() & PACKAGE) == 0){
1066                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1067             }
1068 
1069             if (properties.contains(NESTMATE) && (lookupModes() & PRIVATE) == 0){
1070                 throw new IllegalAccessException("Lookup does not have PRIVATE access");
1071             }
1072 
1073             assert (lookupModes() & (MODULE | PUBLIC)) != 0;
1074 
1075             SecurityManager sm = System.getSecurityManager();
1076             if (sm != null)
1077                 sm.checkPermission(new RuntimePermission("defineClass"));
1078 
1079             return defineClassWithNoCheck(bytes, classPropertiesToFlags(properties));
1080         }
1081 
1082         /**
1083          * Defines a class to the same class loader and in the same runtime package
1084          * and {@linkplain java.security.ProtectionDomain protection domain} as
1085          * this lookup's {@linkplain #lookupClass() lookup class} with
1086          * the given class properties and {@code classData}.
1087          *
1088          * <p> This method defines a class as if calling
1089          * {@link #defineClass(byte[], ClassProperty...) defineClass(bytes, props)}
1090          * and then the class initializer with an injected the {@code classData}
1091          * as a pre-initialized static unnamed field.
1092          * The injected pre-initialized static unnamed field can be
1093          * obtained by calling the {@link Lookup#classData()} method of
1094          * its {@code Lookup} object.
1095          *
1096          * <p> If there is a security manager, its {@code checkPermission} method is first called
1097          * to check {@code RuntimePermission("defineClass")}. </p>
1098          *
1099          * @apiNote
1100          * This method initializes the class, as opposed to the {@link #defineClass(byte[], ClassProperty...)}
1101          * method which does not invoke {@code <clinit>}, because the returned {@code Class}
1102          * is as if it contains a private static unnamed field that is initialized to
1103          * the given {@code classData} along with other declared static fields
1104          * via {@code <clinit>}.
1105          *
1106          * @param bytes      the class bytes
1107          * @param classData pre-initialized class data
1108          * @param props {@linkplain ClassProperty class properties}
1109          * @return the {@code Class} object for the class
1110          *
1111          * @throws IllegalArgumentException the bytes are for a class in a different package
1112          *                                  to the lookup class
1113          * @throws IllegalAccessException   if this lookup does not have {@code PACKAGE} access, or
1114          *                                  if {@code properties} contains {@code NESTMATE} but this lookup
1115          *                                  does not have {@code PRIVATE} access
1116          * @throws LinkageError             if the class is malformed ({@code ClassFormatError}), cannot be
1117          *                                  verified ({@code VerifyError}), is already defined,
1118          *                                  or another linkage error occurs
1119          * @throws SecurityException        if denied by the security manager
1120          * @throws NullPointerException     if {@code bytes} or {@code classData} is {@code null}
1121          *
1122          * @since 12
1123          * @jls 12.7 Unloading of Classes and Interfaces
1124          * @see Lookup#privateLookupIn(Class, Lookup)
1125          * @see Lookup#dropLookupMode(int)
1126          */
1127         public Class<?> defineClassWithClassData(byte[] bytes, Object classData, ClassProperty... props)
1128                 throws IllegalAccessException
1129         {
1130             Objects.requireNonNull(bytes);
1131             Objects.requireNonNull(classData);
1132 
1133             // Is it ever possible to create Lookup for int.class or Object[].class?
1134             assert !lookupClass.isPrimitive() && !lookupClass.isArray();
1135 
1136             if ((lookupModes() & PACKAGE) == 0){
1137                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1138             }
1139 
1140             Set<ClassProperty> properties;
1141             if (props == null || props.length == 0) {
1142                 properties = EMPTY_PROPS;
1143             } else {
1144                 properties = Set.of(props);
1145             }
1146 
1147             if (properties.contains(NESTMATE) && (lookupModes() & PRIVATE) == 0){
1148                 throw new IllegalAccessException("Lookup does not have PRIVATE access");
1149             }
1150 
1151             assert (lookupModes() & (MODULE | PUBLIC)) != 0;
1152 
1153             SecurityManager sm = System.getSecurityManager();
1154             if (sm != null)
1155                 sm.checkPermission(new RuntimePermission("defineClass"));
1156 
1157             return defineClassWithNoCheck(bytes, classPropertiesToFlags(properties), classData);
1158         }
1159 
1160         private static int classPropertiesToFlags(Set<ClassProperty> props) {
1161             if (props.isEmpty()) return 0;
1162 
1163             int flags = 0;
1164             for (ClassProperty cp : props) {
1165                 flags |= cp.flag;
1166                 if (cp == WEAK) {
1167                     // weak class property implies hidden
1168                     flags |= HIDDEN.flag;
1169                 }
1170             }
1171             return flags;
1172         }
1173 
1174         /**
1175          * Returns the class data associated with this lookup class.
1176          * If this lookup class was defined via
1177          * {@link #defineClassWithClassData(byte[], Object, ClassProperty...)
1178          * defineClassWithClassData(bytes, classData, properties)}
1179          * then the supplied {@code classData} object is returned; otherwise,
1180          * {@code null}.
1181          *
1182          * <p> This method will invoke the static class initializer of
1183          * this lookup class if it has not been initialized.
1184          *
1185          * @apiNote
1186          * A class data can be considered as
1187          * private static unnamed field that has been pre-initialized
1188          * and supplied at define class time.
1189          *
1190          * <p> For example a class can pack one or more pre-initialized objects
1191          * in a {@code List} as the class data and at class initialization
1192          * time unpack them for subsequent access.
1193          * The class data is {@code List.of(o1, o2, o3....)}
1194          * passed to {@link #defineClassWithClassData(byte[], Object, ClassProperty...)} where
1195          * {@code <clinit>} of the class bytes does the following:
1196          *
1197          * <pre>{@code
1198          *     private static final T t;
1199          *     private static final R r;
1200          *     static {
1201          *        List<Object> data = (List<Object>) MethodHandles.lookup().classData();
1202          *        t = (T)data.get(0);
1203          *        r = (R)data.get(1);
1204          *     }
1205          *}</pre>
1206          *
1207          * @return the class data if this lookup class was defined via
1208          * {@link #defineClassWithClassData(byte[], Object, ClassProperty...)}; otherwise {@code null}.
1209          *
1210          * @throws IllegalAccessException if this lookup does not have {@code PRIVATE} access
1211          * @since 12
1212          */
1213         public Object classData() throws IllegalAccessException {
1214             if ((lookupModes() & PRIVATE) == 0){
1215                 throw new IllegalAccessException("Lookup does not have PRIVATE access");
1216             }
1217 
1218             // should we allow clearing?  getAndClearClassData
1219             return MethodHandleNatives.classData(lookupClass);
1220         }
1221 
1222         // package-private
1223         static final int HIDDEN_NESTMATE = NESTMATE_CLASS|NONFINDABLE_CLASS|ACCESS_VM_ANNOTATIONS;
1224         static final int WEAK_HIDDEN_NESTMATE =  WEAK_CLASS|NESTMATE_CLASS|NONFINDABLE_CLASS|ACCESS_VM_ANNOTATIONS;
1225         static final Set<ClassProperty> EMPTY_PROPS = Set.of();
1226 
1227         Class<?> defineClassWithNoCheck(byte[] bytes, int flags) {
1228             return defineClassWithNoCheck(bytes, flags, null);
1229         }
1230 
1231         Class<?> defineClassWithNoCheck(byte[] bytes, int flags, Object classData) {
1232             // Can't use lambda during bootstrapping
1233             // parse class bytes to get class name (in internal form)
1234             bytes = bytes.clone();
1235             String name;
1236             try {
1237                 ClassReader reader = new ClassReader(bytes);
1238                 name = reader.getClassName();
1239             } catch (RuntimeException e) {
1240                 // ASM exceptions are poorly specified
1241                 ClassFormatError cfe = new ClassFormatError();
1242                 cfe.initCause(e);
1243                 throw cfe;
1244             }
1245 
1246             // get package and class name in binary form
1247             String cn, pn;
1248             int index = name.lastIndexOf('/');
1249             if (index == -1) {
1250                 cn = name;
1251                 pn = "";
1252             } else {
1253                 cn = name.replace('/', '.');
1254                 pn = cn.substring(0, index);
1255             }
1256             if (!pn.equals(lookupClass.getPackageName())) {
1257                 throw new IllegalArgumentException(cn + " not in same package as lookup class: " + lookupClass.getName());
1258             }
1259 
1260             if ((flags & NONFINDABLE_CLASS) != 0) {
1261                 // ## TODO use '/' as in the name of the VM anonymous class.
1262                 cn = cn + '\\' + ++seq;
1263             }
1264 
1265             // invoke the class loader's defineClass method
1266             ClassLoader loader = lookupClass.getClassLoader();
1267             ProtectionDomain pd = (loader != null) ? lookupClassProtectionDomain() : null;
1268             Class<?> clazz = JLA.defineClass(loader, lookupClass, cn, bytes, pd, flags, classData);
1269             assert clazz.getClassLoader() == lookupClass.getClassLoader()
1270                    && clazz.getPackageName().equals(lookupClass.getPackageName());
1271 
1272             return clazz;
1273         }
1274 
1275         private static volatile int seq = 0;
1276 
1277         private ProtectionDomain lookupClassProtectionDomain() {
1278             ProtectionDomain pd = cachedProtectionDomain;
1279             if (pd == null) {
1280                 cachedProtectionDomain = pd = JLA.protectionDomain(lookupClass);
1281             }
1282             return pd;
1283         }
1284 





1285         // cached protection domain
1286         private volatile ProtectionDomain cachedProtectionDomain;
1287 

1288         // Make sure outer class is initialized first.
1289         static { IMPL_NAMES.getClass(); }
1290 
1291         /** Package-private version of lookup which is trusted. */
1292         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED);
1293 
1294         /** Version of lookup which is trusted minimally.
1295          *  It can only be used to create method handles to publicly accessible
1296          *  members in packages that are exported unconditionally.
1297          */
1298         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, (PUBLIC|UNCONDITIONAL));
1299 
1300         static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
1301 
1302         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
1303             String name = lookupClass.getName();
1304             if (name.startsWith("java.lang.invoke."))
1305                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
1306         }
1307 
1308         /**
1309          * Displays the name of the class from which lookups are to be made.
1310          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
1311          * If there are restrictions on the access permitted to this lookup,
1312          * this is indicated by adding a suffix to the class name, consisting
1313          * of a slash and a keyword.  The keyword represents the strongest
1314          * allowed access, and is chosen as follows:
1315          * <ul>
1316          * <li>If no access is allowed, the suffix is "/noaccess".
1317          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
1318          * <li>If only public access and unconditional access are allowed, the suffix is "/publicLookup".
1319          * <li>If only public and module access are allowed, the suffix is "/module".
1320          * <li>If only public, module and package access are allowed, the suffix is "/package".
1321          * <li>If only public, module, package, and private access are allowed, the suffix is "/private".


1563         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1564             if (refc.isArray()) {
1565                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
1566             }
1567             String name = "<init>";
1568             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
1569             return getDirectConstructor(refc, ctor);
1570         }
1571 
1572         /**
1573          * Looks up a class by name from the lookup context defined by this {@code Lookup} object. The static
1574          * initializer of the class is not run.
1575          * <p>
1576          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, its class
1577          * loader, and the {@linkplain #lookupModes() lookup modes}. In particular, the method first attempts to
1578          * load the requested class, and then determines whether the class is accessible to this lookup object.
1579          *
1580          * @param targetName the fully qualified name of the class to be looked up.
1581          * @return the requested class.
1582          * @exception SecurityException if a security manager is present and it
1583          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1584          * @throws LinkageError if the linkage fails
1585          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader
1586          *                                or the class is not {@linkplain Class#isHidden hidden}
1587          * @throws IllegalAccessException if the class is not accessible, using the allowed access modes.
1588 

1589          * @since 9
1590          * @see Class#isHidden
1591          */
1592         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
1593             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
1594             return accessClass(targetClass);
1595         }
1596 
1597         /**
1598          * Determines if a class can be accessed from the lookup context defined by this {@code Lookup} object. The
1599          * static initializer of the class is not run.
1600          * <p>
1601          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class} and the
1602          * {@linkplain #lookupModes() lookup modes}.
1603          *
1604          * @param targetClass the class to be access-checked
1605          *
1606          * @return the class that has been access-checked
1607          *
1608          * @throws IllegalAccessException if the class is not accessible from the lookup class, using the allowed access
1609          * modes.
1610          * @exception SecurityException if a security manager is present and it


2831             } catch (SecurityException ex) {
2832                 return false;
2833             }
2834             return true;
2835         }
2836         private
2837         MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
2838                 throws ReflectiveOperationException {
2839             if (MethodHandleNatives.refKindIsField(refKind)) {
2840                 return getDirectFieldNoSecurityManager(refKind, defc, member);
2841             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
2842                 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass);
2843             } else if (refKind == REF_newInvokeSpecial) {
2844                 return getDirectConstructorNoSecurityManager(defc, member);
2845             }
2846             // oops
2847             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
2848         }
2849 
2850         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
2851 
2852         /**
2853          * Property of a class to be defined via the
2854          * {@link Lookup#defineClass(byte[], ClassProperty[]) Lookup.defineClass} method.
2855          *
2856          * @since 12
2857          * @see Lookup#defineClass(byte[], ClassProperty[])
2858          * @see Lookup#defineClassWithClassData(byte[], Object, ClassProperty[])
2859          */
2860         public enum ClassProperty {
2861             /**
2862              * A nestmate is a class that is in the same {@linkplain Class#getNestHost nest}
2863              * of a lookup class.  It has access to the private members of all
2864              * classes and interfaces in the same nest.
2865              *
2866              * @see Class#getNestHost()
2867              */
2868             NESTMATE(NESTMATE_CLASS),
2869 
2870             /**
2871              * A hidden class is a class that cannot be referenced by other
2872              * classes.  A Java Virtual Machine implementation may hide
2873              * the hidden frames from {@linkplain Throwable#getStackTrace()
2874              * stack traces}.
2875              *
2876              * @see Class#isHidden()
2877              * @see StackWalker.Option#SHOW_HIDDEN_FRAMES
2878              */
2879             HIDDEN(NONFINDABLE_CLASS),
2880 
2881             /**
2882              * A weak class is a class that may be unloaded even if
2883              * its defining class loader is
2884              * <a href="../ref/package.html#reachability">reachable</a>.
2885              * A weak class is {@linkplain #HIDDEN hidden}.
2886              *
2887              * @jls 12.7 Unloading of Classes and Interfaces
2888              */
2889             WEAK(WEAK_CLASS);
2890 
2891             /* the flag value is used by VM at define class time */
2892             final int flag;
2893             ClassProperty(int flag) {
2894                 this.flag = flag;
2895             }
2896         }
2897     }
2898 
2899     /**
2900      * Produces a method handle constructing arrays of a desired type,
2901      * as if by the {@code anewarray} bytecode.
2902      * The return type of the method handle will be the array type.
2903      * The type of its sole argument will be {@code int}, which specifies the size of the array.
2904      *
2905      * <p> If the returned method handle is invoked with a negative
2906      * array size, a {@code NegativeArraySizeException} will be thrown.
2907      *
2908      * @param arrayClass an array type
2909      * @return a method handle which can create arrays of the given type
2910      * @throws NullPointerException if the argument is {@code null}
2911      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
2912      * @see java.lang.reflect.Array#newInstance(Class, int)
2913      * @jvms 6.5 {@code anewarray} Instruction
2914      * @since 9
2915      */
2916     public static


< prev index next >