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