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