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