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