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