1/*
2 * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package java.lang.invoke;
27
28import jdk.internal.ref.CleanerFactory;
29import sun.invoke.util.Wrapper;
30
31import java.lang.invoke.MethodHandles.Lookup;
32import java.lang.reflect.Field;
33
34import static java.lang.invoke.MethodHandleNatives.Constants.*;
35import static java.lang.invoke.MethodHandleStatics.TRACE_METHOD_LINKAGE;
36import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
37
38/**
39 * The JVM interface for the method handles package is all here.
40 * This is an interface internal and private to an implementation of JSR 292.
41 * <em>This class is not part of the JSR 292 standard.</em>
42 * @author jrose
43 */
44class MethodHandleNatives {
45
46    private MethodHandleNatives() { } // static only
47
48    /// MemberName support
49
50    static native void init(MemberName self, Object ref);
51    static native void expand(MemberName self);
52    static native MemberName resolve(MemberName self, Class<?> caller) throws LinkageError, ClassNotFoundException;
53    static native int getMembers(Class<?> defc, String matchName, String matchSig,
54            int matchFlags, Class<?> caller, int skip, MemberName[] results);
55
56    /// Field layout queries parallel to jdk.internal.misc.Unsafe:
57    static native long objectFieldOffset(MemberName self);  // e.g., returns vmindex
58    static native long staticFieldOffset(MemberName self);  // e.g., returns vmindex
59    static native Object staticFieldBase(MemberName self);  // e.g., returns clazz
60    static native Object getMemberVMInfo(MemberName self);  // returns {vmindex,vmtarget}
61
62    /// CallSite support
63
64    /** Tell the JVM that we need to change the target of a CallSite. */
65    static native void setCallSiteTargetNormal(CallSite site, MethodHandle target);
66    static native void setCallSiteTargetVolatile(CallSite site, MethodHandle target);
67
68    /** Represents a context to track nmethod dependencies on CallSite instance target. */
69    static class CallSiteContext implements Runnable {
70        //@Injected JVM_nmethodBucket* vmdependencies;
71
72        static CallSiteContext make(CallSite cs) {
73            final CallSiteContext newContext = new CallSiteContext();
74            // CallSite instance is tracked by a Cleanable which clears native
75            // structures allocated for CallSite context. Though the CallSite can
76            // become unreachable, its Context is retained by the Cleanable instance
77            // (which is referenced from Cleaner instance which is referenced from
78            // CleanerFactory class) until cleanup is performed.
79            CleanerFactory.cleaner().register(cs, newContext);
80            return newContext;
81        }
82
83        @Override
84        public void run() {
85            MethodHandleNatives.clearCallSiteContext(this);
86        }
87    }
88
89    /** Invalidate all recorded nmethods. */
90    private static native void clearCallSiteContext(CallSiteContext context);
91
92    private static native void registerNatives();
93    static {
94        registerNatives();
95    }
96
97    /**
98     * Compile-time constants go here. This collection exists not only for
99     * reference from clients, but also for ensuring the VM and JDK agree on the
100     * values of these constants (see {@link #verifyConstants()}).
101     */
102    static class Constants {
103        Constants() { } // static only
104
105        static final int
106            MN_IS_METHOD           = 0x00010000, // method (not constructor)
107            MN_IS_CONSTRUCTOR      = 0x00020000, // constructor
108            MN_IS_FIELD            = 0x00040000, // field
109            MN_IS_TYPE             = 0x00080000, // nested type
110            MN_CALLER_SENSITIVE    = 0x00100000, // @CallerSensitive annotation detected
111            MN_REFERENCE_KIND_SHIFT = 24, // refKind
112            MN_REFERENCE_KIND_MASK = 0x0F000000 >> MN_REFERENCE_KIND_SHIFT,
113            // The SEARCH_* bits are not for MN.flags but for the matchFlags argument of MHN.getMembers:
114            MN_SEARCH_SUPERCLASSES = 0x00100000,
115            MN_SEARCH_INTERFACES   = 0x00200000;
116
117        /**
118         * Constant pool reference-kind codes, as used by CONSTANT_MethodHandle CP entries.
119         */
120        static final byte
121            REF_NONE                    = 0,  // null value
122            REF_getField                = 1,
123            REF_getStatic               = 2,
124            REF_putField                = 3,
125            REF_putStatic               = 4,
126            REF_invokeVirtual           = 5,
127            REF_invokeStatic            = 6,
128            REF_invokeSpecial           = 7,
129            REF_newInvokeSpecial        = 8,
130            REF_invokeInterface         = 9,
131            REF_LIMIT                  = 10;
132    }
133
134    static boolean refKindIsValid(int refKind) {
135        return (refKind > REF_NONE && refKind < REF_LIMIT);
136    }
137    static boolean refKindIsField(byte refKind) {
138        assert(refKindIsValid(refKind));
139        return (refKind <= REF_putStatic);
140    }
141    static boolean refKindIsGetter(byte refKind) {
142        assert(refKindIsValid(refKind));
143        return (refKind <= REF_getStatic);
144    }
145    static boolean refKindIsSetter(byte refKind) {
146        return refKindIsField(refKind) && !refKindIsGetter(refKind);
147    }
148    static boolean refKindIsMethod(byte refKind) {
149        return !refKindIsField(refKind) && (refKind != REF_newInvokeSpecial);
150    }
151    static boolean refKindIsConstructor(byte refKind) {
152        return (refKind == REF_newInvokeSpecial);
153    }
154    static boolean refKindHasReceiver(byte refKind) {
155        assert(refKindIsValid(refKind));
156        return (refKind & 1) != 0;
157    }
158    static boolean refKindIsStatic(byte refKind) {
159        return !refKindHasReceiver(refKind) && (refKind != REF_newInvokeSpecial);
160    }
161    static boolean refKindDoesDispatch(byte refKind) {
162        assert(refKindIsValid(refKind));
163        return (refKind == REF_invokeVirtual ||
164                refKind == REF_invokeInterface);
165    }
166    static {
167        final int HR_MASK = ((1 << REF_getField) |
168                             (1 << REF_putField) |
169                             (1 << REF_invokeVirtual) |
170                             (1 << REF_invokeSpecial) |
171                             (1 << REF_invokeInterface)
172                            );
173        for (byte refKind = REF_NONE+1; refKind < REF_LIMIT; refKind++) {
174            assert(refKindHasReceiver(refKind) == (((1<<refKind) & HR_MASK) != 0)) : refKind;
175        }
176    }
177    static String refKindName(byte refKind) {
178        assert(refKindIsValid(refKind));
179        switch (refKind) {
180        case REF_getField:          return "getField";
181        case REF_getStatic:         return "getStatic";
182        case REF_putField:          return "putField";
183        case REF_putStatic:         return "putStatic";
184        case REF_invokeVirtual:     return "invokeVirtual";
185        case REF_invokeStatic:      return "invokeStatic";
186        case REF_invokeSpecial:     return "invokeSpecial";
187        case REF_newInvokeSpecial:  return "newInvokeSpecial";
188        case REF_invokeInterface:   return "invokeInterface";
189        default:                    return "REF_???";
190        }
191    }
192
193    private static native int getNamedCon(int which, Object[] name);
194    static boolean verifyConstants() {
195        Object[] box = { null };
196        for (int i = 0; ; i++) {
197            box[0] = null;
198            int vmval = getNamedCon(i, box);
199            if (box[0] == null)  break;
200            String name = (String) box[0];
201            try {
202                Field con = Constants.class.getDeclaredField(name);
203                int jval = con.getInt(null);
204                if (jval == vmval)  continue;
205                String err = (name+": JVM has "+vmval+" while Java has "+jval);
206                if (name.equals("CONV_OP_LIMIT")) {
207                    System.err.println("warning: "+err);
208                    continue;
209                }
210                throw new InternalError(err);
211            } catch (NoSuchFieldException | IllegalAccessException ex) {
212                String err = (name+": JVM has "+vmval+" which Java does not define");
213                // ignore exotic ops the JVM cares about; we just wont issue them
214                //System.err.println("warning: "+err);
215                continue;
216            }
217        }
218        return true;
219    }
220    static {
221        assert(verifyConstants());
222    }
223
224    // Up-calls from the JVM.
225    // These must NOT be public.
226
227    /**
228     * The JVM is linking an invokedynamic instruction.  Create a reified call site for it.
229     */
230    static MemberName linkCallSite(Object callerObj,
231                                   Object bootstrapMethodObj,
232                                   Object nameObj, Object typeObj,
233                                   Object staticArguments,
234                                   Object[] appendixResult) {
235        MethodHandle bootstrapMethod = (MethodHandle)bootstrapMethodObj;
236        Class<?> caller = (Class<?>)callerObj;
237        String name = nameObj.toString().intern();
238        MethodType type = (MethodType)typeObj;
239        if (!TRACE_METHOD_LINKAGE)
240            return linkCallSiteImpl(caller, bootstrapMethod, name, type,
241                                    staticArguments, appendixResult);
242        return linkCallSiteTracing(caller, bootstrapMethod, name, type,
243                                   staticArguments, appendixResult);
244    }
245    static MemberName linkCallSiteImpl(Class<?> caller,
246                                       MethodHandle bootstrapMethod,
247                                       String name, MethodType type,
248                                       Object staticArguments,
249                                       Object[] appendixResult) {
250        CallSite callSite = CallSite.makeSite(bootstrapMethod,
251                                              name,
252                                              type,
253                                              staticArguments,
254                                              caller);
255        if (callSite instanceof ConstantCallSite) {
256            appendixResult[0] = callSite.dynamicInvoker();
257            return Invokers.linkToTargetMethod(type);
258        } else {
259            appendixResult[0] = callSite;
260            return Invokers.linkToCallSiteMethod(type);
261        }
262    }
263    // Tracing logic:
264    static MemberName linkCallSiteTracing(Class<?> caller,
265                                          MethodHandle bootstrapMethod,
266                                          String name, MethodType type,
267                                          Object staticArguments,
268                                          Object[] appendixResult) {
269        Object bsmReference = bootstrapMethod.internalMemberName();
270        if (bsmReference == null)  bsmReference = bootstrapMethod;
271        Object staticArglist = (staticArguments instanceof Object[] ?
272                                java.util.Arrays.asList((Object[]) staticArguments) :
273                                staticArguments);
274        System.out.println("linkCallSite "+caller.getName()+" "+
275                           bsmReference+" "+
276                           name+type+"/"+staticArglist);
277        try {
278            MemberName res = linkCallSiteImpl(caller, bootstrapMethod, name, type,
279                                              staticArguments, appendixResult);
280            System.out.println("linkCallSite => "+res+" + "+appendixResult[0]);
281            return res;
282        } catch (Throwable ex) {
283            System.out.println("linkCallSite => throw "+ex);
284            throw ex;
285        }
286    }
287
288    /**
289     * The JVM wants a pointer to a MethodType.  Oblige it by finding or creating one.
290     */
291    static MethodType findMethodHandleType(Class<?> rtype, Class<?>[] ptypes) {
292        return MethodType.makeImpl(rtype, ptypes, true);
293    }
294
295    /**
296     * The JVM wants to link a call site that requires a dynamic type check.
297     * Name is a type-checking invoker, invokeExact or invoke.
298     * Return a JVM method (MemberName) to handle the invoking.
299     * The method assumes the following arguments on the stack:
300     * 0: the method handle being invoked
301     * 1-N: the arguments to the method handle invocation
302     * N+1: an optional, implicitly added argument (typically the given MethodType)
303     * <p>
304     * The nominal method at such a call site is an instance of
305     * a signature-polymorphic method (see @PolymorphicSignature).
306     * Such method instances are user-visible entities which are
307     * "split" from the generic placeholder method in {@code MethodHandle}.
308     * (Note that the placeholder method is not identical with any of
309     * its instances.  If invoked reflectively, is guaranteed to throw an
310     * {@code UnsupportedOperationException}.)
311     * If the signature-polymorphic method instance is ever reified,
312     * it appears as a "copy" of the original placeholder
313     * (a native final member of {@code MethodHandle}) except
314     * that its type descriptor has shape required by the instance,
315     * and the method instance is <em>not</em> varargs.
316     * The method instance is also marked synthetic, since the
317     * method (by definition) does not appear in Java source code.
318     * <p>
319     * The JVM is allowed to reify this method as instance metadata.
320     * For example, {@code invokeBasic} is always reified.
321     * But the JVM may instead call {@code linkMethod}.
322     * If the result is an * ordered pair of a {@code (method, appendix)},
323     * the method gets all the arguments (0..N inclusive)
324     * plus the appendix (N+1), and uses the appendix to complete the call.
325     * In this way, one reusable method (called a "linker method")
326     * can perform the function of any number of polymorphic instance
327     * methods.
328     * <p>
329     * Linker methods are allowed to be weakly typed, with any or
330     * all references rewritten to {@code Object} and any primitives
331     * (except {@code long}/{@code float}/{@code double})
332     * rewritten to {@code int}.
333     * A linker method is trusted to return a strongly typed result,
334     * according to the specific method type descriptor of the
335     * signature-polymorphic instance it is emulating.
336     * This can involve (as necessary) a dynamic check using
337     * data extracted from the appendix argument.
338     * <p>
339     * The JVM does not inspect the appendix, other than to pass
340     * it verbatim to the linker method at every call.
341     * This means that the JDK runtime has wide latitude
342     * for choosing the shape of each linker method and its
343     * corresponding appendix.
344     * Linker methods should be generated from {@code LambdaForm}s
345     * so that they do not become visible on stack traces.
346     * <p>
347     * The {@code linkMethod} call is free to omit the appendix
348     * (returning null) and instead emulate the required function
349     * completely in the linker method.
350     * As a corner case, if N==255, no appendix is possible.
351     * In this case, the method returned must be custom-generated to
352     * to perform any needed type checking.
353     * <p>
354     * If the JVM does not reify a method at a call site, but instead
355     * calls {@code linkMethod}, the corresponding call represented
356     * in the bytecodes may mention a valid method which is not
357     * representable with a {@code MemberName}.
358     * Therefore, use cases for {@code linkMethod} tend to correspond to
359     * special cases in reflective code such as {@code findVirtual}
360     * or {@code revealDirect}.
361     */
362    static MemberName linkMethod(Class<?> callerClass, int refKind,
363                                 Class<?> defc, String name, Object type,
364                                 Object[] appendixResult) {
365        if (!TRACE_METHOD_LINKAGE)
366            return linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
367        return linkMethodTracing(callerClass, refKind, defc, name, type, appendixResult);
368    }
369    static MemberName linkMethodImpl(Class<?> callerClass, int refKind,
370                                     Class<?> defc, String name, Object type,
371                                     Object[] appendixResult) {
372        try {
373            if (refKind == REF_invokeVirtual) {
374                if (defc == MethodHandle.class) {
375                    return Invokers.methodHandleInvokeLinkerMethod(
376                            name, fixMethodType(callerClass, type), appendixResult);
377                } else if (defc == VarHandle.class) {
378                    return varHandleOperationLinkerMethod(
379                            name, fixMethodType(callerClass, type), appendixResult);
380                }
381            }
382        } catch (Error e) {
383            // Pass through an Error, including say StackOverflowError or
384            // OutOfMemoryError
385            throw e;
386        } catch (Throwable ex) {
387            // Wrap anything else in LinkageError
388            throw new LinkageError(ex.getMessage(), ex);
389        }
390        throw new LinkageError("no such method "+defc.getName()+"."+name+type);
391    }
392    private static MethodType fixMethodType(Class<?> callerClass, Object type) {
393        if (type instanceof MethodType)
394            return (MethodType) type;
395        else
396            return MethodType.fromDescriptor((String)type, callerClass.getClassLoader());
397    }
398    // Tracing logic:
399    static MemberName linkMethodTracing(Class<?> callerClass, int refKind,
400                                        Class<?> defc, String name, Object type,
401                                        Object[] appendixResult) {
402        System.out.println("linkMethod "+defc.getName()+"."+
403                           name+type+"/"+Integer.toHexString(refKind));
404        try {
405            MemberName res = linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
406            System.out.println("linkMethod => "+res+" + "+appendixResult[0]);
407            return res;
408        } catch (Throwable ex) {
409            System.out.println("linkMethod => throw "+ex);
410            throw ex;
411        }
412    }
413
414    /**
415     * Obtain the method to link to the VarHandle operation.
416     * This method is located here and not in Invokers to avoid
417     * intializing that and other classes early on in VM bootup.
418     */
419    private static MemberName varHandleOperationLinkerMethod(String name,
420                                                             MethodType mtype,
421                                                             Object[] appendixResult) {
422        // Get the signature method type
423        final MethodType sigType = mtype.basicType();
424
425        // Get the access kind from the method name
426        VarHandle.AccessMode ak;
427        try {
428            ak = VarHandle.AccessMode.valueFromMethodName(name);
429        } catch (IllegalArgumentException e) {
430            throw MethodHandleStatics.newInternalError(e);
431        }
432
433        // Create the appendix descriptor constant
434        VarHandle.AccessDescriptor ad = new VarHandle.AccessDescriptor(mtype, ak.at.ordinal(), ak.ordinal());
435        appendixResult[0] = ad;
436
437        if (MethodHandleStatics.VAR_HANDLE_GUARDS) {
438            // If not polymorphic in the return type, such as the compareAndSet
439            // methods that return boolean
440            Class<?> guardReturnType = sigType.returnType();
441            if (ak.at.isMonomorphicInReturnType) {
442                if (ak.at.returnType != mtype.returnType()) {
443                    // The caller contains a different return type than that
444                    // defined by the method
445                    throw newNoSuchMethodErrorOnVarHandle(name, mtype);
446                }
447                // Adjust the return type of the signature method type
448                guardReturnType = ak.at.returnType;
449            }
450
451            // Get the guard method type for linking
452            final Class<?>[] guardParams = new Class<?>[sigType.parameterCount() + 2];
453            // VarHandle at start
454            guardParams[0] = VarHandle.class;
455            for (int i = 0; i < sigType.parameterCount(); i++) {
456                guardParams[i + 1] = sigType.parameterType(i);
457            }
458            // Access descriptor at end
459            guardParams[guardParams.length - 1] = VarHandle.AccessDescriptor.class;
460            MethodType guardType = MethodType.makeImpl(guardReturnType, guardParams, true);
461
462            MemberName linker = new MemberName(
463                    VarHandleGuards.class, getVarHandleGuardMethodName(guardType),
464                    guardType, REF_invokeStatic);
465
466            linker = MemberName.getFactory().resolveOrNull(REF_invokeStatic, linker,
467                                                           VarHandleGuards.class);
468            if (linker != null) {
469                return linker;
470            }
471            // Fall back to lambda form linkage if guard method is not available
472            // TODO Optionally log fallback ?
473        }
474        return Invokers.varHandleInvokeLinkerMethod(ak, mtype);
475    }
476    static String getVarHandleGuardMethodName(MethodType guardType) {
477        String prefix = "guard_";
478        StringBuilder sb = new StringBuilder(prefix.length() + guardType.parameterCount());
479
480        sb.append(prefix);
481        for (int i = 1; i < guardType.parameterCount() - 1; i++) {
482            Class<?> pt = guardType.parameterType(i);
483            sb.append(getCharType(pt));
484        }
485        sb.append('_').append(getCharType(guardType.returnType()));
486        return sb.toString();
487    }
488    static char getCharType(Class<?> pt) {
489        return Wrapper.forBasicType(pt).basicTypeChar();
490    }
491    static NoSuchMethodError newNoSuchMethodErrorOnVarHandle(String name, MethodType mtype) {
492        return new NoSuchMethodError("VarHandle." + name + mtype);
493    }
494
495    /**
496     * The JVM is resolving a CONSTANT_MethodHandle CP entry.  And it wants our help.
497     * It will make an up-call to this method.  (Do not change the name or signature.)
498     * The type argument is a Class for field requests and a MethodType for non-fields.
499     * <p>
500     * Recent versions of the JVM may also pass a resolved MemberName for the type.
501     * In that case, the name is ignored and may be null.
502     */
503    static MethodHandle linkMethodHandleConstant(Class<?> callerClass, int refKind,
504                                                 Class<?> defc, String name, Object type) {
505        try {
506            Lookup lookup = IMPL_LOOKUP.in(callerClass);
507            assert(refKindIsValid(refKind));
508            return lookup.linkMethodHandleConstant((byte) refKind, defc, name, type);
509        } catch (IllegalAccessException ex) {
510            Throwable cause = ex.getCause();
511            if (cause instanceof AbstractMethodError) {
512                throw (AbstractMethodError) cause;
513            } else {
514                Error err = new IllegalAccessError(ex.getMessage());
515                throw initCauseFrom(err, ex);
516            }
517        } catch (NoSuchMethodException ex) {
518            Error err = new NoSuchMethodError(ex.getMessage());
519            throw initCauseFrom(err, ex);
520        } catch (NoSuchFieldException ex) {
521            Error err = new NoSuchFieldError(ex.getMessage());
522            throw initCauseFrom(err, ex);
523        } catch (ReflectiveOperationException ex) {
524            Error err = new IncompatibleClassChangeError();
525            throw initCauseFrom(err, ex);
526        }
527    }
528
529    /**
530     * Use best possible cause for err.initCause(), substituting the
531     * cause for err itself if the cause has the same (or better) type.
532     */
533    private static Error initCauseFrom(Error err, Exception ex) {
534        Throwable th = ex.getCause();
535        if (err.getClass().isInstance(th))
536           return (Error) th;
537        err.initCause(th == null ? ex : th);
538        return err;
539    }
540
541    /**
542     * Is this method a caller-sensitive method?
543     * I.e., does it call Reflection.getCallerClass or a similar method
544     * to ask about the identity of its caller?
545     */
546    static boolean isCallerSensitive(MemberName mem) {
547        if (!mem.isInvocable())  return false;  // fields are not caller sensitive
548
549        return mem.isCallerSensitive() || canBeCalledVirtual(mem);
550    }
551
552    static boolean canBeCalledVirtual(MemberName mem) {
553        assert(mem.isInvocable());
554        Class<?> defc = mem.getDeclaringClass();
555        switch (mem.getName()) {
556        case "checkMemberAccess":
557            return canBeCalledVirtual(mem, java.lang.SecurityManager.class);
558        case "getContextClassLoader":
559            return canBeCalledVirtual(mem, java.lang.Thread.class);
560        }
561        return false;
562    }
563
564    static boolean canBeCalledVirtual(MemberName symbolicRef, Class<?> definingClass) {
565        Class<?> symbolicRefClass = symbolicRef.getDeclaringClass();
566        if (symbolicRefClass == definingClass)  return true;
567        if (symbolicRef.isStatic() || symbolicRef.isPrivate())  return false;
568        return (definingClass.isAssignableFrom(symbolicRefClass) ||  // Msym overrides Mdef
569                symbolicRefClass.isInterface());                     // Mdef implements Msym
570    }
571}
572