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