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