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