NashornBottomLinker.java revision 1265:6af2ee7b09a9
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.util.HashMap;
34import java.util.Map;
35import jdk.internal.dynalink.CallSiteDescriptor;
36import jdk.internal.dynalink.beans.BeansLinker;
37import jdk.internal.dynalink.linker.GuardedInvocation;
38import jdk.internal.dynalink.linker.GuardedTypeConversion;
39import jdk.internal.dynalink.linker.GuardingDynamicLinker;
40import jdk.internal.dynalink.linker.GuardingTypeConverterFactory;
41import jdk.internal.dynalink.linker.LinkRequest;
42import jdk.internal.dynalink.linker.LinkerServices;
43import jdk.internal.dynalink.support.Guards;
44import jdk.nashorn.internal.codegen.types.Type;
45import jdk.nashorn.internal.runtime.JSType;
46import jdk.nashorn.internal.runtime.ScriptRuntime;
47import jdk.nashorn.internal.runtime.UnwarrantedOptimismException;
48
49/**
50 * Nashorn bottom linker; used as a last-resort catch-all linker for all linking requests that fall through all other
51 * linkers (see how {@link Bootstrap} class configures the dynamic linker in its static initializer). It will throw
52 * appropriate ECMAScript errors for attempts to invoke operations on {@code null}, link no-op property getters and
53 * setters for Java objects that couldn't be linked by any other linker, and throw appropriate ECMAScript errors for
54 * attempts to invoke arbitrary Java objects as functions or constructors.
55 */
56final class NashornBottomLinker implements GuardingDynamicLinker, GuardingTypeConverterFactory {
57
58    @Override
59    public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices)
60            throws Exception {
61        final Object self = linkRequest.getReceiver();
62
63        if (self == null) {
64            return linkNull(linkRequest);
65        }
66
67        // None of the objects that can be linked by NashornLinker should ever reach here. Basically, anything below
68        // this point is a generic Java bean. Therefore, reaching here with a ScriptObject is a Nashorn bug.
69        assert isExpectedObject(self) : "Couldn't link " + linkRequest.getCallSiteDescriptor() + " for " + self.getClass().getName();
70
71        return linkBean(linkRequest, linkerServices);
72    }
73
74    private static final MethodHandle EMPTY_PROP_GETTER =
75            MH.dropArguments(MH.constant(Object.class, UNDEFINED), 0, Object.class);
76    private static final MethodHandle EMPTY_ELEM_GETTER =
77            MH.dropArguments(EMPTY_PROP_GETTER, 0, Object.class);
78    private static final MethodHandle EMPTY_PROP_SETTER =
79            MH.asType(EMPTY_ELEM_GETTER, EMPTY_ELEM_GETTER.type().changeReturnType(void.class));
80    private static final MethodHandle EMPTY_ELEM_SETTER =
81            MH.dropArguments(EMPTY_PROP_SETTER, 0, Object.class);
82
83    private static GuardedInvocation linkBean(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
84        final NashornCallSiteDescriptor desc = (NashornCallSiteDescriptor)linkRequest.getCallSiteDescriptor();
85        final Object self = linkRequest.getReceiver();
86        final String operator = desc.getFirstOperator();
87        switch (operator) {
88        case "new":
89            if(BeansLinker.isDynamicConstructor(self)) {
90                throw typeError("no.constructor.matches.args", ScriptRuntime.safeToString(self));
91            }
92            if(BeansLinker.isDynamicMethod(self)) {
93                throw typeError("method.not.constructor", ScriptRuntime.safeToString(self));
94            }
95            throw typeError("not.a.function", ScriptRuntime.safeToString(self));
96        case "call":
97            if(BeansLinker.isDynamicConstructor(self)) {
98                throw typeError("constructor.requires.new", ScriptRuntime.safeToString(self));
99            }
100            if(BeansLinker.isDynamicMethod(self)) {
101                throw typeError("no.method.matches.args", ScriptRuntime.safeToString(self));
102            }
103            throw typeError("not.a.function", ScriptRuntime.safeToString(self));
104        case "callMethod":
105        case "getMethod":
106            throw typeError("no.such.function", getArgument(linkRequest), ScriptRuntime.safeToString(self));
107        case "getProp":
108        case "getElem":
109            if(NashornCallSiteDescriptor.isOptimistic(desc)) {
110                throw new UnwarrantedOptimismException(UNDEFINED, NashornCallSiteDescriptor.getProgramPoint(desc), Type.OBJECT);
111            }
112            if (desc.getOperand() != null) {
113                return getInvocation(EMPTY_PROP_GETTER, self, linkerServices, desc);
114            }
115            return getInvocation(EMPTY_ELEM_GETTER, self, linkerServices, desc);
116        case "setProp":
117        case "setElem": {
118            final boolean strict = NashornCallSiteDescriptor.isStrict(desc);
119            if (strict) {
120                throw typeError("cant.set.property", getArgument(linkRequest), ScriptRuntime.safeToString(self));
121            }
122            if (desc.getOperand() != null) {
123                return getInvocation(EMPTY_PROP_SETTER, self, linkerServices, desc);
124            }
125            return getInvocation(EMPTY_ELEM_SETTER, self, linkerServices, desc);
126        }
127        default:
128            break;
129        }
130        throw new AssertionError("unknown call type " + desc);
131    }
132
133    @Override
134    public GuardedTypeConversion convertToType(final Class<?> sourceType, final Class<?> targetType) throws Exception {
135        final GuardedInvocation gi = convertToTypeNoCast(sourceType, targetType);
136        return gi == null ? null : new GuardedTypeConversion(gi.asType(MH.type(targetType, sourceType)), true);
137    }
138
139    /**
140     * Main part of the implementation of {@link GuardingTypeConverterFactory#convertToType(Class, Class)} that doesn't
141     * care about adapting the method signature; that's done by the invoking method. Returns conversion from Object to String/number/boolean (JS primitive types).
142     * @param sourceType the source type
143     * @param targetType the target type
144     * @return a guarded invocation that converts from the source type to the target type.
145     * @throws Exception if something goes wrong
146     */
147    private static GuardedInvocation convertToTypeNoCast(final Class<?> sourceType, final Class<?> targetType) throws Exception {
148        final MethodHandle mh = CONVERTERS.get(targetType);
149        if (mh != null) {
150            return new GuardedInvocation(mh);
151        }
152
153        return null;
154    }
155
156    private static GuardedInvocation getInvocation(final MethodHandle handle, final Object self, final LinkerServices linkerServices, final CallSiteDescriptor desc) {
157        return Bootstrap.asTypeSafeReturn(new GuardedInvocation(handle, Guards.getClassGuard(self.getClass())), linkerServices, desc);
158    }
159
160    // Used solely in an assertion to figure out if the object we get here is something we in fact expect. Objects
161    // linked by NashornLinker should never reach here.
162    private static boolean isExpectedObject(final Object obj) {
163        return !(NashornLinker.canLinkTypeStatic(obj.getClass()));
164    }
165
166    private static GuardedInvocation linkNull(final LinkRequest linkRequest) {
167        final NashornCallSiteDescriptor desc = (NashornCallSiteDescriptor)linkRequest.getCallSiteDescriptor();
168        final String operator = desc.getFirstOperator();
169        switch (operator) {
170        case "new":
171        case "call":
172            throw typeError("not.a.function", "null");
173        case "callMethod":
174        case "getMethod":
175            throw typeError("no.such.function", getArgument(linkRequest), "null");
176        case "getProp":
177        case "getElem":
178            throw typeError("cant.get.property", getArgument(linkRequest), "null");
179        case "setProp":
180        case "setElem":
181            throw typeError("cant.set.property", getArgument(linkRequest), "null");
182        default:
183            break;
184        }
185        throw new AssertionError("unknown call type " + desc);
186    }
187
188    private static final Map<Class<?>, MethodHandle> CONVERTERS = new HashMap<>();
189    static {
190        CONVERTERS.put(boolean.class, JSType.TO_BOOLEAN.methodHandle());
191        CONVERTERS.put(double.class, JSType.TO_NUMBER.methodHandle());
192        CONVERTERS.put(int.class, JSType.TO_INTEGER.methodHandle());
193        CONVERTERS.put(long.class, JSType.TO_LONG.methodHandle());
194        CONVERTERS.put(String.class, JSType.TO_STRING.methodHandle());
195    }
196
197    private static String getArgument(final LinkRequest linkRequest) {
198        final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor();
199        if (desc.getNameTokenCount() > 2) {
200            return desc.getNameToken(2);
201        }
202        return ScriptRuntime.safeToString(linkRequest.getArguments()[1]);
203    }
204}
205