BrowserJSObjectLinker.java revision 1445:8535274223d7
1/*
2 * Copyright (c) 2014, 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;
29import static jdk.nashorn.internal.runtime.linker.BrowserJSObjectLinker.JSObjectHandles.JSOBJECT_CALL;
30import static jdk.nashorn.internal.runtime.linker.BrowserJSObjectLinker.JSObjectHandles.JSOBJECT_GETMEMBER;
31import static jdk.nashorn.internal.runtime.linker.BrowserJSObjectLinker.JSObjectHandles.JSOBJECT_GETSLOT;
32import static jdk.nashorn.internal.runtime.linker.BrowserJSObjectLinker.JSObjectHandles.JSOBJECT_SETMEMBER;
33import static jdk.nashorn.internal.runtime.linker.BrowserJSObjectLinker.JSObjectHandles.JSOBJECT_SETSLOT;
34
35import java.lang.invoke.MethodHandle;
36import java.lang.invoke.MethodHandles;
37import jdk.internal.dynalink.CallSiteDescriptor;
38import jdk.internal.dynalink.linker.GuardedInvocation;
39import jdk.internal.dynalink.linker.LinkRequest;
40import jdk.internal.dynalink.linker.LinkerServices;
41import jdk.internal.dynalink.linker.TypeBasedGuardingDynamicLinker;
42import jdk.internal.dynalink.support.CallSiteDescriptorFactory;
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.
49 */
50final class BrowserJSObjectLinker implements TypeBasedGuardingDynamicLinker {
51    private static ClassLoader extLoader;
52    static {
53        extLoader = BrowserJSObjectLinker.class.getClassLoader();
54        // in case nashorn is loaded as bootstrap!
55        if (extLoader == null) {
56            extLoader = ClassLoader.getSystemClassLoader().getParent();
57        }
58    }
59
60    private static final String JSOBJECT_CLASS = "netscape.javascript.JSObject";
61    // not final because this is lazily initialized
62    // when we hit a subclass for the first time.
63    private static volatile Class<?> jsObjectClass;
64    private final NashornBeansLinker nashornBeansLinker;
65
66    BrowserJSObjectLinker(final NashornBeansLinker nashornBeansLinker) {
67        this.nashornBeansLinker = nashornBeansLinker;
68    }
69
70    @Override
71    public boolean canLinkType(final Class<?> type) {
72        return canLinkTypeStatic(type);
73    }
74
75    static boolean canLinkTypeStatic(final Class<?> type) {
76        if (jsObjectClass != null && jsObjectClass.isAssignableFrom(type)) {
77            return true;
78        }
79
80        // check if this class is a subclass of JSObject
81        Class<?> clazz = type;
82        while (clazz != null) {
83            if (clazz.getClassLoader() == extLoader &&
84                clazz.getName().equals(JSOBJECT_CLASS)) {
85                jsObjectClass = clazz;
86                return true;
87            }
88            clazz = clazz.getSuperclass();
89        }
90
91        return false;
92    }
93
94    private static void checkJSObjectClass() {
95        assert jsObjectClass != null : JSOBJECT_CLASS + " not found!";
96    }
97
98    @Override
99    public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices) throws Exception {
100        final LinkRequest requestWithoutContext = request.withoutRuntimeContext(); // Nashorn has no runtime context
101        final Object self = requestWithoutContext.getReceiver();
102        final CallSiteDescriptor desc = requestWithoutContext.getCallSiteDescriptor();
103        checkJSObjectClass();
104
105        if (desc.getNameTokenCount() < 2 || !"dyn".equals(desc.getNameToken(CallSiteDescriptor.SCHEME))) {
106            // We only support standard "dyn:*[:*]" operations
107            return null;
108        }
109
110        GuardedInvocation inv;
111        if (jsObjectClass.isInstance(self)) {
112            inv = lookup(desc, request, linkerServices);
113            inv = inv.replaceMethods(linkerServices.filterInternalObjects(inv.getInvocation()), inv.getGuard());
114        } else {
115            throw new AssertionError(); // Should never reach here.
116        }
117
118        return Bootstrap.asTypeSafeReturn(inv, linkerServices, desc);
119    }
120
121    private GuardedInvocation lookup(final CallSiteDescriptor desc, final LinkRequest request, final LinkerServices linkerServices) throws Exception {
122        final String operator = CallSiteDescriptorFactory.tokenizeOperators(desc).get(0);
123        final int c = desc.getNameTokenCount();
124        GuardedInvocation inv;
125        try {
126            inv = nashornBeansLinker.getGuardedInvocation(request, linkerServices);
127        } catch (Throwable th) {
128            inv = null;
129        }
130
131        switch (operator) {
132            case "getProp":
133            case "getElem":
134            case "getMethod":
135                return c > 2? findGetMethod(desc, inv) : findGetIndexMethod(inv);
136            case "setProp":
137            case "setElem":
138                return c > 2? findSetMethod(desc, inv) : findSetIndexMethod();
139            case "call":
140                return findCallMethod(desc);
141            default:
142                return null;
143        }
144    }
145
146    private static GuardedInvocation findGetMethod(final CallSiteDescriptor desc, final GuardedInvocation inv) {
147        if (inv != null) {
148            return inv;
149        }
150        final String name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
151        final MethodHandle getter = MH.insertArguments(JSOBJECT_GETMEMBER, 1, name);
152        return new GuardedInvocation(getter, IS_JSOBJECT_GUARD);
153    }
154
155    private static GuardedInvocation findGetIndexMethod(final GuardedInvocation inv) {
156        final MethodHandle getter = MH.insertArguments(JSOBJECTLINKER_GET, 0, inv.getInvocation());
157        return inv.replaceMethods(getter, inv.getGuard());
158    }
159
160    private static GuardedInvocation findSetMethod(final CallSiteDescriptor desc, final GuardedInvocation inv) {
161        if (inv != null) {
162            return inv;
163        }
164        final MethodHandle getter = MH.insertArguments(JSOBJECT_SETMEMBER, 1, desc.getNameToken(2));
165        return new GuardedInvocation(getter, IS_JSOBJECT_GUARD);
166    }
167
168    private static GuardedInvocation findSetIndexMethod() {
169        return new GuardedInvocation(JSOBJECTLINKER_PUT, IS_JSOBJECT_GUARD);
170    }
171
172    private static GuardedInvocation findCallMethod(final CallSiteDescriptor desc) {
173        final MethodHandle call = MH.insertArguments(JSOBJECT_CALL, 1, "call");
174        return new GuardedInvocation(MH.asCollector(call, Object[].class, desc.getMethodType().parameterCount() - 1), IS_JSOBJECT_GUARD);
175    }
176
177    @SuppressWarnings("unused")
178    private static boolean isJSObject(final Object self) {
179        return jsObjectClass.isInstance(self);
180    }
181
182    @SuppressWarnings("unused")
183    private static Object get(final MethodHandle fallback, final Object jsobj, final Object key) throws Throwable {
184        if (key instanceof Integer) {
185            return JSOBJECT_GETSLOT.invokeExact(jsobj, (int)key);
186        } else if (key instanceof Number) {
187            final int index = getIndex((Number)key);
188            if (index > -1) {
189                return JSOBJECT_GETSLOT.invokeExact(jsobj, index);
190            }
191        } else if (isString(key)) {
192            final String name = key.toString();
193            if (name.indexOf('(') != -1) {
194                return fallback.invokeExact(jsobj, (Object) name);
195            }
196            return JSOBJECT_GETMEMBER.invokeExact(jsobj, name);
197        }
198        return null;
199    }
200
201    @SuppressWarnings("unused")
202    private static void put(final Object jsobj, final Object key, final Object value) throws Throwable {
203        if (key instanceof Integer) {
204            JSOBJECT_SETSLOT.invokeExact(jsobj, (int)key, value);
205        } else if (key instanceof Number) {
206            JSOBJECT_SETSLOT.invokeExact(jsobj, getIndex((Number)key), value);
207        } else if (isString(key)) {
208            JSOBJECT_SETMEMBER.invokeExact(jsobj, key.toString(), value);
209        }
210    }
211
212    private static int getIndex(final Number n) {
213        final double value = n.doubleValue();
214        return JSType.isRepresentableAsInt(value) ? (int)value : -1;
215    }
216
217    private static final MethodHandleFunctionality MH = MethodHandleFactory.getFunctionality();
218    // method handles of the current class
219    private static final MethodHandle IS_JSOBJECT_GUARD  = findOwnMH_S("isJSObject", boolean.class, Object.class);
220    private static final MethodHandle JSOBJECTLINKER_GET = findOwnMH_S("get", Object.class, MethodHandle.class, Object.class, Object.class);
221    private static final MethodHandle JSOBJECTLINKER_PUT = findOwnMH_S("put", Void.TYPE, Object.class, Object.class, Object.class);
222
223    private static MethodHandle findOwnMH_S(final String name, final Class<?> rtype, final Class<?>... types) {
224            return MH.findStatic(MethodHandles.lookup(), BrowserJSObjectLinker.class, name, MH.type(rtype, types));
225    }
226
227    // method handles of netscape.javascript.JSObject class
228    // These are in separate class as we lazily initialize these
229    // method handles when we hit a subclass of JSObject first time.
230    static class JSObjectHandles {
231        // method handles of JSObject class
232        static final MethodHandle JSOBJECT_GETMEMBER     = findJSObjectMH_V("getMember", Object.class, String.class).asType(MH.type(Object.class, Object.class, String.class));
233        static final MethodHandle JSOBJECT_GETSLOT       = findJSObjectMH_V("getSlot", Object.class, int.class).asType(MH.type(Object.class, Object.class, int.class));
234        static final MethodHandle JSOBJECT_SETMEMBER     = findJSObjectMH_V("setMember", Void.TYPE, String.class, Object.class).asType(MH.type(Void.TYPE, Object.class, String.class, Object.class));
235        static final MethodHandle JSOBJECT_SETSLOT       = findJSObjectMH_V("setSlot", Void.TYPE, int.class, Object.class).asType(MH.type(Void.TYPE, Object.class, int.class, Object.class));
236        static final MethodHandle JSOBJECT_CALL          = findJSObjectMH_V("call", Object.class, String.class, Object[].class).asType(MH.type(Object.class, Object.class, String.class, Object[].class));
237
238        private static MethodHandle findJSObjectMH_V(final String name, final Class<?> rtype, final Class<?>... types) {
239            checkJSObjectClass();
240            return MH.findVirtual(MethodHandles.publicLookup(), jsObjectClass, name, MH.type(rtype, types));
241        }
242    }
243}
244