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