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;
  27 
  28 import static jdk.nashorn.internal.lookup.Lookup.MH;
  29 import static jdk.nashorn.internal.runtime.ECMAErrors.referenceError;
  30 import static jdk.nashorn.internal.runtime.JSType.getAccessorTypeIndex;
  31 
  32 import java.lang.invoke.MethodHandle;
  33 import java.lang.invoke.SwitchPoint;
  34 import jdk.dynalink.CallSiteDescriptor;
  35 import jdk.dynalink.linker.GuardedInvocation;
  36 import jdk.dynalink.linker.LinkRequest;
  37 import jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor;
  38 import jdk.nashorn.internal.runtime.linker.NashornGuards;
  39 
  40 /**
  41  * Instances of this class are quite ephemeral; they only exist for the duration of an invocation of
  42  * {@link ScriptObject#findSetMethod(CallSiteDescriptor, jdk.dynalink.linker.LinkRequest)} and
  43  * serve as the actual encapsulation of the algorithm for creating an appropriate property setter method.
  44  */
  45 final class SetMethodCreator {
  46     // See constructor parameters for description of fields
  47     private final ScriptObject       sobj;
  48     private final PropertyMap        map;
  49     private final FindProperty       find;
  50     private final CallSiteDescriptor desc;
  51     private final Class<?>           type;
  52     private final LinkRequest        request;
  53 
  54     /**
  55      * Creates a new property setter method creator.
  56      * @param sobj the object for which we're creating the property setter
  57      * @param find a result of a {@link ScriptObject#findProperty(Object, boolean)} on the object for the property we
  58      * want to create a setter for. Can be null if the property does not yet exist on the object.
  59      * @param desc the descriptor of the call site that triggered the property setter lookup
  60      * @param request the link request
  61      */
  62     SetMethodCreator(final ScriptObject sobj, final FindProperty find, final CallSiteDescriptor desc, final LinkRequest request) {
  63         this.sobj    = sobj;
  64         this.map     = sobj.getMap();
  65         this.find    = find;
  66         this.desc    = desc;
  67         this.type    = desc.getMethodType().parameterType(1);
  68         this.request = request;
  69     }
  70 
  71     private String getName() {
  72         return NashornCallSiteDescriptor.getOperand(desc);
  73     }
  74 
  75     private PropertyMap getMap() {
  76         return map;
  77     }
  78 
  79     /**
  80      * Creates the actual guarded invocation that represents the dynamic setter method for the property.
  81      * @return the actual guarded invocation that represents the dynamic setter method for the property.
  82      */
  83     GuardedInvocation createGuardedInvocation(final SwitchPoint builtinSwitchPoint) {
  84         return createSetMethod(builtinSwitchPoint).createGuardedInvocation();
  85     }
  86 
  87     /**
  88      * This class encapsulates the results of looking up a setter method; it's basically a triple of a method handle,
  89      * a Property object, and flags for invocation.
  90      *
  91      */
  92     private class SetMethod {
  93         private final MethodHandle methodHandle;
  94         private final Property property;
  95 
  96         /**
  97          * Creates a new lookup result.
  98          * @param methodHandle the actual method handle
  99          * @param property the property object. Can be null in case we're creating a new property in the global object.
 100          */
 101         SetMethod(final MethodHandle methodHandle, final Property property) {
 102             assert methodHandle != null;
 103             this.methodHandle = methodHandle;
 104             this.property     = property;
 105         }
 106 
 107         /**
 108          * Composes from its components an actual guarded invocation that represents the dynamic setter method for the property.
 109          * @return the composed guarded invocation that represents the dynamic setter method for the property.
 110          */
 111         GuardedInvocation createGuardedInvocation() {
 112             // getGuard() and getException() either both return null, or neither does. The reason for that is that now
 113             // getGuard returns a map guard that casts its argument to ScriptObject, and if that fails, we need to
 114             // relink on ClassCastException.
 115             final boolean explicitInstanceOfCheck = NashornGuards.explicitInstanceOfCheck(desc, request);
 116             return new GuardedInvocation(methodHandle, NashornGuards.getGuard(sobj, property, desc, explicitInstanceOfCheck),
 117                     (SwitchPoint)null, explicitInstanceOfCheck ? null : ClassCastException.class);
 118         }
 119     }
 120 
 121     private SetMethod createSetMethod(final SwitchPoint builtinSwitchPoint) {
 122         if (find != null) {
 123             return createExistingPropertySetter();
 124         }
 125 
 126         checkStrictCreateNewVariable();
 127 
 128         if (sobj.isScope()) {
 129             return createGlobalPropertySetter();
 130         }
 131 
 132         return createNewPropertySetter(builtinSwitchPoint);
 133     }
 134 
 135     private void checkStrictCreateNewVariable() {
 136         // In strict mode, assignment can not create a new variable.
 137         // See also ECMA Annex C item 4. ReferenceError is thrown.
 138         if (NashornCallSiteDescriptor.isScope(desc) && NashornCallSiteDescriptor.isStrict(desc)) {
 139             throw referenceError("not.defined", getName());
 140         }
 141     }
 142 
 143     private SetMethod createExistingPropertySetter() {
 144         final Property property = find.getProperty();
 145         final boolean isStrict  = NashornCallSiteDescriptor.isStrict(desc);
 146         final MethodHandle methodHandle;
 147 
 148         if (NashornCallSiteDescriptor.isDeclaration(desc)) {
 149             assert property.needsDeclaration();
 150             // This is a LET or CONST being declared. The property is already there but flagged as needing declaration.
 151             // We create a new PropertyMap with the flag removed. The map is installed with a fast compare-and-set
 152             // method if the pre-callsite map is stable (which should be the case for function scopes except for
 153             // non-strict functions containing eval() with var). Otherwise we have to use a slow setter that creates
 154             // a new PropertyMap on the fly.
 155             final PropertyMap oldMap = getMap();
 156             final Property newProperty = property.removeFlags(Property.NEEDS_DECLARATION);
 157             final PropertyMap newMap = oldMap.replaceProperty(property, newProperty);
 158             final MethodHandle fastSetter = find.replaceProperty(newProperty).getSetter(type, isStrict, request);
 159             final MethodHandle slowSetter = MH.insertArguments(ScriptObject.DECLARE_AND_SET, 1, getName()).asType(fastSetter.type());
 160 
 161             // cas map used as guard, if true that means we can do the set fast
 162             MethodHandle casMap = MH.insertArguments(ScriptObject.CAS_MAP, 1, oldMap, newMap);
 163             casMap = MH.dropArguments(casMap, 1, type);
 164             casMap = MH.asType(casMap, casMap.type().changeParameterType(0, Object.class));
 165             methodHandle = MH.guardWithTest(casMap, fastSetter, slowSetter);
 166         } else {
 167             methodHandle = find.getSetter(type, isStrict, request);
 168         }
 169 
 170         assert methodHandle != null;
 171         assert property     != null;
 172 
 173         final MethodHandle boundHandle;
 174         if (!property.isAccessorProperty() && find.isInherited()) {
 175             boundHandle = ScriptObject.addProtoFilter(methodHandle, find.getProtoChainLength());
 176         } else {
 177             boundHandle = methodHandle;
 178         }
 179         return new SetMethod(boundHandle, property);
 180     }
 181 
 182     private SetMethod createGlobalPropertySetter() {
 183         final ScriptObject global = Context.getGlobal();
 184         return new SetMethod(MH.filterArguments(global.addSpill(type, getName()), 0, ScriptObject.GLOBALFILTER), null);
 185     }
 186 
 187     private SetMethod createNewPropertySetter(final SwitchPoint builtinSwitchPoint) {
 188         final SetMethod sm = map.getFreeFieldSlot() > -1 ? createNewFieldSetter(builtinSwitchPoint) : createNewSpillPropertySetter(builtinSwitchPoint);
 189         map.propertyAdded(sm.property, true);
 190         return sm;
 191     }
 192 
 193     private SetMethod createNewSetter(final Property property, final SwitchPoint builtinSwitchPoint) {
 194         property.setBuiltinSwitchPoint(builtinSwitchPoint);
 195 
 196         final PropertyMap oldMap   = getMap();
 197         final PropertyMap newMap   = getNewMap(property);
 198         final boolean     isStrict = NashornCallSiteDescriptor.isStrict(desc);
 199         final String      name     = NashornCallSiteDescriptor.getOperand(desc);
 200 
 201         //fast type specific setter
 202         final MethodHandle fastSetter = property.getSetter(type, newMap); //0 sobj, 1 value, slot folded for spill property already
 203 
 204         //slow setter, that calls ScriptObject.set with appropriate type and key name
 205         MethodHandle slowSetter = ScriptObject.SET_SLOW[getAccessorTypeIndex(type)];
 206         slowSetter = MH.insertArguments(slowSetter, 3, NashornCallSiteDescriptor.getFlags(desc));
 207         slowSetter = MH.insertArguments(slowSetter, 1, name);
 208         slowSetter = MH.asType(slowSetter, slowSetter.type().changeParameterType(0, Object.class));
 209 
 210         assert slowSetter.type().equals(fastSetter.type()) : "slow=" + slowSetter + " != fast=" + fastSetter;
 211 
 212         //cas map used as guard, if true that means we can do the set fast
 213         MethodHandle casMap = MH.insertArguments(ScriptObject.CAS_MAP, 1, oldMap, newMap);
 214         casMap = MH.dropArguments(casMap, 1, type);
 215         casMap = MH.asType(casMap, casMap.type().changeParameterType(0, Object.class));
 216         final MethodHandle casGuard = MH.guardWithTest(casMap, fastSetter, slowSetter);
 217 
 218         //outermost level needs an extendable check. if object can be extended, guard is true and
 219         //we can run the cas setter. The setter goes to "nop" VOID_RETURN if false or throws an
 220         //exception if we are in strict mode and object is not extensible
 221         MethodHandle extCheck = MH.insertArguments(ScriptObject.EXTENSION_CHECK, 1, isStrict, name);
 222         extCheck = MH.asType(extCheck, extCheck.type().changeParameterType(0, Object.class));
 223         extCheck = MH.dropArguments(extCheck, 1, type);
 224 
 225         MethodHandle nop = JSType.VOID_RETURN.methodHandle();
 226         nop = MH.dropArguments(nop, 0, Object.class, type);
 227 
 228         return new SetMethod(MH.asType(MH.guardWithTest(extCheck, casGuard, nop), fastSetter.type()), property);
 229     }
 230 
 231     private SetMethod createNewFieldSetter(final SwitchPoint builtinSwitchPoint) {
 232         return createNewSetter(new AccessorProperty(getName(), getFlags(sobj), sobj.getClass(), getMap().getFreeFieldSlot(), type), builtinSwitchPoint);
 233     }
 234 
 235     private SetMethod createNewSpillPropertySetter(final SwitchPoint builtinSwitchPoint) {
 236         return createNewSetter(new SpillProperty(getName(), getFlags(sobj), getMap().getFreeSpillSlot(), type), builtinSwitchPoint);
 237     }
 238 
 239     private PropertyMap getNewMap(final Property property) {
 240         return getMap().addProperty(property);
 241     }
 242 
 243     private static int getFlags(final ScriptObject scriptObject) {
 244         return scriptObject.useDualFields() ? Property.DUAL_FIELDS : 0;
 245     }
 246 }