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