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