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