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 
  26 package jdk.nashorn.internal.runtime.linker;
  27 
  28 import static jdk.nashorn.internal.runtime.JSType.isString;
  29 import static jdk.nashorn.internal.runtime.linker.BrowserJSObjectLinker.JSObjectHandles.JSOBJECT_CALL;
  30 import static jdk.nashorn.internal.runtime.linker.BrowserJSObjectLinker.JSObjectHandles.JSOBJECT_GETMEMBER;
  31 import static jdk.nashorn.internal.runtime.linker.BrowserJSObjectLinker.JSObjectHandles.JSOBJECT_GETSLOT;
  32 import static jdk.nashorn.internal.runtime.linker.BrowserJSObjectLinker.JSObjectHandles.JSOBJECT_SETMEMBER;
  33 import static jdk.nashorn.internal.runtime.linker.BrowserJSObjectLinker.JSObjectHandles.JSOBJECT_SETSLOT;
  34 
  35 import java.lang.invoke.MethodHandle;
  36 import java.lang.invoke.MethodHandles;
  37 import jdk.dynalink.CallSiteDescriptor;
  38 import jdk.dynalink.linker.GuardedInvocation;
  39 import jdk.dynalink.linker.LinkRequest;
  40 import jdk.dynalink.linker.LinkerServices;
  41 import jdk.dynalink.linker.TypeBasedGuardingDynamicLinker;
  42 import jdk.nashorn.internal.lookup.MethodHandleFactory;
  43 import jdk.nashorn.internal.lookup.MethodHandleFunctionality;
  44 import jdk.nashorn.internal.runtime.JSType;
  45 
  46 /**
  47  * A Dynalink linker to handle web browser built-in JS (DOM etc.) objects.
  48  */
  49 final class BrowserJSObjectLinker implements TypeBasedGuardingDynamicLinker {
  50     private static final String JSOBJECT_CLASS = "netscape.javascript.JSObject";
  51     private static final Class<?> jsObjectClass = findBrowserJSObjectClass();
  52     private final NashornBeansLinker nashornBeansLinker;
  53 
  54     BrowserJSObjectLinker(final NashornBeansLinker nashornBeansLinker) {
  55         this.nashornBeansLinker = nashornBeansLinker;
  56     }
  57 
  58     @Override
  59     public boolean canLinkType(final Class<?> type) {
  60         return canLinkTypeStatic(type);
  61     }
  62 
  63     static boolean canLinkTypeStatic(final Class<?> type) {
  64         return jsObjectClass != null && jsObjectClass.isAssignableFrom(type);
  65     }
  66 
  67     private static void checkJSObjectClass() {
  68         assert jsObjectClass != null : JSOBJECT_CLASS + " not found!";
  69     }
  70 
  71     @Override
  72     public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices) throws Exception {
  73         final Object self = request.getReceiver();
  74         final CallSiteDescriptor desc = request.getCallSiteDescriptor();
  75         checkJSObjectClass();
  76 
  77         assert jsObjectClass.isInstance(self);
  78 
  79         GuardedInvocation inv = lookup(desc, request, linkerServices);
  80         inv = inv.replaceMethods(linkerServices.filterInternalObjects(inv.getInvocation()), inv.getGuard());
  81 
  82         return Bootstrap.asTypeSafeReturn(inv, linkerServices, desc);
  83     }
  84 
  85     private GuardedInvocation lookup(final CallSiteDescriptor desc, final LinkRequest request, final LinkerServices linkerServices) throws Exception {
  86         GuardedInvocation inv;
  87         try {
  88             inv = nashornBeansLinker.getGuardedInvocation(request, linkerServices);
  89         } catch (final Throwable th) {
  90             inv = null;
  91         }
  92 
  93         final String name = NashornCallSiteDescriptor.getOperand(desc);
  94         switch (NashornCallSiteDescriptor.getStandardOperation(desc)) {
  95         case GET:
  96             return name != null ? findGetMethod(name, inv) : findGetIndexMethod(inv);
  97         case SET:
  98             return name != null ? findSetMethod(name, inv) : findSetIndexMethod();
  99         case CALL:
 100             return findCallMethod(desc);
 101         default:
 102             return null;
 103         }
 104     }
 105 
 106     private static GuardedInvocation findGetMethod(final String name, final GuardedInvocation inv) {
 107         if (inv != null) {
 108             return inv;
 109         }
 110         final MethodHandle getter = MH.insertArguments(JSOBJECT_GETMEMBER, 1, name);
 111         return new GuardedInvocation(getter, IS_JSOBJECT_GUARD);
 112     }
 113 
 114     private static GuardedInvocation findGetIndexMethod(final GuardedInvocation inv) {
 115         final MethodHandle getter = MH.insertArguments(JSOBJECTLINKER_GET, 0, inv.getInvocation());
 116         return inv.replaceMethods(getter, inv.getGuard());
 117     }
 118 
 119     private static GuardedInvocation findSetMethod(final String name, final GuardedInvocation inv) {
 120         if (inv != null) {
 121             return inv;
 122         }
 123         final MethodHandle getter = MH.insertArguments(JSOBJECT_SETMEMBER, 1, name);
 124         return new GuardedInvocation(getter, IS_JSOBJECT_GUARD);
 125     }
 126 
 127     private static GuardedInvocation findSetIndexMethod() {
 128         return new GuardedInvocation(JSOBJECTLINKER_PUT, IS_JSOBJECT_GUARD);
 129     }
 130 
 131     private static GuardedInvocation findCallMethod(final CallSiteDescriptor desc) {
 132         final MethodHandle call = MH.insertArguments(JSOBJECT_CALL, 1, "call");
 133         return new GuardedInvocation(MH.asCollector(call, Object[].class, desc.getMethodType().parameterCount() - 1), IS_JSOBJECT_GUARD);
 134     }
 135 
 136     @SuppressWarnings("unused")
 137     private static boolean isJSObject(final Object self) {
 138         return jsObjectClass.isInstance(self);
 139     }
 140 
 141     @SuppressWarnings("unused")
 142     private static Object get(final MethodHandle fallback, final Object jsobj, final Object key) throws Throwable {
 143         if (key instanceof Integer) {
 144             return JSOBJECT_GETSLOT.invokeExact(jsobj, (int)key);
 145         } else if (key instanceof Number) {
 146             final int index = getIndex((Number)key);
 147             if (index > -1) {
 148                 return JSOBJECT_GETSLOT.invokeExact(jsobj, index);
 149             }
 150         } else if (isString(key)) {
 151             final String name = key.toString();
 152             if (name.indexOf('(') != -1) {
 153                 return fallback.invokeExact(jsobj, (Object) name);
 154             }
 155             return JSOBJECT_GETMEMBER.invokeExact(jsobj, name);
 156         }
 157         return null;
 158     }
 159 
 160     @SuppressWarnings("unused")
 161     private static void put(final Object jsobj, final Object key, final Object value) throws Throwable {
 162         if (key instanceof Integer) {
 163             JSOBJECT_SETSLOT.invokeExact(jsobj, (int)key, value);
 164         } else if (key instanceof Number) {
 165             JSOBJECT_SETSLOT.invokeExact(jsobj, getIndex((Number)key), value);
 166         } else if (isString(key)) {
 167             JSOBJECT_SETMEMBER.invokeExact(jsobj, key.toString(), value);
 168         }
 169     }
 170 
 171     private static int getIndex(final Number n) {
 172         final double value = n.doubleValue();
 173         return JSType.isRepresentableAsInt(value) ? (int)value : -1;
 174     }
 175 
 176     private static final MethodHandleFunctionality MH = MethodHandleFactory.getFunctionality();
 177     // method handles of the current class
 178     private static final MethodHandle IS_JSOBJECT_GUARD  = findOwnMH_S("isJSObject", boolean.class, Object.class);
 179     private static final MethodHandle JSOBJECTLINKER_GET = findOwnMH_S("get", Object.class, MethodHandle.class, Object.class, Object.class);
 180     private static final MethodHandle JSOBJECTLINKER_PUT = findOwnMH_S("put", Void.TYPE, Object.class, Object.class, Object.class);
 181 
 182     private static MethodHandle findOwnMH_S(final String name, final Class<?> rtype, final Class<?>... types) {
 183             return MH.findStatic(MethodHandles.lookup(), BrowserJSObjectLinker.class, name, MH.type(rtype, types));
 184     }
 185 
 186     // method handles of netscape.javascript.JSObject class
 187     // These are in separate class as we lazily initialize these
 188     // method handles when we hit a subclass of JSObject first time.
 189     static class JSObjectHandles {
 190         // method handles of JSObject class
 191         static final MethodHandle JSOBJECT_GETMEMBER     = findJSObjectMH_V("getMember", Object.class, String.class).asType(MH.type(Object.class, Object.class, String.class));
 192         static final MethodHandle JSOBJECT_GETSLOT       = findJSObjectMH_V("getSlot", Object.class, int.class).asType(MH.type(Object.class, Object.class, int.class));
 193         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));
 194         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));
 195         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));
 196 
 197         private static MethodHandle findJSObjectMH_V(final String name, final Class<?> rtype, final Class<?>... types) {
 198             checkJSObjectClass();
 199             return MH.findVirtual(MethodHandles.publicLookup(), jsObjectClass, name, MH.type(rtype, types));
 200         }
 201     }
 202 
 203     private static Class<?> findBrowserJSObjectClass() {
 204         ClassLoader extLoader;
 205         extLoader = BrowserJSObjectLinker.class.getClassLoader();
 206         // in case nashorn is loaded as bootstrap!
 207         if (extLoader == null) {
 208             extLoader = ClassLoader.getSystemClassLoader().getParent();
 209         }
 210         try {
 211             return Class.forName(JSOBJECT_CLASS, false, extLoader);
 212         } catch (final ClassNotFoundException e) {
 213             return null;
 214         }
 215     }
 216 }