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