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