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