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