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