1 /*
   2  * Copyright (c) 2010, 2013, 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.lookup.Lookup.MH;
  29 import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
  30 import static jdk.nashorn.internal.runtime.JSType.GET_UNDEFINED;
  31 import static jdk.nashorn.internal.runtime.JSType.TYPE_OBJECT_INDEX;
  32 import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
  33 
  34 import java.lang.invoke.MethodHandle;
  35 import java.lang.invoke.MethodHandles;
  36 import java.util.HashMap;
  37 import java.util.Map;
  38 import java.util.function.Supplier;
  39 import jdk.dynalink.CallSiteDescriptor;
  40 import jdk.dynalink.NamedOperation;
  41 import jdk.dynalink.Operation;
  42 import jdk.dynalink.beans.BeansLinker;
  43 import jdk.dynalink.linker.GuardedInvocation;
  44 import jdk.dynalink.linker.GuardingDynamicLinker;
  45 import jdk.dynalink.linker.GuardingTypeConverterFactory;
  46 import jdk.dynalink.linker.LinkRequest;
  47 import jdk.dynalink.linker.LinkerServices;
  48 import jdk.dynalink.linker.support.Guards;
  49 import jdk.nashorn.internal.codegen.types.Type;
  50 import jdk.nashorn.internal.runtime.JSType;
  51 import jdk.nashorn.internal.runtime.ScriptRuntime;
  52 import jdk.nashorn.internal.runtime.UnwarrantedOptimismException;
  53 
  54 /**
  55  * Nashorn bottom linker; used as a last-resort catch-all linker for all linking requests that fall through all other
  56  * linkers (see how {@link Bootstrap} class configures the dynamic linker in its static initializer). It will throw
  57  * appropriate ECMAScript errors for attempts to invoke operations on {@code null}, link no-op property getters and
  58  * setters for Java objects that couldn't be linked by any other linker, and throw appropriate ECMAScript errors for
  59  * attempts to invoke arbitrary Java objects as functions or constructors.
  60  */
  61 final class NashornBottomLinker implements GuardingDynamicLinker, GuardingTypeConverterFactory {
  62 
  63     @Override
  64     public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices)
  65             throws Exception {
  66         final Object self = linkRequest.getReceiver();
  67 
  68         if (self == null) {
  69             return linkNull(linkRequest);
  70         }
  71 
  72         // None of the objects that can be linked by NashornLinker should ever reach here. Basically, anything below
  73         // this point is a generic Java bean. Therefore, reaching here with a ScriptObject is a Nashorn bug.
  74         assert isExpectedObject(self) : "Couldn't link " + linkRequest.getCallSiteDescriptor() + " for " + self.getClass().getName();
  75 
  76         return linkBean(linkRequest, linkerServices);
  77     }
  78 
  79     private static final MethodHandle EMPTY_PROP_GETTER =
  80             MH.dropArguments(MH.constant(Object.class, UNDEFINED), 0, Object.class);
  81     private static final MethodHandle EMPTY_ELEM_GETTER =
  82             MH.dropArguments(EMPTY_PROP_GETTER, 0, Object.class);
  83     private static final MethodHandle EMPTY_PROP_SETTER =
  84             MH.asType(EMPTY_ELEM_GETTER, EMPTY_ELEM_GETTER.type().changeReturnType(void.class));
  85     private static final MethodHandle EMPTY_ELEM_SETTER =
  86             MH.dropArguments(EMPTY_PROP_SETTER, 0, Object.class);
  87 
  88     private static GuardedInvocation linkBean(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
  89         final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor();
  90         final Object self = linkRequest.getReceiver();
  91         switch (NashornCallSiteDescriptor.getFirstStandardOperation(desc)) {
  92         case NEW:
  93             if(BeansLinker.isDynamicConstructor(self)) {
  94                 throw typeError("no.constructor.matches.args", ScriptRuntime.safeToString(self));
  95             }
  96             if(BeansLinker.isDynamicMethod(self)) {
  97                 throw typeError("method.not.constructor", ScriptRuntime.safeToString(self));
  98             }
  99             throw typeError("not.a.function", NashornCallSiteDescriptor.getFunctionErrorMessage(desc, self));
 100         case CALL:
 101             if(BeansLinker.isDynamicConstructor(self)) {
 102                 throw typeError("constructor.requires.new", ScriptRuntime.safeToString(self));
 103             }
 104             if(BeansLinker.isDynamicMethod(self)) {
 105                 throw typeError("no.method.matches.args", ScriptRuntime.safeToString(self));
 106             }
 107             throw typeError("not.a.function", NashornCallSiteDescriptor.getFunctionErrorMessage(desc, self));
 108         case CALL_METHOD:
 109             throw typeError("no.such.function", getArgument(linkRequest), ScriptRuntime.safeToString(self));
 110         case GET_METHOD:
 111             // evaluate to undefined, later on Undefined will take care of throwing TypeError
 112             return getInvocation(MH.dropArguments(GET_UNDEFINED.get(TYPE_OBJECT_INDEX), 0, Object.class), self, linkerServices, desc);
 113         case GET_PROPERTY:
 114         case GET_ELEMENT:
 115             if(NashornCallSiteDescriptor.isOptimistic(desc)) {
 116                 throw new UnwarrantedOptimismException(UNDEFINED, NashornCallSiteDescriptor.getProgramPoint(desc), Type.OBJECT);
 117             }
 118             if (NashornCallSiteDescriptor.getOperand(desc) != null) {
 119                 return getInvocation(EMPTY_PROP_GETTER, self, linkerServices, desc);
 120             }
 121             return getInvocation(EMPTY_ELEM_GETTER, self, linkerServices, desc);
 122         case SET_PROPERTY:
 123         case SET_ELEMENT:
 124             final boolean strict = NashornCallSiteDescriptor.isStrict(desc);
 125             if (strict) {
 126                 throw typeError("cant.set.property", getArgument(linkRequest), ScriptRuntime.safeToString(self));
 127             }
 128             if (NashornCallSiteDescriptor.getOperand(desc) != null) {
 129                 return getInvocation(EMPTY_PROP_SETTER, self, linkerServices, desc);
 130             }
 131             return getInvocation(EMPTY_ELEM_SETTER, self, linkerServices, desc);
 132         default:
 133             throw new AssertionError("unknown call type " + desc);
 134         }
 135     }
 136 
 137     @Override
 138     public GuardedInvocation convertToType(final Class<?> sourceType, final Class<?> targetType, final Supplier<MethodHandles.Lookup> lookupSupplier) throws Exception {
 139         final GuardedInvocation gi = convertToTypeNoCast(sourceType, targetType);
 140         return gi == null ? null : gi.asType(MH.type(targetType, sourceType));
 141     }
 142 
 143     /**
 144      * Main part of the implementation of {@link GuardingTypeConverterFactory#convertToType(Class, Class)} that doesn't
 145      * care about adapting the method signature; that's done by the invoking method. Returns conversion from Object to String/number/boolean (JS primitive types).
 146      * @param sourceType the source type
 147      * @param targetType the target type
 148      * @return a guarded invocation that converts from the source type to the target type.
 149      * @throws Exception if something goes wrong
 150      */
 151     private static GuardedInvocation convertToTypeNoCast(final Class<?> sourceType, final Class<?> targetType) throws Exception {
 152         final MethodHandle mh = CONVERTERS.get(targetType);
 153         if (mh != null) {
 154             return new GuardedInvocation(mh);
 155         }
 156 
 157         return null;
 158     }
 159 
 160     private static GuardedInvocation getInvocation(final MethodHandle handle, final Object self, final LinkerServices linkerServices, final CallSiteDescriptor desc) {
 161         return Bootstrap.asTypeSafeReturn(new GuardedInvocation(handle, Guards.getClassGuard(self.getClass())), linkerServices, desc);
 162     }
 163 
 164     // Used solely in an assertion to figure out if the object we get here is something we in fact expect. Objects
 165     // linked by NashornLinker should never reach here.
 166     private static boolean isExpectedObject(final Object obj) {
 167         return !(NashornLinker.canLinkTypeStatic(obj.getClass()));
 168     }
 169 
 170     private static GuardedInvocation linkNull(final LinkRequest linkRequest) {
 171         final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor();
 172         switch (NashornCallSiteDescriptor.getFirstStandardOperation(desc)) {
 173         case NEW:
 174         case CALL:
 175             throw typeError("not.a.function", "null");
 176         case CALL_METHOD:
 177         case GET_METHOD:
 178             throw typeError("no.such.function", getArgument(linkRequest), "null");
 179         case GET_PROPERTY:
 180         case GET_ELEMENT:
 181             throw typeError("cant.get.property", getArgument(linkRequest), "null");
 182         case SET_PROPERTY:
 183         case SET_ELEMENT:
 184             throw typeError("cant.set.property", getArgument(linkRequest), "null");
 185         default:
 186             throw new AssertionError("unknown call type " + desc);
 187         }
 188     }
 189 
 190     private static final Map<Class<?>, MethodHandle> CONVERTERS = new HashMap<>();
 191     static {
 192         CONVERTERS.put(boolean.class, JSType.TO_BOOLEAN.methodHandle());
 193         CONVERTERS.put(double.class, JSType.TO_NUMBER.methodHandle());
 194         CONVERTERS.put(int.class, JSType.TO_INTEGER.methodHandle());
 195         CONVERTERS.put(long.class, JSType.TO_LONG.methodHandle());
 196         CONVERTERS.put(String.class, JSType.TO_STRING.methodHandle());
 197     }
 198 
 199     private static String getArgument(final LinkRequest linkRequest) {
 200         final Operation op = linkRequest.getCallSiteDescriptor().getOperation();
 201         if (op instanceof NamedOperation) {
 202             return ((NamedOperation)op).getName().toString();
 203         }
 204         return ScriptRuntime.safeToString(linkRequest.getArguments()[1]);
 205     }
 206 }