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