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