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