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