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