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.objects;
  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.util.ArrayList;
  35 import java.util.Arrays;
  36 import java.util.BitSet;
  37 import jdk.nashorn.internal.runtime.AccessorProperty;
  38 import jdk.nashorn.internal.runtime.JSType;
  39 import jdk.nashorn.internal.runtime.Property;
  40 import jdk.nashorn.internal.runtime.PropertyDescriptor;
  41 import jdk.nashorn.internal.runtime.PropertyMap;
  42 import jdk.nashorn.internal.runtime.ScriptFunction;
  43 import jdk.nashorn.internal.runtime.ScriptObject;
  44 import jdk.nashorn.internal.runtime.ScriptRuntime;
  45 import jdk.nashorn.internal.runtime.arrays.ArrayData;
  46 import jdk.nashorn.internal.runtime.arrays.ArrayIndex;
  47 
  48 /**
  49  * ECMA 10.6 Arguments Object.
  50  *
  51  * Arguments object used for non-strict mode functions. For strict mode, we use
  52  * a different implementation (@see NativeStrictArguments). In non-strict mode,
  53  * named argument access and index argument access (arguments[i]) are linked.
  54  * Modifications reflect on each other access -- till arguments indexed element
  55  * is deleted. After delete, there is no link between named access and indexed
  56  * access for that deleted index alone.
  57  */
  58 public final class NativeArguments extends ScriptObject {
  59 
  60     private static final MethodHandle G$LENGTH = findOwnMH("G$length", Object.class, Object.class);
  61     private static final MethodHandle S$LENGTH = findOwnMH("S$length", void.class, Object.class, Object.class);
  62     private static final MethodHandle G$CALLEE = findOwnMH("G$callee", Object.class, Object.class);
  63     private static final MethodHandle S$CALLEE = findOwnMH("S$callee", void.class, Object.class, Object.class);
  64 
  65     private static final PropertyMap map$;
  66 
  67     static {
  68         final ArrayList<Property> properties = new ArrayList<>(2);
  69         properties.add(AccessorProperty.create("length", Property.NOT_ENUMERABLE, G$LENGTH, S$LENGTH));
  70         properties.add(AccessorProperty.create("callee", Property.NOT_ENUMERABLE, G$CALLEE, S$CALLEE));
  71         map$ = PropertyMap.newMap(properties);
  72     }
  73 
  74     static PropertyMap getInitialMap() {
  75         return map$;
  76     }
  77 
  78     private Object length;
  79     private Object callee;
  80     private final int numMapped;
  81     private final int numParams;
  82 
  83     // These are lazily initialized when delete is invoked on a mapped arg or an unmapped argument is set.
  84     private ArrayData unmappedArgs;
  85     private BitSet deleted;
  86 
  87     NativeArguments(final Object[] arguments, final Object callee, final int numParams, final ScriptObject proto, final PropertyMap map) {
  88         super(proto, map);
  89         setIsArguments();
  90         setArray(ArrayData.allocate(arguments));
  91         this.length = arguments.length;
  92         this.callee = callee;
  93         this.numMapped = Math.min(numParams, arguments.length);
  94         this.numParams = numParams;
  95     }
  96 
  97     @Override
  98     public String getClassName() {
  99         return "Arguments";
 100     }
 101 
 102     /**
 103      * getArgument is used for named argument access.
 104      */
 105     @Override
 106     public Object getArgument(final int key) {
 107         assert key >= 0 && key < numParams : "invalid argument index";
 108         return isMapped(key) ? getArray().getObject(key) : getUnmappedArg(key);
 109     }
 110 
 111     /**
 112      * setArgument is used for named argument set.
 113      */
 114     @Override
 115     public void setArgument(final int key, final Object value) {
 116         assert key >= 0 && key < numParams : "invalid argument index";
 117         if (isMapped(key)) {
 118             setArray(getArray().set(key, value, false));
 119         } else {
 120             setUnmappedArg(key, value);
 121         }
 122     }
 123 
 124     @Override
 125     public boolean delete(final int key, final boolean strict) {
 126         final int index = ArrayIndex.getArrayIndex(key);
 127         return isMapped(index) ? deleteMapped(index, strict) : super.delete(key, strict);
 128     }
 129 
 130     @Override
 131     public boolean delete(final double key, final boolean strict) {
 132         final int index = ArrayIndex.getArrayIndex(key);
 133         return isMapped(index) ? deleteMapped(index, strict) : super.delete(key, strict);
 134     }
 135 
 136     @Override
 137     public boolean delete(final Object key, final boolean strict) {
 138         final Object primitiveKey = JSType.toPrimitive(key, String.class);
 139         final int index = ArrayIndex.getArrayIndex(primitiveKey);
 140         return isMapped(index) ? deleteMapped(index, strict) : super.delete(primitiveKey, strict);
 141     }
 142 
 143     /**
 144      * ECMA 15.4.5.1 [[DefineOwnProperty]] ( P, Desc, Throw ) as specialized in
 145      * ECMA 10.6 for Arguments object.
 146      */
 147     @Override
 148     public boolean defineOwnProperty(final String key, final Object propertyDesc, final boolean reject) {
 149         final int index = ArrayIndex.getArrayIndex(key);
 150         if (index >= 0) {
 151             final boolean isMapped = isMapped(index);
 152             final Object oldValue = isMapped ? getArray().getObject(index) : null;
 153 
 154             if (!super.defineOwnProperty(key, propertyDesc, false)) {
 155                 if (reject) {
 156                     throw typeError("cant.redefine.property",  key, ScriptRuntime.safeToString(this));
 157                 }
 158                 return false;
 159             }
 160 
 161             if (isMapped) {
 162                 // When mapped argument is redefined, if new descriptor is accessor property
 163                 // or data-non-writable property, we have to "unmap" (unlink).
 164                 final PropertyDescriptor desc = toPropertyDescriptor(Global.instance(), propertyDesc);
 165                 if (desc.type() == PropertyDescriptor.ACCESSOR) {
 166                     setDeleted(index, oldValue);
 167                 } else if (desc.has(PropertyDescriptor.WRITABLE) && !desc.isWritable()) {
 168                     // delete and set value from new descriptor if it has one, otherwise use old value
 169                     setDeleted(index, desc.has(PropertyDescriptor.VALUE) ? desc.getValue() : oldValue);
 170                 } else if (desc.has(PropertyDescriptor.VALUE)) {
 171                     setArray(getArray().set(index, desc.getValue(), false));
 172                 }
 173             }
 174 
 175             return true;
 176         }
 177 
 178         return super.defineOwnProperty(key, propertyDesc, reject);
 179     }
 180 
 181     // Internals below this point
 182 
 183     // We track deletions using a bit set (delete arguments[index])
 184     private boolean isDeleted(final int index) {
 185         return deleted != null && deleted.get(index);
 186     }
 187 
 188     private void setDeleted(final int index, final Object unmappedValue) {
 189         if (deleted == null) {
 190             deleted = new BitSet(numMapped);
 191         }
 192         deleted.set(index, true);
 193         setUnmappedArg(index, unmappedValue);
 194     }
 195 
 196     private boolean deleteMapped(final int index, final boolean strict) {
 197         final Object value = getArray().getObject(index);
 198         final boolean success = super.delete(index, strict);
 199         if (success) {
 200             setDeleted(index, value);
 201         }
 202         return success;
 203     }
 204 
 205     private Object getUnmappedArg(final int key) {
 206         assert key >= 0 && key < numParams;
 207         return unmappedArgs == null ? UNDEFINED : unmappedArgs.getObject(key);
 208     }
 209 
 210     private void setUnmappedArg(final int key, final Object value) {
 211         assert key >= 0 && key < numParams;
 212         if (unmappedArgs == null) {
 213             /*
 214              * Declared number of parameters may be more or less than the actual passed
 215              * runtime arguments count. We need to truncate or extend with undefined values.
 216              *
 217              * Example:
 218              *
 219              * // less declared params
 220              * (function (x) { print(arguments); })(20, 44);
 221              *
 222              * // more declared params
 223              * (function (x, y) { print(arguments); })(3);
 224              */
 225             final Object[] newValues = new Object[numParams];
 226             System.arraycopy(getArray().asObjectArray(), 0, newValues, 0, numMapped);
 227             if (numMapped < numParams) {
 228                 Arrays.fill(newValues, numMapped, numParams, UNDEFINED);
 229             }
 230             this.unmappedArgs = ArrayData.allocate(newValues);
 231         }
 232         // Set value of argument
 233         unmappedArgs = unmappedArgs.set(key, value, false);
 234     }
 235 
 236     /**
 237      * Are arguments[index] and corresponding named parameter linked?
 238      *
 239      * In non-strict mode, arguments[index] and corresponding named param are "linked" or "mapped"
 240      * if the argument is provided by the caller. Modifications are tacked b/w each other - until
 241      * (delete arguments[index]) is used. Once deleted, the corresponding arg is no longer 'mapped'.
 242      * Please note that delete can happen only through the arguments array - named param can not
 243      * be deleted. (delete is one-way).
 244      */
 245     private boolean isMapped(final int index) {
 246         // in mapped named args and not marked as "deleted"
 247         return index >= 0 && index < numMapped && !isDeleted(index);
 248     }
 249 
 250     /**
 251      * Factory to create correct Arguments object based on strict mode.
 252      *
 253      * @param arguments the actual arguments array passed
 254      * @param callee the callee function that uses arguments object
 255      * @param numParams the number of declared (named) function parameters
 256      * @return Arguments Object
 257      */
 258     public static ScriptObject allocate(final Object[] arguments, final ScriptFunction callee, final int numParams) {
 259         // Strict functions won't always have a callee for arguments, and will pass null instead.
 260         final boolean isStrict = callee == null || callee.isStrict();
 261         final Global global = Global.instance();
 262         final ScriptObject proto = global.getObjectPrototype();
 263         if (isStrict) {
 264             return new NativeStrictArguments(arguments, numParams, proto, NativeStrictArguments.getInitialMap());
 265         }
 266         return new NativeArguments(arguments, callee, numParams, proto, NativeArguments.getInitialMap());
 267     }
 268 
 269     /**
 270      * Length getter
 271      * @param self self reference
 272      * @return length property value
 273      */
 274     public static Object G$length(final Object self) {
 275         if (self instanceof NativeArguments) {
 276             return ((NativeArguments)self).getArgumentsLength();
 277         }
 278 
 279         return 0;
 280     }
 281 
 282     /**
 283      * Length setter
 284      * @param self self reference
 285      * @param value value for length property
 286      */
 287     public static void S$length(final Object self, final Object value) {
 288         if (self instanceof NativeArguments) {
 289             ((NativeArguments)self).setArgumentsLength(value);
 290         }
 291     }
 292 
 293     /**
 294      * Callee getter
 295      * @param self self reference
 296      * @return value for callee property
 297      */
 298     public static Object G$callee(final Object self) {
 299         if (self instanceof NativeArguments) {
 300             return ((NativeArguments)self).getCallee();
 301         }
 302         return UNDEFINED;
 303     }
 304 
 305     /**
 306      * Callee setter
 307      * @param self self reference
 308      * @param value value for callee property
 309      */
 310     public static void S$callee(final Object self, final Object value) {
 311         if (self instanceof NativeArguments) {
 312             ((NativeArguments)self).setCallee(value);
 313         }
 314     }
 315 
 316     @Override
 317     public Object getLength() {
 318         return length;
 319     }
 320 
 321     private Object getArgumentsLength() {
 322         return length;
 323     }
 324 
 325     private void setArgumentsLength(final Object length) {
 326         this.length = length;
 327     }
 328 
 329     private Object getCallee() {
 330         return callee;
 331     }
 332 
 333     private void setCallee(final Object callee) {
 334         this.callee = callee;
 335     }
 336 
 337     private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) {
 338         return MH.findStatic(MethodHandles.lookup(), NativeArguments.class, name, MH.type(rtype, types));
 339     }
 340 }