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