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.linker.GuardedInvocation;
  40 import jdk.internal.dynalink.linker.LinkerServices;
  41 import jdk.nashorn.internal.codegen.CompilerConstants.Call;
  42 import jdk.nashorn.internal.codegen.RuntimeCallSite;
  43 import jdk.nashorn.internal.runtime.options.Options;
  44 
  45 /**
  46  * This class houses bootstrap method for invokedynamic instructions generated by compiler.
  47  */
  48 public final class Bootstrap {
  49     /** Reference to the seed boostrap function */
  50     public static final Call BOOTSTRAP = staticCallNoLookup(Bootstrap.class, "bootstrap", CallSite.class, Lookup.class, String.class, MethodType.class, int.class);
  51 
  52     // do not create me!!
  53     private Bootstrap() {
  54     }
  55 
  56     private static final DynamicLinker dynamicLinker;
  57     static {
  58         final DynamicLinkerFactory factory = new DynamicLinkerFactory();
  59         factory.setPrioritizedLinkers(new NashornLinker(), new NashornPrimitiveLinker(), new NashornStaticClassLinker(),
  60                 new JSObjectLinker(), new NioBufferLinker(), new ReflectionCheckLinker());
  61         factory.setFallbackLinkers(new BeansLinker(), new NashornBottomLinker());
  62         factory.setSyncOnRelink(true);
  63         final int relinkThreshold = Options.getIntProperty("nashorn.unstable.relink.threshold", -1);
  64         if (relinkThreshold > -1) {
  65             factory.setUnstableRelinkThreshold(relinkThreshold);
  66         }
  67         dynamicLinker = factory.createLinker();
  68     }
  69 
  70     /**
  71      * Create a call site and link it for Nashorn. This version of the method conforms to the invokedynamic bootstrap
  72      * method expected signature and is referenced from Nashorn generated bytecode as the bootstrap method for all
  73      * invokedynamic instructions.
  74      * @param lookup MethodHandle lookup. Ignored as Nashorn only uses public lookup.
  75      * @param opDesc Dynalink dynamic operation descriptor.
  76      * @param type   Method type.
  77      * @param flags  flags for call type, trace/profile etc.
  78      * @return CallSite with MethodHandle to appropriate method or null if not found.
  79      */
  80     public static CallSite bootstrap(final Lookup lookup, final String opDesc, final MethodType type, final int flags) {
  81         return dynamicLinker.link(LinkerCallSite.newLinkerCallSite(opDesc, type, flags));
  82     }
  83 
  84     /**
  85      * Bootstrapper for a specialized Runtime call
  86      *
  87      * @param lookup       lookup
  88      * @param initialName  initial name for callsite
  89      * @param type         method type for call site
  90      *
  91      * @return callsite for a runtime node
  92      */
  93     public static CallSite runtimeBootstrap(final MethodHandles.Lookup lookup, final String initialName, final MethodType type) {
  94         return new RuntimeCallSite(type, initialName);
  95     }
  96 
  97 
  98     /**
  99      * Returns a dynamic invoker for a specified dynamic operation. You can use this method to create a method handle
 100      * that when invoked acts completely as if it were a Nashorn-linked call site. An overview of available dynamic
 101      * operations can be found in the <a href="https://github.com/szegedi/dynalink/wiki/User-Guide-0.4">Dynalink User Guide</a>,
 102      * but we'll show few examples here:
 103      * <ul>
 104      *   <li>Get a named property with fixed name:
 105      *     <pre>
 106      * MethodHandle getColor = Boostrap.createDynamicInvoker("dyn:getProp:color", Object.class, Object.class);
 107      * Object obj = ...; // somehow obtain the object
 108      * Object color = getColor.invokeExact(obj);
 109      *     </pre>
 110      *   </li>
 111      *   <li>Get a named property with variable name:
 112      *     <pre>
 113      * MethodHandle getProperty = Boostrap.createDynamicInvoker("dyn:getElem", Object.class, Object.class, String.class);
 114      * Object obj = ...; // somehow obtain the object
 115      * Object color = getProperty.invokeExact(obj, "color");
 116      * Object shape = getProperty.invokeExact(obj, "shape");
 117      * MethodHandle getNumProperty = Boostrap.createDynamicInvoker("dyn:getElem", Object.class, Object.class, int.class);
 118      * Object elem42 = getNumProperty.invokeExact(obj, 42);
 119      *     </pre>
 120      *   </li>
 121      *   <li>Set a named property with fixed name:
 122      *     <pre>
 123      * MethodHandle setColor = Boostrap.createDynamicInvoker("dyn:setProp:color", void.class, Object.class, Object.class);
 124      * Object obj = ...; // somehow obtain the object
 125      * setColor.invokeExact(obj, Color.BLUE);
 126      *     </pre>
 127      *   </li>
 128      *   <li>Set a property with variable name:
 129      *     <pre>
 130      * MethodHandle setProperty = Boostrap.createDynamicInvoker("dyn:setElem", void.class, Object.class, String.class, Object.class);
 131      * Object obj = ...; // somehow obtain the object
 132      * setProperty.invokeExact(obj, "color", Color.BLUE);
 133      * setProperty.invokeExact(obj, "shape", Shape.CIRCLE);
 134      *     </pre>
 135      *   </li>
 136      *   <li>Call a function on an object; two-step variant. This is the actual variant used by Nashorn-generated code:
 137      *     <pre>
 138      * MethodHandle findFooFunction = Boostrap.createDynamicInvoker("dyn:getMethod:foo", Object.class, Object.class);
 139      * Object obj = ...; // somehow obtain the object
 140      * Object foo_fn = findFooFunction.invokeExact(obj);
 141      * MethodHandle callFunctionWithTwoArgs = Boostrap.createDynamicInvoker("dyn:call", Object.class, Object.class, Object.class, Object.class, Object.class);
 142      * // Note: "call" operation takes a function, then a "this" value, then the arguments:
 143      * Object foo_retval = callFunctionWithTwoArgs.invokeExact(foo_fn, obj, arg1, arg2);
 144      *     </pre>
 145      *   </li>
 146      *   <li>Call a function on an object; single-step variant. Although Nashorn doesn't use this variant and never
 147      *   emits any INVOKEDYNAMIC instructions with {@code dyn:getMethod}, it still supports this standard Dynalink
 148      *   operation:
 149      *     <pre>
 150      * MethodHandle callFunctionFooWithTwoArgs = Boostrap.createDynamicInvoker("dyn:callMethod:foo", Object.class, Object.class, Object.class, Object.class);
 151      * Object obj = ...; // somehow obtain the object
 152      * Object foo_retval = callFunctionFooWithTwoArgs.invokeExact(obj, arg1, arg2);
 153      *     </pre>
 154      *   </li>
 155      * </ul>
 156      * Few additional remarks:
 157      * <ul>
 158      * <li>Just as Nashorn works with any Java object, the invokers returned from this method can also be applied to
 159      * arbitrary Java objects in addition to Nashorn JavaScript objects.</li>
 160      * <li>For invoking a named function on an object, you can also use the {@link InvokeByName} convenience class.</li>
 161      * <li>For Nashorn objects {@code getElem}, {@code getProp}, and {@code getMethod} are handled almost identically,
 162      * since JavaScript doesn't distinguish between different kinds of properties on an object. Either can be used with
 163      * fixed property name or a variable property name. The only significant difference is handling of missing
 164      * properties: {@code getMethod} for a missing member will link to a potential invocation of
 165      * {@code __noSuchMethod__} on the object, {@code getProp} for a missing member will link to a potential invocation
 166      * of {@code __noSuchProperty__}, while {@code getElem} for a missing member will link to an empty getter.</li>
 167      * <li>In similar vein, {@code setElem} and {@code setProp} are handled identically on Nashorn objects.</li>
 168      * <li>There's no rule that the variable property identifier has to be a {@code String} for {@code getProp/setProp}
 169      * and {@code int} for {@code getElem/setElem}. You can declare their type to be {@code int}, {@code double},
 170      * {@code Object}, and so on regardless of the kind of the operation.</li>
 171      * <li>You can be as specific in parameter types as you want. E.g. if you know that the receiver of the operation
 172      * will always be {@code ScriptObject}, you can pass {@code ScriptObject.class} as its parameter type. If you happen
 173      * to link to a method that expects different types, (you can use these invokers on POJOs too, after all, and end up
 174      * linking with their methods that have strongly-typed signatures), all necessary conversions allowed by either Java
 175      * or JavaScript will be applied: if invoked methods specify either primitive or wrapped Java numeric types, or
 176      * {@code String} or {@code boolean/Boolean}, then the parameters might be subjected to standard ECMAScript
 177      * {@code ToNumber}, {@code ToString}, and {@code ToBoolean} conversion, respectively. Less obviously, if the
 178      * expected parameter type is a SAM type, and you pass a JavaScript function, a proxy object implementing the SAM
 179      * type and delegating to the function will be passed. Linkage can often be optimized when linkers have more
 180      * specific type information than "everything can be an object".</li>
 181      * <li>You can also be as specific in return types as you want. For return types any necessary type conversion
 182      * available in either Java or JavaScript will be automatically applied, similar to the process described for
 183      * parameters, only in reverse direction:  if you specify any either primitive or wrapped Java numeric type, or
 184      * {@code String} or {@code boolean/Boolean}, then the return values will be subjected to standard ECMAScript
 185      * {@code ToNumber}, {@code ToString}, and {@code ToBoolean} conversion, respectively. Less obviously, if the return
 186      * type is a SAM type, and the return value is a JavaScript function, a proxy object implementing the SAM type and
 187      * delegating to the function will be returned.</li>
 188      * </ul>
 189      * @param opDesc Dynalink dynamic operation descriptor.
 190      * @param rtype the return type for the operation
 191      * @param ptypes the parameter types for the operation
 192      * @return MethodHandle for invoking the operation.
 193      */
 194     public static MethodHandle createDynamicInvoker(final String opDesc, final Class<?> rtype, final Class<?>... ptypes) {
 195         return createDynamicInvoker(opDesc, MethodType.methodType(rtype, ptypes));
 196     }
 197 
 198     /**
 199      * Returns a dynamic invoker for a specified dynamic operation. Similar to
 200      * {@link #createDynamicInvoker(String, Class, Class...)} but with return and parameter types composed into a
 201      * method type in the signature. See the discussion of that method for details.
 202      * @param opDesc Dynalink dynamic operation descriptor.
 203      * @param type the method type for the operation
 204      * @return MethodHandle for invoking the operation.
 205      */
 206     public static MethodHandle createDynamicInvoker(final String opDesc, final MethodType type) {
 207         return bootstrap(null, opDesc, type, 0).dynamicInvoker();
 208     }
 209 
 210     /**
 211      * Returns the Nashorn's internally used dynamic linker's services object. Note that in code that is processing a
 212      * linking request, you will normally use the {@code LinkerServices} object passed by whatever top-level linker
 213      * invoked the linking (if the call site is in Nashorn-generated code, you'll get this object anyway). You should
 214      * only resort to retrieving a linker services object using this method when you need some linker services (e.g.
 215      * type converter method handles) outside of a code path that is linking a call site.
 216      * @return Nashorn's internal dynamic linker's services object.
 217      */
 218     public static LinkerServices getLinkerServices() {
 219         return dynamicLinker.getLinkerServices();
 220     }
 221 
 222     /**
 223      * Takes a guarded invocation, and ensures its method and guard conform to the type of the call descriptor, using
 224      * all type conversions allowed by the linker's services. This method is used by Nashorn's linkers as a last step
 225      * before returning guarded invocations to the callers. Most of the code used to produce the guarded invocations
 226      * does not make an effort to coordinate types of the methods, and so a final type adjustment before a guarded
 227      * invocation is returned is the responsibility of the linkers themselves.
 228      * @param inv the guarded invocation that needs to be type-converted. Can be null.
 229      * @param linkerServices the linker services object providing the type conversions.
 230      * @param desc the call site descriptor to whose method type the invocation needs to conform.
 231      * @return the type-converted guarded invocation. If input is null, null is returned. If the input invocation
 232      * already conforms to the requested type, it is returned unchanged.
 233      */
 234     static GuardedInvocation asType(final GuardedInvocation inv, final LinkerServices linkerServices, final CallSiteDescriptor desc) {
 235         return inv == null ? null : inv.asType(linkerServices, desc.getMethodType());
 236     }
 237 }
--- EOF ---