aboutsummaryrefslogtreecommitdiff
path: root/src/jdk/nashorn/internal/objects/NativeArguments.java
blob: 3a853eff59b558e0861dbbe1b8c0192ace7cf341 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/*
 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package jdk.nashorn.internal.objects;

import static jdk.nashorn.internal.lookup.Lookup.MH;
import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import jdk.nashorn.internal.runtime.AccessorProperty;
import jdk.nashorn.internal.runtime.Property;
import jdk.nashorn.internal.runtime.PropertyDescriptor;
import jdk.nashorn.internal.runtime.PropertyMap;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.arrays.ArrayData;
import jdk.nashorn.internal.runtime.arrays.ArrayIndex;

/**
 * ECMA 10.6 Arguments Object.
 *
 * Arguments object used for non-strict mode functions. For strict mode, we use
 * a different implementation (@see NativeStrictArguments). In non-strict mode,
 * named argument access and index argument access (arguments[i]) are linked.
 * Modifications reflect on each other access -- till arguments indexed element
 * is deleted. After delete, there is no link between named access and indexed
 * access for that deleted index alone.
 */
public final class NativeArguments extends ScriptObject {

    private static final MethodHandle G$LENGTH = findOwnMH("G$length", Object.class, Object.class);
    private static final MethodHandle S$LENGTH = findOwnMH("S$length", void.class, Object.class, Object.class);
    private static final MethodHandle G$CALLEE = findOwnMH("G$callee", Object.class, Object.class);
    private static final MethodHandle S$CALLEE = findOwnMH("S$callee", void.class, Object.class, Object.class);

    private static final PropertyMap map$;

    static {
        final ArrayList<Property> properties = new ArrayList<>(2);
        properties.add(AccessorProperty.create("length", Property.NOT_ENUMERABLE, G$LENGTH, S$LENGTH));
        properties.add(AccessorProperty.create("callee", Property.NOT_ENUMERABLE, G$CALLEE, S$CALLEE));
        map$ = PropertyMap.newMap(properties).setIsShared();
    }

    static PropertyMap getInitialMap() {
        return map$;
    }

    private Object length;
    private Object callee;
    private final int numMapped;
    private final int numParams;

    // These are lazily initialized when delete is invoked on a mapped arg or an unmapped argument is set.
    private ArrayData unmappedArgs;
    private BitSet deleted;

    NativeArguments(final Object[] arguments, final Object callee, final int numParams, final ScriptObject proto, final PropertyMap map) {
        super(proto, map);
        setIsArguments();
        setArray(ArrayData.allocate(arguments));
        this.length = arguments.length;
        this.callee = callee;
        this.numMapped = Math.min(numParams, arguments.length);
        this.numParams = numParams;
    }

    @Override
    public String getClassName() {
        return "Arguments";
    }

    /**
     * getArgument is used for named argument access.
     */
    @Override
    public Object getArgument(final int key) {
        assert key >= 0 && key < numParams : "invalid argument index";
        return isMapped(key) ? getArray().getObject(key) : getUnmappedArg(key);
    }

    /**
     * setArgument is used for named argument set.
     */
    @Override
    public void setArgument(final int key, final Object value) {
        assert key >= 0 && key < numParams : "invalid argument index";
        if (isMapped(key)) {
            setArray(getArray().set(key, value, false));
        } else {
            setUnmappedArg(key, value);
        }
    }

    @Override
    public boolean delete(final int key, final boolean strict) {
        final int index = ArrayIndex.getArrayIndex(key);
        return isMapped(index) ? deleteMapped(index, strict) : super.delete(key, strict);
    }

    @Override
    public boolean delete(final long key, final boolean strict) {
        final int index = ArrayIndex.getArrayIndex(key);
        return isMapped(index) ? deleteMapped(index, strict) : super.delete(key, strict);
    }

    @Override
    public boolean delete(final double key, final boolean strict) {
        final int index = ArrayIndex.getArrayIndex(key);
        return isMapped(index) ? deleteMapped(index, strict) : super.delete(key, strict);
    }

    @Override
    public boolean delete(final Object key, final boolean strict) {
        final int index = ArrayIndex.getArrayIndex(key);
        return isMapped(index) ? deleteMapped(index, strict) : super.delete(key, strict);
    }

    /**
     * ECMA 15.4.5.1 [[DefineOwnProperty]] ( P, Desc, Throw ) as specialized in
     * ECMA 10.6 for Arguments object.
     */
    @Override
    public boolean defineOwnProperty(final String key, final Object propertyDesc, final boolean reject) {
        final int index = ArrayIndex.getArrayIndex(key);
        if (index >= 0) {
            final boolean isMapped = isMapped(index);
            final Object oldValue = isMapped ? getArray().getObject(index) : null;

            if (!super.defineOwnProperty(key, propertyDesc, false)) {
                if (reject) {
                    throw typeError("cant.redefine.property",  key, ScriptRuntime.safeToString(this));
                }
                return false;
            }

            if (isMapped) {
                // When mapped argument is redefined, if new descriptor is accessor property
                // or data-non-writable property, we have to "unmap" (unlink).
                final PropertyDescriptor desc = toPropertyDescriptor(Global.instance(), propertyDesc);
                if (desc.type() == PropertyDescriptor.ACCESSOR) {
                    setDeleted(index, oldValue);
                } else if (desc.has(PropertyDescriptor.WRITABLE) && !desc.isWritable()) {
                    // delete and set value from new descriptor if it has one, otherwise use old value
                    setDeleted(index, desc.has(PropertyDescriptor.VALUE) ? desc.getValue() : oldValue);
                } else if (desc.has(PropertyDescriptor.VALUE)) {
                    setArray(getArray().set(index, desc.getValue(), false));
                }
            }

            return true;
        }

        return super.defineOwnProperty(key, propertyDesc, reject);
    }

    // Internals below this point

    // We track deletions using a bit set (delete arguments[index])
    private boolean isDeleted(final int index) {
        return deleted != null && deleted.get(index);
    }

    private void setDeleted(final int index, final Object unmappedValue) {
        if (deleted == null) {
            deleted = new BitSet(numMapped);
        }
        deleted.set(index, true);
        setUnmappedArg(index, unmappedValue);
    }

    private boolean deleteMapped(final int index, final boolean strict) {
        final Object value = getArray().getObject(index);
        final boolean success = super.delete(index, strict);
        if (success) {
            setDeleted(index, value);
        }
        return success;
    }

    private Object getUnmappedArg(final int key) {
        assert key >= 0 && key < numParams;
        return unmappedArgs == null ? UNDEFINED : unmappedArgs.getObject(key);
    }

    private void setUnmappedArg(final int key, final Object value) {
        assert key >= 0 && key < numParams;
        if (unmappedArgs == null) {
            /*
             * Declared number of parameters may be more or less than the actual passed
             * runtime arguments count. We need to truncate or extend with undefined values.
             *
             * Example:
             *
             * // less declared params
             * (function (x) { print(arguments); })(20, 44);
             *
             * // more declared params
             * (function (x, y) { print(arguments); })(3);
             */
            final Object[] newValues = new Object[numParams];
            System.arraycopy(getArray().asObjectArray(), 0, newValues, 0, numMapped);
            if (numMapped < numParams) {
                Arrays.fill(newValues, numMapped, numParams, UNDEFINED);
            }
            this.unmappedArgs = ArrayData.allocate(newValues);
        }
        // Set value of argument
        unmappedArgs = unmappedArgs.set(key, value, false);
    }

    /**
     * Are arguments[index] and corresponding named parameter linked?
     *
     * In non-strict mode, arguments[index] and corresponding named param are "linked" or "mapped"
     * if the argument is provided by the caller. Modifications are tacked b/w each other - until
     * (delete arguments[index]) is used. Once deleted, the corresponding arg is no longer 'mapped'.
     * Please note that delete can happen only through the arguments array - named param can not
     * be deleted. (delete is one-way).
     */
    private boolean isMapped(final int index) {
        // in mapped named args and not marked as "deleted"
        return index >= 0 && index < numMapped && !isDeleted(index);
    }

    /**
     * Factory to create correct Arguments object based on strict mode.
     *
     * @param arguments the actual arguments array passed
     * @param callee the callee function that uses arguments object
     * @param numParams the number of declared (named) function parameters
     * @return Arguments Object
     */
    public static ScriptObject allocate(final Object[] arguments, final ScriptFunction callee, final int numParams) {
        // Strict functions won't always have a callee for arguments, and will pass null instead.
        final boolean isStrict = callee == null || callee.isStrict();
        final Global global = Global.instance();
        final ScriptObject proto = global.getObjectPrototype();
        if (isStrict) {
            return new NativeStrictArguments(arguments, numParams, proto, global.getStrictArgumentsMap());
        }
        return new NativeArguments(arguments, callee, numParams, proto, global.getArgumentsMap());
    }

    /**
     * Length getter
     * @param self self reference
     * @return length property value
     */
    public static Object G$length(final Object self) {
        if (self instanceof NativeArguments) {
            return ((NativeArguments)self).getArgumentsLength();
        }

        return 0;
    }

    /**
     * Length setter
     * @param self self reference
     * @param value value for length property
     */
    public static void S$length(final Object self, final Object value) {
        if (self instanceof NativeArguments) {
            ((NativeArguments)self).setArgumentsLength(value);
        }
    }

    /**
     * Callee getter
     * @param self self reference
     * @return value for callee property
     */
    public static Object G$callee(final Object self) {
        if (self instanceof NativeArguments) {
            return ((NativeArguments)self).getCallee();
        }
        return UNDEFINED;
    }

    /**
     * Callee setter
     * @param self self reference
     * @param value value for callee property
     */
    public static void S$callee(final Object self, final Object value) {
        if (self instanceof NativeArguments) {
            ((NativeArguments)self).setCallee(value);
        }
    }

    @Override
    public Object getLength() {
        return length;
    }

    private Object getArgumentsLength() {
        return length;
    }

    private void setArgumentsLength(final Object length) {
        this.length = length;
    }

    private Object getCallee() {
        return callee;
    }

    private void setCallee(final Object callee) {
        this.callee = callee;
    }

    private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) {
        return MH.findStatic(MethodHandles.lookup(), NativeArguments.class, name, MH.type(rtype, types));
    }
}