< 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:


 202      * {@code null} previous lookup class.
 203      * <p>
 204      * Otherwise, {@code M1} and {@code M2} are two different modules.  This method
 205      * returns a {@code Lookup} on {@code targetClass} that records
 206      * the lookup class of the caller as the new previous lookup class and
 207      * drops {@code MODULE} access from the full privilege access.
 208      *
 209      * @param targetClass the target class
 210      * @param caller the caller lookup object
 211      * @return a lookup object for the target class, with private access
 212      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
 213      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 214      * @throws SecurityException if denied by the security manager
 215      * @throws IllegalAccessException if any of the other access checks specified above fails
 216      * @since 9
 217      * @spec JPMS
 218      * @see Lookup#dropLookupMode
 219      * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
 220      */
 221     public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {




 222         SecurityManager sm = System.getSecurityManager();
 223         if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
 224         if (targetClass.isPrimitive())
 225             throw new IllegalArgumentException(targetClass + " is a primitive class");
 226         if (targetClass.isArray())
 227             throw new IllegalArgumentException(targetClass + " is an array class");
 228         // Ensure that we can reason accurately about private and module access.
 229         if (!caller.hasFullPrivilegeAccess())
 230             throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode");
 231 
 232         // previous lookup class is never set if it has MODULE access
 233         assert caller.previousLookupClass() == null;
 234 
 235         Class<?> callerClass = caller.lookupClass();
 236         Module callerModule = callerClass.getModule();  // M1
 237         Module targetModule = targetClass.getModule();  // M2
 238         Class<?> newPreviousClass = null;
 239         int newModes = Lookup.FULL_POWER_MODES;
 240 
 241         if (targetModule != callerModule) {


 246                 assert !pn.isEmpty() : "unnamed package cannot be in named module";
 247                 if (!targetModule.isOpen(pn, callerModule))
 248                     throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 249             }
 250 
 251             // M2 != M1, set previous lookup class to M1 and drop MODULE access
 252             newPreviousClass = callerClass;
 253             newModes &= ~Lookup.MODULE;
 254         }
 255 
 256         if (!callerModule.isNamed() && targetModule.isNamed()) {
 257             IllegalAccessLogger logger = IllegalAccessLogger.illegalAccessLogger();
 258             if (logger != null) {
 259                 logger.logIfOpenedForIllegalAccess(caller, targetClass);
 260             }
 261         }
 262         return Lookup.newLookup(targetClass, newPreviousClass, newModes);
 263     }
 264 
 265     /**



















































 266      * Performs an unchecked "crack" of a
 267      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 268      * The result is as if the user had obtained a lookup object capable enough
 269      * to crack the target method handle, called
 270      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 271      * on the target to obtain its symbolic reference, and then called
 272      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 273      * to resolve the symbolic reference to a member.
 274      * <p>
 275      * If there is a security manager, its {@code checkPermission} method
 276      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 277      * @param <T> the desired type of the result, either {@link Member} or a subtype
 278      * @param target a direct method handle to crack into symbolic reference components
 279      * @param expected a class object representing the desired result type {@code T}
 280      * @return a reference to the method, constructor, or field object
 281      * @throws    SecurityException if the caller is not privileged to call {@code setAccessible}
 282      * @throws    NullPointerException if either argument is {@code null}
 283      * @throws    IllegalArgumentException if the target is not a direct method handle
 284      * @throws    ClassCastException if the member is not of the expected type
 285      * @since 1.8


1383          *  so that it can access only names which can be reached by the original
1384          *  lookup object, and also by the new lookup class.
1385          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1386          *  @see #in
1387          *  @see #dropLookupMode
1388          *
1389          *  @revised 9
1390          *  @spec JPMS
1391          */
1392         public int lookupModes() {
1393             return allowedModes & ALL_MODES;
1394         }
1395 
1396         /** Embody the current class (the lookupClass) as a lookup class
1397          * for method handle creation.
1398          * Must be called by from a method in this package,
1399          * which in turn is called by a method not in this package.
1400          */
1401         Lookup(Class<?> lookupClass) {
1402             this(lookupClass, null, FULL_POWER_MODES);
1403             // make sure we haven't accidentally picked up a privileged class:
1404             checkUnprivilegedlookupClass(lookupClass);
1405         }
1406 
1407         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1408             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1409                     && prevLookupClass.getModule() != lookupClass.getModule());
1410             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1411             this.lookupClass = lookupClass;
1412             this.prevLookupClass = prevLookupClass;
1413             this.allowedModes = allowedModes;
1414         }
1415 
1416         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1417             // make sure we haven't accidentally picked up a privileged class:
1418             checkUnprivilegedlookupClass(lookupClass);
1419             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1420         }
1421 
1422         /**
1423          * Creates a lookup on the specified new lookup class.
1424          * The resulting object will report the specified


1560          * @see MethodHandles#privateLookupIn
1561          * @since 9
1562          */
1563         public Lookup dropLookupMode(int modeToDrop) {
1564             int oldModes = lookupModes();
1565             int newModes = oldModes & ~(modeToDrop | PROTECTED);
1566             switch (modeToDrop) {
1567                 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1568                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1569                 case PACKAGE: newModes &= ~(PRIVATE); break;
1570                 case PROTECTED:
1571                 case PRIVATE:
1572                 case UNCONDITIONAL: break;
1573                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1574             }
1575             if (newModes == oldModes) return this;  // return self if no change
1576             return newLookup(lookupClass(), previousLookupClass(), newModes);
1577         }
1578 
1579         /**
1580          * Defines a class to the same class loader and in the same runtime package and

1581          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1582          * {@linkplain #lookupClass() lookup class}.


1583          *
1584          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1585          * {@link #PACKAGE PACKAGE} access as default (package) members will be
1586          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1587          * that the lookup object was created by a caller in the runtime package (or derived
1588          * from a lookup originally created by suitably privileged code to a target class in
1589          * the runtime package). </p>
1590          *
1591          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1592          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1593          * same package as the lookup class. </p>
1594          *
1595          * <p> This method does not run the class initializer. The class initializer may
1596          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
1597          * Specification</em>. </p>
1598          *
1599          * <p> If there is a security manager and this lookup does not have {@linkplain
1600          * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method
1601          * is first called to check {@code RuntimePermission("defineClass")}. </p>
1602          *
1603          * @param bytes the class bytes
1604          * @return the {@code Class} object for the class
1605          * @throws IllegalArgumentException the bytes are for a class in a different package
1606          * to the lookup class
1607          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1608          * @throws LinkageError if the class is malformed ({@code ClassFormatError}), cannot be
1609          * verified ({@code VerifyError}), is already defined, or another linkage error occurs
1610          * @throws SecurityException if a security manager is present and it
1611          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1612          * @throws NullPointerException if {@code bytes} is {@code null}
1613          * @since 9
1614          * @spec JPMS
1615          * @see Lookup#privateLookupIn
1616          * @see Lookup#dropLookupMode
1617          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1618          */
1619         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {









1620             if (!hasFullPrivilegeAccess()) {
1621                 SecurityManager sm = System.getSecurityManager();
1622                 if (sm != null)
1623                     sm.checkPermission(new RuntimePermission("defineClass"));
1624             }
1625             if ((lookupModes() & PACKAGE) == 0)
1626                 throw new IllegalAccessException("Lookup does not have PACKAGE access");



































































































































































































































































































































































































































1627 
1628             // parse class bytes to get class name (in internal form)
1629             bytes = bytes.clone();
1630             String name;
1631             try {
1632                 ClassReader reader = new ClassReader(bytes);
1633                 name = reader.getClassName();






1634             } catch (RuntimeException e) {
1635                 // ASM exceptions are poorly specified
1636                 ClassFormatError cfe = new ClassFormatError();
1637                 cfe.initCause(e);
1638                 throw cfe;
1639             }
1640 
1641             // get package and class name in binary form
1642             String cn, pn;
1643             int index = name.lastIndexOf('/');
1644             if (index == -1) {
1645                 cn = name;
1646                 pn = "";
1647             } else {
1648                 cn = name.replace('/', '.');
1649                 pn = cn.substring(0, index);
1650             }
1651             if (!pn.equals(lookupClass.getPackageName())) {
1652                 throw new IllegalArgumentException("Class not in same package as lookup class");
1653             }
1654 
1655             // invoke the class loader's defineClass method
1656             ClassLoader loader = lookupClass.getClassLoader();
1657             ProtectionDomain pd = (loader != null) ? lookupClassProtectionDomain() : null;
1658             String source = "__Lookup_defineClass__";
1659             Class<?> clazz = SharedSecrets.getJavaLangAccess().defineClass(loader, cn, bytes, pd, source);
1660             return clazz;
1661         }
1662 
1663         private ProtectionDomain lookupClassProtectionDomain() {
1664             ProtectionDomain pd = cachedProtectionDomain;
1665             if (pd == null) {
1666                 cachedProtectionDomain = pd = protectionDomain(lookupClass);
1667             }
1668             return pd;
1669         }
1670 
1671         private ProtectionDomain protectionDomain(Class<?> clazz) {
1672             PrivilegedAction<ProtectionDomain> pa = clazz::getProtectionDomain;
1673             return AccessController.doPrivileged(pa);
1674         }
1675 
1676         // cached protection domain
1677         private volatile ProtectionDomain cachedProtectionDomain;
1678 
1679 
1680         // Make sure outer class is initialized first.
1681         static { IMPL_NAMES.getClass(); }
1682 
1683         /** Package-private version of lookup which is trusted. */
1684         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
1685 
1686         /** Version of lookup which is trusted minimally.
1687          *  It can only be used to create method handles to publicly accessible
1688          *  members in packages that are exported unconditionally.
1689          */
1690         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
1691 


1692         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
1693             String name = lookupClass.getName();
1694             if (name.startsWith("java.lang.invoke."))
1695                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
1696         }
1697 
1698         /**
1699          * Displays the name of the class from which lookups are to be made.
1700          * followed with "/" and the name of the {@linkplain #previousLookupClass()
1701          * previous lookup class} if present.
1702          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
1703          * If there are restrictions on the access permitted to this lookup,
1704          * this is indicated by adding a suffix to the class name, consisting
1705          * of a slash and a keyword.  The keyword represents the strongest
1706          * allowed access, and is chosen as follows:
1707          * <ul>
1708          * <li>If no access is allowed, the suffix is "/noaccess".
1709          * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
1710          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
1711          * <li>If only public and module access are allowed, the suffix is "/module".


2622          * the {@code Field} object's {@code set} method could return
2623          * normally.  In particular, fields which are both {@code static}
2624          * and {@code final} may never be set.
2625          * <p>
2626          * If the field is {@code static}, and
2627          * if the returned method handle is invoked, the field's class will
2628          * be initialized, if it has not already been initialized.
2629          * @param f the reflected field
2630          * @return a method handle which can store values into the reflected field
2631          * @throws IllegalAccessException if access checking fails,
2632          *         or if the field is {@code final} and write access
2633          *         is not enabled on the {@code Field} object
2634          * @throws NullPointerException if the argument is null
2635          */
2636         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
2637             return unreflectField(f, true);
2638         }
2639 
2640         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
2641             MemberName field = new MemberName(f, isSetter);
2642             if (isSetter && field.isStatic() && field.isFinal())

2643                 throw field.makeAccessException("static final field has no write access", this);




2644             assert(isSetter
2645                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
2646                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
2647             @SuppressWarnings("deprecation")
2648             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
2649             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
2650         }
2651 
2652         /**
2653          * Produces a VarHandle giving access to a reflected field {@code f}
2654          * of type {@code T} declared in a class of type {@code R}.
2655          * The VarHandle's variable type is {@code T}.
2656          * If the field is non-static the VarHandle has one coordinate type,
2657          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
2658          * coordinate types.
2659          * <p>
2660          * Access checking is performed immediately on behalf of the lookup
2661          * class, regardless of the value of the field's {@code accessible}
2662          * flag.
2663          * <p>


3184             if (!putField.isFinal()) {
3185                 // A VarHandle does not support updates to final fields, any
3186                 // such VarHandle to a final field will be read-only and
3187                 // therefore the following write-based accessibility checks are
3188                 // only required for non-final fields
3189                 checkField(putRefKind, refc, putField);
3190                 if (checkSecurity)
3191                     checkSecurityManager(refc, putField);
3192             }
3193 
3194             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
3195                                   restrictProtectedReceiver(getField));
3196             if (doRestrict) {
3197                 assert !getField.isStatic();
3198                 // receiver type of VarHandle is too wide; narrow to caller
3199                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
3200                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
3201                 }
3202                 refc = lookupClass();
3203             }
3204             return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), this.allowedModes == TRUSTED);

3205         }
3206         /** Check access and get the requested constructor. */
3207         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
3208             final boolean checkSecurity = true;
3209             return getDirectConstructorCommon(refc, ctor, checkSecurity);
3210         }
3211         /** Check access and get the requested constructor, eliding security manager checks. */
3212         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
3213             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
3214             return getDirectConstructorCommon(refc, ctor, checkSecurity);
3215         }
3216         /** Common code for all constructors; do not call directly except from immediately above. */
3217         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
3218                                                   boolean checkSecurity) throws IllegalAccessException {
3219             assert(ctor.isConstructor());
3220             checkAccess(REF_newInvokeSpecial, refc, ctor);
3221             // Optionally check with the security manager; this isn't needed for unreflect* calls.
3222             if (checkSecurity)
3223                 checkSecurityManager(refc, ctor);
3224             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here


3296                 checkSecurityManager(defc, resolved2);
3297             } catch (SecurityException ex) {
3298                 return false;
3299             }
3300             return true;
3301         }
3302         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
3303                 throws ReflectiveOperationException {
3304             if (MethodHandleNatives.refKindIsField(refKind)) {
3305                 return getDirectFieldNoSecurityManager(refKind, defc, member);
3306             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
3307                 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member));
3308             } else if (refKind == REF_newInvokeSpecial) {
3309                 return getDirectConstructorNoSecurityManager(defc, member);
3310             }
3311             // oops
3312             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
3313         }
3314 
3315         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();























































3316     }
3317 
3318     /**
3319      * Produces a method handle constructing arrays of a desired type,
3320      * as if by the {@code anewarray} bytecode.
3321      * The return type of the method handle will be the array type.
3322      * The type of its sole argument will be {@code int}, which specifies the size of the array.
3323      *
3324      * <p> If the returned method handle is invoked with a negative
3325      * array size, a {@code NegativeArraySizeException} will be thrown.
3326      *
3327      * @param arrayClass an array type
3328      * @return a method handle which can create arrays of the given type
3329      * @throws NullPointerException if the argument is {@code null}
3330      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
3331      * @see java.lang.reflect.Array#newInstance(Class, int)
3332      * @jvms 6.5 {@code anewarray} Instruction
3333      * @since 9
3334      */
3335     public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {




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


  51 import java.security.ProtectionDomain;
  52 import java.util.ArrayList;
  53 import java.util.Arrays;
  54 import java.util.BitSet;
  55 import java.util.Iterator;
  56 import java.util.List;
  57 import java.util.Objects;
  58 import java.util.Set;
  59 import java.util.concurrent.ConcurrentHashMap;
  60 import java.util.stream.Collectors;
  61 import java.util.stream.Stream;
  62 
  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:


 203      * {@code null} previous lookup class.
 204      * <p>
 205      * Otherwise, {@code M1} and {@code M2} are two different modules.  This method
 206      * returns a {@code Lookup} on {@code targetClass} that records
 207      * the lookup class of the caller as the new previous lookup class and
 208      * drops {@code MODULE} access from the full privilege access.
 209      *
 210      * @param targetClass the target class
 211      * @param caller the caller lookup object
 212      * @return a lookup object for the target class, with private access
 213      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
 214      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 215      * @throws SecurityException if denied by the security manager
 216      * @throws IllegalAccessException if any of the other access checks specified above fails
 217      * @since 9
 218      * @spec JPMS
 219      * @see Lookup#dropLookupMode
 220      * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
 221      */
 222     public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
 223         if (caller.allowedModes == Lookup.TRUSTED) {
 224             return new Lookup(targetClass);
 225         }
 226 
 227         SecurityManager sm = System.getSecurityManager();
 228         if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
 229         if (targetClass.isPrimitive())
 230             throw new IllegalArgumentException(targetClass + " is a primitive class");
 231         if (targetClass.isArray())
 232             throw new IllegalArgumentException(targetClass + " is an array class");
 233         // Ensure that we can reason accurately about private and module access.
 234         if (!caller.hasFullPrivilegeAccess())
 235             throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode");
 236 
 237         // previous lookup class is never set if it has MODULE access
 238         assert caller.previousLookupClass() == null;
 239 
 240         Class<?> callerClass = caller.lookupClass();
 241         Module callerModule = callerClass.getModule();  // M1
 242         Module targetModule = targetClass.getModule();  // M2
 243         Class<?> newPreviousClass = null;
 244         int newModes = Lookup.FULL_POWER_MODES;
 245 
 246         if (targetModule != callerModule) {


 251                 assert !pn.isEmpty() : "unnamed package cannot be in named module";
 252                 if (!targetModule.isOpen(pn, callerModule))
 253                     throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 254             }
 255 
 256             // M2 != M1, set previous lookup class to M1 and drop MODULE access
 257             newPreviousClass = callerClass;
 258             newModes &= ~Lookup.MODULE;
 259         }
 260 
 261         if (!callerModule.isNamed() && targetModule.isNamed()) {
 262             IllegalAccessLogger logger = IllegalAccessLogger.illegalAccessLogger();
 263             if (logger != null) {
 264                 logger.logIfOpenedForIllegalAccess(caller, targetClass);
 265             }
 266         }
 267         return Lookup.newLookup(targetClass, newPreviousClass, newModes);
 268     }
 269 
 270     /**
 271      * Returns the <em>class data</em> associated with the lookup class
 272      * of the specified {@code Lookup} object, or {@code null}.
 273      *
 274      * <p> Classes can be created with class data by calling
 275      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, Lookup.ClassOption...)
 276      * Lookup::defineHiddenClassWithClassData}.
 277      * A hidden class with a class data behaves as if the hidden class
 278      * has a private static final unnamed field pre-initialized with
 279      * the class data and this method is equivalent as if calling
 280      * {@link ConstantBootstraps#getStaticFinal(Lookup, String, Class)} to
 281      * obtain the value of such field corresponding to the class data.
 282      *
 283      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 284      * must have {@link Lookup#ORIGINAL ORIGINAL} access in order to retrieve
 285      * the class data.
 286      *
 287      * @apiNote
 288      * This method can be called as a bootstrap method for a dynamically computed
 289      * constant.  A framework can create a hidden class with class data, for
 290      * example that can be {@code List.of(o1, o2, o3....)} containing more than
 291      * one live object.  The class data is accessible only to the lookup object
 292      * created by the original caller but inaccessible to other members
 293      * in the same nest.  If a framework passes security sensitive live objects
 294      * to a hidden class via class data, it is recommended to load the value
 295      * of class data as a dynamically computed constant instead of storing
 296      * the live objects in private fields which are accessible to other
 297      * nestmates.
 298      *
 299      * @param <T> the type to cast the class data object to
 300      * @param caller the lookup context describing the class performing the
 301      * operation (normally stacked by the JVM)
 302      * @param name ignored
 303      * @param type the type of the class data
 304      * @return the value of the class data if present in the lookup class;
 305      * otherwise {@code null}
 306      * @throws IllegalAccessException if the lookup context does not have
 307      * original caller access
 308      * @throws ClassCastException if the class data cannot be converted to
 309      * the specified {@code type}
 310      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, Lookup.ClassOption...)
 311      * @since 15
 312      */
 313     static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException {
 314         if (!caller.hasFullPrivilegeAccess()) {
 315             throw new IllegalAccessException(caller + " does not have full privilege access");
 316         }
 317         Object classData = MethodHandleNatives.classData(caller.lookupClass);
 318         return type.cast(classData);
 319     }
 320 
 321     /**
 322      * Performs an unchecked "crack" of a
 323      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 324      * The result is as if the user had obtained a lookup object capable enough
 325      * to crack the target method handle, called
 326      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 327      * on the target to obtain its symbolic reference, and then called
 328      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 329      * to resolve the symbolic reference to a member.
 330      * <p>
 331      * If there is a security manager, its {@code checkPermission} method
 332      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 333      * @param <T> the desired type of the result, either {@link Member} or a subtype
 334      * @param target a direct method handle to crack into symbolic reference components
 335      * @param expected a class object representing the desired result type {@code T}
 336      * @return a reference to the method, constructor, or field object
 337      * @throws    SecurityException if the caller is not privileged to call {@code setAccessible}
 338      * @throws    NullPointerException if either argument is {@code null}
 339      * @throws    IllegalArgumentException if the target is not a direct method handle
 340      * @throws    ClassCastException if the member is not of the expected type
 341      * @since 1.8


1439          *  so that it can access only names which can be reached by the original
1440          *  lookup object, and also by the new lookup class.
1441          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1442          *  @see #in
1443          *  @see #dropLookupMode
1444          *
1445          *  @revised 9
1446          *  @spec JPMS
1447          */
1448         public int lookupModes() {
1449             return allowedModes & ALL_MODES;
1450         }
1451 
1452         /** Embody the current class (the lookupClass) as a lookup class
1453          * for method handle creation.
1454          * Must be called by from a method in this package,
1455          * which in turn is called by a method not in this package.
1456          */
1457         Lookup(Class<?> lookupClass) {
1458             this(lookupClass, null, FULL_POWER_MODES);


1459         }
1460 
1461         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1462             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1463                     && prevLookupClass.getModule() != lookupClass.getModule());
1464             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1465             this.lookupClass = lookupClass;
1466             this.prevLookupClass = prevLookupClass;
1467             this.allowedModes = allowedModes;
1468         }
1469 
1470         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1471             // make sure we haven't accidentally picked up a privileged class:
1472             checkUnprivilegedlookupClass(lookupClass);
1473             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1474         }
1475 
1476         /**
1477          * Creates a lookup on the specified new lookup class.
1478          * The resulting object will report the specified


1614          * @see MethodHandles#privateLookupIn
1615          * @since 9
1616          */
1617         public Lookup dropLookupMode(int modeToDrop) {
1618             int oldModes = lookupModes();
1619             int newModes = oldModes & ~(modeToDrop | PROTECTED);
1620             switch (modeToDrop) {
1621                 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1622                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1623                 case PACKAGE: newModes &= ~(PRIVATE); break;
1624                 case PROTECTED:
1625                 case PRIVATE:
1626                 case UNCONDITIONAL: break;
1627                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1628             }
1629             if (newModes == oldModes) return this;  // return self if no change
1630             return newLookup(lookupClass(), previousLookupClass(), newModes);
1631         }
1632 
1633         /**
1634          * Creates and links a class or interface from {@code bytes}
1635          * with the same class loader and in the same runtime package and
1636          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1637          * {@linkplain #lookupClass() lookup class} as if calling
1638          * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1639          * ClassLoader::defineClass}.
1640          *
1641          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1642          * {@link #PACKAGE PACKAGE} access as default (package) members will be
1643          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1644          * that the lookup object was created by a caller in the runtime package (or derived
1645          * from a lookup originally created by suitably privileged code to a target class in
1646          * the runtime package). </p>
1647          *
1648          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1649          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1650          * same package as the lookup class. </p>
1651          *
1652          * <p> This method does not run the class initializer. The class initializer may
1653          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
1654          * Specification</em>. </p>
1655          *
1656          * <p> If there is a security manager and this lookup does not have {@linkplain
1657          * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method
1658          * is first called to check {@code RuntimePermission("defineClass")}. </p>
1659          *
1660          * @param bytes the class bytes
1661          * @return the {@code Class} object for the class
1662          * @throws IllegalArgumentException the bytes are for a class in a different package
1663          * to the lookup class
1664          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1665          * @throws LinkageError if the class is malformed ({@code ClassFormatError}), cannot be
1666          * verified ({@code VerifyError}), is already defined, or another linkage error occurs
1667          * @throws SecurityException if a security manager is present and it
1668          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1669          * @throws NullPointerException if {@code bytes} is {@code null}
1670          * @since 9
1671          * @spec JPMS
1672          * @see Lookup#privateLookupIn
1673          * @see Lookup#dropLookupMode
1674          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1675          */
1676         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1677             ensureDefineClassPermission();
1678             if ((lookupModes() & PACKAGE) == 0)
1679                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1680             return makeClassDefiner(bytes.clone()).defineClass(false);
1681         }
1682 
1683         private void ensureDefineClassPermission() {
1684             if (allowedModes == TRUSTED)  return;
1685 
1686             if (!hasFullPrivilegeAccess()) {
1687                 SecurityManager sm = System.getSecurityManager();
1688                 if (sm != null)
1689                     sm.checkPermission(new RuntimePermission("defineClass"));
1690             }
1691         }
1692 
1693         /**
1694          * Creates a <em>hidden</em> class or interface from {@code bytes},
1695          * returning a {@code Lookup} on the newly created class or interface.
1696          *
1697          * <p> Ordinarily, a class or interface {@code C} is created by a class loader,
1698          * which either defines {@code C} directly or delegates to another class loader.
1699          * A class loader defines {@code C} directly by invoking
1700          * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1701          * ClassLoader::defineClass}, which causes the Java Virtual Machine
1702          * to derive {@code C} from a purported representation in {@code class} file format.
1703          * In situations where use of a class loader is undesirable, a class or interface
1704          * {@code C} can be created by this method instead. This method is capable of
1705          * defining {@code C}, and thereby creating it, without invoking
1706          * {@code ClassLoader::defineClass}.
1707          * Instead, this method defines {@code C} as if by arranging for
1708          * the Java Virtual Machine to derive a nonarray class or interface {@code C}
1709          * from a purported representation in {@code class} file format
1710          * using the following rules:
1711          *
1712          * <ol>
1713          * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup}
1714          * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access.
1715          * This level of access is needed to create {@code C} in the module
1716          * of the lookup class of this {@code Lookup}.</li>
1717          *
1718          * <li> The purported representation in {@code bytes} must be a {@code ClassFile}
1719          * structure of a supported major and minor version. The major and minor version
1720          * may differ from the {@code class} file version of the lookup class of this
1721          * {@code Lookup}.</li>
1722          *
1723          * <li> The value of {@code this_class} must be a valid index in the
1724          * {@code constant_pool} table, and the entry at that index must be a valid
1725          * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name
1726          * encoded in internal form that is specified by this structure. {@code N} must
1727          * denote a class or interface in the same package as the lookup class.</li>
1728          *
1729          * <li> Let {@code CN} be the string {@code N + "." + <suffix>},
1730          * where {@code <suffix>} is an unqualified name that is guaranteed to be unique
1731          * during this execution of the JVM.
1732          *
1733          * <p> Let {@code newBytes} be the {@code ClassFile} structure given by
1734          * {@code bytes} with an additional entry in the {@code constant_pool} table,
1735          * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and
1736          * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class}
1737          * refers to the new {@code CONSTANT_Utf8_info} structure.
1738          *
1739          * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}.
1740          *
1741          * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and
1742          * purported representation {@code newBytes} as if by the rules of JVMS 5.3.5,
1743          * with the following adjustments:
1744          * <ul>
1745          * <li> The constant indicated by {@code this_class} is permitted to specify a name
1746          * that includes a single {@code "."} character, even though this is not a valid
1747          * binary class or interface name in internal form.</li>
1748          *
1749          * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C},
1750          * but no class loader is recorded as an initiating class loader of {@code C}.</li>
1751          *
1752          * <li> {@code C} is considered to have the same runtime package and
1753          * {@linkplain java.security.ProtectionDomain protection domain}
1754          * as the lookup class of this {@code Lookup}.
1755          *
1756          * <li> Let {@code GN} be the binary name obtained by taking {@code N}
1757          * (a binary name encoded in internal form) and replacing ASCII forward slashes with
1758          * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C},
1759          * {@link Class#getName()} returns the string {@code GN + "/" + <suffix>}, even though
1760          * this is not a valid binary class or interface name.</li>
1761          * </ul>
1762          * </li>
1763          * </ol>
1764          *
1765          * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
1766          * Linkage occurs as specified in JVMS 5.4.3, with the following adjustments:
1767          * <ul>
1768          * <li> During verification, whenever it is necessary to load the class named
1769          * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
1770          * made of any class loader.</li>
1771          *
1772          * <li> On any attempt to resolve the entry in the run-time constant pool indicated
1773          * by {@code this_class}, the symbolic reference is considered to be resolved to
1774          * {@code C} and resolution always succeeds immediately.</li>
1775          * </ul>
1776          *
1777          * <p> If the {@code initialize} parameter is {@code true},
1778          * then {@code C} is initialized by the Java Virtual Machine.
1779          *
1780          * <p> The newly created class or interface {@code C} is <em>hidden</em>, in the sense that
1781          * no other class or interface can refer to {@code C} via a constant pool entry.
1782          * That is, a hidden class or interface cannot be named as a supertype, a field type,
1783          * a method parameter type, or a method return type by any other class.
1784          * This is because a hidden class or interface does not have a binary name, so
1785          * there is no internal form available to record in any class's constant pool.
1786          * (Given the {@code Lookup} object returned this method, its lookup class
1787          * is a {@code Class} object for which {@link Class#getName()} returns a string
1788          * that is not a binary name.)
1789          * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
1790          * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
1791          * is not {@linkplain java.lang.instrument.Instrumentation#isModifiableClass(Class)
1792          * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
1793          * JVM Tool Interface</a>.
1794          *
1795          * <p> A class or interface created by
1796          * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1797          * a class loader} has a strong relationship with that class loader.
1798          * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
1799          * that {@linkplain Class#getClassLoader() defined it}.
1800          * This means that a class created by a class loader may be unloaded if and
1801          * only if its defining loader is not reachable and thus may be reclaimed
1802          * by a garbage collector (JLS 12.7).
1803          *
1804          * By default, however, a hidden class or interface may be unloaded even if
1805          * the class loader that is marked as its defining loader is
1806          * <a href="../ref/package.html#reachability">reachable</a>.
1807          * This behavior is useful when a hidden class or interface serves multiple
1808          * classes defined by arbitrary class loaders.  In other cases, a hidden
1809          * class or interface may be linked to a single class (or a small number of classes)
1810          * with the same defining loader as the hidden class or interface.
1811          * In such cases, where the hidden class or interface must be coterminous
1812          * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
1813          * option may be passed in {@code options}.
1814          * This arranges for a hidden class to have the same strong relationship
1815          * with the class loader marked as its defining loader,
1816          * as a normal class or interface has with its own defining loader.
1817          *
1818          * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
1819          * may still prevent a hidden class or interface from being
1820          * unloaded by ensuring that the {@code Class} object is reachable.
1821          *
1822          * <p> The unloading characteristics are set for each hidden class when it is
1823          * defined, and cannot be changed later.  An advantage of allowing hidden classes
1824          * to be unloaded independently of the class loader marked as their defining loader
1825          * is that a very large number of hidden classes may be created by an application.
1826          * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
1827          * just as if normal classes were created by class loaders.
1828          *
1829          * <p> Classes and interfaces in a nest are allowed to have mutual access to
1830          * their private members.  The nest relationship is determined by
1831          * the {@code NestHost} attribute (JVMS 4.7.28) and
1832          * the {@code NestMembers} attribute (JVMS 4.7.29) in a {@code class} file.
1833          * By default, a hidden class belongs to a nest consisting only of itself
1834          * because a hidden class has no binary name.
1835          * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
1836          * to create a hidden class or interface {@code C} as a member of a nest.
1837          * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
1838          * in the {@code ClassFile} structure from which {@code C} was derived.
1839          * Instead, the following rules determine the nest host of {@code C}:
1840          * <ul>
1841          * <li>If the nest host of the lookup class of this {@code Lookup} has previously
1842          *     been determined, then let {@code H} be the nest host of the lookup class.
1843          *     Otherwise, the nest host of the lookup class is determined using the
1844          *     algorithm in JVMS 5.4.4, yielding {@code H}.</li>
1845          * <li>The nest host of {@code C} is determined to be {@code H},
1846          *     the nest host of the lookup class.</li>
1847          * </ul>
1848          *
1849          * <p> A hidden class or interface may be serializable, but this requires a custom
1850          * serialization mechanism in order to ensure that instances are properly serialized
1851          * and deserialized. The default serialization mechanism supports only classes and
1852          * interfaces that are discoverable by their class name.
1853          *
1854          * @param bytes the bytes that make up the class data,
1855          * in the format of a valid {@code class} file as defined by
1856          * <cite>The Java Virtual Machine Specification</cite>.
1857          * @param initialize if {@code true} the class will be initialized.
1858          * @param options {@linkplain ClassOption class options}
1859          * @return the {@code Lookup} object on the hidden class
1860          *
1861          * @throws IllegalAccessException if this {@code Lookup} does not have
1862          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
1863          * @throws SecurityException if a security manager is present and it
1864          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1865          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1866          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
1867          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
1868          * {@bytes} denotes a class in a different package than the lookup class
1869          * @throws IncompatibleClassChangeError if the class or interface named as
1870          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
1871          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
1872          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
1873          * {@code C} is {@code C} itself
1874          * @throws VerifyError if the newly created class cannot be verified
1875          * @throws LinkageError if the newly created class cannot be linked for any other reason
1876          * @throws NullPointerException if any parameter is {@code null}
1877          *
1878          * @since 15
1879          * @see Class#isHiddenClass()
1880          * @jvms 4.2.1 Binary Class and Interface Names
1881          * @jvms 4.2.2 Unqualified Names
1882          * @jvms 4.7.28 The {@code NestHost} Attribute
1883          * @jvms 4.7.29 The {@code NestMembers} Attribute
1884          * @jvms 5.4.3.1 Class and Interface Resolution
1885          * @jvms 5.4.4 Access Control
1886          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
1887          * @jvms 5.4 Linking
1888          * @jvms 5.5 Initialization
1889          * @jls 12.7 Unloading of Classes and Interfaces
1890          */
1891         public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
1892                 throws IllegalAccessException
1893         {
1894             Objects.requireNonNull(bytes);
1895             Objects.requireNonNull(options);
1896 
1897             ensureDefineClassPermission();
1898             if (!hasFullPrivilegeAccess()) {
1899                 throw new IllegalAccessException(this + " does not have full privilege access");
1900             }
1901 
1902             Set<ClassOption> opts = options.length > 0 ? Set.of(options) : Set.of();
1903             return makeHiddenClassDefiner(bytes.clone(), opts, false).defineClassAsLookup(initialize);
1904         }
1905 
1906         /**
1907          * Creates a <em>hidden</em> class or interface from {@code bytes} with associated
1908          * {@linkplain MethodHandles#classData(Lookup, String, Class) class data},
1909          * returning a {@code Lookup} on the newly created class or interface.
1910          *
1911          * <p> This method is equivalent to calling
1912          * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, true, options)}
1913          * as if the hidden class has a private static final unnamed field whose value
1914          * is initialized to {@code classData} right before the class initializer is
1915          * executed.  The newly created class is linked and initialized by the Java
1916          * Virtual Machine.
1917          *
1918          * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData}
1919          * method can be used to retrieve the {@code classData}.
1920          *
1921          * @param bytes     the class bytes
1922          * @param classData pre-initialized class data
1923          * @param options   {@linkplain ClassOption class options}
1924          * @return the {@code Lookup} object on the hidden class
1925          *
1926          * @throws IllegalAccessException if this {@code Lookup} does not have
1927          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
1928          * @throws SecurityException if a security manager is present and it
1929          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1930          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1931          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
1932          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
1933          * {@bytes} denotes a class in a different package than the lookup class
1934          * @throws IncompatibleClassChangeError if the class or interface named as
1935          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
1936          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
1937          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
1938          * {@code C} is {@code C} itself
1939          * @throws VerifyError if the newly created class cannot be verified
1940          * @throws LinkageError if the newly created class cannot be linked for any other reason
1941          * @throws NullPointerException if any parameter is {@code null}
1942          *
1943          * @since 15
1944          * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1945          * @see Class#isHiddenClass()
1946          */
1947         /* package-private */ Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, ClassOption... options)
1948                 throws IllegalAccessException
1949         {
1950             Objects.requireNonNull(bytes);
1951             Objects.requireNonNull(classData);
1952             Objects.requireNonNull(options);
1953 
1954             ensureDefineClassPermission();
1955             if (!hasFullPrivilegeAccess()) {
1956                 throw new IllegalAccessException(this + " does not have full privilege access");
1957             }
1958 
1959             Set<ClassOption> opts = options.length > 0 ? Set.of(options) : Set.of();
1960             return makeHiddenClassDefiner(bytes.clone(), opts, false)
1961                        .defineClassAsLookup(true, classData);
1962         }
1963 
1964         private ClassDefiner makeClassDefiner(byte[] bytes) {
1965             return new ClassDefiner(this, bytes, STRONG_LOADER_LINK);
1966         }
1967 
1968         /**
1969          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
1970          * from the given bytes.
1971          *
1972          * @param bytes   class bytes
1973          * @return ClassDefiner that defines a hidden class of the given bytes.
1974          */
1975         ClassDefiner makeHiddenClassDefiner(byte[] bytes) {
1976             return makeHiddenClassDefiner(bytes, Set.of(), false);
1977         }
1978 
1979         /**
1980          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
1981          * from the given bytes.
1982          *
1983          * @param name    fully-qualified name that specifies the prefix of the hidden class
1984          * @param bytes   class bytes
1985          * @return ClassDefiner that defines a hidden class of the given bytes.
1986          */
1987         ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes) {
1988             return makeHiddenClassDefiner(name, bytes, Set.of(), false);
1989         }
1990 
1991         /**
1992          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
1993          * from the given bytes and options.  This method will read the class file
1994          * and obtain the class name.
1995          *
1996          * @param bytes   class bytes
1997          * @param options class options
1998          * @param accessVmAnnotations true to give the hidden class access to VM annotations
1999          * @return ClassDefiner that defines a hidden class of the given bytes and options
2000          */
2001         ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2002                                             Set<ClassOption> options,
2003                                             boolean accessVmAnnotations) {
2004             int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2005             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2006                 // jdk.internal.vm.annotations are permitted for classes
2007                 // defined to boot loader and platform loader
2008                 flags |= ACCESS_VM_ANNOTATIONS;
2009             }
2010 
2011             return new ClassDefiner(this, bytes, flags);
2012         }
2013 
2014         /**
2015          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2016          * from the given bytes and options.
2017          *
2018          * @param name the name of the class and the name in the class bytes is ignored.
2019          * @param bytes class bytes
2020          * @param options class options
2021          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2022          */
2023         ClassDefiner makeHiddenClassDefiner(String name,
2024                                             byte[] bytes,
2025                                             Set<ClassOption> options,
2026                                             boolean accessVmAnnotations) {
2027             int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2028             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2029                 // jdk.internal.vm.annotations are permitted for classes
2030                 // defined to boot loader and platform loader
2031                 flags |= ACCESS_VM_ANNOTATIONS;
2032             }
2033 
2034             return new ClassDefiner(this, name, bytes, flags);
2035         }
2036 
2037         static class ClassDefiner {
2038             private final Lookup lookup;
2039             private final String name;
2040             private final byte[] bytes;
2041             private final int classFlags;
2042 
2043             // caller should make a defensive copy of the arguments if needed
2044             // before calling this constructor
2045             private ClassDefiner(Lookup lookup, byte[] bytes, int flags) {
2046                 // defining an ordinary class which must be a strongly referenced by its defining loader
2047                 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2048                 this.lookup = lookup;
2049                 this.bytes = bytes;
2050                 this.classFlags = flags;
2051                 this.name = className(bytes);
2052 
2053                 int index = name.lastIndexOf('.');
2054                 String pn = (index == -1) ? "" : name.substring(0, index);
2055                 if (!pn.equals(lookup.lookupClass().getPackageName())) {
2056                     throw newIllegalArgumentException(name + " not in same package as lookup class: " +
2057                             lookup.lookupClass().getName());
2058                 }
2059             }
2060 
2061             // skip package name check
2062             private ClassDefiner(Lookup lookup, String name, byte[] bytes, int flags) {
2063                 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2064                 this.lookup = lookup;
2065                 this.bytes = bytes;
2066                 this.classFlags = flags;
2067                 this.name = name;
2068             }
2069 
2070             String className() {
2071                 return name;
2072             }
2073 
2074             Class<?> defineClass(boolean initialize) {
2075                 return defineClass(initialize, null);
2076             }
2077 
2078             Lookup defineClassAsLookup(boolean initialize) {
2079                 Class<?> c = defineClass(initialize, null);
2080                 return new Lookup(c, null, FULL_POWER_MODES);
2081             }
2082 
2083             /**
2084              * Defines the class of the given bytes and the given classData.
2085              * If {@code initialize} parameter is true, then the class will be initialized.
2086              *
2087              * @param initialize true if the class to be initialized
2088              * @param classData classData or null
2089              * @return the class
2090              *
2091              * @throws LinkageError linkage error
2092              */
2093             Class<?> defineClass(boolean initialize, Object classData) {
2094                 Class<?> lookupClass = lookup.lookupClass();
2095                 ClassLoader loader = lookupClass.getClassLoader();
2096                 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
2097                 Class<?> c = JLA.defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData);
2098                 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
2099                 return c;
2100             }
2101 
2102             Lookup defineClassAsLookup(boolean initialize, Object classData) {
2103                 // initialize must be true if classData is non-null
2104                 assert classData == null || initialize == true;
2105                 Class<?> c = defineClass(initialize, classData);
2106                 return new Lookup(c, null, FULL_POWER_MODES);
2107             }
2108 
2109             private boolean isNestmate() {
2110                 return (classFlags & NESTMATE_CLASS) != 0;
2111             }
2112 
2113             private static String className(byte[] bytes) {


2114                 try {
2115                     ClassReader reader = new ClassReader(bytes);
2116                     if ((reader.getAccess() & Opcodes.ACC_MODULE) != 0) {
2117                         throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set");
2118                     }
2119                     String name = reader.getClassName();
2120                     return name.replace('/', '.');
2121                 } catch (IllegalArgumentException e) {
2122                     throw e;
2123                 } catch (RuntimeException e) {
2124                     // ASM exceptions are poorly specified
2125                     ClassFormatError cfe = new ClassFormatError();
2126                     cfe.initCause(e);
2127                     throw cfe;
2128                 }










2129             }










2130         }
2131 
2132         private ProtectionDomain lookupClassProtectionDomain() {
2133             ProtectionDomain pd = cachedProtectionDomain;
2134             if (pd == null) {
2135                 cachedProtectionDomain = pd = JLA.protectionDomain(lookupClass);
2136             }
2137             return pd;
2138         }
2139 





2140         // cached protection domain
2141         private volatile ProtectionDomain cachedProtectionDomain;
2142 

2143         // Make sure outer class is initialized first.
2144         static { IMPL_NAMES.getClass(); }
2145 
2146         /** Package-private version of lookup which is trusted. */
2147         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
2148 
2149         /** Version of lookup which is trusted minimally.
2150          *  It can only be used to create method handles to publicly accessible
2151          *  members in packages that are exported unconditionally.
2152          */
2153         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
2154 
2155         static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
2156 
2157         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2158             String name = lookupClass.getName();
2159             if (name.startsWith("java.lang.invoke."))
2160                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
2161         }
2162 
2163         /**
2164          * Displays the name of the class from which lookups are to be made.
2165          * followed with "/" and the name of the {@linkplain #previousLookupClass()
2166          * previous lookup class} if present.
2167          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
2168          * If there are restrictions on the access permitted to this lookup,
2169          * this is indicated by adding a suffix to the class name, consisting
2170          * of a slash and a keyword.  The keyword represents the strongest
2171          * allowed access, and is chosen as follows:
2172          * <ul>
2173          * <li>If no access is allowed, the suffix is "/noaccess".
2174          * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
2175          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
2176          * <li>If only public and module access are allowed, the suffix is "/module".


3087          * the {@code Field} object's {@code set} method could return
3088          * normally.  In particular, fields which are both {@code static}
3089          * and {@code final} may never be set.
3090          * <p>
3091          * If the field is {@code static}, and
3092          * if the returned method handle is invoked, the field's class will
3093          * be initialized, if it has not already been initialized.
3094          * @param f the reflected field
3095          * @return a method handle which can store values into the reflected field
3096          * @throws IllegalAccessException if access checking fails,
3097          *         or if the field is {@code final} and write access
3098          *         is not enabled on the {@code Field} object
3099          * @throws NullPointerException if the argument is null
3100          */
3101         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3102             return unreflectField(f, true);
3103         }
3104 
3105         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3106             MemberName field = new MemberName(f, isSetter);
3107             if (isSetter && field.isFinal()) {
3108                 if (field.isStatic()) {
3109                     throw field.makeAccessException("static final field has no write access", this);
3110                 } else if (field.getDeclaringClass().isHiddenClass()){
3111                     throw field.makeAccessException("final field in a hidden class has no write access", this);
3112                 }
3113             }
3114             assert(isSetter
3115                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3116                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3117             @SuppressWarnings("deprecation")
3118             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
3119             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
3120         }
3121 
3122         /**
3123          * Produces a VarHandle giving access to a reflected field {@code f}
3124          * of type {@code T} declared in a class of type {@code R}.
3125          * The VarHandle's variable type is {@code T}.
3126          * If the field is non-static the VarHandle has one coordinate type,
3127          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
3128          * coordinate types.
3129          * <p>
3130          * Access checking is performed immediately on behalf of the lookup
3131          * class, regardless of the value of the field's {@code accessible}
3132          * flag.
3133          * <p>


3654             if (!putField.isFinal()) {
3655                 // A VarHandle does not support updates to final fields, any
3656                 // such VarHandle to a final field will be read-only and
3657                 // therefore the following write-based accessibility checks are
3658                 // only required for non-final fields
3659                 checkField(putRefKind, refc, putField);
3660                 if (checkSecurity)
3661                     checkSecurityManager(refc, putField);
3662             }
3663 
3664             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
3665                                   restrictProtectedReceiver(getField));
3666             if (doRestrict) {
3667                 assert !getField.isStatic();
3668                 // receiver type of VarHandle is too wide; narrow to caller
3669                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
3670                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
3671                 }
3672                 refc = lookupClass();
3673             }
3674             return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(),
3675                                              this.allowedModes == TRUSTED && !getField.getDeclaringClass().isHiddenClass());
3676         }
3677         /** Check access and get the requested constructor. */
3678         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
3679             final boolean checkSecurity = true;
3680             return getDirectConstructorCommon(refc, ctor, checkSecurity);
3681         }
3682         /** Check access and get the requested constructor, eliding security manager checks. */
3683         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
3684             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
3685             return getDirectConstructorCommon(refc, ctor, checkSecurity);
3686         }
3687         /** Common code for all constructors; do not call directly except from immediately above. */
3688         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
3689                                                   boolean checkSecurity) throws IllegalAccessException {
3690             assert(ctor.isConstructor());
3691             checkAccess(REF_newInvokeSpecial, refc, ctor);
3692             // Optionally check with the security manager; this isn't needed for unreflect* calls.
3693             if (checkSecurity)
3694                 checkSecurityManager(refc, ctor);
3695             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here


3767                 checkSecurityManager(defc, resolved2);
3768             } catch (SecurityException ex) {
3769                 return false;
3770             }
3771             return true;
3772         }
3773         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
3774                 throws ReflectiveOperationException {
3775             if (MethodHandleNatives.refKindIsField(refKind)) {
3776                 return getDirectFieldNoSecurityManager(refKind, defc, member);
3777             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
3778                 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member));
3779             } else if (refKind == REF_newInvokeSpecial) {
3780                 return getDirectConstructorNoSecurityManager(defc, member);
3781             }
3782             // oops
3783             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
3784         }
3785 
3786         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
3787 
3788         /**
3789          * The set of class options that specify whether a hidden class created by
3790          * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
3791          * Lookup::defineHiddenClass} method is dynamically added as a new member
3792          * to the nest of a lookup class and/or whether a hidden class has
3793          * a strong relationship with the class loader marked as its defining loader.
3794          *
3795          * @since 15
3796          */
3797         public enum ClassOption {
3798             /**
3799              * This class option specifies the hidden class be added to
3800              * {@linkplain Class#getNestHost nest} of a lookup class as
3801              * a nestmate.
3802              *
3803              * <p> A hidden nestmate class has access to the private members of all
3804              * classes and interfaces in the same nest.
3805              *
3806              * @see Class#getNestHost()
3807              */
3808             NESTMATE(NESTMATE_CLASS),
3809 
3810             /**
3811              *
3812              * This class option specifies the hidden class to have a <em>strong</em>
3813              * relationship with the class loader marked as its defining loader,
3814              * as a normal class or interface has with its own defining loader.
3815              * This means that the hidden class may be unloaded if and only if
3816              * its defining loader is not reachable and thus may be reclaimed
3817              * by a garbage collector (JLS 12.7).
3818              *
3819              * <p> By default, a hidden class or interface may be unloaded
3820              * even if the class loader that is marked as its defining loader is
3821              * <a href="../ref/package.html#reachability">reachable</a>.
3822 
3823              *
3824              * @jls 12.7 Unloading of Classes and Interfaces
3825              */
3826             STRONG(STRONG_LOADER_LINK);
3827 
3828             /* the flag value is used by VM at define class time */
3829             private final int flag;
3830             ClassOption(int flag) {
3831                 this.flag = flag;
3832             }
3833 
3834             static int optionsToFlag(Set<ClassOption> options) {
3835                 int flags = 0;
3836                 for (ClassOption cp : options) {
3837                     flags |= cp.flag;
3838                 }
3839                 return flags;
3840             }
3841         }
3842     }
3843 
3844     /**
3845      * Produces a method handle constructing arrays of a desired type,
3846      * as if by the {@code anewarray} bytecode.
3847      * The return type of the method handle will be the array type.
3848      * The type of its sole argument will be {@code int}, which specifies the size of the array.
3849      *
3850      * <p> If the returned method handle is invoked with a negative
3851      * array size, a {@code NegativeArraySizeException} will be thrown.
3852      *
3853      * @param arrayClass an array type
3854      * @return a method handle which can create arrays of the given type
3855      * @throws NullPointerException if the argument is {@code null}
3856      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
3857      * @see java.lang.reflect.Array#newInstance(Class, int)
3858      * @jvms 6.5 {@code anewarray} Instruction
3859      * @since 9
3860      */
3861     public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {


< prev index next >