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