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