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