1 /*
   2  * Copyright (c) 2008, 2019, 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 jdk.internal.ref.CleanerFactory;
  29 import sun.invoke.util.Wrapper;
  30 
  31 import java.lang.invoke.MethodHandles.Lookup;
  32 import java.lang.reflect.Field;
  33 
  34 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  35 import static java.lang.invoke.MethodHandleStatics.TRACE_METHOD_LINKAGE;
  36 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  37 
  38 /**
  39  * The JVM interface for the method handles package is all here.
  40  * This is an interface internal and private to an implementation of JSR 292.
  41  * <em>This class is not part of the JSR 292 standard.</em>
  42  * @author jrose
  43  */
  44 class MethodHandleNatives {
  45 
  46     private MethodHandleNatives() { } // static only
  47 
  48     /// MemberName support
  49 
  50     static native void init(MemberName self, Object ref);
  51     static native void expand(MemberName self);
  52     static native MemberName resolve(MemberName self, Class<?> caller,
  53             boolean speculativeResolve) throws LinkageError, ClassNotFoundException;
  54     static native int getMembers(Class<?> defc, String matchName, String matchSig,
  55             int matchFlags, Class<?> caller, int skip, MemberName[] results);
  56 
  57     /// Field layout queries parallel to jdk.internal.misc.Unsafe:
  58     static native long objectFieldOffset(MemberName self);  // e.g., returns vmindex
  59     static native long staticFieldOffset(MemberName self);  // e.g., returns vmindex
  60     static native Object staticFieldBase(MemberName self);  // e.g., returns clazz
  61     static native Object getMemberVMInfo(MemberName self);  // returns {vmindex,vmtarget}
  62 
  63     /// CallSite support
  64 
  65     /** Tell the JVM that we need to change the target of a CallSite. */
  66     static native void setCallSiteTargetNormal(CallSite site, MethodHandle target);
  67     static native void setCallSiteTargetVolatile(CallSite site, MethodHandle target);
  68 
  69     static native void copyOutBootstrapArguments(Class<?> caller, int[] indexInfo,
  70                                                  int start, int end,
  71                                                  Object[] buf, int pos,
  72                                                  boolean resolve,
  73                                                  Object ifNotAvailable);
  74 
  75     /** Represents a context to track nmethod dependencies on CallSite instance target. */
  76     static class CallSiteContext implements Runnable {
  77         //@Injected JVM_nmethodBucket* vmdependencies;
  78         //@Injected jlong last_cleanup;
  79 
  80         static CallSiteContext make(CallSite cs) {
  81             final CallSiteContext newContext = new CallSiteContext();
  82             // CallSite instance is tracked by a Cleanable which clears native
  83             // structures allocated for CallSite context. Though the CallSite can
  84             // become unreachable, its Context is retained by the Cleanable instance
  85             // (which is referenced from Cleaner instance which is referenced from
  86             // CleanerFactory class) until cleanup is performed.
  87             CleanerFactory.cleaner().register(cs, newContext);
  88             return newContext;
  89         }
  90 
  91         @Override
  92         public void run() {
  93             MethodHandleNatives.clearCallSiteContext(this);
  94         }
  95     }
  96 
  97     /** Invalidate all recorded nmethods. */
  98     private static native void clearCallSiteContext(CallSiteContext context);
  99 
 100     private static native void registerNatives();
 101     static {
 102         registerNatives();
 103     }
 104 
 105     /**
 106      * Compile-time constants go here. This collection exists not only for
 107      * reference from clients, but also for ensuring the VM and JDK agree on the
 108      * values of these constants (see {@link #verifyConstants()}).
 109      */
 110     static class Constants {
 111         Constants() { } // static only
 112 
 113         static final int
 114             MN_IS_METHOD           = 0x00010000, // method (not constructor)
 115             MN_IS_CONSTRUCTOR      = 0x00020000, // constructor
 116             MN_IS_FIELD            = 0x00040000, // field
 117             MN_IS_TYPE             = 0x00080000, // nested type
 118             MN_CALLER_SENSITIVE    = 0x00100000, // @CallerSensitive annotation detected
 119             MN_REFERENCE_KIND_SHIFT = 24, // refKind
 120             MN_REFERENCE_KIND_MASK = 0x0F000000 >> MN_REFERENCE_KIND_SHIFT,
 121             // The SEARCH_* bits are not for MN.flags but for the matchFlags argument of MHN.getMembers:
 122             MN_SEARCH_SUPERCLASSES = 0x00100000,
 123             MN_SEARCH_INTERFACES   = 0x00200000;
 124 
 125         /**
 126          * Constant pool reference-kind codes, as used by CONSTANT_MethodHandle CP entries.
 127          */
 128         static final byte
 129             REF_NONE                    = 0,  // null value
 130             REF_getField                = 1,
 131             REF_getStatic               = 2,
 132             REF_putField                = 3,
 133             REF_putStatic               = 4,
 134             REF_invokeVirtual           = 5,
 135             REF_invokeStatic            = 6,
 136             REF_invokeSpecial           = 7,
 137             REF_newInvokeSpecial        = 8,
 138             REF_invokeInterface         = 9,
 139             REF_LIMIT                  = 10;
 140     }
 141 
 142     static boolean refKindIsValid(int refKind) {
 143         return (refKind > REF_NONE && refKind < REF_LIMIT);
 144     }
 145     static boolean refKindIsField(byte refKind) {
 146         assert(refKindIsValid(refKind));
 147         return (refKind <= REF_putStatic);
 148     }
 149     static boolean refKindIsGetter(byte refKind) {
 150         assert(refKindIsValid(refKind));
 151         return (refKind <= REF_getStatic);
 152     }
 153     static boolean refKindIsSetter(byte refKind) {
 154         return refKindIsField(refKind) && !refKindIsGetter(refKind);
 155     }
 156     static boolean refKindIsMethod(byte refKind) {
 157         return !refKindIsField(refKind) && (refKind != REF_newInvokeSpecial);
 158     }
 159     static boolean refKindIsConstructor(byte refKind) {
 160         return (refKind == REF_newInvokeSpecial);
 161     }
 162     static boolean refKindHasReceiver(byte refKind) {
 163         assert(refKindIsValid(refKind));
 164         return (refKind & 1) != 0;
 165     }
 166     static boolean refKindIsStatic(byte refKind) {
 167         return !refKindHasReceiver(refKind) && (refKind != REF_newInvokeSpecial);
 168     }
 169     static boolean refKindDoesDispatch(byte refKind) {
 170         assert(refKindIsValid(refKind));
 171         return (refKind == REF_invokeVirtual ||
 172                 refKind == REF_invokeInterface);
 173     }
 174     static {
 175         final int HR_MASK = ((1 << REF_getField) |
 176                              (1 << REF_putField) |
 177                              (1 << REF_invokeVirtual) |
 178                              (1 << REF_invokeSpecial) |
 179                              (1 << REF_invokeInterface)
 180                             );
 181         for (byte refKind = REF_NONE+1; refKind < REF_LIMIT; refKind++) {
 182             assert(refKindHasReceiver(refKind) == (((1<<refKind) & HR_MASK) != 0)) : refKind;
 183         }
 184     }
 185     static String refKindName(byte refKind) {
 186         assert(refKindIsValid(refKind));
 187         switch (refKind) {
 188         case REF_getField:          return "getField";
 189         case REF_getStatic:         return "getStatic";
 190         case REF_putField:          return "putField";
 191         case REF_putStatic:         return "putStatic";
 192         case REF_invokeVirtual:     return "invokeVirtual";
 193         case REF_invokeStatic:      return "invokeStatic";
 194         case REF_invokeSpecial:     return "invokeSpecial";
 195         case REF_newInvokeSpecial:  return "newInvokeSpecial";
 196         case REF_invokeInterface:   return "invokeInterface";
 197         default:                    return "REF_???";
 198         }
 199     }
 200 
 201     private static native int getNamedCon(int which, Object[] name);
 202     static boolean verifyConstants() {
 203         Object[] box = { null };
 204         for (int i = 0; ; i++) {
 205             box[0] = null;
 206             int vmval = getNamedCon(i, box);
 207             if (box[0] == null)  break;
 208             String name = (String) box[0];
 209             try {
 210                 Field con = Constants.class.getDeclaredField(name);
 211                 int jval = con.getInt(null);
 212                 if (jval == vmval)  continue;
 213                 String err = (name+": JVM has "+vmval+" while Java has "+jval);
 214                 if (name.equals("CONV_OP_LIMIT")) {
 215                     System.err.println("warning: "+err);
 216                     continue;
 217                 }
 218                 throw new InternalError(err);
 219             } catch (NoSuchFieldException | IllegalAccessException ex) {
 220                 String err = (name+": JVM has "+vmval+" which Java does not define");
 221                 // ignore exotic ops the JVM cares about; we just wont issue them
 222                 //System.err.println("warning: "+err);
 223                 continue;
 224             }
 225         }
 226         return true;
 227     }
 228     static {
 229         assert(verifyConstants());
 230     }
 231 
 232     // Up-calls from the JVM.
 233     // These must NOT be public.
 234 
 235     /**
 236      * The JVM is linking an invokedynamic instruction.  Create a reified call site for it.
 237      */
 238     static MemberName linkCallSite(Object callerObj,
 239                                    int indexInCP,
 240                                    Object bootstrapMethodObj,
 241                                    Object nameObj, Object typeObj,
 242                                    Object staticArguments,
 243                                    Object[] appendixResult) {
 244         MethodHandle bootstrapMethod = (MethodHandle)bootstrapMethodObj;
 245         Class<?> caller = (Class<?>)callerObj;
 246         String name = nameObj.toString().intern();
 247         MethodType type = (MethodType)typeObj;
 248         if (!TRACE_METHOD_LINKAGE)
 249             return linkCallSiteImpl(caller, bootstrapMethod, name, type,
 250                                     staticArguments, appendixResult);
 251         return linkCallSiteTracing(caller, bootstrapMethod, name, type,
 252                                    staticArguments, appendixResult);
 253     }
 254     static MemberName linkCallSiteImpl(Class<?> caller,
 255                                        MethodHandle bootstrapMethod,
 256                                        String name, MethodType type,
 257                                        Object staticArguments,
 258                                        Object[] appendixResult) {
 259         CallSite callSite = CallSite.makeSite(bootstrapMethod,
 260                                               name,
 261                                               type,
 262                                               staticArguments,
 263                                               caller);
 264         if (callSite instanceof ConstantCallSite) {
 265             appendixResult[0] = callSite.dynamicInvoker();
 266             return Invokers.linkToTargetMethod(type);
 267         } else {
 268             appendixResult[0] = callSite;
 269             return Invokers.linkToCallSiteMethod(type);
 270         }
 271     }
 272     // Tracing logic:
 273     static MemberName linkCallSiteTracing(Class<?> caller,
 274                                           MethodHandle bootstrapMethod,
 275                                           String name, MethodType type,
 276                                           Object staticArguments,
 277                                           Object[] appendixResult) {
 278         Object bsmReference = bootstrapMethod.internalMemberName();
 279         if (bsmReference == null)  bsmReference = bootstrapMethod;
 280         String staticArglist = staticArglistForTrace(staticArguments);
 281         System.out.println("linkCallSite "+caller.getName()+" "+
 282                            bsmReference+" "+
 283                            name+type+"/"+staticArglist);
 284         try {
 285             MemberName res = linkCallSiteImpl(caller, bootstrapMethod, name, type,
 286                                               staticArguments, appendixResult);
 287             System.out.println("linkCallSite => "+res+" + "+appendixResult[0]);
 288             return res;
 289         } catch (Throwable ex) {
 290             ex.printStackTrace(); // print now in case exception is swallowed
 291             System.out.println("linkCallSite => throw "+ex);
 292             throw ex;
 293         }
 294     }
 295 
 296     // this implements the upcall from the JVM, MethodHandleNatives.linkDynamicConstant:
 297     static Object linkDynamicConstant(Object callerObj,
 298                                       int indexInCP,
 299                                       Object bootstrapMethodObj,
 300                                       Object nameObj, Object typeObj,
 301                                       Object staticArguments) {
 302         MethodHandle bootstrapMethod = (MethodHandle)bootstrapMethodObj;
 303         Class<?> caller = (Class<?>)callerObj;
 304         String name = nameObj.toString().intern();
 305         Class<?> type = (Class<?>)typeObj;
 306         if (!TRACE_METHOD_LINKAGE)
 307             return linkDynamicConstantImpl(caller, bootstrapMethod, name, type, staticArguments);
 308         return linkDynamicConstantTracing(caller, bootstrapMethod, name, type, staticArguments);
 309     }
 310 
 311     static Object linkDynamicConstantImpl(Class<?> caller,
 312                                           MethodHandle bootstrapMethod,
 313                                           String name, Class<?> type,
 314                                           Object staticArguments) {
 315         return ConstantBootstraps.makeConstant(bootstrapMethod, name, type, staticArguments, caller);
 316     }
 317 
 318     private static String staticArglistForTrace(Object staticArguments) {
 319         if (staticArguments instanceof Object[])
 320             return "BSA="+java.util.Arrays.asList((Object[]) staticArguments);
 321         if (staticArguments instanceof int[])
 322             return "BSA@"+java.util.Arrays.toString((int[]) staticArguments);
 323         if (staticArguments == null)
 324             return "BSA0=null";
 325         return "BSA1="+staticArguments;
 326     }
 327 
 328     // Tracing logic:
 329     static Object linkDynamicConstantTracing(Class<?> caller,
 330                                              MethodHandle bootstrapMethod,
 331                                              String name, Class<?> type,
 332                                              Object staticArguments) {
 333         Object bsmReference = bootstrapMethod.internalMemberName();
 334         if (bsmReference == null)  bsmReference = bootstrapMethod;
 335         String staticArglist = staticArglistForTrace(staticArguments);
 336         System.out.println("linkDynamicConstant "+caller.getName()+" "+
 337                            bsmReference+" "+
 338                            name+type+"/"+staticArglist);
 339         try {
 340             Object res = linkDynamicConstantImpl(caller, bootstrapMethod, name, type, staticArguments);
 341             System.out.println("linkDynamicConstantImpl => "+res);
 342             return res;
 343         } catch (Throwable ex) {
 344             ex.printStackTrace(); // print now in case exception is swallowed
 345             System.out.println("linkDynamicConstant => throw "+ex);
 346             throw ex;
 347         }
 348     }
 349 
 350     /** The JVM is requesting pull-mode bootstrap when it provides
 351      *  a tuple of the form int[]{ argc, vmindex }.
 352      *  The BSM is expected to call back to the JVM using the caller
 353      *  class and vmindex to resolve the static arguments.
 354      */
 355     static boolean staticArgumentsPulled(Object staticArguments) {
 356         return staticArguments instanceof int[];
 357     }
 358 
 359     /** A BSM runs in pull-mode if and only if its sole arguments
 360      * are (Lookup, BootstrapCallInfo), or can be converted pairwise
 361      * to those types, and it is not of variable arity.
 362      * Excluding error cases, we can just test that the arity is a constant 2.
 363      *
 364      * NOTE: This method currently returns false, since pulling is not currently
 365      * exposed to a BSM. When pull mode is supported the method block will be
 366      * replaced with currently commented out code.
 367      */
 368     static boolean isPullModeBSM(MethodHandle bsm) {
 369         return bsm.type().parameterCount() == 2 && !bsm.isVarargsCollector()
 370                && BootstrapCallInfo.class.isAssignableFrom(bsm.type().parameterType(1));
 371     }
 372 
 373     /**
 374      * The JVM wants a pointer to a MethodType.  Oblige it by finding or creating one.
 375      */
 376     static MethodType findMethodHandleType(Class<?> rtype, Class<?>[] ptypes) {
 377         return MethodType.makeImpl(rtype, ptypes, true);
 378     }
 379 
 380     /**
 381      * The JVM wants to link a call site that requires a dynamic type check.
 382      * Name is a type-checking invoker, invokeExact or invoke.
 383      * Return a JVM method (MemberName) to handle the invoking.
 384      * The method assumes the following arguments on the stack:
 385      * 0: the method handle being invoked
 386      * 1-N: the arguments to the method handle invocation
 387      * N+1: an optional, implicitly added argument (typically the given MethodType)
 388      * <p>
 389      * The nominal method at such a call site is an instance of
 390      * a signature-polymorphic method (see @PolymorphicSignature).
 391      * Such method instances are user-visible entities which are
 392      * "split" from the generic placeholder method in {@code MethodHandle}.
 393      * (Note that the placeholder method is not identical with any of
 394      * its instances.  If invoked reflectively, is guaranteed to throw an
 395      * {@code UnsupportedOperationException}.)
 396      * If the signature-polymorphic method instance is ever reified,
 397      * it appears as a "copy" of the original placeholder
 398      * (a native final member of {@code MethodHandle}) except
 399      * that its type descriptor has shape required by the instance,
 400      * and the method instance is <em>not</em> varargs.
 401      * The method instance is also marked synthetic, since the
 402      * method (by definition) does not appear in Java source code.
 403      * <p>
 404      * The JVM is allowed to reify this method as instance metadata.
 405      * For example, {@code invokeBasic} is always reified.
 406      * But the JVM may instead call {@code linkMethod}.
 407      * If the result is an * ordered pair of a {@code (method, appendix)},
 408      * the method gets all the arguments (0..N inclusive)
 409      * plus the appendix (N+1), and uses the appendix to complete the call.
 410      * In this way, one reusable method (called a "linker method")
 411      * can perform the function of any number of polymorphic instance
 412      * methods.
 413      * <p>
 414      * Linker methods are allowed to be weakly typed, with any or
 415      * all references rewritten to {@code Object} and any primitives
 416      * (except {@code long}/{@code float}/{@code double})
 417      * rewritten to {@code int}.
 418      * A linker method is trusted to return a strongly typed result,
 419      * according to the specific method type descriptor of the
 420      * signature-polymorphic instance it is emulating.
 421      * This can involve (as necessary) a dynamic check using
 422      * data extracted from the appendix argument.
 423      * <p>
 424      * The JVM does not inspect the appendix, other than to pass
 425      * it verbatim to the linker method at every call.
 426      * This means that the JDK runtime has wide latitude
 427      * for choosing the shape of each linker method and its
 428      * corresponding appendix.
 429      * Linker methods should be generated from {@code LambdaForm}s
 430      * so that they do not become visible on stack traces.
 431      * <p>
 432      * The {@code linkMethod} call is free to omit the appendix
 433      * (returning null) and instead emulate the required function
 434      * completely in the linker method.
 435      * As a corner case, if N==255, no appendix is possible.
 436      * In this case, the method returned must be custom-generated to
 437      * perform any needed type checking.
 438      * <p>
 439      * If the JVM does not reify a method at a call site, but instead
 440      * calls {@code linkMethod}, the corresponding call represented
 441      * in the bytecodes may mention a valid method which is not
 442      * representable with a {@code MemberName}.
 443      * Therefore, use cases for {@code linkMethod} tend to correspond to
 444      * special cases in reflective code such as {@code findVirtual}
 445      * or {@code revealDirect}.
 446      */
 447     static MemberName linkMethod(Class<?> callerClass, int refKind,
 448                                  Class<?> defc, String name, Object type,
 449                                  Object[] appendixResult) {
 450         if (!TRACE_METHOD_LINKAGE)
 451             return linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
 452         return linkMethodTracing(callerClass, refKind, defc, name, type, appendixResult);
 453     }
 454     static MemberName linkMethodImpl(Class<?> callerClass, int refKind,
 455                                      Class<?> defc, String name, Object type,
 456                                      Object[] appendixResult) {
 457         try {
 458             if (refKind == REF_invokeVirtual) {
 459                 if (defc == MethodHandle.class) {
 460                     return Invokers.methodHandleInvokeLinkerMethod(
 461                             name, fixMethodType(callerClass, type), appendixResult);
 462                 } else if (defc == VarHandle.class) {
 463                     return varHandleOperationLinkerMethod(
 464                             name, fixMethodType(callerClass, type), appendixResult);
 465                 }
 466             }
 467         } catch (Error e) {
 468             // Pass through an Error, including say StackOverflowError or
 469             // OutOfMemoryError
 470             throw e;
 471         } catch (Throwable ex) {
 472             // Wrap anything else in LinkageError
 473             throw new LinkageError(ex.getMessage(), ex);
 474         }
 475         throw new LinkageError("no such method "+defc.getName()+"."+name+type);
 476     }
 477     private static MethodType fixMethodType(Class<?> callerClass, Object type) {
 478         if (type instanceof MethodType)
 479             return (MethodType) type;
 480         else
 481             return MethodType.fromDescriptor((String)type, callerClass.getClassLoader());
 482     }
 483     // Tracing logic:
 484     static MemberName linkMethodTracing(Class<?> callerClass, int refKind,
 485                                         Class<?> defc, String name, Object type,
 486                                         Object[] appendixResult) {
 487         System.out.println("linkMethod "+defc.getName()+"."+
 488                            name+type+"/"+Integer.toHexString(refKind));
 489         try {
 490             MemberName res = linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
 491             System.out.println("linkMethod => "+res+" + "+appendixResult[0]);
 492             return res;
 493         } catch (Throwable ex) {
 494             System.out.println("linkMethod => throw "+ex);
 495             throw ex;
 496         }
 497     }
 498 
 499     /**
 500      * Obtain the method to link to the VarHandle operation.
 501      * This method is located here and not in Invokers to avoid
 502      * intializing that and other classes early on in VM bootup.
 503      */
 504     private static MemberName varHandleOperationLinkerMethod(String name,
 505                                                              MethodType mtype,
 506                                                              Object[] appendixResult) {
 507         // Get the signature method type
 508         final MethodType sigType = mtype.basicType();
 509 
 510         // Get the access kind from the method name
 511         VarHandle.AccessMode ak;
 512         try {
 513             ak = VarHandle.AccessMode.valueFromMethodName(name);
 514         } catch (IllegalArgumentException e) {
 515             throw MethodHandleStatics.newInternalError(e);
 516         }
 517 
 518         // Create the appendix descriptor constant
 519         VarHandle.AccessDescriptor ad = new VarHandle.AccessDescriptor(mtype, ak.at.ordinal(), ak.ordinal());
 520         appendixResult[0] = ad;
 521 
 522         if (MethodHandleStatics.VAR_HANDLE_GUARDS) {
 523             // If not polymorphic in the return type, such as the compareAndSet
 524             // methods that return boolean
 525             Class<?> guardReturnType = sigType.returnType();
 526             if (ak.at.isMonomorphicInReturnType) {
 527                 if (ak.at.returnType != mtype.returnType()) {
 528                     // The caller contains a different return type than that
 529                     // defined by the method
 530                     throw newNoSuchMethodErrorOnVarHandle(name, mtype);
 531                 }
 532                 // Adjust the return type of the signature method type
 533                 guardReturnType = ak.at.returnType;
 534             }
 535 
 536             // Get the guard method type for linking
 537             final Class<?>[] guardParams = new Class<?>[sigType.parameterCount() + 2];
 538             // VarHandle at start
 539             guardParams[0] = VarHandle.class;
 540             for (int i = 0; i < sigType.parameterCount(); i++) {
 541                 guardParams[i + 1] = sigType.parameterType(i);
 542             }
 543             // Access descriptor at end
 544             guardParams[guardParams.length - 1] = VarHandle.AccessDescriptor.class;
 545             MethodType guardType = MethodType.makeImpl(guardReturnType, guardParams, true);
 546 
 547             MemberName linker = new MemberName(
 548                     VarHandleGuards.class, getVarHandleGuardMethodName(guardType),
 549                     guardType, REF_invokeStatic);
 550 
 551             linker = MemberName.getFactory().resolveOrNull(REF_invokeStatic, linker,
 552                                                            VarHandleGuards.class);
 553             if (linker != null) {
 554                 return linker;
 555             }
 556             // Fall back to lambda form linkage if guard method is not available
 557             // TODO Optionally log fallback ?
 558         }
 559         return Invokers.varHandleInvokeLinkerMethod(ak, mtype);
 560     }
 561     static String getVarHandleGuardMethodName(MethodType guardType) {
 562         String prefix = "guard_";
 563         StringBuilder sb = new StringBuilder(prefix.length() + guardType.parameterCount());
 564 
 565         sb.append(prefix);
 566         for (int i = 1; i < guardType.parameterCount() - 1; i++) {
 567             Class<?> pt = guardType.parameterType(i);
 568             sb.append(getCharType(pt));
 569         }
 570         sb.append('_').append(getCharType(guardType.returnType()));
 571         return sb.toString();
 572     }
 573     static char getCharType(Class<?> pt) {
 574         return Wrapper.forBasicType(pt).basicTypeChar();
 575     }
 576     static NoSuchMethodError newNoSuchMethodErrorOnVarHandle(String name, MethodType mtype) {
 577         return new NoSuchMethodError("VarHandle." + name + mtype);
 578     }
 579 
 580     /**
 581      * The JVM is resolving a CONSTANT_MethodHandle CP entry.  And it wants our help.
 582      * It will make an up-call to this method.  (Do not change the name or signature.)
 583      * The type argument is a Class for field requests and a MethodType for non-fields.
 584      * <p>
 585      * Recent versions of the JVM may also pass a resolved MemberName for the type.
 586      * In that case, the name is ignored and may be null.
 587      */
 588     static MethodHandle linkMethodHandleConstant(Class<?> callerClass, int refKind,
 589                                                  Class<?> defc, String name, Object type) {
 590         try {
 591             Lookup lookup = IMPL_LOOKUP.in(callerClass);
 592             assert(refKindIsValid(refKind));
 593             return lookup.linkMethodHandleConstant((byte) refKind, defc, name, type);
 594         } catch (ReflectiveOperationException ex) {
 595             throw mapLookupExceptionToError(ex);
 596         }
 597     }
 598 
 599     /**
 600      * Map a reflective exception to a linkage error.
 601      */
 602     static LinkageError mapLookupExceptionToError(ReflectiveOperationException ex) {
 603         LinkageError err;
 604         if (ex instanceof IllegalAccessException) {
 605             Throwable cause = ex.getCause();
 606             if (cause instanceof AbstractMethodError) {
 607                 return (AbstractMethodError) cause;
 608             } else {
 609                 err = new IllegalAccessError(ex.getMessage());
 610             }
 611         } else if (ex instanceof NoSuchMethodException) {
 612             err = new NoSuchMethodError(ex.getMessage());
 613         } else if (ex instanceof NoSuchFieldException) {
 614             err = new NoSuchFieldError(ex.getMessage());
 615         } else {
 616             err = new IncompatibleClassChangeError();
 617         }
 618         return initCauseFrom(err, ex);
 619     }
 620 
 621     /**
 622      * Use best possible cause for err.initCause(), substituting the
 623      * cause for err itself if the cause has the same (or better) type.
 624      */
 625     static <E extends Error> E initCauseFrom(E err, Exception ex) {
 626         Throwable th = ex.getCause();
 627         @SuppressWarnings("unchecked")
 628         final Class<E> Eclass = (Class<E>) err.getClass();
 629         if (Eclass.isInstance(th))
 630            return Eclass.cast(th);
 631         err.initCause(th == null ? ex : th);
 632         return err;
 633     }
 634 
 635     /**
 636      * Is this method a caller-sensitive method?
 637      * I.e., does it call Reflection.getCallerClass or a similar method
 638      * to ask about the identity of its caller?
 639      */
 640     static boolean isCallerSensitive(MemberName mem) {
 641         if (!mem.isInvocable())  return false;  // fields are not caller sensitive
 642 
 643         return mem.isCallerSensitive() || canBeCalledVirtual(mem);
 644     }
 645 
 646     static boolean canBeCalledVirtual(MemberName mem) {
 647         assert(mem.isInvocable());
 648         switch (mem.getName()) {
 649         case "getContextClassLoader":
 650             return canBeCalledVirtual(mem, java.lang.Thread.class);
 651         }
 652         return false;
 653     }
 654 
 655     static boolean canBeCalledVirtual(MemberName symbolicRef, Class<?> definingClass) {
 656         Class<?> symbolicRefClass = symbolicRef.getDeclaringClass();
 657         if (symbolicRefClass == definingClass)  return true;
 658         if (symbolicRef.isStatic() || symbolicRef.isPrivate())  return false;
 659         return (definingClass.isAssignableFrom(symbolicRefClass) ||  // Msym overrides Mdef
 660                 symbolicRefClass.isInterface());                     // Mdef implements Msym
 661     }
 662 }