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