1 /*
   2  * Copyright (c) 2010, 2016, 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 
  30 import java.lang.invoke.MethodHandle;
  31 import java.lang.invoke.MethodHandles;
  32 import java.lang.invoke.MethodType;
  33 import java.util.Map;
  34 import javax.script.Bindings;
  35 import jdk.dynalink.CallSiteDescriptor;
  36 import jdk.dynalink.StandardOperation;
  37 import jdk.dynalink.linker.GuardedInvocation;
  38 import jdk.dynalink.linker.LinkRequest;
  39 import jdk.dynalink.linker.LinkerServices;
  40 import jdk.dynalink.linker.TypeBasedGuardingDynamicLinker;
  41 import jdk.nashorn.api.scripting.JSObject;
  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 as well
  48  * as ScriptObjects from other Nashorn contexts.
  49  */
  50 final class JSObjectLinker implements TypeBasedGuardingDynamicLinker {
  51     private final NashornBeansLinker nashornBeansLinker;
  52 
  53     JSObjectLinker(final NashornBeansLinker nashornBeansLinker) {
  54         this.nashornBeansLinker = nashornBeansLinker;
  55     }
  56 
  57     @Override
  58     public boolean canLinkType(final Class<?> type) {
  59         return canLinkTypeStatic(type);
  60     }
  61 
  62     static boolean canLinkTypeStatic(final Class<?> type) {
  63         // can link JSObject also handles Map, Bindings to make
  64         // sure those are not JSObjects.
  65         return Map.class.isAssignableFrom(type) ||
  66                Bindings.class.isAssignableFrom(type) ||
  67                JSObject.class.isAssignableFrom(type);
  68     }
  69 
  70     @Override
  71     public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices) throws Exception {
  72         final Object self = request.getReceiver();
  73         final CallSiteDescriptor desc = request.getCallSiteDescriptor();
  74 
  75         GuardedInvocation inv;
  76         if (self instanceof JSObject) {
  77             inv = lookup(desc, request, linkerServices);
  78             inv = inv.replaceMethods(linkerServices.filterInternalObjects(inv.getInvocation()), inv.getGuard());
  79         } else if (self instanceof Map || self instanceof Bindings) {
  80             // guard to make sure the Map or Bindings does not turn into JSObject later!
  81             final GuardedInvocation beanInv = nashornBeansLinker.getGuardedInvocation(request, linkerServices);
  82             inv = new GuardedInvocation(beanInv.getInvocation(),
  83                 NashornGuards.combineGuards(beanInv.getGuard(), NashornGuards.getNotJSObjectGuard()));
  84         } else {
  85             throw new AssertionError(); // Should never reach here.
  86         }
  87 
  88         return Bootstrap.asTypeSafeReturn(inv, linkerServices, desc);
  89     }
  90 
  91     private GuardedInvocation lookup(final CallSiteDescriptor desc, final LinkRequest request, final LinkerServices linkerServices) throws Exception {
  92         final StandardOperation op = NashornCallSiteDescriptor.getFirstStandardOperation(desc);
  93         if (op == null) {
  94             return null;
  95         }
  96         final String name = NashornCallSiteDescriptor.getOperand(desc);
  97         switch (op) {
  98         case GET_PROPERTY:
  99         case GET_ELEMENT:
 100         case GET_METHOD:
 101             if (name != null) {
 102                 return findGetMethod(name);
 103             }
 104             // For indexed get, we want get GuardedInvocation beans linker and pass it.
 105             // JSObjectLinker.get uses this fallback getter for explicit signature method access.
 106             return findGetIndexMethod(nashornBeansLinker.getGuardedInvocation(request, linkerServices));
 107         case SET_PROPERTY:
 108         case SET_ELEMENT:
 109             return name != null ? findSetMethod(name) : findSetIndexMethod();
 110         case CALL:
 111             return findCallMethod(desc);
 112         case NEW:
 113             return findNewMethod(desc);
 114         default:
 115         }
 116         return null;
 117     }
 118 
 119     private static GuardedInvocation findGetMethod(final String name) {
 120         final MethodHandle getter = MH.insertArguments(JSOBJECT_GETMEMBER, 1, name);
 121         return new GuardedInvocation(getter, IS_JSOBJECT_GUARD);
 122     }
 123 
 124     private static GuardedInvocation findGetIndexMethod(final GuardedInvocation inv) {
 125         final MethodHandle getter = MH.insertArguments(JSOBJECTLINKER_GET, 0, inv.getInvocation());
 126         return inv.replaceMethods(getter, inv.getGuard());
 127     }
 128 
 129     private static GuardedInvocation findSetMethod(final String name) {
 130         final MethodHandle getter = MH.insertArguments(JSOBJECT_SETMEMBER, 1, name);
 131         return new GuardedInvocation(getter, IS_JSOBJECT_GUARD);
 132     }
 133 
 134     private static GuardedInvocation findSetIndexMethod() {
 135         return new GuardedInvocation(JSOBJECTLINKER_PUT, IS_JSOBJECT_GUARD);
 136     }
 137 
 138     private static GuardedInvocation findCallMethod(final CallSiteDescriptor desc) {
 139         MethodHandle mh = JSOBJECT_CALL;
 140         if (NashornCallSiteDescriptor.isApplyToCall(desc)) {
 141             mh = MH.insertArguments(JSOBJECT_CALL_TO_APPLY, 0, JSOBJECT_CALL);
 142         }
 143         final MethodType type = desc.getMethodType();
 144         mh = type.parameterType(type.parameterCount() - 1) == Object[].class ?
 145                 mh :
 146                 MH.asCollector(mh, Object[].class, type.parameterCount() - 2);
 147         return new GuardedInvocation(mh, IS_JSOBJECT_GUARD);
 148     }
 149 
 150     private static GuardedInvocation findNewMethod(final CallSiteDescriptor desc) {
 151         final MethodHandle func = MH.asCollector(JSOBJECT_NEW, Object[].class, desc.getMethodType().parameterCount() - 1);
 152         return new GuardedInvocation(func, IS_JSOBJECT_GUARD);
 153     }
 154 
 155     @SuppressWarnings("unused")
 156     private static boolean isJSObject(final Object self) {
 157         return self instanceof JSObject;
 158     }
 159 
 160     @SuppressWarnings("unused")
 161     private static Object get(final MethodHandle fallback, final Object jsobj, final Object key)
 162         throws Throwable {
 163         if (key instanceof Integer) {
 164             return ((JSObject)jsobj).getSlot((Integer)key);
 165         } else if (key instanceof Number) {
 166             final int index = getIndex((Number)key);
 167             if (index > -1) {
 168                 return ((JSObject)jsobj).getSlot(index);
 169             }
 170         } else if (isString(key)) {
 171             final String name = key.toString();
 172             // get with method name and signature. delegate it to beans linker!
 173             if (name.indexOf('(') != -1) {
 174                 return fallback.invokeExact(jsobj, (Object) name);
 175             }
 176             return ((JSObject)jsobj).getMember(name);
 177         }
 178         return null;
 179     }
 180 
 181     @SuppressWarnings("unused")
 182     private static void put(final Object jsobj, final Object key, final Object value) {
 183         if (key instanceof Integer) {
 184             ((JSObject)jsobj).setSlot((Integer)key, value);
 185         } else if (key instanceof Number) {
 186             ((JSObject)jsobj).setSlot(getIndex((Number)key), value);
 187         } else if (isString(key)) {
 188             ((JSObject)jsobj).setMember(key.toString(), value);
 189         }
 190     }
 191 
 192     private static int getIndex(final Number n) {
 193         final double value = n.doubleValue();
 194         return JSType.isRepresentableAsInt(value) ? (int)value : -1;
 195     }
 196 
 197     @SuppressWarnings("unused")
 198     private static Object callToApply(final MethodHandle mh, final JSObject obj, final Object thiz, final Object... args) {
 199         assert args.length >= 2;
 200         final Object   receiver  = args[0];
 201         final Object[] arguments = new Object[args.length - 1];
 202         System.arraycopy(args, 1, arguments, 0, arguments.length);
 203         try {
 204             return mh.invokeExact(obj, thiz, new Object[] { receiver, arguments });
 205         } catch (final RuntimeException | Error e) {
 206             throw e;
 207         } catch (final Throwable e) {
 208             throw new RuntimeException(e);
 209         }
 210     }
 211 
 212     private static final MethodHandleFunctionality MH = MethodHandleFactory.getFunctionality();
 213 
 214     // method handles of the current class
 215     private static final MethodHandle IS_JSOBJECT_GUARD  = findOwnMH_S("isJSObject", boolean.class, Object.class);
 216     private static final MethodHandle JSOBJECTLINKER_GET = findOwnMH_S("get", Object.class, MethodHandle.class, Object.class, Object.class);
 217     private static final MethodHandle JSOBJECTLINKER_PUT = findOwnMH_S("put", Void.TYPE, Object.class, Object.class, Object.class);
 218 
 219     // method handles of JSObject class
 220     private static final MethodHandle JSOBJECT_GETMEMBER     = findJSObjectMH_V("getMember", Object.class, String.class);
 221     private static final MethodHandle JSOBJECT_SETMEMBER     = findJSObjectMH_V("setMember", Void.TYPE, String.class, Object.class);
 222     private static final MethodHandle JSOBJECT_CALL          = findJSObjectMH_V("call", Object.class, Object.class, Object[].class);
 223     private static final MethodHandle JSOBJECT_CALL_TO_APPLY = findOwnMH_S("callToApply", Object.class, MethodHandle.class, JSObject.class, Object.class, Object[].class);
 224     private static final MethodHandle JSOBJECT_NEW           = findJSObjectMH_V("newObject", Object.class, Object[].class);
 225 
 226     private static MethodHandle findJSObjectMH_V(final String name, final Class<?> rtype, final Class<?>... types) {
 227         return MH.findVirtual(MethodHandles.lookup(), JSObject.class, name, MH.type(rtype, types));
 228     }
 229 
 230     private static MethodHandle findOwnMH_S(final String name, final Class<?> rtype, final Class<?>... types) {
 231         return MH.findStatic(MethodHandles.lookup(), JSObjectLinker.class, name, MH.type(rtype, types));
 232     }
 233 }