Bootstrap.java revision 1483:7cb19fa78763
1/*
2 * Copyright (c) 2010, 2013, 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 jdk.nashorn.internal.runtime.linker;
27
28import static jdk.nashorn.internal.codegen.CompilerConstants.staticCallNoLookup;
29import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
30
31import java.lang.invoke.CallSite;
32import java.lang.invoke.ConstantCallSite;
33import java.lang.invoke.MethodHandle;
34import java.lang.invoke.MethodHandles;
35import java.lang.invoke.MethodHandles.Lookup;
36import java.lang.invoke.MethodType;
37import jdk.internal.dynalink.CallSiteDescriptor;
38import jdk.internal.dynalink.DynamicLinker;
39import jdk.internal.dynalink.DynamicLinkerFactory;
40import jdk.internal.dynalink.beans.BeansLinker;
41import jdk.internal.dynalink.beans.StaticClass;
42import jdk.internal.dynalink.linker.GuardedInvocation;
43import jdk.internal.dynalink.linker.GuardedInvocationTransformer;
44import jdk.internal.dynalink.linker.LinkRequest;
45import jdk.internal.dynalink.linker.LinkerServices;
46import jdk.internal.dynalink.linker.MethodTypeConversionStrategy;
47import jdk.internal.dynalink.linker.support.TypeUtilities;
48import jdk.internal.dynalink.support.NameCodec;
49import jdk.nashorn.api.scripting.JSObject;
50import jdk.nashorn.internal.codegen.CompilerConstants.Call;
51import jdk.nashorn.internal.lookup.MethodHandleFactory;
52import jdk.nashorn.internal.lookup.MethodHandleFunctionality;
53import jdk.nashorn.internal.runtime.ECMAException;
54import jdk.nashorn.internal.runtime.JSType;
55import jdk.nashorn.internal.runtime.OptimisticReturnFilters;
56import jdk.nashorn.internal.runtime.ScriptFunction;
57import jdk.nashorn.internal.runtime.ScriptRuntime;
58import jdk.nashorn.internal.runtime.options.Options;
59
60/**
61 * This class houses bootstrap method for invokedynamic instructions generated by compiler.
62 */
63public final class Bootstrap {
64    /** Reference to the seed boostrap function */
65    public static final Call BOOTSTRAP = staticCallNoLookup(Bootstrap.class, "bootstrap", CallSite.class, Lookup.class, String.class, MethodType.class, int.class);
66
67    private static final MethodHandleFunctionality MH = MethodHandleFactory.getFunctionality();
68
69    private static final MethodHandle VOID_TO_OBJECT = MH.constant(Object.class, ScriptRuntime.UNDEFINED);
70
71    /**
72     * The default dynalink relink threshold for megamorphism is 8. In the case
73     * of object fields only, it is fine. However, with dual fields, in order to get
74     * performance on benchmarks with a lot of object instantiation and then field
75     * reassignment, it can take slightly more relinks to become stable with type
76     * changes swapping out an entire property map and making a map guard fail.
77     * Since we need to set this value statically it must work with possibly changing
78     * optimistic types and dual fields settings. A higher value does not seem to have
79     * any other negative performance implication when running with object-only fields,
80     * so we choose a higher value here.
81     *
82     * See for example octane.gbemu, run with --log=fields:warning to study
83     * megamorphic behavior
84     */
85    private static final int NASHORN_DEFAULT_UNSTABLE_RELINK_THRESHOLD = 16;
86
87    // do not create me!!
88    private Bootstrap() {
89    }
90
91    private static final DynamicLinker dynamicLinker;
92    static {
93        final DynamicLinkerFactory factory = new DynamicLinkerFactory();
94        final NashornBeansLinker nashornBeansLinker = new NashornBeansLinker();
95        factory.setPrioritizedLinkers(
96            new NashornLinker(),
97            new NashornPrimitiveLinker(),
98            new NashornStaticClassLinker(),
99            new BoundCallableLinker(),
100            new JavaSuperAdapterLinker(),
101            new JSObjectLinker(nashornBeansLinker),
102            new BrowserJSObjectLinker(nashornBeansLinker),
103            new ReflectionCheckLinker());
104        factory.setFallbackLinkers(nashornBeansLinker, new NashornBottomLinker());
105        factory.setSyncOnRelink(true);
106        factory.setPrelinkTransformer(new GuardedInvocationTransformer() {
107            @Override
108            public GuardedInvocation filter(final GuardedInvocation inv, final LinkRequest request, final LinkerServices linkerServices) {
109                final CallSiteDescriptor desc = request.getCallSiteDescriptor();
110                return OptimisticReturnFilters.filterOptimisticReturnValue(inv, desc).asType(linkerServices, desc.getMethodType());
111            }
112        });
113        factory.setAutoConversionStrategy(new MethodTypeConversionStrategy() {
114            @Override
115            public MethodHandle asType(final MethodHandle target, final MethodType newType) {
116                return unboxReturnType(target, newType);
117            }
118        });
119        factory.setInternalObjectsFilter(NashornBeansLinker.createHiddenObjectFilter());
120        final int relinkThreshold = Options.getIntProperty("nashorn.unstable.relink.threshold", NASHORN_DEFAULT_UNSTABLE_RELINK_THRESHOLD);
121        if (relinkThreshold > -1) {
122            factory.setUnstableRelinkThreshold(relinkThreshold);
123        }
124
125        // Linkers for any additional language runtimes deployed alongside Nashorn will be picked up by the factory.
126        factory.setClassLoader(Bootstrap.class.getClassLoader());
127
128        dynamicLinker = factory.createLinker();
129    }
130
131    /**
132     * Returns if the given object is a "callable"
133     * @param obj object to be checked for callability
134     * @return true if the obj is callable
135     */
136    public static boolean isCallable(final Object obj) {
137        if (obj == ScriptRuntime.UNDEFINED || obj == null) {
138            return false;
139        }
140
141        return obj instanceof ScriptFunction ||
142            isJSObjectFunction(obj) ||
143            BeansLinker.isDynamicMethod(obj) ||
144            obj instanceof BoundCallable ||
145            isFunctionalInterfaceObject(obj) ||
146            obj instanceof StaticClass;
147    }
148
149    /**
150     * Returns true if the given object is a strict callable
151     * @param callable the callable object to be checked for strictness
152     * @return true if the obj is a strict callable, false if it is a non-strict callable.
153     * @throws ECMAException with {@code TypeError} if the object is not a callable.
154     */
155    public static boolean isStrictCallable(final Object callable) {
156        if (callable instanceof ScriptFunction) {
157            return ((ScriptFunction)callable).isStrict();
158        } else if (isJSObjectFunction(callable)) {
159            return ((JSObject)callable).isStrictFunction();
160        } else if (callable instanceof BoundCallable) {
161            return isStrictCallable(((BoundCallable)callable).getCallable());
162        } else if (BeansLinker.isDynamicMethod(callable) || callable instanceof StaticClass) {
163            return false;
164        }
165        throw notFunction(callable);
166    }
167
168    private static ECMAException notFunction(final Object obj) {
169        return typeError("not.a.function", ScriptRuntime.safeToString(obj));
170    }
171
172    private static boolean isJSObjectFunction(final Object obj) {
173        return obj instanceof JSObject && ((JSObject)obj).isFunction();
174    }
175
176    /**
177     * Returns if the given object is a dynalink Dynamic method
178     * @param obj object to be checked
179     * @return true if the obj is a dynamic method
180     */
181    public static boolean isDynamicMethod(final Object obj) {
182        return BeansLinker.isDynamicMethod(obj instanceof BoundCallable ? ((BoundCallable)obj).getCallable() : obj);
183    }
184
185    /**
186     * Returns if the given object is an instance of an interface annotated with
187     * java.lang.FunctionalInterface
188     * @param obj object to be checked
189     * @return true if the obj is an instance of @FunctionalInterface interface
190     */
191    public static boolean isFunctionalInterfaceObject(final Object obj) {
192        return !JSType.isPrimitive(obj) && (NashornBeansLinker.getFunctionalInterfaceMethodName(obj.getClass()) != null);
193    }
194
195    /**
196     * Create a call site and link it for Nashorn. This version of the method conforms to the invokedynamic bootstrap
197     * method expected signature and is referenced from Nashorn generated bytecode as the bootstrap method for all
198     * invokedynamic instructions.
199     * @param lookup MethodHandle lookup. Ignored as Nashorn only uses public lookup.
200     * @param opDesc Dynalink dynamic operation descriptor.
201     * @param type   Method type.
202     * @param flags  flags for call type, trace/profile etc.
203     * @return CallSite with MethodHandle to appropriate method or null if not found.
204     */
205    public static CallSite bootstrap(final Lookup lookup, final String opDesc, final MethodType type, final int flags) {
206        return dynamicLinker.link(LinkerCallSite.newLinkerCallSite(lookup, opDesc, type, flags));
207    }
208
209    /**
210     * Boostrapper for math calls that may overflow
211     * @param lookup         lookup
212     * @param name           name of operation
213     * @param type           method type
214     * @param programPoint   program point to bind to callsite
215     *
216     * @return callsite for a math intrinsic node
217     */
218    public static CallSite mathBootstrap(final MethodHandles.Lookup lookup, final String name, final MethodType type, final int programPoint) {
219        final MethodHandle mh;
220        switch (name) {
221        case "iadd":
222            mh = JSType.ADD_EXACT.methodHandle();
223            break;
224        case "isub":
225            mh = JSType.SUB_EXACT.methodHandle();
226            break;
227        case "imul":
228            mh = JSType.MUL_EXACT.methodHandle();
229            break;
230        case "idiv":
231            mh = JSType.DIV_EXACT.methodHandle();
232            break;
233        case "irem":
234            mh = JSType.REM_EXACT.methodHandle();
235            break;
236        case "ineg":
237            mh = JSType.NEGATE_EXACT.methodHandle();
238            break;
239        case "ladd":
240            mh = JSType.ADD_EXACT_LONG.methodHandle();
241            break;
242        case "lsub":
243            mh = JSType.SUB_EXACT_LONG.methodHandle();
244            break;
245        case "lmul":
246            mh = JSType.MUL_EXACT_LONG.methodHandle();
247            break;
248        case "ldiv":
249            mh = JSType.DIV_EXACT_LONG.methodHandle();
250            break;
251        case "lrem":
252            mh = JSType.REM_EXACT_LONG.methodHandle();
253            break;
254        case "lneg":
255            mh = JSType.NEGATE_EXACT_LONG.methodHandle();
256            break;
257        default:
258            throw new AssertionError("unsupported math intrinsic");
259        }
260        return new ConstantCallSite(MH.insertArguments(mh, mh.type().parameterCount() - 1, programPoint));
261    }
262
263    /**
264     * Returns a dynamic invoker for a specified dynamic operation using the
265     * public lookup. You can use this method to create a method handle that
266     * when invoked acts completely as if it were a Nashorn-linked call site.
267     * Note that the available operations are encoded in the flags, see
268     * {@link NashornCallSiteDescriptor} operation constants. If the operation
269     * takes a name, it should be set otherwise empty name (not null) should be
270     * used. All names (including the empty one) should be encoded using
271     * {@link NameCodec#encode(String)}. Few examples:
272     * <ul>
273     *   <li>Get a named property with fixed name:
274     *     <pre>
275     * MethodHandle getColor = Boostrap.createDynamicInvoker(
276     *     "color",
277     *     NashornCallSiteDescriptor.GET_PROPERTY,
278     *     Object.class, Object.class);
279     * Object obj = ...; // somehow obtain the object
280     * Object color = getColor.invokeExact(obj);
281     *     </pre>
282     *   </li>
283     *   <li>Get a named property with variable name:
284     *     <pre>
285     * MethodHandle getProperty = Boostrap.createDynamicInvoker(
286     *     NameCodec.encode(""),
287     *     NashornCallSiteDescriptor.GET_PROPERTY,
288     *     Object.class, Object.class, String.class);
289     * Object obj = ...; // somehow obtain the object
290     * Object color = getProperty.invokeExact(obj, "color");
291     * Object shape = getProperty.invokeExact(obj, "shape");
292     *
293     * MethodHandle getNumProperty = Boostrap.createDynamicInvoker(
294     *     NameCodec.encode(""),
295     *     NashornCallSiteDescriptor.GET_ELEMENT,
296     *     Object.class, Object.class, int.class);
297     * Object elem42 = getNumProperty.invokeExact(obj, 42);
298     *     </pre>
299     *   </li>
300     *   <li>Set a named property with fixed name:
301     *     <pre>
302     * MethodHandle setColor = Boostrap.createDynamicInvoker(
303     *     "color",
304     *     NashornCallSiteDescriptor.SET_PROPERTY,
305     *     void.class, Object.class, Object.class);
306     * Object obj = ...; // somehow obtain the object
307     * setColor.invokeExact(obj, Color.BLUE);
308     *     </pre>
309     *   </li>
310     *   <li>Set a property with variable name:
311     *     <pre>
312     * MethodHandle setProperty = Boostrap.createDynamicInvoker(
313     *     NameCodec.encode(""),
314     *     NashornCallSiteDescriptor.SET_PROPERTY,
315     *     void.class, Object.class, String.class, Object.class);
316     * Object obj = ...; // somehow obtain the object
317     * setProperty.invokeExact(obj, "color", Color.BLUE);
318     * setProperty.invokeExact(obj, "shape", Shape.CIRCLE);
319     *     </pre>
320     *   </li>
321     *   <li>Call a function on an object; note it's a two-step process: get the
322     *   method, then invoke the method. This is the actual:
323     *     <pre>
324     * MethodHandle findFooFunction = Boostrap.createDynamicInvoker(
325     *     "foo",
326     *     NashornCallSiteDescriptor.GET_METHOD,
327     *     Object.class, Object.class);
328     * Object obj = ...; // somehow obtain the object
329     * Object foo_fn = findFooFunction.invokeExact(obj);
330     * MethodHandle callFunctionWithTwoArgs = Boostrap.createDynamicCallInvoker(
331     *     Object.class, Object.class, Object.class, Object.class, Object.class);
332     * // Note: "call" operation takes a function, then a "this" value, then the arguments:
333     * Object foo_retval = callFunctionWithTwoArgs.invokeExact(foo_fn, obj, arg1, arg2);
334     *     </pre>
335     *   </li>
336     * </ul>
337     * Few additional remarks:
338     * <ul>
339     * <li>Just as Nashorn works with any Java object, the invokers returned
340     * from this method can also be applied to arbitrary Java objects in
341     * addition to Nashorn JavaScript objects.</li>
342     * <li>For invoking a named function on an object, you can also use the
343     * {@link InvokeByName} convenience class.</li>
344     * <li>There's no rule that the variable property identifier has to be a
345     * {@code String} for {@code GET_PROPERTY/SET_PROPERTY} and {@code int} for
346     * {@code GET_ELEMENT/SET_ELEMENT}. You can declare their type to be
347     * {@code int}, {@code double}, {@code Object}, and so on regardless of the
348     * kind of the operation.</li>
349     * <li>You can be as specific in parameter types as you want. E.g. if you
350     * know that the receiver of the operation will always be
351     * {@code ScriptObject}, you can pass {@code ScriptObject.class} as its
352     * parameter type. If you happen to link to a method that expects different
353     * types, (you can use these invokers on POJOs too, after all, and end up
354     * linking with their methods that have strongly-typed signatures), all
355     * necessary conversions allowed by either Java or JavaScript will be
356     * applied: if invoked methods specify either primitive or wrapped Java
357     * numeric types, or {@code String} or {@code boolean/Boolean}, then the
358     * parameters might be subjected to standard ECMAScript {@code ToNumber},
359     * {@code ToString}, and {@code ToBoolean} conversion, respectively. Less
360     * obviously, if the expected parameter type is a SAM type, and you pass a
361     * JavaScript function, a proxy object implementing the SAM type and
362     * delegating to the function will be passed. Linkage can often be optimized
363     * when linkers have more specific type information than "everything can be
364     * an object".</li>
365     * <li>You can also be as specific in return types as you want. For return
366     * types any necessary type conversion available in either Java or
367     * JavaScript will be automatically applied, similar to the process
368     * described for parameters, only in reverse direction: if you specify any
369     * either primitive or wrapped Java numeric type, or {@code String} or
370     * {@code boolean/Boolean}, then the return values will be subjected to
371     * standard ECMAScript {@code ToNumber}, {@code ToString}, and
372     * {@code ToBoolean} conversion, respectively. Less obviously, if the return
373     * type is a SAM type, and the return value is a JavaScript function, a
374     * proxy object implementing the SAM type and delegating to the function
375     * will be returned.</li>
376     * </ul>
377     * @param name name at the call site. Must not be null. Must be encoded
378     * using {@link NameCodec#encode(String)}. If the operation does not take a
379     * name, use empty string (also has to be encoded).
380     * @param flags the call site flags for the operation; see
381     * {@link NashornCallSiteDescriptor} for available flags. The most important
382     * part of the flags are the ones encoding the actual operation.
383     * @param rtype the return type for the operation
384     * @param ptypes the parameter types for the operation
385     * @return MethodHandle for invoking the operation.
386     */
387    public static MethodHandle createDynamicInvoker(final String name, final int flags, final Class<?> rtype, final Class<?>... ptypes) {
388        return bootstrap(MethodHandles.publicLookup(), name, MethodType.methodType(rtype, ptypes), flags).dynamicInvoker();
389    }
390
391    /**
392     * Returns a dynamic invoker for the {@link NashornCallSiteDescriptor#CALL}
393     * operation using the public lookup.
394     * @param rtype the return type for the operation
395     * @param ptypes the parameter types for the operation
396     * @return a dynamic invoker for the {@code CALL} operation.
397     */
398    public static MethodHandle createDynamicCallInvoker(final Class<?> rtype, final Class<?>... ptypes) {
399        return createDynamicInvoker("", NashornCallSiteDescriptor.CALL, rtype, ptypes);
400    }
401
402    /**
403     * Returns a dynamic invoker for a specified dynamic operation using the
404     * public lookup. Similar to
405     * {@link #createDynamicInvoker(String, int, Class, Class...)} but with
406     * already precomposed method type.
407     * @param name name at the call site.
408     * @param flags flags at the call site
409     * @param type the method type for the operation
410     * @return MethodHandle for invoking the operation.
411     */
412    public static MethodHandle createDynamicInvoker(final String name, final int flags, final MethodType type) {
413        return bootstrap(MethodHandles.publicLookup(), name, type, flags).dynamicInvoker();
414    }
415
416    /**
417     * Binds any object Nashorn can use as a [[Callable]] to a receiver and optionally arguments.
418     * @param callable the callable to bind
419     * @param boundThis the bound "this" value.
420     * @param boundArgs the bound arguments. Can be either null or empty array to signify no arguments are bound.
421     * @return a bound callable.
422     * @throws ECMAException with {@code TypeError} if the object is not a callable.
423     */
424    public static Object bindCallable(final Object callable, final Object boundThis, final Object[] boundArgs) {
425        if (callable instanceof ScriptFunction) {
426            return ((ScriptFunction)callable).createBound(boundThis, boundArgs);
427        } else if (callable instanceof BoundCallable) {
428            return ((BoundCallable)callable).bind(boundArgs);
429        } else if (isCallable(callable)) {
430            return new BoundCallable(callable, boundThis, boundArgs);
431        }
432        throw notFunction(callable);
433    }
434
435    /**
436     * Creates a super-adapter for an adapter, that is, an adapter to the adapter that allows invocation of superclass
437     * methods on it.
438     * @param adapter the original adapter
439     * @return a new adapter that can be used to invoke super methods on the original adapter.
440     */
441    public static Object createSuperAdapter(final Object adapter) {
442        return new JavaSuperAdapter(adapter);
443    }
444
445    /**
446     * If the given class is a reflection-specific class (anything in {@code java.lang.reflect} and
447     * {@code java.lang.invoke} package, as well a {@link Class} and any subclass of {@link ClassLoader}) and there is
448     * a security manager in the system, then it checks the {@code nashorn.JavaReflection} {@code RuntimePermission}.
449     * @param clazz the class being tested
450     * @param isStatic is access checked for static members (or instance members)
451     */
452    public static void checkReflectionAccess(final Class<?> clazz, final boolean isStatic) {
453        ReflectionCheckLinker.checkReflectionAccess(clazz, isStatic);
454    }
455
456    /**
457     * Returns the Nashorn's internally used dynamic linker's services object. Note that in code that is processing a
458     * linking request, you will normally use the {@code LinkerServices} object passed by whatever top-level linker
459     * invoked the linking (if the call site is in Nashorn-generated code, you'll get this object anyway). You should
460     * only resort to retrieving a linker services object using this method when you need some linker services (e.g.
461     * type converter method handles) outside of a code path that is linking a call site.
462     * @return Nashorn's internal dynamic linker's services object.
463     */
464    public static LinkerServices getLinkerServices() {
465        return dynamicLinker.getLinkerServices();
466    }
467
468    /**
469     * Takes a guarded invocation, and ensures its method and guard conform to the type of the call descriptor, using
470     * all type conversions allowed by the linker's services. This method is used by Nashorn's linkers as a last step
471     * before returning guarded invocations. Most of the code used to produce the guarded invocations does not make an
472     * effort to coordinate types of the methods, and so a final type adjustment before a guarded invocation is returned
473     * to the aggregating linker is the responsibility of the linkers themselves.
474     * @param inv the guarded invocation that needs to be type-converted. Can be null.
475     * @param linkerServices the linker services object providing the type conversions.
476     * @param desc the call site descriptor to whose method type the invocation needs to conform.
477     * @return the type-converted guarded invocation. If input is null, null is returned. If the input invocation
478     * already conforms to the requested type, it is returned unchanged.
479     */
480    static GuardedInvocation asTypeSafeReturn(final GuardedInvocation inv, final LinkerServices linkerServices, final CallSiteDescriptor desc) {
481        return inv == null ? null : inv.asTypeSafeReturn(linkerServices, desc.getMethodType());
482    }
483
484    /**
485     * Adapts the return type of the method handle with {@code explicitCastArguments} when it is an unboxing
486     * conversion. This will ensure that nulls are unwrapped to false or 0.
487     * @param target the target method handle
488     * @param newType the desired new type. Note that this method does not adapt the method handle completely to the
489     * new type, it only adapts the return type; this is allowed as per
490     * {@link DynamicLinkerFactory#setAutoConversionStrategy(MethodTypeConversionStrategy)}, which is what this method
491     * is used for.
492     * @return the method handle with adapted return type, if it required an unboxing conversion.
493     */
494    private static MethodHandle unboxReturnType(final MethodHandle target, final MethodType newType) {
495        final MethodType targetType = target.type();
496        final Class<?> oldReturnType = targetType.returnType();
497        final Class<?> newReturnType = newType.returnType();
498        if (TypeUtilities.isWrapperType(oldReturnType)) {
499            if (newReturnType.isPrimitive()) {
500                // The contract of setAutoConversionStrategy is such that the difference between newType and targetType
501                // can only be JLS method invocation conversions.
502                assert TypeUtilities.isMethodInvocationConvertible(oldReturnType, newReturnType);
503                return MethodHandles.explicitCastArguments(target, targetType.changeReturnType(newReturnType));
504            }
505        } else if (oldReturnType == void.class && newReturnType == Object.class) {
506            return MethodHandles.filterReturnValue(target, VOID_TO_OBJECT);
507        }
508        return target;
509    }
510}
511