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.lookup.Lookup.MH;
  29 
  30 import java.lang.invoke.MethodHandle;
  31 import java.lang.invoke.MethodHandles;
  32 import java.lang.invoke.MethodType;
  33 import java.lang.reflect.Modifier;
  34 import java.security.AccessControlContext;
  35 import java.security.AccessController;
  36 import java.security.PrivilegedAction;
  37 import java.util.Collection;
  38 import java.util.Deque;
  39 import java.util.List;
  40 import java.util.Map;
  41 import java.util.Queue;
  42 import java.util.function.Supplier;
  43 import javax.script.Bindings;
  44 import jdk.dynalink.CallSiteDescriptor;
  45 import jdk.dynalink.SecureLookupSupplier;
  46 import jdk.dynalink.linker.ConversionComparator;
  47 import jdk.dynalink.linker.GuardedInvocation;
  48 import jdk.dynalink.linker.GuardingTypeConverterFactory;
  49 import jdk.dynalink.linker.LinkRequest;
  50 import jdk.dynalink.linker.LinkerServices;
  51 import jdk.dynalink.linker.TypeBasedGuardingDynamicLinker;
  52 import jdk.dynalink.linker.support.Guards;
  53 import jdk.dynalink.linker.support.Lookup;
  54 import jdk.nashorn.api.scripting.JSObject;
  55 import jdk.nashorn.api.scripting.ScriptObjectMirror;
  56 import jdk.nashorn.api.scripting.ScriptUtils;
  57 import jdk.nashorn.internal.codegen.CompilerConstants.Call;
  58 import jdk.nashorn.internal.objects.NativeArray;
  59 import jdk.nashorn.internal.runtime.AccessControlContextFactory;
  60 import jdk.nashorn.internal.runtime.JSType;
  61 import jdk.nashorn.internal.runtime.ListAdapter;
  62 import jdk.nashorn.internal.runtime.ScriptFunction;
  63 import jdk.nashorn.internal.runtime.ScriptObject;
  64 import jdk.nashorn.internal.runtime.Undefined;
  65 
  66 /**
  67  * This is the main dynamic linker for Nashorn. It is used for linking all {@link ScriptObject} and its subclasses (this
  68  * includes {@link ScriptFunction} and its subclasses) as well as {@link Undefined}.
  69  */
  70 final class NashornLinker implements TypeBasedGuardingDynamicLinker, GuardingTypeConverterFactory, ConversionComparator {
  71     private static final AccessControlContext GET_LOOKUP_PERMISSION_CONTEXT =
  72             AccessControlContextFactory.createAccessControlContext(SecureLookupSupplier.GET_LOOKUP_PERMISSION_NAME);
  73 
  74     private static final ClassValue<MethodHandle> ARRAY_CONVERTERS = new ClassValue<MethodHandle>() {
  75         @Override
  76         protected MethodHandle computeValue(final Class<?> type) {
  77             return createArrayConverter(type);
  78         }
  79     };
  80 
  81     /**
  82      * Returns true if {@code ScriptObject} is assignable from {@code type}, or it is {@code Undefined}.
  83      */
  84     @Override
  85     public boolean canLinkType(final Class<?> type) {
  86         return canLinkTypeStatic(type);
  87     }
  88 
  89     static boolean canLinkTypeStatic(final Class<?> type) {
  90         return ScriptObject.class.isAssignableFrom(type) || Undefined.class == type;
  91     }
  92 
  93     @Override
  94     public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices) throws Exception {
  95         final CallSiteDescriptor desc = request.getCallSiteDescriptor();
  96         return Bootstrap.asTypeSafeReturn(getGuardedInvocation(request, desc), linkerServices, desc);
  97     }
  98 
  99     private static GuardedInvocation getGuardedInvocation(final LinkRequest request, final CallSiteDescriptor desc) {
 100         final Object self = request.getReceiver();
 101 
 102         final GuardedInvocation inv;
 103         if (self instanceof ScriptObject) {
 104             inv = ((ScriptObject)self).lookup(desc, request);
 105         } else if (self instanceof Undefined) {
 106             inv = Undefined.lookup(desc);
 107         } else {
 108             throw new AssertionError(self.getClass().getName()); // Should never reach here.
 109         }
 110 
 111         return inv;
 112     }
 113 
 114     @Override
 115     public GuardedInvocation convertToType(final Class<?> sourceType, final Class<?> targetType, final Supplier<MethodHandles.Lookup> lookupSupplier) throws Exception {
 116         GuardedInvocation gi = convertToTypeNoCast(sourceType, targetType, lookupSupplier);
 117         if(gi == null) {
 118             gi = getSamTypeConverter(sourceType, targetType, lookupSupplier);
 119         }
 120         return gi == null ? null : gi.asType(MH.type(targetType, sourceType));
 121     }
 122 
 123     /**
 124      * Main part of the implementation of {@link GuardingTypeConverterFactory#convertToType(Class, Class)} that doesn't
 125      * care about adapting the method signature; that's done by the invoking method. Returns either a built-in
 126      * conversion to primitive (or primitive wrapper) Java types or to String, or a just-in-time generated converter to
 127      * a SAM type (if the target type is a SAM type).
 128      * @param sourceType the source type
 129      * @param targetType the target type
 130      * @return a guarded invocation that converts from the source type to the target type.
 131      * @throws Exception if something goes wrong
 132      */
 133     private static GuardedInvocation convertToTypeNoCast(final Class<?> sourceType, final Class<?> targetType, final Supplier<MethodHandles.Lookup> lookupSupplier) throws Exception {
 134         final MethodHandle mh = JavaArgumentConverters.getConverter(targetType);
 135         if (mh != null) {
 136             return new GuardedInvocation(mh, canLinkTypeStatic(sourceType) ? null : IS_NASHORN_OR_UNDEFINED_TYPE);
 137         }
 138 
 139         final GuardedInvocation arrayConverter = getArrayConverter(sourceType, targetType, lookupSupplier);
 140         if(arrayConverter != null) {
 141             return arrayConverter;
 142         }
 143 
 144         return getMirrorConverter(sourceType, targetType);
 145     }
 146 
 147     /**
 148      * Returns a guarded invocation that converts from a source type that is ScriptFunction, or a subclass or a
 149      * superclass of it) to a SAM type.
 150      * @param sourceType the source type (presumably ScriptFunction or a subclass or a superclass of it)
 151      * @param targetType the target type (presumably a SAM type)
 152      * @return a guarded invocation that converts from the source type to the target SAM type. null is returned if
 153      * either the source type is neither ScriptFunction, nor a subclass, nor a superclass of it, or if the target type
 154      * is not a SAM type.
 155      * @throws Exception if something goes wrong; generally, if there's an issue with creation of the SAM proxy type
 156      * constructor.
 157      */
 158     private static GuardedInvocation getSamTypeConverter(final Class<?> sourceType, final Class<?> targetType, final Supplier<MethodHandles.Lookup> lookupSupplier) throws Exception {
 159         // If source type is more generic than ScriptFunction class, we'll need to use a guard
 160         final boolean isSourceTypeGeneric = sourceType.isAssignableFrom(ScriptFunction.class);
 161 
 162         if ((isSourceTypeGeneric || ScriptFunction.class.isAssignableFrom(sourceType)) && isAutoConvertibleFromFunction(targetType)) {
 163             final MethodHandle ctor = JavaAdapterFactory.getConstructor(ScriptFunction.class, targetType, getCurrentLookup(lookupSupplier));
 164             assert ctor != null; // if isAutoConvertibleFromFunction() returned true, then ctor must exist.
 165             return new GuardedInvocation(ctor, isSourceTypeGeneric ? IS_SCRIPT_FUNCTION : null);
 166         }
 167         return null;
 168     }
 169 
 170     private static MethodHandles.Lookup getCurrentLookup(final Supplier<MethodHandles.Lookup> lookupSupplier) {
 171         return AccessController.doPrivileged(new PrivilegedAction<MethodHandles.Lookup>() {
 172             @Override
 173             public MethodHandles.Lookup run() {
 174                 return lookupSupplier.get();
 175             }
 176         }, GET_LOOKUP_PERMISSION_CONTEXT);
 177     }
 178 
 179     /**
 180      * Returns a guarded invocation that converts from a source type that is NativeArray to a Java array or List or
 181      * Queue or Deque or Collection type.
 182      * @param sourceType the source type (presumably NativeArray a superclass of it)
 183      * @param targetType the target type (presumably an array type, or List or Queue, or Deque, or Collection)
 184      * @return a guarded invocation that converts from the source type to the target type. null is returned if
 185      * either the source type is neither NativeArray, nor a superclass of it, or if the target type is not an array
 186      * type, List, Queue, Deque, or Collection.
 187      */
 188     private static GuardedInvocation getArrayConverter(final Class<?> sourceType, final Class<?> targetType, final Supplier<MethodHandles.Lookup> lookupSupplier) {
 189         final boolean isSourceTypeNativeArray = sourceType == NativeArray.class;
 190         // If source type is more generic than NativeArray class, we'll need to use a guard
 191         final boolean isSourceTypeGeneric = !isSourceTypeNativeArray && sourceType.isAssignableFrom(NativeArray.class);
 192 
 193         if (isSourceTypeNativeArray || isSourceTypeGeneric) {
 194             final MethodHandle guard = isSourceTypeGeneric ? IS_NATIVE_ARRAY : null;
 195             if(targetType.isArray()) {
 196                 final MethodHandle mh = ARRAY_CONVERTERS.get(targetType);
 197                 final MethodHandle mhWithLookup;
 198                 if (mh.type().parameterCount() == 2) {
 199                     assert mh.type().parameterType(1) == SecureLookupSupplier.class;
 200                     // We enter this branch when the array's ultimate component
 201                     // type is a SAM type; we use a handle to JSType.toJavaArrayWithLookup
 202                     // for these in the converter MH and must bind it here with
 203                     // a secure supplier for the current lookup. By retrieving
 204                     // the lookup, we'll also (correctly) inform the type
 205                     // converter that this array converter is lookup specific.
 206                     // We then need to wrap the returned lookup into a
 207                     // new SecureLookupSupplier in order to bind it to the
 208                     // JSType.toJavaArrayWithLookup() parameter.
 209                     mhWithLookup = MH.insertArguments(mh, 1,
 210                             new SecureLookupSupplier(getCurrentLookup(lookupSupplier)));
 211                 } else {
 212                     mhWithLookup = mh;
 213                 }
 214                 return new GuardedInvocation(mhWithLookup, guard);
 215             } else if(targetType == List.class) {
 216                 return new GuardedInvocation(TO_LIST, guard);
 217             } else if(targetType == Deque.class) {
 218                 return new GuardedInvocation(TO_DEQUE, guard);
 219             } else if(targetType == Queue.class) {
 220                 return new GuardedInvocation(TO_QUEUE, guard);
 221             } else if(targetType == Collection.class) {
 222                 return new GuardedInvocation(TO_COLLECTION, guard);
 223             }
 224         }
 225         return null;
 226     }
 227 
 228     private static MethodHandle createArrayConverter(final Class<?> type) {
 229         assert type.isArray();
 230 
 231         final Class<?> componentType = type.getComponentType();
 232         final Call converterCall;
 233         // Is the ultimate component type of this array a SAM type?
 234         if (isComponentTypeAutoConvertibleFromFunction(componentType)) {
 235             converterCall = JSType.TO_JAVA_ARRAY_WITH_LOOKUP;
 236         } else {
 237             converterCall = JSType.TO_JAVA_ARRAY;
 238         }
 239         final MethodHandle typeBoundConverter = MH.insertArguments(converterCall.methodHandle(), 1, componentType);
 240         return MH.asType(typeBoundConverter, typeBoundConverter.type().changeReturnType(type));
 241     }
 242 
 243     private static boolean isComponentTypeAutoConvertibleFromFunction(final Class<?> targetType) {
 244         if (targetType.isArray()) {
 245             return isComponentTypeAutoConvertibleFromFunction(targetType.getComponentType());
 246         }
 247         return isAutoConvertibleFromFunction(targetType);
 248     }
 249 
 250     private static GuardedInvocation getMirrorConverter(final Class<?> sourceType, final Class<?> targetType) {
 251         // Could've also used (targetType.isAssignableFrom(ScriptObjectMirror.class) && targetType != Object.class) but
 252         // it's probably better to explicitly spell out the supported target types
 253         if (targetType == Map.class || targetType == Bindings.class || targetType == JSObject.class || targetType == ScriptObjectMirror.class) {
 254             if (ScriptObject.class.isAssignableFrom(sourceType)) {
 255                 return new GuardedInvocation(CREATE_MIRROR);
 256             } else if (sourceType.isAssignableFrom(ScriptObject.class) || sourceType.isInterface()) {
 257                 return new GuardedInvocation(CREATE_MIRROR, IS_SCRIPT_OBJECT);
 258             }
 259         }
 260         return null;
 261     }
 262 
 263     private static boolean isAutoConvertibleFromFunction(final Class<?> clazz) {
 264         return isAbstractClass(clazz) && !ScriptObject.class.isAssignableFrom(clazz) &&
 265                 JavaAdapterFactory.isAutoConvertibleFromFunction(clazz);
 266     }
 267 
 268     /**
 269      * Utility method used by few other places in the code. Tests if the class has the abstract modifier and is not an
 270      * array class. For some reason, array classes have the abstract modifier set in HotSpot JVM, and we don't want to
 271      * treat array classes as abstract.
 272      * @param clazz the inspected class
 273      * @return true if the class is abstract and is not an array type.
 274      */
 275     static boolean isAbstractClass(final Class<?> clazz) {
 276         return Modifier.isAbstract(clazz.getModifiers()) && !clazz.isArray();
 277     }
 278 
 279 
 280     @Override
 281     public Comparison compareConversion(final Class<?> sourceType, final Class<?> targetType1, final Class<?> targetType2) {
 282         if(sourceType == NativeArray.class) {
 283             // Prefer lists, as they're less costly to create than arrays.
 284             if(isList(targetType1)) {
 285                 if(!isList(targetType2)) {
 286                     return Comparison.TYPE_1_BETTER;
 287                 }
 288             } else if(isList(targetType2)) {
 289                 return Comparison.TYPE_2_BETTER;
 290             }
 291             // Then prefer arrays
 292             if(targetType1.isArray()) {
 293                 if(!targetType2.isArray()) {
 294                     return Comparison.TYPE_1_BETTER;
 295                 }
 296             } else if(targetType2.isArray()) {
 297                 return Comparison.TYPE_2_BETTER;
 298             }
 299         }
 300         if(ScriptObject.class.isAssignableFrom(sourceType)) {
 301             // Prefer interfaces
 302             if(targetType1.isInterface()) {
 303                 if(!targetType2.isInterface()) {
 304                     return Comparison.TYPE_1_BETTER;
 305                 }
 306             } else if(targetType2.isInterface()) {
 307                 return Comparison.TYPE_2_BETTER;
 308             }
 309         }
 310         return Comparison.INDETERMINATE;
 311     }
 312 
 313     private static boolean isList(final Class<?> clazz) {
 314         return clazz == List.class || clazz == Deque.class;
 315     }
 316 
 317     private static final MethodHandle IS_SCRIPT_OBJECT = Guards.isInstance(ScriptObject.class, MH.type(Boolean.TYPE, Object.class));
 318     private static final MethodHandle IS_SCRIPT_FUNCTION = Guards.isInstance(ScriptFunction.class, MH.type(Boolean.TYPE, Object.class));
 319     private static final MethodHandle IS_NATIVE_ARRAY = Guards.isOfClass(NativeArray.class, MH.type(Boolean.TYPE, Object.class));
 320 
 321     private static final MethodHandle IS_NASHORN_OR_UNDEFINED_TYPE = findOwnMH("isNashornTypeOrUndefined", Boolean.TYPE, Object.class);
 322     private static final MethodHandle CREATE_MIRROR = findOwnMH("createMirror", Object.class, Object.class);
 323 
 324     private static final MethodHandle TO_COLLECTION;
 325     private static final MethodHandle TO_DEQUE;
 326     private static final MethodHandle TO_LIST;
 327     private static final MethodHandle TO_QUEUE;
 328     static {
 329         final MethodHandle listAdapterCreate = new Lookup(MethodHandles.lookup()).findStatic(
 330                 ListAdapter.class, "create", MethodType.methodType(ListAdapter.class, Object.class));
 331         TO_COLLECTION = asReturning(listAdapterCreate, Collection.class);
 332         TO_DEQUE = asReturning(listAdapterCreate, Deque.class);
 333         TO_LIST = asReturning(listAdapterCreate, List.class);
 334         TO_QUEUE = asReturning(listAdapterCreate, Queue.class);
 335     }
 336 
 337     private static MethodHandle asReturning(final MethodHandle mh, final Class<?> nrtype) {
 338         return mh.asType(mh.type().changeReturnType(nrtype));
 339     }
 340 
 341     @SuppressWarnings("unused")
 342     private static boolean isNashornTypeOrUndefined(final Object obj) {
 343         return obj instanceof ScriptObject || obj instanceof Undefined;
 344     }
 345 
 346     @SuppressWarnings("unused")
 347     private static Object createMirror(final Object obj) {
 348         return obj instanceof ScriptObject? ScriptUtils.wrap((ScriptObject)obj) : obj;
 349     }
 350 
 351     private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) {
 352         return MH.findStatic(MethodHandles.lookup(), NashornLinker.class, name, MH.type(rtype, types));
 353     }
 354 }
 355