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