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