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.reflect.Modifier; 33 import java.util.Deque; 34 import java.util.List; 35 import jdk.internal.dynalink.CallSiteDescriptor; 36 import jdk.internal.dynalink.linker.ConversionComparator; 37 import jdk.internal.dynalink.linker.GuardedInvocation; 38 import jdk.internal.dynalink.linker.GuardingTypeConverterFactory; 39 import jdk.internal.dynalink.linker.LinkRequest; 40 import jdk.internal.dynalink.linker.LinkerServices; 41 import jdk.internal.dynalink.linker.TypeBasedGuardingDynamicLinker; 42 import jdk.internal.dynalink.support.Guards; 43 import jdk.nashorn.internal.objects.NativeArray; 44 import jdk.nashorn.internal.runtime.JSType; 45 import jdk.nashorn.internal.runtime.ScriptFunction; 46 import jdk.nashorn.internal.runtime.ScriptObject; 47 import jdk.nashorn.internal.runtime.Undefined; 48 49 /** 50 * This is the main dynamic linker for Nashorn. It is used for linking all {@link ScriptObject} and its subclasses (this 51 * includes {@link ScriptFunction} and its subclasses) as well as {@link Undefined}. 52 */ 53 final class NashornLinker implements TypeBasedGuardingDynamicLinker, GuardingTypeConverterFactory, ConversionComparator { 54 private static final ClassValue<MethodHandle> ARRAY_CONVERTERS = new ClassValue<MethodHandle>() { 55 @Override 56 protected MethodHandle computeValue(Class<?> type) { 57 return createArrayConverter(type); 58 } 59 }; 60 61 /** 62 * Returns true if {@code ScriptObject} is assignable from {@code type}, or it is {@code Undefined}. 63 */ 64 @Override 65 public boolean canLinkType(final Class<?> type) { 66 return canLinkTypeStatic(type); 67 } 68 69 static boolean canLinkTypeStatic(final Class<?> type) { 70 return ScriptObject.class.isAssignableFrom(type) || Undefined.class == type; 71 } 72 73 @Override 74 public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices) throws Exception { 75 final LinkRequest requestWithoutContext = request.withoutRuntimeContext(); // Nashorn has no runtime context 76 final Object self = requestWithoutContext.getReceiver(); 77 final CallSiteDescriptor desc = requestWithoutContext.getCallSiteDescriptor(); 78 79 if (desc.getNameTokenCount() < 2 || !"dyn".equals(desc.getNameToken(CallSiteDescriptor.SCHEME))) { 80 // We only support standard "dyn:*[:*]" operations 81 return null; 82 } 83 84 final GuardedInvocation inv; 85 if (self instanceof ScriptObject) { 86 inv = ((ScriptObject)self).lookup(desc, request); 87 } else if (self instanceof Undefined) { 88 inv = Undefined.lookup(desc); 89 } else { 90 throw new AssertionError(); // Should never reach here. 91 } 92 93 return Bootstrap.asType(inv, linkerServices, desc); 94 } 95 96 @Override 97 public GuardedInvocation convertToType(final Class<?> sourceType, final Class<?> targetType) throws Exception { 98 final GuardedInvocation gi = convertToTypeNoCast(sourceType, targetType); 99 return gi == null ? null : gi.asType(MH.type(targetType, sourceType)); 100 } 101 102 /** 103 * Main part of the implementation of {@link GuardingTypeConverterFactory#convertToType(Class, Class)} that doesn't 104 * care about adapting the method signature; that's done by the invoking method. Returns either a built-in 105 * conversion to primitive (or primitive wrapper) Java types or to String, or a just-in-time generated converter to 106 * a SAM type (if the target type is a SAM type). 107 * @param sourceType the source type 108 * @param targetType the target type 109 * @return a guarded invocation that converts from the source type to the target type. 110 * @throws Exception if something goes wrong 111 */ 112 private static GuardedInvocation convertToTypeNoCast(final Class<?> sourceType, final Class<?> targetType) throws Exception { 113 final MethodHandle mh = JavaArgumentConverters.getConverter(targetType); 114 if (mh != null) { 115 return new GuardedInvocation(mh, canLinkTypeStatic(sourceType) ? null : IS_NASHORN_OR_UNDEFINED_TYPE); 116 } 117 118 GuardedInvocation inv = getArrayConverter(sourceType, targetType); 119 if(inv != null) { 120 return inv; 121 } 122 123 return getSamTypeConverter(sourceType, targetType); 124 } 125 126 /** 127 * Returns a guarded invocation that converts from a source type that is ScriptFunction, or a subclass or a 128 * superclass of it) to a SAM type. 129 * @param sourceType the source type (presumably ScriptFunction or a subclass or a superclass of it) 130 * @param targetType the target type (presumably a SAM type) 131 * @return a guarded invocation that converts from the source type to the target SAM type. null is returned if 132 * either the source type is neither ScriptFunction, nor a subclass, nor a superclass of it, or if the target type 133 * is not a SAM type. 134 * @throws Exception if something goes wrong; generally, if there's an issue with creation of the SAM proxy type 135 * constructor. 136 */ 137 private static GuardedInvocation getSamTypeConverter(final Class<?> sourceType, final Class<?> targetType) throws Exception { 138 // If source type is more generic than ScriptFunction class, we'll need to use a guard 139 final boolean isSourceTypeGeneric = sourceType.isAssignableFrom(ScriptFunction.class); 140 141 if ((isSourceTypeGeneric || ScriptFunction.class.isAssignableFrom(sourceType)) && isAutoConvertibleFromFunction(targetType)) { 142 final MethodHandle ctor = JavaAdapterFactory.getConstructor(ScriptFunction.class, targetType); 143 assert ctor != null; // if isAutoConvertibleFromFunction() returned true, then ctor must exist. 144 return new GuardedInvocation(ctor, isSourceTypeGeneric ? IS_SCRIPT_FUNCTION : null); 145 } 146 return null; 147 } 148 149 /** 150 * Returns a guarded invocation that converts from a source type that is NativeArray to a Java array or List or 151 * Deque type. 152 * @param sourceType the source type (presumably NativeArray a superclass of it) 153 * @param targetType the target type (presumably an array type, or List or Deque) 154 * @return a guarded invocation that converts from the source type to the target type. null is returned if 155 * either the source type is neither NativeArray, nor a superclass of it, or if the target type is not an array 156 * type, List, or Deque. 157 */ 158 private static GuardedInvocation getArrayConverter(final Class<?> sourceType, final Class<?> targetType) { 159 final boolean isSourceTypeNativeArray = sourceType == NativeArray.class; 160 // If source type is more generic than ScriptFunction class, we'll need to use a guard 161 final boolean isSourceTypeGeneric = !isSourceTypeNativeArray && sourceType.isAssignableFrom(NativeArray.class); 162 163 if (isSourceTypeNativeArray || isSourceTypeGeneric) { 164 final MethodHandle guard = isSourceTypeGeneric ? IS_NATIVE_ARRAY : null; 165 if(targetType.isArray()) { 166 return new GuardedInvocation(ARRAY_CONVERTERS.get(targetType), guard); 167 } 168 if(targetType == List.class) { 169 return new GuardedInvocation(JSType.TO_JAVA_LIST.methodHandle(), guard); 170 } 171 if(targetType == Deque.class) { 172 return new GuardedInvocation(JSType.TO_JAVA_DEQUE.methodHandle(), guard); 173 } 174 } 175 return null; 176 } 177 178 private static MethodHandle createArrayConverter(final Class<?> type) { 179 assert type.isArray(); 180 final MethodHandle converter = MH.insertArguments(JSType.TO_JAVA_ARRAY.methodHandle(), 1, type.getComponentType()); 181 return MH.asType(converter, converter.type().changeReturnType(type)); 182 } 183 184 private static boolean isAutoConvertibleFromFunction(final Class<?> clazz) { 185 return isAbstractClass(clazz) && !ScriptObject.class.isAssignableFrom(clazz) && 186 JavaAdapterFactory.isAutoConvertibleFromFunction(clazz); 187 } 188 189 /** 190 * Utility method used by few other places in the code. Tests if the class has the abstract modifier and is not an 191 * array class. For some reason, array classes have the abstract modifier set in HotSpot JVM, and we don't want to 192 * treat array classes as abstract. 193 * @param clazz the inspected class 194 * @return true if the class is abstract and is not an array type. 195 */ 196 static boolean isAbstractClass(final Class<?> clazz) { 197 return Modifier.isAbstract(clazz.getModifiers()) && !clazz.isArray(); 198 } 199 200 201 @Override 202 public Comparison compareConversion(final Class<?> sourceType, final Class<?> targetType1, final Class<?> targetType2) { 203 if(sourceType == NativeArray.class) { 204 // Prefer lists, as they're less costly to create than arrays. 205 if(isList(targetType1)) { 206 if(!isList(targetType2)) { 207 return Comparison.TYPE_1_BETTER; 208 } 209 } else if(isList(targetType2)) { 210 return Comparison.TYPE_2_BETTER; 211 } 212 // Then prefer arrays 213 if(targetType1.isArray()) { 214 if(!targetType2.isArray()) { 215 return Comparison.TYPE_1_BETTER; 216 } 217 } else if(targetType2.isArray()) { 218 return Comparison.TYPE_2_BETTER; 219 } 220 } 221 if(ScriptObject.class.isAssignableFrom(sourceType)) { 222 // Prefer interfaces 223 if(targetType1.isInterface()) { 224 if(!targetType2.isInterface()) { 225 return Comparison.TYPE_1_BETTER; 226 } 227 } else if(targetType2.isInterface()) { 228 return Comparison.TYPE_2_BETTER; 229 } 230 } 231 return Comparison.INDETERMINATE; 232 } 233 234 private static boolean isList(Class<?> clazz) { 235 return clazz == List.class || clazz == Deque.class; 236 } 237 238 private static final MethodHandle IS_SCRIPT_FUNCTION = Guards.isInstance(ScriptFunction.class, MH.type(Boolean.TYPE, Object.class)); 239 private static final MethodHandle IS_NATIVE_ARRAY = Guards.isOfClass(NativeArray.class, MH.type(Boolean.TYPE, Object.class)); 240 241 private static final MethodHandle IS_NASHORN_OR_UNDEFINED_TYPE = findOwnMH("isNashornTypeOrUndefined", 242 Boolean.TYPE, Object.class); 243 244 @SuppressWarnings("unused") 245 private static boolean isNashornTypeOrUndefined(final Object obj) { 246 return obj instanceof ScriptObject || obj instanceof Undefined; 247 } 248 249 private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) { 250 return MH.findStatic(MethodHandles.lookup(), NashornLinker.class, name, MH.type(rtype, types)); 251 } 252 } 253