/* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.nashorn.internal.runtime.linker; import static jdk.nashorn.internal.codegen.CompilerConstants.staticCallNoLookup; import static jdk.nashorn.internal.runtime.ECMAErrors.typeError; import java.lang.invoke.CallSite; import java.lang.invoke.ConstantCallSite; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.invoke.MethodType; import jdk.dynalink.CallSiteDescriptor; import jdk.dynalink.DynamicLinker; import jdk.dynalink.DynamicLinkerFactory; import jdk.dynalink.beans.BeansLinker; import jdk.dynalink.beans.StaticClass; import jdk.dynalink.linker.GuardedInvocation; import jdk.dynalink.linker.GuardedInvocationTransformer; import jdk.dynalink.linker.LinkRequest; import jdk.dynalink.linker.LinkerServices; import jdk.dynalink.linker.MethodTypeConversionStrategy; import jdk.dynalink.linker.support.TypeUtilities; import jdk.nashorn.api.scripting.JSObject; import jdk.nashorn.internal.codegen.CompilerConstants.Call; import jdk.nashorn.internal.lookup.MethodHandleFactory; import jdk.nashorn.internal.lookup.MethodHandleFunctionality; import jdk.nashorn.internal.runtime.Context; import jdk.nashorn.internal.runtime.ECMAException; import jdk.nashorn.internal.runtime.JSType; import jdk.nashorn.internal.runtime.OptimisticReturnFilters; import jdk.nashorn.internal.runtime.ScriptFunction; import jdk.nashorn.internal.runtime.ScriptRuntime; /** * This class houses bootstrap method for invokedynamic instructions generated by compiler. */ public final class Bootstrap { /** Reference to the seed boostrap function */ public static final Call BOOTSTRAP = staticCallNoLookup(Bootstrap.class, "bootstrap", CallSite.class, Lookup.class, String.class, MethodType.class, int.class); private static final MethodHandleFunctionality MH = MethodHandleFactory.getFunctionality(); private static final MethodHandle VOID_TO_OBJECT = MH.constant(Object.class, ScriptRuntime.UNDEFINED); // do not create me!! private Bootstrap() { } /** * Creates a Nashorn dynamic linker with the given app class loader. * @param appLoader the app class loader. It will be used to discover * additional language runtime linkers (if any). * @param unstableRelinkThreshold the unstable relink threshold * @return a newly created dynamic linker. */ public static DynamicLinker createDynamicLinker(final ClassLoader appLoader, final int unstableRelinkThreshold) { final DynamicLinkerFactory factory = new DynamicLinkerFactory(); final NashornBeansLinker nashornBeansLinker = new NashornBeansLinker(); factory.setPrioritizedLinkers( new NashornLinker(), new NashornPrimitiveLinker(), new NashornStaticClassLinker(), new BoundCallableLinker(), new JavaSuperAdapterLinker(), new JSObjectLinker(nashornBeansLinker), new BrowserJSObjectLinker(nashornBeansLinker), new ReflectionCheckLinker()); factory.setFallbackLinkers(nashornBeansLinker, new NashornBottomLinker()); factory.setSyncOnRelink(true); factory.setPrelinkTransformer(new GuardedInvocationTransformer() { @Override public GuardedInvocation filter(final GuardedInvocation inv, final LinkRequest request, final LinkerServices linkerServices) { final CallSiteDescriptor desc = request.getCallSiteDescriptor(); return OptimisticReturnFilters.filterOptimisticReturnValue(inv, desc).asType(linkerServices, desc.getMethodType()); } }); factory.setAutoConversionStrategy(new MethodTypeConversionStrategy() { @Override public MethodHandle asType(final MethodHandle target, final MethodType newType) { return unboxReturnType(target, newType); } }); factory.setInternalObjectsFilter(NashornBeansLinker.createHiddenObjectFilter()); factory.setUnstableRelinkThreshold(unstableRelinkThreshold); // Linkers for any additional language runtimes deployed alongside Nashorn will be picked up by the factory. factory.setClassLoader(appLoader); return factory.createLinker(); } /** * Returns if the given object is a "callable" * @param obj object to be checked for callability * @return true if the obj is callable */ public static boolean isCallable(final Object obj) { if (obj == ScriptRuntime.UNDEFINED || obj == null) { return false; } return obj instanceof ScriptFunction || isJSObjectFunction(obj) || BeansLinker.isDynamicMethod(obj) || obj instanceof BoundCallable || isFunctionalInterfaceObject(obj) || obj instanceof StaticClass; } /** * Returns true if the given object is a strict callable * @param callable the callable object to be checked for strictness * @return true if the obj is a strict callable, false if it is a non-strict callable. * @throws ECMAException with {@code TypeError} if the object is not a callable. */ public static boolean isStrictCallable(final Object callable) { if (callable instanceof ScriptFunction) { return ((ScriptFunction)callable).isStrict(); } else if (isJSObjectFunction(callable)) { return ((JSObject)callable).isStrictFunction(); } else if (callable instanceof BoundCallable) { return isStrictCallable(((BoundCallable)callable).getCallable()); } else if (BeansLinker.isDynamicMethod(callable) || callable instanceof StaticClass) { return false; } throw notFunction(callable); } private static ECMAException notFunction(final Object obj) { return typeError("not.a.function", ScriptRuntime.safeToString(obj)); } private static boolean isJSObjectFunction(final Object obj) { return obj instanceof JSObject && ((JSObject)obj).isFunction(); } /** * Returns if the given object is a dynalink Dynamic method * @param obj object to be checked * @return true if the obj is a dynamic method */ public static boolean isDynamicMethod(final Object obj) { return BeansLinker.isDynamicMethod(obj instanceof BoundCallable ? ((BoundCallable)obj).getCallable() : obj); } /** * Returns if the given object is an instance of an interface annotated with * java.lang.FunctionalInterface * @param obj object to be checked * @return true if the obj is an instance of @FunctionalInterface interface */ public static boolean isFunctionalInterfaceObject(final Object obj) { return !JSType.isPrimitive(obj) && (NashornBeansLinker.getFunctionalInterfaceMethodName(obj.getClass()) != null); } /** * Create a call site and link it for Nashorn. This version of the method conforms to the invokedynamic bootstrap * method expected signature and is referenced from Nashorn generated bytecode as the bootstrap method for all * invokedynamic instructions. * @param lookup MethodHandle lookup. Ignored as Nashorn only uses public lookup. * @param opDesc Dynalink dynamic operation descriptor. * @param type Method type. * @param flags flags for call type, trace/profile etc. * @return CallSite with MethodHandle to appropriate method or null if not found. */ public static CallSite bootstrap(final Lookup lookup, final String opDesc, final MethodType type, final int flags) { return Context.getDynamicLinker(lookup.lookupClass()).link(LinkerCallSite.newLinkerCallSite(lookup, opDesc, type, flags)); } /** * Boostrapper for math calls that may overflow * @param lookup lookup * @param name name of operation * @param type method type * @param programPoint program point to bind to callsite * * @return callsite for a math intrinsic node */ public static CallSite mathBootstrap(final Lookup lookup, final String name, final MethodType type, final int programPoint) { final MethodHandle mh; switch (name) { case "iadd": mh = JSType.ADD_EXACT.methodHandle(); break; case "isub": mh = JSType.SUB_EXACT.methodHandle(); break; case "imul": mh = JSType.MUL_EXACT.methodHandle(); break; case "idiv": mh = JSType.DIV_EXACT.methodHandle(); break; case "irem": mh = JSType.REM_EXACT.methodHandle(); break; case "ineg": mh = JSType.NEGATE_EXACT.methodHandle(); break; default: throw new AssertionError("unsupported math intrinsic"); } return new ConstantCallSite(MH.insertArguments(mh, mh.type().parameterCount() - 1, programPoint)); } /** * Returns a dynamic invoker for a specified dynamic operation using the * public lookup. You can use this method to create a method handle that * when invoked acts completely as if it were a Nashorn-linked call site. * Note that the available operations are encoded in the flags, see * {@link NashornCallSiteDescriptor} operation constants. If the operation * takes a name, it should be set otherwise empty name (not null) should be * used. All names (including the empty one) should be encoded using * {@link NameCodec#encode(String)}. Few examples: *
* MethodHandle getColor = Boostrap.createDynamicInvoker( * "color", * NashornCallSiteDescriptor.GET_PROPERTY, * Object.class, Object.class); * Object obj = ...; // somehow obtain the object * Object color = getColor.invokeExact(obj); **
* MethodHandle getProperty = Boostrap.createDynamicInvoker( * NameCodec.encode(""), * NashornCallSiteDescriptor.GET_PROPERTY, * Object.class, Object.class, String.class); * Object obj = ...; // somehow obtain the object * Object color = getProperty.invokeExact(obj, "color"); * Object shape = getProperty.invokeExact(obj, "shape"); * * MethodHandle getNumProperty = Boostrap.createDynamicInvoker( * NameCodec.encode(""), * NashornCallSiteDescriptor.GET_ELEMENT, * Object.class, Object.class, int.class); * Object elem42 = getNumProperty.invokeExact(obj, 42); **
* MethodHandle setColor = Boostrap.createDynamicInvoker( * "color", * NashornCallSiteDescriptor.SET_PROPERTY, * void.class, Object.class, Object.class); * Object obj = ...; // somehow obtain the object * setColor.invokeExact(obj, Color.BLUE); **
* MethodHandle setProperty = Boostrap.createDynamicInvoker( * NameCodec.encode(""), * NashornCallSiteDescriptor.SET_PROPERTY, * void.class, Object.class, String.class, Object.class); * Object obj = ...; // somehow obtain the object * setProperty.invokeExact(obj, "color", Color.BLUE); * setProperty.invokeExact(obj, "shape", Shape.CIRCLE); **
* MethodHandle findFooFunction = Boostrap.createDynamicInvoker( * "foo", * NashornCallSiteDescriptor.GET_METHOD, * Object.class, Object.class); * Object obj = ...; // somehow obtain the object * Object foo_fn = findFooFunction.invokeExact(obj); * MethodHandle callFunctionWithTwoArgs = Boostrap.createDynamicCallInvoker( * Object.class, Object.class, Object.class, Object.class, Object.class); * // Note: "call" operation takes a function, then a "this" value, then the arguments: * Object foo_retval = callFunctionWithTwoArgs.invokeExact(foo_fn, obj, arg1, arg2); **