BrowserJSObjectLinker.java revision 1470:04ed602df062
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 LinkRequest requestWithoutContext = request.withoutRuntimeContext(); // Nashorn has no runtime context
100        final Object self = requestWithoutContext.getReceiver();
101        final CallSiteDescriptor desc = requestWithoutContext.getCallSiteDescriptor();
102        checkJSObjectClass();
103
104        if (desc.getNameTokenCount() < 2 || !"dyn".equals(desc.getNameToken(CallSiteDescriptor.SCHEME))) {
105            // We only support standard "dyn:*[:*]" operations
106            return null;
107        }
108
109        GuardedInvocation inv;
110        if (jsObjectClass.isInstance(self)) {
111            inv = lookup(desc, request, linkerServices);
112            inv = inv.replaceMethods(linkerServices.filterInternalObjects(inv.getInvocation()), inv.getGuard());
113        } else {
114            throw new AssertionError(); // Should never reach here.
115        }
116
117        return Bootstrap.asTypeSafeReturn(inv, linkerServices, desc);
118    }
119
120    private GuardedInvocation lookup(final CallSiteDescriptor desc, final LinkRequest request, final LinkerServices linkerServices) throws Exception {
121        final String operator = desc.tokenizeOperators().get(0);
122        final int c = desc.getNameTokenCount();
123        GuardedInvocation inv;
124        try {
125            inv = nashornBeansLinker.getGuardedInvocation(request, linkerServices);
126        } catch (final Throwable th) {
127            inv = null;
128        }
129
130        switch (operator) {
131            case "getProp":
132            case "getElem":
133            case "getMethod":
134                return c > 2? findGetMethod(desc, inv) : findGetIndexMethod(inv);
135            case "setProp":
136            case "setElem":
137                return c > 2? findSetMethod(desc, inv) : findSetIndexMethod();
138            case "call":
139                return findCallMethod(desc);
140            default:
141                return null;
142        }
143    }
144
145    private static GuardedInvocation findGetMethod(final CallSiteDescriptor desc, final GuardedInvocation inv) {
146        if (inv != null) {
147            return inv;
148        }
149        final String name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
150        final MethodHandle getter = MH.insertArguments(JSOBJECT_GETMEMBER, 1, name);
151        return new GuardedInvocation(getter, IS_JSOBJECT_GUARD);
152    }
153
154    private static GuardedInvocation findGetIndexMethod(final GuardedInvocation inv) {
155        final MethodHandle getter = MH.insertArguments(JSOBJECTLINKER_GET, 0, inv.getInvocation());
156        return inv.replaceMethods(getter, inv.getGuard());
157    }
158
159    private static GuardedInvocation findSetMethod(final CallSiteDescriptor desc, final GuardedInvocation inv) {
160        if (inv != null) {
161            return inv;
162        }
163        final MethodHandle getter = MH.insertArguments(JSOBJECT_SETMEMBER, 1, desc.getNameToken(2));
164        return new GuardedInvocation(getter, IS_JSOBJECT_GUARD);
165    }
166
167    private static GuardedInvocation findSetIndexMethod() {
168        return new GuardedInvocation(JSOBJECTLINKER_PUT, IS_JSOBJECT_GUARD);
169    }
170
171    private static GuardedInvocation findCallMethod(final CallSiteDescriptor desc) {
172        final MethodHandle call = MH.insertArguments(JSOBJECT_CALL, 1, "call");
173        return new GuardedInvocation(MH.asCollector(call, Object[].class, desc.getMethodType().parameterCount() - 1), IS_JSOBJECT_GUARD);
174    }
175
176    @SuppressWarnings("unused")
177    private static boolean isJSObject(final Object self) {
178        return jsObjectClass.isInstance(self);
179    }
180
181    @SuppressWarnings("unused")
182    private static Object get(final MethodHandle fallback, final Object jsobj, final Object key) throws Throwable {
183        if (key instanceof Integer) {
184            return JSOBJECT_GETSLOT.invokeExact(jsobj, (int)key);
185        } else if (key instanceof Number) {
186            final int index = getIndex((Number)key);
187            if (index > -1) {
188                return JSOBJECT_GETSLOT.invokeExact(jsobj, index);
189            }
190        } else if (isString(key)) {
191            final String name = key.toString();
192            if (name.indexOf('(') != -1) {
193                return fallback.invokeExact(jsobj, (Object) name);
194            }
195            return JSOBJECT_GETMEMBER.invokeExact(jsobj, name);
196        }
197        return null;
198    }
199
200    @SuppressWarnings("unused")
201    private static void put(final Object jsobj, final Object key, final Object value) throws Throwable {
202        if (key instanceof Integer) {
203            JSOBJECT_SETSLOT.invokeExact(jsobj, (int)key, value);
204        } else if (key instanceof Number) {
205            JSOBJECT_SETSLOT.invokeExact(jsobj, getIndex((Number)key), value);
206        } else if (isString(key)) {
207            JSOBJECT_SETMEMBER.invokeExact(jsobj, key.toString(), value);
208        }
209    }
210
211    private static int getIndex(final Number n) {
212        final double value = n.doubleValue();
213        return JSType.isRepresentableAsInt(value) ? (int)value : -1;
214    }
215
216    private static final MethodHandleFunctionality MH = MethodHandleFactory.getFunctionality();
217    // method handles of the current class
218    private static final MethodHandle IS_JSOBJECT_GUARD  = findOwnMH_S("isJSObject", boolean.class, Object.class);
219    private static final MethodHandle JSOBJECTLINKER_GET = findOwnMH_S("get", Object.class, MethodHandle.class, Object.class, Object.class);
220    private static final MethodHandle JSOBJECTLINKER_PUT = findOwnMH_S("put", Void.TYPE, Object.class, Object.class, Object.class);
221
222    private static MethodHandle findOwnMH_S(final String name, final Class<?> rtype, final Class<?>... types) {
223            return MH.findStatic(MethodHandles.lookup(), BrowserJSObjectLinker.class, name, MH.type(rtype, types));
224    }
225
226    // method handles of netscape.javascript.JSObject class
227    // These are in separate class as we lazily initialize these
228    // method handles when we hit a subclass of JSObject first time.
229    static class JSObjectHandles {
230        // method handles of JSObject class
231        static final MethodHandle JSOBJECT_GETMEMBER     = findJSObjectMH_V("getMember", Object.class, String.class).asType(MH.type(Object.class, Object.class, String.class));
232        static final MethodHandle JSOBJECT_GETSLOT       = findJSObjectMH_V("getSlot", Object.class, int.class).asType(MH.type(Object.class, Object.class, int.class));
233        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));
234        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));
235        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));
236
237        private static MethodHandle findJSObjectMH_V(final String name, final Class<?> rtype, final Class<?>... types) {
238            checkJSObjectClass();
239            return MH.findVirtual(MethodHandles.publicLookup(), jsObjectClass, name, MH.type(rtype, types));
240        }
241    }
242}
243