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 return Modifier.isFinal(flags); 402 } 403 /** Utility method to query whether this member or its defining class is final. */ 404 public boolean canBeStaticallyBound() { 405 return Modifier.isFinal(flags | clazz.getModifiers()); 406 } 407 /** Utility method to query the modifier flags of this member. */ 408 public boolean isVolatile() { 409 return Modifier.isVolatile(flags); 410 } 411 /** Utility method to query the modifier flags of this member. */ 412 public boolean isAbstract() { 413 return Modifier.isAbstract(flags); 414 } 415 /** Utility method to query the modifier flags of this member. */ 416 public boolean isNative() { 417 return Modifier.isNative(flags); 418 } 419 // let the rest (native, volatile, transient, etc.) be tested via Modifier.isFoo 420 421 // unofficial modifier flags, used by HotSpot: 422 static final int BRIDGE = 0x00000040; 423 static final int VARARGS = 0x00000080; 424 static final int SYNTHETIC = 0x00001000; 425 static final int ANNOTATION = 0x00002000; 426 static final int ENUM = 0x00004000; 427 428 /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */ 429 public boolean isBridge() { 430 return allFlagsSet(IS_METHOD | BRIDGE); 431 } 432 /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */ 433 public boolean isVarargs() { 434 return allFlagsSet(VARARGS) && isInvocable(); 435 } 436 /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */ 437 public boolean isSynthetic() { 438 return allFlagsSet(SYNTHETIC); 439 } 440 441 /** Query whether this member is a flat field */ 442 public boolean isFlat() { return (flags & MN_FLAT_FIELD) == MN_FLAT_FIELD; } 443 444 /** Query whether this member is a null-restricted field */ 445 public boolean isNullRestricted() { return (flags & MN_NULL_RESTRICTED) == MN_NULL_RESTRICTED; } 446 447 static final String CONSTRUCTOR_NAME = "<init>"; 448 449 // modifiers exported by the JVM: 450 static final int RECOGNIZED_MODIFIERS = 0xFFFF; 451 452 // private flags, not part of RECOGNIZED_MODIFIERS: 453 static final int 454 IS_METHOD = MN_IS_METHOD, // method (not constructor) 455 IS_CONSTRUCTOR = MN_IS_CONSTRUCTOR, // constructor 456 IS_FIELD = MN_IS_FIELD, // field 457 IS_TYPE = MN_IS_TYPE, // nested type 458 CALLER_SENSITIVE = MN_CALLER_SENSITIVE, // @CallerSensitive annotation detected 459 TRUSTED_FINAL = MN_TRUSTED_FINAL; // trusted final field 460 461 static final int ALL_ACCESS = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED; 462 static final int ALL_KINDS = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE; 463 static final int IS_INVOCABLE = IS_METHOD | IS_CONSTRUCTOR; 464 465 /** Utility method to query whether this member is a method or constructor. */ 466 public boolean isInvocable() { 467 return anyFlagSet(IS_INVOCABLE); 468 } 469 /** Query whether this member is a method. */ 470 public boolean isMethod() { 471 return allFlagsSet(IS_METHOD); 472 } 473 /** Query whether this member is a constructor. */ 474 public boolean isConstructor() { 475 return allFlagsSet(IS_CONSTRUCTOR); 476 } 477 /** Query whether this member is a field. */ 478 public boolean isField() { 479 return allFlagsSet(IS_FIELD); 480 } 481 /** Query whether this member is a type. */ 482 public boolean isType() { 483 return allFlagsSet(IS_TYPE); 484 } 485 /** Utility method to query whether this member is neither public, private, nor protected. */ 486 public boolean isPackage() { 487 return !anyFlagSet(ALL_ACCESS); 488 } 489 /** Query whether this member has a CallerSensitive annotation. */ 490 public boolean isCallerSensitive() { 491 return allFlagsSet(CALLER_SENSITIVE); 492 } 493 /** Query whether this member is a trusted final field. */ 494 public boolean isTrustedFinalField() { 495 return allFlagsSet(TRUSTED_FINAL | IS_FIELD); 496 } 497 498 /** 499 * Check if MemberName is a call to a method named {@code name} in class {@code declaredClass}. 500 */ 501 public boolean refersTo(Class<?> declc, String n) { 502 return clazz == declc && getName().equals(n); 503 } 504 505 /** Initialize a query. It is not resolved. */ 506 private void init(Class<?> defClass, String name, Object type, int flags) { 507 // defining class is allowed to be null (for a naked name/type pair) 508 //name.toString(); // null check 509 //type.equals(type); // null check 510 // fill in fields: 511 this.clazz = defClass; 512 this.name = name; 513 this.type = type; 514 this.flags = flags; 515 assert(anyFlagSet(ALL_KINDS) && this.resolution == null); // nobody should have touched this yet 516 //assert(referenceKindIsConsistent()); // do this after resolution 517 } 518 519 /** 520 * Calls down to the VM to fill in the fields. This method is 521 * synchronized to avoid racing calls. 522 */ 523 private void expandFromVM() { 524 if (type != null) { 525 return; 526 } 527 if (!isResolved()) { 528 return; 529 } 530 MethodHandleNatives.expand(this); 531 } 532 533 // Capturing information from the Core Reflection API: 534 private static int flagsMods(int flags, int mods, byte refKind) { 535 assert((flags & RECOGNIZED_MODIFIERS) == 0 536 && (mods & ~RECOGNIZED_MODIFIERS) == 0 537 && (refKind & ~MN_REFERENCE_KIND_MASK) == 0); 538 return flags | mods | (refKind << MN_REFERENCE_KIND_SHIFT); 539 } 540 /** Create a name for the given reflected method. The resulting name will be in a resolved state. */ 541 public MemberName(Method m) { 542 this(m, false); 543 } 544 @SuppressWarnings("LeakingThisInConstructor") 545 public MemberName(Method m, boolean wantSpecial) { 546 Objects.requireNonNull(m); 547 // fill in vmtarget, vmindex while we have m in hand: 548 MethodHandleNatives.init(this, m); 549 if (clazz == null) { // MHN.init failed 550 if (m.getDeclaringClass() == MethodHandle.class && 551 isMethodHandleInvokeName(m.getName())) { 552 // The JVM did not reify this signature-polymorphic instance. 553 // Need a special case here. 554 // See comments on MethodHandleNatives.linkMethod. 555 MethodType type = MethodType.methodType(m.getReturnType(), m.getParameterTypes()); 556 int flags = flagsMods(IS_METHOD, m.getModifiers(), REF_invokeVirtual); 557 init(MethodHandle.class, m.getName(), type, flags); 558 if (isMethodHandleInvoke()) 559 return; 560 } 561 if (m.getDeclaringClass() == VarHandle.class && 562 isVarHandleMethodInvokeName(m.getName())) { 563 // The JVM did not reify this signature-polymorphic instance. 564 // Need a special case here. 565 // See comments on MethodHandleNatives.linkMethod. 566 MethodType type = MethodType.methodType(m.getReturnType(), m.getParameterTypes()); 567 int flags = flagsMods(IS_METHOD, m.getModifiers(), REF_invokeVirtual); 568 init(VarHandle.class, m.getName(), type, flags); 569 if (isVarHandleMethodInvoke()) 570 return; 571 } 572 throw new LinkageError(m.toString()); 573 } 574 assert(isResolved()); 575 this.name = m.getName(); 576 if (this.type == null) 577 this.type = new Object[] { m.getReturnType(), m.getParameterTypes() }; 578 if (wantSpecial) { 579 if (isAbstract()) 580 throw new AbstractMethodError(this.toString()); 581 if (getReferenceKind() == REF_invokeVirtual) 582 changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual); 583 else if (getReferenceKind() == REF_invokeInterface) 584 // invokeSpecial on a default method 585 changeReferenceKind(REF_invokeSpecial, REF_invokeInterface); 586 } 587 } 588 public MemberName asSpecial() { 589 switch (getReferenceKind()) { 590 case REF_invokeSpecial: return this; 591 case REF_invokeVirtual: return clone().changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual); 592 case REF_invokeInterface: return clone().changeReferenceKind(REF_invokeSpecial, REF_invokeInterface); 593 case REF_newInvokeSpecial: return clone().changeReferenceKind(REF_invokeSpecial, REF_newInvokeSpecial); 594 } 595 throw new IllegalArgumentException(this.toString()); 596 } 597 /** If this MN is not REF_newInvokeSpecial, return a clone with that ref. kind. 598 * In that case it must already be REF_invokeSpecial. 599 */ 600 public MemberName asConstructor() { 601 switch (getReferenceKind()) { 602 case REF_invokeSpecial: return clone().changeReferenceKind(REF_newInvokeSpecial, REF_invokeSpecial); 603 case REF_newInvokeSpecial: return this; 604 } 605 throw new IllegalArgumentException(this.toString()); 606 } 607 /** If this MN is a REF_invokeSpecial, return a clone with the "normal" kind 608 * REF_invokeVirtual; also switch either to REF_invokeInterface if clazz.isInterface. 609 * The end result is to get a fully virtualized version of the MN. 610 * (Note that resolving in the JVM will sometimes devirtualize, changing 611 * REF_invokeVirtual of a final to REF_invokeSpecial, and REF_invokeInterface 612 * in some corner cases to either of the previous two; this transform 613 * undoes that change under the assumption that it occurred.) 614 */ 615 public MemberName asNormalOriginal() { 616 byte refKind = getReferenceKind(); 617 byte newRefKind = switch (refKind) { 618 case REF_invokeInterface, 619 REF_invokeVirtual, 620 REF_invokeSpecial -> clazz.isInterface() ? REF_invokeInterface : REF_invokeVirtual; 621 default -> refKind; 622 }; 623 if (newRefKind == refKind) 624 return this; 625 MemberName result = clone().changeReferenceKind(newRefKind, refKind); 626 assert(this.referenceKindIsConsistentWith(result.getReferenceKind())); 627 return result; 628 } 629 /** Create a name for the given reflected constructor. The resulting name will be in a resolved state. */ 630 @SuppressWarnings("LeakingThisInConstructor") 631 public MemberName(Constructor<?> ctor) { 632 Objects.requireNonNull(ctor); 633 // fill in vmtarget, vmindex while we have ctor in hand: 634 MethodHandleNatives.init(this, ctor); 635 assert(isResolved() && this.clazz != null); 636 this.name = CONSTRUCTOR_NAME; 637 if (this.type == null) 638 this.type = new Object[] { void.class, ctor.getParameterTypes() }; 639 } 640 /** Create a name for the given reflected field. The resulting name will be in a resolved state. 641 */ 642 public MemberName(Field fld) { 643 this(fld, false); 644 } 645 static { 646 // the following MemberName constructor relies on these ranges matching up 647 assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField)); 648 } 649 @SuppressWarnings("LeakingThisInConstructor") 650 public MemberName(Field fld, boolean makeSetter) { 651 Objects.requireNonNull(fld); 652 // fill in vmtarget, vmindex while we have fld in hand: 653 MethodHandleNatives.init(this, fld); 654 assert(isResolved() && this.clazz != null); 655 this.name = fld.getName(); 656 this.type = fld.getType(); 657 byte refKind = this.getReferenceKind(); 658 assert(refKind == (isStatic() ? REF_getStatic : REF_getField)); 659 if (makeSetter) { 660 changeReferenceKind((byte)(refKind + (REF_putStatic - REF_getStatic)), refKind); 661 } 662 } 663 public boolean isGetter() { 664 return MethodHandleNatives.refKindIsGetter(getReferenceKind()); 665 } 666 public boolean isSetter() { 667 return MethodHandleNatives.refKindIsSetter(getReferenceKind()); 668 } 669 670 /** Create a name for the given class. The resulting name will be in a resolved state. */ 671 public MemberName(Class<?> type) { 672 init(type.getDeclaringClass(), type.getSimpleName(), type, 673 flagsMods(IS_TYPE, type.getModifiers(), REF_NONE)); 674 initResolved(true); 675 } 676 677 /** 678 * Create a name for a signature-polymorphic invoker. 679 * This is a placeholder for a signature-polymorphic instance 680 * (of MH.invokeExact, etc.) that the JVM does not reify. 681 * See comments on {@link MethodHandleNatives#linkMethod}. 682 */ 683 static MemberName makeMethodHandleInvoke(String name, MethodType type) { 684 return makeMethodHandleInvoke(name, type, MH_INVOKE_MODS | SYNTHETIC); 685 } 686 static MemberName makeMethodHandleInvoke(String name, MethodType type, int mods) { 687 MemberName mem = new MemberName(MethodHandle.class, name, type, REF_invokeVirtual); 688 mem.flags |= mods; // it's not resolved, but add these modifiers anyway 689 assert(mem.isMethodHandleInvoke()) : mem; 690 return mem; 691 } 692 693 static MemberName makeVarHandleMethodInvoke(String name, MethodType type) { 694 return makeVarHandleMethodInvoke(name, type, MH_INVOKE_MODS | SYNTHETIC); 695 } 696 static MemberName makeVarHandleMethodInvoke(String name, MethodType type, int mods) { 697 MemberName mem = new MemberName(VarHandle.class, name, type, REF_invokeVirtual); 698 mem.flags |= mods; // it's not resolved, but add these modifiers anyway 699 assert(mem.isVarHandleMethodInvoke()) : mem; 700 return mem; 701 } 702 703 // bare-bones constructor; the JVM will fill it in 704 MemberName() { } 705 706 // locally useful cloner 707 @Override protected MemberName clone() { 708 try { 709 return (MemberName) super.clone(); 710 } catch (CloneNotSupportedException ex) { 711 throw newInternalError(ex); 712 } 713 } 714 715 /** Get the definition of this member name. 716 * This may be in a super-class of the declaring class of this member. 717 */ 718 public MemberName getDefinition() { 719 if (!isResolved()) throw new IllegalStateException("must be resolved: "+this); 720 if (isType()) return this; 721 MemberName res = this.clone(); 722 res.clazz = null; 723 res.type = null; 724 res.name = null; 725 res.resolution = res; 726 res.expandFromVM(); 727 assert(res.getName().equals(this.getName())); 728 return res; 729 } 730 731 @Override 732 @SuppressWarnings({"deprecation", "removal"}) 733 public int hashCode() { 734 // Avoid autoboxing getReferenceKind(), since this is used early and will force 735 // early initialization of Byte$ByteCache 736 return Objects.hash(clazz, new Byte(getReferenceKind()), name, getType()); 737 } 738 739 @Override 740 public boolean equals(Object that) { 741 return that instanceof MemberName mn && this.equals(mn); 742 } 743 744 /** Decide if two member names have exactly the same symbolic content. 745 * Does not take into account any actual class members, so even if 746 * two member names resolve to the same actual member, they may 747 * be distinct references. 748 */ 749 public boolean equals(MemberName that) { 750 if (this == that) return true; 751 if (that == null) return false; 752 return this.clazz == that.clazz 753 && this.getReferenceKind() == that.getReferenceKind() 754 && Objects.equals(this.name, that.name) 755 && Objects.equals(this.getType(), that.getType()); 756 } 757 758 // Construction from symbolic parts, for queries: 759 /** Create a field or type name from the given components: 760 * Declaring class, name, type, reference kind. 761 * The declaring class may be supplied as null if this is to be a bare name and type. 762 * The resulting name will in an unresolved state. 763 */ 764 public MemberName(Class<?> defClass, String name, Class<?> type, byte refKind) { 765 init(defClass, name, type, flagsMods(IS_FIELD, 0, refKind)); 766 initResolved(false); 767 } 768 /** Create a method or constructor name from the given components: 769 * Declaring class, name, type, reference kind. 770 * It will be a constructor if and only if the name is {@code "<init>"}. 771 * The declaring class may be supplied as null if this is to be a bare name and type. 772 * The last argument is optional, a boolean which requests REF_invokeSpecial. 773 * The resulting name will in an unresolved state. 774 */ 775 public MemberName(Class<?> defClass, String name, MethodType type, byte refKind) { 776 int initFlags = CONSTRUCTOR_NAME.equals(name) ? IS_CONSTRUCTOR : IS_METHOD; 777 init(defClass, name, type, flagsMods(initFlags, 0, refKind)); 778 initResolved(false); 779 } 780 /** Create a method, constructor, or field name from the given components: 781 * Reference kind, declaring class, name, type. 782 */ 783 public MemberName(byte refKind, Class<?> defClass, String name, Object type) { 784 int kindFlags; 785 if (MethodHandleNatives.refKindIsField(refKind)) { 786 kindFlags = IS_FIELD; 787 if (!(type instanceof Class)) 788 throw newIllegalArgumentException("not a field type"); 789 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 790 kindFlags = IS_METHOD; 791 if (!(type instanceof MethodType)) 792 throw newIllegalArgumentException("not a method type"); 793 } else if (refKind == REF_newInvokeSpecial) { 794 kindFlags = IS_CONSTRUCTOR; 795 if (!(type instanceof MethodType) || 796 !CONSTRUCTOR_NAME.equals(name)) 797 throw newIllegalArgumentException("not a constructor type or name"); 798 } else { 799 throw newIllegalArgumentException("bad reference kind "+refKind); 800 } 801 init(defClass, name, type, flagsMods(kindFlags, 0, refKind)); 802 initResolved(false); 803 } 804 805 /** Query whether this member name is resolved. 806 * A resolved member name is one for which the JVM has found 807 * a method, constructor, field, or type binding corresponding exactly to the name. 808 * (Document?) 809 */ 810 public boolean isResolved() { 811 return resolution == null; 812 } 813 814 void initResolved(boolean isResolved) { 815 assert(this.resolution == null); // not initialized yet! 816 if (!isResolved) 817 this.resolution = this; 818 assert(isResolved() == isResolved); 819 } 820 821 void ensureTypeVisible(Class<?> refc) { 822 if (isInvocable()) { 823 MethodType type; 824 if (this.type instanceof MethodType mt) 825 type = mt; 826 else 827 this.type = type = getMethodType(); 828 if (type.erase() == type) return; 829 if (VerifyAccess.ensureTypeVisible(type, refc)) return; 830 throw new LinkageError("bad method type alias: "+type+" not visible from "+refc); 831 } else { 832 Class<?> type; 833 if (this.type instanceof Class<?> cl) 834 type = cl; 835 else 836 this.type = type = getFieldType(); 837 if (VerifyAccess.ensureTypeVisible(type, refc)) return; 838 throw new LinkageError("bad field type alias: "+type+" not visible from "+refc); 839 } 840 } 841 842 843 /** Produce a string form of this member name. 844 * For types, it is simply the type's own string (as reported by {@code toString}). 845 * For fields, it is {@code "DeclaringClass.name/type"}. 846 * For methods and constructors, it is {@code "DeclaringClass.name(ptype...)rtype"}. 847 * If the declaring class is null, the prefix {@code "DeclaringClass."} is omitted. 848 * If the member is unresolved, a prefix {@code "*."} is prepended. 849 */ 850 @SuppressWarnings("LocalVariableHidesMemberVariable") 851 @Override 852 public String toString() { 853 if (isType()) 854 return type.toString(); // class java.lang.String 855 // else it is a field, method, or constructor 856 StringBuilder buf = new StringBuilder(); 857 if (getDeclaringClass() != null) { 858 buf.append(getName(clazz)); 859 buf.append('.'); 860 } 861 String name = this.name; // avoid expanding from VM 862 buf.append(name == null ? "*" : name); 863 Object type = this.type; // avoid expanding from VM 864 if (!isInvocable()) { 865 buf.append('/'); 866 buf.append(type == null ? "*" : getName(type)); 867 } else { 868 buf.append(type == null ? "(*)*" : getName(type)); 869 } 870 byte refKind = getReferenceKind(); 871 if (refKind != REF_NONE) { 872 buf.append('/'); 873 buf.append(MethodHandleNatives.refKindName(refKind)); 874 } 875 //buf.append("#").append(System.identityHashCode(this)); 876 return buf.toString(); 877 } 878 private static String getName(Object obj) { 879 if (obj instanceof Class<?> cl) 880 return cl.getName(); 881 return String.valueOf(obj); 882 } 883 884 public IllegalAccessException makeAccessException(String message, Object from) { 885 message = message + ": " + this; 886 if (from != null) { 887 if (from == MethodHandles.publicLookup()) { 888 message += ", from public Lookup"; 889 } else { 890 Module m; 891 Class<?> plc; 892 if (from instanceof MethodHandles.Lookup lookup) { 893 from = lookup.lookupClass(); 894 m = lookup.lookupClass().getModule(); 895 plc = lookup.previousLookupClass(); 896 } else { 897 m = ((Class<?>)from).getModule(); 898 plc = null; 899 } 900 message += ", from " + from + " (" + m + ")"; 901 if (plc != null) { 902 message += ", previous lookup " + 903 plc.getName() + " (" + plc.getModule() + ")"; 904 } 905 } 906 } 907 return new IllegalAccessException(message); 908 } 909 private String message() { 910 if (isResolved()) 911 return "no access"; 912 else if (isConstructor()) 913 return "no such constructor"; 914 else if (isMethod()) 915 return "no such method"; 916 else 917 return "no such field"; 918 } 919 public ReflectiveOperationException makeAccessException() { 920 String message = message() + ": " + this; 921 ReflectiveOperationException ex; 922 if (isResolved() || !(resolution instanceof NoSuchMethodError || 923 resolution instanceof NoSuchFieldError)) 924 ex = new IllegalAccessException(message); 925 else if (isConstructor()) 926 ex = new NoSuchMethodException(message); 927 else if (isMethod()) 928 ex = new NoSuchMethodException(message); 929 else 930 ex = new NoSuchFieldException(message); 931 if (resolution instanceof Throwable res) 932 ex.initCause(res); 933 return ex; 934 } 935 936 /** Actually making a query requires an access check. */ 937 /*non-public*/ 938 static Factory getFactory() { 939 return Factory.INSTANCE; 940 } 941 /** A factory type for resolving member names with the help of the VM. 942 * TBD: Define access-safe public constructors for this factory. 943 */ 944 /*non-public*/ 945 static class Factory { 946 private Factory() { } // singleton pattern 947 static final Factory INSTANCE = new Factory(); 948 949 /** Produce a resolved version of the given member. 950 * Super types are searched (for inherited members) if {@code searchSupers} is true. 951 * Access checking is performed on behalf of the given {@code lookupClass}. 952 * If lookup fails or access is not permitted, null is returned. 953 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in. 954 */ 955 private MemberName resolve(byte refKind, MemberName ref, Class<?> lookupClass, int allowedModes, 956 boolean speculativeResolve) { 957 MemberName m = ref.clone(); // JVM will side-effect the ref 958 assert(refKind == m.getReferenceKind()); 959 try { 960 // There are 4 entities in play here: 961 // * LC: lookupClass 962 // * REFC: symbolic reference class (MN.clazz before resolution); 963 // * DEFC: resolved method holder (MN.clazz after resolution); 964 // * PTYPES: parameter types (MN.type) 965 // 966 // What we care about when resolving a MemberName is consistency between DEFC and PTYPES. 967 // We do type alias (TA) checks on DEFC to ensure that. DEFC is not known until the JVM 968 // finishes the resolution, so do TA checks right after MHN.resolve() is over. 969 // 970 // All parameters passed by a caller are checked against MH type (PTYPES) on every invocation, 971 // so it is safe to call a MH from any context. 972 // 973 // REFC view on PTYPES doesn't matter, since it is used only as a starting point for resolution and doesn't 974 // participate in method selection. 975 m = MethodHandleNatives.resolve(m, lookupClass, allowedModes, speculativeResolve); 976 if (m == null && speculativeResolve) { 977 return null; 978 } 979 m.ensureTypeVisible(m.getDeclaringClass()); 980 m.resolution = null; 981 } catch (ClassNotFoundException | LinkageError ex) { 982 // JVM reports that the "bytecode behavior" would get an error 983 assert(!m.isResolved()); 984 m.resolution = ex; 985 return m; 986 } 987 assert(m.referenceKindIsConsistent()); 988 m.initResolved(true); 989 assert(m.vminfoIsConsistent()); 990 return m; 991 } 992 /** Produce a resolved version of the given member. 993 * Super types are searched (for inherited members) if {@code searchSupers} is true. 994 * Access checking is performed on behalf of the given {@code lookupClass}. 995 * If lookup fails or access is not permitted, a {@linkplain ReflectiveOperationException} is thrown. 996 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in. 997 */ 998 public <NoSuchMemberException extends ReflectiveOperationException> 999 MemberName resolveOrFail(byte refKind, MemberName m, 1000 Class<?> lookupClass, int allowedModes, 1001 Class<NoSuchMemberException> nsmClass) 1002 throws IllegalAccessException, NoSuchMemberException { 1003 assert lookupClass != null || allowedModes == LM_TRUSTED; 1004 MemberName result = resolve(refKind, m, lookupClass, allowedModes, false); 1005 if (result.isResolved()) 1006 return result; 1007 ReflectiveOperationException ex = result.makeAccessException(); 1008 if (ex instanceof IllegalAccessException iae) throw iae; 1009 throw nsmClass.cast(ex); 1010 } 1011 /** Produce a resolved version of the given member. 1012 * Super types are searched (for inherited members) if {@code searchSupers} is true. 1013 * Access checking is performed on behalf of the given {@code lookupClass}. 1014 * If lookup fails or access is not permitted, return null. 1015 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in. 1016 */ 1017 public MemberName resolveOrNull(byte refKind, MemberName m, Class<?> lookupClass, int allowedModes) { 1018 assert lookupClass != null || allowedModes == LM_TRUSTED; 1019 MemberName result = resolve(refKind, m, lookupClass, allowedModes, true); 1020 if (result != null && result.isResolved()) 1021 return result; 1022 return null; 1023 } 1024 } 1025 }