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