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:
196 * {@code null} previous lookup class.
197 * <p>
198 * Otherwise, {@code M1} and {@code M2} are two different modules. This method
199 * returns a {@code Lookup} on {@code targetClass} that records
200 * the lookup class of the caller as the new previous lookup class and
201 * drops {@code MODULE} access from the full capabilities mode.
202 *
203 * @param targetClass the target class
204 * @param caller the caller lookup object
205 * @return a lookup object for the target class, with private access
206 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
207 * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
208 * @throws SecurityException if denied by the security manager
209 * @throws IllegalAccessException if any of the other access checks specified above fails
210 * @since 9
211 * @spec JPMS
212 * @see Lookup#dropLookupMode
213 * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
214 */
215 public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
216 SecurityManager sm = System.getSecurityManager();
217 if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
218 if (targetClass.isPrimitive())
219 throw new IllegalArgumentException(targetClass + " is a primitive class");
220 if (targetClass.isArray())
221 throw new IllegalArgumentException(targetClass + " is an array class");
222 // Ensure that we can reason accurately about private and module access.
223 if ((caller.lookupModes() & Lookup.PRIVATE) == 0)
224 throw new IllegalAccessException("caller does not have PRIVATE lookup mode");
225 if ((caller.lookupModes() & Lookup.MODULE) == 0)
226 throw new IllegalAccessException("caller does not have MODULE lookup mode");
227
228 // previous lookup class is never set if it has MODULE access
229 assert caller.previousLookupClass() == null;
230
231 Class<?> callerClass = caller.lookupClass();
232 Module callerModule = callerClass.getModule(); // M1
233 Module targetModule = targetClass.getModule(); // M2
234 Class<?> newPreviousClass = null;
235 int newModes = Lookup.FULL_POWER_MODES;
1078 * different module from the current lookup class.
1079 * </ul>
1080 * <li>Any attempt to reach a third module loses all access.</li>
1081 * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1082 * all access modes are dropped.</li>
1083 * </ul>
1084 *
1085 * <h2><a id="secmgr"></a>Security manager interactions</h2>
1086 * Although bytecode instructions can only refer to classes in
1087 * a related class loader, this API can search for methods in any
1088 * class, as long as a reference to its {@code Class} object is
1089 * available. Such cross-loader references are also possible with the
1090 * Core Reflection API, and are impossible to bytecode instructions
1091 * such as {@code invokestatic} or {@code getfield}.
1092 * There is a {@linkplain java.lang.SecurityManager security manager API}
1093 * to allow applications to check such cross-loader references.
1094 * These checks apply to both the {@code MethodHandles.Lookup} API
1095 * and the Core Reflection API
1096 * (as found on {@link java.lang.Class Class}).
1097 * <p>
1098 * If a security manager is present, member and class lookups are subject to
1099 * additional checks.
1100 * From one to three calls are made to the security manager.
1101 * Any of these calls can refuse access by throwing a
1102 * {@link java.lang.SecurityException SecurityException}.
1103 * Define {@code smgr} as the security manager,
1104 * {@code lookc} as the lookup class of the current lookup object,
1105 * {@code refc} as the containing class in which the member
1106 * is being sought, and {@code defc} as the class in which the
1107 * member is actually defined.
1108 * (If a class or other type is being accessed,
1109 * the {@code refc} and {@code defc} values are the class itself.)
1110 * The value {@code lookc} is defined as <em>not present</em>
1111 * if the current lookup object does not have
1112 * <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1113 * The calls are made according to the following rules:
1114 * <ul>
1115 * <li><b>Step 1:</b>
1116 * If {@code lookc} is not present, or if its class loader is not
1117 * the same as or an ancestor of the class loader of {@code refc},
1118 * then {@link SecurityManager#checkPackageAccess
1119 * smgr.checkPackageAccess(refcPkg)} is called,
1123 * {@code lookc} is not present, then
1124 * {@link SecurityManager#checkPermission smgr.checkPermission}
1125 * with {@code RuntimePermission("accessDeclaredMembers")} is called.
1126 * <li><b>Step 2b:</b>
1127 * If the retrieved class has a {@code null} class loader,
1128 * and {@code lookc} is not present, then
1129 * {@link SecurityManager#checkPermission smgr.checkPermission}
1130 * with {@code RuntimePermission("getClassLoader")} is called.
1131 * <li><b>Step 3:</b>
1132 * If the retrieved member is not public,
1133 * and if {@code lookc} is not present,
1134 * and if {@code defc} and {@code refc} are different,
1135 * then {@link SecurityManager#checkPackageAccess
1136 * smgr.checkPackageAccess(defcPkg)} is called,
1137 * where {@code defcPkg} is the package of {@code defc}.
1138 * </ul>
1139 * Security checks are performed after other access checks have passed.
1140 * Therefore, the above rules presuppose a member or class that is public,
1141 * or else that is being accessed from a lookup class that has
1142 * rights to access the member or class.
1143 *
1144 * <h2><a id="callsens"></a>Caller sensitive methods</h2>
1145 * A small number of Java methods have a special property called caller sensitivity.
1146 * A <em>caller-sensitive</em> method can behave differently depending on the
1147 * identity of its immediate caller.
1148 * <p>
1149 * If a method handle for a caller-sensitive method is requested,
1150 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1151 * but they take account of the lookup class in a special way.
1152 * The resulting method handle behaves as if it were called
1153 * from an instruction contained in the lookup class,
1154 * so that the caller-sensitive method detects the lookup class.
1155 * (By contrast, the invoker of the method handle is disregarded.)
1156 * Thus, in the case of caller-sensitive methods,
1157 * different lookup classes may give rise to
1158 * differently behaving method handles.
1159 * <p>
1160 * In cases where the lookup object is
1161 * {@link MethodHandles#publicLookup() publicLookup()},
1162 * or some other lookup object without
1360 * so that it can access only names which can be reached by the original
1361 * lookup object, and also by the new lookup class.
1362 * @return the lookup modes, which limit the kinds of access performed by this lookup object
1363 * @see #in
1364 * @see #dropLookupMode
1365 *
1366 * @revised 9
1367 * @spec JPMS
1368 */
1369 public int lookupModes() {
1370 return allowedModes & ALL_MODES;
1371 }
1372
1373 /** Embody the current class (the lookupClass) as a lookup class
1374 * for method handle creation.
1375 * Must be called by from a method in this package,
1376 * which in turn is called by a method not in this package.
1377 */
1378 Lookup(Class<?> lookupClass) {
1379 this(lookupClass, null, FULL_POWER_MODES);
1380 // make sure we haven't accidentally picked up a privileged class:
1381 checkUnprivilegedlookupClass(lookupClass);
1382 }
1383
1384 private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1385 assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1386 && prevLookupClass.getModule() != lookupClass.getModule());
1387 assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1388 this.lookupClass = lookupClass;
1389 this.prevLookupClass = prevLookupClass;
1390 this.allowedModes = allowedModes;
1391 }
1392
1393 private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1394 // make sure we haven't accidentally picked up a privileged class:
1395 checkUnprivilegedlookupClass(lookupClass);
1396 return new Lookup(lookupClass, prevLookupClass, allowedModes);
1397 }
1398
1399 /**
1400 * Creates a lookup on the specified new lookup class.
1401 * The resulting object will report the specified
1402 * class as its own {@link #lookupClass() lookupClass}.
1403 *
1404 * <p>
1405 * However, the resulting {@code Lookup} object is guaranteed
1406 * to have no more access capabilities than the original.
1407 * In particular, access capabilities can be lost as follows:<ul>
1408 * <li>If the new lookup class is in a different module from the old one,
1409 * i.e. {@link #MODULE MODULE} access is lost.
1410 * <li>If the new lookup class is in a different package
1485 }
1486 // Allow nestmate lookups to be created without special privilege:
1487 if ((newModes & PRIVATE) != 0
1488 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1489 newModes &= ~(PRIVATE|PROTECTED);
1490 }
1491 if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1492 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1493 // The requested class it not accessible from the lookup class.
1494 // No permissions.
1495 newModes = 0;
1496 }
1497 return newLookup(requestedLookupClass, plc, newModes);
1498 }
1499
1500 /**
1501 * Creates a lookup on the same lookup class which this lookup object
1502 * finds members, but with a lookup mode that has lost the given lookup mode.
1503 * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1504 * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED} or {@link #PRIVATE PRIVATE}.
1505 * {@link #PROTECTED PROTECTED} is always
1506 * dropped and so the resulting lookup mode will never have this access capability.
1507 * When dropping {@code PACKAGE} then the resulting lookup will not have {@code PACKAGE}
1508 * or {@code PRIVATE} access. When dropping {@code MODULE} then the resulting lookup will
1509 * not have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. If {@code PUBLIC}
1510 * is dropped then the resulting lookup has no access. If {@code UNCONDITIONAL}
1511 * is dropped then the resulting lookup has no access.
1512 *
1513 * @apiNote
1514 * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1515 * delegate non-public access within the package of the lookup class without
1516 * conferring private access. A lookup with {@code MODULE} but not
1517 * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1518 * the module of the lookup class without conferring package access.
1519 * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1520 * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1521 * to public classes accessible to both the module of the lookup class
1522 * and the module of the previous lookup class.
1523 *
1524 * @param modeToDrop the lookup mode to drop
1525 * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1526 * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1572 * @throws IllegalArgumentException the bytes are for a class in a different package
1573 * to the lookup class
1574 * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1575 * @throws LinkageError if the class is malformed ({@code ClassFormatError}), cannot be
1576 * verified ({@code VerifyError}), is already defined, or another linkage error occurs
1577 * @throws SecurityException if denied by the security manager
1578 * @throws NullPointerException if {@code bytes} is {@code null}
1579 * @since 9
1580 * @spec JPMS
1581 * @see Lookup#privateLookupIn
1582 * @see Lookup#dropLookupMode
1583 * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1584 */
1585 public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1586 SecurityManager sm = System.getSecurityManager();
1587 if (sm != null)
1588 sm.checkPermission(new RuntimePermission("defineClass"));
1589 if ((lookupModes() & PACKAGE) == 0)
1590 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1591 assert (lookupModes() & (MODULE|PUBLIC)) != 0;
1592
1593 // parse class bytes to get class name (in internal form)
1594 bytes = bytes.clone();
1595 String name;
1596 try {
1597 ClassReader reader = new ClassReader(bytes);
1598 name = reader.getClassName();
1599 } catch (RuntimeException e) {
1600 // ASM exceptions are poorly specified
1601 ClassFormatError cfe = new ClassFormatError();
1602 cfe.initCause(e);
1603 throw cfe;
1604 }
1605
1606 // get package and class name in binary form
1607 String cn, pn;
1608 int index = name.lastIndexOf('/');
1609 if (index == -1) {
1610 cn = name;
1611 pn = "";
1612 } else {
1613 cn = name.replace('/', '.');
1614 pn = cn.substring(0, index);
1615 }
1616 if (!pn.equals(lookupClass.getPackageName())) {
1617 throw new IllegalArgumentException("Class not in same package as lookup class");
1618 }
1619
1620 // invoke the class loader's defineClass method
1621 ClassLoader loader = lookupClass.getClassLoader();
1622 ProtectionDomain pd = (loader != null) ? lookupClassProtectionDomain() : null;
1623 String source = "__Lookup_defineClass__";
1624 Class<?> clazz = SharedSecrets.getJavaLangAccess().defineClass(loader, cn, bytes, pd, source);
1625 return clazz;
1626 }
1627
1628 private ProtectionDomain lookupClassProtectionDomain() {
1629 ProtectionDomain pd = cachedProtectionDomain;
1630 if (pd == null) {
1631 cachedProtectionDomain = pd = protectionDomain(lookupClass);
1632 }
1633 return pd;
1634 }
1635
1636 private ProtectionDomain protectionDomain(Class<?> clazz) {
1637 PrivilegedAction<ProtectionDomain> pa = clazz::getProtectionDomain;
1638 return AccessController.doPrivileged(pa);
1639 }
1640
1641 // cached protection domain
1642 private volatile ProtectionDomain cachedProtectionDomain;
1643
1644
1645 // Make sure outer class is initialized first.
1646 static { IMPL_NAMES.getClass(); }
1647
1648 /** Package-private version of lookup which is trusted. */
1649 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
1650
1651 /** Version of lookup which is trusted minimally.
1652 * It can only be used to create method handles to publicly accessible
1653 * members in packages that are exported unconditionally.
1654 */
1655 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
1656
1657 private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
1658 String name = lookupClass.getName();
1659 if (name.startsWith("java.lang.invoke."))
1660 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
1661 }
1662
1663 /**
1664 * Displays the name of the class from which lookups are to be made.
1665 * followed with "/" and the name of the {@linkplain #previousLookupClass()
1666 * previous lookup class} if present.
1667 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
1668 * If there are restrictions on the access permitted to this lookup,
1669 * this is indicated by adding a suffix to the class name, consisting
1670 * of a slash and a keyword. The keyword represents the strongest
1671 * allowed access, and is chosen as follows:
1672 * <ul>
1673 * <li>If no access is allowed, the suffix is "/noaccess".
1674 * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
1675 * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
1676 * <li>If only public and module access are allowed, the suffix is "/module".
1695 * @revised 9
1696 * @spec JPMS
1697 */
1698 @Override
1699 public String toString() {
1700 String cname = lookupClass.getName();
1701 if (prevLookupClass != null)
1702 cname += "/" + prevLookupClass.getName();
1703 switch (allowedModes) {
1704 case 0: // no privileges
1705 return cname + "/noaccess";
1706 case UNCONDITIONAL:
1707 return cname + "/publicLookup";
1708 case PUBLIC:
1709 return cname + "/public";
1710 case PUBLIC|MODULE:
1711 return cname + "/module";
1712 case PUBLIC|PACKAGE:
1713 case PUBLIC|MODULE|PACKAGE:
1714 return cname + "/package";
1715 case FULL_POWER_MODES & (~PROTECTED):
1716 case FULL_POWER_MODES & ~(PROTECTED|MODULE):
1717 return cname + "/private";
1718 case FULL_POWER_MODES:
1719 case FULL_POWER_MODES & (~MODULE):
1720 return cname;
1721 case TRUSTED:
1722 return "/trusted"; // internal only; not exported
1723 default: // Should not happen, but it's a bitfield...
1724 cname = cname + "/" + Integer.toHexString(allowedModes);
1725 assert(false) : cname;
1726 return cname;
1727 }
1728 }
1729
1730 /**
1731 * Produces a method handle for a static method.
1732 * The type of the method handle will be that of the method.
1733 * (Since static methods do not take receivers, there is no
1734 * additional receiver argument inserted into the method handle type,
1735 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
1736 * The method and all its argument types must be accessible to the lookup object.
1737 * <p>
1738 * The returned method handle will have
1739 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3243 checkSecurityManager(defc, resolved2);
3244 } catch (SecurityException ex) {
3245 return false;
3246 }
3247 return true;
3248 }
3249 private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
3250 throws ReflectiveOperationException {
3251 if (MethodHandleNatives.refKindIsField(refKind)) {
3252 return getDirectFieldNoSecurityManager(refKind, defc, member);
3253 } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
3254 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass);
3255 } else if (refKind == REF_newInvokeSpecial) {
3256 return getDirectConstructorNoSecurityManager(defc, member);
3257 }
3258 // oops
3259 throw newIllegalArgumentException("bad MethodHandle constant #"+member);
3260 }
3261
3262 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
3263 }
3264
3265 /**
3266 * Produces a method handle constructing arrays of a desired type,
3267 * as if by the {@code anewarray} bytecode.
3268 * The return type of the method handle will be the array type.
3269 * The type of its sole argument will be {@code int}, which specifies the size of the array.
3270 *
3271 * <p> If the returned method handle is invoked with a negative
3272 * array size, a {@code NegativeArraySizeException} will be thrown.
3273 *
3274 * @param arrayClass an array type
3275 * @return a method handle which can create arrays of the given type
3276 * @throws NullPointerException if the argument is {@code null}
3277 * @throws IllegalArgumentException if {@code arrayClass} is not an array type
3278 * @see java.lang.reflect.Array#newInstance(Class, int)
3279 * @jvms 6.5 {@code anewarray} Instruction
3280 * @since 9
3281 */
3282 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.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.concurrent.ConcurrentHashMap;
58 import java.util.stream.Collectors;
59 import java.util.stream.Stream;
60
61 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
62 import static java.lang.invoke.MethodHandleNatives.Constants.*;
63 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
64 import static java.lang.invoke.MethodType.methodType;
65
66 /**
67 * This class consists exclusively of static methods that operate on or return
68 * method handles. They fall into several categories:
195 * {@code null} previous lookup class.
196 * <p>
197 * Otherwise, {@code M1} and {@code M2} are two different modules. This method
198 * returns a {@code Lookup} on {@code targetClass} that records
199 * the lookup class of the caller as the new previous lookup class and
200 * drops {@code MODULE} access from the full capabilities mode.
201 *
202 * @param targetClass the target class
203 * @param caller the caller lookup object
204 * @return a lookup object for the target class, with private access
205 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
206 * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
207 * @throws SecurityException if denied by the security manager
208 * @throws IllegalAccessException if any of the other access checks specified above fails
209 * @since 9
210 * @spec JPMS
211 * @see Lookup#dropLookupMode
212 * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
213 */
214 public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
215 if (caller.allowedModes == Lookup.TRUSTED) {
216 return new Lookup(targetClass);
217 }
218
219 SecurityManager sm = System.getSecurityManager();
220 if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
221 if (targetClass.isPrimitive())
222 throw new IllegalArgumentException(targetClass + " is a primitive class");
223 if (targetClass.isArray())
224 throw new IllegalArgumentException(targetClass + " is an array class");
225 // Ensure that we can reason accurately about private and module access.
226 if ((caller.lookupModes() & Lookup.PRIVATE) == 0)
227 throw new IllegalAccessException("caller does not have PRIVATE lookup mode");
228 if ((caller.lookupModes() & Lookup.MODULE) == 0)
229 throw new IllegalAccessException("caller does not have MODULE lookup mode");
230
231 // previous lookup class is never set if it has MODULE access
232 assert caller.previousLookupClass() == null;
233
234 Class<?> callerClass = caller.lookupClass();
235 Module callerModule = callerClass.getModule(); // M1
236 Module targetModule = targetClass.getModule(); // M2
237 Class<?> newPreviousClass = null;
238 int newModes = Lookup.FULL_POWER_MODES;
1081 * different module from the current lookup class.
1082 * </ul>
1083 * <li>Any attempt to reach a third module loses all access.</li>
1084 * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1085 * all access modes are dropped.</li>
1086 * </ul>
1087 *
1088 * <h2><a id="secmgr"></a>Security manager interactions</h2>
1089 * Although bytecode instructions can only refer to classes in
1090 * a related class loader, this API can search for methods in any
1091 * class, as long as a reference to its {@code Class} object is
1092 * available. Such cross-loader references are also possible with the
1093 * Core Reflection API, and are impossible to bytecode instructions
1094 * such as {@code invokestatic} or {@code getfield}.
1095 * There is a {@linkplain java.lang.SecurityManager security manager API}
1096 * to allow applications to check such cross-loader references.
1097 * These checks apply to both the {@code MethodHandles.Lookup} API
1098 * and the Core Reflection API
1099 * (as found on {@link java.lang.Class Class}).
1100 * <p>
1101 * If a security manager is present, member and class lookups are
1102 * subject to additional checks.
1103 * From one to three calls are made to the security manager.
1104 * Any of these calls can refuse access by throwing a
1105 * {@link java.lang.SecurityException SecurityException}.
1106 * Define {@code smgr} as the security manager,
1107 * {@code lookc} as the lookup class of the current lookup object,
1108 * {@code refc} as the containing class in which the member
1109 * is being sought, and {@code defc} as the class in which the
1110 * member is actually defined.
1111 * (If a class or other type is being accessed,
1112 * the {@code refc} and {@code defc} values are the class itself.)
1113 * The value {@code lookc} is defined as <em>not present</em>
1114 * if the current lookup object does not have
1115 * <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1116 * The calls are made according to the following rules:
1117 * <ul>
1118 * <li><b>Step 1:</b>
1119 * If {@code lookc} is not present, or if its class loader is not
1120 * the same as or an ancestor of the class loader of {@code refc},
1121 * then {@link SecurityManager#checkPackageAccess
1122 * smgr.checkPackageAccess(refcPkg)} is called,
1126 * {@code lookc} is not present, then
1127 * {@link SecurityManager#checkPermission smgr.checkPermission}
1128 * with {@code RuntimePermission("accessDeclaredMembers")} is called.
1129 * <li><b>Step 2b:</b>
1130 * If the retrieved class has a {@code null} class loader,
1131 * and {@code lookc} is not present, then
1132 * {@link SecurityManager#checkPermission smgr.checkPermission}
1133 * with {@code RuntimePermission("getClassLoader")} is called.
1134 * <li><b>Step 3:</b>
1135 * If the retrieved member is not public,
1136 * and if {@code lookc} is not present,
1137 * and if {@code defc} and {@code refc} are different,
1138 * then {@link SecurityManager#checkPackageAccess
1139 * smgr.checkPackageAccess(defcPkg)} is called,
1140 * where {@code defcPkg} is the package of {@code defc}.
1141 * </ul>
1142 * Security checks are performed after other access checks have passed.
1143 * Therefore, the above rules presuppose a member or class that is public,
1144 * or else that is being accessed from a lookup class that has
1145 * rights to access the member or class.
1146 * <p>
1147 * If a security manager is present and the current lookup object does not have
1148 * <a href="MethodHandles.Lookup.html#privacc">private access</a>, then
1149 * {@link #defineClass(byte[]) defineClass} and
1150 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass}
1151 * call {@link SecurityManager#checkPermission smgr.checkPermission}
1152 * with {@code RuntimePermission("defineClass")} is called.
1153 *
1154 * <h2><a id="callsens"></a>Caller sensitive methods</h2>
1155 * A small number of Java methods have a special property called caller sensitivity.
1156 * A <em>caller-sensitive</em> method can behave differently depending on the
1157 * identity of its immediate caller.
1158 * <p>
1159 * If a method handle for a caller-sensitive method is requested,
1160 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1161 * but they take account of the lookup class in a special way.
1162 * The resulting method handle behaves as if it were called
1163 * from an instruction contained in the lookup class,
1164 * so that the caller-sensitive method detects the lookup class.
1165 * (By contrast, the invoker of the method handle is disregarded.)
1166 * Thus, in the case of caller-sensitive methods,
1167 * different lookup classes may give rise to
1168 * differently behaving method handles.
1169 * <p>
1170 * In cases where the lookup object is
1171 * {@link MethodHandles#publicLookup() publicLookup()},
1172 * or some other lookup object without
1370 * so that it can access only names which can be reached by the original
1371 * lookup object, and also by the new lookup class.
1372 * @return the lookup modes, which limit the kinds of access performed by this lookup object
1373 * @see #in
1374 * @see #dropLookupMode
1375 *
1376 * @revised 9
1377 * @spec JPMS
1378 */
1379 public int lookupModes() {
1380 return allowedModes & ALL_MODES;
1381 }
1382
1383 /** Embody the current class (the lookupClass) as a lookup class
1384 * for method handle creation.
1385 * Must be called by from a method in this package,
1386 * which in turn is called by a method not in this package.
1387 */
1388 Lookup(Class<?> lookupClass) {
1389 this(lookupClass, null, FULL_POWER_MODES);
1390 }
1391
1392 private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1393 assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1394 && prevLookupClass.getModule() != lookupClass.getModule());
1395 assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1396 this.lookupClass = lookupClass;
1397 this.prevLookupClass = prevLookupClass;
1398 this.allowedModes = allowedModes;
1399 assert !lookupClass.isPrimitive() && !lookupClass.isArray();
1400 }
1401
1402 private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1403 // make sure we haven't accidentally picked up a privileged class:
1404 checkUnprivilegedlookupClass(lookupClass);
1405 return new Lookup(lookupClass, prevLookupClass, allowedModes);
1406 }
1407
1408 /**
1409 * Creates a lookup on the specified new lookup class.
1410 * The resulting object will report the specified
1411 * class as its own {@link #lookupClass() lookupClass}.
1412 *
1413 * <p>
1414 * However, the resulting {@code Lookup} object is guaranteed
1415 * to have no more access capabilities than the original.
1416 * In particular, access capabilities can be lost as follows:<ul>
1417 * <li>If the new lookup class is in a different module from the old one,
1418 * i.e. {@link #MODULE MODULE} access is lost.
1419 * <li>If the new lookup class is in a different package
1494 }
1495 // Allow nestmate lookups to be created without special privilege:
1496 if ((newModes & PRIVATE) != 0
1497 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1498 newModes &= ~(PRIVATE|PROTECTED);
1499 }
1500 if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1501 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1502 // The requested class it not accessible from the lookup class.
1503 // No permissions.
1504 newModes = 0;
1505 }
1506 return newLookup(requestedLookupClass, plc, newModes);
1507 }
1508
1509 /**
1510 * Creates a lookup on the same lookup class which this lookup object
1511 * finds members, but with a lookup mode that has lost the given lookup mode.
1512 * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1513 * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED} or {@link #PRIVATE PRIVATE}.
1514 * {@link #PROTECTED PROTECTED} is always dropped and
1515 * so the resulting lookup mode will never have this access capability.
1516 * When dropping {@code PACKAGE} then the resulting lookup will not have {@code PACKAGE}
1517 * or {@code PRIVATE} access. When dropping {@code MODULE} then the resulting lookup will
1518 * not have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. If {@code PUBLIC}
1519 * is dropped then the resulting lookup has no access. If {@code UNCONDITIONAL}
1520 * is dropped then the resulting lookup has no access.
1521 *
1522 * @apiNote
1523 * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1524 * delegate non-public access within the package of the lookup class without
1525 * conferring private access. A lookup with {@code MODULE} but not
1526 * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1527 * the module of the lookup class without conferring package access.
1528 * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1529 * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1530 * to public classes accessible to both the module of the lookup class
1531 * and the module of the previous lookup class.
1532 *
1533 * @param modeToDrop the lookup mode to drop
1534 * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1535 * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1581 * @throws IllegalArgumentException the bytes are for a class in a different package
1582 * to the lookup class
1583 * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1584 * @throws LinkageError if the class is malformed ({@code ClassFormatError}), cannot be
1585 * verified ({@code VerifyError}), is already defined, or another linkage error occurs
1586 * @throws SecurityException if denied by the security manager
1587 * @throws NullPointerException if {@code bytes} is {@code null}
1588 * @since 9
1589 * @spec JPMS
1590 * @see Lookup#privateLookupIn
1591 * @see Lookup#dropLookupMode
1592 * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1593 */
1594 public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1595 SecurityManager sm = System.getSecurityManager();
1596 if (sm != null)
1597 sm.checkPermission(new RuntimePermission("defineClass"));
1598 if ((lookupModes() & PACKAGE) == 0)
1599 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1600 assert (lookupModes() & (MODULE|PUBLIC)) != 0;
1601 return makeClassDefiner(bytes.clone()).defineClass(false);
1602 }
1603
1604 private void checkDefineClassPermission() {
1605 SecurityManager sm = System.getSecurityManager();
1606 if (sm == null) return;
1607 if (allowedModes == TRUSTED) return;
1608
1609 if (!hasPrivateAccess()) {
1610 sm.checkPermission(new RuntimePermission("defineClass"));
1611 }
1612 }
1613
1614 /**
1615 * Creates a {@code Lookup} on a <em>hidden class</em> defined to
1616 * the same class loader and in the same runtime package and
1617 * {@linkplain java.security.ProtectionDomain protection domain} as this
1618 * lookup's {@linkplain #lookupClass() lookup class}.
1619 *
1620 * If {@code options} has {@link ClassOption#NESTMATE NESTMATE} class
1621 * option, then the hidden class is added as a member into
1622 * {@linkplain Class#getNestHost() the nest} of this lookup's lookup class.
1623 *
1624 * If {@code options} has {@link ClassOption#WEAK WEAK}, then
1625 * the hidden class is weakly referenced from its defining class loader
1626 * and may be unloaded while its defining class loader is strongly reachable.
1627 *
1628 * The hidden class is initialized if the {@code initialize} parameter is
1629 * {@code true}.
1630 *
1631 * <p> A {@link Class#isHiddenClass() <em>hidden</em>} class has the
1632 * following additional properties:
1633 * <ul>
1634 * <li>Naming:
1635 * The name of a hidden class returned by {@link Class#getName()} is
1636 * defined by the JVM of this form:
1637 * {@code <fully-qualified binary name> + '/' + <suffix>}<br>
1638 * where {@code <fully-qualified binary name>} is the class name
1639 * from the class bytes and {@code <suffix>} must be an unique unqualified
1640 * name (see JVMS 4.2.2)
1641 * <li>Class resolution:
1642 * A hidden class cannot be referenced in other classes and cannot be
1643 * named as a field type, a method parameter type and a method return type.
1644 * It is not discoverable by its class loader for example via
1645 * {@link Class#forName(String, boolean, ClassLoader)},
1646 * {@link ClassLoader#loadClass(String, boolean)} and also bytecode linkage.
1647 * <li>Class retransformation:
1648 * A hidden class is not {@linkplain java.lang.instrument.Instrumentation#isModifiableClass(Class)
1649 * modifiable} by Java agents or tool agents using
1650 * the <a href="{@docRoot}/../specs/jvmti.html">JVM Tool Interface</a>.
1651 * <li>Serialization:
1652 * The default serialization mechanism records the name of a class in
1653 * its serialized form and finds the class by name during deserialization.
1654 * A <em>serializable</em> hidden class requires a custom serialization
1655 * mechanism in order to ensure that instances are properly serialized
1656 * and deserialized.
1657 * </ul>
1658 *
1659 * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must
1660 * have {@code PRIVATE} and {@code MODULE} access to create a hidden class
1661 * in the module of this lookup class.
1662 *
1663 * <p> The {@code bytes} parameter is the class bytes of a valid class file
1664 * (as defined by the <em>The Java Virtual Machine Specification</em>)
1665 * with a class name in the same package as the lookup class.
1666 *
1667 * @param bytes the class bytes
1668 * @param initialize if {@code true} the class will be initialized.
1669 * @param options {@linkplain ClassOption class options}
1670 * @return the {@code Lookup} object on the hidden class
1671 *
1672 * @throws IllegalArgumentException the bytes are for a class in a different package
1673 * to the lookup class
1674 * @throws IllegalAccessException if this lookup does not have {@code PRIVATE} and {@code MODULE} access
1675 * @throws LinkageError if the class is malformed ({@code ClassFormatError}), cannot be
1676 * verified ({@code VerifyError}), is already defined,
1677 * or another linkage error occurs
1678 * @throws SecurityException if a security manager is present and it
1679 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1680 * @throws NullPointerException if {@code bytes} is {@code null}
1681 *
1682 * @since 14
1683 * @see Class#isHiddenClass()
1684 * @jvms 4.2.2 Unqualified Names
1685 * @jls 12.3 Linking of Classes and Interfaces
1686 * @jls 12.4 Initialization of Classes and Interfaces
1687 */
1688 public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
1689 throws IllegalAccessException
1690 {
1691 Objects.requireNonNull(bytes);
1692
1693 checkDefineClassPermission();
1694 if ((lookupModes() & (PRIVATE|MODULE)) != (PRIVATE|MODULE)){
1695 throw new IllegalAccessException(this + " does not have PRIVATE or MODULE access");
1696 }
1697
1698 Set<ClassOption> opts = (options != null && options.length > 0) ? Set.of(options) : Set.of();
1699 Class<?> c = makeHiddenClassDefiner(bytes.clone(), opts).defineClass(initialize, null);
1700 return new Lookup(c, null, FULL_POWER_MODES);
1701 }
1702
1703 /**
1704 * Creates a {@code Lookup} on a <em>hidden class</em> with {@code classData}
1705 * defined to the same class loader and in the same runtime package
1706 * and {@linkplain java.security.ProtectionDomain protection domain} as
1707 * this lookup's {@linkplain #lookupClass() lookup class} with
1708 * the given class options.
1709 *
1710 * <p> This method is equivalent to calling
1711 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)}
1712 * as if the hidden class has a private static final unnamed field
1713 * pre-initialized with the given {@code classData}.
1714 * The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData} method
1715 * can be used to retrieve the {@code classData}.
1716 *
1717 * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must
1718 * have {@code PRIVATE} and {@code MODULE} access in order to create a
1719 * hidden class in the module of this lookup class.
1720 *
1721 * @param bytes the class bytes
1722 * @param classData pre-initialized class data
1723 * @param initialize if {@code true} the class will be initialized.
1724 * @param options {@linkplain ClassOption class options}
1725 * @return the {@code Lookup} object on the hidden class
1726 *
1727 * @throws IllegalArgumentException the bytes are for a class in a different package
1728 * to the lookup class
1729 * @throws IllegalAccessException if this lookup does not have {@code PRIVATE} and {@code MODULE} access
1730 * @throws LinkageError if the class is malformed ({@code ClassFormatError}), cannot be
1731 * verified ({@code VerifyError}), is already defined,
1732 * or another linkage error occurs
1733 * @throws SecurityException if a security manager is present and it
1734 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1735 * @throws NullPointerException if {@code bytes} is {@code null}
1736 *
1737 * @since 14
1738 * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1739 * @see Class#isHiddenClass()
1740 */
1741 /* package-private */ Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options)
1742 throws IllegalAccessException
1743 {
1744 Objects.requireNonNull(bytes);
1745 Objects.requireNonNull(classData);
1746
1747 checkDefineClassPermission();
1748 if ((lookupModes() & (PRIVATE|MODULE)) != (PRIVATE|MODULE)){
1749 throw new IllegalAccessException(this + " does not have PRIVATE or MODULE access");
1750 }
1751
1752 Set<ClassOption> opts = (options != null && options.length > 0) ? Set.of(options) : Set.of();
1753 Class<?> c = makeHiddenClassDefiner(bytes.clone(), opts).defineClass(initialize, classData);
1754 return new Lookup(c, null, FULL_POWER_MODES);
1755 }
1756
1757 private ClassDefiner makeClassDefiner(byte[] bytes) {
1758 return new ClassDefiner(this, bytes, Set.of(), 0);
1759 }
1760
1761 /**
1762 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
1763 * from the given bytes and options.
1764 *
1765 * @param bytes class bytes
1766 * @param options class options
1767 * @return ClassDefiner that defines a hidden class of the given bytes and options
1768 */
1769 ClassDefiner makeHiddenClassDefiner(byte[] bytes, Set<ClassOption> options) {
1770 return new ClassDefiner(this, bytes, options, HIDDEN_CLASS);
1771 }
1772
1773 /**
1774 * This method is only called by MethodHandleImpl.BindCaller.makeInjectedInvoker.
1775 *
1776 * @param name the name of the class and the name in the class bytes is ignored.
1777 * @param bytes class bytes
1778 * @return ClassDefiner that defines a hidden class of the given bytes
1779 */
1780 ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes) {
1781 return new ClassDefiner(this, name, bytes, HIDDEN_CLASS);
1782 }
1783
1784 static class ClassDefiner {
1785 private final Lookup lookup;
1786 private final String name;
1787 private final byte[] bytes;
1788 private final int classFlags;
1789
1790 // caller should make a defensive copy of the arguments if needed
1791 // before calling this constructor
1792 private ClassDefiner(Lookup lookup, byte[] bytes, Set<ClassOption> options, int flags) {
1793 this.lookup = lookup;
1794 this.bytes = bytes;
1795 this.classFlags = flags | ClassOption.optionsToFlag(options);
1796 this.name = className(bytes);
1797
1798 int index = name.lastIndexOf('.');
1799 String pn = (index == -1) ? "" : name.substring(0, index);
1800 if (!pn.equals(lookup.lookupClass().getPackageName())) {
1801 throw newIllegalArgumentException(name + " not in same package as lookup class: " +
1802 lookup.lookupClass().getName());
1803 }
1804 }
1805
1806 // skip package name check
1807 private ClassDefiner(Lookup lookup, String name, byte[] bytes, int flags) {
1808 this.lookup = lookup;
1809 this.bytes = bytes;
1810 this.classFlags = flags;
1811 this.name = name;
1812 }
1813
1814 String className() {
1815 return name;
1816 }
1817
1818 Class<?> defineClass(boolean initialize) {
1819 return defineClass(initialize, null);
1820 }
1821
1822 /**
1823 * Defines the class of the given bytes and the given classData.
1824 * If {@code initialize} parameter is true, then the class will be initialized.
1825 *
1826 * @param initialize true if the class to be initialized
1827 * @param classData classData or null
1828 * @return the class
1829 *
1830 * @throws LinkageError linkage error
1831 */
1832 Class<?> defineClass(boolean initialize, Object classData) {
1833 Class<?> lookupClass = lookup.lookupClass();
1834 ClassLoader loader = lookupClass.getClassLoader();
1835 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
1836 Class<?> c = JLA.defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData);
1837 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
1838 return c;
1839 }
1840
1841 private boolean isNestmate() {
1842 return (classFlags & NESTMATE_CLASS) != 0;
1843 }
1844
1845 private static String className(byte[] bytes) {
1846 try {
1847 ClassReader reader = new ClassReader(bytes);
1848 String name = reader.getClassName();
1849 return name.replace('/', '.');
1850 } catch (IllegalArgumentException e) {
1851 throw e;
1852 } catch (RuntimeException e) {
1853 // ASM exceptions are poorly specified
1854 ClassFormatError cfe = new ClassFormatError();
1855 cfe.initCause(e);
1856 throw cfe;
1857 }
1858 }
1859 }
1860
1861 private ProtectionDomain lookupClassProtectionDomain() {
1862 ProtectionDomain pd = cachedProtectionDomain;
1863 if (pd == null) {
1864 cachedProtectionDomain = pd = JLA.protectionDomain(lookupClass);
1865 }
1866 return pd;
1867 }
1868
1869 // cached protection domain
1870 private volatile ProtectionDomain cachedProtectionDomain;
1871
1872 // Make sure outer class is initialized first.
1873 static { IMPL_NAMES.getClass(); }
1874
1875 /** Package-private version of lookup which is trusted. */
1876 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
1877
1878 /** Version of lookup which is trusted minimally.
1879 * It can only be used to create method handles to publicly accessible
1880 * members in packages that are exported unconditionally.
1881 */
1882 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
1883
1884 static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
1885
1886 private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
1887 String name = lookupClass.getName();
1888 if (name.startsWith("java.lang.invoke."))
1889 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
1890 }
1891
1892 /**
1893 * Displays the name of the class from which lookups are to be made.
1894 * followed with "/" and the name of the {@linkplain #previousLookupClass()
1895 * previous lookup class} if present.
1896 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
1897 * If there are restrictions on the access permitted to this lookup,
1898 * this is indicated by adding a suffix to the class name, consisting
1899 * of a slash and a keyword. The keyword represents the strongest
1900 * allowed access, and is chosen as follows:
1901 * <ul>
1902 * <li>If no access is allowed, the suffix is "/noaccess".
1903 * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
1904 * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
1905 * <li>If only public and module access are allowed, the suffix is "/module".
1924 * @revised 9
1925 * @spec JPMS
1926 */
1927 @Override
1928 public String toString() {
1929 String cname = lookupClass.getName();
1930 if (prevLookupClass != null)
1931 cname += "/" + prevLookupClass.getName();
1932 switch (allowedModes) {
1933 case 0: // no privileges
1934 return cname + "/noaccess";
1935 case UNCONDITIONAL:
1936 return cname + "/publicLookup";
1937 case PUBLIC:
1938 return cname + "/public";
1939 case PUBLIC|MODULE:
1940 return cname + "/module";
1941 case PUBLIC|PACKAGE:
1942 case PUBLIC|MODULE|PACKAGE:
1943 return cname + "/package";
1944 case PUBLIC|PACKAGE|PRIVATE:
1945 case PUBLIC|MODULE|PACKAGE|PRIVATE:
1946 return cname + "/private";
1947 case FULL_POWER_MODES:
1948 case FULL_POWER_MODES & ~(MODULE):
1949 return cname;
1950 case TRUSTED:
1951 return "/trusted"; // internal only; not exported
1952 default: // Should not happen, but it's a bitfield...
1953 cname = cname + "/" + Integer.toHexString(allowedModes);
1954 assert(false) : cname;
1955 return cname;
1956 }
1957 }
1958
1959 /**
1960 * Produces a method handle for a static method.
1961 * The type of the method handle will be that of the method.
1962 * (Since static methods do not take receivers, there is no
1963 * additional receiver argument inserted into the method handle type,
1964 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
1965 * The method and all its argument types must be accessible to the lookup object.
1966 * <p>
1967 * The returned method handle will have
1968 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3472 checkSecurityManager(defc, resolved2);
3473 } catch (SecurityException ex) {
3474 return false;
3475 }
3476 return true;
3477 }
3478 private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
3479 throws ReflectiveOperationException {
3480 if (MethodHandleNatives.refKindIsField(refKind)) {
3481 return getDirectFieldNoSecurityManager(refKind, defc, member);
3482 } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
3483 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass);
3484 } else if (refKind == REF_newInvokeSpecial) {
3485 return getDirectConstructorNoSecurityManager(defc, member);
3486 }
3487 // oops
3488 throw newIllegalArgumentException("bad MethodHandle constant #"+member);
3489 }
3490
3491 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
3492
3493 /**
3494 * The set of class options that specify whether a hidden class created by
3495 * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
3496 * Lookup::defineHiddenMethod} method is dynamically added as
3497 * a new member to the nest of a lookup class and whether a hidden class
3498 * is weakly referenced by its defining class loader.
3499 *
3500 * @since 14
3501 */
3502 public enum ClassOption {
3503 /**
3504 * This class option specifies the hidden class be added to
3505 * {@linkplain Class#getNestHost nest} of a lookup class as
3506 * a nestmate.
3507 *
3508 * <p> A hidden nestmate class has access to the private members of all
3509 * classes and interfaces in the same nest.
3510 *
3511 * @see Class#getNestHost()
3512 */
3513 NESTMATE(NESTMATE_CLASS),
3514
3515 /**
3516 * This class option specifies the hidden class be weakly
3517 * referenced by its defining class loader such that it
3518 * may be unloaded while its defining class loader is
3519 * <a href="../ref/package.html#reachability">strongly reachable</a>.
3520 *
3521 * @jls 12.7 Unloading of Classes and Interfaces
3522 */
3523 WEAK(WEAK_CLASS);
3524
3525 /* the flag value is used by VM at define class time */
3526 private final int flag;
3527 ClassOption(int flag) {
3528 this.flag = flag;
3529 }
3530
3531 static int optionsToFlag(Set<ClassOption> options) {
3532 int flags = 0;
3533 for (ClassOption cp : options) {
3534 flags |= cp.flag;
3535 }
3536 return flags;
3537 }
3538 }
3539 }
3540
3541 /**
3542 * Produces a method handle constructing arrays of a desired type,
3543 * as if by the {@code anewarray} bytecode.
3544 * The return type of the method handle will be the array type.
3545 * The type of its sole argument will be {@code int}, which specifies the size of the array.
3546 *
3547 * <p> If the returned method handle is invoked with a negative
3548 * array size, a {@code NegativeArraySizeException} will be thrown.
3549 *
3550 * @param arrayClass an array type
3551 * @return a method handle which can create arrays of the given type
3552 * @throws NullPointerException if the argument is {@code null}
3553 * @throws IllegalArgumentException if {@code arrayClass} is not an array type
3554 * @see java.lang.reflect.Array#newInstance(Class, int)
3555 * @jvms 6.5 {@code anewarray} Instruction
3556 * @since 9
3557 */
3558 public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
|