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