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