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