NashornBeansLinker.java revision 1551:f3b883bec2d0
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.Method;
34import java.lang.reflect.Modifier;
35import jdk.dynalink.CallSiteDescriptor;
36import jdk.dynalink.NamedOperation;
37import jdk.dynalink.StandardOperation;
38import jdk.dynalink.beans.BeansLinker;
39import jdk.dynalink.linker.ConversionComparator.Comparison;
40import jdk.dynalink.linker.GuardedInvocation;
41import jdk.dynalink.linker.GuardingDynamicLinker;
42import jdk.dynalink.linker.LinkRequest;
43import jdk.dynalink.linker.LinkerServices;
44import jdk.dynalink.linker.MethodHandleTransformer;
45import jdk.dynalink.linker.support.DefaultInternalObjectFilter;
46import jdk.dynalink.linker.support.Lookup;
47import jdk.nashorn.api.scripting.ScriptUtils;
48import jdk.nashorn.internal.runtime.ConsString;
49import jdk.nashorn.internal.runtime.Context;
50import jdk.nashorn.internal.runtime.ScriptObject;
51import jdk.nashorn.internal.runtime.options.Options;
52
53/**
54 * This linker delegates to a {@code BeansLinker} but passes it a special linker services object that has a modified
55 * {@code compareConversion} method that favors conversion of {@link ConsString} to either {@link String} or
56 * {@link CharSequence}. It also provides a {@link #createHiddenObjectFilter()} method for use with bootstrap that will
57 * ensure that we never pass internal engine objects that should not be externally observable (currently ConsString and
58 * ScriptObject) to Java APIs, but rather that we flatten it into a String. We can't just add this functionality as
59 * custom converters via {@code GuaardingTypeConverterFactory}, since they are not consulted when
60 * the target method handle parameter signature is {@code Object}. This linker also makes sure that primitive
61 * {@link String} operations can be invoked on a {@link ConsString}, and allows invocation of objects implementing
62 * the {@link FunctionalInterface} attribute.
63 */
64public class NashornBeansLinker implements GuardingDynamicLinker {
65    // System property to control whether to wrap ScriptObject->ScriptObjectMirror for
66    // Object type arguments of Java method calls, field set and array set.
67    private static final boolean MIRROR_ALWAYS = Options.getBooleanProperty("nashorn.mirror.always", true);
68
69    private static final MethodHandle EXPORT_ARGUMENT;
70    private static final MethodHandle IMPORT_RESULT;
71    private static final MethodHandle FILTER_CONSSTRING;
72
73    static {
74        final Lookup lookup  = new Lookup(MethodHandles.lookup());
75        EXPORT_ARGUMENT      = lookup.findOwnStatic("exportArgument", Object.class, Object.class);
76        IMPORT_RESULT        = lookup.findOwnStatic("importResult", Object.class, Object.class);
77        FILTER_CONSSTRING    = lookup.findOwnStatic("consStringFilter", Object.class, Object.class);
78    }
79
80    // cache of @FunctionalInterface method of implementor classes
81    private static final ClassValue<String> FUNCTIONAL_IFACE_METHOD_NAME = new ClassValue<String>() {
82        @Override
83        protected String computeValue(final Class<?> type) {
84            return findFunctionalInterfaceMethodName(type);
85        }
86    };
87
88    private final BeansLinker beansLinker = new BeansLinker();
89
90    @Override
91    public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
92        final Object self = linkRequest.getReceiver();
93        final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor();
94        if (self instanceof ConsString) {
95            // In order to treat ConsString like a java.lang.String we need a link request with a string receiver.
96            final Object[] arguments = linkRequest.getArguments();
97            arguments[0] = "";
98            final LinkRequest forgedLinkRequest = linkRequest.replaceArguments(desc, arguments);
99            final GuardedInvocation invocation = getGuardedInvocation(beansLinker, forgedLinkRequest, linkerServices);
100            // If an invocation is found we add a filter that makes it work for both Strings and ConsStrings.
101            return invocation == null ? null : invocation.filterArguments(0, FILTER_CONSSTRING);
102        }
103
104        if (self != null && NamedOperation.getBaseOperation(desc.getOperation()) == StandardOperation.CALL) {
105            // Support CALL on any object that supports some @FunctionalInterface
106            // annotated interface. This way Java method, constructor references or
107            // implementations of java.util.function.* interfaces can be called as though
108            // those are script functions.
109            final String name = getFunctionalInterfaceMethodName(self.getClass());
110            if (name != null) {
111                final MethodType callType = desc.getMethodType();
112                // drop callee (Undefined ScriptFunction) and change the request to be CALL_METHOD:<name>
113                final CallSiteDescriptor newDesc = new CallSiteDescriptor(
114                        NashornCallSiteDescriptor.getLookupInternal(desc),
115                        new NamedOperation(StandardOperation.CALL_METHOD, name),
116                        desc.getMethodType().dropParameterTypes(1, 2));
117                final GuardedInvocation gi = getGuardedInvocation(beansLinker,
118                        linkRequest.replaceArguments(newDesc, linkRequest.getArguments()),
119                        new NashornBeansLinkerServices(linkerServices));
120
121                // drop 'thiz' passed from the script.
122                return gi.replaceMethods(
123                    MH.dropArguments(linkerServices.filterInternalObjects(gi.getInvocation()), 1, callType.parameterType(1)),
124                    gi.getGuard());
125            }
126        }
127        return getGuardedInvocation(beansLinker, linkRequest, linkerServices);
128    }
129
130    /**
131     * Delegates to the specified linker but injects its linker services wrapper so that it will apply all special
132     * conversions that this class does.
133     * @param delegateLinker the linker to which the actual work is delegated to.
134     * @param linkRequest the delegated link request
135     * @param linkerServices the original link services that will be augmented with special conversions
136     * @return the guarded invocation from the delegate, possibly augmented with special conversions
137     * @throws Exception if the delegate throws an exception
138     */
139    public static GuardedInvocation getGuardedInvocation(final GuardingDynamicLinker delegateLinker, final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
140        return delegateLinker.getGuardedInvocation(linkRequest, new NashornBeansLinkerServices(linkerServices));
141    }
142
143    @SuppressWarnings("unused")
144    private static Object exportArgument(final Object arg) {
145        return exportArgument(arg, MIRROR_ALWAYS);
146    }
147
148    static Object exportArgument(final Object arg, final boolean mirrorAlways) {
149        if (arg instanceof ConsString) {
150            return arg.toString();
151        } else if (mirrorAlways && arg instanceof ScriptObject) {
152            return ScriptUtils.wrap((ScriptObject)arg);
153        } else {
154            return arg;
155        }
156    }
157
158    @SuppressWarnings("unused")
159    private static Object importResult(final Object arg) {
160        return ScriptUtils.unwrap(arg);
161    }
162
163    @SuppressWarnings("unused")
164    private static Object consStringFilter(final Object arg) {
165        return arg instanceof ConsString ? arg.toString() : arg;
166    }
167
168    private static String findFunctionalInterfaceMethodName(final Class<?> clazz) {
169        if (clazz == null) {
170            return null;
171        }
172
173        for (final Class<?> iface : clazz.getInterfaces()) {
174            // check accessibility up-front
175            if (! Context.isAccessibleClass(iface)) {
176                continue;
177            }
178
179            // check for @FunctionalInterface
180            if (iface.isAnnotationPresent(FunctionalInterface.class)) {
181                // return the first abstract method
182                for (final Method m : iface.getMethods()) {
183                    if (Modifier.isAbstract(m.getModifiers())) {
184                        return m.getName();
185                    }
186                }
187            }
188        }
189
190        // did not find here, try super class
191        return findFunctionalInterfaceMethodName(clazz.getSuperclass());
192    }
193
194    // Returns @FunctionalInterface annotated interface's single abstract
195    // method name. If not found, returns null.
196    static String getFunctionalInterfaceMethodName(final Class<?> clazz) {
197        return FUNCTIONAL_IFACE_METHOD_NAME.get(clazz);
198    }
199
200    static MethodHandleTransformer createHiddenObjectFilter() {
201        return new DefaultInternalObjectFilter(EXPORT_ARGUMENT, MIRROR_ALWAYS ? IMPORT_RESULT : null);
202    }
203
204    private static class NashornBeansLinkerServices implements LinkerServices {
205        private final LinkerServices linkerServices;
206
207        NashornBeansLinkerServices(final LinkerServices linkerServices) {
208            this.linkerServices = linkerServices;
209        }
210
211        @Override
212        public MethodHandle asType(final MethodHandle handle, final MethodType fromType) {
213            return linkerServices.asType(handle, fromType);
214        }
215
216        @Override
217        public MethodHandle getTypeConverter(final Class<?> sourceType, final Class<?> targetType) {
218            return linkerServices.getTypeConverter(sourceType, targetType);
219        }
220
221        @Override
222        public boolean canConvert(final Class<?> from, final Class<?> to) {
223            return linkerServices.canConvert(from, to);
224        }
225
226        @Override
227        public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest) throws Exception {
228            return linkerServices.getGuardedInvocation(linkRequest);
229        }
230
231        @Override
232        public Comparison compareConversion(final Class<?> sourceType, final Class<?> targetType1, final Class<?> targetType2) {
233            if (sourceType == ConsString.class) {
234                if (String.class == targetType1 || CharSequence.class == targetType1) {
235                    return Comparison.TYPE_1_BETTER;
236                }
237
238                if (String.class == targetType2 || CharSequence.class == targetType2) {
239                    return Comparison.TYPE_2_BETTER;
240                }
241            }
242            return linkerServices.compareConversion(sourceType, targetType1, targetType2);
243        }
244
245        @Override
246        public MethodHandle filterInternalObjects(final MethodHandle target) {
247            return linkerServices.filterInternalObjects(target);
248        }
249    }
250}
251