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 java.util.Objects;
  35 import jdk.dynalink.CallSiteDescriptor;
  36 import jdk.dynalink.Operation;
  37 import jdk.dynalink.StandardOperation;
  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.api.scripting.JSObject;
  43 import jdk.nashorn.api.scripting.ScriptObjectMirror;
  44 import jdk.nashorn.internal.lookup.MethodHandleFactory;
  45 import jdk.nashorn.internal.lookup.MethodHandleFunctionality;
  46 import jdk.nashorn.internal.runtime.Context;
  47 import jdk.nashorn.internal.runtime.JSType;
  48 import jdk.nashorn.internal.runtime.ScriptRuntime;
  49 import jdk.nashorn.internal.objects.Global;
  50 
  51 /**
  52  * A Dynalink linker to handle web browser built-in JS (DOM etc.) objects as well
  53  * as ScriptObjects from other Nashorn contexts.
  54  */
  55 final class JSObjectLinker implements TypeBasedGuardingDynamicLinker {
  56     private final NashornBeansLinker nashornBeansLinker;
  57 
  58     JSObjectLinker(final NashornBeansLinker nashornBeansLinker) {
  59         this.nashornBeansLinker = nashornBeansLinker;
  60     }
  61 
  62     @Override
  63     public boolean canLinkType(final Class<?> type) {
  64         return canLinkTypeStatic(type);
  65     }
  66 
  67     private static boolean canLinkTypeStatic(final Class<?> type) {
  68         // can link JSObject also handles Map (this includes Bindings) to make
  69         // sure those are not JSObjects.
  70         return Map.class.isAssignableFrom(type) ||
  71                JSObject.class.isAssignableFrom(type);
  72     }
  73 
  74     @Override
  75     public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices) throws Exception {
  76         final Object self = request.getReceiver();
  77         final CallSiteDescriptor desc = request.getCallSiteDescriptor();
  78         if (self == null || !canLinkTypeStatic(self.getClass())) {
  79             return null;
  80         }
  81 
  82         GuardedInvocation inv;
  83         if (self instanceof JSObject) {
  84             inv = lookup(desc, request, linkerServices);
  85             inv = inv.replaceMethods(linkerServices.filterInternalObjects(inv.getInvocation()), inv.getGuard());
  86         } else if (self instanceof Map) {
  87             // guard to make sure the Map or Bindings does not turn into JSObject later!
  88             final GuardedInvocation beanInv = nashornBeansLinker.getGuardedInvocation(request, linkerServices);
  89             inv = new GuardedInvocation(beanInv.getInvocation(),
  90                 NashornGuards.combineGuards(beanInv.getGuard(), NashornGuards.getNotJSObjectGuard()));
  91         } else {
  92             throw new AssertionError("got instanceof: " + self.getClass()); // Should never reach here.
  93         }
  94 
  95         return Bootstrap.asTypeSafeReturn(inv, linkerServices, desc);
  96     }
  97 
  98     private GuardedInvocation lookup(final CallSiteDescriptor desc, final LinkRequest request, final LinkerServices linkerServices) throws Exception {
  99         final Operation op = NashornCallSiteDescriptor.getBaseOperation(desc);
 100         if (op instanceof StandardOperation) {
 101             final String name = NashornCallSiteDescriptor.getOperand(desc);
 102             switch ((StandardOperation)op) {
 103             case GET:
 104                 if (NashornCallSiteDescriptor.hasStandardNamespace(desc)) {
 105                     if (name != null) {
 106                         return findGetMethod(name);
 107                     }
 108                     // For indexed get, we want get GuardedInvocation beans linker and pass it.
 109                     // JSObjectLinker.get uses this fallback getter for explicit signature method access.
 110                     return findGetIndexMethod(nashornBeansLinker.getGuardedInvocation(request, linkerServices));
 111                 }
 112                 break;
 113             case SET:
 114                 if (NashornCallSiteDescriptor.hasStandardNamespace(desc)) {
 115                     return name != null ? findSetMethod(name) : findSetIndexMethod();
 116                 }
 117                 break;
 118             case REMOVE:
 119                 if (NashornCallSiteDescriptor.hasStandardNamespace(desc)) {
 120                     return new GuardedInvocation(
 121                             name == null ? JSOBJECTLINKER_DEL : MH.insertArguments(JSOBJECTLINKER_DEL, 1, name),
 122                             IS_JSOBJECT_GUARD);
 123                 }
 124                 break;
 125             case CALL:
 126                 return findCallMethod(desc);
 127             case NEW:
 128                 return findNewMethod(desc);
 129             default:
 130             }
 131         }
 132         return null;
 133     }
 134 
 135     private static GuardedInvocation findGetMethod(final String name) {
 136         final MethodHandle getter = MH.insertArguments(JSOBJECT_GETMEMBER, 1, name);
 137         return new GuardedInvocation(getter, IS_JSOBJECT_GUARD);
 138     }
 139 
 140     private static GuardedInvocation findGetIndexMethod(final GuardedInvocation inv) {
 141         final MethodHandle getter = MH.insertArguments(JSOBJECTLINKER_GET, 0, inv.getInvocation());
 142         return inv.replaceMethods(getter, inv.getGuard());
 143     }
 144 
 145     private static GuardedInvocation findSetMethod(final String name) {
 146         final MethodHandle getter = MH.insertArguments(JSOBJECT_SETMEMBER, 1, name);
 147         return new GuardedInvocation(getter, IS_JSOBJECT_GUARD);
 148     }
 149 
 150     private static GuardedInvocation findSetIndexMethod() {
 151         return new GuardedInvocation(JSOBJECTLINKER_PUT, IS_JSOBJECT_GUARD);
 152     }
 153 
 154     private static GuardedInvocation findCallMethod(final CallSiteDescriptor desc) {
 155         MethodHandle mh = NashornCallSiteDescriptor.isScope(desc)? JSOBJECT_SCOPE_CALL : JSOBJECT_CALL;
 156         if (NashornCallSiteDescriptor.isApplyToCall(desc)) {
 157             mh = MH.insertArguments(JSOBJECT_CALL_TO_APPLY, 0, mh);
 158         }
 159         final MethodType type = desc.getMethodType();
 160         mh = type.parameterType(type.parameterCount() - 1) == Object[].class ?
 161                 mh :
 162                 MH.asCollector(mh, Object[].class, type.parameterCount() - 2);
 163         return new GuardedInvocation(mh, IS_JSOBJECT_GUARD);
 164     }
 165 
 166     private static GuardedInvocation findNewMethod(final CallSiteDescriptor desc) {
 167         final MethodHandle func = MH.asCollector(JSOBJECT_NEW, Object[].class, desc.getMethodType().parameterCount() - 1);
 168         return new GuardedInvocation(func, IS_JSOBJECT_GUARD);
 169     }
 170 
 171     @SuppressWarnings("unused")
 172     private static boolean isJSObject(final Object self) {
 173         return self instanceof JSObject;
 174     }
 175 
 176     @SuppressWarnings("unused")
 177     private static Object get(final MethodHandle fallback, final Object jsobj, final Object key)
 178         throws Throwable {
 179         if (key instanceof Integer) {
 180             return ((JSObject)jsobj).getSlot((Integer)key);
 181         } else if (key instanceof Number) {
 182             final int index = getIndex((Number)key);
 183             if (index > -1) {
 184                 return ((JSObject)jsobj).getSlot(index);
 185             } else {
 186                 return ((JSObject)jsobj).getMember(JSType.toString(key));
 187             }
 188         } else if (isString(key)) {
 189             final String name = key.toString();
 190             // get with method name and signature. delegate it to beans linker!
 191             if (name.indexOf('(') != -1) {
 192                 return fallback.invokeExact(jsobj, (Object) name);
 193             }
 194             return ((JSObject)jsobj).getMember(name);
 195         }
 196         return null;
 197     }
 198 
 199     @SuppressWarnings("unused")
 200     private static void put(final Object jsobj, final Object key, final Object value) {
 201         if (key instanceof Integer) {
 202             ((JSObject)jsobj).setSlot((Integer)key, value);
 203         } else if (key instanceof Number) {
 204             final int index = getIndex((Number)key);
 205             if (index > -1) {
 206                 ((JSObject)jsobj).setSlot(index, value);
 207             } else {
 208                 ((JSObject)jsobj).setMember(JSType.toString(key), value);
 209             }
 210         } else if (isString(key)) {
 211             ((JSObject)jsobj).setMember(key.toString(), value);
 212         }
 213     }
 214 
 215     @SuppressWarnings("unused")
 216     private static boolean del(final Object jsobj, final Object key) {
 217         if (jsobj instanceof ScriptObjectMirror) {
 218             return ((ScriptObjectMirror)jsobj).delete(key);
 219         }
 220         ((JSObject) jsobj).removeMember(Objects.toString(key));
 221         return true;
 222     }
 223 
 224     private static int getIndex(final Number n) {
 225         final double value = n.doubleValue();
 226         return JSType.isRepresentableAsInt(value) ? (int)value : -1;
 227     }
 228 
 229     @SuppressWarnings("unused")
 230     private static Object callToApply(final MethodHandle mh, final JSObject obj, final Object thiz, final Object... args) {
 231         assert args.length >= 1;
 232         final Object   receiver  = args[0];
 233         final Object[] arguments = new Object[args.length - 1];
 234         System.arraycopy(args, 1, arguments, 0, arguments.length);
 235         try {
 236             return mh.invokeExact(obj, thiz, new Object[] { receiver, arguments });
 237         } catch (final RuntimeException | Error e) {
 238             throw e;
 239         } catch (final Throwable e) {
 240             throw new RuntimeException(e);
 241         }
 242     }
 243 
 244     // This is used when a JSObject is called as scope call to do undefined -> Global this translation.
 245     @SuppressWarnings("unused")
 246     private static Object jsObjectScopeCall(final JSObject jsObj, final Object thiz, final Object[] args) {
 247         final Object modifiedThiz;
 248         if (thiz == ScriptRuntime.UNDEFINED && !jsObj.isStrictFunction()) {
 249             final Global global = Context.getGlobal();
 250             modifiedThiz = ScriptObjectMirror.wrap(global, global);
 251         } else {
 252             modifiedThiz = thiz;
 253         }
 254         return jsObj.call(modifiedThiz, args);
 255     }
 256 
 257     private static final MethodHandleFunctionality MH = MethodHandleFactory.getFunctionality();
 258 
 259     // method handles of the current class
 260     private static final MethodHandle IS_JSOBJECT_GUARD  = findOwnMH_S("isJSObject", boolean.class, Object.class);
 261     private static final MethodHandle JSOBJECTLINKER_GET = findOwnMH_S("get", Object.class, MethodHandle.class, Object.class, Object.class);
 262     private static final MethodHandle JSOBJECTLINKER_PUT = findOwnMH_S("put", Void.TYPE, Object.class, Object.class, Object.class);
 263     private static final MethodHandle JSOBJECTLINKER_DEL = findOwnMH_S("del", boolean.class, Object.class, Object.class);
 264 
 265     // method handles of JSObject class
 266     private static final MethodHandle JSOBJECT_GETMEMBER     = findJSObjectMH_V("getMember", Object.class, String.class);
 267     private static final MethodHandle JSOBJECT_SETMEMBER     = findJSObjectMH_V("setMember", Void.TYPE, String.class, Object.class);
 268     private static final MethodHandle JSOBJECT_CALL          = findJSObjectMH_V("call", Object.class, Object.class, Object[].class);
 269     private static final MethodHandle JSOBJECT_SCOPE_CALL    = findOwnMH_S("jsObjectScopeCall", Object.class, JSObject.class, Object.class, Object[].class);
 270     private static final MethodHandle JSOBJECT_CALL_TO_APPLY = findOwnMH_S("callToApply", Object.class, MethodHandle.class, JSObject.class, Object.class, Object[].class);
 271     private static final MethodHandle JSOBJECT_NEW           = findJSObjectMH_V("newObject", Object.class, Object[].class);
 272 
 273     private static MethodHandle findJSObjectMH_V(final String name, final Class<?> rtype, final Class<?>... types) {
 274         return MH.findVirtual(MethodHandles.lookup(), JSObject.class, name, MH.type(rtype, types));
 275     }
 276 
 277     private static MethodHandle findOwnMH_S(final String name, final Class<?> rtype, final Class<?>... types) {
 278         return MH.findStatic(MethodHandles.lookup(), JSObjectLinker.class, name, MH.type(rtype, types));
 279     }
 280 }