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 
  31 import java.lang.invoke.MethodHandle;
  32 import java.lang.invoke.MethodHandles;
  33 import java.lang.invoke.MethodType;
  34 import java.lang.invoke.SwitchPoint;
  35 import jdk.internal.dynalink.CallSiteDescriptor;
  36 import jdk.internal.dynalink.linker.GuardedInvocation;
  37 import jdk.internal.dynalink.linker.LinkRequest;
  38 import jdk.internal.dynalink.support.CallSiteDescriptorFactory;
  39 import jdk.internal.dynalink.support.Guards;
  40 import jdk.nashorn.internal.runtime.Context;
  41 import jdk.nashorn.internal.runtime.FindProperty;
  42 import jdk.nashorn.internal.runtime.GlobalConstants;
  43 import jdk.nashorn.internal.runtime.JSType;
  44 import jdk.nashorn.internal.runtime.ScriptObject;
  45 import jdk.nashorn.internal.runtime.ScriptRuntime;
  46 import jdk.nashorn.internal.runtime.UserAccessorProperty;
  47 
  48 /**
  49  * Implements lookup of methods to link for dynamic operations on JavaScript primitive values (booleans, strings, and
  50  * numbers). This class is only public so it can be accessed by classes in the {@code jdk.nashorn.internal.objects}
  51  * package.
  52  */
  53 public final class PrimitiveLookup {
  54 
  55     /** Method handle to link setters on primitive base. See ES5 8.7.2. */
  56     private static final MethodHandle PRIMITIVE_SETTER = findOwnMH("primitiveSetter",
  57             MH.type(void.class, ScriptObject.class, Object.class, Object.class, boolean.class, Object.class));
  58 
  59 
  60     private PrimitiveLookup() {
  61     }
  62 
  63     /**
  64      * Returns a guarded invocation representing the linkage for a dynamic operation on a primitive Java value.
  65      * @param request the link request for the dynamic call site.
  66      * @param receiverClass the class of the receiver value (e.g., {@link java.lang.Boolean}, {@link java.lang.String} etc.)
  67      * @param wrappedReceiver a transient JavaScript native wrapper object created as the object proxy for the primitive
  68      * value; see ECMAScript 5.1, section 8.7.1 for discussion of using {@code [[Get]]} on a property reference with a
  69      * primitive base value. This instance will be used to delegate actual lookup.
  70      * @param wrapFilter A method handle that takes a primitive value of type specified in the {@code receiverClass} and
  71      * creates a transient native wrapper of the same type as {@code wrappedReceiver} for subsequent invocations of the
  72      * method - it will be combined into the returned invocation as an argument filter on the receiver.
  73      * @return a guarded invocation representing the operation at the call site when performed on a JavaScript primitive
  74      * @param protoFilter A method handle that walks up the proto chain of this receiver object
  75      * type {@code receiverClass}.
  76      */
  77     public static GuardedInvocation lookupPrimitive(final LinkRequest request, final Class<?> receiverClass,
  78                                                     final ScriptObject wrappedReceiver, final MethodHandle wrapFilter,
  79                                                     final MethodHandle protoFilter) {
  80         return lookupPrimitive(request, Guards.getInstanceOfGuard(receiverClass), wrappedReceiver, wrapFilter, protoFilter);
  81     }
  82 
  83     /**
  84      * Returns a guarded invocation representing the linkage for a dynamic operation on a primitive Java value.
  85      * @param request the link request for the dynamic call site.
  86      * @param guard an explicit guard that will be used for the returned guarded invocation.
  87      * @param wrappedReceiver a transient JavaScript native wrapper object created as the object proxy for the primitive
  88      * value; see ECMAScript 5.1, section 8.7.1 for discussion of using {@code [[Get]]} on a property reference with a
  89      * primitive base value. This instance will be used to delegate actual lookup.
  90      * @param wrapFilter A method handle that takes a primitive value of type guarded by the {@code guard} and
  91      * creates a transient native wrapper of the same type as {@code wrappedReceiver} for subsequent invocations of the
  92      * method - it will be combined into the returned invocation as an argument filter on the receiver.
  93      * @param protoFilter A method handle that walks up the proto chain of this receiver object
  94      * @return a guarded invocation representing the operation at the call site when performed on a JavaScript primitive
  95      * type (that is implied by both {@code guard} and {@code wrappedReceiver}).
  96      */
  97     public static GuardedInvocation lookupPrimitive(final LinkRequest request, final MethodHandle guard,
  98                                                     final ScriptObject wrappedReceiver, final MethodHandle wrapFilter,
  99                                                     final MethodHandle protoFilter) {
 100         final CallSiteDescriptor desc = request.getCallSiteDescriptor();
 101         final String name;
 102         final FindProperty find;
 103 
 104         if (desc.getNameTokenCount() > 2) {
 105             name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
 106             find = wrappedReceiver.findProperty(name, true);
 107         } else {
 108             name = null;
 109             find = null;
 110         }
 111 
 112         final String firstOp = CallSiteDescriptorFactory.tokenizeOperators(desc).get(0);
 113 
 114         switch (firstOp) {
 115         case "getProp":
 116         case "getElem":
 117         case "getMethod":
 118             //checks whether the property name is hard-coded in the call-site (i.e. a getProp vs a getElem, or setProp vs setElem)
 119             //if it is we can make assumptions on the property: that if it is not defined on primitive wrapper itself it never will be.
 120             //so in that case we can skip creation of primitive wrapper and start our search with the prototype.
 121             if (name != null) {
 122                 if (find == null) {
 123                     // Give up early, give chance to BeanLinker and NashornBottomLinker to deal with it.
 124                     return null;
 125                 }
 126 
 127                 final SwitchPoint sp = find.getProperty().getBuiltinSwitchPoint(); //can use this instead of proto filter
 128                 if (sp instanceof Context.BuiltinSwitchPoint && !sp.hasBeenInvalidated()) {
 129                     return new GuardedInvocation(GlobalConstants.staticConstantGetter(find.getObjectValue()), guard, sp, null);
 130                 }
 131 
 132                 if (find.isInherited() && !(find.getProperty() instanceof UserAccessorProperty)) {
 133                     // If property is found in the prototype object bind the method handle directly to
 134                     // the proto filter instead of going through wrapper instantiation below.
 135                     final ScriptObject proto = wrappedReceiver.getProto();
 136                     final GuardedInvocation link = proto.lookup(desc, request);
 137 
 138                     if (link != null) {
 139                         final MethodHandle invocation = link.getInvocation(); //this contains the builtin switchpoint
 140                         final MethodHandle adaptedInvocation = MH.asType(invocation, invocation.type().changeParameterType(0, Object.class));
 141                         final MethodHandle method = MH.filterArguments(adaptedInvocation, 0, protoFilter);
 142                         final MethodHandle protoGuard = MH.filterArguments(link.getGuard(), 0, protoFilter);
 143                         return new GuardedInvocation(method, NashornGuards.combineGuards(guard, protoGuard));
 144                     }
 145                 }
 146             }
 147             break;
 148         case "setProp":
 149         case "setElem":
 150             return getPrimitiveSetter(name, guard, wrapFilter, NashornCallSiteDescriptor.isStrict(desc));
 151         default:
 152             break;
 153         }
 154 
 155         final GuardedInvocation link = wrappedReceiver.lookup(desc, request);
 156         if (link != null) {
 157             MethodHandle method = link.getInvocation();
 158             final Class<?> receiverType = method.type().parameterType(0);
 159             if (receiverType != Object.class) {
 160                 final MethodType wrapType = wrapFilter.type();
 161                 assert receiverType.isAssignableFrom(wrapType.returnType());
 162                 method = MH.filterArguments(method, 0, MH.asType(wrapFilter, wrapType.changeReturnType(receiverType)));
 163             }
 164 
 165             return new GuardedInvocation(method, guard, link.getSwitchPoints(), null);
 166         }
 167 
 168         return null;
 169     }
 170 
 171     private static GuardedInvocation getPrimitiveSetter(final String name, final MethodHandle guard,
 172                                                         final MethodHandle wrapFilter, final boolean isStrict) {
 173         MethodHandle filter = MH.asType(wrapFilter, wrapFilter.type().changeReturnType(ScriptObject.class));
 174         final MethodHandle target;
 175 
 176         if (name == null) {
 177             filter = MH.dropArguments(filter, 1, Object.class, Object.class);
 178             target = MH.insertArguments(PRIMITIVE_SETTER, 3, isStrict);
 179         } else {
 180             filter = MH.dropArguments(filter, 1, Object.class);
 181             target = MH.insertArguments(PRIMITIVE_SETTER, 2, name, isStrict);
 182         }
 183 
 184         return new GuardedInvocation(MH.foldArguments(target, filter), guard);
 185     }
 186 
 187 
 188     @SuppressWarnings("unused")
 189     private static void primitiveSetter(final ScriptObject wrappedSelf, final Object self, final Object key,
 190                                         final boolean strict, final Object value) {
 191         // See ES5.1 8.7.2 PutValue (V, W)
 192         final String name = JSType.toString(key);
 193         final FindProperty find = wrappedSelf.findProperty(name, true);
 194         if (find == null || !(find.getProperty() instanceof UserAccessorProperty) || !find.getProperty().isWritable()) {
 195             if (strict) {
 196                 throw typeError("property.not.writable", name, ScriptRuntime.safeToString(self));
 197             }
 198             return;
 199         }
 200         // property found and is a UserAccessorProperty
 201         find.setValue(value, strict);
 202     }
 203 
 204     private static MethodHandle findOwnMH(final String name, final MethodType type) {
 205         return MH.findStatic(MethodHandles.lookup(), PrimitiveLookup.class, name, type);
 206     }
 207 }