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