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