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 decriptive.
  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 //        if (isConstructor() && refKind != REF_newInvokeSpecial)
 331 //            flags += (IS_METHOD - IS_CONSTRUCTOR);
 332 //        else if (refKind == REF_newInvokeSpecial && isMethod())
 333 //            flags += (IS_CONSTRUCTOR - IS_METHOD);
 334         return this;
 335     }
 336 
 337     private boolean testFlags(int mask, int value) {
 338         return (flags & mask) == value;
 339     }
 340     private boolean testAllFlags(int mask) {
 341         return testFlags(mask, mask);
 342     }
 343     private boolean testAnyFlags(int mask) {
 344         return !testFlags(mask, 0);
 345     }
 346 
 347     /** Utility method to query if this member is a method handle invocation (invoke or invokeExact). */
 348     public boolean isMethodHandleInvoke() {
 349         final int bits = MH_INVOKE_MODS;
 350         final int negs = Modifier.STATIC;
 351         if (testFlags(bits | negs, bits) &&
 352             clazz == MethodHandle.class) {
 353             return isMethodHandleInvokeName(name);
 354         }
 355         return false;
 356     }
 357     public static boolean isMethodHandleInvokeName(String name) {
 358         return name.equals("invoke") || name.equals("invokeExact");
 359     }
 360     private static final int MH_INVOKE_MODS = Modifier.NATIVE | Modifier.FINAL | Modifier.PUBLIC;
 361 
 362     /** Utility method to query the modifier flags of this member. */
 363     public boolean isStatic() {
 364         return Modifier.isStatic(flags);
 365     }
 366     /** Utility method to query the modifier flags of this member. */
 367     public boolean isPublic() {
 368         return Modifier.isPublic(flags);
 369     }
 370     /** Utility method to query the modifier flags of this member. */
 371     public boolean isPrivate() {
 372         return Modifier.isPrivate(flags);
 373     }
 374     /** Utility method to query the modifier flags of this member. */
 375     public boolean isProtected() {
 376         return Modifier.isProtected(flags);
 377     }
 378     /** Utility method to query the modifier flags of this member. */
 379     public boolean isFinal() {
 380         return Modifier.isFinal(flags);
 381     }
 382     /** Utility method to query whether this member or its defining class is final. */
 383     public boolean canBeStaticallyBound() {
 384         return Modifier.isFinal(flags | clazz.getModifiers());
 385     }
 386     /** Utility method to query the modifier flags of this member. */
 387     public boolean isVolatile() {
 388         return Modifier.isVolatile(flags);
 389     }
 390     /** Utility method to query the modifier flags of this member. */
 391     public boolean isAbstract() {
 392         return Modifier.isAbstract(flags);
 393     }
 394     /** Utility method to query the modifier flags of this member. */
 395     public boolean isNative() {
 396         return Modifier.isNative(flags);
 397     }
 398     // let the rest (native, volatile, transient, etc.) be tested via Modifier.isFoo
 399 
 400     // unofficial modifier flags, used by HotSpot:
 401     static final int BRIDGE    = 0x00000040;
 402     static final int VARARGS   = 0x00000080;
 403     static final int SYNTHETIC = 0x00001000;
 404     static final int ANNOTATION= 0x00002000;
 405     static final int ENUM      = 0x00004000;
 406     /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */
 407     public boolean isBridge() {
 408         return testAllFlags(IS_METHOD | BRIDGE);
 409     }
 410     /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */
 411     public boolean isVarargs() {
 412         return testAllFlags(VARARGS) && isInvocable();
 413     }
 414     /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */
 415     public boolean isSynthetic() {
 416         return testAllFlags(SYNTHETIC);
 417     }
 418 
 419     static final String CONSTRUCTOR_NAME = "<init>";  // the ever-popular
 420 
 421     // modifiers exported by the JVM:
 422     static final int RECOGNIZED_MODIFIERS = 0xFFFF;
 423 
 424     // private flags, not part of RECOGNIZED_MODIFIERS:
 425     static final int
 426             IS_METHOD        = MN_IS_METHOD,        // method (not constructor)
 427             IS_CONSTRUCTOR   = MN_IS_CONSTRUCTOR,   // constructor
 428             IS_FIELD         = MN_IS_FIELD,         // field
 429             IS_TYPE          = MN_IS_TYPE,          // nested type
 430             CALLER_SENSITIVE = MN_CALLER_SENSITIVE; // @CallerSensitive annotation detected
 431 
 432     static final int ALL_ACCESS = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED;
 433     static final int ALL_KINDS = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE;
 434     static final int IS_INVOCABLE = IS_METHOD | IS_CONSTRUCTOR;
 435     static final int IS_FIELD_OR_METHOD = IS_METHOD | IS_FIELD;
 436     static final int SEARCH_ALL_SUPERS = MN_SEARCH_SUPERCLASSES | MN_SEARCH_INTERFACES;
 437 
 438     /** Utility method to query whether this member is a method or constructor. */
 439     public boolean isInvocable() {
 440         return testAnyFlags(IS_INVOCABLE);
 441     }
 442     /** Utility method to query whether this member is a method, constructor, or field. */
 443     public boolean isFieldOrMethod() {
 444         return testAnyFlags(IS_FIELD_OR_METHOD);
 445     }
 446     /** Query whether this member is a method. */
 447     public boolean isMethod() {
 448         return testAllFlags(IS_METHOD);
 449     }
 450     /** Query whether this member is a constructor. */
 451     public boolean isConstructor() {
 452         return testAllFlags(IS_CONSTRUCTOR);
 453     }
 454     /** Query whether this member is a field. */
 455     public boolean isField() {
 456         return testAllFlags(IS_FIELD);
 457     }
 458     /** Query whether this member is a type. */
 459     public boolean isType() {
 460         return testAllFlags(IS_TYPE);
 461     }
 462     /** Utility method to query whether this member is neither public, private, nor protected. */
 463     public boolean isPackage() {
 464         return !testAnyFlags(ALL_ACCESS);
 465     }
 466     /** Query whether this member has a CallerSensitive annotation. */
 467     public boolean isCallerSensitive() {
 468         return testAllFlags(CALLER_SENSITIVE);
 469     }
 470 
 471     /** Utility method to query whether this member is accessible from a given lookup class. */
 472     public boolean isAccessibleFrom(Class<?> lookupClass) {
 473         return VerifyAccess.isMemberAccessible(this.getDeclaringClass(), this.getDeclaringClass(), flags,
 474                                                lookupClass, ALL_ACCESS|MethodHandles.Lookup.PACKAGE);
 475     }
 476 
 477     /** Initialize a query.   It is not resolved. */
 478     private void init(Class<?> defClass, String name, Object type, int flags) {
 479         // defining class is allowed to be null (for a naked name/type pair)
 480         //name.toString();  // null check
 481         //type.equals(type);  // null check
 482         // fill in fields:
 483         this.clazz = defClass;
 484         this.name = name;
 485         this.type = type;
 486         this.flags = flags;
 487         assert(testAnyFlags(ALL_KINDS));
 488         assert(this.resolution == null);  // nobody should have touched this yet
 489         //assert(referenceKindIsConsistent());  // do this after resolution
 490     }
 491 
 492     /**
 493      * Calls down to the VM to fill in the fields.  This method is
 494      * synchronized to avoid racing calls.
 495      */
 496     private void expandFromVM() {
 497         if (type != null) {
 498             return;
 499         }
 500         if (!isResolved()) {
 501             return;
 502         }
 503         MethodHandleNatives.expand(this);
 504     }
 505 
 506     // Capturing information from the Core Reflection API:
 507     private static int flagsMods(int flags, int mods, byte refKind) {
 508         assert((flags & RECOGNIZED_MODIFIERS) == 0);
 509         assert((mods & ~RECOGNIZED_MODIFIERS) == 0);
 510         assert((refKind & ~MN_REFERENCE_KIND_MASK) == 0);
 511         return flags | mods | (refKind << MN_REFERENCE_KIND_SHIFT);
 512     }
 513     /** Create a name for the given reflected method.  The resulting name will be in a resolved state. */
 514     public MemberName(Method m) {
 515         this(m, false);
 516     }
 517     @SuppressWarnings("LeakingThisInConstructor")
 518     public MemberName(Method m, boolean wantSpecial) {
 519         m.getClass();  // NPE check
 520         // fill in vmtarget, vmindex while we have m in hand:
 521         MethodHandleNatives.init(this, m);
 522         if (clazz == null) {  // MHN.init failed
 523             if (m.getDeclaringClass() == MethodHandle.class &&
 524                 isMethodHandleInvokeName(m.getName())) {
 525                 // The JVM did not reify this signature-polymorphic instance.
 526                 // Need a special case here.
 527                 // See comments on MethodHandleNatives.linkMethod.
 528                 MethodType type = MethodType.methodType(m.getReturnType(), m.getParameterTypes());
 529                 int flags = flagsMods(IS_METHOD, m.getModifiers(), REF_invokeVirtual);
 530                 init(MethodHandle.class, m.getName(), type, flags);
 531                 if (isMethodHandleInvoke())
 532                     return;
 533             }
 534             throw new LinkageError(m.toString());
 535         }
 536         assert(isResolved() && this.clazz != null);
 537         this.name = m.getName();
 538         if (this.type == null)
 539             this.type = new Object[] { m.getReturnType(), m.getParameterTypes() };
 540         if (wantSpecial) {
 541             if (isAbstract())
 542                 throw new AbstractMethodError(this.toString());
 543             if (getReferenceKind() == REF_invokeVirtual)
 544                 changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual);
 545             else if (getReferenceKind() == REF_invokeInterface)
 546                 // invokeSpecial on a default method
 547                 changeReferenceKind(REF_invokeSpecial, REF_invokeInterface);
 548         }
 549     }
 550     public MemberName asSpecial() {
 551         switch (getReferenceKind()) {
 552         case REF_invokeSpecial:     return this;
 553         case REF_invokeVirtual:     return clone().changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual);
 554         case REF_invokeInterface:   return clone().changeReferenceKind(REF_invokeSpecial, REF_invokeInterface);
 555         case REF_newInvokeSpecial:  return clone().changeReferenceKind(REF_invokeSpecial, REF_newInvokeSpecial);
 556         }
 557         throw new IllegalArgumentException(this.toString());
 558     }
 559     /** If this MN is not REF_newInvokeSpecial, return a clone with that ref. kind.
 560      *  In that case it must already be REF_invokeSpecial.
 561      */
 562     public MemberName asConstructor() {
 563         switch (getReferenceKind()) {
 564         case REF_invokeSpecial:     return clone().changeReferenceKind(REF_newInvokeSpecial, REF_invokeSpecial);
 565         case REF_newInvokeSpecial:  return this;
 566         }
 567         throw new IllegalArgumentException(this.toString());
 568     }
 569     /** If this MN is a REF_invokeSpecial, return a clone with the "normal" kind
 570      *  REF_invokeVirtual; also switch either to REF_invokeInterface if clazz.isInterface.
 571      *  The end result is to get a fully virtualized version of the MN.
 572      *  (Note that resolving in the JVM will sometimes devirtualize, changing
 573      *  REF_invokeVirtual of a final to REF_invokeSpecial, and REF_invokeInterface
 574      *  in some corner cases to either of the previous two; this transform
 575      *  undoes that change under the assumption that it occurred.)
 576      */
 577     public MemberName asNormalOriginal() {
 578         byte normalVirtual = clazz.isInterface() ? REF_invokeInterface : REF_invokeVirtual;
 579         byte refKind = getReferenceKind();
 580         byte newRefKind = refKind;
 581         MemberName result = this;
 582         switch (refKind) {
 583         case REF_invokeInterface:
 584         case REF_invokeVirtual:
 585         case REF_invokeSpecial:
 586             newRefKind = normalVirtual;
 587             break;
 588         }
 589         if (newRefKind == refKind)
 590             return this;
 591         result = clone().changeReferenceKind(newRefKind, refKind);
 592         assert(this.referenceKindIsConsistentWith(result.getReferenceKind()));
 593         return result;
 594     }
 595     /** Create a name for the given reflected constructor.  The resulting name will be in a resolved state. */
 596     @SuppressWarnings("LeakingThisInConstructor")
 597     public MemberName(Constructor<?> ctor) {
 598         ctor.getClass();  // NPE check
 599         // fill in vmtarget, vmindex while we have ctor in hand:
 600         MethodHandleNatives.init(this, ctor);
 601         assert(isResolved() && this.clazz != null);
 602         this.name = CONSTRUCTOR_NAME;
 603         if (this.type == null)
 604             this.type = new Object[] { void.class, ctor.getParameterTypes() };
 605     }
 606     /** Create a name for the given reflected field.  The resulting name will be in a resolved state.
 607      */
 608     public MemberName(Field fld) {
 609         this(fld, false);
 610     }
 611     @SuppressWarnings("LeakingThisInConstructor")
 612     public MemberName(Field fld, boolean makeSetter) {
 613         fld.getClass();  // NPE check
 614         // fill in vmtarget, vmindex while we have fld in hand:
 615         MethodHandleNatives.init(this, fld);
 616         assert(isResolved() && this.clazz != null);
 617         this.name = fld.getName();
 618         this.type = fld.getType();
 619         assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField));
 620         byte refKind = this.getReferenceKind();
 621         assert(refKind == (isStatic() ? REF_getStatic : REF_getField));
 622         if (makeSetter) {
 623             changeReferenceKind((byte)(refKind + (REF_putStatic - REF_getStatic)), refKind);
 624         }
 625     }
 626     public boolean isGetter() {
 627         return MethodHandleNatives.refKindIsGetter(getReferenceKind());
 628     }
 629     public boolean isSetter() {
 630         return MethodHandleNatives.refKindIsSetter(getReferenceKind());
 631     }
 632     public MemberName asSetter() {
 633         byte refKind = getReferenceKind();
 634         assert(MethodHandleNatives.refKindIsGetter(refKind));
 635         assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField));
 636         byte setterRefKind = (byte)(refKind + (REF_putField - REF_getField));
 637         return clone().changeReferenceKind(setterRefKind, refKind);
 638     }
 639     /** Create a name for the given class.  The resulting name will be in a resolved state. */
 640     public MemberName(Class<?> type) {
 641         init(type.getDeclaringClass(), type.getSimpleName(), type,
 642                 flagsMods(IS_TYPE, type.getModifiers(), REF_NONE));
 643         initResolved(true);
 644     }
 645 
 646     /**
 647      * Create a name for a signature-polymorphic invoker.
 648      * This is a placeholder for a signature-polymorphic instance
 649      * (of MH.invokeExact, etc.) that the JVM does not reify.
 650      * See comments on {@link MethodHandleNatives#linkMethod}.
 651      */
 652     static MemberName makeMethodHandleInvoke(String name, MethodType type) {
 653         return makeMethodHandleInvoke(name, type, MH_INVOKE_MODS | SYNTHETIC);
 654     }
 655     static MemberName makeMethodHandleInvoke(String name, MethodType type, int mods) {
 656         MemberName mem = new MemberName(MethodHandle.class, name, type, REF_invokeVirtual);
 657         mem.flags |= mods;  // it's not resolved, but add these modifiers anyway
 658         assert(mem.isMethodHandleInvoke()) : mem;
 659         return mem;
 660     }
 661 
 662     // bare-bones constructor; the JVM will fill it in
 663     MemberName() { }
 664 
 665     // locally useful cloner
 666     @Override protected MemberName clone() {
 667         try {
 668             return (MemberName) super.clone();
 669         } catch (CloneNotSupportedException ex) {
 670             throw newInternalError(ex);
 671         }
 672      }
 673 
 674     /** Get the definition of this member name.
 675      *  This may be in a super-class of the declaring class of this member.
 676      */
 677     public MemberName getDefinition() {
 678         if (!isResolved())  throw new IllegalStateException("must be resolved: "+this);
 679         if (isType())  return this;
 680         MemberName res = this.clone();
 681         res.clazz = null;
 682         res.type = null;
 683         res.name = null;
 684         res.resolution = res;
 685         res.expandFromVM();
 686         assert(res.getName().equals(this.getName()));
 687         return res;
 688     }
 689 
 690     @Override
 691     public int hashCode() {
 692         return Objects.hash(clazz, getReferenceKind(), name, getType());
 693     }
 694     @Override
 695     public boolean equals(Object that) {
 696         return (that instanceof MemberName && this.equals((MemberName)that));
 697     }
 698 
 699     /** Decide if two member names have exactly the same symbolic content.
 700      *  Does not take into account any actual class members, so even if
 701      *  two member names resolve to the same actual member, they may
 702      *  be distinct references.
 703      */
 704     public boolean equals(MemberName that) {
 705         if (this == that)  return true;
 706         if (that == null)  return false;
 707         return this.clazz == that.clazz
 708                 && this.getReferenceKind() == that.getReferenceKind()
 709                 && Objects.equals(this.name, that.name)
 710                 && Objects.equals(this.getType(), that.getType());
 711     }
 712 
 713     // Construction from symbolic parts, for queries:
 714     /** Create a field or type name from the given components:
 715      *  Declaring class, name, type, reference kind.
 716      *  The declaring class may be supplied as null if this is to be a bare name and type.
 717      *  The resulting name will in an unresolved state.
 718      */
 719     public MemberName(Class<?> defClass, String name, Class<?> type, byte refKind) {
 720         init(defClass, name, type, flagsMods(IS_FIELD, 0, refKind));
 721         initResolved(false);
 722     }
 723     /** Create a field or type name from the given components:  Declaring class, name, type.
 724      *  The declaring class may be supplied as null if this is to be a bare name and type.
 725      *  The modifier flags default to zero.
 726      *  The resulting name will in an unresolved state.
 727      */
 728     public MemberName(Class<?> defClass, String name, Class<?> type, Void unused) {
 729         this(defClass, name, type, REF_NONE);
 730         initResolved(false);
 731     }
 732     /** Create a method or constructor name from the given components:  Declaring class, name, type, modifiers.
 733      *  It will be a constructor if and only if the name is {@code "&lt;init&gt;"}.
 734      *  The declaring class may be supplied as null if this is to be a bare name and type.
 735      *  The last argument is optional, a boolean which requests REF_invokeSpecial.
 736      *  The resulting name will in an unresolved state.
 737      */
 738     public MemberName(Class<?> defClass, String name, MethodType type, byte refKind) {
 739         int initFlags = (name != null && name.equals(CONSTRUCTOR_NAME) ? IS_CONSTRUCTOR : IS_METHOD);
 740         init(defClass, name, type, flagsMods(initFlags, 0, refKind));
 741         initResolved(false);
 742     }
 743     /** Create a method, constructor, or field name from the given components:
 744      *  Reference kind, declaring class, name, type.
 745      */
 746     public MemberName(byte refKind, Class<?> defClass, String name, Object type) {
 747         int kindFlags;
 748         if (MethodHandleNatives.refKindIsField(refKind)) {
 749             kindFlags = IS_FIELD;
 750             if (!(type instanceof Class))
 751                 throw newIllegalArgumentException("not a field type");
 752         } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
 753             kindFlags = IS_METHOD;
 754             if (!(type instanceof MethodType))
 755                 throw newIllegalArgumentException("not a method type");
 756         } else if (refKind == REF_newInvokeSpecial) {
 757             kindFlags = IS_CONSTRUCTOR;
 758             if (!(type instanceof MethodType) ||
 759                 !CONSTRUCTOR_NAME.equals(name))
 760                 throw newIllegalArgumentException("not a constructor type or name");
 761         } else {
 762             throw newIllegalArgumentException("bad reference kind "+refKind);
 763         }
 764         init(defClass, name, type, flagsMods(kindFlags, 0, refKind));
 765         initResolved(false);
 766     }
 767     /** Query whether this member name is resolved to a non-static, non-final method.
 768      */
 769     public boolean hasReceiverTypeDispatch() {
 770         return MethodHandleNatives.refKindDoesDispatch(getReferenceKind());
 771     }
 772 
 773     /** Query whether this member name is resolved.
 774      *  A resolved member name is one for which the JVM has found
 775      *  a method, constructor, field, or type binding corresponding exactly to the name.
 776      *  (Document?)
 777      */
 778     public boolean isResolved() {
 779         return resolution == null;
 780     }
 781 
 782     private void initResolved(boolean isResolved) {
 783         assert(this.resolution == null);  // not initialized yet!
 784         if (!isResolved)
 785             this.resolution = this;
 786         assert(isResolved() == isResolved);
 787     }
 788 
 789     void checkForTypeAlias() {
 790         if (isInvocable()) {
 791             MethodType type;
 792             if (this.type instanceof MethodType)
 793                 type = (MethodType) this.type;
 794             else
 795                 this.type = type = getMethodType();
 796             if (type.erase() == type)  return;
 797             if (VerifyAccess.isTypeVisible(type, clazz))  return;
 798             throw new LinkageError("bad method type alias: "+type+" not visible from "+clazz);
 799         } else {
 800             Class<?> type;
 801             if (this.type instanceof Class<?>)
 802                 type = (Class<?>) this.type;
 803             else
 804                 this.type = type = getFieldType();
 805             if (VerifyAccess.isTypeVisible(type, clazz))  return;
 806             throw new LinkageError("bad field type alias: "+type+" not visible from "+clazz);
 807         }
 808     }
 809 
 810 
 811     /** Produce a string form of this member name.
 812      *  For types, it is simply the type's own string (as reported by {@code toString}).
 813      *  For fields, it is {@code "DeclaringClass.name/type"}.
 814      *  For methods and constructors, it is {@code "DeclaringClass.name(ptype...)rtype"}.
 815      *  If the declaring class is null, the prefix {@code "DeclaringClass."} is omitted.
 816      *  If the member is unresolved, a prefix {@code "*."} is prepended.
 817      */
 818     @SuppressWarnings("LocalVariableHidesMemberVariable")
 819     @Override
 820     public String toString() {
 821         if (isType())
 822             return type.toString();  // class java.lang.String
 823         // else it is a field, method, or constructor
 824         StringBuilder buf = new StringBuilder();
 825         if (getDeclaringClass() != null) {
 826             buf.append(getName(clazz));
 827             buf.append('.');
 828         }
 829         String name = getName();
 830         buf.append(name == null ? "*" : name);
 831         Object type = getType();
 832         if (!isInvocable()) {
 833             buf.append('/');
 834             buf.append(type == null ? "*" : getName(type));
 835         } else {
 836             buf.append(type == null ? "(*)*" : getName(type));
 837         }
 838         byte refKind = getReferenceKind();
 839         if (refKind != REF_NONE) {
 840             buf.append('/');
 841             buf.append(MethodHandleNatives.refKindName(refKind));
 842         }
 843         //buf.append("#").append(System.identityHashCode(this));
 844         return buf.toString();
 845     }
 846     private static String getName(Object obj) {
 847         if (obj instanceof Class<?>)
 848             return ((Class<?>)obj).getName();
 849         return String.valueOf(obj);
 850     }
 851 
 852     public IllegalAccessException makeAccessException(String message, Object from) {
 853         message = message + ": "+ toString();
 854         if (from != null)  message += ", from " + from;
 855         return new IllegalAccessException(message);
 856     }
 857     private String message() {
 858         if (isResolved())
 859             return "no access";
 860         else if (isConstructor())
 861             return "no such constructor";
 862         else if (isMethod())
 863             return "no such method";
 864         else
 865             return "no such field";
 866     }
 867     public ReflectiveOperationException makeAccessException() {
 868         String message = message() + ": "+ toString();
 869         ReflectiveOperationException ex;
 870         if (isResolved() || !(resolution instanceof NoSuchMethodError ||
 871                               resolution instanceof NoSuchFieldError))
 872             ex = new IllegalAccessException(message);
 873         else if (isConstructor())
 874             ex = new NoSuchMethodException(message);
 875         else if (isMethod())
 876             ex = new NoSuchMethodException(message);
 877         else
 878             ex = new NoSuchFieldException(message);
 879         if (resolution instanceof Throwable)
 880             ex.initCause((Throwable) resolution);
 881         return ex;
 882     }
 883 
 884     /** Actually making a query requires an access check. */
 885     /*non-public*/ static Factory getFactory() {
 886         return Factory.INSTANCE;
 887     }
 888     /** A factory type for resolving member names with the help of the VM.
 889      *  TBD: Define access-safe public constructors for this factory.
 890      */
 891     /*non-public*/ static class Factory {
 892         private Factory() { } // singleton pattern
 893         static Factory INSTANCE = new Factory();
 894 
 895         private static int ALLOWED_FLAGS = ALL_KINDS;
 896 
 897         /// Queries
 898         List<MemberName> getMembers(Class<?> defc,
 899                 String matchName, Object matchType,
 900                 int matchFlags, Class<?> lookupClass) {
 901             matchFlags &= ALLOWED_FLAGS;
 902             String matchSig = null;
 903             if (matchType != null) {
 904                 matchSig = BytecodeDescriptor.unparse(matchType);
 905                 if (matchSig.startsWith("("))
 906                     matchFlags &= ~(ALL_KINDS & ~IS_INVOCABLE);
 907                 else
 908                     matchFlags &= ~(ALL_KINDS & ~IS_FIELD);
 909             }
 910             final int BUF_MAX = 0x2000;
 911             int len1 = matchName == null ? 10 : matchType == null ? 4 : 1;
 912             MemberName[] buf = newMemberBuffer(len1);
 913             int totalCount = 0;
 914             ArrayList<MemberName[]> bufs = null;
 915             int bufCount = 0;
 916             for (;;) {
 917                 bufCount = MethodHandleNatives.getMembers(defc,
 918                         matchName, matchSig, matchFlags,
 919                         lookupClass,
 920                         totalCount, buf);
 921                 if (bufCount <= buf.length) {
 922                     if (bufCount < 0)  bufCount = 0;
 923                     totalCount += bufCount;
 924                     break;
 925                 }
 926                 // JVM returned to us with an intentional overflow!
 927                 totalCount += buf.length;
 928                 int excess = bufCount - buf.length;
 929                 if (bufs == null)  bufs = new ArrayList<>(1);
 930                 bufs.add(buf);
 931                 int len2 = buf.length;
 932                 len2 = Math.max(len2, excess);
 933                 len2 = Math.max(len2, totalCount / 4);
 934                 buf = newMemberBuffer(Math.min(BUF_MAX, len2));
 935             }
 936             ArrayList<MemberName> result = new ArrayList<>(totalCount);
 937             if (bufs != null) {
 938                 for (MemberName[] buf0 : bufs) {
 939                     Collections.addAll(result, buf0);
 940                 }
 941             }
 942             result.addAll(Arrays.asList(buf).subList(0, bufCount));
 943             // Signature matching is not the same as type matching, since
 944             // one signature might correspond to several types.
 945             // So if matchType is a Class or MethodType, refilter the results.
 946             if (matchType != null && matchType != matchSig) {
 947                 for (Iterator<MemberName> it = result.iterator(); it.hasNext();) {
 948                     MemberName m = it.next();
 949                     if (!matchType.equals(m.getType()))
 950                         it.remove();
 951                 }
 952             }
 953             return result;
 954         }
 955         /** Produce a resolved version of the given member.
 956          *  Super types are searched (for inherited members) if {@code searchSupers} is true.
 957          *  Access checking is performed on behalf of the given {@code lookupClass}.
 958          *  If lookup fails or access is not permitted, null is returned.
 959          *  Otherwise a fresh copy of the given member is returned, with modifier bits filled in.
 960          */
 961         private MemberName resolve(byte refKind, MemberName ref, Class<?> lookupClass) {
 962             MemberName m = ref.clone();  // JVM will side-effect the ref
 963             assert(refKind == m.getReferenceKind());
 964             try {
 965                 m = MethodHandleNatives.resolve(m, lookupClass);
 966                 m.checkForTypeAlias();
 967                 m.resolution = null;
 968             } catch (LinkageError ex) {
 969                 // JVM reports that the "bytecode behavior" would get an error
 970                 assert(!m.isResolved());
 971                 m.resolution = ex;
 972                 return m;
 973             }
 974             assert(m.referenceKindIsConsistent());
 975             m.initResolved(true);
 976             assert(m.vminfoIsConsistent());
 977             return m;
 978         }
 979         /** Produce a resolved version of the given member.
 980          *  Super types are searched (for inherited members) if {@code searchSupers} is true.
 981          *  Access checking is performed on behalf of the given {@code lookupClass}.
 982          *  If lookup fails or access is not permitted, a {@linkplain ReflectiveOperationException} is thrown.
 983          *  Otherwise a fresh copy of the given member is returned, with modifier bits filled in.
 984          */
 985         public
 986         <NoSuchMemberException extends ReflectiveOperationException>
 987         MemberName resolveOrFail(byte refKind, MemberName m, Class<?> lookupClass,
 988                                  Class<NoSuchMemberException> nsmClass)
 989                 throws IllegalAccessException, NoSuchMemberException {
 990             MemberName result = resolve(refKind, m, lookupClass);
 991             if (result.isResolved())
 992                 return result;
 993             ReflectiveOperationException ex = result.makeAccessException();
 994             if (ex instanceof IllegalAccessException)  throw (IllegalAccessException) ex;
 995             throw nsmClass.cast(ex);
 996         }
 997         /** Produce a resolved version of the given member.
 998          *  Super types are searched (for inherited members) if {@code searchSupers} is true.
 999          *  Access checking is performed on behalf of the given {@code lookupClass}.
1000          *  If lookup fails or access is not permitted, return null.
1001          *  Otherwise a fresh copy of the given member is returned, with modifier bits filled in.
1002          */
1003         public
1004         MemberName resolveOrNull(byte refKind, MemberName m, Class<?> lookupClass) {
1005             MemberName result = resolve(refKind, m, lookupClass);
1006             if (result.isResolved())
1007                 return result;
1008             return null;
1009         }
1010         /** Return a list of all methods defined by the given class.
1011          *  Super types are searched (for inherited members) if {@code searchSupers} is true.
1012          *  Access checking is performed on behalf of the given {@code lookupClass}.
1013          *  Inaccessible members are not added to the last.
1014          */
1015         public List<MemberName> getMethods(Class<?> defc, boolean searchSupers,
1016                 Class<?> lookupClass) {
1017             return getMethods(defc, searchSupers, null, null, lookupClass);
1018         }
1019         /** Return a list of matching methods defined by the given class.
1020          *  Super types are searched (for inherited members) if {@code searchSupers} is true.
1021          *  Returned methods will match the name (if not null) and the type (if not null).
1022          *  Access checking is performed on behalf of the given {@code lookupClass}.
1023          *  Inaccessible members are not added to the last.
1024          */
1025         public List<MemberName> getMethods(Class<?> defc, boolean searchSupers,
1026                 String name, MethodType type, Class<?> lookupClass) {
1027             int matchFlags = IS_METHOD | (searchSupers ? SEARCH_ALL_SUPERS : 0);
1028             return getMembers(defc, name, type, matchFlags, lookupClass);
1029         }
1030         /** Return a list of all constructors defined by the given class.
1031          *  Access checking is performed on behalf of the given {@code lookupClass}.
1032          *  Inaccessible members are not added to the last.
1033          */
1034         public List<MemberName> getConstructors(Class<?> defc, Class<?> lookupClass) {
1035             return getMembers(defc, null, null, IS_CONSTRUCTOR, lookupClass);
1036         }
1037         /** Return a list of all fields defined by the given class.
1038          *  Super types are searched (for inherited members) if {@code searchSupers} is true.
1039          *  Access checking is performed on behalf of the given {@code lookupClass}.
1040          *  Inaccessible members are not added to the last.
1041          */
1042         public List<MemberName> getFields(Class<?> defc, boolean searchSupers,
1043                 Class<?> lookupClass) {
1044             return getFields(defc, searchSupers, null, null, lookupClass);
1045         }
1046         /** Return a list of all fields defined by the given class.
1047          *  Super types are searched (for inherited members) if {@code searchSupers} is true.
1048          *  Returned fields will match the name (if not null) and the type (if not null).
1049          *  Access checking is performed on behalf of the given {@code lookupClass}.
1050          *  Inaccessible members are not added to the last.
1051          */
1052         public List<MemberName> getFields(Class<?> defc, boolean searchSupers,
1053                 String name, Class<?> type, Class<?> lookupClass) {
1054             int matchFlags = IS_FIELD | (searchSupers ? SEARCH_ALL_SUPERS : 0);
1055             return getMembers(defc, name, type, matchFlags, lookupClass);
1056         }
1057         /** Return a list of all nested types defined by the given class.
1058          *  Super types are searched (for inherited members) if {@code searchSupers} is true.
1059          *  Access checking is performed on behalf of the given {@code lookupClass}.
1060          *  Inaccessible members are not added to the last.
1061          */
1062         public List<MemberName> getNestedTypes(Class<?> defc, boolean searchSupers,
1063                 Class<?> lookupClass) {
1064             int matchFlags = IS_TYPE | (searchSupers ? SEARCH_ALL_SUPERS : 0);
1065             return getMembers(defc, null, null, matchFlags, lookupClass);
1066         }
1067         private static MemberName[] newMemberBuffer(int length) {
1068             MemberName[] buf = new MemberName[length];
1069             // fill the buffer with dummy structs for the JVM to fill in
1070             for (int i = 0; i < length; i++)
1071                 buf[i] = new MemberName();
1072             return buf;
1073         }
1074     }
1075 
1076 //    static {
1077 //        System.out.println("Hello world!  My methods are:");
1078 //        System.out.println(Factory.INSTANCE.getMethods(MemberName.class, true, null));
1079 //    }
1080 }