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