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.value.PrimitiveClass; 29 import sun.invoke.util.VerifyAccess; 30 31 import java.lang.reflect.Constructor; 32 import java.lang.reflect.Field; 33 import java.lang.reflect.Member; 34 import java.lang.reflect.Method; 35 import java.lang.reflect.Modifier; 36 import java.util.Objects; 37 38 import static java.lang.invoke.MethodHandleNatives.Constants.*; 39 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; 40 import static java.lang.invoke.MethodHandleStatics.newInternalError; 41 42 /** 43 * A {@code MemberName} is a compact symbolic datum which fully characterizes 44 * a method or field reference. 45 * A member name refers to a field, method, constructor, or member type. 46 * Every member name has a simple name (a string) and a type (either a Class or MethodType). 47 * A member name may also have a non-null declaring class, or it may be simply 48 * a naked name/type pair. 49 * A member name may also have non-zero modifier flags. 50 * Finally, a member name may be either resolved or unresolved. 51 * If it is resolved, the existence of the named member has been determined by the JVM. 52 * <p> 53 * Whether resolved or not, a member name provides no access rights or 54 * invocation capability to its possessor. It is merely a compact 55 * representation of all symbolic information necessary to link to 56 * and properly use the named member. 57 * <p> 58 * When resolved, a member name's internal implementation may include references to JVM metadata. 59 * This representation is stateless and only descriptive. 60 * It provides no private information and no capability to use the member. 61 * <p> 62 * By contrast, a {@linkplain java.lang.reflect.Method} contains fuller information 63 * about the internals of a method (except its bytecodes) and also 64 * allows invocation. A MemberName is much lighter than a Method, 65 * since it contains about 7 fields to the 16 of Method (plus its sub-arrays), 66 * and those seven fields omit much of the information in Method. 67 * @author jrose 68 */ 69 70 /*non-public*/ 71 final class MemberName implements Member, Cloneable { 72 private Class<?> clazz; // class in which the member is defined 73 private String name; // may be null if not yet materialized 74 private Object type; // may be null if not yet materialized 75 private int flags; // modifier bits; see reflect.Modifier 76 private ResolvedMethodName method; // cached resolved method information 77 //@Injected intptr_t vmindex; // vtable index or offset of resolved member 78 Object resolution; // if null, this guy is resolved 79 80 /** Return the declaring class of this member. 81 * In the case of a bare name and type, the declaring class will be null. 82 */ 83 public Class<?> getDeclaringClass() { 84 return clazz; 85 } 86 87 /** Utility method producing the class loader of the declaring class. */ 88 public ClassLoader getClassLoader() { 89 return clazz.getClassLoader(); 90 } 91 92 /** Return the simple name of this member. 93 * For a type, it is the same as {@link Class#getSimpleName}. 94 * For a method or field, it is the simple name of the member. 95 * For an identity object constructor, it is {@code "<init>"}. 96 * For a value class static factory method, it is {@code "<vnew>"}. 97 */ 98 public String getName() { 99 if (name == null) { 100 expandFromVM(); 101 if (name == null) { 102 return null; 103 } 104 } 105 return name; 106 } 107 108 public MethodType getMethodOrFieldType() { 109 if (isInvocable()) 110 return getMethodType(); 111 if (isGetter()) 112 return MethodType.methodType(getFieldType()); 113 if (isSetter()) 114 return MethodType.methodType(void.class, getFieldType()); 115 throw new InternalError("not a method or field: "+this); 116 } 117 118 /** Return the declared type of this member, which 119 * must be a method or constructor. 120 */ 121 public MethodType getMethodType() { 122 if (type == null) { 123 expandFromVM(); 124 if (type == null) { 125 return null; 126 } 127 } 128 if (!isInvocable()) { 129 throw newIllegalArgumentException("not invocable, no method type"); 130 } 131 132 { 133 // Get a snapshot of type which doesn't get changed by racing threads. 134 final Object type = this.type; 135 if (type instanceof MethodType mt) { 136 return mt; 137 } 138 } 139 140 // type is not a MethodType yet. Convert it thread-safely. 141 synchronized (this) { 142 if (type instanceof String sig) { 143 MethodType res = MethodType.fromDescriptor(sig, getClassLoader()); 144 type = res; 145 } else if (type instanceof Object[] typeInfo) { 146 Class<?>[] ptypes = (Class<?>[]) typeInfo[1]; 147 Class<?> rtype = (Class<?>) typeInfo[0]; 148 MethodType res = MethodType.methodType(rtype, ptypes, true); 149 type = res; 150 } 151 // Make sure type is a MethodType for racing threads. 152 assert type instanceof MethodType : "bad method type " + type; 153 } 154 return (MethodType) type; 155 } 156 157 /** Return the descriptor of this member, which 158 * must be a method or constructor. 159 */ 160 String getMethodDescriptor() { 161 if (type == null) { 162 expandFromVM(); 163 if (type == null) { 164 return null; 165 } 166 } 167 if (!isInvocable()) { 168 throw newIllegalArgumentException("not invocable, no method type"); 169 } 170 171 // Get a snapshot of type which doesn't get changed by racing threads. 172 final Object type = this.type; 173 if (type instanceof String str) { 174 return str; 175 } else { 176 return getMethodType().toMethodDescriptorString(); 177 } 178 } 179 180 /** Return the actual type under which this method or constructor must be invoked. 181 * For non-static methods or constructors, this is the type with a leading parameter, 182 * a reference to declaring class. For static methods, it is the same as the declared type. 183 */ 184 public MethodType getInvocationType() { 185 MethodType itype = getMethodOrFieldType(); 186 Class<?> c = PrimitiveClass.isPrimitiveClass(clazz) ? PrimitiveClass.asValueType(clazz) : clazz; 187 if (isObjectConstructor() && getReferenceKind() == REF_newInvokeSpecial) 188 return itype.changeReturnType(c); 189 if (!isStatic()) 190 return itype.insertParameterTypes(0, c); 191 return itype; 192 } 193 194 /** Return the declared type of this member, which 195 * must be a field or type. 196 * If it is a type member, that type itself is returned. 197 */ 198 public Class<?> getFieldType() { 199 if (type == null) { 200 expandFromVM(); 201 if (type == null) { 202 return null; 203 } 204 } 205 if (isInvocable()) { 206 throw newIllegalArgumentException("not a field or nested class, no simple type"); 207 } 208 209 { 210 // Get a snapshot of type which doesn't get changed by racing threads. 211 final Object type = this.type; 212 if (type instanceof Class<?> cl) { 213 return cl; 214 } 215 } 216 217 // type is not a Class yet. Convert it thread-safely. 218 synchronized (this) { 219 if (type instanceof String sig) { 220 MethodType mtype = MethodType.fromDescriptor("()"+sig, getClassLoader()); 221 Class<?> res = mtype.returnType(); 222 type = res; 223 } 224 // Make sure type is a Class for racing threads. 225 assert type instanceof Class<?> : "bad field type " + type; 226 } 227 return (Class<?>) type; 228 } 229 230 /** Utility method to produce either the method type or field type of this member. */ 231 public Object getType() { 232 return (isInvocable() ? getMethodType() : getFieldType()); 233 } 234 235 /** Return the modifier flags of this member. 236 * @see java.lang.reflect.Modifier 237 */ 238 public int getModifiers() { 239 return (flags & RECOGNIZED_MODIFIERS); 240 } 241 242 /** Return the reference kind of this member, or zero if none. 243 */ 244 public byte getReferenceKind() { 245 return (byte) ((flags >>> MN_REFERENCE_KIND_SHIFT) & MN_REFERENCE_KIND_MASK); 246 } 247 private boolean referenceKindIsConsistent() { 248 byte refKind = getReferenceKind(); 249 if (refKind == REF_NONE) return isType(); 250 if (isField()) { 251 assert(staticIsConsistent()); 252 assert(MethodHandleNatives.refKindIsField(refKind)); 253 } else if (isObjectConstructor()) { 254 assert(refKind == REF_newInvokeSpecial || refKind == REF_invokeSpecial); 255 } else if (isMethod()) { 256 assert(staticIsConsistent()); 257 assert(MethodHandleNatives.refKindIsMethod(refKind)); 258 if (clazz.isInterface()) 259 assert(refKind == REF_invokeInterface || 260 refKind == REF_invokeStatic || 261 refKind == REF_invokeSpecial || 262 refKind == REF_invokeVirtual && isObjectPublicMethod()); 263 } else { 264 assert(false); 265 } 266 return true; 267 } 268 private boolean isObjectPublicMethod() { 269 if (clazz == Object.class) return true; 270 MethodType mtype = getMethodType(); 271 if (name.equals("toString") && mtype.returnType() == String.class && mtype.parameterCount() == 0) 272 return true; 273 if (name.equals("hashCode") && mtype.returnType() == int.class && mtype.parameterCount() == 0) 274 return true; 275 if (name.equals("equals") && mtype.returnType() == boolean.class && mtype.parameterCount() == 1 && mtype.parameterType(0) == Object.class) 276 return true; 277 return false; 278 } 279 280 /*non-public*/ 281 boolean referenceKindIsConsistentWith(int originalRefKind) { 282 int refKind = getReferenceKind(); 283 if (refKind == originalRefKind) return true; 284 if (getClass().desiredAssertionStatus()) { 285 switch (originalRefKind) { 286 case REF_invokeInterface -> { 287 // Looking up an interface method, can get (e.g.) Object.hashCode 288 assert (refKind == REF_invokeVirtual || refKind == REF_invokeSpecial) : this; 289 } 290 case REF_invokeVirtual, REF_newInvokeSpecial -> { 291 // Looked up a virtual, can get (e.g.) final String.hashCode. 292 assert (refKind == REF_invokeSpecial) : this; 293 } 294 default -> { 295 assert (false) : this + " != " + MethodHandleNatives.refKindName((byte) originalRefKind); 296 } 297 } 298 } 299 return true; 300 } 301 private boolean staticIsConsistent() { 302 byte refKind = getReferenceKind(); 303 return MethodHandleNatives.refKindIsStatic(refKind) == isStatic() || getModifiers() == 0; 304 } 305 private boolean vminfoIsConsistent() { 306 byte refKind = getReferenceKind(); 307 assert(isResolved()); // else don't call 308 Object vminfo = MethodHandleNatives.getMemberVMInfo(this); 309 assert(vminfo instanceof Object[]); 310 long vmindex = (Long) ((Object[])vminfo)[0]; 311 Object vmtarget = ((Object[])vminfo)[1]; 312 if (MethodHandleNatives.refKindIsField(refKind)) { 313 assert(vmindex >= 0) : vmindex + ":" + this; 314 assert(vmtarget instanceof Class); 315 } else { 316 if (MethodHandleNatives.refKindDoesDispatch(refKind)) 317 assert(vmindex >= 0) : vmindex + ":" + this; 318 else 319 assert(vmindex < 0) : vmindex; 320 assert(vmtarget instanceof MemberName) : vmtarget + " in " + this; 321 } 322 return true; 323 } 324 325 private MemberName changeReferenceKind(byte refKind, byte oldKind) { 326 assert(getReferenceKind() == oldKind && MethodHandleNatives.refKindIsValid(refKind)); 327 flags += (((int)refKind - oldKind) << MN_REFERENCE_KIND_SHIFT); 328 return this; 329 } 330 331 private boolean matchingFlagsSet(int mask, int flags) { 332 return (this.flags & mask) == flags; 333 } 334 private boolean allFlagsSet(int flags) { 335 return (this.flags & flags) == flags; 336 } 337 private boolean anyFlagSet(int flags) { 338 return (this.flags & flags) != 0; 339 } 340 341 /** Utility method to query if this member is a method handle invocation (invoke or invokeExact). 342 */ 343 public boolean isMethodHandleInvoke() { 344 final int bits = MH_INVOKE_MODS &~ Modifier.PUBLIC; 345 final int negs = Modifier.STATIC; 346 if (matchingFlagsSet(bits | negs, bits) && clazz == MethodHandle.class) { 347 return isMethodHandleInvokeName(name); 348 } 349 return false; 350 } 351 public static boolean isMethodHandleInvokeName(String name) { 352 return switch (name) { 353 case "invoke", "invokeExact" -> true; 354 default -> false; 355 }; 356 } 357 public boolean isVarHandleMethodInvoke() { 358 final int bits = MH_INVOKE_MODS &~ Modifier.PUBLIC; 359 final int negs = Modifier.STATIC; 360 if (matchingFlagsSet(bits | negs, bits) && clazz == VarHandle.class) { 361 return isVarHandleMethodInvokeName(name); 362 } 363 return false; 364 } 365 public static boolean isVarHandleMethodInvokeName(String name) { 366 try { 367 VarHandle.AccessMode.valueFromMethodName(name); 368 return true; 369 } catch (IllegalArgumentException e) { 370 return false; 371 } 372 } 373 private static final int MH_INVOKE_MODS = Modifier.NATIVE | Modifier.FINAL | Modifier.PUBLIC; 374 375 /** Utility method to query the modifier flags of this member. */ 376 public boolean isStatic() { 377 return Modifier.isStatic(flags); 378 } 379 /** Utility method to query the modifier flags of this member. */ 380 public boolean isPublic() { 381 return Modifier.isPublic(flags); 382 } 383 /** Utility method to query the modifier flags of this member. */ 384 public boolean isPrivate() { 385 return Modifier.isPrivate(flags); 386 } 387 /** Utility method to query the modifier flags of this member. */ 388 public boolean isProtected() { 389 return Modifier.isProtected(flags); 390 } 391 /** Utility method to query the modifier flags of this member. */ 392 public boolean isFinal() { 393 // all fields declared in a value type are effectively final 394 assert(!clazz.isValue() || !isField() || Modifier.isFinal(flags)); 395 return Modifier.isFinal(flags); 396 } 397 /** Utility method to query whether this member or its defining class is final. */ 398 public boolean canBeStaticallyBound() { 399 return Modifier.isFinal(flags | clazz.getModifiers()); 400 } 401 /** Utility method to query the modifier flags of this member. */ 402 public boolean isVolatile() { 403 return Modifier.isVolatile(flags); 404 } 405 /** Utility method to query the modifier flags of this member. */ 406 public boolean isAbstract() { 407 return Modifier.isAbstract(flags); 408 } 409 /** Utility method to query the modifier flags of this member. */ 410 public boolean isNative() { 411 return Modifier.isNative(flags); 412 } 413 // let the rest (native, volatile, transient, etc.) be tested via Modifier.isFoo 414 415 // unofficial modifier flags, used by HotSpot: 416 static final int BRIDGE = 0x00000040; 417 static final int VARARGS = 0x00000080; 418 static final int SYNTHETIC = 0x00001000; 419 static final int ANNOTATION = 0x00002000; 420 static final int ENUM = 0x00004000; 421 422 /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */ 423 public boolean isBridge() { 424 return allFlagsSet(IS_METHOD | BRIDGE); 425 } 426 /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */ 427 public boolean isVarargs() { 428 return allFlagsSet(VARARGS) && isInvocable(); 429 } 430 /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */ 431 public boolean isSynthetic() { 432 return allFlagsSet(SYNTHETIC); 433 } 434 435 /** Query whether this member is a flattened field */ 436 public boolean isFlattened() { return (flags & MN_FLATTENED) == MN_FLATTENED; } 437 438 /** Query whether this member is a field of a primitive class. */ 439 public boolean isInlineableField() { 440 if (isField()) { 441 Class<?> type = getFieldType(); 442 return PrimitiveClass.isPrimitiveValueType(type) || (type.isValue() && !PrimitiveClass.isPrimitiveClass(type)); 443 } 444 return false; 445 } 446 447 static final String CONSTRUCTOR_NAME = "<init>"; 448 static final String VALUE_FACTORY_NAME = "<vnew>"; // the ever-popular 449 450 // modifiers exported by the JVM: 451 static final int RECOGNIZED_MODIFIERS = 0xFFFF; 452 453 // private flags, not part of RECOGNIZED_MODIFIERS: 454 static final int 455 IS_METHOD = MN_IS_METHOD, // method (not object constructor) 456 IS_OBJECT_CONSTRUCTOR = MN_IS_OBJECT_CONSTRUCTOR, // object constructor 457 IS_FIELD = MN_IS_FIELD, // field 458 IS_TYPE = MN_IS_TYPE, // nested type 459 CALLER_SENSITIVE = MN_CALLER_SENSITIVE, // @CallerSensitive annotation detected 460 TRUSTED_FINAL = MN_TRUSTED_FINAL; // trusted final field 461 462 static final int ALL_ACCESS = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED; 463 static final int ALL_KINDS = IS_METHOD | IS_OBJECT_CONSTRUCTOR | IS_FIELD | IS_TYPE; 464 static final int IS_INVOCABLE = IS_METHOD | IS_OBJECT_CONSTRUCTOR; 465 466 /** Utility method to query whether this member is a method or constructor. */ 467 public boolean isInvocable() { 468 return anyFlagSet(IS_INVOCABLE); 469 } 470 /** Query whether this member is a method. */ 471 public boolean isMethod() { 472 return allFlagsSet(IS_METHOD); 473 } 474 /** Query whether this member is a constructor. */ 475 public boolean isObjectConstructor() { 476 return allFlagsSet(IS_OBJECT_CONSTRUCTOR); 477 } 478 /** Query whether this member is an object constructor or static <init> factory */ 479 public boolean isStaticValueFactoryMethod() { 480 return VALUE_FACTORY_NAME.equals(name) && isMethod(); 481 } 482 483 /** Query whether this member is a field. */ 484 public boolean isField() { 485 return allFlagsSet(IS_FIELD); 486 } 487 /** Query whether this member is a type. */ 488 public boolean isType() { 489 return allFlagsSet(IS_TYPE); 490 } 491 /** Utility method to query whether this member is neither public, private, nor protected. */ 492 public boolean isPackage() { 493 return !anyFlagSet(ALL_ACCESS); 494 } 495 /** Query whether this member has a CallerSensitive annotation. */ 496 public boolean isCallerSensitive() { 497 return allFlagsSet(CALLER_SENSITIVE); 498 } 499 /** Query whether this member is a trusted final field. */ 500 public boolean isTrustedFinalField() { 501 return allFlagsSet(TRUSTED_FINAL | IS_FIELD); 502 } 503 504 /** 505 * Check if MemberName is a call to a method named {@code name} in class {@code declaredClass}. 506 */ 507 public boolean refersTo(Class<?> declc, String n) { 508 return clazz == declc && getName().equals(n); 509 } 510 511 /** Initialize a query. It is not resolved. */ 512 private void init(Class<?> defClass, String name, Object type, int flags) { 513 // defining class is allowed to be null (for a naked name/type pair) 514 //name.toString(); // null check 515 //type.equals(type); // null check 516 // fill in fields: 517 this.clazz = defClass; 518 this.name = name; 519 this.type = type; 520 this.flags = flags; 521 assert(anyFlagSet(ALL_KINDS) && this.resolution == null); // nobody should have touched this yet 522 //assert(referenceKindIsConsistent()); // do this after resolution 523 } 524 525 /** 526 * Calls down to the VM to fill in the fields. This method is 527 * synchronized to avoid racing calls. 528 */ 529 private void expandFromVM() { 530 if (type != null) { 531 return; 532 } 533 if (!isResolved()) { 534 return; 535 } 536 MethodHandleNatives.expand(this); 537 } 538 539 // Capturing information from the Core Reflection API: 540 private static int flagsMods(int flags, int mods, byte refKind) { 541 assert((flags & RECOGNIZED_MODIFIERS) == 0 542 && (mods & ~RECOGNIZED_MODIFIERS) == 0 543 && (refKind & ~MN_REFERENCE_KIND_MASK) == 0); 544 return flags | mods | (refKind << MN_REFERENCE_KIND_SHIFT); 545 } 546 /** Create a name for the given reflected method. The resulting name will be in a resolved state. */ 547 public MemberName(Method m) { 548 this(m, false); 549 } 550 @SuppressWarnings("LeakingThisInConstructor") 551 public MemberName(Method m, boolean wantSpecial) { 552 Objects.requireNonNull(m); 553 // fill in vmtarget, vmindex while we have m in hand: 554 MethodHandleNatives.init(this, m); 555 if (clazz == null) { // MHN.init failed 556 if (m.getDeclaringClass() == MethodHandle.class && 557 isMethodHandleInvokeName(m.getName())) { 558 // The JVM did not reify this signature-polymorphic instance. 559 // Need a special case here. 560 // See comments on MethodHandleNatives.linkMethod. 561 MethodType type = MethodType.methodType(m.getReturnType(), m.getParameterTypes()); 562 int flags = flagsMods(IS_METHOD, m.getModifiers(), REF_invokeVirtual); 563 init(MethodHandle.class, m.getName(), type, flags); 564 if (isMethodHandleInvoke()) 565 return; 566 } 567 if (m.getDeclaringClass() == VarHandle.class && 568 isVarHandleMethodInvokeName(m.getName())) { 569 // The JVM did not reify this signature-polymorphic instance. 570 // Need a special case here. 571 // See comments on MethodHandleNatives.linkMethod. 572 MethodType type = MethodType.methodType(m.getReturnType(), m.getParameterTypes()); 573 int flags = flagsMods(IS_METHOD, m.getModifiers(), REF_invokeVirtual); 574 init(VarHandle.class, m.getName(), type, flags); 575 if (isVarHandleMethodInvoke()) 576 return; 577 } 578 throw new LinkageError(m.toString()); 579 } 580 assert(isResolved()); 581 this.name = m.getName(); 582 if (this.type == null) 583 this.type = new Object[] { m.getReturnType(), m.getParameterTypes() }; 584 if (wantSpecial) { 585 if (isAbstract()) 586 throw new AbstractMethodError(this.toString()); 587 if (getReferenceKind() == REF_invokeVirtual) 588 changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual); 589 else if (getReferenceKind() == REF_invokeInterface) 590 // invokeSpecial on a default method 591 changeReferenceKind(REF_invokeSpecial, REF_invokeInterface); 592 } 593 } 594 public MemberName asSpecial() { 595 switch (getReferenceKind()) { 596 case REF_invokeSpecial: return this; 597 case REF_invokeVirtual: return clone().changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual); 598 case REF_invokeInterface: return clone().changeReferenceKind(REF_invokeSpecial, REF_invokeInterface); 599 case REF_newInvokeSpecial: return clone().changeReferenceKind(REF_invokeSpecial, REF_newInvokeSpecial); 600 } 601 throw new IllegalArgumentException(this.toString()); 602 } 603 /** If this MN is not REF_newInvokeSpecial, return a clone with that ref. kind. 604 * In that case it must already be REF_invokeSpecial. 605 */ 606 public MemberName asObjectConstructor() { 607 switch (getReferenceKind()) { 608 case REF_invokeSpecial: return clone().changeReferenceKind(REF_newInvokeSpecial, REF_invokeSpecial); 609 case REF_newInvokeSpecial: return this; 610 } 611 throw new IllegalArgumentException(this.toString()); 612 } 613 /** If this MN is a REF_invokeSpecial, return a clone with the "normal" kind 614 * REF_invokeVirtual; also switch either to REF_invokeInterface if clazz.isInterface. 615 * The end result is to get a fully virtualized version of the MN. 616 * (Note that resolving in the JVM will sometimes devirtualize, changing 617 * REF_invokeVirtual of a final to REF_invokeSpecial, and REF_invokeInterface 618 * in some corner cases to either of the previous two; this transform 619 * undoes that change under the assumption that it occurred.) 620 */ 621 public MemberName asNormalOriginal() { 622 byte refKind = getReferenceKind(); 623 byte newRefKind = switch (refKind) { 624 case REF_invokeInterface, 625 REF_invokeVirtual, 626 REF_invokeSpecial -> clazz.isInterface() ? REF_invokeInterface : REF_invokeVirtual; 627 default -> refKind; 628 }; 629 if (newRefKind == refKind) 630 return this; 631 MemberName result = clone().changeReferenceKind(newRefKind, refKind); 632 assert(this.referenceKindIsConsistentWith(result.getReferenceKind())); 633 return result; 634 } 635 /** Create a name for the given reflected constructor. The resulting name will be in a resolved state. */ 636 @SuppressWarnings("LeakingThisInConstructor") 637 public MemberName(Constructor<?> ctor) { 638 Objects.requireNonNull(ctor); 639 // fill in vmtarget, vmindex while we have ctor in hand: 640 MethodHandleNatives.init(this, ctor); 641 assert(isResolved() && this.clazz != null); 642 this.name = this.clazz.isValue() ? VALUE_FACTORY_NAME : CONSTRUCTOR_NAME; 643 if (this.type == null) { 644 Class<?> rtype = void.class; 645 if (isStatic()) { // a value class static factory, not a true constructor 646 rtype = getDeclaringClass(); 647 } 648 this.type = new Object[] { rtype, ctor.getParameterTypes() }; 649 } 650 } 651 /** Create a name for the given reflected field. The resulting name will be in a resolved state. 652 */ 653 public MemberName(Field fld) { 654 this(fld, false); 655 } 656 static { 657 // the following MemberName constructor relies on these ranges matching up 658 assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField)); 659 } 660 @SuppressWarnings("LeakingThisInConstructor") 661 public MemberName(Field fld, boolean makeSetter) { 662 Objects.requireNonNull(fld); 663 // fill in vmtarget, vmindex while we have fld in hand: 664 MethodHandleNatives.init(this, fld); 665 assert(isResolved() && this.clazz != null); 666 this.name = fld.getName(); 667 this.type = fld.getType(); 668 byte refKind = this.getReferenceKind(); 669 assert(refKind == (isStatic() ? REF_getStatic : REF_getField)); 670 if (makeSetter) { 671 changeReferenceKind((byte)(refKind + (REF_putStatic - REF_getStatic)), refKind); 672 } 673 } 674 public boolean isGetter() { 675 return MethodHandleNatives.refKindIsGetter(getReferenceKind()); 676 } 677 public boolean isSetter() { 678 return MethodHandleNatives.refKindIsSetter(getReferenceKind()); 679 } 680 681 /** Create a name for the given class. The resulting name will be in a resolved state. */ 682 public MemberName(Class<?> type) { 683 init(type.getDeclaringClass(), type.getSimpleName(), type, 684 flagsMods(IS_TYPE, type.getModifiers(), REF_NONE)); 685 initResolved(true); 686 } 687 688 /** 689 * Create a name for a signature-polymorphic invoker. 690 * This is a placeholder for a signature-polymorphic instance 691 * (of MH.invokeExact, etc.) that the JVM does not reify. 692 * See comments on {@link MethodHandleNatives#linkMethod}. 693 */ 694 static MemberName makeMethodHandleInvoke(String name, MethodType type) { 695 return makeMethodHandleInvoke(name, type, MH_INVOKE_MODS | SYNTHETIC); 696 } 697 static MemberName makeMethodHandleInvoke(String name, MethodType type, int mods) { 698 MemberName mem = new MemberName(MethodHandle.class, name, type, REF_invokeVirtual); 699 mem.flags |= mods; // it's not resolved, but add these modifiers anyway 700 assert(mem.isMethodHandleInvoke()) : mem; 701 return mem; 702 } 703 704 static MemberName makeVarHandleMethodInvoke(String name, MethodType type) { 705 return makeVarHandleMethodInvoke(name, type, MH_INVOKE_MODS | SYNTHETIC); 706 } 707 static MemberName makeVarHandleMethodInvoke(String name, MethodType type, int mods) { 708 MemberName mem = new MemberName(VarHandle.class, name, type, REF_invokeVirtual); 709 mem.flags |= mods; // it's not resolved, but add these modifiers anyway 710 assert(mem.isVarHandleMethodInvoke()) : mem; 711 return mem; 712 } 713 714 // bare-bones constructor; the JVM will fill it in 715 MemberName() { } 716 717 // locally useful cloner 718 @Override protected MemberName clone() { 719 try { 720 return (MemberName) super.clone(); 721 } catch (CloneNotSupportedException ex) { 722 throw newInternalError(ex); 723 } 724 } 725 726 /** Get the definition of this member name. 727 * This may be in a super-class of the declaring class of this member. 728 */ 729 public MemberName getDefinition() { 730 if (!isResolved()) throw new IllegalStateException("must be resolved: "+this); 731 if (isType()) return this; 732 MemberName res = this.clone(); 733 res.clazz = null; 734 res.type = null; 735 res.name = null; 736 res.resolution = res; 737 res.expandFromVM(); 738 assert(res.getName().equals(this.getName())); 739 return res; 740 } 741 742 @Override 743 @SuppressWarnings({"deprecation", "removal"}) 744 public int hashCode() { 745 // Avoid autoboxing getReferenceKind(), since this is used early and will force 746 // early initialization of Byte$ByteCache 747 return Objects.hash(clazz, new Byte(getReferenceKind()), name, getType()); 748 } 749 750 @Override 751 public boolean equals(Object that) { 752 return that instanceof MemberName mn && this.equals(mn); 753 } 754 755 /** Decide if two member names have exactly the same symbolic content. 756 * Does not take into account any actual class members, so even if 757 * two member names resolve to the same actual member, they may 758 * be distinct references. 759 */ 760 public boolean equals(MemberName that) { 761 if (this == that) return true; 762 if (that == null) return false; 763 return this.clazz == that.clazz 764 && this.getReferenceKind() == that.getReferenceKind() 765 && Objects.equals(this.name, that.name) 766 && Objects.equals(this.getType(), that.getType()); 767 } 768 769 // Construction from symbolic parts, for queries: 770 /** Create a field or type name from the given components: 771 * Declaring class, name, type, reference kind. 772 * The declaring class may be supplied as null if this is to be a bare name and type. 773 * The resulting name will in an unresolved state. 774 */ 775 public MemberName(Class<?> defClass, String name, Class<?> type, byte refKind) { 776 init(defClass, name, type, flagsMods(IS_FIELD, 0, refKind)); 777 initResolved(false); 778 } 779 /** Create a method or constructor name from the given components: 780 * Declaring class, name, type, reference kind. 781 * It will be an object constructor if and only if the name is {@code "<init>"}. 782 * It will be a value class instance factory method if and only if the name is {@code "<vnew>"}. 783 * The declaring class may be supplied as null if this is to be a bare name and type. 784 * The last argument is optional, a boolean which requests REF_invokeSpecial. 785 * The resulting name will in an unresolved state. 786 */ 787 public MemberName(Class<?> defClass, String name, MethodType type, byte refKind) { 788 int initFlags = CONSTRUCTOR_NAME.equals(name) ? IS_OBJECT_CONSTRUCTOR : IS_METHOD; 789 init(defClass, name, type, flagsMods(initFlags, 0, refKind)); 790 initResolved(false); 791 } 792 /** Create a method, constructor, or field name from the given components: 793 * Reference kind, declaring class, name, type. 794 */ 795 public MemberName(byte refKind, Class<?> defClass, String name, Object type) { 796 int kindFlags; 797 if (MethodHandleNatives.refKindIsField(refKind)) { 798 kindFlags = IS_FIELD; 799 if (!(type instanceof Class)) 800 throw newIllegalArgumentException("not a field type"); 801 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 802 kindFlags = IS_METHOD; 803 if (!(type instanceof MethodType)) 804 throw newIllegalArgumentException("not a method type"); 805 } else if (refKind == REF_newInvokeSpecial) { 806 kindFlags = IS_OBJECT_CONSTRUCTOR; 807 if (!(type instanceof MethodType) || 808 !CONSTRUCTOR_NAME.equals(name)) 809 throw newIllegalArgumentException("not a constructor type or name"); 810 } else { 811 throw newIllegalArgumentException("bad reference kind "+refKind); 812 } 813 init(defClass, name, type, flagsMods(kindFlags, 0, refKind)); 814 initResolved(false); 815 } 816 817 /** Query whether this member name is resolved. 818 * A resolved member name is one for which the JVM has found 819 * a method, constructor, field, or type binding corresponding exactly to the name. 820 * (Document?) 821 */ 822 public boolean isResolved() { 823 return resolution == null; 824 } 825 826 void initResolved(boolean isResolved) { 827 assert(this.resolution == null); // not initialized yet! 828 if (!isResolved) 829 this.resolution = this; 830 assert(isResolved() == isResolved); 831 } 832 833 void checkForTypeAlias(Class<?> refc) { 834 if (isInvocable()) { 835 MethodType type; 836 if (this.type instanceof MethodType mt) 837 type = mt; 838 else 839 this.type = type = getMethodType(); 840 if (type.erase() == type) return; 841 if (VerifyAccess.isTypeVisible(type, refc)) return; 842 throw new LinkageError("bad method type alias: "+type+" not visible from "+refc); 843 } else { 844 Class<?> type; 845 if (this.type instanceof Class<?> cl) 846 type = cl; 847 else 848 this.type = type = getFieldType(); 849 if (VerifyAccess.isTypeVisible(type, refc)) return; 850 throw new LinkageError("bad field type alias: "+type+" not visible from "+refc); 851 } 852 } 853 854 855 /** Produce a string form of this member name. 856 * For types, it is simply the type's own string (as reported by {@code toString}). 857 * For fields, it is {@code "DeclaringClass.name/type"}. 858 * For methods and constructors, it is {@code "DeclaringClass.name(ptype...)rtype"}. 859 * If the declaring class is null, the prefix {@code "DeclaringClass."} is omitted. 860 * If the member is unresolved, a prefix {@code "*."} is prepended. 861 */ 862 @SuppressWarnings("LocalVariableHidesMemberVariable") 863 @Override 864 public String toString() { 865 if (isType()) 866 return type.toString(); // class java.lang.String 867 // else it is a field, method, or constructor 868 StringBuilder buf = new StringBuilder(); 869 if (getDeclaringClass() != null) { 870 buf.append(getName(clazz)); 871 buf.append('.'); 872 } 873 String name = this.name; // avoid expanding from VM 874 buf.append(name == null ? "*" : name); 875 Object type = this.type; // avoid expanding from VM 876 if (!isInvocable()) { 877 buf.append('/'); 878 buf.append(type == null ? "*" : getName(type)); 879 } else { 880 buf.append(type == null ? "(*)*" : getName(type)); 881 } 882 byte refKind = getReferenceKind(); 883 if (refKind != REF_NONE) { 884 buf.append('/'); 885 buf.append(MethodHandleNatives.refKindName(refKind)); 886 } 887 //buf.append("#").append(System.identityHashCode(this)); 888 return buf.toString(); 889 } 890 private static String getName(Object obj) { 891 if (obj instanceof Class<?> cl) 892 return cl.getName(); 893 return String.valueOf(obj); 894 } 895 896 public IllegalAccessException makeAccessException(String message, Object from) { 897 message = message + ": " + this; 898 if (from != null) { 899 if (from == MethodHandles.publicLookup()) { 900 message += ", from public Lookup"; 901 } else { 902 Module m; 903 Class<?> plc; 904 if (from instanceof MethodHandles.Lookup lookup) { 905 from = lookup.lookupClass(); 906 m = lookup.lookupClass().getModule(); 907 plc = lookup.previousLookupClass(); 908 } else { 909 m = ((Class<?>)from).getModule(); 910 plc = null; 911 } 912 message += ", from " + from + " (" + m + ")"; 913 if (plc != null) { 914 message += ", previous lookup " + 915 plc.getName() + " (" + plc.getModule() + ")"; 916 } 917 } 918 } 919 return new IllegalAccessException(message); 920 } 921 private String message() { 922 if (isResolved()) 923 return "no access"; 924 else if (isObjectConstructor()) 925 return "no such constructor"; 926 else if (isMethod()) 927 return "no such method"; 928 else 929 return "no such field"; 930 } 931 public ReflectiveOperationException makeAccessException() { 932 String message = message() + ": " + this; 933 ReflectiveOperationException ex; 934 if (isResolved() || !(resolution instanceof NoSuchMethodError || 935 resolution instanceof NoSuchFieldError)) 936 ex = new IllegalAccessException(message); 937 else if (isObjectConstructor()) 938 ex = new NoSuchMethodException(message); 939 else if (isMethod()) 940 ex = new NoSuchMethodException(message); 941 else 942 ex = new NoSuchFieldException(message); 943 if (resolution instanceof Throwable res) 944 ex.initCause(res); 945 return ex; 946 } 947 948 /** Actually making a query requires an access check. */ 949 /*non-public*/ 950 static Factory getFactory() { 951 return Factory.INSTANCE; 952 } 953 /** A factory type for resolving member names with the help of the VM. 954 * TBD: Define access-safe public constructors for this factory. 955 */ 956 /*non-public*/ 957 static class Factory { 958 private Factory() { } // singleton pattern 959 static final Factory INSTANCE = new Factory(); 960 961 /** Produce a resolved version of the given member. 962 * Super types are searched (for inherited members) if {@code searchSupers} is true. 963 * Access checking is performed on behalf of the given {@code lookupClass}. 964 * If lookup fails or access is not permitted, null is returned. 965 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in. 966 */ 967 private MemberName resolve(byte refKind, MemberName ref, Class<?> lookupClass, int allowedModes, 968 boolean speculativeResolve) { 969 MemberName m = ref.clone(); // JVM will side-effect the ref 970 assert(refKind == m.getReferenceKind()); 971 try { 972 // There are 4 entities in play here: 973 // * LC: lookupClass 974 // * REFC: symbolic reference class (MN.clazz before resolution); 975 // * DEFC: resolved method holder (MN.clazz after resolution); 976 // * PTYPES: parameter types (MN.type) 977 // 978 // What we care about when resolving a MemberName is consistency between DEFC and PTYPES. 979 // We do type alias (TA) checks on DEFC to ensure that. DEFC is not known until the JVM 980 // finishes the resolution, so do TA checks right after MHN.resolve() is over. 981 // 982 // All parameters passed by a caller are checked against MH type (PTYPES) on every invocation, 983 // so it is safe to call a MH from any context. 984 // 985 // REFC view on PTYPES doesn't matter, since it is used only as a starting point for resolution and doesn't 986 // participate in method selection. 987 m = MethodHandleNatives.resolve(m, lookupClass, allowedModes, speculativeResolve); 988 if (m == null && speculativeResolve) { 989 return null; 990 } 991 m.checkForTypeAlias(m.getDeclaringClass()); 992 m.resolution = null; 993 } catch (ClassNotFoundException | LinkageError ex) { 994 // JVM reports that the "bytecode behavior" would get an error 995 assert(!m.isResolved()); 996 m.resolution = ex; 997 return m; 998 } 999 assert(m.referenceKindIsConsistent()); 1000 m.initResolved(true); 1001 assert(m.vminfoIsConsistent()); 1002 return m; 1003 } 1004 /** Produce a resolved version of the given member. 1005 * Super types are searched (for inherited members) if {@code searchSupers} is true. 1006 * Access checking is performed on behalf of the given {@code lookupClass}. 1007 * If lookup fails or access is not permitted, a {@linkplain ReflectiveOperationException} is thrown. 1008 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in. 1009 */ 1010 public <NoSuchMemberException extends ReflectiveOperationException> 1011 MemberName resolveOrFail(byte refKind, MemberName m, 1012 Class<?> lookupClass, int allowedModes, 1013 Class<NoSuchMemberException> nsmClass) 1014 throws IllegalAccessException, NoSuchMemberException { 1015 assert lookupClass != null || allowedModes == LM_TRUSTED; 1016 MemberName result = resolve(refKind, m, lookupClass, allowedModes, false); 1017 if (result.isResolved()) 1018 return result; 1019 ReflectiveOperationException ex = result.makeAccessException(); 1020 if (ex instanceof IllegalAccessException iae) throw iae; 1021 throw nsmClass.cast(ex); 1022 } 1023 /** Produce a resolved version of the given member. 1024 * Super types are searched (for inherited members) if {@code searchSupers} is true. 1025 * Access checking is performed on behalf of the given {@code lookupClass}. 1026 * If lookup fails or access is not permitted, return null. 1027 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in. 1028 */ 1029 public MemberName resolveOrNull(byte refKind, MemberName m, Class<?> lookupClass, int allowedModes) { 1030 assert lookupClass != null || allowedModes == LM_TRUSTED; 1031 MemberName result = resolve(refKind, m, lookupClass, allowedModes, true); 1032 if (result != null && result.isResolved()) 1033 return result; 1034 return null; 1035 } 1036 } 1037 }