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