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