JSObjectLinker.java revision 1831:ba05e6f3d85c
1135446Strhodes/*
2135446Strhodes * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
3135446Strhodes * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4135446Strhodes *
5135446Strhodes * This code is free software; you can redistribute it and/or modify it
6135446Strhodes * under the terms of the GNU General Public License version 2 only, as
7135446Strhodes * published by the Free Software Foundation.  Oracle designates this
8135446Strhodes * particular file as subject to the "Classpath" exception as provided
9135446Strhodes * by Oracle in the LICENSE file that accompanied this code.
10135446Strhodes *
11135446Strhodes * This code is distributed in the hope that it will be useful, but WITHOUT
12135446Strhodes * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13135446Strhodes * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14135446Strhodes * version 2 for more details (a copy is included in the LICENSE file that
15135446Strhodes * accompanied this code).
16135446Strhodes *
17135446Strhodes * You should have received a copy of the GNU General Public License version
18135446Strhodes * 2 along with this work; if not, write to the Free Software Foundation,
19135446Strhodes * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20135446Strhodes *
21135446Strhodes * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22135446Strhodes * or visit www.oracle.com if you need additional information or have any
23135446Strhodes * questions.
24135446Strhodes */
25135446Strhodes
26135446Strhodespackage jdk.nashorn.internal.runtime.linker;
27135446Strhodes
28135446Strhodesimport static jdk.nashorn.internal.runtime.JSType.isString;
29135446Strhodes
30135446Strhodesimport java.lang.invoke.MethodHandle;
31135446Strhodesimport java.lang.invoke.MethodHandles;
32135446Strhodesimport java.lang.invoke.MethodType;
33135446Strhodesimport java.util.Map;
34135446Strhodesimport javax.script.Bindings;
35135446Strhodesimport jdk.dynalink.CallSiteDescriptor;
36135446Strhodesimport jdk.dynalink.Operation;
37135446Strhodesimport jdk.dynalink.StandardOperation;
38135446Strhodesimport jdk.dynalink.linker.GuardedInvocation;
39135446Strhodesimport jdk.dynalink.linker.LinkRequest;
40135446Strhodesimport jdk.dynalink.linker.LinkerServices;
41135446Strhodesimport jdk.dynalink.linker.TypeBasedGuardingDynamicLinker;
42135446Strhodesimport jdk.nashorn.api.scripting.JSObject;
43135446Strhodesimport jdk.nashorn.api.scripting.ScriptObjectMirror;
44135446Strhodesimport jdk.nashorn.internal.lookup.MethodHandleFactory;
45135446Strhodesimport jdk.nashorn.internal.lookup.MethodHandleFunctionality;
46135446Strhodesimport jdk.nashorn.internal.runtime.Context;
47135446Strhodesimport jdk.nashorn.internal.runtime.JSType;
48135446Strhodesimport jdk.nashorn.internal.runtime.ScriptRuntime;
49135446Strhodesimport jdk.nashorn.internal.objects.Global;
50135446Strhodes
51135446Strhodes/**
52135446Strhodes * A Dynalink linker to handle web browser built-in JS (DOM etc.) objects as well
53135446Strhodes * as ScriptObjects from other Nashorn contexts.
54135446Strhodes */
55135446Strhodesfinal class JSObjectLinker implements TypeBasedGuardingDynamicLinker {
56135446Strhodes    private final NashornBeansLinker nashornBeansLinker;
57135446Strhodes
58135446Strhodes    JSObjectLinker(final NashornBeansLinker nashornBeansLinker) {
59135446Strhodes        this.nashornBeansLinker = nashornBeansLinker;
60135446Strhodes    }
61135446Strhodes
62135446Strhodes    @Override
63135446Strhodes    public boolean canLinkType(final Class<?> type) {
64135446Strhodes        return canLinkTypeStatic(type);
65135446Strhodes    }
66135446Strhodes
67135446Strhodes    static boolean canLinkTypeStatic(final Class<?> type) {
68135446Strhodes        // can link JSObject also handles Map, Bindings to make
69135446Strhodes        // sure those are not JSObjects.
70135446Strhodes        return Map.class.isAssignableFrom(type) ||
71135446Strhodes               Bindings.class.isAssignableFrom(type) ||
72135446Strhodes               JSObject.class.isAssignableFrom(type);
73135446Strhodes    }
74135446Strhodes
75135446Strhodes    @Override
76135446Strhodes    public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices) throws Exception {
77135446Strhodes        final Object self = request.getReceiver();
78135446Strhodes        final CallSiteDescriptor desc = request.getCallSiteDescriptor();
79135446Strhodes        if (self == null || !canLinkTypeStatic(self.getClass())) {
80135446Strhodes            return null;
81135446Strhodes        }
82135446Strhodes
83135446Strhodes        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            }
180        } else if (isString(key)) {
181            final String name = key.toString();
182            // get with method name and signature. delegate it to beans linker!
183            if (name.indexOf('(') != -1) {
184                return fallback.invokeExact(jsobj, (Object) name);
185            }
186            return ((JSObject)jsobj).getMember(name);
187        }
188        return null;
189    }
190
191    @SuppressWarnings("unused")
192    private static void put(final Object jsobj, final Object key, final Object value) {
193        if (key instanceof Integer) {
194            ((JSObject)jsobj).setSlot((Integer)key, value);
195        } else if (key instanceof Number) {
196            ((JSObject)jsobj).setSlot(getIndex((Number)key), value);
197        } else if (isString(key)) {
198            ((JSObject)jsobj).setMember(key.toString(), value);
199        }
200    }
201
202    private static int getIndex(final Number n) {
203        final double value = n.doubleValue();
204        return JSType.isRepresentableAsInt(value) ? (int)value : -1;
205    }
206
207    @SuppressWarnings("unused")
208    private static Object callToApply(final MethodHandle mh, final JSObject obj, final Object thiz, final Object... args) {
209        assert args.length >= 2;
210        final Object   receiver  = args[0];
211        final Object[] arguments = new Object[args.length - 1];
212        System.arraycopy(args, 1, arguments, 0, arguments.length);
213        try {
214            return mh.invokeExact(obj, thiz, new Object[] { receiver, arguments });
215        } catch (final RuntimeException | Error e) {
216            throw e;
217        } catch (final Throwable e) {
218            throw new RuntimeException(e);
219        }
220    }
221
222    // This is used when a JSObject is called as scope call to do undefined -> Global this translation.
223    @SuppressWarnings("unused")
224    private static Object jsObjectScopeCall(final JSObject jsObj, final Object thiz, final Object[] args) {
225        final Object modifiedThiz;
226        if (thiz == ScriptRuntime.UNDEFINED && !jsObj.isStrictFunction()) {
227            final Global global = Context.getGlobal();
228            modifiedThiz = ScriptObjectMirror.wrap(global, global);
229        } else {
230            modifiedThiz = thiz;
231        }
232        return jsObj.call(modifiedThiz, args);
233    }
234
235    private static final MethodHandleFunctionality MH = MethodHandleFactory.getFunctionality();
236
237    // method handles of the current class
238    private static final MethodHandle IS_JSOBJECT_GUARD  = findOwnMH_S("isJSObject", boolean.class, Object.class);
239    private static final MethodHandle JSOBJECTLINKER_GET = findOwnMH_S("get", Object.class, MethodHandle.class, Object.class, Object.class);
240    private static final MethodHandle JSOBJECTLINKER_PUT = findOwnMH_S("put", Void.TYPE, Object.class, Object.class, Object.class);
241
242    // method handles of JSObject class
243    private static final MethodHandle JSOBJECT_GETMEMBER     = findJSObjectMH_V("getMember", Object.class, String.class);
244    private static final MethodHandle JSOBJECT_SETMEMBER     = findJSObjectMH_V("setMember", Void.TYPE, String.class, Object.class);
245    private static final MethodHandle JSOBJECT_CALL          = findJSObjectMH_V("call", Object.class, Object.class, Object[].class);
246    private static final MethodHandle JSOBJECT_SCOPE_CALL    = findOwnMH_S("jsObjectScopeCall", Object.class, JSObject.class, Object.class, Object[].class);
247    private static final MethodHandle JSOBJECT_CALL_TO_APPLY = findOwnMH_S("callToApply", Object.class, MethodHandle.class, JSObject.class, Object.class, Object[].class);
248    private static final MethodHandle JSOBJECT_NEW           = findJSObjectMH_V("newObject", Object.class, Object[].class);
249
250    private static MethodHandle findJSObjectMH_V(final String name, final Class<?> rtype, final Class<?>... types) {
251        return MH.findVirtual(MethodHandles.lookup(), JSObject.class, name, MH.type(rtype, types));
252    }
253
254    private static MethodHandle findOwnMH_S(final String name, final Class<?> rtype, final Class<?>... types) {
255        return MH.findStatic(MethodHandles.lookup(), JSObjectLinker.class, name, MH.type(rtype, types));
256    }
257}
258