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