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