NashornBottomLinker.java revision 1598:30c3bcdb762c
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;
29import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
30import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
31
32import java.lang.invoke.MethodHandle;
33import java.lang.invoke.MethodHandles;
34import java.lang.invoke.MethodType;
35import java.util.HashMap;
36import java.util.Map;
37import java.util.function.Supplier;
38import jdk.dynalink.CallSiteDescriptor;
39import jdk.dynalink.NamedOperation;
40import jdk.dynalink.Operation;
41import jdk.dynalink.StandardOperation;
42import jdk.dynalink.beans.BeansLinker;
43import jdk.dynalink.linker.GuardedInvocation;
44import jdk.dynalink.linker.GuardingDynamicLinker;
45import jdk.dynalink.linker.GuardingTypeConverterFactory;
46import jdk.dynalink.linker.LinkRequest;
47import jdk.dynalink.linker.LinkerServices;
48import jdk.dynalink.linker.support.Lookup;
49import jdk.nashorn.internal.codegen.types.Type;
50import jdk.nashorn.internal.runtime.ECMAException;
51import jdk.nashorn.internal.runtime.JSType;
52import jdk.nashorn.internal.runtime.ScriptRuntime;
53import jdk.nashorn.internal.runtime.UnwarrantedOptimismException;
54
55/**
56 * Nashorn bottom linker; used as a last-resort catch-all linker for all linking requests that fall through all other
57 * linkers (see how {@link Bootstrap} class configures the dynamic linker in its static initializer). It will throw
58 * appropriate ECMAScript errors for attempts to invoke operations on {@code null}, link no-op property getters and
59 * setters for Java objects that couldn't be linked by any other linker, and throw appropriate ECMAScript errors for
60 * attempts to invoke arbitrary Java objects as functions or constructors.
61 */
62final class NashornBottomLinker implements GuardingDynamicLinker, GuardingTypeConverterFactory {
63
64    @Override
65    public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices)
66            throws Exception {
67        final Object self = linkRequest.getReceiver();
68
69        if (self == null) {
70            return linkNull(linkRequest);
71        }
72
73        // None of the objects that can be linked by NashornLinker should ever reach here. Basically, anything below
74        // this point is a generic Java bean. Therefore, reaching here with a ScriptObject is a Nashorn bug.
75        assert isExpectedObject(self) : "Couldn't link " + linkRequest.getCallSiteDescriptor() + " for " + self.getClass().getName();
76
77        return linkBean(linkRequest);
78    }
79
80    private static final MethodHandle EMPTY_PROP_GETTER =
81            MH.dropArguments(MH.constant(Object.class, UNDEFINED), 0, Object.class);
82    private static final MethodHandle EMPTY_ELEM_GETTER =
83            MH.dropArguments(EMPTY_PROP_GETTER, 0, Object.class);
84    private static final MethodHandle EMPTY_PROP_SETTER =
85            MH.asType(EMPTY_ELEM_GETTER, EMPTY_ELEM_GETTER.type().changeReturnType(void.class));
86    private static final MethodHandle EMPTY_ELEM_SETTER =
87            MH.dropArguments(EMPTY_PROP_SETTER, 0, Object.class);
88
89    private static final MethodHandle THROW_NO_SUCH_FUNCTION;
90    private static final MethodHandle THROW_STRICT_PROPERTY_SETTER;
91    private static final MethodHandle THROW_OPTIMISTIC_UNDEFINED;
92
93    static {
94        final Lookup lookup = new Lookup(MethodHandles.lookup());
95        THROW_NO_SUCH_FUNCTION = lookup.findOwnStatic("throwNoSuchFunction", Object.class, Object.class, Object.class);
96        THROW_STRICT_PROPERTY_SETTER = lookup.findOwnStatic("throwStrictPropertySetter", void.class, Object.class, Object.class);
97        THROW_OPTIMISTIC_UNDEFINED = lookup.findOwnStatic("throwOptimisticUndefined", Object.class, int.class);
98    }
99
100    private static GuardedInvocation linkBean(final LinkRequest linkRequest) throws Exception {
101        final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor();
102        final Object self = linkRequest.getReceiver();
103        switch (NashornCallSiteDescriptor.getFirstStandardOperation(desc)) {
104        case NEW:
105            if(BeansLinker.isDynamicConstructor(self)) {
106                throw typeError("no.constructor.matches.args", ScriptRuntime.safeToString(self));
107            }
108            if(BeansLinker.isDynamicMethod(self)) {
109                throw typeError("method.not.constructor", ScriptRuntime.safeToString(self));
110            }
111            throw typeError("not.a.function", NashornCallSiteDescriptor.getFunctionErrorMessage(desc, self));
112        case CALL:
113            if(BeansLinker.isDynamicConstructor(self)) {
114                throw typeError("constructor.requires.new", ScriptRuntime.safeToString(self));
115            }
116            if(BeansLinker.isDynamicMethod(self)) {
117                throw typeError("no.method.matches.args", ScriptRuntime.safeToString(self));
118            }
119            throw typeError("not.a.function", NashornCallSiteDescriptor.getFunctionErrorMessage(desc, self));
120        default:
121            // Everything else is supposed to have been already handled by Bootstrap.beansLinker
122            // delegating to linkNoSuchBeanMember
123            throw new AssertionError("unknown call type " + desc);
124        }
125    }
126
127    static MethodHandle linkMissingBeanMember(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
128        final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor();
129        final StandardOperation op = NashornCallSiteDescriptor.getFirstStandardOperation(desc);
130        if (op != null) {
131            final String operand = NashornCallSiteDescriptor.getOperand(desc);
132            switch (op) {
133            case CALL_METHOD:
134                return adaptThrower(bindOperand(THROW_NO_SUCH_FUNCTION, operand), desc);
135            case GET_METHOD:
136            case GET_PROPERTY:
137            case GET_ELEMENT: {
138                if (NashornCallSiteDescriptor.isOptimistic(desc)) {
139                    return adaptThrower(MethodHandles.insertArguments(THROW_OPTIMISTIC_UNDEFINED, 0, NashornCallSiteDescriptor.getProgramPoint(desc)), desc);
140                }
141                if (NashornCallSiteDescriptor.getOperand(desc) != null) {
142                    return getInvocation(EMPTY_PROP_GETTER, linkerServices, desc);
143                }
144                return getInvocation(EMPTY_ELEM_GETTER, linkerServices, desc);
145            }
146            case SET_PROPERTY:
147            case SET_ELEMENT:
148                final boolean strict = NashornCallSiteDescriptor.isStrict(desc);
149                if (strict) {
150                    return adaptThrower(bindOperand(THROW_STRICT_PROPERTY_SETTER, operand), desc);
151                }
152                if (NashornCallSiteDescriptor.getOperand(desc) != null) {
153                    return getInvocation(EMPTY_PROP_SETTER, linkerServices, desc);
154                }
155                return getInvocation(EMPTY_ELEM_SETTER, linkerServices, desc);
156            default:
157            }
158        }
159        throw new AssertionError("unknown call type " + desc);
160    }
161
162    private static MethodHandle bindOperand(final MethodHandle handle, final String operand) {
163        return operand == null ? handle : MethodHandles.insertArguments(handle, 1, operand);
164    }
165
166    private static MethodHandle adaptThrower(final MethodHandle handle, final CallSiteDescriptor desc) {
167        final MethodType targetType = desc.getMethodType();
168        final int paramCount = handle.type().parameterCount();
169        return MethodHandles
170                .dropArguments(handle, paramCount, targetType.parameterList().subList(paramCount, targetType.parameterCount()))
171                .asType(targetType);
172    }
173
174    @SuppressWarnings("unused")
175    private static Object throwNoSuchFunction(final Object self, final Object name) {
176        throw createTypeError(self, name, "no.such.function");
177    }
178
179    @SuppressWarnings("unused")
180    private static void throwStrictPropertySetter(final Object self, final Object name) {
181        throw createTypeError(self, name, "cant.set.property");
182    }
183
184    private static ECMAException createTypeError(final Object self, final Object name, final String msg) {
185        return typeError(msg, String.valueOf(name), ScriptRuntime.safeToString(self));
186    }
187
188    @SuppressWarnings("unused")
189    private static Object throwOptimisticUndefined(final int programPoint) {
190        throw new UnwarrantedOptimismException(UNDEFINED, programPoint, Type.OBJECT);
191    }
192
193    @Override
194    public GuardedInvocation convertToType(final Class<?> sourceType, final Class<?> targetType, final Supplier<MethodHandles.Lookup> lookupSupplier) throws Exception {
195        final GuardedInvocation gi = convertToTypeNoCast(sourceType, targetType);
196        return gi == null ? null : gi.asType(MH.type(targetType, sourceType));
197    }
198
199    /**
200     * Main part of the implementation of {@link GuardingTypeConverterFactory#convertToType} that doesn't
201     * care about adapting the method signature; that's done by the invoking method. Returns conversion
202     * from Object to String/number/boolean (JS primitive types).
203     * @param sourceType the source type
204     * @param targetType the target type
205     * @return a guarded invocation that converts from the source type to the target type.
206     * @throws Exception if something goes wrong
207     */
208    private static GuardedInvocation convertToTypeNoCast(final Class<?> sourceType, final Class<?> targetType) throws Exception {
209        final MethodHandle mh = CONVERTERS.get(targetType);
210        if (mh != null) {
211            return new GuardedInvocation(mh);
212        }
213
214        return null;
215    }
216
217    private static MethodHandle getInvocation(final MethodHandle handle, final LinkerServices linkerServices, final CallSiteDescriptor desc) {
218        return linkerServices.asTypeLosslessReturn(handle, desc.getMethodType());
219    }
220
221    // Used solely in an assertion to figure out if the object we get here is something we in fact expect. Objects
222    // linked by NashornLinker should never reach here.
223    private static boolean isExpectedObject(final Object obj) {
224        return !(NashornLinker.canLinkTypeStatic(obj.getClass()));
225    }
226
227    private static GuardedInvocation linkNull(final LinkRequest linkRequest) {
228        final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor();
229        switch (NashornCallSiteDescriptor.getFirstStandardOperation(desc)) {
230        case NEW:
231        case CALL:
232            throw typeError("not.a.function", "null");
233        case CALL_METHOD:
234        case GET_METHOD:
235            throw typeError("no.such.function", getArgument(linkRequest), "null");
236        case GET_PROPERTY:
237        case GET_ELEMENT:
238            throw typeError("cant.get.property", getArgument(linkRequest), "null");
239        case SET_PROPERTY:
240        case SET_ELEMENT:
241            throw typeError("cant.set.property", getArgument(linkRequest), "null");
242        default:
243            throw new AssertionError("unknown call type " + desc);
244        }
245    }
246
247    private static final Map<Class<?>, MethodHandle> CONVERTERS = new HashMap<>();
248    static {
249        CONVERTERS.put(boolean.class, JSType.TO_BOOLEAN.methodHandle());
250        CONVERTERS.put(double.class, JSType.TO_NUMBER.methodHandle());
251        CONVERTERS.put(int.class, JSType.TO_INTEGER.methodHandle());
252        CONVERTERS.put(long.class, JSType.TO_LONG.methodHandle());
253        CONVERTERS.put(String.class, JSType.TO_STRING.methodHandle());
254    }
255
256    private static String getArgument(final LinkRequest linkRequest) {
257        final Operation op = linkRequest.getCallSiteDescriptor().getOperation();
258        if (op instanceof NamedOperation) {
259            return ((NamedOperation)op).getName().toString();
260        }
261        return ScriptRuntime.safeToString(linkRequest.getArguments()[1]);
262    }
263}
264