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