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