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 
  26 package jdk.nashorn.internal.runtime.linker;
  27 
  28 import static jdk.nashorn.internal.codegen.CompilerConstants.staticCallNoLookup;
  29 
  30 import java.lang.invoke.CallSite;
  31 import java.lang.invoke.MethodHandle;
  32 import java.lang.invoke.MethodHandles;
  33 import java.lang.invoke.MethodHandles.Lookup;
  34 import java.lang.invoke.MethodType;
  35 import jdk.internal.dynalink.CallSiteDescriptor;
  36 import jdk.internal.dynalink.DynamicLinker;
  37 import jdk.internal.dynalink.DynamicLinkerFactory;
  38 import jdk.internal.dynalink.beans.BeansLinker;
  39 import jdk.internal.dynalink.beans.StaticClass;
  40 import jdk.internal.dynalink.linker.GuardedInvocation;
  41 import jdk.internal.dynalink.linker.LinkerServices;
  42 import jdk.nashorn.api.scripting.JSObject;
  43 import jdk.nashorn.internal.codegen.CompilerConstants.Call;
  44 import jdk.nashorn.internal.codegen.RuntimeCallSite;
  45 import jdk.nashorn.internal.runtime.JSType;
  46 import jdk.nashorn.internal.runtime.ScriptFunction;
  47 import jdk.nashorn.internal.runtime.ScriptRuntime;
  48 import jdk.nashorn.internal.runtime.options.Options;
  49 
  50 /**
  51  * This class houses bootstrap method for invokedynamic instructions generated by compiler.
  52  */
  53 public final class Bootstrap {
  54     /** Reference to the seed boostrap function */
  55     public static final Call BOOTSTRAP = staticCallNoLookup(Bootstrap.class, "bootstrap", CallSite.class, Lookup.class, String.class, MethodType.class, int.class);
  56 
  57     // do not create me!!
  58     private Bootstrap() {
  59     }
  60 
  61     private static final DynamicLinker dynamicLinker;
  62     static {
  63         final DynamicLinkerFactory factory = new DynamicLinkerFactory();
  64         final NashornBeansLinker nashornBeansLinker = new NashornBeansLinker();
  65         final JSObjectLinker jsObjectLinker = new JSObjectLinker(nashornBeansLinker);
  66         factory.setPrioritizedLinkers(
  67             new NashornLinker(),
  68             new NashornPrimitiveLinker(),
  69             new NashornStaticClassLinker(),
  70             new BoundDynamicMethodLinker(),
  71             new JavaSuperAdapterLinker(),
  72             jsObjectLinker,
  73             new ReflectionCheckLinker());
  74         factory.setFallbackLinkers(nashornBeansLinker, new NashornBottomLinker());
  75         factory.setSyncOnRelink(true);
  76         final int relinkThreshold = Options.getIntProperty("nashorn.unstable.relink.threshold", -1);
  77         if (relinkThreshold > -1) {
  78             factory.setUnstableRelinkThreshold(relinkThreshold);
  79         }
  80 
  81         // Linkers for any additional language runtimes deployed alongside Nashorn will be picked up by the factory.
  82         factory.setClassLoader(Bootstrap.class.getClassLoader());
  83 
  84         dynamicLinker = factory.createLinker();
  85     }
  86 
  87     /**
  88      * Returns if the given object is a "callable"
  89      * @param obj object to be checked for callability
  90      * @return true if the obj is callable
  91      */
  92     public static boolean isCallable(final Object obj) {
  93         if (obj == ScriptRuntime.UNDEFINED || obj == null) {
  94             return false;
  95         }
  96 
  97         return obj instanceof ScriptFunction ||
  98             ((obj instanceof JSObject) && ((JSObject)obj).isFunction()) ||
  99             isDynamicMethod(obj) ||
 100             isFunctionalInterfaceObject(obj) ||
 101             obj instanceof StaticClass;
 102     }
 103 
 104     /**
 105      * Returns if the given object is a dynalink Dynamic method
 106      * @param obj object to be checked
 107      * @return true if the obj is a dynamic method
 108      */
 109     public static boolean isDynamicMethod(final Object obj) {
 110         return obj instanceof BoundDynamicMethod || BeansLinker.isDynamicMethod(obj);
 111     }
 112 
 113     /**
 114      * Returns if the given object is an instance of an interface annotated with
 115      * java.lang.FunctionalInterface
 116      * @param obj object to be checked
 117      * @return true if the obj is an instance of @FunctionalInterface interface
 118      */
 119     public static boolean isFunctionalInterfaceObject(final Object obj) {
 120         return !JSType.isPrimitive(obj) && (NashornBottomLinker.getFunctionalInterfaceMethod(obj.getClass()) != null);
 121     }
 122 
 123     /**
 124      * Create a call site and link it for Nashorn. This version of the method conforms to the invokedynamic bootstrap
 125      * method expected signature and is referenced from Nashorn generated bytecode as the bootstrap method for all
 126      * invokedynamic instructions.
 127      * @param lookup MethodHandle lookup. Ignored as Nashorn only uses public lookup.
 128      * @param opDesc Dynalink dynamic operation descriptor.
 129      * @param type   Method type.
 130      * @param flags  flags for call type, trace/profile etc.
 131      * @return CallSite with MethodHandle to appropriate method or null if not found.
 132      */
 133     public static CallSite bootstrap(final Lookup lookup, final String opDesc, final MethodType type, final int flags) {
 134         return dynamicLinker.link(LinkerCallSite.newLinkerCallSite(lookup, opDesc, type, flags));
 135     }
 136 
 137     /**
 138      * Bootstrapper for a specialized Runtime call
 139      *
 140      * @param lookup       lookup
 141      * @param initialName  initial name for callsite
 142      * @param type         method type for call site
 143      *
 144      * @return callsite for a runtime node
 145      */
 146     public static CallSite runtimeBootstrap(final MethodHandles.Lookup lookup, final String initialName, final MethodType type) {
 147         return new RuntimeCallSite(type, initialName);
 148     }
 149 
 150     /**
 151      * Returns a dynamic invoker for a specified dynamic operation using the public lookup. You can use this method to
 152      * create a method handle that when invoked acts completely as if it were a Nashorn-linked call site. An overview of
 153      * available dynamic operations can be found in the
 154      * <a href="https://github.com/szegedi/dynalink/wiki/User-Guide-0.6">Dynalink User Guide</a>, but we'll show few
 155      * examples here:
 156      * <ul>
 157      *   <li>Get a named property with fixed name:
 158      *     <pre>
 159      * MethodHandle getColor = Boostrap.createDynamicInvoker("dyn:getProp:color", Object.class, Object.class);
 160      * Object obj = ...; // somehow obtain the object
 161      * Object color = getColor.invokeExact(obj);
 162      *     </pre>
 163      *   </li>
 164      *   <li>Get a named property with variable name:
 165      *     <pre>
 166      * MethodHandle getProperty = Boostrap.createDynamicInvoker("dyn:getElem", Object.class, Object.class, String.class);
 167      * Object obj = ...; // somehow obtain the object
 168      * Object color = getProperty.invokeExact(obj, "color");
 169      * Object shape = getProperty.invokeExact(obj, "shape");
 170      * MethodHandle getNumProperty = Boostrap.createDynamicInvoker("dyn:getElem", Object.class, Object.class, int.class);
 171      * Object elem42 = getNumProperty.invokeExact(obj, 42);
 172      *     </pre>
 173      *   </li>
 174      *   <li>Set a named property with fixed name:
 175      *     <pre>
 176      * MethodHandle setColor = Boostrap.createDynamicInvoker("dyn:setProp:color", void.class, Object.class, Object.class);
 177      * Object obj = ...; // somehow obtain the object
 178      * setColor.invokeExact(obj, Color.BLUE);
 179      *     </pre>
 180      *   </li>
 181      *   <li>Set a property with variable name:
 182      *     <pre>
 183      * MethodHandle setProperty = Boostrap.createDynamicInvoker("dyn:setElem", void.class, Object.class, String.class, Object.class);
 184      * Object obj = ...; // somehow obtain the object
 185      * setProperty.invokeExact(obj, "color", Color.BLUE);
 186      * setProperty.invokeExact(obj, "shape", Shape.CIRCLE);
 187      *     </pre>
 188      *   </li>
 189      *   <li>Call a function on an object; two-step variant. This is the actual variant used by Nashorn-generated code:
 190      *     <pre>
 191      * MethodHandle findFooFunction = Boostrap.createDynamicInvoker("dyn:getMethod:foo", Object.class, Object.class);
 192      * Object obj = ...; // somehow obtain the object
 193      * Object foo_fn = findFooFunction.invokeExact(obj);
 194      * MethodHandle callFunctionWithTwoArgs = Boostrap.createDynamicInvoker("dyn:call", Object.class, Object.class, Object.class, Object.class, Object.class);
 195      * // Note: "call" operation takes a function, then a "this" value, then the arguments:
 196      * Object foo_retval = callFunctionWithTwoArgs.invokeExact(foo_fn, obj, arg1, arg2);
 197      *     </pre>
 198      *   </li>
 199      *   <li>Call a function on an object; single-step variant. Although Nashorn doesn't use this variant and never
 200      *   emits any INVOKEDYNAMIC instructions with {@code dyn:getMethod}, it still supports this standard Dynalink
 201      *   operation:
 202      *     <pre>
 203      * MethodHandle callFunctionFooWithTwoArgs = Boostrap.createDynamicInvoker("dyn:callMethod:foo", Object.class, Object.class, Object.class, Object.class);
 204      * Object obj = ...; // somehow obtain the object
 205      * Object foo_retval = callFunctionFooWithTwoArgs.invokeExact(obj, arg1, arg2);
 206      *     </pre>
 207      *   </li>
 208      * </ul>
 209      * Few additional remarks:
 210      * <ul>
 211      * <li>Just as Nashorn works with any Java object, the invokers returned from this method can also be applied to
 212      * arbitrary Java objects in addition to Nashorn JavaScript objects.</li>
 213      * <li>For invoking a named function on an object, you can also use the {@link InvokeByName} convenience class.</li>
 214      * <li>For Nashorn objects {@code getElem}, {@code getProp}, and {@code getMethod} are handled almost identically,
 215      * since JavaScript doesn't distinguish between different kinds of properties on an object. Either can be used with
 216      * fixed property name or a variable property name. The only significant difference is handling of missing
 217      * properties: {@code getMethod} for a missing member will link to a potential invocation of
 218      * {@code __noSuchMethod__} on the object, {@code getProp} for a missing member will link to a potential invocation
 219      * of {@code __noSuchProperty__}, while {@code getElem} for a missing member will link to an empty getter.</li>
 220      * <li>In similar vein, {@code setElem} and {@code setProp} are handled identically on Nashorn objects.</li>
 221      * <li>There's no rule that the variable property identifier has to be a {@code String} for {@code getProp/setProp}
 222      * and {@code int} for {@code getElem/setElem}. You can declare their type to be {@code int}, {@code double},
 223      * {@code Object}, and so on regardless of the kind of the operation.</li>
 224      * <li>You can be as specific in parameter types as you want. E.g. if you know that the receiver of the operation
 225      * will always be {@code ScriptObject}, you can pass {@code ScriptObject.class} as its parameter type. If you happen
 226      * to link to a method that expects different types, (you can use these invokers on POJOs too, after all, and end up
 227      * linking with their methods that have strongly-typed signatures), all necessary conversions allowed by either Java
 228      * or JavaScript will be applied: if invoked methods specify either primitive or wrapped Java numeric types, or
 229      * {@code String} or {@code boolean/Boolean}, then the parameters might be subjected to standard ECMAScript
 230      * {@code ToNumber}, {@code ToString}, and {@code ToBoolean} conversion, respectively. Less obviously, if the
 231      * expected parameter type is a SAM type, and you pass a JavaScript function, a proxy object implementing the SAM
 232      * type and delegating to the function will be passed. Linkage can often be optimized when linkers have more
 233      * specific type information than "everything can be an object".</li>
 234      * <li>You can also be as specific in return types as you want. For return types any necessary type conversion
 235      * available in either Java or JavaScript will be automatically applied, similar to the process described for
 236      * parameters, only in reverse direction:  if you specify any either primitive or wrapped Java numeric type, or
 237      * {@code String} or {@code boolean/Boolean}, then the return values will be subjected to standard ECMAScript
 238      * {@code ToNumber}, {@code ToString}, and {@code ToBoolean} conversion, respectively. Less obviously, if the return
 239      * type is a SAM type, and the return value is a JavaScript function, a proxy object implementing the SAM type and
 240      * delegating to the function will be returned.</li>
 241      * </ul>
 242      * @param opDesc Dynalink dynamic operation descriptor.
 243      * @param rtype the return type for the operation
 244      * @param ptypes the parameter types for the operation
 245      * @return MethodHandle for invoking the operation.
 246      */
 247     public static MethodHandle createDynamicInvoker(final String opDesc, final Class<?> rtype, final Class<?>... ptypes) {
 248         return createDynamicInvoker(opDesc, MethodType.methodType(rtype, ptypes));
 249     }
 250 
 251     /**
 252      * Returns a dynamic invoker for a specified dynamic operation using the public lookup. Similar to
 253      * {@link #createDynamicInvoker(String, Class, Class...)} but with return and parameter types composed into a
 254      * method type in the signature. See the discussion of that method for details.
 255      * @param opDesc Dynalink dynamic operation descriptor.
 256      * @param type the method type for the operation
 257      * @return MethodHandle for invoking the operation.
 258      */
 259     public static MethodHandle createDynamicInvoker(final String opDesc, final MethodType type) {
 260         return bootstrap(MethodHandles.publicLookup(), opDesc, type, 0).dynamicInvoker();
 261     }
 262 
 263     /**
 264      * Binds a bean dynamic method (returned by invoking {@code dyn:getMethod} on an object linked with
 265      * {@code BeansLinker} to a receiver.
 266      * @param dynamicMethod the dynamic method to bind
 267      * @param boundThis the bound "this" value.
 268      * @return a bound dynamic method.
 269      */
 270     public static Object bindDynamicMethod(Object dynamicMethod, Object boundThis) {
 271         return new BoundDynamicMethod(dynamicMethod, boundThis);
 272     }
 273 
 274     /**
 275      * Creates a super-adapter for an adapter, that is, an adapter to the adapter that allows invocation of superclass
 276      * methods on it.
 277      * @param adapter the original adapter
 278      * @return a new adapter that can be used to invoke super methods on the original adapter.
 279      */
 280     public static Object createSuperAdapter(final Object adapter) {
 281         return new JavaSuperAdapter(adapter);
 282     }
 283 
 284     /**
 285      * If the given class is a reflection-specific class (anything in {@code java.lang.reflect} and
 286      * {@code java.lang.invoke} package, as well a {@link Class} and any subclass of {@link ClassLoader}) and there is
 287      * a security manager in the system, then it checks the {@code nashorn.JavaReflection} {@code RuntimePermission}.
 288      * @param clazz the class being tested
 289      * @param isStatic is access checked for static members (or instance members)
 290      */
 291     public static void checkReflectionAccess(Class<?> clazz, boolean isStatic) {
 292         ReflectionCheckLinker.checkReflectionAccess(clazz, isStatic);
 293     }
 294 
 295     /**
 296      * Returns the Nashorn's internally used dynamic linker's services object. Note that in code that is processing a
 297      * linking request, you will normally use the {@code LinkerServices} object passed by whatever top-level linker
 298      * invoked the linking (if the call site is in Nashorn-generated code, you'll get this object anyway). You should
 299      * only resort to retrieving a linker services object using this method when you need some linker services (e.g.
 300      * type converter method handles) outside of a code path that is linking a call site.
 301      * @return Nashorn's internal dynamic linker's services object.
 302      */
 303     public static LinkerServices getLinkerServices() {
 304         return dynamicLinker.getLinkerServices();
 305     }
 306 
 307     /**
 308      * Takes a guarded invocation, and ensures its method and guard conform to the type of the call descriptor, using
 309      * all type conversions allowed by the linker's services. This method is used by Nashorn's linkers as a last step
 310      * before returning guarded invocations to the callers. Most of the code used to produce the guarded invocations
 311      * does not make an effort to coordinate types of the methods, and so a final type adjustment before a guarded
 312      * invocation is returned is the responsibility of the linkers themselves.
 313      * @param inv the guarded invocation that needs to be type-converted. Can be null.
 314      * @param linkerServices the linker services object providing the type conversions.
 315      * @param desc the call site descriptor to whose method type the invocation needs to conform.
 316      * @return the type-converted guarded invocation. If input is null, null is returned. If the input invocation
 317      * already conforms to the requested type, it is returned unchanged.
 318      */
 319     static GuardedInvocation asType(final GuardedInvocation inv, final LinkerServices linkerServices, final CallSiteDescriptor desc) {
 320         return inv == null ? null : inv.asType(linkerServices, desc.getMethodType());
 321     }
 322 }
--- EOF ---