< prev index next >

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

Print this page

   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.misc.Unsafe;
  30 import jdk.internal.misc.VM;
  31 import jdk.internal.org.objectweb.asm.ClassReader;
  32 import jdk.internal.org.objectweb.asm.Opcodes;
  33 import jdk.internal.org.objectweb.asm.Type;
  34 import jdk.internal.reflect.CallerSensitive;
  35 import jdk.internal.reflect.CallerSensitiveAdapter;
  36 import jdk.internal.reflect.Reflection;
  37 import jdk.internal.util.ClassFileDumper;

  38 import jdk.internal.vm.annotation.ForceInline;
  39 import sun.invoke.util.ValueConversions;
  40 import sun.invoke.util.VerifyAccess;
  41 import sun.invoke.util.Wrapper;
  42 import sun.reflect.misc.ReflectUtil;
  43 import sun.security.util.SecurityConstants;
  44 
  45 import java.lang.constant.ConstantDescs;
  46 import java.lang.invoke.LambdaForm.BasicType;
  47 import java.lang.reflect.Constructor;
  48 import java.lang.reflect.Field;
  49 import java.lang.reflect.Member;
  50 import java.lang.reflect.Method;
  51 import java.lang.reflect.Modifier;
  52 import java.nio.ByteOrder;
  53 import java.security.ProtectionDomain;
  54 import java.util.ArrayList;
  55 import java.util.Arrays;
  56 import java.util.BitSet;
  57 import java.util.Comparator;

 688      * If the desired member is {@code protected}, the usual JVM rules apply,
 689      * including the requirement that the lookup class must either be in the
 690      * same package as the desired member, or must inherit that member.
 691      * (See the Java Virtual Machine Specification, sections {@jvms
 692      * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
 693      * In addition, if the desired member is a non-static field or method
 694      * in a different package, the resulting method handle may only be applied
 695      * to objects of the lookup class or one of its subclasses.
 696      * This requirement is enforced by narrowing the type of the leading
 697      * {@code this} parameter from {@code C}
 698      * (which will necessarily be a superclass of the lookup class)
 699      * to the lookup class itself.
 700      * <p>
 701      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 702      * that the receiver argument must match both the resolved method <em>and</em>
 703      * the current class.  Again, this requirement is enforced by narrowing the
 704      * type of the leading parameter to the resulting method handle.
 705      * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
 706      * <p>
 707      * The JVM represents constructors and static initializer blocks as internal methods
 708      * with special names ({@value ConstantDescs#INIT_NAME} and {@value
 709      * ConstantDescs#CLASS_INIT_NAME}).
 710      * The internal syntax of invocation instructions allows them to refer to such internal
 711      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 712      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 713      * <p>
 714      * If the relationship between nested types is expressed directly through the
 715      * {@code NestHost} and {@code NestMembers} attributes
 716      * (see the Java Virtual Machine Specification, sections {@jvms
 717      * 4.7.28} and {@jvms 4.7.29}),
 718      * then the associated {@code Lookup} object provides direct access to
 719      * the lookup class and all of its nestmates
 720      * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
 721      * Otherwise, access between nested classes is obtained by the Java compiler creating
 722      * a wrapper method to access a private method of another class in the same nest.
 723      * For example, a nested class {@code C.D}
 724      * can access private members within other related classes such as
 725      * {@code C}, {@code C.D.E}, or {@code C.B},
 726      * but the Java compiler may need to generate wrapper methods in
 727      * those related classes.  In such cases, a {@code Lookup} object on
 728      * {@code C.E} would be unable to access those private members.
 729      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,

1609          *  so that it can access only names which can be reached by the original
1610          *  lookup object, and also by the new lookup class.
1611          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1612          *  @see #in
1613          *  @see #dropLookupMode
1614          */
1615         public int lookupModes() {
1616             return allowedModes & ALL_MODES;
1617         }
1618 
1619         /** Embody the current class (the lookupClass) as a lookup class
1620          * for method handle creation.
1621          * Must be called by from a method in this package,
1622          * which in turn is called by a method not in this package.
1623          */
1624         Lookup(Class<?> lookupClass) {
1625             this(lookupClass, null, FULL_POWER_MODES);
1626         }
1627 
1628         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {

1629             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1630                     && prevLookupClass.getModule() != lookupClass.getModule());
1631             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1632             this.lookupClass = lookupClass;
1633             this.prevLookupClass = prevLookupClass;
1634             this.allowedModes = allowedModes;
1635         }
1636 
1637         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1638             // make sure we haven't accidentally picked up a privileged class:
1639             checkUnprivilegedlookupClass(lookupClass);
1640             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1641         }
1642 
1643         /**
1644          * Creates a lookup on the specified new lookup class.
1645          * The resulting object will report the specified
1646          * class as its own {@link #lookupClass() lookupClass}.
1647          *
1648          * <p>

2786          * If the returned method handle is invoked, the constructor's class will
2787          * be initialized, if it has not already been initialized.
2788          * <p><b>Example:</b>
2789          * {@snippet lang="java" :
2790 import static java.lang.invoke.MethodHandles.*;
2791 import static java.lang.invoke.MethodType.*;
2792 ...
2793 MethodHandle MH_newArrayList = publicLookup().findConstructor(
2794   ArrayList.class, methodType(void.class, Collection.class));
2795 Collection orig = Arrays.asList("x", "y");
2796 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
2797 assert(orig != copy);
2798 assertEquals(orig, copy);
2799 // a variable-arity constructor:
2800 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
2801   ProcessBuilder.class, methodType(void.class, String[].class));
2802 ProcessBuilder pb = (ProcessBuilder)
2803   MH_newProcessBuilder.invoke("x", "y", "z");
2804 assertEquals("[x, y, z]", pb.command().toString());
2805          * }


2806          * @param refc the class or interface from which the method is accessed
2807          * @param type the type of the method, with the receiver argument omitted, and a void return type
2808          * @return the desired method handle
2809          * @throws NoSuchMethodException if the constructor does not exist
2810          * @throws IllegalAccessException if access checking fails
2811          *                                or if the method's variable arity modifier bit
2812          *                                is set and {@code asVarargsCollector} fails
2813          * @throws    SecurityException if a security manager is present and it
2814          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2815          * @throws NullPointerException if any argument is null
2816          */
2817         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2818             if (refc.isArray()) {
2819                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2820             }



2821             String name = ConstantDescs.INIT_NAME;
2822             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2823             return getDirectConstructor(refc, ctor);
2824         }
2825 
2826         /**
2827          * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2828          * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2829          * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class,
2830          * and then determines whether the class is accessible to this lookup object.
2831          * <p>
2832          * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}.
2833          * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences
2834          * of {@code '['} and followed by the element type as encoded in the
2835          * {@linkplain Class##nameFormat table} specified in {@link Class#getName}.
2836          * <p>
2837          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2838          * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2839          *
2840          * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class

3496          * arguments passed to the method handle.
3497          * <p>
3498          * If the constructor's {@code accessible} flag is not set,
3499          * access checking is performed immediately on behalf of the lookup class.
3500          * <p>
3501          * The returned method handle will have
3502          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3503          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3504          * <p>
3505          * If the returned method handle is invoked, the constructor's class will
3506          * be initialized, if it has not already been initialized.
3507          * @param c the reflected constructor
3508          * @return a method handle which can invoke the reflected constructor
3509          * @throws IllegalAccessException if access checking fails
3510          *                                or if the method's variable arity modifier bit
3511          *                                is set and {@code asVarargsCollector} fails
3512          * @throws NullPointerException if the argument is null
3513          */
3514         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3515             MemberName ctor = new MemberName(c);
3516             assert(ctor.isConstructor());
3517             @SuppressWarnings("deprecation")
3518             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3519             return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);









3520         }
3521 
3522         /*
3523          * Produces a method handle that is capable of creating instances of the given class
3524          * and instantiated by the given constructor.  No security manager check.
3525          *
3526          * This method should only be used by ReflectionFactory::newConstructorForSerialization.
3527          */
3528         /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException {
3529             MemberName ctor = new MemberName(c);
3530             assert(ctor.isConstructor() && constructorInSuperclass(decl, c));
3531             checkAccess(REF_newInvokeSpecial, decl, ctor);
3532             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
3533             return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor);
3534         }
3535 
3536         private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) {
3537             if (decl == ctor.getDeclaringClass())
3538                 return true;
3539 
3540             Class<?> cl = decl;
3541             while ((cl = cl.getSuperclass()) != null) {
3542                 if (cl == ctor.getDeclaringClass()) {
3543                     return true;
3544                 }
3545             }
3546             return false;
3547         }
3548 
3549         /**
3550          * Produces a method handle giving read access to a reflected field.

3771                                             ReflectiveOperationException.class);
3772         }
3773 
3774         MemberName resolveOrNull(byte refKind, MemberName member) {
3775             // do this before attempting to resolve
3776             if (!isClassAccessible(member.getDeclaringClass())) {
3777                 return null;
3778             }
3779             Objects.requireNonNull(member.getName());
3780             Objects.requireNonNull(member.getType());
3781             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes);
3782         }
3783 
3784         MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) {
3785             // do this before attempting to resolve
3786             if (!isClassAccessible(refc)) {
3787                 return null;
3788             }
3789             Objects.requireNonNull(type);
3790             // implicit null-check of name
3791             if (name.startsWith("<") && refKind != REF_newInvokeSpecial) {
3792                 return null;
3793             }

3794             return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes);
3795         }
3796 
3797         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
3798             if (!isClassAccessible(refc)) {
3799                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
3800             }
3801         }
3802 
3803         boolean isClassAccessible(Class<?> refc) {
3804             Objects.requireNonNull(refc);
3805             Class<?> caller = lookupClassOrNull();
3806             Class<?> type = refc;
3807             while (type.isArray()) {
3808                 type = type.getComponentType();
3809             }
3810             return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes);
3811         }
3812 












3813         /** Check name for an illegal leading "&lt;" character. */
3814         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3815             if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
3816                 throw new NoSuchMethodException("illegal method name: "+name);

3817         }
3818 
3819         /**
3820          * Find my trustable caller class if m is a caller sensitive method.
3821          * If this lookup object has original full privilege access, then the caller class is the lookupClass.
3822          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3823          */
3824         Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3825             if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) {
3826                 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3827                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3828             }
3829             return this;
3830         }
3831 
3832         /**
3833          * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3834          * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3835          *
3836          * @deprecated This method was originally designed to test {@code PRIVATE} access

3900 
3901             @SuppressWarnings("removal")
3902             SecurityManager smgr = System.getSecurityManager();
3903             if (smgr == null)  return;
3904 
3905             // Step 1:
3906             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3907             if (!fullPrivilegeLookup ||
3908                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3909                 ReflectUtil.checkPackageAccess(refc);
3910             }
3911 
3912             // Step 2a:
3913             if (m.isPublic()) return;
3914             if (!fullPrivilegeLookup) {
3915                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3916             }
3917 
3918             // Step 3:
3919             Class<?> defc = m.getDeclaringClass();
3920             if (!fullPrivilegeLookup && defc != refc) {
3921                 ReflectUtil.checkPackageAccess(defc);
3922             }
3923         }
3924 
3925         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3926             boolean wantStatic = (refKind == REF_invokeStatic);
3927             String message;
3928             if (m.isConstructor())
3929                 message = "expected a method, not a constructor";
3930             else if (!m.isMethod())
3931                 message = "expected a method";
3932             else if (wantStatic != m.isStatic())
3933                 message = wantStatic ? "expected a static method" : "expected a non-static method";
3934             else
3935                 { checkAccess(refKind, refc, m); return; }
3936             throw m.makeAccessException(message, this);
3937         }
3938 
3939         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3940             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3941             String message;
3942             if (wantStatic != m.isStatic())
3943                 message = wantStatic ? "expected a static field" : "expected a non-static field";
3944             else
3945                 { checkAccess(refKind, refc, m); return; }
3946             throw m.makeAccessException(message, this);
3947         }
3948 

3987                 throw m.makeAccessException("unexpected set of a final field", this);
3988             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
3989             if ((requestedModes & allowedModes) != 0) {
3990                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
3991                                                     mods, lookupClass(), previousLookupClass(), allowedModes))
3992                     return;
3993             } else {
3994                 // Protected members can also be checked as if they were package-private.
3995                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
3996                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
3997                     return;
3998             }
3999             throw m.makeAccessException(accessFailedMessage(refc, m), this);
4000         }
4001 
4002         String accessFailedMessage(Class<?> refc, MemberName m) {
4003             Class<?> defc = m.getDeclaringClass();
4004             int mods = m.getModifiers();
4005             // check the class first:
4006             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
4007                                (defc == refc ||
4008                                 Modifier.isPublic(refc.getModifiers())));
4009             if (!classOK && (allowedModes & PACKAGE) != 0) {
4010                 // ignore previous lookup class to check if default package access
4011                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
4012                            (defc == refc ||
4013                             VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
4014             }
4015             if (!classOK)
4016                 return "class is not public";
4017             if (Modifier.isPublic(mods))
4018                 return "access to public member failed";  // (how?, module not readable?)
4019             if (Modifier.isPrivate(mods))
4020                 return "member is private";
4021             if (Modifier.isProtected(mods))
4022                 return "member is protected";
4023             return "member is private to package";
4024         }
4025 
4026         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
4027             int allowedModes = this.allowedModes;
4028             if (allowedModes == TRUSTED)  return;
4029             if ((lookupModes() & PRIVATE) == 0
4030                 || (specialCaller != lookupClass()
4031                        // ensure non-abstract methods in superinterfaces can be special-invoked
4032                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))

4069             final boolean doRestrict    = false;
4070             final boolean checkSecurity = true;
4071             return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup);
4072         }
4073         /** Check access and get the requested method, eliding security manager checks. */
4074         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4075             final boolean doRestrict    = true;
4076             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4077             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
4078         }
4079         /** Common code for all methods; do not call directly except from immediately above. */
4080         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
4081                                                    boolean checkSecurity,
4082                                                    boolean doRestrict,
4083                                                    Lookup boundCaller) throws IllegalAccessException {
4084             checkMethod(refKind, refc, method);
4085             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4086             if (checkSecurity)
4087                 checkSecurityManager(refc, method);
4088             assert(!method.isMethodHandleInvoke());
4089 
4090             if (refKind == REF_invokeSpecial &&
4091                 refc != lookupClass() &&
4092                 !refc.isInterface() && !lookupClass().isInterface() &&
4093                 refc != lookupClass().getSuperclass() &&
4094                 refc.isAssignableFrom(lookupClass())) {
4095                 assert(!method.getName().equals(ConstantDescs.INIT_NAME));  // not this code path
4096 
4097                 // Per JVMS 6.5, desc. of invokespecial instruction:
4098                 // If the method is in a superclass of the LC,
4099                 // and if our original search was above LC.super,
4100                 // repeat the search (symbolic lookup) from LC.super
4101                 // and continue with the direct superclass of that class,
4102                 // and so forth, until a match is found or no further superclasses exist.
4103                 // FIXME: MemberName.resolve should handle this instead.
4104                 Class<?> refcAsSuper = lookupClass();
4105                 MemberName m2;
4106                 do {
4107                     refcAsSuper = refcAsSuper.getSuperclass();
4108                     m2 = new MemberName(refcAsSuper,
4109                                         method.getName(),

4218                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
4219                 }
4220                 refc = lookupClass();
4221             }
4222             return VarHandles.makeFieldHandle(getField, refc,
4223                                               this.allowedModes == TRUSTED && !getField.isTrustedFinalField());
4224         }
4225         /** Check access and get the requested constructor. */
4226         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4227             final boolean checkSecurity = true;
4228             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4229         }
4230         /** Check access and get the requested constructor, eliding security manager checks. */
4231         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4232             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4233             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4234         }
4235         /** Common code for all constructors; do not call directly except from immediately above. */
4236         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
4237                                                   boolean checkSecurity) throws IllegalAccessException {
4238             assert(ctor.isConstructor());
4239             checkAccess(REF_newInvokeSpecial, refc, ctor);
4240             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4241             if (checkSecurity)
4242                 checkSecurityManager(refc, ctor);
4243             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
4244             return DirectMethodHandle.make(ctor).setVarargs(ctor);
4245         }
4246 
4247         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
4248          */
4249         /*non-public*/
4250         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
4251                 throws ReflectiveOperationException {
4252             if (!(type instanceof Class || type instanceof MethodType))
4253                 throw new InternalError("unresolved MemberName");
4254             MemberName member = new MemberName(refKind, defc, name, type);
4255             MethodHandle mh = LOOKASIDE_TABLE.get(member);
4256             if (mh != null) {
4257                 checkSymbolicClass(defc);
4258                 return mh;

5124      * If the requested type is primitive, widening primitive conversions are attempted,
5125      * else reference conversions are attempted.
5126      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
5127      * @param type the return type of the desired method handle
5128      * @param value the value to return
5129      * @return a method handle of the given return type and no arguments, which always returns the given value
5130      * @throws NullPointerException if the {@code type} argument is null
5131      * @throws ClassCastException if the value cannot be converted to the required return type
5132      * @throws IllegalArgumentException if the given type is {@code void.class}
5133      */
5134     public static MethodHandle constant(Class<?> type, Object value) {
5135         if (type.isPrimitive()) {
5136             if (type == void.class)
5137                 throw newIllegalArgumentException("void type");
5138             Wrapper w = Wrapper.forPrimitiveType(type);
5139             value = w.convert(value, type);
5140             if (w.zero().equals(value))
5141                 return zero(w, type);
5142             return insertArguments(identity(type), 0, value);
5143         } else {
5144             if (value == null)
5145                 return zero(Wrapper.OBJECT, type);
5146             return identity(type).bindTo(value);
5147         }
5148     }
5149 
5150     /**
5151      * Produces a method handle which returns its sole argument when invoked.
5152      * @param type the type of the sole parameter and return value of the desired method handle
5153      * @return a unary method handle which accepts and returns the given type
5154      * @throws NullPointerException if the argument is null
5155      * @throws IllegalArgumentException if the given type is {@code void.class}
5156      */
5157     public static MethodHandle identity(Class<?> type) {
5158         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
5159         int pos = btw.ordinal();
5160         MethodHandle ident = IDENTITY_MHS[pos];
5161         if (ident == null) {
5162             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
5163         }
5164         if (ident.type().returnType() == type)

5169     }
5170 
5171     /**
5172      * Produces a constant method handle of the requested return type which
5173      * returns the default value for that type every time it is invoked.
5174      * The resulting constant method handle will have no side effects.
5175      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
5176      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
5177      * since {@code explicitCastArguments} converts {@code null} to default values.
5178      * @param type the expected return type of the desired method handle
5179      * @return a constant method handle that takes no arguments
5180      *         and returns the default value of the given type (or void, if the type is void)
5181      * @throws NullPointerException if the argument is null
5182      * @see MethodHandles#constant
5183      * @see MethodHandles#empty
5184      * @see MethodHandles#explicitCastArguments
5185      * @since 9
5186      */
5187     public static MethodHandle zero(Class<?> type) {
5188         Objects.requireNonNull(type);
5189         return type.isPrimitive() ?  zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type);








5190     }
5191 
5192     private static MethodHandle identityOrVoid(Class<?> type) {
5193         return type == void.class ? zero(type) : identity(type);
5194     }
5195 
5196     /**
5197      * Produces a method handle of the requested type which ignores any arguments, does nothing,
5198      * and returns a suitable default depending on the return type.
5199      * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
5200      * <p>The returned method handle is equivalent to
5201      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
5202      *
5203      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
5204      * {@code guardWithTest(pred, target, empty(target.type())}.
5205      * @param type the type of the desired method handle
5206      * @return a constant method handle of the given type, which returns a default value of the given return type
5207      * @throws NullPointerException if the argument is null
5208      * @see MethodHandles#zero
5209      * @see MethodHandles#constant
5210      * @since 9
5211      */
5212     public static  MethodHandle empty(MethodType type) {
5213         Objects.requireNonNull(type);
5214         return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes());
5215     }
5216 
5217     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
5218     private static MethodHandle makeIdentity(Class<?> ptype) {
5219         MethodType mtype = methodType(ptype, ptype);
5220         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
5221         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
5222     }
5223 
5224     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
5225         int pos = btw.ordinal();
5226         MethodHandle zero = ZERO_MHS[pos];
5227         if (zero == null) {
5228             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
5229         }
5230         if (zero.type().returnType() == rtype)
5231             return zero;
5232         assert(btw == Wrapper.OBJECT);
5233         return makeZero(rtype);
5234     }
5235     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
5236     private static MethodHandle makeZero(Class<?> rtype) {
5237         MethodType mtype = methodType(rtype);
5238         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
5239         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);

   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.value.PrimitiveClass;
  30 import jdk.internal.misc.Unsafe;
  31 import jdk.internal.misc.VM;
  32 import jdk.internal.org.objectweb.asm.ClassReader;
  33 import jdk.internal.org.objectweb.asm.Opcodes;
  34 import jdk.internal.org.objectweb.asm.Type;
  35 import jdk.internal.reflect.CallerSensitive;
  36 import jdk.internal.reflect.CallerSensitiveAdapter;
  37 import jdk.internal.reflect.Reflection;
  38 import jdk.internal.util.ClassFileDumper;
  39 import jdk.internal.value.ValueClass;
  40 import jdk.internal.vm.annotation.ForceInline;
  41 import sun.invoke.util.ValueConversions;
  42 import sun.invoke.util.VerifyAccess;
  43 import sun.invoke.util.Wrapper;
  44 import sun.reflect.misc.ReflectUtil;
  45 import sun.security.util.SecurityConstants;
  46 
  47 import java.lang.constant.ConstantDescs;
  48 import java.lang.invoke.LambdaForm.BasicType;
  49 import java.lang.reflect.Constructor;
  50 import java.lang.reflect.Field;
  51 import java.lang.reflect.Member;
  52 import java.lang.reflect.Method;
  53 import java.lang.reflect.Modifier;
  54 import java.nio.ByteOrder;
  55 import java.security.ProtectionDomain;
  56 import java.util.ArrayList;
  57 import java.util.Arrays;
  58 import java.util.BitSet;
  59 import java.util.Comparator;

 690      * If the desired member is {@code protected}, the usual JVM rules apply,
 691      * including the requirement that the lookup class must either be in the
 692      * same package as the desired member, or must inherit that member.
 693      * (See the Java Virtual Machine Specification, sections {@jvms
 694      * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
 695      * In addition, if the desired member is a non-static field or method
 696      * in a different package, the resulting method handle may only be applied
 697      * to objects of the lookup class or one of its subclasses.
 698      * This requirement is enforced by narrowing the type of the leading
 699      * {@code this} parameter from {@code C}
 700      * (which will necessarily be a superclass of the lookup class)
 701      * to the lookup class itself.
 702      * <p>
 703      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 704      * that the receiver argument must match both the resolved method <em>and</em>
 705      * the current class.  Again, this requirement is enforced by narrowing the
 706      * type of the leading parameter to the resulting method handle.
 707      * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
 708      * <p>
 709      * The JVM represents constructors and static initializer blocks as internal methods
 710      * with special names ({@value ConstantDescs#INIT_NAME},
 711      * {@value ConstantDescs#VNEW_NAME} and {@value ConstantDescs#CLASS_INIT_NAME}).
 712      * The internal syntax of invocation instructions allows them to refer to such internal
 713      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 714      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 715      * <p>
 716      * If the relationship between nested types is expressed directly through the
 717      * {@code NestHost} and {@code NestMembers} attributes
 718      * (see the Java Virtual Machine Specification, sections {@jvms
 719      * 4.7.28} and {@jvms 4.7.29}),
 720      * then the associated {@code Lookup} object provides direct access to
 721      * the lookup class and all of its nestmates
 722      * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
 723      * Otherwise, access between nested classes is obtained by the Java compiler creating
 724      * a wrapper method to access a private method of another class in the same nest.
 725      * For example, a nested class {@code C.D}
 726      * can access private members within other related classes such as
 727      * {@code C}, {@code C.D.E}, or {@code C.B},
 728      * but the Java compiler may need to generate wrapper methods in
 729      * those related classes.  In such cases, a {@code Lookup} object on
 730      * {@code C.E} would be unable to access those private members.
 731      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,

1611          *  so that it can access only names which can be reached by the original
1612          *  lookup object, and also by the new lookup class.
1613          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1614          *  @see #in
1615          *  @see #dropLookupMode
1616          */
1617         public int lookupModes() {
1618             return allowedModes & ALL_MODES;
1619         }
1620 
1621         /** Embody the current class (the lookupClass) as a lookup class
1622          * for method handle creation.
1623          * Must be called by from a method in this package,
1624          * which in turn is called by a method not in this package.
1625          */
1626         Lookup(Class<?> lookupClass) {
1627             this(lookupClass, null, FULL_POWER_MODES);
1628         }
1629 
1630         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1631             assert PrimitiveClass.isPrimaryType(lookupClass);
1632             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1633                     && prevLookupClass.getModule() != lookupClass.getModule());
1634             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1635             this.lookupClass = lookupClass;
1636             this.prevLookupClass = prevLookupClass;
1637             this.allowedModes = allowedModes;
1638         }
1639 
1640         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1641             // make sure we haven't accidentally picked up a privileged class:
1642             checkUnprivilegedlookupClass(lookupClass);
1643             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1644         }
1645 
1646         /**
1647          * Creates a lookup on the specified new lookup class.
1648          * The resulting object will report the specified
1649          * class as its own {@link #lookupClass() lookupClass}.
1650          *
1651          * <p>

2789          * If the returned method handle is invoked, the constructor's class will
2790          * be initialized, if it has not already been initialized.
2791          * <p><b>Example:</b>
2792          * {@snippet lang="java" :
2793 import static java.lang.invoke.MethodHandles.*;
2794 import static java.lang.invoke.MethodType.*;
2795 ...
2796 MethodHandle MH_newArrayList = publicLookup().findConstructor(
2797   ArrayList.class, methodType(void.class, Collection.class));
2798 Collection orig = Arrays.asList("x", "y");
2799 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
2800 assert(orig != copy);
2801 assertEquals(orig, copy);
2802 // a variable-arity constructor:
2803 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
2804   ProcessBuilder.class, methodType(void.class, String[].class));
2805 ProcessBuilder pb = (ProcessBuilder)
2806   MH_newProcessBuilder.invoke("x", "y", "z");
2807 assertEquals("[x, y, z]", pb.command().toString());
2808          * }
2809          *
2810          *
2811          * @param refc the class or interface from which the method is accessed
2812          * @param type the type of the method, with the receiver argument omitted, and a void return type
2813          * @return the desired method handle
2814          * @throws NoSuchMethodException if the constructor does not exist
2815          * @throws IllegalAccessException if access checking fails
2816          *                                or if the method's variable arity modifier bit
2817          *                                is set and {@code asVarargsCollector} fails
2818          * @throws    SecurityException if a security manager is present and it
2819          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2820          * @throws NullPointerException if any argument is null
2821          */
2822         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2823             if (refc.isArray()) {
2824                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2825             }
2826             if (type.returnType() != void.class) {
2827                 throw new NoSuchMethodException("Constructors must have void return type: " + refc.getName());
2828             }
2829             String name = ConstantDescs.INIT_NAME;
2830             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2831             return getDirectConstructor(refc, ctor);
2832         }
2833 
2834         /**
2835          * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2836          * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2837          * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class,
2838          * and then determines whether the class is accessible to this lookup object.
2839          * <p>
2840          * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}.
2841          * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences
2842          * of {@code '['} and followed by the element type as encoded in the
2843          * {@linkplain Class##nameFormat table} specified in {@link Class#getName}.
2844          * <p>
2845          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2846          * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2847          *
2848          * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class

3504          * arguments passed to the method handle.
3505          * <p>
3506          * If the constructor's {@code accessible} flag is not set,
3507          * access checking is performed immediately on behalf of the lookup class.
3508          * <p>
3509          * The returned method handle will have
3510          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3511          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3512          * <p>
3513          * If the returned method handle is invoked, the constructor's class will
3514          * be initialized, if it has not already been initialized.
3515          * @param c the reflected constructor
3516          * @return a method handle which can invoke the reflected constructor
3517          * @throws IllegalAccessException if access checking fails
3518          *                                or if the method's variable arity modifier bit
3519          *                                is set and {@code asVarargsCollector} fails
3520          * @throws NullPointerException if the argument is null
3521          */
3522         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3523             MemberName ctor = new MemberName(c);
3524             assert(ctor.isObjectConstructor() || ctor.isStaticValueFactoryMethod());
3525             @SuppressWarnings("deprecation")
3526             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3527             Class<?> defc = c.getDeclaringClass();
3528             if (ctor.isObjectConstructor()) {
3529                 assert(ctor.getMethodType().returnType() == void.class);
3530                 return lookup.getDirectConstructorNoSecurityManager(defc, ctor);
3531             } else {
3532                 // static init factory is a static method
3533                 assert(ctor.isMethod() && ctor.getMethodType().returnType() == defc && ctor.getReferenceKind() == REF_invokeStatic) : ctor.toString();
3534                 assert(!MethodHandleNatives.isCallerSensitive(ctor));  // must not be caller-sensitive
3535                 return lookup.getDirectMethodNoSecurityManager(ctor.getReferenceKind(), defc, ctor, lookup);
3536             }
3537         }
3538 
3539         /*
3540          * Produces a method handle that is capable of creating instances of the given class
3541          * and instantiated by the given constructor.  No security manager check.
3542          *
3543          * This method should only be used by ReflectionFactory::newConstructorForSerialization.
3544          */
3545         /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException {
3546             MemberName ctor = new MemberName(c);
3547             assert(ctor.isObjectConstructor() && constructorInSuperclass(decl, c));
3548             checkAccess(REF_newInvokeSpecial, decl, ctor);
3549             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
3550             return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor);
3551         }
3552 
3553         private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) {
3554             if (decl == ctor.getDeclaringClass())
3555                 return true;
3556 
3557             Class<?> cl = decl;
3558             while ((cl = cl.getSuperclass()) != null) {
3559                 if (cl == ctor.getDeclaringClass()) {
3560                     return true;
3561                 }
3562             }
3563             return false;
3564         }
3565 
3566         /**
3567          * Produces a method handle giving read access to a reflected field.

3788                                             ReflectiveOperationException.class);
3789         }
3790 
3791         MemberName resolveOrNull(byte refKind, MemberName member) {
3792             // do this before attempting to resolve
3793             if (!isClassAccessible(member.getDeclaringClass())) {
3794                 return null;
3795             }
3796             Objects.requireNonNull(member.getName());
3797             Objects.requireNonNull(member.getType());
3798             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes);
3799         }
3800 
3801         MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) {
3802             // do this before attempting to resolve
3803             if (!isClassAccessible(refc)) {
3804                 return null;
3805             }
3806             Objects.requireNonNull(type);
3807             // implicit null-check of name
3808             if (isIllegalMethodName(refKind, name)) {
3809                 return null;
3810             }
3811 
3812             return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes);
3813         }
3814 
3815         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
3816             if (!isClassAccessible(refc)) {
3817                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
3818             }
3819         }
3820 
3821         boolean isClassAccessible(Class<?> refc) {
3822             Objects.requireNonNull(refc);
3823             Class<?> caller = lookupClassOrNull();
3824             Class<?> type = refc;
3825             while (type.isArray()) {
3826                 type = type.getComponentType();
3827             }
3828             return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes);
3829         }
3830 
3831         /*
3832          * "<init>" can only be invoked via invokespecial
3833          * "<vnew>" factory can only invoked via invokestatic
3834          */
3835         boolean isIllegalMethodName(byte refKind, String name) {
3836             if (name.startsWith("<")) {
3837                 return MemberName.VALUE_FACTORY_NAME.equals(name) ? refKind != REF_invokeStatic
3838                                                                   : refKind != REF_newInvokeSpecial;
3839             }
3840             return false;
3841         }
3842 
3843         /** Check name for an illegal leading "&lt;" character. */
3844         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3845             if (isIllegalMethodName(refKind, name)) {
3846                 throw new NoSuchMethodException("illegal method name: " + name + " " + refKind);
3847             }
3848         }
3849 
3850         /**
3851          * Find my trustable caller class if m is a caller sensitive method.
3852          * If this lookup object has original full privilege access, then the caller class is the lookupClass.
3853          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3854          */
3855         Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3856             if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) {
3857                 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3858                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3859             }
3860             return this;
3861         }
3862 
3863         /**
3864          * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3865          * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3866          *
3867          * @deprecated This method was originally designed to test {@code PRIVATE} access

3931 
3932             @SuppressWarnings("removal")
3933             SecurityManager smgr = System.getSecurityManager();
3934             if (smgr == null)  return;
3935 
3936             // Step 1:
3937             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3938             if (!fullPrivilegeLookup ||
3939                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3940                 ReflectUtil.checkPackageAccess(refc);
3941             }
3942 
3943             // Step 2a:
3944             if (m.isPublic()) return;
3945             if (!fullPrivilegeLookup) {
3946                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3947             }
3948 
3949             // Step 3:
3950             Class<?> defc = m.getDeclaringClass();
3951             if (!fullPrivilegeLookup && PrimitiveClass.asPrimaryType(defc) != PrimitiveClass.asPrimaryType(refc)) {
3952                 ReflectUtil.checkPackageAccess(defc);
3953             }
3954         }
3955 
3956         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3957             boolean wantStatic = (refKind == REF_invokeStatic);
3958             String message;
3959             if (m.isObjectConstructor())
3960                 message = "expected a method, not a constructor";
3961             else if (!m.isMethod())
3962                 message = "expected a method";
3963             else if (wantStatic != m.isStatic())
3964                 message = wantStatic ? "expected a static method" : "expected a non-static method";
3965             else
3966                 { checkAccess(refKind, refc, m); return; }
3967             throw m.makeAccessException(message, this);
3968         }
3969 
3970         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3971             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3972             String message;
3973             if (wantStatic != m.isStatic())
3974                 message = wantStatic ? "expected a static field" : "expected a non-static field";
3975             else
3976                 { checkAccess(refKind, refc, m); return; }
3977             throw m.makeAccessException(message, this);
3978         }
3979 

4018                 throw m.makeAccessException("unexpected set of a final field", this);
4019             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
4020             if ((requestedModes & allowedModes) != 0) {
4021                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
4022                                                     mods, lookupClass(), previousLookupClass(), allowedModes))
4023                     return;
4024             } else {
4025                 // Protected members can also be checked as if they were package-private.
4026                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
4027                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
4028                     return;
4029             }
4030             throw m.makeAccessException(accessFailedMessage(refc, m), this);
4031         }
4032 
4033         String accessFailedMessage(Class<?> refc, MemberName m) {
4034             Class<?> defc = m.getDeclaringClass();
4035             int mods = m.getModifiers();
4036             // check the class first:
4037             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
4038                                (PrimitiveClass.asPrimaryType(defc) == PrimitiveClass.asPrimaryType(refc) ||
4039                                 Modifier.isPublic(refc.getModifiers())));
4040             if (!classOK && (allowedModes & PACKAGE) != 0) {
4041                 // ignore previous lookup class to check if default package access
4042                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
4043                            (PrimitiveClass.asPrimaryType(defc) == PrimitiveClass.asPrimaryType(refc) ||
4044                             VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
4045             }
4046             if (!classOK)
4047                 return "class is not public";
4048             if (Modifier.isPublic(mods))
4049                 return "access to public member failed";  // (how?, module not readable?)
4050             if (Modifier.isPrivate(mods))
4051                 return "member is private";
4052             if (Modifier.isProtected(mods))
4053                 return "member is protected";
4054             return "member is private to package";
4055         }
4056 
4057         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
4058             int allowedModes = this.allowedModes;
4059             if (allowedModes == TRUSTED)  return;
4060             if ((lookupModes() & PRIVATE) == 0
4061                 || (specialCaller != lookupClass()
4062                        // ensure non-abstract methods in superinterfaces can be special-invoked
4063                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))

4100             final boolean doRestrict    = false;
4101             final boolean checkSecurity = true;
4102             return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup);
4103         }
4104         /** Check access and get the requested method, eliding security manager checks. */
4105         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4106             final boolean doRestrict    = true;
4107             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4108             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
4109         }
4110         /** Common code for all methods; do not call directly except from immediately above. */
4111         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
4112                                                    boolean checkSecurity,
4113                                                    boolean doRestrict,
4114                                                    Lookup boundCaller) throws IllegalAccessException {
4115             checkMethod(refKind, refc, method);
4116             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4117             if (checkSecurity)
4118                 checkSecurityManager(refc, method);
4119             assert(!method.isMethodHandleInvoke());

4120             if (refKind == REF_invokeSpecial &&
4121                 refc != lookupClass() &&
4122                 !refc.isInterface() && !lookupClass().isInterface() &&
4123                 refc != lookupClass().getSuperclass() &&
4124                 refc.isAssignableFrom(lookupClass())) {
4125                 assert(!method.getName().equals(ConstantDescs.INIT_NAME));  // not this code path
4126 
4127                 // Per JVMS 6.5, desc. of invokespecial instruction:
4128                 // If the method is in a superclass of the LC,
4129                 // and if our original search was above LC.super,
4130                 // repeat the search (symbolic lookup) from LC.super
4131                 // and continue with the direct superclass of that class,
4132                 // and so forth, until a match is found or no further superclasses exist.
4133                 // FIXME: MemberName.resolve should handle this instead.
4134                 Class<?> refcAsSuper = lookupClass();
4135                 MemberName m2;
4136                 do {
4137                     refcAsSuper = refcAsSuper.getSuperclass();
4138                     m2 = new MemberName(refcAsSuper,
4139                                         method.getName(),

4248                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
4249                 }
4250                 refc = lookupClass();
4251             }
4252             return VarHandles.makeFieldHandle(getField, refc,
4253                                               this.allowedModes == TRUSTED && !getField.isTrustedFinalField());
4254         }
4255         /** Check access and get the requested constructor. */
4256         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4257             final boolean checkSecurity = true;
4258             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4259         }
4260         /** Check access and get the requested constructor, eliding security manager checks. */
4261         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4262             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4263             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4264         }
4265         /** Common code for all constructors; do not call directly except from immediately above. */
4266         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
4267                                                   boolean checkSecurity) throws IllegalAccessException {
4268             assert(ctor.isObjectConstructor());
4269             checkAccess(REF_newInvokeSpecial, refc, ctor);
4270             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4271             if (checkSecurity)
4272                 checkSecurityManager(refc, ctor);
4273             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
4274             return DirectMethodHandle.make(ctor).setVarargs(ctor);
4275         }
4276 
4277         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
4278          */
4279         /*non-public*/
4280         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
4281                 throws ReflectiveOperationException {
4282             if (!(type instanceof Class || type instanceof MethodType))
4283                 throw new InternalError("unresolved MemberName");
4284             MemberName member = new MemberName(refKind, defc, name, type);
4285             MethodHandle mh = LOOKASIDE_TABLE.get(member);
4286             if (mh != null) {
4287                 checkSymbolicClass(defc);
4288                 return mh;

5154      * If the requested type is primitive, widening primitive conversions are attempted,
5155      * else reference conversions are attempted.
5156      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
5157      * @param type the return type of the desired method handle
5158      * @param value the value to return
5159      * @return a method handle of the given return type and no arguments, which always returns the given value
5160      * @throws NullPointerException if the {@code type} argument is null
5161      * @throws ClassCastException if the value cannot be converted to the required return type
5162      * @throws IllegalArgumentException if the given type is {@code void.class}
5163      */
5164     public static MethodHandle constant(Class<?> type, Object value) {
5165         if (type.isPrimitive()) {
5166             if (type == void.class)
5167                 throw newIllegalArgumentException("void type");
5168             Wrapper w = Wrapper.forPrimitiveType(type);
5169             value = w.convert(value, type);
5170             if (w.zero().equals(value))
5171                 return zero(w, type);
5172             return insertArguments(identity(type), 0, value);
5173         } else {
5174             if (!PrimitiveClass.isPrimitiveValueType(type) && value == null)
5175                 return zero(Wrapper.OBJECT, type);
5176             return identity(type).bindTo(value);
5177         }
5178     }
5179 
5180     /**
5181      * Produces a method handle which returns its sole argument when invoked.
5182      * @param type the type of the sole parameter and return value of the desired method handle
5183      * @return a unary method handle which accepts and returns the given type
5184      * @throws NullPointerException if the argument is null
5185      * @throws IllegalArgumentException if the given type is {@code void.class}
5186      */
5187     public static MethodHandle identity(Class<?> type) {
5188         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
5189         int pos = btw.ordinal();
5190         MethodHandle ident = IDENTITY_MHS[pos];
5191         if (ident == null) {
5192             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
5193         }
5194         if (ident.type().returnType() == type)

5199     }
5200 
5201     /**
5202      * Produces a constant method handle of the requested return type which
5203      * returns the default value for that type every time it is invoked.
5204      * The resulting constant method handle will have no side effects.
5205      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
5206      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
5207      * since {@code explicitCastArguments} converts {@code null} to default values.
5208      * @param type the expected return type of the desired method handle
5209      * @return a constant method handle that takes no arguments
5210      *         and returns the default value of the given type (or void, if the type is void)
5211      * @throws NullPointerException if the argument is null
5212      * @see MethodHandles#constant
5213      * @see MethodHandles#empty
5214      * @see MethodHandles#explicitCastArguments
5215      * @since 9
5216      */
5217     public static MethodHandle zero(Class<?> type) {
5218         Objects.requireNonNull(type);
5219         if (type.isPrimitive()) {
5220             return zero(Wrapper.forPrimitiveType(type), type);
5221         } else if (PrimitiveClass.isPrimitiveValueType(type)) {
5222             // singleton default value
5223             Object value = ValueClass.zeroInstance(type);
5224             return identity(type).bindTo(value);
5225         } else {
5226             return zero(Wrapper.OBJECT, type);
5227         }
5228     }
5229 
5230     private static MethodHandle identityOrVoid(Class<?> type) {
5231         return type == void.class ? zero(type) : identity(type);
5232     }
5233 
5234     /**
5235      * Produces a method handle of the requested type which ignores any arguments, does nothing,
5236      * and returns a suitable default depending on the return type.
5237      * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
5238      * <p>The returned method handle is equivalent to
5239      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
5240      *
5241      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
5242      * {@code guardWithTest(pred, target, empty(target.type())}.
5243      * @param type the type of the desired method handle
5244      * @return a constant method handle of the given type, which returns a default value of the given return type
5245      * @throws NullPointerException if the argument is null
5246      * @see MethodHandles#zero
5247      * @see MethodHandles#constant
5248      * @since 9
5249      */
5250     public static  MethodHandle empty(MethodType type) {
5251         Objects.requireNonNull(type);
5252         return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes());
5253     }
5254 
5255     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
5256     private static MethodHandle makeIdentity(Class<?> ptype) {
5257         MethodType mtype = MethodType.methodType(ptype, ptype);
5258         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
5259         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
5260     }
5261 
5262     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
5263         int pos = btw.ordinal();
5264         MethodHandle zero = ZERO_MHS[pos];
5265         if (zero == null) {
5266             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
5267         }
5268         if (zero.type().returnType() == rtype)
5269             return zero;
5270         assert(btw == Wrapper.OBJECT);
5271         return makeZero(rtype);
5272     }
5273     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
5274     private static MethodHandle makeZero(Class<?> rtype) {
5275         MethodType mtype = methodType(rtype);
5276         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
5277         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
< prev index next >