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