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
500 * do not require any access checks, and are used
501 * independently of any {@code Lookup} object.
502 * <p>
503 * If the desired member is {@code protected}, the usual JVM rules apply,
504 * including the requirement that the lookup class must either be in the
505 * same package as the desired member, or must inherit that member.
506 * (See the Java Virtual Machine Specification, sections {@jvms
507 * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
508 * In addition, if the desired member is a non-static field or method
509 * in a different package, the resulting method handle may only be applied
510 * to objects of the lookup class or one of its subclasses.
511 * This requirement is enforced by narrowing the type of the leading
512 * {@code this} parameter from {@code C}
513 * (which will necessarily be a superclass of the lookup class)
514 * to the lookup class itself.
515 * <p>
516 * The JVM imposes a similar requirement on {@code invokespecial} instruction,
517 * that the receiver argument must match both the resolved method <em>and</em>
518 * the current class. Again, this requirement is enforced by narrowing the
519 * type of the leading parameter to the resulting method handle.
520 * (See the Java Virtual Machine Specification, section {@jmvs 4.10.1.9}.)
521 * <p>
522 * The JVM represents constructors and static initializer blocks as internal methods
523 * with special names ({@code "<init>"} and {@code "<clinit>"}).
524 * The internal syntax of invocation instructions allows them to refer to such internal
525 * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
526 * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
527 * <p>
528 * If the relationship between nested types is expressed directly through the
529 * {@code NestHost} and {@code NestMembers} attributes
530 * (see the Java Virtual Machine Specification, sections {@jvms
531 * 4.7.28} and {@jvms 4.7.29}),
532 * then the associated {@code Lookup} object provides direct access to
533 * the lookup class and all of its nestmates
534 * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
535 * Otherwise, access between nested classes is obtained by the Java compiler creating
536 * a wrapper method to access a private method of another class in the same nest.
537 * For example, a nested class {@code C.D}
538 * can access private members within other related classes such as
539 * {@code C}, {@code C.D.E}, or {@code C.B},
540 * but the Java compiler may need to generate wrapper methods in
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
|
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
556 * do not require any access checks, and are used
557 * independently of any {@code Lookup} object.
558 * <p>
559 * If the desired member is {@code protected}, the usual JVM rules apply,
560 * including the requirement that the lookup class must either be in the
561 * same package as the desired member, or must inherit that member.
562 * (See the Java Virtual Machine Specification, sections {@jvms
563 * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
564 * In addition, if the desired member is a non-static field or method
565 * in a different package, the resulting method handle may only be applied
566 * to objects of the lookup class or one of its subclasses.
567 * This requirement is enforced by narrowing the type of the leading
568 * {@code this} parameter from {@code C}
569 * (which will necessarily be a superclass of the lookup class)
570 * to the lookup class itself.
571 * <p>
572 * The JVM imposes a similar requirement on {@code invokespecial} instruction,
573 * that the receiver argument must match both the resolved method <em>and</em>
574 * the current class. Again, this requirement is enforced by narrowing the
575 * type of the leading parameter to the resulting method handle.
576 * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
577 * <p>
578 * The JVM represents constructors and static initializer blocks as internal methods
579 * with special names ({@code "<init>"} and {@code "<clinit>"}).
580 * The internal syntax of invocation instructions allows them to refer to such internal
581 * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
582 * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
583 * <p>
584 * If the relationship between nested types is expressed directly through the
585 * {@code NestHost} and {@code NestMembers} attributes
586 * (see the Java Virtual Machine Specification, sections {@jvms
587 * 4.7.28} and {@jvms 4.7.29}),
588 * then the associated {@code Lookup} object provides direct access to
589 * the lookup class and all of its nestmates
590 * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
591 * Otherwise, access between nested classes is obtained by the Java compiler creating
592 * a wrapper method to access a private method of another class in the same nest.
593 * For example, a nested class {@code C.D}
594 * can access private members within other related classes such as
595 * {@code C}, {@code C.D.E}, or {@code C.B},
596 * but the Java compiler may need to generate wrapper methods in
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 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 IllegalAccessException if this lookup does not have {@code PACKAGE} access
1663 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1664 * @throws IllegalArgumentException the bytes are for a class in a different package
1665 * to the lookup class
1666 * @throws VerifyError if the newly created class cannot be verified
1667 * @throws LinkageError if the newly created class cannot be linked for any other reason
1668 * @throws SecurityException if a security manager is present and it
1669 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1670 * @throws NullPointerException if {@code bytes} is {@code null}
1671 * @since 9
1672 * @spec JPMS
1673 * @see Lookup#privateLookupIn
1674 * @see Lookup#dropLookupMode
1675 * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1676 */
1677 public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1678 ensureDefineClassPermission();
1679 if ((lookupModes() & PACKAGE) == 0)
1680 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1681 return makeClassDefiner(bytes.clone()).defineClass(false);
1682 }
1683
1684 private void ensureDefineClassPermission() {
1685 if (allowedModes == TRUSTED) return;
1686
1687 if (!hasFullPrivilegeAccess()) {
1688 SecurityManager sm = System.getSecurityManager();
1689 if (sm != null)
1690 sm.checkPermission(new RuntimePermission("defineClass"));
1691 }
1692 }
1693
1694 /**
1695 * The set of class options that specify whether a hidden class created by
1696 * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1697 * Lookup::defineHiddenClass} method is dynamically added as a new member
1698 * to the nest of a lookup class and/or whether a hidden class has
1699 * a strong relationship with the class loader marked as its defining loader.
1700 *
1701 * @since 15
1702 */
1703 public enum ClassOption {
1704 /**
1705 * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest}
1706 * of a lookup class as a nestmate.
1707 *
1708 * <p> A hidden nestmate class has access to the private members of all
1709 * classes and interfaces in the same nest.
1710 *
1711 * @see Class#getNestHost()
1712 */
1713 NESTMATE(NESTMATE_CLASS),
1714
1715 /**
1716 * Specifies that a hidden class has a <em>strong</em>
1717 * relationship with the class loader marked as its defining loader,
1718 * as a normal class or interface has with its own defining loader.
1719 * This means that the hidden class may be unloaded if and only if
1720 * its defining loader is not reachable and thus may be reclaimed
1721 * by a garbage collector (JLS 12.7).
1722 *
1723 * <p> By default, a hidden class or interface may be unloaded
1724 * even if the class loader that is marked as its defining loader is
1725 * <a href="../ref/package.html#reachability">reachable</a>.
1726
1727 *
1728 * @jls 12.7 Unloading of Classes and Interfaces
1729 */
1730 STRONG(STRONG_LOADER_LINK);
1731
1732 /* the flag value is used by VM at define class time */
1733 private final int flag;
1734 ClassOption(int flag) {
1735 this.flag = flag;
1736 }
1737
1738 static int optionsToFlag(Set<ClassOption> options) {
1739 int flags = 0;
1740 for (ClassOption cp : options) {
1741 flags |= cp.flag;
1742 }
1743 return flags;
1744 }
1745 }
1746
1747 /**
1748 * Creates a <em>hidden</em> class or interface from {@code bytes},
1749 * returning a {@code Lookup} on the newly created class or interface.
1750 *
1751 * <p> Ordinarily, a class or interface {@code C} is created by a class loader,
1752 * which either defines {@code C} directly or delegates to another class loader.
1753 * A class loader defines {@code C} directly by invoking
1754 * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1755 * ClassLoader::defineClass}, which causes the Java Virtual Machine
1756 * to derive {@code C} from a purported representation in {@code class} file format.
1757 * In situations where use of a class loader is undesirable, a class or interface
1758 * {@code C} can be created by this method instead. This method is capable of
1759 * defining {@code C}, and thereby creating it, without invoking
1760 * {@code ClassLoader::defineClass}.
1761 * Instead, this method defines {@code C} as if by arranging for
1762 * the Java Virtual Machine to derive a nonarray class or interface {@code C}
1763 * from a purported representation in {@code class} file format
1764 * using the following rules:
1765 *
1766 * <ol>
1767 * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup}
1768 * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access.
1769 * This level of access is needed to create {@code C} in the module
1770 * of the lookup class of this {@code Lookup}.</li>
1771 *
1772 * <li> The purported representation in {@code bytes} must be a {@code ClassFile}
1773 * structure of a supported major and minor version. The major and minor version
1774 * may differ from the {@code class} file version of the lookup class of this
1775 * {@code Lookup}.</li>
1776 *
1777 * <li> The value of {@code this_class} must be a valid index in the
1778 * {@code constant_pool} table, and the entry at that index must be a valid
1779 * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name
1780 * encoded in internal form that is specified by this structure. {@code N} must
1781 * denote a class or interface in the same package as the lookup class.</li>
1782 *
1783 * <li> Let {@code CN} be the string {@code N + "." + <suffix>},
1784 * where {@code <suffix>} is an unqualified name that is guaranteed to be unique
1785 * during this execution of the JVM.
1786 *
1787 * <p> Let {@code newBytes} be the {@code ClassFile} structure given by
1788 * {@code bytes} with an additional entry in the {@code constant_pool} table,
1789 * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and
1790 * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class}
1791 * refers to the new {@code CONSTANT_Utf8_info} structure.
1792 *
1793 * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}.
1794 *
1795 * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and
1796 * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5},
1797 * with the following adjustments:
1798 * <ul>
1799 * <li> The constant indicated by {@code this_class} is permitted to specify a name
1800 * that includes a single {@code "."} character, even though this is not a valid
1801 * binary class or interface name in internal form.</li>
1802 *
1803 * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C},
1804 * but no class loader is recorded as an initiating class loader of {@code C}.</li>
1805 *
1806 * <li> {@code C} is considered to have the same runtime
1807 * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module}
1808 * and {@linkplain java.security.ProtectionDomain protection domain}
1809 * as the lookup class of this {@code Lookup}.
1810 * <li> Let {@code GN} be the binary name obtained by taking {@code N}
1811 * (a binary name encoded in internal form) and replacing ASCII forward slashes with
1812 * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C},
1813 * {@link Class#getName()} returns the string {@code GN + "/" + <suffix>}, even though
1814 * this is not a valid binary class or interface name.</li>
1815 * </ul>
1816 * </li>
1817 * </ol>
1818 *
1819 * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
1820 * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments:
1821 * <ul>
1822 * <li> During verification, whenever it is necessary to load the class named
1823 * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
1824 * made of any class loader.</li>
1825 *
1826 * <li> On any attempt to resolve the entry in the run-time constant pool indicated
1827 * by {@code this_class}, the symbolic reference is considered to be resolved to
1828 * {@code C} and resolution always succeeds immediately.</li>
1829 * </ul>
1830 *
1831 * <p> If the {@code initialize} parameter is {@code true},
1832 * then {@code C} is initialized by the Java Virtual Machine.
1833 *
1834 * <p> The newly created class or interface {@code C} serves as the
1835 * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object
1836 * returned by this method. {@code C} is <em>hidden</em> in the sense that
1837 * no other class or interface can refer to {@code C} via a constant pool entry.
1838 * That is, a hidden class or interface cannot be named as a supertype, a field type,
1839 * a method parameter type, or a method return type by any other class.
1840 * This is because a hidden class or interface does not have a binary name, so
1841 * there is no internal form available to record in any class's constant pool.
1842 * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
1843 * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
1844 * is not {@linkplain java.lang.instrument.Instrumentation#isModifiableClass(Class)
1845 * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
1846 * JVM Tool Interface</a>.
1847 *
1848 * <p> A class or interface created by
1849 * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1850 * a class loader} has a strong relationship with that class loader.
1851 * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
1852 * that {@linkplain Class#getClassLoader() defined it}.
1853 * This means that a class created by a class loader may be unloaded if and
1854 * only if its defining loader is not reachable and thus may be reclaimed
1855 * by a garbage collector (JLS 12.7).
1856 *
1857 * By default, however, a hidden class or interface may be unloaded even if
1858 * the class loader that is marked as its defining loader is
1859 * <a href="../ref/package.html#reachability">reachable</a>.
1860 * This behavior is useful when a hidden class or interface serves multiple
1861 * classes defined by arbitrary class loaders. In other cases, a hidden
1862 * class or interface may be linked to a single class (or a small number of classes)
1863 * with the same defining loader as the hidden class or interface.
1864 * In such cases, where the hidden class or interface must be coterminous
1865 * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
1866 * option may be passed in {@code options}.
1867 * This arranges for a hidden class to have the same strong relationship
1868 * with the class loader marked as its defining loader,
1869 * as a normal class or interface has with its own defining loader.
1870 *
1871 * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
1872 * may still prevent a hidden class or interface from being
1873 * unloaded by ensuring that the {@code Class} object is reachable.
1874 *
1875 * <p> The unloading characteristics are set for each hidden class when it is
1876 * defined, and cannot be changed later. An advantage of allowing hidden classes
1877 * to be unloaded independently of the class loader marked as their defining loader
1878 * is that a very large number of hidden classes may be created by an application.
1879 * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
1880 * just as if normal classes were created by class loaders.
1881 *
1882 * <p> Classes and interfaces in a nest are allowed to have mutual access to
1883 * their private members. The nest relationship is determined by
1884 * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and
1885 * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file.
1886 * By default, a hidden class belongs to a nest consisting only of itself
1887 * because a hidden class has no binary name.
1888 * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
1889 * to create a hidden class or interface {@code C} as a member of a nest.
1890 * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
1891 * in the {@code ClassFile} structure from which {@code C} was derived.
1892 * Instead, the following rules determine the nest host of {@code C}:
1893 * <ul>
1894 * <li>If the nest host of the lookup class of this {@code Lookup} has previously
1895 * been determined, then let {@code H} be the nest host of the lookup class.
1896 * Otherwise, the nest host of the lookup class is determined using the
1897 * algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li>
1898 * <li>The nest host of {@code C} is determined to be {@code H},
1899 * the nest host of the lookup class.</li>
1900 * </ul>
1901 *
1902 * <p> A hidden class or interface may be serializable, but this requires a custom
1903 * serialization mechanism in order to ensure that instances are properly serialized
1904 * and deserialized. The default serialization mechanism supports only classes and
1905 * interfaces that are discoverable by their class name.
1906 *
1907 * @param bytes the bytes that make up the class data,
1908 * in the format of a valid {@code class} file as defined by
1909 * <cite>The Java Virtual Machine Specification</cite>.
1910 * @param initialize if {@code true} the class will be initialized.
1911 * @param options {@linkplain ClassOption class options}
1912 * @return the {@code Lookup} object on the hidden class
1913 *
1914 * @throws IllegalAccessException if this {@code Lookup} does not have
1915 * {@linkplain #hasFullPrivilegeAccess() full privilege} access
1916 * @throws SecurityException if a security manager is present and it
1917 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1918 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1919 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
1920 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
1921 * {@bytes} denotes a class in a different package than the lookup class
1922 * @throws IncompatibleClassChangeError if the class or interface named as
1923 * the direct superclass of {@code C} is in fact an interface, or if any of the classes
1924 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
1925 * @throws ClassCircularityError if any of the superclasses or superinterfaces of
1926 * {@code C} is {@code C} itself
1927 * @throws VerifyError if the newly created class cannot be verified
1928 * @throws LinkageError if the newly created class cannot be linked for any other reason
1929 * @throws NullPointerException if any parameter is {@code null}
1930 *
1931 * @since 15
1932 * @see Class#isHidden()
1933 * @jvms 4.2.1 Binary Class and Interface Names
1934 * @jvms 4.2.2 Unqualified Names
1935 * @jvms 4.7.28 The {@code NestHost} Attribute
1936 * @jvms 4.7.29 The {@code NestMembers} Attribute
1937 * @jvms 5.4.3.1 Class and Interface Resolution
1938 * @jvms 5.4.4 Access Control
1939 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
1940 * @jvms 5.4 Linking
1941 * @jvms 5.5 Initialization
1942 * @jls 12.7 Unloading of Classes and Interfaces
1943 */
1944 public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
1945 throws IllegalAccessException
1946 {
1947 Objects.requireNonNull(bytes);
1948 Objects.requireNonNull(options);
1949
1950 ensureDefineClassPermission();
1951 if (!hasFullPrivilegeAccess()) {
1952 throw new IllegalAccessException(this + " does not have full privilege access");
1953 }
1954
1955 return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize);
1956 }
1957
1958 /**
1959 * Creates a <em>hidden</em> class or interface from {@code bytes} with associated
1960 * {@linkplain MethodHandles#classData(Lookup, String, Class) class data},
1961 * returning a {@code Lookup} on the newly created class or interface.
1962 *
1963 * <p> This method is equivalent to calling
1964 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, true, options)}
1965 * as if the hidden class has a private static final unnamed field whose value
1966 * is initialized to {@code classData} right before the class initializer is
1967 * executed. The newly created class is linked and initialized by the Java
1968 * Virtual Machine.
1969 *
1970 * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData}
1971 * method can be used to retrieve the {@code classData}.
1972 *
1973 * @param bytes the class bytes
1974 * @param classData pre-initialized class data
1975 * @param options {@linkplain ClassOption class options}
1976 * @return the {@code Lookup} object on the hidden class
1977 *
1978 * @throws IllegalAccessException if this {@code Lookup} does not have
1979 * {@linkplain #hasFullPrivilegeAccess() full privilege} access
1980 * @throws SecurityException if a security manager is present and it
1981 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1982 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1983 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
1984 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
1985 * {@bytes} denotes a class in a different package than the lookup class
1986 * @throws IncompatibleClassChangeError if the class or interface named as
1987 * the direct superclass of {@code C} is in fact an interface, or if any of the classes
1988 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
1989 * @throws ClassCircularityError if any of the superclasses or superinterfaces of
1990 * {@code C} is {@code C} itself
1991 * @throws VerifyError if the newly created class cannot be verified
1992 * @throws LinkageError if the newly created class cannot be linked for any other reason
1993 * @throws NullPointerException if any parameter is {@code null}
1994 *
1995 * @since 15
1996 * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1997 * @see Class#isHidden()
1998 */
1999 /* package-private */ Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, ClassOption... options)
2000 throws IllegalAccessException
2001 {
2002 Objects.requireNonNull(bytes);
2003 Objects.requireNonNull(classData);
2004 Objects.requireNonNull(options);
2005
2006 ensureDefineClassPermission();
2007 if (!hasFullPrivilegeAccess()) {
2008 throw new IllegalAccessException(this + " does not have full privilege access");
2009 }
2010
2011 return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false)
2012 .defineClassAsLookup(true, classData);
2013 }
2014
2015 /*
2016 * Validates the given bytes to be a class or interface and the class name
2017 * is in the same package as the lookup class.
2018 *
2019 * This method returns the class name.
2020 */
2021 private String validateAndGetClassName(byte[] bytes) {
2022 try {
2023 ClassReader reader = new ClassReader(bytes);
2024 if ((reader.getAccess() & Opcodes.ACC_MODULE) != 0) {
2025 throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set");
2026 }
2027 String name = reader.getClassName().replace('/', '.');
2028 int index = name.lastIndexOf('.');
2029 String pn = (index == -1) ? "" : name.substring(0, index);
2030 if (!pn.equals(lookupClass.getPackageName())) {
2031 throw newIllegalArgumentException(name + " not in same package as lookup class: " +
2032 lookupClass.getName());
2033 }
2034 return name;
2035 } catch (IllegalArgumentException e) {
2036 throw e;
2037 } catch (RuntimeException e) {
2038 // ASM exceptions are poorly specified
2039 ClassFormatError cfe = new ClassFormatError();
2040 cfe.initCause(e);
2041 throw cfe;
2042 }
2043 }
2044
2045
2046 /*
2047 * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2048 * from the given bytes.
2049 *
2050 * Caller should make a defensive copy of the arguments if needed
2051 * before calling this factory method.
2052 *
2053 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2054 * {@bytes} denotes a class in a different package than the lookup class
2055 */
2056 private ClassDefiner makeClassDefiner(byte[] bytes) {
2057 return new ClassDefiner(this, validateAndGetClassName(bytes), bytes, STRONG_LOADER_LINK);
2058 }
2059
2060 /**
2061 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2062 * from the given bytes. The name must be in the same package as the lookup class.
2063 *
2064 * Caller should make a defensive copy of the arguments if needed
2065 * before calling this factory method.
2066 *
2067 * @param bytes class bytes
2068 * @return ClassDefiner that defines a hidden class of the given bytes.
2069 *
2070 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2071 * {@bytes} denotes a class in a different package than the lookup class
2072 */
2073 ClassDefiner makeHiddenClassDefiner(byte[] bytes) {
2074 return makeHiddenClassDefiner(validateAndGetClassName(bytes), bytes, Set.of(), false);
2075 }
2076
2077 /**
2078 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2079 * from the given bytes and options.
2080 * The name must be in the same package as the lookup class.
2081 *
2082 * Caller should make a defensive copy of the arguments if needed
2083 * before calling this factory method.
2084 *
2085 * @param bytes class bytes
2086 * @param options class options
2087 * @param accessVmAnnotations true to give the hidden class access to VM annotations
2088 * @return ClassDefiner that defines a hidden class of the given bytes and options
2089 *
2090 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2091 * {@bytes} denotes a class in a different package than the lookup class
2092 */
2093 ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2094 Set<ClassOption> options,
2095 boolean accessVmAnnotations) {
2096 return makeHiddenClassDefiner(validateAndGetClassName(bytes), bytes, options, accessVmAnnotations);
2097 }
2098
2099 /**
2100 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2101 * from the given bytes. No package name check on the given name.
2102 *
2103 * @param name fully-qualified name that specifies the prefix of the hidden class
2104 * @param bytes class bytes
2105 * @return ClassDefiner that defines a hidden class of the given bytes.
2106 */
2107 ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes) {
2108 return makeHiddenClassDefiner(name, bytes, Set.of(), false);
2109 }
2110
2111 /**
2112 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2113 * from the given bytes and options. No package name check on the given name.
2114 *
2115 * @param name the name of the class and the name in the class bytes is ignored.
2116 * @param bytes class bytes
2117 * @param options class options
2118 * @param accessVmAnnotations true to give the hidden class access to VM annotations
2119 */
2120 ClassDefiner makeHiddenClassDefiner(String name,
2121 byte[] bytes,
2122 Set<ClassOption> options,
2123 boolean accessVmAnnotations) {
2124 int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2125 if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2126 // jdk.internal.vm.annotations are permitted for classes
2127 // defined to boot loader and platform loader
2128 flags |= ACCESS_VM_ANNOTATIONS;
2129 }
2130
2131 return new ClassDefiner(this, name, bytes, flags);
2132 }
2133
2134 static class ClassDefiner {
2135 private final Lookup lookup;
2136 private final String name;
2137 private final byte[] bytes;
2138 private final int classFlags;
2139
2140 private ClassDefiner(Lookup lookup, String name, byte[] bytes, int flags) {
2141 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2142 this.lookup = lookup;
2143 this.bytes = bytes;
2144 this.classFlags = flags;
2145 this.name = name;
2146 }
2147
2148 String className() {
2149 return name;
2150 }
2151
2152 Class<?> defineClass(boolean initialize) {
2153 return defineClass(initialize, null);
2154 }
2155
2156 Lookup defineClassAsLookup(boolean initialize) {
2157 Class<?> c = defineClass(initialize, null);
2158 return new Lookup(c, null, FULL_POWER_MODES);
2159 }
2160
2161 /**
2162 * Defines the class of the given bytes and the given classData.
2163 * If {@code initialize} parameter is true, then the class will be initialized.
2164 *
2165 * @param initialize true if the class to be initialized
2166 * @param classData classData or null
2167 * @return the class
2168 *
2169 * @throws LinkageError linkage error
2170 */
2171 Class<?> defineClass(boolean initialize, Object classData) {
2172 Class<?> lookupClass = lookup.lookupClass();
2173 ClassLoader loader = lookupClass.getClassLoader();
2174 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
2175 Class<?> c = JLA.defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData);
2176 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
2177 return c;
2178 }
2179
2180 Lookup defineClassAsLookup(boolean initialize, Object classData) {
2181 // initialize must be true if classData is non-null
2182 assert classData == null || initialize == true;
2183 Class<?> c = defineClass(initialize, classData);
2184 return new Lookup(c, null, FULL_POWER_MODES);
2185 }
2186
2187 private boolean isNestmate() {
2188 return (classFlags & NESTMATE_CLASS) != 0;
2189 }
2190 }
2191
2192 private ProtectionDomain lookupClassProtectionDomain() {
2193 ProtectionDomain pd = cachedProtectionDomain;
2194 if (pd == null) {
2195 cachedProtectionDomain = pd = JLA.protectionDomain(lookupClass);
2196 }
2197 return pd;
2198 }
2199
2200 // cached protection domain
2201 private volatile ProtectionDomain cachedProtectionDomain;
2202
2203 // Make sure outer class is initialized first.
2204 static { IMPL_NAMES.getClass(); }
2205
2206 /** Package-private version of lookup which is trusted. */
2207 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
2208
2209 /** Version of lookup which is trusted minimally.
2210 * It can only be used to create method handles to publicly accessible
2211 * members in packages that are exported unconditionally.
2212 */
2213 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
2214
2215 static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
2216
2217 private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2218 String name = lookupClass.getName();
2219 if (name.startsWith("java.lang.invoke."))
2220 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
2221 }
2222
2223 /**
2224 * Displays the name of the class from which lookups are to be made.
2225 * followed with "/" and the name of the {@linkplain #previousLookupClass()
2226 * previous lookup class} if present.
2227 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
2228 * If there are restrictions on the access permitted to this lookup,
2229 * this is indicated by adding a suffix to the class name, consisting
2230 * of a slash and a keyword. The keyword represents the strongest
2231 * allowed access, and is chosen as follows:
2232 * <ul>
2233 * <li>If no access is allowed, the suffix is "/noaccess".
2234 * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
2235 * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
2236 * <li>If only public and module access are allowed, the suffix is "/module".
3147 * the {@code Field} object's {@code set} method could return
3148 * normally. In particular, fields which are both {@code static}
3149 * and {@code final} may never be set.
3150 * <p>
3151 * If the field is {@code static}, and
3152 * if the returned method handle is invoked, the field's class will
3153 * be initialized, if it has not already been initialized.
3154 * @param f the reflected field
3155 * @return a method handle which can store values into the reflected field
3156 * @throws IllegalAccessException if access checking fails,
3157 * or if the field is {@code final} and write access
3158 * is not enabled on the {@code Field} object
3159 * @throws NullPointerException if the argument is null
3160 */
3161 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3162 return unreflectField(f, true);
3163 }
3164
3165 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3166 MemberName field = new MemberName(f, isSetter);
3167 if (isSetter && field.isFinal()) {
3168 if (field.isStatic()) {
3169 throw field.makeAccessException("static final field has no write access", this);
3170 } else if (field.getDeclaringClass().isHidden()){
3171 throw field.makeAccessException("final field in a hidden class has no write access", this);
3172 }
3173 }
3174 assert(isSetter
3175 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3176 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3177 @SuppressWarnings("deprecation")
3178 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
3179 return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
3180 }
3181
3182 /**
3183 * Produces a VarHandle giving access to a reflected field {@code f}
3184 * of type {@code T} declared in a class of type {@code R}.
3185 * The VarHandle's variable type is {@code T}.
3186 * If the field is non-static the VarHandle has one coordinate type,
3187 * {@code R}. Otherwise, the field is static, and the VarHandle has no
3188 * coordinate types.
3189 * <p>
3190 * Access checking is performed immediately on behalf of the lookup
3191 * class, regardless of the value of the field's {@code accessible}
3192 * flag.
3193 * <p>
3714 if (!putField.isFinal()) {
3715 // A VarHandle does not support updates to final fields, any
3716 // such VarHandle to a final field will be read-only and
3717 // therefore the following write-based accessibility checks are
3718 // only required for non-final fields
3719 checkField(putRefKind, refc, putField);
3720 if (checkSecurity)
3721 checkSecurityManager(refc, putField);
3722 }
3723
3724 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
3725 restrictProtectedReceiver(getField));
3726 if (doRestrict) {
3727 assert !getField.isStatic();
3728 // receiver type of VarHandle is too wide; narrow to caller
3729 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
3730 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
3731 }
3732 refc = lookupClass();
3733 }
3734 return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(),
3735 this.allowedModes == TRUSTED && !getField.getDeclaringClass().isHidden());
3736 }
3737 /** Check access and get the requested constructor. */
3738 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
3739 final boolean checkSecurity = true;
3740 return getDirectConstructorCommon(refc, ctor, checkSecurity);
3741 }
3742 /** Check access and get the requested constructor, eliding security manager checks. */
3743 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
3744 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants
3745 return getDirectConstructorCommon(refc, ctor, checkSecurity);
3746 }
3747 /** Common code for all constructors; do not call directly except from immediately above. */
3748 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
3749 boolean checkSecurity) throws IllegalAccessException {
3750 assert(ctor.isConstructor());
3751 checkAccess(REF_newInvokeSpecial, refc, ctor);
3752 // Optionally check with the security manager; this isn't needed for unreflect* calls.
3753 if (checkSecurity)
3754 checkSecurityManager(refc, ctor);
3755 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here
|