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