1 /*
   2  * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   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 java.lang.invoke.MethodHandles.Lookup;
  29 import java.lang.reflect.Field;
  30 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  31 import static java.lang.invoke.MethodHandleStatics.*;
  32 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  33 
  34 /**
  35  * The JVM interface for the method handles package is all here.
  36  * This is an interface internal and private to an implementation of JSR 292.
  37  * <em>This class is not part of the JSR 292 standard.</em>
  38  * @author jrose
  39  */
  40 class MethodHandleNatives {
  41 
  42     private MethodHandleNatives() { } // static only
  43 
  44     /// MemberName support
  45 
  46     static native void init(MemberName self, Object ref);
  47     static native void expand(MemberName self);
  48     static native MemberName resolve(MemberName self, Class<?> caller) throws LinkageError;
  49     static native int getMembers(Class<?> defc, String matchName, String matchSig,
  50             int matchFlags, Class<?> caller, int skip, MemberName[] results);
  51 
  52     /// Field layout queries parallel to sun.misc.Unsafe:
  53     static native long objectFieldOffset(MemberName self);  // e.g., returns vmindex
  54     static native long staticFieldOffset(MemberName self);  // e.g., returns vmindex
  55     static native Object staticFieldBase(MemberName self);  // e.g., returns clazz
  56     static native Object getMemberVMInfo(MemberName self);  // returns {vmindex,vmtarget}
  57 
  58     /// CallSite support
  59 
  60     /** Tell the JVM that we need to change the target of a CallSite. */
  61     static native void setCallSiteTargetNormal(CallSite site, MethodHandle target);
  62     static native void setCallSiteTargetVolatile(CallSite site, MethodHandle target);
  63 
  64     private static native void registerNatives();
  65     static {
  66         registerNatives();
  67 
  68         // The JVM calls MethodHandleNatives.<clinit>.  Cascade the <clinit> calls as needed:
  69         MethodHandleImpl.initStatics();
  70     }
  71 
  72     /**
  73      * Compile-time constants go here. This collection exists not only for
  74      * reference from clients, but also for ensuring the VM and JDK agree on the
  75      * values of these constants (see {@link #verifyConstants()}).
  76      */
  77     static class Constants {
  78         Constants() { } // static only
  79 
  80         static final int
  81             MN_IS_METHOD           = 0x00010000, // method (not constructor)
  82             MN_IS_CONSTRUCTOR      = 0x00020000, // constructor
  83             MN_IS_FIELD            = 0x00040000, // field
  84             MN_IS_TYPE             = 0x00080000, // nested type
  85             MN_CALLER_SENSITIVE    = 0x00100000, // @CallerSensitive annotation detected
  86             MN_REFERENCE_KIND_SHIFT = 24, // refKind
  87             MN_REFERENCE_KIND_MASK = 0x0F000000 >> MN_REFERENCE_KIND_SHIFT,
  88             // The SEARCH_* bits are not for MN.flags but for the matchFlags argument of MHN.getMembers:
  89             MN_SEARCH_SUPERCLASSES = 0x00100000,
  90             MN_SEARCH_INTERFACES   = 0x00200000;
  91 
  92         /**
  93          * Constant pool reference-kind codes, as used by CONSTANT_MethodHandle CP entries.
  94          */
  95         static final byte
  96             REF_NONE                    = 0,  // null value
  97             REF_getField                = 1,
  98             REF_getStatic               = 2,
  99             REF_putField                = 3,
 100             REF_putStatic               = 4,
 101             REF_invokeVirtual           = 5,
 102             REF_invokeStatic            = 6,
 103             REF_invokeSpecial           = 7,
 104             REF_newInvokeSpecial        = 8,
 105             REF_invokeInterface         = 9,
 106             REF_LIMIT                  = 10;
 107     }
 108 
 109     static boolean refKindIsValid(int refKind) {
 110         return (refKind > REF_NONE && refKind < REF_LIMIT);
 111     }
 112     static boolean refKindIsField(byte refKind) {
 113         assert(refKindIsValid(refKind));
 114         return (refKind <= REF_putStatic);
 115     }
 116     static boolean refKindIsGetter(byte refKind) {
 117         assert(refKindIsValid(refKind));
 118         return (refKind <= REF_getStatic);
 119     }
 120     static boolean refKindIsSetter(byte refKind) {
 121         return refKindIsField(refKind) && !refKindIsGetter(refKind);
 122     }
 123     static boolean refKindIsMethod(byte refKind) {
 124         return !refKindIsField(refKind) && (refKind != REF_newInvokeSpecial);
 125     }
 126     static boolean refKindIsConstructor(byte refKind) {
 127         return (refKind == REF_newInvokeSpecial);
 128     }
 129     static boolean refKindHasReceiver(byte refKind) {
 130         assert(refKindIsValid(refKind));
 131         return (refKind & 1) != 0;
 132     }
 133     static boolean refKindIsStatic(byte refKind) {
 134         return !refKindHasReceiver(refKind) && (refKind != REF_newInvokeSpecial);
 135     }
 136     static boolean refKindDoesDispatch(byte refKind) {
 137         assert(refKindIsValid(refKind));
 138         return (refKind == REF_invokeVirtual ||
 139                 refKind == REF_invokeInterface);
 140     }
 141     static {
 142         final int HR_MASK = ((1 << REF_getField) |
 143                              (1 << REF_putField) |
 144                              (1 << REF_invokeVirtual) |
 145                              (1 << REF_invokeSpecial) |
 146                              (1 << REF_invokeInterface)
 147                             );
 148         for (byte refKind = REF_NONE+1; refKind < REF_LIMIT; refKind++) {
 149             assert(refKindHasReceiver(refKind) == (((1<<refKind) & HR_MASK) != 0)) : refKind;
 150         }
 151     }
 152     static String refKindName(byte refKind) {
 153         assert(refKindIsValid(refKind));
 154         switch (refKind) {
 155         case REF_getField:          return "getField";
 156         case REF_getStatic:         return "getStatic";
 157         case REF_putField:          return "putField";
 158         case REF_putStatic:         return "putStatic";
 159         case REF_invokeVirtual:     return "invokeVirtual";
 160         case REF_invokeStatic:      return "invokeStatic";
 161         case REF_invokeSpecial:     return "invokeSpecial";
 162         case REF_newInvokeSpecial:  return "newInvokeSpecial";
 163         case REF_invokeInterface:   return "invokeInterface";
 164         default:                    return "REF_???";
 165         }
 166     }
 167 
 168     private static native int getNamedCon(int which, Object[] name);
 169     static boolean verifyConstants() {
 170         Object[] box = { null };
 171         for (int i = 0; ; i++) {
 172             box[0] = null;
 173             int vmval = getNamedCon(i, box);
 174             if (box[0] == null)  break;
 175             String name = (String) box[0];
 176             try {
 177                 Field con = Constants.class.getDeclaredField(name);
 178                 int jval = con.getInt(null);
 179                 if (jval == vmval)  continue;
 180                 String err = (name+": JVM has "+vmval+" while Java has "+jval);
 181                 if (name.equals("CONV_OP_LIMIT")) {
 182                     System.err.println("warning: "+err);
 183                     continue;
 184                 }
 185                 throw new InternalError(err);
 186             } catch (NoSuchFieldException | IllegalAccessException ex) {
 187                 String err = (name+": JVM has "+vmval+" which Java does not define");
 188                 // ignore exotic ops the JVM cares about; we just wont issue them
 189                 //System.err.println("warning: "+err);
 190                 continue;
 191             }
 192         }
 193         return true;
 194     }
 195     static {
 196         assert(verifyConstants());
 197     }
 198 
 199     // Up-calls from the JVM.
 200     // These must NOT be public.
 201 
 202     /**
 203      * The JVM is linking an invokedynamic instruction.  Create a reified call site for it.
 204      */
 205     static MemberName linkCallSite(Object callerObj,
 206                                    Object bootstrapMethodObj,
 207                                    Object nameObj, Object typeObj,
 208                                    Object staticArguments,
 209                                    Object[] appendixResult) {
 210         MethodHandle bootstrapMethod = (MethodHandle)bootstrapMethodObj;
 211         Class<?> caller = (Class<?>)callerObj;
 212         String name = nameObj.toString().intern();
 213         MethodType type = (MethodType)typeObj;
 214         if (!TRACE_METHOD_LINKAGE)
 215             return linkCallSiteImpl(caller, bootstrapMethod, name, type,
 216                                     staticArguments, appendixResult);
 217         return linkCallSiteTracing(caller, bootstrapMethod, name, type,
 218                                    staticArguments, appendixResult);
 219     }
 220     static MemberName linkCallSiteImpl(Class<?> caller,
 221                                        MethodHandle bootstrapMethod,
 222                                        String name, MethodType type,
 223                                        Object staticArguments,
 224                                        Object[] appendixResult) {
 225         CallSite callSite = CallSite.makeSite(bootstrapMethod,
 226                                               name,
 227                                               type,
 228                                               staticArguments,
 229                                               caller);
 230         if (callSite instanceof ConstantCallSite) {
 231             appendixResult[0] = callSite.dynamicInvoker();
 232             return Invokers.linkToTargetMethod(type);
 233         } else {
 234             appendixResult[0] = callSite;
 235             return Invokers.linkToCallSiteMethod(type);
 236         }
 237     }
 238     // Tracing logic:
 239     static MemberName linkCallSiteTracing(Class<?> caller,
 240                                           MethodHandle bootstrapMethod,
 241                                           String name, MethodType type,
 242                                           Object staticArguments,
 243                                           Object[] appendixResult) {
 244         Object bsmReference = bootstrapMethod.internalMemberName();
 245         if (bsmReference == null)  bsmReference = bootstrapMethod;
 246         Object staticArglist = (staticArguments instanceof Object[] ?
 247                                 java.util.Arrays.asList((Object[]) staticArguments) :
 248                                 staticArguments);
 249         System.out.println("linkCallSite "+caller.getName()+" "+
 250                            bsmReference+" "+
 251                            name+type+"/"+staticArglist);
 252         try {
 253             MemberName res = linkCallSiteImpl(caller, bootstrapMethod, name, type,
 254                                               staticArguments, appendixResult);
 255             System.out.println("linkCallSite => "+res+" + "+appendixResult[0]);
 256             return res;
 257         } catch (Throwable ex) {
 258             System.out.println("linkCallSite => throw "+ex);
 259             throw ex;
 260         }
 261     }
 262 
 263     /**
 264      * The JVM wants a pointer to a MethodType.  Oblige it by finding or creating one.
 265      */
 266     static MethodType findMethodHandleType(Class<?> rtype, Class<?>[] ptypes) {
 267         return MethodType.makeImpl(rtype, ptypes, true);
 268     }
 269 
 270     /**
 271      * The JVM wants to link a call site that requires a dynamic type check.
 272      * Name is a type-checking invoker, invokeExact or invoke.
 273      * Return a JVM method (MemberName) to handle the invoking.
 274      * The method assumes the following arguments on the stack:
 275      * 0: the method handle being invoked
 276      * 1-N: the arguments to the method handle invocation
 277      * N+1: an optional, implicitly added argument (typically the given MethodType)
 278      * <p>
 279      * The nominal method at such a call site is an instance of
 280      * a signature-polymorphic method (see @PolymorphicSignature).
 281      * Such method instances are user-visible entities which are
 282      * "split" from the generic placeholder method in {@code MethodHandle}.
 283      * (Note that the placeholder method is not identical with any of
 284      * its instances.  If invoked reflectively, is guaranteed to throw an
 285      * {@code UnsupportedOperationException}.)
 286      * If the signature-polymorphic method instance is ever reified,
 287      * it appears as a "copy" of the original placeholder
 288      * (a native final member of {@code MethodHandle}) except
 289      * that its type descriptor has shape required by the instance,
 290      * and the method instance is <em>not</em> varargs.
 291      * The method instance is also marked synthetic, since the
 292      * method (by definition) does not appear in Java source code.
 293      * <p>
 294      * The JVM is allowed to reify this method as instance metadata.
 295      * For example, {@code invokeBasic} is always reified.
 296      * But the JVM may instead call {@code linkMethod}.
 297      * If the result is an * ordered pair of a {@code (method, appendix)},
 298      * the method gets all the arguments (0..N inclusive)
 299      * plus the appendix (N+1), and uses the appendix to complete the call.
 300      * In this way, one reusable method (called a "linker method")
 301      * can perform the function of any number of polymorphic instance
 302      * methods.
 303      * <p>
 304      * Linker methods are allowed to be weakly typed, with any or
 305      * all references rewritten to {@code Object} and any primitives
 306      * (except {@code long}/{@code float}/{@code double})
 307      * rewritten to {@code int}.
 308      * A linker method is trusted to return a strongly typed result,
 309      * according to the specific method type descriptor of the
 310      * signature-polymorphic instance it is emulating.
 311      * This can involve (as necessary) a dynamic check using
 312      * data extracted from the appendix argument.
 313      * <p>
 314      * The JVM does not inspect the appendix, other than to pass
 315      * it verbatim to the linker method at every call.
 316      * This means that the JDK runtime has wide latitude
 317      * for choosing the shape of each linker method and its
 318      * corresponding appendix.
 319      * Linker methods should be generated from {@code LambdaForm}s
 320      * so that they do not become visible on stack traces.
 321      * <p>
 322      * The {@code linkMethod} call is free to omit the appendix
 323      * (returning null) and instead emulate the required function
 324      * completely in the linker method.
 325      * As a corner case, if N==255, no appendix is possible.
 326      * In this case, the method returned must be custom-generated to
 327      * to perform any needed type checking.
 328      * <p>
 329      * If the JVM does not reify a method at a call site, but instead
 330      * calls {@code linkMethod}, the corresponding call represented
 331      * in the bytecodes may mention a valid method which is not
 332      * representable with a {@code MemberName}.
 333      * Therefore, use cases for {@code linkMethod} tend to correspond to
 334      * special cases in reflective code such as {@code findVirtual}
 335      * or {@code revealDirect}.
 336      */
 337     static MemberName linkMethod(Class<?> callerClass, int refKind,
 338                                  Class<?> defc, String name, Object type,
 339                                  Object[] appendixResult) {
 340         if (!TRACE_METHOD_LINKAGE)
 341             return linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
 342         return linkMethodTracing(callerClass, refKind, defc, name, type, appendixResult);
 343     }
 344     static MemberName linkMethodImpl(Class<?> callerClass, int refKind,
 345                                      Class<?> defc, String name, Object type,
 346                                      Object[] appendixResult) {
 347         try {
 348             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
 349                 return Invokers.methodHandleInvokeLinkerMethod(name, fixMethodType(callerClass, type), appendixResult);
 350             }
 351         } catch (Throwable ex) {
 352             if (ex instanceof LinkageError)
 353                 throw (LinkageError) ex;
 354             else
 355                 throw new LinkageError(ex.getMessage(), ex);
 356         }
 357         throw new LinkageError("no such method "+defc.getName()+"."+name+type);
 358     }
 359     private static MethodType fixMethodType(Class<?> callerClass, Object type) {
 360         if (type instanceof MethodType)
 361             return (MethodType) type;
 362         else
 363             return MethodType.fromMethodDescriptorString((String)type, callerClass.getClassLoader());
 364     }
 365     // Tracing logic:
 366     static MemberName linkMethodTracing(Class<?> callerClass, int refKind,
 367                                         Class<?> defc, String name, Object type,
 368                                         Object[] appendixResult) {
 369         System.out.println("linkMethod "+defc.getName()+"."+
 370                            name+type+"/"+Integer.toHexString(refKind));
 371         try {
 372             MemberName res = linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
 373             System.out.println("linkMethod => "+res+" + "+appendixResult[0]);
 374             return res;
 375         } catch (Throwable ex) {
 376             System.out.println("linkMethod => throw "+ex);
 377             throw ex;
 378         }
 379     }
 380 
 381 
 382     /**
 383      * The JVM is resolving a CONSTANT_MethodHandle CP entry.  And it wants our help.
 384      * It will make an up-call to this method.  (Do not change the name or signature.)
 385      * The type argument is a Class for field requests and a MethodType for non-fields.
 386      * <p>
 387      * Recent versions of the JVM may also pass a resolved MemberName for the type.
 388      * In that case, the name is ignored and may be null.
 389      */
 390     static MethodHandle linkMethodHandleConstant(Class<?> callerClass, int refKind,
 391                                                  Class<?> defc, String name, Object type) {
 392         try {
 393             Lookup lookup = IMPL_LOOKUP.in(callerClass);
 394             assert(refKindIsValid(refKind));
 395             return lookup.linkMethodHandleConstant((byte) refKind, defc, name, type);
 396         } catch (IllegalAccessException ex) {
 397             Throwable cause = ex.getCause();
 398             if (cause instanceof AbstractMethodError) {
 399                 throw (AbstractMethodError) cause;
 400             } else {
 401                 Error err = new IllegalAccessError(ex.getMessage());
 402                 throw initCauseFrom(err, ex);
 403             }
 404         } catch (NoSuchMethodException ex) {
 405             Error err = new NoSuchMethodError(ex.getMessage());
 406             throw initCauseFrom(err, ex);
 407         } catch (NoSuchFieldException ex) {
 408             Error err = new NoSuchFieldError(ex.getMessage());
 409             throw initCauseFrom(err, ex);
 410         } catch (ReflectiveOperationException ex) {
 411             Error err = new IncompatibleClassChangeError();
 412             throw initCauseFrom(err, ex);
 413         }
 414     }
 415 
 416     /**
 417      * Use best possible cause for err.initCause(), substituting the
 418      * cause for err itself if the cause has the same (or better) type.
 419      */
 420     static private Error initCauseFrom(Error err, Exception ex) {
 421         Throwable th = ex.getCause();
 422         if (err.getClass().isInstance(th))
 423            return (Error) th;
 424         err.initCause(th == null ? ex : th);
 425         return err;
 426     }
 427 
 428     /**
 429      * Is this method a caller-sensitive method?
 430      * I.e., does it call Reflection.getCallerClass or a similar method
 431      * to ask about the identity of its caller?
 432      */
 433     static boolean isCallerSensitive(MemberName mem) {
 434         if (!mem.isInvocable())  return false;  // fields are not caller sensitive
 435 
 436         return mem.isCallerSensitive() || canBeCalledVirtual(mem);
 437     }
 438 
 439     static boolean canBeCalledVirtual(MemberName mem) {
 440         assert(mem.isInvocable());
 441         Class<?> defc = mem.getDeclaringClass();
 442         switch (mem.getName()) {
 443         case "checkMemberAccess":
 444             return canBeCalledVirtual(mem, java.lang.SecurityManager.class);
 445         case "getContextClassLoader":
 446             return canBeCalledVirtual(mem, java.lang.Thread.class);
 447         }
 448         return false;
 449     }
 450 
 451     static boolean canBeCalledVirtual(MemberName symbolicRef, Class<?> definingClass) {
 452         Class<?> symbolicRefClass = symbolicRef.getDeclaringClass();
 453         if (symbolicRefClass == definingClass)  return true;
 454         if (symbolicRef.isStatic() || symbolicRef.isPrivate())  return false;
 455         return (definingClass.isAssignableFrom(symbolicRefClass) ||  // Msym overrides Mdef
 456                 symbolicRefClass.isInterface());                     // Mdef implements Msym
 457     }
 458 }