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