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