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