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