Bootstrap.java revision 1504:252538e8c232
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.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 MethodHandles.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        case "ladd":
226            mh = JSType.ADD_EXACT_LONG.methodHandle();
227            break;
228        case "lsub":
229            mh = JSType.SUB_EXACT_LONG.methodHandle();
230            break;
231        case "lmul":
232            mh = JSType.MUL_EXACT_LONG.methodHandle();
233            break;
234        case "ldiv":
235            mh = JSType.DIV_EXACT_LONG.methodHandle();
236            break;
237        case "lrem":
238            mh = JSType.REM_EXACT_LONG.methodHandle();
239            break;
240        case "lneg":
241            mh = JSType.NEGATE_EXACT_LONG.methodHandle();
242            break;
243        default:
244            throw new AssertionError("unsupported math intrinsic");
245        }
246        return new ConstantCallSite(MH.insertArguments(mh, mh.type().parameterCount() - 1, programPoint));
247    }
248
249    /**
250     * Returns a dynamic invoker for a specified dynamic operation using the
251     * public lookup. You can use this method to create a method handle that
252     * when invoked acts completely as if it were a Nashorn-linked call site.
253     * Note that the available operations are encoded in the flags, see
254     * {@link NashornCallSiteDescriptor} operation constants. If the operation
255     * takes a name, it should be set otherwise empty name (not null) should be
256     * used. All names (including the empty one) should be encoded using
257     * {@link NameCodec#encode(String)}. Few examples:
258     * <ul>
259     *   <li>Get a named property with fixed name:
260     *     <pre>
261     * MethodHandle getColor = Boostrap.createDynamicInvoker(
262     *     "color",
263     *     NashornCallSiteDescriptor.GET_PROPERTY,
264     *     Object.class, Object.class);
265     * Object obj = ...; // somehow obtain the object
266     * Object color = getColor.invokeExact(obj);
267     *     </pre>
268     *   </li>
269     *   <li>Get a named property with variable name:
270     *     <pre>
271     * MethodHandle getProperty = Boostrap.createDynamicInvoker(
272     *     NameCodec.encode(""),
273     *     NashornCallSiteDescriptor.GET_PROPERTY,
274     *     Object.class, Object.class, String.class);
275     * Object obj = ...; // somehow obtain the object
276     * Object color = getProperty.invokeExact(obj, "color");
277     * Object shape = getProperty.invokeExact(obj, "shape");
278     *
279     * MethodHandle getNumProperty = Boostrap.createDynamicInvoker(
280     *     NameCodec.encode(""),
281     *     NashornCallSiteDescriptor.GET_ELEMENT,
282     *     Object.class, Object.class, int.class);
283     * Object elem42 = getNumProperty.invokeExact(obj, 42);
284     *     </pre>
285     *   </li>
286     *   <li>Set a named property with fixed name:
287     *     <pre>
288     * MethodHandle setColor = Boostrap.createDynamicInvoker(
289     *     "color",
290     *     NashornCallSiteDescriptor.SET_PROPERTY,
291     *     void.class, Object.class, Object.class);
292     * Object obj = ...; // somehow obtain the object
293     * setColor.invokeExact(obj, Color.BLUE);
294     *     </pre>
295     *   </li>
296     *   <li>Set a property with variable name:
297     *     <pre>
298     * MethodHandle setProperty = Boostrap.createDynamicInvoker(
299     *     NameCodec.encode(""),
300     *     NashornCallSiteDescriptor.SET_PROPERTY,
301     *     void.class, Object.class, String.class, Object.class);
302     * Object obj = ...; // somehow obtain the object
303     * setProperty.invokeExact(obj, "color", Color.BLUE);
304     * setProperty.invokeExact(obj, "shape", Shape.CIRCLE);
305     *     </pre>
306     *   </li>
307     *   <li>Call a function on an object; note it's a two-step process: get the
308     *   method, then invoke the method. This is the actual:
309     *     <pre>
310     * MethodHandle findFooFunction = Boostrap.createDynamicInvoker(
311     *     "foo",
312     *     NashornCallSiteDescriptor.GET_METHOD,
313     *     Object.class, Object.class);
314     * Object obj = ...; // somehow obtain the object
315     * Object foo_fn = findFooFunction.invokeExact(obj);
316     * MethodHandle callFunctionWithTwoArgs = Boostrap.createDynamicCallInvoker(
317     *     Object.class, Object.class, Object.class, Object.class, Object.class);
318     * // Note: "call" operation takes a function, then a "this" value, then the arguments:
319     * Object foo_retval = callFunctionWithTwoArgs.invokeExact(foo_fn, obj, arg1, arg2);
320     *     </pre>
321     *   </li>
322     * </ul>
323     * Few additional remarks:
324     * <ul>
325     * <li>Just as Nashorn works with any Java object, the invokers returned
326     * from this method can also be applied to arbitrary Java objects in
327     * addition to Nashorn JavaScript objects.</li>
328     * <li>For invoking a named function on an object, you can also use the
329     * {@link InvokeByName} convenience class.</li>
330     * <li>There's no rule that the variable property identifier has to be a
331     * {@code String} for {@code GET_PROPERTY/SET_PROPERTY} and {@code int} for
332     * {@code GET_ELEMENT/SET_ELEMENT}. You can declare their type to be
333     * {@code int}, {@code double}, {@code Object}, and so on regardless of the
334     * kind of the operation.</li>
335     * <li>You can be as specific in parameter types as you want. E.g. if you
336     * know that the receiver of the operation will always be
337     * {@code ScriptObject}, you can pass {@code ScriptObject.class} as its
338     * parameter type. If you happen to link to a method that expects different
339     * types, (you can use these invokers on POJOs too, after all, and end up
340     * linking with their methods that have strongly-typed signatures), all
341     * necessary conversions allowed by either Java or JavaScript will be
342     * applied: if invoked methods specify either primitive or wrapped Java
343     * numeric types, or {@code String} or {@code boolean/Boolean}, then the
344     * parameters might be subjected to standard ECMAScript {@code ToNumber},
345     * {@code ToString}, and {@code ToBoolean} conversion, respectively. Less
346     * obviously, if the expected parameter type is a SAM type, and you pass a
347     * JavaScript function, a proxy object implementing the SAM type and
348     * delegating to the function will be passed. Linkage can often be optimized
349     * when linkers have more specific type information than "everything can be
350     * an object".</li>
351     * <li>You can also be as specific in return types as you want. For return
352     * types any necessary type conversion available in either Java or
353     * JavaScript will be automatically applied, similar to the process
354     * described for parameters, only in reverse direction: if you specify any
355     * either primitive or wrapped Java numeric type, or {@code String} or
356     * {@code boolean/Boolean}, then the return values will be subjected to
357     * standard ECMAScript {@code ToNumber}, {@code ToString}, and
358     * {@code ToBoolean} conversion, respectively. Less obviously, if the return
359     * type is a SAM type, and the return value is a JavaScript function, a
360     * proxy object implementing the SAM type and delegating to the function
361     * will be returned.</li>
362     * </ul>
363     * @param name name at the call site. Must not be null. Must be encoded
364     * using {@link NameCodec#encode(String)}. If the operation does not take a
365     * name, use empty string (also has to be encoded).
366     * @param flags the call site flags for the operation; see
367     * {@link NashornCallSiteDescriptor} for available flags. The most important
368     * part of the flags are the ones encoding the actual operation.
369     * @param rtype the return type for the operation
370     * @param ptypes the parameter types for the operation
371     * @return MethodHandle for invoking the operation.
372     */
373    public static MethodHandle createDynamicInvoker(final String name, final int flags, final Class<?> rtype, final Class<?>... ptypes) {
374        return bootstrap(MethodHandles.publicLookup(), name, MethodType.methodType(rtype, ptypes), flags).dynamicInvoker();
375    }
376
377    /**
378     * Returns a dynamic invoker for the {@link NashornCallSiteDescriptor#CALL}
379     * operation using the public lookup.
380     * @param rtype the return type for the operation
381     * @param ptypes the parameter types for the operation
382     * @return a dynamic invoker for the {@code CALL} operation.
383     */
384    public static MethodHandle createDynamicCallInvoker(final Class<?> rtype, final Class<?>... ptypes) {
385        return createDynamicInvoker("", NashornCallSiteDescriptor.CALL, rtype, ptypes);
386    }
387
388    /**
389     * Returns a dynamic invoker for a specified dynamic operation using the
390     * public lookup. Similar to
391     * {@link #createDynamicInvoker(String, int, Class, Class...)} but with
392     * already precomposed method type.
393     * @param name name at the call site.
394     * @param flags flags at the call site
395     * @param type the method type for the operation
396     * @return MethodHandle for invoking the operation.
397     */
398    public static MethodHandle createDynamicInvoker(final String name, final int flags, final MethodType type) {
399        return bootstrap(MethodHandles.publicLookup(), name, type, flags).dynamicInvoker();
400    }
401
402    /**
403     * Binds any object Nashorn can use as a [[Callable]] to a receiver and optionally arguments.
404     * @param callable the callable to bind
405     * @param boundThis the bound "this" value.
406     * @param boundArgs the bound arguments. Can be either null or empty array to signify no arguments are bound.
407     * @return a bound callable.
408     * @throws ECMAException with {@code TypeError} if the object is not a callable.
409     */
410    public static Object bindCallable(final Object callable, final Object boundThis, final Object[] boundArgs) {
411        if (callable instanceof ScriptFunction) {
412            return ((ScriptFunction)callable).createBound(boundThis, boundArgs);
413        } else if (callable instanceof BoundCallable) {
414            return ((BoundCallable)callable).bind(boundArgs);
415        } else if (isCallable(callable)) {
416            return new BoundCallable(callable, boundThis, boundArgs);
417        }
418        throw notFunction(callable);
419    }
420
421    /**
422     * Creates a super-adapter for an adapter, that is, an adapter to the adapter that allows invocation of superclass
423     * methods on it.
424     * @param adapter the original adapter
425     * @return a new adapter that can be used to invoke super methods on the original adapter.
426     */
427    public static Object createSuperAdapter(final Object adapter) {
428        return new JavaSuperAdapter(adapter);
429    }
430
431    /**
432     * If the given class is a reflection-specific class (anything in {@code java.lang.reflect} and
433     * {@code java.lang.invoke} package, as well a {@link Class} and any subclass of {@link ClassLoader}) and there is
434     * a security manager in the system, then it checks the {@code nashorn.JavaReflection} {@code RuntimePermission}.
435     * @param clazz the class being tested
436     * @param isStatic is access checked for static members (or instance members)
437     */
438    public static void checkReflectionAccess(final Class<?> clazz, final boolean isStatic) {
439        ReflectionCheckLinker.checkReflectionAccess(clazz, isStatic);
440    }
441
442    /**
443     * Returns the Nashorn's internally used dynamic linker's services object. Note that in code that is processing a
444     * linking request, you will normally use the {@code LinkerServices} object passed by whatever top-level linker
445     * invoked the linking (if the call site is in Nashorn-generated code, you'll get this object anyway). You should
446     * only resort to retrieving a linker services object using this method when you need some linker services (e.g.
447     * type converter method handles) outside of a code path that is linking a call site.
448     * @return Nashorn's internal dynamic linker's services object.
449     */
450    public static LinkerServices getLinkerServices() {
451        return Context.getDynamicLinker().getLinkerServices();
452    }
453
454    /**
455     * Takes a guarded invocation, and ensures its method and guard conform to the type of the call descriptor, using
456     * all type conversions allowed by the linker's services. This method is used by Nashorn's linkers as a last step
457     * before returning guarded invocations. Most of the code used to produce the guarded invocations does not make an
458     * effort to coordinate types of the methods, and so a final type adjustment before a guarded invocation is returned
459     * to the aggregating linker is the responsibility of the linkers themselves.
460     * @param inv the guarded invocation that needs to be type-converted. Can be null.
461     * @param linkerServices the linker services object providing the type conversions.
462     * @param desc the call site descriptor to whose method type the invocation needs to conform.
463     * @return the type-converted guarded invocation. If input is null, null is returned. If the input invocation
464     * already conforms to the requested type, it is returned unchanged.
465     */
466    static GuardedInvocation asTypeSafeReturn(final GuardedInvocation inv, final LinkerServices linkerServices, final CallSiteDescriptor desc) {
467        return inv == null ? null : inv.asTypeSafeReturn(linkerServices, desc.getMethodType());
468    }
469
470    /**
471     * Adapts the return type of the method handle with {@code explicitCastArguments} when it is an unboxing
472     * conversion. This will ensure that nulls are unwrapped to false or 0.
473     * @param target the target method handle
474     * @param newType the desired new type. Note that this method does not adapt the method handle completely to the
475     * new type, it only adapts the return type; this is allowed as per
476     * {@link DynamicLinkerFactory#setAutoConversionStrategy(MethodTypeConversionStrategy)}, which is what this method
477     * is used for.
478     * @return the method handle with adapted return type, if it required an unboxing conversion.
479     */
480    private static MethodHandle unboxReturnType(final MethodHandle target, final MethodType newType) {
481        final MethodType targetType = target.type();
482        final Class<?> oldReturnType = targetType.returnType();
483        final Class<?> newReturnType = newType.returnType();
484        if (TypeUtilities.isWrapperType(oldReturnType)) {
485            if (newReturnType.isPrimitive()) {
486                // The contract of setAutoConversionStrategy is such that the difference between newType and targetType
487                // can only be JLS method invocation conversions.
488                assert TypeUtilities.isMethodInvocationConvertible(oldReturnType, newReturnType);
489                return MethodHandles.explicitCastArguments(target, targetType.changeReturnType(newReturnType));
490            }
491        } else if (oldReturnType == void.class && newReturnType == Object.class) {
492            return MethodHandles.filterReturnValue(target, VOID_TO_OBJECT);
493        }
494        return target;
495    }
496}
497