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.ScriptRuntime.UNDEFINED;
  31 
  32 import java.lang.invoke.MethodHandle;
  33 import java.lang.invoke.MethodHandles;
  34 import java.lang.invoke.MethodType;
  35 import java.util.HashMap;
  36 import java.util.Map;
  37 import java.util.function.Supplier;
  38 import jdk.dynalink.CallSiteDescriptor;
  39 import jdk.dynalink.NamedOperation;
  40 import jdk.dynalink.Operation;
  41 import jdk.dynalink.beans.BeansLinker;
  42 import jdk.dynalink.beans.StaticClass;
  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.dynalink.linker.support.Lookup;
  50 import jdk.nashorn.internal.codegen.types.Type;
  51 import jdk.nashorn.internal.runtime.ECMAException;
  52 import jdk.nashorn.internal.runtime.JSType;
  53 import jdk.nashorn.internal.runtime.ScriptRuntime;
  54 import jdk.nashorn.internal.runtime.UnwarrantedOptimismException;
  55 
  56 /**
  57  * Nashorn bottom linker; used as a last-resort catch-all linker for all linking requests that fall through all other
  58  * linkers (see how {@link Bootstrap} class configures the dynamic linker in its static initializer). It will throw
  59  * appropriate ECMAScript errors for attempts to invoke operations on {@code null}, link no-op property getters and
  60  * setters for Java objects that couldn't be linked by any other linker, and throw appropriate ECMAScript errors for
  61  * attempts to invoke arbitrary Java objects as functions or constructors.
  62  */
  63 final class NashornBottomLinker implements GuardingDynamicLinker, GuardingTypeConverterFactory {
  64 
  65     @Override
  66     public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices)
  67             throws Exception {
  68         final Object self = linkRequest.getReceiver();
  69 
  70         if (self == null) {
  71             return linkNull(linkRequest);
  72         }
  73 
  74         // None of the objects that can be linked by NashornLinker should ever reach here. Basically, anything below
  75         // this point is a generic Java bean. Therefore, reaching here with a ScriptObject is a Nashorn bug.
  76         assert isExpectedObject(self) : "Couldn't link " + linkRequest.getCallSiteDescriptor() + " for " + self.getClass().getName();
  77 
  78         return linkBean(linkRequest);
  79     }
  80 
  81     private static final MethodHandle EMPTY_PROP_GETTER =
  82             MH.dropArguments(MH.constant(Object.class, UNDEFINED), 0, Object.class);
  83     private static final MethodHandle EMPTY_ELEM_GETTER =
  84             MH.dropArguments(EMPTY_PROP_GETTER, 0, Object.class);
  85     private static final MethodHandle EMPTY_PROP_SETTER =
  86             MH.asType(EMPTY_ELEM_GETTER, EMPTY_ELEM_GETTER.type().changeReturnType(void.class));
  87     private static final MethodHandle EMPTY_ELEM_SETTER =
  88             MH.dropArguments(EMPTY_PROP_SETTER, 0, Object.class);
  89 
  90     private static final MethodHandle THROW_STRICT_PROPERTY_SETTER;
  91     private static final MethodHandle THROW_STRICT_PROPERTY_REMOVER;
  92     private static final MethodHandle THROW_OPTIMISTIC_UNDEFINED;
  93     private static final MethodHandle MISSING_PROPERTY_REMOVER;
  94 
  95     static {
  96         final Lookup lookup = new Lookup(MethodHandles.lookup());
  97         THROW_STRICT_PROPERTY_SETTER = lookup.findOwnStatic("throwStrictPropertySetter", void.class, Object.class, Object.class);
  98         THROW_STRICT_PROPERTY_REMOVER = lookup.findOwnStatic("throwStrictPropertyRemover", boolean.class, Object.class, Object.class);
  99         THROW_OPTIMISTIC_UNDEFINED = lookup.findOwnStatic("throwOptimisticUndefined", Object.class, int.class);
 100         MISSING_PROPERTY_REMOVER = lookup.findOwnStatic("missingPropertyRemover", boolean.class, Object.class, Object.class);
 101     }
 102 
 103     private static GuardedInvocation linkBean(final LinkRequest linkRequest) throws Exception {
 104         final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor();
 105         final Object self = linkRequest.getReceiver();
 106         switch (NashornCallSiteDescriptor.getStandardOperation(desc)) {
 107         case NEW:
 108             if(BeansLinker.isDynamicConstructor(self)) {
 109                 throw typeError("no.constructor.matches.args", ScriptRuntime.safeToString(self));
 110             }
 111             if(BeansLinker.isDynamicMethod(self)) {
 112                 throw typeError("method.not.constructor", ScriptRuntime.safeToString(self));
 113             }
 114             throw typeError("not.a.function", NashornCallSiteDescriptor.getFunctionErrorMessage(desc, self));
 115         case CALL:
 116             if(BeansLinker.isDynamicConstructor(self)) {
 117                 throw typeError("constructor.requires.new", ScriptRuntime.safeToString(self));
 118             }
 119             if(BeansLinker.isDynamicMethod(self)) {
 120                 throw typeError("no.method.matches.args", ScriptRuntime.safeToString(self));
 121             }
 122             throw typeError("not.a.function", NashornCallSiteDescriptor.getFunctionErrorMessage(desc, self));
 123         default:
 124             // Everything else is supposed to have been already handled by Bootstrap.beansLinker
 125             // delegating to linkNoSuchBeanMember
 126             throw new AssertionError("unknown call type " + desc);
 127         }
 128     }
 129 
 130     static MethodHandle linkMissingBeanMember(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
 131         final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor();
 132         final String operand = NashornCallSiteDescriptor.getOperand(desc);
 133         final boolean strict = NashornCallSiteDescriptor.isStrict(desc);
 134         switch (NashornCallSiteDescriptor.getStandardOperation(desc)) {
 135         case GET:
 136             if (NashornCallSiteDescriptor.isOptimistic(desc)) {
 137                 return adaptThrower(MethodHandles.insertArguments(THROW_OPTIMISTIC_UNDEFINED, 0, NashornCallSiteDescriptor.getProgramPoint(desc)), desc);
 138             } else if (operand != null) {
 139                 return getInvocation(EMPTY_PROP_GETTER, linkerServices, desc);
 140             }
 141             return getInvocation(EMPTY_ELEM_GETTER, linkerServices, desc);
 142         case SET:
 143             if (strict) {
 144                 return adaptThrower(bindOperand(THROW_STRICT_PROPERTY_SETTER, operand), desc);
 145             } else if (operand != null) {
 146                 return getInvocation(EMPTY_PROP_SETTER, linkerServices, desc);
 147             }
 148             return getInvocation(EMPTY_ELEM_SETTER, linkerServices, desc);
 149         case REMOVE:
 150             if (strict) {
 151                 return adaptThrower(bindOperand(THROW_STRICT_PROPERTY_REMOVER, operand), desc);
 152             }
 153             return getInvocation(bindOperand(MISSING_PROPERTY_REMOVER, operand), linkerServices, desc);
 154         default:
 155             throw new AssertionError("unknown call type " + desc);
 156         }
 157     }
 158 
 159     private static MethodHandle bindOperand(final MethodHandle handle, final String operand) {
 160         return operand == null ? handle : MethodHandles.insertArguments(handle, 1, operand);
 161     }
 162 
 163     private static MethodHandle adaptThrower(final MethodHandle handle, final CallSiteDescriptor desc) {
 164         final MethodType targetType = desc.getMethodType();
 165         final int paramCount = handle.type().parameterCount();
 166         return MethodHandles
 167                 .dropArguments(handle, paramCount, targetType.parameterList().subList(paramCount, targetType.parameterCount()))
 168                 .asType(targetType);
 169     }
 170 
 171     @SuppressWarnings("unused")
 172     private static void throwStrictPropertySetter(final Object self, final Object name) {
 173         throw createTypeError(self, name, "cant.set.property");
 174     }
 175 
 176     @SuppressWarnings("unused")
 177     private static boolean throwStrictPropertyRemover(final Object self, final Object name) {
 178         if (isNonConfigurableProperty(self, name)) {
 179             throw createTypeError(self, name, "cant.delete.property");
 180         }
 181         return true;
 182     }
 183 
 184     @SuppressWarnings("unused")
 185     private static boolean missingPropertyRemover(final Object self, final Object name) {
 186         return !isNonConfigurableProperty(self, name);
 187     }
 188 
 189     // Corresponds to ECMAScript 5.1 8.12.7 [[Delete]] point 3 check for "isConfigurable" (but negated)
 190     private static boolean isNonConfigurableProperty(final Object self, final Object name) {
 191         if (self instanceof StaticClass) {
 192             final Class<?> clazz = ((StaticClass)self).getRepresentedClass();
 193             return BeansLinker.getReadableStaticPropertyNames(clazz).contains(name) ||
 194                    BeansLinker.getWritableStaticPropertyNames(clazz).contains(name) ||
 195                    BeansLinker.getStaticMethodNames(clazz).contains(name);
 196         }
 197         final Class<?> clazz = self.getClass();
 198         return BeansLinker.getReadableInstancePropertyNames(clazz).contains(name) ||
 199             BeansLinker.getWritableInstancePropertyNames(clazz).contains(name) ||
 200             BeansLinker.getInstanceMethodNames(clazz).contains(name);
 201     }
 202 
 203     private static ECMAException createTypeError(final Object self, final Object name, final String msg) {
 204         return typeError(msg, String.valueOf(name), ScriptRuntime.safeToString(self));
 205     }
 206 
 207     @SuppressWarnings("unused")
 208     private static Object throwOptimisticUndefined(final int programPoint) {
 209         throw new UnwarrantedOptimismException(UNDEFINED, programPoint, Type.OBJECT);
 210     }
 211 
 212     @Override
 213     public GuardedInvocation convertToType(final Class<?> sourceType, final Class<?> targetType, final Supplier<MethodHandles.Lookup> lookupSupplier) throws Exception {
 214         final GuardedInvocation gi = convertToTypeNoCast(sourceType, targetType);
 215         return gi == null ? null : gi.asType(MH.type(targetType, sourceType));
 216     }
 217 
 218     /**
 219      * Main part of the implementation of {@link GuardingTypeConverterFactory#convertToType} that doesn't
 220      * care about adapting the method signature; that's done by the invoking method. Returns conversion
 221      * from Object to String/number/boolean (JS primitive types).
 222      * @param sourceType the source type
 223      * @param targetType the target type
 224      * @return a guarded invocation that converts from the source type to the target type.
 225      * @throws Exception if something goes wrong
 226      */
 227     private static GuardedInvocation convertToTypeNoCast(final Class<?> sourceType, final Class<?> targetType) throws Exception {
 228         final MethodHandle mh = CONVERTERS.get(targetType);
 229         if (mh != null) {
 230             return new GuardedInvocation(mh);
 231         }
 232 
 233         return null;
 234     }
 235 
 236     private static MethodHandle getInvocation(final MethodHandle handle, final LinkerServices linkerServices, final CallSiteDescriptor desc) {
 237         return linkerServices.asTypeLosslessReturn(handle, desc.getMethodType());
 238     }
 239 
 240     // Used solely in an assertion to figure out if the object we get here is something we in fact expect. Objects
 241     // linked by NashornLinker should never reach here.
 242     private static boolean isExpectedObject(final Object obj) {
 243         return !(NashornLinker.canLinkTypeStatic(obj.getClass()));
 244     }
 245 
 246     private static GuardedInvocation linkNull(final LinkRequest linkRequest) {
 247         final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor();
 248         switch (NashornCallSiteDescriptor.getStandardOperation(desc)) {
 249         case NEW:
 250         case CALL:
 251             throw typeError("not.a.function", "null");
 252         case GET:
 253             throw typeError(NashornCallSiteDescriptor.isMethodFirstOperation(desc) ? "no.such.function" : "cant.get.property", getArgument(linkRequest), "null");
 254         case SET:
 255             throw typeError("cant.set.property", getArgument(linkRequest), "null");
 256         case REMOVE:
 257             throw typeError("cant.delete.property", getArgument(linkRequest), "null");
 258         default:
 259             throw new AssertionError("unknown call type " + desc);
 260         }
 261     }
 262 
 263     private static final Map<Class<?>, MethodHandle> CONVERTERS = new HashMap<>();
 264     static {
 265         CONVERTERS.put(boolean.class, JSType.TO_BOOLEAN.methodHandle());
 266         CONVERTERS.put(double.class, JSType.TO_NUMBER.methodHandle());
 267         CONVERTERS.put(int.class, JSType.TO_INTEGER.methodHandle());
 268         CONVERTERS.put(long.class, JSType.TO_LONG.methodHandle());
 269         CONVERTERS.put(String.class, JSType.TO_STRING.methodHandle());
 270     }
 271 
 272     private static String getArgument(final LinkRequest linkRequest) {
 273         final Operation op = linkRequest.getCallSiteDescriptor().getOperation();
 274         if (op instanceof NamedOperation) {
 275             return ((NamedOperation)op).getName().toString();
 276         }
 277         return ScriptRuntime.safeToString(linkRequest.getArguments()[1]);
 278     }
 279 }