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