rt/emul/compact/src/main/java/java/lang/invoke/MethodHandleNatives.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 12 Aug 2014 22:57:16 +0200
branchjdk8
changeset 1671 c1732e50ebe7
parent 1670 b913b6b415a0
permissions -rw-r--r--
Need to initialize flags. getFields throws SecurityException on bck2brwsr VM - avoid.
jaroslav@1646
     1
/*
jaroslav@1646
     2
 * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
jaroslav@1646
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@1646
     4
 *
jaroslav@1646
     5
 * This code is free software; you can redistribute it and/or modify it
jaroslav@1646
     6
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@1646
     7
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@1646
     8
 * particular file as subject to the "Classpath" exception as provided
jaroslav@1646
     9
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@1646
    10
 *
jaroslav@1646
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@1646
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@1646
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@1646
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@1646
    15
 * accompanied this code).
jaroslav@1646
    16
 *
jaroslav@1646
    17
 * You should have received a copy of the GNU General Public License version
jaroslav@1646
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@1646
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@1646
    20
 *
jaroslav@1646
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@1646
    22
 * or visit www.oracle.com if you need additional information or have any
jaroslav@1646
    23
 * questions.
jaroslav@1646
    24
 */
jaroslav@1646
    25
jaroslav@1646
    26
package java.lang.invoke;
jaroslav@1646
    27
jaroslav@1646
    28
import static java.lang.invoke.MethodHandleNatives.Constants.*;
jaroslav@1646
    29
import static java.lang.invoke.MethodHandleStatics.*;
jaroslav@1669
    30
import java.lang.invoke.MethodHandles.Lookup;
jaroslav@1646
    31
import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
jaroslav@1669
    32
import java.lang.reflect.Constructor;
jaroslav@1669
    33
import java.lang.reflect.Field;
jaroslav@1670
    34
import java.lang.reflect.Member;
jaroslav@1669
    35
import java.lang.reflect.Method;
jaroslav@1646
    36
jaroslav@1646
    37
/**
jaroslav@1646
    38
 * The JVM interface for the method handles package is all here.
jaroslav@1646
    39
 * This is an interface internal and private to an implementation of JSR 292.
jaroslav@1646
    40
 * <em>This class is not part of the JSR 292 standard.</em>
jaroslav@1646
    41
 * @author jrose
jaroslav@1646
    42
 */
jaroslav@1646
    43
class MethodHandleNatives {
jaroslav@1646
    44
jaroslav@1646
    45
    private MethodHandleNatives() { } // static only
jaroslav@1646
    46
jaroslav@1646
    47
    /// MemberName support
jaroslav@1646
    48
jaroslav@1669
    49
    static void init(MemberName self, Object ref) {
jaroslav@1671
    50
        final Member mem = (Member)ref;
jaroslav@1671
    51
        self.clazz = mem.getDeclaringClass();
jaroslav@1671
    52
        int mod = mem.getModifiers();
jaroslav@1671
    53
        if (ref instanceof Method) {
jaroslav@1671
    54
            mod  |= MemberName.IS_METHOD;
jaroslav@1671
    55
        }
jaroslav@1671
    56
        if (ref instanceof Constructor) {
jaroslav@1671
    57
            mod  |= MemberName.IS_CONSTRUCTOR;
jaroslav@1671
    58
        }
jaroslav@1671
    59
        self.flags = mod;
jaroslav@1669
    60
    }
jaroslav@1669
    61
    
jaroslav@1669
    62
    static void expand(MemberName self) {
jaroslav@1669
    63
    }
jaroslav@1669
    64
    
jaroslav@1661
    65
    static MemberName resolve(MemberName self, Class<?> caller) throws LinkageError {
jaroslav@1661
    66
        return self;
jaroslav@1661
    67
    }
jaroslav@1669
    68
    static int getMembers(Class<?> defc, String matchName, String matchSig,
jaroslav@1669
    69
            int matchFlags, Class<?> caller, int skip, MemberName[] results) {
jaroslav@1669
    70
        int orig = skip;
jaroslav@1669
    71
        for (Method m : defc.getMethods()) {
jaroslav@1669
    72
            if (skip == results.length) {
jaroslav@1669
    73
                break;
jaroslav@1669
    74
            }
jaroslav@1669
    75
            MemberName mn = new MemberName(m);
jaroslav@1669
    76
            results[skip++] = mn;
jaroslav@1669
    77
        }
jaroslav@1669
    78
        for (Constructor m : defc.getConstructors()) {
jaroslav@1669
    79
            if (skip == results.length) {
jaroslav@1669
    80
                break;
jaroslav@1669
    81
            }
jaroslav@1669
    82
            MemberName mn = new MemberName(m);
jaroslav@1669
    83
            results[skip++] = mn;
jaroslav@1669
    84
        }
jaroslav@1671
    85
//        for (Field m : defc.getFields()) {
jaroslav@1671
    86
//            if (skip == results.length) {
jaroslav@1671
    87
//                break;
jaroslav@1671
    88
//            }
jaroslav@1671
    89
//            MemberName mn = new MemberName(m);
jaroslav@1671
    90
//            results[skip++] = mn;
jaroslav@1671
    91
//        }
jaroslav@1669
    92
        return skip - orig;
jaroslav@1669
    93
    }
jaroslav@1646
    94
jaroslav@1646
    95
    /// Field layout queries parallel to sun.misc.Unsafe:
jaroslav@1646
    96
    static native long objectFieldOffset(MemberName self);  // e.g., returns vmindex
jaroslav@1646
    97
    static native long staticFieldOffset(MemberName self);  // e.g., returns vmindex
jaroslav@1646
    98
    static native Object staticFieldBase(MemberName self);  // e.g., returns clazz
jaroslav@1646
    99
    static native Object getMemberVMInfo(MemberName self);  // returns {vmindex,vmtarget}
jaroslav@1646
   100
jaroslav@1646
   101
    /// MethodHandle support
jaroslav@1646
   102
jaroslav@1646
   103
    /// CallSite support
jaroslav@1646
   104
jaroslav@1646
   105
    /** Tell the JVM that we need to change the target of a CallSite. */
jaroslav@1646
   106
    static native void setCallSiteTargetNormal(CallSite site, MethodHandle target);
jaroslav@1646
   107
    static native void setCallSiteTargetVolatile(CallSite site, MethodHandle target);
jaroslav@1646
   108
jaroslav@1646
   109
    static {
jaroslav@1646
   110
        // The JVM calls MethodHandleNatives.<clinit>.  Cascade the <clinit> calls as needed:
jaroslav@1646
   111
        MethodHandleImpl.initStatics();
jaroslav@1646
   112
}
jaroslav@1646
   113
jaroslav@1646
   114
    // All compile-time constants go here.
jaroslav@1646
   115
    // There is an opportunity to check them against the JVM's idea of them.
jaroslav@1646
   116
    static class Constants {
jaroslav@1646
   117
        Constants() { } // static only
jaroslav@1646
   118
        // MethodHandleImpl
jaroslav@1646
   119
        static final int // for getConstant
jaroslav@1646
   120
                GC_COUNT_GWT = 4,
jaroslav@1646
   121
                GC_LAMBDA_SUPPORT = 5;
jaroslav@1646
   122
jaroslav@1646
   123
        // MemberName
jaroslav@1646
   124
        // The JVM uses values of -2 and above for vtable indexes.
jaroslav@1646
   125
        // Field values are simple positive offsets.
jaroslav@1646
   126
        // Ref: src/share/vm/oops/methodOop.hpp
jaroslav@1646
   127
        // This value is negative enough to avoid such numbers,
jaroslav@1646
   128
        // but not too negative.
jaroslav@1646
   129
        static final int
jaroslav@1646
   130
                MN_IS_METHOD           = 0x00010000, // method (not constructor)
jaroslav@1646
   131
                MN_IS_CONSTRUCTOR      = 0x00020000, // constructor
jaroslav@1646
   132
                MN_IS_FIELD            = 0x00040000, // field
jaroslav@1646
   133
                MN_IS_TYPE             = 0x00080000, // nested type
jaroslav@1646
   134
                MN_CALLER_SENSITIVE    = 0x00100000, // @CallerSensitive annotation detected
jaroslav@1646
   135
                MN_REFERENCE_KIND_SHIFT = 24, // refKind
jaroslav@1646
   136
                MN_REFERENCE_KIND_MASK = 0x0F000000 >> MN_REFERENCE_KIND_SHIFT,
jaroslav@1646
   137
                // The SEARCH_* bits are not for MN.flags but for the matchFlags argument of MHN.getMembers:
jaroslav@1646
   138
                MN_SEARCH_SUPERCLASSES = 0x00100000,
jaroslav@1646
   139
                MN_SEARCH_INTERFACES   = 0x00200000;
jaroslav@1646
   140
jaroslav@1646
   141
        /**
jaroslav@1646
   142
         * Basic types as encoded in the JVM.  These code values are not
jaroslav@1646
   143
         * intended for use outside this class.  They are used as part of
jaroslav@1646
   144
         * a private interface between the JVM and this class.
jaroslav@1646
   145
         */
jaroslav@1646
   146
        static final int
jaroslav@1646
   147
            T_BOOLEAN  =  4,
jaroslav@1646
   148
            T_CHAR     =  5,
jaroslav@1646
   149
            T_FLOAT    =  6,
jaroslav@1646
   150
            T_DOUBLE   =  7,
jaroslav@1646
   151
            T_BYTE     =  8,
jaroslav@1646
   152
            T_SHORT    =  9,
jaroslav@1646
   153
            T_INT      = 10,
jaroslav@1646
   154
            T_LONG     = 11,
jaroslav@1646
   155
            T_OBJECT   = 12,
jaroslav@1646
   156
            //T_ARRAY    = 13
jaroslav@1646
   157
            T_VOID     = 14,
jaroslav@1646
   158
            //T_ADDRESS  = 15
jaroslav@1646
   159
            T_ILLEGAL  = 99;
jaroslav@1646
   160
jaroslav@1646
   161
        /**
jaroslav@1646
   162
         * Constant pool entry types.
jaroslav@1646
   163
         */
jaroslav@1646
   164
        static final byte
jaroslav@1646
   165
            CONSTANT_Utf8                = 1,
jaroslav@1646
   166
            CONSTANT_Integer             = 3,
jaroslav@1646
   167
            CONSTANT_Float               = 4,
jaroslav@1646
   168
            CONSTANT_Long                = 5,
jaroslav@1646
   169
            CONSTANT_Double              = 6,
jaroslav@1646
   170
            CONSTANT_Class               = 7,
jaroslav@1646
   171
            CONSTANT_String              = 8,
jaroslav@1646
   172
            CONSTANT_Fieldref            = 9,
jaroslav@1646
   173
            CONSTANT_Methodref           = 10,
jaroslav@1646
   174
            CONSTANT_InterfaceMethodref  = 11,
jaroslav@1646
   175
            CONSTANT_NameAndType         = 12,
jaroslav@1646
   176
            CONSTANT_MethodHandle        = 15,  // JSR 292
jaroslav@1646
   177
            CONSTANT_MethodType          = 16,  // JSR 292
jaroslav@1646
   178
            CONSTANT_InvokeDynamic       = 18,
jaroslav@1646
   179
            CONSTANT_LIMIT               = 19;   // Limit to tags found in classfiles
jaroslav@1646
   180
jaroslav@1646
   181
        /**
jaroslav@1646
   182
         * Access modifier flags.
jaroslav@1646
   183
         */
jaroslav@1646
   184
        static final char
jaroslav@1646
   185
            ACC_PUBLIC                 = 0x0001,
jaroslav@1646
   186
            ACC_PRIVATE                = 0x0002,
jaroslav@1646
   187
            ACC_PROTECTED              = 0x0004,
jaroslav@1646
   188
            ACC_STATIC                 = 0x0008,
jaroslav@1646
   189
            ACC_FINAL                  = 0x0010,
jaroslav@1646
   190
            ACC_SYNCHRONIZED           = 0x0020,
jaroslav@1646
   191
            ACC_VOLATILE               = 0x0040,
jaroslav@1646
   192
            ACC_TRANSIENT              = 0x0080,
jaroslav@1646
   193
            ACC_NATIVE                 = 0x0100,
jaroslav@1646
   194
            ACC_INTERFACE              = 0x0200,
jaroslav@1646
   195
            ACC_ABSTRACT               = 0x0400,
jaroslav@1646
   196
            ACC_STRICT                 = 0x0800,
jaroslav@1646
   197
            ACC_SYNTHETIC              = 0x1000,
jaroslav@1646
   198
            ACC_ANNOTATION             = 0x2000,
jaroslav@1646
   199
            ACC_ENUM                   = 0x4000,
jaroslav@1646
   200
            // aliases:
jaroslav@1646
   201
            ACC_SUPER                  = ACC_SYNCHRONIZED,
jaroslav@1646
   202
            ACC_BRIDGE                 = ACC_VOLATILE,
jaroslav@1646
   203
            ACC_VARARGS                = ACC_TRANSIENT;
jaroslav@1646
   204
jaroslav@1646
   205
        /**
jaroslav@1646
   206
         * Constant pool reference-kind codes, as used by CONSTANT_MethodHandle CP entries.
jaroslav@1646
   207
         */
jaroslav@1646
   208
        static final byte
jaroslav@1646
   209
            REF_NONE                    = 0,  // null value
jaroslav@1646
   210
            REF_getField                = 1,
jaroslav@1646
   211
            REF_getStatic               = 2,
jaroslav@1646
   212
            REF_putField                = 3,
jaroslav@1646
   213
            REF_putStatic               = 4,
jaroslav@1646
   214
            REF_invokeVirtual           = 5,
jaroslav@1646
   215
            REF_invokeStatic            = 6,
jaroslav@1646
   216
            REF_invokeSpecial           = 7,
jaroslav@1646
   217
            REF_newInvokeSpecial        = 8,
jaroslav@1646
   218
            REF_invokeInterface         = 9,
jaroslav@1646
   219
            REF_LIMIT                  = 10;
jaroslav@1646
   220
    }
jaroslav@1646
   221
jaroslav@1646
   222
    static boolean refKindIsValid(int refKind) {
jaroslav@1646
   223
        return (refKind > REF_NONE && refKind < REF_LIMIT);
jaroslav@1646
   224
    }
jaroslav@1646
   225
    static boolean refKindIsField(byte refKind) {
jaroslav@1646
   226
        assert(refKindIsValid(refKind));
jaroslav@1646
   227
        return (refKind <= REF_putStatic);
jaroslav@1646
   228
    }
jaroslav@1646
   229
    static boolean refKindIsGetter(byte refKind) {
jaroslav@1646
   230
        assert(refKindIsValid(refKind));
jaroslav@1646
   231
        return (refKind <= REF_getStatic);
jaroslav@1646
   232
    }
jaroslav@1646
   233
    static boolean refKindIsSetter(byte refKind) {
jaroslav@1646
   234
        return refKindIsField(refKind) && !refKindIsGetter(refKind);
jaroslav@1646
   235
    }
jaroslav@1646
   236
    static boolean refKindIsMethod(byte refKind) {
jaroslav@1646
   237
        return !refKindIsField(refKind) && (refKind != REF_newInvokeSpecial);
jaroslav@1646
   238
    }
jaroslav@1646
   239
    static boolean refKindIsConstructor(byte refKind) {
jaroslav@1646
   240
        return (refKind == REF_newInvokeSpecial);
jaroslav@1646
   241
    }
jaroslav@1646
   242
    static boolean refKindHasReceiver(byte refKind) {
jaroslav@1646
   243
        assert(refKindIsValid(refKind));
jaroslav@1646
   244
        return (refKind & 1) != 0;
jaroslav@1646
   245
    }
jaroslav@1646
   246
    static boolean refKindIsStatic(byte refKind) {
jaroslav@1646
   247
        return !refKindHasReceiver(refKind) && (refKind != REF_newInvokeSpecial);
jaroslav@1646
   248
    }
jaroslav@1646
   249
    static boolean refKindDoesDispatch(byte refKind) {
jaroslav@1646
   250
        assert(refKindIsValid(refKind));
jaroslav@1646
   251
        return (refKind == REF_invokeVirtual ||
jaroslav@1646
   252
                refKind == REF_invokeInterface);
jaroslav@1646
   253
    }
jaroslav@1646
   254
    static {
jaroslav@1646
   255
        final int HR_MASK = ((1 << REF_getField) |
jaroslav@1646
   256
                             (1 << REF_putField) |
jaroslav@1646
   257
                             (1 << REF_invokeVirtual) |
jaroslav@1646
   258
                             (1 << REF_invokeSpecial) |
jaroslav@1646
   259
                             (1 << REF_invokeInterface)
jaroslav@1646
   260
                            );
jaroslav@1646
   261
        for (byte refKind = REF_NONE+1; refKind < REF_LIMIT; refKind++) {
jaroslav@1646
   262
            assert(refKindHasReceiver(refKind) == (((1<<refKind) & HR_MASK) != 0)) : refKind;
jaroslav@1646
   263
        }
jaroslav@1646
   264
    }
jaroslav@1646
   265
    static String refKindName(byte refKind) {
jaroslav@1646
   266
        assert(refKindIsValid(refKind));
jaroslav@1646
   267
        switch (refKind) {
jaroslav@1646
   268
        case REF_getField:          return "getField";
jaroslav@1646
   269
        case REF_getStatic:         return "getStatic";
jaroslav@1646
   270
        case REF_putField:          return "putField";
jaroslav@1646
   271
        case REF_putStatic:         return "putStatic";
jaroslav@1646
   272
        case REF_invokeVirtual:     return "invokeVirtual";
jaroslav@1646
   273
        case REF_invokeStatic:      return "invokeStatic";
jaroslav@1646
   274
        case REF_invokeSpecial:     return "invokeSpecial";
jaroslav@1646
   275
        case REF_newInvokeSpecial:  return "newInvokeSpecial";
jaroslav@1646
   276
        case REF_invokeInterface:   return "invokeInterface";
jaroslav@1646
   277
        default:                    return "REF_???";
jaroslav@1646
   278
        }
jaroslav@1646
   279
    }
jaroslav@1646
   280
jaroslav@1646
   281
    private static native int getNamedCon(int which, Object[] name);
jaroslav@1646
   282
    static boolean verifyConstants() {
jaroslav@1646
   283
        Object[] box = { null };
jaroslav@1646
   284
        for (int i = 0; ; i++) {
jaroslav@1646
   285
            box[0] = null;
jaroslav@1646
   286
            int vmval = getNamedCon(i, box);
jaroslav@1646
   287
            if (box[0] == null)  break;
jaroslav@1646
   288
            String name = (String) box[0];
jaroslav@1646
   289
            try {
jaroslav@1646
   290
                Field con = Constants.class.getDeclaredField(name);
jaroslav@1646
   291
                int jval = con.getInt(null);
jaroslav@1646
   292
                if (jval == vmval)  continue;
jaroslav@1646
   293
                String err = (name+": JVM has "+vmval+" while Java has "+jval);
jaroslav@1646
   294
                if (name.equals("CONV_OP_LIMIT")) {
jaroslav@1646
   295
                    System.err.println("warning: "+err);
jaroslav@1646
   296
                    continue;
jaroslav@1646
   297
                }
jaroslav@1646
   298
                throw new InternalError(err);
jaroslav@1651
   299
            } catch (IllegalAccessException ex) {
jaroslav@1646
   300
                String err = (name+": JVM has "+vmval+" which Java does not define");
jaroslav@1646
   301
                // ignore exotic ops the JVM cares about; we just wont issue them
jaroslav@1646
   302
                //System.err.println("warning: "+err);
jaroslav@1646
   303
                continue;
jaroslav@1646
   304
            }
jaroslav@1646
   305
        }
jaroslav@1646
   306
        return true;
jaroslav@1646
   307
    }
jaroslav@1646
   308
    static {
jaroslav@1646
   309
        assert(verifyConstants());
jaroslav@1646
   310
    }
jaroslav@1646
   311
jaroslav@1646
   312
    // Up-calls from the JVM.
jaroslav@1646
   313
    // These must NOT be public.
jaroslav@1646
   314
jaroslav@1646
   315
    /**
jaroslav@1646
   316
     * The JVM is linking an invokedynamic instruction.  Create a reified call site for it.
jaroslav@1646
   317
     */
jaroslav@1646
   318
    static MemberName linkCallSite(Object callerObj,
jaroslav@1646
   319
                                   Object bootstrapMethodObj,
jaroslav@1646
   320
                                   Object nameObj, Object typeObj,
jaroslav@1646
   321
                                   Object staticArguments,
jaroslav@1646
   322
                                   Object[] appendixResult) {
jaroslav@1646
   323
        MethodHandle bootstrapMethod = (MethodHandle)bootstrapMethodObj;
jaroslav@1646
   324
        Class<?> caller = (Class<?>)callerObj;
jaroslav@1646
   325
        String name = nameObj.toString().intern();
jaroslav@1646
   326
        MethodType type = (MethodType)typeObj;
jaroslav@1646
   327
        CallSite callSite = CallSite.makeSite(bootstrapMethod,
jaroslav@1646
   328
                                              name,
jaroslav@1646
   329
                                              type,
jaroslav@1646
   330
                                              staticArguments,
jaroslav@1646
   331
                                              caller);
jaroslav@1646
   332
        if (callSite instanceof ConstantCallSite) {
jaroslav@1646
   333
            appendixResult[0] = callSite.dynamicInvoker();
jaroslav@1646
   334
            return Invokers.linkToTargetMethod(type);
jaroslav@1646
   335
        } else {
jaroslav@1646
   336
            appendixResult[0] = callSite;
jaroslav@1646
   337
            return Invokers.linkToCallSiteMethod(type);
jaroslav@1646
   338
        }
jaroslav@1646
   339
    }
jaroslav@1646
   340
jaroslav@1646
   341
    /**
jaroslav@1646
   342
     * The JVM wants a pointer to a MethodType.  Oblige it by finding or creating one.
jaroslav@1646
   343
     */
jaroslav@1646
   344
    static MethodType findMethodHandleType(Class<?> rtype, Class<?>[] ptypes) {
jaroslav@1646
   345
        return MethodType.makeImpl(rtype, ptypes, true);
jaroslav@1646
   346
    }
jaroslav@1646
   347
jaroslav@1646
   348
    /**
jaroslav@1646
   349
     * The JVM wants to link a call site that requires a dynamic type check.
jaroslav@1646
   350
     * Name is a type-checking invoker, invokeExact or invoke.
jaroslav@1646
   351
     * Return a JVM method (MemberName) to handle the invoking.
jaroslav@1646
   352
     * The method assumes the following arguments on the stack:
jaroslav@1646
   353
     * 0: the method handle being invoked
jaroslav@1646
   354
     * 1-N: the arguments to the method handle invocation
jaroslav@1646
   355
     * N+1: an optional, implicitly added argument (typically the given MethodType)
jaroslav@1646
   356
     * <p>
jaroslav@1646
   357
     * The nominal method at such a call site is an instance of
jaroslav@1646
   358
     * a signature-polymorphic method (see @PolymorphicSignature).
jaroslav@1646
   359
     * Such method instances are user-visible entities which are
jaroslav@1646
   360
     * "split" from the generic placeholder method in {@code MethodHandle}.
jaroslav@1646
   361
     * (Note that the placeholder method is not identical with any of
jaroslav@1646
   362
     * its instances.  If invoked reflectively, is guaranteed to throw an
jaroslav@1646
   363
     * {@code UnsupportedOperationException}.)
jaroslav@1646
   364
     * If the signature-polymorphic method instance is ever reified,
jaroslav@1646
   365
     * it appears as a "copy" of the original placeholder
jaroslav@1646
   366
     * (a native final member of {@code MethodHandle}) except
jaroslav@1646
   367
     * that its type descriptor has shape required by the instance,
jaroslav@1646
   368
     * and the method instance is <em>not</em> varargs.
jaroslav@1646
   369
     * The method instance is also marked synthetic, since the
jaroslav@1646
   370
     * method (by definition) does not appear in Java source code.
jaroslav@1646
   371
     * <p>
jaroslav@1646
   372
     * The JVM is allowed to reify this method as instance metadata.
jaroslav@1646
   373
     * For example, {@code invokeBasic} is always reified.
jaroslav@1646
   374
     * But the JVM may instead call {@code linkMethod}.
jaroslav@1646
   375
     * If the result is an * ordered pair of a {@code (method, appendix)},
jaroslav@1646
   376
     * the method gets all the arguments (0..N inclusive)
jaroslav@1646
   377
     * plus the appendix (N+1), and uses the appendix to complete the call.
jaroslav@1646
   378
     * In this way, one reusable method (called a "linker method")
jaroslav@1646
   379
     * can perform the function of any number of polymorphic instance
jaroslav@1646
   380
     * methods.
jaroslav@1646
   381
     * <p>
jaroslav@1646
   382
     * Linker methods are allowed to be weakly typed, with any or
jaroslav@1646
   383
     * all references rewritten to {@code Object} and any primitives
jaroslav@1646
   384
     * (except {@code long}/{@code float}/{@code double})
jaroslav@1646
   385
     * rewritten to {@code int}.
jaroslav@1646
   386
     * A linker method is trusted to return a strongly typed result,
jaroslav@1646
   387
     * according to the specific method type descriptor of the
jaroslav@1646
   388
     * signature-polymorphic instance it is emulating.
jaroslav@1646
   389
     * This can involve (as necessary) a dynamic check using
jaroslav@1646
   390
     * data extracted from the appendix argument.
jaroslav@1646
   391
     * <p>
jaroslav@1646
   392
     * The JVM does not inspect the appendix, other than to pass
jaroslav@1646
   393
     * it verbatim to the linker method at every call.
jaroslav@1646
   394
     * This means that the JDK runtime has wide latitude
jaroslav@1646
   395
     * for choosing the shape of each linker method and its
jaroslav@1646
   396
     * corresponding appendix.
jaroslav@1646
   397
     * Linker methods should be generated from {@code LambdaForm}s
jaroslav@1646
   398
     * so that they do not become visible on stack traces.
jaroslav@1646
   399
     * <p>
jaroslav@1646
   400
     * The {@code linkMethod} call is free to omit the appendix
jaroslav@1646
   401
     * (returning null) and instead emulate the required function
jaroslav@1646
   402
     * completely in the linker method.
jaroslav@1646
   403
     * As a corner case, if N==255, no appendix is possible.
jaroslav@1646
   404
     * In this case, the method returned must be custom-generated to
jaroslav@1646
   405
     * to perform any needed type checking.
jaroslav@1646
   406
     * <p>
jaroslav@1646
   407
     * If the JVM does not reify a method at a call site, but instead
jaroslav@1646
   408
     * calls {@code linkMethod}, the corresponding call represented
jaroslav@1646
   409
     * in the bytecodes may mention a valid method which is not
jaroslav@1646
   410
     * representable with a {@code MemberName}.
jaroslav@1646
   411
     * Therefore, use cases for {@code linkMethod} tend to correspond to
jaroslav@1646
   412
     * special cases in reflective code such as {@code findVirtual}
jaroslav@1646
   413
     * or {@code revealDirect}.
jaroslav@1646
   414
     */
jaroslav@1646
   415
    static MemberName linkMethod(Class<?> callerClass, int refKind,
jaroslav@1646
   416
                                 Class<?> defc, String name, Object type,
jaroslav@1646
   417
                                 Object[] appendixResult) {
jaroslav@1646
   418
        if (!TRACE_METHOD_LINKAGE)
jaroslav@1646
   419
            return linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
jaroslav@1646
   420
        return linkMethodTracing(callerClass, refKind, defc, name, type, appendixResult);
jaroslav@1646
   421
    }
jaroslav@1646
   422
    static MemberName linkMethodImpl(Class<?> callerClass, int refKind,
jaroslav@1646
   423
                                     Class<?> defc, String name, Object type,
jaroslav@1646
   424
                                     Object[] appendixResult) {
jaroslav@1646
   425
        try {
jaroslav@1646
   426
            if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
jaroslav@1646
   427
                return Invokers.methodHandleInvokeLinkerMethod(name, fixMethodType(callerClass, type), appendixResult);
jaroslav@1646
   428
            }
jaroslav@1646
   429
        } catch (Throwable ex) {
jaroslav@1646
   430
            if (ex instanceof LinkageError)
jaroslav@1646
   431
                throw (LinkageError) ex;
jaroslav@1646
   432
            else
jaroslav@1646
   433
                throw new LinkageError(ex.getMessage(), ex);
jaroslav@1646
   434
        }
jaroslav@1646
   435
        throw new LinkageError("no such method "+defc.getName()+"."+name+type);
jaroslav@1646
   436
    }
jaroslav@1646
   437
    private static MethodType fixMethodType(Class<?> callerClass, Object type) {
jaroslav@1646
   438
        if (type instanceof MethodType)
jaroslav@1646
   439
            return (MethodType) type;
jaroslav@1646
   440
        else
jaroslav@1646
   441
            return MethodType.fromMethodDescriptorString((String)type, callerClass.getClassLoader());
jaroslav@1646
   442
    }
jaroslav@1646
   443
    // Tracing logic:
jaroslav@1646
   444
    static MemberName linkMethodTracing(Class<?> callerClass, int refKind,
jaroslav@1646
   445
                                        Class<?> defc, String name, Object type,
jaroslav@1646
   446
                                        Object[] appendixResult) {
jaroslav@1646
   447
        System.out.println("linkMethod "+defc.getName()+"."+
jaroslav@1646
   448
                           name+type+"/"+Integer.toHexString(refKind));
jaroslav@1646
   449
        try {
jaroslav@1646
   450
            MemberName res = linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
jaroslav@1646
   451
            System.out.println("linkMethod => "+res+" + "+appendixResult[0]);
jaroslav@1646
   452
            return res;
jaroslav@1646
   453
        } catch (Throwable ex) {
jaroslav@1646
   454
            System.out.println("linkMethod => throw "+ex);
jaroslav@1646
   455
            throw ex;
jaroslav@1646
   456
        }
jaroslav@1646
   457
    }
jaroslav@1646
   458
jaroslav@1646
   459
jaroslav@1646
   460
    /**
jaroslav@1646
   461
     * The JVM is resolving a CONSTANT_MethodHandle CP entry.  And it wants our help.
jaroslav@1646
   462
     * It will make an up-call to this method.  (Do not change the name or signature.)
jaroslav@1646
   463
     * The type argument is a Class for field requests and a MethodType for non-fields.
jaroslav@1646
   464
     * <p>
jaroslav@1646
   465
     * Recent versions of the JVM may also pass a resolved MemberName for the type.
jaroslav@1646
   466
     * In that case, the name is ignored and may be null.
jaroslav@1646
   467
     */
jaroslav@1646
   468
    static MethodHandle linkMethodHandleConstant(Class<?> callerClass, int refKind,
jaroslav@1646
   469
                                                 Class<?> defc, String name, Object type) {
jaroslav@1646
   470
        try {
jaroslav@1646
   471
            Lookup lookup = IMPL_LOOKUP.in(callerClass);
jaroslav@1646
   472
            assert(refKindIsValid(refKind));
jaroslav@1646
   473
            return lookup.linkMethodHandleConstant((byte) refKind, defc, name, type);
jaroslav@1646
   474
        } catch (IllegalAccessException ex) {
jaroslav@1646
   475
            Throwable cause = ex.getCause();
jaroslav@1646
   476
            if (cause instanceof AbstractMethodError) {
jaroslav@1646
   477
                throw (AbstractMethodError) cause;
jaroslav@1646
   478
            } else {
jaroslav@1646
   479
                Error err = new IllegalAccessError(ex.getMessage());
jaroslav@1646
   480
                throw initCauseFrom(err, ex);
jaroslav@1646
   481
            }
jaroslav@1646
   482
        } catch (NoSuchMethodException ex) {
jaroslav@1646
   483
            Error err = new NoSuchMethodError(ex.getMessage());
jaroslav@1646
   484
            throw initCauseFrom(err, ex);
jaroslav@1646
   485
        } catch (NoSuchFieldException ex) {
jaroslav@1646
   486
            Error err = new NoSuchFieldError(ex.getMessage());
jaroslav@1646
   487
            throw initCauseFrom(err, ex);
jaroslav@1646
   488
        } catch (ReflectiveOperationException ex) {
jaroslav@1646
   489
            Error err = new IncompatibleClassChangeError();
jaroslav@1646
   490
            throw initCauseFrom(err, ex);
jaroslav@1646
   491
        }
jaroslav@1646
   492
    }
jaroslav@1646
   493
jaroslav@1646
   494
    /**
jaroslav@1646
   495
     * Use best possible cause for err.initCause(), substituting the
jaroslav@1646
   496
     * cause for err itself if the cause has the same (or better) type.
jaroslav@1646
   497
     */
jaroslav@1646
   498
    static private Error initCauseFrom(Error err, Exception ex) {
jaroslav@1646
   499
        Throwable th = ex.getCause();
jaroslav@1646
   500
        if (err.getClass().isInstance(th))
jaroslav@1646
   501
           return (Error) th;
jaroslav@1646
   502
        err.initCause(th == null ? ex : th);
jaroslav@1646
   503
        return err;
jaroslav@1646
   504
    }
jaroslav@1646
   505
jaroslav@1646
   506
    /**
jaroslav@1646
   507
     * Is this method a caller-sensitive method?
jaroslav@1646
   508
     * I.e., does it call Reflection.getCallerClass or a similer method
jaroslav@1646
   509
     * to ask about the identity of its caller?
jaroslav@1646
   510
     */
jaroslav@1646
   511
    static boolean isCallerSensitive(MemberName mem) {
jaroslav@1646
   512
        if (!mem.isInvocable())  return false;  // fields are not caller sensitive
jaroslav@1646
   513
jaroslav@1646
   514
        return mem.isCallerSensitive() || canBeCalledVirtual(mem);
jaroslav@1646
   515
    }
jaroslav@1646
   516
jaroslav@1646
   517
    static boolean canBeCalledVirtual(MemberName mem) {
jaroslav@1646
   518
        assert(mem.isInvocable());
jaroslav@1646
   519
        Class<?> defc = mem.getDeclaringClass();
jaroslav@1646
   520
        switch (mem.getName()) {
jaroslav@1646
   521
        case "checkMemberAccess":
jaroslav@1651
   522
            return true; //canBeCalledVirtual(mem, java.lang.SecurityManager.class);
jaroslav@1646
   523
        case "getContextClassLoader":
jaroslav@1646
   524
            return canBeCalledVirtual(mem, java.lang.Thread.class);
jaroslav@1646
   525
        }
jaroslav@1646
   526
        return false;
jaroslav@1646
   527
    }
jaroslav@1646
   528
jaroslav@1646
   529
    static boolean canBeCalledVirtual(MemberName symbolicRef, Class<?> definingClass) {
jaroslav@1646
   530
        Class<?> symbolicRefClass = symbolicRef.getDeclaringClass();
jaroslav@1646
   531
        if (symbolicRefClass == definingClass)  return true;
jaroslav@1646
   532
        if (symbolicRef.isStatic() || symbolicRef.isPrivate())  return false;
jaroslav@1646
   533
        return (definingClass.isAssignableFrom(symbolicRefClass) ||  // Msym overrides Mdef
jaroslav@1646
   534
                symbolicRefClass.isInterface());                     // Mdef implements Msym
jaroslav@1646
   535
    }
jaroslav@1646
   536
}