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