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