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 can be assigned to null. */ 477 public boolean canBeNull() { 478 if (isField()) { 479 Class<?> type = getFieldType(); 480 return type == type.asBoxType(); 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 this.type = new Object[] { void.class, ctor.getParameterTypes() }; 690 } 691 /** Create a name for the given reflected field. The resulting name will be in a resolved state. 692 */ 693 public MemberName(Field fld) { 694 this(fld, false); 695 } 696 @SuppressWarnings("LeakingThisInConstructor") 697 public MemberName(Field fld, boolean makeSetter) { 698 Objects.requireNonNull(fld); 699 // fill in vmtarget, vmindex while we have fld in hand: 700 MethodHandleNatives.init(this, fld); 701 assert(isResolved() && this.clazz != null); 702 this.name = fld.getName(); 703 this.type = fld.getType(); 704 assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField)); 705 byte refKind = this.getReferenceKind(); 706 assert(refKind == (isStatic() ? REF_getStatic : REF_getField)); 707 if (makeSetter) { 708 changeReferenceKind((byte)(refKind + (REF_putStatic - REF_getStatic)), refKind); 709 } 710 } 711 public boolean isGetter() { 712 return MethodHandleNatives.refKindIsGetter(getReferenceKind()); 713 } 714 public boolean isSetter() { 715 return MethodHandleNatives.refKindIsSetter(getReferenceKind()); 716 } 717 public MemberName asSetter() { 718 byte refKind = getReferenceKind(); 719 assert(MethodHandleNatives.refKindIsGetter(refKind)); 720 assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField)); 721 byte setterRefKind = (byte)(refKind + (REF_putField - REF_getField)); 722 return clone().changeReferenceKind(setterRefKind, refKind); 723 } 724 /** Create a name for the given class. The resulting name will be in a resolved state. */ 725 public MemberName(Class<?> type) { 726 init(type.getDeclaringClass(), type.getSimpleName(), type, 727 flagsMods(IS_TYPE, type.getModifiers(), REF_NONE)); 728 initResolved(true); 729 } 730 731 /** 732 * Create a name for a signature-polymorphic invoker. 733 * This is a placeholder for a signature-polymorphic instance 734 * (of MH.invokeExact, etc.) that the JVM does not reify. 735 * See comments on {@link MethodHandleNatives#linkMethod}. 736 */ 737 static MemberName makeMethodHandleInvoke(String name, MethodType type) { 738 return makeMethodHandleInvoke(name, type, MH_INVOKE_MODS | SYNTHETIC); 739 } 740 static MemberName makeMethodHandleInvoke(String name, MethodType type, int mods) { 741 MemberName mem = new MemberName(MethodHandle.class, name, type, REF_invokeVirtual); 742 mem.flags |= mods; // it's not resolved, but add these modifiers anyway 743 assert(mem.isMethodHandleInvoke()) : mem; 744 return mem; 745 } 746 747 static MemberName makeVarHandleMethodInvoke(String name, MethodType type) { 748 return makeVarHandleMethodInvoke(name, type, MH_INVOKE_MODS | SYNTHETIC); 749 } 750 static MemberName makeVarHandleMethodInvoke(String name, MethodType type, int mods) { 751 MemberName mem = new MemberName(VarHandle.class, name, type, REF_invokeVirtual); 752 mem.flags |= mods; // it's not resolved, but add these modifiers anyway 753 assert(mem.isVarHandleMethodInvoke()) : mem; 754 return mem; 755 } 756 757 // bare-bones constructor; the JVM will fill it in 758 MemberName() { } 759 760 // locally useful cloner 761 @Override protected MemberName clone() { 762 try { 763 return (MemberName) super.clone(); 764 } catch (CloneNotSupportedException ex) { 765 throw newInternalError(ex); 766 } 767 } 768 769 /** Get the definition of this member name. 770 * This may be in a super-class of the declaring class of this member. 771 */ 772 public MemberName getDefinition() { 773 if (!isResolved()) throw new IllegalStateException("must be resolved: "+this); 774 if (isType()) return this; 775 MemberName res = this.clone(); 776 res.clazz = null; 777 res.type = null; 778 res.name = null; 779 res.resolution = res; 780 res.expandFromVM(); 781 assert(res.getName().equals(this.getName())); 782 return res; 783 } 784 785 @Override 786 @SuppressWarnings("deprecation") 787 public int hashCode() { 788 // Avoid autoboxing getReferenceKind(), since this is used early and will force 789 // early initialization of Byte$ByteCache 790 return Objects.hash(clazz, new Byte(getReferenceKind()), name, getType()); 791 } 792 793 @Override 794 public boolean equals(Object that) { 795 return (that instanceof MemberName && this.equals((MemberName)that)); 796 } 797 798 /** Decide if two member names have exactly the same symbolic content. 799 * Does not take into account any actual class members, so even if 800 * two member names resolve to the same actual member, they may 801 * be distinct references. 802 */ 803 public boolean equals(MemberName that) { 804 if (this == that) return true; 805 if (that == null) return false; 806 return this.clazz == that.clazz 807 && this.getReferenceKind() == that.getReferenceKind() 808 && Objects.equals(this.name, that.name) 809 && Objects.equals(this.getType(), that.getType()); 810 } 811 812 // Construction from symbolic parts, for queries: 813 /** Create a field or type name from the given components: 814 * Declaring class, name, type, reference kind. 815 * The declaring class may be supplied as null if this is to be a bare name and type. 816 * The resulting name will in an unresolved state. 817 */ 818 public MemberName(Class<?> defClass, String name, Class<?> type, byte refKind) { 819 init(defClass, name, type, flagsMods(IS_FIELD, 0, refKind)); 820 initResolved(false); 821 } 822 /** Create a method or constructor name from the given components: 823 * Declaring class, name, type, reference kind. 824 * It will be a constructor if and only if the name is {@code "<init>"}. 825 * The declaring class may be supplied as null if this is to be a bare name and type. 826 * The last argument is optional, a boolean which requests REF_invokeSpecial. 827 * The resulting name will in an unresolved state. 828 */ 829 public MemberName(Class<?> defClass, String name, MethodType type, byte refKind) { 830 int initFlags = (name != null && name.equals(CONSTRUCTOR_NAME) ? IS_CONSTRUCTOR : IS_METHOD); 831 init(defClass, name, type, flagsMods(initFlags, 0, refKind)); 832 initResolved(false); 833 } 834 /** Create a method, constructor, or field name from the given components: 835 * Reference kind, declaring class, name, type. 836 */ 837 public MemberName(byte refKind, Class<?> defClass, String name, Object type) { 838 int kindFlags; 839 if (MethodHandleNatives.refKindIsField(refKind)) { 840 kindFlags = IS_FIELD; 841 if (!(type instanceof Class)) 842 throw newIllegalArgumentException("not a field type"); 843 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 844 kindFlags = IS_METHOD; 845 if (!(type instanceof MethodType)) 846 throw newIllegalArgumentException("not a method type"); 847 } else if (refKind == REF_newInvokeSpecial) { 848 kindFlags = IS_CONSTRUCTOR; 849 if (!(type instanceof MethodType) || 850 !CONSTRUCTOR_NAME.equals(name)) 851 throw newIllegalArgumentException("not a constructor type or name"); 852 } else { 853 throw newIllegalArgumentException("bad reference kind "+refKind); 854 } 855 init(defClass, name, type, flagsMods(kindFlags, 0, refKind)); 856 initResolved(false); 857 } 858 /** Query whether this member name is resolved to a non-static, non-final method. 859 */ 860 public boolean hasReceiverTypeDispatch() { 861 return MethodHandleNatives.refKindDoesDispatch(getReferenceKind()); 862 } 863 864 /** Query whether this member name is resolved. 865 * A resolved member name is one for which the JVM has found 866 * a method, constructor, field, or type binding corresponding exactly to the name. 867 * (Document?) 868 */ 869 public boolean isResolved() { 870 return resolution == null; 871 } 872 873 void initResolved(boolean isResolved) { 874 assert(this.resolution == null); // not initialized yet! 875 if (!isResolved) 876 this.resolution = this; 877 assert(isResolved() == isResolved); 878 } 879 880 void checkForTypeAlias(Class<?> refc) { 881 if (isInvocable()) { 882 MethodType type; 883 if (this.type instanceof MethodType) 884 type = (MethodType) this.type; 885 else 886 this.type = type = getMethodType(); 887 if (type.erase() == type) return; 888 if (VerifyAccess.isTypeVisible(type, refc)) return; 889 throw new LinkageError("bad method type alias: "+type+" not visible from "+refc); 890 } else { 891 Class<?> type; 892 if (this.type instanceof Class<?>) 893 type = (Class<?>) this.type; 894 else 895 this.type = type = getFieldType(); 896 if (VerifyAccess.isTypeVisible(type, refc)) return; 897 throw new LinkageError("bad field type alias: "+type+" not visible from "+refc); 898 } 899 } 900 901 902 /** Produce a string form of this member name. 903 * For types, it is simply the type's own string (as reported by {@code toString}). 904 * For fields, it is {@code "DeclaringClass.name/type"}. 905 * For methods and constructors, it is {@code "DeclaringClass.name(ptype...)rtype"}. 906 * If the declaring class is null, the prefix {@code "DeclaringClass."} is omitted. 907 * If the member is unresolved, a prefix {@code "*."} is prepended. 908 */ 909 @SuppressWarnings("LocalVariableHidesMemberVariable") 910 @Override 911 public String toString() { 912 if (isType()) 913 return type.toString(); // class java.lang.String 914 // else it is a field, method, or constructor 915 StringBuilder buf = new StringBuilder(); 916 if (getDeclaringClass() != null) { 917 buf.append(getName(clazz)); 918 buf.append('.'); 919 } 920 String name = this.name; // avoid expanding from VM 921 buf.append(name == null ? "*" : name); 922 Object type = this.type; // avoid expanding from VM 923 if (!isInvocable()) { 924 buf.append('/'); 925 buf.append(type == null ? "*" : getName(type)); 926 } else { 927 buf.append(type == null ? "(*)*" : getName(type)); 928 } 929 byte refKind = getReferenceKind(); 930 if (refKind != REF_NONE) { 931 buf.append('/'); 932 buf.append(MethodHandleNatives.refKindName(refKind)); 933 } 934 //buf.append("#").append(System.identityHashCode(this)); 935 return buf.toString(); 936 } 937 private static String getName(Object obj) { 938 if (obj instanceof Class<?>) 939 return ((Class<?>)obj).getName(); 940 return String.valueOf(obj); 941 } 942 943 public IllegalAccessException makeAccessException(String message, Object from) { 944 message = message + ": "+ toString(); 945 if (from != null) { 946 if (from == MethodHandles.publicLookup()) { 947 message += ", from public Lookup"; 948 } else { 949 Module m; 950 if (from instanceof MethodHandles.Lookup) { 951 MethodHandles.Lookup lookup = (MethodHandles.Lookup)from; 952 m = lookup.lookupClass().getModule(); 953 } else { 954 m = from.getClass().getModule(); 955 } 956 message += ", from " + from + " (" + m + ")"; 957 } 958 } 959 return new IllegalAccessException(message); 960 } 961 private String message() { 962 if (isResolved()) 963 return "no access"; 964 else if (isConstructor()) 965 return "no such constructor"; 966 else if (isMethod()) 967 return "no such method"; 968 else 969 return "no such field"; 970 } 971 public ReflectiveOperationException makeAccessException() { 972 String message = message() + ": "+ toString(); 973 ReflectiveOperationException ex; 974 if (isResolved() || !(resolution instanceof NoSuchMethodError || 975 resolution instanceof NoSuchFieldError)) 976 ex = new IllegalAccessException(message); 977 else if (isConstructor()) 978 ex = new NoSuchMethodException(message); 979 else if (isMethod()) 980 ex = new NoSuchMethodException(message); 981 else 982 ex = new NoSuchFieldException(message); 983 if (resolution instanceof Throwable) 984 ex.initCause((Throwable) resolution); 985 return ex; 986 } 987 988 /** Actually making a query requires an access check. */ 989 /*non-public*/ static Factory getFactory() { 990 return Factory.INSTANCE; 991 } 992 /** A factory type for resolving member names with the help of the VM. 993 * TBD: Define access-safe public constructors for this factory. 994 */ 995 /*non-public*/ static class Factory { 996 private Factory() { } // singleton pattern 997 static Factory INSTANCE = new Factory(); 998 999 private static int ALLOWED_FLAGS = ALL_KINDS; 1000 1001 /// Queries 1002 List<MemberName> getMembers(Class<?> defc, 1003 String matchName, Object matchType, 1004 int matchFlags, Class<?> lookupClass) { 1005 matchFlags &= ALLOWED_FLAGS; 1006 String matchSig = null; 1007 if (matchType != null) { 1008 matchSig = BytecodeDescriptor.unparse(matchType); 1009 if (matchSig.startsWith("(")) 1010 matchFlags &= ~(ALL_KINDS & ~IS_INVOCABLE); 1011 else 1012 matchFlags &= ~(ALL_KINDS & ~IS_FIELD); 1013 } 1014 final int BUF_MAX = 0x2000; 1015 int len1 = matchName == null ? 10 : matchType == null ? 4 : 1; 1016 MemberName[] buf = newMemberBuffer(len1); 1017 int totalCount = 0; 1018 ArrayList<MemberName[]> bufs = null; 1019 int bufCount = 0; 1020 for (;;) { 1021 bufCount = MethodHandleNatives.getMembers(defc, 1022 matchName, matchSig, matchFlags, 1023 lookupClass, 1024 totalCount, buf); 1025 if (bufCount <= buf.length) { 1026 if (bufCount < 0) bufCount = 0; 1027 totalCount += bufCount; 1028 break; 1029 } 1030 // JVM returned to us with an intentional overflow! 1031 totalCount += buf.length; 1032 int excess = bufCount - buf.length; 1033 if (bufs == null) bufs = new ArrayList<>(1); 1034 bufs.add(buf); 1035 int len2 = buf.length; 1036 len2 = Math.max(len2, excess); 1037 len2 = Math.max(len2, totalCount / 4); 1038 buf = newMemberBuffer(Math.min(BUF_MAX, len2)); 1039 } 1040 ArrayList<MemberName> result = new ArrayList<>(totalCount); 1041 if (bufs != null) { 1042 for (MemberName[] buf0 : bufs) { 1043 Collections.addAll(result, buf0); 1044 } 1045 } 1046 for (int i = 0; i < bufCount; i++) { 1047 result.add(buf[i]); 1048 } 1049 // Signature matching is not the same as type matching, since 1050 // one signature might correspond to several types. 1051 // So if matchType is a Class or MethodType, refilter the results. 1052 if (matchType != null && matchType != matchSig) { 1053 for (Iterator<MemberName> it = result.iterator(); it.hasNext();) { 1054 MemberName m = it.next(); 1055 if (!matchType.equals(m.getType())) 1056 it.remove(); 1057 } 1058 } 1059 return result; 1060 } 1061 /** Produce a resolved version of the given member. 1062 * Super types are searched (for inherited members) if {@code searchSupers} is true. 1063 * Access checking is performed on behalf of the given {@code lookupClass}. 1064 * If lookup fails or access is not permitted, null is returned. 1065 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in. 1066 */ 1067 private MemberName resolve(byte refKind, MemberName ref, Class<?> lookupClass, 1068 boolean speculativeResolve) { 1069 MemberName m = ref.clone(); // JVM will side-effect the ref 1070 assert(refKind == m.getReferenceKind()); 1071 try { 1072 // There are 4 entities in play here: 1073 // * LC: lookupClass 1074 // * REFC: symbolic reference class (MN.clazz before resolution); 1075 // * DEFC: resolved method holder (MN.clazz after resolution); 1076 // * PTYPES: parameter types (MN.type) 1077 // 1078 // What we care about when resolving a MemberName is consistency between DEFC and PTYPES. 1079 // We do type alias (TA) checks on DEFC to ensure that. DEFC is not known until the JVM 1080 // finishes the resolution, so do TA checks right after MHN.resolve() is over. 1081 // 1082 // All parameters passed by a caller are checked against MH type (PTYPES) on every invocation, 1083 // so it is safe to call a MH from any context. 1084 // 1085 // REFC view on PTYPES doesn't matter, since it is used only as a starting point for resolution and doesn't 1086 // participate in method selection. 1087 m = MethodHandleNatives.resolve(m, lookupClass, speculativeResolve); 1088 if (m == null && speculativeResolve) { 1089 return null; 1090 } 1091 m.checkForTypeAlias(m.getDeclaringClass()); 1092 m.resolution = null; 1093 } catch (ClassNotFoundException | LinkageError ex) { 1094 // JVM reports that the "bytecode behavior" would get an error 1095 assert(!m.isResolved()); 1096 m.resolution = ex; 1097 return m; 1098 } 1099 assert(m.referenceKindIsConsistent()); 1100 m.initResolved(true); 1101 assert(m.vminfoIsConsistent()); 1102 return m; 1103 } 1104 /** Produce a resolved version of the given member. 1105 * Super types are searched (for inherited members) if {@code searchSupers} is true. 1106 * Access checking is performed on behalf of the given {@code lookupClass}. 1107 * If lookup fails or access is not permitted, a {@linkplain ReflectiveOperationException} is thrown. 1108 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in. 1109 */ 1110 public 1111 <NoSuchMemberException extends ReflectiveOperationException> 1112 MemberName resolveOrFail(byte refKind, MemberName m, Class<?> lookupClass, 1113 Class<NoSuchMemberException> nsmClass) 1114 throws IllegalAccessException, NoSuchMemberException { 1115 MemberName result = resolve(refKind, m, lookupClass, false); 1116 if (result.isResolved()) 1117 return result; 1118 ReflectiveOperationException ex = result.makeAccessException(); 1119 if (ex instanceof IllegalAccessException) throw (IllegalAccessException) ex; 1120 throw nsmClass.cast(ex); 1121 } 1122 /** Produce a resolved version of the given member. 1123 * Super types are searched (for inherited members) if {@code searchSupers} is true. 1124 * Access checking is performed on behalf of the given {@code lookupClass}. 1125 * If lookup fails or access is not permitted, return null. 1126 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in. 1127 */ 1128 public 1129 MemberName resolveOrNull(byte refKind, MemberName m, Class<?> lookupClass) { 1130 MemberName result = resolve(refKind, m, lookupClass, true); 1131 if (result != null && result.isResolved()) 1132 return result; 1133 return null; 1134 } 1135 /** Return a list of all methods defined by the given class. 1136 * Super types are searched (for inherited members) if {@code searchSupers} is true. 1137 * Access checking is performed on behalf of the given {@code lookupClass}. 1138 * Inaccessible members are not added to the last. 1139 */ 1140 public List<MemberName> getMethods(Class<?> defc, boolean searchSupers, 1141 Class<?> lookupClass) { 1142 return getMethods(defc, searchSupers, null, null, lookupClass); 1143 } 1144 /** Return a list of matching methods defined by the given class. 1145 * Super types are searched (for inherited members) if {@code searchSupers} is true. 1146 * Returned methods will match the name (if not null) and the type (if not null). 1147 * Access checking is performed on behalf of the given {@code lookupClass}. 1148 * Inaccessible members are not added to the last. 1149 */ 1150 public List<MemberName> getMethods(Class<?> defc, boolean searchSupers, 1151 String name, MethodType type, Class<?> lookupClass) { 1152 int matchFlags = IS_METHOD | (searchSupers ? SEARCH_ALL_SUPERS : 0); 1153 return getMembers(defc, name, type, matchFlags, lookupClass); 1154 } 1155 /** Return a list of all constructors defined by the given class. 1156 * Access checking is performed on behalf of the given {@code lookupClass}. 1157 * Inaccessible members are not added to the last. 1158 */ 1159 public List<MemberName> getConstructors(Class<?> defc, Class<?> lookupClass) { 1160 return getMembers(defc, null, null, IS_CONSTRUCTOR, lookupClass); 1161 } 1162 /** Return a list of all fields defined by the given class. 1163 * Super types are searched (for inherited members) if {@code searchSupers} is true. 1164 * Access checking is performed on behalf of the given {@code lookupClass}. 1165 * Inaccessible members are not added to the last. 1166 */ 1167 public List<MemberName> getFields(Class<?> defc, boolean searchSupers, 1168 Class<?> lookupClass) { 1169 return getFields(defc, searchSupers, null, null, lookupClass); 1170 } 1171 /** Return a list of all fields defined by the given class. 1172 * Super types are searched (for inherited members) if {@code searchSupers} is true. 1173 * Returned fields will match the name (if not null) and the type (if not null). 1174 * Access checking is performed on behalf of the given {@code lookupClass}. 1175 * Inaccessible members are not added to the last. 1176 */ 1177 public List<MemberName> getFields(Class<?> defc, boolean searchSupers, 1178 String name, Class<?> type, Class<?> lookupClass) { 1179 int matchFlags = IS_FIELD | (searchSupers ? SEARCH_ALL_SUPERS : 0); 1180 return getMembers(defc, name, type, matchFlags, lookupClass); 1181 } 1182 /** Return a list of all nested types defined by the given class. 1183 * Super types are searched (for inherited members) if {@code searchSupers} is true. 1184 * Access checking is performed on behalf of the given {@code lookupClass}. 1185 * Inaccessible members are not added to the last. 1186 */ 1187 public List<MemberName> getNestedTypes(Class<?> defc, boolean searchSupers, 1188 Class<?> lookupClass) { 1189 int matchFlags = IS_TYPE | (searchSupers ? SEARCH_ALL_SUPERS : 0); 1190 return getMembers(defc, null, null, matchFlags, lookupClass); 1191 } 1192 private static MemberName[] newMemberBuffer(int length) { 1193 MemberName[] buf = new MemberName[length]; 1194 // fill the buffer with dummy structs for the JVM to fill in 1195 for (int i = 0; i < length; i++) 1196 buf[i] = new MemberName(); 1197 return buf; 1198 } 1199 } 1200 }