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