JSObjectLinker.java revision 1678:58cac5dc254d
1/*
2 * Copyright (c) 2010, 2016, 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.runtime.JSType.isString;
29
30import java.lang.invoke.MethodHandle;
31import java.lang.invoke.MethodHandles;
32import java.lang.invoke.MethodType;
33import java.util.Map;
34import javax.script.Bindings;
35import jdk.dynalink.CallSiteDescriptor;
36import jdk.dynalink.StandardOperation;
37import jdk.dynalink.linker.GuardedInvocation;
38import jdk.dynalink.linker.LinkRequest;
39import jdk.dynalink.linker.LinkerServices;
40import jdk.dynalink.linker.TypeBasedGuardingDynamicLinker;
41import jdk.nashorn.api.scripting.JSObject;
42import jdk.nashorn.internal.lookup.MethodHandleFactory;
43import jdk.nashorn.internal.lookup.MethodHandleFunctionality;
44import jdk.nashorn.internal.runtime.JSType;
45
46/**
47 * A Dynalink linker to handle web browser built-in JS (DOM etc.) objects as well
48 * as ScriptObjects from other Nashorn contexts.
49 */
50final class JSObjectLinker implements TypeBasedGuardingDynamicLinker {
51    private final NashornBeansLinker nashornBeansLinker;
52
53    JSObjectLinker(final NashornBeansLinker nashornBeansLinker) {
54        this.nashornBeansLinker = nashornBeansLinker;
55    }
56
57    @Override
58    public boolean canLinkType(final Class<?> type) {
59        return canLinkTypeStatic(type);
60    }
61
62    static boolean canLinkTypeStatic(final Class<?> type) {
63        // can link JSObject also handles Map, Bindings to make
64        // sure those are not JSObjects.
65        return Map.class.isAssignableFrom(type) ||
66               Bindings.class.isAssignableFrom(type) ||
67               JSObject.class.isAssignableFrom(type);
68    }
69
70    @Override
71    public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices) throws Exception {
72        final Object self = request.getReceiver();
73        final CallSiteDescriptor desc = request.getCallSiteDescriptor();
74        if (self == null || !canLinkTypeStatic(self.getClass())) {
75            return null;
76        }
77
78        GuardedInvocation inv;
79        if (self instanceof JSObject) {
80            inv = lookup(desc, request, linkerServices);
81            inv = inv.replaceMethods(linkerServices.filterInternalObjects(inv.getInvocation()), inv.getGuard());
82        } else if (self instanceof Map || self instanceof Bindings) {
83            // guard to make sure the Map or Bindings does not turn into JSObject later!
84            final GuardedInvocation beanInv = nashornBeansLinker.getGuardedInvocation(request, linkerServices);
85            inv = new GuardedInvocation(beanInv.getInvocation(),
86                NashornGuards.combineGuards(beanInv.getGuard(), NashornGuards.getNotJSObjectGuard()));
87        } else {
88            throw new AssertionError("got instanceof: " + self.getClass()); // Should never reach here.
89        }
90
91        return Bootstrap.asTypeSafeReturn(inv, linkerServices, desc);
92    }
93
94    private GuardedInvocation lookup(final CallSiteDescriptor desc, final LinkRequest request, final LinkerServices linkerServices) throws Exception {
95        final StandardOperation op = NashornCallSiteDescriptor.getFirstStandardOperation(desc);
96        if (op == null) {
97            return null;
98        }
99        final String name = NashornCallSiteDescriptor.getOperand(desc);
100        switch (op) {
101        case GET_PROPERTY:
102        case GET_ELEMENT:
103        case GET_METHOD:
104            if (name != null) {
105                return findGetMethod(name);
106            }
107            // For indexed get, we want get GuardedInvocation beans linker and pass it.
108            // JSObjectLinker.get uses this fallback getter for explicit signature method access.
109            return findGetIndexMethod(nashornBeansLinker.getGuardedInvocation(request, linkerServices));
110        case SET_PROPERTY:
111        case SET_ELEMENT:
112            return name != null ? findSetMethod(name) : findSetIndexMethod();
113        case CALL:
114            return findCallMethod(desc);
115        case NEW:
116            return findNewMethod(desc);
117        default:
118        }
119        return null;
120    }
121
122    private static GuardedInvocation findGetMethod(final String name) {
123        final MethodHandle getter = MH.insertArguments(JSOBJECT_GETMEMBER, 1, name);
124        return new GuardedInvocation(getter, IS_JSOBJECT_GUARD);
125    }
126
127    private static GuardedInvocation findGetIndexMethod(final GuardedInvocation inv) {
128        final MethodHandle getter = MH.insertArguments(JSOBJECTLINKER_GET, 0, inv.getInvocation());
129        return inv.replaceMethods(getter, inv.getGuard());
130    }
131
132    private static GuardedInvocation findSetMethod(final String name) {
133        final MethodHandle getter = MH.insertArguments(JSOBJECT_SETMEMBER, 1, name);
134        return new GuardedInvocation(getter, IS_JSOBJECT_GUARD);
135    }
136
137    private static GuardedInvocation findSetIndexMethod() {
138        return new GuardedInvocation(JSOBJECTLINKER_PUT, IS_JSOBJECT_GUARD);
139    }
140
141    private static GuardedInvocation findCallMethod(final CallSiteDescriptor desc) {
142        MethodHandle mh = JSOBJECT_CALL;
143        if (NashornCallSiteDescriptor.isApplyToCall(desc)) {
144            mh = MH.insertArguments(JSOBJECT_CALL_TO_APPLY, 0, JSOBJECT_CALL);
145        }
146        final MethodType type = desc.getMethodType();
147        mh = type.parameterType(type.parameterCount() - 1) == Object[].class ?
148                mh :
149                MH.asCollector(mh, Object[].class, type.parameterCount() - 2);
150        return new GuardedInvocation(mh, IS_JSOBJECT_GUARD);
151    }
152
153    private static GuardedInvocation findNewMethod(final CallSiteDescriptor desc) {
154        final MethodHandle func = MH.asCollector(JSOBJECT_NEW, Object[].class, desc.getMethodType().parameterCount() - 1);
155        return new GuardedInvocation(func, IS_JSOBJECT_GUARD);
156    }
157
158    @SuppressWarnings("unused")
159    private static boolean isJSObject(final Object self) {
160        return self instanceof JSObject;
161    }
162
163    @SuppressWarnings("unused")
164    private static Object get(final MethodHandle fallback, final Object jsobj, final Object key)
165        throws Throwable {
166        if (key instanceof Integer) {
167            return ((JSObject)jsobj).getSlot((Integer)key);
168        } else if (key instanceof Number) {
169            final int index = getIndex((Number)key);
170            if (index > -1) {
171                return ((JSObject)jsobj).getSlot(index);
172            }
173        } else if (isString(key)) {
174            final String name = key.toString();
175            // get with method name and signature. delegate it to beans linker!
176            if (name.indexOf('(') != -1) {
177                return fallback.invokeExact(jsobj, (Object) name);
178            }
179            return ((JSObject)jsobj).getMember(name);
180        }
181        return null;
182    }
183
184    @SuppressWarnings("unused")
185    private static void put(final Object jsobj, final Object key, final Object value) {
186        if (key instanceof Integer) {
187            ((JSObject)jsobj).setSlot((Integer)key, value);
188        } else if (key instanceof Number) {
189            ((JSObject)jsobj).setSlot(getIndex((Number)key), value);
190        } else if (isString(key)) {
191            ((JSObject)jsobj).setMember(key.toString(), value);
192        }
193    }
194
195    private static int getIndex(final Number n) {
196        final double value = n.doubleValue();
197        return JSType.isRepresentableAsInt(value) ? (int)value : -1;
198    }
199
200    @SuppressWarnings("unused")
201    private static Object callToApply(final MethodHandle mh, final JSObject obj, final Object thiz, final Object... args) {
202        assert args.length >= 2;
203        final Object   receiver  = args[0];
204        final Object[] arguments = new Object[args.length - 1];
205        System.arraycopy(args, 1, arguments, 0, arguments.length);
206        try {
207            return mh.invokeExact(obj, thiz, new Object[] { receiver, arguments });
208        } catch (final RuntimeException | Error e) {
209            throw e;
210        } catch (final Throwable e) {
211            throw new RuntimeException(e);
212        }
213    }
214
215    private static final MethodHandleFunctionality MH = MethodHandleFactory.getFunctionality();
216
217    // method handles of the current class
218    private static final MethodHandle IS_JSOBJECT_GUARD  = findOwnMH_S("isJSObject", boolean.class, Object.class);
219    private static final MethodHandle JSOBJECTLINKER_GET = findOwnMH_S("get", Object.class, MethodHandle.class, Object.class, Object.class);
220    private static final MethodHandle JSOBJECTLINKER_PUT = findOwnMH_S("put", Void.TYPE, Object.class, Object.class, Object.class);
221
222    // method handles of JSObject class
223    private static final MethodHandle JSOBJECT_GETMEMBER     = findJSObjectMH_V("getMember", Object.class, String.class);
224    private static final MethodHandle JSOBJECT_SETMEMBER     = findJSObjectMH_V("setMember", Void.TYPE, String.class, Object.class);
225    private static final MethodHandle JSOBJECT_CALL          = findJSObjectMH_V("call", Object.class, Object.class, Object[].class);
226    private static final MethodHandle JSOBJECT_CALL_TO_APPLY = findOwnMH_S("callToApply", Object.class, MethodHandle.class, JSObject.class, Object.class, Object[].class);
227    private static final MethodHandle JSOBJECT_NEW           = findJSObjectMH_V("newObject", Object.class, Object[].class);
228
229    private static MethodHandle findJSObjectMH_V(final String name, final Class<?> rtype, final Class<?>... types) {
230        return MH.findVirtual(MethodHandles.lookup(), JSObject.class, name, MH.type(rtype, types));
231    }
232
233    private static MethodHandle findOwnMH_S(final String name, final Class<?> rtype, final Class<?>... types) {
234        return MH.findStatic(MethodHandles.lookup(), JSObjectLinker.class, name, MH.type(rtype, types));
235    }
236}
237